Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Show steering messages where the model receives them (#1652)

Regan Bell46387a932ae1
diff --git a/plugins/web-ui/src/chat.ts b/plugins/web-ui/src/chat.ts
index e2ca376d5..9566393f1 100644
--- a/plugins/web-ui/src/chat.ts
+++ b/plugins/web-ui/src/chat.ts
@@ -65,6 +65,8 @@ import {
import {
continuableMessages,
messagesWithStreaming,
+ userEntryMessage,
+ appendConsumedSteers,
withBase,
type SessionPin,
activeRunForThread,
@@ -115,6 +117,7 @@ import {
import {
buildTimeline,
messageWorkTimeline,
+ workTimelineSegments,
streamingTextTail,
currentTextPhase,
postSpeechText,
@@ -281,6 +284,38 @@ export function createChatSurface(
labelSpeakers: false,
};
+ const inlineSteers = new Map<number, { message: AgentMessage; index: number }>();
+ const steerMessageCache = new WeakMap<WorkBlock["activity"], Array<{ seq: number; message: AgentMessage }>>();
+
+ function prepareMessageRows(messages: AgentMessage[]): void {
+ inlineSteers.clear();
+ const messageIndices = new Map(
+ messages.map((message, index) => [(message as { entrySeq?: number }).entrySeq, index]),
+ );
+ for (const message of messages) {
+ const activity = (message as AssistantWork).work?.activity;
+ if (!activity) continue;
+ let steers = steerMessageCache.get(activity);
+ if (!steers) {
+ steers = activity.flatMap((entry) => {
+ if (entry.type !== "user") return [];
+ const user = userEntryMessage(entry);
+ return user?.steered ? [{ seq: entry.seq, message: user as AgentMessage }] : [];
+ });
+ steerMessageCache.set(activity, steers);
+ }
+ for (const steer of steers) {
+ const index = messageIndices.get(steer.seq);
+ inlineSteers.set(steer.seq, {
+ message: index === undefined ? steer.message : messages[index]!,
+ index:
+ index === undefined ? -1 : index - (chatState.inheritedExpanded ? chatState.inheritedMessages.length : 0),
+ });
+ }
+ }
+ updateSpeakerLabels([...messages, ...[...inlineSteers.values()].map((steer) => steer.message)]);
+ }
+
function updateSpeakerLabels(messages: AgentMessage[]): void {
const names = new Set<string>();
for (const m of messages) {
@@ -830,6 +865,7 @@ export function createChatSurface(
function observeLiveWork(agent: Agent): (work: WorkBlock) => void {
return (work: WorkBlock) => {
if (agent !== chatState.agent) return;
+ appendConsumedSteers(agent.state.messages, work);
chatState.liveWork = work;
syncWorkTicker();
scheduleStreamDraw(agent);
@@ -1036,7 +1072,7 @@ export function createChatSurface(
let approvals: PendingApproval[] = [];
const draw = () => {
const shownMessages = chatState.inheritedExpanded ? [...chatState.inheritedMessages, ...messages] : messages;
- updateSpeakerLabels(shownMessages);
+ prepareMessageRows(shownMessages);
render(
html`
<div class="custom-chat-shell">
@@ -1408,7 +1444,7 @@ export function createChatSurface(
const messages = chatState.inheritedExpanded
? [...chatState.inheritedMessages, ...currentMessages]
: currentMessages;
- updateSpeakerLabels(messages);
+ prepareMessageRows(messages);
const isNewUser = sessionsState.list.filter((s) => s.id).length === 0;
const editingApp = appEditSlug(chatState.threadRef, appState.me?.user);
const showWelcome =
@@ -1577,6 +1613,7 @@ export function createChatSurface(
index: number,
isStreaming: boolean,
): TemplateResult | typeof nothing {
+ if ((message as { steered?: boolean }).steered) return nothing;
const msg = message as AssistantWork & {
stopReason?: string;
errorMessage?: string;
@@ -1587,8 +1624,10 @@ export function createChatSurface(
const cacheable =
!isStreaming &&
!(message as { subagentMail?: SubagentMailRef }).subagentMail &&
- !work?.activity.some((activity) =>
- ["session", "sessions"].includes((activity.payload as ToolPayload | null)?.tool ?? ""),
+ !work?.activity.some(
+ (activity) =>
+ activity.type === "user" ||
+ ["session", "sessions"].includes((activity.payload as ToolPayload | null)?.tool ?? ""),
) &&
(!work || ((work.status === "complete" || work.status === "failed") && !work.pendingApprovals?.length));
if (!cacheable) return chatMessage(message, index, isStreaming);
@@ -1638,10 +1677,16 @@ export function createChatSurface(
return tpl;
}
- function chatMessage(message: AgentMessage, index: number, isStreaming = false): TemplateResult | typeof nothing {
+ function chatMessage(
+ message: AgentMessage,
+ index: number,
+ isStreaming = false,
+ inline = false,
+ ): TemplateResult | typeof nothing {
const hidden = message as { opener?: boolean; resumeAnchor?: boolean };
if (hidden.opener || hidden.resumeAnchor) return nothing;
const role = (message as { role?: string }).role;
+ if (!inline && (message as { steered?: boolean }).steered) return nothing;
if (role === "user" || role === "user-with-attachments") {
const mail = (message as { subagentMail?: SubagentMailRef }).subagentMail;
if (mail) {
@@ -1669,7 +1714,6 @@ export function createChatSurface(
data-index=${index}
data-entry-seqs=${messageEntrySeqs(message).join(" ")}
>
- ${steered ? html`<div class="steer-label">↪ steered the running task</div>` : nothing}
${speaker ? html`<div class="speaker-label">${speaker}</div>` : nothing}
${attachmentGallery(attachments, (attachment) => browserRenderableImage(attachment.mimeType), userAttachmentBadge)}
<div
@@ -1745,20 +1789,25 @@ export function createChatSurface(
const showWork =
shouldShowApprovalWork(msg, work, text) &&
shouldShowWork(work, isStreaming || msg.stopReason === "error" || msg.stopReason === "aborted" ? "" : text);
- let workView = showWork
- ? workBlock(
- work,
- isStreaming,
- msg.stopReason === "aborted" || msg.stopReason === "error" ? "" : text,
- (msg as AssistantWork).streamingBaseline ?? "",
- )
- : nothing;
+ const steeringOnly =
+ !showWork && work ? messageWorkTimeline(work, text).filter((item) => item.kind === "steer") : [];
+ let workView: TemplateResult | typeof nothing =
+ work && steeringOnly.length ? html`${steeringOnly.map((item) => renderTimelineItem(item, work))}` : nothing;
+ if (showWork) {
+ workView = workBlock(
+ work,
+ isStreaming,
+ msg.stopReason === "aborted" || msg.stopReason === "error" ? "" : text,
+ (msg as AssistantWork).streamingBaseline ?? "",
+ );
+ }
if (msg.stopReason === "aborted") {
workView = work ? workBlock(work, false, "", "", true) : html`<div class="stopped-head">You stopped</div>`;
}
const deliveredFiles = (msg as AssistantWork).deliveredFiles;
const hasVisibleContent =
showWork ||
+ steeringOnly.length > 0 ||
hasText ||
Boolean(deliveredFiles?.length) ||
msg.content.some((chunk) => chunk.type === "thinking" && chunk.thinking.trim());
@@ -1767,7 +1816,9 @@ export function createChatSurface(
<article
class="message-row assistant-row ${isStreaming ? "streaming" : ""}"
data-index=${index}
- data-entry-seqs=${messageEntrySeqs(message).join(" ")}
+ data-entry-seqs=${messageEntrySeqs(message)
+ .filter((seq) => !inlineSteers.has(seq))
+ .join(" ")}
>
<div class="assistant-body">
${workView} ${assistantContent(msg, isStreaming, showWork)} ${assistantFileList(deliveredFiles)}
@@ -2442,70 +2493,86 @@ export function createChatSurface(
isStreaming &&
currentTextPhase(work)?.phase !== "final_answer" &&
(work.status === "working" || work.status === "thinking");
- const replies: string[] = [];
- const timeline = messageWorkTimeline(work, active ? "" : text).filter((item) => {
- const speech = item.kind === "tool" ? postSpeechText(item.row) : null;
- if (speech === null) return true;
- replies.push(speech);
- return false;
- });
- const tail = active ? streamingTextTail(text, work.activity) : "";
- const stopping = isStreaming && runSlot.stopGeneration === runSlot.generation;
- const animating = active && !stopping;
- let label = stopping ? "Stop requested" : workLabel(work);
- if (stopped) label = `You stopped after ${goalElapsedLabel(0, workSeconds(work) * 1000)}`;
- if (timeline.length === 1 && !tail.trim() && !stopped && !stopping && !work.stale && !work.pendingApprovals?.length)
- return html`${renderTimelineItem(timeline[0]!, work)}${replies.map((reply) => html`<div class="streaming-text" dir="auto">${markdown(reply)}</div>`)}`;
- let fold =
- timeline.length || tail.trim() || work.pendingApprovals?.length
- ? html`<details
- class=${stopped ? "stopped-work" : `work work-fold work-${work.status}`}
- ?open=${active || !!work.pendingApprovals?.length}
- >
- <summary class=${stopped ? "stopped-head" : "work-head"}>
- ${sheenLabel(label, animating)}<span class="activity-chevron">${icon(ChevronRight, 14)}</span>
- </summary>
- ${stopped ? nothing : html`<div class="work-divider"></div>`}
- <div class="work-rows">
- ${guard(
- [
- work,
- work.activity,
- work.status,
- work.stale,
- work.pendingApprovals,
- active,
- active ? "" : text,
- sessionsState.list,
- ],
- () =>
- repeat(
- activityGroups(timeline),
- (items) => timelineKey(items[0]!),
- (items) => {
- if (items.length === 1 || items[0]?.kind === "text") return renderTimelineItem(items[0]!, work);
- const summary = activityGroupSummary(items, work.status);
- const groupIcon = { read: BookOpen, search: Search, execute: Terminal, other: Wrench }[
- summary.category
- ];
- return html`<details class="activity-group work-fold" ?open=${active || summary.attention}>
- <summary class="work-head">
- ${icon(groupIcon, 15)}<span>${summary.label}</span
- ><span class="activity-chevron">${icon(ChevronRight, 14)}</span>
- </summary>
- <div class="work-rows">
- ${repeat(items, timelineKey, (item) => renderTimelineItem(item, work))}
- </div>
- </details>`;
- },
- ),
- )}
- ${tail.trim() ? html`<div class="work-said streaming-text ${animating ? "live-stream" : ""}">${markdown(tail, animating, streamingTextTail(baseline, work.activity))}</div>` : nothing}
- </div>
- </details>`
- : nothing;
- if (stopped && fold === nothing) fold = html`<div class="stopped-head">${label}</div>`;
- return html`${fold}${replies.map((reply) => html`<div class="streaming-text" dir="auto">${markdown(reply)}</div>`)}`;
+ const segments = workTimelineSegments(messageWorkTimeline(work, active ? "" : text));
+ return html`${segments.map((segment, index) => {
+ const steer = segment[0];
+ if (steer?.kind === "steer") return renderTimelineItem(steer, work);
+ const last = index === segments.length - 1;
+ const replies: string[] = [];
+ const timeline = segment.filter((item) => {
+ const speech = item.kind === "tool" ? postSpeechText(item.row) : null;
+ if (speech === null) return true;
+ replies.push(speech);
+ return false;
+ });
+ const tail = active && last ? streamingTextTail(text, work.activity) : "";
+ const stopping = isStreaming && runSlot.stopGeneration === runSlot.generation;
+ const animating = active && last && !stopping;
+ let label = last ? workLabel(work) : "Worked";
+ if (stopping && last) label = "Stop requested";
+ if (stopped && last) label = `You stopped after ${goalElapsedLabel(0, workSeconds(work) * 1000)}`;
+ if (
+ timeline.length === 1 &&
+ !tail.trim() &&
+ !(last && (stopped || stopping || work.stale || work.pendingApprovals?.length))
+ )
+ return html`${renderTimelineItem(timeline[0]!, work)}${replies.map((reply) => html`<div class="streaming-text" dir="auto">${markdown(reply)}</div>`)}`;
+ let fold =
+ timeline.length || tail.trim() || (last && (active || work.pendingApprovals?.length))
+ ? html`<details
+ class=${stopped && last ? "stopped-work" : `work work-fold work-${work.status}`}
+ ?open=${last && (active || !!work.pendingApprovals?.length)}
+ >
+ <summary class=${stopped && last ? "stopped-head" : "work-head"}>
+ ${sheenLabel(label, animating)}<span class="activity-chevron">${icon(ChevronRight, 14)}</span>
+ </summary>
+ ${stopped && last ? nothing : html`<div class="work-divider"></div>`}
+ <div class="work-rows">
+ ${guard(
+ [
+ work,
+ work.activity,
+ work.status,
+ work.stale,
+ work.pendingApprovals,
+ active,
+ active ? "" : text,
+ sessionsState.list,
+ index,
+ last,
+ ],
+ () =>
+ repeat(
+ activityGroups(timeline),
+ (items) => timelineKey(items[0]!),
+ (items) => {
+ if (items.length === 1 || items[0]?.kind === "text") return renderTimelineItem(items[0]!, work);
+ const summary = activityGroupSummary(items, work.status);
+ const groupIcon = { read: BookOpen, search: Search, execute: Terminal, other: Wrench }[
+ summary.category
+ ];
+ return html`<details
+ class="activity-group work-fold"
+ ?open=${(active && last) || summary.attention}
+ >
+ <summary class="work-head">
+ ${icon(groupIcon, 15)}<span>${summary.label}</span
+ ><span class="activity-chevron">${icon(ChevronRight, 14)}</span>
+ </summary>
+ <div class="work-rows">
+ ${repeat(items, timelineKey, (item) => renderTimelineItem(item, work))}
+ </div>
+ </details>`;
+ },
+ ),
+ )}
+ ${tail.trim() ? html`<div class="work-said streaming-text ${animating ? "live-stream" : ""}">${markdown(tail, animating, streamingTextTail(baseline, work.activity))}</div>` : nothing}
+ </div>
+ </details>`
+ : nothing;
+ if (stopped && last && fold === nothing) fold = html`<div class="stopped-head">${label}</div>`;
+ return html`${fold}${replies.map((reply) => html`<div class="streaming-text" dir="auto">${markdown(reply)}</div>`)}`;
+ })}`;
}
function approvalSummaryView(a: PendingApproval, expanded = false): TemplateResult {
@@ -2557,6 +2624,12 @@ export function createChatSurface(
function renderTimelineItem(item: TimelineItem, work: WorkBlock): TemplateResult {
const status = work.status;
const stale = work.stale === true;
+ if (item.kind === "steer") {
+ const steer = inlineSteers.get(item.activity.seq);
+ return html`<div class="inline-steer">
+ ${steer ? chatMessage(steer.message, steer.index, false, true) : nothing}
+ </div>`;
+ }
if (item.kind === "thinking") {
const thought = thinkingPresentation((item.activity.payload as { thinking?: string }).thinking ?? "");
return html`<details class="thinking-row">
diff --git a/plugins/web-ui/src/composer.ts b/plugins/web-ui/src/composer.ts
index 7c7b450ba..50438abe2 100644
--- a/plugins/web-ui/src/composer.ts
+++ b/plugins/web-ui/src/composer.ts
@@ -295,6 +295,24 @@ export function createComposerSurface(ctx: ConvCtx, options: ComposerOptions = {
);
}
+ const steeringRuns = new Map<string, Array<QueuedRun & { ts: string }>>();
+
+ function steeringRunsFor(threadRef: string | null, agent: Agent): QueuedRun[] {
+ const steering = threadRef ? steeringRuns.get(threadRef) : undefined;
+ if (!threadRef || !steering) return [];
+ const settled = !agent.state.isStreaming && !ctx.chat.hasLiveRun();
+ const intakes = new Set(
+ agent.state.messages.flatMap((m) => {
+ const { steered, ts } = m as { steered?: boolean; ts?: string };
+ return steered && ts ? [ts] : [];
+ }),
+ );
+ const waiting = settled ? [] : steering.filter((run) => !intakes.has(run.ts));
+ if (waiting.length) steeringRuns.set(threadRef, waiting);
+ else steeringRuns.delete(threadRef);
+ return waiting;
+ }
+
const fileDrag = createFileDragState((dragging) => {
composerState.dragging = dragging;
ctx.chat.drawActiveChat();
@@ -774,7 +792,9 @@ export function createComposerSurface(ctx: ConvCtx, options: ComposerOptions = {
const queued = [...queuedRunsFor(ctx.chat.state.threadRef)];
if (queuedEdit?.threadRef === ctx.chat.state.threadRef && !queued.some((q) => q.runId === queuedEdit?.runId))
queued.push({ runId: queuedEdit.runId, text: queuedEdit.original });
- if (!queued.length) return nothing;
+ const threadRef = ctx.chat.state.threadRef;
+ const steering = steeringRunsFor(threadRef, agent);
+ if (!queued.length && !steering.length) return nothing;
const steerable =
agent.state.isStreaming &&
!ctx.chat.isStopping() &&
@@ -786,6 +806,16 @@ export function createComposerSurface(ctx: ConvCtx, options: ComposerOptions = {
};
return html`
<div class="queued-strip" role="list" aria-label="Queued messages">
+ ${steering.map(
+ (q) => html`
+ <div class="queued-chip queued-steering" role="listitem" aria-busy="true">
+ <span class="queued-tag">Steering</span>
+ <span class="queued-text" dir="auto" ${tip(q.text || "Files, no text")}
+ >${q.text || (q.hasAttachments ? "(files)" : "")}</span
+ >
+ </div>
+ `,
+ )}
${queued.map((q) =>
queuedEdit?.runId === q.runId && queuedEdit.threadRef === ctx.chat.state.threadRef
? html` <div class="queued-chip queued-editing" role="listitem">
@@ -1422,12 +1452,21 @@ export function createComposerSurface(ctx: ConvCtx, options: ComposerOptions = {
if (outcome.ok || outcome.replayed) {
forgetQueuedRun(threadRef, queued.runId);
bumpSessionActivity(threadRef);
- if (agent === ctx.chat.state.agent && threadRef === ctx.chat.state.threadRef) {
+ if (outcome.ok)
+ steeringRuns.set(threadRef, [
+ ...(steeringRuns.get(threadRef) ?? []).filter((run) => run.runId !== queued.runId),
+ { ...queued, ts: `queued-steer:${threadRef}:${queued.runId}` },
+ ]);
+ if (
+ !outcome.ok &&
+ outcome.replayed &&
+ 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") {
diff --git a/plugins/web-ui/src/core-bridge.ts b/plugins/web-ui/src/core-bridge.ts
index faf60decb..b53e8b100 100644
--- a/plugins/web-ui/src/core-bridge.ts
+++ b/plugins/web-ui/src/core-bridge.ts
@@ -396,7 +396,15 @@ export interface SessionEntry {
export interface ToolActivity {
seq: number;
parentSeq: number | null;
- type: "tool_call" | "tool_result" | "approval_request" | "approval_resolved" | "thinking" | "text" | "text_start";
+ type:
+ | "tool_call"
+ | "tool_result"
+ | "approval_request"
+ | "approval_resolved"
+ | "thinking"
+ | "text"
+ | "text_start"
+ | "user";
payload: unknown;
createdAt: number;
truncated?: boolean;
@@ -1289,6 +1297,8 @@ function parseActivity(raw: unknown): ToolActivity[] {
const a = item as Partial<ToolActivity> | null;
if (!a || typeof a.seq !== "number" || typeof a.type !== "string" || !ACTIVITY_TYPES.has(a.type)) continue;
if (a.type === "thinking" && !isRenderableThinking(a.payload)) continue;
+ if (a.type === "user" && !(a.payload as { steered?: boolean; hidden?: boolean } | null)?.steered) continue;
+ if (a.type === "user" && (a.payload as { hidden?: boolean } | null)?.hidden) continue;
out.push({
seq: a.seq,
parentSeq: a.parentSeq ?? null,
@@ -1632,6 +1642,7 @@ function sleep(ms: number): Promise<void> {
}
const ACTIVITY_TYPES = new Set<string>([
+ "user",
"tool_call",
"tool_result",
"approval_request",
@@ -1794,6 +1805,59 @@ function userEntryText(payload: unknown): string | null {
return display.trim() ? display : null;
}
+export function userEntryMessage(
+ entry: Pick<SessionEntry, "payload" | "seq" | "createdAt">,
+): HistoryUserMessage | null {
+ const payload = entry.payload as {
+ text?: string;
+ hidden?: boolean;
+ runId?: string;
+ steered?: boolean;
+ name?: string;
+ ts?: string;
+ attachments?: Array<{ name?: string; mimetype?: string; sizeBytes?: number; artifactId?: string }>;
+ } | null;
+ if (payload?.hidden) return null;
+ const text = userEntryText(payload) ?? "";
+ const attachments = payload?.attachments ?? [];
+ if (!text && !attachments.length) return null;
+ const mail = subagentMailOf(payload);
+ return {
+ role: "user",
+ ...(typeof payload?.runId === "string" ? { runId: payload.runId } : {}),
+ ...(entry.seq !== undefined ? { entrySeq: entry.seq } : {}),
+ content: text,
+ timestamp: entry.createdAt,
+ ...(mail ? { subagentMail: mail } : {}),
+ ...(payload?.steered ? { steered: true } : {}),
+ ...(typeof payload?.name === "string" && payload.name.trim() ? { speaker: payload.name.trim() } : {}),
+ ...(typeof payload?.ts === "string" && payload.ts ? { ts: payload.ts } : {}),
+ ...(attachments.length
+ ? {
+ attachments: attachments.map((a, i) => ({
+ id: a.artifactId ?? `${entry.seq ?? entry.createdAt}:${i}`,
+ type: a.mimetype?.startsWith("image/") ? ("image" as const) : ("document" as const),
+ fileName: a.name ?? "file",
+ mimeType: a.mimetype ?? "application/octet-stream",
+ ...(typeof a.sizeBytes === "number" ? { size: a.sizeBytes } : {}),
+ ...(a.artifactId ? { artifactId: a.artifactId } : {}),
+ })),
+ }
+ : {}),
+ };
+}
+
+export function appendConsumedSteers(messages: AgentMessage[], work: WorkBlock): void {
+ const recorded = new Set(messages.map((message) => (message as { entrySeq?: number }).entrySeq));
+ for (const activity of work.activity) {
+ if (activity.type !== "user" || recorded.has(activity.seq)) continue;
+ const message = userEntryMessage(activity);
+ if (!message?.steered) continue;
+ messages.push(message as AgentMessage);
+ recorded.add(activity.seq);
+ }
+}
+
export function entriesToMessages(entries: SessionEntry[], model?: Model<Api>): AgentMessage[] {
const out: AgentMessage[] = [];
const userByTs = new Map<string, HistoryUserMessage>();
@@ -1916,7 +1980,7 @@ export function entriesToMessages(entries: SessionEntry[], model?: Model<Api>):
}
continue;
}
- if (ACTIVITY_TYPES.has(e.type)) {
+ if (e.type !== "user" && ACTIVITY_TYPES.has(e.type)) {
const activity: ToolActivity = {
seq: e.seq ?? out.length,
parentSeq: e.parentSeq ?? null,
@@ -1966,31 +2030,17 @@ export function entriesToMessages(entries: SessionEntry[], model?: Model<Api>):
spillHeldPosts();
flushWork("", e.createdAt);
}
- const atts = payload?.attachments ?? [];
- const userText = userEntryText(e.payload) ?? text;
- if (text || atts.length) {
- const mail = subagentMailOf(e.payload);
- const msg: HistoryUserMessage = {
- role: "user",
- ...(typeof payload?.runId === "string" ? { runId: payload.runId } : {}),
- ...(e.seq !== undefined ? { entrySeq: e.seq } : {}),
- content: userText,
- timestamp: e.createdAt,
- ...(mail ? { subagentMail: mail } : {}),
- ...(payload?.steered ? { steered: true } : {}),
- ...(typeof payload?.name === "string" && payload.name.trim() ? { speaker: payload.name.trim() } : {}),
- ...(typeof payload?.ts === "string" && payload.ts ? { ts: payload.ts } : {}),
- };
+ const msg = userEntryMessage(e);
+ if (msg) {
if (msg.ts) userByTs.set(msg.ts, msg);
- if (atts.length) {
- msg.attachments = atts.map((a, i) => ({
- id: a.artifactId ?? `${e.seq ?? e.createdAt}:${i}`,
- type: a.mimetype?.startsWith("image/") ? "image" : "document",
- fileName: a.name ?? "file",
- mimeType: a.mimetype ?? "application/octet-stream",
- ...(typeof a.sizeBytes === "number" ? { size: a.sizeBytes } : {}),
- ...(a.artifactId ? { artifactId: a.artifactId } : {}),
- }));
+ if (msg.steered) {
+ pending.push({
+ seq: e.seq ?? out.length,
+ parentSeq: e.parentSeq ?? null,
+ type: "user",
+ payload: e.payload,
+ createdAt: e.createdAt,
+ });
}
out.push(msg as AgentMessage);
}
diff --git a/plugins/web-ui/src/shell.css b/plugins/web-ui/src/shell.css
index 36a730737..2c1e4b406 100644
--- a/plugins/web-ui/src/shell.css
+++ b/plugins/web-ui/src/shell.css
@@ -1723,12 +1723,6 @@ a.chat-row-open {
margin-top: 10px;
}
-.steer-label {
- font-size: 11px;
- color: var(--muted-foreground);
- margin: 2px 4px 3px 0;
- user-select: none;
-}
.steered-row .user-bubble {
border: 1px dashed var(--border);
}
@@ -12851,3 +12845,21 @@ body.app-edit-embed .custom-chat-shell.app-edit-chat > .chat-bottom-dock {
color: var(--muted-foreground);
font-size: 11px;
}
+
+.inline-steer {
+ margin-block: 16px;
+}
+
+.message-stack .inline-steer .user-row {
+ width: 100%;
+ position: relative;
+ top: auto;
+ z-index: auto;
+ margin: 0;
+ padding-top: 0;
+ pointer-events: auto;
+}
+
+.inline-steer .user-row .message-meta {
+ justify-content: flex-end;
+}
diff --git a/plugins/web-ui/src/timeline.ts b/plugins/web-ui/src/timeline.ts
index b9bf551c1..1c2ac8357 100644
--- a/plugins/web-ui/src/timeline.ts
+++ b/plugins/web-ui/src/timeline.ts
@@ -50,11 +50,21 @@ export interface ToolRowModel {
}
export type TimelineItem =
+ | { kind: "steer"; activity: ToolActivity }
| { kind: "thinking"; activity: ToolActivity }
| { kind: "text"; activity: ToolActivity }
| { kind: "tool"; row: ToolRowModel }
| { kind: "approval"; approval: PendingApproval };
+export function workTimelineSegments(items: TimelineItem[]): TimelineItem[][] {
+ const segments: TimelineItem[][] = [[]];
+ for (const item of items) {
+ if (item.kind === "steer") segments.push([item], []);
+ else segments.at(-1)!.push(item);
+ }
+ return segments;
+}
+
function isTerminalWorkStatus(status: WorkBlock["status"]): boolean {
return status === "complete" || status === "failed";
}
@@ -183,7 +193,14 @@ function buildTimelineUncached(work: WorkBlock): TimelineItem[] {
let open: ToolRowModel | null = null;
for (const a of work.activity) {
if (a.type === "text_start") continue;
- if (a.type === "thinking") {
+ if (a.type === "user") {
+ if (
+ (a.payload as { steered?: boolean; hidden?: boolean } | null)?.steered &&
+ !(a.payload as { hidden?: boolean } | null)?.hidden
+ )
+ items.push({ kind: "steer", activity: a });
+ open = null;
+ } else if (a.type === "thinking") {
items.push({ kind: "thinking", activity: a });
open = null;
} else if (a.type === "text") {
diff --git a/plugins/web-ui/src/transcript-viewport.ts b/plugins/web-ui/src/transcript-viewport.ts
index 3e530b6b2..a68f49b17 100644
--- a/plugins/web-ui/src/transcript-viewport.ts
+++ b/plugins/web-ui/src/transcript-viewport.ts
@@ -305,7 +305,7 @@ export function createTranscriptViewport() {
if (stack) observer?.observe(stack);
}
const nextPins = scroller?.querySelector<HTMLElement>(".pinned-strip") ?? null;
- const prompts = stack?.querySelectorAll<HTMLElement>(".user-row");
+ const prompts = stack?.querySelectorAll<HTMLElement>(":scope > .user-row");
const nextPrompt = prompts?.item(prompts.length - 1) ?? null;
if (pins !== nextPins) {
changed = true;
diff --git a/plugins/web-ui/test/activity-folding.test.ts b/plugins/web-ui/test/activity-folding.test.ts
index 9dbd0be0d..3db76f881 100644
--- a/plugins/web-ui/test/activity-folding.test.ts
+++ b/plugins/web-ui/test/activity-folding.test.ts
@@ -52,3 +52,97 @@ test("a subagent header includes its parent title in the breadcrumb", async () =
await h.close();
}
});
+
+test("steering separates tool folds with a visible unlabelled user message", async () => {
+ const tool = (seq: number) => [
+ {
+ seq,
+ type: "tool_call",
+ createdAt: seq * 1000,
+ payload: { tool: "execute", callId: String(seq), command: `echo step-${seq}` },
+ },
+ {
+ seq: seq + 1,
+ type: "tool_result",
+ createdAt: (seq + 1) * 1000,
+ payload: { tool: "execute", callId: String(seq), code: 0, stdout: String(seq) },
+ },
+ ];
+ const entries = [
+ { seq: 0, type: "user", createdAt: 0, payload: { text: "Original request" } },
+ ...tool(1),
+ ...tool(3),
+ { seq: 5, type: "user", createdAt: 5000, payload: { text: "Use the smaller sample", steered: true } },
+ ...tool(6),
+ ...tool(8),
+ { seq: 10, type: "assistant", createdAt: 10000, payload: { text: "Done" } },
+ ];
+ const h = await harness({ path: `/s/${SESSION.id}`, listSessions: [SESSION], entries });
+ try {
+ h.releaseSessions();
+ await h.boot();
+ await h.sessionsReady();
+ const steer = document.querySelector(".inline-steer")!;
+ assert.equal(document.querySelectorAll(".inline-steer").length, 1);
+ assert.equal(document.querySelectorAll(".message-stack > .steered-row").length, 0);
+ assert.equal(
+ steer.querySelector<HTMLElement & { content: string }>("qm-markdown")?.content,
+ "Use the smaller sample",
+ );
+ assert.equal(steer.closest("details"), null);
+ assert.equal(document.querySelector(".steer-label"), null);
+ assert.doesNotMatch(document.body.textContent!, /steered the running task/);
+ const folds = [...document.querySelectorAll(".work.work-fold")];
+ assert.equal(folds.length, 2);
+ assert.match(folds[0]!.textContent!, /step-1/);
+ assert.match(folds[1]!.textContent!, /step-6/);
+ assert.ok(folds[0]!.compareDocumentPosition(steer) & Node.DOCUMENT_POSITION_FOLLOWING);
+ assert.ok(steer.compareDocumentPosition(folds[1]!) & Node.DOCUMENT_POSITION_FOLLOWING);
+ const conv = h.visibleConversation();
+ const user = conv.state.agent!.state.messages.find(
+ (message) => (message as { entrySeq?: number }).entrySeq === 5,
+ ) as unknown as { speaker: string; edited: boolean; deleted: boolean };
+ (conv.state.agent!.state.messages[0] as unknown as { speaker: string }).speaker = "Requester";
+ user.speaker = "Another person";
+ user.edited = true;
+ conv.drawActiveChat();
+ assert.equal(document.querySelector(".inline-steer .speaker-label")?.textContent, "Another person");
+ assert.equal(document.querySelector(".inline-steer .revision-badge")?.textContent, "(edited)");
+ user.deleted = true;
+ conv.drawActiveChat();
+ assert.equal(document.querySelector(".inline-steer .revision-badge")?.textContent, "(deleted)");
+ (conv.state.agent!.state.messages.at(-1) as unknown as { approvalDecision: string }).approvalDecision = "denied";
+ conv.drawActiveChat();
+ assert.equal(document.querySelectorAll(".tool-expandable").length, 0);
+ assert.equal(document.querySelectorAll(".inline-steer").length, 1);
+ } finally {
+ await h.close();
+ }
+});
+
+test("stopping a steered run preserves earlier singleton tools and labels only its last segment stopped", async () => {
+ const entries = [
+ { seq: 0, type: "user", createdAt: 0, payload: { text: "Original request" } },
+ { seq: 1, type: "tool_call", createdAt: 1000, payload: { tool: "execute", callId: "a", command: "echo before" } },
+ { seq: 2, type: "tool_result", createdAt: 2000, payload: { tool: "execute", callId: "a", code: 0 } },
+ { seq: 3, type: "user", createdAt: 3000, payload: { text: "Change direction", steered: true } },
+ { seq: 4, type: "tool_call", createdAt: 4000, payload: { tool: "execute", callId: "b", command: "echo after" } },
+ { seq: 5, type: "tool_result", createdAt: 5000, payload: { tool: "execute", callId: "b", code: 0 } },
+ { seq: 6, type: "assistant", createdAt: 6000, payload: { text: "(stopped)", stopped: true } },
+ ];
+ const h = await harness({ path: `/s/${SESSION.id}`, listSessions: [SESSION], entries });
+ try {
+ h.releaseSessions();
+ await h.boot();
+ await h.sessionsReady();
+ const tools = [...document.querySelectorAll(".tool-expandable")];
+ assert.equal(tools.length, 2);
+ assert.equal(tools[0]!.closest(".work-fold, .stopped-work"), null);
+ assert.equal(document.querySelectorAll(".stopped-work").length, 1);
+ assert.ok(tools[1]!.closest(".stopped-work"));
+ assert.equal(document.querySelectorAll(".stopped-head").length, 1);
+ assert.equal(document.querySelector(".inline-steer")!.closest("details"), null);
+ } finally {
+ await h.close();
+ }
+});
diff --git a/plugins/web-ui/test/chat-settled-row-cache.test.ts b/plugins/web-ui/test/chat-settled-row-cache.test.ts
index de3386c7a..b3531a7aa 100644
--- a/plugins/web-ui/test/chat-settled-row-cache.test.ts
+++ b/plugins/web-ui/test/chat-settled-row-cache.test.ts
@@ -8,10 +8,10 @@ test("the transcript renders rows through the settled-row cache", () => {
assert.match(chat, /messages\.map\(\(m, i\) =>\s*settledChatMessage\(m, i - inheritedOffset,/);
});
-test("live, approval-paused, and subagent rows bypass the cache (their render reads mutable state)", () => {
+test("live, approval-paused, subagent, and steered work rows bypass the cache (their render reads mutable state)", () => {
assert.match(
chat,
- /const cacheable =\s*!isStreaming &&\s*!\(message as \{ subagentMail\?: SubagentMailRef \}\)\.subagentMail &&\s*!work\?\.activity\.some\(\(activity\) =>\s*\["session", "sessions"\]\.includes\(\(activity\.payload as ToolPayload \| null\)\?\.tool \?\? ""\),?\s*\) &&\s*\(!work \|\| \(\(work\.status === "complete" \|\| work\.status === "failed"\) && !work\.pendingApprovals\?\.length\)\)/,
+ /const cacheable =\s*!isStreaming &&\s*!\(message as \{ subagentMail\?: SubagentMailRef \}\)\.subagentMail &&\s*!work\?\.activity\.some\(\s*\(activity\) =>\s*activity.type === "user" \|\|\s*\["session", "sessions"\]\.includes\(\(activity\.payload as ToolPayload \| null\)\?\.tool \?\? ""\),?\s*\) &&\s*\(!work \|\| \(\(work\.status === "complete" \|\| work\.status === "failed"\) && !work\.pendingApprovals\?\.length\)\)/,
);
assert.match(chat, /if \(!cacheable\) return chatMessage\(message, index, isStreaming\);/);
});
@@ -40,3 +40,15 @@ test("the cache key covers every mutable render input of a settled row", () => {
test("prompt expansion is managed by the viewport without invalidating cached templates", () => {
assert.doesNotMatch(chat, /expandedPrompt|togglePromptExpanded/);
});
+
+test("canonical steering rows never enter the standalone cache during resume startup", () => {
+ const settled = chat.slice(chat.indexOf("function settledChatMessage"), chat.indexOf("function chatMessage"));
+ const suppression = settled.indexOf("if ((message as { steered?: boolean }).steered) return nothing;");
+ assert.ok(suppression >= 0);
+ assert.ok(suppression < settled.indexOf("settledRowCache.get"));
+});
+
+test("inline steering shows the user message without redundant steering chrome", () => {
+ assert.match(chat, /class="inline-steer"/);
+ assert.doesNotMatch(chat, /steer-label|steered the running task/);
+});
diff --git a/plugins/web-ui/test/core-bridge-idle.test.ts b/plugins/web-ui/test/core-bridge-idle.test.ts
index e1da34768..5a61791bc 100644
--- a/plugins/web-ui/test/core-bridge-idle.test.ts
+++ b/plugins/web-ui/test/core-bridge-idle.test.ts
@@ -1,3 +1,4 @@
+import { buildTimeline } from "../src/timeline.ts";
import { test, afterEach } from "node:test";
import assert from "node:assert/strict";
import { createAssistantMessageEventStream } from "@earendil-works/pi-ai";
@@ -415,3 +416,34 @@ test("a stored quarantine refusal renders the canned copy on the web, never the
assert.doesNotMatch(final.errorMessage ?? "", /internal screening details/);
assert.match(final.errorMessage ?? "", /security screen flagged/);
});
+
+test("live run polling includes only consumed visible steering in activity order", async () => {
+ instantSleep();
+ stubRuns([
+ {
+ status: "done",
+ result: { status: "ok", reply: "Done" },
+ activity: [
+ { seq: 1, type: "user", createdAt: 1, payload: { text: "start" } },
+ { seq: 2, type: "tool_call", createdAt: 2, payload: { tool: "execute", callId: "a" } },
+ { seq: 3, type: "tool_result", createdAt: 3, payload: { tool: "execute", callId: "a" } },
+ { seq: 4, type: "user", createdAt: 4, payload: { text: "Change direction", steered: true } },
+ { seq: 5, type: "user", createdAt: 5, payload: { text: "Hidden", steered: true, hidden: true } },
+ { seq: 6, type: "tool_call", createdAt: 6, payload: { tool: "execute", callId: "b" } },
+ ],
+ },
+ ]);
+ const stream = createAssistantMessageEventStream();
+ const partial = blankAssistant() as AssistantWork;
+ partial.work = { status: "thinking", activity: [] };
+ await pollRun(stream, partial, "run-steer", freshAcc(Date.now()));
+ const final = (await drain(stream)) as AssistantWork;
+ assert.deepEqual(
+ final.work!.activity.map((entry) => entry.seq),
+ [2, 3, 4, 6],
+ );
+ assert.deepEqual(
+ buildTimeline(final.work!).map((item) => item.kind),
+ ["tool", "steer", "tool"],
+ );
+});
diff --git a/plugins/web-ui/test/history.test.ts b/plugins/web-ui/test/history.test.ts
index bd557689f..ebfe78503 100644
--- a/plugins/web-ui/test/history.test.ts
+++ b/plugins/web-ui/test/history.test.ts
@@ -5,6 +5,8 @@ import { JSDOM } from "jsdom";
import type { AgentMessage } from "@earendil-works/pi-agent-core";
import {
attachPendingApprovals,
+ appendConsumedSteers,
+ forkCutSeq,
continuableMessages,
messagesWithStreaming,
currentEarlierCount,
@@ -58,7 +60,7 @@ test("steering keeps the active turn together through hydration and tool complet
assert.equal(resumed.popped.length, 1);
assert.deepEqual(
(resumed.popped[0] as AssistantWork).work?.activity.map((entry) => entry.seq),
- [2, 3],
+ [2, 3, 4, 5],
);
const finished = entriesToMessages([
...entries,
@@ -72,7 +74,11 @@ test("steering keeps the active turn together through hydration and tool complet
const work = (finished.at(-1) as AssistantWork).work!;
assert.deepEqual(
work.activity.map((entry) => entry.seq),
- [2, 3, 6],
+ [2, 3, 4, 5, 6],
+ );
+ assert.deepEqual(
+ buildTimeline(work).map((item) => item.kind),
+ ["text", "tool", "steer", "steer"],
);
const tools = buildTimeline(work).filter((item) => item.kind === "tool");
assert.equal(tools.length, 1);
@@ -103,7 +109,7 @@ test("steering preserves an in-flight post and does not promote its closing narr
);
assert.deepEqual(
replies[1]!.work?.activity.map((entry) => entry.seq),
- [6],
+ [5, 6],
);
});
@@ -1614,3 +1620,72 @@ test("finish_silently retains explicit posts and audit without a phantom closing
replies.some((m) => m.work?.activity.some((a) => (a.payload as { tool?: string }).tool === "finish_silently")),
);
});
+
+test("steering retains intake identity, authors and attachments after history reload", () => {
+ const messages = entriesToMessages([
+ { type: "user", seq: 1, createdAt: 1, payload: { text: "start" } },
+ { type: "tool_call", seq: 2, createdAt: 2, payload: { tool: "read", callId: "a" } },
+ { type: "tool_result", seq: 3, createdAt: 3, payload: { tool: "read", callId: "a" } },
+ {
+ type: "user",
+ seq: 4,
+ createdAt: 4,
+ payload: {
+ text: "Use this instead",
+ steered: true,
+ name: "Alex",
+ ts: "input-1",
+ attachments: [{ name: "sample.png", mimetype: "image/png", artifactId: "image-1" }],
+ },
+ },
+ { type: "tool_call", seq: 5, createdAt: 5, payload: { tool: "read", callId: "b" } },
+ { type: "tool_result", seq: 6, createdAt: 6, payload: { tool: "read", callId: "b" } },
+ { type: "assistant", seq: 7, createdAt: 7, payload: { text: "Done" } },
+ ]);
+ const work = (messages.at(-1) as AssistantWork).work!;
+ const timeline = messageWorkTimeline(work, "Done");
+ assert.deepEqual(
+ timeline.map((item) => item.kind),
+ ["tool", "steer", "tool"],
+ );
+ assert.equal(timeline[1]?.kind === "steer" && timeline[1].activity.seq, 4);
+ const steer = messages[1] as unknown as {
+ entrySeq: number;
+ speaker: string;
+ attachments: Array<{ artifactId: string }>;
+ };
+ assert.equal(steer.entrySeq, 4);
+ assert.equal(steer.speaker, "Alex");
+ assert.equal(steer.attachments[0]?.artifactId, "image-1");
+});
+
+test("hidden steering never creates a history row or work marker", () => {
+ const messages = entriesToMessages([
+ { type: "user", seq: 1, createdAt: 1, payload: { text: "start" } },
+ { type: "user", seq: 2, createdAt: 2, payload: { text: "private instruction", steered: true, hidden: true } },
+ { type: "assistant", seq: 3, createdAt: 3, payload: { text: "Done" } },
+ ]);
+ assert.equal(messages.length, 2);
+ assert.equal((messages[1] as AssistantWork).work, undefined);
+});
+
+test("live consumed steers join canonical history once and survive stopped/error fork accounting", () => {
+ const entries: SessionEntry[] = [
+ { type: "user", seq: 1, createdAt: 1, payload: { text: "start" } },
+ { type: "tool_call", seq: 2, createdAt: 2, payload: { tool: "execute", callId: "a" } },
+ { type: "user", seq: 3, createdAt: 3, payload: { text: "Change direction", steered: true } },
+ { type: "tool_result", seq: 4, createdAt: 4, payload: { tool: "execute", callId: "a" } },
+ { type: "assistant", seq: 5, createdAt: 5, payload: { text: "(stopped)", stopped: true } },
+ ];
+ const work = (entriesToMessages(entries).at(-1) as AssistantWork).work!;
+ for (const reason of ["aborted", "error"] as const) {
+ const live = entriesToMessages(entries.slice(0, 1));
+ appendConsumedSteers(live, work);
+ appendConsumedSteers(live, work);
+ assert.equal(live.length, 2);
+ assert.equal((live[1] as { entrySeq?: number }).entrySeq, 3);
+ live.push({ ...entriesToMessages(entries).at(-1)!, stopReason: reason } as AgentMessage);
+ assert.equal(forkCutSeq(entries, live.filter((message) => message.role === "user").length, false), undefined);
+ assert.equal(forkCutSeq(entries, 2, true), 3);
+ }
+});
diff --git a/plugins/web-ui/test/pending-steer-chip.test.ts b/plugins/web-ui/test/pending-steer-chip.test.ts
new file mode 100644
index 000000000..67495abb8
--- /dev/null
+++ b/plugins/web-ui/test/pending-steer-chip.test.ts
@@ -0,0 +1,164 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import type { Agent } from "@earendil-works/pi-agent-core";
+import { JSDOM } from "jsdom";
+import { createServer } from "vite";
+import type { ComposerSurface, ConvCtx } from "../src/conv-types.ts";
+
+test("a steered queued message stays visible as Steering until model intake or the run ends", async (t) => {
+ const dom = new JSDOM('<!doctype html><div id="app"></div><div id="composer"></div>', {
+ url: "http://localhost/",
+ pretendToBeVisual: true,
+ });
+ Object.defineProperty(dom.window, "matchMedia", {
+ value: () => ({ matches: false, addEventListener() {}, removeEventListener() {} }),
+ });
+ const globals = {
+ window: dom.window,
+ document: dom.window.document,
+ location: dom.window.location,
+ history: dom.window.history,
+ localStorage: dom.window.localStorage,
+ navigator: dom.window.navigator,
+ HTMLElement: dom.window.HTMLElement,
+ HTMLInputElement: dom.window.HTMLInputElement,
+ HTMLTextAreaElement: dom.window.HTMLTextAreaElement,
+ Element: dom.window.Element,
+ Node: dom.window.Node,
+ Event: dom.window.Event,
+ customElements: dom.window.customElements,
+ getComputedStyle: dom.window.getComputedStyle.bind(dom.window),
+ requestAnimationFrame: dom.window.requestAnimationFrame.bind(dom.window),
+ cancelAnimationFrame: dom.window.cancelAnimationFrame.bind(dom.window),
+ fetch: async () => Response.json({ sessions: [] }),
+ };
+ const descriptors = new Map<string, PropertyDescriptor | undefined>();
+ for (const [key, value] of Object.entries(globals)) {
+ descriptors.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
+ Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
+ }
+ const vite = await createServer({ server: { middlewareMode: true, hmr: false }, appType: "custom" });
+ let composer: ComposerSurface | undefined;
+ try {
+ const { appState } = await vite.ssrLoadModule("/src/shell-state.ts");
+ const { createComposerSurface } = await vite.ssrLoadModule("/src/composer.ts");
+ const { seedRuntimeConfig } = await vite.ssrLoadModule("/src/runtime-config-store.ts");
+ const { render } = await vite.ssrLoadModule("lit");
+ appState.me = { user: "tester", org: "test" };
+ const model = {
+ id: "alpha",
+ name: "Alpha",
+ label: "Alpha",
+ buttonLabel: "Alpha",
+ provider: "openai",
+ api: "openai-responses",
+ reasoning: true,
+ input: ["text"],
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
+ contextWindow: 100_000,
+ maxTokens: 4096,
+ };
+ seedRuntimeConfig("personal:tester", {
+ scopeId: "personal:tester",
+ approvedHarnesses: ["pi"],
+ modelsByHarness: { pi: ["alpha"] },
+ modelCatalog: { alpha: model },
+ orgDefault: { harnessId: "pi", modelId: "alpha", revision: 1 },
+ effective: { harnessId: "pi", modelId: "alpha" },
+ scopeOverride: null,
+ upgradeAvailable: false,
+ });
+ const threadRef = "web:tester:steering";
+ const host = document.querySelector<HTMLElement>("#composer")!;
+ const agentState = { isStreaming: true, model, messages: [] as unknown[] };
+ const agent = { state: agentState } as unknown as Agent;
+ let live = true;
+ const signalled: string[] = [];
+ const draw = (): void => render(composer!.queuedStrip(agent), host);
+ const ctx = {
+ pane: false,
+ chat: {
+ state: { agent, host, threadRef, sessionId: "s", scopeId: "personal:tester" },
+ isStopping: () => false,
+ hasLiveRun: () => live,
+ signalLiveRun: async (_kind: string, _text: string, queuedRunId: string) => {
+ signalled.push(queuedRunId);
+ return { ok: true };
+ },
+ drawActiveChat: draw,
+ resumeIfIdle() {},
+ },
+ } as unknown as ConvCtx;
+ composer = createComposerSurface(ctx);
+ ctx.composer = composer!;
+ const chips = () =>
+ [...host.querySelectorAll(".queued-chip")].map((chip) => ({
+ tag: chip.querySelector(".queued-tag")?.textContent?.trim(),
+ text: chip.querySelector(".queued-text")?.textContent?.trim(),
+ }));
+ const steer = async (runId: string): Promise<void> => {
+ composer!.setQueuedRuns(threadRef, [{ runId, text: "same text" }]);
+ draw();
+ host.querySelector<HTMLButtonElement>(".queued-steer")!.click();
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ assert.ok(signalled.includes(runId));
+ draw();
+ };
+ const intake = (runId: string, entrySeq: number): void => {
+ agentState.messages.push({
+ role: "user",
+ content: "same text",
+ steered: true,
+ entrySeq,
+ ts: `queued-steer:${threadRef}:${runId}`,
+ });
+ };
+
+ await t.test("accepting a steer keeps the chip and fabricates no transcript message", async () => {
+ await steer("q1");
+ assert.deepEqual(composer!.queuedRunsFor(threadRef), []);
+ assert.deepEqual(chips(), [{ tag: "Steering", text: "same text" }]);
+ assert.equal(agentState.messages.length, 0);
+ });
+
+ await t.test("repeated text settles only the steer whose intake ts arrived", async () => {
+ await steer("q2");
+ assert.deepEqual(chips(), [
+ { tag: "Steering", text: "same text" },
+ { tag: "Steering", text: "same text" },
+ ]);
+ intake("q2", 4);
+ draw();
+ assert.deepEqual(chips(), [{ tag: "Steering", text: "same text" }]);
+ intake("q1", 5);
+ draw();
+ assert.deepEqual(chips(), []);
+ });
+
+ await t.test("an unrelated steered message with the same text does not settle the chip", async () => {
+ await steer("q3");
+ agentState.messages.push({ role: "user", content: "same text", steered: true, entrySeq: 6, ts: "other" });
+ draw();
+ assert.deepEqual(chips(), [{ tag: "Steering", text: "same text" }]);
+ });
+
+ await t.test("the chip goes when the run ends without intake", async () => {
+ agentState.isStreaming = false;
+ live = false;
+ draw();
+ assert.deepEqual(chips(), []);
+ agentState.isStreaming = true;
+ live = true;
+ draw();
+ assert.deepEqual(chips(), []);
+ });
+ } finally {
+ composer?.dispose?.();
+ await vite.close();
+ dom.window.close();
+ for (const [key, descriptor] of descriptors) {
+ if (descriptor) Object.defineProperty(globalThis, key, descriptor);
+ else delete (globalThis as Record<string, unknown>)[key];
+ }
+ }
+});
diff --git a/plugins/web-ui/test/timeline.test.ts b/plugins/web-ui/test/timeline.test.ts
index 571d85917..9f52fa846 100644
--- a/plugins/web-ui/test/timeline.test.ts
+++ b/plugins/web-ui/test/timeline.test.ts
@@ -7,6 +7,7 @@ import {
streamedAnswer,
streamingTextTail,
buildTimeline,
+ workTimelineSegments,
toolCategory,
toolRowKind,
toolExecutionOutput,
@@ -458,3 +459,38 @@ test("stopped stream projection uses the final boundary even when final text rep
};
assert.equal(streamedAnswer("Same words\n\nSame words again", work), "Same words again");
});
+
+test("steering splits visible work without breaking a tool that completes across intake", () => {
+ const work: WorkBlock = {
+ status: "working",
+ activity: [
+ act(1, "tool_call", { tool: "execute", callId: "a", command: "first" }),
+ act(2, "user", { steered: true, text: "Change direction" }),
+ act(3, "tool_result", { tool: "execute", callId: "a", code: 0 }),
+ act(4, "tool_call", { tool: "execute", callId: "b", command: "second" }),
+ act(5, "user", { steered: true, text: "Keep it brief" }),
+ ],
+ };
+ const segments = workTimelineSegments(buildTimeline(work));
+ assert.deepEqual(
+ segments.map((items) => items.map((item) => item.kind)),
+ [["tool"], ["steer"], ["tool"], ["steer"], []],
+ );
+ const first = segments[0]![0]!;
+ assert.ok(first.kind === "tool");
+ assert.equal(first.row.call?.seq, 1);
+ assert.equal(first.row.result?.seq, 3);
+ assert.equal(toolRowKind(first.row, work.status), "ok");
+ assert.deepEqual(
+ work.activity.map((entry) => entry.seq),
+ [1, 2, 3, 4, 5],
+ );
+});
+
+test("ordinary and hidden user events do not become steering markers", () => {
+ const work: WorkBlock = {
+ status: "complete",
+ activity: [act(1, "user", { text: "ordinary" }), act(2, "user", { text: "hidden", steered: true, hidden: true })],
+ };
+ assert.deepEqual(buildTimeline(work), []);
+});
diff --git a/plugins/web-ui/test/transcript-viewport.test.ts b/plugins/web-ui/test/transcript-viewport.test.ts
index b1bf9e17c..096988155 100644
--- a/plugins/web-ui/test/transcript-viewport.test.ts
+++ b/plugins/web-ui/test/transcript-viewport.test.ts
@@ -933,3 +933,18 @@ test("the latest-prompt marker moves between rows and is restored after a templa
f.close();
}
});
+
+test("an inline steer does not take the sticky prompt marker from the original request", () => {
+ const f = fixture();
+ try {
+ const work = f.s.ownerDocument.createElement("article");
+ work.className = "assistant-row";
+ work.innerHTML = '<div class="inline-steer"><article class="user-row steered-row" data-index="1"></article></div>';
+ f.prompt.after(work);
+ f.viewport.sync(f.s);
+ assert.equal(f.prompt.classList.contains("latest-prompt"), true);
+ assert.equal(work.querySelector(".steered-row")!.classList.contains("latest-prompt"), false);
+ } finally {
+ f.close();
+ }
+});
diff --git a/plugins/web-ui/test/work-fold-source.test.ts b/plugins/web-ui/test/work-fold-source.test.ts
index 9b8893897..f7dc93abf 100644
--- a/plugins/web-ui/test/work-fold-source.test.ts
+++ b/plugins/web-ui/test/work-fold-source.test.ts
@@ -5,13 +5,13 @@ import test from "node:test";
const chat = readFileSync(new URL("../src/chat.ts", import.meta.url), "utf8");
const css = readFileSync(new URL("../src/shell.css", import.meta.url), "utf8");
-test("live and completed work share one chronological duration fold", () => {
- assert.match(chat, /class=\$\{stopped \? "stopped-work" : `work work-fold work-\$\{work.status\}`\}/);
+test("live and completed work keep chronological folds split around steering", () => {
+ assert.match(chat, /class=\$\{stopped && last \? "stopped-work" : `work work-fold work-\$\{work.status\}`\}/);
assert.match(chat, /messageWorkTimeline\(work, active \? "" : text\)/);
- assert.match(chat, /let label = stopping \? "Stop requested" : workLabel\(work\)/);
- assert.match(chat, /const animating = active && !stopping;/);
+ assert.match(chat, /let label = last \? workLabel\(work\) : "Worked"/);
+ assert.match(chat, /const animating = active && last && !stopping;/);
assert.match(chat, /sheenLabel\(label, animating\)/);
- assert.match(chat, /\?open=\$\{active \|\| !!work.pendingApprovals\?\.length\}/);
+ assert.match(chat, /\?open=\$\{last && \(active \|\| !!work.pendingApprovals\?\.length\)\}/);
assert.doesNotMatch(chat, /function segmentSummaryLabel/);
});
@@ -92,7 +92,7 @@ test("stopped work shares posted reply rendering and shows one status without ac
const block = chat.slice(chat.indexOf(" function workBlock("), chat.indexOf(" function approvalSummaryView("));
assert.match(block, /postSpeechText\(item.row\)/);
assert.match(block, /replies.map\(\(reply\) => html`<div class="streaming-text"/);
- assert.match(block, /if \(stopped && fold === nothing\) fold = html`<div class="stopped-head">/);
+ assert.match(block, /if \(stopped && last && fold === nothing\) fold = html`<div class="stopped-head">/);
assert.doesNotMatch(chat, /stopped-note|function stoppedWork/);
});
diff --git a/src/core/orchestrator.ts b/src/core/orchestrator.ts
index 380e5472d..c9cf2e231 100644
--- a/src/core/orchestrator.ts
+++ b/src/core/orchestrator.ts
@@ -642,7 +642,12 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
return result;
};
const mirrorRunActivity = async (appended: SessionEntry): Promise<void> => {
- if (input.runId && deps.runActivity && ACTIVITY_ENTRY_TYPES.has(appended.type)) {
+ if (
+ input.runId &&
+ deps.runActivity &&
+ (ACTIVITY_ENTRY_TYPES.has(appended.type) ||
+ (appended.type === "user" && (appended.payload as { steered?: boolean })?.steered === true))
+ ) {
await deps.runActivity
.append(input.runId, {
seq: appended.seq,
@@ -3395,7 +3400,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
payload.name = actor.displayName.trim();
if (input.displayText?.trim() && payload.text === input.text && typeof payload.display !== "string")
payload.display = input.displayText;
- if (syntheticPrompt || continuation) payload.hidden = true;
+ if ((syntheticPrompt || continuation) && payload.steered !== true) payload.hidden = true;
return { ...tainted, payload };
})();
const appended = await withManagedRosterVersion(() => deps.sessions.append(lease, stored));
@@ -3700,11 +3705,21 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
if (rec.kind !== "message" || rec.meta?.bareText === undefined) {
return withManagedRosterVersion(() => deps.sessions.appendTape(lease, rec));
}
+ const recordedSteer = emittedEntries.find(
+ (entry) =>
+ entry.seq === rec.entrySeq &&
+ entry.type === "user" &&
+ isObj(entry.payload) &&
+ entry.payload.steered === true,
+ )?.payload;
const meta = {
...rec.meta,
...swarmEntryProvenance,
...(actor.displayName?.trim() ? { author: actor.displayName.trim() } : {}),
- ...(syntheticPrompt || continuation ? { hidden: true } : {}),
+ ...((isObj(recordedSteer) && recordedSteer.hidden === true) ||
+ ((syntheticPrompt || continuation) && !recordedSteer)
+ ? { hidden: true }
+ : {}),
...(input.displayText?.trim() && rec.meta.bareText === input.text
? { display: input.displayText }
: {}),
diff --git a/src/harness/claude-harness.ts b/src/harness/claude-harness.ts
index f698f0922..e2f184bf6 100644
--- a/src/harness/claude-harness.ts
+++ b/src/harness/claude-harness.ts
@@ -1,5 +1,5 @@
import { documentBlocks } from "./document-inputs.ts";
-import { randomBytes } from "node:crypto";
+import { randomBytes, randomUUID } from "node:crypto";
import { spawn } from "node:child_process";
import { chownSync, mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
@@ -46,10 +46,18 @@ import {
oneShotModelUtilities,
oneShotRunner,
tapeReplyCheckpoint,
+ recordSteerIntake,
+ type SteerIntake,
transitionTask,
type HarnessToolPlumbing,
} from "./harness-shared.ts";
-import { reconstructMessagesFromHistory, seedPriorTurns, zeroUsage, type PiReplayMessage } from "./replay.ts";
+import {
+ recordedMessageTimestamps,
+ reconstructMessagesFromHistory,
+ seedPriorTurns,
+ zeroUsage,
+ type PiReplayMessage,
+} from "./replay.ts";
export interface ClaudeHarnessOptions extends HarnessToolPlumbing {
modelId?: string | ((scope?: ScopeId) => string | undefined);
@@ -238,6 +246,7 @@ function promptText(turn: HarnessTurnInput): string {
function userMessage(text: string, images: HarnessTurnInput["images"] = []): SDKUserMessage {
return {
type: "user",
+ uuid: randomUUID(),
message: {
role: "user",
content: [
@@ -398,16 +407,22 @@ export function createClaudeHarness(opts: ClaudeHarnessOptions = {}): Harness {
let recordedSteps = 0;
let lastTotalCostUsd = 0;
let settled = false;
- const steerPrompts: SDKUserMessage[] = [];
+ const steerPrompts: Array<{ message: SDKUserMessage; intake: SteerIntake }> = [];
let streamedText = "";
let initialUserEchoSkipped = false;
- const appendTape = async (payload: unknown, trigger = false) => {
+ const seenUserMessages = new Set<string>();
+ const appendTape = async (
+ payload: unknown,
+ trigger = false,
+ stamp?: Awaited<ReturnType<typeof recordSteerIntake>>,
+ ) => {
if (!turn.tape) return;
await turn.tape({
kind: "message",
harness: "claude",
payload,
scopeLabel: turn.scopeLabel,
+ ...stamp,
...(trigger
? {
entrySeq: userEntry.seq,
@@ -468,6 +483,7 @@ export function createClaudeHarness(opts: ClaudeHarnessOptions = {}): Harness {
allowDangerouslySkipPermissions: true,
persistSession: false,
includePartialMessages: true,
+ extraArgs: { "replay-user-messages": null },
...(processIdentity
? { spawnClaudeCodeProcess: (options: SpawnOptions) => spawnClaudeProcess(options, processIdentity) }
: {}),
@@ -506,22 +522,13 @@ export function createClaudeHarness(opts: ClaudeHarnessOptions = {}): Harness {
turn.runId,
{
onAbort: async () => interrupt(true),
- onSteer: async (steer, ts, request) => {
+ onSteer: async (steer, ts, request, acknowledge) => {
+ if (ts && recordedMessageTimestamps(turn.history).has(ts)) return;
const prepared = await turn.prepareSteer?.(steer, request);
+ if (settled || interrupted) return false;
const prompt = prepared?.text ?? steer;
- await turn.emit({
- type: "user",
- payload: {
- text: steer,
- ...(ts ? { ts } : {}),
- steered: true,
- ...(prepared?.attachments?.length ? { attachments: prepared.attachments } : {}),
- },
- scopeLabel: turn.scopeLabel,
- });
const baseMessage = userMessage(prompt, prepared?.images);
- steerPrompts.push(baseMessage);
- const message = userMessage(prompt, prepared?.images);
+ const message = { ...userMessage(prompt, prepared?.images), uuid: baseMessage.uuid };
if (Array.isArray(message.message.content))
message.message.content.push(
...((await documentBlocks(
@@ -531,8 +538,14 @@ export function createClaudeHarness(opts: ClaudeHarnessOptions = {}): Harness {
turn.cancel,
)) as unknown as typeof message.message.content),
);
+ if (settled || interrupted) return false;
+ steerPrompts.push({
+ message: baseMessage,
+ intake: { text: steer, ts, attachments: prepared?.attachments, acknowledge },
+ });
pendingPrompts++;
queue.push(message);
+ return false;
},
},
{ onError: (error) => swallow("claude signal poll", error) },
@@ -627,22 +640,37 @@ export function createClaudeHarness(opts: ClaudeHarnessOptions = {}): Harness {
entryCount: turn.history.length,
});
}
- if (message.type === "user" && !initialUserEchoSkipped) initialUserEchoSkipped = true;
- else if (message.type === "assistant" || message.type === "user") {
+ if (message.type === "assistant" || message.type === "user") {
let tapeMessage: SDKMessage = message;
- if (message.type === "user" && Array.isArray(message.message.content)) {
- const text = message.message.content.find((block) => block.type === "text")?.text;
+ let stamp: Awaited<ReturnType<typeof recordSteerIntake>> | undefined;
+ if (message.type === "user" && !message.parent_tool_use_id) {
+ if (message.uuid && seenUserMessages.has(message.uuid)) continue;
+ if (message.uuid) seenUserMessages.add(message.uuid);
+ const content = message.message.content;
+ const echoedText =
+ typeof content === "string" ? content : content.find((block) => block.type === "text")?.text;
+ if (
+ !initialUserEchoSkipped &&
+ (message.uuid === initial.uuid || (!message.uuid && echoedText === promptText(turn)))
+ ) {
+ initialUserEchoSkipped = true;
+ continue;
+ }
const index = steerPrompts.findIndex(
- (prompt) =>
- Array.isArray(prompt.message.content) &&
- prompt.message.content.some((block) => block.type === "text" && block.text === text),
+ ({ message: prompt }) =>
+ prompt.uuid === message.uuid ||
+ (!message.uuid &&
+ Array.isArray(prompt.message.content) &&
+ prompt.message.content.some((block) => block.type === "text" && block.text === echoedText)),
);
if (index >= 0) {
- const [base] = steerPrompts.splice(index, 1);
- tapeMessage = { ...message, message: { ...message.message, content: base!.message.content } };
+ const [steer] = steerPrompts.splice(index, 1);
+ await flushThinking();
+ stamp = await recordSteerIntake(turn, steer!.intake);
+ tapeMessage = { ...message, message: { ...message.message, content: steer!.message.message.content } };
}
}
- await appendTape(stripClaudeImageBytes(tapeMessage));
+ await appendTape(stripClaudeImageBytes(tapeMessage), false, stamp);
}
if (message.type === "system" && message.subtype === "task_started") {
const callId = message.tool_use_id ?? message.task_id;
diff --git a/src/harness/codex-harness.ts b/src/harness/codex-harness.ts
index fb167a425..fcc3c7ca2 100644
--- a/src/harness/codex-harness.ts
+++ b/src/harness/codex-harness.ts
@@ -31,11 +31,18 @@ import {
oneShotModelUtilities,
oneShotRunner,
tapeReplyCheckpoint,
+ recordSteerIntake,
+ type SteerIntake,
transitionTask,
type BridgedTool,
type HarnessToolPlumbing,
} from "./harness-shared.ts";
-import { reconstructMessagesFromHistory, seedPriorTurns, type PiReplayMessage } from "./replay.ts";
+import {
+ recordedMessageTimestamps,
+ reconstructMessagesFromHistory,
+ seedPriorTurns,
+ type PiReplayMessage,
+} from "./replay.ts";
export interface CodexHarnessOptions extends HarnessToolPlumbing {
modelId?: string | ((scope?: ScopeId) => string | undefined);
@@ -140,6 +147,8 @@ type ActiveTurn = {
firstOutputAt: number | null;
fallbackInputTokens: number;
tapeError?: Error;
+ seenUserItems: Set<string>;
+ pendingSteers: Array<{ prompt: string; inputText: string; intake: SteerIntake }>;
interrupt?: () => Promise<void>;
stopped: boolean;
};
@@ -535,6 +544,27 @@ export function createCodexHarness(opts: CodexHarnessOptions = {}): Harness {
}
}
if (method === "item/completed") {
+ let stamp: Awaited<ReturnType<typeof recordSteerIntake>> | undefined;
+ let tapeItem = item;
+ if (
+ threadId === state.threadId &&
+ item.type === "userMessage" &&
+ Array.isArray(item.content) &&
+ typeof item.id === "string"
+ ) {
+ if (state.seenUserItems.has(item.id)) return;
+ state.seenUserItems.add(item.id);
+ const text = item.content
+ .filter((part) => part.type === "text")
+ .map((part) => part.text)
+ .join("\n");
+ const index = state.pendingSteers.findIndex((steer) => steer.inputText === text);
+ if (index >= 0) {
+ const [steer] = state.pendingSteers.splice(index, 1);
+ stamp = await recordSteerIntake(state.turn, steer!.intake);
+ tapeItem = { type: "message", role: "user", content: [{ type: "input_text", text: steer!.prompt }] };
+ }
+ }
state.completedItems.push(item);
if (state.turn.tape && !state.tapeError) {
try {
@@ -542,7 +572,8 @@ export function createCodexHarness(opts: CodexHarnessOptions = {}): Harness {
kind: "message",
harness: "codex",
scopeLabel: state.turn.scopeLabel,
- payload: item,
+ payload: tapeItem,
+ ...stamp,
});
} catch (error) {
state.tapeError = asError(error);
@@ -1045,6 +1076,8 @@ export function createCodexHarness(opts: CodexHarnessOptions = {}): Harness {
reject: rejectCompleted,
responseItems: [],
completedItems: [],
+ pendingSteers: [],
+ seenUserItems: new Set(),
publicMessages: new Map(),
taskIds: new Map(),
taskStatuses: new Map(),
@@ -1178,49 +1211,40 @@ export function createCodexHarness(opts: CodexHarnessOptions = {}): Harness {
stoppedByUser = true;
await interrupt(true);
},
- onSteer: async (text, ts, request) => {
+ onSteer: async (text, ts, request, acknowledge) => {
+ if (ts && recordedMessageTimestamps(turn.history).has(ts)) return;
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,
- ...(prepared?.attachments?.length ? { attachments: prepared.attachments } : {}),
- },
- scopeLabel: turn.scopeLabel,
- });
- if (turn.tape) {
- await turn.tape({
- kind: "message",
- harness: "codex",
- scopeLabel: turn.scopeLabel,
- entrySeq: steered.seq,
- meta: {
- bareText: text,
- ...(ts ? { ts } : {}),
- entryCreatedAt: steered.createdAt,
- },
- payload: { type: "message", role: "user", content: [{ type: "input_text", text: prompt }] },
- });
- }
const documentText = await documentsFallbackText(
prepared?.documents ?? [],
turn.cancel,
documentTextBudget,
);
- await rt.server.request("turn/steer", {
- threadId,
- expectedTurnId: turnId,
- input: [
- userInput([prompt, documentText].filter(Boolean).join("\n\n")),
- ...(prepared?.images ?? []).map((image) => ({
- type: "image",
- url: `data:${image.mimeType};base64,${image.dataBase64}`,
- })),
- ],
- });
+ const inputText = [prompt, documentText].filter(Boolean).join("\n\n");
+ const steer = {
+ prompt,
+ inputText,
+ intake: { text, ts, attachments: prepared?.attachments, acknowledge },
+ };
+ state.pendingSteers.push(steer);
+ try {
+ await rt.server.request("turn/steer", {
+ threadId,
+ expectedTurnId: turnId,
+ input: [
+ userInput(inputText),
+ ...(prepared?.images ?? []).map((image) => ({
+ type: "image",
+ url: `data:${image.mimeType};base64,${image.dataBase64}`,
+ })),
+ ],
+ });
+ } catch (error) {
+ const index = state.pendingSteers.indexOf(steer);
+ if (index >= 0) state.pendingSteers.splice(index, 1);
+ throw error;
+ }
+ return false;
},
},
{ onError: (error) => swallow("codex signal poll", error) },
diff --git a/src/harness/harness-shared.ts b/src/harness/harness-shared.ts
index 2aeea2a9f..4ae31b200 100644
--- a/src/harness/harness-shared.ts
+++ b/src/harness/harness-shared.ts
@@ -11,8 +11,8 @@ import { createAgentTools, type AgentToolsOptions, type ToolContextRef } from ".
import { rehydrateOpenGoal } from "./goal.ts";
import type { HarnessLlmRequestRecord, HarnessModelUtilities, HarnessTurnInput, HarnessTurnResult } from "./harness.ts";
import { sanitizeTitle, TITLE_GENERATION_PROMPT, titleUserPrompt } from "./pi-harness.ts";
-import { tapeCheckpointPayload, tapeEntryMirrorRecord } from "../sessions/session-store.ts";
-import { swallow } from "../util/errors.ts";
+import { tapeCheckpointPayload, tapeEntryMirrorRecord, type NewTapeRecord } from "../sessions/session-store.ts";
+import { swallow, swallowAs } from "../util/errors.ts";
export interface HarnessToolPlumbing {
scratchExec?: boolean;
@@ -37,6 +37,39 @@ export type BridgedTool = {
): Promise<{ content?: Array<{ type?: string; text?: string }>; terminate?: boolean }>;
};
+export interface SteerIntake {
+ text: string;
+ ts?: string;
+ attachments?: HarnessTurnInput["attachments"];
+ acknowledge?: () => Promise<void>;
+}
+
+export async function recordSteerIntake(
+ turn: HarnessTurnInput,
+ steer: SteerIntake,
+): Promise<Pick<NewTapeRecord, "entrySeq" | "meta">> {
+ const entry = await turn.emit({
+ type: "user",
+ payload: {
+ text: steer.text,
+ ...(steer.ts ? { ts: steer.ts } : {}),
+ steered: true,
+ ...(steer.attachments?.length ? { attachments: steer.attachments } : {}),
+ },
+ scopeLabel: turn.scopeLabel,
+ });
+ await steer.acknowledge?.().catch(swallowAs("steer acknowledge", undefined));
+ return {
+ entrySeq: entry.seq,
+ meta: {
+ bareText: steer.text,
+ ...(steer.ts ? { ts: steer.ts } : {}),
+ ...(steer.attachments?.length ? { attachments: steer.attachments } : {}),
+ entryCreatedAt: entry.createdAt,
+ },
+ };
+}
+
export async function tapeReplyCheckpoint(
turn: Pick<HarnessTurnInput, "tape" | "scopeLabel">,
entry: Pick<SessionEntry, "seq" | "createdAt" | "payload">,
diff --git a/src/harness/opencode-harness.ts b/src/harness/opencode-harness.ts
index 18583d779..f1afa58a2 100644
--- a/src/harness/opencode-harness.ts
+++ b/src/harness/opencode-harness.ts
@@ -44,10 +44,12 @@ import {
oneShotModelUtilities,
oneShotRunner,
tapeReplyCheckpoint,
+ recordSteerIntake,
+ type SteerIntake,
type BridgedTool,
type HarnessToolPlumbing,
} from "./harness-shared.ts";
-import { reconstructMessagesFromHistory } from "./replay.ts";
+import { recordedMessageTimestamps, reconstructMessagesFromHistory } from "./replay.ts";
import { countTokens } from "../util/tokens.ts";
const OPENCODE_VERSION = "1.18.31";
@@ -109,6 +111,13 @@ type ActiveTurn = {
history: unknown[];
userSeq: number | null;
captures: LlmCapture[];
+ steers: Array<{
+ text: string;
+ parts: unknown[];
+ intake: SteerIntake;
+ stamp?: Awaited<ReturnType<typeof recordSteerIntake>>;
+ messageId: string;
+ }>;
model: string;
seenText: Map<string, string>;
seenTasks: Map<string, string>;
@@ -168,6 +177,21 @@ function equalSecret(actual: string, expected: string): boolean {
return left.length === right.length && timingSafeEqual(left, right);
}
+const OPENCODE_ID_ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
+let openCodeIdTime = 0;
+let openCodeIdCounter = 0;
+
+export function openCodeMessageId(now = Date.now()): string {
+ if (now !== openCodeIdTime) {
+ openCodeIdTime = now;
+ openCodeIdCounter = 0;
+ }
+ openCodeIdCounter++;
+ const ordered = (BigInt(now) * 4096n + BigInt(openCodeIdCounter)) & 0xffffffffffffn;
+ const suffix = Array.from(randomBytes(14), (byte) => OPENCODE_ID_ALPHABET[byte % 62]).join("");
+ return `msg_${ordered.toString(16).padStart(12, "0")}${suffix}`;
+}
+
function sessionToken(secret: string, sessionId: string): string {
return createHmac("sha256", secret).update(sessionId).digest("base64url");
}
@@ -475,6 +499,7 @@ export function createOpenCodeHarness(opts: OpenCodeHarnessOptions = {}): Harnes
const childState = (parent: ActiveTurn): ActiveTurn => ({
...parent,
child: true,
+ steers: [],
seenText: new Map(),
seenTasks: new Map(),
eventTail: Promise.resolve(),
@@ -608,6 +633,17 @@ export function createOpenCodeHarness(opts: OpenCodeHarnessOptions = {}): Harnes
}
if (sessionMatch[2] === "capture") {
const request = JSON.parse((await body(req)).toString("utf8")) as Record<string, unknown>;
+ if (!state.child && Array.isArray(request.messages)) {
+ await state.eventTail;
+ for (const message of request.messages) {
+ if (message.info?.role !== "user") continue;
+ const id = message.info?.id;
+ const steer = state.steers.find((steer) => !steer.stamp && steer.messageId === id);
+ if (steer) {
+ steer.stamp = await recordSteerIntake(state.turn, steer.intake);
+ }
+ }
+ }
const model = state.model;
state.captures.push({
sessionId: requestedSessionId,
@@ -880,6 +916,7 @@ export function createOpenCodeHarness(opts: OpenCodeHarnessOptions = {}): Harnes
history: replayMessages(reconstructMessagesFromHistory(turn.history), sessionId, model),
userSeq: userEntry.seq,
captures: [],
+ steers: [],
model: selectedModel,
seenText: new Map(),
seenTasks: new Map(),
@@ -934,11 +971,11 @@ export function createOpenCodeHarness(opts: OpenCodeHarnessOptions = {}): Harnes
}
return parts;
};
- const steeredTapeParts: Array<{ text: string; parts: unknown[] }> = [];
const queueSignal = (
text: string,
images: HarnessTurnInput["images"] = [],
documents: HarnessTurnInput["documents"] = [],
+ intake: SteerIntake,
): Promise<void> => {
const pending = (async () => {
const parts = [
@@ -950,9 +987,24 @@ export function createOpenCodeHarness(opts: OpenCodeHarnessOptions = {}): Harnes
url: `data:${image.mimeType};base64,${image.dataBase64}`,
})),
];
- steeredTapeParts.push({ text, parts: [...parts] });
+ const steer = {
+ text,
+ parts: [...parts],
+ intake,
+ messageId: openCodeMessageId(),
+ };
parts.push(...(await documentParts(documents)));
- await rt.client.session.promptAsync({ path: { id: sessionId }, body: { model, agent: "qm", parts } });
+ state.steers.push(steer);
+ try {
+ await rt.client.session.promptAsync({
+ path: { id: sessionId },
+ body: { model, agent: "qm", parts, messageID: steer.messageId },
+ });
+ } catch (error) {
+ const index = state.steers.indexOf(steer);
+ if (index >= 0) state.steers.splice(index, 1);
+ throw error;
+ }
await waitForSessionIdle(rt.client, sessionId, wallMs > 0 ? wallMs : OPENCODE_IDLE_WAIT_MS);
})();
queuedSignals.add(pending);
@@ -965,20 +1017,17 @@ export function createOpenCodeHarness(opts: OpenCodeHarnessOptions = {}): Harnes
turn.runId,
{
onAbort: async () => abort(true),
- onSteer: async (text, ts, request) => {
+ onSteer: async (text, ts, request, acknowledge) => {
+ if (ts && recordedMessageTimestamps(turn.history).has(ts)) return;
const prepared = await turn.prepareSteer?.(text, request);
const prompt = prepared?.text ?? text;
- await turn.emit({
- type: "user",
- payload: {
- text,
- ...(ts ? { ts } : {}),
- steered: true,
- ...(prepared?.attachments?.length ? { attachments: prepared.attachments } : {}),
- },
- scopeLabel: turn.scopeLabel,
+ await queueSignal(prompt, prepared?.images, prepared?.documents, {
+ text,
+ ts,
+ attachments: prepared?.attachments,
+ acknowledge,
});
- await queueSignal(prompt, prepared?.images, prepared?.documents);
+ return false;
},
},
{ onError: (error) => swallow("opencode signal poll", error), drainOnStop: true },
@@ -1090,19 +1139,15 @@ export function createOpenCodeHarness(opts: OpenCodeHarnessOptions = {}): Harnes
const isTrigger = role === "user" && !tapedTriggerUser;
if (isTrigger) tapedTriggerUser = true;
const steered =
- role === "user"
- ? steeredTapeParts.find((steer) =>
- (message.parts as Array<{ type?: string; text?: string }>).some(
- (part) => part.type === "text" && part.text === steer.text,
- ),
- )
- : undefined;
+ role === "user" ? state.steers.find((steer) => steer.messageId === message.info.id) : undefined;
+ if (steered && !steered.stamp) continue;
const storedParts = isTrigger ? tapePromptParts : steered?.parts;
await turn.tape({
kind: "message",
harness: "opencode",
payload: stripDataUrls(storedParts ? { ...message, parts: storedParts } : message),
scopeLabel: turn.scopeLabel,
+ ...steered?.stamp,
...(isTrigger
? {
entrySeq: userEntry.seq,
diff --git a/src/harness/pi-harness.ts b/src/harness/pi-harness.ts
index b4f27296a..5969aefb9 100644
--- a/src/harness/pi-harness.ts
+++ b/src/harness/pi-harness.ts
@@ -1,3 +1,4 @@
+import { recordSteerIntake, type SteerIntake } from "./harness-shared.ts";
import { withDocumentInputs, type DocumentModel } from "./document-inputs.ts";
import { gatewayModelsJson, gatewayModelsVersion } from "../model/gateway-models.ts";
import { Type } from "typebox";
@@ -47,7 +48,6 @@ import type {
LlmCallUsage,
LlmTransportMeta,
NewTapeRecord,
- TapeMeta,
TapeRecord,
} from "../sessions/session-store.ts";
import { tapeCheckpointPayload, tapeEntryMirrorRecord } from "../sessions/session-store.ts";
@@ -1906,45 +1906,34 @@ export function createPiHarness(opts?: PiHarnessOptions): Harness {
let tapeError: Error | undefined;
let tapedTriggerUser = false;
const toolAbort = new AbortController();
- 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 {
- images: steer!.images,
- meta: {
- bareText: steer!.bareText ?? steer!.text,
- ...(steer!.ts ? { ts: steer!.ts } : {}),
- ...(steer!.attachments?.length ? { attachments: steer!.attachments } : {}),
- entryCreatedAt: steer!.entryCreatedAt,
- },
- };
- };
+ const pendingSteerTapeMeta: Array<
+ SteerIntake & {
+ prompt: string;
+ images?: HarnessTurnInput["images"];
+ }
+ > = [];
const tapeMessage = async (message: unknown): Promise<void> => {
- if (!turn.tape || tapeError) return;
const role = (message as { role?: string }).role;
if (role !== "user" && role !== "assistant" && role !== "toolResult") return;
const isTrigger = role === "user" && !tapedTriggerUser;
if (isTrigger) tapedTriggerUser = true;
+ const steerAt =
+ role === "user" && !isTrigger
+ ? pendingSteerTapeMeta.findIndex(
+ (steer) => steer.prompt === textFromContent((message as { content?: unknown }).content),
+ )
+ : -1;
+ const steer = steerAt >= 0 ? pendingSteerTapeMeta.splice(steerAt, 1)[0] : undefined;
+ if (steer) await thinkTail;
+ const steerStamp = steer ? await recordSteerIntake(turn, steer) : undefined;
+ if (!turn.tape || tapeError) return;
const callId = role === "toolResult" ? (message as { toolCallId?: unknown }).toolCallId : undefined;
const resultScope = typeof callId === "string" ? entry.ref.tapeResultScopes?.get(callId) : undefined;
if (typeof callId === "string") entry.ref.tapeResultScopes?.delete(callId);
- const steerStamp = role === "user" && !isTrigger ? steerTapeStamp(message) : undefined;
const rec: NewTapeRecord = {
kind: "message",
harness: "pi",
- payload: stripImageBytes(message, isTrigger ? turn.images : steerStamp?.images),
+ payload: stripImageBytes(message, isTrigger ? turn.images : steer?.images),
scopeLabel: resultScope ?? turn.scopeLabel,
...(isTrigger
? {
@@ -1957,7 +1946,7 @@ export function createPiHarness(opts?: PiHarnessOptions): Harness {
},
}
: {}),
- ...(steerStamp ? { meta: steerStamp.meta } : {}),
+ ...steerStamp,
};
try {
await turn.tape(rec);
@@ -2092,41 +2081,11 @@ export function createPiHarness(opts?: PiHarnessOptions): Harness {
if (!turn.tape) return;
await turn.tape(tapeEntryMirrorRecord(mirrored));
};
- const tapeLeftoverSteers = async (): Promise<void> => {
- const leftovers = pendingSteerTapeMeta.splice(0);
- if (!turn.tape) return;
- for (const steer of leftovers) {
- await turn.tape({
- kind: "message",
- harness: "pi",
- payload: {
- role: "user",
- 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.bareText ?? steer.text,
- ...(steer.attachments?.length ? { attachments: steer.attachments } : {}),
- ...(steer.ts ? { ts: steer.ts } : {}),
- entryCreatedAt: steer.entryCreatedAt,
- },
- });
- }
- };
const checkpointSubturn = async (
finalEntry: { seq: number; createdAt: number },
reply: string,
): Promise<void> => {
if (!turn.tape) return;
- await tapeLeftoverSteers();
await turn.tape({
kind: "annotation",
payload: tapeCheckpointPayload("subturnEnd", {
@@ -2151,6 +2110,7 @@ export function createPiHarness(opts?: PiHarnessOptions): Harness {
entry.ref.abortSignal = toolAbort.signal;
const onCancel = (): void => {
toolAbort.abort();
+ entry.agentSession.clearQueue();
void entry.agentSession.abort().catch(swallowAs("pi: lease-lost abort", undefined));
};
if (turn.cancel) {
@@ -2164,51 +2124,45 @@ export function createPiHarness(opts?: PiHarnessOptions): Harness {
signals,
turn.runId,
{
- onSteer: async (text, ts, request) => {
+ onSteer: async (text, ts, request, acknowledge) => {
+ if (ts && steeredSeen.has(ts)) return;
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,
- ...(prepared?.attachments?.length ? { attachments: prepared.attachments } : {}),
- },
- scopeLabel: turn.scopeLabel,
- });
- 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) return false;
+ if (!entry.agentSession.isStreaming || toolAbort.signal.aborted) return false;
+ const steer = {
+ text,
+ prompt,
+ ts,
+ images: prepared?.images,
+ attachments: prepared?.attachments,
+ acknowledge,
+ };
+ pendingSteerTapeMeta.push(steer);
+ if (ts) steeredSeen.add(ts);
if (prepared?.documents?.length)
entry.ref.documents = [...(entry.ref.documents ?? []), ...prepared.documents];
entry.ref.silentRequested = false;
- await entry.agentSession.steer(
- prompt,
- prepared?.images?.map((image) => ({
- type: "image" as const,
- mimeType: image.mimeType,
- data: image.dataBase64,
- })),
- );
+ try {
+ await entry.agentSession.steer(
+ prompt,
+ prepared?.images?.map((image) => ({
+ type: "image" as const,
+ mimeType: image.mimeType,
+ data: image.dataBase64,
+ })),
+ );
+ } catch (error) {
+ const at = pendingSteerTapeMeta.indexOf(steer);
+ if (at >= 0) pendingSteerTapeMeta.splice(at, 1);
+ if (ts) steeredSeen.delete(ts);
+ throw error;
+ }
+ return false;
},
onAbort: async () => {
userAborted = true;
toolAbort.abort();
+ entry.agentSession.clearQueue();
await entry.agentSession.abort();
},
},
@@ -2394,6 +2348,7 @@ export function createPiHarness(opts?: PiHarnessOptions): Harness {
} finally {
turn.cancel?.removeEventListener("abort", onCancel);
await stopSignalPoll?.();
+ if (pendingSteerTapeMeta.length) entry.agentSession.clearQueue();
unsubscribeTape?.();
unsubscribe?.();
await thinkTail;
diff --git a/src/runs/run-signal-store.ts b/src/runs/run-signal-store.ts
index 1bd148f4b..634ece615 100644
--- a/src/runs/run-signal-store.ts
+++ b/src/runs/run-signal-store.ts
@@ -156,7 +156,7 @@ export function waitForClientResult(
const SIGNAL_POLL_MS = 5_000;
export interface SignalPollHandlers {
- onSteer(text: string, ts?: string, request?: TurnRequest): Promise<void | boolean>;
+ onSteer(text: string, ts?: string, request?: TurnRequest, acknowledge?: () => Promise<void>): Promise<void | boolean>;
onAbort(): Promise<void>;
}
@@ -190,7 +190,9 @@ export function startSignalPoll(
}
} else if (!declined.has(id)) {
if (s.text || s.request?.attachments?.length) {
- const delivered = await handlers.onSteer(s.text ?? "", s.ts, s.request);
+ const delivered = await handlers.onSteer(s.text ?? "", s.ts, s.request, () =>
+ signals.acknowledge(runId, id),
+ );
if (delivered === false) {
declined.add(id);
continue;
diff --git a/src/sessions/session-store.ts b/src/sessions/session-store.ts
index 1152745df..09155b67f 100644
--- a/src/sessions/session-store.ts
+++ b/src/sessions/session-store.ts
@@ -249,7 +249,7 @@ export async function appendEntryOutsideTurn(
export const TAPE_IMPORT_MAX_ENTRIES = 500;
-export interface TapeMeta {
+interface TapeMeta {
bareText?: string;
ts?: string;
changeTime?: string;
diff --git a/test/claude-harness-turn.test.ts b/test/claude-harness-turn.test.ts
index eda6419c4..6b0c213d8 100644
--- a/test/claude-harness-turn.test.ts
+++ b/test/claude-harness-turn.test.ts
@@ -120,9 +120,9 @@ test("a steered turn persists every reply, not only the last result's", async ()
const runId = "run-steer";
currentScript = async function* (prompts) {
const iterator = prompts[Symbol.asyncIterator]();
- await iterator.next();
+ yield (await iterator.next()).value as unknown as FakeSdkMessage;
await signals.send(runId, { kind: "steer", text: "now do the other three", ts: "123.456" });
- await iterator.next();
+ yield (await iterator.next()).value as unknown as FakeSdkMessage;
yield assistantMessage("msg_A", "The capital of France is Paris.", {
input_tokens: 3,
output_tokens: 8,
@@ -532,7 +532,9 @@ test("steering forwards prepared images and file paths while retaining the origi
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;
+ const next = (await iterator.next()).value!;
+ injected = next.message.content;
+ yield next as unknown as FakeSdkMessage;
yield resultMessage("saw the image");
yield resultMessage("done");
};
@@ -670,3 +672,65 @@ for (const surfaceTools of [false, true]) {
assert.ok(entries.some((entry) => entry.type === "tool_result" && (entry.payload as { silent?: boolean }).silent));
});
}
+
+test("Claude emits repeated-text steers only at distinct native user echoes", async () => {
+ const signals = createMemoryRunSignalStore();
+ const tape: unknown[] = [];
+ const { turn, entries } = harnessTurn({
+ runId: "echo-intake",
+ input: "same text",
+ tape: async (row) => {
+ tape.push(row);
+ },
+ });
+ currentScript = async function* (prompts) {
+ const iterator = prompts[Symbol.asyncIterator]();
+ yield (await iterator.next()).value as unknown as FakeSdkMessage;
+ await signals.send("echo-intake", { kind: "steer", text: "same text", ts: "one" });
+ const first = (await iterator.next()).value as unknown as FakeSdkMessage;
+ await signals.send("echo-intake", { kind: "steer", text: "same text", ts: "two" });
+ const second = (await iterator.next()).value as unknown as FakeSdkMessage;
+ assert.equal(entries.filter((entry) => entry.type === "user").length, 1);
+ assert.equal((await signals.pending("echo-intake")).length, 2);
+ yield first;
+ yield first;
+ assert.equal(entries.filter((entry) => entry.type === "user").length, 2);
+ yield {
+ ...second,
+ message: {
+ role: "user",
+ content: [
+ ...(first.message as { content: unknown[] }).content,
+ ...(second.message as { content: unknown[] }).content,
+ ],
+ },
+ };
+ yield resultMessage("first");
+ yield resultMessage("second");
+ yield resultMessage("third");
+ };
+ await createClaudeHarness({ signals }).turns.runTurn(turn);
+ assert.deepEqual(capturedOptions.extraArgs, { "replay-user-messages": null });
+ const users = entries.filter((entry) => entry.type === "user");
+ assert.deepEqual(
+ users.map((entry) => (entry.payload as { ts?: string }).ts),
+ [undefined, "one", "two"],
+ );
+ assert.equal((await signals.pending("echo-intake")).length, 0);
+ assert.equal(tape.filter((row) => (row as { meta?: { ts?: string } }).meta?.ts).length, 2);
+});
+
+test("Claude retains a queued message which the SDK never consumes", async () => {
+ const signals = createMemoryRunSignalStore();
+ const { turn, entries } = harnessTurn({ runId: "no-echo" });
+ currentScript = async function* (prompts) {
+ const iterator = prompts[Symbol.asyncIterator]();
+ yield (await iterator.next()).value as unknown as FakeSdkMessage;
+ await signals.send("no-echo", { kind: "steer", text: "not yet", ts: "pending" });
+ await iterator.next();
+ yield resultMessage("original reply");
+ };
+ await createClaudeHarness({ signals }).turns.runTurn(turn);
+ assert.equal(entries.filter((entry) => entry.type === "user").length, 1);
+ assert.equal((await signals.pending("no-echo"))[0]?.signal.ts, "pending");
+});
diff --git a/test/codex-harness.test.ts b/test/codex-harness.test.ts
index 9c306752c..917e123ed 100644
--- a/test/codex-harness.test.ts
+++ b/test/codex-harness.test.ts
@@ -1981,8 +1981,13 @@ test("Codex steers extracted documents into the active turn without copying cont
if (msg.method === "turn/steer") {
writeFileSync(${JSON.stringify(capture)}, JSON.stringify(msg.params));
send({ id: msg.id, result: {} });
+ setTimeout(() => {
+ send({ method: "item/completed", params: { threadId: "thread-sf", item: { id: "steered-user", type: "userMessage", content: msg.params.input } } });
+ send({ method: "item/completed", params: { threadId: "thread-sf", item: { id: "steered-user", type: "userMessage", content: msg.params.input } } });
send({ method: "item/completed", params: { threadId: "thread-sf", item: { id: "answer", type: "agentMessage", phase: "final_answer", text: "document read" } } });
- return send({ method: "turn/completed", params: { threadId: "thread-sf", turn: { id: "turn-sf", status: "completed", items: [] } } });
+ send({ method: "turn/completed", params: { threadId: "thread-sf", turn: { id: "turn-sf", status: "completed", items: [] } } });
+ }, 100);
+ return;
}
if (msg.method === "turn/interrupt") {`,
);
@@ -1994,6 +1999,7 @@ test("Codex steers extracted documents into the active turn without copying cont
rmSync(dir, { recursive: true, force: true });
});
const tape: unknown[] = [];
+ const entries: SessionEntry[] = [];
const scope = "personal:tester" as ScopeId;
const running = harness.turns.runTurn({
session: { id: "steer-document-session" } as Session,
@@ -2007,8 +2013,16 @@ test("Codex steers extracted documents into the active turn without copying cont
tools: {} as HarnessTurnInput["tools"],
scopeLabel: scope,
orgScopeId: scope,
- emit: async (entry) =>
- ({ ...entry, sessionId: "steer-document-session", seq: 1, createdAt: Date.now() }) as SessionEntry,
+ emit: async (entry) => {
+ const saved = {
+ ...entry,
+ sessionId: "steer-document-session",
+ seq: entries.length,
+ createdAt: Date.now(),
+ } as SessionEntry;
+ entries.push(saved);
+ return saved;
+ },
recordModelCall: () => {},
tape: async (row) => {
tape.push(row);
@@ -2030,7 +2044,14 @@ test("Codex steers extracted documents into the active turn without copying cont
await new Promise((resolve) => setTimeout(resolve, 10));
}
await signals.send("steer-document-run", { kind: "steer", text: "read the document", ts: "doc.1" });
+ while (!existsSync(capture)) {
+ if (Date.now() > deadline) throw new Error("mock Codex did not receive steer");
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ }
+ assert.equal(entries.filter((entry) => entry.type === "user").length, 1, "turn/steer acceptance is not intake");
await running;
+ assert.equal(entries.filter((entry) => entry.type === "user").length, 2);
+ assert.equal((await signals.pending("steer-document-run")).length, 0);
assert.match(readFileSync(capture, "utf8"), /STEER-PRIVATE-492/);
assert.doesNotMatch(JSON.stringify(tape), /STEER-PRIVATE-492/);
assert.doesNotMatch(readFileSync(capture, "utf8"), /OUTSIDE-BUDGET-492/);
diff --git a/test/opencode-harness.test.ts b/test/opencode-harness.test.ts
index 3a079c6e3..d56006e1b 100644
--- a/test/opencode-harness.test.ts
+++ b/test/opencode-harness.test.ts
@@ -1,7 +1,7 @@
import test from "node:test";
import { createMemoryRunSignalStore } from "../src/runs/run-signal-store.ts";
import assert from "node:assert/strict";
-import { existsSync, chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
@@ -9,6 +9,7 @@ import {
createOpenCodeHarness,
latestAssistantParts,
openCodeHarnessConfigOptions,
+ openCodeMessageId,
} from "../src/harness/opencode-harness.ts";
import type { OpencodeClient } from "@opencode-ai/sdk";
import type { Config } from "../src/config.ts";
@@ -440,6 +441,31 @@ test("OpenCode advertises aliases only for tools available on the turn", async (
}
});
+const NATIVE_OPENCODE_MESSAGE_IDS = [
+ { id: "msg_0db05f98c001fMdjYWHxM9sh5P", created: 1790380997004 },
+ { id: "msg_0db05f9bd001g2O0sXZ8G8uRZ0", created: 1790380997053 },
+ { id: "msg_0db05f9df001L0AWD5YFiFs5Wr", created: 1790380997087 },
+];
+
+function nativeOpenCodeTimestamp(id: string): number {
+ return Number(BigInt("0x" + id.slice("msg_".length, "msg_".length + 12)) / 4096n);
+}
+
+test("OpenCode steer message IDs sort against IDs minted by native OpenCode 1.18.31", () => {
+ for (const native of NATIVE_OPENCODE_MESSAGE_IDS) {
+ const before = openCodeMessageId(native.created - 1);
+ const after = openCodeMessageId(native.created + 1);
+ assert.match(before, /^msg_[0-9a-f]{12}[0-9A-Za-z]{14}$/);
+ assert.equal(before.length, native.id.length);
+ assert.ok(before < native.id, `${before} must sort before native ${native.id}`);
+ assert.ok(native.id < after, `${after} must sort after native ${native.id}`);
+ assert.equal(nativeOpenCodeTimestamp(after), nativeOpenCodeTimestamp(native.id) + 1);
+ }
+ const first = openCodeMessageId(1790380997200);
+ const second = openCodeMessageId(1790380997200);
+ assert.ok(first < second, "IDs minted in the same millisecond keep creation order");
+});
+
test("OpenCode includes steered PDF and extracted documents without copying echoed contents into tape", async (t) => {
const dir = mkdtempSync(join(tmpdir(), "qm-opencode-steer-doc-"));
const capturePath = join(dir, "steered.json");
@@ -456,11 +482,16 @@ test("OpenCode includes steered PDF and extracted documents without copying echo
if (req.method === "POST" && message) {
process.qaInitial = JSON.parse(await readBody(req));
while (!process.qaSteered) await new Promise(resolve => setTimeout(resolve, 10));
+ while (!require("node:fs").existsSync(${JSON.stringify(capturePath + ".release")})) await new Promise(resolve => setTimeout(resolve, 5));
+ await capture("ses_main", { messages: [
+ { info: { id: "initial", role: "user" }, parts: process.qaInitial.parts },
+ { info: { id: process.qaSteered.messageID, role: "user" }, parts: process.qaSteered.parts },
+ ] });
return json(res, ${okAssistant});
}
if (req.method === "GET" && message) return json(res, [
{ info: { id: "initial", role: "user" }, parts: process.qaInitial.parts },
- { info: { id: "steered", role: "user" }, parts: process.qaSteered.parts },
+ { info: { id: process.qaSteered.messageID, role: "user" }, parts: process.qaSteered.parts },
${okAssistant},
]);
`,
@@ -474,7 +505,8 @@ test("OpenCode includes steered PDF and extracted documents without copying echo
const pdf = readFileSync(new URL("./fixtures/documents/sample.pdf", import.meta.url)).toString("base64");
const docx = readFileSync(new URL("./fixtures/documents/sample.docx", import.meta.url)).toString("base64");
const tape: unknown[] = [];
- const turn = turnInput([], []);
+ const entries: SessionEntry[] = [];
+ const turn = turnInput(entries, []);
turn.runId = "opencode-steer-docs";
turn.tape = async (row) => {
tape.push(row);
@@ -499,7 +531,26 @@ test("OpenCode includes steered PDF and extracted documents without copying echo
],
});
await signals.send(turn.runId, { kind: "steer", text: "read the documents", ts: "doc.1" });
- await harness.turns.runTurn(turn);
+ const steerWindowStart = Date.now();
+ const running = harness.turns.runTurn(turn);
+ const deadline = Date.now() + 8_000;
+ while (!existsSync(capturePath)) {
+ if (Date.now() > deadline) throw new Error("mock OpenCode did not receive steer");
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ }
+ const steerWindowEnd = Date.now();
+ const steeredMessageId = (JSON.parse(readFileSync(capturePath, "utf8")) as { messageID: string }).messageID;
+ assert.match(steeredMessageId, /^msg_[0-9a-f]{12}[0-9A-Za-z]{14}$/);
+ const steeredAt = nativeOpenCodeTimestamp(steeredMessageId);
+ assert.ok(
+ steeredAt >= steerWindowStart % 2 ** 36 && steeredAt <= steerWindowEnd % 2 ** 36,
+ "the queued steer carries a native OpenCode time-ordered message ID",
+ );
+ assert.equal(entries.filter((entry) => entry.type === "user").length, 1, "queued input is not model intake");
+ writeFileSync(capturePath + ".release", "continue");
+ await running;
+ assert.equal(entries.filter((entry) => entry.type === "user").length, 2);
+ assert.equal((await signals.pending(turn.runId)).length, 0);
const sent = readFileSync(capturePath, "utf8");
assert.ok(sent.includes(pdf));
assert.ok(!sent.includes("OUTSIDE-BUDGET-492"));
diff --git a/test/orchestrator-steer-visibility.test.ts b/test/orchestrator-steer-visibility.test.ts
new file mode 100644
index 000000000..c8d73579d
--- /dev/null
+++ b/test/orchestrator-steer-visibility.test.ts
@@ -0,0 +1,108 @@
+import "./support/auto-fake-sprites.ts";
+import { mock, test } from "node:test";
+import assert from "node:assert/strict";
+import * as mockHarness from "../src/harness/mock-harness.ts";
+import { recordSteerIntake } from "../src/harness/harness-shared.ts";
+import type { HarnessTurnInput, HarnessTurnResult } from "../src/harness/harness.ts";
+import type { TurnRequest } from "../src/types.ts";
+import { testConfig } from "./support/test-config.ts";
+
+let exercise: ((turn: HarnessTurnInput) => Promise<HarnessTurnResult | void>) | undefined;
+mock.module("../src/harness/mock-harness.ts", {
+ namedExports: {
+ ...mockHarness,
+ createMockHarness: () => {
+ const harness = mockHarness.createMockHarness();
+ const run = harness.turns.runTurn;
+ harness.turns.runTurn = async (turn) => {
+ if (!exercise) return run(turn);
+ return (await exercise(turn)) ?? { reply: "Done" };
+ };
+ return harness;
+ },
+ },
+});
+const { buildApp } = await import("../src/wiring.ts");
+
+for (const mode of ["retry", "handoff"] as const) {
+ test(`a ${mode} hides its synthetic trigger but not real steer intake in entries, tape, or activity`, async () => {
+ const built = buildApp(testConfig());
+ const request: TurnRequest = {
+ surface: "test",
+ actor: { externalId: "U1" },
+ conversation: { kind: "dm", threadRef: "resume-steer-visibility" },
+ text: "!work-then-boom",
+ idempotencyKey: "resume-steer-visibility",
+ };
+ if (mode === "retry") await assert.rejects(built.app.turn(request), /boom/);
+ let runId: string | undefined;
+ exercise = async (turn) => {
+ runId = turn.runId;
+ if (mode === "handoff" && turn.input === request.text) {
+ await turn.emit({ type: "user", payload: { text: turn.input }, scopeLabel: turn.scopeLabel });
+ return {
+ reply: "",
+ runtimeHandoff: {
+ choice: { harnessId: turn.runtime!.harnessId!, modelId: turn.runtime!.modelId! },
+ lifetime: "task",
+ },
+ };
+ }
+ assert.match(turn.input, /previous attempt|Runtime handoff completed/);
+ const trigger = await turn.emit({ type: "user", payload: { text: turn.input }, scopeLabel: turn.scopeLabel });
+ await turn.tape!({
+ kind: "message",
+ harness: "pi",
+ payload: { role: "user", content: turn.input },
+ scopeLabel: turn.scopeLabel,
+ entrySeq: trigger.seq,
+ meta: { bareText: turn.input, entryCreatedAt: trigger.createdAt },
+ });
+ const stamp = await recordSteerIntake(turn, { text: "Change of plan", ts: "steer-visible" });
+ await turn.tape!({
+ kind: "message",
+ harness: "pi",
+ payload: { role: "user", content: "Change of plan" },
+ scopeLabel: turn.scopeLabel,
+ ...stamp,
+ });
+ const privateEntry = await turn.emit({
+ type: "user",
+ payload: { text: "private steer", steered: true, hidden: true },
+ scopeLabel: turn.scopeLabel,
+ });
+ await turn.tape!({
+ kind: "message",
+ harness: "pi",
+ payload: { role: "user", content: "private steer" },
+ scopeLabel: turn.scopeLabel,
+ entrySeq: privateEntry.seq,
+ meta: { bareText: "private steer", entryCreatedAt: privateEntry.createdAt },
+ });
+ };
+ try {
+ const result = await built.app.turn(request);
+ assert.equal(result.status, "ok");
+ const session = await built.app.getSession(result.sessionId!);
+ const users = session!.entries.filter((entry) => entry.type === "user");
+ assert.equal((users[1]!.payload as { hidden?: boolean }).hidden, true);
+ assert.equal((users[2]!.payload as { text?: string }).text, "Change of plan");
+ assert.notEqual((users[2]!.payload as { hidden?: boolean }).hidden, true);
+ assert.equal((users[3]!.payload as { hidden?: boolean }).hidden, true);
+ const activity = (await built.app.getRun(runId!))!.activity ?? [];
+ const liveSteer = activity.find(
+ (entry) => entry.type === "user" && (entry.payload as { text?: string }).text === "Change of plan",
+ );
+ assert.ok(liveSteer);
+ assert.notEqual((liveSteer.payload as { hidden?: boolean }).hidden, true);
+ const tape = await built.sessions.getTape(result.sessionId!);
+ for (const entry of users.slice(1)) {
+ const row = tape.find((row) => row.kind === "message" && row.entrySeq === entry.seq);
+ assert.ok(row);
+ assert.equal(row.meta?.hidden === true, (entry.payload as { hidden?: boolean }).hidden === true);
+ }
+ } finally {
+ exercise = undefined;
+ }
+ });
+}
diff --git a/test/pi-harness-tape-sync.test.ts b/test/pi-harness-tape-sync.test.ts
index 2be768851..efffe52cd 100644
--- a/test/pi-harness-tape-sync.test.ts
+++ b/test/pi-harness-tape-sync.test.ts
@@ -101,11 +101,41 @@ for (const variant of ["text", "images", "documents", "finished during preparati
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);
+ if (calls === 1) {
+ setTimeout(() => {
+ void signals.send("run-order", { kind: "steer", text: "actually, do it differently", ts: "1712.001" });
+ if (!finishDuringPreparation)
+ setTimeout(() => {
+ assert.equal(
+ sink.entries.filter((entry) => entry.type === "user").length,
+ 1,
+ "enqueue is not model intake",
+ );
+ releaseFirstStep();
+ }, 100);
+ }, 30);
+ const events = textReplyEvents("first step");
+ if (variant === "text") {
+ for (const event of events) if (typeof event.index === "number") event.index = 1;
+ events.splice(
+ 1,
+ 0,
+ { type: "content_block_start", index: 0, content_block: { type: "thinking", thinking: "" } },
+ { type: "content_block_delta", index: 0, delta: { type: "thinking_delta", thinking: "before the steer" } },
+ { type: "content_block_stop", index: 0 },
+ );
+ }
+ return gatedSse(events, 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) => {
+ if (entry.type === "thinking") await new Promise((resolve) => setTimeout(resolve, 100));
+ return emit(entry);
+ };
if (withImages)
turn.prepareSteer = async (text) => {
if (finishDuringPreparation) {
@@ -120,15 +150,6 @@ for (const variant of ["text", "images", "documents", "finished during preparati
: {}),
};
};
- 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");
@@ -164,6 +185,17 @@ for (const variant of ["text", "images", "documents", "finished during preparati
assert.ok(JSON.stringify(requestMessages[1]).includes(documentBase64));
assert.ok(!JSON.stringify(sink.tape).includes(documentBase64));
}
+ const steeredEntry = sink.entries.find(
+ (entry) => entry.type === "user" && (entry.payload as { steered?: boolean }).steered,
+ );
+ assert.ok(steeredEntry);
+ if (variant === "text")
+ assert.ok(
+ steeredEntry.seq > sink.entries.find((entry) => entry.type === "thinking")!.seq,
+ "slow persistence of prior thinking must not cross the intake event",
+ );
+ assert.equal(messageRows[2]!.entrySeq, steeredEntry.seq);
+ assert.deepEqual(await signals.takePending("run-order"), [], "consumed steer is acknowledged");
assert.equal(calls, 2);
assert.equal(tapeRowsAtDispatch[0], 1, "the trigger user row is committed before the first dispatch");
assert.equal(
@@ -385,3 +417,165 @@ test("Pi Responses captures exclude history and document text without changing r
globalThis.fetch = realFetch;
}
});
+
+for (const stopBeforeIntake of [false, true]) {
+ test(`steering during a tool ${stopBeforeIntake ? "survives Stop without fabricated intake" : "lands after its result in live and replay order"}`, async () => {
+ const signals = createMemoryRunSignalStore();
+ const harness = createPiHarness({ apiKey: "sk-test", signals });
+ const store = createMemorySessionStore();
+ const session = await store.getOrCreateByThread("web:steer-tool", "dm", "personal:tester" as ScopeId);
+ const lease = (await store.acquireLease(session.id, "turn")).lease!;
+ const realFetch = globalThis.fetch;
+ let calls = 0;
+ globalThis.fetch = (async () => {
+ if (++calls > 1) return sse(textReplyEvents("done"));
+ const events = textReplyEvents("");
+ events[1] = {
+ type: "content_block_start",
+ index: 0,
+ content_block: { type: "tool_use", id: "read-memory", name: "memory", input: {} },
+ };
+ events[2] = {
+ type: "content_block_delta",
+ index: 0,
+ delta: { type: "input_json_delta", partial_json: JSON.stringify({ action: "read" }) },
+ };
+ events[4] = { type: "message_delta", delta: { stop_reason: "tool_use" }, usage: { output_tokens: 3 } };
+ return sse(events);
+ }) as typeof fetch;
+ const entries: SessionEntry[] = [];
+ try {
+ await harness.turns.runTurn(
+ turnInput(
+ session.id,
+ { entries: [], tape: [] },
+ {
+ session,
+ runId: "tool-steer",
+ tools: {
+ memoryRead: async () => {
+ await signals.send("tool-steer", { kind: "steer", text: "use the other file", ts: "tool.1" });
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ assert.equal(entries.filter((entry) => entry.type === "user").length, 1);
+ assert.equal((await signals.pending("tool-steer")).length, 1);
+ if (stopBeforeIntake) {
+ await signals.send("tool-steer", { kind: "abort" });
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ }
+ return "saved facts";
+ },
+ } as HarnessTurnInput["tools"],
+ emit: async (entry) => {
+ const saved = await store.append(lease, entry);
+ entries.push(saved);
+ return saved;
+ },
+ tape: (row) => store.appendTape(lease, row),
+ },
+ ),
+ );
+ const tape = await store.getTape(session.id);
+ const steerRows = tape.filter((row) => row.meta?.ts === "tool.1");
+ const users = entries.filter((entry) => entry.type === "user");
+ if (stopBeforeIntake) {
+ assert.equal(users.length, 1);
+ assert.equal(steerRows.length, 0);
+ assert.equal((await signals.pending("tool-steer")).filter((row) => row.signal.kind === "steer").length, 1);
+ const before = calls;
+ await harness.turns.runTurn(turnInput(session.id, { entries: [], tape: [] }));
+ assert.equal(calls, before + 1, "cached Pi session must not redeliver the queued steer on its own");
+ } else {
+ assert.deepEqual(
+ entries.map((entry) => entry.type),
+ ["user", "tool_call", "tool_result", "user", "assistant"],
+ );
+ assert.equal(steerRows[0]?.entrySeq, users[1]?.seq);
+ assert.equal(steerRows[0]?.meta?.entryCreatedAt, users[1]?.createdAt);
+ const { projectTapeEntries } = await import("../src/harness/tape-projection.ts");
+ const replay = projectTapeEntries(session.id, tape);
+ assert.ok(replay);
+ assert.deepEqual(
+ replay.entries.map((entry) => [entry.seq, entry.type]),
+ entries.map((entry) => [entry.seq, entry.type]),
+ );
+ assert.equal((await signals.pending("tool-steer")).length, 0);
+ }
+ } finally {
+ globalThis.fetch = realFetch;
+ await store.releaseLease(lease);
+ await harness.turns.close?.();
+ }
+ });
+}
+
+for (const failure of ["acknowledge", "tape"] as const) {
+ test(`a consumed steer is recorded when ${failure === "acknowledge" ? "its acknowledgement fails" : "an earlier tape append failed"}`, async () => {
+ const signals = createMemoryRunSignalStore();
+ if (failure === "acknowledge")
+ signals.acknowledge = async () => {
+ throw new Error("signal store unavailable");
+ };
+ const harness = createPiHarness({ apiKey: "sk-test", signals });
+ const sink: Sink = { entries: [], tape: [] };
+ const realFetch = globalThis.fetch;
+ let calls = 0;
+ globalThis.fetch = (async () => {
+ if (++calls > 1) return sse(textReplyEvents("done"));
+ const events = textReplyEvents("");
+ events[1] = {
+ type: "content_block_start",
+ index: 0,
+ content_block: { type: "tool_use", id: "read-memory", name: "memory", input: {} },
+ };
+ events[2] = {
+ type: "content_block_delta",
+ index: 0,
+ delta: { type: "input_json_delta", partial_json: JSON.stringify({ action: "read" }) },
+ };
+ events[4] = { type: "message_delta", delta: { stop_reason: "tool_use" }, usage: { output_tokens: 3 } };
+ return sse(events);
+ }) as typeof fetch;
+ try {
+ const turn = turnInput("steer-failure", sink, {
+ runId: "steer-failure",
+ tools: {
+ memoryRead: async () => {
+ await signals.send("steer-failure", { kind: "steer", text: "use the other file", ts: "fail.1" });
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ return "saved facts";
+ },
+ } as HarnessTurnInput["tools"],
+ tape: async (rec: NewTapeRecord) => {
+ if (failure === "tape" && rec.kind === "message" && (rec.payload as { role?: string }).role === "toolResult")
+ throw new Error("tape insert refused");
+ sink.tape.push(rec);
+ },
+ });
+ const steered = () =>
+ sink.entries.filter((entry) => entry.type === "user" && (entry.payload as { steered?: boolean }).steered);
+ if (failure === "tape") {
+ await assert.rejects(harness.turns.runTurn(turn), /tape insert refused/);
+ assert.equal(steered().length, 1, "the consumed steer keeps its canonical intake entry");
+ assert.equal((await signals.pending("steer-failure")).length, 0, "the recorded steer is acknowledged");
+ assert.equal(
+ sink.tape.some((rec) => rec.meta?.ts === "fail.1"),
+ false,
+ "no tape row is written after the tape failed",
+ );
+ } else {
+ const result = await harness.turns.runTurn(turn);
+ assert.equal(result.reply, "done", "an acknowledgement failure does not tear down the live turn");
+ assert.equal(steered().length, 1);
+ assert.equal(sink.tape.find((rec) => rec.meta?.ts === "fail.1")?.entrySeq, steered()[0]!.seq);
+ assert.equal(
+ (await signals.pending("steer-failure")).filter((row) => row.signal.kind === "steer").length,
+ 1,
+ "an unacknowledged steer stays pending for replay",
+ );
+ }
+ } finally {
+ globalThis.fetch = realFetch;
+ await harness.turns.close?.();
+ }
+ });
+}
diff --git a/test/run-signal-store.test.ts b/test/run-signal-store.test.ts
index a1a937885..45f5055b3 100644
--- a/test/run-signal-store.test.ts
+++ b/test/run-signal-store.test.ts
@@ -703,3 +703,31 @@ test("pg store: a client_result round-trips, dedupes, and wakes a waiter", { ski
await store.close?.();
}
});
+
+test("a queued steer remains durable until its native intake acknowledges it", async () => {
+ const store = createMemoryRunSignalStore();
+ let acknowledge: (() => Promise<void>) | undefined;
+ let deliveries = 0;
+ const stop = startSignalPoll(
+ store,
+ "intake",
+ {
+ onSteer: async (_text, _ts, _request, ack) => {
+ deliveries++;
+ acknowledge = ack;
+ return false;
+ },
+ onAbort: async () => {},
+ },
+ { intervalMs: 5 },
+ );
+ await store.send("intake", { kind: "steer", text: "queued, not consumed" });
+ await until(() => !!acknowledge);
+ await sleep(20);
+ assert.equal(deliveries, 1);
+ assert.equal((await store.pending("intake")).length, 1);
+ await acknowledge!();
+ await acknowledge!();
+ await stop();
+ assert.deepEqual(await store.pending("intake"), []);
+});
diff --git a/test/steer-entry-flag.test.ts b/test/steer-entry-flag.test.ts
index bb67858bc..4a906bd81 100644
--- a/test/steer-entry-flag.test.ts
+++ b/test/steer-entry-flag.test.ts
@@ -11,10 +11,11 @@ function source(file: string): string {
}
test("every harness still flags the mid-turn message it persists", () => {
+ assert.match(source("harness-shared.ts"), /steered: true/);
for (const file of HARNESSES) {
assert.match(
source(file),
- /steered: true/,
+ /recordSteerIntake/,
`${file} no longer stamps steered:true — a requeued run will re-answer a turn this harness steered`,
);
}