Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

web-ui: queue a mid-turn message by default; steer only on request (#448)

Regan Bellb938625a3ba2
diff --git a/plugins/web-ui/server/index.ts b/plugins/web-ui/server/index.ts
index d81374377..58478e1b5 100644
--- a/plugins/web-ui/server/index.ts
+++ b/plugins/web-ui/server/index.ts
@@ -1601,6 +1601,18 @@ const routeRequest = async (req: IncomingMessage, res: ServerResponse) => {
if (method === "GET" && path === "/api/runs/active") {
const threadRef = url.searchParams.get("threadRef") ?? "";
if (!threadRef.startsWith("web:")) return json(res, 404, { error: "not_found" });
+ let queued: Array<{ runId: string; text: string }> = [];
+ let durableRunId: string | null = null;
+ const durable = await coreFetch("GET", `/v1/runs?threadRef=${encodeURIComponent(threadRef)}`);
+ if (durable.status >= 200 && durable.status < 300) {
+ try {
+ const parsed = JSON.parse(durable.text) as { runId?: string | null; queued?: typeof queued };
+ durableRunId = parsed.runId ?? null;
+ queued = parsed.queued ?? [];
+ } catch {
+ /* leave the queue empty; the run lookups below still answer */
+ }
+ }
const tryRun = async (runId: string, ownedByUser = true): Promise<boolean> => {
const r = await coreFetch("GET", `/v1/runs/${encodeURIComponent(runId)}`);
if (r.status < 200 || r.status >= 300) {
@@ -1619,23 +1631,15 @@ const routeRequest = async (req: IncomingMessage, res: ServerResponse) => {
return false;
}
rememberRun(runId, user, threadRef);
- json(res, 200, { runId, run });
+ const waiting = queued.filter((q) => q.runId !== runId);
+ json(res, 200, { runId, run, ...(waiting.length ? { queued: waiting } : {}) });
return true;
};
+ if (durableRunId && (await tryRun(durableRunId, false))) return;
for (const runId of Array.from(activeRunsByThread.get(threadKey(user, threadRef)) ?? [])) {
if (await tryRun(runId)) return;
}
- const d = await coreFetch("GET", `/v1/runs?threadRef=${encodeURIComponent(threadRef)}`);
- if (d.status >= 200 && d.status < 300) {
- let runId: string | null = null;
- try {
- runId = (JSON.parse(d.text) as { runId?: string | null }).runId ?? null;
- } catch {
- void 0;
- }
- if (runId && (await tryRun(runId, false))) return;
- }
- json(res, 200, { runId: null, run: null });
+ json(res, 200, { runId: null, run: null, ...(queued.length ? { queued } : {}) });
return;
}
@@ -1659,6 +1663,13 @@ const routeRequest = async (req: IncomingMessage, res: ServerResponse) => {
return relay(res, r);
}
+ if (method === "POST" && path.startsWith("/api/runs/") && path.endsWith("/withdraw")) {
+ const id = decodeURIComponent(path.slice("/api/runs/".length, -"/withdraw".length));
+ const r = await coreFetch("POST", `/v1/runs/${encodeURIComponent(id)}/withdraw`);
+ if (r.status >= 200 && r.status < 300) forgetRun(id);
+ return relay(res, r);
+ }
+
if (method === "GET" && path.startsWith("/api/runs/") && path.endsWith("/events")) {
const id = decodeURIComponent(path.slice("/api/runs/".length, -"/events".length));
let closed = false;
diff --git a/plugins/web-ui/src/chat.ts b/plugins/web-ui/src/chat.ts
index ef6da3fc4..1b4a483eb 100644
--- a/plugins/web-ui/src/chat.ts
+++ b/plugins/web-ui/src/chat.ts
@@ -380,6 +380,7 @@ export function createChatSurface(
if (agent !== chatState.agent) return;
adoptActiveSessionFromList(agent);
await refreshTranscriptFromEntries(agent);
+ void followNextQueuedRun(agent, threadRef, normalStreamFn, onWork);
if (wasUnsaved && chatState.sessionId) void settleNewSessionTitle(agent, threadRef);
});
});
@@ -628,6 +629,37 @@ export function createChatSurface(
};
}
+ async function followNextQueuedRun(
+ agent: Agent,
+ threadRef: string,
+ normalStreamFn: Agent["streamFn"],
+ onWork: (work: WorkBlock) => void,
+ ): Promise<void> {
+ let active: Awaited<ReturnType<typeof activeRunForThread>>;
+ try {
+ active = await activeRunForThread(threadRef);
+ } catch {
+ return;
+ }
+ if (agent !== chatState.agent || threadRef !== chatState.threadRef || agent.state.isStreaming) return;
+ const next = ctx.composer.queuedRunsFor(threadRef).find((r) => r.runId === active.runId);
+ ctx.composer.setQueuedRuns(threadRef, active.queued);
+ if (!active.runId || !active.run) return drawActiveChat(agent);
+ const recorded = (agent.state.messages.at(-1) as { role?: string } | undefined)?.role === "user";
+ if (!recorded && !next) return drawActiveChat(agent);
+ agent.streamFn = makeRunResumeStreamFn(active.runId, active.run, onWork, runSlot);
+ try {
+ await (recorded ? agent.continue() : agent.prompt(next!.text));
+ } catch (err) {
+ if (agent === chatState.agent) ctx.composer.state.error = errMessage(err, "Could not follow the queued message.");
+ } finally {
+ if (agent === chatState.agent) {
+ agent.streamFn = normalStreamFn;
+ await refreshTranscriptFromEntries(agent);
+ }
+ }
+ }
+
async function resumeTrackedRun(
agent: Agent,
threadRef: string,
@@ -641,7 +673,15 @@ export function createChatSurface(
} catch {
return false;
}
- if (!activeRun || agent !== chatState.agent || appState.currentView !== "chats" || agent.state.isStreaming)
+ if (agent === chatState.agent && threadRef === chatState.threadRef)
+ ctx.composer.setQueuedRuns(threadRef, activeRun.queued);
+ if (
+ !activeRun.runId ||
+ !activeRun.run ||
+ agent !== chatState.agent ||
+ appState.currentView !== "chats" ||
+ agent.state.isStreaming
+ )
return false;
// Pull the transcript before attaching so the turn's triggering user message
// (written by core, not by this tab) is on screen while the run streams.
@@ -2166,6 +2206,7 @@ export function createChatSurface(
state: chatState,
hasLiveRun: () => hasLiveRun(runSlot),
signalLiveRun: (kind, text) => signalLiveRun(runSlot, kind, text),
+ currentTurnOptions,
newChat,
teardown: teardownActiveChat,
resetChatState,
diff --git a/plugins/web-ui/src/composer.ts b/plugins/web-ui/src/composer.ts
index 65ef5a4b1..a103132ce 100644
--- a/plugins/web-ui/src/composer.ts
+++ b/plugins/web-ui/src/composer.ts
@@ -9,6 +9,7 @@ import {
Brain,
Check,
ChevronDown,
+ CornerDownRight,
FileText,
Paperclip,
SlidersHorizontal,
@@ -19,10 +20,14 @@ import {
} from "lucide";
import {
api,
+ ApiError,
fetchRuntimeConfig,
+ queueTurn,
updateRuntimeConfig,
+ withdrawRun,
type ApprovalDecision,
type PendingApproval,
+ type QueuedRun,
type RuntimeConfig,
} from "./core-bridge";
import { errMessage, swallow } from "../../chassis/src/errors";
@@ -38,6 +43,7 @@ import {
getModelOptionsForHarness,
harnessSupportsEffort,
harnessSupportsFastMode,
+ harnessSupportsSteer,
type EffortLevel,
type ModelOption,
type ModelOptionValue,
@@ -226,6 +232,24 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {
const pastedTextIds = new Set<string>();
+ const queuedRuns = new Map<string, QueuedRun[]>();
+
+ function queuedRunsFor(threadRef: string | null): QueuedRun[] {
+ return (threadRef ? queuedRuns.get(threadRef) : undefined) ?? [];
+ }
+
+ function setQueuedRuns(threadRef: string, runs: QueuedRun[]): void {
+ if (runs.length) queuedRuns.set(threadRef, runs);
+ else queuedRuns.delete(threadRef);
+ }
+
+ function forgetQueuedRun(threadRef: string, runId: string): void {
+ setQueuedRuns(
+ threadRef,
+ queuedRunsFor(threadRef).filter((r) => r.runId !== runId),
+ );
+ }
+
let dragDepth = 0;
let skillsLoading = false;
let slashActiveIndex = 0;
@@ -350,7 +374,7 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {
const attachingDisabled = inputBlocked;
let placeholder = "Ask anything";
if (inputBlocked) placeholder = runtimePending ? "Loading runtime…" : "Approve or deny to continue";
- else if (agent.state.isStreaming) placeholder = "Steer the running task…";
+ else if (agent.state.isStreaming) placeholder = "Queue a message for after this turn…";
let composerNotice: TemplateResult | typeof nothing = nothing;
if (composerState.processingFiles) {
composerNotice = html`<div class="composer-note">Preparing files...</div>`;
@@ -428,6 +452,7 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {
`
: nothing
}
+ ${queuedStrip(agent)}
${
approvalPauses.length
? composerApprovalPanel(approvalPauses)
@@ -650,20 +675,64 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {
${icon(ArrowUp, 17)}
</button>`;
}
- const canSteer = Boolean(composerState.draft.trim());
- const steerTitle = composerState.attachments.length
- ? "Steer the running task (attachments stay for your next message)"
- : "Steer the running task";
+ const canQueue = Boolean(composerState.draft.trim());
return html`
<button class="stop-btn" type="button" title="Stop" aria-label="Stop" @click=${() => stopStreaming(agent)}>
${icon(Square, 16)}
</button>
- <button class="send-btn" type="submit" title=${steerTitle} aria-label=${steerTitle} ?disabled=${!canSteer}>
+ <button
+ class="send-btn"
+ type="submit"
+ title="Queue for after this turn"
+ aria-label="Queue for after this turn"
+ ?disabled=${!canQueue}
+ >
${icon(ArrowUp, 17)}
</button>
`;
}
+ function queuedStrip(agent: Agent): TemplateResult | typeof nothing {
+ const queued = queuedRunsFor(ctx.chat.state.threadRef);
+ if (!queued.length) return nothing;
+ const steerable =
+ agent.state.isStreaming && ctx.chat.hasLiveRun() && harnessSupportsSteer(currentModelOption().harnessId);
+ return html`
+ <div class="queued-strip" role="list" aria-label="Queued messages">
+ ${queued.map(
+ (q) => html`
+ <div class="queued-chip" role="listitem">
+ <span class="queued-tag">Queued</span>
+ <span class="queued-text" title=${q.text}>${q.text}</span>
+ <button
+ type="button"
+ class="queued-steer"
+ ?disabled=${!steerable}
+ title=${
+ steerable
+ ? "Steer the running task with this instead of waiting"
+ : "Nothing running can take this — it will go out as its own turn"
+ }
+ @click=${() => void steerQueued(agent, q)}
+ >
+ ${icon(CornerDownRight, 13)}<span>Steer</span>
+ </button>
+ <button
+ type="button"
+ class="chip-x"
+ title="Remove"
+ aria-label="Remove queued message"
+ @click=${() => void removeQueued(agent, q)}
+ >
+ ${icon(X, 13)}
+ </button>
+ </div>
+ `,
+ )}
+ </div>
+ `;
+ }
+
function composerApprovalPanel(approvals: PendingApproval[]): TemplateResult {
const busy = ctx.chat.state.resolvingApprovals.size > 0;
const decide = (decision: ApprovalDecision): void => {
@@ -1102,66 +1171,87 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {
agent.abort();
}
- async function sendSteer(agent: Agent): Promise<void> {
+ async function queueDraft(agent: Agent): Promise<void> {
+ const threadRef = ctx.chat.state.threadRef;
const text = composerState.draft.trim();
- if (!text) return;
- if (ctx.chat.state.threadRef) bumpSessionActivity(ctx.chat.state.threadRef);
+ if (!text || !threadRef) return;
clearActiveDraft();
composerState.draft = "";
composerState.error = "";
- agent.state.messages.push({
- role: "user",
- content: text,
- timestamp: Date.now(),
- steered: true,
- } as unknown as AgentMessage);
ctx.chat.drawActiveChat(agent);
clearComposerDom(agent);
- if (!ctx.chat.hasLiveRun()) {
- // The turn is between run states: submitted but /api/turn hasn't returned the
- // run id yet, or the stream is tearing down. Dropping the message here is a
- // silent no-op the user reads as a dead composer — hold it and deliver when
- // the run slot settles (steer the live run, or resend as an ordinary prompt).
- steerWhenLive(agent, text, 0);
- return;
- }
- await deliverSteer(agent, text);
+ if (!(await enqueueTurn(agent, threadRef, text))) composerState.draft = text;
+ ctx.chat.drawActiveChat(agent);
}
- async function deliverSteer(agent: Agent, text: string): Promise<void> {
+ async function enqueueTurn(agent: Agent, threadRef: string, text: string): Promise<boolean> {
try {
- const outcome = await ctx.chat.signalLiveRun("steer", text);
- if (!outcome.ok) recoverEndedRunSteer(agent, text, outcome);
+ const queued = await queueTurn(threadRef, text, agent, ctx.chat.currentTurnOptions);
+ setQueuedRuns(threadRef, [...queuedRunsFor(threadRef), queued]);
+ bumpSessionActivity(threadRef);
+ return true;
} catch (err) {
- composerState.error = errMessage(err, "Could not steer the running task.");
- ctx.chat.drawActiveChat(agent);
+ composerState.error = errMessage(err, "Could not queue the message.");
+ return false;
}
}
- function steerWhenLive(agent: Agent, text: string, attempt: number): void {
- if (agent !== ctx.chat.state.agent) return;
- if (ctx.chat.hasLiveRun()) {
- void deliverSteer(agent, text);
- return;
+ async function removeQueued(agent: Agent, queued: QueuedRun): Promise<void> {
+ const threadRef = ctx.chat.state.threadRef;
+ if (!threadRef) return;
+ composerState.error = "";
+ try {
+ await withdrawRun(queued.runId);
+ } catch (err) {
+ if (!(err instanceof ApiError && (err.status === 409 || err.status === 404))) {
+ composerState.error = errMessage(err, "Could not remove the queued message.");
+ return ctx.chat.drawActiveChat(agent);
+ }
}
- if (!agent.state.isStreaming) {
- // The run ended without the slot ever going live — recover exactly like a
- // steer that raced the run's end: resend the text as an ordinary prompt.
- recoverEndedRunSteer(agent, text, {});
- return;
+ forgetQueuedRun(threadRef, queued.runId);
+ ctx.chat.drawActiveChat(agent);
+ }
+
+ async function steerQueued(agent: Agent, queued: QueuedRun): Promise<void> {
+ const threadRef = ctx.chat.state.threadRef;
+ if (!threadRef) return;
+ if (!ctx.chat.hasLiveRun()) {
+ composerState.error = "That turn already finished — this message will run as its own turn.";
+ return ctx.chat.drawActiveChat(agent);
}
- if (attempt < 40) {
- window.setTimeout(() => steerWhenLive(agent, text, attempt + 1), 250);
- return;
+ composerState.error = "";
+ try {
+ if (!(await withdrawRun(queued.runId))) return ctx.chat.drawActiveChat(agent);
+ } catch (err) {
+ const started = err instanceof ApiError && err.status === 409;
+ const gone = err instanceof ApiError && err.status === 404;
+ if (started) composerState.error = "That message already started — it's the running turn now.";
+ else if (gone) composerState.error = "That message was already removed in another tab.";
+ else composerState.error = errMessage(err, "Could not steer with that message.");
+ if (started || gone) forgetQueuedRun(threadRef, queued.runId);
+ return ctx.chat.drawActiveChat(agent);
}
- const last = agent.state.messages[agent.state.messages.length - 1] as
- { role?: string; content?: unknown } | undefined;
- if (last?.role === "user" && last.content === text) agent.state.messages.pop();
- // Don't clobber anything typed while the message was held: put the held text
- // back in front of the newer draft instead of overwriting it.
- composerState.draft = composerState.draft.trim() ? `${text}\n\n${composerState.draft}` : text;
- composerState.error = "Could not deliver the message — the running task never settled. It is back in the composer.";
+ forgetQueuedRun(threadRef, queued.runId);
+ bumpSessionActivity(threadRef);
+ agent.state.messages.push({
+ role: "user",
+ content: queued.text,
+ timestamp: Date.now(),
+ steered: true,
+ } as unknown as AgentMessage);
ctx.chat.drawActiveChat(agent);
+
+ try {
+ const outcome = await ctx.chat.signalLiveRun("steer", queued.text);
+ if (!outcome.ok) recoverEndedRunSteer(agent, queued.text, outcome);
+ } catch (err) {
+ composerState.error = errMessage(err, "Could not steer the running task.");
+ const last = agent.state.messages[agent.state.messages.length - 1] as
+ { role?: string; content?: unknown } | undefined;
+ if (last?.role === "user" && last.content === queued.text) agent.state.messages.pop();
+ if (!(await enqueueTurn(agent, threadRef, queued.text))) composerState.draft = queued.text;
+ ctx.chat.drawActiveChat(agent);
+ }
}
// The run ended before the steer landed (the client believed it was still live).
@@ -1216,7 +1306,7 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {
if (composerState.pasteView) closePasteView(agent);
if (ctx.chat.state.resolvingApprovals.size > 0) return;
if (ctx.chat.hasUnresolvedApproval()) return;
- if (agent.state.isStreaming) return sendSteer(agent);
+ if (agent.state.isStreaming) return queueDraft(agent);
const text = composerState.draft.trim();
if (!text && composerState.attachments.length === 0) return;
if (ctx.chat.state.threadRef) {
@@ -1499,6 +1589,8 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {
return {
state: composerState,
composerForm,
+ queuedRunsFor,
+ setQueuedRuns,
resetComposer,
focusComposerEnd,
resizeComposer,
diff --git a/plugins/web-ui/src/conv-types.ts b/plugins/web-ui/src/conv-types.ts
index 6ae240709..652c368be 100644
--- a/plugins/web-ui/src/conv-types.ts
+++ b/plugins/web-ui/src/conv-types.ts
@@ -2,7 +2,14 @@ import type { Agent } from "@earendil-works/pi-agent-core";
import type { TemplateResult } from "lit";
import type { DensityTier } from "./density";
import type { Attachment } from "@earendil-works/pi-web-ui";
-import type { ApprovalDecision, CoreSession, PendingApproval, entriesToMessages } from "./core-bridge";
+import type {
+ ApprovalDecision,
+ CoreSession,
+ PendingApproval,
+ QueuedRun,
+ TurnOptions,
+ entriesToMessages,
+} from "./core-bridge";
import type { EffortLevel, ModelOption } from "./model-options";
import type { ComposerMenu } from "./composer";
@@ -56,6 +63,7 @@ export interface ChatSurface {
state: ChatState;
hasLiveRun(): boolean;
signalLiveRun(kind: "abort" | "steer", text?: string): Promise<import("./core-bridge").SignalOutcome>;
+ currentTurnOptions(): TurnOptions;
newChat(context?: { scopeId: string; name: string | null }): string;
teardown(): void;
resetChatState(): void;
@@ -107,6 +115,8 @@ interface ComposerState {
export interface ComposerSurface {
state: ComposerState;
composerForm(agent: Agent): TemplateResult;
+ queuedRunsFor(threadRef: string | null): QueuedRun[];
+ setQueuedRuns(threadRef: string, runs: QueuedRun[]): void;
resetComposer(): void;
focusComposerEnd(): void;
resizeComposer(): void;
diff --git a/plugins/web-ui/src/core-bridge.ts b/plugins/web-ui/src/core-bridge.ts
index bfee77f88..c8cf68e6b 100644
--- a/plugins/web-ui/src/core-bridge.ts
+++ b/plugins/web-ui/src/core-bridge.ts
@@ -346,8 +346,14 @@ export interface TurnOptions {
}
export interface ActiveRun {
+ runId: string | null;
+ run: RunPoll | null;
+ queued: QueuedRun[];
+}
+
+export interface QueuedRun {
runId: string;
- run: RunPoll;
+ text: string;
}
export function isContinuable(s: Pick<CoreSession, "threadRef" | "scopeId">, user: string): boolean {
@@ -590,10 +596,32 @@ export function makeCoreStreamFn(
return fn as unknown as StreamFn;
}
-export async function activeRunForThread(threadRef: string): Promise<ActiveRun | null> {
+export async function activeRunForThread(threadRef: string): Promise<ActiveRun> {
const q = new URLSearchParams({ threadRef });
- const r = await api<{ runId?: string | null; run?: RunPoll | null }>(`/api/runs/active?${q.toString()}`);
- return r.runId && r.run ? { runId: r.runId, run: r.run } : null;
+ const r = await api<{ runId?: string | null; run?: RunPoll | null; queued?: QueuedRun[] }>(
+ `/api/runs/active?${q.toString()}`,
+ );
+ const live = r.runId && r.run ? { runId: r.runId, run: r.run } : { runId: null, run: null };
+ return { ...live, queued: r.queued ?? [] };
+}
+
+export async function queueTurn(
+ threadRef: string,
+ text: string,
+ agent: Agent,
+ getTurnOptions?: () => TurnOptions,
+): Promise<QueuedRun> {
+ const submit = await api<{ runId?: string }>("/api/turn", {
+ method: "POST",
+ body: JSON.stringify(turnRequestBody(threadRef, text, agent.state.model, agent, getTurnOptions)),
+ });
+ if (!submit.runId) throw new Error("Could not queue the message.");
+ return { runId: submit.runId, text };
+}
+
+export async function withdrawRun(runId: string): Promise<boolean> {
+ const r = await api<{ withdrawn?: boolean }>(runPath(runId, "/withdraw"), { method: "POST" });
+ return r.withdrawn === true;
}
export function makeRunResumeStreamFn(
@@ -649,6 +677,34 @@ export function makeOpenerStreamFn(
return fn as unknown as StreamFn;
}
+function turnRequestBody(
+ threadRef: string,
+ text: string,
+ model: Model<Api>,
+ agent: Agent,
+ getTurnOptions?: () => TurnOptions,
+ attachments: CoreAttachment[] = [],
+): Record<string, unknown> {
+ const turnOptions = getTurnOptions?.() ?? {};
+ const thinkingLevel =
+ !turnOptions.harness || harnessSupportsEffort(turnOptions.harness)
+ ? (turnOptions.effortLevel ?? agent.state.thinkingLevel ?? defaultEffortForModel(model))
+ : undefined;
+ const timezone = browserTimezone();
+ return {
+ text,
+ threadRef,
+ ...(turnOptions.harness ? { harness: turnOptions.harness } : {}),
+ model: model.id,
+ ...(thinkingLevel ? { thinkingLevel } : {}),
+ ...(typeof turnOptions.fastMode === "boolean" ? { fastMode: turnOptions.fastMode } : {}),
+ ...(timezone ? { timezone } : {}),
+ ...(turnOptions.scopeId ? { scopeId: turnOptions.scopeId } : {}),
+ ...(turnOptions.channelName ? { channelName: turnOptions.channelName } : {}),
+ ...(attachments.length ? { attachments } : {}),
+ };
+}
+
async function drive(
stream: AssistantMessageEventStream,
model: Model<Api>,
@@ -665,12 +721,6 @@ async function drive(
const work: WorkBlock = { status: "thinking", activity: [] };
(partial as AssistantWork).work = work;
const notify = (): void => onWork?.(work);
- const turnOptions = getTurnOptions?.() ?? {};
- const thinkingLevel =
- !turnOptions.harness || harnessSupportsEffort(turnOptions.harness)
- ? (turnOptions.effortLevel ?? agent.state.thinkingLevel ?? defaultEffortForModel(model))
- : undefined;
- const timezone = browserTimezone();
try {
notify();
stream.push({ type: "start", partial });
@@ -683,16 +733,7 @@ async function drive(
const submit = await api<{ status?: string; runId?: string; reply?: string }>("/api/turn", {
method: "POST",
body: JSON.stringify({
- text,
- threadRef,
- ...(turnOptions.harness ? { harness: turnOptions.harness } : {}),
- model: model.id,
- ...(thinkingLevel ? { thinkingLevel } : {}),
- ...(typeof turnOptions.fastMode === "boolean" ? { fastMode: turnOptions.fastMode } : {}),
- ...(timezone ? { timezone } : {}),
- ...(turnOptions.scopeId ? { scopeId: turnOptions.scopeId } : {}),
- ...(turnOptions.channelName ? { channelName: turnOptions.channelName } : {}),
- ...(attachments.length ? { attachments } : {}),
+ ...turnRequestBody(threadRef, text, model, agent, getTurnOptions, attachments),
...(approval ? { approval } : {}),
...(opener ? { proactiveOpener: true } : {}),
}),
diff --git a/plugins/web-ui/src/model-options.ts b/plugins/web-ui/src/model-options.ts
index 5ee2c799f..658cebe4c 100644
--- a/plugins/web-ui/src/model-options.ts
+++ b/plugins/web-ui/src/model-options.ts
@@ -212,6 +212,10 @@ export function harnessSupportsFastMode(harnessId: string): boolean {
return harnessId === "pi" || harnessId === "claude";
}
+export function harnessSupportsSteer(harnessId: string): boolean {
+ return harnessId === "pi" || harnessId === "claude" || harnessId === "codex" || harnessId === "opencode";
+}
+
export function defaultEffortForModel(model: Model<Api>): EffortLevel {
const provider = String(model.provider ?? model.api ?? "").toLowerCase();
return provider.includes("anthropic") ? "low" : "auto";
diff --git a/plugins/web-ui/src/shell.css b/plugins/web-ui/src/shell.css
index 557218850..a5b17752d 100644
--- a/plugins/web-ui/src/shell.css
+++ b/plugins/web-ui/src/shell.css
@@ -1454,6 +1454,65 @@ a.chat-row-open {
gap: 6px;
margin-top: 9px;
}
+.queued-strip {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ margin-top: 9px;
+}
+.queued-chip {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ min-height: 28px;
+ padding: 4px 6px 4px 8px;
+ border: 1px dashed var(--border);
+ border-radius: 8px;
+ background: var(--background);
+ color: var(--muted-foreground);
+ font-size: 12px;
+ line-height: 1.2;
+}
+.queued-tag {
+ flex: none;
+ text-transform: uppercase;
+ letter-spacing: 0.04em;
+ font-size: 10px;
+ opacity: 0.75;
+}
+.queued-text {
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ color: var(--foreground);
+}
+.queued-steer {
+ flex: none;
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ padding: 2px 8px;
+ border: 1px solid var(--border);
+ border-radius: 999px;
+ background: var(--background);
+ color: var(--foreground);
+ font-size: 11px;
+ cursor: pointer;
+ transition: background 0.12s ease;
+}
+.queued-steer:hover:not(:disabled) {
+ background: var(--secondary);
+}
+.queued-steer:disabled {
+ opacity: 0.45;
+ cursor: default;
+}
+.queued-steer:focus-visible {
+ outline: 2px solid color-mix(in srgb, var(--foreground) 35%, transparent);
+ outline-offset: 2px;
+}
.file-chip {
display: inline-flex;
align-items: center;
@@ -6925,6 +6984,7 @@ h3.ambient-field-label {
}
[data-density] .runtime-upgrade,
[data-density] .attachment-strip,
+[data-density] .queued-strip,
[data-density] .composer-approval-panel,
[data-density] .composer-note,
[data-density] .composer-error {
diff --git a/plugins/web-ui/test/active-run-discovery-route.test.ts b/plugins/web-ui/test/active-run-discovery-route.test.ts
new file mode 100644
index 000000000..25c0a49fe
--- /dev/null
+++ b/plugins/web-ui/test/active-run-discovery-route.test.ts
@@ -0,0 +1,108 @@
+import { mintPortalIdentity, PORTAL_IDENTITY_HEADER } from "../../chassis/src/portal-identity.ts";
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { createServer, type IncomingMessage } from "node:http";
+import type { AddressInfo } from "node:net";
+
+// The scenario Bugbot caught on this feature: a surface instance that saw only the QUEUE
+// submission holds the pending run in its local index and nothing else. Core's durable answer
+// names the actual head. Discovery must report core's head as the live run — a pending turn
+// queued behind a running one is never "active", however this instance learned of it.
+const THREAD = "web:alice:t-disc";
+const runStatus = new Map<string, string>([
+ ["run-live", "running"],
+ ["run-queued", "pending"],
+]);
+let durableHead: string | null = "run-live";
+let queued: Array<{ runId: string; text: string }> = [{ runId: "run-queued", text: "after this" }];
+
+const core = createServer((req: IncomingMessage, res) => {
+ const u = new URL(req.url ?? "", "http://core");
+ const reply = (status: number, body: unknown): void => {
+ res.writeHead(status, { "content-type": "application/json" });
+ res.end(JSON.stringify(body));
+ };
+ if (req.method === "POST" && u.pathname === "/v1/turns") {
+ let body = "";
+ req.on("data", (c) => (body += c));
+ return void req.on("end", () => reply(200, { status: "queued", runId: "run-queued" }));
+ }
+ if (req.method === "GET" && u.pathname === "/v1/runs")
+ return reply(200, { runId: durableHead, ...(queued.length ? { queued } : {}) });
+ const m = /^\/v1\/runs\/([^/]+)$/.exec(u.pathname);
+ if (req.method === "GET" && m) {
+ const status = runStatus.get(decodeURIComponent(m[1]!));
+ return status ? reply(200, { status }) : reply(404, { error: "not_found" });
+ }
+ reply(404, { error: "not_found" });
+});
+await new Promise<void>((r) => core.listen(0, r));
+
+const SECRET = "active-run-discovery-test";
+process.env.CORE_API_URL = `http://localhost:${(core.address() as AddressInfo).port}`;
+process.env.CORE_SIGNING_SECRET = SECRET;
+process.env.WEB_UI_PRINCIPALS = "alice";
+
+const { handler } = await import("../server/index.ts");
+const surface = createServer((req, res) => void handler(req, res));
+await new Promise<void>((r) => surface.listen(0, r));
+const base = `http://localhost:${(surface.address() as AddressInfo).port}`;
+const IDENTITY = {
+ cookie: "webuiuser=alice",
+ [PORTAL_IDENTITY_HEADER]: mintPortalIdentity({ p: "alice", exp: Date.now() + 60_000 }, SECRET),
+ "content-type": "application/json",
+};
+
+test.after(() => {
+ surface.close();
+ core.close();
+});
+
+test("a pending run this instance remembered never masks core's running head", async () => {
+ // Seed the instance-local index with ONLY the queued (pending) run — exactly what an instance
+ // that handled the queue submission but not the original send looks like.
+ const seed = await fetch(`${base}/api/turn`, {
+ method: "POST",
+ headers: IDENTITY,
+ body: JSON.stringify({ text: "after this", threadRef: THREAD }),
+ });
+ assert.equal(seed.status, 200);
+ assert.equal(((await seed.json()) as { runId?: string }).runId, "run-queued");
+
+ const r = await fetch(`${base}/api/runs/active?threadRef=${encodeURIComponent(THREAD)}`, { headers: IDENTITY });
+ assert.equal(r.status, 200);
+ const body = (await r.json()) as { runId: string | null; queued?: Array<{ runId: string }> };
+ assert.equal(body.runId, "run-live", "core's durable head is the live run, not the remembered pending one");
+ assert.deepEqual(
+ body.queued?.map((q) => q.runId),
+ ["run-queued"],
+ "the pending turn stays reported as queued",
+ );
+});
+
+test("when core's head IS the remembered run, it reports live once and never doubles as queued", async () => {
+ durableHead = "run-queued";
+ runStatus.set("run-queued", "running");
+ queued = [{ runId: "run-queued", text: "after this" }];
+ const r = await fetch(`${base}/api/runs/active?threadRef=${encodeURIComponent(THREAD)}`, { headers: IDENTITY });
+ assert.equal(r.status, 200);
+ const body = (await r.json()) as { runId: string | null; queued?: Array<{ runId: string }> };
+ assert.equal(body.runId, "run-queued");
+ assert.equal(body.queued, undefined, "the followed run is filtered out of the queue");
+});
+
+test("nothing in flight answers null with whatever core still holds queued", async () => {
+ durableHead = null;
+ // Both remembered runs are terminal now: the walk prunes them instead of reporting one.
+ runStatus.set("run-queued", "done");
+ runStatus.set("run-live", "done");
+ queued = [{ runId: "run-later", text: "still waiting" }];
+ const r = await fetch(`${base}/api/runs/active?threadRef=${encodeURIComponent(THREAD)}`, { headers: IDENTITY });
+ assert.equal(r.status, 200);
+ const body = (await r.json()) as { runId: string | null; queued?: Array<{ runId: string }> };
+ assert.equal(body.runId, null);
+ assert.deepEqual(
+ body.queued?.map((q) => q.runId),
+ ["run-later"],
+ );
+});
diff --git a/plugins/web-ui/test/composer-source.test.ts b/plugins/web-ui/test/composer-source.test.ts
index 5a0a31455..5f503874c 100644
--- a/plugins/web-ui/test/composer-source.test.ts
+++ b/plugins/web-ui/test/composer-source.test.ts
@@ -54,14 +54,17 @@ test("attaching files is allowed while a turn is streaming", () => {
assert.ok(guards.length > 0, "streaming still gates steer/send routing");
});
-test("steering with pending attachments explains they ride the next message", () => {
- assert.match(composer, /attachments stay for your next message/);
+test("a mid-turn submit queues — attachments cannot ride a queued message and stay for the next", () => {
+ // Mid-turn Enter queues through core (queueDraft), so the steer-button attachment note is gone;
+ // the queue button gates only on draft text, never on the run slot.
+ assert.match(composer, /title="Queue for after this turn"/);
+ assert.doesNotMatch(composer, /attachments stay for your next message/);
});
test("a steer whose run already ended is recovered, never silently dropped", () => {
- // sendSteer must inspect the signal outcome and route a failed steer through recovery.
- assert.match(composer, /const outcome = await ctx\.chat\.signalLiveRun\("steer", text\);/);
- assert.match(composer, /if \(!outcome\.ok\) recoverEndedRunSteer\(agent, text, outcome\);/);
+ // steerQueued must inspect the signal outcome and route a failed steer through recovery.
+ assert.match(composer, /const outcome = await ctx\.chat\.signalLiveRun\("steer", queued\.text\);/);
+ assert.match(composer, /if \(!outcome\.ok\) recoverEndedRunSteer\(agent, queued\.text, outcome\);/);
// Replayed by core → detach from the stale stream and attach to the fresh run.
assert.match(composer, /function recoverEndedRunSteer\(/);
assert.match(composer, /attachWhenIdle\(agent, 0\);/);
diff --git a/plugins/web-ui/test/queue-by-default.test.ts b/plugins/web-ui/test/queue-by-default.test.ts
new file mode 100644
index 000000000..cc76c77e4
--- /dev/null
+++ b/plugins/web-ui/test/queue-by-default.test.ts
@@ -0,0 +1,228 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { existsSync, readFileSync, readdirSync } from "node:fs";
+import { harnessSupportsSteer } from "../src/model-options.ts";
+
+const composer = readFileSync(new URL("../src/composer.ts", import.meta.url), "utf8");
+const chat = readFileSync(new URL("../src/chat.ts", import.meta.url), "utf8");
+const bridge = readFileSync(new URL("../src/core-bridge.ts", import.meta.url), "utf8");
+const server = readFileSync(new URL("../server/index.ts", import.meta.url), "utf8");
+
+test("a mid-turn Enter queues the message — it no longer steers the running turn", () => {
+ assert.match(composer, /if \(agent\.state\.isStreaming\) return queueDraft\(agent\);/);
+ assert.doesNotMatch(composer, /isStreaming\) return sendSteer\(/);
+ assert.match(composer, /placeholder = "Queue a message for after this turn…"/);
+ assert.match(composer, /title="Queue for after this turn"/);
+});
+
+// The whole point of the rewrite: the queue is core's, not the browser's. A queued message is a
+// real run core will execute whether or not this tab survives, so there is nothing to flush, no
+// per-tab store to keep in sync, and no way for two tabs to send the same message twice.
+test("the queue lives in core, not in the browser", () => {
+ assert.ok(!existsSync(new URL("../src/message-queue.ts", import.meta.url)), "the localStorage queue module is gone");
+ for (const [name, src] of [
+ ["composer", composer],
+ ["chat", chat],
+ ] as const) {
+ assert.doesNotMatch(src, /"web-ui:queued"/, `${name} persists no queue of its own`);
+ assert.doesNotMatch(src, /flushQueuedMessages/, `${name} has no flush path left`);
+ }
+ assert.match(
+ composer,
+ /const queuedRuns = new Map<string, QueuedRun\[\]>\(\);/,
+ "what the composer holds is a view of core's queue, rebuilt from core — not a store",
+ );
+ assert.match(composer, /const queued = await queueTurn\(threadRef, text, agent, ctx\.chat\.currentTurnOptions\);/);
+ assert.match(
+ bridge,
+ /export async function queueTurn\([\s\S]{0,600}?api<\{ runId\?: string \}>\("\/api\/turn"/,
+ "queuing is an ordinary turn submission; core enqueues it behind the live run",
+ );
+});
+
+test("a queued turn carries the same model, effort and scope a typed one would", () => {
+ assert.match(bridge, /function turnRequestBody\(/);
+ const body = bridge.slice(bridge.indexOf("function turnRequestBody"));
+ assert.match(body, /thinkingLevel/);
+ assert.match(body, /scopeId: turnOptions\.scopeId/);
+ assert.match(bridge, /\.\.\.turnRequestBody\(threadRef, text, model, agent, getTurnOptions, attachments\),/);
+ assert.match(bridge, /turnRequestBody\(threadRef, text, agent\.state\.model, agent, getTurnOptions\)/);
+});
+
+// Found in live QA: when the Steer control was swapped in and out of an existing strip, a tab that
+// opened the conversation BEFORE its run attached (the queue draws first, the live run a moment
+// later) ended up with a Steer button that received clicks but ran nothing. Whether the harness can
+// steer is fixed for the conversation, so the button's presence must be too — only its enabled
+// state may change.
+test("the Steer control's presence is fixed for the conversation; only enablement changes", () => {
+ const strip = composer.slice(
+ composer.indexOf("function queuedStrip"),
+ composer.indexOf("function composerApprovalPanel"),
+ );
+ assert.match(strip, /\?disabled=\$\{!steerable\}/, "an unusable Steer is disabled, never removed");
+ assert.doesNotMatch(
+ strip,
+ /steerable\s*\?\s*html`<button/,
+ "the button must not be conditionally inserted into a strip that is already on screen",
+ );
+});
+
+test("steering is reachable only as an explicit act on a queued row", () => {
+ const strip = composer.slice(
+ composer.indexOf("function queuedStrip"),
+ composer.indexOf("function composerApprovalPanel"),
+ );
+ assert.match(strip, /class="queued-steer"/);
+ assert.match(strip, /steerQueued\(agent, q\)/);
+ assert.match(strip, /class="chip-x"[\s\S]{0,240}removeQueued\(agent, q\)/);
+ assert.match(
+ composer,
+ /const steerable =\s*agent\.state\.isStreaming && ctx\.chat\.hasLiveRun\(\) && harnessSupportsSteer\(currentModelOption\(\)\.harnessId\);/,
+ "Steer acts only against a live run on a harness that can fold one in",
+ );
+});
+
+// The one ordering that matters: withdraw is atomic, so putting it first means the message is
+// either steered or run — never both, and never neither.
+test("Steer withdraws the queued run before it signals, and only then shows the steered row", () => {
+ const fn = composer.slice(
+ composer.indexOf("async function steerQueued"),
+ composer.indexOf("async function sendPrompt"),
+ );
+ const withdraw = fn.indexOf("await withdrawRun(queued.runId)");
+ const signal = fn.indexOf('signalLiveRun("steer"');
+ const push = fn.indexOf("agent.state.messages.push");
+ assert.ok(withdraw > 0 && signal > withdraw, "the run is off the queue before its text is folded in");
+ assert.ok(
+ push > withdraw && signal > push,
+ "the steered row shows before the signal so a run that ended first can recover it in place",
+ );
+ assert.match(
+ fn,
+ /if \(!outcome\.ok\) recoverEndedRunSteer\(agent, queued\.text, outcome\);/,
+ "a steer the run outlived is recovered (replayed run followed, or resent as its own turn)",
+ );
+ assert.match(fn, /if \(!\(await withdrawRun\(queued\.runId\)\)\) return ctx\.chat\.drawActiveChat\(agent\);/);
+ assert.match(
+ fn,
+ /err instanceof ApiError && err\.status === 409[\s\S]{0,240}?already started/,
+ "losing to the claim is reported as running, not as a failure to steer",
+ );
+ assert.match(
+ fn,
+ /err instanceof ApiError && err\.status === 404[\s\S]{0,240}?already removed/,
+ "a run another tab withdrew is reported gone",
+ );
+ assert.match(
+ fn,
+ /if \(started \|\| gone\) forgetQueuedRun\(threadRef, queued\.runId\);/,
+ "both ways out of the queue clear the chip — no ghost row survives a lost race",
+ );
+ assert.match(
+ fn,
+ /catch \(err\) \{[\s\S]{0,600}?Could not steer the running task[\s\S]{0,600}?await enqueueTurn\(agent, threadRef, queued\.text\)/,
+ "a steer that never reached core puts the message back on the queue as its own turn",
+ );
+});
+
+test("× cancels the queued run in core, and treats a lost race as running rather than removed", () => {
+ const fn = composer.slice(
+ composer.indexOf("async function removeQueued"),
+ composer.indexOf("async function steerQueued"),
+ );
+ assert.match(fn, /await withdrawRun\(queued\.runId\)/);
+ assert.match(
+ fn,
+ /if \(!\(err instanceof ApiError && \(err\.status === 409 \|\| err\.status === 404\)\)\)/,
+ "409 (claimed) and 404 (withdrawn elsewhere) both mean the run left the queue — the chip goes",
+ );
+ assert.match(bridge, /export async function withdrawRun\(runId: string\): Promise<boolean>/);
+ assert.match(
+ server,
+ /path\.endsWith\("\/withdraw"\)[\s\S]{0,320}?\/v1\/runs\/\$\{encodeURIComponent\(id\)\}\/withdraw/,
+ );
+});
+
+// A queue outlives the run it was sent behind: when the head finishes between core's read and the
+// surface's, the answer has no live run but the queue is still real. Reporting the followed run as
+// queued, or dropping the queue with the run, both put the strip out of step with core.
+test("a thread with no live run still reports its queue, and the followed run is never in it", () => {
+ assert.match(server, /const waiting = queued\.filter\(\(q\) => q\.runId !== runId\);/);
+ assert.match(bridge, /queued: QueuedRun\[\];/, "the queue is always present, not optional");
+ assert.match(bridge, /return \{ \.\.\.live, queued: r\.queued \?\? \[\] \};/);
+ assert.match(
+ bridge,
+ /export async function activeRunForThread\(threadRef: string\): Promise<ActiveRun>/,
+ "the call no longer answers null, which used to take the queue down with it",
+ );
+});
+
+test("the strip renders core's queue, refreshed from the same read that names the live run", () => {
+ assert.match(composer, /function queuedStrip[\s\S]{0,140}?queuedRunsFor\(ctx\.chat\.state\.threadRef\)/);
+ assert.match(chat, /setQueuedRuns\(threadRef, activeRun\.queued\)/);
+ assert.match(bridge, /queued\?: QueuedRun\[\]/);
+ assert.match(server, /json\(res, 200, \{ runId, run, \.\.\.\(waiting\.length \? \{ queued: waiting \} : \{\}\) \}\)/);
+});
+
+// Nothing is sent when a turn settles: core already started the next queued run. The client's only
+// job is to show it, so a client that never comes back costs the person nothing but the view.
+test("settling a turn follows the next queued run instead of sending it", () => {
+ assert.match(chat, /void followNextQueuedRun\(agent, threadRef, normalStreamFn, onWork\);/);
+ const fn = chat.slice(
+ chat.indexOf("async function followNextQueuedRun"),
+ chat.indexOf("async function resumeTrackedRun"),
+ );
+ assert.match(fn, /makeRunResumeStreamFn\(active\.runId, active\.run, onWork, runSlot\)/, "it attaches to core's run");
+ assert.doesNotMatch(fn, /queueTurn/, "it never submits anything");
+ assert.match(
+ fn,
+ /await \(recorded \? agent\.continue\(\) : agent\.prompt\(next!\.text\)\)/,
+ "an already-recorded turn is resumed, never prompted a second time onto the screen",
+ );
+ assert.match(fn, /await refreshTranscriptFromEntries\(agent\)/);
+ // A second tab watching the same conversation never saw the send, so only core can say what is
+ // still queued — trusting this tab's list left it drawing a turn a worker had already claimed.
+ assert.match(fn, /active = await activeRunForThread\(threadRef\)/, "the queue is re-read from core on settle");
+ assert.match(fn, /setQueuedRuns\(threadRef, active\.queued\)/, "core's answer replaces the list");
+ assert.match(
+ fn,
+ /const next = ctx\.composer\.queuedRunsFor\(threadRef\)\.find\(\(r\) => r\.runId === active\.runId\)/,
+ "it renders the live run as ours only when it is one this tab queued",
+ );
+ // A tab that was already open when ANOTHER tab queued work has an empty local list. Bailing on
+ // that emptiness meant it never asked core, so it sat idle through a run core had already
+ // started — the exact staleness re-reading core exists to cure.
+ assert.doesNotMatch(fn, /queuedRunsFor\(threadRef\)\.length\) return;/, "emptiness must not skip the re-read");
+ assert.match(
+ fn,
+ /const recorded = \(agent\.state\.messages\.at\(-1\) as \{ role\?: string \} \| undefined\)\?\.role === "user";/,
+ "a trailing user entry is how a tab recognises a queued turn it never sent",
+ );
+});
+
+// A spine-routed turn's `text` is a <wake> envelope; the person's words are in displayText. A
+// surface that renders `text` shows the envelope, and Steer would fold the envelope into the live
+// turn in place of the message.
+test("the queue exposes what the person typed, never the wake envelope that wraps it", () => {
+ const appTurn = readFileSync(new URL("../../../src/api/app-turn.ts", import.meta.url), "utf8");
+ const fn = appTurn.slice(appTurn.indexOf("async activeRunForThread"), appTurn.indexOf("async withdrawRun"));
+ assert.match(fn, /text: run\.request\.displayText \?\? run\.request\.text \?\? ""/);
+});
+
+// The Steer button is only honest if the harness running the conversation can actually fold a
+// mid-turn message in. Core declares that per adapter; this keeps the client's copy from drifting.
+test("every harness core says can steer is one the web UI offers Steer for", () => {
+ const dir = new URL("../../../src/harness/", import.meta.url);
+ const declared = new Map<string, boolean>();
+ for (const file of readdirSync(dir)) {
+ if (!file.endsWith("-harness.ts")) continue;
+ const src = readFileSync(new URL(file, dir), "utf8");
+ const id = /defineHarness\(\s*\{\s*id:\s*"([^"]+)"/.exec(src)?.[1] ?? file.replace("-harness.ts", "");
+ const caps = /capabilities: new Set\(\[([^\]]*)\]\)/.exec(src)?.[1] ?? "";
+ declared.set(id, caps.includes('"steer"'));
+ }
+ assert.ok(declared.size >= 4, `expected to find the harness adapters, saw ${[...declared.keys()].join(", ")}`);
+ for (const [id, canSteer] of declared) {
+ assert.equal(harnessSupportsSteer(id), canSteer, `harnessSupportsSteer("${id}") disagrees with core`);
+ }
+});
diff --git a/plugins/web-ui/test/steer-recovery-source.test.ts b/plugins/web-ui/test/steer-recovery-source.test.ts
index b101dc6c3..d4114a0fe 100644
--- a/plugins/web-ui/test/steer-recovery-source.test.ts
+++ b/plugins/web-ui/test/steer-recovery-source.test.ts
@@ -28,24 +28,31 @@ test("resuming a tracked run pulls the transcript first so the triggering messag
const composer = readFileSync(new URL("../src/composer.ts", import.meta.url), "utf8");
-test("a steer typed before the run slot goes live is held and delivered, never dropped", () => {
- const at = composer.indexOf("async function sendSteer");
+test("a message typed mid-turn is never dropped by the run-slot window — it queues through core", () => {
+ // sendSteer's held-steer machinery (steerWhenLive/deliverSteer) is gone: mid-turn Enter now
+ // queues via POST /api/turn regardless of run-slot state, so there is no submit window in
+ // which a message can silently vanish. The queue path gates only on text and thread.
+ const at = composer.indexOf("async function queueDraft");
assert.ok(at >= 0);
- const body = composer.slice(at, composer.indexOf("async function deliverSteer", at));
- // the old guard silently returned when the slot had no run id yet
- assert.doesNotMatch(
+ const body = composer.slice(at, composer.indexOf("async function enqueueTurn", at));
+ assert.doesNotMatch(body, /hasLiveRun\(\)/, "queueing must not depend on the run slot");
+ assert.match(body, /if \(!text \|\| !threadRef\) return;/);
+ assert.match(
body,
- /if \(!text \|\| !ctx\.chat\.hasLiveRun\(\)\) return;/,
- "steer dropped in the submit window",
+ /if \(!\(await enqueueTurn\(agent, threadRef, text\)\)\) composerState\.draft = text;/,
+ "a queue core never took goes back in the composer",
);
- assert.match(body, /steerWhenLive\(agent, text, 0\);/);
+ assert.ok(composer.indexOf("function steerWhenLive") < 0, "the held-steer shim is gone with its window");
});
-test("steerWhenLive settles every way a run slot can: live steer, ended resend, timeout restore", () => {
- const at = composer.indexOf("function steerWhenLive");
+test("a queued steer the run outlived settles every way: replay followed, ended resend, requeue", () => {
+ const at = composer.indexOf("async function steerQueued");
assert.ok(at >= 0);
- const body = composer.slice(at, composer.indexOf("// The run ended before the steer landed", at));
- assert.match(body, /void deliverSteer\(agent, text\);/);
- assert.match(body, /recoverEndedRunSteer\(agent, text, \{\}\);/);
- assert.match(body, /composerState\.draft = composerState\.draft\.trim\(\)/);
+ const body = composer.slice(at, composer.indexOf("function recoverEndedRunSteer", at));
+ assert.match(body, /if \(!outcome\.ok\) recoverEndedRunSteer\(agent, queued\.text, outcome\);/);
+ assert.match(
+ body,
+ /if \(!\(await enqueueTurn\(agent, threadRef, queued\.text\)\)\) composerState\.draft = queued\.text;/,
+ "a signal that never reached core re-queues the withdrawn text",
+ );
});
diff --git a/src/api/app-turn.ts b/src/api/app-turn.ts
index a038be37b..d4ece64fd 100644
--- a/src/api/app-turn.ts
+++ b/src/api/app-turn.ts
@@ -36,6 +36,7 @@ export function createTurnMethods(
| "pendingApprovalForThread"
| "getRun"
| "activeRunForThread"
+ | "withdrawRun"
| "signalRun"
| "replayOrphanedRunSignals"
> {
@@ -486,8 +487,22 @@ export function createTurnMethods(
},
async activeRunForThread(threadRef, viewer) {
- const run = await deps.runs.activeForThread(threadRef);
- return run && (!viewer || (await viewerMayUseRun(run, viewer))) ? { runId: run.id } : null;
+ const inFlight = await deps.runs.inFlightForThread(threadRef);
+ const visible: typeof inFlight = [];
+ for (const run of inFlight) if (!viewer || (await viewerMayUseRun(run, viewer))) visible.push(run);
+ const live = visible[0];
+ if (!live) return null;
+ const queued = visible
+ .slice(1)
+ .map((run) => ({ runId: run.id, text: run.request.displayText ?? run.request.text ?? "" }));
+ return { runId: live.id, ...(queued.length ? { queued } : {}) };
+ },
+
+ async withdrawRun(runId, viewer) {
+ const run = await deps.runs.get(runId);
+ if (!run) return { withdrawn: false, reason: "not_found" };
+ if (viewer && !(await viewerMayUseRun(run, viewer))) return { withdrawn: false, reason: "not_found" };
+ return (await deps.runs.withdraw(runId)) ? { withdrawn: true } : { withdrawn: false, reason: "started" };
},
async signalRun(runId, signal, viewer) {
diff --git a/src/api/app-types.ts b/src/api/app-types.ts
index f89e39461..c6b5536bc 100644
--- a/src/api/app-types.ts
+++ b/src/api/app-types.ts
@@ -239,7 +239,11 @@ export interface App {
startedAt: number | null;
finishedAt: number | null;
} | null>;
- activeRunForThread(threadRef: string, viewer?: string): Promise<{ runId: string } | null>;
+ activeRunForThread(
+ threadRef: string,
+ viewer?: string,
+ ): Promise<{ runId: string; queued?: Array<{ runId: string; text: string }> } | null>;
+ withdrawRun(runId: string, viewer?: string): Promise<{ withdrawn: boolean; reason?: string }>;
signalRun(
runId: string,
signal: RunSignal,
diff --git a/src/api/routes/turns.ts b/src/api/routes/turns.ts
index ce7b4cd26..14d841334 100644
--- a/src/api/routes/turns.ts
+++ b/src/api/routes/turns.ts
@@ -98,7 +98,15 @@ async function getActiveRunForThread(ctx: ApiCtx): Promise<void> {
const threadRef = url.searchParams.get("threadRef") ?? "";
if (!threadRef) return sendJson(res, 400, { error: "bad_request", message: "threadRef required" });
const active = await app.activeRunForThread(threadRef, actor?.p);
- return sendJson(res, 200, { runId: active?.runId ?? null });
+ return sendJson(res, 200, { runId: active?.runId ?? null, ...(active?.queued ? { queued: active.queued } : {}) });
+}
+
+async function postRunWithdraw(ctx: ApiCtx): Promise<void> {
+ const { res, app, actor } = ctx;
+ const outcome = await app.withdrawRun(ctx.params.id!, actor?.p);
+ if (outcome.withdrawn) return sendJson(res, 200, outcome);
+ if (outcome.reason === "not_found") return sendJson(res, 404, { error: "not_found" });
+ return sendJson(res, 409, outcome);
}
async function listDeliveries(ctx: ApiCtx): Promise<void> {
@@ -157,6 +165,7 @@ export const turnRoutes: ReadonlyArray<Route<ApiCtx>> = [
{ method: "GET", path: "/v1/approvals/:id", auth: "source", handle: getApproval },
{ method: "POST", path: "/v1/runs/:id/delivery-state", auth: "source", handle: postRunDeliveryState },
{ method: "POST", path: "/v1/runs/:id/signal", auth: "source", handle: postRunSignal },
+ { method: "POST", path: "/v1/runs/:id/withdraw", auth: "source", handle: postRunWithdraw },
{ method: "GET", path: "/v1/runs/:id", auth: "source", handle: getRun },
{ method: "GET", path: "/v1/runs", auth: "source", handle: getActiveRunForThread },
{ method: "GET", path: "/v1/deliveries", auth: "source", handle: listDeliveries },
diff --git a/src/runs/memory-run-store.ts b/src/runs/memory-run-store.ts
index ab0a54386..62e5d7e4c 100644
--- a/src/runs/memory-run-store.ts
+++ b/src/runs/memory-run-store.ts
@@ -139,6 +139,20 @@ export function createMemoryRunStore(opts?: { maxClaims?: number }): MemoryRunti
);
},
+ async inFlightForThread(sessionId) {
+ return [...runs.values()]
+ .filter((r) => r.sessionId === sessionId && !isTerminal(r.status))
+ .sort((a, b) => a.createdAt - b.createdAt);
+ },
+
+ async withdraw(runId) {
+ const run = runs.get(runId);
+ if (!run || run.status !== "pending") return false;
+ runs.delete(runId);
+ if (run.dedupKey) byKey.delete(run.dedupKey);
+ return true;
+ },
+
async activeSessionIds() {
const ids = new Set<string>();
for (const r of runs.values()) if (!isTerminal(r.status)) ids.add(r.sessionId);
diff --git a/src/runs/postgres-run-store.ts b/src/runs/postgres-run-store.ts
index 4ab32edc7..a3c4b1b6b 100644
--- a/src/runs/postgres-run-store.ts
+++ b/src/runs/postgres-run-store.ts
@@ -55,6 +55,8 @@ export function createPostgresRunStore(connectionString: string, opts?: { maxCla
)`,
`ALTER TABLE runs ADD COLUMN IF NOT EXISTS delivery_state TEXT`,
`ALTER TABLE runs ADD COLUMN IF NOT EXISTS error_attempts INT NOT NULL DEFAULT 0`,
+ `ALTER TABLE runs ADD COLUMN IF NOT EXISTS seq BIGSERIAL`,
+ `CREATE INDEX IF NOT EXISTS idx_runs_status_created_seq ON runs(status, created_at, seq)`,
`CREATE INDEX IF NOT EXISTS idx_runs_status_created ON runs(status, created_at)`,
`CREATE INDEX IF NOT EXISTS idx_runs_session_active_created
ON runs(session_id, created_at DESC) WHERE status IN ('pending','running')`,
@@ -147,7 +149,7 @@ export function createPostgresRunStore(connectionString: string, opts?: { maxCla
WHERE id = (
SELECT id FROM runs WHERE status='pending'
AND session_id NOT IN (SELECT session_id FROM runs WHERE status='running')
- ORDER BY created_at ASC FOR UPDATE SKIP LOCKED LIMIT 1
+ ORDER BY created_at ASC, seq ASC FOR UPDATE SKIP LOCKED LIMIT 1
) RETURNING *`,
[token, now + ttlMs, workerId, now],
);
@@ -239,6 +241,19 @@ export function createPostgresRunStore(connectionString: string, opts?: { maxCla
return rows[0] ? rowToRun(rows[0]) : null;
},
+ async inFlightForThread(sessionId: string): Promise<Run[]> {
+ const { rows } = await q(
+ "SELECT * FROM runs WHERE session_id = $1 AND status IN ('pending','running') ORDER BY created_at ASC, seq ASC",
+ [sessionId],
+ );
+ return rows.map(rowToRun);
+ },
+
+ async withdraw(runId: string): Promise<boolean> {
+ const { rowCount } = await q("DELETE FROM runs WHERE id = $1 AND status = 'pending'", [runId]);
+ return (rowCount ?? 0) > 0;
+ },
+
async activeSessionIds(): Promise<string[]> {
const { rows } = await q("SELECT DISTINCT session_id FROM runs WHERE status IN ('pending','running')");
return rows.map((r) => r.session_id as string);
diff --git a/src/runs/run-store.ts b/src/runs/run-store.ts
index 3429f08f5..ae21eecd6 100644
--- a/src/runs/run-store.ts
+++ b/src/runs/run-store.ts
@@ -72,6 +72,10 @@ export interface RunStore {
activeForThread(sessionId: string): Promise<Run | null>;
+ inFlightForThread(sessionId: string): Promise<Run[]>;
+
+ withdraw(runId: string): Promise<boolean>;
+
activeSessionIds(): Promise<string[]>;
list(opts?: { limit?: number }): Promise<Run[]>;
diff --git a/test/postgres-store.test.ts b/test/postgres-store.test.ts
index cc5103bb1..11dd772b9 100644
--- a/test/postgres-store.test.ts
+++ b/test/postgres-store.test.ts
@@ -1084,6 +1084,73 @@ test("pg run store: one-running-per-session holds under concurrent claims (uniqu
}
});
+test(
+ "pg run store: same-instant submissions keep send order, and the claim takes the displayed head",
+ { skip },
+ async () => {
+ const { runs, close } = createPostgresRunStore(URL!);
+ try {
+ // created_at is Date.now(), so six quick enqueues tie; seq breaks the tie in insertion
+ // order. The queue read and the claim agree on it, so what a surface shows as next IS next.
+ const created = [];
+ for (let i = 0; i < 6; i++) created.push((await runs.enqueue({ sessionId: "sSeq", request: turn(`m${i}`) })).run);
+ const expected = created.map((r) => r.id);
+ assert.deepEqual(
+ (await runs.inFlightForThread("sSeq")).map((r) => r.id),
+ expected,
+ "the queue reads back in send order even when created_at ties",
+ );
+ const claimed = await runs.claim("wSeq", 60_000);
+ assert.equal(claimed?.id, expected[0], "the worker claims exactly the head the queue displays");
+
+ // Rows that predate the seq column get backfilled in heap order, not send order. seq is a
+ // tie-break BEHIND created_at, so a scrambled backfill can only ever decide between rows
+ // sharing a millisecond — simulate the worst backfill and prove created_at still rules.
+ const pg = (await import("pg")).default;
+ const raw = new pg.Pool({ connectionString: URL });
+ try {
+ const early = (await runs.enqueue({ sessionId: "sBackfill", request: turn("early") })).run;
+ await new Promise((r) => setTimeout(r, 5));
+ const late = (await runs.enqueue({ sessionId: "sBackfill", request: turn("late") })).run;
+ await raw.query("UPDATE runs SET seq = 999999999 WHERE id = $1", [early.id]);
+ assert.deepEqual(
+ (await runs.inFlightForThread("sBackfill")).map((r) => r.id),
+ [early.id, late.id],
+ "created_at outranks a scrambled seq",
+ );
+ } finally {
+ await raw.end();
+ }
+ } finally {
+ await close();
+ }
+ },
+);
+
+test("pg run store: withdraw and claim cannot both win the same queued run", { skip }, async () => {
+ const { runs, close } = createPostgresRunStore(URL!);
+ try {
+ const live = (await runs.enqueue({ sessionId: "sWd", request: turn("live") })).run;
+ assert.ok(await runs.claimById(live.id, "w1", 60_000));
+ // Eight withdrawals of one queued run: the DELETE is guarded on status='pending', so exactly
+ // one can report success — the surface never shows a message as both removed and running.
+ const queued = (await runs.enqueue({ sessionId: "sWd", request: turn("queued") })).run;
+ const results = await Promise.all(Array.from({ length: 8 }, () => runs.withdraw(queued.id)));
+ assert.equal(results.filter(Boolean).length, 1, "exactly one withdrawal wins");
+ assert.equal(await runs.get(queued.id), null);
+
+ // And against a claim: whoever loses reports honestly rather than silently dropping the turn.
+ const contested = (await runs.enqueue({ sessionId: "sWd2", request: turn("contested") })).run;
+ const [withdrawn, claimed] = await Promise.all([
+ runs.withdraw(contested.id),
+ runs.claimById(contested.id, "w2", 60_000),
+ ]);
+ assert.notEqual(withdrawn, Boolean(claimed), "the run is either withdrawn or running, never both");
+ } finally {
+ await close();
+ }
+});
+
test("pg run store indexes newest active run by session", { skip }, async () => {
const { close } = createPostgresRunStore(URL!);
const pg = (await import("pg")).default;
diff --git a/test/run-store.test.ts b/test/run-store.test.ts
index fd5fe4b3e..00b6b291e 100644
--- a/test/run-store.test.ts
+++ b/test/run-store.test.ts
@@ -47,6 +47,70 @@ for (const backend of backends) {
assert.equal(await runs.activeForThread("sX"), null, "terminal run is not active");
});
+ test(`[${backend.name}] inFlightForThread puts the running turn first and the queue behind it`, async () => {
+ const { runs } = backend.make();
+ assert.deepEqual(await runs.inFlightForThread("sQ"), [], "nothing in flight");
+ const first = (await runs.enqueue({ sessionId: "sQ", request: turn("first") })).run;
+ const second = (await runs.enqueue({ sessionId: "sQ", request: turn("second") })).run;
+ const third = (await runs.enqueue({ sessionId: "sQ", request: turn("third") })).run;
+ const claimed = await runs.claim("w1", 5_000);
+ assert.equal(claimed?.id, first.id, "the oldest run takes the session's one running slot");
+ assert.deepEqual(
+ (await runs.inFlightForThread("sQ")).map((r) => r.id),
+ [first.id, second.id, third.id],
+ "oldest first: the live turn, then what is queued behind it in send order",
+ );
+ assert.deepEqual(await runs.inFlightForThread("other"), [], "scoped to the thread");
+ await runs.complete(first.id, claimed?.leaseToken ?? "", { status: "ok", reply: "done" });
+ assert.deepEqual(
+ (await runs.inFlightForThread("sQ")).map((r) => r.id),
+ [second.id, third.id],
+ "a finished turn leaves the list; the queue keeps its order",
+ );
+ });
+
+ test(`[${backend.name}] same-instant submissions keep send order, and the claim takes the displayed head`, async () => {
+ const { runs } = backend.make();
+ // Six enqueues inside (usually) one millisecond: createdAt ties, so FIFO here is only as
+ // real as the store's tie handling. Send order must survive, and the worker must take
+ // exactly the head the queue displays.
+ const created = [];
+ for (let i = 0; i < 6; i++) created.push((await runs.enqueue({ sessionId: "sT", request: turn(`m${i}`) })).run);
+ const expected = created.map((r) => r.id);
+ assert.deepEqual(
+ (await runs.inFlightForThread("sT")).map((r) => r.id),
+ expected,
+ "the queue reads back in send order even when createdAt ties",
+ );
+ const claimed = await runs.claim("w1", 5_000);
+ assert.equal(claimed?.id, expected[0], "the worker claims exactly the head the queue displays");
+ });
+
+ test(`[${backend.name}] withdraw drops a queued run and refuses one already claimed`, async () => {
+ const { runs } = backend.make();
+ const live = (await runs.enqueue({ sessionId: "sW", request: turn("live") })).run;
+ const queued = (await runs.enqueue({ sessionId: "sW", request: turn("queued") })).run;
+ assert.ok(await runs.claim("w1", 5_000));
+ assert.equal(await runs.withdraw(queued.id), true, "a run that has not started can be withdrawn");
+ assert.equal(await runs.get(queued.id), null, "and it is gone, so no worker can ever claim it");
+ assert.equal(await runs.withdraw(queued.id), false, "withdrawing it twice is not a second removal");
+ assert.equal(await runs.withdraw(live.id), false, "a running turn cannot be un-sent");
+ assert.equal((await runs.get(live.id))?.status, "running", "and is left untouched");
+ assert.deepEqual(
+ (await runs.inFlightForThread("sW")).map((r) => r.id),
+ [live.id],
+ );
+ });
+
+ test(`[${backend.name}] a withdrawn run frees its dedup key`, async () => {
+ const { runs } = backend.make();
+ const first = (await runs.enqueue({ sessionId: "sD", request: turn("once"), dedupKey: "k" })).run;
+ assert.equal(await runs.withdraw(first.id), true);
+ const again = await runs.enqueue({ sessionId: "sD", request: turn("once"), dedupKey: "k" });
+ assert.equal(again.deduped, false, "the key is free again — a withdrawn turn can be re-sent");
+ assert.notEqual(again.run.id, first.id);
+ });
+
test(`[${backend.name}] activeSessionIds lists distinct in-flight sessions, drops terminal ones`, async () => {
const { runs } = backend.make();
assert.deepEqual(await runs.activeSessionIds(), [], "nothing in flight");
diff --git a/test/wake-steering.test.ts b/test/wake-steering.test.ts
index 9c3a70c70..062914497 100644
--- a/test/wake-steering.test.ts
+++ b/test/wake-steering.test.ts
@@ -53,6 +53,10 @@ function dm(text: string, channel: string): TurnRequest {
};
}
+// A web turn. Web is deliberately excluded from core-side mid-turn steering: on web a mid-turn
+// message QUEUES by default — it is submitted as its own turn and waits for the session lock —
+// and steering is a separate, explicit act on the queued row. So a turn that reaches core mid-run
+// must stay a real second run; folding it into the live one would be the bug.
function web(text: string, threadRef: string): TurnRequest {
return {
surface: "web",
@@ -528,6 +532,55 @@ test("web's queued second run waits for the lock: not claimable until the live r
);
});
+test("web's queue is durable and readable: core names the live run, then what waits behind it", async () => {
+ const built = freshApp();
+ const threadRef = "web:U1:visible";
+ const first = await built.app.turn(web("summarize the incident", threadRef));
+ await built.runs.claimById(first.runId!, "w1", 30_000);
+ const second = await built.app.turn(web("then the timeline", threadRef));
+ const third = await built.app.turn(web("and who was paged", threadRef));
+
+ const active = await built.app.activeRunForThread(threadRef);
+ assert.equal(active?.runId, first.runId, "the live run is the head, not the newest message");
+ assert.deepEqual(
+ active?.queued,
+ [
+ { runId: second.runId!, text: "then the timeline" },
+ { runId: third.runId!, text: "and who was paged" },
+ ],
+ "the queue comes back in send order, with the text — enough for any surface to render it",
+ );
+
+ // A queued turn is withdrawable right up to the moment a worker takes it, and not after.
+ assert.deepEqual(await built.app.withdrawRun(second.runId!), { withdrawn: true });
+ assert.deepEqual(
+ (await built.app.activeRunForThread(threadRef))?.queued,
+ [{ runId: third.runId!, text: "and who was paged" }],
+ "the withdrawn turn is off the queue and will never run",
+ );
+ assert.deepEqual(
+ await built.app.withdrawRun(first.runId!),
+ { withdrawn: false, reason: "started" },
+ "the running turn is not withdrawable — it can only be steered or stopped",
+ );
+ assert.deepEqual(await built.app.withdrawRun("no-such-run"), { withdrawn: false, reason: "not_found" });
+});
+
+test("a queued web turn runs on its own — the sender's client need never come back", async () => {
+ const built = freshApp();
+ const threadRef = "web:U1:unattended";
+ const first = await built.app.turn(web("the long one", threadRef));
+ const live = await built.runs.claimById(first.runId!, "w1", 30_000);
+ const queued = await built.app.turn(web("the queued one", threadRef));
+
+ await built.runs.complete(live!.id, live!.leaseToken!, { status: "ok", reply: "done" });
+ const next = await built.runs.claim("w2", 30_000);
+ assert.equal(next?.id, queued.runId, "the queued turn is claimed by a worker, with no client involved");
+ assert.equal(next?.request.text, "the queued one");
+});
+
+// ── Orphaned-signal replay: a steer that loses the pickup race is never dropped ────────────────
+
const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));
async function until<T>(get: () => Promise<T | undefined>, ms = 3_000): Promise<T> {
const deadline = Date.now() + ms;