Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(chat): wake subagent waits when sending queued input now
zszz3b4eaa93a6d3e
diff --git a/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx b/apps/desktop/src/features/chat/transcript/AssistantTurn.tsxindex 36ab919a9..17e138d0f 100644--- a/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx+++ b/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx@@ -55,6 +55,7 @@ import { slotMessage } from "../../../plugins/renderer-slots/slot-message";type AssistantTurnProps = {entry: AssistantTurnEntry;isActive: boolean;+ delegationsLive?: boolean;runtimeActivity?: AgentActivity;};@@ -62,7 +63,7 @@ function assistantTurnPropsEqual(previous: AssistantTurnProps,next: AssistantTurnProps,) {- if (previous.isActive !== next.isActive || previous.runtimeActivity !== next.runtimeActivity) return false;+ if (previous.isActive !== next.isActive || previous.delegationsLive !== next.delegationsLive || previous.runtimeActivity !== next.runtimeActivity) return false;if (previous.entry === next.entry) return true;if (previous.entry.id !== next.entry.id ||@@ -132,11 +133,13 @@ export function TranscriptEntryView({entry,isRunning,isActive,+ delegationsLive,runtimeActivity,}: {entry: TranscriptEntry;isRunning: boolean;isActive: boolean;+ delegationsLive?: boolean;runtimeActivity?: AgentActivity;}) {if (entry.kind === "assistant-turn") {@@ -144,6 +147,7 @@ export function TranscriptEntryView({<AssistantTurnentry={entry}isActive={isActive}+ delegationsLive={delegationsLive}runtimeActivity={runtimeActivity}/>);@@ -163,6 +167,7 @@ function transcriptEntryKey(entry: TranscriptEntry): string {type TranscriptHistoryProps = {entries: TranscriptEntry[];isRunning: boolean;+ liveDelegations?: ReadonlyMap<string, true>;};/**@@ -173,6 +178,7 @@ type TranscriptHistoryProps = {export const TranscriptHistory = memo(function TranscriptHistory({entries,isRunning,+ liveDelegations,}: TranscriptHistoryProps) {return (<>@@ -182,6 +188,7 @@ export const TranscriptHistory = memo(function TranscriptHistory({entry={entry}isRunning={isRunning}isActive={false}+ delegationsLive={entry.kind === "assistant-turn" && liveDelegations?.has(entry.id)}/>))}</>@@ -189,6 +196,7 @@ export const TranscriptHistory = memo(function TranscriptHistory({}, (previous, next) => {if (previous.isRunning !== next.isRunning ||+ previous.liveDelegations !== next.liveDelegations ||previous.entries.length !== next.entries.length) {return false;@@ -228,6 +236,7 @@ export const TranscriptTail = memo(function TranscriptTail({export const AssistantTurn = memo(function AssistantTurn({entry,isActive,+ delegationsLive,runtimeActivity,}: AssistantTurnProps) {const { t } = useTranslation();@@ -293,8 +302,8 @@ export const AssistantTurn = memo(function AssistantTurn({// or text and never on a Task's attached child transcript identity.const delegationItems = useMemo(() => tools.map((message) => ({ kind: "tool" as const, message })), [tools]);const rawDelegationStatuses = useMemo(- () => collectDelegationStatuses(delegationItems, { turnLive: isActive }),- [delegationItems, isActive],+ () => collectDelegationStatuses(delegationItems, { turnLive: isActive || delegationsLive === true }),+ [delegationItems, isActive, delegationsLive],);const rawDelegationTimings = useMemo(() => collectDelegationTimings(delegationItems),diff --git a/apps/desktop/src/features/chat/transcript/ChatTranscript.tsx b/apps/desktop/src/features/chat/transcript/ChatTranscript.tsxindex faa7a889e..242d6c41f 100644--- a/apps/desktop/src/features/chat/transcript/ChatTranscript.tsx+++ b/apps/desktop/src/features/chat/transcript/ChatTranscript.tsx@@ -1,4 +1,4 @@-import { memo, type MouseEvent as ReactMouseEvent } from "react";+import { memo, useMemo, useRef, type MouseEvent as ReactMouseEvent } from "react";import { useTranslation } from "react-i18next";import type { PlanningState, UiMessage } from "@pi-desktop/shared";import { proposalKindForMode } from "@pi-desktop/shared";@@ -16,6 +16,8 @@ import {WorkingIndicator,} from "./ActivityGroup";import { TranscriptHistory, TranscriptTail } from "./AssistantTurn";+import { collectLiveDelegationEntries } from "../../../lib/live-delegation-entries";+import { reuseReadonlyMap } from "../../../lib/assistant-turns";import { useTranscriptScroll } from "./hooks/useTranscriptScroll";import type { TranscriptSearchTarget } from "../../../lib/transcript-reading";import { TranscriptSearchContext } from "../../../lib/transcript-search-context";@@ -153,6 +155,13 @@ function TranscriptBody({});const specializedActivity = agentActivity;+ const rawLiveDelegations = useMemo(+ () => collectLiveDelegationEntries(historyEntries, tailEntry, transcriptRunning),+ [historyEntries, tailEntry, transcriptRunning],+ );+ const liveDelegationsRef = useRef(rawLiveDelegations);+ const liveDelegations = reuseReadonlyMap(liveDelegationsRef.current, rawLiveDelegations);+ liveDelegationsRef.current = liveDelegations;const hasSpecializedActivity = specializedActivity !== undefined;// Existing output does not mean the turn has finished: a text stream can// pause, and completed tool rows can outlive their activity. Keep one tail@@ -271,7 +280,7 @@ function TranscriptBody({// view, which is exactly the jitter this avoids.<div className="transcript-hydration-spacer" aria-hidden />) : null}- <TranscriptHistory entries={historyEntries} isRunning={isRunning} />+ <TranscriptHistory entries={historyEntries} isRunning={isRunning} liveDelegations={liveDelegations} />{tailEntry ? (<TranscriptTailentry={tailEntry}diff --git a/apps/desktop/src/lib/live-delegation-entries.ts b/apps/desktop/src/lib/live-delegation-entries.tsnew file mode 100644index 000000000..fca5d65bd--- /dev/null+++ b/apps/desktop/src/lib/live-delegation-entries.ts@@ -0,0 +1,23 @@+import type { TranscriptEntry } from "./assistant-turns";++/** Collect replies in the running turn across steering and compaction. */+export function collectLiveDelegationEntries(+ history: readonly TranscriptEntry[],+ tail: TranscriptEntry | undefined,+ running: boolean,+): ReadonlyMap<string, true> {+ const live = new Map<string, true>();+ if (!running) return live;+ for (let index = history.length; index >= 0; index -= 1) {+ const entry = index === history.length ? tail : history[index];+ if (!entry) continue;+ if (entry.kind === "assistant-turn") {+ live.set(entry.id, true);+ } else if (entry.kind === "message") {+ const { message } = entry;+ if (message.role === "user" && message.steering) continue;+ if (message.role === "user" || message.role === "system") break;+ }+ }+ return live;+}diff --git a/apps/desktop/src/stores/slices/queue-slice.ts b/apps/desktop/src/stores/slices/queue-slice.tsindex dc3fb3f2c..f602b0ea1 100644--- a/apps/desktop/src/stores/slices/queue-slice.ts+++ b/apps/desktop/src/stores/slices/queue-slice.ts@@ -296,30 +296,14 @@ export function createQueueSlice({promptId,),}));- let prioritized = false;try {+ // The Host delivers promoted input into the active turn, or keeps it+ // queued when that turn can no longer accept steering.await api.prioritizeQueuedPrompt(promptId);- prioritized = true;- // Send now keeps its graceful stop: the active turn reaches its- // boundary before the promoted row starts.- if (get().runningSessions[sessionId] &&- queuedPromptForSession(get().queuedPrompts, sessionId, promptId)) {- const result = await api.stop(sessionId);- if (!result.requested) {- await get().refreshQueuedPrompts(sessionId);- if (queuedPromptForSession(get().queuedPrompts, sessionId, promptId)) {- get().showToast(i18n.t("chat.queuedPromptStopFailed"), { variant: "info" });- }- }- }} catch (error) {await get().refreshQueuedPrompts(sessionId);const detail = error instanceof Error ? error.message : String(error);- const stillQueued = queuedPromptForSession(get().queuedPrompts, sessionId, promptId);- get().showToast(- prioritized && stillQueued ? `${i18n.t("chat.queuedPromptStopFailed")} ${detail}` : detail,- { variant: "error" },- );+ get().showToast(detail, { variant: "error" });}},diff --git a/apps/desktop/test/queue-pending-actions.test.mjs b/apps/desktop/test/queue-pending-actions.test.mjsindex c8d259b12..80a284004 100644--- a/apps/desktop/test/queue-pending-actions.test.mjs+++ b/apps/desktop/test/queue-pending-actions.test.mjs@@ -82,6 +82,54 @@ test("sending the first prompt derives a replaceable title instead of renaming",}});+test("Send now promotes queued input without stopping the running session", async () => {+ const server = await createServer({+ root: fileURLToPath(new URL("..", import.meta.url)), configFile: false,+ server: { middlewareMode: true, hmr: false, ws: false }, appType: "custom",+ optimizeDeps: { noDiscovery: true, include: [] },+ });+ const previousWindow = globalThis.window;+ try {+ const { createQueueSlice } = await server.ssrLoadModule("/src/stores/slices/queue-slice.ts");+ const invoked = [];+ let entries = [];+ globalThis.window = { piDesktop: { invoke: async (channel, payload) => {+ invoked.push([channel, payload]);+ if (channel === IPC.invoke.agentQueuePush) {+ const entry = { ...payload, id: "queued-correction", position: 1, createdAt: "2026-10-13T00:00:00Z" };+ entries = [entry];+ return { ok: true, data: entry };+ }+ if (channel === IPC.invoke.agentQueuePrioritize) return { ok: true, data: { ok: true } };+ if (channel === IPC.invoke.agentStop) return { ok: true, data: { requested: true } };+ if (channel === IPC.invoke.agentQueueList) return { ok: true, data: { entries } };+ throw new Error(`Unexpected IPC: ${channel}`);+ } } };+ let state = {+ activeSessionId: "session-a", sessions: [{ id: "session-a", source: "desktop" }],+ pendingPlans: {}, runningSessions: { "session-a": true }, queuedPrompts: {}, showToast: assert.fail,+ };+ const slice = createQueueSlice({+ get: () => state,+ set: (patch) => { state = { ...state, ...(typeof patch === "function" ? patch(state) : patch) }; },+ promptAttachmentsFromDraft: () => [],+ });+ Object.assign(state, slice);+ assert.equal(await slice.sendPrompt("Correct the plan now."), true);+ assert.equal(state.queuedPrompts["session-a"].length, 1);+ assert.equal(invoked.some(([channel]) => channel === IPC.invoke.agentQueuePrioritize), false);+ await slice.sendQueuedNow("queued-correction");+ assert.equal(invoked.filter(([channel]) => channel === IPC.invoke.agentQueuePrioritize).length, 1);+ assert.equal(invoked.some(([channel]) => channel === IPC.invoke.agentStop), false);+ assert.equal(state.runningSessions["session-a"], true);+ slice.applyQueueChanged({ sessionId: "session-a", entries: [] });+ assert.deepEqual(state.queuedPrompts["session-a"] ?? [], []);+ } finally {+ globalThis.window = previousWindow;+ await server.close();+ }+});+test("pending queue actions stay locked until admission succeeds", async (t) => {const server = await createServer({root: fileURLToPath(new URL("..", import.meta.url)),diff --git a/apps/desktop/test/send-now-subagent-rendering.test.mjs b/apps/desktop/test/send-now-subagent-rendering.test.mjsnew file mode 100644index 000000000..916c6b7d5--- /dev/null+++ b/apps/desktop/test/send-now-subagent-rendering.test.mjs@@ -0,0 +1,68 @@+import assert from "node:assert/strict";+import test from "node:test";+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { createInstance } from "i18next";+import { I18nextProvider } from "react-i18next";+import { catalogs } from "@pi-desktop/i18n";+import { createServer } from "vite";+import { fileURLToPath } from "node:url";++test("a steering response keeps the earlier delegation card live until parent settlement", async () => {+ const vite = await createServer({+ root: fileURLToPath(new URL("..", import.meta.url)), configFile: false,+ server: { middlewareMode: true, hmr: false, ws: false },+ esbuild: { jsx: "automatic" }, appType: "custom",+ optimizeDeps: { noDiscovery: true, include: [] },+ });+ try {+ const { TranscriptHistory } = await vite.ssrLoadModule("/src/features/chat/transcript/AssistantTurn.tsx");+ const { buildTranscriptEntries } = await vite.ssrLoadModule("/src/lib/assistant-turns.ts");+ const { collectLiveDelegationEntries } = await vite.ssrLoadModule("/src/lib/live-delegation-entries.ts");+ const { SlotSessionProvider } = await vite.ssrLoadModule("/src/plugins/renderer-slots/use-slots.tsx");+ const i18n = createInstance();+ await i18n.init({ lng: "en", resources: { en: { translation: catalogs.en } } });+ const message = (id, role, content, extra = {}) => ({+ id, role, content, createdAt: "2026-10-13T00:00:00.000Z", ...extra,+ });+ const task = message("task", "tool", "", {+ toolName: "Task", toolCallId: "task", toolStatus: "success",+ toolArgs: { agent: "explorer", task: "Investigate" },+ toolResult: { details: { delegationId: "delegate", status: "running", startedAt: Date.parse("2026-10-13T00:00:00Z") } },+ });+ const messages = [message("user", "user", "Start a delegate."), task,+ message("wait", "tool", "", { toolName: "TaskWait", toolCallId: "wait", toolStatus: "success",+ toolResult: { details: { status: "interrupted", delegations: [{ delegationId: "delegate", status: "running" }] } } }),+ message("steer", "user", "Correct the plan.", { steering: true }),+ message("reply", "assistant", "Correction handled."),+ ];+ const { entries } = buildTranscriptEntries(messages);+ const history = entries.slice(0, -1);+ const render = (liveDelegations) => renderToStaticMarkup(createElement(I18nextProvider, { i18n },+ createElement(SlotSessionProvider, { sessionId: "fixture" },+ createElement(TranscriptHistory, { entries: history, isRunning: true, liveDelegations }))));+ const live = render(collectLiveDelegationEntries(history, entries.at(-1), true));+ assert.match(live, /Subagent working/);+ assert.match(live, /Stop explorer/);+ assert.doesNotMatch(live, /Subagent finished with warnings/);+ const settled = render(collectLiveDelegationEntries(history, entries.at(-1), false));+ assert.doesNotMatch(settled, /Subagent working/);+ assert.doesNotMatch(settled, /Stop explorer/);+ const beforeReply = entries.slice(0, -1);+ assert.equal(collectLiveDelegationEntries(beforeReply.slice(0, -1), beforeReply.at(-1), true).has("task"), true);+ const nextUser = { kind: "message", message: message("next", "user", "Next task.") };+ assert.equal(collectLiveDelegationEntries(entries, nextUser, true).has("task"), false);+ assert.equal(collectLiveDelegationEntries(entries, { kind: "message", message: message("system", "system", "Restart") }, true).has("task"), false);+ const compaction = { kind: "compaction", mark: { id: "checkpoint" } };+ assert.equal(collectLiveDelegationEntries([...history, compaction], entries.at(-1), true).has("task"), true);+ const completedTask = { ...task, toolResult: { details: { delegationId: "delegate", status: "completed" } } };+ const completeEntries = buildTranscriptEntries(messages.map(m => m.id === task.id ? completedTask : m)).entries;+ const completeHistory = completeEntries.slice(0, -1);+ const completedHtml = renderToStaticMarkup(createElement(I18nextProvider, { i18n },+ createElement(SlotSessionProvider, { sessionId: "fixture" },+ createElement(TranscriptHistory, { entries: completeHistory, isRunning: true,+ liveDelegations: collectLiveDelegationEntries(completeHistory, completeEntries.at(-1), true) }))));+ assert.match(completedHtml, /Subagent completed/);+ assert.doesNotMatch(completedHtml, /Stop explorer/);+ } finally { await vite.close(); }+});diff --git a/docs/adr/0213-persist-host-owned-turn-queue.md b/docs/adr/0213-persist-host-owned-turn-queue.mdindex d4ed6449b..15c469332 100644--- a/docs/adr/0213-persist-host-owned-turn-queue.md+++ b/docs/adr/0213-persist-host-owned-turn-queue.md@@ -42,7 +42,8 @@ table and RPC surface, not a file the module writes.work.4. **The renderer's in-memory queue is retired.** The composer pushesthrough `agent/queue/push`, mirrors `agent/event/queueChanged`, and its- "send now" is `agent/queue/prioritize` followed by a graceful stop.+ "send now" uses `agent/queue/prioritize` to deliver promoted input into the+ current turn through steering (ADR 0265, issue #1607).5. **Schema v20 extends queued input provenance.** `user_message_id` preservesthe stable user row across queue recovery, and `voice_origin_json` recordsthe originating Live Voice call and operation. Both columns are nullable,diff --git a/docs/adr/0265-turn-queue-priority-block-and-row-actions.md b/docs/adr/0265-turn-queue-priority-block-and-row-actions.mdindex e68749ba9..efb5698e5 100644--- a/docs/adr/0265-turn-queue-priority-block-and-row-actions.md+++ b/docs/adr/0265-turn-queue-priority-block-and-row-actions.md@@ -31,16 +31,16 @@ queue at all even though the Host already orders it by a durable `position`.instead of silently moving it again. `session.queuePrioritize` keeps movingoptimistic mirror does the same.3. **Promotion fixes order, but does not prevent cancellation.** A promoted- row disables move up, move down, edit, and Send now. Its label explains that- it is waiting for the current task to finish. Remove remains available until- delivery, and the renderer waits for Host confirmation before removing it.+ row disables move up, move down, edit, and Send now. Its label is Waiting to+ send. Remove remains available until delivery, and the renderer waits for+ Host confirmation before removing it.Cancellation, promotion, reordering, and delivery reservation share sessionadmission serialization. Runtime delivery runs outside that lock and reservesonly its own input. Once an input is reserved or accepted as steering input,cancellation returns `CONFLICT`; consuming an input in another turn must- not be mistaken for an earlier successful cancellation. A refused or failed- graceful stop is reported without discarding the queued input. There is no- un-promote path. Acceptance is recorded before durable cleanup; failed cleanup+ not be mistaken for an earlier successful cancellation. Refused steering+ retains the queued input for the next turn. There is no un-promote path.+ Acceptance is recorded before durable cleanup; failed cleanupemits an error and remains retryable without re-execution in the live Host.The queue retains its record when persistence fails. Acceptance is an in-memoryguard, not a durable receipt: restart after failed cleanup retains the existing@@ -59,17 +59,18 @@ queue at all even though the Host already orders it by a durable `position`.refused with a toast while the input is non-empty, and the emptiness checkruns against the live editor read because the draft cache is not written perkeystroke.-6. **The promoted block is delivered as adjacent messages, not as separate- turns.** Promotion still does not touch the running turn by itself: the- renderer requests the existing graceful `agent/stop`, and the block leaves at- the next boundary. The first promoted entry then starts the turn, and every- later promoted entry is injected into that same turn as user input over the- Composer's existing steering channel. The transcript therefore reads- `user: first`, `user: second` and the model answers once. The injection is- retried a bounded number of times because the runtime only accepts input for- a live run; an entry that is still undelivered stays queued and leaves at the- next boundary as its own turn, which is the previous behavior and never a- lost prompt. An injected entry's own RACP turn is canceled: its input was+6. **The promoted block is delivered into the active turn.** Promotion uses+ steering so the parent handles user input while delegates keep working+ (issue #1607). An active `TaskWait` yields to accepted steering; ordinary+ tools keep their normal boundaries. Immediate delivery accepts only the+ paired caller's own input with the active turn's permission mode. External+ Desktop turns use the stored session mode; module-admitted turns use their+ principal-specific ceiling. Other input retains turn-boundary delivery.+ When there is no active turn, the first promoted entry starts the turn and+ later promoted entries join it as steering input, in click order.+ Runtime refusals are retried within a bounded budget. Undelivered input+ remains queued for its own turn at the next boundary.+ An injected entry's own RACP turn is canceled: its input wasdelivered by another turn, and no client may be left believing it is stillwaiting.7. **The turn's owner is authoritative about its end.** A runtime terminal eventdiff --git a/docs/adr/active-turn-steering.md b/docs/adr/active-turn-steering.mdindex 4f997034e..b7809b2f3 100644--- a/docs/adr/active-turn-steering.md+++ b/docs/adr/active-turn-steering.md@@ -20,8 +20,10 @@ attachment validation against the running model and workspace; the sidecarrechecks the target after asynchronous preparation and calls `Agent.steer`.Steering keeps the active configuration and durable turn. Started tools finish-before the next model request consumes input. The runtime handles admission-at its closing boundary and while awaiting delegates. Stop closes admission+before the next model request consumes input, except `TaskWait`, which yields+to accepted user input without canceling its delegates (issue #1607). The+runtime handles admission at its closing boundary and while awaiting delegates.+Stop closes admissionand retains accepted input as history without independently replaying it.The existing event-persistence module journals input through the outbox.diff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.mdindex dcdf1e96c..a5ee9d72f 100644--- a/docs/spec/03-runtime/01-ipc-protocol.md+++ b/docs/spec/03-runtime/01-ipc-protocol.md@@ -306,9 +306,8 @@ finalized as `completed`; the request does not abort the provider stream,cancel running tools, or open a second concurrent turn. An idle session returns`requested: false`.-The renderer owns the removable, in-memory queued-prompt list per session. It-calls this channel only for a queued item's **Send now** action and releases-that item through the ordinary `agent/prompt` flow after the terminal event.+The Host owns the persisted prompt queue. **Send now** uses queue promotion and+steering into the active turn; it does not call this graceful-stop channel.### 5.2a stop-subagents@@ -593,10 +592,14 @@ entries and `IDEMPOTENCY_CONFLICT` when a key is reused with other input.`entries` arrive in delivery order: promoted entries first in ascending`priority` (the order they were promoted), then every remaining entry by`position`. `prioritize` appends an entry to the end of that priority block-without touching the running turn, refuses an entry that already carries a-priority with `CONFLICT`, and refuses a turn that is no longer queued. The-renderer's "send now" then requests a graceful stop so the entry starts at-the next boundary. `reorder` swaps one non-promoted entry with its adjacent+and attempts steering delivery into the active runtime turn, refuses an entry+that already carries a priority with `CONFLICT`, and refuses a turn that is no+longer queued. Delivery runs outside the session admission lock, reserves only+the input being delivered, and never requests stop or abort. A queued input+with a different effective permission mode stays queued so its own grants are+preserved. Immediate promotion delivers only the paired caller's own input;+other principals retain the existing turn-boundary delivery and queue policy.+`reorder` swaps one non-promoted entry with its adjacentnon-promoted neighbour and reports `moved: false` for a promoted entry, amissing entry, or a block/queue edge; a promoted entry is never a neighbour.`remove` cancels an entry that has not started. A restored queue stays held@@ -604,10 +607,11 @@ until the desktop attaches as the owner, so a reboot never starts workunattended.The promoted block is delivered as adjacent messages rather than as separate-turns: the first promoted entry starts the turn at the boundary and every later-promoted entry is injected into that same turn through the steering channel+turns: promoted entries join the active turn through the steering channel+when it accepts input. With no active turn, the first promoted entry starts+the turn and every later promoted entry is injected into that same turn(`pi-desktop/agent/steer` with the running turn's id), so the transcript shows-the user rows one after another and the model answers once. An injected entry+the user rows in click order within one turn. An injected entryleaves the queue and its own turn is canceled because it never runs on its own.An entry the runtime refuses to accept stays queued and leaves at the nextboundary as its own turn.diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.mdindex faf09f5d3..af6b8df8e 100644--- a/docs/spec/03-runtime/02-agent-runtime.md+++ b/docs/spec/03-runtime/02-agent-runtime.md@@ -88,8 +88,11 @@ when another input arrives before the initial user message has been consumed.An admission after pi's last queue poll suppresses the terminal event andcontinues once pi has released the run, with the same turn identity and withouta second public `agent_start`. Existing context/provider recovery takes-precedence over that continuation. Steering also wakes a parent that is idle-waiting for background delegates; it does not cancel those delegates.+precedence over that continuation. Steering wakes both a parent that is idle+waiting for background delegates and an active `TaskWait`; it does not cancel+those delegates. `TaskWait` returns `details.status: "interrupted"`, includes+the current delegation states, and tells the parent to handle the new user+input before waiting again. The same durable turn and pending reports remain.Abort, graceful stop, fatal errors and terminal settlement close admission.Accepted but unconsumed input remains transcript/context history and is removeddiff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex 66e46e854..5dba0c330 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -2422,6 +2422,12 @@ summary can wrap rather than forcing the user to resize the divider. Completedescriptions remain available through the node's accessible name/hover title;the node and its live process never create horizontal overflow.+An accepted steering message creates a new visual reply without ending the+parent runtime turn. Earlier delegation cards in that running turn keep their+live status and Stop controls across steering replies and compaction dividers.+A new ordinary user turn, parent settlement, or history reading ends that live+projection; terminal Task snapshots still take precedence.+The lifecycle rows (`TaskWait`/`TaskList`/`TaskStop`) stay compact tool rows —they are not topology nodes and must not inflate the subagent counts — but theyare presented as subagent rows rather than as generic tool calls (D269). A@@ -3009,20 +3015,20 @@ reasoning-level control.after an app restart, when that in-memory draft is unavailable, restore theHost-stored content and image/file attachments without rewriting the content;while the input is non-empty (or holds attachments) the action is refused with- a toast and nothing changes. Remove drops the row immediately.+ a toast and nothing changes. Remove drops the row after Host acknowledgement.- Send now: promotes the row to the end of the session's priority block, so asecond Send now leaves behind the first instead of replacing it at the head.- It then requests `agent/stop`, and the promoted block is released after the- current reply/tool batch completes normally, before every waiting row. The- first promoted row starts the turn and the rest join it as adjacent user- messages, so the block is answered once. When idle it starts immediately.+ The Host delivers promoted input into the current turn through steering;+ it does not request `agent/stop`. `TaskWait` yields without canceling delegates.+ Refused input or an input with a different effective permission mode retains+ its durable queue entry until the next turn. When idle it starts immediately.- A pending queue row is locked until Host admission returns its durable id: moveup/down, Send now, edit, and remove are disabled. All five tooltips explainthat it is saving; Send now also displays the localized Saving label. Direct edit/remove actions leave the pending row and draftunchanged; after admission, ordinary waiting-row actions become available.- A promoted row fixes order: move up/down and edit are disabled withtheir tooltip and `aria-disabled` state intact, and the Send now button reads- as waiting for the current task (`chat.sendNowPending`). Remove remains+ Waiting to send (`chat.sendNowPending`). Remove remainsavailable until delivery and waits for Host acknowledgement. If deliveryalready started, show a conflict message directing the user to Stop.The row carries a distinctdiff --git a/docs/spec/04-ux/09-interaction-patterns.md b/docs/spec/04-ux/09-interaction-patterns.mdindex d5f1a728b..f0c52fad5 100644--- a/docs/spec/04-ux/09-interaction-patterns.md+++ b/docs/spec/04-ux/09-interaction-patterns.md@@ -788,13 +788,13 @@ may be retained while exactly one workspace supplies the visible shell context.returns a durable id. While admission is pending, row actions are disabledwith Saving tooltips and a Saving label on Send now; edit/remove leave boththe queue and composer draft unchanged.-- Send now moves its row to the head and requests the new `agent/stop` channel.- The current assistant response and completed tool batch finish normally;- after `agent_end` and durable turn finalization, the promoted row is- dispatched through the normal `agent/prompt` flow before the remaining rows.- An idle Send now dispatches immediately. While waiting, promoted rows retain- Remove and explain that the current task must finish. A refused or failed- graceful stop reports an error without losing the queued message. Removal+- Send now promotes its row in click order and asks the Host to deliver it as+ steering input into the active turn. It does not request a stop. An active+ `TaskWait` returns early so the parent handles the new input while its+ delegates keep working. Other started tools retain their normal boundaries.+ An idle Send now dispatches immediately. Refused input or an input admitted+ under a different permission mode stays queued for the next turn. Promoted+ rows retain Remove until delivery and show Waiting to send. Removalwaits for Host acknowledgement; if delivery wins the race, report that themessage has already started and direct the user to Stop.- Without Send now, the next FIFO row starts automatically after the active@@ -1635,8 +1635,9 @@ This does not prevent state changes — it makes them instant.1. All keyboard shortcuts in §1 are functional and do not conflict with system shortcuts2. Enter sends when Enter-to-send is on; when it is off, Cmd/Ctrl+Enter sends and Enter/Shift+Enter insert a newline3. Abort immediately cancels running turn and pending permissions without confirmation dialog-3a. Send stays enabled while running, queues prompts per session, and Send now- finishes the current boundary before releasing its prioritized prompt+3a. Send stays enabled while running and queues prompts per session. Send now+ delivers promoted input into the current turn and wakes `TaskWait` without+ canceling delegates; refused input stays queued.4. Long content (>50 lines for messages, >10 for args, >20 for results) is collapsed by default with expand link5. Tool results that were cut short show a truncation marker or chip per D306; a filled Read window of a longer file does not6. Permission interrupt inserts an inline card, disables the composer, anddiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 0e304861c..02af329a0 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -8,6 +8,37 @@## 1. Goals+### E2E-QUEUE-send-now-wakes-subagents++- **Preconditions:** Dedicated request worktree with built workspace packages,+ compatible reused Host binary, temporary HOME/data/project, and a local SSE+ model fixture. Production Composer queue service, Main IPC, AgentHost, Rust+ Host and agent sidecar are used; no installed app or real account is used.+ The fixture requires Linux/macOS HOME isolation and refuses Windows before+ Host startup because known-folder lookup does not honor that isolation.+- **Steps:** Start two background delegates and let the parent enter TaskWait.+ Submit ordinary FIFO input and a correction, then choose Send now on the+ correction. Hold both delegate responses until the parent answers the+ correction. Release both responses and observe report delivery and FIFO drain.+- **Expected:** The correction reaches the same durable turn, TaskWait returns+ interrupted, and neither delegate is aborted. The correction appears once+ in history and leaves the durable queue only after acceptance. Ordinary+ input remains queued until parent settlement. Both reports reach the parent+ and the remaining FIFO input runs once. No graceful stop is requested.+ In rendered Electron, expand the earlier process after the steering reply:+ both delegate nodes remain running with Stop controls, then become completed+ after their reports arrive; the ordinary queued row remains until settlement.+- **Coverage:** `pnpm test:e2e:send-now-subagents` runs the headless process+ journey; append `-- --auto` to repeat with the session in auto mode.+ `queue-pending-actions.test.mjs` covers normal send followed by Send+ now through the production renderer service. AgentHost tests cover click+ order, concurrent delivery/cancellation, stale targets, and permission-mode+ preservation; runtime tests cover input before/during TaskWait and existing+ stop/dispose behavior. `send-now-subagent-rendering.test.mjs` covers the+ steering transcript path, parent settlement, ordinary-turn boundaries,+ compaction, and terminal Task snapshots through the real React rendering.+ The headless command does not replace the rendered Electron check above.+### E2E-STORAGE-custom-location-and-maintenance- **Preconditions:** Dedicated request worktree, current remote-main base, shared@@ -2131,7 +2162,7 @@ identify the platform validation still needed.composer. 3) Remove the second queued row and switch to B. 4) Send a promptin B, then return to A before either run completes. 5) Choose Send now on A'sremaining queued row, then choose Send now on a second row. 6) Observe A- through the current tool/reply boundary and then the next turn. 7) Start+ through the next model request within the same turn. 7) Startanother run in A, clear the draft to expose the single Stop button, pressStop, and inspect the queue. 8) Repeat with two queued prompts, let the activeturn finish without Send now, and delay its host `session.endTurn` response@@ -2147,11 +2178,10 @@ identify the platform validation still needed.state: disabled Send while idle and empty, enabled Send while running withcontent (which queues the prompt), and Stop while running with an emptydraft. A's two prompts appear in FIFO order, the removed row never sends,- and B's queue remains independent. Send now requests a graceful stop: the- current batch completes with a normal `agent_end`/completed turn, then the- promoted rows are delivered in the order they were promoted, before any- waiting row, without `AGENT_BUSY`: the first starts the turn and the rest join- it as adjacent user messages, so the model answers once for the whole block.+ and B's queue remains independent. Send now delivers promoted input in click+ order into the current turn without requesting a stop. An active TaskWait+ yields to the input while delegates keep running. Refused input or input+ with a different permission mode remains queued for a later turn.A promoted row locks move/edit and Send now, but permits removal; promotion isone-way. Move up/down swaps only waiting rows, never crosses the promotedblock, and persists. Edit is refused with a visible message while the input@@ -2186,14 +2216,14 @@ identify the platform validation still needed.least one completed tool batch; three prompts are queued behind it.the first queued row. 3) Confirm the promoted block orders third → first, thatboth rows lock their move/edit actions, and that the remaining row is- still editable. 4) Let the boundary pass and observe the transcript.+ still editable. 4) Observe steering delivery at the next model request.- **Expected**: The first click is delivered first and the second second — theclick order is the delivery order, not "last click wins" and not the original- queue order. Both rows appear as adjacent user messages in one turn and the- model answers once; the queue no longer lists either promoted row. Both+ queue order. Both rows appear as user messages in the same active turn;+ the queue no longer lists either accepted promoted row. Bothpromoted rows show as waiting and cannot be edited or reordered. Removal- remains available until delivery. A refused or failed graceful stop reports- a message and leaves the row cancelable. If cancellation wins admission,+ remains available until delivery. Refused steering retains the row for the+ next turn and leaves it cancelable. If cancellation wins admission,the input never executes; if delivery wins, cancellation reports that italready started. The row disappears only after Host acknowledgement.A stalled steering delivery does not block admission or cancellation of otherdiff --git a/package.json b/package.jsonindex 684058061..0c3c85449 100644--- a/package.json+++ b/package.json@@ -64,6 +64,7 @@"test:e2e:work-panel-drag": "node scripts/e2e-work-panel-drag.mjs","test:e2e:supervision": "node scripts/e2e-supervision.mjs","test:e2e:subagents": "node scripts/e2e-subagents.mjs",+ "test:e2e:send-now-subagents": "node scripts/e2e-send-now-subagents.mjs","test:e2e:subagent-parent-error": "node scripts/e2e-subagent-parent-error.mjs","test:e2e:subagent-models": "node scripts/e2e-subagent-models.mjs","check:marketplace": "node scripts/check-marketplace-catalog.mjs",diff --git a/packages/agent-host/src/agent-host.test.ts b/packages/agent-host/src/agent-host.test.tsindex c93c85bfd..22d80e77f 100644--- a/packages/agent-host/src/agent-host.test.ts+++ b/packages/agent-host/src/agent-host.test.ts@@ -516,8 +516,39 @@ describe("AgentHost turns", () => {});+ it("delivers Send now into the active turn without stopping it or draining ordinary input", async () => {+ const { host, runtime } = build();+ const first = await host.startTurn(owner, { sessionId: "s1", input: { text: "original task" }, context: { requestId: "initial" } });+ const second = await host.startTurn(owner, { sessionId: "s1", admission: "queue", input: { text: "ordinary follow-up" }, context: { requestId: "queued" } });+ const attachments = [{ kind: "file" as const, path: "/fixture/notes.txt", name: "notes.txt" }];+ const correction = await host.startTurn(owner, {+ sessionId: "s1", admission: "queue",+ input: { text: "correct the plan", userMessageId: "correction-user", attachments },+ context: { requestId: "correction" },+ });+ expect(runtime.steers).toEqual([]);++ await host.prioritizeTurn(owner, correction.turn.id);++ expect(runtime.steers).toEqual([expect.objectContaining({+ sessionId: "s1", turnId: "rt_1", content: "correct the plan",+ userMessageId: "correction-user", attachments,+ })]);+ expect(runtime.stops).toEqual([]);+ expect(runtime.aborts).toEqual([]);+ expect(runtime.prompts.map((entry) => entry.content)).toEqual(["original task"]);+ expect(host.getTurn(first.turn.id).status).toBe("running");+ expect(host.getTurn(correction.turn.id).status).toBe("canceled");+ expect(host.queueEntries("s1").map((entry) => entry.turn.id)).toEqual([second.turn.id]);++ host.endTurn("s1", "rt_1", "completed");+ await vi.waitFor(() => expect(runtime.prompts.map((entry) => entry.content)).toEqual(["original task", "ordinary follow-up"]));+ expect(runtime.steers).toHaveLength(1);+ });+it("folds the rest of the promoted block into the started turn, in click order", async () => {const { host, runtime } = build();+ runtime.refuseSteers = true;const first = await host.startTurn(controller, { sessionId: "s1", input: { text: "one" }, context: { requestId: "r1" } });host.ingest(envelope("s1", first.turn.id, { type: "agent_start" }));const second = await host.startTurn(controller, { sessionId: "s1", admission: "queue", input: { text: "two" }, context: { requestId: "r2" } });@@ -528,6 +559,7 @@ describe("AgentHost turns", () => {await host.prioritizeTurn(controller, second.turn.id);expect(host.queueEntries("s1").map((entry) => entry.content)).toEqual(["three", "two"]);+ runtime.refuseSteers = false;host.ingest(envelope("s1", first.turn.id, { type: "agent_end", messageIds: [] }));await new Promise((resolve) => setTimeout(resolve, 0));await new Promise((resolve) => setTimeout(resolve, 0));@@ -543,6 +575,104 @@ describe("AgentHost turns", () => {expect(host.getTurn(third.turn.id).status).toBe("running");});+ it("retains queued input whose permission mode differs from the active turn", async () => {+ const { host, runtime } = build({ permissionMode: "auto" });+ const first = await host.startTurn(owner, { sessionId: "s1", input: { text: "owner task" }, context: { requestId: "owner" } });+ const queued = await host.startTurn(controller, {+ sessionId: "s1", admission: "queue", input: { text: "remote input" }, context: { requestId: "remote" },+ });+ expect(first.turn.effectivePermissionMode).toBe("auto");+ expect(queued.turn.effectivePermissionMode).toBe("ask");++ await host.prioritizeTurn(controller, queued.turn.id);++ expect(runtime.steers).toEqual([]);+ expect(runtime.stops).toEqual([]);+ expect(host.queueEntries("s1").map((entry) => entry.turn.id)).toEqual([queued.turn.id]);+ host.endTurn("s1", "rt_1", "completed");+ await vi.waitFor(() => expect(runtime.prompts).toHaveLength(2));+ expect(runtime.prompts[1]?.effectivePermissionMode).toBe("ask");+ });++ it("delivers into an externally started Desktop turn using the stored session mode", async () => {+ const { host, runtime } = build({ permissionMode: "auto" });+ host.ingest(envelope("s1", "desktop-turn", { type: "agent_start" }));+ const correction = await host.startTurn(owner, { sessionId: "s1", admission: "queue", input: { text: "correct now" }, context: { requestId: "correction" } });+ await host.prioritizeTurn(owner, correction.turn.id);+ expect(runtime.steers).toEqual([expect.objectContaining({ turnId: "desktop-turn", content: "correct now" })]);+ expect(host.queueEntries("s1")).toEqual([]);+ expect(runtime.stops).toEqual([]);+ });++ it.each([controller, owner])("keeps remote input queued when promoting into an externally started Desktop turn ($subject)", async (promoter) => {+ const { host, runtime } = build();+ host.ingest(envelope("s1", "desktop-turn", { type: "agent_start" }));+ const queued = await host.startTurn(controller, { sessionId: "s1", admission: "queue", input: { text: "remote input" }, context: { requestId: "remote" } });+ await host.prioritizeTurn(promoter, queued.turn.id);+ expect(runtime.steers).toEqual([]);+ expect(host.queueEntries("s1").map((entry) => entry.turn.id)).toEqual([queued.turn.id]);+ expect(runtime.stops).toEqual([]);+ });++ it("preserves boundary delivery for an unpaired controller's Send now", async () => {+ const { host, runtime } = build();+ const first = await host.startTurn(controller, { sessionId: "s1", input: { text: "remote task" }, context: { requestId: "first" } });+ const queued = await host.startTurn(controller, { sessionId: "s1", admission: "queue", input: { text: "remote follow-up" }, context: { requestId: "second" } });+ await host.prioritizeTurn(controller, queued.turn.id);+ expect(runtime.steers).toEqual([]);+ expect(host.queueEntries("s1")).toHaveLength(1);+ host.endTurn("s1", first.turn.id, "completed");+ await vi.waitFor(() => expect(runtime.prompts.map((entry) => entry.content)).toEqual(["remote task", "remote follow-up"]));+ });++ it("serializes concurrent Send now deliveries without stopping or duplicating input", async () => {+ const { host, runtime } = build();+ await host.startTurn(owner, { sessionId: "s1", input: { text: "original" }, context: { requestId: "original" } });+ const first = await host.startTurn(owner, { sessionId: "s1", admission: "queue", input: { text: "first correction" }, context: { requestId: "first" } });+ const second = await host.startTurn(owner, { sessionId: "s1", admission: "queue", input: { text: "second correction" }, context: { requestId: "second" } });+ let acknowledge!: () => void;+ const pending = new Promise<void>((resolve) => { acknowledge = resolve; });+ runtime.steer = async (request) => {+ runtime.steers.push(request);+ if (request.content === "first correction") await pending;+ return { accepted: true };+ };+ const firstSend = host.prioritizeTurn(owner, first.turn.id);+ await vi.waitFor(() => expect(runtime.steers).toHaveLength(1));+ await host.prioritizeTurn(owner, second.turn.id);+ await expect(host.prioritizeTurn(owner, first.turn.id)).rejects.toMatchObject({ code: "CONFLICT" });+ await expect(host.cancelTurn(owner, first.turn.id)).rejects.toMatchObject({ code: "CONFLICT" });+ expect(runtime.steers.map((entry) => entry.content)).toEqual(["first correction"]);+ acknowledge();+ await firstSend;+ expect(runtime.steers.map((entry) => entry.content)).toEqual(["first correction", "second correction"]);+ expect(host.queueEntries("s1")).toEqual([]);+ expect(runtime.stops).toEqual([]);+ });++ it("preserves queued input when its target turn ends during steering admission", async () => {+ const { host, runtime } = build();+ await host.startTurn(owner, { sessionId: "s1", input: { text: "original" }, context: { requestId: "original" } });+ const queued = await host.startTurn(owner, { sessionId: "s1", admission: "queue", input: { text: "correction" }, context: { requestId: "correction" } });+ let refuse!: () => void;+ const pending = new Promise<void>((resolve) => { refuse = resolve; });+ const attempted: string[] = [];+ runtime.steer = async (request) => {+ attempted.push(request.turnId);+ await pending;+ return { accepted: false };+ };+ const send = host.prioritizeTurn(owner, queued.turn.id);+ await vi.waitFor(() => expect(attempted).toEqual(["rt_1"]));+ host.endTurn("s1", "rt_1", "completed");+ expect(host.queueEntries("s1")).toHaveLength(1);+ refuse();+ await send;+ await vi.waitFor(() => expect(runtime.prompts.map((entry) => entry.content)).toEqual(["original", "correction"]));+ expect(attempted).toEqual(["rt_1"]);+ expect(host.queueEntries("s1")).toEqual([]);+ });+it("keeps a promoted row queued when the runtime cannot steer it", async () => {const { host, runtime } = build();runtime.refuseSteers = true;diff --git a/packages/agent-host/src/agent-host.ts b/packages/agent-host/src/agent-host.tsindex c80cda617..86bb3c742 100644--- a/packages/agent-host/src/agent-host.ts+++ b/packages/agent-host/src/agent-host.ts@@ -701,11 +701,11 @@ export class AgentHost {});}- /** Promote a queued turn to the end of its session's priority block ("send now"). */+ /** Promote queued input and deliver it into the active turn when possible. */async prioritizeTurn(principal: Principal, turnId: string): Promise<RacpTurn> {this.requireRole(principal, "turn/prioritize");const state = this.stateForTurn(turnId);- return this.withAdmission(state.id, async () => {+ const runtimeTurnId = await this.withAdmission(state.id, async () => {const turn = state.turns.get(turnId)!;if (turn.deliveryPending || turn.deliveredIntoTurnId || turn.status !== "queued") {throw racpError("CONFLICT", "only a queued turn can be prioritized");@@ -714,8 +714,17 @@ export class AgentHost {throw racpError("CONFLICT", "the turn is already prioritized");}this.afterQueueMove(state, turn.id);- return this.toRacpTurn(state, turn);+ return this.activeRuntimeTurnId(state);});+ // Runtime delivery stays outside admission so slow steering cannot block+ // cancellation or admission of other inputs.+ if (runtimeTurnId) await this.deliverPromotedBlock(state, runtimeTurnId, principal);+ return this.toRacpTurn(state, this.ensureTurn(state, turnId));+ }++ private activeRuntimeTurnId(state: SessionState): string | undefined {+ const turn = state.activeTurnId ? state.turns.get(state.activeTurnId) : undefined;+ return turn && isActive(turn.status) ? turn.runtimeTurnId ?? turn.id : undefined;}/**@@ -1039,24 +1048,30 @@ export class AgentHost {}/**- * Deliver the promoted entries that are still queued into the turn that just- * started, so "Send now" twice puts both messages in front of the model- * together instead of spreading them over two turns (ADR 0265).- *- * The runtime only accepts input for a turn whose run is live, so a refusal is- * retried a bounded number of times. Anything still undelivered stays queued- * and leaves at the next boundary as its own turn: the previous behavior is- * the fallback, never a lost prompt.+ * Deliver promoted input into the active runtime turn (ADR 0265).+ * Runtime refusals are retried within a bounded budget; undelivered input+ * remains queued for its own turn at the next boundary.*/- private async deliverPromotedBlock(state: SessionState, runtimeTurnId: string): Promise<void> {+ private async deliverPromotedBlock(state: SessionState, runtimeTurnId: string, principal?: Principal): Promise<void> {const steer = this.runtime.steer?.bind(this.runtime);if (!steer) return;for (let attempt = 0; attempt < PROMOTED_DELIVERY_ATTEMPTS; attempt += 1) {const head = await this.withAdmission(state.id, async () => {const record = this.queue.peek(state.id);if (!record || record.priority === undefined) return undefined;- const active = state.activeTurnId ? state.turns.get(state.activeTurnId) : undefined;- if (!active || active.runtimeTurnId !== runtimeTurnId) return undefined;+ if (this.activeRuntimeTurnId(state) !== runtimeTurnId) return undefined;+ const active = state.turns.get(state.activeTurnId!);+ const externalDesktopTurn = active?.principalSubject === undefined && active?.runtimeTurnId === undefined;+ // Immediate delivery accepts only the paired caller's own input.+ if (principal && (!principal.pairedDevice || record.principalSubject !== principal.subject)) return undefined;+ // Desktop turns require a caller because they have no module admission ceiling.+ if (externalDesktopTurn && !principal) return undefined;+ // Steering preserves grants: Desktop turns use the session mode;+ // module-admitted turns use their principal-specific ceiling.+ const activePermissionMode = externalDesktopTurn+ ? state.permissionMode+ : active?.effectivePermissionMode;+ if (activePermissionMode !== record.effectivePermissionMode) return undefined;const turn = this.ensureTurn(state, record.id);if (turn.deliveryPending || turn.deliveredIntoTurnId) return undefined;turn.deliveryPending = true;diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.tsindex 090d4c9dd..ae5998edb 100644--- a/packages/agent-runtime/src/runtime.test.ts+++ b/packages/agent-runtime/src/runtime.test.ts@@ -8329,6 +8329,70 @@ describe("DesktopAgentRuntime subagents", () => {},);+ it.each(["during", "before"] as const)("handles steering %s TaskWait while its delegate continues running", async (timing) => {+ subagentRuns.calls.length = 0;+ subagentRuns.instances.length = 0;+ subagentRuns.deferred = true;+ subagentRuns.result = undefined;+ let waiting!: () => void;+ const beganWaiting = new Promise<void>((resolve) => { waiting = resolve; });+ const runtime = createRuntime({ subagents: [explorer], onEvent: (value) => {+ const envelope = value as AgentEventEnvelope;+ if (envelope.event.type === "status" && envelope.event.status.activity?.phase === "waiting-subagents") waiting();+ } });+ const correct = () => runtime.steer({ text: "Correct the plan now." }, "active-turn", {+ id: "correction-user", role: "user", content: "Correct the plan now.",+ createdAt: "2026-10-13T00:00:00.000Z", steering: true,+ });+ const requests: AgentMessage[][] = [];+ const internals = runtime as unknown as {+ models: { streamSimple: (model: unknown, context: { messages: AgentMessage[] }) => ReturnType<typeof createAssistantMessageEventStream> };+ };+ internals.models = { streamSimple: (_model, context) => {+ requests.push([...context.messages]);+ const round = requests.length;+ const message = assistantMessage({+ content: round === 1+ ? [{ type: "toolCall", id: "delegate", name: "Task", arguments: { agent: "explorer", task: "Inspect the fixture." } }]+ : round === 2+ ? [{ type: "toolCall", id: "wait", name: "TaskWait", arguments: {} }]+ : [{ type: "text", text: "I have adjusted the plan." }],+ stopReason: round <= 2 ? "toolUse" : "stop",+ }) as unknown as AssistantMessage;+ const stream = createAssistantMessageEventStream();+ queueMicrotask(() => {+ if (round === 2 && timing === "before") correct();+ stream.push({ type: "start", partial: message });+ stream.push({ type: "done", reason: round <= 2 ? "toolUse" : "stop", message });+ stream.end(message);+ });+ return stream;+ } };+ const running = runtime.prompt("Start the inspection.", "initial-user", "active-turn");+ try {+ await beganWaiting;+ if (timing === "during") {+ expect(requests).toHaveLength(2);+ correct();+ }+ await vi.waitFor(() => expect(requests.length).toBeGreaterThanOrEqual(3));+ expect(JSON.stringify(requests[2])).toContain("Correct the plan now.");+ expect(JSON.stringify(requests[2])).toContain("Interrupted by new user input");+ const delegate = subagentRuns.calls[0] as { signal: AbortSignal };+ expect(delegate.signal.aborted).toBe(false);+ expect(runtime.getStatus().currentTurnId).toBe("active-turn");+ expect(runtime.getStatus().isRunning).toBe(true);+ subagentRuns.resolveRun?.({ agentName: "explorer", status: "completed", report: "Fixture inspected.", turns: 1, toolCalls: 0 });+ await running;+ expect(JSON.stringify(requests.at(-1))).toContain("Fixture inspected.");+ } finally {+ await runtime.abort();+ await running;+ await runtime.dispose();+ subagentRuns.deferred = false;+ }+ });+it("converges through TaskWait with reports and statuses", async () => {const runtime = createRuntime({ subagents: [explorer] });subagentRuns.calls.length = 0;diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.tsindex 2ef3ab783..5da3b4ba2 100644--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@ -5291,7 +5291,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when thename: SUBAGENT_WAIT_TOOL_NAME,label: "Task Wait",description:- "Wait for one or more subagents started by Task and return their reports. `delegationIds` defaults to every running subagent; use mode \"any\" with `minCompleted` to converge as soon as the first (or first N) finish. Settled delegations return immediately, so re-reading a report by id is cheap. A wait timeout is not a failure: unfinished delegates keep working and the runtime delivers their reports when they finish.",+ "Wait for one or more subagents started by Task and return their reports. `delegationIds` defaults to every running subagent; use mode \"any\" with `minCompleted` to converge as soon as the first (or first N) finish. Settled delegations return immediately, so re-reading a report by id is cheap. New user input interrupts the wait without canceling delegates; handle it before waiting again. A wait timeout is not a failure: unfinished delegates keep working and the runtime delivers their reports when they finish.",parameters: Type.Object({delegationIds: Type.Optional(Type.Array(@@ -5358,17 +5358,24 @@ Do not invent objections or turn speculative risks into blockers. Stop when the: Math.min(Math.max(minCompleted, 1), targets.length);const deadline = Date.now() + timeoutSeconds * 1000;this.beginDelegationWait(targets);+ const waitAbort = new AbortController();+ this.steeringWaitAbort = waitAbort;let timedOut = false;try {- timedOut = await this.waitForDelegations(- targets,- targetCompleted,- deadline,- signal,- );+ if (!this.pendingSteering.size) {+ timedOut = await this.waitForDelegations(+ targets,+ targetCompleted,+ deadline,+ signal ? AbortSignal.any([signal, waitAbort.signal]) : waitAbort.signal,+ );+ }} finally {+ if (this.steeringWaitAbort === waitAbort) this.steeringWaitAbort = undefined;this.endDelegationWait();}+ const interrupted = this.pendingSteering.size > 0 && !signal?.aborted &&+ !this.runCancelled && !this.disposed && !this.turnHadError;// A settled report included in this bounded result reached the parent;// the idle resume must not deliver it a second time. Omitted reports// stay pending so the idle resume can deliver them later. Running@@ -5391,14 +5398,16 @@ Do not invent objections or turn speculative risks into blockers. Stop when the? formatDelegationHeartbeat(record): (record.result?.report ?? `(${record.status} without a report)`),}));- const note = timedOut- ? `Still running after ${timeoutSeconds}s: ${results.filter((r) => r.status !== "running").length}/${targets.length} finished. This is not a failure — unfinished delegates keep working and the runtime will deliver their reports when they finish. Call TaskStop only to cancel.\n${targets- .filter((record) => record.status === "running")- .map(formatDelegationHeartbeat)- .join("\n")}`- : mode === "any"- ? `Converged after ${results.filter((r) => r.status !== "running").length} of ${targets.length} finished.`- : undefined;+ const note = interrupted+ ? "Interrupted by new user input. Unfinished subagents keep working; handle the user's message before waiting again."+ : timedOut+ ? `Still running after ${timeoutSeconds}s: ${results.filter((r) => r.status !== "running").length}/${targets.length} finished. This is not a failure — unfinished delegates keep working and the runtime will deliver their reports when they finish. Call TaskStop only to cancel.\n${targets+ .filter((record) => record.status === "running")+ .map(formatDelegationHeartbeat)+ .join("\n")}`+ : mode === "any"+ ? `Converged after ${results.filter((r) => r.status !== "running").length} of ${targets.length} finished.`+ : undefined;const unknownNote =unknownIds.length > 0? `Unknown delegation ids (not found in this session): ${unknownIds.join(", ")}.`@@ -5423,7 +5432,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the},],details: {- status: timedOut ? "timeout" : "completed",+ status: interrupted ? "interrupted" : timedOut ? "timeout" : "completed",...(unknownIds.length ? { unknownIds } : {}),delegations: results,},@@ -5446,6 +5455,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when theconst settledCount = () =>targets.filter((record) => record.status !== "running").length;if (settledCount() >= targetCompleted) return Promise.resolve(false);+ if (signal?.aborted) return Promise.resolve(true);return new Promise<boolean>((resolve) => {let done = false;const finish = (timedOut: boolean) => {diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.tsindex ba49c42c9..82c37efe4 100644--- a/packages/i18n/src/locales/de/index.ts+++ b/packages/i18n/src/locales/de/index.ts@@ -300,7 +300,7 @@ export const de = {"queuedPromptEmpty": "Nachricht in der Warteschlange","removeQueuedPrompt": "Nachricht in der Warteschlange entfernen","sendNow": "Jetzt senden",- sendNowPending: "Warten auf das Ende der aktuellen Aufgabe",+ sendNowPending: "Wartet auf Versand",queuedPromptStopFailed: "Die aktuelle Aufgabe konnte nicht gestoppt werden. Diese Nachricht wartet noch und kann abgebrochen werden.",queuedPromptAlreadyStarted: "Diese Nachricht wird bereits ausgeführt. Verwenden Sie Stopp, um die laufende Aufgabe zu stoppen.","moveQueuedPromptUp": "Nach oben",diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex dd29be878..5c1a0a263 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -312,7 +312,7 @@ export const en = {queuedPromptEmpty: "Queued message",removeQueuedPrompt: "Remove queued message",sendNow: "Send now",- sendNowPending: "Waiting for the current task to finish",+ sendNowPending: "Waiting to send",queuedPromptStopFailed: "Could not stop the current task. This message is still queued and can be canceled.",queuedPromptAlreadyStarted: "This message has already started. Use Stop to stop the running task.",moveQueuedPromptUp: "Move up",diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.tsindex 417fd6e8e..91358b675 100644--- a/packages/i18n/src/locales/es/index.ts+++ b/packages/i18n/src/locales/es/index.ts@@ -300,7 +300,7 @@ export const es = {"queuedPromptEmpty": "Mensaje en cola","removeQueuedPrompt": "Eliminar mensaje en cola","sendNow": "Enviar ahora",- sendNowPending: "Esperando a que termine la tarea actual",+ sendNowPending: "En espera de envío",queuedPromptStopFailed: "No se pudo detener la tarea actual. Este mensaje sigue en cola y se puede cancelar.",queuedPromptAlreadyStarted: "Este mensaje ya se está ejecutando. Usa Detener para detener la tarea actual.","moveQueuedPromptUp": "Subir",diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.tsindex 05fba4e52..ac415d2e2 100644--- a/packages/i18n/src/locales/fr/index.ts+++ b/packages/i18n/src/locales/fr/index.ts@@ -300,7 +300,7 @@ export const fr = {"queuedPromptEmpty": "Message en file d'attente","removeQueuedPrompt": "Supprimer le message en file d'attente","sendNow": "Envoyer maintenant",- sendNowPending: "En attente de la fin de la tâche en cours",+ sendNowPending: "En attente d’envoi",queuedPromptStopFailed: "Impossible d’arrêter la tâche en cours. Ce message reste en attente et peut être annulé.",queuedPromptAlreadyStarted: "Ce message est déjà en cours d’exécution. Utilisez Arrêter pour arrêter la tâche.","moveQueuedPromptUp": "Monter",diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.tsindex b378c3047..53edd300c 100644--- a/packages/i18n/src/locales/ko/index.ts+++ b/packages/i18n/src/locales/ko/index.ts@@ -309,7 +309,7 @@ export const ko = {queuedPromptEmpty: "대기 중인 메시지",removeQueuedPrompt: "대기 중인 메시지 제거",sendNow: "지금 보내기",- sendNowPending: "현재 작업이 끝나기를 기다리는 중",+ sendNowPending: "전송 대기 중",queuedPromptStopFailed: "현재 작업을 중지하지 못했습니다. 이 메시지는 아직 대기 중이며 취소할 수 있습니다.",queuedPromptAlreadyStarted: "이 메시지는 이미 실행 중입니다. 중지 버튼을 사용하세요.",moveQueuedPromptUp: "위로",diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.tsindex ad3f3c419..177bf9672 100644--- a/packages/i18n/src/locales/pt-BR/index.ts+++ b/packages/i18n/src/locales/pt-BR/index.ts@@ -299,7 +299,7 @@ export const ptBR = {queuedPromptEmpty: "Mensagem na fila",removeQueuedPrompt: "Remover prompt da fila",sendNow: "Enviar agora",- sendNowPending: "Aguardando a tarefa atual terminar",+ sendNowPending: "Aguardando envio",queuedPromptStopFailed: "Não foi possível parar a tarefa atual. Esta mensagem continua na fila e pode ser cancelada.",queuedPromptAlreadyStarted: "Esta mensagem já começou. Use Parar para interromper a tarefa em execução.",moveQueuedPromptUp: "Mover para cima",diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.tsindex ad117a44e..3ff312f8f 100644--- a/packages/i18n/src/locales/tr/index.ts+++ b/packages/i18n/src/locales/tr/index.ts@@ -309,7 +309,7 @@ export const tr = {queuedPromptEmpty: "Kuyruktaki ileti",removeQueuedPrompt: "Kuyruktaki iletiyi kaldır",sendNow: "Şimdi gönder",- sendNowPending: "Geçerli görevin bitmesi bekleniyor",+ sendNowPending: "Gönderim bekleniyor",queuedPromptStopFailed: "Geçerli görev durdurulamadı. Bu mesaj hâlâ kuyrukta ve iptal edilebilir.",queuedPromptAlreadyStarted: "Bu mesaj zaten çalıştırılıyor. Çalışan görevi durdurmak için Durdur düğmesini kullanın.",moveQueuedPromptUp: "Yukarı taşı",diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.tsindex a30a61088..9c9c4334e 100644--- a/packages/i18n/src/locales/zh-CN/index.ts+++ b/packages/i18n/src/locales/zh-CN/index.ts@@ -302,7 +302,7 @@ export const zhCN = {queuedPromptEmpty: "待发送消息",removeQueuedPrompt: "移除待发送消息",sendNow: "立即发送",- sendNowPending: "等待当前任务结束",+ sendNowPending: "等待发送",queuedPromptStopFailed: "未能停止当前任务。这条消息仍在排队,可以取消。",queuedPromptAlreadyStarted: "这条消息已经开始执行,请使用停止按钮。",moveQueuedPromptUp: "上移",diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.tsindex 3837f68a5..6fdf8b8ac 100644--- a/packages/i18n/src/locales/zh-TW/index.ts+++ b/packages/i18n/src/locales/zh-TW/index.ts@@ -302,7 +302,7 @@ export const zhTW = {queuedPromptEmpty: "待發送訊息",removeQueuedPrompt: "移除待發送訊息",sendNow: "立即傳送",- sendNowPending: "等待目前任務結束",+ sendNowPending: "等待傳送",queuedPromptStopFailed: "無法停止目前任務。這則訊息仍在排隊,可以取消。",queuedPromptAlreadyStarted: "這則訊息已經開始執行,請使用停止按鈕。",moveQueuedPromptUp: "上移",diff --git a/scripts/README.md b/scripts/README.mdindex 649663c0f..5523822a4 100644--- a/scripts/README.md+++ b/scripts/README.md@@ -64,6 +64,7 @@ The scenarios are specified in| `e2e-config-sync-multidevice.mjs` | `pnpm test:e2e:config-sync` | Four isolated host-core processes against a SigV4-validating local S3 fixture; covers credential opt-out, approvals, concurrent edits/conflict resolution, mapped skill resources, deletion, sync/backup restore, restart, password rewrap, encrypted storage and cleanup || `e2e-supervision.mjs` | `pnpm test:e2e:supervision` | Process supervision and restart behavior || `e2e-subagents.mjs` | `pnpm test:e2e:subagents` | Subagent registry over RPC, then through the real loader (D202) |+| `e2e-send-now-subagents.mjs` | `pnpm test:e2e:send-now-subagents` | Production Composer queue and Main IPC with real Rust Host/agent sidecar and a local SSE fixture; Send now wakes TaskWait, preserves two live delegates and reports, and retains ordinary FIFO input. Uses temporary HOME/data and accepts `PI_DESKTOP_HOST_BIN` for a reused Host binary. || `e2e-agent-live.mjs` | `node scripts/e2e-agent-live.mjs` | Live streaming chat through agent-runtime + host-core. Requires `PI_DESKTOP_TEST_API_KEY`, `PI_DESKTOP_TEST_BASE_URL`, and `PI_DESKTOP_TEST_MODEL` (no defaults), so it has no `pnpm` alias |### Configuration-sync live S3 opt-indiff --git a/scripts/e2e-send-now-subagents.mjs b/scripts/e2e-send-now-subagents.mjsnew file mode 100644index 000000000..94a0aa521--- /dev/null+++ b/scripts/e2e-send-now-subagents.mjs@@ -0,0 +1,252 @@+#!/usr/bin/env node+// Production Composer queue, Main IPC, AgentHost, Rust Host and agent sidecar.+// Only model transport and launch configuration are fixtures; data is isolated.+// The harness persists steering echoes and settles Host turns; it does not+// replace coverage of the production outbox or rendered Electron UI.+import assert from "node:assert/strict";+import { spawn } from "node:child_process";+import { randomUUID } from "node:crypto";+import { mkdtempSync, mkdirSync, rmSync } from "node:fs";+import { createServer } from "node:http";+import { register } from "node:module";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { createInterface } from "node:readline";+import { fileURLToPath } from "node:url";+import { createServer as createViteServer } from "vite";+import { IPC, PROTOCOL_VERSION } from "../packages/shared/dist/index.js";+import { Host, resolveHostBinary } from "./e2e/host.mjs";++register(new URL("../apps/desktop/test/helpers/ts-import-hooks.mjs", import.meta.url));+const { createAgentHostBridge } = await import("../apps/desktop/electron/main/agent-host-bridge.ts");+const { registerAgentIpc } = await import("../apps/desktop/electron/main/ipc/agent-ipc.ts");+const { createSessionCoordination } = await import("../apps/desktop/electron/main/runtime/session-coordination.ts");+// Rust's Windows known-folder lookup ignores HOME/USERPROFILE. Refuse before+// Host startup rather than risk touching real global agent documents.+if (process.platform === "win32") throw new Error("Send now E2E requires Linux/macOS HOME isolation; no Host or registry writes were attempted.");+const root = mkdtempSync(join(tmpdir(), "pi-send-now-e2e-"));+const dataDir = join(root, "data");+const homeDir = join(root, "home");+const projectPath = join(root, "project");+for (const path of [dataDir, homeDir, projectPath]) mkdirSync(path);+const env = { ...process.env, HOME: homeDir, USERPROFILE: homeDir, PI_DESKTOP_DATA_DIR: dataDir,+ HTTP_PROXY: "", HTTPS_PROXY: "", ALL_PROXY: "", NO_PROXY: "127.0.0.1,localhost" };+const host = new Host(resolveHostBinary(), dataDir, { env });+const events = [];+const requests = [];+const calls = [];+const held = new Map();+const abortedDelegates = new Set();+const observers = new Set();+const activeTurns = new Map();+const handlers = new Map();+const pending = new Map();+let child, lines, vite, bridge, provider, slice, state, sessionId;+let eventWork = Promise.resolve();+let stderr = "";+let eventError;+const changed = () => { for (const check of [...observers]) check(); };+function until(predicate, label) {+ if (predicate()) return Promise.resolve();+ return new Promise((resolve, reject) => {+ const finish = (error) => {+ clearTimeout(timer); observers.delete(check);+ error ? reject(error) : resolve();+ };+ const check = () => { if (eventError) finish(eventError); else if (predicate()) finish(); };+ const timer = setTimeout(() => finish(new Error(`${label}\n${stderr}\nLast request: ${JSON.stringify(requests.at(-1)?.messages).slice(-4000)}`)), 15_000);+ observers.add(check);+ check();+ });+}+function send(message) { child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", ...message })}\n`); }+function rpc(method, params) {+ const id = randomUUID();+ calls.push(method);+ return new Promise((resolve, reject) => {+ const timer = setTimeout(() => { pending.delete(id); reject(new Error(`Timeout: ${method}\n${stderr}`)); }, 15_000);+ pending.set(id, { resolve, reject, timer });+ send({ id, method, params });+ });+}+function reply(res, delta, reason = "stop") {+ const base = { id: randomUUID(), object: "chat.completion.chunk", created: 1, model: "fixture" };+ res.writeHead(200, { "content-type": "text/event-stream" });+ res.write(`data: ${JSON.stringify({ ...base, choices: [{ index: 0, delta: { role: "assistant", ...delta }, finish_reason: null }] })}\n\n`);+ res.write(`data: ${JSON.stringify({ ...base, choices: [{ index: 0, delta: {}, finish_reason: reason }], usage: { prompt_tokens: 10, completion_tokens: 1, total_tokens: 11 } })}\n\n`);+ res.end("data: [DONE]\n\n");+}+async function respondModel(req, res) {+ let body = "";+ for await (const chunk of req) body += chunk;+ const payload = JSON.parse(body);+ requests.push(payload);+ const content = payload.messages.filter((message) => message.role === "user").at(-1)?.content;+ const lastUser = typeof content === "string" ? content : (content ?? []).map((part) => part.text ?? "").join("\n");+ if (payload.model === "delegate-fixture") {+ const name = lastUser.includes("Delegate A fixture") ? "Delegate A fixture" : "Delegate B fixture";+ held.set(name, res);+ res.on("close", () => {+ if (!res.writableEnded) abortedDelegates.add(name);+ changed();+ });+ } else if (lastUser === "Start two delegates and wait.") {+ if (requests.length >= 6) {+ eventError = new Error(`Fixture unexpectedly repeated the parent request: ${JSON.stringify(payload.messages).slice(-5000)}`);+ reply(res, { content: "Fixture failed." });+ changed();+ return;+ }+ const started = payload.messages.some((message) => message.role === "tool");+ const toolCalls = started+ ? [{ index: 0, id: "wait", type: "function", function: { name: "TaskWait", arguments: "{}" } }]+ : ["A", "B"].map((name, index) => ({ index, id: `delegate-${name}`, type: "function",+ function: { name: "Task", arguments: JSON.stringify({ agent: name === "A" ? "explorer" : "reviewer", task: `Delegate ${name} fixture` }) } }));+ reply(res, { tool_calls: toolCalls }, "tool_calls");+ } else if (lastUser === "Correct the plan now.") {+ reply(res, { content: "Correction handled while delegates are running." });+ } else if (lastUser === "Ordinary follow-up.") {+ reply(res, { content: "Ordinary follow-up processed." });+ } else {+ reply(res, { content: "Both delegate reports received." });+ }+ changed();+}+const model = createServer((req, res) => {+ void respondModel(req, res).catch((error) => { eventError = error; res.destroy(); changed(); });+});+const coordination = createSessionCoordination({ activeTurns, getMainWindow: () => null, getViewingSessionId: () => null });+async function finishTurn(id, reason, _errorCode, options = {}) {+ const turnId = options.turnId ?? activeTurns.get(id);+ if (!turnId || activeTurns.get(id) !== turnId) return;+ await host.call("session.endTurn", { turnId, status: reason, createNotification: false });+ activeTurns.delete(id);+ bridge?.agentHost.endTurn(id, turnId, reason === "aborted" ? "interrupted" : reason === "error" ? "failed" : "completed");+ changed();+}+async function ingest(envelope) {+ events.push(envelope);+ if (envelope.event.type === "message_end" && envelope.event.message.role === "user" && envelope.event.message.steering) {+ await host.call("session.appendMessage", { sessionId: envelope.sessionId, turnId: envelope.turnId, message: envelope.event.message });+ }+ if (!envelope.parentToolCallId && envelope.event.type === "agent_end") {+ await finishTurn(envelope.sessionId, "completed", undefined, { turnId: envelope.turnId });+ } else {+ bridge?.ingest(envelope);+ }+ changed();+}+const invoke = (channel, args) => {+ const handler = handlers.get(channel);+ assert.equal(typeof handler, "function", `Missing production Main handler: ${channel}`);+ return handler(...args);+};+const previousWindow = globalThis.window;+try {+ await host.start(PROTOCOL_VERSION);+ await new Promise((resolve) => model.listen(0, "127.0.0.1", resolve));+ provider = { id: "fixture", name: "Fixture", modelId: "fixture", baseUrl: `http://127.0.0.1:${model.address().port}/v1`,+ apiKey: "", authKind: "none", apiStyle: "openai-chat", supportsReasoning: false, supportedThinkingLevels: ["off"] };+ child = spawn(process.execPath, [fileURLToPath(new URL("../packages/agent-runtime/dist/sidecar.js", import.meta.url))], { env, stdio: ["pipe", "pipe", "pipe"] });+ child.stderr.on("data", (chunk) => { stderr = (stderr + String(chunk)).slice(-8000); });+ lines = createInterface({ input: child.stdout });+ lines.on("line", (line) => {+ const message = JSON.parse(line);+ if (message.method === "host.proxy") {+ void host.call(message.params.method, message.params.params).then(+ (result) => send({ id: message.id, result }),+ (error) => send({ id: message.id, error: { code: -32000, message: error.message, data: { errorCode: error.errorCode } } }),+ );+ } else if (message.id != null) {+ const entry = pending.get(message.id);+ if (!entry) return;+ pending.delete(message.id); clearTimeout(entry.timer);+ message.error ? entry.reject(new Error(JSON.stringify(message.error))) : entry.resolve(message.result);+ } else if (message.method === "agent.event") {+ eventWork = eventWork.then(() => ingest(message.params)).catch((error) => { eventError = error; changed(); });+ }+ });+ const sidecar = { call: rpc, setProjectInstructionRoot() {}, clearProjectInstructionRoot() {}, clearVendorAuthBindings() {} };+ registerAgentIpc({+ registrar: { handle: (channel, handler) => handlers.set(channel, handler) },+ getHost: () => host, getSidecar: () => sidecar, getAgentHostBridge: () => bridge,+ logger: { app() {} }, dataDir, activeTurns, activeTurnUsages: new Map(),+ vendorOAuth: { async resolveAuth() { throw new Error("Fixture does not use OAuth"); } },+ agentExtensions: { cancelPrompts() {} }, cancelSessionTools() {}, persistenceOutbox: { async flush() {} },+ approvedExecutionIdsBySession: new Map(), claimedExecutionSessions: new Map(),+ acquireSessionOperation: coordination.acquireSessionOperation, isTurnDispatchable: coordination.isTurnDispatchable,+ lockAbortReason: coordination.lockAbortReason, finishTurn,+ async resolveAgentRuntimeLaunch(id) {+ return { providerId: provider.id, modelId: provider.modelId, projectPath,+ sidecarParams: { sessionId: id, mode: "agent", provider, projectPath, thinkingLevel: "off",+ commandShell: { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true },+ subagentProviders: { "fixture/delegate-fixture": { ...provider, modelId: "delegate-fixture" } },+ subagents: ["explorer", "reviewer"].map((name) => ({ name, description: "Local fixture delegate", tools: ["Read"],+ prompt: "Answer the fixture task.", source: "builtin", model: { providerId: "fixture", modelId: "delegate-fixture" } })) } };+ },+ emitAgentEvent: (envelope) => bridge?.ingest(envelope), setNotificationViewingSessionId() {},+ async optionalWorkspaceRoot() { return projectPath; },+ composerCommandService: { async buildComposerCommands() { return []; } }, async loadComposerTemplatesCached() { return []; },+ async finishApprovedExecution() {}, async dispatchApprovedPlan() {}, async dispatchExecutionForProposal() {},+ });+ bridge = createAgentHostBridge({ channels: IPC.invoke, getHost: () => host, invoke,+ isSessionBusy: coordination.isSessionBusy, log() {},+ onQueueChange: (event) => slice?.applyQueueChanged(event) });+ await bridge.agentHost.start();+ sessionId = (await host.call("session.create", { title: "Send now fixture", mode: "agent", projectPath })).session.id;+ if (process.argv.includes("--auto")) await host.call("session.configure", { id: sessionId, mode: "agent", permissionMode: "auto" });+ vite = await createViteServer({ root: fileURLToPath(new URL("../apps/desktop", import.meta.url)), configFile: false,+ server: { middlewareMode: true, hmr: false, ws: false }, appType: "custom", optimizeDeps: { noDiscovery: true, include: [] } });+ const { createQueueSlice } = await vite.ssrLoadModule("/src/stores/slices/queue-slice.ts");+ globalThis.window = { piDesktop: { invoke: async (channel, ...args) => ({ ok: true, data: await invoke(channel, args) }) } };+ state = { activeSessionId: sessionId, sessions: [{ id: sessionId, source: "desktop" }],+ queuedPrompts: {}, runningSessions: { [sessionId]: true }, pendingPlans: {}, showToast: assert.fail };+ slice = createQueueSlice({ get: () => state,+ set: (patch) => { state = { ...state, ...(typeof patch === "function" ? patch(state) : patch) }; }, promptAttachmentsFromDraft: () => [] });+ Object.assign(state, slice);+ await invoke(IPC.invoke.agentPrompt, [{ sessionId, content: "Start two delegates and wait." }]);+ await until(() => held.size === 2 && events.some((entry) => entry.event.type === "status" && entry.event.status.activity?.phase === "waiting-subagents"), "Parent did not reach TaskWait with two live delegates");+ const originalTurnId = activeTurns.get(sessionId);+ assert.equal(await slice.sendPrompt("Ordinary follow-up."), true);+ assert.equal(await slice.sendPrompt("Correct the plan now."), true);+ const correction = state.queuedPrompts[sessionId].find((entry) => entry.content === "Correct the plan now.");+ assert.ok(correction);+ await slice.sendQueuedNow(correction.id);+ await until(() => events.some((entry) => entry.event.type === "message_end" && entry.event.message.content === "Correction handled while delegates are running."), "Send now did not wake the parent's TaskWait");+ assert.equal(activeTurns.get(sessionId), originalTurnId);+ assert.equal(held.size, 2);+ assert.equal(abortedDelegates.size, 0);+ assert.equal(calls.includes("agent.stop"), false);+ assert.equal(calls.includes("agent.abort"), false);+ assert.deepEqual(bridge.queue.list(sessionId).map((entry) => entry.content), ["Ordinary follow-up."]);+ const durableQueue = await host.call("session.queueList", { sessionId });+ assert.deepEqual(durableQueue.entries.map((entry) => entry.content), ["Ordinary follow-up."]);+ const history = await host.call("session.get", { id: sessionId });+ assert.equal(history.session.messages.filter((entry) => entry.content === "Correct the plan now.").length, 1);+ assert.ok(requests.some((request) => request.model === "fixture" && request.messages.some((message) =>+ message.role === "tool" && String(message.content).includes("Interrupted by new user input"))));+ console.log("PASS Send now: current turn handles correction; both delegates remain running; ordinary input remains durably queued");++ for (const [name, res] of held) reply(res, { content: `${name} completed successfully.` });+ await until(() => events.some((entry) => entry.event.type === "message_end" && entry.event.message.content === "Ordinary follow-up processed."), "Delegate completion did not release the ordinary follow-up");+ await until(() => !activeTurns.has(sessionId), "Final follow-up did not settle");+ await eventWork;+ assert.equal(abortedDelegates.size, 0);+ assert.equal(bridge.queue.list(sessionId).length, 0);+ assert.equal((await host.call("session.queueList", { sessionId })).entries.length, 0);+ assert.ok(requests.some((entry) => JSON.stringify(entry.messages).includes("Delegate A fixture completed successfully.") && JSON.stringify(entry.messages).includes("Delegate B fixture completed successfully.")));+ console.log("PASS Send now: both reports return to the same parent turn; remaining FIFO input runs after settlement");+} finally {+ globalThis.window = previousWindow;+ await vite?.close();+ for (const entry of pending.values()) clearTimeout(entry.timer);+ lines?.close();+ if (child && child.exitCode === null) {+ const exited = new Promise((resolve) => child.once("exit", resolve)); child.kill(); await exited;+ }+ for (const res of held.values()) if (!res.writableEnded) res.destroy();+ model.closeAllConnections();+ await new Promise((resolve) => model.close(resolve));+ await host.stop();+ rmSync(root, { recursive: true, force: true });+}