Skip to content

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

Rust

prioritize human messages ahead of queued agent traffic (#2334)

ktdca77ecfe450
diff --git a/packages/coding-agent/.changes/eng-6158-human-message-priority.md b/packages/coding-agent/.changes/eng-6158-human-message-priority.md
new file mode 100644
index 0000000000..840234c368
--- /dev/null
+++ b/packages/coding-agent/.changes/eng-6158-human-message-priority.md
@@ -0,0 +1 @@
+- Changed the prompt queue so messages you send are delivered before queued agent-to-agent messages, background notices, and scheduled prompts, while keeping your own messages in the order you sent them.
diff --git a/packages/coding-agent/src/core/agent-messages.ts b/packages/coding-agent/src/core/agent-messages.ts
index f49df9195d..62bf08e600 100644
--- a/packages/coding-agent/src/core/agent-messages.ts
+++ b/packages/coding-agent/src/core/agent-messages.ts
@@ -13,6 +13,7 @@ export const AGENT_MESSAGE_CUSTOM_TYPE = "agent_message";
export const AGENT_MESSAGE_SKILL_NAME = "agent-message";
export const AGENT_MESSAGE_IMPORT_NAME = "agent_message";
export const AGENT_MESSAGE_SOURCE = "agent_message";
+export const AGENT_MESSAGE_ID_PREFIX = "agentmsg_";
export const AGENT_MESSAGE_RECEIVED_PREVIEW_LABEL = "Agent message received";
export const DEFAULT_AGENT_MESSAGE_MAX_CHARS = 16_384;
export const DEFAULT_AGENT_MESSAGE_MAX_PENDING_PER_SESSION = 20;
@@ -318,7 +319,12 @@ export function assertAgentFamilyReach(
}
export function createAgentSessionMessageId(): string {
- return `agentmsg_${randomUUID()}`;
+ return `${AGENT_MESSAGE_ID_PREFIX}${randomUUID()}`;
+}
+
+/** Distinguishes agent-to-agent ids from the synthetic ids callers mint to track prompt completion. */
+export function isAgentSessionMessageId(id: string | undefined): boolean {
+ return id !== undefined && id.startsWith(AGENT_MESSAGE_ID_PREFIX);
}
export function normalizeAgentSessionMessage(message: string, maxChars = DEFAULT_AGENT_MESSAGE_MAX_CHARS): string {
diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.ts
index e185a12793..af96fc909e 100644
--- a/packages/coding-agent/src/core/agent-session.ts
+++ b/packages/coding-agent/src/core/agent-session.ts
@@ -55,6 +55,7 @@ import {
DEFAULT_AGENT_MESSAGE_MAX_PENDING_PER_SESSION,
formatAgentSessionNameUnavailable,
isAgentSessionMessage,
+ isAgentSessionMessageId,
isAgentSessionMessagePrompt,
normalizeAgentSessionMessage,
parseAgentSessionMessagePromptId,
@@ -295,6 +296,8 @@ import {
queuedMessageLaneDeliveryPolicy,
type RuntimeActivity,
type SessionAction,
+ type SessionActionPlacement,
+ type SessionActionPriority,
type SessionActionSnapshot,
type SessionCommandPayload,
type SessionTurnPayload,
@@ -595,6 +598,8 @@ export interface PromptOptions {
agentMessageId?: string;
content?: (TextContent | ImageContent)[];
customMessage?: CustomMessage;
+ /** Overrides the queue priority inferred from the source and message. */
+ priority?: SessionActionPriority;
}
interface InternalPromptOptions extends PromptOptions {
@@ -755,6 +760,7 @@ export interface SessionActionRecoveryAction {
source: InputSource | "internal";
delivery: DeliveryPolicy;
wake: WakePolicy;
+ priority?: SessionActionPriority;
payload: SessionActionRecoveryPayload;
queueKey?: string;
agentMessageId?: string;
@@ -781,6 +787,25 @@ function cloneQueuedAgentMessage(message: QueuedAgentMessage): QueuedAgentMessag
};
}
+function isHumanInputSource(source: InputSource | "internal"): boolean {
+ return source === "interactive" || source === "rpc";
+}
+
+/**
+ * Only input a person submits outranks the rest of the queue. Agent-to-agent prompts carry an
+ * agent message id, and every machine-generated turn (bash completions, heartbeats, continuations,
+ * restored internal input) is either a custom message or admitted from a non-human source. Ids
+ * callers mint to await their own prompt are not agent traffic and keep human priority.
+ */
+function sessionActionPriorityFor(
+ humanSource: boolean,
+ message: QueuedAgentMessage | undefined,
+ agentMessageId: string | undefined,
+): SessionActionPriority {
+ if (!humanSource || isAgentSessionMessageId(agentMessageId)) return "background";
+ return message === undefined || message.role === "user" ? "user" : "background";
+}
+
function primaryDeliveryRecord(action: QueuedSessionAction): DeliveryRecord {
if (action.payload.kind !== "turn") throw new Error(`Session action ${action.id} is not a turn`);
const record = action.payload.records.find((candidate) => candidate.role === "primary");
@@ -2723,6 +2748,8 @@ export class AgentSession {
const action = this._createPreparedTurnAction("followUp", normalized.text, normalized.images, {
message,
resumeIfIdle: true,
+ // Front insertion only holds while nothing can be admitted ahead of it.
+ priority: "pinned",
});
this._admitSessionInput(action, { front: true, wake: false });
}
@@ -5501,6 +5528,7 @@ export class AgentSession {
options?.resumeIfIdle ||
(options?.queueIfBusy === true && canSelectSessionAction(this._runtimeActivity())),
source: options?.source ?? "internal",
+ priority: options?.priority,
executionPolicy:
options?.executionPolicy ??
(visibleQueued ? this._turnExecutionPolicy("queued") : this._turnExecutionPolicy("injected")),
@@ -5604,6 +5632,7 @@ export class AgentSession {
{
agentMessageId: options?.agentMessageId,
source: isInternalPrompt ? "internal" : (options?.source ?? "interactive"),
+ priority: options?.priority,
},
);
const result = this._admitSessionInput(action, {
@@ -5658,6 +5687,7 @@ export class AgentSession {
options?.resumeIfIdle ||
(options?.queueIfBusy === true && canSelectSessionAction(this._runtimeActivity())),
source: isInternalPrompt ? "internal" : (options?.source ?? "interactive"),
+ priority: options?.priority,
executionPolicy: visibleQueued
? this._turnExecutionPolicy("queued")
: this._turnExecutionPolicy("directPrompt", {
@@ -5805,6 +5835,7 @@ export class AgentSession {
queueKey?: string;
agentMessageId?: string;
resumeIfIdle?: boolean;
+ priority?: SessionActionPriority;
} = {},
): Promise<void> {
const normalized = this._normalizeSubmission(text, images, {
@@ -5821,6 +5852,7 @@ export class AgentSession {
queueKey: options.queueKey,
agentMessageId: options.agentMessageId,
resumeIfIdle: options.resumeIfIdle,
+ priority: options.priority ?? sessionActionPriorityFor(true, undefined, options.agentMessageId),
});
}
@@ -5838,6 +5870,7 @@ export class AgentSession {
queueKey?: string;
agentMessageId?: string;
resumeIfIdle?: boolean;
+ priority?: SessionActionPriority;
} = {},
): Promise<boolean> {
const normalized = this._normalizeSubmission(text, images, {
@@ -5854,6 +5887,7 @@ export class AgentSession {
queueKey: options.queueKey,
agentMessageId: options.agentMessageId,
resumeIfIdle: options.resumeIfIdle,
+ priority: options.priority ?? sessionActionPriorityFor(true, undefined, options.agentMessageId),
});
}
@@ -5926,10 +5960,15 @@ export class AgentSession {
}
: {}),
};
+ const primaryMessage =
+ payload.kind === "turn" ? payload.records.find((record) => record.role === "primary")?.message : undefined;
return {
id: recovered.id,
source: recovered.source,
delivery: recovered.delivery,
+ priority:
+ recovered.priority ??
+ sessionActionPriorityFor(isHumanInputSource(recovered.source), primaryMessage, recovered.agentMessageId),
wake: recovered.wake,
payload,
lifecycle: { state: "queued" },
@@ -5965,6 +6004,7 @@ export class AgentSession {
this._createSessionCommandAction(text, customMessage.details.command, images, schedule, {
agentMessageId,
source: "internal",
+ priority: sessionActionPriorityFor(true, undefined, agentMessageId),
}),
{ restore: true },
).accepted;
@@ -5978,6 +6018,9 @@ export class AgentSession {
message: snapshot.customMessage,
prefixMessages: snapshot.prefixMessages,
source: "internal",
+ priority: sessionActionPriorityFor(true, snapshot.customMessage, snapshot.agentMessageId),
+ // Restored input replays the order it was admitted in.
+ preserveOrder: true,
});
}
@@ -6156,6 +6199,7 @@ export class AgentSession {
suppressAutonomousContinuation?: boolean;
resumeIfIdle?: boolean;
source?: InputSource | "internal";
+ priority?: SessionActionPriority;
executionPolicy?: TurnExecutionPolicy;
queueVisible?: boolean;
acceptedAgentMessage?: boolean;
@@ -6189,10 +6233,13 @@ export class AgentSession {
acceptedAgentMessage: options.acceptedAgentMessage ?? false,
acceptedBeforeCompletion: options.acceptedBeforeCompletion ?? false,
};
+ const source = options.source ?? "internal";
return {
id,
- source: options.source ?? "internal",
+ source,
delivery: this._deliveryPolicy(schedule),
+ priority:
+ options.priority ?? sessionActionPriorityFor(isHumanInputSource(source), message, options.agentMessageId),
wake:
options.resumeIfIdle === true
? "immediate"
@@ -6215,12 +6262,16 @@ export class AgentSession {
options: {
agentMessageId?: string;
source?: InputSource | "internal";
+ priority?: SessionActionPriority;
} = {},
): QueuedSessionAction {
+ const source = options.source ?? "internal";
return {
id: randomUUID(),
- source: options.source ?? "internal",
+ source,
delivery: this._deliveryPolicy(schedule),
+ priority:
+ options.priority ?? sessionActionPriorityFor(isHumanInputSource(source), undefined, options.agentMessageId),
wake: "immediate",
payload: { kind: "session_command", text, command, images },
lifecycle: { state: "queued" },
@@ -6260,6 +6311,7 @@ export class AgentSession {
options: {
restore?: boolean;
front?: boolean;
+ preserveOrder?: boolean;
wake?: boolean;
immediatelyEligible?: boolean;
} = {},
@@ -6299,8 +6351,12 @@ export class AgentSession {
const canStartImmediately =
options.immediatelyEligible === true &&
(this._actionStore.unfinishedActions().length === 0 || options.front === true);
- if (options.front) this._actionStore.enqueueFront(action);
- else this._actionStore.enqueue(action);
+ const placement: SessionActionPlacement = options.front
+ ? "front"
+ : options.restore || options.preserveOrder
+ ? "tail"
+ : "priority";
+ this._actionStore.enqueue(action, placement);
let disposition: "starts_when_admitted" | "queued" = "queued";
if (canStartImmediately && this._actionStore.selectFirst() === action) disposition = "starts_when_admitted";
const controller = this._actionStore.ticketFor(action);
@@ -6341,13 +6397,15 @@ export class AgentSession {
suppressAutonomousContinuation?: boolean;
resumeIfIdle?: boolean;
source?: InputSource | "internal";
+ priority?: SessionActionPriority;
+ preserveOrder?: boolean;
} = {},
): Promise<boolean> {
const action = this._createPreparedTurnAction(schedule, text, images, options);
if (action.suppressAutonomousContinuation) {
this._markAutonomousContinuationSuppressed(primaryDeliveryRecord(action).message);
}
- return this._admitSessionInput(action).accepted;
+ return this._admitSessionInput(action, { preserveOrder: options.preserveOrder }).accepted;
}
private _runtimeActivity(): RuntimeActivity {
@@ -7307,6 +7365,7 @@ export class AgentSession {
id: action.id,
source: action.source,
delivery: action.delivery,
+ priority: action.priority,
wake: action.wake,
...(action.queueKey ? { queueKey: action.queueKey } : {}),
...(action.agentMessageId ? { agentMessageId: action.agentMessageId } : {}),
diff --git a/packages/coding-agent/src/core/session-action-store.ts b/packages/coding-agent/src/core/session-action-store.ts
index 937eea09a1..29472146ad 100644
--- a/packages/coding-agent/src/core/session-action-store.ts
+++ b/packages/coding-agent/src/core/session-action-store.ts
@@ -7,6 +7,12 @@ import type { SessionSlashCommand } from "./slash-commands.js";
export type DeliveryPolicy = "next_turn_boundary" | "when_run_idle";
export type WakePolicy = "immediate" | "on_lower_boundary" | "external_resume";
+/** Queue order inside a delivery lane: human input outranks agent-to-agent and other machine traffic. */
+export type SessionActionPriority = "pinned" | "user" | "background";
+export type SessionActionPlacement = "priority" | "tail" | "front";
+
+const PRIORITY_RANK: Record<SessionActionPriority, number> = { pinned: 2, user: 1, background: 0 };
+
export type QueuedMessageLane = "steering" | "followUp";
export function queuedMessageLaneDeliveryPolicy(lane: QueuedMessageLane): DeliveryPolicy {
@@ -68,6 +74,7 @@ export interface SessionAction<TPayload extends SessionActionPayload = SessionAc
id: string;
source: InputSource | "internal";
delivery: DeliveryPolicy;
+ priority: SessionActionPriority;
wake: WakePolicy;
payload: TPayload;
lifecycle: ActionLifecycle;
@@ -210,17 +217,10 @@ export class ActionStore<TAction extends SessionAction = SessionAction> {
private readonly whenRunIdle: TAction[] = [];
private readonly tickets = new Map<string, ActionTicketController>();
- enqueue(action: TAction): void {
- this.assertNewAction(action);
- this.list(action.delivery).push(action);
- this.tickets.set(action.id, new ActionTicketController(action.id));
- }
-
- enqueueFront(action: TAction): void {
+ enqueue(action: TAction, placement: SessionActionPlacement = "priority"): void {
this.assertNewAction(action);
const list = this.list(action.delivery);
- const firstQueued = list.findIndex((item) => item.lifecycle.state === "queued");
- list.splice(firstQueued < 0 ? list.length : firstQueued, 0, action);
+ list.splice(this.insertionIndex(list, action, placement), 0, action);
this.tickets.set(action.id, new ActionTicketController(action.id));
}
@@ -319,6 +319,26 @@ export class ActionStore<TAction extends SessionAction = SessionAction> {
this.tickets.delete(action.id);
}
+ /**
+ * Queued actions are ordered by priority and stay FIFO within a priority. Actions that are
+ * no longer queued are already committed to this turn, so nothing is inserted ahead of them.
+ */
+ private insertionIndex(list: readonly TAction[], action: TAction, placement: SessionActionPlacement): number {
+ if (placement === "tail") return list.length;
+ if (placement === "front") {
+ const firstQueued = list.findIndex((item) => item.lifecycle.state === "queued");
+ return firstQueued < 0 ? list.length : firstQueued;
+ }
+ const rank = PRIORITY_RANK[action.priority];
+ let index = list.length;
+ for (let position = list.length - 1; position >= 0; position--) {
+ const item = list[position];
+ if (!item || item.lifecycle.state !== "queued" || PRIORITY_RANK[item.priority] >= rank) break;
+ index = position;
+ }
+ return index;
+ }
+
private actions(policy?: DeliveryPolicy): readonly TAction[] {
if (policy) return this.list(policy);
return [...this.nextTurnBoundary, ...this.whenRunIdle];
diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
index c1dc74e997..5953974b93 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
@@ -2104,6 +2104,8 @@ export class AgentDaemon {
}
await session.followUp(runnableJob.prompt, undefined, {
resumeIfIdle: true,
+ // A scheduled prompt is machine-triggered, so it must not outrank live human input.
+ priority: "background",
});
return;
}
@@ -2136,6 +2138,8 @@ export class AgentDaemon {
await session.promptUntilAccepted(current.prompt, {
streamingBehavior: "followUp",
source: "rpc",
+ // A scheduled prompt is machine-triggered, so it must not outrank live human input.
+ priority: "background",
admissionCommitted,
});
} catch (error) {
diff --git a/packages/coding-agent/src/package-manager-cli.ts b/packages/coding-agent/src/package-manager-cli.ts
index d85251aba9..98544f6a92 100644
--- a/packages/coding-agent/src/package-manager-cli.ts
+++ b/packages/coding-agent/src/package-manager-cli.ts
@@ -636,6 +636,7 @@ function isSessionActionRecoveryAction(value: unknown): value is SessionActionRe
typeof value.id !== "string" ||
typeof value.source !== "string" ||
(value.delivery !== "next_turn_boundary" && value.delivery !== "when_run_idle") ||
+ (value.priority !== undefined && !isStringEnum(value.priority, ["pinned", "user", "background"])) ||
(value.wake !== "immediate" && value.wake !== "on_lower_boundary" && value.wake !== "external_resume") ||
!isRecord(value.payload) ||
typeof value.payload.text !== "string" ||
diff --git a/packages/coding-agent/test/daemon-mode.test.ts b/packages/coding-agent/test/daemon-mode.test.ts
index 05abc03892..8904b9a24f 100644
--- a/packages/coding-agent/test/daemon-mode.test.ts
+++ b/packages/coding-agent/test/daemon-mode.test.ts
@@ -8885,7 +8885,10 @@ describe("daemon mode helpers", () => {
await fixture.runCronJob(makeCronJob({ id: "cron-1", source: "cron", activeSessionId: fixture.activeSessionId }));
- expect(fixture.followUp).toHaveBeenCalledWith("heartbeat prompt", undefined, { resumeIfIdle: true });
+ expect(fixture.followUp).toHaveBeenCalledWith("heartbeat prompt", undefined, {
+ resumeIfIdle: true,
+ priority: "background",
+ });
expect(fixture.prompt).not.toHaveBeenCalled();
expect(fixture.promptHeartbeat).not.toHaveBeenCalled();
});
diff --git a/packages/coding-agent/test/session-action-store.test.ts b/packages/coding-agent/test/session-action-store.test.ts
index 990f75f391..9b908a585d 100644
--- a/packages/coding-agent/test/session-action-store.test.ts
+++ b/packages/coding-agent/test/session-action-store.test.ts
@@ -9,18 +9,24 @@ import {
type DeliveryPolicy,
type RuntimeActivity,
type SessionAction,
+ type SessionActionPriority,
transitionSessionAction,
} from "../src/core/session-action-store.js";
let nextId = 0;
-function turn(text: string, delivery: DeliveryPolicy = "when_run_idle"): SessionAction {
+function turn(
+ text: string,
+ delivery: DeliveryPolicy = "when_run_idle",
+ priority: SessionActionPriority = "background",
+): SessionAction {
const id = `action-${nextId++}`;
const message: UserMessage = { role: "user", content: text, timestamp: nextId };
return {
id,
source: "internal",
delivery,
+ priority,
wake: "external_resume",
payload: {
kind: "turn",
@@ -31,11 +37,16 @@ function turn(text: string, delivery: DeliveryPolicy = "when_run_idle"): Session
};
}
-function command(text: string, delivery: DeliveryPolicy = "when_run_idle"): SessionAction {
+function command(
+ text: string,
+ delivery: DeliveryPolicy = "when_run_idle",
+ priority: SessionActionPriority = "background",
+): SessionAction {
return {
id: `action-${nextId++}`,
source: "internal",
delivery,
+ priority,
wake: "immediate",
payload: {
kind: "session_command",
@@ -115,6 +126,53 @@ describe("ActionStore selection", () => {
expect(store.activeActions()).toEqual([compact]);
});
+ it("queues human input ahead of background work and behind earlier human input", () => {
+ const store = new ActionStore();
+ const agentOne = turn("a1", "next_turn_boundary");
+ const agentTwo = turn("a2", "next_turn_boundary");
+ const humanOne = turn("h1", "next_turn_boundary", "user");
+ const agentThree = turn("a3", "next_turn_boundary");
+ const humanTwo = turn("h2", "next_turn_boundary", "user");
+ for (const action of [agentOne, agentTwo, humanOne, agentThree, humanTwo]) store.enqueue(action);
+
+ expect(store.queuedActions("next_turn_boundary")).toEqual([humanOne, humanTwo, agentOne, agentTwo, agentThree]);
+ });
+
+ it("never inserts ahead of an action that already left the queue", () => {
+ const store = new ActionStore();
+ const running = turn("running", "next_turn_boundary");
+ const agent = turn("a1", "next_turn_boundary");
+ store.enqueue(running);
+ store.enqueue(agent);
+ expect(store.selectFirst()).toBe(running);
+ const human = turn("h1", "next_turn_boundary", "user");
+ store.enqueue(human);
+
+ expect(store.ownedActions()).toEqual([running, human, agent]);
+ });
+
+ it("keeps pinned actions ahead of later human input", () => {
+ const store = new ActionStore();
+ const agent = turn("a1");
+ store.enqueue(agent);
+ const pinned = turn("goal context", "when_run_idle", "pinned");
+ store.enqueue(pinned, "front");
+ const human = turn("h1", "when_run_idle", "user");
+ store.enqueue(human);
+
+ expect(store.queuedActions()).toEqual([pinned, human, agent]);
+ });
+
+ it("appends restored actions verbatim", () => {
+ const store = new ActionStore();
+ const agent = turn("a1");
+ const human = turn("h1", "when_run_idle", "user");
+ store.enqueue(agent, "tail");
+ store.enqueue(human, "tail");
+
+ expect(store.queuedActions()).toEqual([agent, human]);
+ });
+
it("supports front insertion without changing rollback-at-original-position", () => {
const store = new ActionStore();
const selected = turn("selected");
@@ -123,7 +181,7 @@ describe("ActionStore selection", () => {
store.enqueue(tail);
expect(store.selectFirst()).toBe(selected);
const front = turn("goal context");
- store.enqueueFront(front);
+ store.enqueue(front, "front");
store.rollback(selected);
expect(store.queuedActions()).toEqual([selected, front, tail]);
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 afe121da90..bbabeffa94 100644
--- a/packages/coding-agent/test/suite/agent-session-queue.test.ts
+++ b/packages/coding-agent/test/suite/agent-session-queue.test.ts
@@ -1915,7 +1915,8 @@ describe("AgentSession queue characterization", () => {
{ deliverAs: "nextTurn" },
);
await harness.session.queueAgentMessagePrompt(firstPrompt, "followUp");
- await harness.session.followUp("surviving");
+ // Both inputs stay in one priority class so the agent message keeps the batch anchor.
+ await harness.session.followUp("surviving", undefined, { priority: "background" });
pause.release();
await harness.session.waitForIdle();
@@ -2038,9 +2039,10 @@ describe("AgentSession queue characterization", () => {
gatePreparation = false;
expect(pause).toBeDefined();
+ // The prompt without an agent message id is human input, so it queues ahead.
expect(harness.session.clearQueue()).toEqual({
steering: [],
- followUp: ["clear first while preparing", "clear second while preparing"],
+ followUp: ["clear second while preparing", "clear first while preparing"],
});
pause?.release();
await firstCompletionRejection;
@@ -3355,7 +3357,11 @@ describe("AgentSession scheduler scenarios", () => {
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" });
+ await harness.session.followUp("last anchor", undefined, {
+ queueKey: "heartbeat:one",
+ // A heartbeat follow-up is machine input, so it queues behind the agent messages.
+ priority: "background",
+ });
expect(prepared).toEqual([]);
expect(getUserTexts(harness)).toEqual([]);
diff --git a/packages/coding-agent/test/suite/regressions/6158-human-message-priority.test.ts b/packages/coding-agent/test/suite/regressions/6158-human-message-priority.test.ts
new file mode 100644
index 0000000000..5f5067afd8
--- /dev/null
+++ b/packages/coding-agent/test/suite/regressions/6158-human-message-priority.test.ts
@@ -0,0 +1,120 @@
+import { fauxAssistantMessage, fauxToolCall } from "@earendil-works/pi-ai";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { createAgentSessionMessage } from "../../../src/core/agent-messages.js";
+import { conversationMessages, createHarness, getMessageText, type Harness } from "../harness.js";
+import { createWaitingHarness } from "../scheduling.js";
+
+function agentMessage(id: string, body: string) {
+ return createAgentSessionMessage({
+ id,
+ source: "agent_message",
+ message: body,
+ target: { activeSessionId: "active-target", sessionId: "session-target", sessionName: "target" },
+ });
+}
+
+async function queueAgentMessage(harness: Harness, id: string, body: string): Promise<void> {
+ const message = agentMessage(id, body);
+ await harness.session.acceptAgentMessagePrompt(message.content as string, {
+ expandPromptTemplates: false,
+ streamingBehavior: "steer",
+ queueIfBusy: true,
+ customMessage: message,
+ });
+}
+
+describe("#6158 human messages outrank agent messages in the queue", () => {
+ const harnesses: Harness[] = [];
+
+ afterEach(() => {
+ while (harnesses.length > 0) harnesses.pop()?.cleanup();
+ });
+
+ it("queues human input ahead of pending agent messages and keeps human order", async () => {
+ const waiting = await createWaitingHarness();
+ harnesses.push(waiting.harness);
+ const session = waiting.harness.session;
+ waiting.harness.setResponses([
+ fauxAssistantMessage(fauxToolCall("wait", {}), { stopReason: "toolUse" }),
+ ...Array.from({ length: 6 }, (_, index) => fauxAssistantMessage(`reply ${index}`)),
+ ]);
+ await waiting.waitForToolStart;
+
+ await queueAgentMessage(waiting.harness, "agentmsg_one", "agent one");
+ await session.prompt("human one", { streamingBehavior: "steer", queueIfBusy: true });
+ await queueAgentMessage(waiting.harness, "agentmsg_two", "agent two");
+ await session.prompt("human two", { streamingBehavior: "steer", queueIfBusy: true });
+ await queueAgentMessage(waiting.harness, "agentmsg_three", "agent three");
+
+ expect(session.getSteeringMessages().map((text) => text.split("\n").pop())).toEqual([
+ "human one",
+ "human two",
+ "agent one",
+ "agent two",
+ "agent three",
+ ]);
+
+ waiting.releaseToolExecution();
+ await waiting.promptPromise;
+ await session.waitForIdle();
+
+ const delivered = conversationMessages(session)
+ .map((message) => getMessageText(message).split("\n").pop())
+ .filter((text): text is string => text !== undefined && /^(human|agent) /.test(text));
+ expect(delivered).toEqual(["human one", "human two", "agent one", "agent two", "agent three"]);
+ });
+
+ it("keeps a prompt that waits for its own completion at human priority", async () => {
+ const waiting = await createWaitingHarness();
+ harnesses.push(waiting.harness);
+ const session = waiting.harness.session;
+ waiting.harness.setResponses([
+ fauxAssistantMessage(fauxToolCall("wait", {}), { stopReason: "toolUse" }),
+ ...Array.from({ length: 4 }, (_, index) => fauxAssistantMessage(`reply ${index}`)),
+ ]);
+ await waiting.waitForToolStart;
+
+ await queueAgentMessage(waiting.harness, "agentmsg_wait", "agent wait");
+ const pending = session.promptAndWait("human wait", { streamingBehavior: "steer", queueIfBusy: true });
+ await vi.waitFor(() => expect(session.getSteeringMessages()).toHaveLength(2));
+
+ expect(session.getSteeringMessages()[0]).toBe("human wait");
+
+ waiting.releaseToolExecution();
+ await pending;
+ await session.waitForIdle();
+ });
+
+ it("keeps an agent message ahead of a human follow-up the user deferred to its own lane", async () => {
+ const waiting = await createWaitingHarness();
+ harnesses.push(waiting.harness);
+ const session = waiting.harness.session;
+ waiting.harness.setResponses([
+ fauxAssistantMessage(fauxToolCall("wait", {}), { stopReason: "toolUse" }),
+ ...Array.from({ length: 4 }, (_, index) => fauxAssistantMessage(`reply ${index}`)),
+ ]);
+ await waiting.waitForToolStart;
+
+ await queueAgentMessage(waiting.harness, "agentmsg_lane", "agent lane");
+ await session.prompt("human lane", { streamingBehavior: "followUp", queueIfBusy: true });
+
+ expect(session.getSteeringMessages()).toHaveLength(1);
+ expect(session.getFollowUpMessages()).toEqual(["human lane"]);
+
+ waiting.releaseToolExecution();
+ await session.dispose();
+ });
+
+ it("restores a persisted queue in its stored order", async () => {
+ const harness = await createHarness();
+ harnesses.push(harness);
+ const session = harness.session;
+ await session.restoreSteeringMessage("agent restored", undefined, {
+ agentMessageId: "agentmsg_restored",
+ customMessage: agentMessage("agentmsg_restored", "agent restored"),
+ });
+ await session.restoreSteeringMessage("human restored");
+
+ expect(session.getSteeringMessages()).toEqual(["agent restored", "human restored"]);
+ });
+});