A local-first multi-agent app development platform, built on PenguinHarness
feat(core,server,web): recall queued steering and follow-up messages into the composer (#321)
Yaowei Zhenge16e9552e3b6
diff --git a/changelog/unreleased/2026-08-16-recall-queued-messages.md b/changelog/unreleased/2026-08-16-recall-queued-messages.mdnew file mode 100644index 00000000..9292a9a3--- /dev/null+++ b/changelog/unreleased/2026-08-16-recall-queued-messages.md@@ -0,0 +1,28 @@+# Recall queued steering and follow-up messages into the composer++- **Date:** 2026-08-16+- **Type:** feature+- **Scope:** `core`, `server`, `web`+- **PR:** [#321](https://github.com/Prism-Shadow/penguin-harness/pull/321)+- **Issue:** [#287](https://github.com/Prism-Shadow/penguin-harness/issues/287)++[中文版](2026-08-16-recall-queued-messages.zh.md)++A mid-run message that is still waiting — an undelivered steering message, or a follow-up queued behind the current run — can now be recalled back into the input box, edited, and resent. The implementation grew out of the draft [#304](https://github.com/Prism-Shadow/penguin-harness/pull/304) opened by @Myriad-Dreamin.++## Web App++- Every queued hint line above the composer — the undelivered-steering mirror and the new per-entry follow-up list — ends in an icon-only recall control: a curved-back arrow with no label text, drawn at the size and gray the other icon controls on a hint row use, carrying "Recall" as its accessible name and a tooltip saying what it does.+- Clicking it withdraws the message server-side and restores its original content into the draft. The text lands in front of whatever is currently typed, merged against the textarea's live value so keystrokes made while the request is in flight survive, and images and file attachments come back as composer chips (files are read back from the Session scratchpad, whose copies are then deleted). A recalled follow-up also restores the per-turn thinking level it was queued with, and a recall that brings file attachments back releases a staged goal chip, since a goal draft cannot carry files.+- The recall controls are disabled while a send is in flight, and a recall the server refuses surfaces as a toast while the hint retires on its own.+- Every recall re-broadcasts `task_state`, so the hint line disappears in the other tabs too — including the tab that originally sent the message, which drops its local "steering queued" bridge as soon as the server's mirror has arrived.++## Server++- `DELETE /api/sessions/:id/steer/:steerId` and `DELETE /api/sessions/:id/follow-ups/:followUpId` withdraw a waiting message and return its original content `{text, images, files}`, the follow-up's with its `thinkingLevel`.+- The recall handles ride `task_state` events: `pendingSteering` entries gained an `id`, and the new `pendingFollowUps` field lists each queued follow-up's content next to the existing `queued` count. The SSE subscribe snapshot carries `pendingFollowUps` as well, which is what rebuilds the hint lines after a reload.+- A steering message that already reached the model, and a follow-up that already auto-started, answer 409 `not_pending`. A recall landing in the gap between a run going idle and the follow-up drain's locked dequeue wins exactly once, and the drain then starts nothing.++## Core++- `ContextEngine` and `Session` gained `unsteer(input)`, which withdraws a queued steering input, matched by identity, before delivery and refuses once the queue has drained.diff --git a/changelog/unreleased/2026-08-16-recall-queued-messages.zh.md b/changelog/unreleased/2026-08-16-recall-queued-messages.zh.mdnew file mode 100644index 00000000..27dac1b1--- /dev/null+++ b/changelog/unreleased/2026-08-16-recall-queued-messages.zh.md@@ -0,0 +1,28 @@+# 将排队中的 steering 与后续消息撤回到输入框++- **Date:** 2026-08-16+- **Type:** feature+- **Scope:** `core`, `server`, `web`+- **PR:** [#321](https://github.com/Prism-Shadow/penguin-harness/pull/321)+- **Issue:** [#287](https://github.com/Prism-Shadow/penguin-harness/issues/287)++[English](2026-08-16-recall-queued-messages.md)++运行途中仍在等待的消息——尚未投递的 steering 消息,或排在当前运行之后的后续消息——现在可以撤回到输入框,编辑之后重新发送。这份实现脱胎于 @Myriad-Dreamin 提出的草稿 [#304](https://github.com/Prism-Shadow/penguin-harness/pull/304)。++## Web App++- 输入框上方的每一条排队提示行——尚未投递的 steering 镜像,以及新增的逐条后续消息列表——末尾都带一个纯图标的撤回控件:一枚向后弯回的箭头,不带文字标签,尺寸与灰度沿用提示行上其他图标控件,无障碍名称为「Recall」,并配一个说明其作用的 tooltip。+- 点击它会在服务端撤下这条消息,并把它原本的内容恢复进草稿。文本落在当前已输入内容的前面,并与文本框的实时值合并,因此请求在途期间敲下的字不会被覆盖;图片与文件附件则以输入框附件条的形式回来(文件从 Session scratchpad 读回,那里的副本随后删除)。撤回一条后续消息还会恢复它排队时携带的单轮思考档位;若撤回带回了文件附件,暂存的 goal 标签会被释放,因为 goal 草稿不能携带文件。+- 发送在途期间撤回控件置为禁用;服务端拒绝的撤回以 toast 呈现,提示行则自行退场。+- 每次撤回都会重新广播 `task_state`,于是提示行在其他标签页里也会消失——包括最初发出这条消息的那个标签页,它在服务端的镜像到达后就撤下本地的「steering 已排队」桥接。++## Server++- `DELETE /api/sessions/:id/steer/:steerId` 与 `DELETE /api/sessions/:id/follow-ups/:followUpId` 撤下一条仍在等待的消息,并返回它原本的内容 `{text, images, files}`,后续消息还会带上它的 `thinkingLevel`。+- 撤回所需的句柄随 `task_state` 事件下发:`pendingSteering` 的条目新增了 `id`,新增的 `pendingFollowUps` 字段在既有的 `queued` 计数旁列出每条排队后续消息的内容。SSE 订阅时的快照同样携带 `pendingFollowUps`,页面重新加载后正是靠它重建这些提示行。+- 已经送达模型的 steering 消息,以及已经自动开跑的后续消息,都回 409 `not_pending`。落在运行转入空闲与后续消息 drain 加锁出队之间那道缝隙里的撤回恰好只成功一次,drain 随后不会启动任何任务。++## Core++- `ContextEngine` 与 `Session` 新增了 `unsteer(input)`:在投递之前按对象标识撤下一条排队中的 steering 输入,队列一旦排空即拒绝撤回。diff --git a/packages/core/src/engine/context-engine.ts b/packages/core/src/engine/context-engine.tsindex d8a49881..68074e60 100644--- a/packages/core/src/engine/context-engine.ts+++ b/packages/core/src/engine/context-engine.ts@@ -493,6 +493,20 @@ export class ContextEngine {return true;}+ /**+ * Withdraws a queued steering input that has not been delivered yet. `input` is the exact+ * list previously passed to `steer` (matched by identity — the host that queued it is the+ * one recalling it, and it holds the reference). Returns false when the entry is no longer+ * in the queue: it was already drained into the next request input (or the run exited),+ * which the host surfaces as "already delivered" rather than an error.+ */+ unsteer(input: OmniMessage[]): boolean {+ const i = this.steeringQueue.indexOf(input);+ if (i < 0) return false;+ this.steeringQueue.splice(i, 1);+ return true;+ }+/*** Drains the steering queue into standalone `[user_steering]` user messages (one per* queued entry, in arrival order, each followed by its images), yielding every message todiff --git a/packages/core/src/session.ts b/packages/core/src/session.tsindex c549c1a6..27370918 100644--- a/packages/core/src/session.ts+++ b/packages/core/src/session.ts@@ -552,6 +552,16 @@ export class Session {return this.engine?.steer(input) ?? false;}+ /**+ * Withdraws a steering input queued via `steer` before the engine delivers it: `input` is+ * the exact list that was passed to `steer` (matched by identity). Returns false when it+ * is no longer queued — already delivered to the model, or the run exited — so the host+ * reports "already delivered" instead of silently pretending the recall worked.+ */+ unsteer(input: OmniMessage[]): boolean {+ return this.engine?.unsteer(input) ?? false;+ }+/*** Skips the in-progress reconnect backoff and fires the next retry immediately (the* user's "retry now" on the reconnect countdown): the attempt counter is unchanged —diff --git a/packages/core/test/engine.test.ts b/packages/core/test/engine.test.tsindex a9290636..249eb519 100644--- a/packages/core/test/engine.test.ts+++ b/packages/core/test/engine.test.ts@@ -2485,6 +2485,38 @@ describe("ContextEngine mid-run steering ([user_steering])", () => {expect(engine.steer([userText("late")])).toBe(false);});+ it("unsteer withdraws a queued entry before delivery; refuses once drained or idle", async () => {+ const llm = new FakeLLM();+ const trace = new Writer({ tracesDir: traces, sessionId: "sess_unsteer" });+ const engine = new ContextEngine({ llm, environment: steeringEnvironment(), trace });++ // Idle: nothing queued, nothing to withdraw.+ const idleInput = [userText("never queued")];+ expect(engine.unsteer(idleInput)).toBe(false);++ const kept = [userText("focus on the tests")];+ const recalled = [userText("actually, never mind")];+ const approve: ApproveFn = async () => {+ expect(engine.steer(kept)).toBe(true);+ expect(engine.steer(recalled)).toBe(true);+ // Withdraw the second entry while both are still queued; a second attempt on the+ // same entry finds nothing.+ expect(engine.unsteer(recalled)).toBe(true);+ expect(engine.unsteer(recalled)).toBe(false);+ return "allow";+ };+ const all = await collectRun(engine, [userText("go")], approve);++ // Only the kept entry was delivered — streamed, and fed to the next turn's input.+ const expected = ["[user_steering]\nfocus on the tests\n[/user_steering]"];+ expect(steeringTexts(all)).toEqual(expected);+ expect(steeringTexts(llm.receivedSecondInput!)).toEqual(expected);+ expect(steeringTexts(await readTrace(trace.currentPath()))).toEqual(expected);++ // After delivery (queue drained, run over): the kept entry can no longer be withdrawn.+ expect(engine.unsteer(kept)).toBe(false);+ });+it("delivers steering left at loop end as a [user_steering] continuation turn (traced, streamed)", async () => {// Turn 1 ends with no tool calls while steering is queued mid-stream -> the engine keeps// looping and sends the queued text as the next input, wrapped in the same marker (UIsdiff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.mdindex f5f2ea2a..7ca3d3f6 100644--- a/packages/docs/content/server-api.en.md+++ b/packages/docs/content/server-api.en.md@@ -185,6 +185,8 @@ The paths below omit the `/api/sessions/:sessionId` prefix. For the storage mode| GET | /stream | SSE event stream (next section) || POST | /tasks | Start a Task: `{input: TaskInputPart[], thinkingLevel?, queueIfBusy?}` → 202. With `queueIfBusy`, a busy session holds the input as a follow-up (`queued: true`) and auto-starts it as an ordinary next task once idle; `task_state` events report the queued count. `file` input parts are written to the Session scratchpad and handed to the model as `[attached file: <path>]` lines (see the request body below). With `goal: {budget?}` the input starts a goal loop instead: it must carry non-empty text (an image alone states no objective), any images it carries fold into the objective as scratchpad path lines whatever the model's vision, and `file` parts are refused — nothing folds them into a re-injected objective — see [Goal mode](/goal-mode) || POST | /steer | Mid-run steering: `{text, images?}` queues a message for the running Task (delivered between turns as a standalone `[user_steering]` user message, with its images right behind it) → 202; either field can carry the message on its own, but a request with neither is a 400; 409 `not_running` when no Task is in progress |+| DELETE | /steer/:steerId | Recall an undelivered steering message (ids ride `task_state`'s `pendingSteering`): withdraws it from the queue → 200 with its original content `{text, images, files}` (files read back from the scratchpad as data URLs, their disk copies deleted) so the composer can restore it for editing; 409 `not_pending` once it was delivered to the model |+| DELETE | /follow-ups/:followUpId | Recall a queued follow-up task (ids ride `task_state`'s `pendingFollowUps`): removes it before it auto-starts → 200 with its original content `{text, images, files, thinkingLevel?}`; 409 `not_pending` once it already started || POST | /approvals/:toolCallId | Approval decision: `{decision}` is `allow` or `deny` → 204 || POST | /abort | Interrupt the current Task: 202 when triggered, 204 when idle || POST | /retry-now | "Retry now" on the reconnect countdown: skips the in-progress backoff wait, firing the next retry immediately (attempt counter unchanged) → 200 `{skipped}` — `skipped:false` is the benign "no wait in progress" case, never an error |diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.mdindex 19456ab1..51bf95f4 100644--- a/packages/docs/content/server-api.zh.md+++ b/packages/docs/content/server-api.zh.md@@ -185,6 +185,8 @@ Trace 下载对任意成员开放;导入仅限 owner(同 Agent 快照导入| GET | /stream | SSE 事件流(见下节) || POST | /tasks | 发起 Task:`{input: TaskInputPart[], thinkingLevel?, queueIfBusy?}` → 202。带 `queueIfBusy` 时,运行中的 Session 会把输入暂存为跟进消息(`queued: true`),空闲后按序自动作为普通 Task 发出;`task_state` 事件携带排队数。`file` 类型的输入会写入 Session scratchpad,以 `[attached file: <路径>]` 行交给模型(见下方请求体)。带 `goal: {budget?}` 时该输入转为发起目标循环:必须含非空文字(一张图说明不了目标),随行的图片一律折叠成 scratchpad 路径行写入目标文本、与模型是否支持视觉无关,而 `file` 会被拒绝——没有东西能把它折进每轮重注入的目标里——见[目标模式](/goal-mode) || POST | /steer | 运行中插话:`{text, images?}` 为运行中的 Task 排队一条消息(作为独立的 `[user_steering]` 用户消息随下一轮送达,图片紧随其后)→ 202;两个字段任一非空即可成消息,都为空则 400;无 Task 运行返回 409 `not_running` |+| DELETE | /steer/:steerId | 撤回一条尚未送达的插话(id 随 `task_state` 的 `pendingSteering` 下发):从队列中撤出 → 200,返回其原始内容 `{text, images, files}`(文件从 scratchpad 读回为 data URL,磁盘副本随之删除),供输入框恢复编辑;已送达模型则 409 `not_pending` |+| DELETE | /follow-ups/:followUpId | 撤回一条排队中的跟进消息(id 随 `task_state` 的 `pendingFollowUps` 下发):在自动发出前移除 → 200,返回其原始内容 `{text, images, files, thinkingLevel?}`;已自动发出则 409 `not_pending` || POST | /approvals/:toolCallId | 审批决定:`{decision}` 取 `allow` 或 `deny` → 204 || POST | /abort | 中断当前 Task:已触发返回 202,无任务返回 204 || POST | /retry-now | 重连倒计时上的「立即重试」:跳过进行中的退避等待、立刻发起下一次重试(重试计数不变)→ 200 `{skipped}`——`skipped:false` 表示当前没有等待可跳过(良性空操作,非错误) |diff --git a/packages/docs/content/web-app.en.md b/packages/docs/content/web-app.en.mdindex 8648eff3..80f74913 100644--- a/packages/docs/content/web-app.en.md+++ b/packages/docs/content/web-app.en.md@@ -59,7 +59,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, ≤ 10MB each and 12MB in total; an oversize pick is refused before it is read, so nothing is uploaded to earn the rejection); 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;+- 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;- **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.mdindex 27b13b8b..99805af7 100644--- a/packages/docs/content/web-app.zh.md+++ b/packages/docs/content/web-app.zh.md@@ -59,7 +59,7 @@ penguin web- 「+」菜单收纳输入附加项:**上传图片**、**上传文件**与目标模式。附件不限类型(一次最多 20 个,单个 ≤ 10MB、合计 ≤ 12MB;超限的文件在读取前即被拒绝,不会先上传再报错),已选文件按选择顺序以可移除的小卡片显示在文本框上方;只带附件、没有正文也可发送。发送时文件写入该 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.tsindex 03fda9f1..fe47bfd2 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -1050,6 +1050,8 @@ export interface SteerRequest {* stream, and the whole list drops when the run exits (core discards undelivered steering).*/export interface PendingSteeringInfo {+ /** Server-assigned id, stable for the entry's queued lifetime: the handle DELETE /steer/:steerId recalls it by. */+ id: string;/** The message text as accepted (trimmed); may be empty when images/files carry the message. */text: string;/** Number of images that rode along. */@@ -1058,6 +1060,42 @@ export interface PendingSteeringInfo {files: number;}+/**+ * One follow-up task queued with `queueIfBusy` but not yet auto-started. Carried on+ * `task_state` events and the SSE subscribe snapshot (like `pendingSteering`) so the+ * composer can show each queued message's content with a recall affordance; entries leave+ * the list when they auto-start on idle — or when DELETE /follow-ups/:followUpId recalls one.+ */+export interface PendingFollowUpInfo {+ /** Server-assigned id, stable for the entry's queued lifetime: the handle DELETE /follow-ups/:followUpId recalls it by. */+ id: string;+ /** The queued input's text parts, joined; may be empty when images/files carry the message. */+ text: string;+ /** Number of images in the queued input. */+ images: number;+ /** Number of file attachments in the queued input. */+ files: number;+}++/**+ * Response of the two recall endpoints — DELETE /api/sessions/:id/steer/:steerId and+ * DELETE /api/sessions/:id/follow-ups/:followUpId: the withdrawn message's original content,+ * for the composer to restore into the input box for editing and resending (#287). File+ * attachments are read back from the Session scratchpad (then deleted from it); one that+ * disappeared meanwhile is omitted rather than failing the recall. 409 `not_pending` when+ * the entry is no longer queued — steering already delivered to the model, or a follow-up+ * already auto-started (or unknown id either way).+ */+export interface RecalledMessageResponse {+ text: string;+ /** The images as submitted (`data:` / http(s) URLs). */+ images: string[];+ /** The file attachments, re-encoded as base64 data URLs (the shape the composer submits them in). */+ files: { fileName: string; dataUrl: string }[];+ /** Follow-up recall only: the per-turn thinking level the entry was queued with, when one was. */+ thinkingLevel?: ThinkingLevelName;+}+export interface ApprovalDecisionRequest {decision: "allow" | "deny";}@@ -1109,6 +1147,8 @@ 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[];+ /** Queued follow-up tasks awaiting auto-start (absent = none): per-entry content + recall handle, alongside the `queued` count. */+ pendingFollowUps?: PendingFollowUpInfo[];}/** The model-generated title after the first turn has been persisted (for in-place list updates). */| { type: "session_title"; sessionId: string; title: string }diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.tsindex 19305fe6..81bc7a38 100644--- a/packages/server/src/http/routes/sessions.ts+++ b/packages/server/src/http/routes/sessions.ts@@ -19,6 +19,7 @@ import type {MessagesLiveTail,MessagesPageInfo,MessagesResponse,+ RecalledMessageResponse,ServerEvent,SessionCategory,SessionCreateResponse,@@ -54,9 +55,11 @@ import {assertAttachmentBudget,attachFilesToInput,parseAttachmentPart,+ readRecalledFiles,removeAttachments,} from "../../services/task-attachments.js";import type { TaskAttachment } from "../../services/task-attachments.js";+import type { RecallStore } from "../../runtime/session-manager.js";/** Max title length for manual renames: looser than the auto-generated 30-char limit, to accommodate users' own organizing conventions. */const SESSION_TITLE_MAX = 120;@@ -203,6 +206,10 @@ function resolveScratchpadFile(dir: string, fileName: string): string | null {interface ParsedTaskInput {messages: OmniMessage[];attachments: TaskAttachment[];+ /** The `text` parts in order, as submitted — the recall store's text (pre-attachment-lines). */+ texts: string[];+ /** The `image_url` parts in order, as submitted — the recall store's images. */+ images: string[];}/** Validate Prompt input parts: text, image (data: / http(s) URL), or an uploaded file. */@@ -213,6 +220,8 @@ function parseTaskInput(body: Record<string, unknown>): ParsedTaskInput {}const messages: OmniMessage[] = [];const attachments: TaskAttachment[] = [];+ const texts: string[] = [];+ const images: string[] = [];input.forEach((item, i) => {if (item === null || typeof item !== "object" || Array.isArray(item)) {throw badRequest(`input[${i}] must be an object.`);@@ -223,10 +232,13 @@ function parseTaskInput(body: Record<string, unknown>): ParsedTaskInput {throw badRequest(`input[${i}].text must be a non-empty string.`);}messages.push(userText(part.text));+ texts.push(part.text);return;}if (part.type === "image_url") {- messages.push(imageUrlMessage(requireImageUrl(part.imageUrl, `input[${i}].imageUrl`)));+ const url = requireImageUrl(part.imageUrl, `input[${i}].imageUrl`);+ messages.push(imageUrlMessage(url));+ images.push(url);return;}if (part.type === "file") {@@ -240,7 +252,48 @@ function parseTaskInput(body: Record<string, unknown>): ParsedTaskInput {}throw badRequest(`input[${i}].type must be one of text / image_url / file.`);});- return { messages, attachments };+ return { messages, attachments, texts, images };+}++/**+ * The recall store of a queued message (see session-manager RecallStore): the submitted+ * content plus where each attachment landed on disk, zipped from the validated parts and+ * `attachFilesToInput`'s written paths (same order — the writes are sequential).+ */+function recallStore(+ text: string,+ images: string[],+ attachments: TaskAttachment[],+ written: string[],+): RecallStore {+ return {+ text,+ images,+ files: written.map((p, i) => ({+ fileName: attachments[i]!.fileName,+ path: p,+ mime: attachments[i]!.mime,+ })),+ };+}++/**+ * Serve one recall (#287): read the withdrawn message's file attachments back into data URLs,+ * delete their scratchpad copies (nothing references them anymore — leaving them would strand+ * a second copy when the user resends), and hand the composer-shaped content back.+ */+async function recalledResponse(+ recall: RecallStore,+ thinkingLevel?: ThinkingLevelName,+): Promise<RecalledMessageResponse> {+ const files = await readRecalledFiles(recall.files);+ await removeAttachments(recall.files.map((f) => f.path));+ return {+ text: recall.text,+ images: recall.images,+ files,+ ...(thinkingLevel !== undefined ? { thinkingLevel } : {}),+ };}/**@@ -657,14 +710,16 @@ 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 pendingFollowUps = deps.manager.pendingFollowUpsOf(row.sessionId);const initialEvents: ServerEvent[] = [{type: "task_state",state: deps.manager.statusOf(row.sessionId),queued: deps.manager.pendingFollowUpCount(row.sessionId),- // Undelivered steering rides the snapshot too, so the composer's "steering queued"- // hint (and what it says) survives a reload.+ // Undelivered steering and queued follow-ups ride the snapshot too, so the composer's+ // queued hints (and what they say) survive a reload....(pendingSteering.length > 0 ? { pendingSteering } : {}),+ ...(pendingFollowUps.length > 0 ? { pendingFollowUps } : {}),},...deps.manager.pendingApprovals(row.sessionId).map((p) => ({type: "approval_request" as const,@@ -735,6 +790,9 @@ export function sessionsRoutes(deps: AppDeps): Hono<AppEnv> {const { sessionId, queued } = await deps.manager.startTask(row.sessionId, input, {...(thinkingLevel !== undefined ? { thinkingLevel } : {}),queueIfBusy,+ // Original content, kept while the input waits in the follow-up queue so a recall+ // (DELETE /follow-ups/:id) can hand it back; unused when the task starts directly.+ recall: recallStore(parsed.texts.join("\n"), parsed.images, parsed.attachments, written),});return c.json({ sessionId, queued } satisfies TaskCreateResponse, 202);} catch (err) {@@ -774,11 +832,7 @@ export function sessionsRoutes(deps: AppDeps): Hono<AppEnv> {row.sessionId,);try {- deps.manager.steer(row.sessionId, input, {- text,- images: images.length,- files: files.length,- });+ deps.manager.steer(row.sessionId, input, recallStore(text, images, files, written));} catch (err) {// 409 (not running) or any other refusal: the files must not stay behind — the// frontend falls back to a normal task POST, which writes its own copies.@@ -788,6 +842,29 @@ export function sessionsRoutes(deps: AppDeps): Hono<AppEnv> {return c.body(null, 202);});+ // Recall an undelivered steering message back to the composer (#287): withdraws it from+ // the queue and returns its original content for editing and resending. 409 not_pending+ // once it was delivered to the model (or the id is unknown) — nothing left to take back.+ app.delete("/:sessionId/steer/:steerId", async (c) => {+ const row = resolveSession(c);+ const recall = deps.manager.recallSteering(row.sessionId, pathParam(c, "steerId"));+ return c.json((await recalledResponse(recall)) satisfies RecalledMessageResponse);+ });++ // Recall a queued follow-up task back to the composer (#287): removes it from the queue+ // before it auto-starts and returns its original content (with the thinking level it was+ // queued with). 409 not_pending once it already started (or the id is unknown).+ app.delete("/:sessionId/follow-ups/:followUpId", async (c) => {+ const row = resolveSession(c);+ const { recall, thinkingLevel } = deps.manager.recallFollowUp(+ row.sessionId,+ pathParam(c, "followUpId"),+ );+ return c.json(+ (await recalledResponse(recall, thinkingLevel)) satisfies RecalledMessageResponse,+ );+ });+// The Session's most recent goal run (for restoring the chat page's goal banner on load).app.get("/:sessionId/goal", (c) => {const row = resolveSession(c);diff --git a/packages/server/src/runtime/session-manager.ts b/packages/server/src/runtime/session-manager.tsindex ecd082b6..d5160154 100644--- a/packages/server/src/runtime/session-manager.ts+++ b/packages/server/src/runtime/session-manager.ts@@ -25,6 +25,7 @@* `SessionLoader`: production uses the core SDK (createCoreSessionLoader), tests inject* a fake Session (issuing no real LLM requests).*/+import { randomUUID } from "node:crypto";import fs from "node:fs/promises";import path from "node:path";import {@@ -49,7 +50,13 @@ import type {TextPayload,ThinkingLevelName,} from "@prismshadow/penguin-core";-import type { PendingSteeringInfo, ServerEvent, SessionStatus } from "../api/types.js";+import type {+ PendingFollowUpInfo,+ PendingSteeringInfo,+ ServerEvent,+ SessionStatus,+} from "../api/types.js";+import type { RecallableFile } from "../services/task-attachments.js";import { HttpError, isMissingCredential, modelCredentialMissing } from "../http/errors.js";import type { GoalsRepo } from "../db/repos/goals.js";import type { SessionRow, SessionsRepo } from "../db/repos/sessions.js";@@ -93,6 +100,13 @@ export interface RuntimeSession {compactability(): CompactAvailability;/** Queues a mid-run steering input (core `Session.steer`); false when no Task is running. */steer(input: OmniMessage[]): boolean;+ /**+ * Withdraws a steering input queued via `steer` before core delivers it (core+ * `Session.unsteer`, matched by input-list identity); false when it is no longer queued —+ * already delivered, or the run exited. Optional: test fakes may omit it, in which case+ * every recall reports "already delivered".+ */+ unsteer?(input: OmniMessage[]): boolean;/** Skips the in-progress reconnect backoff, firing the next retry immediately (core `Session.skipReconnectWait`); false when no wait is in progress. */skipReconnectWait(): boolean;toolPermission(name: string): "r" | "rw" | undefined;@@ -230,10 +244,33 @@ export interface SessionManagerDeps {now?: () => Date;}+/**+ * A queued message's original content, held while it waits in a queue so a recall (DELETE+ * /steer/:id, DELETE /follow-ups/:id) can hand it back to the composer for editing (#287).+ * `text` and `images` are the same strings the queued input already references (no extra+ * copy); files stay on disk in the Session scratchpad and are read back only at recall.+ */+export interface RecallStore {+ text: string;+ images: string[];+ files: RecallableFile[];+}+/** One queued follow-up task (`queueIfBusy`): the task input plus the per-turn thinking level it was posted with. */interface QueuedFollowUp {+ /** Recall handle (PendingFollowUpInfo.id), assigned at queue time. */+ id: string;input: OmniMessage[];thinkingLevel?: ThinkingLevelName;+ /** Original content for recall; absent when the queueing path predates or bypasses the route (recall then returns 409). */+ recall?: RecallStore;+}++/** One undelivered steering entry: the display info broadcast on task_state, plus what a recall needs — the exact input list core queued (its unsteer handle) and the original content. */+interface PendingSteeringEntry {+ info: PendingSteeringInfo;+ input: OmniMessage[];+ recall: RecallStore;}/** Active-table entry: a loaded runtime Session plus its running state. */@@ -287,9 +324,10 @@ interface RuntimeEntry {* of core's steering queue (same FIFO order), so the composer's "steering queued" hint and* its content survive reloads: pushed on `steer`, shifted as each `[user_steering]`* message appears on the drive stream, dropped wholesale when the run exits (core- * discards undelivered steering on abort/completion). Broadcast on every `task_state`.+ * discards undelivered steering on abort/completion). The `info` halves are broadcast on+ * every `task_state`; the rest is the recall handle (see recallSteering).*/- pendingSteering: PendingSteeringInfo[];+ pendingSteering: PendingSteeringEntry[];/** Timestamp of last activity (refreshed on load / status flip / drive completion), used for idle-eviction checks. */lastActivityMs: number;}@@ -313,6 +351,16 @@ function agentKey(projectId: string, agentId: string): string {return `${projectId}\0${agentId}`;}+/** The `task_state` display info of one queued follow-up (see PendingFollowUpInfo); an entry queued without a recall store truthfully reports empty content. */+function followUpInfo(f: QueuedFollowUp): PendingFollowUpInfo {+ return {+ id: f.id,+ text: f.recall?.text ?? "",+ images: f.recall?.images.length ?? 0,+ files: f.recall?.files.length ?? 0,+ };+}+/** If msg is a run_subagent tool call carrying a `prompt`, return its id and prompt (for use as the subagent's title); otherwise null. *//** Whether this main-stream message is a delivered `[user_steering]` user text (one per queued steering entry, see core's steeringMessages). */function isDeliveredSteering(msg: OmniMessage): boolean {@@ -433,7 +481,12 @@ export class SessionManager {/** Steering messages queued but not yet delivered to the model (display mirror; see RuntimeEntry.pendingSteering). */pendingSteeringOf(sessionId: string): PendingSteeringInfo[] {- return this.entries.get(sessionId)?.pendingSteering ?? [];+ return (this.entries.get(sessionId)?.pendingSteering ?? []).map((p) => p.info);+ }++ /** Queued follow-up tasks awaiting auto-start, as their display/recall info (id + content summary). */+ pendingFollowUpsOf(sessionId: string): PendingFollowUpInfo[] {+ return (this.entries.get(sessionId)?.followUps ?? []).map(followUpInfo);}/**@@ -557,7 +610,7 @@ export class SessionManager {async startTask(sessionId: string,input: OmniMessage[],- opts?: { thinkingLevel?: ThinkingLevelName; queueIfBusy?: boolean },+ opts?: { thinkingLevel?: ThinkingLevelName; queueIfBusy?: boolean; recall?: RecallStore },): Promise<{ sessionId: string; queued: boolean }> {return this.withLock(sessionId, async () => {this.assertOpen();@@ -566,8 +619,11 @@ export class SessionManager {const entry = await this.ensureEntry(sessionId);if (entry.status !== "idle" && opts?.queueIfBusy) {entry.followUps.push({+ id: randomUUID(),input,...(opts.thinkingLevel !== undefined ? { thinkingLevel: opts.thinkingLevel } : {}),+ // The original content rides the queue so a recall can hand it back (see recallFollowUp).+ ...(opts.recall !== undefined ? { recall: opts.recall } : {}),});entry.lastActivityMs = Date.now();// Re-publish the current state so subscribers pick up the new queued count (the@@ -897,12 +953,13 @@ export class SessionManager {* or the run finished in the race window — the caller falls back to submitting a normal* task, which carries the same text and images.*- * `info` is the queued message's display summary: mirrored on the entry and broadcast via- * `task_state` (and the SSE subscribe snapshot) until the delivered `[user_steering]`- * message is observed on the stream — that is what keeps the composer's "steering queued"- * hint, content included, alive across reloads.+ * `recall` is the queued message's original content: its summary (with a fresh id) is+ * mirrored on the entry and broadcast via `task_state` (and the SSE subscribe snapshot)+ * until the delivered `[user_steering]` message is observed on the stream — that is what+ * keeps the composer's "steering queued" hint, content included, alive across reloads —+ * and the content itself is what a recall (recallSteering) hands back to the composer.*/- steer(sessionId: string, input: OmniMessage[], info: PendingSteeringInfo): void {+ steer(sessionId: string, input: OmniMessage[], recall: RecallStore): void {const entry = this.entries.get(sessionId);if (!entry || entry.status !== "running" || !entry.session.steer(input)) {throw new HttpError(@@ -911,11 +968,75 @@ export class SessionManager {"This Session has no Task in progress; send the message as a new task instead.",);}- entry.pendingSteering.push(info);+ entry.pendingSteering.push({+ info: {+ id: randomUUID(),+ text: recall.text,+ images: recall.images.length,+ files: recall.files.length,+ },+ input,+ recall,+ });entry.lastActivityMs = Date.now();this.publishState(entry, entry.status);}+ /**+ * Recall an undelivered steering message (#287): withdraw it from core's queue and the+ * display mirror, re-broadcast state, and hand back its original content for the composer+ * to restore. 409 `not_pending` when the entry is no longer queued — already delivered to+ * the model (core's `unsteer` says so authoritatively; the mirror can lag behind delivery+ * until the `[user_steering]` message is observed on the stream), the run exited, or the+ * id is unknown — all the same outcome for the caller: nothing left to take back.+ */+ 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.",+ );+ }+ entry.pendingSteering.splice(i, 1);+ entry.lastActivityMs = Date.now();+ this.publishState(entry, entry.status);+ return pending.recall;+ }++ /**+ * Recall a queued follow-up task (#287): remove it from the queue before it auto-starts,+ * re-broadcast state, and hand back its original content (plus the thinking level it was+ * queued with). 409 `not_pending` when the id is not in the queue — it already+ * auto-started (or the runtime was evicted/restarted, which empties the queue) — or the+ * entry has no recall store to give back.+ */+ recallFollowUp(+ sessionId: string,+ followUpId: string,+ ): { recall: RecallStore; thinkingLevel?: ThinkingLevelName } {+ const entry = this.entries.get(sessionId);+ const i = entry?.followUps.findIndex((f) => f.id === followUpId) ?? -1;+ const queued = i >= 0 ? entry!.followUps[i]! : undefined;+ if (!entry || !queued?.recall) {+ throw new HttpError(+ 409,+ "not_pending",+ "This follow-up message already started and can no longer be recalled.",+ );+ }+ entry.followUps.splice(i, 1);+ entry.lastActivityMs = Date.now();+ this.publishState(entry, entry.status);+ return {+ recall: queued.recall,+ ...(queued.thinkingLevel !== undefined ? { thinkingLevel: queued.thinkingLevel } : {}),+ };+ }+/*** "Retry now" on the reconnect countdown: skip the in-progress backoff wait and fire* the next retry immediately (the attempt counter is unchanged — the skipped wait does@@ -1571,7 +1692,12 @@ export class SessionManager {type: "task_state",state,queued: entry.followUps.length,- ...(entry.pendingSteering.length > 0 ? { pendingSteering: entry.pendingSteering } : {}),+ ...(entry.pendingSteering.length > 0+ ? { pendingSteering: entry.pendingSteering.map((p) => p.info) }+ : {}),+ ...(entry.followUps.length > 0+ ? { pendingFollowUps: entry.followUps.map(followUpInfo) }+ : {}),});}diff --git a/packages/server/src/services/task-attachments.ts b/packages/server/src/services/task-attachments.tsindex d7d2f738..805aad87 100644--- a/packages/server/src/services/task-attachments.ts+++ b/packages/server/src/services/task-attachments.ts@@ -100,6 +100,12 @@ export interface TaskAttachment {/** Original file name as submitted (validated: non-empty, no path separators, no `..`). */fileName: string;bytes: Buffer;+ /**+ * Media type from the submitted data URL (parameters included, e.g. `text/plain;charset=utf-8`);+ * empty when the URL carried none. Kept so a queued message's recall can re-encode the+ * on-disk bytes into the same data URL shape the composer submitted (see readRecalledFiles).+ */+ mime: string;}/**@@ -136,11 +142,11 @@ export function parseAttachmentPart(// type from the payload. The payload's character class is the actual check that it IS// base64 (whitespace tolerated — line-wrapped encoders decode fine).const match =- typeof dataUrl === "string" ? /^data:[^,]*;base64,([A-Za-z0-9+/=\s]+)$/.exec(dataUrl) : null;+ typeof dataUrl === "string" ? /^data:([^,]*);base64,([A-Za-z0-9+/=\s]+)$/.exec(dataUrl) : null;if (!match) {throw badRequest(`${field}[${index}].dataUrl must be a base64 data: URL of the file's bytes.`);}- const bytes = Buffer.from(match[1]!, "base64");+ const bytes = Buffer.from(match[2]!, "base64");if (bytes.length === 0) {throw badRequest(`${field}[${index}].dataUrl decodes to an empty file.`);}@@ -151,7 +157,42 @@ export function parseAttachmentPart(`Attached file exceeds the ${MAX_ATTACHMENT_BYTES / (1024 * 1024)}MB limit.`,);}- return { fileName, bytes };+ return { fileName, bytes, mime: match[1]! };+}++/**+ * A queued message's file attachment as held for recall: the scratchpad path it was written+ * to, plus what is needed to rebuild the composer-shaped part — the submitted name and media+ * type (the bytes stay on disk; queued entries never hold file payloads in memory).+ */+export interface RecallableFile {+ fileName: string;+ path: string;+ mime: string;+}++/**+ * Read recalled attachments back from the scratchpad into the `{fileName, dataUrl}` shape the+ * composer submits. Best effort: a file that disappeared meanwhile (Session deleted from+ * another tab, manual cleanup) is omitted rather than failing the whole recall — the text and+ * images still come back. The caller deletes the on-disk copies afterwards (removeAttachments);+ * reading first keeps the two steps safely ordered.+ */+export async function readRecalledFiles(+ files: RecallableFile[],+): Promise<{ fileName: string; dataUrl: string }[]> {+ const read = await Promise.all(+ files.map(async (f) => {+ try {+ const bytes = await fs.readFile(f.path);+ const mime = f.mime || "application/octet-stream";+ return { fileName: f.fileName, dataUrl: `data:${mime};base64,${bytes.toString("base64")}` };+ } catch {+ return null;+ }+ }),+ );+ return read.filter((f) => f !== null);}/**diff --git a/packages/server/test/followup.test.ts b/packages/server/test/followup.test.tsindex c2b23078..cb4face2 100644--- a/packages/server/test/followup.test.ts+++ b/packages/server/test/followup.test.ts@@ -11,7 +11,7 @@ import { approvalDecision, assistantText, toolCall } from "@prismshadow/penguin-import type { ApproveFn, OmniMessage } from "@prismshadow/penguin-core";import type { TaskCreateResponse } from "../src/api/types.js";import type { SessionRow } from "../src/db/repos/sessions.js";-import type { RuntimeSession } from "../src/runtime/session-manager.js";+import type { RecallStore, RuntimeSession } from "../src/runtime/session-manager.js";import { apiClient, createTestApp, provisionUser, waitFor } from "./helpers.js";import type { TestApp } from "./helpers.js";@@ -99,4 +99,137 @@ describe("follow-up queue route", () => {t.deps.manager.decideApproval(SID, "tc-fu", "allow");await waitFor(() => t.deps.manager.statusOf(SID) === "idle");});++ it("recall (#287): DELETE withdraws a queued follow-up with its content and thinking level; the rest auto-start", async () => {+ await api.post(`/api/sessions/${SID}/tasks`, { input: [{ type: "text", text: "task 1" }] });+ await waitFor(() => t.deps.manager.pendingApprovalCount(SID) === 1);++ const png = "data:image/png;base64,AAAA";+ await api.post(`/api/sessions/${SID}/tasks`, {+ input: [+ { type: "text", text: "follow-up 1" },+ { type: "image_url", imageUrl: png },+ ],+ queueIfBusy: true,+ thinkingLevel: "high",+ });+ await api.post(`/api/sessions/${SID}/tasks`, {+ input: [{ type: "text", text: "follow-up 2" }],+ queueIfBusy: true,+ });+ const pending = t.deps.manager.pendingFollowUpsOf(SID);+ expect(pending).toEqual([+ { id: expect.any(String), text: "follow-up 1", images: 1, files: 0 },+ { id: expect.any(String), text: "follow-up 2", images: 0, files: 0 },+ ]);++ // The recall returns the original content plus the per-turn level it was queued with.+ const res = await api.delete(`/api/sessions/${SID}/follow-ups/${pending[0]!.id}`);+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({+ text: "follow-up 1",+ images: [png],+ files: [],+ thinkingLevel: "high",+ });+ expect(t.deps.manager.pendingFollowUpCount(SID)).toBe(1);++ // Recalled means never started: only the remaining follow-up auto-starts.+ t.deps.manager.decideApproval(SID, "tc-fu", "allow");+ await waitFor(() => runs.length === 2);+ expect(runs[1]).toEqual(["follow-up 2"]);++ // Gone (recalled or auto-started) → 409 not_pending.+ const again = await api.delete(`/api/sessions/${SID}/follow-ups/${pending[0]!.id}`);+ expect(again.status).toBe(409);+ expect(((await again.json()) as { error: { code: string } }).error.code).toBe("not_pending");++ await waitFor(() => t.deps.manager.pendingApprovalCount(SID) === 1);+ t.deps.manager.decideApproval(SID, "tc-fu", "allow");+ await waitFor(() => t.deps.manager.statusOf(SID) === "idle");+ });++ it("the SSE subscribe snapshot carries the queued follow-up list (what makes the recall lines survive reloads)", async () => {+ await api.post(`/api/sessions/${SID}/tasks`, { input: [{ type: "text", text: "task 1" }] });+ await waitFor(() => t.deps.manager.pendingApprovalCount(SID) === 1);+ await api.post(`/api/sessions/${SID}/tasks`, {+ input: [{ type: "text", text: "queued for later" }],+ queueIfBusy: true,+ });++ // The first SSE frames are the initial task_state snapshot: it must carry the per-entry+ // list (id + content), not just the queued count — a reloaded page rebuilds each hint+ // line with its recall handle from this alone.+ const res = await api.get(`/api/sessions/${SID}/stream`);+ const reader = res.body!.getReader();+ let seen = "";+ for (let i = 0; i < 5 && !seen.includes("task_state"); i += 1) {+ const { value, done } = await reader.read();+ if (done) break;+ seen += new TextDecoder().decode(value);+ }+ await reader.cancel();+ expect(seen).toContain('"task_state"');+ expect(seen).toContain('"pendingFollowUps"');+ expect(seen).toContain("queued for later");++ t.deps.manager.decideApproval(SID, "tc-fu", "allow");+ await waitFor(() => runs.length === 2);+ await waitFor(() => t.deps.manager.pendingApprovalCount(SID) === 1);+ t.deps.manager.decideApproval(SID, "tc-fu", "allow");+ await waitFor(() => t.deps.manager.statusOf(SID) === "idle");+ });++ it("recall (#287) racing the auto-start: a recall in the idle gap wins exactly once", async () => {+ await api.post(`/api/sessions/${SID}/tasks`, { input: [{ type: "text", text: "task 1" }] });+ await waitFor(() => t.deps.manager.pendingApprovalCount(SID) === 1);+ await api.post(`/api/sessions/${SID}/tasks`, {+ input: [{ type: "text", text: "recalled at the wire" }],+ queueIfBusy: true,+ });+ const [queued] = t.deps.manager.pendingFollowUpsOf(SID);++ // Between drive's idle flip and the drain's locked dequeue lies a microtask-wide gap:+ // the idle task_state broadcast runs its channel listeners synchronously, while the+ // startQueuedFollowUp scheduled right after it only dequeues a promise-chain hop later.+ // A recall enqueued as a microtask from inside the idle broadcast therefore lands+ // exactly in that gap — after the auto-start was scheduled (the queue was still+ // non-empty then), before it shifts the entry. Exactly-one-of must hold: the recall+ // wins, and the drain's under-lock revalidation finds the queue empty and starts nothing.+ const result: { recalled?: { recall: RecallStore }; err?: unknown } = {};+ let fired = false;+ let lastQueued = -1;+ const unsubscribe = t.deps.channels.get(SID).subscribe((evt) => {+ if (evt.event !== "server_event") return;+ const ev = JSON.parse(evt.data) as { type?: string; state?: string; queued?: number };+ if (ev.type !== "task_state") return;+ lastQueued = ev.queued ?? -1;+ if (ev.state !== "idle" || fired) return;+ fired = true;+ queueMicrotask(() => {+ try {+ result.recalled = t.deps.manager.recallFollowUp(SID, queued!.id);+ } catch (e) {+ result.err = e;+ }+ });+ });++ // Finish run 1: drive flips to idle (its broadcast queues the recall) and schedules the+ // auto-start behind it; then give the scheduled drain time to reach its revalidation.+ t.deps.manager.decideApproval(SID, "tc-fu", "allow");+ await waitFor(() => fired && t.deps.manager.statusOf(SID) === "idle");+ await new Promise((resolve) => setTimeout(resolve, 25));+ unsubscribe();++ expect(result.err).toBeUndefined();+ expect(result.recalled?.recall.text).toBe("recalled at the wire");+ // Exactly once: withdrawn, never started — run 1 stays the only run, and nothing is left queued.+ expect(runs).toEqual([["task 1"]]);+ expect(t.deps.manager.pendingFollowUpCount(SID)).toBe(0);+ expect(t.deps.manager.statusOf(SID)).toBe("idle");+ // What another tab sees: the recall's own task_state broadcast already reports the+ // emptied queue, so the entry disappears there without a reload.+ expect(lastQueued).toBe(0);+ });});diff --git a/packages/server/test/session-manager.test.ts b/packages/server/test/session-manager.test.tsindex 1a65fe7e..b2da5552 100644--- a/packages/server/test/session-manager.test.ts+++ b/packages/server/test/session-manager.test.ts@@ -381,7 +381,7 @@ describe("session-manager", () => {const manager = makeManager(loaderOf(fake));const steerErr = (text: string): unknown => {try {- manager.steer("session-1", [userText(text)], { text, images: 0, files: 0 });+ manager.steer("session-1", [userText(text)], { text, images: [], files: [] });return null;} catch (e) {return e;@@ -433,11 +433,18 @@ describe("session-manager", () => {await waitFor(() => manager.pendingApprovalCount("session-1") === 1);// Two queued steering messages: the mirror keeps both, in queue order.- manager.steer("session-1", [userText("a")], { text: "focus on tests", images: 0, files: 0 });- manager.steer("session-1", [userText("b")], { text: "later", images: 1, files: 2 });+ manager.steer("session-1", [userText("a")], { text: "focus on tests", images: [], files: [] });+ manager.steer("session-1", [userText("b")], {+ text: "later",+ images: ["data:image/png;base64,aa"],+ files: [+ { fileName: "a.txt", path: "/tmp/a.txt", mime: "text/plain" },+ { fileName: "b.txt", path: "/tmp/b.txt", mime: "text/plain" },+ ],+ });expect(manager.pendingSteeringOf("session-1")).toEqual([- { text: "focus on tests", images: 0, files: 0 },- { text: "later", images: 1, files: 2 },+ { id: expect.any(String), text: "focus on tests", images: 0, files: 0 },+ { id: expect.any(String), text: "later", images: 1, files: 2 },]);// First delivery observed on the stream: the mirror shifts while the run is still going.@@ -445,7 +452,7 @@ describe("session-manager", () => {await waitFor(() => manager.pendingSteeringOf("session-1").length === 1);expect(manager.statusOf("session-1")).toBe("running");expect(manager.pendingSteeringOf("session-1")).toEqual([- { text: "later", images: 1, files: 2 },+ { id: expect.any(String), text: "later", images: 1, files: 2 },]);// Run end: core discards undelivered steering, and the mirror goes with it.diff --git a/packages/server/test/steer.test.ts b/packages/server/test/steer.test.tsindex fa0cb2e5..49cb7a7d 100644--- a/packages/server/test/steer.test.ts+++ b/packages/server/test/steer.test.ts@@ -48,6 +48,14 @@ function steeringFakeSession(sessionId: string, steered: OmniMessage[][]): Runtisteered.push(input);return true;},+ // Same contract as core: withdraw by input-list identity, false once "delivered"+ // (tests simulate delivery by emptying `steered`).+ unsteer: (input: OmniMessage[]) => {+ const i = steered.indexOf(input);+ if (i < 0) return false;+ steered.splice(i, 1);+ return true;+ },skipReconnectWait: () => false,async *run(_input: OmniMessage[], opts: { approve: ApproveFn; signal: AbortSignal }) {const tc = toolCall({ name: "exec_command", arguments: "{}", toolCallId: "tc-steer" });@@ -248,7 +256,7 @@ describe("steer route", () => {await waitFor(() => t.deps.manager.pendingApprovalCount(SID) === 1);await api.post(`/api/sessions/${SID}/steer`, { text: "hold on" });expect(t.deps.manager.pendingSteeringOf(SID)).toEqual([- { text: "hold on", images: 0, files: 0 },+ { id: expect.any(String), text: "hold on", images: 0, files: 0 },]);// The first SSE frames are the initial task_state snapshot: it must carry the mirror.@@ -268,4 +276,63 @@ describe("steer route", () => {t.deps.manager.decideApproval(SID, "tc-steer", "allow");await waitFor(() => t.deps.manager.statusOf(SID) === "idle");});++ it("recall (#287): DELETE withdraws the queued entry, returns its original content, and cleans the scratchpad", async () => {+ await t.deps.manager.startTask(SID, [userText("go")]);+ await waitFor(() => t.deps.manager.pendingApprovalCount(SID) === 1);++ const png = "data:image/png;base64,AAAA";+ const data = `data:text/plain;base64,${Buffer.from("hello notes").toString("base64")}`;+ const posted = await api.post(`/api/sessions/${SID}/steer`, {+ text: " keep me ",+ images: [png],+ files: [{ fileName: "notes.txt", dataUrl: data }],+ });+ expect(posted.status).toBe(202);+ expect(steered).toHaveLength(1);+ const [info] = t.deps.manager.pendingSteeringOf(SID);+ expect(info).toEqual({ id: expect.any(String), text: "keep me", images: 1, files: 1 });++ // The recall hands the whole message back in the composer's own shape — the file read+ // back from the scratchpad as the very data URL it was submitted as.+ const res = await api.delete(`/api/sessions/${SID}/steer/${info!.id}`);+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({+ text: "keep me",+ images: [png],+ files: [{ fileName: "notes.txt", dataUrl: data }],+ });++ // Withdrawn everywhere: core's queue (the fake's unsteer), the mirror, and the disk copy.+ expect(steered).toHaveLength(0);+ expect(t.deps.manager.pendingSteeringOf(SID)).toEqual([]);+ const dir = path.join(scratchpadDir(t.root, "steerer-default_project", "default_agent"), SID);+ expect(await readdir(dir).catch(() => [])).toEqual([]);++ // Nothing left under that id: a second recall (double click, another tab) is a 409.+ const again = await api.delete(`/api/sessions/${SID}/steer/${info!.id}`);+ expect(again.status).toBe(409);+ expect(((await again.json()) as { error: { code: string } }).error.code).toBe("not_pending");++ t.deps.manager.decideApproval(SID, "tc-steer", "allow");+ await waitFor(() => t.deps.manager.statusOf(SID) === "idle");+ });++ 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);+ await api.post(`/api/sessions/${SID}/steer`, { text: "too late" });+ const [info] = t.deps.manager.pendingSteeringOf(SID);++ // Simulate core having drained the queue (delivery is imminent/underway): the mirror+ // still shows the entry until the [user_steering] message is observed on the stream.+ steered.length = 0;+ const res = await api.delete(`/api/sessions/${SID}/steer/${info!.id}`);+ expect(res.status).toBe(409);+ expect(((await res.json()) as { error: { code: string } }).error.code).toBe("not_pending");+ expect(t.deps.manager.pendingSteeringOf(SID)).toHaveLength(1);++ t.deps.manager.decideApproval(SID, "tc-steer", "allow");+ await waitFor(() => t.deps.manager.statusOf(SID) === "idle");+ });});diff --git a/packages/web/e2e/reloaded-followup.spec.mjs b/packages/web/e2e/reloaded-followup.spec.mjsindex 9a7a21a6..241721fb 100644--- a/packages/web/e2e/reloaded-followup.spec.mjs+++ b/packages/web/e2e/reloaded-followup.spec.mjs@@ -101,7 +101,13 @@ test("a stale steer response after reload queues the follow-up instead of strandthinkingLevel: "high",});expect(await response.json()).toMatchObject({ queued: true });- await expect(page.getByText("1 条跟进消息已排队,本轮结束后自动发送")).toBeVisible();+ // The queued hint is now one line per entry carrying that entry's own content (the bare+ // "N queued" count is only the fallback for a server that predates pendingFollowUps), and+ // it ends in the icon-only recall control — which must still answer to its name (#287).+ await expect(+ page.getByText("跟进消息已排队,本轮结束后自动发送:hello after reload"),+ ).toBeVisible();+ await expect(page.getByRole("button", { name: "撤回" })).toHaveCount(1);await expect(composer).toHaveValue("");// The first task completes, then the accepted follow-up reaches the LLM and produces adiff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.tsindex 8d09238e..0b85bcfa 100644--- a/packages/web/src/api/endpoints.ts+++ b/packages/web/src/api/endpoints.ts@@ -71,6 +71,7 @@ import type {SkillArchiveInstallRequest,SkillInstallRequest,SkillLibraryResponse,+ RecalledMessageResponse,RetryNowResponse,SteerRequest,TaskCreateRequest,@@ -483,6 +484,20 @@ export const postSteer = (sessionId: string, body: SteerRequest) =>body,});+/** Recall an undelivered steering message back to the composer (#287): returns its original content; 409 not_pending once it was delivered to the model. */+export const recallSteer = (sessionId: string, steerId: string) =>+ apiFetch<RecalledMessageResponse>(+ `/api/sessions/${encodeURIComponent(sessionId)}/steer/${encodeURIComponent(steerId)}`,+ { method: "DELETE" },+ );++/** Recall a queued follow-up task back to the composer (#287): returns its original content (+ queued thinking level); 409 not_pending once it already auto-started. */+export const recallFollowUp = (sessionId: string, followUpId: string) =>+ apiFetch<RecalledMessageResponse>(+ `/api/sessions/${encodeURIComponent(sessionId)}/follow-ups/${encodeURIComponent(followUpId)}`,+ { method: "DELETE" },+ );+export const postCompact = (sessionId: string) =>// Same shape as tasks: the response carries the actual current session_id (a new id after self-healing; the frontend updates its route accordingly).apiFetch<TaskCreateResponse>(`/api/sessions/${encodeURIComponent(sessionId)}/compact`, {diff --git a/packages/web/src/features/chat/chat-input.tsx b/packages/web/src/features/chat/chat-input.tsxindex 17cac14c..fcccce5e 100644--- a/packages/web/src/features/chat/chat-input.tsx+++ b/packages/web/src/features/chat/chat-input.tsx@@ -71,7 +71,9 @@ import type {ApprovalMode,ModelInfo,ModelRefDto,+ PendingFollowUpInfo,PendingSteeringInfo,+ RecalledMessageResponse,SessionStatus,SkillMetadataItem,TaskInputPart,@@ -102,6 +104,7 @@ import {skillSlashItems,} from "./skill-use";import { GOAL_ICON, UNLIMITED_BUDGET, parseBudgetInput } from "./goal-use";+import { mergeRecalledDraft } from "./recall-draft";import {caretOnFirstLine,caretOnLastLine,@@ -816,13 +819,14 @@ function readDataUrl(file: File): Promise<string | null> {});}-/**- * Appends the draft's attachments to a task input — images first (in pick order), then files.- * One place, because every send path submits the same draft: the normal send, the follow-up- * queue, the @ handoff and the `/model` switch.- */+/** Approximate decoded byte size of a base64 data URL (for the recalled attachment's chip; display only). */+function dataUrlBytes(dataUrl: string): number {+ const body = dataUrl.slice(dataUrl.indexOf(",") + 1).replace(/[=\s]+/g, "");+ return Math.floor((body.length * 3) / 4);+}+/** One-line summary of a queued steering message: its text, then image/file counts for what the text cannot show. */-function steeringSummary(p: PendingSteeringInfo): string {+function steeringSummary(p: { text: string; images: number; files: number }): string {const parts: string[] = [];const line = p.text.replace(/\s+/g, " ").trim();if (line) parts.push(line);@@ -831,6 +835,60 @@ function steeringSummary(p: PendingSteeringInfo): string {return parts.join(" \u00b7 ");}+/**+ * Curved-back arrow glyph (24×24 line path) for the recall control: arrowhead at the left,+ * the shaft looping back beneath it — the undo reading, not the trash-can one. A recalled+ * message is not discarded, it comes back to the composer, and the icon has to say that on+ * its own (owner directive: this control carries no text).+ */+const RECALL_ICON = "M9 14L4 9l5-5M4 9h10.5a5.5 5.5 0 0 1 0 11H11";++/**+ * One queued-message hint line (undelivered steering / queued follow-up) with its recall+ * button (#287): the button withdraws the message server-side and puts its content back into+ * the input box for editing and resending. No button when the channel offers no recall+ * (old server: entries without ids, or no handler supplied).+ *+ * Icon-only, so the two localized strings become its accessible name instead of its body:+ * `recallQueued` is the short one the button is *called* (aria-label), `recallQueuedTitle` the+ * tooltip that says what happens. Sized like the other icon controls on a text-xs row, and+ * `shrink-0` next to the truncating label so it survives narrow widths. It carries the icon+ * set's gray (a step darker than the hint text it sits beside), not the label's: gray-400 on+ * white is under the 3:1 an interactive control owes, and this one is interactive.+ */+function QueuedMessageLine({+ label,+ onRecall,+ disabled,+}: {+ label: string;+ onRecall?: () => void;+ disabled: boolean;+}) {+ return (+ <div className="flex min-w-0 items-center gap-1">+ <p className="min-w-0 truncate text-xs text-gray-400 dark:text-gray-500">{label}</p>+ {onRecall && (+ <button+ type="button"+ aria-label={S.chat.recallQueued}+ title={S.chat.recallQueuedTitle}+ disabled={disabled}+ onClick={onRecall}+ className="flex h-5 w-5 shrink-0 items-center justify-center rounded text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 disabled:cursor-not-allowed disabled:opacity-40 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200"+ >+ <GlyphIcon d={RECALL_ICON} size={13} />+ </button>+ )}+ </div>+ );+}++/**+ * Appends the draft's attachments to a task input — images first (in pick order), then files.+ * One place, because every send path submits the same draft: the normal send, the follow-up+ * queue, the @ handoff and the `/model` switch.+ */function appendAttachmentParts(input: TaskInputPart[],images: string[],@@ -848,8 +906,11 @@ export function ChatInput({onSteer,steeringDeliveredCount,pendingSteering = [],+ onRecallSteering,onQueueFollowUp,queuedFollowUps = 0,+ pendingFollowUps = [],+ onRecallFollowUp,onStop,onCompact,modelRef,@@ -920,6 +981,13 @@ export function ChatInput({* reloads (#136). The local post-202 flag only bridges until the first event arrives.*/pendingSteering?: 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+ * failed (already delivered — the parent toasts). Renders the recall button on each+ * pending-steering line when supplied.+ */+ onRecallSteering?: (steerId: string) => Promise<RecalledMessageResponse | null>;/*** Follow-up queue (session state only): posts the full input with `queueIfBusy` — a busy* session holds it server-side and auto-sends it as an ordinary next task once the current@@ -929,6 +997,14 @@ export function ChatInput({onQueueFollowUp?: (input: TaskInputPart[]) => Promise<boolean>;/** Server-reported queued follow-up count (from task_state): renders the "N queued" hint until they auto-send. */queuedFollowUps?: number;+ /**+ * Queued follow-up tasks with per-entry content (from task_state): renders one line each —+ * with a recall button — instead of the bare count; empty on old servers (the count hint+ * stays as the fallback).+ */+ pendingFollowUps?: PendingFollowUpInfo[];+ /** Recall a queued follow-up (#287): same contract as onRecallSteering, for the follow-up queue. */+ onRecallFollowUp?: (followUpId: string) => Promise<RecalledMessageResponse | null>;/*** Used instead of onSend when an `/agent` target chip is staged: opens a new chat for the* target agent (the current Session receives no message). Returns whether it succeeded@@ -1288,10 +1364,81 @@ export function ChatInput({const steerBaseline = useRef(0);useEffect(() => {if (!steerPending) return;- if (!running || (steeringDeliveredCount ?? 0) > steerBaseline.current) {+ // ...and once the server's mirror has actually arrived, since from then on the mirror is+ // what renders the hint. Dropping the bridge there is what keeps a recall in ANOTHER tab+ // from stranding this one: that empties pendingSteering without a delivery and without+ // ending the run, so a bridge still raised would fall back to the bare "steering queued"+ // hint for a message that no longer exists (#287).+ if (+ !running ||+ (steeringDeliveredCount ?? 0) > steerBaseline.current ||+ pendingSteering.length > 0+ ) {setSteerPending(false);}- }, [steerPending, running, steeringDeliveredCount]);+ }, [steerPending, running, steeringDeliveredCount, pendingSteering.length]);++ // Recall a queued message back into the draft (#287): the server withdraws the entry and+ // returns its original content. One recall at a time; the id doubles as the busy flag so+ // every recall button disables while one is in flight.+ const [recallingId, setRecallingId] = useState<string | null>(null);+ /** Restores recalled content into the draft: its text goes in FRONT of whatever is currently typed (it was composed first), attachments likewise; caret parked at the end, applyHistory-style. */+ const applyRecalled = (r: RecalledMessageResponse) => {+ // The recall round-trip may have taken keystrokes: read the live value off the controlled+ // textarea rather than this closure's render-time `text`, or anything typed while the+ // DELETE was in flight would be overwritten by the merge.+ const { text: merged, dropGoal } = mergeRecalledDraft({+ recalledText: r.text,+ currentText: textareaRef.current?.value ?? text,+ recalledFiles: r.files.length,+ goalOn,+ });+ setText(merged);+ onTextChange?.(merged);+ setCaret(merged.length);+ if (r.images.length > 0) setImages((prev) => [...r.images, ...prev]);+ if (r.files.length > 0) {+ // A goal draft cannot carry the restored files — release the staged chip rather than+ // strand them behind a dead Send (why: see mergeRecalledDraft).+ if (dropGoal) toggleGoal(false);+ setAttachments((prev) => [+ ...r.files.map((f) => ({+ name: f.fileName,+ size: dataUrlBytes(f.dataUrl),+ dataUrl: f.dataUrl,+ })),+ ...prev,+ ]);+ }+ requestAnimationFrame(() => {+ const el = textareaRef.current;+ if (!el) return;+ el.focus();+ el.setSelectionRange(el.value.length, el.value.length);+ el.scrollTop = el.scrollHeight;+ });+ };+ const recallQueued = async (+ id: string,+ recall: (id: string) => Promise<RecalledMessageResponse | null>,+ ) => {+ // `busy` too: a send in flight is about to clear the draft, which would wipe the+ // restored content if the recall slid in between. Both conditions also disable the+ // buttons, so this guard is only the race backstop — the refusal is never silent.+ if (recallingId !== null || busy) return;+ setRecallingId(id);+ try {+ const r = await recall(id);+ if (r) {+ // The mirror entry is gone server-side; drop the local post-202 bridge flag with it,+ // or the bare "steering queued" hint would resurrect once pendingSteering empties.+ setSteerPending(false);+ applyRecalled(r);+ }+ } finally {+ setRecallingId(null);+ }+ };/** 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(@@ -2092,14 +2239,20 @@ export function ChatInput({{/* Mid-run steering queued: the server's undelivered-steering mirror, one line perqueued message with its content — task_state-fed, so it survives reloads (#136,- #140). The local steerPending flag only bridges the gap between the 202 and the- first task_state that carries the mirror. */}+ #140) — plus a recall button that takes the message back into this input for+ editing and resending (#287). The local steerPending flag only bridges the gap+ between the 202 and the first task_state that carries the mirror. */}{pendingSteering.length > 0 ? (<div className="anim-fade mb-1">{pendingSteering.map((p, i) => (- <p key={i} className="truncate text-xs text-gray-400 dark:text-gray-500">- {S.chat.steerQueuedItem(steeringSummary(p))}- </p>+ <QueuedMessageLine+ key={p.id ?? i}+ label={S.chat.steerQueuedItem(steeringSummary(p))}+ disabled={recallingId !== null || busy}+ {...(onRecallSteering && p.id+ ? { onRecall: () => void recallQueued(p.id, onRecallSteering) }+ : {})}+ />))}</div>) : (@@ -2110,12 +2263,29 @@ export function ChatInput({))}- {/* Queued follow-ups (server-side, auto-sent once this run finishes): count from- task_state — survives reloads because the queue lives on the server. */}- {queuedFollowUps > 0 && (- <p className="anim-fade mb-1 text-xs text-gray-400 dark:text-gray-500">- {S.chat.followUpQueuedChip(queuedFollowUps)}- </p>+ {/* Queued follow-ups (server-side, auto-sent once this run finishes): one line per+ queued message with its content and a recall button (#287) — task_state-fed, so it+ survives reloads; the bare count stays as the fallback for a server that predates+ the per-entry list. */}+ {pendingFollowUps.length > 0 ? (+ <div className="anim-fade mb-1">+ {pendingFollowUps.map((p) => (+ <QueuedMessageLine+ key={p.id}+ label={S.chat.followUpQueuedItem(steeringSummary(p))}+ disabled={recallingId !== null || busy}+ {...(onRecallFollowUp+ ? { onRecall: () => void recallQueued(p.id, onRecallFollowUp) }+ : {})}+ />+ ))}+ </div>+ ) : (+ queuedFollowUps > 0 && (+ <p className="anim-fade mb-1 text-xs text-gray-400 dark:text-gray-500">+ {S.chat.followUpQueuedChip(queuedFollowUps)}+ </p>+ ))}{/* Auth-dead session (model credentials failed): slim notice above the composer, samediff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsxindex d365c6c4..1284cd9b 100644--- a/packages/web/src/features/chat/chat-page.tsx+++ b/packages/web/src/features/chat/chat-page.tsx@@ -1095,6 +1095,40 @@ export function ChatPage() {[selected, discardSessionDraft],);+ // Recall a queued message back into the composer (#287): the DELETE returns the original+ // content (text / images / files) and the input area restores it as the draft. A 409+ // not_pending (steering already delivered, follow-up already started) surfaces as a toast;+ // the queued hint retires on its own via the re-broadcast task_state.+ const onRecallSteering = useCallback(+ async (steerId: string) => {+ if (!selected) return null;+ try {+ return await api.recallSteer(selected.sessionId, steerId);+ } catch (e) {+ toastError(apiErrorText(e));+ return null;+ }+ },+ [selected],+ );++ const onRecallFollowUp = useCallback(+ async (followUpId: string) => {+ if (!selected) return null;+ try {+ const res = await api.recallFollowUp(selected.sessionId, followUpId);+ // The follow-up was queued with a per-turn thinking level: restore it with the draft,+ // so an unedited resend goes out exactly as it was queued.+ if (res.thinkingLevel) setTurnThinkingLevel(res.thinkingLevel);+ return res;+ } catch (e) {+ toastError(apiErrorText(e));+ return null;+ }+ },+ [selected],+ );+const onApprove = useCallback(async (toolCallId: string, decision: "allow" | "deny", origin: string[]) => {if (!selected) return;@@ -1381,8 +1415,11 @@ 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}+ onRecallSteering={onRecallSteering}onQueueFollowUp={onQueueFollowUp}queuedFollowUps={stream.queuedFollowUps}+ pendingFollowUps={stream.pendingFollowUps}+ onRecallFollowUp={onRecallFollowUp}onStop={onStop}onCompact={onCompact}modelRef={activeModelRef}diff --git a/packages/web/src/features/chat/recall-draft.ts b/packages/web/src/features/chat/recall-draft.tsnew file mode 100644index 00000000..7324e86c--- /dev/null+++ b/packages/web/src/features/chat/recall-draft.ts@@ -0,0 +1,42 @@+/**+ * How a recalled queued message (#287) merges back into the composer's draft.+ *+ * Pulled out of ChatInput for the same reason as `midRunAction`: the restore makes two small+ * decisions whose reasons are invisible at the call site, and inline they are easy to break+ * one at a time.+ *+ * - The recalled text goes in FRONT of whatever is currently typed — it was composed first —+ * and a newline joins the two only when both sides actually carry text (a whitespace-only+ * draft counts as empty, so the restore never leaves a stray blank line behind it).+ * - A staged goal chip is released when the recall brings file attachments back. A goal+ * draft cannot carry files: engaging the chip clears them and the server refuses them+ * (see ChatInput's toggleGoal), so keeping the chip would park the restored files behind+ * a Send that can never enable — and by the time the composer sees them, their scratchpad+ * copies are already deleted server-side, making the chips the only copy left. Images+ * never release the chip: a goal carries them (folded into the objective as path lines).+ */+export interface RecalledDraftMerge {+ /** The new draft body: recalled text in front, the current draft behind. */+ text: string;+ /** Release the staged goal chip (the recall restored file attachments, which a goal draft cannot carry). */+ dropGoal: boolean;+}++export function mergeRecalledDraft(args: {+ /** The withdrawn message's text, as the server handed it back. */+ recalledText: string;+ /** What is currently typed (the composer's live value, not a stale render's). */+ currentText: string;+ /** Number of file attachments the recall brought back. */+ recalledFiles: number;+ /** Whether the goal chip is currently staged. */+ goalOn: boolean;+}): RecalledDraftMerge {+ const current = args.currentText;+ const text = current.trim()+ ? args.recalledText+ ? `${args.recalledText}\n${current}`+ : current+ : args.recalledText;+ return { text, dropGoal: args.goalOn && args.recalledFiles > 0 };+}diff --git a/packages/web/src/features/chat/use-session-stream.ts b/packages/web/src/features/chat/use-session-stream.tsindex 3f0e9a63..a4476047 100644--- a/packages/web/src/features/chat/use-session-stream.ts+++ b/packages/web/src/features/chat/use-session-stream.ts@@ -18,6 +18,7 @@import { useCallback, useEffect, useRef, useState } from "react";import type {GoalServerEvent,+ PendingFollowUpInfo,PendingSteeringInfo,SessionStatus,} from "@prismshadow/penguin-server/api";@@ -63,6 +64,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[];+ /** 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[];/*** Timestamp (ms) of the last main-session auth failure (request_end with status "auth"),* or null. Derived from the model, so it survives history replay and resets when@@ -114,6 +117,7 @@ export function useSessionStream(const [taskState, setTaskState] = useState<SessionStatus>(initialStatus);const [queuedFollowUps, setQueuedFollowUps] = useState(0);const [pendingSteering, setPendingSteering] = useState<PendingSteeringInfo[]>([]);+ const [pendingFollowUps, setPendingFollowUps] = useState<PendingFollowUpInfo[]>([]);const [error, setError] = useState<string | null>(null);const [pendingTick, setPendingTick] = useState(0);const [goal, setGoal] = useState<GoalBannerState | null>(null);@@ -192,6 +196,7 @@ export function useSessionStream(setTaskState("idle");setQueuedFollowUps(0);setPendingSteering([]);+ setPendingFollowUps([]);setLoading(false);setError(null);setGoal(null);@@ -208,6 +213,7 @@ export function useSessionStream(setGoal(null);setQueuedFollowUps(0);setPendingSteering([]);+ setPendingFollowUps([]);setPendingTick((t) => t + 1);// Restore an in-flight goal's banner (only when still active — a long-finished goal@@ -235,6 +241,7 @@ export function useSessionStream(onTaskState: setTaskState,onQueuedFollowUps: setQueuedFollowUps,onPendingSteering: setPendingSteering,+ onPendingFollowUps: setPendingFollowUps,onLoading: setLoading,onError: setError,onModelChange: bump,@@ -318,6 +325,7 @@ export function useSessionStream(taskState,queuedFollowUps,pendingSteering,+ pendingFollowUps,lastAuthFailureMs: (controllerRef.current?.model ?? placeholderRef.current).lastAuthFailureMs,dismissModelAuthDead,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.tsindex a220010d..6aa153b2 100644--- a/packages/web/src/lib/omni/stream-controller.ts+++ b/packages/web/src/lib/omni/stream-controller.ts@@ -35,6 +35,7 @@ import type {GoalServerEvent,MessagesLiveTail,MessagesPageInfo,+ PendingFollowUpInfo,PendingSteeringInfo,ServerEvent,SessionStatus,@@ -121,6 +122,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;+ /** Queued follow-up tasks carried on task_state events (absent = none): each entry's content + recall handle, alongside the count. */+ onPendingFollowUps?: (items: PendingFollowUpInfo[]) => void;onLoading: (loading: boolean) => void;/** History load failure message (null = clear). */onError: (message: string | null) => void;@@ -290,6 +293,7 @@ export function createStreamController(deps: StreamControllerDeps): StreamControdeps.onTaskState(ev.state);deps.onQueuedFollowUps?.(ev.queued ?? 0);deps.onPendingSteering?.(ev.pendingSteering ?? []);+ deps.onPendingFollowUps?.(ev.pendingFollowUps ?? []);if (ev.state === "idle") {// Task ended (or the snapshot confirms idle): finalize the current Task's stats; pending approvals have already converged server-side.notifyTaskIdle(model);@@ -606,6 +610,7 @@ export function createStreamController(deps: StreamControllerDeps): StreamControdeps.onTaskState(ev.state);deps.onQueuedFollowUps?.(ev.queued ?? 0);deps.onPendingSteering?.(ev.pendingSteering ?? []);+ deps.onPendingFollowUps?.(ev.pendingFollowUps ?? []);}buffer.push({ kind: "server", ev, id: eventId });return;diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex 025fdd9d..a7528952 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -1080,6 +1080,13 @@ Scenarios:/** Server-side queued follow-up count (auto-sent once the current run finishes). */followUpQueuedChip: (n: number) =>`${n} follow-up ${n === 1 ? "message" : "messages"} queued — sent when this run finishes`,+ /** One queued follow-up's hint line, with its content (per-entry variant of followUpQueuedChip). */+ followUpQueuedItem: (content: string) =>+ `Follow-up queued — sent when this run finishes: ${content}`,+ /** Accessible name of the recall control on a queued steering / follow-up line — it is icon-only (a curved-back arrow), so this is what names it for screen readers (#287). */+ recallQueued: "Recall",+ /** Its tooltip: what the icon does, spelled out. */+ recallQueuedTitle: "Recall to the input box to edit and resend",send: "Send",stop: "Stop",compact: "Compact context",@@ -1484,6 +1491,7 @@ Scenarios:schedule_not_found: "This scheduled task no longer exists.",unknown_skill: "This skill is not in the library.",file_not_found: "This file no longer exists.",+ not_pending: "This message already went out and can no longer be recalled.",file_too_large: "The file is too large.",too_many_files: "Too many files attached to one message.",payload_too_large: "The request is too large.",diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex 70ce3f74..d12dd76b 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -1036,6 +1036,12 @@ Benchmark:followUpSend: "排队为下一条消息",/** Server-side queued follow-up count (auto-sent once the current run finishes). */followUpQueuedChip: (n: number) => `${n} 条跟进消息已排队,本轮结束后自动发送`,+ /** One queued follow-up's hint line, with its content (per-entry variant of followUpQueuedChip). */+ followUpQueuedItem: (content: string) => `跟进消息已排队,本轮结束后自动发送:${content}`,+ /** Accessible name of the recall control on a queued steering / follow-up line — it is icon-only (a curved-back arrow), so this is what names it for screen readers (#287). */+ recallQueued: "撤回",+ /** Its tooltip: what the icon does, spelled out. */+ recallQueuedTitle: "撤回到输入框,编辑后重新发送",send: "发送",stop: "停止",compact: "压缩上下文",@@ -1438,6 +1444,7 @@ Benchmark:schedule_not_found: "该定时任务已不存在。",unknown_skill: "该技能不在技能库中。",file_not_found: "该文件已不存在。",+ not_pending: "该消息已发出,无法撤回。",file_too_large: "文件过大。",too_many_files: "一条消息附加的文件过多。",payload_too_large: "请求体过大。",diff --git a/packages/web/test/recall-draft.test.ts b/packages/web/test/recall-draft.test.tsnew file mode 100644index 00000000..78c1fc54--- /dev/null+++ b/packages/web/test/recall-draft.test.ts@@ -0,0 +1,46 @@+/**+ * mergeRecalledDraft: how a recalled queued message (#287) merges back into the composer.+ *+ * Two rules live here. The recalled text goes in front of whatever is typed (it was composed+ * first), joined by a newline only when both sides carry text. And a staged goal chip is+ * released exactly when file attachments come back: a goal draft cannot carry files (engaging+ * the chip clears them, the server refuses them), and the recalled files' scratchpad copies+ * are already deleted server-side — keeping the chip would park their only remaining copy+ * behind a Send that can never enable.+ */+import { describe, expect, it } from "vitest";+import { mergeRecalledDraft } from "../src/features/chat/recall-draft";++const merge = (over: Partial<Parameters<typeof mergeRecalledDraft>[0]> = {}) =>+ mergeRecalledDraft({+ recalledText: "recalled",+ currentText: "",+ recalledFiles: 0,+ goalOn: false,+ ...over,+ });++describe("mergeRecalledDraft — text placement", () => {+ it("recalled text lands in front of the current draft, newline-joined", () => {+ expect(merge({ currentText: "already typed" }).text).toBe("recalled\nalready typed");+ });++ it("either side alone comes through without a stray newline", () => {+ expect(merge().text).toBe("recalled");+ // An attachments-only recall (empty text) leaves the typed draft untouched.+ expect(merge({ recalledText: "", currentText: "already typed" }).text).toBe("already typed");+ });++ it("a whitespace-only draft counts as empty", () => {+ expect(merge({ currentText: " \n " }).text).toBe("recalled");+ expect(merge({ recalledText: "", currentText: " " }).text).toBe("");+ });+});++describe("mergeRecalledDraft — staged goal chip", () => {+ it("releases the chip only when files come back while it is staged", () => {+ expect(merge({ goalOn: true, recalledFiles: 1 }).dropGoal).toBe(true);+ expect(merge({ goalOn: true, recalledFiles: 0 }).dropGoal).toBe(false);+ expect(merge({ goalOn: false, recalledFiles: 1 }).dropGoal).toBe(false);+ });+});diff --git a/packages/web/test/stream-controller.test.ts b/packages/web/test/stream-controller.test.tsindex 4013e2fb..21e7ddca 100644--- a/packages/web/test/stream-controller.test.ts+++ b/packages/web/test/stream-controller.test.ts@@ -20,6 +20,7 @@ import type { OmniMessage, TokenCounts } from "@prismshadow/penguin-core/omnimesimport type {MessagesLiveTail,MessagesPageInfo,+ PendingFollowUpInfo,PendingSteeringInfo,ServerEvent,SessionStatus,@@ -45,6 +46,7 @@ interface Harness {controller: StreamController;states: SessionStatus[];pendingSteering: PendingSteeringInfo[][];+ pendingFollowUps: PendingFollowUpInfo[][];errors: Array<string | null>;loadings: boolean[];loadCalls: () => number;@@ -71,6 +73,7 @@ function createHarness(): Harness {}> = [];const states: SessionStatus[] = [];const pendingSteering: PendingSteeringInfo[][] = [];+ const pendingFollowUps: PendingFollowUpInfo[][] = [];const errors: Array<string | null> = [];const loadings: boolean[] = [];const pageArgs: Array<MessagesPageQuery | undefined> = [];@@ -89,6 +92,7 @@ function createHarness(): Harness {}),onTaskState: (s) => states.push(s),onPendingSteering: (items) => pendingSteering.push(items),+ onPendingFollowUps: (items) => pendingFollowUps.push(items),onLoading: (l) => loadings.push(l),onError: (e) => errors.push(e),onModelChange: () => {},@@ -99,6 +103,7 @@ function createHarness(): Harness {controller,states,pendingSteering,+ pendingFollowUps,errors,loadings,loadCalls: () => calls,@@ -207,11 +212,27 @@ describe("in-stream task_state is the authoritative running state (history-closih.controller.handleServer({type: "task_state",state: "running",- pendingSteering: [{ text: "hold on", images: 0, files: 1 }],+ pendingSteering: [{ id: "st-1", text: "hold on", images: 0, files: 1 }],});// A later event without the field means "none left" — reported as empty, not skipped.h.controller.handleServer({ type: "task_state", state: "running" });- expect(h.pendingSteering).toEqual([[{ text: "hold on", images: 0, files: 1 }], []]);+ expect(h.pendingSteering).toEqual([[{ id: "st-1", text: "hold on", 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();+ h.controller.handleServer({+ type: "task_state",+ state: "running",+ queued: 1,+ pendingFollowUps: [{ id: "fu-1", text: "next up", images: 1, files: 0 }],+ });+ h.controller.handleServer({ type: "task_state", state: "running" });+ expect(h.pendingFollowUps).toEqual([+ [{ id: "fu-1", text: "next up", images: 1, files: 0 }],+ [],+ ]);});it("closes the current Task before an auto-started queued follow-up begins", async () => {