Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Support files and images when steering running tasks (#1357)

Regan Bell037d3940ecfa
diff --git a/plugins/web-ui/server/index.ts b/plugins/web-ui/server/index.ts
index 8804a0235..e64c50721 100644
--- a/plugins/web-ui/server/index.ts
+++ b/plugins/web-ui/server/index.ts
@@ -2406,6 +2406,7 @@ const apiRoutes: readonly WebRoute[] = [
threadRef?: unknown;
scopeId?: unknown;
channelName?: unknown;
+ queuedRunId?: unknown;
}>(req, res, false);
if (!p) return;
const kind = typeof p.kind === "string" ? p.kind : "";
@@ -2428,7 +2429,12 @@ const apiRoutes: readonly WebRoute[] = [
res,
"POST",
`/v1/runs/${encodeURIComponent(id)}/signal`,
- JSON.stringify({ kind, ...(text !== undefined ? { text } : {}), ...steerFields }),
+ JSON.stringify({
+ kind,
+ ...(text !== undefined ? { text } : {}),
+ ...steerFields,
+ ...(typeof p.queuedRunId === "string" ? { queuedRunId: p.queuedRunId } : {}),
+ }),
);
},
},
diff --git a/plugins/web-ui/src/chat.ts b/plugins/web-ui/src/chat.ts
index 0c1e207f3..49db3f83b 100644
--- a/plugins/web-ui/src/chat.ts
+++ b/plugins/web-ui/src/chat.ts
@@ -2864,12 +2864,18 @@ export function createChatSurface(
return {
state: chatState,
hasLiveRun: () => hasLiveRun(runSlot),
- signalLiveRun: (kind, text) =>
- signalLiveRun(runSlot, kind, text, {
- threadRef: chatState.threadRef,
- scopeId: chatState.scopeId,
- channelName: chatState.contextName,
- }),
+ signalLiveRun: (kind, text, queuedRunId) =>
+ signalLiveRun(
+ runSlot,
+ kind,
+ text,
+ {
+ threadRef: chatState.threadRef,
+ scopeId: chatState.scopeId,
+ channelName: chatState.contextName,
+ },
+ queuedRunId,
+ ),
stopLiveRun,
isStopping: () => runSlot.stopGeneration === runSlot.generation,
currentTurnOptions,
diff --git a/plugins/web-ui/src/composer.ts b/plugins/web-ui/src/composer.ts
index 885b2906c..52257e936 100644
--- a/plugins/web-ui/src/composer.ts
+++ b/plugins/web-ui/src/composer.ts
@@ -28,7 +28,6 @@ import {
ApiError,
editQueuedRun,
approvalBlocksComposer,
- latestTranscriptSeq,
MAX_ATTACHMENT_BYTES,
MAX_FILES_PER_MESSAGE,
mintSendKey,
@@ -38,14 +37,13 @@ import {
tooManyFilesNote,
uploadAttachments,
userSendMessage,
- verifySteerDelivered,
withdrawRun,
type ApprovalDecision,
type CoreAttachment,
type PendingApproval,
type QueuedRun,
} from "./core-bridge";
-import { errMessage, swallow } from "../../chassis/src/errors";
+import { errMessage } from "../../chassis/src/errors";
import { fieldSelect, icon, modelMark } from "./ui";
import {
EFFORT_LEVELS,
@@ -769,8 +767,7 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {
if (!queued.length) return nothing;
const steerable =
agent.state.isStreaming && ctx.chat.hasLiveRun() && harnessSupportsSteer(currentModelOption()?.harnessId ?? "");
- const steerTip = (q: QueuedRun): string => {
- if (q.hasAttachments) return "This message carries files, which can't fold into a running task";
+ const steerTip = (): string => {
if (steerable) return "Steer the running task with this instead of waiting";
return "Nothing running can take this. It will go out as its own turn";
};
@@ -828,8 +825,8 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {
<button
type="button"
class="queued-steer"
- ?disabled=${!steerable || q.hasAttachments}
- ${tip(steerTip(q))}
+ ?disabled=${!steerable}
+ ${tip(steerTip())}
@click=${() => void steerQueued(agent, q)}
>
${icon(CornerDownRight, 13)}<span>Steer</span>
@@ -2009,73 +2006,41 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {
ctx.chat.drawActiveChat(agent);
}
+ const pendingSteers = new Set<string>();
+
async function steerQueued(agent: Agent, queued: QueuedRun): Promise<void> {
const threadRef = ctx.chat.state.threadRef;
- if (!threadRef || queued.hasAttachments) 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 (!threadRef || !ctx.chat.hasLiveRun() || pendingSteers.has(queued.runId)) return;
+ pendingSteers.add(queued.runId);
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);
- }
- 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);
-
- const sentAt = Date.now();
- const steerSessionId = ctx.chat.state.sessionId;
- const sinceSeq = steerSessionId
- ? await latestTranscriptSeq(steerSessionId).catch((e: unknown) => {
- swallow("web-ui: steer baseline", e);
- return undefined;
- })
- : undefined;
- try {
- const outcome = await ctx.chat.signalLiveRun("steer", queued.text);
- if (!outcome.ok) await recoverEndedRunSteer(agent, queued.text, outcome);
- } catch (err) {
- if (steerSessionId && (await verifySteerDelivered(steerSessionId, queued.text, sentAt, undefined, sinceSeq))) {
- composerState.error = "";
- return ctx.chat.drawActiveChat(agent);
+ const outcome = await ctx.chat.signalLiveRun("steer", queued.text, queued.runId);
+ if (outcome.ok || outcome.replayed) {
+ forgetQueuedRun(threadRef, queued.runId);
+ bumpSessionActivity(threadRef);
+ if (agent === ctx.chat.state.agent && threadRef === ctx.chat.state.threadRef) {
+ agent.state.messages.push({
+ role: "user",
+ content: queued.text,
+ timestamp: Date.now(),
+ ...(outcome.ok ? { steered: true } : {}),
+ } as unknown as AgentMessage);
+ }
+ } else if (outcome.reason === "queued_changed") {
+ if (agent === ctx.chat.state.agent && threadRef === ctx.chat.state.threadRef)
+ composerState.error = "The queued message changed. Try steering it again.";
+ } else if (outcome.reason === "queued_started" || outcome.reason === "not_found") {
+ forgetQueuedRun(threadRef, queued.runId);
}
- 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);
- }
- }
-
- async function recoverEndedRunSteer(agent: Agent, text: string, outcome: { replayed?: boolean }): Promise<void> {
- const last = agent.state.messages[agent.state.messages.length - 1] as
- { role?: string; content?: unknown; steered?: boolean } | undefined;
- if (last?.role === "user" && last.content === text) {
- if (outcome.replayed) delete last.steered;
- else agent.state.messages.pop();
+ } catch (err) {
+ if (agent === ctx.chat.state.agent && threadRef === ctx.chat.state.threadRef)
+ composerState.error = errMessage(err, "Could not confirm steering. Try again.");
+ } finally {
+ pendingSteers.delete(queued.runId);
}
- if (!outcome.replayed) composerState.draft = text;
+ if (agent !== ctx.chat.state.agent || threadRef !== ctx.chat.state.threadRef) return;
ctx.chat.drawActiveChat(agent);
- await agent.waitForIdle();
- if (agent !== ctx.chat.state.agent) return;
- if (outcome.replayed) ctx.chat.resumeIfIdle();
- else if (composerState.draft === text) await sendPrompt(agent);
+ ctx.chat.resumeIfIdle();
}
async function sendPrompt(agent: Agent): Promise<void> {
diff --git a/plugins/web-ui/src/conv-types.ts b/plugins/web-ui/src/conv-types.ts
index dc45f5c10..3460135d0 100644
--- a/plugins/web-ui/src/conv-types.ts
+++ b/plugins/web-ui/src/conv-types.ts
@@ -64,7 +64,11 @@ interface ChatState {
export interface ChatSurface {
state: ChatState;
hasLiveRun(): boolean;
- signalLiveRun(kind: "abort" | "steer", text?: string): Promise<import("./core-bridge").SignalOutcome>;
+ signalLiveRun(
+ kind: "abort" | "steer",
+ text?: string,
+ queuedRunId?: string,
+ ): Promise<import("./core-bridge").SignalOutcome>;
stopLiveRun(): Promise<void>;
isStopping(): boolean;
currentTurnOptions(): TurnOptions;
diff --git a/plugins/web-ui/src/core-bridge.ts b/plugins/web-ui/src/core-bridge.ts
index 313730856..cf974574e 100644
--- a/plugins/web-ui/src/core-bridge.ts
+++ b/plugins/web-ui/src/core-bridge.ts
@@ -811,6 +811,7 @@ export async function signalLiveRun(
kind: "abort" | "steer",
text: string | undefined,
context: SteerContext,
+ queuedRunId?: string,
): Promise<SignalOutcome> {
const run = slot.runId !== null ? { runId: slot.runId } : null;
if (!run) throw new Error("No active run to signal.");
@@ -826,7 +827,12 @@ export async function signalLiveRun(
await api(runPath(run.runId, "/signal"), {
method: "POST",
signal: kind === "abort" ? AbortSignal.timeout(RUN_REQUEST_TIMEOUT_MS) : undefined,
- body: JSON.stringify({ kind, ...(text !== undefined ? { text } : {}), ...steerContext }),
+ body: JSON.stringify({
+ kind,
+ ...(text !== undefined ? { text } : {}),
+ ...steerContext,
+ ...(queuedRunId ? { queuedRunId } : {}),
+ }),
});
return { ok: true };
} catch (err) {
@@ -845,52 +851,6 @@ export async function signalLiveRun(
}
}
-const STEER_VERIFY_DELAYS_MS = [1200, 2200, 3600];
-const STEER_VERIFY_SKEW_MS = 120_000;
-
-export async function latestTranscriptSeq(sessionId: string): Promise<number | undefined> {
- const page = await fetchTranscript(sessionId, { tailTurns: 1 });
- const seqs = (page.entries ?? []).flatMap((e) => (e.seq === undefined ? [] : [e.seq]));
- return seqs.length ? Math.max(...seqs) : undefined;
-}
-
-function steerTextMatches(stored: string, wanted: string): boolean {
- return stored === wanted || stored.endsWith(`: ${wanted}`);
-}
-
-export async function verifySteerDelivered(
- sessionId: string | null,
- text: string,
- sentAt: number,
- delays: readonly number[] = STEER_VERIFY_DELAYS_MS,
- sinceSeq?: number,
-): Promise<boolean> {
- if (!sessionId) return false;
- const wanted = text.trim();
- if (!wanted) return false;
- for (const delay of delays) {
- await sleep(delay);
- try {
- const page = await fetchTranscript(sessionId, { tailTurns: 3 });
- const found = (page.entries ?? []).some((e) => {
- if (e.type !== "user") return false;
- if (sinceSeq !== undefined && !(e.seq !== undefined && e.seq > sinceSeq)) return false;
- const p = e.payload as { text?: string; steered?: boolean } | null;
- return (
- p?.steered === true &&
- typeof p.text === "string" &&
- steerTextMatches(p.text.trim(), wanted) &&
- e.createdAt >= sentAt - STEER_VERIFY_SKEW_MS
- );
- });
- if (found) return true;
- } catch (e) {
- swallow("web-ui: verify steer delivery", e);
- }
- }
- return false;
-}
-
export function makeCoreStreamFn(
threadRef: string,
agent: Agent,
diff --git a/plugins/web-ui/test/approval-handoff.test.ts b/plugins/web-ui/test/approval-handoff.test.ts
index 7cd6ec831..11cb4d6ce 100644
--- a/plugins/web-ui/test/approval-handoff.test.ts
+++ b/plugins/web-ui/test/approval-handoff.test.ts
@@ -186,6 +186,7 @@ test("approval handoff unlocks queue and steer without losing pending decisions"
assert.deepEqual(requests.find((r) => r.path === "/api/runs/r1/signal")?.body, {
kind: "steer",
text: "use the smaller change",
+ queuedRunId: "q1",
threadRef: row.threadRef,
scopeId: row.scopeId,
});
diff --git a/plugins/web-ui/test/attachment-limits.test.ts b/plugins/web-ui/test/attachment-limits.test.ts
index 70720ba3e..b89c54f20 100644
--- a/plugins/web-ui/test/attachment-limits.test.ts
+++ b/plugins/web-ui/test/attachment-limits.test.ts
@@ -8,8 +8,6 @@ import {
oversizeAttachmentNote,
requestStop,
uploadAttachments,
- verifySteerDelivered,
- latestTranscriptSeq,
} from "../src/core-bridge.ts";
const realFetch = globalThis.fetch;
@@ -89,49 +87,6 @@ test("a non-413 upload failure is noted per file with its reason", async () => {
assert.match(skipped[0]!.note, /network unreachable/);
});
-test("verifySteerDelivered finds a landed steer in the transcript tail", async () => {
- globalThis.fetch = (async () =>
- new Response(
- JSON.stringify({
- entries: [{ type: "user", payload: { text: "alice: make it louder", steered: true }, createdAt: Date.now() }],
- }),
- { status: 200 },
- )) as typeof fetch;
- assert.equal(await verifySteerDelivered("s1", "make it louder", Date.now(), [0]), true);
-});
-
-test("verifySteerDelivered says no when the text never made the transcript", async () => {
- globalThis.fetch = (async () =>
- new Response(JSON.stringify({ entries: [{ type: "user", payload: { text: "other" }, createdAt: Date.now() }] }), {
- status: 200,
- })) as typeof fetch;
- assert.equal(await verifySteerDelivered("s1", "make it louder", Date.now(), [0]), false);
-});
-
-test("verifySteerDelivered ignores an ordinary (non-steered) message with the same text", async () => {
- globalThis.fetch = (async () =>
- new Response(
- JSON.stringify({ entries: [{ type: "user", payload: { text: "continue" }, createdAt: Date.now() }] }),
- { status: 200 },
- )) as typeof fetch;
- assert.equal(
- await verifySteerDelivered("s1", "continue", Date.now(), [0]),
- false,
- "a repeated 'continue' that was typed, not steered, must not count as the lost steer",
- );
-});
-
-test("verifySteerDelivered ignores a stale steered match from before the attempt", async () => {
- globalThis.fetch = (async () =>
- new Response(
- JSON.stringify({
- entries: [{ type: "user", payload: { text: "make it louder", steered: true }, createdAt: 1000 }],
- }),
- { status: 200 },
- )) as typeof fetch;
- assert.equal(await verifySteerDelivered("s1", "make it louder", Date.now(), [0]), false);
-});
-
test("requestStop targets the current submit generation, not a fixed flag", () => {
const slot = createRunSlot();
assert.equal(slot.stopGeneration, null);
@@ -189,33 +144,6 @@ test("queued turns carry the staged attachments; attachment-only queues are real
assert.match(bridge, /attachments: CoreAttachment\[\] = \[\],\n\): Promise<QueuedRun>/);
});
-test("a queued run that carries files cannot be steered — steering would drop them", () => {
- assert.match(composer, /\?disabled=\$\{!steerable \|\| q\.hasAttachments\}/);
- assert.match(composer, /if \(!threadRef \|\| queued\.hasAttachments\) return;/);
- const appTurn = readFileSync(new URL("../../../src/api/app-turn.ts", import.meta.url), "utf8");
- assert.match(
- appTurn,
- /\.\.\.\(run\.request\.attachments\?\.length \? \{ hasAttachments: true \} : \{\}\)/,
- "core names which queued runs carry files, so every tab knows, not just the one that queued",
- );
-});
-
-test("an ambiguous steer failure verifies against the transcript before re-submitting", () => {
- const fn = composer.slice(
- composer.indexOf("async function steerQueued"),
- composer.indexOf("function recoverEndedRunSteer"),
- );
- const verify = fn.indexOf("await verifySteerDelivered(steerSessionId, queued.text, sentAt, undefined, sinceSeq)");
- const requeue = fn.indexOf("await enqueueTurn(agent, threadRef, queued.text)");
- assert.ok(verify > 0, "the transcript is consulted first");
- assert.ok(requeue > verify, "only a steer that provably never arrived goes back on the queue");
- assert.match(
- fn,
- /const steerSessionId = ctx\.chat\.state\.sessionId;/,
- "the session is captured before signaling so a mid-steer switch verifies the right transcript",
- );
-});
-
test("Stop pressed before the run id arrives still stops core's run", () => {
assert.match(chat, /requestStop\(runSlot\);/);
assert.match(composer, /void ctx\.chat\.stopLiveRun\(\)\.catch/);
@@ -230,56 +158,6 @@ test("confirmed aborted output is preserved during transcript refresh", () => {
assert.match(chat, /if \(last\?\.stopReason === "aborted"\) return drawActiveChat\(agent\);/);
});
-test("verifySteerDelivered only trusts a steered entry newer than the baseline it was given", async () => {
- globalThis.fetch = (async () =>
- new Response(
- JSON.stringify({
- entries: [
- { type: "user", seq: 4, payload: { text: "yes", steered: true }, createdAt: Date.now() - 30_000 },
- { type: "user", seq: 5, payload: { text: "yes, run the tests", steered: true }, createdAt: Date.now() },
- ],
- }),
- { status: 200 },
- )) as typeof fetch;
- assert.equal(
- await verifySteerDelivered("s1", "yes", Date.now(), [0], 4),
- false,
- "an earlier identical steer and a longer steer containing the word are not this steer",
- );
- assert.equal(await verifySteerDelivered("s1", "yes", Date.now(), [0], 3), true, "seq 4 is newer than baseline 3");
- assert.equal(await verifySteerDelivered("s1", "yes, run the tests", Date.now(), [0], 4), true);
-});
-
-test("verifySteerDelivered matches the attributed form core stores for another person's steer", async () => {
- globalThis.fetch = (async () =>
- new Response(
- JSON.stringify({
- entries: [{ type: "user", seq: 9, payload: { text: "Ada: ship it", steered: true }, createdAt: Date.now() }],
- }),
- { status: 200 },
- )) as typeof fetch;
- assert.equal(await verifySteerDelivered("s1", "ship it", Date.now(), [0], 8), true);
- assert.equal(await verifySteerDelivered("s1", "it", Date.now(), [0], 8), false, "no substring matches");
-});
-
-test("latestTranscriptSeq reads the newest seq from the tail, or nothing for an empty session", async () => {
- globalThis.fetch = (async () =>
- new Response(
- JSON.stringify({
- entries: [
- { type: "user", seq: 7 },
- { type: "assistant", seq: 12 },
- ],
- }),
- {
- status: 200,
- },
- )) as typeof fetch;
- assert.equal(await latestTranscriptSeq("s1"), 12);
- globalThis.fetch = (async () => new Response(JSON.stringify({ entries: [] }), { status: 200 })) as typeof fetch;
- assert.equal(await latestTranscriptSeq("s1"), undefined);
-});
-
test("an empty attachment is reported and left out rather than silently dropped", async () => {
const { uploaded, skipped } = await uploadAttachments([
{ id: "e1", type: "document", fileName: "empty.txt", mimeType: "text/plain", size: 0, content: "" },
diff --git a/plugins/web-ui/test/post-reply-recovery.test.ts b/plugins/web-ui/test/post-reply-recovery.test.ts
index 1a51f4781..fa02e4e1a 100644
--- a/plugins/web-ui/test/post-reply-recovery.test.ts
+++ b/plugins/web-ui/test/post-reply-recovery.test.ts
@@ -421,7 +421,7 @@ test("post replies remain visible in new and continuing conversations", async (t
});
for (const edited of [false, true]) {
await t.test(
- `delayed ended-run steer ${edited ? "preserves a newer draft" : "resends after completion"}`,
+ `ended-run steer keeps the durable queue and ${edited ? "preserves a newer draft" : "leaves the composer empty"}`,
async (sub) => {
sub.after(() => {
intercept = undefined;
@@ -431,16 +431,21 @@ test("post replies remain visible in new and continuing conversations", async (t
let oldRunLive = true;
let signalled = false;
let resends = 0;
+ let withdrawals = 0;
+ const queued = [{ runId: "queued", text: "Follow-up question" }];
intercept = (path) => {
if (path.includes("/api/runs/active"))
return Promise.resolve(
Response.json({
runId: oldRunLive ? "r1" : null,
run: oldRunLive ? { status: "running" } : null,
- queued: [],
+ queued,
}),
);
- if (path === "/api/runs/queued/withdraw") return Promise.resolve(Response.json({ withdrawn: true }));
+ if (path === "/api/runs/queued/withdraw") {
+ withdrawals++;
+ return Promise.resolve(Response.json({ withdrawn: true }));
+ }
if (path === "/api/runs/r1/signal") {
signalled = true;
return Promise.resolve(Response.json({ reason: "terminal", replayed: false }, { status: 409 }));
@@ -459,17 +464,20 @@ test("post replies remain visible in new and continuing conversations", async (t
conv!.composer.setQueuedRuns(row.threadRef, [{ runId: "queued", text: "Follow-up question" }]);
conv!.drawActiveChat(agent);
host.querySelector<HTMLButtonElement>(".queued-steer")!.click();
- await until(() => signalled && conv!.composer.state.draft === "Follow-up question");
+ await until(() => signalled);
+ await settle();
+ assert.equal(conv!.composer.state.draft, "");
+ assert.deepEqual(conv!.composer.queuedRunsFor(row.threadRef), queued);
if (edited) conv!.composer.state.draft = "New draft";
- await new Promise((resolve) => setTimeout(resolve, 5_200));
assert.equal(resends, 0);
oldRunLive = false;
run.emit("done", { status: "done", result: { status: "ok", reply: "Original answer" } });
await turn;
- if (!edited) await until(() => resends === 1);
await settle();
- assert.equal(resends, edited ? 0 : 1);
- if (edited) assert.equal(conv!.composer.state.draft, "New draft");
+ assert.equal(resends, 0);
+ assert.equal(withdrawals, 0);
+ assert.deepEqual(conv!.composer.queuedRunsFor(row.threadRef), queued);
+ assert.equal(conv!.composer.state.draft, edited ? "New draft" : "");
intercept = undefined;
},
);
diff --git a/plugins/web-ui/test/queue-by-default.test.ts b/plugins/web-ui/test/queue-by-default.test.ts
index 2ef8132c4..64a641ac5 100644
--- a/plugins/web-ui/test/queue-by-default.test.ts
+++ b/plugins/web-ui/test/queue-by-default.test.ts
@@ -69,11 +69,7 @@ test("the Steer control's presence is fixed for the conversation; only enablemen
composer.indexOf("function queuedStrip"),
composer.indexOf("function composerApprovalPanel"),
);
- assert.match(
- strip,
- /\?disabled=\$\{!steerable \|\| q\.hasAttachments\}/,
- "an unusable Steer is disabled, never removed",
- );
+ assert.match(strip, /\?disabled=\$\{!steerable\}/, "an unusable Steer is disabled, never removed");
assert.doesNotMatch(
strip,
/steerable\s*\?\s*html`<button/,
@@ -96,52 +92,15 @@ test("steering is reachable only as an explicit act on a queued row", () => {
);
});
-// 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", () => {
+test("Steer asks core to transfer the durable queued message before showing it as delivered", () => {
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\) await 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,1400}?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",
- );
- assert.match(
- fn,
- /if \(steerSessionId && \(await verifySteerDelivered\(steerSessionId, queued\.text, sentAt, undefined, sinceSeq\)\)\)[\s\S]{0,120}?return ctx\.chat\.drawActiveChat\(agent\)/,
- "an ambiguous failure verifies the steer landed before it would re-enqueue",
- );
+ assert.match(fn, /signalLiveRun\("steer", queued\.text, queued\.runId\)/);
+ assert.doesNotMatch(fn, /withdrawRun|enqueueTurn|verifySteerDelivered/);
+ assert.ok(fn.indexOf("signalLiveRun") < fn.indexOf("agent.state.messages.push"));
+ assert.match(fn, /agent === ctx\.chat\.state\.agent && threadRef === ctx\.chat\.state\.threadRef/);
});
test("× cancels the queued run in core, and treats a lost race as running rather than removed", () => {
diff --git a/plugins/web-ui/test/steer-recovery-source.test.ts b/plugins/web-ui/test/steer-recovery-source.test.ts
index b5a83ad57..4818d5af9 100644
--- a/plugins/web-ui/test/steer-recovery-source.test.ts
+++ b/plugins/web-ui/test/steer-recovery-source.test.ts
@@ -45,14 +45,18 @@ test("a message typed mid-turn is never dropped by the run-slot window — it qu
assert.ok(composer.indexOf("function steerWhenLive") < 0, "the held-steer shim is gone with its window");
});
-test("a queued steer the run outlived settles every way: replay followed, ended resend, requeue", () => {
+test("a failed steer keeps the durable queue and does not resubmit into a different conversation", () => {
const at = composer.indexOf("async function steerQueued");
- assert.ok(at >= 0);
- const body = composer.slice(at, composer.indexOf("function recoverEndedRunSteer", at));
- assert.match(body, /if \(!outcome\.ok\) await 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",
- );
+ const body = composer.slice(at, composer.indexOf("async function sendPrompt", at));
+ assert.doesNotMatch(body, /enqueueTurn|withdrawRun/);
+ assert.match(body, /Could not confirm steering/);
+ assert.match(body, /if \(agent !== ctx\.chat\.state\.agent \|\| threadRef !== ctx\.chat\.state\.threadRef\) return/);
+});
+
+test("concurrent clicks share one in-flight steer", () => {
+ const at = composer.indexOf("async function steerQueued");
+ const body = composer.slice(at, composer.indexOf("async function sendPrompt", at));
+ assert.ok(body.indexOf("pendingSteers.has(queued.runId)") < body.indexOf('signalLiveRun("steer"'));
+ assert.match(body, /pendingSteers.add\(queued.runId\)/);
+ assert.match(body, /finally \{\s*pendingSteers.delete\(queued.runId\)/);
});
diff --git a/src/api/app-turn.ts b/src/api/app-turn.ts
index 383750d78..dd361139e 100644
--- a/src/api/app-turn.ts
+++ b/src/api/app-turn.ts
@@ -508,11 +508,6 @@ export function createTurnMethods(
return req.async ? { status: "queued", runId: targetRun.id, steered: true } : drive(targetRun.id);
if (decision === "unscreened") injectedText = `${unscreenedNotice("mid-turn message")}\n${steerText}`;
}
- // A mid-run message can carry files. They can't be materialized into
- // the live turn's inbox, but the run must hear about them — name
- // them in the steer (with the message ts so the agent can pull each
- // via the surface-file API), and never report a captionless file as
- // steered while silently dropping it.
const fileNames = (req.attachments ?? []).map((a) =>
a.sourceId
? `${a.name} (fetch via surface-file, ts ${origin.kind === "human" ? (origin.messageTs ?? origin.entryTs) : origin.entryTs})`
@@ -811,8 +806,32 @@ export function createTurnMethods(
const run = await deps.runs.get(runId);
if (!run) return { accepted: false, reason: "not_found" };
if (viewer && !(await viewerMayUseRun(run, viewer))) return { accepted: false, reason: "not_found" };
+ const queuedKey = signal.queuedRunId
+ ? `queued-steer:${run.request.conversation.threadRef}:${signal.queuedRunId}`
+ : undefined;
+ if (queuedKey && (await deps.signals.hasDedupeKey(queuedKey))) return { accepted: true };
if (isTerminal(run.status)) return { accepted: false, reason: "terminal" };
- if (signal.kind === "steer" && !signal.text?.trim()) {
+ if (signal.queuedRunId) {
+ const queued = await deps.runs.get(signal.queuedRunId);
+ if (!queued || (viewer && !(await viewerMayUseRun(queued, viewer))))
+ return { accepted: false, reason: "not_found" };
+ if (
+ signal.kind !== "steer" ||
+ !signal.request ||
+ queued.request.conversation.threadRef !== run.request.conversation.threadRef
+ )
+ return { accepted: false, reason: "conversation_mismatch" };
+ if (queued.id === run.id || queued.status !== "pending") return { accepted: false, reason: "queued_started" };
+ const text = queued.request.displayText ?? queued.request.text;
+ signal = {
+ ...signal,
+ text,
+ ts: queuedKey,
+ dedupeKey: queuedKey,
+ request: { ...signal.request, text, attachments: queued.request.attachments, idempotencyKey: queuedKey },
+ };
+ }
+ if (signal.kind === "steer" && !signal.text?.trim() && !signal.request?.attachments?.length) {
return { accepted: false, reason: "text_required" };
}
if (signal.request && signal.request.conversation.threadRef !== run.request.conversation.threadRef) {
@@ -829,10 +848,16 @@ export function createTurnMethods(
outbound = {
...signal,
ts: signal.ts ?? `${Date.now()}.${crypto.randomUUID().slice(0, 8)}`,
- ...(steerer ? { text: attributedSteerText(steerer, run.request.actor.id, signal.text!) } : {}),
+ ...(steerer ? { text: attributedSteerText(steerer, run.request.actor.id, signal.text ?? "") } : {}),
};
}
- await deps.signals.send(runId, outbound);
+ if (signal.queuedRunId) {
+ if (!(await deps.runs.steerQueued(signal.queuedRunId, runId, outbound, deps.signals))) {
+ if (await deps.signals.hasDedupeKey(queuedKey!)) return { accepted: true };
+ const queued = await deps.runs.get(signal.queuedRunId);
+ return { accepted: false, reason: queued?.status === "pending" ? "queued_changed" : "queued_started" };
+ }
+ } else await deps.signals.send(runId, outbound);
const after = await deps.runs.get(runId);
if (!after || isTerminal(after.status)) {
const drained = await replayOrphanedRunSignals(runId);
diff --git a/src/api/routes/turns.ts b/src/api/routes/turns.ts
index f677e91e3..6ef825f76 100644
--- a/src/api/routes/turns.ts
+++ b/src/api/routes/turns.ts
@@ -99,6 +99,7 @@ async function postRunSignal(ctx: ApiCtx): Promise<void> {
return sendJson(res, 400, { error: "bad_request", message: "kind must be abort or steer" });
}
const text = isObj(body) && typeof body.text === "string" ? body.text : undefined;
+ const queuedRunId = isObj(body) && typeof body.queuedRunId === "string" ? body.queuedRunId : undefined;
const ts = isObj(body) && typeof body.ts === "string" && body.ts ? body.ts : undefined;
let request: TurnRequest | undefined;
if (isObj(body) && body.request !== undefined) {
@@ -114,7 +115,13 @@ async function postRunSignal(ctx: ApiCtx): Promise<void> {
}
const outcome = await app.signalRun(
id,
- { kind, ...(text !== undefined ? { text } : {}), ...(ts ? { ts } : {}), ...(request ? { request } : {}) },
+ {
+ kind,
+ ...(text !== undefined ? { text } : {}),
+ ...(ts ? { ts } : {}),
+ ...(request ? { request } : {}),
+ ...(queuedRunId ? { queuedRunId } : {}),
+ },
actor?.p,
);
if (outcome.accepted) return sendJson(res, 200, outcome);
diff --git a/src/core/orchestrator.ts b/src/core/orchestrator.ts
index 5e02da1ce..15103988f 100644
--- a/src/core/orchestrator.ts
+++ b/src/core/orchestrator.ts
@@ -3054,6 +3054,56 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
};
return deps.harness.turns.runTurn({
session,
+ prepareSteer: async (text, request) => {
+ if (!request?.attachments?.length) return { text };
+ const seed = `${fileRegistration.seed}:steer:${randomUUID()}`;
+ const inboxDir = `${turnInboxDir}/${randomUUID()}`;
+ const received = strictReadOnly
+ ? { metas: [], images: [], tooMany: [], unavailable: [], blocked: [], unscreened: [] }
+ : await materializeInbound(
+ deps.sandbox,
+ await provision(),
+ request.attachments,
+ blobTransfer,
+ { ...fileRegistration, seed },
+ inboxDir,
+ securityPolicy.inboundScreening === "external"
+ ? ({ content, name, mimetype }) =>
+ classifySecurityData(
+ JSON.stringify({ name, mimetype, content }),
+ actor.id,
+ scopeId,
+ undefined,
+ {
+ hook: "tool_response",
+ surface: "inbound_file",
+ origin: input.origin.kind,
+ },
+ )
+ : undefined,
+ );
+ const issues = inboundIssueList({
+ ...received,
+ surfaceNotes: strictReadOnly
+ ? request.attachments.map((a) => `${safeAttachmentName(a.name)} — unavailable in read-only mode`)
+ : [],
+ });
+ return {
+ text: [
+ text,
+ inboundManifest(received.metas, inboxDir),
+ issues.length ? fileEventPayload("in", issues).text : "",
+ securityPolicy.inboundScreening === "external" &&
+ (received.unscreened.length || received.metas.some((a) => !isScreenableTextAttachment(a.mimetype)))
+ ? unscreenedNotice("inbound content")
+ : "",
+ ]
+ .filter(Boolean)
+ .join("\n\n"),
+ attachments: received.metas,
+ images: received.images,
+ };
+ },
...(userProviderKeys ? { providerKeys: userProviderKeys } : {}),
...(claudeOauthToken ? { claudeOauthToken } : {}),
...(userHarnessOverride && !restoredRuntime && runtimeHandoffs === 0 ? { runtimePinned: true } : {}),
diff --git a/src/harness/claude-harness.ts b/src/harness/claude-harness.ts
index 9cc50e162..91a1208e5 100644
--- a/src/harness/claude-harness.ts
+++ b/src/harness/claude-harness.ts
@@ -467,15 +467,22 @@ export function createClaudeHarness(opts: ClaudeHarnessOptions = {}): Harness {
turn.runId,
{
onAbort: async () => interrupt(true),
- onSteer: async (steer, ts) => {
+ onSteer: async (steer, ts, request) => {
+ const prepared = await turn.prepareSteer?.(steer, request);
+ const prompt = prepared?.text ?? steer;
await turn.emit({
type: "user",
- payload: { text: steer, ...(ts ? { ts } : {}), steered: true },
+ payload: {
+ text: steer,
+ ...(ts ? { ts } : {}),
+ steered: true,
+ ...(prepared?.attachments?.length ? { attachments: prepared.attachments } : {}),
+ },
scopeLabel: turn.scopeLabel,
});
- steerPrompts.push(steer);
+ steerPrompts.push(prompt);
pendingPrompts++;
- queue.push(userMessage(steer));
+ queue.push(userMessage(prompt, prepared?.images));
},
},
{ onError: (error) => swallow("claude signal poll", error) },
diff --git a/src/harness/codex-harness.ts b/src/harness/codex-harness.ts
index c81be103d..642b5c86a 100644
--- a/src/harness/codex-harness.ts
+++ b/src/harness/codex-harness.ts
@@ -1157,10 +1157,17 @@ export function createCodexHarness(opts: CodexHarnessOptions = {}): Harness {
turn.runId,
{
onAbort: async () => interrupt(true),
- onSteer: async (text, ts) => {
+ onSteer: async (text, ts, request) => {
+ const prepared = await turn.prepareSteer?.(text, request);
+ const prompt = prepared?.text ?? text;
const steered = await turn.emit({
type: "user",
- payload: { text, ...(ts ? { ts } : {}), steered: true },
+ payload: {
+ text,
+ ...(ts ? { ts } : {}),
+ steered: true,
+ ...(prepared?.attachments?.length ? { attachments: prepared.attachments } : {}),
+ },
scopeLabel: turn.scopeLabel,
});
if (turn.tape) {
@@ -1174,10 +1181,20 @@ export function createCodexHarness(opts: CodexHarnessOptions = {}): Harness {
...(ts ? { ts } : {}),
entryCreatedAt: steered.createdAt,
},
- payload: { type: "message", role: "user", content: [{ type: "input_text", text }] },
+ payload: { type: "message", role: "user", content: [{ type: "input_text", text: prompt }] },
});
}
- await rt.server.request("turn/steer", { threadId, expectedTurnId: turnId, input: [userInput(text)] });
+ await rt.server.request("turn/steer", {
+ threadId,
+ expectedTurnId: turnId,
+ input: [
+ userInput(prompt),
+ ...(prepared?.images ?? []).map((image) => ({
+ type: "image",
+ url: `data:${image.mimeType};base64,${image.dataBase64}`,
+ })),
+ ],
+ });
},
},
{ onError: (error) => swallow("codex signal poll", error) },
diff --git a/src/harness/harness.ts b/src/harness/harness.ts
index bd3a8e384..72cf8ac90 100644
--- a/src/harness/harness.ts
+++ b/src/harness/harness.ts
@@ -1,5 +1,5 @@
import type { RuntimeControl, RuntimeHandoff } from "./runtime-types.ts";
-import type { AttachmentMeta, ConversationTurn, ScopeId, Session, SessionEntry } from "../types.ts";
+import type { AttachmentMeta, ConversationTurn, ScopeId, Session, SessionEntry, TurnRequest } from "../types.ts";
import type { HarnessId } from "../model/pi-models.ts";
import type {
GapPhases,
@@ -82,6 +82,10 @@ export interface HarnessTurnInput {
overheard?: OverheardEntryPayload[];
attachments?: AttachmentMeta[];
images?: HarnessImage[];
+ prepareSteer?(
+ text: string,
+ request?: TurnRequest,
+ ): Promise<{ text: string; attachments?: AttachmentMeta[]; images?: HarnessImage[] }>;
runtime?: Partial<RuntimeChoice>;
runtimeControl?: RuntimeControl;
runtimeActorId?: string;
diff --git a/src/harness/opencode-harness.ts b/src/harness/opencode-harness.ts
index acafdf882..d3c527f61 100644
--- a/src/harness/opencode-harness.ts
+++ b/src/harness/opencode-harness.ts
@@ -888,11 +888,23 @@ export function createOpenCodeHarness(opts: OpenCodeHarnessOptions = {}): Harnes
}
const wallMs = turn.turnWallClockMs ?? defaultTurnWallClockMs;
const queuedSignals = new Set<Promise<void>>();
- const queueSignal = (text: string): Promise<void> => {
+ const queueSignal = (text: string, images: HarnessTurnInput["images"] = []): Promise<void> => {
const pending = (async () => {
await rt.client.session.promptAsync({
path: { id: sessionId },
- body: { model, agent: "qm", parts: [{ type: "text", text }] },
+ body: {
+ model,
+ agent: "qm",
+ parts: [
+ { type: "text", text },
+ ...images.map((image, index) => ({
+ type: "file" as const,
+ mime: image.mimeType,
+ filename: `image-${index + 1}`,
+ url: `data:${image.mimeType};base64,${image.dataBase64}`,
+ })),
+ ],
+ },
});
await waitForSessionIdle(rt.client, sessionId, wallMs > 0 ? wallMs : OPENCODE_IDLE_WAIT_MS);
})();
@@ -906,13 +918,20 @@ export function createOpenCodeHarness(opts: OpenCodeHarnessOptions = {}): Harnes
turn.runId,
{
onAbort: async () => abort(true),
- onSteer: async (text, ts) => {
+ onSteer: async (text, ts, request) => {
+ const prepared = await turn.prepareSteer?.(text, request);
+ const prompt = prepared?.text ?? text;
await turn.emit({
type: "user",
- payload: { text, ...(ts ? { ts } : {}), steered: true },
+ payload: {
+ text,
+ ...(ts ? { ts } : {}),
+ steered: true,
+ ...(prepared?.attachments?.length ? { attachments: prepared.attachments } : {}),
+ },
scopeLabel: turn.scopeLabel,
});
- await queueSignal(text);
+ await queueSignal(prompt, prepared?.images);
},
},
{ onError: (error) => swallow("opencode signal poll", error), drainOnStop: true },
diff --git a/src/harness/pi-harness.ts b/src/harness/pi-harness.ts
index eb0eaf081..513dd919e 100644
--- a/src/harness/pi-harness.ts
+++ b/src/harness/pi-harness.ts
@@ -1815,16 +1815,29 @@ export function createPiHarness(opts?: PiHarnessOptions): Harness {
let tapeError: Error | undefined;
let tapedTriggerUser = false;
const toolAbort = new AbortController();
- const pendingSteerTapeMeta: Array<{ text: string; ts?: string; entryCreatedAt: number }> = [];
- const steerTapeStamp = (message: unknown): TapeMeta | undefined => {
+ const pendingSteerTapeMeta: Array<{
+ text: string;
+ bareText?: string;
+ ts?: string;
+ entryCreatedAt: number;
+ images?: HarnessTurnInput["images"];
+ attachments?: HarnessTurnInput["attachments"];
+ }> = [];
+ const steerTapeStamp = (
+ message: unknown,
+ ): { meta: TapeMeta; images?: HarnessTurnInput["images"] } | undefined => {
const text = textFromContent((message as { content?: unknown }).content);
const at = pendingSteerTapeMeta.findIndex((p) => p.text === text);
if (at < 0) return undefined;
const [steer] = pendingSteerTapeMeta.splice(at, 1);
return {
- bareText: steer!.text,
- ...(steer!.ts ? { ts: steer!.ts } : {}),
- entryCreatedAt: steer!.entryCreatedAt,
+ images: steer!.images,
+ meta: {
+ bareText: steer!.bareText ?? steer!.text,
+ ...(steer!.ts ? { ts: steer!.ts } : {}),
+ ...(steer!.attachments?.length ? { attachments: steer!.attachments } : {}),
+ entryCreatedAt: steer!.entryCreatedAt,
+ },
};
};
const tapeMessage = async (message: unknown): Promise<void> => {
@@ -1840,7 +1853,7 @@ export function createPiHarness(opts?: PiHarnessOptions): Harness {
const rec: NewTapeRecord = {
kind: "message",
harness: "pi",
- payload: stripImageBytes(message, isTrigger ? turn.images : undefined),
+ payload: stripImageBytes(message, isTrigger ? turn.images : steerStamp?.images),
scopeLabel: resultScope ?? turn.scopeLabel,
...(isTrigger
? {
@@ -1853,7 +1866,7 @@ export function createPiHarness(opts?: PiHarnessOptions): Harness {
},
}
: {}),
- ...(steerStamp ? { meta: steerStamp } : {}),
+ ...(steerStamp ? { meta: steerStamp.meta } : {}),
};
try {
await turn.tape(rec);
@@ -1999,12 +2012,20 @@ export function createPiHarness(opts?: PiHarnessOptions): Harness {
harness: "pi",
payload: {
role: "user",
- content: [{ type: "text", text: steer.text }],
+ content: [
+ { type: "text", text: steer.text },
+ ...(steer.images ?? []).map((image) => ({
+ type: "image",
+ mimeType: image.mimeType,
+ ...(image.artifactId ? { artifactRef: image.artifactId } : { omitted: true }),
+ })),
+ ],
timestamp: steer.entryCreatedAt,
},
scopeLabel: turn.scopeLabel,
meta: {
- bareText: steer.text,
+ bareText: steer.bareText ?? steer.text,
+ ...(steer.attachments?.length ? { attachments: steer.attachments } : {}),
...(steer.ts ? { ts: steer.ts } : {}),
entryCreatedAt: steer.entryCreatedAt,
},
@@ -2054,22 +2075,45 @@ export function createPiHarness(opts?: PiHarnessOptions): Harness {
signals,
turn.runId,
{
- onSteer: async (text, ts) => {
+ onSteer: async (text, ts, request) => {
+ const prepared = await turn.prepareSteer?.(text, request);
+ const prompt = prepared?.text ?? text;
+ if (!entry.agentSession.isStreaming) return false;
if (ts && !steeredSeen.has(ts)) {
steeredSeen.add(ts);
try {
const steered = await turn.emit({
type: "user",
- payload: { text, ts, steered: true },
+ payload: {
+ text,
+ ts,
+ steered: true,
+ ...(prepared?.attachments?.length ? { attachments: prepared.attachments } : {}),
+ },
scopeLabel: turn.scopeLabel,
});
- pendingSteerTapeMeta.push({ text, ts, entryCreatedAt: steered.createdAt });
+ pendingSteerTapeMeta.push({
+ text: prompt,
+ bareText: text,
+ ts,
+ entryCreatedAt: steered.createdAt,
+ images: prepared?.images,
+ attachments: prepared?.attachments,
+ });
} catch (e) {
swallow("pi: steer persist", e);
}
}
- if (entry.agentSession.isStreaming) entry.ref.silentRequested = false;
- await entry.agentSession.steer(text);
+ if (!entry.agentSession.isStreaming) return false;
+ entry.ref.silentRequested = false;
+ await entry.agentSession.steer(
+ prompt,
+ prepared?.images?.map((image) => ({
+ type: "image" as const,
+ mimeType: image.mimeType,
+ data: image.dataBase64,
+ })),
+ );
},
onAbort: async () => {
userAborted = true;
diff --git a/src/runs/memory-run-store.ts b/src/runs/memory-run-store.ts
index 3ee7442c9..4ef126ef9 100644
--- a/src/runs/memory-run-store.ts
+++ b/src/runs/memory-run-store.ts
@@ -243,6 +243,24 @@ export function createMemoryRunStore(opts?: { maxClaims?: number }): MemoryRunti
return true;
},
+ async steerQueued(queuedRunId, targetRunId, signal, signals) {
+ const queued = runs.get(queuedRunId);
+ const target = runs.get(targetRunId);
+ if (!queued || queued.status !== "pending" || !target || isTerminal(target.status) || queuedRunId === targetRunId)
+ return false;
+ if ((queued.request.displayText ?? queued.request.text) !== signal.request?.text) return false;
+ runs.delete(queuedRunId);
+ try {
+ await signals.send(targetRunId, signal);
+ } catch (error) {
+ runs.set(queuedRunId, queued);
+ throw error;
+ }
+ retryAfter.delete(queuedRunId);
+ if (queued.dedupKey) byKey.delete(queued.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-signal-store.ts b/src/runs/postgres-run-signal-store.ts
index 6127b9ef2..066899b87 100644
--- a/src/runs/postgres-run-signal-store.ts
+++ b/src/runs/postgres-run-signal-store.ts
@@ -121,22 +121,6 @@ export function createPostgresRunSignalStore(connectionString: string): RunSigna
return toSignals(rows);
},
- async takeLive(runId) {
- const { rows } = await q(
- `WITH taken AS (
- UPDATE run_signals SET consumed_at=$2
- WHERE run_id=$1 AND consumed_at IS NULL AND kind <> 'abort'
- RETURNING id, kind, text, payload
- )
- SELECT id, kind, text, payload FROM taken
- UNION ALL
- SELECT id, kind, text, payload FROM run_signals
- WHERE run_id=$1 AND kind='abort' AND consumed_at IS NULL`,
- [runId, Date.now()],
- );
- return toSignals(rows);
- },
-
async pendingRunIds() {
const { rows } = await q(`SELECT DISTINCT run_id FROM run_signals WHERE consumed_at IS NULL`);
return rows.map((r) => r.run_id as string);
diff --git a/src/runs/postgres-run-store.ts b/src/runs/postgres-run-store.ts
index 1dabe1926..4445d07ba 100644
--- a/src/runs/postgres-run-store.ts
+++ b/src/runs/postgres-run-store.ts
@@ -447,6 +447,32 @@ export function createPostgresRunStore(connectionString: string, opts?: { maxCla
return (rowCount ?? 0) > 0;
},
+ async steerQueued(queuedRunId, targetRunId, signal, signals) {
+ await signals.hasDedupeKey(signal.dedupeKey!);
+ const { rows } = await q(
+ `WITH target AS (
+ SELECT id FROM runs WHERE id=$2 AND status IN ('pending','running') FOR UPDATE
+ ), moved AS (
+ DELETE FROM runs WHERE id=$1 AND id<>$2 AND status='pending'
+ AND COALESCE(request::jsonb->>'displayText',request::jsonb->>'text') = $5::jsonb->'request'->>'text'
+ AND EXISTS (SELECT 1 FROM target) RETURNING id
+ ), sent AS (
+ INSERT INTO run_signals(run_id,kind,text,payload,created_at,dedupe_key)
+ SELECT $2,$3,$4,$5,$6,$7 FROM moved RETURNING id
+ ) SELECT pg_notify('run_signals',$2) FROM sent`,
+ [
+ queuedRunId,
+ targetRunId,
+ signal.kind,
+ signal.text ?? null,
+ JSON.stringify(signal),
+ Date.now(),
+ signal.dedupeKey ?? null,
+ ],
+ );
+ return rows.length > 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-signal-store.ts b/src/runs/run-signal-store.ts
index 8ebdcc276..1d915f7eb 100644
--- a/src/runs/run-signal-store.ts
+++ b/src/runs/run-signal-store.ts
@@ -11,6 +11,7 @@ export interface RunSignal {
request?: TurnRequest;
dedupeKey?: string;
sessionRequest?: OrchestratorInput;
+ queuedRunId?: string;
}
export interface RunSignalStore {
@@ -19,7 +20,6 @@ export interface RunSignalStore {
pending(runId: string): Promise<Array<{ id: string; signal: RunSignal }>>;
acknowledge(runId: string, id: string): Promise<void>;
takePending(runId: string): Promise<RunSignal[]>;
- takeLive(runId: string): Promise<RunSignal[]>;
steerAuthors(runId: string): Promise<string[]>;
pendingRunIds(): Promise<string[]>;
prune(olderThanMs: number): Promise<void>;
@@ -71,13 +71,6 @@ export function createMemoryRunSignalStore(): RunSignalStore {
pending.delete(runId);
return list;
},
- async takeLive(runId) {
- const list = pending.get(runId) ?? [];
- const aborts = list.filter((s) => s.kind === "abort");
- if (aborts.length) pending.set(runId, aborts);
- else pending.delete(runId);
- return list;
- },
async pendingRunIds() {
return [...pending.keys()];
},
@@ -104,7 +97,7 @@ export function createMemoryRunSignalStore(): RunSignalStore {
const SIGNAL_POLL_MS = 5_000;
export interface SignalPollHandlers {
- onSteer(text: string, ts?: string): Promise<void>;
+ onSteer(text: string, ts?: string, request?: TurnRequest): Promise<void | boolean>;
onAbort(): Promise<void>;
}
@@ -114,6 +107,7 @@ export function startSignalPoll(
handlers: SignalPollHandlers,
opts?: { intervalMs?: number; onError?: (e: unknown) => void; drainOnStop?: boolean },
): () => Promise<void> {
+ const declined = new Set<string>();
let draining = false;
let redrain = false;
let accepting = true;
@@ -127,13 +121,26 @@ export function startSignalPoll(
draining = true;
inFlight = (async () => {
let abortDelivered = false;
- for (const s of await signals.takeLive(runId)) {
- if (s.kind === "abort") {
- if (!abortDelivered) {
- await handlers.onAbort();
- abortDelivered = true;
+ for (const { id, signal: s } of await signals.pending(runId)) {
+ try {
+ if (s.kind === "abort") {
+ if (!abortDelivered) {
+ await handlers.onAbort();
+ abortDelivered = true;
+ }
+ } else if (!declined.has(id)) {
+ if (s.text || s.request?.attachments?.length) {
+ const delivered = await handlers.onSteer(s.text ?? "", s.ts, s.request);
+ if (delivered === false) {
+ declined.add(id);
+ continue;
+ }
+ }
+ await signals.acknowledge(runId, id);
}
- } else if (s.text) await handlers.onSteer(s.text, s.ts);
+ } catch (e) {
+ opts?.onError?.(e);
+ }
}
})()
.catch((e: unknown) => opts?.onError?.(e))
diff --git a/src/runs/run-store.ts b/src/runs/run-store.ts
index d619eee80..afbe66caf 100644
--- a/src/runs/run-store.ts
+++ b/src/runs/run-store.ts
@@ -1,4 +1,5 @@
import type { SubscribeOptions } from "../util/event-bus.ts";
+import type { RunSignal, RunSignalStore } from "./run-signal-store.ts";
import type { TurnResult } from "../types.ts";
import type { OrchestratorInput } from "../core/orchestrator.ts";
@@ -94,6 +95,7 @@ export interface RunStore {
inFlightForThread(sessionId: string): Promise<Run[]>;
withdraw(runId: string): Promise<boolean>;
+ steerQueued(queuedRunId: string, targetRunId: string, signal: RunSignal, signals: RunSignalStore): Promise<boolean>;
editPendingText(runId: string, text: string, expectedText: string): Promise<boolean>;
diff --git a/test/claude-harness-turn.test.ts b/test/claude-harness-turn.test.ts
index 1088a0b8b..354cdd71f 100644
--- a/test/claude-harness-turn.test.ts
+++ b/test/claude-harness-turn.test.ts
@@ -499,3 +499,44 @@ for (const terminal of [{ stop_reason: "max_tokens" }, { is_error: true }]) {
);
});
}
+
+test("steering forwards prepared images and file paths while retaining the original caption in history", async () => {
+ const signals = createMemoryRunSignalStore();
+ const runId = "run-steer-files";
+ const request = {
+ surface: "web",
+ actor: { externalId: "U1" },
+ conversation: { kind: "dm" as const, threadRef: "files" },
+ text: "check this",
+ attachments: [{ name: "photo.png", mimetype: "image/png", sizeBytes: 3, blobId: "b1" }],
+ };
+ let injected: unknown;
+ currentScript = async function* (prompts) {
+ const iterator = prompts[Symbol.asyncIterator]();
+ await iterator.next();
+ await signals.send(runId, { kind: "steer", text: "check this", ts: "files.1", request });
+ injected = (await iterator.next()).value?.message.content;
+ yield resultMessage("saw the image");
+ yield resultMessage("done");
+ };
+ const harness = createClaudeHarness({ signals });
+ const { turn, entries } = harnessTurn({ runId });
+ turn.prepareSteer = async (text, received) => {
+ assert.equal(text, "check this");
+ assert.deepEqual(received, request);
+ return {
+ text: "check this\nThe file is in inbox/steer/photo.png",
+ attachments: [{ name: "photo.png", mimetype: "image/png", sizeBytes: 3, direction: "in", artifactId: "f1" }],
+ images: [{ mimeType: "image/png", dataBase64: "YWJj", artifactId: "f1" }],
+ };
+ };
+ await harness.turns.runTurn(turn);
+ assert.deepEqual(injected, [
+ { type: "text", text: "check this\nThe file is in inbox/steer/photo.png" },
+ { type: "image", source: { type: "base64", media_type: "image/png", data: "YWJj" } },
+ ]);
+ const entry = entries.find((e) => (e.payload as { steered?: boolean }).steered);
+ assert.ok(entry);
+ assert.equal((entry.payload as { text: string }).text, "check this");
+ assert.equal((entry.payload as { attachments: Array<{ artifactId: string }> }).attachments[0]?.artifactId, "f1");
+});
diff --git a/test/pi-harness-tape-sync.test.ts b/test/pi-harness-tape-sync.test.ts
index 668c7a1d7..8cfaf407c 100644
--- a/test/pi-harness-tape-sync.test.ts
+++ b/test/pi-harness-tape-sync.test.ts
@@ -78,64 +78,97 @@ function gatedSse(events: Array<Record<string, unknown>>, gate: Promise<void>):
return new Response(stream, { status: 200, headers: { "content-type": "text/event-stream" } });
}
-test("tape rows land synchronously in consumption order, steers at their injection point", async () => {
- const signals = createMemoryRunSignalStore();
- const harness = createPiHarness({ apiKey: "sk-test", signals });
- const sink: Sink = { entries: [], tape: [] };
- let releaseFirstStep = () => {};
- const steerQueued = new Promise<void>((resolve) => {
- releaseFirstStep = () => setTimeout(resolve, 50);
- });
- const tapeRowsAtDispatch: number[] = [];
- const requestMessages: Array<Array<{ role: string }>> = [];
- const realFetch = globalThis.fetch;
- let calls = 0;
- globalThis.fetch = (async (_url: string | URL | Request, init?: RequestInit) => {
- calls += 1;
- tapeRowsAtDispatch.push(sink.tape.filter((rec) => rec.kind === "message").length);
- requestMessages.push((JSON.parse(String(init?.body ?? "{}")) as { messages?: [] }).messages ?? []);
- if (calls === 1) return gatedSse(textReplyEvents("first step"), steerQueued);
- return sse(textReplyEvents("final reply"));
- }) as typeof globalThis.fetch;
- try {
- const turn = turnInput("tape-order", sink, { runId: "run-order" });
- const emit = turn.emit;
- turn.emit = async (entry) => {
- const appended = await emit(entry);
- if (entry.type === "user" && (entry.payload as { steered?: unknown }).steered === true) releaseFirstStep();
- return appended;
- };
- setTimeout(() => {
- void signals.send("run-order", { kind: "steer", text: "actually, do it differently", ts: "1712.001" });
- }, 30);
- const result = await harness.turns.runTurn(turn);
- assert.equal(result.reply, "final reply");
+for (const variant of ["text", "images", "finished during preparation"]) {
+ const withImages = variant !== "text";
+ const finishDuringPreparation = variant === "finished during preparation";
+ test(`tape rows land in consumption order, including steered ${variant}`, async () => {
+ const signals = createMemoryRunSignalStore();
+ const harness = createPiHarness({ apiKey: "sk-test", signals });
+ const sink: Sink = { entries: [], tape: [] };
+ let releaseFirstStep = () => {};
+ const steerQueued = new Promise<void>((resolve) => {
+ releaseFirstStep = () => setTimeout(resolve, 50);
+ });
+ const tapeRowsAtDispatch: number[] = [];
+ const requestMessages: Array<Array<{ role: string }>> = [];
+ const realFetch = globalThis.fetch;
+ let calls = 0;
+ globalThis.fetch = (async (_url: string | URL | Request, init?: RequestInit) => {
+ calls += 1;
+ tapeRowsAtDispatch.push(sink.tape.filter((rec) => rec.kind === "message").length);
+ requestMessages.push((JSON.parse(String(init?.body ?? "{}")) as { messages?: [] }).messages ?? []);
+ if (calls === 1) return gatedSse(textReplyEvents("first step"), steerQueued);
+ return sse(textReplyEvents("final reply"));
+ }) as typeof globalThis.fetch;
+ try {
+ const turn = turnInput("tape-order", sink, { runId: "run-order" });
+ if (withImages)
+ turn.prepareSteer = async (text) => {
+ if (finishDuringPreparation) {
+ releaseFirstStep();
+ await new Promise((resolve) => setTimeout(resolve, 150));
+ }
+ return {
+ text: `${text}\nFile available in inbox/photo.png`,
+ images: [{ mimeType: "image/png", dataBase64: "YWJj", artifactId: "steered-photo" }],
+ };
+ };
+ const emit = turn.emit;
+ turn.emit = async (entry) => {
+ const appended = await emit(entry);
+ if (entry.type === "user" && (entry.payload as { steered?: unknown }).steered === true) releaseFirstStep();
+ return appended;
+ };
+ setTimeout(() => {
+ void signals.send("run-order", { kind: "steer", text: "actually, do it differently", ts: "1712.001" });
+ }, 30);
+ const result = await harness.turns.runTurn(turn);
+ if (finishDuringPreparation) {
+ assert.equal(result.reply, "first step");
+ const pending = await signals.takePending("run-order");
+ assert.equal(pending.length, 1);
+ assert.equal(pending[0]?.text, "actually, do it differently");
+ return;
+ }
+ assert.equal(result.reply, "final reply");
- const messageRows = sink.tape.filter((rec) => rec.kind === "message");
- assert.deepEqual(
- messageRows.map((rec) => (rec.payload as { role: string }).role),
- ["user", "assistant", "user", "assistant"],
- "the tape holds exactly the consumed messages, in consumption order",
- );
- assert.equal(messageRows[0]!.meta?.bareText, "do the thing");
- assert.equal(messageRows[2]!.meta?.bareText, "actually, do it differently");
- assert.equal(messageRows[2]!.meta?.ts, "1712.001", "the steer row is stamped with its arrival ts");
- assert.equal(calls, 2);
- assert.equal(tapeRowsAtDispatch[0], 1, "the trigger user row is committed before the first dispatch");
- assert.equal(
- tapeRowsAtDispatch[1],
- 3,
- "step 2 is not dispatched until the trigger, first reply, and injected steer are all on the tape",
- );
- assert.deepEqual(
- requestMessages[1]!.map((message) => message.role),
- ["user", "assistant", "user"],
- "the steer was injected into the model context exactly where the tape says",
- );
- } finally {
- globalThis.fetch = realFetch;
- }
-});
+ const messageRows = sink.tape.filter((rec) => rec.kind === "message");
+ assert.deepEqual(
+ messageRows.map((rec) => (rec.payload as { role: string }).role),
+ ["user", "assistant", "user", "assistant"],
+ "the tape holds exactly the consumed messages, in consumption order",
+ );
+ assert.equal(messageRows[0]!.meta?.bareText, "do the thing");
+ assert.equal(messageRows[2]!.meta?.bareText, "actually, do it differently");
+ assert.equal(messageRows[2]!.meta?.ts, "1712.001", "the steer row is stamped with its arrival ts");
+ if (withImages) {
+ const content = (messageRows[2]!.payload as { content: Array<Record<string, unknown>> }).content;
+ assert.deepEqual(
+ content.find((block) => block.type === "image"),
+ {
+ type: "image",
+ mimeType: "image/png",
+ artifactRef: "steered-photo",
+ },
+ );
+ }
+ assert.equal(calls, 2);
+ assert.equal(tapeRowsAtDispatch[0], 1, "the trigger user row is committed before the first dispatch");
+ assert.equal(
+ tapeRowsAtDispatch[1],
+ 3,
+ "step 2 is not dispatched until the trigger, first reply, and injected steer are all on the tape",
+ );
+ assert.deepEqual(
+ requestMessages[1]!.map((message) => message.role),
+ ["user", "assistant", "user"],
+ "the steer was injected into the model context exactly where the tape says",
+ );
+ } finally {
+ globalThis.fetch = realFetch;
+ }
+ });
+}
test("a failed tape append fails the turn loudly with the append error, no checkpoint", async () => {
const harness = createPiHarness({ apiKey: "sk-test" });
diff --git a/test/queued-steer-store.test.ts b/test/queued-steer-store.test.ts
new file mode 100644
index 000000000..367c60f6b
--- /dev/null
+++ b/test/queued-steer-store.test.ts
@@ -0,0 +1,79 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { randomUUID } from "node:crypto";
+import { createMemoryRunStore } from "../src/runs/memory-run-store.ts";
+import { createPostgresRunStore } from "../src/runs/postgres-run-store.ts";
+import { createMemoryRunSignalStore, type RunSignal } from "../src/runs/run-signal-store.ts";
+import { createPostgresRunSignalStore } from "../src/runs/postgres-run-signal-store.ts";
+import type { OrchestratorInput } from "../src/core/orchestrator.ts";
+
+for (const backend of ["memory", "postgres"] as const) {
+ test(
+ `${backend}: queued steering transfers files once or leaves the original queue intact`,
+ {
+ skip: backend === "postgres" && !process.env.DATABASE_URL ? "DATABASE_URL required" : false,
+ },
+ async () => {
+ const runtime = backend === "memory" ? createMemoryRunStore() : createPostgresRunStore(process.env.DATABASE_URL!);
+ const signals =
+ backend === "memory" ? createMemoryRunSignalStore() : createPostgresRunSignalStore(process.env.DATABASE_URL!);
+ const runs = runtime.runs;
+ const sessionId = randomUUID();
+ const actor = { id: "queued-owner", type: "internal" as const };
+ const request: OrchestratorInput = {
+ actor,
+ conversation: { kind: "dm", threadRef: sessionId, audience: [actor] },
+ origin: { kind: "direct" },
+ text: "",
+ };
+ const attachments = [{ name: "file.txt", blobId: "queued-blob", sizeBytes: 3, mimetype: "text/plain" }];
+ try {
+ const { run: target } = await runs.enqueue({ sessionId, request: { ...request, text: "working" } });
+ const { run: queued } = await runs.enqueue({ sessionId, request: { ...request, attachments } });
+ const signal: RunSignal = {
+ kind: "steer",
+ text: "",
+ dedupeKey: randomUUID(),
+ request: {
+ surface: "web",
+ actor: { externalId: actor.id },
+ conversation: { kind: "dm", threadRef: sessionId },
+ text: "",
+ attachments,
+ },
+ };
+ const moved = await Promise.all([
+ runs.steerQueued(queued.id, target.id, signal, signals),
+ runs.steerQueued(queued.id, target.id, signal, signals),
+ ]);
+ assert.equal(moved.filter(Boolean).length, 1);
+ assert.equal(await runs.get(queued.id), null);
+ const pending = await signals.takePending(target.id);
+ assert.equal(pending.length, 1);
+ assert.deepEqual(pending[0]?.request?.attachments, attachments);
+ const { run: edited } = await runs.enqueue({ sessionId, request: { ...request, attachments } });
+ assert.equal(await runs.editPendingText(edited.id, "new caption", ""), true);
+ assert.equal(
+ await runs.steerQueued(edited.id, target.id, { ...signal, dedupeKey: randomUUID() }, signals),
+ false,
+ );
+ assert.equal((await runs.get(edited.id))?.request.text, "new caption");
+ assert.equal((await signals.pending(target.id)).length, 0);
+ await runs.withdraw(edited.id);
+ const lease = await runs.claimById(target.id, "test", 10000);
+ assert.ok(lease?.leaseToken);
+ await runs.complete(target.id, lease.leaseToken, { status: "ok", reply: "done" });
+ const { run: late } = await runs.enqueue({ sessionId, request: { ...request, attachments } });
+ assert.equal(
+ await runs.steerQueued(late.id, target.id, { ...signal, dedupeKey: randomUUID() }, signals),
+ false,
+ );
+ assert.deepEqual((await runs.get(late.id))?.request.attachments, attachments);
+ await runs.withdraw(late.id);
+ } finally {
+ await signals.close?.();
+ await runs.close?.();
+ }
+ },
+ );
+}
diff --git a/test/run-signal-route.test.ts b/test/run-signal-route.test.ts
index 3344e6a03..4651b13cc 100644
--- a/test/run-signal-route.test.ts
+++ b/test/run-signal-route.test.ts
@@ -628,3 +628,34 @@ test("web proxy: /api/runs/active tracks queued runs — the live one first, the
).json()) as { runId?: string | null };
assert.equal(active2.runId, second, "once the live run finishes, the queued one becomes active");
});
+
+test("web steering atomically transfers file-only queues and deduplicates retries", async () => {
+ const threadRef = "web:U1:steer-files";
+ const attachments = [{ name: "report.txt", mimetype: "text/plain", sizeBytes: 6, blobId: "steer-blob" }];
+ const submit = async (text: string, files: import("../src/types.ts").IncomingAttachment[] = []) => {
+ const res = await fetch(
+ `${webBase}/api/turn`,
+ asUser("U1", {
+ method: "POST",
+ body: JSON.stringify({ text, threadRef, attachments: files }),
+ }),
+ );
+ return ((await res.json()) as { runId: string }).runId;
+ };
+ const runId = await submit("working");
+ const queuedRunId = await submit("", attachments);
+ for (let i = 0; i < 2; i++) {
+ const response = await fetch(
+ `${webBase}/api/runs/${runId}/signal`,
+ asUser("U1", {
+ method: "POST",
+ body: JSON.stringify({ kind: "steer", text: "", threadRef, queuedRunId }),
+ }),
+ );
+ assert.equal(response.status, 200, await response.text());
+ }
+ assert.equal(await built.runs.get(queuedRunId), null);
+ const signals = await built.signals.takePending(runId);
+ assert.equal(signals.length, 1);
+ assert.deepEqual(signals[0]?.request?.attachments, attachments);
+});
diff --git a/test/run-signal-store.test.ts b/test/run-signal-store.test.ts
index 4b186fcf1..2101e2eef 100644
--- a/test/run-signal-store.test.ts
+++ b/test/run-signal-store.test.ts
@@ -29,18 +29,19 @@ test("memory store: send appends, takePending drains in order and consumes", asy
assert.equal((await store.takePending("other")).length, 1, "other run unaffected");
});
-test("memory store: takeLive consumes steers but leaves an abort pending for the terminal drain", async () => {
+test("memory store: pending retains steers until acknowledged and leaves aborts for terminal drain", async () => {
const store = createMemoryRunSignalStore();
await store.send("r1", { kind: "steer", text: "a" });
await store.send("r1", { kind: "abort" });
await store.send("r1", { kind: "steer", text: "b" });
assert.deepEqual(
- (await store.takeLive("r1")).map((s) => s.kind),
+ (await store.pending("r1")).map((s) => s.signal.kind),
["steer", "abort", "steer"],
"a live drain sees everything pending, in order",
);
+ for (const row of await store.pending("r1")) if (row.signal.kind === "steer") await store.acknowledge("r1", row.id);
assert.deepEqual(
- (await store.takeLive("r1")).map((s) => s.kind),
+ (await store.pending("r1")).map((s) => s.signal.kind),
["abort"],
"steers are consumed exactly once; the abort is never consumed by a live drain",
);
@@ -49,7 +50,7 @@ test("memory store: takeLive consumes steers but leaves an abort pending for the
["abort"],
"the terminal drain is what consumes the abort",
);
- assert.deepEqual(await store.takeLive("r1"), []);
+ assert.deepEqual(await store.pending("r1"), []);
assert.deepEqual(await store.pendingRunIds(), [], "nothing outlives the terminal drain");
});
@@ -66,7 +67,7 @@ test("startSignalPoll: a user stop outlives a lease-losing poller, is honored by
await until(() => loserAborts >= 1);
await loser();
assert.deepEqual(
- (await store.takeLive("r1")).map((s) => s.kind),
+ (await store.pending("r1")).map((s) => s.signal.kind),
["abort"],
"the losing poller did not consume the stop",
);
@@ -316,7 +317,7 @@ test("pg store: NOTIFY doorbell reaches a listener on a different connection", {
}
});
-test("pg store: takeLive consumes steers but leaves an abort pending for the terminal drain", { skip }, async () => {
+test("pg store: pending retains steers until acknowledged and leaves aborts for terminal drain", { skip }, async () => {
const store = createPostgresRunSignalStore(URL!);
const runId = `test-run-${Date.now()}-${Math.random().toString(36).slice(2)}`;
try {
@@ -324,12 +325,14 @@ test("pg store: takeLive consumes steers but leaves an abort pending for the ter
await store.send(runId, { kind: "abort" });
await store.send(runId, { kind: "steer", text: "b" });
assert.deepEqual(
- (await store.takeLive(runId)).map((s) => s.kind),
+ (await store.pending(runId)).map((s) => s.signal.kind),
["steer", "abort", "steer"],
"a live drain sees everything pending, in order",
);
+ for (const row of await store.pending(runId))
+ if (row.signal.kind === "steer") await store.acknowledge(runId, row.id);
assert.deepEqual(
- (await store.takeLive(runId)).map((s) => s.kind),
+ (await store.pending(runId)).map((s) => s.signal.kind),
["abort"],
"steers are consumed exactly once; the abort is never consumed by a live drain",
);
@@ -339,7 +342,7 @@ test("pg store: takeLive consumes steers but leaves an abort pending for the ter
["abort"],
"the terminal drain is what consumes the abort",
);
- assert.deepEqual(await store.takeLive(runId), []);
+ assert.deepEqual(await store.pending(runId), []);
assert.ok(!(await store.pendingRunIds()).includes(runId), "nothing outlives the terminal drain");
} finally {
await store.close?.();
@@ -468,3 +471,105 @@ for (const backend of ["memory", "postgres"] as const) {
},
);
}
+test("startSignalPoll delivers the request and files even when a steer has no caption", async () => {
+ const signals = createMemoryRunSignalStore();
+ const request = {
+ surface: "web",
+ actor: { externalId: "U1" },
+ conversation: { kind: "dm" as const, threadRef: "files" },
+ text: "",
+ attachments: [{ name: "report.txt", mimetype: "text/plain", sizeBytes: 3, blobId: "b1" }],
+ };
+ let received: unknown;
+ const stop = startSignalPoll(signals, "files", {
+ onAbort: async () => {},
+ onSteer: async (text, ts, carried) => {
+ received = { text, ts, request: carried };
+ },
+ });
+ try {
+ await signals.send("files", { kind: "steer", request, ts: "1" });
+ await until(() => received !== undefined);
+ assert.deepEqual(received, { text: "", ts: "1", request });
+ } finally {
+ await stop();
+ }
+});
+
+test("failed preparation preserves the entire pending batch for retry", async () => {
+ const store = createMemoryRunSignalStore();
+ await store.send("prepare-failure", { kind: "steer", text: "first" });
+ await store.send("prepare-failure", { kind: "steer", text: "second" });
+ let failed = false;
+ const stop = startSignalPoll(
+ store,
+ "prepare-failure",
+ {
+ onSteer: async () => {
+ throw new Error("upload unavailable");
+ },
+ onAbort: async () => {},
+ },
+ {
+ intervalMs: 10,
+ onError: () => {
+ failed = true;
+ },
+ },
+ );
+ await until(() => failed);
+ await stop();
+ assert.deepEqual(
+ (await store.takePending("prepare-failure")).map((s) => s.text),
+ ["first", "second"],
+ );
+});
+
+test("a declined late steer stays durable for terminal replay without spinning", async () => {
+ const store = createMemoryRunSignalStore();
+ let attempts = 0;
+ const stop = startSignalPoll(
+ store,
+ "late-steer",
+ {
+ onSteer: async () => {
+ attempts++;
+ return false;
+ },
+ onAbort: async () => {},
+ },
+ { intervalMs: 10 },
+ );
+ await store.send("late-steer", { kind: "steer", text: "late" });
+ await until(() => attempts > 0);
+ await sleep(35);
+ await stop();
+ assert.equal(attempts, 1);
+ assert.equal((await store.takePending("late-steer"))[0]?.text, "late");
+});
+
+test("failed attachment preparation does not block Stop", async () => {
+ const store = createMemoryRunSignalStore();
+ await store.send("stop-after-failure", { kind: "steer", text: "file" });
+ await store.send("stop-after-failure", { kind: "abort" });
+ let aborted = false;
+ const stop = startSignalPoll(
+ store,
+ "stop-after-failure",
+ {
+ onSteer: async () => {
+ throw new Error("upload unavailable");
+ },
+ onAbort: async () => {
+ aborted = true;
+ },
+ },
+ { intervalMs: 5 },
+ );
+ try {
+ await until(() => aborted);
+ } finally {
+ await stop();
+ }
+ assert.equal((await store.pending("stop-after-failure"))[0]?.signal.text, "file");
+});
diff --git a/test/system-prompt-order.test.ts b/test/system-prompt-order.test.ts
index 5b7d6b9f8..2c28c6a00 100644
--- a/test/system-prompt-order.test.ts
+++ b/test/system-prompt-order.test.ts
@@ -1,3 +1,5 @@
+import type { Harness, HarnessTurnInput } from "../src/harness/harness.ts";
+import { createMemoryBlobTransferStore, type BlobTransferStore } from "../src/persistence/blob-transfer.ts";
import type { SecurityScreener } from "../src/security/security-screener.ts";
import { createSkillBundleStore, type SkillBundleStore } from "../src/skills/skill-bundle-store.ts";
import { verifyCapabilityToken } from "../src/auth/capability-token.ts";
@@ -90,6 +92,8 @@ const skills = {
function buildOrchestrator(
extra: {
+ blobTransfer?: BlobTransferStore;
+ harness?: Harness;
memoryPolicy?: import("../src/memory/policy.ts").MemoryPolicy;
crons?: CronStore;
sandbox?: Sandbox;
@@ -870,3 +874,116 @@ test("Open uses the exact skill snapshot that passed screening despite an in-fli
assert.match(result.reply ?? "", /SAFE_DESCRIPTION/);
assert.doesNotMatch(result.reply ?? "", /UNSCREENED_UPDATE|UNSCREENED_BODY/);
});
+
+test("steered files materialize in separate inboxes and keep distinct durable artifacts", async () => {
+ const blobTransfer = createMemoryBlobTransferStore();
+ const first = await blobTransfer.put(Buffer.from("first file"));
+ const second = await blobTransfer.put(Buffer.from("second file"));
+ const writes = new Map<string, string>();
+ const sandbox: Sandbox = {
+ ...readSandbox(),
+ removeDir: async () => {},
+ listDir: async () => [],
+ writeFile: async () => {},
+ writeFileBytes: async (_handle, path, bytes) => {
+ writes.set(path, Buffer.from(bytes).toString());
+ },
+ };
+ const harness = createMockHarness();
+ const prepared: Array<Awaited<ReturnType<NonNullable<HarnessTurnInput["prepareSteer"]>>>> = [];
+ harness.turns.runTurn = async (turn) => {
+ for (const blob of [first, second]) {
+ prepared.push(
+ await turn.prepareSteer!("read this", {
+ surface: "web",
+ actor: { externalId: actor.id },
+ conversation: { kind: "dm", threadRef: "steer-files" },
+ text: "read this",
+ attachments: [{ name: "report.txt", mimetype: "text/plain", ...blob }],
+ }),
+ );
+ }
+ return { reply: "done" };
+ };
+ const { orchestrator, config, files } = buildOrchestrator({ harness, sandbox, blobTransfer });
+ await config.setSecurityPosture(scopeId("org", ORG), "dangerous");
+ const result = await orchestrator.handleTurn(dm("steer-files", "hello"));
+ assert.equal(result.status, "ok", result.reason);
+ const inboundWrites = [...writes].filter(([path]) => path.endsWith("/report.txt"));
+ assert.equal(inboundWrites.length, 2);
+ assert.deepEqual(
+ inboundWrites.map(([, content]) => content),
+ ["first file", "second file"],
+ );
+ for (const [i, [path]] of inboundWrites.entries()) {
+ assert.ok(prepared[i]!.text.includes(path));
+ assert.ok(await files.get(prepared[i]!.attachments![0]!.artifactId!));
+ }
+ assert.notEqual(prepared[0]!.attachments![0]!.artifactId, prepared[1]!.attachments![0]!.artifactId);
+});
+
+test("read-only turns report steered files as unavailable without provisioning a sandbox", async () => {
+ const harness = createMockHarness();
+ let prepared: Awaited<ReturnType<NonNullable<HarnessTurnInput["prepareSteer"]>>> | undefined;
+ harness.turns.runTurn = async (turn) => {
+ prepared = await turn.prepareSteer!("", {
+ surface: "web",
+ actor: { externalId: actor.id },
+ conversation: { kind: "dm", threadRef: "steer-strict" },
+ text: "",
+ attachments: [{ name: "secret.txt", mimetype: "text/plain", sizeBytes: 4, blobId: "b1" }],
+ });
+ return { reply: "done" };
+ };
+ const { orchestrator, config } = buildOrchestrator({ harness });
+ await config.setSecurityPosture(scopeId("org", ORG), "strict");
+ const result = await orchestrator.handleTurn(dm("steer-strict", "hello", { readOnly: true }));
+ assert.equal(result.status, "ok", result.reason);
+ assert.deepEqual(prepared?.attachments, []);
+ assert.match(prepared?.text ?? "", /secret.txt/);
+});
+
+test("steered documents use the inbound security screen before writing their contents", async () => {
+ const blobTransfer = createMemoryBlobTransferStore();
+ const blob = await blobTransfer.put(Buffer.from("STEER_UNTRUSTED_CONTENT"));
+ const writes: string[] = [];
+ const sandbox: Sandbox = {
+ ...readSandbox(),
+ removeDir: async () => {},
+ listDir: async () => [],
+ writeFile: async () => {},
+ writeFileBytes: async (_handle, path) => {
+ writes.push(path);
+ },
+ };
+ const harness = createMockHarness();
+ let prepared: Awaited<ReturnType<NonNullable<HarnessTurnInput["prepareSteer"]>>> | undefined;
+ harness.turns.runTurn = async (turn) => {
+ prepared = await turn.prepareSteer!("read the attachment", {
+ surface: "web",
+ actor: { externalId: actor.id },
+ conversation: { kind: "dm", threadRef: "steer-screen" },
+ text: "read the attachment",
+ attachments: [{ name: "unsafe.txt", mimetype: "text/plain", ...blob }],
+ });
+ return { reply: "done" };
+ };
+ const securityScreener: SecurityScreener = {
+ provider: "test",
+ shadow: false,
+ classify: async ({ payload }) => ({
+ verdict: { decision: payload.includes("STEER_UNTRUSTED_CONTENT") ? "strict" : "auto" },
+ score: 0,
+ threshold: 1,
+ }),
+ };
+ const { orchestrator } = buildOrchestrator({ harness, sandbox, blobTransfer, securityScreener });
+ const result = await orchestrator.handleTurn(dm("steer-screen", "hello"));
+ assert.equal(result.status, "ok", result.reason);
+ assert.deepEqual(prepared?.attachments, []);
+ assert.match(prepared?.text ?? "", /unsafe.txt.*withheld/);
+ assert.equal(
+ writes.some((path) => path.endsWith("unsafe.txt")),
+ false,
+ );
+});