The Open Framework for Building Agents
fix(eve): render background tasks as one owned TUI section (#1808)
Rui8bf1e5b028c8
diff --git a/.changeset/background-task-tui.md b/.changeset/background-task-tui.mdnew file mode 100644index 000000000..52b661d17--- /dev/null+++ b/.changeset/background-task-tui.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Render background subagent activity in one persistent dev TUI section across parent turns. Idle task wakes render while the prompt remains active, remote child streams use the authenticated parent proxy, and child boundaries finalize sections without later-turn cancellation closing unrelated background work.diff --git a/.changeset/idle-task-hitl-tui.md b/.changeset/idle-task-hitl-tui.mdnew file mode 100644index 000000000..61bc4133d--- /dev/null+++ b/.changeset/idle-task-hitl-tui.md@@ -0,0 +1,5 @@+---+"eve": patch+---++The dev TUI now presents and routes approval or question prompts raised by background tasks while the parent session is idle, instead of leaving the task blocked.diff --git a/packages/eve/src/cli/dev/tui/runner.test.ts b/packages/eve/src/cli/dev/tui/runner.test.tsindex 519ed44d3..f0ca9a8b7 100644--- a/packages/eve/src/cli/dev/tui/runner.test.ts+++ b/packages/eve/src/cli/dev/tui/runner.test.ts@@ -80,6 +80,19 @@ function messageResponseOf(events: readonly unknown[]): MessageResponse {});}+function messageStreamResponseOf(events: readonly MessageStreamEvent[]): Response {+ const encoder = new TextEncoder();+ return new Response(+ new ReadableStream<Uint8Array>({+ start(controller) {+ for (const event of events)+ controller.enqueue(encoder.encode(`${JSON.stringify(event)}\n`));+ controller.close();+ },+ }),+ );+}+function isStamped(event: unknown): event is MessageStreamEvent {return typeof (event as MessageStreamEvent).meta?.id === "string";}@@ -552,6 +565,421 @@ function sessionYieldingTurns(turns: ReadonlyArray<readonly unknown[]>): ClientSreturn session;}+describe("EveTUIRunner idle session follow", () => {+ it("does not start idle following when model setup has no session", async () => {+ const handle = vi.fn(async () => ({ message: "dismissed" }));+ const renderIdleStream = vi.fn(async () => {});+ const runner = new EveTUIRunner({+ renderer: fakeRenderer({+ renderIdleStream,+ setupFlow: createFakeSetupFlowRenderer(),+ }),+ name: "Weather Agent",+ appRoot: "/tmp/weather-agent",+ initialInput: "/model",+ bootDetections: [],+ getVercelAuthStatus: vi.fn(async (): Promise<"authenticated"> => "authenticated"),+ promptCommandHandler: { handle },+ });++ await expect(runner.run()).resolves.toBeUndefined();++ expect(handle).toHaveBeenCalledWith(+ { type: "extension", name: "model", argument: "" },+ expect.objectContaining({ initialModelStep: "provider" }),+ );+ expect(renderIdleStream).not.toHaveBeenCalled();+ });++ it("renders a wake turn while prompting, then stops before send without replay", async () => {+ const client = stubClient();+ const session = client.sessions.attach("session_test");+ const prompt = createDeferred<string | undefined>();+ const wakeRendered = createDeferred<void>();+ const idleEvents: AgentTUIStreamEvent[] = [];+ const sendEvents: AgentTUIStreamEvent[] = [];+ let idleStopped = false;+ let streamCalls = 0;+ const wakeEvents = [+ {+ type: "actions.requested",+ data: {+ actions: [+ {+ callId: "peek-1",+ input: { taskIds: ["task_123"] },+ kind: "tool-call",+ toolName: "task_peek",+ },+ ],+ sequence: 1,+ stepIndex: 0,+ turnId: "wake-turn",+ },+ },+ {+ type: "action.result",+ data: {+ result: {+ callId: "peek-1",+ kind: "tool-result",+ output: { tasks: [{ status: "completed", taskId: "task_123" }] },+ toolName: "task_peek",+ },+ sequence: 1,+ status: "completed",+ stepIndex: 0,+ turnId: "wake-turn",+ },+ },+ {+ type: "message.appended",+ data: {+ messageDelta: "Background research finished.",+ messageSoFar: "Background research finished.",+ sequence: 1,+ stepIndex: 1,+ turnId: "wake-turn",+ },+ },+ {+ type: "message.completed",+ data: {+ finishReason: "stop",+ message: "Background research finished.",+ sequence: 1,+ stepIndex: 1,+ turnId: "wake-turn",+ },+ },+ { type: "turn.completed", data: { sequence: 1, turnId: "wake-turn" } },+ { type: "session.waiting", data: { wait: "next-user-message" } },+ ].map((event, index) => stampTestEvent(event as UnstampedMessageStreamEvent, index));+ vi.spyOn(session, "stream").mockImplementation((options?: { signal?: AbortSignal }) => {+ streamCalls += 1;+ const signal = options?.signal;+ const events = streamCalls === 1 ? wakeEvents : [];+ return {+ async *[Symbol.asyncIterator]() {+ try {+ for (const event of events) yield event;+ await new Promise<void>((resolve) => {+ if (signal?.aborted) resolve();+ else signal?.addEventListener("abort", () => resolve(), { once: true });+ });+ } finally {+ idleStopped = true;+ }+ },+ };+ });+ const send = vi.spyOn(session, "send").mockImplementation(async () => {+ expect(idleStopped).toBe(true);+ return messageResponseOf([+ {+ type: "message.appended",+ data: {+ messageDelta: "Follow-up answer.",+ messageSoFar: "Follow-up answer.",+ sequence: 2,+ stepIndex: 0,+ turnId: "follow-up-turn",+ },+ },+ { type: "session.waiting", data: { wait: "next-user-message" } },+ ]);+ });+ const renderer = fakeRenderer({+ readPrompt: vi+ .fn()+ .mockImplementationOnce(() => prompt.promise)+ .mockResolvedValueOnce(undefined),+ renderIdleStream: vi.fn(async (result) => {+ for await (const event of result.events) idleEvents.push(event);+ if (idleEvents.some((event) => event.type === "assistant-delta")) wakeRendered.resolve();+ }),+ renderStream: vi.fn(async (result) => {+ for await (const event of result.events) sendEvents.push(event);+ }),+ });+ const runner = new EveTUIRunner({ client, session, renderer, name: "Research Agent" });++ const running = runner.run();+ await wakeRendered.promise;+ prompt.resolve("What else?");+ await running;++ expect(send).toHaveBeenCalledOnce();+ expect(idleEvents.filter((event) => event.type === "assistant-delta")).toEqual([+ {+ delta: "Background research finished.",+ id: "text:wake-turn:1",+ type: "assistant-delta",+ },+ ]);+ expect(sendEvents.filter((event) => event.type === "assistant-delta")).toEqual([+ {+ delta: "Follow-up answer.",+ id: "text:follow-up-turn:0",+ type: "assistant-delta",+ },+ ]);+ });++ it("answers a background-task approval that arrives while the prompt is idle", async () => {+ const session = stubSession();+ const prompt = createDeferred<string | undefined>();+ const requestId = "task_123:approval-1";+ const wakeEvents = [+ stampTestEvent({+ type: "input.requested",+ data: {+ sequence: 1,+ stepIndex: 0,+ turnId: "wake-turn",+ requests: [+ {+ action: {+ callId: "call-1",+ input: { summary: "Return LOCAL-OK" },+ kind: "tool-call",+ toolName: "confirm_local_task",+ },+ display: "confirmation",+ kind: "tool-approval",+ options: [+ { id: "approve", label: "Approve" },+ { id: "cancel", label: "Cancel" },+ ],+ prompt: "Approve tool call: confirm_local_task",+ requestId,+ },+ ],+ },+ } as UnstampedMessageStreamEvent),+ stampTestEvent({+ type: "session.waiting",+ data: { continuationToken: "session-id", wait: "next-user-message" },+ }),+ ];+ let streamCalls = 0;+ vi.spyOn(session, "stream").mockImplementation((options?: { signal?: AbortSignal }) => {+ streamCalls += 1;+ const events = streamCalls === 1 ? wakeEvents : [];+ return {+ async *[Symbol.asyncIterator]() {+ for (const event of events) yield event;+ await new Promise<void>((resolve) => {+ if (options?.signal?.aborted) resolve();+ else options?.signal?.addEventListener("abort", () => resolve(), { once: true });+ });+ },+ };+ });+ const send = vi.spyOn(session, "send");+ const respond = vi.spyOn(session, "respond").mockImplementation(async () =>+ messageResponseOf([+ {+ type: "session.waiting",+ data: { continuationToken: "session-id", wait: "next-user-message" },+ },+ ]),+ );+ const renderer = fakeRenderer({+ readPrompt: vi+ .fn()+ .mockImplementationOnce(() => prompt.promise)+ .mockResolvedValueOnce(undefined),+ readToolApproval: vi.fn(async () => ({ approved: true })),+ renderIdleStream: vi.fn(async (result) => {+ for await (const event of result.events) void event;+ }),+ renderStream: vi.fn(async (result) => {+ for await (const event of result.events) void event;+ }),+ suspendPromptForInput: vi.fn(() => prompt.reject(interruptedError())),+ });++ await new EveTUIRunner({ session, renderer, name: "Task Agent" }).run();++ expect(renderer.suspendPromptForInput).toHaveBeenCalledOnce();+ expect(renderer.readToolApproval).toHaveBeenCalledWith(+ expect.objectContaining({ approvalId: requestId, toolName: "confirm_local_task" }),+ { title: "Task Agent" },+ );+ expect(respond).toHaveBeenCalledWith([{ requestId, optionId: "approve" }], {+ signal: expect.any(AbortSignal),+ });+ expect(send).not.toHaveBeenCalled();+ });++ it("parks idle authorization wake turns until their callback completes", async () => {+ const session = stubSession();+ const prompt = createDeferred<string | undefined>();+ const completed = createDeferred<void>();+ const updates: Array<{ name: string; state: string }> = [];+ const pendingCounts: number[] = [];+ const wakeEvents = [+ stampTestEvent(+ {+ type: "authorization.required",+ data: {+ authorization: { url: "https://connect.vercel.com/authorize/linear" },+ description: "Authorization required for linear",+ name: "linear",+ sequence: 1,+ stepIndex: 0,+ turnId: "wake-turn",+ webhookUrl: "https://eve.test/connections/linear/callback",+ },+ } as UnstampedMessageStreamEvent,+ 0,+ ),+ stampTestEvent(+ {+ type: "session.waiting",+ data: { continuationToken: "session-id", wait: "next-user-message" },+ },+ 1,+ ),+ stampTestEvent(+ {+ type: "authorization.completed",+ data: {+ name: "linear",+ outcome: "authorized",+ sequence: 2,+ stepIndex: 0,+ turnId: "wake-turn",+ },+ } as UnstampedMessageStreamEvent,+ 2,+ ),+ stampTestEvent(+ {+ type: "session.waiting",+ data: { continuationToken: "session-id", wait: "next-user-message" },+ },+ 3,+ ),+ ];+ vi.spyOn(session, "stream").mockReturnValue(+ (async function* () {+ for (const event of wakeEvents) yield event;+ })(),+ );+ const renderer = fakeRenderer({+ readPrompt: vi.fn().mockImplementationOnce(() => prompt.promise),+ renderIdleStream: vi.fn(async (result) => {+ for await (const event of result.events) void event;+ }),+ upsertConnectionAuth: (update) => {+ updates.push({ name: update.name, state: update.state });+ if (update.state === "authorized") completed.resolve();+ },+ setConnectionAuthPendingCount: (count) => pendingCounts.push(count),+ });+ const runner = new EveTUIRunner({ session, renderer, name: "Weather Agent" });++ const running = runner.run();+ await completed.promise;+ prompt.resolve(undefined);+ await running;++ expect(updates).toEqual([+ { name: "linear", state: "required" },+ { name: "linear", state: "pending" },+ { name: "linear", state: "authorized" },+ ]);+ expect(pendingCounts).toEqual([1, 0]);+ });++ it("replaces a failed idle source exactly once before submitting the prompt", async () => {+ const client = stubClient();+ const failedSession = client.sessions.attach("session-a");+ const failedSend = vi.spyOn(failedSession, "send");+ vi.spyOn(failedSession, "stream").mockReturnValue(+ (async function* () {+ yield stampTestEvent({+ type: "session.failed",+ data: { code: "SESSION_FAILED", message: "idle source failed", sessionId: "session-a" },+ } as UnstampedMessageStreamEvent);+ })(),+ );+ const replacement = sessionYielding([{ type: "session.waiting" }]);+ const createSession = mockSessionCreation(client, replacement);+ const prompt = createDeferred<string | undefined>();+ const prompts: Array<Promise<string | undefined> | string | undefined> = [+ prompt.promise,+ undefined,+ ];+ const renderer = fakeRenderer({+ readPrompt: vi.fn(async () => await prompts.shift()),+ renderIdleStream: vi.fn(async (result) => {+ for await (const event of result.events) void event;+ prompt.resolve("hello after failure");+ }),+ renderStream: vi.fn(async (result) => {+ for await (const event of result.events) void event;+ }),+ });++ await new EveTUIRunner({ client, session: failedSession, renderer }).run();++ expect(createSession).toHaveBeenCalledOnce();+ expect(replacement.send).toHaveBeenCalledOnce();+ expect(replacement.send).toHaveBeenCalledWith(+ "hello after failure",+ expect.objectContaining({ message: "hello after failure" }),+ );+ expect(failedSend).not.toHaveBeenCalled();+ });++ it("does not replace B for a stale idle failure from A", async () => {+ const client = stubClient();+ const failedSession = client.sessions.attach("session-a");+ vi.spyOn(failedSession, "stream").mockReturnValue(+ (async function* () {+ yield stampTestEvent({+ type: "session.failed",+ data: { code: "SESSION_FAILED", message: "idle source failed", sessionId: "session-a" },+ } as UnstampedMessageStreamEvent);+ })(),+ );+ vi.spyOn(failedSession, "reset").mockResolvedValue({+ previousSessionId: "session-a",+ status: "reset",+ });+ const sessionB = sessionYielding([{ type: "session.waiting" }]);+ const createSession = mockSessionCreation(client, sessionB);+ const firstPrompt = createDeferred<string | undefined>();+ const prompts: Array<Promise<string | undefined> | string | undefined> = [+ firstPrompt.promise,+ "hello on B",+ undefined,+ ];+ const renderer = fakeRenderer({+ readPrompt: vi.fn(async () => await prompts.shift()),+ renderIdleStream: vi.fn(async (result) => {+ for await (const event of result.events) void event;+ firstPrompt.resolve("/reset");+ }),+ renderStream: vi.fn(async (result) => {+ for await (const event of result.events) void event;+ }),+ });++ await new EveTUIRunner({ client, session: failedSession, renderer }).run();++ expect(createSession).toHaveBeenCalledOnce();+ expect(sessionB.send).toHaveBeenCalledOnce();+ expect(sessionB.send).toHaveBeenCalledWith(+ "hello on B",+ expect.objectContaining({ message: "hello on B" }),+ );+ });+});+describe("EveTUIRunner development session continuity", () => {it("keeps the REPL session when HMR publishes a new runtime revision", async () => {const requests: Array<{ readonly method: string; readonly url: URL }> = [];@@ -2285,11 +2713,9 @@ describe("EveTUIRunner renderer teardown", () => {it("finishes the section on the child's own turn boundary, before subagent.completed", async () => {const client = stubClient();- const childSession = client.sessions.attach("child-session");- vi.spyOn(client.sessions, "attach").mockReturnValue(childSession);- vi.spyOn(childSession, "stream").mockImplementation(() => ({- async *[Symbol.asyncIterator]() {- yield stampTestEvent(+ vi.spyOn(client, "fetch").mockResolvedValue(+ messageStreamResponseOf([+ stampTestEvent({type: "message.completed",data: {@@ -2301,16 +2727,16 @@ describe("EveTUIRunner renderer teardown", () => {},} as UnstampedMessageStreamEvent,0,- );- yield stampTestEvent(+ ),+ stampTestEvent({type: "session.waiting",data: { continuationToken: "session-id", wait: "next-user-message" },} as UnstampedMessageStreamEvent,1,- );- },- }));+ ),+ ]),+ );const completeSubagent = vi.fn();const completed = createDeferred<void>();@@ -2332,11 +2758,12 @@ describe("EveTUIRunner renderer teardown", () => {}),subagents: {begin: vi.fn(),+ background: vi.fn(),upsertStep: vi.fn(),upsertTool: vi.fn(),removeTool: vi.fn(),markChildToolCallId: vi.fn(),- complete: (update: { callId: string }) => {+ complete: (update: { authoritative: boolean; callId: string }) => {completeSubagent(update);completed.resolve();},@@ -2348,6 +2775,7 @@ describe("EveTUIRunner renderer teardown", () => {data: {callId: "call-child",childSessionId: "child-session",+ childStreamPath: "/eve/v1/session/child-session/stream",name: "weather-child",sequence: 0,sessionId: "parent-session",@@ -2369,34 +2797,80 @@ describe("EveTUIRunner renderer teardown", () => {await runner.run();await completed.promise;- expect(completeSubagent).toHaveBeenCalledWith({ callId: "call-child" });+ expect(completeSubagent).toHaveBeenCalledWith({ authoritative: true, callId: "call-child" });+ });++ it("does not settle a subagent section when completed carries a background receipt", async () => {+ const backgroundSubagent = vi.fn();+ const completeSubagent = vi.fn();+ const runner = new EveTUIRunner({+ name: "Weather Agent",+ renderer: fakeRenderer({+ readPrompt: vi.fn().mockResolvedValueOnce("delegate").mockResolvedValueOnce(undefined),+ renderStream: vi.fn(async (result) => {+ for await (const event of result.events as AsyncIterable<unknown>) void event;+ }),+ subagents: {+ begin: vi.fn(),+ background: backgroundSubagent,+ upsertStep: vi.fn(),+ upsertTool: vi.fn(),+ removeTool: vi.fn(),+ markChildToolCallId: vi.fn(),+ complete: completeSubagent,+ },+ }),+ session: sessionYielding([+ {+ type: "subagent.called",+ data: {+ callId: "call-child",+ childSessionId: "child-session",+ childStreamPath: "/eve/v1/session/child-session/stream",+ name: "researcher",+ sequence: 0,+ sessionId: "parent-session",+ toolName: "researcher",+ turnId: "turn-parent",+ workflowId: "workflow-parent",+ },+ },+ {+ type: "subagent.completed",+ data: {+ backgroundTask: { status: "working", taskId: "task_123" },+ callId: "call-child",+ output: '{"status":"working","taskId":"task_123"}',+ subagentName: "researcher",+ },+ },+ { type: "turn.completed", data: { sequence: 0, turnId: "turn-parent" } },+ { type: "session.waiting", data: { wait: "next-user-message" } },+ ]),+ });++ await runner.run();++ expect(backgroundSubagent).toHaveBeenCalledWith({ callId: "call-child" });+ expect(completeSubagent).not.toHaveBeenCalled();});it("aborts child-session streams when Ctrl-C exits the runner", async () => {const client = stubClient();- const childSession = client.sessions.attach("child-session");let childSignal: AbortSignal | undefined;- vi.spyOn(client.sessions, "attach").mockReturnValue(childSession);- vi.spyOn(childSession, "stream").mockImplementation((options) => {- const signal = options?.signal;+ vi.spyOn(client, "fetch").mockImplementation(async (_path, init) => {+ const signal = init?.signal as AbortSignal | undefined;if (signal === undefined) {throw new Error("Expected the child stream to receive an abort signal.");}childSignal = signal;- return {- async *[Symbol.asyncIterator]() {- await new Promise<void>((resolve) => {- signal.addEventListener("abort", () => resolve(), { once: true });- });- yield stampTestEvent(- {- type: "session.waiting",- data: { continuationToken: "session-id", wait: "next-user-message" },- } as UnstampedMessageStreamEvent,- 1,- );- },- };+ return new Response(+ new ReadableStream<Uint8Array>({+ start(controller) {+ signal.addEventListener("abort", () => controller.close(), { once: true });+ },+ }),+ );});const runner = new EveTUIRunner({@@ -2417,6 +2891,7 @@ describe("EveTUIRunner renderer teardown", () => {data: {callId: "call-child",childSessionId: "child-session",+ childStreamPath: "/eve/v1/session/child-session/stream",name: "weather-child",sequence: 0,sessionId: "parent-session",@@ -3296,32 +3771,37 @@ describe("EveTUIRunner session id reporting", () => {describe("EveTUIRunner cancelled-turn subagent settling", () => {it("settles subagent sections when the turn is cancelled by a steer", async () => {// A child stream that never ends on its own — it only stops when the- // pump aborts it (the settleAll path under test).- const childStream = (options?: { signal?: AbortSignal }) => ({- [Symbol.asyncIterator](): AsyncIterator<unknown> {- return {- next: () =>- new Promise((resolve) => {- options?.signal?.addEventListener(- "abort",- () => resolve({ done: true, value: undefined }),- { once: true },- );- }),- };- },- });+ // pump aborts it (the scoped cancellation path under test).const client = stubClient();- vi.spyOn(client.sessions, "attach").mockReturnValue({- stream: (options?: { signal?: AbortSignal }) => childStream(options),- } as never);+ vi.spyOn(client, "fetch").mockImplementation(+ async (_path, init) =>+ new Response(+ new ReadableStream<Uint8Array>({+ start(controller) {+ init?.signal?.addEventListener("abort", () => controller.close(), { once: true });+ },+ }),+ ),+ );const session = sessionYielding([+ {+ type: "subagent.called",+ data: {+ callId: "call-a",+ childSessionId: "child-a",+ childStreamPath: "/eve/v1/session/child-a/stream",+ name: "researcher",+ sequence: 0,+ turnId: "turn-a",+ },+ },{type: "subagent.called",data: {callId: "call-1",childSessionId: "child-1",+ childStreamPath: "/eve/v1/session/child-1/stream",name: "researcher",sequence: 1,turnId: "turn-1",@@ -3332,6 +3812,7 @@ describe("EveTUIRunner cancelled-turn subagent settling", () => {]);const view = {begin: vi.fn(),+ background: vi.fn(),upsertStep: vi.fn(),upsertTool: vi.fn(),removeTool: vi.fn(),@@ -3352,10 +3833,12 @@ describe("EveTUIRunner cancelled-turn subagent settling", () => {const runner = new EveTUIRunner({ session, client, renderer, name: "Weather Agent" });await runner.run();+ expect(view.begin).toHaveBeenCalledWith({ callId: "call-a", name: "researcher" });expect(view.begin).toHaveBeenCalledWith({ callId: "call-1", name: "researcher" });// `subagent.completed` never arrives for a cancelled delegation — the// cancellation itself must close the section.- expect(view.complete).toHaveBeenCalledWith({ callId: "call-1" });+ expect(view.complete).toHaveBeenCalledWith({ authoritative: true, callId: "call-1" });+ expect(view.complete).not.toHaveBeenCalledWith({ authoritative: true, callId: "call-a" });});});diff --git a/packages/eve/src/cli/dev/tui/runner.ts b/packages/eve/src/cli/dev/tui/runner.tsindex 2d9860140..f46fa2856 100644--- a/packages/eve/src/cli/dev/tui/runner.ts+++ b/packages/eve/src/cli/dev/tui/runner.ts@@ -22,6 +22,7 @@ import {import { loadDevelopmentEnvironmentFiles } from "#cli/dev/environment.js";import { subscribeDevelopmentSandboxPrewarmLogs } from "#execution/sandbox/development-prewarm.js";import { createEventDeduper } from "#protocol/event-dedupe.js";+import { isCurrentTurnBoundaryEvent } from "#protocol/message.js";import {createDevelopmentRuntimeArtifactRefresher,type DevelopmentRuntimeArtifactRefresher,@@ -292,6 +293,12 @@ export type AgentTUIRenderer = {options?: AgentTUISessionOptions,): Promise<AgentTUIInputQuestionResponse | undefined>;renderStream(result: AgentTUIStreamResult, options?: AgentTUISessionOptions): Promise<void>;+ /**+ * Renders a server-initiated turn while `readPrompt` still owns input.+ * Unlike `renderStream`, this must not replace the active key consumer or+ * clear the user's draft.+ */+ renderIdleStream?(result: AgentTUIStreamResult, options?: AgentTUISessionOptions): Promise<void>;/*** The renderer's whole subagent surface — sections, nested steps and* tools, ghost sweeps, completion. One optional capability with required@@ -353,6 +360,8 @@ export type AgentTUIRenderer = {* lifecycle ends.*/shutdown?(): void;+ /** Suspends an idle prompt so a server-initiated HITL request can own input. */+ suspendPromptForInput?(): void;requestInterrupt?(): void;exitRequested?(): boolean;};@@ -520,6 +529,8 @@ export class EveTUIRunner {* eve `InputResponse[]` payloads on the next `send()`.*/readonly #pendingInputRequests = new Map<string, InputRequest>();+ /** Idle wake result handed from the prompt follower into the normal HITL response loop. */+ #idleInputResult?: AgentTUIStreamResult;/*** callId → live state for one subagent dispatch. Persists across turn* boundaries because a subagent dispatched in one turn may not emit@@ -550,12 +561,10 @@ export class EveTUIRunner {*/readonly #pendingConnectionAuths = new Set<string>();/**- * Set when the active server session reaches a terminal failure — either a- * `session.failed` stream event or a transport error dispatching the turn.- * The run loop starts a fresh session before the next prompt so the user can- * keep going instead of typing into a dead session.+ * The exact session that reported a terminal failure. Recovery replaces it+ * only if it is still current, so a stale failure from A cannot replace B.*/- #sessionFailed = false;+ #failedSession?: ClientSession;#unsubscribeDevelopmentSandboxLogs?: () => void;readonly #lifecycle?: CommandLifecycle;@@ -768,21 +777,23 @@ export class EveTUIRunner {}try {- prompt = await this.#readPromptWithIdleRefresh(promptOptions);+ prompt = await this.#readPromptFollowingSession(promptOptions);} catch (error) {if (isInterruptedError(error)) {- return;+ if (this.#idleInputResult === undefined) return;+ streamWithoutPrompt = true;+ prompt = "";+ } else {+ throw error;}-- throw error;}- if (prompt == null) {+ if (prompt == null && this.#idleInputResult === undefined) {return;}}- const command = parsePromptCommand(prompt);+ const command = this.#idleInputResult === undefined ? parsePromptCommand(prompt!) : null;if (command?.type === "exit") {this.#lifecycle?.requestStop();@@ -959,12 +970,19 @@ export class EveTUIRunner {hasRunTurn = true;}- let result = followCurrentSession- ? this.#streamCurrentSession()- : await this.#streamTurn({- prompt: streamWithoutPrompt ? undefined : prompt,- inputResponses: pendingInputResponses,- });+ const idleInputResult = this.#idleInputResult;+ this.#idleInputResult = undefined;+ let result =+ idleInputResult ??+ (followCurrentSession+ ? this.#streamCurrentSession()+ : await (async () => {+ this.#recoverFailedSession();+ return await this.#streamTurn({+ prompt: streamWithoutPrompt ? undefined : prompt,+ inputResponses: pendingInputResponses,+ });+ })());// The session id becomes known once the send is accepted; keep the// renderer's copy fresh so the parting line can name the session.const acceptedSessionId = this.#session?.state.sessionId;@@ -1055,9 +1073,7 @@ export class EveTUIRunner {}if (result.turnState && result.turnState.boundaryEvent === undefined) {- if (result.turnState.aborted) {- this.#sessionFailed = true;- } else {+ if (!result.turnState.aborted) {const strandedSessionId = this.#session?.state.sessionId;this.#renderer.renderNotice?.(strandedSessionId@@ -1091,8 +1107,9 @@ export class EveTUIRunner {// restores them into the next prompt's editable buffer instead of// firing them into a session whose state the user hasn't seen.const boundaryEvent = result.turnState?.boundaryEvent;+ const currentSessionFailed = this.#failedSession === this.#session;if (- !this.#sessionFailed &&+ !currentSessionFailed &&(boundaryEvent === "session.waiting" || boundaryEvent === "session.completed")) {prompt = this.#renderer.takeQueuedPrompt?.();@@ -1102,23 +1119,7 @@ export class EveTUIRunner {// failure, or a user interrupt). Replace it with a fresh one so the// next prompt isn't sent into a dead session, but keep the transcript// on screen. Server-side context is gone with the old session.- if (this.#sessionFailed) {- this.#sessionFailed = false;- this.#startNewSession();- // An aborted turn keeps its explicit notice — the boundary line alone- // would hide that the interrupted turn may still run on the server.- if (result.turnState?.aborted) {- this.#renderer.renderNotice?.(- "Stopped following the turn and started a new session. Earlier context was cleared; the interrupted turn may still be running on the server.",- );- } else if (this.#renderer.renderSessionBoundary !== undefined) {- this.#renderer.renderSessionBoundary();- } else {- this.#renderer.renderNotice?.(- "Session ended — started a new session. Earlier context was cleared.",- );- }- }+ this.#recoverFailedSession(result.turnState?.aborted === true);}}@@ -1139,6 +1140,27 @@ export class EveTUIRunner {this.#runtimeArtifacts?.clear();}+ /** Clears one failure marker and replaces its source only by identity. */+ #recoverFailedSession(aborted = false): void {+ const failedSession = this.#failedSession;+ if (failedSession === undefined) return;+ this.#failedSession = undefined;+ if (this.#session !== failedSession) return;++ this.#startNewSession();+ if (aborted) {+ this.#renderer.renderNotice?.(+ "Stopped following the turn and started a new session. Earlier context was cleared; the interrupted turn may still be running on the server.",+ );+ } else if (this.#renderer.renderSessionBoundary !== undefined) {+ this.#renderer.renderSessionBoundary();+ } else {+ this.#renderer.renderNotice?.(+ "Session ended — started a new session. Earlier context was cleared.",+ );+ }+ }+/** Resets the durable owner before clearing the local conversation view. */async #resetCurrentSession(): Promise<boolean> {if (this.#session === undefined) {@@ -1216,6 +1238,84 @@ export class EveTUIRunner {}}+ /**+ * Gives the idle prompt exclusive ownership handoff with `send()`:+ * follow while the prompt is open, then abort and await the follow before+ * returning the submitted prompt. Both readers advance the same session+ * cursor, so the next send starts after every wake event already rendered.+ */+ async #readPromptFollowingSession(options: AgentTUISessionOptions): Promise<string | undefined> {+ const prompt = this.#readPromptWithIdleRefresh(options);+ if (+ this.#renderer.renderIdleStream === undefined ||+ this.#session?.state.sessionId === undefined+ ) {+ return await prompt;+ }++ const controller = new AbortController();+ const follow = this.#followIdleSession(controller.signal, options).catch((error: unknown) => {+ if (!controller.signal.aborted) {+ this.#renderer.renderNotice?.(+ `Stopped following session updates: ${toErrorMessage(error)}`,+ );+ }+ });+ try {+ return await prompt;+ } finally {+ controller.abort();+ await follow;+ }+ }++ /**+ * Holds one boundary-blind parent stream open, splitting it into complete+ * turns for rendering. The underlying iterator stays shared across those+ * turns and advances the ClientSession cursor once it is stopped.+ */+ async #followIdleSession(signal: AbortSignal, options: AgentTUISessionOptions): Promise<void> {+ const sourceSession = this.#session;+ if (sourceSession === undefined) return;+ const source = sourceSession.stream({ signal })[Symbol.asyncIterator]();+ try {+ while (!signal.aborted) {+ let consumed = false;+ const turn = {+ async *[Symbol.asyncIterator]() {+ while (!signal.aborted) {+ const next = await source.next();+ if (next.done === true) return;+ consumed = true;+ yield next.value;+ if (isCurrentTurnBoundaryEvent(next.value)) return;+ }+ },+ };+ const result = this.#createTUIStreamResult(turn, () => {}, sourceSession);+ await this.#renderer.renderIdleStream!(result, {+ ...options,+ continueSession: true,+ });+ this.#enterPendingConnectionAuthorization(result);+ if (+ (result.turnState?.pendingApprovals.length ?? 0) > 0 ||+ (result.turnState?.pendingQuestions.length ?? 0) > 0+ ) {+ this.#idleInputResult = {+ events: (async function* () {})(),+ turnState: result.turnState,+ };+ this.#renderer.suspendPromptForInput?.();+ return;+ }+ if (!consumed) return;+ }+ } finally {+ await source.return?.();+ }+ }+async #streamTurn(input: {prompt: string | undefined;inputResponses: readonly InputResponse[] | undefined;@@ -1234,6 +1334,7 @@ export class EveTUIRunner {}let response: Awaited<ReturnType<ClientSession["send"]>>;+ const sourceSession = this.#session;try {if (this.#runtimeArtifacts !== undefined) {await this.#runtimeArtifacts.refresh({@@ -1277,7 +1378,7 @@ export class EveTUIRunner {// where the assistant response would have appeared, then let the// loop recover onto a fresh session before the next prompt.this.#remoteConnection?.reportFailure(error);- this.#sessionFailed = true;+ this.#failedSession = sourceSession;return {events: errorOnlyTUIStream({errorText: this.#formatTransportError(error),@@ -1286,7 +1387,7 @@ export class EveTUIRunner {};}- return this.#createTUIStreamResult(response, () => abortController.abort());+ return this.#createTUIStreamResult(response, () => abortController.abort(), this.#session);}/**@@ -1309,7 +1410,10 @@ export class EveTUIRunner {* restores the submitted message into the prompt instead of losing it.* Single-flight per turn: repeated cancel keys join the running loop.*/- async #requestTurnCancellation(turnState: AgentTUITurnState): Promise<void> {+ async #requestTurnCancellation(+ turnState: AgentTUITurnState,+ sourceSession: ClientSession | undefined,+ ): Promise<void> {if (turnState.cancelInFlight === true) return;turnState.cancelInFlight = true;try {@@ -1317,7 +1421,7 @@ export class EveTUIRunner {if (turnState.boundaryEvent !== undefined || turnState.aborted === true) return;const turnId = turnState.turnId;try {- const result = await this.#session?.cancel(turnId === undefined ? undefined : { turnId });+ const result = await sourceSession?.cancel(turnId === undefined ? undefined : { turnId });// Accepted means the turn's cancellation hook consumed the// request; the turn settles at its next safe boundary.if (result?.status === "accepted") return;@@ -1338,39 +1442,42 @@ export class EveTUIRunner {throw new Error("Cannot stream a session before its first turn is accepted.");}const abortController = new AbortController();+ const sourceSession = this.#session;return this.#createTUIStreamResult(- this.#session.stream({ signal: abortController.signal }),+ sourceSession.stream({ signal: abortController.signal }),() => abortController.abort(),+ sourceSession,);}#createTUIStreamResult(events: AsyncIterable<MessageStreamEvent>,abort: () => void,+ sourceSession: ClientSession | undefined,): AgentTUIStreamResult {const turnState = createTurnState();return {abort: () => {turnState.aborted = true;+ this.#failedSession = sourceSession;abort();},cancel: () => {- void this.#requestTurnCancellation(turnState);+ void this.#requestTurnCancellation(turnState, sourceSession);},events: eveEventsToTUIStream({events,pendingInputRequests: this.#pendingInputRequests,turnState,onSubagentCalled: (called) => this.#subagentPump.begin(called),+ onSubagentBackgrounded: (callId) => this.#subagentPump.background(callId),onSubagentCompleted: (callId) => this.#subagentPump.settle(callId),- // A cancelled turn cancels its pending descendants server-side;- // settle their sections and stop their child streams so stale- // subagent output cannot paint into the next (steered) turn.- onTurnCancelled: () => this.#subagentPump.settleAll(),+ // Cancellation is turn-scoped; background descendants survive.+ onTurnCancelled: (turnId) => this.#subagentPump.settleCancelledTurn(turnId),onConnectionAuthRequired: (event) => this.#handleConnectionAuthRequired(event),onConnectionAuthCompleted: (event) => this.#handleConnectionAuthCompleted(event),onTerminalFailure: () => {- this.#sessionFailed = true;+ this.#failedSession = sourceSession;},failureHintOverride: this.#appRoot === undefined ? undefined : localFailureHint,}),@@ -1808,8 +1915,9 @@ type EveStreamTranslatorInput = {pendingInputRequests: Map<string, InputRequest>;turnState: AgentTUITurnState;onSubagentCalled?: (event: SubagentCalledStreamEvent) => void;+ onSubagentBackgrounded?: (callId: string) => void;onSubagentCompleted?: (callId: string) => void;- onTurnCancelled?: () => void;+ onTurnCancelled?: (turnId: string) => void;onConnectionAuthRequired?: (event: AuthorizationRequiredStreamEvent) => void;onConnectionAuthCompleted?: (event: AuthorizationCompletedStreamEvent) => void;onTerminalFailure?: (event: SessionFailedStreamEvent) => void;@@ -1834,6 +1942,7 @@ async function* eveEventsToTUIStream(pendingInputRequests,turnState,onSubagentCalled,+ onSubagentBackgrounded,onSubagentCompleted,onTurnCancelled,onConnectionAuthRequired,@@ -2167,7 +2276,7 @@ async function* eveEventsToTUIStream(case "turn.cancelled":// A cooperative cancel (`/cancel`, Esc, Ctrl+C, or a steer) — not a failure.// `session.waiting` follows and finishes the stream normally.- onTurnCancelled?.();+ onTurnCancelled?.(event.data.turnId);yield* closeOpenParts(textParts, "assistant-complete", stepEpoch);yield* closeOpenParts(reasoningParts, "reasoning-complete", stepEpoch);yield { type: "turn-cancelled" };@@ -2190,7 +2299,11 @@ async function* eveEventsToTUIStream(case "subagent.completed": {const completed = event as SubagentCompletedStreamEvent;- onSubagentCompleted?.(completed.data.callId);+ if (completed.data.backgroundTask === undefined) {+ onSubagentCompleted?.(completed.data.callId);+ } else {+ onSubagentBackgrounded?.(completed.data.callId);+ }break;}diff --git a/packages/eve/src/cli/dev/tui/subagent-pump.test.ts b/packages/eve/src/cli/dev/tui/subagent-pump.test.tsindex ae369ceb9..5c8235b7c 100644--- a/packages/eve/src/cli/dev/tui/subagent-pump.test.ts+++ b/packages/eve/src/cli/dev/tui/subagent-pump.test.ts@@ -1,4 +1,4 @@-import { describe, expect, it, vi } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";import { Client, type MessageStreamEvent } from "#client/index.js";import { stampTestEvent } from "#internal/testing/events.js";@@ -6,9 +6,14 @@ import type { UnstampedMessageStreamEvent, SubagentCalledStreamEvent } from "#primport { SubagentPump, type SubagentView } from "./subagent-pump.js";+afterEach(() => {+ vi.useRealTimers();+});+function fakeView(): SubagentView {return {begin: vi.fn(),+ background: vi.fn(),upsertStep: vi.fn(),upsertTool: vi.fn(),removeTool: vi.fn(),@@ -18,41 +23,35 @@ function fakeView(): SubagentView {}/**- * A hand-pumped child event stream: events pushed after `settleAll` aborts+ * A hand-pumped child response: events pushed after scoped cancellation aborts* the pump must never reach the view.*/function pushableChildStream() {- const queue: MessageStreamEvent[] = [];- let wake: (() => void) | undefined;+ let controller: ReadableStreamDefaultController<Uint8Array> | undefined;let aborted = false;+ const encoder = new TextEncoder();return {push(event: MessageStreamEvent) {- queue.push(event);- wake?.();- wake = undefined;+ if (aborted) return;+ controller?.enqueue(encoder.encode(`${JSON.stringify(event)}\n`));},- stream(options?: { signal?: AbortSignal }): AsyncIterable<MessageStreamEvent> {- const signal = options?.signal;- return {- async *[Symbol.asyncIterator]() {- while (true) {- if (signal?.aborted) {- aborted = true;- return;- }- const next = queue.shift();- if (next !== undefined) {- yield next;- continue;- }- await new Promise<void>((resolve) => {- wake = resolve;- signal?.addEventListener("abort", () => resolve(), { once: true });- });- }- },- };+ response(signal?: AbortSignal): Response {+ return new Response(+ new ReadableStream<Uint8Array>({+ start(nextController) {+ controller = nextController;+ signal?.addEventListener(+ "abort",+ () => {+ aborted = true;+ nextController.close();+ },+ { once: true },+ );+ },+ }),+ );},get aborted() {return aborted;@@ -60,19 +59,33 @@ function pushableChildStream() {};}-function subagentCalled(callId: string): SubagentCalledStreamEvent {+function subagentCalled(callId: string, turnId = "turn-1"): SubagentCalledStreamEvent {return {type: "subagent.called",data: {callId,childSessionId: `child_${callId}`,+ childStreamPath: `/eve/v1/children/${callId}/stream`,name: "researcher",sequence: 1,- turnId: "turn-1",+ turnId,},} as SubagentCalledStreamEvent;}+function responseOf(events: readonly MessageStreamEvent[]): Response {+ const encoder = new TextEncoder();+ return new Response(+ new ReadableStream<Uint8Array>({+ start(controller) {+ for (const event of events)+ controller.enqueue(encoder.encode(`${JSON.stringify(event)}\n`));+ controller.close();+ },+ }),+ );+}+function reasoningEvent(delta: string, index = 0): MessageStreamEvent {return stampTestEvent({@@ -99,17 +112,65 @@ function boundaryEvent(index: number): MessageStreamEvent {);}+function failedBoundaryEvent(index: number): MessageStreamEvent {+ return stampTestEvent(+ {+ type: "session.failed",+ data: { code: "SESSION_FAILED", message: "child failed", sessionId: "child_call-1" },+ } as UnstampedMessageStreamEvent,+ index,+ );+}+async function settleAsyncWork(): Promise<void> {for (let i = 0; i < 8; i += 1) await Promise.resolve();}-describe("SubagentPump.settleAll", () => {- it("closes live sections and stops stale child output after a cancelled turn", async () => {+describe("SubagentPump.settleCancelledTurn", () => {+ it("cancels only foreground descendants of the exact turn", async () => {+ const backgroundA = pushableChildStream();+ const backgroundB = pushableChildStream();+ const foregroundB = pushableChildStream();+ const streams = new Map([+ ["/eve/v1/children/background-a/stream", backgroundA],+ ["/eve/v1/children/background-b/stream", backgroundB],+ ["/eve/v1/children/foreground-b/stream", foregroundB],+ ]);+ const client = new Client({ host: "http://localhost:3000" });+ vi.spyOn(client, "fetch").mockImplementation(async (path, init) => {+ const child = streams.get(path);+ if (child === undefined) throw new Error(`Unexpected child path: ${path}`);+ return child.response(init?.signal ?? undefined);+ });+ const view = fakeView();+ const pump = new SubagentPump({ client, view, formatActionResultError: () => "failed" });++ pump.begin(subagentCalled("background-a", "turn-a"));+ pump.background("background-a");+ pump.begin(subagentCalled("background-b", "turn-b"));+ pump.background("background-b");+ pump.begin(subagentCalled("foreground-b", "turn-b"));+ await settleAsyncWork();++ pump.settleCancelledTurn("turn-b");++ expect(view.complete).toHaveBeenCalledTimes(1);+ expect(view.complete).toHaveBeenCalledWith({+ authoritative: true,+ callId: "foreground-b",+ });+ expect(foregroundB.aborted).toBe(true);+ expect(backgroundA.aborted).toBe(false);+ expect(backgroundB.aborted).toBe(false);+ pump.abortAll();+ });++ it("closes live sections and stops stale child output after cancellation", async () => {const child = pushableChildStream();const client = new Client({ host: "http://localhost:3000" });- vi.spyOn(client.sessions, "attach").mockReturnValue({- stream: (options?: { signal?: AbortSignal }) => child.stream(options),- } as never);+ vi.spyOn(client, "fetch").mockImplementation(async (_path, init) =>+ child.response(init?.signal ?? undefined),+ );const view = fakeView();const pump = new SubagentPump({ client, view, formatActionResultError: () => "failed" });@@ -121,8 +182,8 @@ describe("SubagentPump.settleAll", () => {);// The parent turn is cancelled: sections settle and the stream stops.- pump.settleAll();- expect(view.complete).toHaveBeenCalledWith({ callId: "call-1" });+ pump.settleCancelledTurn("turn-1");+ expect(view.complete).toHaveBeenCalledWith({ authoritative: true, callId: "call-1" });expect(view.upsertStep).toHaveBeenCalledWith(expect.objectContaining({ callId: "call-1", finalized: true }),);@@ -140,42 +201,184 @@ describe("SubagentPump.settleAll", () => {});});-describe("SubagentPump child stream replay", () => {- it("folds a replayed child transcript in once when the pump restarts", async () => {- const transcript = [reasoningEvent("looked up the forecast", 0), boundaryEvent(1)];- let opened = 0;+describe("SubagentPump background receipts", () => {+ it("keeps the section open until the child stream reaches its own boundary", async () => {+ const child = pushableChildStream();const client = new Client({ host: "http://localhost:3000" });- vi.spyOn(client.sessions, "attach").mockReturnValue({- stream: () => {- opened += 1;- return {- async *[Symbol.asyncIterator]() {- for (const event of transcript) yield event;- },- };- },- } as never);+ vi.spyOn(client, "fetch").mockImplementation(async (_path, init) =>+ child.response(init?.signal ?? undefined),+ );const view = fakeView();const pump = new SubagentPump({ client, view, formatActionResultError: () => "failed" });- const called = subagentCalled("call-1");- pump.begin(called);+ pump.begin(subagentCalled("call-1"));+ pump.background("call-1");++ expect(view.background).toHaveBeenCalledWith({ callId: "call-1" });+ expect(view.complete).not.toHaveBeenCalled();++ child.push(reasoningEvent("still working", 0));+ child.push(boundaryEvent(1));+ await settleAsyncWork();++ expect(view.upsertStep).toHaveBeenCalledWith(+ expect.objectContaining({ callId: "call-1", reasoning: "still working" }),+ );+ expect(view.complete).toHaveBeenCalledWith({ authoritative: true, callId: "call-1" });+ });++ it("treats a child failure boundary as authoritative completion", async () => {+ const child = pushableChildStream();+ const client = new Client({ host: "http://localhost:3000" });+ vi.spyOn(client, "fetch").mockImplementation(async (_path, init) =>+ child.response(init?.signal ?? undefined),+ );+ const view = fakeView();+ const pump = new SubagentPump({ client, view, formatActionResultError: () => "failed" });++ pump.begin(subagentCalled("call-1"));+ pump.background("call-1");+ child.push(failedBoundaryEvent(0));+ await settleAsyncWork();++ expect(view.complete).toHaveBeenCalledWith({ authoritative: true, callId: "call-1" });+ });++ it("reopens after parent completion and upgrades at the child boundary", async () => {+ const child = pushableChildStream();+ const client = new Client({ host: "http://localhost:3000" });+ vi.spyOn(client, "fetch").mockImplementation(async (_path, init) =>+ child.response(init?.signal ?? undefined),+ );+ const view = fakeView();+ const pump = new SubagentPump({ client, view, formatActionResultError: () => "failed" });++ pump.begin(subagentCalled("call-1"));+ pump.settle("call-1");+ expect(view.complete).toHaveBeenCalledWith({ authoritative: false, callId: "call-1" });+ pump.begin(subagentCalled("call-1"));+ expect(view.begin).toHaveBeenCalledOnce();++ child.push(reasoningEvent("delayed output", 0));+ child.push(boundaryEvent(1));+ await settleAsyncWork();++ expect(view.begin).toHaveBeenCalledTimes(2);+ expect(view.upsertStep).toHaveBeenCalledWith(+ expect.objectContaining({ callId: "call-1", reasoning: "delayed output" }),+ );+ expect(view.complete).toHaveBeenLastCalledWith({ authoritative: true, callId: "call-1" });+ });+});++describe("SubagentPump child stream transport", () => {+ it("leaves connection authorization events to the parent runner", async () => {+ const client = new Client({ host: "http://localhost:3000" });+ vi.spyOn(client, "fetch").mockResolvedValue(+ responseOf([+ stampTestEvent(+ {+ type: "authorization.required",+ data: {+ description: "Authorize stub-mcp",+ name: "stub-mcp",+ sequence: 1,+ stepIndex: 0,+ turnId: "child-turn",+ },+ } as UnstampedMessageStreamEvent,+ 0,+ ),+ stampTestEvent(+ {+ type: "authorization.completed",+ data: {+ name: "stub-mcp",+ outcome: "authorized",+ sequence: 2,+ stepIndex: 0,+ turnId: "child-turn",+ },+ } as UnstampedMessageStreamEvent,+ 1,+ ),+ boundaryEvent(2),+ ]),+ );+ const view = fakeView();+ const pump = new SubagentPump({ client, view, formatActionResultError: () => "failed" });++ pump.begin(subagentCalled("call-1"));+ await vi.waitFor(() =>+ expect(view.complete).toHaveBeenCalledWith({ authoritative: true, callId: "call-1" }),+ );++ expect(view.upsertStep).not.toHaveBeenCalled();+ expect(view.upsertTool).not.toHaveBeenCalled();+ });++ it("reopens an exhausted source at its cursor without replaying output", async () => {+ vi.useFakeTimers();+ const first = reasoningEvent("looked up ", 0);+ const second = reasoningEvent("the forecast", 1);+ const client = new Client({ host: "http://localhost:3000" });+ const fetch = vi+ .spyOn(client, "fetch")+ .mockResolvedValueOnce(responseOf([first]))+ .mockResolvedValueOnce(responseOf([first, second, boundaryEvent(2)]));+ const view = fakeView();+ const pump = new SubagentPump({ client, view, formatActionResultError: () => "failed" });++ pump.begin(subagentCalled("call-1"));await settleAsyncWork();+ await vi.advanceTimersByTimeAsync(100);+ await settleAsyncWork();++ expect(fetch).toHaveBeenNthCalledWith(+ 1,+ "/eve/v1/children/call-1/stream",+ expect.objectContaining({ signal: expect.any(AbortSignal) }),+ );+ expect(fetch).toHaveBeenNthCalledWith(+ 2,+ "/eve/v1/children/call-1/stream?startIndex=1",+ expect.objectContaining({ signal: expect.any(AbortSignal) }),+ );+ expect(view.upsertStep).toHaveBeenLastCalledWith(+ expect.objectContaining({ reasoning: "looked up the forecast" }),+ );+ expect(view.complete).toHaveBeenCalledWith({ authoritative: true, callId: "call-1" });+ });++ it("uses the parent-authored child path and never the remote URL", async () => {+ const client = new Client({ host: "https://parent.example" });+ const fetch = vi.spyOn(client, "fetch").mockResolvedValue(responseOf([boundaryEvent(0)]));+ const pump = new SubagentPump({ client, view: fakeView(), formatActionResultError: () => "" });+ const called = subagentCalled("remote-call");+ called.data.childStreamPath = "/eve/v1/session/parent/subagents/remote-call/child/stream";+ called.data.remote = { url: "https://remote.example/private" };+pump.begin(called);await settleAsyncWork();- expect(opened).toBe(2);- const reasoning = vi- .mocked(view.upsertStep)- .mock.calls.map(([update]) => update.reasoning)- .filter((text): text is string => text !== undefined && text.length > 0);- expect(reasoning.length).toBeGreaterThan(0);- for (const text of reasoning) {- expect(text).toBe("looked up the forecast");- }- const sectionKeys = new Set(- vi.mocked(view.upsertStep).mock.calls.map(([update]) => update.sectionKey),+ expect(fetch).toHaveBeenCalledWith(+ called.data.childStreamPath,+ expect.objectContaining({ signal: expect.any(AbortSignal) }),);- expect(sectionKeys.size).toBe(1);+ expect(fetch.mock.calls.flatMap((call) => call).join(" ")).not.toContain("remote.example");+ });++ it("does not reopen after abortAll", async () => {+ vi.useFakeTimers();+ const client = new Client({ host: "http://localhost:3000" });+ const fetch = vi.spyOn(client, "fetch").mockResolvedValue(responseOf([]));+ const pump = new SubagentPump({ client, view: fakeView(), formatActionResultError: () => "" });++ pump.begin(subagentCalled("call-1"));+ await settleAsyncWork();+ pump.abortAll();+ await vi.advanceTimersByTimeAsync(10_000);++ expect(fetch).toHaveBeenCalledOnce();});});diff --git a/packages/eve/src/cli/dev/tui/subagent-pump.ts b/packages/eve/src/cli/dev/tui/subagent-pump.tsindex 38e2fc73e..d04702e40 100644--- a/packages/eve/src/cli/dev/tui/subagent-pump.ts+++ b/packages/eve/src/cli/dev/tui/subagent-pump.ts@@ -7,6 +7,7 @@*/import type { Client } from "#client/index.js";+import { readNdjsonStream } from "#client/ndjson.js";import { createEventDeduper, type EventDeduper } from "#protocol/event-dedupe.js";import {isCurrentTurnBoundaryEvent,@@ -14,9 +15,8 @@ import {type MessageStreamEvent,type SubagentCalledStreamEvent,} from "#protocol/message.js";-import { toErrorMessage } from "#shared/errors.js";--import { isAbortLikeError } from "./errors.js";+const childStreamReconnectBaseDelayMs = 100;+const childStreamReconnectMaxDelayMs = 2_000;/*** The renderer's subagent surface. One cohesive capability: a renderer that@@ -29,12 +29,14 @@ import { isAbortLikeError } from "./errors.js";export interface SubagentView {/** Opens a call's section the moment its dispatch is announced. */begin(update: { callId: string; name: string }): void;+ /** Keeps a receipt-returned background call mutable across parent turns. */+ background(update: { callId: string }): void;upsertStep(update: SubagentStepUpdate): void;upsertTool(update: SubagentToolUpdate): void;/** Drops a child tool row whose call never materialized. */removeTool(update: { callId: string; childCallId: string }): void;/** Marks a call complete so its section collapses on `└ Done…`. */- complete(update: { callId: string }): void;+ complete(update: { authoritative: boolean; callId: string }): void;/** Suppresses the parent-level tool row for a child-owned call id. */markChildToolCallId(callId: string): void;}@@ -63,14 +65,16 @@ type SubagentToolState = {export type SubagentRun = {name: string;- /**- * The run's one lifecycle authority. `settled` means the final assistant- * message is in (the child's turn boundary, or the parent's- * `subagent.completed` fallback); a late child event — a HITL-parked- * turn resuming — explicitly reopens the run rather than mutating a- * completed section by accident.- */- status: "running" | "settled";+ /** Parent turn that originated this dispatch; cancellation is scoped to it. */+ parentTurnId: string;+ /** A receipt-returned task survives cancellation of its originating turn. */+ background: boolean;+ /** Parent completion is provisional; only a child boundary is authoritative. */+ status: "open" | "provisional" | "authoritative";+ /** Parent-authored route on the parent origin, valid for local and remote children. */+ childStreamPath: string;+ /** Absolute durable cursor retained across exhausted transport sources. */+ childStreamIndex: number;/*** One entry per logical "child message" — independent of the child's* `stepIndex` field, which the harness can reuse across multiple@@ -149,7 +153,11 @@ export class SubagentPump {if (existing === undefined) {this.#runs.set(callId, {name: called.data.name,- status: "running",+ parentTurnId: called.data.turnId,+ background: false,+ status: "open",+ childStreamPath: called.data.childStreamPath,+ childStreamIndex: 0,steps: new Map(),currentSectionKey: null,nextSectionKey: 0,@@ -160,21 +168,31 @@ export class SubagentPump {existing.name = called.data.name;}this.#view?.markChildToolCallId(callId);+ if (existing !== undefined && existing.status !== "open") return;this.#view?.begin({ callId, name: called.data.name });this.#startPump(called);}/**- * Parent reports subagent.completed. The child stream pump terminates- * itself on the child's own turn boundary — the authoritative finish- * signal, which already finalized the section — so this is a fallback- * for runs whose boundary never reached us (a dropped child stream, a- * HITL-parked turn resuming later). We do NOT abort the pump here,- * because the child's `message.completed` event may still be in flight- * (the parent and child streams are independent HTTP connections).+ * Parent completion is provisional because the child's final events can be+ * in flight on an independent connection. The pump remains open until the+ * child boundary supplies authoritative completion.*/settle(callId: string): void {- this.#finalizeRun(callId);+ this.#finalizeRun(callId, false);+ }++ /**+ * The originating call returned a task receipt, not the child's result.+ * Keep the section open until the child stream reaches its own boundary.+ * A child that already settled before the receipt raced in stays settled.+ */+ background(callId: string): void {+ const run = this.#runs.get(callId);+ if (run === undefined) return;+ run.background = true;+ if (run.status === "authoritative") return;+ this.#view?.background({ callId });}abortAll(): void {@@ -186,21 +204,16 @@ export class SubagentPump {}/**- * Settles every live run and stops its child stream. Called when the- * parent turn is cancelled (`/cancel`, a key-driven steer, or an empty-queue- * cancel): the server cancels the pending descendants, so their sections must- * close now. A child still flushing reasoning would otherwise keep painting- * stale sections into the next (steered) turn's transcript. Runs stay- * registered so a late parent `subagent.completed` settles as a no-op.+ * Settles and aborts only foreground descendants of the cancelled parent+ * turn. Background tasks survive even when that same turn started them.*/- settleAll(): void {- for (const callId of this.#runs.keys()) {- this.#finalizeRun(callId);- }- for (const controller of this.#pumps.values()) {- controller.abort();+ settleCancelledTurn(turnId: string): void {+ for (const [callId, run] of this.#runs) {+ if (run.parentTurnId !== turnId || run.background) continue;+ this.#finalizeRun(callId, true);+ this.#pumps.get(callId)?.abort();+ this.#pumps.delete(callId);}- this.#pumps.clear();}/**@@ -220,52 +233,52 @@ export class SubagentPump {if (this.#pumps.has(callId)) return;const client = this.#client;if (!client) return;+ const run = this.#runs.get(callId);+ if (run === undefined || run.status === "authoritative") return;const controller = new AbortController();this.#pumps.set(callId, controller);void (async () => {- let boundaryReached = false;+ let reconnectDelayMs = childStreamReconnectBaseDelayMs;try {- const childSession = client.sessions.attach(called.data.childSessionId);- const stream = childSession.stream({ signal: controller.signal });- for await (const event of stream) {- if (controller.signal.aborted) break;- this.#applyChildEvent(callId, event);- if (isCurrentTurnBoundaryEvent(event)) {- // The child's own turn boundary — its final assistant message- // is in — is what finishes the section. The parent's- // `subagent.completed` arrives independently (often later, once- // the parent's turn resumes) and only acts as a fallback.- boundaryReached = true;- break;- }- }- } catch (error) {- if (!isAbortLikeError(error)) {- const errorText = toErrorMessage(error);- const run = this.#runs.get(callId);- if (run) {- const { key, step } = openCurrentSubagentSection(run);- step.message = step.message- ? `${step.message}\n\nstream error: ${errorText}`- : `stream error: ${errorText}`;- step.finalized = true;- run.currentSectionKey = null;- this.#view?.upsertStep({- callId,- subagentName: run.name,- sectionKey: key,- reasoning: step.reasoning,- message: step.message,- finalized: true,- });+ while (!controller.signal.aborted && run.status !== "authoritative") {+ let deliveredEvent = false;+ try {+ const response = await client.fetch(+ streamPathAt(run.childStreamPath, run.childStreamIndex),+ {+ cache: "no-store",+ signal: controller.signal,+ },+ );+ if (!response.ok || response.body === null) {+ await response.body?.cancel().catch(() => {});+ throw new Error(`Child stream returned ${response.status}.`);+ }++ for await (const event of readNdjsonStream(response.body)) {+ if (controller.signal.aborted) return;+ deliveredEvent = true;+ run.childStreamIndex += 1;+ this.#applyChildEvent(callId, event);+ if (isCurrentTurnBoundaryEvent(event)) {+ this.#finalizeRun(callId, true);+ return;+ }+ }+ } catch {+ if (controller.signal.aborted) return;}++ reconnectDelayMs = deliveredEvent+ ? childStreamReconnectBaseDelayMs+ : Math.min(reconnectDelayMs * 2, childStreamReconnectMaxDelayMs);+ await abortableDelay(reconnectDelayMs, controller.signal);}} finally {- this.#pumps.delete(callId);+ if (this.#pumps.get(callId) === controller) this.#pumps.delete(callId);}- if (boundaryReached) this.#finalizeRun(callId);})();}@@ -326,10 +339,11 @@ export class SubagentPump {* the idempotency authority — the child's turn boundary and the parent's* `subagent.completed` can both land here.*/- #finalizeRun(callId: string): void {+ #finalizeRun(callId: string, authoritative: boolean): void {const run = this.#runs.get(callId);- if (!run || run.status === "settled") return;- run.status = "settled";+ if (!run || run.status === "authoritative") return;+ if (!authoritative && run.status === "provisional") return;+ run.status = authoritative ? "authoritative" : "provisional";for (const [sectionKey, step] of run.steps) {if (!step.finalized) {step.finalized = true;@@ -345,7 +359,7 @@ export class SubagentPump {}run.currentSectionKey = null;this.#sweepPreparingTools(callId, run);- this.#view?.complete({ callId });+ this.#view?.complete({ authoritative, callId });}/**@@ -366,11 +380,10 @@ export class SubagentPump {const run = this.#runs.get(callId);if (!run) return;if (!run.seenChildEvents.admit(event)) return;- // A child event after settle is a HITL-parked turn resuming: reopen the- // run explicitly (begin clears the header's Done mark) instead of- // mutating a completed section by accident.- if (run.status === "settled") {- run.status = "running";+ // Parent completion is provisional. Any delayed child event reopens the+ // mutable cohort until the child stream supplies its own boundary.+ if (run.status === "provisional") {+ run.status = "open";this.#view?.begin({ callId, name: run.name });}const view = this.#view;@@ -508,6 +521,27 @@ export class SubagentPump {}}+function streamPathAt(path: string, startIndex: number): string {+ if (startIndex === 0) return path;+ return `${path}${path.includes("?") ? "&" : "?"}startIndex=${startIndex}`;+}++async function abortableDelay(ms: number, signal: AbortSignal): Promise<void> {+ if (signal.aborted) return;+ await new Promise<void>((resolve) => {+ const onAbort = () => {+ clearTimeout(timer);+ resolve();+ };+ const timer = setTimeout(() => {+ signal.removeEventListener("abort", onAbort);+ resolve();+ }, ms);+ timer.unref?.();+ signal.addEventListener("abort", onAbort, { once: true });+ });+}+function openCurrentSubagentSection(run: SubagentRun): {key: number;step: SubagentChildStep;diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.test.tsindex 01edda46f..00433dae5 100644--- a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts@@ -987,6 +987,8 @@ describe("TerminalRenderer (inline scrollback)", () => {it("settles an authorization block when its callback arrives in a later stream pass", async () => {const { screen, renderer } = makeRenderer();renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });+ renderer.beginSubagent({ callId: "background", name: "researcher" });+ renderer.backgroundSubagent({ callId: "background" });renderer.upsertConnectionAuth({name: "linear",description: "Authorization required for linear",@@ -1015,6 +1017,7 @@ describe("TerminalRenderer (inline scrollback)", () => {renderer.shutdown();const snapshot = screen.snapshot();+ expect(countOccurrences(snapshot, "linear · authorization")).toBe(1);expect(snapshot).toContain("linear · authorization · authorized");expect(snapshot).toContain("Authorization complete");expect(snapshot).not.toContain("linear · authorization · required");@@ -1149,6 +1152,54 @@ describe("TerminalRenderer (inline scrollback)", () => {renderer.shutdown();});+ it("keeps late background child output inside its section across parent turns", async () => {+ const { screen, renderer } = makeRenderer();+ renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });+ renderer.beginSubagent({ callId: "s1", name: "researcher" });+ renderer.backgroundSubagent({ callId: "s1" });++ await renderer.renderStream(+ streamOf([+ { type: "assistant-delta", id: "parent-1", delta: "Research task started." },+ { type: "assistant-complete", id: "parent-1" },+ { type: "finish" },+ ]),+ { continueSession: true },+ );+ await renderer.renderStream(+ streamOf([+ { type: "assistant-delta", id: "parent-2", delta: "It is still running." },+ { type: "assistant-complete", id: "parent-2" },+ { type: "finish" },+ ]),+ { continueSession: true, submittedPrompt: "cool" },+ );++ // The child emits after both parent turns. It still inserts beside its+ // call's header, not at the current transcript edge beneath parent-2.+ renderer.upsertSubagentTool({+ callId: "s1",+ subagentName: "researcher",+ childCallId: "dig-1",+ toolName: "dig",+ input: { phase: "sources" },+ status: "executing",+ });++ const snapshot = screen.snapshot();+ const header = snapshot.indexOf("※ subagent(researcher)");+ const child = snapshot.indexOf("dig");+ const firstParent = snapshot.indexOf("Research task started.");+ const user = snapshot.indexOf("cool");+ const secondParent = snapshot.indexOf("It is still running.");+ expect(firstParent).toBeGreaterThan(-1);+ expect(user).toBeGreaterThan(firstParent);+ expect(secondParent).toBeGreaterThan(user);+ expect(header).toBeGreaterThan(secondParent);+ expect(child).toBeGreaterThan(header);+ renderer.shutdown();+ });+it("swaps a dispatch's preparing placeholder for the section header", async () => {const { screen, renderer } = makeRenderer();renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });@@ -1249,7 +1300,7 @@ describe("TerminalRenderer (inline scrollback)", () => {expect(screen.snapshot()).toContain("Fetched https://one.example");expect(screen.snapshot()).not.toContain("Done");- renderer.completeSubagent({ callId: "s1" });+ renderer.completeSubagent({ authoritative: true, callId: "s1" });const snapshot = screen.snapshot();// Completed: the corner reports Done with the counted footnote and the// children fold away — the parent's reply carries the conclusion.@@ -1259,6 +1310,112 @@ describe("TerminalRenderer (inline scrollback)", () => {renderer.shutdown();});+ it("commits an authoritative background completion out of the live prompt region", async () => {+ const { screen, input, renderer } = makeRenderer();+ renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });+ renderer.beginSubagent({ callId: "s1", name: "researcher" });+ renderer.backgroundSubagent({ callId: "s1" });+ renderer.upsertSubagentTool({+ callId: "s1",+ subagentName: "researcher",+ childCallId: "dig-1",+ toolName: "dig",+ input: { phase: "sources" },+ status: "done",+ output: { ok: true },+ });++ renderer.completeSubagent({ authoritative: true, callId: "s1" });+ const outputAfterCommit = screen.rawOutput().length;+ const prompt = renderer.readPrompt();+ input.type("next message");++ // Prompt repaint must not redraw the completed subagent cohort: it has+ // moved to immutable scrollback and no longer occupies the live region.+ expect(screen.rawOutput().slice(outputAfterCommit)).not.toContain("subagent(researcher)");+ input.enter();+ expect(await prompt).toBe("next message");+ renderer.shutdown();+ });++ it("keeps parent completion provisional until delayed child output reaches its boundary", async () => {+ const { screen, input, renderer } = makeRenderer();+ renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });+ renderer.beginSubagent({ callId: "s1", name: "researcher" });+ renderer.upsertSubagentStep({+ callId: "s1",+ subagentName: "researcher",+ sectionKey: 0,+ reasoning: "",+ message: "parent-visible output",+ finalized: true,+ });+ renderer.completeSubagent({ authoritative: false, callId: "s1" });+ await renderer.renderStream(streamOf([{ type: "finish" }]), { continueSession: true });++ renderer.beginSubagent({ callId: "s1", name: "researcher" });+ renderer.upsertSubagentStep({+ callId: "s1",+ subagentName: "researcher",+ sectionKey: 1,+ reasoning: "",+ message: "delayed child output",+ finalized: true,+ });++ expect(screen.snapshot()).toContain("delayed child output");+ expect(screen.snapshot()).not.toContain("└ Done");++ renderer.completeSubagent({ authoritative: true, callId: "s1" });+ const outputAfterCommit = screen.rawOutput().length;+ const prompt = renderer.readPrompt();+ input.type("next");+ expect(screen.rawOutput().slice(outputAfterCommit)).not.toContain("subagent(researcher)");+ input.enter();+ await prompt;+ renderer.shutdown();+ });++ it.each(["active", "idle"] as const)(+ "settles only the %s cancelled turn's top-level tools",+ async (mode) => {+ const { screen, renderer } = makeRenderer();+ renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });+ renderer.beginSubagent({ callId: "background", name: "researcher" });+ renderer.backgroundSubagent({ callId: "background" });+ renderer.upsertSubagentTool({+ callId: "background",+ subagentName: "researcher",+ childCallId: "child-bash",+ toolName: "bash",+ input: { command: "background-child" },+ status: "executing",+ });+ const result = streamOf([+ {+ type: "tool-call",+ toolCallId: "current-bash",+ toolName: "bash",+ input: { command: "idle-current" },+ },+ { type: "turn-cancelled" },+ { type: "finish" },+ ]);++ if (mode === "active") {+ await renderer.renderStream(result, { continueSession: true });+ } else {+ await renderer.renderIdleStream(result, { continueSession: true });+ }++ const snapshot = screen.snapshot();+ expect(snapshot).toContain("background-child");+ expect(snapshot).toContain("idle-current");+ expect(countOccurrences(snapshot, "interrupted")).toBe(1);+ renderer.shutdown();+ },+ );+it("renders parallel calls to the same subagent as ordinal-numbered sections", async () => {const { screen, renderer } = makeRenderer();renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });@@ -1405,6 +1562,39 @@ describe("TerminalRenderer (inline scrollback)", () => {renderer.shutdown();});+ it("renders an idle wake turn without corrupting the active prompt draft", async () => {+ const { screen, input, renderer } = makeRenderer();+ const prompt = renderer.readPrompt();+ input.type("draft in progress");++ await renderer.renderIdleStream(+ streamOf([+ {+ type: "tool-call",+ input: { taskIds: ["task_123"] },+ toolCallId: "peek-1",+ toolName: "task_peek",+ },+ {+ type: "tool-result",+ output: { tasks: [{ status: "completed", taskId: "task_123" }] },+ toolCallId: "peek-1",+ },+ { type: "assistant-delta", id: "wake-1", delta: "Research finished." },+ { type: "assistant-complete", id: "wake-1" },+ { type: "finish" },+ ]),+ { continueSession: true },+ );++ const snapshot = screen.snapshot();+ expect(snapshot).toContain("Research finished.");+ expect(snapshot).toContain("draft in progress");+ input.enter();+ expect(await prompt).toBe("draft in progress");+ renderer.shutdown();+ });+it("never submits an empty or whitespace-only prompt", async () => {const { input, renderer } = makeRenderer();diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.tsindex dd6e7f380..f3a84b260 100644--- a/packages/eve/src/cli/dev/tui/terminal-renderer.ts+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.ts@@ -309,6 +309,8 @@ type RenderTurnState = {text: Map<string, string>;reasoning: Map<string, string>;tools: Map<string, NativeToolState>;+ cancelled: boolean;+ restoreCancelledPrompt: boolean;};type NativeToolState = {@@ -388,6 +390,10 @@ export class TerminalRenderer implements AgentTUIRenderer {#updateSequence = 0;/** Call ids per subagent name, for the sections' ordinal subtitles. */readonly #subagentCallsByName = new Map<string, string[]>();+ /** Background sections kept at the live edge until their child boundary. */+ readonly #backgroundSubagentCallIds = new Set<string>();+ /** Parent-completed sections retained as mutable until the child boundary. */+ readonly #provisionalSubagentCallIds = new Set<string>();/** Session-local file contents, so write blocks can render real diffs. */readonly #fileContents = new FileContentCache();readonly #subagentHeaders = new Set<string>();@@ -907,6 +913,8 @@ export class TerminalRenderer implements AgentTUIRenderer {text: new Map(),reasoning: new Map(),tools: new Map(),+ cancelled: false,+ restoreCancelledPrompt: true,};try {@@ -948,7 +956,7 @@ export class TerminalRenderer implements AgentTUIRenderer {// An interrupted or cancelled turn gets no terminal updates for its// in-flight calls; a block left `running` would keep the settled// prefix wedged and freeze scrollback for the rest of the session.- if (this.#interrupted || this.#turnCancelled) this.#settleInterruptedToolBlocks();+ if (this.#interrupted || turnState.cancelled) this.#settleCurrentTurnToolBlocks(turnState);this.#finalizeAllBlocks();this.#diagnostics?.reportStats();this.#paint();@@ -959,6 +967,51 @@ export class TerminalRenderer implements AgentTUIRenderer {}}+ /**+ * Applies a wake-initiated turn without taking input ownership from the+ * prompt. Paints use the same live region, so the editor redraws around+ * incoming tool and assistant blocks exactly as it does for subagent pumps.+ */+ async renderIdleStream(+ result: AgentTUIStreamResult,+ options?: AgentTUISessionOptions,+ ): Promise<void> {+ const displayModes: DisplayModes = {+ tools: options?.tools ?? this.#tools,+ reasoning: options?.reasoning ?? this.#reasoning,+ assistantResponseStats: options?.assistantResponseStats ?? this.#assistantResponseStats,+ };+ const turnState: RenderTurnState = {+ text: new Map(),+ reasoning: new Map(),+ tools: new Map(),+ cancelled: false,+ restoreCancelledPrompt: false,+ };++ try {+ for await (const event of iterateTUIStream(result.events)) {+ this.#applyStreamEvent(event, displayModes, turnState);+ }+ } catch (error) {+ const summary = summarizeKnownError(error);+ if (summary === null) {+ this.#addErrorBlock("Error", toErrorMessage(error), { detail: inspectError(error) });+ } else {+ this.#addErrorBlock(summary.name, summary.message, {+ detail: inspectError(error),+ hint: summary.hint,+ });+ }+ } finally {+ this.#sweepPreparingToolBlocks(turnState);+ if (turnState.cancelled) this.#settleCurrentTurnToolBlocks(turnState);+ this.#finalizeAllBlocks();+ this.#diagnostics?.reportStats();+ this.#paint();+ }+ }+async readToolApproval(request: AgentTUIToolApprovalRequest,options?: AgentTUISessionOptions,@@ -1306,7 +1359,7 @@ export class TerminalRenderer implements AgentTUIRenderer {return;}- this.#upsertBlock({+ this.#upsertSubagentBlock({id: subagentStepSectionId(update.callId, update.sectionKey),kind: "subagent-step",subagentCallId: update.callId,@@ -1382,7 +1435,7 @@ export class TerminalRenderer implements AgentTUIRenderer {} else if (update.errorText !== undefined) {block.result = stripTerminalControls(update.errorText);}- this.#upsertBlock(block);+ this.#upsertSubagentBlock(block);this.#syncSubagentChildLiveness(update.callId);this.#paint();}@@ -1412,6 +1465,7 @@ export class TerminalRenderer implements AgentTUIRenderer {*/readonly subagents: SubagentView = {begin: (update) => this.beginSubagent(update),+ background: (update) => this.backgroundSubagent(update),upsertStep: (update) => this.upsertSubagentStep(update),upsertTool: (update) => this.upsertSubagentTool(update),removeTool: (update) => this.removeSubagentTool(update),@@ -1430,7 +1484,26 @@ export class TerminalRenderer implements AgentTUIRenderer {if (this.#subagents === "hidden") return;this.#ensureSubagentHeader(update.callId, update.name);const header = this.#blockById.get(subagentHeaderId(update.callId));- if (header?.status === "done") delete header.status;+ if (header !== undefined) {+ if (header.status === "done") delete header.status;+ header.live = true;+ }+ this.#provisionalSubagentCallIds.delete(update.callId);+ this.#paint();+ }++ /**+ * A background receipt closes the model tool call, not the child. Mark the+ * header running so turn finalization cannot commit immutable scrollback+ * before the child pump has folded in its later events.+ */+ backgroundSubagent(update: { callId: string }): void {+ const header = this.#blockById.get(subagentHeaderId(update.callId));+ if (header === undefined || this.#committedIds.has(subagentHeaderId(update.callId))) return;+ header.status = "running";+ header.live = true;+ header.updateSeq = ++this.#updateSequence;+ this.#backgroundSubagentCallIds.add(update.callId);this.#paint();}@@ -1439,10 +1512,22 @@ export class TerminalRenderer implements AgentTUIRenderer {* section's closing corner reports `Done`. The header stays live until the* turn finalizes (committing mid-turn would freeze its child window).*/- completeSubagent(update: { callId: string }): void {+ completeSubagent(update: { authoritative: boolean; callId: string }): void {const header = this.#blockById.get(subagentHeaderId(update.callId));if (header === undefined) return;header.status = "done";+ if (update.authoritative) {+ this.#backgroundSubagentCallIds.delete(update.callId);+ this.#provisionalSubagentCallIds.delete(update.callId);+ for (const block of this.#blocks) {+ if (block.subagentCallId === update.callId) block.live = false;+ }+ } else {+ this.#provisionalSubagentCallIds.add(update.callId);+ for (const block of this.#blocks) {+ if (block.subagentCallId === update.callId) block.live = true;+ }+ }this.#paint();}@@ -1569,6 +1654,8 @@ export class TerminalRenderer implements AgentTUIRenderer {this.#childToolCallIds.clear();this.#parentToolBlockIds.clear();this.#subagentHeaders.clear();+ this.#backgroundSubagentCallIds.clear();+ this.#provisionalSubagentCallIds.clear();this.#subagentCallsByName.clear();this.#todoItems = undefined;this.#todoCommittedSignature = undefined;@@ -2683,6 +2770,11 @@ export class TerminalRenderer implements AgentTUIRenderer {}}+ suspendPromptForInput(): void {+ this.#streamDraft = { cursor: this.#inputCursor, text: this.#inputText };+ this.#stop();+ }+requestInterrupt(): void {this.#interrupted = true;if (this.#setupFlow !== undefined) this.#consumeKey?.({ type: "ctrl-c" });@@ -3092,7 +3184,18 @@ export class TerminalRenderer implements AgentTUIRenderer {#pushBlock(block: Block) {if (block.id !== this.#devRebuild?.id) this.#settleDevRebuildStatus();block.updateSeq = ++this.#updateSequence;- this.#blocks.push(block);+ const isBackgroundChild =+ block.subagentCallId !== undefined &&+ this.#backgroundSubagentCallIds.has(block.subagentCallId);+ const backgroundIndex = isBackgroundChild+ ? -1+ : this.#blocks.findIndex(+ (candidate) =>+ candidate.subagentCallId !== undefined &&+ this.#backgroundSubagentCallIds.has(candidate.subagentCallId),+ );+ if (backgroundIndex < 0) this.#blocks.push(block);+ else this.#blocks.splice(backgroundIndex, 0, block);if (block.id) this.#blockById.set(block.id, block);}@@ -3224,6 +3327,36 @@ export class TerminalRenderer implements AgentTUIRenderer {this.#pushBlock(block);}+ /**+ * Inserts a new child beside the rest of its call's cohort instead of at+ * the transcript's live edge. Background children can emit after parent+ * and user blocks from later turns; arrival order must not split their+ * section.+ */+ #upsertSubagentBlock(block: Block) {+ if (block.id && this.#committedIds.has(block.id)) return;+ const existing = block.id ? this.#blockById.get(block.id) : undefined;+ if (existing !== undefined) {+ Object.assign(existing, block);+ existing.updateSeq = ++this.#updateSequence;+ return;+ }++ const callId = block.subagentCallId;+ if (callId === undefined) {+ this.#pushBlock(block);+ return;+ }+ if (block.id !== this.#devRebuild?.id) this.#settleDevRebuildStatus();+ block.updateSeq = ++this.#updateSequence;+ let anchor = -1;+ for (let index = 0; index < this.#blocks.length; index += 1) {+ if (this.#blocks[index]?.subagentCallId === callId) anchor = index;+ }+ this.#blocks.splice(anchor < 0 ? this.#blocks.length : anchor + 1, 0, block);+ if (block.id !== undefined) this.#blockById.set(block.id, block);+ }+#removeBlock(id: string) {this.#blocks = this.#blocks.filter((candidate) => candidate.id !== id);this.#blockById.delete(id);@@ -3235,6 +3368,8 @@ export class TerminalRenderer implements AgentTUIRenderer {// stay live past this stream boundary so their later terminal update can// replace the same transcript block.if (+ (block.subagentCallId !== undefined &&+ this.#provisionalSubagentCallIds.has(block.subagentCallId)) ||block.status === "approval" ||block.status === "running" ||(block.kind === "connection-auth" && block.live)@@ -3399,7 +3534,9 @@ export class TerminalRenderer implements AgentTUIRenderer {case "turn-cancelled":// The server settled the turn cooperatively (a key-driven steer or an// empty-queue cancel); its in-flight tool calls get no further updates.- // The interrupted-blocks sweep settles them at stream end.+ // The current pass's top-level-tool sweep settles them at stream end.+ turnState.cancelled = true;+ if (!turnState.restoreCancelledPrompt) break;this.#turnCancelled = true;// A cancellation nobody asked for through THIS prompt — a stale// cancel from the previous turn landing late (the unguarded@@ -3507,13 +3644,15 @@ export class TerminalRenderer implements AgentTUIRenderer {}/**- * Flips still-running tool blocks of an interrupted turn to a terminal- * state. Approval-parked blocks are spared — a later pass can still- * settle them.+ * Flips this pass's still-running top-level tool blocks to a terminal state.+ * Approval-parked and out-of-band subagent blocks remain mutable.*/- #settleInterruptedToolBlocks(): void {- for (const block of this.#blocks) {- if (block.kind !== "tool" && block.kind !== "subagent-tool") continue;+ #settleCurrentTurnToolBlocks(turnState: RenderTurnState): void {+ for (const toolCallId of turnState.tools.keys()) {+ if (this.#childToolCallIds.has(toolCallId)) continue;+ const id = this.#parentToolBlockIds.get(toolCallId) ?? toolSectionId(toolCallId);+ const block = this.#blockById.get(id);+ if (block?.kind !== "tool") continue;if (block.status !== "running") continue;block.status = "error";block.result = "interrupted";diff --git a/packages/eve/test/tui-client/tui-background-task-hitl.ts b/packages/eve/test/tui-client/tui-background-task-hitl.tsnew file mode 100644index 000000000..efa324cae--- /dev/null+++ b/packages/eve/test/tui-client/tui-background-task-hitl.ts@@ -0,0 +1,95 @@+import { Buffer } from "node:buffer";+import { setTimeout as sleep } from "node:timers/promises";++import { Client } from "eve/client";+import { EveTUIRunner, MockScreen, MockUserInput } from "./lib/tui.ts";++import { run } from "./lib/run.ts";+import { theme } from "./lib/theme.ts";++/**+ * End-to-end proof that a local background task can raise HITL after its+ * dispatching parent turn has completed. The real task workflow must wake the+ * idle TUI, each answer must route directly to the blocked child, and the task+ * must eventually wake the parent with its terminal notification.+ */++process.env.EVE_TUI_UNICODE = "1";++const GATES = ["first_gate", "second_gate", "third_gate"] as const;++run(+ {+ app: "fixture-tasks",+ kind: "local-build",+ startEnv: { ...process.env, EVE_E2E_MODEL: "mock" },+ },+ async (target) => {+ const client = new Client({ host: target.baseUrl });+ const screen = new MockScreen({ columns: 120, rows: 50 });+ const input = new MockUserInput();+ const runner = new EveTUIRunner({+ client,+ screen,+ userInput: input,+ name: "Background task HITL smoke",+ });++ const runPromise = runner.run().catch((error: unknown) => {+ if (error instanceof Error && error.message === "Interrupted") return;+ throw error;+ });++ await screen.waitForIdlePrompt(5_000);+ input.type("TASK-HITL-ROUTING");+ input.enter();++ await screen.waitForText("TASK-HITL-STARTED", 60_000);+ console.log(theme.muted("[tui-background-task-hitl] background task started"));++ for (const gate of GATES) {+ await waitForCondition(() => approvalPromptVisible(screen.snapshot(), gate), {+ timeoutMs: 60_000,+ label: `approval prompt for ${gate}`,+ onTimeout: () => screen.snapshot(),+ });+ await sleep(500);+ input.emit("data", Buffer.from("y"));+ console.log(theme.muted(`[tui-background-task-hitl] approved ${gate}`));+ }++ await screen.waitForText("TASK-NOTIFICATION-ACK", 60_000);+ await screen.waitForIdlePrompt(30_000);++ const finalSnapshot = screen.snapshot();+ if (finalSnapshot.includes("Error")) {+ throw new Error(`Final screen contains an Error section:\n${finalSnapshot}`);+ }++ console.log(theme.muted("[tui-background-task-hitl] task completed and parent returned idle"));+ input.ctrlC();+ input.ctrlC();+ await runPromise;+ },+);++function approvalPromptVisible(snapshot: string, toolName: string): boolean {+ return (+ snapshot.includes(`Approve ${toolName}?`) ||+ snapshot.includes(`Approve ${toolName.replaceAll("_", " ")}?`)+ );+}++async function waitForCondition(+ predicate: () => boolean,+ options: { timeoutMs: number; label: string; intervalMs?: number; onTimeout?: () => string },+): Promise<void> {+ const intervalMs = options.intervalMs ?? 100;+ const deadline = Date.now() + options.timeoutMs;+ while (Date.now() < deadline) {+ if (predicate()) return;+ await sleep(intervalMs);+ }+ const extra = options.onTimeout?.() ?? "";+ throw new Error(`Timed out waiting for: ${options.label}${extra ? `\n\n${extra}` : ""}`);+}diff --git a/packages/eve/test/tui-client/tui-connection-auth-states.ts b/packages/eve/test/tui-client/tui-connection-auth-states.tsindex 03cf308db..7c19fd055 100644--- a/packages/eve/test/tui-client/tui-connection-auth-states.ts+++ b/packages/eve/test/tui-client/tui-connection-auth-states.ts@@ -61,6 +61,9 @@ class FakeSession extends ClientSession {}override stream(): AsyncIterable<MessageStreamEvent> {+ // A durable session tail cannot expose a callback continuation before+ // the turn that parked for that callback has been accepted.+ if (this.#continuationIndex >= this.#turnIndex) return pacedEvents([]);const events = this.#continuations[this.#continuationIndex] ?? [];this.#continuationIndex += 1;return pacedEvents(events);diff --git a/packages/eve/test/tui-client/tui-packed-install-model.ts b/packages/eve/test/tui-client/tui-packed-install-model.tsindex eea85cea3..ecd51572e 100644--- a/packages/eve/test/tui-client/tui-packed-install-model.ts+++ b/packages/eve/test/tui-client/tui-packed-install-model.ts@@ -98,12 +98,7 @@ void (async () => {const screen = new MockScreen({ columns: 100, rows: 40 });const input = new MockUserInput();const runner = new EveTUIRunner({- // `/model` never dispatches a turn; a turn in this test is a bug.- session: {- send: async () => {- throw new Error("unexpected turn dispatched during /model smoke test");- },- },+ // `/model` runs before the first chat turn, so no client session exists yet.screen,userInput: input,name: "Packed install model command",