Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

Interrupting mid-tool-call no longer discards a queued steering message (#605)

Yaowei Zheng33f356c10e6c
diff --git a/changelog/unreleased/2026-09-03-steering-returned-on-interrupt.md b/changelog/unreleased/2026-09-03-steering-returned-on-interrupt.md
new file mode 100644
index 00000000..842de0d9
--- /dev/null
+++ b/changelog/unreleased/2026-09-03-steering-returned-on-interrupt.md
@@ -0,0 +1,29 @@
+# Interrupting mid-tool-call no longer discards a queued steering message
+
+- **Date:** 2026-09-03
+- **Type:** fix
+- **Scope:** `server`, `web`
+- **PR:** [#605](https://github.com/Prism-Shadow/penguin-harness/pull/605)
+
+[中文版](2026-09-03-steering-returned-on-interrupt.zh.md)
+
+A message steered into a running Task and still waiting for its next tool round was thrown
+away when the run was interrupted, taking the text the user had already typed with it. The
+undelivered message is now handed back and returns to the composer, ready to send again.
+
+## Details
+
+- Core drops its steering queue as a run exits, so the server used to drop its mirror with it.
+ What is in that mirror when the run ends is exactly what was never delivered — entries leave
+ it as their `[user_steering]` message appears on the stream, and the mirror is read after that
+ stream is drained — so those entries are now handed back instead of discarded.
+- Handed-back entries ride `task_state` events and the SSE subscribe snapshot as
+ `returnedSteering`, and the composer takes each one through the same recall channel a queued
+ line's button already used: the text returns to the input box, images and file attachments
+ are restored with it, and the "steering queued" hint retires.
+- A reload restores them too, so a closed tab does not strand the message.
+- Entries are not cleared when the next run starts: the message was never delivered whatever
+ happens afterwards. Only taking it back — or the runtime entry's idle eviction — removes one.
+- Steering delivered before the interrupt is unaffected, and a subagent's undelivered steering
+ still ends with its run: it comes from the model or the agents panel, and no composer is
+ waiting to take it back.
diff --git a/changelog/unreleased/2026-09-03-steering-returned-on-interrupt.zh.md b/changelog/unreleased/2026-09-03-steering-returned-on-interrupt.zh.md
new file mode 100644
index 00000000..26c4f867
--- /dev/null
+++ b/changelog/unreleased/2026-09-03-steering-returned-on-interrupt.zh.md
@@ -0,0 +1,18 @@
+# 工具执行中打断不再丢弃排队的插话
+
+- **Date:** 2026-09-03
+- **Type:** fix
+- **Scope:** `server`, `web`
+- **PR:** [#605](https://github.com/Prism-Shadow/penguin-harness/pull/605)
+
+[English](2026-09-03-steering-returned-on-interrupt.md)
+
+插进运行中 Task、还等着下一轮工具送达的消息,在打断时会被直接丢掉,用户已经打好的那段话也一并消失。现在这条未送达的插话会被退回输入框,可以直接再发。
+
+## 细节
+
+- 核心在运行结束时丢弃自己的 steering 队列,服务端此前也随之丢弃镜像。运行结束时镜像里剩下的恰好是从未送达的那些——条目以流上出现 `[user_steering]` 消息为准出队,而镜像是在流排空之后才读的——所以这些条目改为退回,不再丢弃。
+- 退回的条目随 `task_state` 事件与 SSE 订阅快照以 `returnedSteering` 下发,输入区经排队行的撤回按钮本就在用的同一条通道取回:正文回到输入框,图片与文件附件一并还原,「插话已排队」提示随之消失。
+- 刷新后同样会取回,标签页关掉也不会把消息搁死。
+- 下一次运行开始不清除这些条目:无论之后发生什么,这条消息确实从未送达。只有取回、或运行时条目被空闲淘汰才会移除。
+- 打断前已送达的插话不受影响;子会话的未送达插话仍随其本轮丢弃——它来自模型或智能体面板,没有等着收回它的输入框。
diff --git a/packages/docs/content/web-app.en.md b/packages/docs/content/web-app.en.md
index e5788fb5..6502ccf1 100644
--- a/packages/docs/content/web-app.en.md
+++ b/packages/docs/content/web-app.en.md
@@ -71,7 +71,7 @@ Copy buttons across the app confirm at the button itself: the copy icon flips to
- The "+" menu holds the input add-ons: **image upload**, **file attachment** and goal mode. An attachment can be any type (up to 20 at a time, and by default ≤ 100MB each and 120MB in total — an admin can change both sizes under **System settings → Upload limits**, see below; an oversize pick is refused before it is read, so nothing is uploaded to earn the rejection, and the message names the limit actually in force); selected files show as removable chips above the text body in the order they were picked, and a message with attachments and no text is sendable. On send the files are written into the Session's scratchpad — deleted with the Session — and the message gains an `[attached file: <path>]` line per file, which the conversation renders as an "Attached files" notice: the bytes never enter the conversation, the model opens each file by path with its ordinary file tools;
- Files can also be **dragged onto the chat area** — the conversation and the composer, on the chat page and the draft page alike: while a file drag is over that region a "Drop files to attach" overlay covers it (it hides as soon as the drag moves off; dragging text or anything that isn't a file is ignored), and releasing attaches the whole batch to the composer — images join the pasted-image pipeline, everything else becomes file attachments, with the same type and size validation and the same errors as the "+" menu. Dropping works while a Task is running too (the attachments then send per the mid-run send mode below); goal mode takes dropped images but refuses files with a notice. Only the chat area reacts: dropping a file on the sidebar, the top bar, the docked panels or any page without a composer attaches nothing and shows nothing — it is simply ignored, instead of the browser navigating away to the dropped file;
- Typing `/` opens the slash menu: trigger context compaction (`/compact`), hand the conversation over to another Agent (`/agent`), switch the model (`/model`) — both switch commands appear in an active session only, since a draft has nothing to switch and picks its Agent and model up front — or toggle installed Skills — chosen Skills are sent along with the message in a `[use_skills]` block;
-- While a Task is running the input stays live and the toolbar keeps a single action button: an empty composer shows **Stop**, and typing turns it into **Send**, whose behavior follows the **mid-run send mode** from the toolbar's More-settings popover (a compact extensible settings panel, also available in draft state; the choice is remembered): **Steer** (default) delivers the text **and any attached images** mid-run as a `[user_steering]` user message with the next turn (an image with no caption sends on its own, and the delivered message renders as a steering chip with its images inside it), **Queue** holds the whole message server-side as a follow-up and auto-sends it as an ordinary new message when the run finishes (an "N queued" hint shows near the input until then; the queue survives page reloads). A draft steering cannot carry — selected skills, file attachments, or a staged `/agent` or `/model` pick, with no text and no image — falls back to the queue for that one send, so the button never sits disabled with Stop displaced. Each queued hint line — an undelivered steering message or a queued follow-up — ends in a **recall** control (a curved-back arrow, "Recall") that withdraws the message back into the input box (attachments included) for editing and resending; a steering message that already reached the model can no longer be recalled;
+- While a Task is running the input stays live and the toolbar keeps a single action button: an empty composer shows **Stop**, and typing turns it into **Send**, whose behavior follows the **mid-run send mode** from the toolbar's More-settings popover (a compact extensible settings panel, also available in draft state; the choice is remembered): **Steer** (default) delivers the text **and any attached images** mid-run as a `[user_steering]` user message with the next turn (an image with no caption sends on its own, and the delivered message renders as a steering chip with its images inside it), **Queue** holds the whole message server-side as a follow-up and auto-sends it as an ordinary new message when the run finishes (an "N queued" hint shows near the input until then; the queue survives page reloads). A draft steering cannot carry — selected skills, file attachments, or a staged `/agent` or `/model` pick, with no text and no image — falls back to the queue for that one send, so the button never sits disabled with Stop displaced. Each queued hint line — an undelivered steering message or a queued follow-up — ends in a **recall** control (a curved-back arrow, "Recall") that withdraws the message back into the input box (attachments included) for editing and resending; a steering message that already reached the model can no longer be recalled. When the run ends before a steering message was delivered — pressing Stop while a tool is still running is the usual way — you do not have to reach for that control: the message returns to the input box on its own, attachments and all, ready to edit and send again, so an interrupt never eats what you had already typed;
- **Goal mode** (the "+" menu, or `/goal`) turns the draft into an objective the system loops Tasks against. Attached images ride along and are always sent as scratchpad paths (a goal objective is re-injected as text every round — see [Goal mode](/goal-mode)); text is still required, since a picture alone states no objective, and file attachments are refused. Round 1's bubble shows the attachments in full, later rounds collapse them into a chip that expands on click;
- `/agent` and `/model` stage their pick instead of acting on it: the chosen Agent or model becomes a chip above the text body and nothing is sent yet, so you keep typing — Enter/Send is what hands the conversation over (a new chat for that Agent) or forks it onto the chosen model, carrying the text along; with an empty composer a default message is filled in, and the chip's × cancels. Both chips are cached with the draft, so they survive a reload or a trip to another conversation together with the text. A model fork additionally waits for the Session to be idle — it continues from the Session's Trace, which a running turn or a compaction is still writing — and a line above the composer says so while it waits;
- When human approval is required, tool calls show inline allow/deny buttons in the message stream; the approval mode can be changed mid-Session;
diff --git a/packages/docs/content/web-app.zh.md b/packages/docs/content/web-app.zh.md
index dfff116b..7d1b959f 100644
--- a/packages/docs/content/web-app.zh.md
+++ b/packages/docs/content/web-app.zh.md
@@ -71,7 +71,7 @@ penguin web
- 「+」菜单收纳输入附加项:**上传图片**、**上传文件**与目标模式。附件不限类型(一次最多 20 个,默认单个 ≤ 100MB、合计 ≤ 120MB——两个尺寸均可由管理员在**系统设置 → 上传限制**中调整,见下文;超限的文件在读取前即被拒绝,不会先上传再报错,提示中会写出当前生效的上限),已选文件按选择顺序以可移除的小卡片显示在文本框上方;只带附件、没有正文也可发送。发送时文件写入该 Session 的 scratchpad(随 Session 一并删除),消息里每个文件追加一行 `[attached file: <path>]`,对话中渲染为一条「附加文件」提示:文件内容不进入对话,模型用普通文件工具按路径读取;
- 也可以把文件**拖拽到聊天区**上传(聊天区即对话与输入框所在区域,会话页与草稿页皆可):文件拖到该区域上方时显示覆盖该区域的「松开以添加附件」浮层(拖离即消失,拖动文本等非文件内容不触发),松开即把整批文件附加到输入框——图片走粘贴图片的同一管线,其余文件成为附件,类型与大小校验及报错与「+」菜单一致。任务运行中同样可以拖入(附件按下述运行中发送方式送出);目标模式下拖入的图片照常附加、文件会以提示拒绝。只有聊天区会响应:把文件放到侧边栏、顶栏、右侧停靠面板或任何没有输入框的页面上,既不显示浮层也不会添加附件,只是被直接忽略,同时不会让浏览器跳转打开该文件;
- 输入 `/` 打开快捷菜单:触发上下文压缩(`/compact`)、把会话交接给其他 Agent(`/agent`)、切换模型(`/model`)——两个切换命令都只在进行中的会话里提供,草稿没有可切换的对话,Agent 与模型本就在草稿页选定——或勾选已安装的 Skill——所选 Skill 会以 `[use_skills]` 块随消息发送;
-- Task 运行期间输入框保持可用,工具条只保留一个操作按钮:输入框为空时是**停止**,一旦输入内容即变为**发送**,其行为遵循工具条「更多设置」弹出分组中的**运行中发送方式**(一个可扩展的设置面板,草稿态同样可设,选择会被记忆):**插话**(默认)把文字以 `[user_steering]` 用户消息随下一轮送达运行中的 Agent;**排队** 把整条消息暂存在服务端,本轮结束后自动作为普通新消息发出(期间在输入框附近显示「N 条已排队」提示;队列存放在服务端,刷新页面不丢失)。每条排队提示——未送达的插话或排队中的跟进消息——行尾都带一枚**撤回**按钮(一个向回弯的箭头图标),可把消息(含附件)撤回到输入框编辑后重新发送;插话一旦送达模型即不可撤回;
+- Task 运行期间输入框保持可用,工具条只保留一个操作按钮:输入框为空时是**停止**,一旦输入内容即变为**发送**,其行为遵循工具条「更多设置」弹出分组中的**运行中发送方式**(一个可扩展的设置面板,草稿态同样可设,选择会被记忆):**插话**(默认)把文字以 `[user_steering]` 用户消息随下一轮送达运行中的 Agent;**排队** 把整条消息暂存在服务端,本轮结束后自动作为普通新消息发出(期间在输入框附近显示「N 条已排队」提示;队列存放在服务端,刷新页面不丢失)。每条排队提示——未送达的插话或排队中的跟进消息——行尾都带一枚**撤回**按钮(一个向回弯的箭头图标),可把消息(含附件)撤回到输入框编辑后重新发送;插话一旦送达模型即不可撤回。运行在插话送达之前结束时(工具跑着的时候按停止是最常见的情形)不用你动手:这条插话会自动回到输入框,附件一并还原,改完可以直接再发——打断不会吃掉已经打好的话;
- `/agent` 与 `/model` 都是暂存而非立即生效:选中的 Agent 或模型只在文本区上方留下一枚 chip,此时不发送任何内容,可以继续输入——按 Enter / 点发送才真正交接(为该 Agent 新开一个对话)或换用所选模型继续本对话,输入的文字随之带走;正文为空时自动填入默认消息,点 chip 上的 × 即可取消。两枚 chip 都随草稿缓存,刷新页面或切到别的会话再回来时与文字一同恢复;其中切换模型还需等待会话空闲——新会话要从本会话的 Trace 接续,而运行中的一轮或压缩仍在写入——等待期间输入框上方会给出说明;
- 需要人工审批时,工具调用在消息流中内联显示“允许 / 拒绝”按钮;审批模式在会话中途可随时调整;
- 引擎在重连退避等待(≥2 秒)期间,重试提示行会实时倒计时到下一次尝试,并内联提供**立即重试**(跳过剩余等待)与**放弃**(普通中断)两个按钮;
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index 9b8a974b..10b332a9 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -2201,6 +2201,13 @@ export type ServerEvent =
queued?: number;
/** Steering messages queued but not yet delivered (absent = none): lets the composer's hint and its content survive reloads. */
pendingSteering?: PendingSteeringInfo[];
+ /**
+ * Steering the run ended without delivering (absent = none) — an interrupt while a tool
+ * was running is the ordinary way to produce one. Handed back rather than discarded: the
+ * composer recalls each by the same handle and restores it into the draft, so the typed
+ * message returns to the input box instead of being lost.
+ */
+ returnedSteering?: PendingSteeringInfo[];
/** Queued follow-up tasks awaiting auto-start (absent = none): per-entry content + recall handle, alongside the `queued` count. */
pendingFollowUps?: PendingFollowUpInfo[];
/**
diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.ts
index 6c6928af..2219c44d 100644
--- a/packages/server/src/http/routes/sessions.ts
+++ b/packages/server/src/http/routes/sessions.ts
@@ -852,6 +852,7 @@ export function sessionsRoutes(deps: AppDeps): Hono<AppEnv> {
// caused by a stale running/idle in the list; followed by replaying all still-pending
// approval requests.
const pendingSteering = deps.manager.pendingSteeringOf(row.sessionId);
+ const returnedSteering = deps.manager.returnedSteeringOf(row.sessionId);
const pendingFollowUps = deps.manager.pendingFollowUpsOf(row.sessionId);
const subagents = deps.manager.subagentsOf(row.sessionId);
const initialEvents: ServerEvent[] = [
@@ -863,6 +864,9 @@ export function sessionsRoutes(deps: AppDeps): Hono<AppEnv> {
// snapshot too, so the composer's queued hints and the panel's running marks
// survive a reload.
...(pendingSteering.length > 0 ? { pendingSteering } : {}),
+ // Undelivered steering handed back by a finished run rides the snapshot as well, so a
+ // reload still returns the message to the composer instead of stranding it.
+ ...(returnedSteering.length > 0 ? { returnedSteering } : {}),
...(pendingFollowUps.length > 0 ? { pendingFollowUps } : {}),
...(subagents.length > 0 ? { subagents } : {}),
},
diff --git a/packages/server/src/runtime/session-manager.ts b/packages/server/src/runtime/session-manager.ts
index 64401260..fc4f6440 100644
--- a/packages/server/src/runtime/session-manager.ts
+++ b/packages/server/src/runtime/session-manager.ts
@@ -422,6 +422,20 @@ interface RuntimeEntry {
* every `task_state`; the rest is the recall handle (see recallSteering).
*/
pendingSteering: PendingSteeringEntry[];
+ /**
+ * Steering the run ended without ever delivering — handed back to the user instead of
+ * discarded (#287 follow-up). An interrupt mid-tool-call is the ordinary way to get here:
+ * core drops its queue when the run exits, so the message would otherwise vanish with the
+ * text the user had already typed.
+ *
+ * Entries move here from `pendingSteering` when the run exits and stay recallable by the
+ * same handle, so the composer pulls them back into its draft (auto-recall on observing
+ * them, a reload included). They are deliberately NOT cleared when the next run starts:
+ * the message was never delivered whatever happens later, and dropping it there would
+ * reintroduce exactly the loss this list exists to prevent. Only a recall — or the entry's
+ * idle eviction — removes one.
+ */
+ returnedSteering: PendingSteeringEntry[];
/** Timestamp of last activity (refreshed on load / status flip / drive completion), used for idle-eviction checks. */
lastActivityMs: number;
}
@@ -587,6 +601,11 @@ export class SessionManager {
return (this.entries.get(sessionId)?.pendingSteering ?? []).map((p) => p.info);
}
+ /** Steering a finished run never delivered, waiting for the composer to take it back (see RuntimeEntry.returnedSteering). */
+ returnedSteeringOf(sessionId: string): PendingSteeringInfo[] {
+ return (this.entries.get(sessionId)?.returnedSteering ?? []).map((p) => p.info);
+ }
+
/**
* Live subagent children of an ACTIVE runtime entry (empty when the session is not loaded
* — after a restart there is no in-process child left to report, so empty is the truth).
@@ -711,6 +730,7 @@ export class SessionManager {
pendingInputs: [],
pendingBootstrap: [],
pendingSteering: [],
+ returnedSteering: [],
lastActivityMs: Date.now(),
});
// Same wiring as ensureEntry: adopt IS the entry path for a session created in this
@@ -1210,19 +1230,35 @@ export class SessionManager {
*/
recallSteering(sessionId: string, steerId: string): RecallStore {
const entry = this.entries.get(sessionId);
- const i = entry?.pendingSteering.findIndex((p) => p.info.id === steerId) ?? -1;
- const pending = i >= 0 ? entry!.pendingSteering[i]! : undefined;
- if (!entry || !pending || !(entry.session.unsteer?.(pending.input) ?? false)) {
- throw new HttpError(
- 409,
- "not_pending",
- "This steering message was already delivered to the model and can no longer be recalled.",
- );
+ if (entry) {
+ const queued = entry.pendingSteering.findIndex((p) => p.info.id === steerId);
+ if (queued >= 0) {
+ const pending = entry.pendingSteering[queued]!;
+ // Still queued on a live run: core decides, since the mirror can lag a delivery that
+ // has not reached the stream yet.
+ if (entry.session.unsteer?.(pending.input) ?? false) {
+ entry.pendingSteering.splice(queued, 1);
+ entry.lastActivityMs = Date.now();
+ this.publishState(entry, entry.status);
+ return pending.recall;
+ }
+ }
+ // Handed back when the run exited without delivering it: core's queue is gone, so there
+ // is nothing to unsteer and the mirror is the only authority left — it holds exactly
+ // what the drained stream never showed as delivered (see RuntimeEntry.returnedSteering).
+ const returned = entry.returnedSteering.findIndex((p) => p.info.id === steerId);
+ if (returned >= 0) {
+ const [taken] = entry.returnedSteering.splice(returned, 1);
+ entry.lastActivityMs = Date.now();
+ this.publishState(entry, entry.status);
+ return taken!.recall;
+ }
}
- entry.pendingSteering.splice(i, 1);
- entry.lastActivityMs = Date.now();
- this.publishState(entry, entry.status);
- return pending.recall;
+ throw new HttpError(
+ 409,
+ "not_pending",
+ "This steering message was already delivered to the model and can no longer be recalled.",
+ );
}
/**
@@ -1596,6 +1632,7 @@ export class SessionManager {
pendingInputs: [],
pendingBootstrap: [],
pendingSteering: [],
+ returnedSteering: [],
lastActivityMs: Date.now(),
};
this.entries.set(currentId, entry);
@@ -1831,9 +1868,15 @@ export class SessionManager {
entry.abort = null;
entry.running = null;
// The run is over, so core has discarded any undelivered steering (see ContextEngine's
- // steeringQueue) — drop the mirror with it; the idle publish below broadcasts the
- // now-empty state.
- entry.pendingSteering = [];
+ // steeringQueue). What is still in the mirror was therefore never delivered — entries
+ // are shifted out as their `[user_steering]` message appears on the stream, and this
+ // runs after that stream is drained — so hand it back to the user rather than dropping
+ // it: the composer recalls it into its draft. Interrupting while a tool runs is the
+ // ordinary way to get here, and the typed message must survive it.
+ if (entry.pendingSteering.length > 0) {
+ entry.returnedSteering = [...entry.returnedSteering, ...entry.pendingSteering];
+ entry.pendingSteering = [];
+ }
entry.lastActivityMs = Date.now();
// Run-end stamp (see the run-start counterpart at the top of drive). Guarded like
// every other write in this finally: what follows — the idle broadcast and the
@@ -1949,6 +1992,9 @@ export class SessionManager {
...(entry.pendingSteering.length > 0
? { pendingSteering: entry.pendingSteering.map((p) => p.info) }
: {}),
+ ...(entry.returnedSteering.length > 0
+ ? { returnedSteering: entry.returnedSteering.map((p) => p.info) }
+ : {}),
...(entry.followUps.length > 0
? { pendingFollowUps: entry.followUps.map(followUpInfo) }
: {}),
diff --git a/packages/server/test/steer.test.ts b/packages/server/test/steer.test.ts
index 49cb7a7d..f892cd68 100644
--- a/packages/server/test/steer.test.ts
+++ b/packages/server/test/steer.test.ts
@@ -19,6 +19,7 @@ import {
assistantText,
scratchpadDir,
toolCall,
+ userSteeringText,
userText,
} from "@prismshadow/penguin-core";
import type { ApproveFn, OmniMessage } from "@prismshadow/penguin-core";
@@ -318,6 +319,97 @@ describe("steer route", () => {
await waitFor(() => t.deps.manager.statusOf(SID) === "idle");
});
+ it("an interrupt hands undelivered steering back instead of dropping it, and the recall still returns it", async () => {
+ // The user's case: the model is mid tool call (this run parks on its approval) when the
+ // interrupt lands. Core drops its steering queue as the run exits, so before this the
+ // queued message — and everything the user had typed into it — vanished with the run.
+ await t.deps.manager.startTask(SID, [userText("go")]);
+ await waitFor(() => t.deps.manager.pendingApprovalCount(SID) === 1);
+
+ const data = `data:text/plain;base64,${Buffer.from("keep my notes").toString("base64")}`;
+ const posted = await api.post(`/api/sessions/${SID}/steer`, {
+ text: " wait, do it differently ",
+ files: [{ fileName: "notes.txt", dataUrl: data }],
+ });
+ expect(posted.status).toBe(202);
+ const [queued] = t.deps.manager.pendingSteeringOf(SID);
+ expect(queued).toEqual({
+ id: expect.any(String),
+ text: "wait, do it differently",
+ images: 0,
+ files: 1,
+ });
+
+ expect(t.deps.manager.abortTask(SID)).toBe(true);
+ await waitFor(() => t.deps.manager.statusOf(SID) === "idle");
+
+ // Off the queue (nothing is going to deliver it now) but not gone: handed back, under the
+ // same id, so the composer can take it from there.
+ expect(t.deps.manager.pendingSteeringOf(SID)).toEqual([]);
+ expect(t.deps.manager.returnedSteeringOf(SID)).toEqual([queued]);
+
+ // And the recall returns the whole message, attachment included, exactly as a queued one
+ // would have — this is what puts it back in the input box.
+ const res = await api.delete(`/api/sessions/${SID}/steer/${queued!.id}`);
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({
+ text: "wait, do it differently",
+ images: [],
+ files: [{ fileName: "notes.txt", dataUrl: data }],
+ });
+ expect(t.deps.manager.returnedSteeringOf(SID)).toEqual([]);
+
+ // Taken once only: a second attempt (another tab racing the same handback) is a 409.
+ const again = await api.delete(`/api/sessions/${SID}/steer/${queued!.id}`);
+ expect(again.status).toBe(409);
+ expect(((await again.json()) as { error: { code: string } }).error.code).toBe("not_pending");
+ });
+
+ it("steering the run DID deliver is not handed back", async () => {
+ // The mirror is shifted as each [user_steering] message appears on the stream, and the
+ // handback runs after that stream is drained. A delivered message must therefore not
+ // return to the composer as though the user still owed it.
+ const delivering: OmniMessage[][] = [];
+ const sid2 = "session-2026-07-06-10-00-00-ccdd0002";
+ const row: SessionRow = {
+ sessionId: sid2,
+ projectId: "steerer-default_project",
+ agentId: "default_agent",
+ modelId: "m1",
+ provider: "custom",
+ workspace: "/tmp/w",
+ approvalMode: "always-ask",
+ title: null,
+ createdAt: new Date().toISOString(),
+ lastActiveAt: new Date().toISOString(),
+ };
+ t.deps.sessionsRepo.insert(row);
+ t.deps.manager.adopt(row, {
+ ...steeringFakeSession(sid2, delivering),
+ async *run(_input: OmniMessage[], opts: { approve: ApproveFn; signal: AbortSignal }) {
+ const tc = toolCall({ name: "exec_command", arguments: "{}", toolCallId: "tc-steer" });
+ yield tc;
+ const decision = await opts.approve(tc);
+ yield approvalDecision(decision, "tc-steer");
+ // The delivery itself: core emits one such message per queued entry.
+ yield userText(userSteeringText("already gone"));
+ yield assistantText("done");
+ },
+ });
+
+ await t.deps.manager.startTask(sid2, [userText("go")]);
+ await waitFor(() => t.deps.manager.pendingApprovalCount(sid2) === 1);
+ await api.post(`/api/sessions/${sid2}/steer`, { text: "already gone" });
+ expect(t.deps.manager.pendingSteeringOf(sid2)).toHaveLength(1);
+
+ t.deps.manager.decideApproval(sid2, "tc-steer", "allow");
+ await waitFor(() => t.deps.manager.statusOf(sid2) === "idle");
+
+ // Shifted out by the delivery, so the run had nothing left to hand back.
+ expect(t.deps.manager.pendingSteeringOf(sid2)).toEqual([]);
+ expect(t.deps.manager.returnedSteeringOf(sid2)).toEqual([]);
+ });
+
it("recall after delivery → 409 not_pending; the mirror entry is left for the stream shift to retire", async () => {
await t.deps.manager.startTask(SID, [userText("go")]);
await waitFor(() => t.deps.manager.pendingApprovalCount(SID) === 1);
diff --git a/packages/web/e2e/steer-abort.spec.mjs b/packages/web/e2e/steer-abort.spec.mjs
new file mode 100644
index 00000000..d165d836
--- /dev/null
+++ b/packages/web/e2e/steer-abort.spec.mjs
@@ -0,0 +1,73 @@
+/**
+ * Interrupting while a tool runs must not eat a queued steering message.
+ *
+ * Core drops its steering queue as the run exits, so a message queued for "the next tool
+ * round" used to vanish on abort, taking whatever the user had typed into it with it. The
+ * server now hands the undelivered entry back and the composer takes it into its draft, so
+ * the message returns to the input box and can be sent again.
+ *
+ * The LLM is mock-llm.mjs's "slow stream test": a ~8s exec_command keeps the Task busy, which
+ * is the window this whole case lives in — steer, then stop before delivery.
+ */
+import { test, expect } from "@playwright/test";
+import { provisionAndLogin } from "./auth.mjs";
+
+const BASE = process.env.BASE_URL;
+const MOCK = process.env.MOCK_URL;
+const U = "steerabortuser";
+const P = "password123";
+const STEER_TEXT = "steer: actually stop and summarize instead";
+
+/** Create a session for the user's auto-provisioned project (models PUT is idempotent). */
+async function createSession(page, approvalMode) {
+ const projects = await (await page.request.get(`${BASE}/api/projects`)).json();
+ const projectId = projects.projects[0].projectId;
+ const put = await page.request.put(`${BASE}/api/projects/${projectId}/models`, {
+ data: {
+ defaultModel: { provider: "custom", modelId: "claude-4-8" },
+ models: [
+ {
+ provider: "custom",
+ modelId: "claude-4-8",
+ apiKey: "sk-mock",
+ baseUrl: MOCK,
+ contextWindow: 200000,
+ },
+ ],
+ },
+ });
+ expect(put.ok(), "put models").toBeTruthy();
+ const res = await page.request.post(
+ `${BASE}/api/projects/${projectId}/agents/default_agent/sessions`,
+ { data: { provider: "custom", modelId: "claude-4-8", approvalMode } },
+ );
+ expect(res.ok(), `create session: ${await res.text()}`).toBeTruthy();
+ return (await res.json()).session.sessionId;
+}
+
+test("interrupting mid-tool-call returns the queued steering message to the composer", async ({
+ page,
+}) => {
+ await provisionAndLogin(page.request, U, P);
+ const sessionId = await createSession(page, "always-ask");
+ await page.goto(`${BASE}/chat/${sessionId}`);
+ const ta = page.locator("textarea").first();
+ await ta.waitFor();
+ await ta.fill("slow stream test");
+ await page.getByRole("button", { name: "发送" }).click();
+ await expect(page.getByText("exec_command").first()).toBeVisible();
+ await page.getByRole("button", { name: "允许" }).click();
+
+ // Steer while the ~8s tool run keeps the Task busy: queued, not yet delivered.
+ await ta.fill(STEER_TEXT);
+ await ta.press("Enter");
+ await expect(page.getByText(`插话已排队,将随下一轮送达:${STEER_TEXT}`)).toBeVisible();
+ await expect(ta).toHaveValue("");
+
+ // Interrupt while the tool is still running — the case that used to lose the message.
+ await page.getByRole("button", { name: "停止" }).click();
+
+ // It comes back to the input box, ready to send again, and stops claiming to be queued.
+ await expect(ta).toHaveValue(STEER_TEXT, { timeout: 15_000 });
+ await expect(page.getByText(/插话已排队/)).toHaveCount(0);
+});
diff --git a/packages/web/src/features/chat/chat-input.tsx b/packages/web/src/features/chat/chat-input.tsx
index 5c5c5c31..c22cd96f 100644
--- a/packages/web/src/features/chat/chat-input.tsx
+++ b/packages/web/src/features/chat/chat-input.tsx
@@ -768,6 +768,7 @@ export function ChatInput({
onSteer,
steeringDeliveredCount,
pendingSteering = [],
+ returnedSteering = [],
onRecallSteering,
onQueueFollowUp,
queuedFollowUps = 0,
@@ -842,6 +843,13 @@ export function ChatInput({
* reloads (#136). The local post-202 flag only bridges until the first event arrives.
*/
pendingSteering?: PendingSteeringInfo[];
+ /**
+ * Steering a finished run never delivered — an interrupt while a tool was running is the
+ * ordinary way to produce one. This component takes each back into the draft as soon as it
+ * sees it, through the same recall channel a queued line's button uses, so the typed message
+ * lands in the input box instead of disappearing with the run.
+ */
+ returnedSteering?: PendingSteeringInfo[];
/**
* Recall an undelivered steering message (#287): resolves to its original content, which
* this component restores into the draft (text / images / files), or null when the recall
@@ -1315,6 +1323,29 @@ export function ChatInput({
}
};
+ /**
+ * Steering a finished run never delivered returns to the draft on its own. Interrupting
+ * while a tool is still running is the ordinary way to produce one: core drops its queue as
+ * the run exits, so without this the message — and the text the user had already typed into
+ * it — would simply disappear.
+ *
+ * It goes through the same recall channel the queued lines' button uses, so the merge into
+ * the draft, the attachment restore and the one-at-a-time guard are all the existing ones.
+ * Ids are marked BEFORE the request, not after: a recall that loses the race to another tab
+ * answers 409, and a retry on the next render would spin.
+ */
+ const autoRecalledIds = useRef<Set<string>>(new Set());
+ useEffect(() => {
+ if (!onRecallSteering || busy || recallingId !== null) return;
+ // Oldest first, matching the order the user typed them.
+ const next = returnedSteering.find((p) => !autoRecalledIds.current.has(p.id));
+ if (!next) return;
+ autoRecalledIds.current.add(next.id);
+ void recallQueued(next.id, onRecallSteering);
+ // recallQueued is re-created every render; depending on it would re-run this on each one.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [returnedSteering, onRecallSteering, busy, recallingId]);
+
/** Toggle a skill on/off (shared by dropdown option clicks and the slash skill command); the change callback lets the parent write it into the draft. */
const toggleSkill = useCallback(
(name: string) => {
diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsx
index 0f0cf919..b0cffd19 100644
--- a/packages/web/src/features/chat/chat-page.tsx
+++ b/packages/web/src/features/chat/chat-page.tsx
@@ -1604,6 +1604,7 @@ export function ChatPage() {
// "queued" indicator up until this count increases (i.e. the steering message arrived).
steeringDeliveredCount={stream.model.items.filter((i) => i.kind === "user_steering").length}
pendingSteering={stream.pendingSteering}
+ returnedSteering={stream.returnedSteering}
onRecallSteering={onRecallSteering}
onQueueFollowUp={onQueueFollowUp}
queuedFollowUps={stream.queuedFollowUps}
diff --git a/packages/web/src/features/chat/use-session-stream.ts b/packages/web/src/features/chat/use-session-stream.ts
index 3517be68..9f0838ff 100644
--- a/packages/web/src/features/chat/use-session-stream.ts
+++ b/packages/web/src/features/chat/use-session-stream.ts
@@ -65,6 +65,8 @@ export interface SessionStreamState {
queuedFollowUps: number;
/** Steering messages queued on the server but not yet delivered (from task_state events): keeps the composer's hint and its content across reloads. */
pendingSteering: PendingSteeringInfo[];
+ /** Steering a finished run never delivered (from task_state events): the composer takes each back into its draft, so an interrupt never eats the typed message. */
+ returnedSteering: PendingSteeringInfo[];
/** Queued follow-up tasks (from task_state events): per-entry content + recall handle; empty on old servers (the count above still renders a plain hint). */
pendingFollowUps: PendingFollowUpInfo[];
/**
@@ -109,6 +111,7 @@ export function useSessionStream(
const [taskState, setTaskState] = useState<SessionStatus>(initialStatus);
const [queuedFollowUps, setQueuedFollowUps] = useState(0);
const [pendingSteering, setPendingSteering] = useState<PendingSteeringInfo[]>([]);
+ const [returnedSteering, setReturnedSteering] = useState<PendingSteeringInfo[]>([]);
const [pendingFollowUps, setPendingFollowUps] = useState<PendingFollowUpInfo[]>([]);
const [subagents, setSubagents] = useState<SubagentRuntimeInfo[]>([]);
const [error, setError] = useState<string | null>(null);
@@ -189,6 +192,7 @@ export function useSessionStream(
setTaskState("idle");
setQueuedFollowUps(0);
setPendingSteering([]);
+ setReturnedSteering([]);
setPendingFollowUps([]);
setSubagents([]);
setLoading(false);
@@ -207,6 +211,7 @@ export function useSessionStream(
setGoal(null);
setQueuedFollowUps(0);
setPendingSteering([]);
+ setReturnedSteering([]);
setPendingFollowUps([]);
setSubagents([]);
setPendingTick((t) => t + 1);
@@ -236,6 +241,7 @@ export function useSessionStream(
onTaskState: setTaskState,
onQueuedFollowUps: setQueuedFollowUps,
onPendingSteering: setPendingSteering,
+ onReturnedSteering: setReturnedSteering,
onPendingFollowUps: setPendingFollowUps,
onSubagents: setSubagents,
onLoading: setLoading,
@@ -313,6 +319,7 @@ export function useSessionStream(
taskState,
queuedFollowUps,
pendingSteering,
+ returnedSteering,
pendingFollowUps,
subagents,
pendingApprovals: controllerRef.current?.pendingApprovals ?? EMPTY_PENDING,
diff --git a/packages/web/src/lib/omni/stream-controller.ts b/packages/web/src/lib/omni/stream-controller.ts
index 4ceae07f..2c302fdd 100644
--- a/packages/web/src/lib/omni/stream-controller.ts
+++ b/packages/web/src/lib/omni/stream-controller.ts
@@ -123,6 +123,8 @@ export interface StreamControllerDeps {
onQueuedFollowUps?: (count: number) => void;
/** Undelivered steering messages carried on task_state events (absent = none): keeps the composer's "steering queued" hint alive across reloads. */
onPendingSteering?: (items: PendingSteeringInfo[]) => void;
+ /** Steering a finished run never delivered: the composer takes it back into its draft. */
+ onReturnedSteering?: (items: PendingSteeringInfo[]) => void;
/** Queued follow-up tasks carried on task_state events (absent = none): each entry's content + recall handle, alongside the count. */
onPendingFollowUps?: (items: PendingFollowUpInfo[]) => void;
/** Live subagent children carried on task_state events (absent = none): the panel's structural running marks — no tool-output text parsing for live sessions. */
@@ -312,6 +314,7 @@ export function createStreamController(deps: StreamControllerDeps): StreamContro
deps.onTaskState(ev.state);
deps.onQueuedFollowUps?.(ev.queued ?? 0);
deps.onPendingSteering?.(ev.pendingSteering ?? []);
+ deps.onReturnedSteering?.(ev.returnedSteering ?? []);
deps.onPendingFollowUps?.(ev.pendingFollowUps ?? []);
deps.onSubagents?.(ev.subagents ?? []);
if (ev.state === "idle") {
@@ -627,6 +630,7 @@ export function createStreamController(deps: StreamControllerDeps): StreamContro
deps.onTaskState(ev.state);
deps.onQueuedFollowUps?.(ev.queued ?? 0);
deps.onPendingSteering?.(ev.pendingSteering ?? []);
+ deps.onReturnedSteering?.(ev.returnedSteering ?? []);
deps.onPendingFollowUps?.(ev.pendingFollowUps ?? []);
}
buffer.push({ kind: "server", ev, id: eventId });
diff --git a/packages/web/test/stream-controller.test.ts b/packages/web/test/stream-controller.test.ts
index 21e7ddca..defc6606 100644
--- a/packages/web/test/stream-controller.test.ts
+++ b/packages/web/test/stream-controller.test.ts
@@ -46,6 +46,7 @@ interface Harness {
controller: StreamController;
states: SessionStatus[];
pendingSteering: PendingSteeringInfo[][];
+ returnedSteering: PendingSteeringInfo[][];
pendingFollowUps: PendingFollowUpInfo[][];
errors: Array<string | null>;
loadings: boolean[];
@@ -73,6 +74,7 @@ function createHarness(): Harness {
}> = [];
const states: SessionStatus[] = [];
const pendingSteering: PendingSteeringInfo[][] = [];
+ const returnedSteering: PendingSteeringInfo[][] = [];
const pendingFollowUps: PendingFollowUpInfo[][] = [];
const errors: Array<string | null> = [];
const loadings: boolean[] = [];
@@ -92,6 +94,7 @@ function createHarness(): Harness {
}),
onTaskState: (s) => states.push(s),
onPendingSteering: (items) => pendingSteering.push(items),
+ onReturnedSteering: (items) => returnedSteering.push(items),
onPendingFollowUps: (items) => pendingFollowUps.push(items),
onLoading: (l) => loadings.push(l),
onError: (e) => errors.push(e),
@@ -103,6 +106,7 @@ function createHarness(): Harness {
controller,
states,
pendingSteering,
+ returnedSteering,
pendingFollowUps,
errors,
loadings,
@@ -219,6 +223,20 @@ describe("in-stream task_state is the authoritative running state (history-closi
expect(h.pendingSteering).toEqual([[{ id: "st-1", text: "hold on", images: 0, files: 1 }], []]);
});
+ it("reports steering the run handed back, so the composer can take it into its draft", async () => {
+ const h = createHarness();
+ void h.controller.load();
+ // The interrupt case: the run went idle and reported the message it never delivered.
+ h.controller.handleServer({
+ type: "task_state",
+ state: "idle",
+ returnedSteering: [{ id: "st-1", text: "wait", images: 0, files: 1 }],
+ });
+ // Once the composer has taken it, the next event omits the field — reported as empty.
+ h.controller.handleServer({ type: "task_state", state: "idle" });
+ expect(h.returnedSteering).toEqual([[{ id: "st-1", text: "wait", images: 0, files: 1 }], []]);
+ });
+
it("reports the queued follow-up list from task_state, and its absence as empty", async () => {
const h = createHarness();
void h.controller.load();