The Open Framework for Building Agents
fix(client): give default message parts stable identities (#3878)
OwenKephart8aca3d8d02e0
diff --git a/.changeset/approval-sign-in-attempt-id.md b/.changeset/approval-sign-in-attempt-id.mdnew file mode 100644index 000000000..f48e7767c--- /dev/null+++ b/.changeset/approval-sign-in-attempt-id.md@@ -0,0 +1,5 @@+---+"eve": patch+---++A sign-in prompt that eve raises while checking who may answer an approval now includes its `attemptId`, so clients match the completion to that prompt instead of leaving it open.diff --git a/.changeset/eve-dev-agent-store.md b/.changeset/eve-dev-agent-store.mdnew file mode 100644index 000000000..f4672bf09--- /dev/null+++ b/.changeset/eve-dev-agent-store.md@@ -0,0 +1,5 @@+---+"eve": patch+---++The `eve dev` terminal UI now runs on the shared agent store: the prompt stays open while the agent works, including turns the agent starts on its own, approvals and questions open as soon as they arrive, and slash commands run immediately. `Esc` or `Ctrl+C` cancels the running turn instead of steering with queued messages, and an approval or question names the task that asked. While a sign-in is open, the turn bar names the connection it waits for, and a turn cancelled from another client puts its message back in the prompt.diff --git a/.changeset/late-workflow-approval-result.md b/.changeset/late-workflow-approval-result.mdnew file mode 100644index 000000000..0c551387f--- /dev/null+++ b/.changeset/late-workflow-approval-result.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Keep a tool's completed result visible when an approval decision arrives after that result. The TUI no longer shows a finished workflow call as interrupted during subsequent turns.diff --git a/.changeset/shared-conversation-client.md b/.changeset/shared-conversation-client.mdnew file mode 100644index 000000000..88a56912d--- /dev/null+++ b/.changeset/shared-conversation-client.md@@ -0,0 +1,5 @@+---+"eve": minor+---++Frontend hooks and `EveAgentStore` now share one conversation client: default hooks return `ConversationState` (messages plus root turns, input requests, tasks, and agent sessions) instead of `EveMessageData`, and every snapshot exposes canonical `conversation` alongside a custom reducer's `data`. Answers to open input requests are accepted while a turn runs, `followSubagents: true` follows each agent tool's session into `conversation.agents`, a held turn stays `streaming` with `turns[turnId].waiting` set, and `EveAgentStore` adds a `client` option plus `compact()`, `clear()`, and `retire()`.diff --git a/.changeset/stable-message-part-ids.md b/.changeset/stable-message-part-ids.mdnew file mode 100644index 000000000..274621456--- /dev/null+++ b/.changeset/stable-message-part-ids.md@@ -0,0 +1,5 @@+---+"eve": patch+---++The default message reducer gives assistant text and reasoning parts a stable `id` across streaming, completion, and replay, and keeps late-arriving participant messages ahead of their turn's response. Authorization parts match completions by `attemptId` and mark callback-backed sign-ins with `awaitsCallback`; replayed tool events no longer reopen a settled approval, and rejected tool results render as denied.diff --git a/apps/docs/registry/channel/web/app/_components/agent-chat.tsx b/apps/docs/registry/channel/web/app/_components/agent-chat.tsxindex 1a0d4452f..23d895fd6 100644--- a/apps/docs/registry/channel/web/app/_components/agent-chat.tsx+++ b/apps/docs/registry/channel/web/app/_components/agent-chat.tsx@@ -75,6 +75,9 @@ export function AgentChat({const hasConversationContent = sessionless || !isEmpty || errorMessage !== undefined;const showConversationLayout = isResuming || hasConversationContent;const activeSessionId = sessionId ?? agent.session?.sessionId;+ // Answers are accepted while work runs; the server's settlement closes each request.+ const canRespond = (requestId: string) =>+ !isResuming && agent.data.inputs[requestId]?.status === "open";const requestCancellation = () => {setCancellationError(undefined);@@ -152,7 +155,7 @@ export function AgentChat({isPendingAssistantShell &&message.id === lastMessage.id ? null : (<AgentMessage- canRespond={!isBusy && !isResuming}+ canRespond={canRespond}isStreaming={agent.status === "streaming" && index === agent.data.messages.length - 1}diff --git a/apps/docs/registry/channel/web/app/_components/agent-message.tsx b/apps/docs/registry/channel/web/app/_components/agent-message.tsxindex c94f8ff84..22c76010e 100644--- a/apps/docs/registry/channel/web/app/_components/agent-message.tsx+++ b/apps/docs/registry/channel/web/app/_components/agent-message.tsx@@ -55,7 +55,7 @@ export function AgentMessage({message,onInputResponses,}: {- readonly canRespond: boolean;+ readonly canRespond: (requestId: string) => boolean;readonly isStreaming: boolean;readonly message: EveMessage;readonly onInputResponses: (responses: readonly AgentInputResponse[]) => void | Promise<void>;@@ -96,7 +96,7 @@ function AgentMessagePart({part,showCaret,}: {- readonly canRespond: boolean;+ readonly canRespond: (requestId: string) => boolean;readonly onInputResponses: (responses: readonly AgentInputResponse[]) => void | Promise<void>;readonly part: EveMessagePart;readonly showCaret: boolean;@@ -126,7 +126,7 @@ function AgentMessagePart({if (inputRequest?.kind === "question") {return (<QuestionRequest- canRespond={canRespond}+ canRespond={canRespond(inputRequest.requestId)}inputRequest={inputRequest}inputResponse={part.toolMetadata?.eve?.inputResponse}onInputResponses={onInputResponses}@@ -405,7 +405,7 @@ function InputRequestActions({onInputResponses,part,}: {- readonly canRespond: boolean;+ readonly canRespond: (requestId: string) => boolean;readonly onInputResponses: (responses: readonly AgentInputResponse[]) => void | Promise<void>;readonly part: EveDynamicToolPart;}) {@@ -418,19 +418,30 @@ function InputRequestActions({const selectedOption = inputRequest.options?.find((option) => option.id === inputResponse?.optionId,);+ // An approval can settle before its batch resolves, without an input response.+ const settledApproval =+ part.approval?.approved === undefined+ ? undefined+ : part.approval.approved+ ? "Approved"+ : "Denied";return (<div className="space-y-3 rounded-md border border-yellow-500/30 bg-yellow-500/5 p-3"><p className="text-muted-foreground text-sm">{inputRequest.prompt}</p>- {inputResponse ? (+ {inputResponse || settledApproval ? (<p className="font-medium text-sm">- Responded: {selectedOption?.label ?? inputResponse.text ?? inputResponse.optionId}+ Responded:{" "}+ {selectedOption?.label ??+ inputResponse?.text ??+ inputResponse?.optionId ??+ settledApproval}</p>) : (<div className="flex flex-wrap gap-2">{inputRequest.options?.map((option) => (<Button- disabled={!canRespond}+ disabled={!canRespond(inputRequest.requestId)}key={option.id}onClick={() => {void onInputResponses([@@ -456,9 +467,14 @@ function InputRequestActions({function partKey(part: EveMessagePart, index: number): string {switch (part.type) {case "authorization":- return `authorization:${part.turnId}:${part.stepIndex}:${part.name}`;+ return part.attemptId === undefined+ ? `authorization:${part.turnId}:${part.stepIndex}:${part.name}`+ : `authorization:${part.attemptId}`;case "dynamic-tool":return part.toolCallId;+ case "reasoning":+ case "text":+ return `${part.type}:${part.id ?? index}`;default:return `${part.type}:${index}`;}diff --git a/apps/templates/eve-chat-template/apps/web/app/_components/agent-chat.tsx b/apps/templates/eve-chat-template/apps/web/app/_components/agent-chat.tsxindex b35e8eb13..869a862d0 100644--- a/apps/templates/eve-chat-template/apps/web/app/_components/agent-chat.tsx+++ b/apps/templates/eve-chat-template/apps/web/app/_components/agent-chat.tsx@@ -5,6 +5,7 @@ import type {AuthorizationRequiredStreamEvent,ClientSession,ClientSessionState,+ ConversationState,EveAgentStoreSnapshot,EveMessageData,MessageStreamEvent,@@ -13,7 +14,7 @@ import type {SendTurnOptions,} from "eve/client";import type { EveMessage } from "eve/react";-import { defaultMessageReducer, useEveAgent } from "eve/react";+import { conversationReducer, useEveAgent } from "eve/react";import {AlertCircleIcon,ChevronDownIcon,@@ -49,7 +50,7 @@ import {import type { ActiveChat, SetupStatus, Viewer } from "@/lib/chat/types";import { cn } from "@/lib/utils";-type AgentSnapshot = EveAgentStoreSnapshot<EveMessageData>;+type AgentSnapshot = EveAgentStoreSnapshot<ConversationState>;export type DraftHandlers = {readonly clearDraft: () => void;@@ -124,8 +125,8 @@ function attachClientSession(session: ClientSessionState | undefined): ClientSes});}-function reduceEventsToMessageData(events: readonly MessageStreamEvent[]): EveMessageData {- const reducer = defaultMessageReducer();+function reduceEventsToMessageData(events: readonly MessageStreamEvent[]): ConversationState {+ const reducer = conversationReducer;let data = reducer.initial();for (const event of events) {diff --git a/docs/guides/dev-tui.md b/docs/guides/dev-tui.mdindex eba29cc09..b145c06d3 100644--- a/docs/guides/dev-tui.md+++ b/docs/guides/dev-tui.md@@ -94,25 +94,25 @@ Required authorization or deployment setup still runs for the selected item. Pre## Work with the agent-Type a message and press `Enter` to send it. When the agent asks a question or requests tool approval, respond in the prompt shown by the UI. Connection authorization can open a browser; keep local `eve dev` running until the browser returns to it.+Type a message and press `Enter` to send it. When the agent asks a question or requests tool approval, respond in the prompt shown by the UI. Each answer is sent as soon as you give it. When several requests are open, the prompt shows its place among them, such as `2 of 5`, and names the task that asked as its transcript lines do. Connection authorization can open a browser; keep local `eve dev` running until the browser returns to it.The activity line shows **Thinking** while the model reasons or waits to respond, **Generating** while it writes a response or tool input, **Running** while tools execute, and **Waiting for** followed by task names while the turn waits on [tasks](../tools/tasks). A blinking dot and elapsed time indicate progress, with token counts shown when available. The activity line disappears when the turn finishes or needs your input.A task, such as a call to a subagent, writes one line to the transcript when it starts and one when it finishes, fails, or is stopped. The finished line names how long the task took and, for a subagent, what it did, such as `Read 3 files, Ran 2 commands`. While tasks work, a panel above the prompt shows each task's current activity and elapsed time. The UI does not show the model's own `task_wait` and `task_cancel` calls; their effect appears as the waiting activity line and a stopped task's line.-While a turn is running, `Enter` sends your message immediately as steering. Before assistant output begins, the runtime interrupts pending model generation and continues the same turn with your correction. Executing tools finish safely. After output begins, steering applies at the next workflow boundary and preserves streamed text.+The prompt stays open while the agent works, including turns started elsewhere, such as a scheduled run. While a turn is running, `Enter` sends your message immediately as steering. Before assistant output begins, the runtime interrupts pending model generation and continues the same turn with your correction. Executing tools finish safely. After output begins, steering applies at the next workflow boundary and preserves streamed text.-Slash commands wait until the turn ends, except `/cancel`, which cancels directly. If the session does not support steering, messages queue for the next turn. Press `Esc` or `Ctrl+C` to cancel a turn with no queued messages. With queued messages, these keys select the oldest message for steering, or for the next turn if steering is unavailable. If a direct cancellation requested with `/cancel` or `Ctrl+C` does not settle, press `Ctrl+C` to stop waiting. The UI then returns to the prompt and asks you to press `Ctrl+C` again to exit. At an idle prompt, press `Ctrl+C` twice to exit.+Slash commands run immediately, even during a turn. Press `Esc` or `Ctrl+C`, or run `/cancel`, to cancel a running turn. If you cancel before the turn has started, eve waits for that turn's ID before sending cancellation, so the request cannot cancel a later turn. If a cancellation does not settle, press `Ctrl+C` again to stop waiting: eve starts a new session, and the next `Ctrl+C` exits. At an idle prompt, press `Ctrl+C` twice to exit.-| Key | Action |-| ------------- | ----------------------------------------------------------------------------------------------------------------------- |-| `Enter` | Send the current message or answer. |-| `Shift+Enter` | Insert a newline. Requires a terminal that reports modified keys. |-| `Esc` | Cancel a running turn, or steer with the oldest queued message. |-| `Ctrl+C` | Cancel or steer during a turn; stop a pending cancellation, then exit on the next press; press twice to exit when idle. |-| `↑` / `↓` | Move through input lines or sent-message history. |-| `Ctrl+L` | Cycle log display modes. |-| `Ctrl+R` | Redraw the screen. |+| Key | Action |+| ------------- | ---------------------------------------------------------------------------------------------------------- |+| `Enter` | Send the current message or answer. |+| `Shift+Enter` | Insert a newline. Requires a terminal that reports modified keys. |+| `Esc` | Cancel a running turn. |+| `Ctrl+C` | Cancel a running turn; press again to stop waiting and start a new session; press twice to exit when idle. |+| `↑` / `↓` | Move through input lines or sent-message history. |+| `Ctrl+L` | Cycle log display modes. |+| `Ctrl+R` | Redraw the screen. |## Logs and tracesdiff --git a/docs/guides/frontend/overview.mdx b/docs/guides/frontend/overview.mdxindex 8822912f9..8c7b3afe8 100644--- a/docs/guides/frontend/overview.mdx+++ b/docs/guides/frontend/overview.mdx@@ -53,7 +53,7 @@ export function Chat() {<article key={message.id}><header>{message.role}</header>{message.parts.map((part, index) =>- part.type === "text" ? <p key={index}>{part.text}</p> : null,+ part.type === "text" ? <p key={part.id ?? index}>{part.text}</p> : null,)}</article>))}@@ -70,21 +70,22 @@ export function Chat() {`useEveAgent()` returns the current UI state plus commands:-| Field | What it is |-| --------- | ----------------------------------------------------------------------------------------- |-| `data` | Projected UI state from the reducer. Defaults to `{ messages }`. |-| `status` | `"ready"`, `"resuming"`, `"submitted"`, `"streaming"`, or `"error"`. Drives the composer. |-| `error` | The latest session creation, stream, resume, or turn failure. |-| `events` | Raw eve stream events for this session. |-| `session` | Serializable fixed session cursor (`sessionId`, `streamIndex`). |-| `prewarm` | Create the durable session without starting a turn. |-| `send` | Send text or a multi-part message, with per-turn options. |-| `respond` | Answer pending HITL input requests, with per-turn options. |-| `resume` | Replay an attached session and follow its in-flight turn. |-| `cancel` | Request durable cancellation of the active turn. |-| `reset` | Clear local events, data, errors, and the local session cursor. |--Most chat UIs only need `data.messages` and `status`. Drop down to `events` when you need the authoritative wire events directly, for example to persist an audit log or build a custom projection.+| Field | What it is |+| -------------- | ----------------------------------------------------------------------------------------- |+| `data` | The selected projection: `ConversationState` by default, or your custom reducer's state. |+| `conversation` | Canonical conversation state, including messages, root turns and inputs, and child state. |+| `status` | `"ready"`, `"resuming"`, `"submitted"`, `"streaming"`, or `"error"`. Drives the composer. |+| `error` | The latest session creation, stream, resume, or turn failure. |+| `events` | Raw eve stream events for this session. |+| `session` | Serializable fixed session cursor (`sessionId`, `streamIndex`). |+| `prewarm` | Create the durable session without starting a turn. |+| `send` | Send text or a multi-part message, with per-turn options. |+| `respond` | Answer pending HITL input requests, with per-turn options. |+| `resume` | Replay an attached session and follow its in-flight turn. |+| `cancel` | Request durable cancellation of the active turn. |+| `reset` | Clear local events, data, errors, and the local session cursor. |++Most chat UIs only need `data.messages` and `status` with the default reducer. Use `conversation` for session state when a custom reducer shapes `data`. Drop down to `events` when you need the authoritative wire events directly, for example to persist an audit log or build a custom projection.Pass `prewarm: true` to start a workflow when the chat mounts and after each reset:@@ -157,9 +158,10 @@ change the option from `false` to `true` again, reset, or send a message to recoThe hook keeps consuming one session stream across turns and idle periods. Replies,authorization updates, and turns started elsewhere all update the same projection. Separately-delivered participant messages remain separate bubbles even when they steer the same active turn;-a single event that coalesces multiple deliveries remains one bubble. A turn settling does not-close the connection. The transport reconnects from its cursor after a disconnect or the+delivered participant messages remain separate bubbles before that turn's assistant response, even+when they arrive after the response begins. A single event that coalesces multiple deliveries+remains one bubble. A turn settling does not close the connection. The transport reconnects from+its cursor after a disconnect or theserver's renewable 60-second lease; lease renewal does not start a turn or clear UI state.Unmounting or resetting closes the local stream without cancelling the old durable session.@@ -168,9 +170,15 @@ the reset, it prepares the next owned session; otherwise, the next send createssupplied `session` remains externally owned and is never replaced by prewarming or reset. Use`initialSession` with `resume: true` to restore a saved chat.-`data.messages` are eve-owned `EveMessage[]`. Common text, reasoning, file, and dynamic-tool parts follow the [AI SDK `UIMessage`](https://ai-sdk.dev/docs/reference/ai-sdk-core/ui-message) rendering convention, but the types are not interchangeable. eve also exposes authorization and HITL metadata, and a file part's URL can be absent. Adapt those parts before passing messages to an API typed as `UIMessage[]`.+`data.messages` are eve-owned `EveMessage[]`. Assistant text and reasoning parts have a stable `id` from the event that created the part. Appends and completion retain that ID. Use `part.id` to key streamed assistant content, including successive text parts within one step. Older events without an ID get a best-effort fallback. User text parts may not have an ID.-When the root agent delegates, its stream emits `agent.started` with the child's `sessionId`, and the subagent tool call's `task.settled` carries the child's reply. The child session can remain available for reuse. Detailed child progress lives on the child session's stream instead of being flattened into the root `data.messages`. When your UI needs live subagent activity, attach a [client session](../client/overview#sessions) to the parent and pass the `agent.started` event from `events` to [`session.agent()`](../client/streaming#follow-a-subagent) and follow the child with `stream()`. It follows local and remote children through the parent, so the browser never calls a remote deployment directly. See [What the parent sees](../../subagents#what-the-parent-sees) for the complete contract.+Common text, reasoning, file, and dynamic-tool parts follow the [AI SDK `UIMessage`](https://ai-sdk.dev/docs/reference/ai-sdk-core/ui-message) rendering convention, but the types are not interchangeable. eve also exposes authorization and HITL metadata, and a file part's URL can be absent. Adapt those parts before passing messages to an API typed as `UIMessage[]`.++When the root agent delegates, its stream emits `task.started` for the call, `agent.started` with the child's `sessionId`, and `task.settled` with the call's result, failure, or cancellation. The default reducer settles the subagent's tool part from `task.settled`, so the part shows the call's outcome rather than its start receipt. `data.tasks[taskId].calls[callId]` records each call's `status`, `output`, and `error`, and `data.agents[sessionId]` records each session a call opened, with its `taskId` and opening `callId`. These records come from the root stream alone.++Detailed child progress lives on the child session's stream, not in the root `data.messages`. Pass `followSubagents: true` to follow the session each subagent call reaches while the component is mounted; following is off by default. Narrow `data.agents[sessionId].observation.status` before reading its `conversation`: `"not-followed"` has no child detail, `"following"` has live detail, and `"idle"` has everything the calls so far produced and resumes when another call reaches the task. `"unavailable"` means the stream failed, not that the child failed. Calls that continue a task with its `taskId` reach the same session, so one session's `conversation.messages`, `inputs`, and `turns` span all of them. Sessions that a custom task opens with `ctx.agent` are recorded but not followed.++If you manage your own session rather than using the hook, pass an `agent.started` event from `events` to [`session.agent()`](../client/streaming#follow-a-subagent) and follow the child with `stream()`. It follows local and remote children through the parent, so the browser never calls a remote deployment directly. See [What the parent sees](../../subagents#what-the-parent-sees) for the complete contract.## Sending and streaming@@ -192,13 +200,15 @@ await agent.send([Assistant text, reasoning, tool calls, and tool results stream into `data` as they arrive, and a new turn moves `status` from `ready` to `submitted` to `streaming` and back. Resuming an attached session uses `resuming` while eve performs bounded catch-up. Disable message and HITL submission in that state. A settled tail moves directly to `ready`; an in-flight tail moves to `streaming` before eve follows it.+A turn stays open while tasks it started are working. `status` stays `streaming` until the turn ends, and `data.turns[turnId].waiting` is `true` while the turn is parked, until its next step starts. When a call the turn runs asks a question, `send()` resolves at that point, as `session.send().result()` does; answer with `respond()` while the turn stays open.+To steer an active turn with a follow-up, send the message with `turnPolicy: "steer"`. Before answer output or local tool execution begins, eve interrupts pending model generation and continues the same turn with the correction. Executing tools finish and checkpoint their results first; after answer output starts, steering waits for the next committed workflow boundary. Reasoning and search progress do not count as answer output. The hook stays attached through completion:```tsxawait agent.send(message, { turnPolicy: "steer" });```-Other message sends and HITL responses reject while the hook is processing a turn. Call `cancel()` to stop the durable server-side turn without replacing it, and `reset()` to clear local state so the next send starts a fresh durable session.+Other message sends reject while the hook is processing a turn. Answers to open input requests are accepted at any time; see [Human-in-the-loop prompts](#human-in-the-loop-prompts). The default `data.inputs` ledger keeps each request's originating `turnId` and `stepIndex`, response and settlement status, including requests left open after their originating turn ends; `data.activeTurnId` tracks the current root turn when known. A request from a task's run also carries that task's `taskId`. Each followed session keeps its own ledger in `data.agents[sessionId].observation.conversation`. Call `cancel()` to stop the durable server-side turn without replacing it, and `reset()` to clear local state so the next send starts a fresh durable session.`cancel()` can be called as soon as `status` is `"submitted"`; the hook waits for the active response to identify its turn when necessary, sends one guarded cancellation request, and keeps the event stream attached. The promise resolves when eve accepts the request or reports that no turn is active, and rejects if the cancellation request fails. The turn then settles on the same stream as `turn.cancelled` followed by `session.waiting`, so the session is safe to continue.@@ -216,18 +226,14 @@ received attachment as a `file` part on the user message. The part includes `med## Human-in-the-loop prompts-Tools opt into approval with `approval`, and workflow tools such as the opt-in `ask_question` tool ask the user a question with `ctx.ask()` — see [Human-in-the-loop](/docs/human-in-the-loop) for the server-side model. Either way the stream emits an `input.requested` event, and the pending request rides on a `dynamic-tool` part at `part.toolMetadata?.eve?.inputRequest`. Scan every message because an unrelated turn can add newer messages while an approval stays open, then answer through the same session with `respond()`:+Tools opt into approval with `approval`, and workflow tools such as the opt-in `ask_question` tool ask the user a question with `ctx.ask()` — see [Human-in-the-loop](/docs/human-in-the-loop) for the server-side model. Either way the stream emits an `input.requested` event. The default projection keeps open requests in `data.inputs`, including requests introduced on earlier turns while unrelated work continues. Render from that ledger and answer through the same session with `respond()`. The request also appears on its originating `dynamic-tool` part at `part.toolMetadata?.eve?.inputRequest` for inline display:```tsx-const pendingRequests = agent.data.messages- .flatMap((message) => message.parts)- .flatMap((part) => {- if (part.type !== "dynamic-tool" || part.state !== "approval-requested") return [];- const request = part.toolMetadata?.eve?.inputRequest;- return request ? [request] : [];- });+import { openConversationInputs } from "eve/react";++const pendingRequests = openConversationInputs(agent.data).map((input) => input.request);-const inputDisabled = ["submitted", "streaming", "resuming"].includes(agent.status);+const inputDisabled = agent.status === "resuming";return pendingRequests.map((request) => (<fieldset disabled={inputDisabled} key={request.requestId}>@@ -252,11 +258,11 @@ return pendingRequests.map((request) => ());```-For a question with `allowFreeform`, render a text input and send `{ requestId, text }`. The default reducer keeps each request pending until the server confirms its resolution through `input.resolved` or `approval.settled`. Disable input controls while the response is being processed; a refused approval attempt leaves the request answerable. Approved tools update again when eve streams their result.+For a question with `allowFreeform`, render a text input and send `{ requestId, text }`. You can answer while other work runs. For example, when one model step asks to approve two tools, the first approval settles on its own and the second stays answerable while the batch waits for it. `respond()` marks each answered request `responded` in `data.inputs` until the server settles it through `approval.settled` or `input.resolved`, so `openConversationInputs()` no longer returns it. Answering a request that is no longer open rejects without contacting the server. A refused approval attempt, or a response that never reaches the server, reopens the request. Approved tools update again when eve streams their result.## Authorization prompts-Connections and tools that need OAuth or another grant emit `authorization.required`. The default reducer projects that into an `authorization` message part with the display name, instructions, device code, and user-facing sign-in URL. Render that part as a normal chat message, then keep the session cursor; eve resumes the parked turn when the callback completes and updates the part after `authorization.completed`:+Connections and tools that need OAuth or another grant emit `authorization.required`. The default reducer projects that into an `authorization` message part with the display name, instructions, device code, and user-facing sign-in URL. When multiple people authorize the same connection in one session, the client matches completion to the corresponding `attemptId`, not merely the connection name. The part stays `required` until eve reports the outcome, then becomes `completed`. `awaitsCallback` is `true` when the sign-in's callback settles the attempt and resumes the parked turn. Render the part as a normal chat message and keep the session cursor so eve can resume the parked turn:```tsximport type { EveMessagePart } from "eve/react";@@ -284,7 +290,7 @@ function AuthorizationPrompt({ part }: { part: EveMessagePart }) {}```-For fully custom state machines, `authorization.required` and `authorization.completed` are still available on `events` and `onEvent`.+With a custom reducer, authorization attempts remain available in `conversation.messages`; `authorization.required` and `authorization.completed` are also available on `events` and `onEvent`.## Attach page context per turn@@ -324,11 +330,11 @@ const agent = useEveAgent({});```-The `optimistic` option (default `true`) projects submitted user messages into `data` before eve confirms them with a `message.received` event. These are reducer-facing projection events only. `events` stays the authoritative eve stream. For an existing session, the hook reconciles each placeholder with the server's delivery ID, so an unrelated or identical message cannot consume it.+The `optimistic` option (default `true`) projects submitted user messages into `data` before eve confirms them with a `message.received` event. Steered follow-ups appear before the active turn's assistant response once the turn is known; if the send fails, the failed placeholder stays in place. These are reducer-facing projection events only. `events` stays the authoritative eve stream. For an existing session, the hook reconciles each placeholder with the server's delivery ID, so an unrelated or identical message cannot consume it.## Custom reducer-The default reducer projects events into `{ messages }` (`EveMessageData`). When you want `data` shaped differently, pass a `reducer` implementing `EveAgentReducer<TData>`:+The default hook uses `conversationReducer`, which includes the `EveMessageData` message fields plus turn and input state (`ConversationState`). When you want `data` shaped differently, pass a `reducer` implementing `EveAgentReducer<TData>`:```tsximport { useEveAgent } from "eve/react";@@ -345,10 +351,10 @@ const toolCounter: EveAgentReducer<ToolLog> = {};const agent = useEveAgent({ reducer: toolCounter });-// agent.data is ToolLog+// agent.data is ToolLog; agent.conversation remains ConversationState.```-`reduce(data, event)` receives both authoritative eve stream events and client projection events (`client.message.submitted`, `client.message.failed`, `client.input.responded`). `client.input.responded` notifies custom reducers that an answer was submitted, not that it was accepted. The default reducer waits for server settlement; the durable `input.resolved` event records the server-accepted outcome and lets replayed history rebuild the same HITL state. Return `data` unchanged for events your reducer does not handle.+`reduce(data, event)` receives authoritative eve stream events and client projection events (`client.message.submitted`, `client.message.failed`, `client.input.responded`). The custom reducer only shapes `data`: the client maintains `conversation` separately for authorization, input requests, turns, and child following. Agent-session observations update `conversation.agents`, not the custom reducer. The built-in reducer makes `data` and `conversation` the same state. `client.input.responded` tells a custom reducer an answer was submitted, not that the server accepted it; the durable `input.resolved` event confirms settlement. Return `data` unchanged for events your reducer does not handle.## Resumable sessionsdiff --git a/docs/guides/frontend/use-eve-agent-svelte.mdx b/docs/guides/frontend/use-eve-agent-svelte.mdxindex 4c365e41e..2fbc70d74 100644--- a/docs/guides/frontend/use-eve-agent-svelte.mdx+++ b/docs/guides/frontend/use-eve-agent-svelte.mdx@@ -62,21 +62,15 @@ Call `agent.send(text)` for text or pass content parts for attachments. The API## Human-in-the-loop prompts-Pending requests appear in `agent.data.messages`. Use the Svelte exports when narrowing message parts, then answer through `agent.respond()`:+Open requests appear in the `agent.data.inputs` ledger. Read them with `openConversationInputs()`, then answer through `agent.respond()`. An answered request leaves the list right away, so its buttons can't be pressed twice:```svelte<script lang="ts">- import { useEveAgent } from "eve/svelte";+ import { openConversationInputs, useEveAgent } from "eve/svelte";const agent = useEveAgent();const pendingRequests = $derived(- agent.data.messages.flatMap((message) =>- message.parts.flatMap((part) => {- if (part.type !== "dynamic-tool" || part.state !== "approval-requested") return [];- const request = part.toolMetadata?.eve?.inputRequest;- return request ? [request] : [];- }),- ),+ openConversationInputs(agent.data).map((input) => input.request),);</script>@@ -128,7 +122,7 @@ Pass `onEvent`, `onError`, `onFinish`, or `onSessionChange` when the application## Custom reducer-Import `EveAgentReducer` from `eve/svelte` when projecting events into application-specific state. The resulting `agent.data` uses the reducer's `TData` type. See [Custom reducer](./overview#custom-reducer) for the reducer contract and client projection events.+Import `EveAgentReducer` from `eve/svelte` when projecting events into application-specific state. The resulting `agent.data` uses the reducer's `TData` type; `agent.conversation` remains `ConversationState`. See [Custom reducer](./overview#custom-reducer) for the reducer contract and client projection events.## What to read nextdiff --git a/docs/guides/frontend/use-eve-agent-vue.mdx b/docs/guides/frontend/use-eve-agent-vue.mdxindex ec0a83b47..f7055706f 100644--- a/docs/guides/frontend/use-eve-agent-vue.mdx+++ b/docs/guides/frontend/use-eve-agent-vue.mdx@@ -61,23 +61,17 @@ Call `send(text)` for text or pass content parts for attachments. The API and tr## Human-in-the-loop prompts-Pending requests appear in `data.value.messages`. Use the Vue exports when narrowing message parts, then answer through `respond()`:+Open requests appear in the `data.value.inputs` ledger. Read them with `openConversationInputs()`, then answer through `respond()`. An answered request leaves the list right away, so its buttons can't be pressed twice:```vue<script setup lang="ts">import { computed } from "vue";-import { useEveAgent } from "eve/vue";+import { openConversationInputs, useEveAgent } from "eve/vue";const { data, respond } = useEveAgent();const pendingRequests = computed(() =>- data.value.messages.flatMap((message) =>- message.parts.flatMap((part) => {- if (part.type !== "dynamic-tool" || part.state !== "approval-requested") return [];- const request = part.toolMetadata?.eve?.inputRequest;- return request ? [request] : [];- }),- ),+ openConversationInputs(data.value).map((input) => input.request),);</script>@@ -130,7 +124,7 @@ Pass `onEvent`, `onError`, `onFinish`, or `onSessionChange` when the application## Custom reducer-Import `EveAgentReducer` from `eve/vue` when projecting events into application-specific state. The resulting `data` remains a `ComputedRef<TData>`. See [Custom reducer](./overview#custom-reducer) for the reducer contract and client projection events.+Import `EveAgentReducer` from `eve/vue` when projecting events into application-specific state. The resulting `data` remains a `ComputedRef<TData>`; `conversation` remains a `ComputedRef<ConversationState>` regardless of your reducer. See [Custom reducer](./overview#custom-reducer) for the reducer contract and client projection events.## What to read nextdiff --git a/docs/tools/human-in-the-loop.md b/docs/tools/human-in-the-loop.mdindex 355ea8732..6b229ba1b 100644--- a/docs/tools/human-in-the-loop.md+++ b/docs/tools/human-in-the-loop.md@@ -236,7 +236,7 @@ Channels turn requests into native UI: the Slack adapter renders approvals as buFrom your own frontend, scan all messages for pending requests and answer through the same session — see [Building a frontend](/docs/guides/frontend/overview#human-in-the-loop-prompts) for the client-side reducer and `inputResponses` shape.-The default message reducer waits for server confirmation before marking any input request answered. Use the store's `submitted` or `streaming` status to show that a response is being processed; submitting a response alone does not resolve an approval, question, or session-limit prompt. The `client.input.responded` event remains a submission notification for custom reducers, not confirmation that the server accepted the answer.+You can answer while a turn is running, such as the second approval of a batch while the first answer is still settling. The default message reducer waits for server confirmation before marking any input request answered. A submitted answer marks its request `responded` in `data.inputs` until `approval.settled` or `input.resolved` arrives; submitting a response alone does not resolve an approval, question, or session-limit prompt. Answering a request that is no longer open rejects without a server request. The `client.input.responded` event remains a submission notification for custom reducers, not confirmation that the server accepted the answer.## What to read nextdiff --git a/packages/eve/src/cli/commands/init.integration.test.ts b/packages/eve/src/cli/commands/init.integration.test.tsindex 6f991d8a1..f19a50218 100644--- a/packages/eve/src/cli/commands/init.integration.test.ts+++ b/packages/eve/src/cli/commands/init.integration.test.ts@@ -10,9 +10,9 @@ import { EveTUIRunner } from "#cli/dev/tui/runner.js";import { createDevBootProgressReporter } from "#cli/dev/boot-progress.js";import { startCliLiveRow } from "#cli/ui/live-row.js";import * as liveRow from "#cli/ui/live-row.js";-import { Client, MessageResponse } from "#client/index.js";+import { Client } from "#client/index.js";+import { FakeEveServer, reply } from "#cli/dev/tui/test/fake-eve-server.js";import { createTestAgentInfoResult } from "#internal/testing/agent-info-fixture.js";-import { stampTestEvents } from "#internal/testing/events.js";import { stripAnsi } from "#cli/ui/terminal-text.js";import { packageInstallResult, packageProcessResult } from "#internal/testing/package-process.js";import { detectPackageManager } from "#setup/package-manager.js";@@ -138,6 +138,7 @@ async function createHostProject(afterEach(() => {vi.restoreAllMocks();vi.unstubAllEnvs();+ vi.unstubAllGlobals();});describe("runInitCommand", () => {@@ -216,34 +217,8 @@ describe("runInitCommand", () => {},};vi.spyOn(client, "info").mockResolvedValue(info);- const session = client.sessions.attach("session_init");- vi.spyOn(session, "stream").mockImplementation(async function* () {});- const send = vi.spyOn(session, "send").mockImplementation(- async () =>- new MessageResponse({- sessionId: "session_init",- cancelTurn: async () => ({ status: "no_active_turn" }),- createStream: async function* () {- yield* stampTestEvents([- { type: "turn.started", data: { sequence: 1, turnId: "turn_init" } },- {- type: "message.completed",- data: {- sequence: 2,- turnId: "turn_init",- stepIndex: 0,- finishReason: "stop",- message: "Hello Alice, your agent is ready.",- },- },- {- type: "session.waiting",- data: { continuationToken: "session_init", wait: "next-user-message" },- },- ]);- },- }),- );+ const server = new FakeEveServer(reply("Hello Alice, your agent is ready."));+ vi.stubGlobal("fetch", server.fetch);const handle = vi.fn(async () => {if (!connected) {const provider = await renderer.setupFlow.readSelect({@@ -255,7 +230,7 @@ describe("runInitCommand", () => {}return { message: connected ? "Using existing connection." : "Model connected." };});- const readPrompt = vi.spyOn(renderer, "readPrompt");+ const readInput = vi.spyOn(renderer, "readInput");deps.spawnPackageManager.mockImplementation(async (_manager, projectPath, args) => {expect(args).toContain("--onboard");const progress = startCliLiveRow(output, { output: screen, elapsed: true });@@ -263,7 +238,6 @@ describe("runInitCommand", () => {report({ type: "phase-started", phase: "compiling internal artifacts" });const runner = new EveTUIRunner({client,- session,renderer,appRoot: projectPath,onboard: true,@@ -285,7 +259,7 @@ describe("runInitCommand", () => {expect(screen.snapshot()).not.toContain("Starting your agent");input.enter();}- await vi.waitFor(() => expect(readPrompt).toHaveBeenCalled());+ await vi.waitFor(() => expect(readInput).toHaveBeenCalled());expect(screen.snapshot()).not.toContain("/login");expect(screen.rawOutput()).not.toContain("Using existing connection.");expect(screen.rawOutput()).not.toContain("Model connected.");@@ -296,7 +270,7 @@ describe("runInitCommand", () => {input.type("/exit");input.enter();await run;- expect(send).toHaveBeenCalledOnce();+ expect(server.requestsTo("POST", "/eve/v1/session")).toHaveLength(1);expect(handle).toHaveBeenCalledOnce();expect(screen.snapshot()).not.toContain("Starting your agent");expect(screen.rawOutput()).not.toContain("compiling internal artifacts");diff --git a/packages/eve/src/cli/dev/tui/conversation-view.test.ts b/packages/eve/src/cli/dev/tui/conversation-view.test.tsnew file mode 100644index 000000000..3e8c27c68--- /dev/null+++ b/packages/eve/src/cli/dev/tui/conversation-view.test.ts@@ -0,0 +1,24 @@+import { describe, expect, it } from "vitest";+import { stampTestEvent } from "#internal/testing/events.js";+import { createStepStartedEvent } from "#protocol/message.js";+import { tuiSessionReducer } from "./conversation-view.js";++const reportedModel = (modelId: string) =>+ tuiSessionReducer.reduce(+ tuiSessionReducer.initial(),+ stampTestEvent(+ createStepStartedEvent({ modelId, sequence: 0, stepIndex: 0, turnId: "turn_1" }),+ 0,+ ),+ ).modelId;++describe("tuiSessionReducer", () => {+ it("keeps terminal controls out of the model id the status line prints", () => {+ expect(reportedModel("\u001b]0;renamed\u0007anthropic/claude\u001b[31m")).toBe(+ "anthropic/claude",+ );+ expect(reportedModel(" anthropic/claude \n\t fast ")).toBe("anthropic/claude fast");+ expect(reportedModel("\u001b[2J")).toBeUndefined();+ expect(reportedModel("m".repeat(300))).toHaveLength(256);+ });+});diff --git a/packages/eve/src/cli/dev/tui/conversation-view.ts b/packages/eve/src/cli/dev/tui/conversation-view.tsnew file mode 100644index 000000000..23035fa7b--- /dev/null+++ b/packages/eve/src/cli/dev/tui/conversation-view.ts@@ -0,0 +1,167 @@+import type { ConversationState } from "#client/conversation-state.js";+import { stripAnsi } from "#cli/ui/terminal-text.js";+import type { EveAgentStoreSnapshot } from "#client/eve-agent-store.js";+import type { EveAgentReducer } from "#client/reducer.js";+import { isTaskRetryRefusal } from "#protocol/task-tools.js";+import {+ failureKey,+ formatFailureDetail,+ formatFailureHint,+ formatFailureMessage,+ type FailureStreamEvent,+} from "./errors.js";++export interface TokenUsage {+ readonly inputTokens: number;+ readonly outputTokens: number;+}++/** Terminal presentation facts that the canonical conversation does not model. */+export interface TuiSessionData {+ /** Step usage summed across the session; the renderer subtracts a turn baseline. */+ readonly usage: TokenUsage;+ /** The latest step's report, whose input restates the context size. */+ readonly lastStepUsage?: { readonly inputTokens?: number; readonly outputTokens?: number };+ /** The model the latest turn resolved; cleared when another turn starts. */+ readonly modelId?: string;+ readonly modelTurnId?: string;+ /** One entry per failure cascade (`step.failed` → `turn.failed` → `session.failed`). */+ readonly failures: readonly FailureStreamEvent[];+ readonly sessionFailed: boolean;+ /** Failure keys seen since the last `turn.started`, for cascade deduplication. */+ readonly turnFailureKeys: readonly string[];+ /** Tools' authored `label` copy by call, which the canonical conversation drops. */+ readonly toolLabels: Readonly<Record<string, ToolLabels>>;+ /** Calls the session refused for the model to retry; people only see the retry. */+ readonly withdrawnCallIds: readonly string[];+}++export interface ToolLabels {+ readonly start?: string;+ readonly complete?: string;+}++export const tuiSessionReducer: EveAgentReducer<TuiSessionData> = {+ initial: () => ({+ usage: { inputTokens: 0, outputTokens: 0 },+ failures: [],+ sessionFailed: false,+ turnFailureKeys: [],+ toolLabels: {},+ withdrawnCallIds: [],+ }),+ reduce(data, event) {+ switch (event.type) {+ case "actions.requested": {+ const presentation = event.data.presentation;+ if (presentation === undefined) return data;+ const toolLabels = { ...data.toolLabels };+ for (const action of event.data.actions) {+ const start = presentation[action.callId]?.label;+ if (start !== undefined) toolLabels[action.callId] = { start };+ }+ return { ...data, toolLabels };+ }+ case "action.result": {+ const { callId } = event.data.result;+ if (isTaskRetryRefusal(event)) {+ return { ...data, withdrawnCallIds: [...data.withdrawnCallIds, callId] };+ }+ const complete = event.data.presentation?.[callId]?.label;+ if (complete === undefined) return data;+ const toolLabels = {+ ...data.toolLabels,+ [callId]: { ...data.toolLabels[callId], complete },+ };+ return { ...data, toolLabels };+ }+ case "turn.started": {+ const { turnId } = event.data;+ if (data.turnFailureKeys.length === 0 && turnId === data.modelTurnId) return data;+ const { modelId: _modelId, ...rest } = data;+ return turnId === data.modelTurnId+ ? { ...data, turnFailureKeys: [] }+ : { ...rest, modelTurnId: turnId, turnFailureKeys: [] };+ }+ case "step.started": {+ // The model id is printed in the status line, so it must not carry terminal controls.+ const modelId =+ stripAnsi(event.data.modelId.slice(0, 256)).replace(/\s+/gu, " ").trim() || undefined;+ if (modelId === data.modelId) return data;+ const { modelId: _modelId, ...rest } = data;+ const modelTurnId = event.data.turnId;+ return modelId === undefined ? { ...rest, modelTurnId } : { ...rest, modelId, modelTurnId };+ }+ case "step.completed": {+ const usage = event.data.usage;+ if (usage === undefined) return data;+ return {+ ...data,+ lastStepUsage: usage,+ usage: {+ inputTokens: data.usage.inputTokens + (usage.inputTokens ?? 0),+ outputTokens: data.usage.outputTokens + (usage.outputTokens ?? 0),+ },+ };+ }+ case "step.failed":+ case "turn.failed":+ case "session.failed": {+ const key = failureKey(event);+ const sessionFailed = data.sessionFailed || event.type === "session.failed";+ if (data.turnFailureKeys.includes(key)) return { ...data, sessionFailed };+ return {+ ...data,+ failures: [...data.failures, event],+ sessionFailed,+ turnFailureKeys: [...data.turnFailureKeys, key],+ };+ }+ default:+ return data;+ }+ },+};++/** One rendered failure cascade. */+export interface AgentTUIFailure {+ readonly message: string;+ readonly hint?: string;+ /** Diagnostic dump for unrecognized failures. */+ readonly detail?: string;+}++/** Everything the renderer draws for the session, derived from one store snapshot. */+export interface AgentTUIConversationView {+ readonly conversation: ConversationState;+ /** A turn is being submitted or is running, including server-initiated turns. */+ readonly working: boolean;+ readonly data: TuiSessionData;+ readonly failures: readonly AgentTUIFailure[];+}++export function conversationView(+ snapshot: EveAgentStoreSnapshot<TuiSessionData>,+ /** Replaces a failure's harness hint with a surface-local fix. */+ failureHint?: (event: FailureStreamEvent) => string | undefined,+): AgentTUIConversationView {+ return {+ conversation: snapshot.conversation,+ working: isWorking(snapshot.status),+ data: snapshot.data,+ failures: snapshot.data.failures.map((event) => {+ const failure: { message: string; hint?: string; detail?: string } = {+ message: formatFailureMessage(event),+ };+ const hint = failureHint?.(event) ?? formatFailureHint(event);+ if (hint !== undefined) failure.hint = hint;+ const detail = formatFailureDetail(event);+ if (detail !== undefined) failure.detail = detail;+ return failure;+ }),+ };+}++export function isWorking(status: EveAgentStoreSnapshot<unknown>["status"]): boolean {+ return status === "submitted" || status === "streaming" || status === "resuming";+}diff --git a/packages/eve/src/cli/dev/tui/flow-drawer.ts b/packages/eve/src/cli/dev/tui/flow-drawer.tsindex dba585999..d5907b5cd 100644--- a/packages/eve/src/cli/dev/tui/flow-drawer.ts+++ b/packages/eve/src/cli/dev/tui/flow-drawer.ts@@ -1,4 +1,5 @@import type { Theme } from "./theme.js";+import { sliceVisible, visibleLength } from "#cli/ui/terminal-text.js";import { renderFlowPanel, type FlowPanelState } from "./setup-panel.js";/** Temporary setup content enclosed by a drawer and its navigation controls. */@@ -17,20 +18,49 @@ export function renderFlowDrawer(state: FlowPanelState, theme: Theme, width: numreturn { rows: frameDrawer(drawerBody, theme, width), controls };}-/** Frames a transient command panel with the same rules as a setup flow. */+/**+ * Frames a transient command panel with the same rules as a setup flow. A `corner` label sits at+ * the right end of the top rule.+ */export function renderTransientDrawer(body: readonly string[],controls: readonly string[],theme: Theme,width: number,+ corner?: string,): FlowDrawer {return {- rows: frameDrawer(body, theme, width),+ rows: frameDrawer(body, theme, width, corner),controls: controls.map((control) => ` ${theme.colors.dim(control)}`),};}-function frameDrawer(body: readonly string[], theme: Theme, width: number): string[] {+function frameDrawer(+ body: readonly string[],+ theme: Theme,+ width: number,+ corner?: string,+): string[] {const divider = theme.colors.dim(theme.glyph.dash.repeat(Math.max(1, width)));- return [divider, "", ...body, "", divider];+ return [+ corner === undefined ? divider : labeledRule(corner, theme, width),+ "",+ ...body,+ "",+ divider,+ ];+}++/** Ends the label two cells from the edge, mirroring the body's two-space indent. */+function labeledRule(label: string, theme: Theme, width: number): string {+ const dash = theme.glyph.dash;+ // Two dashes lead, two trail, and a space pads each side of the label.+ const room = width - 6;+ if (room < 1) return theme.colors.dim(dash.repeat(Math.max(1, width)));+ const text =+ visibleLength(label) <= room+ ? label+ : `${sliceVisible(label, room - visibleLength(theme.glyph.ellipsis))}${theme.glyph.ellipsis}`;+ const lead = width - visibleLength(text) - 4;+ return theme.colors.dim(`${dash.repeat(lead)} ${text} ${dash.repeat(2)}`);}diff --git a/packages/eve/src/cli/dev/tui/message-queue.test.ts b/packages/eve/src/cli/dev/tui/message-queue.test.tsindex c8e397799..7caf88ce4 100644--- a/packages/eve/src/cli/dev/tui/message-queue.test.ts+++ b/packages/eve/src/cli/dev/tui/message-queue.test.ts@@ -13,96 +13,22 @@ describe("MessageQueue", () => {}expect(queue.full).toBe(true);expect(queue.enqueue("one too many")).toBe(false);- expect(queue.size).toBe(MESSAGE_QUEUE_LIMIT);});- it("pops the oldest message into the steer payload on Esc", () => {- const queue = new MessageQueue();- queue.enqueue("first");- queue.enqueue("second");-- expect(queue.handleEscape()).toBe("steer");- expect(queue.view()).toMatchObject({ steering: true, messages: ["second"] });- expect(queue.takePrompt()).toBe("first");- // The remaining message stays queued for the steered turn.- expect(queue.view().messages).toEqual(["second"]);- });-- it("coalesces repeated Esc pops into one staged steer payload", () => {- const queue = new MessageQueue();- queue.enqueue("first");- queue.enqueue("second");-- expect(queue.handleEscape()).toBe("steer");- expect(queue.handleEscape()).toBe("steer");- expect(queue.takePrompt()).toBe("first\n\nsecond");- expect(queue.idle).toBe(true);- });-- it("re-reports steer while a steer payload is staged", () => {- const queue = new MessageQueue();- queue.enqueue("only");- queue.handleEscape();-- expect(queue.handleEscape()).toBe("steer");- expect(queue.view().cancelling).toBe(false);- });-- it("cancels on the first empty-queue Esc", () => {- const queue = new MessageQueue();- expect(queue.handleEscape()).toBe("cancel");- expect(queue.view().cancelling).toBe(true);- });-- it("keeps repeated empty-queue Esc cancellation idempotent", () => {- const queue = new MessageQueue();- expect(queue.handleEscape()).toBe("cancel");- expect(queue.handleEscape()).toBe("cancel");- expect(queue.view().cancelling).toBe(true);- });-- it("requests direct cancellation without consuming queued messages", () => {- const queue = new MessageQueue();- queue.enqueue("follow-up");-- queue.requestCancellation();-- expect(queue.view().cancelling).toBe(true);- expect(queue.takePrompt()).toBe("follow-up");- });-- it("drains the whole queue as one coalesced prompt at a turn boundary", () => {+ it("drains the whole queue as one coalesced prompt", () => {const queue = new MessageQueue();queue.enqueue("first");queue.enqueue("second");expect(queue.takePrompt()).toBe("first\n\nsecond");expect(queue.takePrompt()).toBeUndefined();});-- it("restores staged and queued messages into one draft", () => {- const queue = new MessageQueue();- queue.enqueue("first");- queue.enqueue("second");- queue.handleEscape();-- expect(queue.restoreDraft()).toBe("first\n\nsecond");- expect(queue.idle).toBe(true);- });-- it("clears per-turn esc state when a new turn begins", () => {- const queue = new MessageQueue();- queue.handleEscape();- queue.handleEscape();- queue.beginTurn();- expect(queue.view().cancelling).toBe(false);- });});describe("renderMessageQueueRows", () => {- const render = (queue: MessageQueue, working = true) =>- renderMessageQueueRows({ view: queue.view(), width: 80, theme, working });+ const render = (queue: MessageQueue) =>+ renderMessageQueueRows({ view: queue.view(), width: 80, theme });- it("renders nothing while idle", () => {+ it("renders nothing while empty", () => {expect(render(new MessageQueue())).toEqual([]);});@@ -113,7 +39,6 @@ describe("renderMessageQueueRows", () => {const rows = render(queue);expect(rows[0]).toContain("↑ Queue 2/5");- expect(rows[0]).toContain("esc or ctrl+c steers with the next message");expect(rows[1]).toContain("│ first message");expect(rows[1]).not.toContain("second line");expect(rows[2]).toContain("└ second message");@@ -124,29 +49,4 @@ describe("renderMessageQueueRows", () => {for (let index = 0; index < MESSAGE_QUEUE_LIMIT; index += 1) queue.enqueue("m");expect(render(queue)[0]).toContain("queue full");});-- it("drops the esc hint when no turn is streaming", () => {- const queue = new MessageQueue();- queue.enqueue("waiting");- expect(render(queue, false)[0]).not.toContain("esc");- });-- it("shows the steering header while awaiting an execution boundary", () => {- const queue = new MessageQueue();- queue.enqueue("go north");- queue.enqueue("go south");- queue.handleEscape();-- const rows = render(queue);- expect(rows[0]).toContain("Steering — waiting for the next boundary…");- expect(rows[0]).toContain("1/5 still queued");- expect(rows[1]).toContain("└ go south");- });-- it("confirms cancellation after one empty-queue Esc", () => {- const queue = new MessageQueue();- queue.handleEscape();- expect(render(queue)).toEqual([expect.stringContaining("Cancelling turn…")]);- expect(render(queue)[0]).toContain("Ctrl+C to stop waiting, then again to exit");- });});diff --git a/packages/eve/src/cli/dev/tui/message-queue.ts b/packages/eve/src/cli/dev/tui/message-queue.tsindex a27ad82a5..6c266e11e 100644--- a/packages/eve/src/cli/dev/tui/message-queue.ts+++ b/packages/eve/src/cli/dev/tui/message-queue.ts@@ -1,18 +1,7 @@/**- * The pinned message-queue panel: client-side state and pure rendering for- * messages submitted while a turn is still streaming.- *- * When steering is unavailable, Enter queues the draft (up to- * {@link MESSAGE_QUEUE_LIMIT}); each queued- * message waits for the turn to end, where the whole queue coalesces into- * the next turn's message. Esc or Ctrl+C pops the oldest message to steer the- * conversation instead of waiting: the renderer sends the popped message to- * the active session for admission at its next execution boundary.- * `/cancel` requests cancellation directly. Either key on an empty queue- * cancels the turn immediately without a replacement message.- *- * The renderer owns lifecycle (keys, cancel requests, when the runner drains- * the queue); this module only holds the queue state machine and paints rows.+ * The pinned message-queue panel: messages submitted while the agent is still+ * starting. Each queued message waits for the agent to become ready, where the+ * whole queue coalesces into the first turn's message.*/import type { Theme } from "./theme.js";@@ -22,46 +11,19 @@ import { clipVisible, stripTerminalControls } from "#cli/ui/terminal-text.js";/** Most messages the queue holds; Enter on a full queue keeps the draft. */export const MESSAGE_QUEUE_LIMIT = 5;-/** What one Esc press did to the queue state. */-type MessageQueueEscapeOutcome =- /**- * A message is staged for steering. The caller sends it to the active- * session; repeated presses may select more queued messages.- */- | "steer"- /** Empty queue — the caller should cancel the turn. */- | "cancel";-/** Read-only projection consumed by {@link renderMessageQueueRows}. */-interface MessageQueueView {+export interface MessageQueueView {readonly messages: readonly string[];readonly full: boolean;- /** A popped message is awaiting steering admission. */- readonly steering: boolean;- /** A cancel key on an empty queue landed; cancellation was requested. */- readonly cancelling: boolean;}export class MessageQueue {#messages: string[] = [];- #steerMessage: string | undefined;- #cancelRequested = false;-- get size(): number {- return this.#messages.length;- }get full(): boolean {return this.#messages.length >= MESSAGE_QUEUE_LIMIT;}- /** True when nothing is queued, staged, or cancelling. */- get idle(): boolean {- return (- this.#messages.length === 0 && this.#steerMessage === undefined && !this.#cancelRequested- );- }-/** Queues one message; returns false (draft stays put) when full. */enqueue(message: string): boolean {if (this.full) return false;@@ -69,141 +31,43 @@ export class MessageQueue {return true;}- /**- * Applies one Esc or Ctrl+C press. Pops the oldest queued message into the- * staged steer payload while any remain; with an empty queue, requests- * cancellation immediately.- */- handleEscape(): MessageQueueEscapeOutcome {- const popped = this.#messages.shift();- if (popped !== undefined) {- this.#steerMessage = joinMessages(this.#steerMessage, popped);- return "steer";- }- if (this.#steerMessage !== undefined) {- // Retry an unaccepted steering message before requesting cancellation.- return "steer";- }- this.#cancelRequested = true;- return "cancel";- }-- /** Marks a direct cancellation request without consuming queued messages. */- requestCancellation(): void {- this.#cancelRequested = true;- }-- /** Clears per-turn Esc state when a new stream starts rendering. */- beginTurn(): void {- this.#cancelRequested = false;- }-- /**- * The next prompt to submit after a turn boundary: the staged steer- * message when one exists (remaining queued messages stay queued for the- * steered turn), otherwise the whole queue coalesced into one message.- */+ /** Every queued message coalesced into one prompt; clears the queue. */takePrompt(): string | undefined {- this.#cancelRequested = false;- const steer = this.#steerMessage;- if (steer !== undefined) {- this.#steerMessage = undefined;- return steer;- }- return this.#takeAllMessages();- }-- /** Takes only a key-selected message for immediate boundary steering. */- takeSteering(): string | undefined {- const message = this.#steerMessage;- this.#steerMessage = undefined;- return message;- }-- /** Preserves an unaccepted steering message for a later retry. */- restoreSteering(message: string): void {- this.#steerMessage = joinOptionalMessages(message, this.#steerMessage);- }-- /**- * Everything still held — staged steer payload plus queued messages —- * coalesced for restoring into the prompt editor when a turn ends without- * a clean boundary (interrupt, transport failure). Clears the queue.- */- restoreDraft(): string | undefined {- this.#cancelRequested = false;- const steer = this.#steerMessage;- this.#steerMessage = undefined;- return joinOptionalMessages(steer, this.#takeAllMessages());- }-- reset(): void {- this.#messages = [];- this.#steerMessage = undefined;- this.#cancelRequested = false;- }-- view(): MessageQueueView {- return {- messages: [...this.#messages],- full: this.full,- steering: this.#steerMessage !== undefined,- cancelling: this.#cancelRequested,- };- }-- #takeAllMessages(): string | undefined {if (this.#messages.length === 0) return undefined;- const combined = this.#messages.reduce<string | undefined>(joinOptionalMessages, undefined);+ const combined = this.#messages.join("\n\n");this.#messages = [];return combined;}-}--function joinMessages(existing: string | undefined, appended: string): string {- return existing === undefined ? appended : `${existing}\n\n${appended}`;-}-function joinOptionalMessages(a: string | undefined, b: string | undefined): string | undefined {- if (b === undefined) return a;- return joinMessages(a, b);+ view(): MessageQueueView {+ return { messages: [...this.#messages], full: this.full };+ }}-interface MessageQueuePanelRowsInput {+export interface MessageQueuePanelRowsInput {readonly view: MessageQueueView;readonly width: number;readonly theme: Theme;- /** True while a turn streams — the only state in which keys steer. */- readonly working: boolean;}/*** Paints the pinned queue panel, indented so its marks share the tool* column. Queued messages ride a `│` rail under the header (one clipped- * line each) and the last closes it with `└`. The header carries the Esc- * affordance — the panel is where steering and cancellation are taught.+ * line each) and the last closes it with `└`.*/export function renderMessageQueueRows(input: MessageQueuePanelRowsInput): string[] {- const { view, width, theme, working } = input;+ const { view, width, theme } = input;+ if (view.messages.length === 0) return [];const c = theme.colors;const g = theme.glyph;const lead = TOOL_COLUMN_LEAD;-- if (view.messages.length === 0 && !view.steering) {- if (!working) return [];- if (view.cancelling) {- return [- clipVisible(- `${lead}${c.yellow(g.dotActive)} ${c.dim("Cancelling turn… · Ctrl+C to stop waiting, then again to exit")}`,- width,- ),- ];- }- return [];- }-+ const count = `${String(view.messages.length)}/${String(MESSAGE_QUEUE_LIMIT)}`;+ const fullness = view.full ? ` ${g.dot} queue full` : "";const rows = [- clipVisible(`${lead}${c.gray(g.arrowUp)} ${headerBody(view, working, theme)}`, width),+ clipVisible(+ `${lead}${c.gray(g.arrowUp)} ${c.bold("Queue")} ${c.dim(`${count}${fullness}`)}`,+ width,+ ),];for (const [index, message] of view.messages.entries()) {const rail = index === view.messages.length - 1 ? g.corner : g.rule;@@ -213,19 +77,6 @@ export function renderMessageQueueRows(input: MessageQueuePanelRowsInput): strinreturn rows;}-function headerBody(view: MessageQueueView, working: boolean, theme: Theme): string {- const c = theme.colors;- const dot = ` ${theme.glyph.dot} `;- const count = `${String(view.messages.length)}/${String(MESSAGE_QUEUE_LIMIT)}`;- if (view.steering) {- const remaining = view.messages.length > 0 ? `${dot}${count} still queued` : "";- return c.dim(`Steering — waiting for the next boundary…${remaining}`);- }- const fullness = view.full ? `${dot}queue full` : "";- const hint = working ? `${dot}esc or ctrl+c steers with the next message` : "";- return `${c.bold("Queue")} ${c.dim(`${count}${fullness}${hint}`)}`;-}-function firstLine(text: string): string {return text.split(/\r?\n/u, 1)[0] ?? "";}diff --git a/packages/eve/src/cli/dev/tui/prompt-command-handler.test.ts b/packages/eve/src/cli/dev/tui/prompt-command-handler.test.tsindex 8d94c19ff..7ba0122af 100644--- a/packages/eve/src/cli/dev/tui/prompt-command-handler.test.ts+++ b/packages/eve/src/cli/dev/tui/prompt-command-handler.test.ts@@ -38,10 +38,7 @@ const WORKSPACE_TARGET = {function context(renderer: Partial<AgentTUIRenderer> = {}): PromptCommandHandlerContext {return {- renderer: {- renderStream: vi.fn(async () => {}),- ...renderer,- },+ renderer: { ...renderer },title: "Weather Agent",};}diff --git a/packages/eve/src/cli/dev/tui/question-panel.ts b/packages/eve/src/cli/dev/tui/question-panel.tsindex 945362254..23ec49c35 100644--- a/packages/eve/src/cli/dev/tui/question-panel.ts+++ b/packages/eve/src/cli/dev/tui/question-panel.ts@@ -8,13 +8,14 @@* hosts lifecycle and keys; this module only paints rows.*/-import type { AgentTUIInputOption } from "./runner.js";+import type { AgentTUIInputContext, AgentTUIInputOption } from "./runner.js";import { visibleLine, type LineState } from "./line-editor.js";import type { Theme } from "./theme.js";import {clipVisible,renderInputText,renderInputWithBlockCursor,+ stripTerminalControls,wrapVisibleLine,} from "#cli/ui/terminal-text.js";import { renderOptionRow } from "#setup/cli/option-row.js";@@ -61,6 +62,19 @@ export function renderQuestionPanel(return rows.map((row) => clipVisible(row, width));}+/** Who asked for a prompt and where it sits among the open requests, for the drawer's corner. */+export function inputContextLabel(+ context: AgentTUIInputContext | undefined,+ theme: Theme,+): string | undefined {+ const parts: string[] = [];+ if (context?.requester !== undefined) parts.push(stripTerminalControls(context.requester));+ if (context?.position !== undefined) {+ parts.push(`${context.position.index} of ${context.position.total}`);+ }+ return parts.length === 0 ? undefined : parts.join(` ${theme.glyph.dot} `);+}+export function renderQuestionChoices(options: readonly AgentTUIInputOption[],cursor: number,diff --git a/packages/eve/src/cli/dev/tui/runner.integration.test.ts b/packages/eve/src/cli/dev/tui/runner.integration.test.tsnew file mode 100644index 000000000..9e9888920--- /dev/null+++ b/packages/eve/src/cli/dev/tui/runner.integration.test.ts@@ -0,0 +1,513 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { Client } from "#client/client.js";+import {+ createActionsRequestedEvent,+ createAgentStartedEvent,+ createInputRequestedEvent,+ createMessageAppendedEvent,+ createMessageCompletedEvent,+ createSessionFailedEvent,+ createMessageReceivedEvent,+ createSessionWaitingEvent,+ createTaskSettledEvent,+ createTaskStartedEvent,+ createTurnCancelledEvent,+ createTurnCompletedEvent,+ createTurnStartedEvent,+ createTurnWaitingEvent,+} from "#protocol/message.js";+import type { AgentTUIConversationView } from "./conversation-view.js";+import { interruptedError } from "./errors.js";+import {+ EveTUIRunner,+ type AgentTUIInput,+ type AgentTUIRenderer,+ type AgentTUIToolApprovalRequest,+} from "./runner.js";+import { FakeEveServer, reply, silent } from "./test/fake-eve-server.js";++afterEach(() => {+ vi.unstubAllGlobals();+});++/** A renderer whose composer the test drives, recording every conversation view. */+function scriptedRenderer(overrides: Partial<AgentTUIRenderer> = {}) {+ const views: AgentTUIConversationView[] = [];+ const reads: Array<{ resolve: (input: AgentTUIInput | undefined) => void; done: boolean }> = [];+ const renderer: AgentTUIRenderer = {+ renderConversation: (view) => views.push(view),+ readInput: vi.fn(+ (options) =>+ new Promise<AgentTUIInput | undefined>((resolve, reject) => {+ const read = {+ done: false,+ resolve: (input: AgentTUIInput | undefined) => {+ read.done = true;+ if (input === undefined) reject(interruptedError());+ else resolve(input);+ },+ };+ reads.push(read);+ options?.signal?.addEventListener("abort", () => {+ read.done = true;+ resolve(undefined);+ });+ }),+ ),+ ...overrides,+ };+ const pending = () => reads.findLast((read) => !read.done);+ return {+ renderer,+ views,+ latest: () => views.at(-1)!,+ /** Waits for the composer to open, then answers it. `undefined` leaves the session. */+ async input(input: AgentTUIInput | undefined) {+ await vi.waitFor(() => expect(pending()).toBeDefined());+ pending()!.resolve(input);+ },+ };+}++function assistantText(view: AgentTUIConversationView): string[] {+ return view.conversation.messages.flatMap((message) =>+ message.role === "assistant"+ ? message.parts.flatMap((part) => (part.type === "text" ? [part.text] : []))+ : [],+ );+}++function startRunner(+ server: FakeEveServer,+ renderer: AgentTUIRenderer,+ fetch: typeof globalThis.fetch = server.fetch,+) {+ vi.stubGlobal("fetch", fetch);+ const run = new EveTUIRunner({+ client: new Client({ host: "http://localhost:3000" }),+ renderer,+ name: "Review Agent",+ }).run();+ return run;+}++describe("eve dev conversation", () => {+ it("renders server-initiated turns between sends from the one session stream", async () => {+ const server = new FakeEveServer(reply("Bob received the update."));+ const tui = scriptedRenderer();+ const run = startRunner(server, tui.renderer);++ await tui.input({ type: "submit", text: "Tell Bob about the release." });+ await vi.waitFor(() =>+ expect(assistantText(tui.latest())).toContain("Bob received the update."),+ );+ await vi.waitFor(() => expect(tui.latest().working).toBe(false));++ // Alice's scheduled review wakes the agent while the composer is open.+ server.emit([+ createTurnStartedEvent({ sequence: 0, turnId: "wake" }),+ createMessageCompletedEvent({+ finishReason: "stop",+ message: "Alice finished the review.",+ sequence: 1,+ stepIndex: 0,+ turnId: "wake",+ }),+ createSessionWaitingEvent(),+ ]);+ await vi.waitFor(() =>+ expect(assistantText(tui.latest())).toEqual([+ "Bob received the update.",+ "Alice finished the review.",+ ]),+ );++ await tui.input({ type: "submit", text: "Thanks." });+ await vi.waitFor(() => expect(server.requestsTo("POST", "/session_1")).toHaveLength(1));+ await tui.input(undefined);+ await run;+ expect(server.requestsTo("GET", "/stream")).toHaveLength(1);+ expect(server.requestsTo("POST", "/session_1")[0]?.body).toMatchObject({+ turnPolicy: "queue",+ });+ });++ it("steers the running turn with a message sent while it works", async () => {+ const server = new FakeEveServer(silent());+ const tui = scriptedRenderer();+ const run = startRunner(server, tui.renderer);++ await tui.input({ type: "submit", text: "Start the review." });+ await vi.waitFor(() => expect(server.sessionId).toBe("session_1"));+ server.emit(+ [+ createTurnStartedEvent({ sequence: 0, turnId: "turn_1" }),+ createMessageAppendedEvent({+ messageDelta: "Reviewing",+ sequence: 1,+ stepIndex: 0,+ turnId: "turn_1",+ }),+ ],+ "delivery_1",+ );+ await vi.waitFor(() => expect(tui.latest().working).toBe(true));++ await tui.input({ type: "submit", text: "Include Bob's note." });+ await vi.waitFor(() => expect(server.requestsTo("POST", "/session_1")).toHaveLength(1));+ expect(server.requestsTo("POST", "/session_1")[0]?.body).toMatchObject({+ message: "Include Bob's note.",+ turnPolicy: "steer",+ });+ await tui.input(undefined);+ await run;+ });++ it("answers an approval that arrives while the composer is open", async () => {+ const server = new FakeEveServer(reply("Ready."));+ const readToolApproval = vi.fn(async () => ({ approved: true }));+ const tui = scriptedRenderer({ readToolApproval });+ const run = startRunner(server, tui.renderer);++ await tui.input({ type: "submit", text: "Hello." });+ await vi.waitFor(() => expect(tui.latest().working).toBe(false));+ server.emit([+ createTurnStartedEvent({ sequence: 0, turnId: "wake" }),+ createInputRequestedEvent({+ requests: [+ {+ action: {+ callId: "call_1",+ input: { path: "notes.md" },+ kind: "tool-call",+ toolName: "write_file",+ },+ kind: "tool-approval",+ options: [+ { id: "approve", label: "Approve" },+ { id: "cancel", label: "Cancel" },+ ],+ prompt: "Approve write_file?",+ requestId: "approval_1",+ },+ ],+ sequence: 1,+ stepIndex: 0,+ turnId: "wake",+ }),+ createSessionWaitingEvent(),+ ]);++ await vi.waitFor(() => expect(readToolApproval).toHaveBeenCalledOnce());+ await vi.waitFor(() => expect(server.requestsTo("POST", "/session_1")).toHaveLength(1));+ expect(server.requestsTo("POST", "/session_1")[0]?.body).toMatchObject({+ inputResponses: [{ requestId: "approval_1", optionId: "approve" }],+ });+ await tui.input(undefined);+ await run;+ });++ it("answers an agent's approval while its held turn waits and follows the agent's reply", async () => {+ const server = new FakeEveServer(silent());+ const readToolApproval = vi.fn(async () => ({ approved: true }));+ const tui = scriptedRenderer({ readToolApproval });+ const run = startRunner(server, tui.renderer);++ await tui.input({ type: "submit", text: "Ask the researcher for Alice's region." });+ await vi.waitFor(() => expect(server.sessionId).toBe("session_1"));+ const task = {+ callId: "call_1",+ kind: "agent" as const,+ name: "researcher",+ taskId: "task_1",+ turnId: "turn_1",+ };+ server.emit(+ [+ createMessageReceivedEvent({+ message: "Ask the researcher for Alice's region.",+ sequence: 0,+ turnId: "turn_1",+ }),+ createTurnStartedEvent({ sequence: 0, turnId: "turn_1" }),+ createTaskStartedEvent(task),+ createAgentStartedEvent({ ...task, parentSessionId: "session_1", sessionId: "child_1" }),+ createInputRequestedEvent({+ requests: [+ {+ action: { callId: "lookup_1", input: {}, kind: "tool-call", toolName: "lookup" },+ kind: "tool-approval",+ prompt: "Approve lookup?",+ requestId: "approval_1",+ },+ ],+ sequence: 1,+ stepIndex: 0,+ taskId: "task_1",+ turnId: "turn_1",+ }),+ createTurnWaitingEvent({ sequence: 1, turnId: "turn_1" }),+ ],+ "delivery_1",+ );++ await vi.waitFor(() => expect(readToolApproval).toHaveBeenCalledOnce());+ await vi.waitFor(() => expect(server.requestsTo("POST", "/session_1")).toHaveLength(1));+ expect(server.requestsTo("POST", "/session_1")[0]?.body).toMatchObject({+ inputResponses: [{ requestId: "approval_1", optionId: "approve" }],+ });+ expect(tui.latest().working).toBe(true);+ await vi.waitFor(() => expect(server.requestsTo("GET", "/child_1/stream")).toHaveLength(1));++ server.emit(+ [+ createTurnStartedEvent({ sequence: 0, turnId: "child_turn" }),+ createMessageReceivedEvent({+ message: "Find Alice's region.",+ sequence: 0,+ turnId: "child_turn",+ }),+ createMessageCompletedEvent({+ finishReason: "stop",+ message: "Alice works in the west region.",+ sequence: 1,+ stepIndex: 0,+ turnId: "child_turn",+ }),+ createTurnCompletedEvent({ sequence: 2, turnId: "child_turn" }),+ ],+ undefined,+ "child_1",+ );+ server.emit([+ createTaskSettledEvent({+ ...task,+ output: "Alice works in the west region.",+ status: "completed",+ }),+ createTurnCompletedEvent({ sequence: 2, turnId: "turn_1" }),+ createSessionWaitingEvent(),+ ]);+ await vi.waitFor(() => expect(tui.latest().working).toBe(false));+ await vi.waitFor(() =>+ expect(tui.latest().conversation.agents.child_1?.observation.status).toBe("idle"),+ );+ await tui.input(undefined);+ await run;+ });++ it("sends each approval as it is answered and counts the ones that arrive meanwhile", async () => {+ const server = new FakeEveServer(silent());+ const firstAnswer = Promise.withResolvers<{ approved: boolean }>();+ const readToolApproval = vi.fn((request: AgentTUIToolApprovalRequest) =>+ request.approvalId === "approval_task_1"+ ? firstAnswer.promise+ : Promise.resolve({ approved: true }),+ );+ const tui = scriptedRenderer({ readToolApproval });+ const run = startRunner(server, tui.renderer);++ await tui.input({ type: "submit", text: "Pick two numbers." });+ await vi.waitFor(() => expect(server.sessionId).toBe("session_1"));+ const calls = ["task_1", "task_2"].map((taskId) => ({+ callId: `pick_${taskId}`,+ kind: "agent" as const,+ name: "number_picker",+ taskId,+ turnId: "turn_1",+ }));+ const approval = (taskId: string) =>+ createInputRequestedEvent({+ requests: [+ {+ action: {+ callId: `random_${taskId}`,+ input: {},+ kind: "tool-call",+ toolName: "random_number",+ },+ kind: "tool-approval",+ prompt: "Approve random_number?",+ requestId: `approval_${taskId}`,+ },+ ],+ sequence: 2,+ stepIndex: 0,+ taskId,+ turnId: "turn_1",+ });+ server.emit(+ [+ createTurnStartedEvent({ sequence: 0, turnId: "turn_1" }),+ createActionsRequestedEvent({+ actions: calls.map(({ callId }) => ({+ callId,+ input: { message: "Pick a number." },+ kind: "tool-call" as const,+ toolName: "number_picker",+ })),+ sequence: 1,+ stepIndex: 0,+ turnId: "turn_1",+ }),+ ...calls.flatMap((call, index) => [+ createTaskStartedEvent(call),+ createAgentStartedEvent({+ ...call,+ parentSessionId: "session_1",+ sessionId: `child_${String(index + 1)}`,+ }),+ ]),+ approval("task_1"),+ createTurnWaitingEvent({ sequence: 2, turnId: "turn_1" }),+ ],+ "delivery_1",+ );+ await vi.waitFor(() => expect(readToolApproval).toHaveBeenCalledOnce());+ // Bob's approval arrives while Alice is still deciding on the first one.+ server.emit(+ [approval("task_2"), createTurnWaitingEvent({ sequence: 2, turnId: "turn_1" })],+ "delivery_1",+ );+ await vi.waitFor(() => expect(tui.latest().conversation.inputs.approval_task_2).toBeDefined());+ firstAnswer.resolve({ approved: true });++ await vi.waitFor(() => expect(server.requestsTo("POST", "/session_1")).toHaveLength(2));+ expect(readToolApproval.mock.calls.map(([request]) => request.context)).toEqual([+ { taskId: "task_1" },+ { position: { index: 2, total: 2 }, taskId: "task_2" },+ ]);+ expect(+ server.requestsTo("POST", "/session_1").map((request) => request.body?.inputResponses),+ ).toEqual([+ [{ optionId: "approve", requestId: "approval_task_1" }],+ [{ optionId: "approve", requestId: "approval_task_2" }],+ ]);+ await tui.input(undefined);+ await run;+ });++ it.each([+ ["Esc", { type: "cancel" }],+ ["/cancel", { type: "submit", text: "/cancel" }],+ ] as const)("cancels with %s only the turn the user watched start", async (_label, cancel) => {+ const server = new FakeEveServer(silent());+ const created = Promise.withResolvers<void>();+ const tui = scriptedRenderer();+ const run = startRunner(server, tui.renderer, async (input, init) => {+ // Hold session creation open so the cancel lands before any session exists.+ if (init?.method === "POST" && new URL(String(input)).pathname === "/eve/v1/session") {+ await created.promise;+ }+ return await server.fetch(input, init);+ });++ await tui.input({ type: "submit", text: "Write a long report." });+ await vi.waitFor(() => expect(tui.latest().working).toBe(true));+ await tui.input(cancel);+ created.resolve();+ await vi.waitFor(() => expect(server.sessionId).toBe("session_1"));+ await Promise.resolve();+ // No turn ID yet: cancellation waits instead of guessing.+ expect(server.requestsTo("POST", "/cancel")).toHaveLength(0);++ server.emit([createTurnStartedEvent({ sequence: 0, turnId: "turn_1" })], "delivery_1");+ await vi.waitFor(() => expect(server.requestsTo("POST", "/cancel")).toHaveLength(1));+ expect(server.requestsTo("POST", "/cancel")[0]?.body).toMatchObject({ turnId: "turn_1" });+ server.emit(+ [createTurnCancelledEvent({ sequence: 1, turnId: "turn_1" }), createSessionWaitingEvent()],+ "delivery_1",+ );+ await vi.waitFor(() => expect(tui.latest().working).toBe(false));+ await tui.input(undefined);+ await run;+ });++ it("puts a message back when another client cancels its turn, but not when this prompt does", async () => {+ const server = new FakeEveServer(silent());+ const restored: string[] = [];+ const tui = scriptedRenderer({ restoreDraft: (text) => restored.push(text) });+ const run = startRunner(server, tui.renderer);+ const cancelled = (turnId: string, message: string, delivery: string) => {+ server.emit(+ [+ createTurnStartedEvent({ sequence: 0, turnId }),+ createMessageReceivedEvent({ message, sequence: 1, turnId }),+ ],+ delivery,+ );+ return () =>+ server.emit(+ [createTurnCancelledEvent({ sequence: 2, turnId }), createSessionWaitingEvent()],+ delivery,+ );+ };++ // Bob cancels Alice's turn from another client.+ await tui.input({ type: "submit", text: "Draft the release notes." });+ await vi.waitFor(() => expect(server.sessionId).toBe("session_1"));+ cancelled("turn_1", "Draft the release notes.", "delivery_1")();+ await vi.waitFor(() => expect(restored).toEqual(["Draft the release notes."]));+ await vi.waitFor(() => expect(tui.latest().working).toBe(false));++ // Alice cancels her own next turn.+ await tui.input({ type: "submit", text: "Summarize Bob's feedback." });+ await vi.waitFor(() => expect(server.requestsTo("POST", "/session_1")).toHaveLength(1));+ const settle = cancelled("turn_2", "Summarize Bob's feedback.", "delivery_2");+ await vi.waitFor(() => expect(tui.latest().working).toBe(true));+ await tui.input({ type: "cancel" });+ await vi.waitFor(() => expect(server.requestsTo("POST", "/cancel")).toHaveLength(1));+ settle();+ await vi.waitFor(() => expect(tui.latest().working).toBe(false));+ expect(restored).toEqual(["Draft the release notes."]);+ await tui.input(undefined);+ await run;+ });++ it("starts a fresh session after the current one fails", async () => {+ const server = new FakeEveServer(silent());+ const renderSessionBoundary = vi.fn();+ const tui = scriptedRenderer({ renderSessionBoundary });+ const run = startRunner(server, tui.renderer);++ await tui.input({ type: "submit", text: "Hello." });+ await vi.waitFor(() => expect(server.sessionId).toBe("session_1"));+ server.emit(+ [+ createTurnStartedEvent({ sequence: 0, turnId: "turn_1" }),+ createSessionFailedEvent({+ code: "SANDBOX_LOST",+ message: "The sandbox stopped.",+ sessionId: "session_1",+ }),+ ],+ "delivery_1",+ );+ await vi.waitFor(() => expect(renderSessionBoundary).toHaveBeenCalledOnce());+ expect(tui.latest().conversation.messages).toEqual([]);++ await tui.input({ type: "submit", text: "Try again." });+ await vi.waitFor(() => expect(server.sessionId).toBe("session_2"));+ expect(server.requestsTo("POST", "/eve/v1/session")).toHaveLength(2);+ await tui.input(undefined);+ await run;+ });++ it("retires the session on /reset before the next message", async () => {+ const server = new FakeEveServer(reply("Done."));+ const reset = vi.fn();+ const tui = scriptedRenderer({ reset });+ const run = startRunner(server, tui.renderer);++ await tui.input({ type: "submit", text: "Hello." });+ await vi.waitFor(() => expect(tui.latest().working).toBe(false));+ await tui.input({ type: "submit", text: "/reset" });+ await vi.waitFor(() => expect(reset).toHaveBeenCalledOnce());+ expect(server.requestsTo("POST", "/session_1/reset")).toHaveLength(1);++ await tui.input({ type: "submit", text: "Start over." });+ await vi.waitFor(() => expect(server.sessionId).toBe("session_2"));+ await tui.input(undefined);+ await run;+ });+});diff --git a/packages/eve/src/cli/dev/tui/runner.test.ts b/packages/eve/src/cli/dev/tui/runner.test.tsindex c88930b1c..bdb05b5f6 100644--- a/packages/eve/src/cli/dev/tui/runner.test.ts+++ b/packages/eve/src/cli/dev/tui/runner.test.ts@@ -1,23 +1,19 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import {- Client,- ClientError,- MessageResponse,- type AgentInfoResult,- type ClientSession,- type CreateSessionOptions,- type MessageStreamEvent,- type SendTurnInput,-} from "#client/index.js";-import { getApplicationInfo } from "#internal/application/paths.js";-import { stampTestEvent } from "#internal/testing/events.js";+import { Client, ClientError, type AgentInfoResult } from "#client/index.js";import { createTestAgentInfoResult } from "#internal/testing/agent-info-fixture.js";import { resolveTestVercelTarget } from "#internal/testing/verified-vercel-target.js";+import { getApplicationInfo } from "#internal/application/paths.js";import {- EVE_MESSAGE_STREAM_VERSION,- EVE_STREAM_VERSION_HEADER,- type UnstampedMessageStreamEvent,+ createActionResultEvent,+ createActionsRequestedEvent,+ createInputRequestedEvent,+ createSessionFailedEvent,+ createSessionWaitingEvent,+ createAgentStartedEvent,+ createTaskSettledEvent,+ createTaskStartedEvent,+ createTurnStartedEvent,} from "#protocol/message.js";import { createDevelopmentCredentialGate } from "#services/dev-client/credential-gate.js";import type { VercelDeploymentResolution } from "#setup/vercel-deployment.js";@@ -27,13 +23,14 @@ import {registryHandoffAddress,type AgentTUIAgentHeader,type AgentTUIRenderer,+ type AgentTUIInput,type AgentTUISessionOptions,- type AgentTUIStreamEvent,- type CommandPresentation,type PromptCommandOutcome,} from "./runner.js";import { createPromptCommandHandler } from "./prompt-command-handler.js";-import { promptCommandsFor, type PromptCommand } from "./prompt-commands.js";+import { parsePromptCommand, promptCommandsFor } from "./prompt-commands.js";+import type { AgentTUIConversationView, AgentTUIFailure } from "./conversation-view.js";+import { FakeEveServer, type FakeEveTurn } from "./test/fake-eve-server.js";import { interruptedError } from "./errors.js";import type { RemoteAuthFlow } from "./remote-auth.js";import type { RemoteAuthCompletedMutation } from "./remote-auth-result.js";@@ -78,356 +75,6 @@ describe("registryHandoffAddress", () => {}),).toBeUndefined();});-- it("opens every distinct registry handoff in result order", async () => {- const handledCommands: Array<Extract<PromptCommand, { type: "extension" }>> = [];- const handle = vi.fn(async (command: Extract<PromptCommand, { type: "extension" }>) => {- handledCommands.push(command);- return { message: "done" };- });- const renderer = fakeRenderer({- readPrompt: vi- .fn()- .mockResolvedValueOnce("add integrations")- .mockResolvedValueOnce(undefined),- renderStream: vi.fn(async (result) => {- for await (const _event of result.events as AsyncIterable<AgentTUIStreamEvent>) {- // Consume the turn so both handoffs reach the runner queue.- }- }),- });-- await new EveTUIRunner({- session: sessionYielding([- {- type: "actions.requested",- data: {- actions: [- {- callId: "slack-add",- input: { address: "channel/slack" },- kind: "tool-call",- toolName: "selfmod__registry_add",- },- {- callId: "linear-add",- input: { address: "connection/linear" },- kind: "tool-call",- toolName: "selfmod__registry_add",- },- ],- },- },- {- type: "action.result",- data: {- result: {- callId: "slack-add",- kind: "tool-result",- output: { status: "needs-terminal", address: "channel/slack" },- },- status: "completed",- },- },- {- type: "action.result",- data: {- result: {- callId: "linear-add",- kind: "tool-result",- output: { status: "needs-terminal", address: "connection/linear" },- },- status: "completed",- },- },- { type: "session.completed" },- ]),- renderer,- name: "Weather Agent",- appRoot: "/tmp/weather-agent",- bootDetections: [],- detectProjectIdentity: vi.fn(async () => undefined),- promptCommandHandler: { handle },- }).run();-- expect(handledCommands).toEqual([- { type: "extension", name: "add", argument: "channel/slack" },- { type: "extension", name: "add", argument: "connection/linear" },- ]);- });-- it("submits a parallel approval response before opening queued setup", async () => {- const order: string[] = [];- const session = stubSession();- vi.spyOn(session, "send").mockResolvedValueOnce(- messageResponseOf([- {- type: "actions.requested",- data: {- actions: [- {- callId: "registry-add",- input: { address: "channel/slack" },- kind: "tool-call",- toolName: "selfmod__registry_add",- },- ],- },- },- {- type: "action.result",- data: {- result: {- callId: "registry-add",- kind: "tool-result",- output: { status: "needs-terminal", address: "channel/slack" },- },- status: "completed",- },- },- {- type: "input.requested",- data: {- requests: [- {- action: {- callId: "write-file",- input: { path: "agent.ts" },- kind: "tool-call",- toolName: "write_file",- },- display: "confirmation",- kind: "tool-approval",- options: [- { id: "approve", label: "Approve" },- { id: "cancel", label: "Cancel" },- ],- prompt: "Approve write_file",- requestId: "approval-1",- },- ],- },- },- { type: "session.waiting" },- ]),- );- vi.spyOn(session, "respond").mockImplementationOnce(async () => {- order.push("respond");- return messageResponseOf([{ type: "session.completed" }]);- });- const handle = vi.fn(async () => {- order.push("setup");- return { message: "done" };- });-- await new EveTUIRunner({- session,- renderer: fakeRenderer({- readPrompt: vi.fn().mockResolvedValueOnce("add slack").mockResolvedValueOnce(undefined),- readToolApproval: vi.fn(async () => ({ approved: true })),- renderStream: vi.fn(async (result) => {- for await (const _event of result.events as AsyncIterable<AgentTUIStreamEvent>) {- // Consume each continuation to its boundary.- }- }),- }),- name: "Weather Agent",- appRoot: "/tmp/weather-agent",- bootDetections: [],- detectProjectIdentity: vi.fn(async () => undefined),- promptCommandHandler: { handle },- }).run();-- expect(order).toEqual(["respond", "setup"]);- expect(session.respond).toHaveBeenCalledWith(- [{ requestId: "approval-1", optionId: "approve" }],- expect.any(Object),- );- });-- it("suspends the idle prompt before opening a subagent registry handoff", async () => {- const idlePromptStarted = createDeferred<void>();- const promptSuspended = createDeferred<void>();- const handle = vi.fn(async () => ({- message: "Slack setup completed.",- }));- const client = stubClient();- const fetchChild = vi- .fn<typeof fetch>()- .mockResolvedValueOnce(- messageStreamResponseOf([- stampTestEvent(- {- type: "actions.requested",- data: {- actions: [- {- callId: "registry-add",- input: { address: "channel/slack" },- kind: "tool-call",- toolName: "registry_add",- },- ],- sequence: 1,- stepIndex: 0,- turnId: "child-turn",- },- } as UnstampedMessageStreamEvent,- 0,- ),- stampTestEvent(- {- type: "input.requested",- data: {- requests: [- {- action: {- callId: "registry-add",- input: { address: "channel/slack" },- kind: "tool-call",- toolName: "registry_add",- },- display: "confirmation",- kind: "tool-approval",- options: [- { id: "approve", label: "Approve" },- { id: "cancel", label: "Cancel" },- ],- prompt: "Approve tool call: registry_add",- requestId: "approval-1",- },- ],- sequence: 2,- stepIndex: 0,- turnId: "child-turn",- },- } as UnstampedMessageStreamEvent,- 1,- ),- stampTestEvent(- {- type: "session.waiting",- data: { continuationToken: "child-session", wait: "next-user-message" },- } as UnstampedMessageStreamEvent,- 2,- ),- ]),- )- .mockImplementationOnce(async () => {- await idlePromptStarted.promise;- return messageStreamResponseOf([- stampTestEvent(- {- type: "actions.requested",- data: {- actions: [- {- callId: "registry-add",- input: { address: "channel/slack" },- kind: "tool-call",- toolName: "registry_add",- },- ],- sequence: 3,- stepIndex: 0,- turnId: "child-turn",- },- } as UnstampedMessageStreamEvent,- 3,- ),- stampTestEvent(- {- type: "action.result",- data: {- result: {- callId: "registry-add",- kind: "tool-result",- output: { status: "needs-terminal", address: "channel/slack" },- toolName: "registry_add",- },- sequence: 4,- status: "completed",- stepIndex: 0,- turnId: "child-turn",- },- } as UnstampedMessageStreamEvent,- 4,- ),- stampTestEvent({ type: "session.completed" } as UnstampedMessageStreamEvent, 5),- ]);- });- vi.stubGlobal("fetch", fetchChild);- const renderer = fakeRenderer({- readPrompt: vi- .fn()- .mockResolvedValueOnce("add slack")- .mockImplementationOnce(async () => {- idlePromptStarted.resolve();- await promptSuspended.promise;- return undefined;- }),- renderStream: vi.fn(async (result) => {- for await (const _event of result.events as AsyncIterable<AgentTUIStreamEvent>) {- // Consume the parent stream while the child pump follows its session.- }- }),- suspendPromptForInput: () => promptSuspended.resolve(),- subagents: {- begin: vi.fn(),- end: vi.fn(),- upsertStep: vi.fn(),- upsertTool: vi.fn(),- removeTool: vi.fn(),- markChildToolCallId: vi.fn(),- },- });-- await new EveTUIRunner({- client,- session: sessionYielding([- {- type: "task.started",- data: {- callId: "selfmod-call",- kind: "agent",- name: "self-modification__agent",- taskId: "self-modification__agent-selfmod-call",- turnId: "parent-turn",- },- },- {- type: "agent.started",- data: {- callId: "selfmod-call",- name: "self-modification__agent",- sessionId: "child-session",- streamPath: "/eve/v1/session/child-session/stream",- taskId: "self-modification__agent-selfmod-call",- turnId: "parent-turn",- },- },- { type: "turn.completed", data: { sequence: 1, turnId: "parent-turn" } },- {- type: "session.waiting",- data: { continuationToken: "parent-session", wait: "next-user-message" },- },- ]),- renderer,- name: "Weather Agent",- appRoot: "/tmp/weather-agent",- bootDetections: [],- detectProjectIdentity: vi.fn(async () => undefined),- promptCommandHandler: { handle },- }).run();-- const resumed = new URL(String(fetchChild.mock.calls[1]![0]));- expect(resumed.pathname).toBe("/eve/v1/session/child-session/stream");- expect(resumed.searchParams.get("startIndex")).toBe("3");- expect(handle).toHaveBeenCalledWith(- { type: "extension", name: "add", argument: "channel/slack" },- expect.objectContaining({ title: "Add to your agent" }),- );- });});/**@@ -439,58 +86,6 @@ function stubClient(): Client {return new Client({ host: "http://localhost:3000" });}-/** Real `ClientSession` handle; harmless until `send`/`stream` are spied. */-function stubSession(): ClientSession {- return stubClient().sessions.attach("session_test");-}--function mockSessionCreation(client: Client, session: ClientSession) {- return vi- .spyOn(client.sessions, "create")- .mockImplementation(async (input: CreateSessionOptions | SendTurnInput = {}) => {- if (!("message" in input)) return { session };- return { response: await session.send(input.message, input), session };- });-}--/**- * Wraps literal stream events in a real `MessageResponse`. Each literal is- * stamped as its own emission; pass the same stamped event twice to model a- * re-delivery.- */-function messageResponseOf(events: readonly unknown[]): MessageResponse {- const stamped = events.map((event, index) =>- isStamped(event) ? event : stampTestEvent(event as UnstampedMessageStreamEvent, index),- );- return new MessageResponse({- cancelTurn: async () => ({ status: "no_active_turn" }),- createStream: async function* () {- for (const event of stamped) yield event;- },- sessionId: "session_test",- });-}--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();- },- }),- {- headers: { [EVE_STREAM_VERSION_HEADER]: EVE_MESSAGE_STREAM_VERSION },- },- );-}--function isStamped(event: unknown): event is MessageStreamEvent {- return typeof (event as MessageStreamEvent).meta?.id === "string";-}-const AGENT_INFO: AgentInfoResult = createTestAgentInfoResult({agentRoot: "/tmp/weather-agent/agent",appRoot: "/tmp/weather-agent",@@ -512,14 +107,70 @@ afterEach(() => {vi.useRealTimers();});+describe("parsePromptCommand", () => {+ it("parses /model with a provider/model slug", () => {+ expect(parsePromptCommand("/model anthropic/claude-opus-4.6")).toEqual({+ type: "extension",+ name: "model",+ argument: "anthropic/claude-opus-4.6",+ });+ });++ it("trims whitespace around the command and slug", () => {+ expect(parsePromptCommand(" /model anthropic/claude-opus-4.6 ")).toEqual({+ type: "extension",+ name: "model",+ argument: "anthropic/claude-opus-4.6",+ });+ });++ it("parses bare /model as an empty slug", () => {+ expect(parsePromptCommand("/model")).toEqual({+ type: "extension",+ name: "model",+ argument: "",+ });+ });++ it("recognizes /reset, /cancel, /clear, /compact, /exit, and /quit", () => {+ expect(parsePromptCommand("/reset")).toEqual({ type: "reset" });+ expect(parsePromptCommand("/cancel")).toEqual({ type: "cancel" });+ expect(parsePromptCommand("/clear")).toEqual({ type: "clear" });+ expect(parsePromptCommand("/compact")).toEqual({ type: "compact" });+ expect(parsePromptCommand("/exit")).toEqual({ type: "exit" });+ expect(parsePromptCommand("/quit")).toEqual({ type: "exit" });+ });++ it("does not match near-misses or normal messages", () => {+ expect(parsePromptCommand("hello")).toBeNull();+ expect(parsePromptCommand("/models")).toBeNull();+ expect(parsePromptCommand("what does /model do?")).toBeNull();+ });+});+function fakeRenderer(overrides: Partial<AgentTUIRenderer> = {}): AgentTUIRenderer {return {- renderStream: vi.fn(async () => {}),- readPrompt: vi.fn(async () => undefined),+ readInput: vi.fn(async () => undefined),...overrides,};}+/** Adapts a scripted prompt reader to the composer: text submits, `undefined` leaves. */+function submitting(read: (options?: AgentTUISessionOptions) => Promise<string | undefined>) {+ return vi.fn(async (options?: AgentTUISessionOptions): Promise<AgentTUIInput | undefined> => {+ const text = await read(options);+ return text === undefined ? undefined : { type: "submit", text };+ });+}++/** A composer that submits each text in order, then leaves the session. */+function inputs(texts: Array<string | undefined>) {+ return vi.fn(async (): Promise<AgentTUIInput | undefined> => {+ const text = texts.shift();+ return text === undefined ? undefined : { type: "submit", text };+ });+}+function idleSetupFlow(): SetupFlowRenderer {return {begin: vi.fn(),@@ -568,17 +219,16 @@ describe("EveTUIRunner agent header", () => {);const renderer = fakeRenderer();const runner = new EveTUIRunner({- session: stubSession(),client,renderer,serverUrl: "http://localhost:3000",});const run = runner.run();await vi.advanceTimersByTimeAsync(1999);- expect(renderer.readPrompt).not.toHaveBeenCalled();+ expect(renderer.readInput).not.toHaveBeenCalled();await vi.advanceTimersByTimeAsync(1);await run;- expect(renderer.readPrompt).toHaveBeenCalled();+ expect(renderer.readInput).toHaveBeenCalled();expect(client.info).toHaveBeenCalledOnce();});@@ -587,7 +237,6 @@ describe("EveTUIRunner agent header", () => {const client = stubClient();vi.spyOn(client, "info").mockResolvedValue(AGENT_INFO);const runner = new EveTUIRunner({- session: stubSession(),client,renderer: fakeRenderer({renderAgentHeader: () => order.push("render"),@@ -610,7 +259,6 @@ describe("EveTUIRunner agent header", () => {vi.spyOn(client, "info").mockResolvedValue(AGENT_INFO);const runner = new EveTUIRunner({- session: stubSession(),client,renderer,serverUrl: "http://localhost:3000",@@ -626,7 +274,7 @@ describe("EveTUIRunner agent header", () => {localDevelopment: false,info: AGENT_INFO,});- expect(renderer.readPrompt).toHaveBeenCalled();+ expect(renderer.readInput).toHaveBeenCalled();});it("still renders a header when info cannot be fetched", async () => {@@ -638,7 +286,6 @@ describe("EveTUIRunner agent header", () => {vi.spyOn(client, "info").mockRejectedValue(new Error("unauthorized"));const runner = new EveTUIRunner({- session: stubSession(),client,renderer,serverUrl: "http://localhost:3000",@@ -663,7 +310,6 @@ describe("EveTUIRunner agent header", () => {.mockRejectedValueOnce(new ClientError(500, "Runner did not become ready in time")).mockResolvedValueOnce(AGENT_INFO);const runner = new EveTUIRunner({- session: stubSession(),client,renderer,serverUrl: "http://localhost:3000",@@ -685,2552 +331,72 @@ describe("EveTUIRunner agent header", () => {},]);});+});- it("refreshes the agent header when a dev artifact refresh changes the model", async () => {- const headers: AgentTUIAgentHeader[] = [];- const prompts: Array<string | undefined> = ["first", "second", undefined];- const nextInfo: AgentInfoResult = {- ...AGENT_INFO,- agent: {- ...AGENT_INFO.agent,- model: {- id: "anthropic/claude-sonnet-5",- routing: { kind: "gateway", target: "anthropic" },- },- },- };- const client = stubClient();- vi.spyOn(client, "info").mockResolvedValueOnce(AGENT_INFO).mockResolvedValueOnce(nextInfo);- vi.stubGlobal(- "fetch",- vi.fn(async () => {- const revision = prompts.length >= 2 ? "snapshot-a" : "snapshot-b";- return Response.json({ revision });- }),- );-- const renderer: AgentTUIRenderer = {- readPrompt: vi.fn(async () => prompts.shift()),- renderAgentHeader: (header) => headers.push(header),- renderStream: vi.fn(async (result) => {- for await (const event of result.events as AsyncIterable<unknown>) {- void event;- }- }),- };- const session = sessionYielding([{ type: "session.waiting" }]);-+describe("EveTUIRunner development session continuity", () => {+ it("does not call the cancel API before a session has started", async () => {+ const results: string[] = [];+ const prompts: Array<string | undefined> = ["/cancel", undefined];const runner = new EveTUIRunner({- session,- client,- renderer,- serverUrl: "http://localhost:3000",+ client: stubClient(),name: "Weather Agent",+ renderer: fakeRenderer({+ readInput: inputs(prompts),+ finishCommand: (outcome) => {+ if (outcome.kind === "result") results.push(outcome.message ?? outcome.summary ?? "");+ },+ }),});await runner.run();- expect(headers).toHaveLength(2);- expect(headers[0]?.info?.agent.model.id).toBe("gpt-5");- expect(headers[1]?.info?.agent.model.id).toBe("anthropic/claude-sonnet-5");- expect(client.info).toHaveBeenCalledTimes(2);- expect(session.send).toHaveBeenCalledTimes(2);+ expect(results).toEqual(["No active turn to cancel"]);});+});- it("retries a transient info failure while refreshing the agent header", async () => {- vi.useFakeTimers();- const headers: AgentTUIAgentHeader[] = [];- const prompt = createDeferred<string | undefined>();- const nextInfo: AgentInfoResult = {- ...AGENT_INFO,- agent: {- ...AGENT_INFO.agent,- model: {- id: "anthropic/claude-sonnet-5",- routing: { kind: "gateway", target: "anthropic" },- },- },- };+describe("EveTUIRunner initial input", () => {+ it("uses the startup draft captured after the agent info probe", async () => {+ const info = createDeferred<typeof AGENT_INFO>();const client = stubClient();- vi.spyOn(client, "info")- .mockResolvedValueOnce(AGENT_INFO)- .mockRejectedValueOnce(new ClientError(500, "Runner did not become ready in time"))- .mockResolvedValueOnce(nextInfo);- const revisions = ["snapshot-a", "snapshot-b"];- const fetchMock = vi.fn(async () =>- Response.json({ revision: revisions.shift() ?? "snapshot-b" }),- );- vi.stubGlobal("fetch", fetchMock);-- const renderer: AgentTUIRenderer = {- readPrompt: vi.fn(async () => await prompt.promise),- renderAgentHeader: (header) => headers.push(header),- renderStream: vi.fn(async () => {}),+ vi.spyOn(client, "info").mockReturnValue(info.promise);+ const startup = {+ finish: vi.fn(() => ({ draft: "typed while loading", queuedPrompt: undefined })),};- const session = sessionYielding([{ type: "session.waiting" }]);-+ const renderer = fakeRenderer();const runner = new EveTUIRunner({- session,client,renderer,serverUrl: "http://localhost:3000",- name: "Weather Agent",+ startup,});- const run = runner.run();- await settleAsyncWork();- await vi.advanceTimersByTimeAsync(0);- expect(headers).toHaveLength(1);- expect(fetchMock).toHaveBeenCalledTimes(1);-- await vi.advanceTimersByTimeAsync(500);- await settleAsyncWork();- await vi.advanceTimersByTimeAsync(100);+ const running = runner.run();await settleAsyncWork();+ expect(startup.finish).not.toHaveBeenCalled();+ info.resolve(AGENT_INFO);+ await running;- expect(headers).toHaveLength(2);- expect(headers[1]?.info?.agent.model.id).toBe("anthropic/claude-sonnet-5");- expect(client.info).toHaveBeenCalledTimes(3);- expect(session.send).not.toHaveBeenCalled();-- prompt.resolve(undefined);- await run;- });-- it("waits for an in-flight idle refresh before sending a prompt", async () => {- vi.useFakeTimers();- const prompt = createDeferred<string | undefined>();- const revisionResponse = createDeferred<Response>();- const client = stubClient();- vi.spyOn(client, "info").mockResolvedValue(AGENT_INFO);- vi.stubGlobal(- "fetch",- vi.fn(async () => await revisionResponse.promise),+ expect(startup.finish).toHaveBeenCalledOnce();+ expect(renderer.readInput).toHaveBeenCalledWith(+ expect.objectContaining({ initialDraft: "typed while loading" }),);- const session = sessionYielding([{ type: "session.waiting" }]);- const prompts: Array<Promise<string | undefined> | string | undefined> = [- prompt.promise,- undefined,- ];-- const renderer: AgentTUIRenderer = {- readPrompt: vi.fn(async () => await prompts.shift()),- renderAgentHeader: vi.fn(),- renderStream: vi.fn(async (result) => {- for await (const event of result.events as AsyncIterable<unknown>) {- void event;- }- }),- };-- const runner = new EveTUIRunner({- session,- client,- renderer,- serverUrl: "http://localhost:3000",- name: "Weather Agent",- });-- const run = runner.run();- await settleAsyncWork();- prompt.resolve("hello");- await settleAsyncWork();-- expect(session.send).not.toHaveBeenCalled();-- revisionResponse.resolve(Response.json({ revision: "snapshot-a" }));- await run;+ });+});- expect(session.send).toHaveBeenCalledTimes(1);- });-});--function sessionYielding(events: readonly unknown[]): ClientSession {- const session = stubSession();- vi.spyOn(session, "send").mockImplementation(async () => messageResponseOf(events));- vi.spyOn(session, "respond").mockImplementation(async () => messageResponseOf(events));- return session;-}--function sessionYieldingTurns(turns: ReadonlyArray<readonly unknown[]>): ClientSession {- const session = stubSession();- let index = 0;- const nextResponse = async () => {- const events = turns[index] ?? [];- index += 1;- return messageResponseOf(events);- };- vi.spyOn(session, "send").mockImplementation(nextResponse);- vi.spyOn(session, "respond").mockImplementation(nextResponse);- return 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",- onboard: true,- bootDetections: [],- getVercelAuthStatus: vi.fn(async (): Promise<"authenticated"> => "authenticated"),- promptCommandHandler: { handle },- });-- await expect(runner.run()).resolves.toBeUndefined();-- expect(handle).toHaveBeenCalledWith(- { type: "extension", name: "login", argument: "" },- expect.objectContaining({ initialModelStep: "provider" }),- );- expect(renderIdleStream).not.toHaveBeenCalled();- });-- it("renders an idle-session turn after two quiet minutes without another user message", async () => {- vi.useFakeTimers();- const session = stubSession();- const prompt = createDeferred<string | undefined>();- const idleEvents: AgentTUIStreamEvent[] = [];- const wakeEvents = [- { type: "turn.started", data: { sequence: 1, turnId: "wake-turn" } },- {- type: "step.started",- data: { modelId: "test-model", sequence: 1, stepIndex: 0, turnId: "wake-turn" },- },- {- type: "message.completed",- data: {- finishReason: "stop",- message: "Alice's review is ready for Bob.",- sequence: 1,- stepIndex: 0,- 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));- let connections = 0;- const signals: AbortSignal[] = [];- vi.stubGlobal(- "fetch",- vi.fn(async (_url: unknown, init?: RequestInit) => {- connections += 1;- if (init?.signal) signals.push(init.signal);- if (connections === 8) return messageStreamResponseOf(wakeEvents);- let removeAbortListener: (() => void) | undefined;- return new Response(- new ReadableStream<Uint8Array>({- start(controller) {- const abort = () => controller.close();- init?.signal?.addEventListener("abort", abort, { once: true });- removeAbortListener = () => init?.signal?.removeEventListener("abort", abort);- },- cancel() {- removeAbortListener?.();- },- }),- { headers: { [EVE_STREAM_VERSION_HEADER]: EVE_MESSAGE_STREAM_VERSION } },- );- }),- );- const send = vi.spyOn(session, "send");- const runner = new EveTUIRunner({- session,- name: "Research Agent",- renderer: fakeRenderer({- readPrompt: () => prompt.promise,- renderIdleStream: async (result) => {- for await (const event of result.events) idleEvents.push(event);- },- }),- });- const running = runner.run();- try {- await vi.advanceTimersByTimeAsync(130_000);- expect(connections).toBeGreaterThanOrEqual(8);- expect(idleEvents).toContainEqual({ type: "turn-start", turnId: "wake-turn" });- expect(idleEvents).toContainEqual({ type: "step-start", modelId: "test-model" });- expect(idleEvents).toContainEqual({- type: "assistant-complete",- id: "text:wake-turn:0",- text: "Alice's review is ready for Bob.",- });- expect(send).not.toHaveBeenCalled();- } finally {- prompt.resolve(undefined);- await running;- }- expect(signals.every((signal) => signal.aborted)).toBe(true);- expect(session.state.streamIndex).toBe(wakeEvents.length);- });-- it.each(["session.completed", "session.failed"] as const)(- "stops idle following at %s even while the prompt remains open",- async (type) => {- vi.useFakeTimers();- const prompt = createDeferred<string | undefined>();- const fetch = vi.fn(async () =>- messageStreamResponseOf([- stampTestEvent({- type,- data: { sessionId: "session_test", code: "SESSION_FAILED", message: "Session ended." },- } as UnstampedMessageStreamEvent),- ]),- );- vi.stubGlobal("fetch", fetch);- const runner = new EveTUIRunner({- session: stubSession(),- name: "Research Agent",- renderer: fakeRenderer({- readPrompt: () => prompt.promise,- renderIdleStream: async (result) => {- for await (const event of result.events) {- void event;- }- },- }),- });- const running = runner.run();- try {- await vi.advanceTimersByTimeAsync(130_000);- expect(fetch).toHaveBeenCalledOnce();- } finally {- prompt.resolve(undefined);- await running;- }- },- );-- 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: "lookup-1",- input: { query: "research status" },- kind: "tool-call",- toolName: "lookup",- },- ],- sequence: 1,- stepIndex: 0,- turnId: "wake-turn",- },- },- {- type: "action.result",- data: {- result: {- callId: "lookup-1",- kind: "tool-result",- output: { status: "finished" },- toolName: "lookup",- },- sequence: 1,- status: "completed",- stepIndex: 0,- turnId: "wake-turn",- },- },- {- type: "message.appended",- data: {- messageDelta: "Research finished.",- sequence: 1,- stepIndex: 1,- turnId: "wake-turn",- },- },- {- type: "message.completed",- data: {- finishReason: "stop",- message: "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.",- 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: "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("reconnects idle following when a transport stream ends before an approval arrives", async () => {- const session = stubSession();- const prompt = createDeferred<string | undefined>();- const requestId = "approval-after-reconnect";- const firstWakeEvents = [- stampTestEvent({- type: "message.appended",- data: {- messageDelta: "Still working.",- sequence: 1,- stepIndex: 0,- turnId: "progress-turn",- },- } as UnstampedMessageStreamEvent),- stampTestEvent({- type: "session.waiting",- data: { continuationToken: "session-id", wait: "next-user-message" },- }),- ];- const wakeEvents = [- stampTestEvent({- type: "input.requested",- data: {- sequence: 1,- stepIndex: 0,- turnId: "wake-turn",- requests: [- {- action: {- callId: "call-1",- input: { address: "connection/linear" },- kind: "tool-call",- toolName: "selfmod__registry_add",- },- display: "confirmation",- kind: "tool-approval",- options: [- { id: "approve", label: "Approve" },- { id: "cancel", label: "Cancel" },- ],- prompt: "Approve tool call: selfmod__registry_add",- 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 }) => {- const call = ++streamCalls;- const events = call === 1 ? firstWakeEvents : call === 2 ? wakeEvents : [];- return {- async *[Symbol.asyncIterator]() {- for (const event of events) yield event;- if (call === 2) {- await new Promise<void>((resolve) => {- if (options?.signal?.aborted) resolve();- else options?.signal?.addEventListener("abort", () => resolve(), { once: true });- });- }- },- };- });- const idleEvents: AgentTUIStreamEvent[] = [];- const fallback = setTimeout(() => prompt.resolve(undefined), 1_000);- const renderer = fakeRenderer({- readPrompt: vi- .fn()- .mockImplementationOnce(() => prompt.promise)- .mockResolvedValueOnce(undefined),- readToolApproval: vi.fn(async () => ({ approved: false })),- renderIdleStream: vi.fn(async (result) => {- for await (const event of result.events) idleEvents.push(event);- }),- renderStream: vi.fn(async (result) => {- for await (const event of result.events) void event;- }),- suspendPromptForInput: vi.fn(() => prompt.reject(interruptedError())),- });-- try {- await new EveTUIRunner({ session, renderer, name: "Task Agent" }).run();- } finally {- clearTimeout(fallback);- }-- expect(streamCalls).toBeGreaterThanOrEqual(2);- expect(idleEvents.filter((event) => event.type === "assistant-delta")).toEqual([- { delta: "Still working.", id: "text:progress-turn:0", type: "assistant-delta" },- ]);- expect(renderer.readToolApproval).toHaveBeenCalledWith(- expect.objectContaining({ approvalId: requestId, toolName: "selfmod__registry_add" }),- { title: "Task Agent" },- );- });-- it("answers an approval that arrives while the prompt is idle", async () => {- const session = stubSession();- const prompt = createDeferred<string | undefined>();- const requestId = "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 }> = [];- const revisions = ["revision-a", "revision-a", "revision-b", "revision-b"];- const encoder = new TextEncoder();- let nextRevision = 0;- let nextSession = 0;- let nextDelivery = 0;- vi.stubGlobal(- "fetch",- vi.fn(async (input: Parameters<typeof fetch>[0], init?: RequestInit) => {- const url = new URL(- typeof input === "string" ? input : input instanceof URL ? input : input.url,- );- const method = init?.method ?? "GET";- requests.push({ method, url });-- if (url.pathname.startsWith("/eve/v1/dev/runtime-artifacts")) {- const revision = revisions[Math.min(nextRevision, revisions.length - 1)] ?? "revision";- nextRevision += 1;- return Response.json({ revision });- }-- if (method === "POST") {- const sessionId =- url.pathname === "/eve/v1/session"- ? `session-${String(++nextSession)}`- : (url.pathname.split("/")[4] ?? `session-${String(++nextSession)}`);- return Response.json({ sessionId, deliveryId: `delivery-${++nextDelivery}` });- }-- return new Response(- new ReadableStream<Uint8Array>({- start(controller) {- controller.enqueue(- encoder.encode(- `${JSON.stringify({- ...stampTestEvent({- type: "session.waiting",- data: { continuationToken: "session-id", wait: "next-user-message" },- } as UnstampedMessageStreamEvent),- meta: {- at: new Date().toISOString(),- id: `event-${nextDelivery}`,- deliveryIds: [`delivery-${nextDelivery}`],- },- })}\n`,- ),- );- controller.close();- },- }),- {- headers: { [EVE_STREAM_VERSION_HEADER]: EVE_MESSAGE_STREAM_VERSION },- },- );- }),- );-- const client = stubClient();- vi.spyOn(client, "info").mockResolvedValue(AGENT_INFO);- const session = client.sessions.attach("session-1");- const createSession = vi.spyOn(client.sessions, "create");- const prompts: Array<string | undefined> = ["first", "second", undefined];- const runner = new EveTUIRunner({- client,- name: "Weather Agent",- renderer: {- readPrompt: vi.fn(async () => prompts.shift()),- renderStream: vi.fn(async (result) => {- for await (const event of result.events as AsyncIterable<unknown>) {- void event;- }- }),- },- serverUrl: "http://localhost:3000",- session,- });-- await runner.run();-- expect(createSession).not.toHaveBeenCalled();- expect(session.state.sessionId).toBe("session-1");- expect(- requests- .filter(- (request) =>- request.method === "POST" && request.url.pathname.startsWith("/eve/v1/session"),- )- .map((request) => request.url.pathname),- ).toEqual(["/eve/v1/session/session-1", "/eve/v1/session/session-1"]);- });-- it("starts a fresh session only after an explicit /reset command", async () => {- const initialSession = sessionYielding([{ type: "session.waiting" }]);- const reset = vi- .spyOn(initialSession, "reset")- .mockResolvedValue({ previousSessionId: "session_1", status: "reset" });- const newSession = sessionYielding([{ type: "session.waiting" }]);- const client = stubClient();- const createSession = mockSessionCreation(client, newSession);- const prompts: Array<string | undefined> = ["first", "/reset", "second", undefined];- const runner = new EveTUIRunner({- client,- name: "Weather Agent",- renderer: {- readPrompt: vi.fn(async () => prompts.shift()),- renderStream: vi.fn(async (result) => {- for await (const event of result.events as AsyncIterable<unknown>) {- void event;- }- }),- },- session: initialSession,- });-- await runner.run();-- expect(createSession).toHaveBeenCalledOnce();- expect(reset).toHaveBeenCalledOnce();- expect(initialSession.send).toHaveBeenCalledOnce();- expect(newSession.send).toHaveBeenCalledOnce();- });-- it("compacts the active session without sending a prompt", async () => {- const session = sessionYielding([]);- const compact = vi- .spyOn(session, "compact")- .mockResolvedValue({ sessionId: "session_1", status: "accepted" });- const stream = vi.spyOn(session, "stream").mockReturnValue(- (async function* () {- yield stampTestEvent(- {- data: { continuationToken: "session-id", wait: "next-user-message" },- type: "session.waiting",- },- 0,- );- })(),- );- const results: string[] = [];- const prompts: Array<string | undefined> = ["/compact", undefined];- const runner = new EveTUIRunner({- name: "Weather Agent",- renderer: fakeRenderer({- readPrompt: vi.fn(async () => prompts.shift()),- finishCommand: (outcome) => {- if (outcome.kind === "result") results.push(outcome.message ?? "");- },- renderStream: vi.fn(async (result) => {- for await (const event of result.events) {- void event;- }- }),- }),- session,- });-- await runner.run();-- expect(compact).toHaveBeenCalledOnce();- expect(stream).toHaveBeenCalledOnce();- expect(session.send).not.toHaveBeenCalled();- expect(results).toEqual([""]);- });-- it.each(["/clear", "/new"])(- "%s clears the active session context without sending a prompt",- async (command) => {- const session = sessionYielding([]);- const clear = vi- .spyOn(session, "clear")- .mockResolvedValue({ sessionId: "session_1", status: "accepted" });- const stream = vi.spyOn(session, "stream").mockReturnValue(- (async function* () {- yield stampTestEvent(- {- data: { continuationToken: "session-id", wait: "next-user-message" },- type: "session.waiting",- },- 0,- );- })(),- );- const results: string[] = [];- const prompts: Array<string | undefined> = [command, undefined];- const runner = new EveTUIRunner({- name: "Weather Agent",- renderer: fakeRenderer({- readPrompt: vi.fn(async () => prompts.shift()),- finishCommand: (outcome) => {- if (outcome.kind === "result") results.push(outcome.message ?? "");- },- renderStream: vi.fn(async (result) => {- for await (const event of result.events) {- void event;- }- }),- }),- session,- });-- await runner.run();-- expect(clear).toHaveBeenCalledOnce();- expect(stream).toHaveBeenCalledOnce();- expect(session.send).not.toHaveBeenCalled();- expect(results).toEqual([]);- },- );-- it("keeps /clear in the transcript when clearing fails", async () => {- const session = sessionYielding([]);- vi.spyOn(session, "clear").mockRejectedValue(new Error("World unavailable"));- const outcomes: CommandPresentation[] = [];- const prompts: Array<string | undefined> = ["/clear", undefined];- await new EveTUIRunner({- name: "Weather Agent",- renderer: fakeRenderer({- readPrompt: vi.fn(async () => prompts.shift()),- finishCommand: (outcome) => outcomes.push(outcome),- }),- session,- }).run();-- expect(outcomes).toEqual([- {- kind: "result",- message: "World unavailable",- summary: "Couldn't clear the session",- },- ]);- });-- it("cancels an active turn without sending a prompt", async () => {- const session = stubClient().sessions.attach("session_1");- const cancel = vi- .spyOn(session, "cancel")- .mockResolvedValue({ sessionId: "session_1", status: "accepted" });- const send = vi.spyOn(session, "send");- const stream = vi.spyOn(session, "stream").mockReturnValue(- (async function* () {- yield stampTestEvent(- {- data: { continuationToken: "session-id", wait: "next-user-message" },- type: "session.waiting",- },- 0,- );- })(),- );- const results: string[] = [];- const prompts: Array<string | undefined> = ["/cancel", undefined];- const runner = new EveTUIRunner({- name: "Weather Agent",- renderer: fakeRenderer({- readPrompt: vi.fn(async () => prompts.shift()),- finishCommand: (outcome) => {- if (outcome.kind === "result") results.push(outcome.message ?? "");- },- renderStream: vi.fn(async (result) => {- for await (const event of result.events) {- void event;- }- }),- }),- session,- });-- await runner.run();-- expect(cancel).toHaveBeenCalledOnce();- expect(stream).toHaveBeenCalledOnce();- expect(send).not.toHaveBeenCalled();- expect(results).toEqual([""]);- });-- it("does not call the cancel API before a session has started", async () => {- const results: string[] = [];- const prompts: Array<string | undefined> = ["/cancel", undefined];- const runner = new EveTUIRunner({- name: "Weather Agent",- renderer: fakeRenderer({- readPrompt: vi.fn(async () => prompts.shift()),- finishCommand: (outcome) => {- if (outcome.kind === "result") results.push(outcome.message ?? "");- },- }),- });-- await runner.run();-- expect(results).toEqual([""]);- });-- it("keeps the current transcript and session when /reset cannot reset the owner", async () => {- const session = sessionYielding([]);- const reset = vi.spyOn(session, "reset").mockRejectedValue(new Error("World unavailable"));- const resetRenderer = vi.fn();- const outcomes: CommandPresentation[] = [];- const prompts: Array<string | undefined> = ["/reset", undefined];- const runner = new EveTUIRunner({- name: "Weather Agent",- renderer: fakeRenderer({- readPrompt: vi.fn(async () => prompts.shift()),- finishCommand: (outcome) => outcomes.push(outcome),- reset: resetRenderer,- }),- session,- });-- await runner.run();-- expect(reset).toHaveBeenCalledOnce();- expect(resetRenderer).not.toHaveBeenCalled();- expect(outcomes).toEqual([- { kind: "result", message: "Couldn't reset the session: World unavailable" },- ]);- });-- it("resets rather than sending a queued /reset after a turn boundary", async () => {- const initialSession = sessionYielding([{ type: "session.waiting" }]);- const reset = vi- .spyOn(initialSession, "reset")- .mockResolvedValue({ previousSessionId: "session_1", status: "reset" });- const newSession = sessionYielding([]);- const client = stubClient();- const createSession = mockSessionCreation(client, newSession);- const prompts: Array<string | undefined> = ["first", undefined];- const renderer = fakeRenderer({- readPrompt: vi.fn(async () => prompts.shift()),- renderStream: vi.fn(async (result) => {- for await (const event of result.events as AsyncIterable<unknown>) {- void event;- }- }),- takeQueuedPrompt: vi.fn(() => "/reset"),- });- const runner = new EveTUIRunner({- client,- name: "Weather Agent",- renderer,- session: initialSession,- });-- await runner.run();-- expect(reset).toHaveBeenCalledOnce();- expect(createSession).not.toHaveBeenCalled();- expect(initialSession.send).toHaveBeenCalledOnce();- expect(newSession.send).not.toHaveBeenCalled();- });-});--describe("EveTUIRunner terminal-failure recovery", () => {- it("starts a fresh session and posts a notice after session.failed", async () => {- const notices: string[] = [];- const prompts: Array<string | undefined> = ["what else can you do", undefined];-- const failingSession = sessionYielding([- {- type: "session.failed",- data: { code: "HookConflictError", message: "HookConflictError: token in use" },- },- ]);- const recoveredSession = sessionYielding([]);- const client = stubClient();- const sessionFactory = mockSessionCreation(client, recoveredSession);-- const renderer: AgentTUIRenderer = {- readPrompt: vi.fn(async () => prompts.shift()),- renderNotice: (text) => notices.push(text),- renderStream: vi.fn(async (result) => {- // Draining the stream runs the event translator, which fires the- // runner's terminal-failure hook on `session.failed`.- for await (const event of result.events as AsyncIterable<unknown>) {- void event;- }- }),- };-- const runner = new EveTUIRunner({- session: failingSession,- client,- renderer,- name: "Weather Agent",- });-- await runner.run();-- // Exactly one recovery session was created, and the failed session was- // only used for the one (failing) turn.- expect(sessionFactory).not.toHaveBeenCalled();- expect(failingSession.send).toHaveBeenCalledTimes(1);- expect(recoveredSession.send).not.toHaveBeenCalled();- expect(notices).toHaveLength(1);- expect(notices[0]).toContain("new session");- });-- it("preserves the session and posts a notice when the stream ends without a boundary", async () => {- const notices: string[] = [];- const prompts: Array<string | undefined> = ["run something long", undefined];-- const strandedSession = sessionYielding([{ type: "turn.started", data: {} }]);- const client = stubClient();- const sessionFactory = vi.spyOn(client.sessions, "create");-- const runner = new EveTUIRunner({- client,- name: "Weather Agent",- renderer: {- readPrompt: vi.fn(async () => prompts.shift()),- renderNotice: (text) => notices.push(text),- renderStream: vi.fn(async (result) => {- for await (const event of result.events as AsyncIterable<unknown>) {- void event;- }- }),- },- session: strandedSession,- });-- await runner.run();-- expect(sessionFactory).not.toHaveBeenCalled();- expect(notices).toHaveLength(1);- expect(notices[0]).toContain("Lost");- expect(notices[0]).not.toContain("new session");- });-- it("starts a fresh session when the user interrupts a turn mid-stream", async () => {- const notices: string[] = [];- const prompts: Array<string | undefined> = ["run something long", undefined];-- const interruptedSession = sessionYielding([{ type: "turn.started", data: {} }]);- const replacementSession = sessionYielding([]);- const client = stubClient();- const sessionFactory = mockSessionCreation(client, replacementSession);-- const runner = new EveTUIRunner({- client,- name: "Weather Agent",- renderer: {- readPrompt: vi.fn(async () => prompts.shift()),- renderNotice: (text) => notices.push(text),- renderStream: vi.fn(async (result) => {- for await (const event of result.events as AsyncIterable<unknown>) {- void event;- result.abort?.();- break;- }- }),- },- session: interruptedSession,- });-- await runner.run();-- expect(sessionFactory).not.toHaveBeenCalled();- expect(notices).toHaveLength(1);- expect(notices[0]).toContain("new session");- expect(notices[0]).toContain("may still be running");- });-});--describe("EveTUIRunner delayed dev build errors", () => {- it("flushes delayed dev build errors before dispatching a user prompt", async () => {- const calls: string[] = [];- const prompts: Array<string | undefined> = ["hello", undefined];- const session = stubSession();- vi.spyOn(session, "send").mockImplementation(async () => {- calls.push("send");- return messageResponseOf([{ type: "session.waiting" }]);- });- const renderer: AgentTUIRenderer = {- readPrompt: vi.fn(async () => prompts.shift()),- flushDelayedDevBuildErrors: vi.fn(() => {- calls.push("flush");- }),- renderStream: vi.fn(async () => {}),- };-- const runner = new EveTUIRunner({ session, renderer, name: "Weather Agent" });-- await runner.run();-- expect(calls).toEqual(["flush", "send"]);- expect(renderer.flushDelayedDevBuildErrors).toHaveBeenCalledTimes(1);- });-- it("does not flush delayed dev build errors for local slash commands", async () => {- const prompts: Array<string | undefined> = ["/help", undefined];- const renderer: AgentTUIRenderer = {- readPrompt: vi.fn(async () => prompts.shift()),- flushDelayedDevBuildErrors: vi.fn(),- renderNotice: vi.fn(),- renderStream: vi.fn(async () => {}),- };-- const runner = new EveTUIRunner({- session: sessionYielding([{ type: "session.waiting" }]),- renderer,- name: "Weather Agent",- });-- await runner.run();-- expect(renderer.flushDelayedDevBuildErrors).not.toHaveBeenCalled();- });-});--describe("EveTUIRunner /traces", () => {- it("opens the renderer's trace viewer with the app root and optional reference", async () => {- const prompts: Array<string | undefined> = ["/traces abc123", "/traces", undefined];- const open = vi.fn(async () => {});- const renderer: AgentTUIRenderer = {- readPrompt: vi.fn(async () => prompts.shift()),- renderStream: vi.fn(async () => {}),- traceViewer: { open },- };-- const runner = new EveTUIRunner({- session: sessionYielding([{ type: "session.waiting" }]),- renderer,- name: "Weather Agent",- appRoot: "/tmp/weather-agent",- });-- await runner.run();-- expect(open).toHaveBeenCalledTimes(2);- expect(open).toHaveBeenNthCalledWith(1, {- appRoot: "/tmp/weather-agent",- sessionId: "session_test",- reference: "abc123",- });- expect(open).toHaveBeenNthCalledWith(2, {- appRoot: "/tmp/weather-agent",- sessionId: "session_test",- reference: undefined,- });- });-- it("renders a local-only notice when the session has no trace viewer", async () => {- const prompts: Array<string | undefined> = ["/traces", undefined];- const notices: string[] = [];- const renderer: AgentTUIRenderer = {- readPrompt: vi.fn(async () => prompts.shift()),- renderNotice: vi.fn((text: string) => {- notices.push(text);- }),- renderStream: vi.fn(async () => {}),- };-- const runner = new EveTUIRunner({- session: sessionYielding([{ type: "session.waiting" }]),- renderer,- name: "Weather Agent",- });-- await runner.run();-- expect(notices.some((text) => text.includes("/traces is only available"))).toBe(true);- });-});--describe("EveTUIRunner initial input", () => {- it("uses the startup draft captured after the agent info probe", async () => {- const info = createDeferred<typeof AGENT_INFO>();- const client = stubClient();- vi.spyOn(client, "info").mockReturnValue(info.promise);- const startup = {- finish: vi.fn(() => ({ draft: "typed while loading", queuedPrompt: undefined })),- };- const renderer = fakeRenderer();- const runner = new EveTUIRunner({- session: stubSession(),- client,- renderer,- serverUrl: "http://localhost:3000",- startup,- });-- const running = runner.run();- await settleAsyncWork();- expect(startup.finish).not.toHaveBeenCalled();- info.resolve(AGENT_INFO);- await running;-- expect(startup.finish).toHaveBeenCalledOnce();- expect(renderer.readPrompt).toHaveBeenCalledWith(- expect.objectContaining({ initialDraft: "typed while loading" }),- );- });-- it.each(["cancelled", "error"] as const)(- "keeps startup input through login and restores queued messages on %s",- async (result) => {- const login = createDeferred<void>();- const startup = {- finish: vi.fn(() => ({ draft: "still editing", queuedPrompt: "Hello Alice" })),- };- const handle = vi.fn(async () => {- await login.promise;- return result === "cancelled"- ? { cancelled: true as const, message: "Connect a model with /login when you’re ready." }- : { failed: true as const, message: "Could not connect. Retry with /login." };- });- const session = stubSession();- vi.spyOn(session, "send");- const renderer = fakeRenderer({- setupFlow: createFakeSetupFlowRenderer(),- renderCommandInvocation: vi.fn(),- finishCommand: vi.fn(),- });- const runner = new EveTUIRunner({- session,- renderer,- startup,- appRoot: "/tmp/agent",- onboard: true,- bootDetections: [],- promptCommandHandler: { handle },- });- const run = runner.run();- await vi.waitFor(() => expect(handle).toHaveBeenCalledOnce());- expect(startup.finish).not.toHaveBeenCalled();- login.resolve();- await run;- expect(startup.finish).toHaveBeenCalledOnce();- expect(session.send).not.toHaveBeenCalled();- expect(renderer.readPrompt).toHaveBeenCalledWith(- expect.objectContaining({ initialDraft: "Hello Alice\n\nstill editing" }),- );- expect(renderer.renderCommandInvocation).not.toHaveBeenCalled();- expect(renderer.finishCommand).toHaveBeenCalledWith({- kind: "result",- message:- result === "cancelled"- ? "Connect a model with /login when you’re ready."- : "Could not connect. Retry with /login.",- summary: undefined,- });- },- );-- it("sends startup messages queued while the agent builds", async () => {- const client = stubClient();- vi.spyOn(client, "info").mockResolvedValue(AGENT_INFO);- const session = sessionYielding([{ type: "session.waiting" }]);- const startup = {- finish: vi.fn(() => ({- draft: "still editing",- queuedPrompt: "first message\n\nsecond message",- })),- };- const renderer = fakeRenderer();- const runner = new EveTUIRunner({- session,- client,- renderer,- serverUrl: "http://localhost:3000",- startup,- });-- await runner.run();-- expect(session.send).toHaveBeenCalledWith(- "first message\n\nsecond message",- expect.objectContaining({ turnPolicy: "queue" }),- );- expect(renderer.readPrompt).toHaveBeenCalledWith(- expect.objectContaining({ initialDraft: "still editing" }),- );- });-- it("seeds only the first prompt's editable buffer with --input text", async () => {- const seenOptions: Array<AgentTUISessionOptions | undefined> = [];- const prompts: Array<string | undefined> = ["edited and sent", undefined];- const session = sessionYielding([{ type: "session.waiting" }]);-- const renderer: AgentTUIRenderer = {- readPrompt: vi.fn(async (options?: AgentTUISessionOptions) => {- seenOptions.push(options);- return prompts.shift();- }),- renderStream: vi.fn(async (result) => {- for await (const event of result.events as AsyncIterable<unknown>) {- void event;- }- }),- };-- const runner = new EveTUIRunner({- session,- renderer,- name: "Weather Agent",- initialInput: "draft me",- });-- await runner.run();-- expect(seenOptions[0]?.initialDraft).toBe("draft me");- expect(seenOptions[1]?.initialDraft).toBeUndefined();- // The seed is a draft, not an auto-submit: the turn carries the text the- // user actually sent, not the seeded value.- expect(session.send).toHaveBeenCalledTimes(1);- expect(session.send).toHaveBeenNthCalledWith(1, "edited and sent", {- signal: expect.any(AbortSignal),- turnPolicy: "queue",- });- });-});--describe("EveTUIRunner native continuation state", () => {- it.each(["rejected", "failed", "timed-out"])(- "offers a retry after a %s approval attempt",- async (outcome) => {- const prompts: Array<string | undefined> = ["Prepare Alice's task", undefined];- const session = sessionYieldingTurns([- [- {- type: "input.requested",- data: {- requests: [- {- action: { callId: "call-1", input: {}, kind: "tool-call", toolName: "save_note" },- kind: "tool-approval",- requestId: "request-1",- prompt: "Approve Alice's note?",- options: [- { id: "approve", label: "Approve" },- { id: "cancel", label: "Cancel" },- ],- },- ],- },- },- { type: "session.waiting" },- ],- [- { type: "approval.candidate", data: { requestId: "request-1", outcome } },- { type: "session.waiting" },- ],- [- { type: "approval.settled", data: { requestId: "request-1", outcome: "cancelled" } },- {- type: "input.resolved",- data: { resolutions: [{ requestId: "request-1", outcome: "cancelled" }] },- },- { type: "session.waiting" },- ],- ]);- const readToolApproval = vi- .fn()- .mockResolvedValueOnce({ approved: true })- .mockResolvedValueOnce({ approved: false });- const renderer = fakeRenderer({- readPrompt: vi.fn(async () => prompts.shift()),- readToolApproval,- renderStream: vi.fn(async (result) => {- for await (const event of result.events) void event;- }),- });- await new EveTUIRunner({ session, renderer }).run();- expect(readToolApproval).toHaveBeenCalledTimes(2);- expect(session.respond).toHaveBeenNthCalledWith(- 2,- [{ requestId: "request-1", optionId: "cancel" }],- { signal: expect.any(AbortSignal) },- );- },- );-- it("continues an input request from eve-native turn state", async () => {- const prompts: Array<string | undefined> = ["approve this", undefined];- const session = sessionYieldingTurns([- [- {- type: "input.requested",- data: {- requests: [- {- action: {- callId: "call-1",- input: { city: "SF" },- kind: "tool-call",- toolName: "get_weather",- },- display: "confirmation",- kind: "tool-approval",- options: [- { id: "approve", label: "Approve" },- { id: "cancel", label: "Cancel" },- ],- prompt: "Approve get_weather?",- requestId: "request-1",- },- ],- },- },- {- type: "session.waiting",- data: { continuationToken: "session-id", wait: "next-user-message" },- },- ],- [- {- type: "session.waiting",- data: { continuationToken: "session-id", wait: "next-user-message" },- },- ],- ]);- const renderer: AgentTUIRenderer = {- readPrompt: vi.fn(async () => prompts.shift()),- readToolApproval: vi.fn(async () => ({ approved: true })),- renderStream: vi.fn(async (result) => {- for await (const event of result.events as AsyncIterable<unknown>) {- void event;- }- }),- };-- const runner = new EveTUIRunner({- session,- renderer,- name: "Weather Agent",- });-- await runner.run();-- expect(session.send).toHaveBeenCalledTimes(1);- expect(session.send).toHaveBeenNthCalledWith(1, "approve this", {- signal: expect.any(AbortSignal),- turnPolicy: "queue",- });- expect(session.respond).toHaveBeenCalledWith(- [{ requestId: "request-1", optionId: "approve" }],- { signal: expect.any(AbortSignal) },- );- });-- it.each([{ chosenOptionId: "continue" }, { chosenOptionId: "stop" }])(- "renders a session-limit continuation as a question and submits $chosenOptionId",- async ({ chosenOptionId }) => {- const prompts: Array<string | undefined> = ["keep going", undefined];- const session = sessionYieldingTurns([- [- {- type: "input.requested",- data: {- requests: [- {- action: {- callId: "wrun_1:limit:input:19093",- input: { kind: "input", limit: 10_000, usedTokens: 19_093 },- kind: "tool-call",- toolName: "session_limit_continuation",- },- allowFreeform: false,- display: "confirmation",- kind: "session-limit",- options: [- { id: "continue", label: "Approve" },- { id: "stop", label: "Stop" },- ],- prompt: "This session has hit the input-token limit (10K) per session.",- requestId: "wrun_1:limit:input:19093",- },- ],- },- },- {- type: "session.waiting",- data: { continuationToken: "session-id", wait: "next-user-message" },- },- ],- [- {- type: "session.waiting",- data: { continuationToken: "session-id", wait: "next-user-message" },- },- ],- ]);- const readToolApproval = vi.fn(async () => ({ approved: true }));- const readInputQuestion = vi.fn(async () => ({ optionId: chosenOptionId }));- const renderer: AgentTUIRenderer = {- readPrompt: vi.fn(async () => prompts.shift()),- readToolApproval,- readInputQuestion,- renderStream: vi.fn(async (result) => {- for await (const event of result.events as AsyncIterable<unknown>) {- void event;- }- }),- };-- const runner = new EveTUIRunner({- session,- renderer,- name: "Limit Agent",- });-- await runner.run();-- // Renders in the question pane with the prompt copy and labeled- // options — never through the y/n tool-approval flow.- expect(readToolApproval).not.toHaveBeenCalled();- expect(readInputQuestion).toHaveBeenCalledWith(- expect.objectContaining({- display: "select",- prompt: "This session has hit the input-token limit (10K) per session.",- options: [- expect.objectContaining({ id: "continue", label: "Approve" }),- expect.objectContaining({ id: "stop", label: "Stop" }),- ],- }),- expect.anything(),- );- expect(session.respond).toHaveBeenCalledWith(- [{ requestId: "wrun_1:limit:input:19093", optionId: chosenOptionId }],- { signal: expect.any(AbortSignal) },- );- },- );-});--describe("EveTUIRunner connection authorization", () => {- it("continues a parked interactive authorization session until the callback completes", async () => {- const prompts: Array<string | undefined> = ["connect linear", undefined];- const updates: Array<{ name: string; state: string }> = [];- const pendingCounts: number[] = [];- const session = sessionYielding([- {- type: "authorization.required",- data: {- authorization: { url: "https://connect.vercel.com/authorize/linear" },- description: "Authorization required for linear",- name: "linear",- webhookUrl: "https://eve.test/connections/linear/callback",- },- },- { type: "session.waiting", data: { wait: "connection-authorization" } },- ]);- vi.spyOn(session, "stream").mockImplementation(async function* () {- yield stampTestEvent({- type: "authorization.completed",- data: { name: "linear", outcome: "authorized" },- } as UnstampedMessageStreamEvent);- yield stampTestEvent({- type: "session.waiting",- data: { continuationToken: "session-id", wait: "next-user-message" },- } as UnstampedMessageStreamEvent);- });- const renderer: AgentTUIRenderer = {- readPrompt: vi.fn(async () => prompts.shift()),- upsertConnectionAuth: (update) => updates.push({ name: update.name, state: update.state }),- setConnectionAuthPendingCount: (count) => pendingCounts.push(count),- renderStream: vi.fn(async (result) => {- for await (const event of result.events as AsyncIterable<AgentTUIStreamEvent>) {- void event;- }- }),- };-- const runner = new EveTUIRunner({ session, renderer, name: "Weather Agent" });- await runner.run();-- expect(session.stream).toHaveBeenCalledTimes(1);- expect(updates).toEqual([- { name: "linear", state: "required" },- { name: "linear", state: "pending" },- { name: "linear", state: "authorized" },- ]);- expect(pendingCounts).toEqual([1, 0]);- });-});--describe("EveTUIRunner failure rendering", () => {- it("renders one error block for a step/turn/session failure cascade", async () => {- const prompts: Array<string | undefined> = ["hello", undefined];- const emitted: AgentTUIStreamEvent[] = [];- const failureData = {- code: "MODEL_CALL_FAILED",- message: "model call failed terminally",- details: {- errorId: "err-1",- message: "model call failed terminally",- detail: "Error: model call failed terminally\n at turn (harness/tool-loop.ts:1:1)",- },- };- const session = sessionYielding([- { type: "step.failed", data: { ...failureData, sequence: 0, stepIndex: 0, turnId: "t0" } },- { type: "turn.failed", data: { ...failureData, sequence: 0, turnId: "t0" } },- { type: "session.failed", data: { ...failureData, sessionId: "s0" } },- ]);- const client = stubClient();- mockSessionCreation(client, sessionYielding([]));-- const renderer: AgentTUIRenderer = {- readPrompt: vi.fn(async () => prompts.shift()),- renderNotice: vi.fn(),- renderStream: vi.fn(async (result) => {- for await (const event of result.events as AsyncIterable<AgentTUIStreamEvent>) {- emitted.push(event);- }- }),- };-- const runner = new EveTUIRunner({ session, client, renderer, name: "Weather Agent" });- await runner.run();-- const errors = emitted.filter((event) => event.type === "error");- expect(errors).toHaveLength(1);- expect(errors[0]).toMatchObject({- errorText: "MODEL_CALL_FAILED: model call failed terminally",- detail: "Error: model call failed terminally\n at turn (harness/tool-loop.ts:1:1)",- });- });-- it("omits detail when the failure carries only a curated summary", async () => {- const prompts: Array<string | undefined> = ["hello", undefined];- const emitted: AgentTUIStreamEvent[] = [];- const session = sessionYielding([- {- type: "turn.failed",- data: {- code: "MODEL_CALL_FAILED",- message: "MODEL_CALL_FAILED: bad gateway key",- details: { errorId: "err-2", message: "bad gateway key", name: "GatewayError" },- sequence: 0,- turnId: "t0",- },- },- {- type: "session.waiting",- data: { continuationToken: "session-id", wait: "next-user-message" },- },- ]);-- const renderer: AgentTUIRenderer = {- readPrompt: vi.fn(async () => prompts.shift()),- renderStream: vi.fn(async (result) => {- for await (const event of result.events as AsyncIterable<AgentTUIStreamEvent>) {- emitted.push(event);- }- }),- };-- const runner = new EveTUIRunner({ session, renderer, name: "Weather Agent" });- await runner.run();-- const errors = emitted.filter((event) => event.type === "error");- expect(errors).toHaveLength(1);- // The message already carries its own code prefix — no "Code: Code:".- expect(errors[0]).toEqual({- type: "error",- errorText: "MODEL_CALL_FAILED: bad gateway key",- });- });-});--describe("EveTUIRunner reused step indexes", () => {- it("renders a follow-up turn carried by the same steering stream", async () => {- const prompts: Array<string | undefined> = ["start", undefined];- const emitted: AgentTUIStreamEvent[] = [];- const session = sessionYielding([- { type: "turn.started", data: { sequence: 0, turnId: "turn_0" } },- { type: "step.started", data: { sequence: 0, stepIndex: 0, turnId: "turn_0" } },- {- type: "message.completed",- data: {- finishReason: "stop",- message: "First answer.",- sequence: 0,- stepIndex: 0,- turnId: "turn_0",- },- },- { type: "turn.completed", data: { sequence: 0, turnId: "turn_0" } },- { type: "turn.started", data: { sequence: 1, turnId: "turn_1" } },- { type: "step.started", data: { sequence: 1, stepIndex: 0, turnId: "turn_1" } },- {- type: "message.completed",- data: {- finishReason: "stop",- message: "Follow-up answer.",- sequence: 1,- stepIndex: 0,- turnId: "turn_1",- },- },- { type: "turn.completed", data: { sequence: 1, turnId: "turn_1" } },- { type: "session.waiting", data: { wait: "next-user-message" } },- ]);- const renderer: AgentTUIRenderer = {- readPrompt: vi.fn(async () => prompts.shift()),- renderStream: vi.fn(async (result) => {- for await (const event of result.events as AsyncIterable<AgentTUIStreamEvent>) {- emitted.push(event);- }- }),- };-- await new EveTUIRunner({ session, renderer, name: "Weather Agent" }).run();-- expect(- emitted.flatMap((event) =>- event.type === "assistant-complete" && event.text !== undefined ? [event.text] : [],- ),- ).toEqual(["First answer.", "Follow-up answer."]);- expect(emitted.filter((event) => event.type === "turn-start")).toEqual([- { type: "turn-start", turnId: "turn_0" },- { type: "turn-start", turnId: "turn_1" },- ]);- });-- it("renders the post-subagent message that the harness emits under a reused stepIndex", async () => {- // Mirrors the real parent stream around a subagent dispatch: the second- // model call arrives under a fresh `step.started` but the SAME- // `turnId:stepIndex` key as the already-completed first message. It must- // render as its own assistant block, not be dropped as a replay.- const prompts: Array<string | undefined> = ["delegate to the subagent", undefined];- const emitted: AgentTUIStreamEvent[] = [];- const session = sessionYielding([- { type: "step.started", data: { sequence: 0, stepIndex: 0, turnId: "t0" } },- {- type: "message.appended",- data: {- messageDelta: "I'll call the subagent.",- sequence: 0,- stepIndex: 0,- turnId: "t0",- },- },- {- type: "message.completed",- data: {- finishReason: "tool-calls",- message: "I'll call the subagent.",- sequence: 0,- stepIndex: 0,- turnId: "t0",- },- },- { type: "step.completed", data: { sequence: 0, stepIndex: 0, turnId: "t0", usage: {} } },- { type: "step.started", data: { sequence: 0, stepIndex: 0, turnId: "t0" } },- {- type: "message.appended",- data: {- messageDelta: "The subagent returned TOKEN-123.",- sequence: 0,- stepIndex: 0,- turnId: "t0",- },- },- {- type: "message.completed",- data: {- finishReason: "stop",- message: "The subagent returned TOKEN-123.",- sequence: 0,- stepIndex: 0,- turnId: "t0",- },- },- { type: "turn.completed", data: { sequence: 0, turnId: "t0" } },- {- type: "session.waiting",- data: { continuationToken: "session-id", wait: "next-user-message" },- },- ]);-- const renderer: AgentTUIRenderer = {- readPrompt: vi.fn(async () => prompts.shift()),- renderStream: vi.fn(async (result) => {- for await (const event of result.events as AsyncIterable<AgentTUIStreamEvent>) {- emitted.push(event);- }- }),- };-- const runner = new EveTUIRunner({ session, renderer, name: "Weather Agent" });- await runner.run();-- const deltas = emitted.filter((event) => event.type === "assistant-delta");- expect(deltas).toHaveLength(2);- // Distinct block ids — the second message is its own generation/block.- expect(deltas[0]?.id).not.toBe(deltas[1]?.id);- expect(deltas[0]?.delta).toBe("I'll call the subagent.");- expect(deltas[1]?.delta).toBe("The subagent returned TOKEN-123.");- const completes = emitted.filter((event) => event.type === "assistant-complete");- expect(completes).toHaveLength(2);- });-- it("renders the answer a model writes after a provider-executed tool in the same step", async () => {- // One model call: a preamble, a provider-executed web search, then the- // answer, all under the same `turnId:stepIndex` with no new `step.started`.- const prompts: Array<string | undefined> = ["who won the finals", undefined];- const emitted: AgentTUIStreamEvent[] = [];- const part = { sequence: 0, stepIndex: 0, turnId: "t0" };- const session = sessionYielding([- { type: "step.started", data: part },- { type: "message.appended", data: { ...part, messageDelta: "I'll look it up." } },- {- type: "message.completed",- data: { ...part, finishReason: "tool-calls", message: "I'll look it up." },- },- {- type: "actions.requested",- data: {- ...part,- actions: [- {- callId: "search-1",- input: { query: "finals winner" },- kind: "tool-call",- toolName: "web_search",- },- ],- },- },- {- type: "action.result",- data: {- ...part,- result: {- callId: "search-1",- kind: "tool-result",- output: { results: [] },- toolName: "web_search",- },- status: "completed",- },- },- { type: "message.appended", data: { ...part, messageDelta: "The Knicks won." } },- {- type: "message.completed",- data: { ...part, finishReason: "stop", message: "The Knicks won." },- },- { type: "step.completed", data: { ...part, usage: {} } },- { type: "turn.completed", data: { sequence: 0, turnId: "t0" } },- {- type: "session.waiting",- data: { continuationToken: "session-id", wait: "next-user-message" },- },- ]);- const renderer: AgentTUIRenderer = {- readPrompt: vi.fn(async () => prompts.shift()),- renderStream: vi.fn(async (result) => {- for await (const event of result.events as AsyncIterable<AgentTUIStreamEvent>) {- emitted.push(event);- }- }),- };-- await new EveTUIRunner({ session, renderer, name: "Weather Agent" }).run();-- const deltas = emitted.filter((event) => event.type === "assistant-delta");- expect(deltas.map((event) => event.delta)).toEqual(["I'll look it up.", "The Knicks won."]);- expect(deltas[0]?.id).not.toBe(deltas[1]?.id);- expect(emitted.map((event) => event.type)).toEqual(- expect.arrayContaining(["tool-call", "tool-result"]),- );- expect(emitted.findIndex((event) => event.type === "tool-result")).toBeLessThan(- emitted.findIndex((event) => event.type === "assistant-delta" && event.id === deltas[1]?.id),- );- });-});--describe("EveTUIRunner replay guards", () => {- it("renders a re-delivered chunk once even after the next step reuses its key", async () => {- // Coordinates alone cannot tell a re-delivered chunk apart from a fresh- // model call reusing `stepIndex`; only the id can.- const appended = stampTestEvent(- {- type: "message.appended",- data: {- messageDelta: "Sunny.",- sequence: 0,- stepIndex: 0,- turnId: "turn_0",- },- } as UnstampedMessageStreamEvent,- 1,- );- const prompts: Array<string | undefined> = ["weather", undefined];- const emitted: AgentTUIStreamEvent[] = [];- const session = sessionYielding([- { type: "step.started", data: { sequence: 0, stepIndex: 0, turnId: "turn_0" } },- appended,- {- type: "message.completed",- data: {- finishReason: "stop",- message: "Sunny.",- sequence: 0,- stepIndex: 0,- turnId: "turn_0",- },- },- { type: "step.started", data: { sequence: 1, stepIndex: 0, turnId: "turn_0" } },- appended,- {- type: "session.waiting",- data: { continuationToken: "session-id", wait: "next-user-message" },- },- ]);- const renderer: AgentTUIRenderer = {- readPrompt: vi.fn(async () => prompts.shift()),- renderStream: vi.fn(async (result) => {- for await (const event of result.events as AsyncIterable<AgentTUIStreamEvent>) {- emitted.push(event);- }- }),- };-- const runner = new EveTUIRunner({ session, renderer, name: "Weather Agent" });- await runner.run();-- const deltas = emitted.filter((event) => event.type === "assistant-delta");- expect(deltas).toEqual([{ type: "assistant-delta", id: "text:turn_0:0", delta: "Sunny." }]);- });-- it("deduplicates repeated call IDs and replaces retried text with the completed text", async () => {- const prompts: Array<string | undefined> = ["weather", undefined];- const emitted: AgentTUIStreamEvent[] = [];- const session = sessionYielding([- {- type: "actions.requested",- data: {- actions: [- {- callId: "call-original",- input: { city: "New York" },- kind: "tool-call",- toolName: "get_weather",- },- ],- sequence: 0,- stepIndex: 0,- turnId: "turn_0",- },- },- {- type: "actions.requested",- data: {- actions: [- {- callId: "call-original",- input: { city: "New York" },- kind: "tool-call",- toolName: "get_weather",- },- ],- sequence: 0,- stepIndex: 0,- turnId: "turn_0",- },- },- {- type: "action.result",- data: {- result: {- callId: "call-original",- kind: "tool-result",- output: "Sunny in New York",- },- sequence: 0,- status: "completed",- stepIndex: 0,- turnId: "turn_0",- },- },- {- type: "actions.requested",- data: {- actions: [- {- callId: "call-replay",- input: { city: "New York" },- kind: "tool-call",- toolName: "get_weather",- },- ],- sequence: 0,- stepIndex: 0,- turnId: "turn_0",- },- },- {- type: "action.result",- data: {- result: {- callId: "call-replay",- kind: "tool-result",- output: "Sunny in New York",- },- sequence: 0,- status: "completed",- stepIndex: 0,- turnId: "turn_0",- },- },- {- type: "message.appended",- data: {- messageDelta: "Using",- sequence: 0,- stepIndex: 1,- turnId: "turn_0",- },- },- {- type: "message.appended",- data: {- messageDelta: " the first",- sequence: 0,- stepIndex: 1,- turnId: "turn_0",- },- },- {- type: "message.appended",- data: {- messageDelta: " the retry",- sequence: 0,- stepIndex: 1,- turnId: "turn_0",- },- },- {- type: "message.appended",- data: {- messageDelta: " collision",- sequence: 0,- stepIndex: 1,- turnId: "turn_0",- },- },- {- type: "message.completed",- data: {- finishReason: "stop",- message: "Using the first answer.",- sequence: 0,- stepIndex: 1,- turnId: "turn_0",- },- },- {- type: "turn.completed",- data: {- sequence: 0,- turnId: "turn_0",- },- },- {- type: "actions.requested",- data: {- actions: [- {- callId: "call-post-turn",- input: { city: "New York" },- kind: "tool-call",- toolName: "get_weather",- },- ],- sequence: 0,- stepIndex: 0,- turnId: "turn_0",- },- },- {- type: "session.waiting",- data: { continuationToken: "session-id", wait: "next-user-message" },- },- ]);-- const renderer: AgentTUIRenderer = {- readPrompt: vi.fn(async () => prompts.shift()),- renderStream: vi.fn(async (result) => {- for await (const event of result.events as AsyncIterable<AgentTUIStreamEvent>) {- emitted.push(event);- }- }),- };-- const runner = new EveTUIRunner({- session,- renderer,- name: "Weather Agent",- });-- await runner.run();-- const toolCalls = emitted.filter((event) => event.type === "tool-call");- const toolResults = emitted.filter((event) => event.type === "tool-result");- const streamedText = emitted- .filter((event) => event.type === "assistant-delta")- .map((event) => event.delta)- .join("");- const assistantCompletes = emitted.filter((event) => event.type === "assistant-complete");-- expect(toolCalls.map((event) => event.toolCallId)).toEqual(["call-original", "call-replay"]);- expect(toolResults.map((event) => event.toolCallId)).toEqual(["call-original", "call-replay"]);- expect(streamedText).toContain("the retry collision");- expect(assistantCompletes).toEqual([- {- type: "assistant-complete",- id: "text:turn_0:1",- text: "Using the first answer.",- },- ]);- expect(emitted.filter((event) => event.type === "finish")).toHaveLength(1);- });-- it("renders every call in a 100-way bash fan-out with identical input", async () => {- const prompts: Array<string | undefined> = ["run the fan-out", undefined];- const emitted: AgentTUIStreamEvent[] = [];- const sentence = Array.from({ length: 100 }, (_, index) => `word-${index + 1}`).join(" ");- const command = `printf '%s\\n' '${sentence}'`;- const session = sessionYielding([- ...Array.from({ length: 100 }, (_, index) => ({- type: "actions.requested",- data: {- actions: [- {- callId: `bash-${index + 1}`,- input: { command },- kind: "tool-call",- toolName: "bash",- },- ],- sequence: 0,- stepIndex: 0,- turnId: "turn_0",- },- })),- {- type: "session.waiting",- data: { continuationToken: "session-id", wait: "next-user-message" },- },- ]);-- const renderer: AgentTUIRenderer = {- readPrompt: vi.fn(async () => prompts.shift()),- renderStream: vi.fn(async (result) => {- for await (const event of result.events as AsyncIterable<AgentTUIStreamEvent>) {- emitted.push(event);- }- }),- };-- const runner = new EveTUIRunner({ session, renderer, name: "Weather Agent" });- await runner.run();-- const toolCalls = emitted.filter((event) => event.type === "tool-call");- expect(toolCalls).toHaveLength(100);- expect(toolCalls.map((event) => event.toolCallId)).toEqual(- Array.from({ length: 100 }, (_, index) => `bash-${index + 1}`),- );- });-- it("renders a known tool result that arrives after turn.completed", async () => {- const prompts: Array<string | undefined> = ["weather", undefined];- const emitted: AgentTUIStreamEvent[] = [];- const session = sessionYielding([- {- type: "actions.requested",- data: {- actions: [- {- callId: "call-late",- input: { command: "find /workspace -type f | sort" },- kind: "tool-call",- toolName: "bash",- },- ],- sequence: 0,- stepIndex: 0,- turnId: "turn_0",- },- },- {- type: "turn.completed",- data: {- sequence: 0,- turnId: "turn_0",- },- },- {- type: "action.result",- data: {- result: {- callId: "call-late",- kind: "tool-result",- output: { exitCode: 0, stderr: "", stdout: "/workspace/weather-codes.md\n" },- },- sequence: 0,- status: "completed",- stepIndex: 0,- turnId: "turn_0",- },- },- {- type: "session.waiting",- data: { continuationToken: "session-id", wait: "next-user-message" },- },- ]);-- const renderer: AgentTUIRenderer = {- readPrompt: vi.fn(async () => prompts.shift()),- renderStream: vi.fn(async (result) => {- for await (const event of result.events as AsyncIterable<AgentTUIStreamEvent>) {- emitted.push(event);- }- }),- };-- const runner = new EveTUIRunner({- session,- renderer,- name: "Weather Agent",- });-- await runner.run();-- expect(emitted.filter((event) => event.type === "tool-call")).toHaveLength(1);- expect(emitted.filter((event) => event.type === "tool-result")).toEqual([- {- output: { exitCode: 0, stderr: "", stdout: "/workspace/weather-codes.md\n" },- toolCallId: "call-late",- type: "tool-result",- },- ]);- });-- it("preserves a rejected action result instead of rendering it as success", async () => {- const prompts: Array<string | undefined> = ["run the tool", undefined];- const emitted: AgentTUIStreamEvent[] = [];- const session = sessionYielding([- {- type: "actions.requested",- data: {- actions: [- {- callId: "call-rejected",- input: { command: "rm something" },- kind: "tool-call",- toolName: "bash",- },- ],- sequence: 0,- stepIndex: 0,- turnId: "turn_0",- },- },- {- type: "action.result",- data: {- error: { code: "USER_REJECTED", message: "Denied by user." },- result: {- callId: "call-rejected",- kind: "tool-result",- output: null,- },- sequence: 0,- status: "rejected",- stepIndex: 0,- turnId: "turn_0",- },- },- {- type: "session.waiting",- data: { continuationToken: "session-id", wait: "next-user-message" },- },- ]);- const renderer: AgentTUIRenderer = {- readPrompt: vi.fn(async () => prompts.shift()),- renderStream: vi.fn(async (result) => {- for await (const event of result.events as AsyncIterable<AgentTUIStreamEvent>) {- emitted.push(event);- }- }),- };-- await new EveTUIRunner({ session, renderer, name: "Weather Agent" }).run();-- expect(emitted.filter((event) => event.type === "tool-result")).toEqual([]);- expect(emitted.filter((event) => event.type === "tool-rejected")).toEqual([- {- type: "tool-rejected",- toolCallId: "call-rejected",- reason: "Denied by user.",- },- ]);- });-});--describe("EveTUIRunner setup commands", () => {- function recordingRenderer(prompts: Array<string | undefined>) {- const notices: string[] = [];- const renderer: AgentTUIRenderer = {- readPrompt: vi.fn(async () => prompts.shift()),- renderNotice: (text) => notices.push(text),- renderStream: vi.fn(async (result) => {- for await (const event of result.events as AsyncIterable<unknown>) {- void event;- }- }),- };- return { renderer, notices };- }-- it("answers /deploy with an unsupported notice when the renderer cannot suspend", async () => {- const session = sessionYielding([]);- const { renderer, notices } = recordingRenderer(["/deploy", undefined]);-- const runner = new EveTUIRunner({- session,- renderer,- name: "Weather Agent",- appRoot: "/tmp/weather-agent",- promptCommandHandler: createPromptCommandHandler({- target: {- kind: "local",- serverUrl: "http://localhost:3000",- workspaceRoot: "/tmp/weather-agent",- },- }),- });- await runner.run();-- expect(notices).toHaveLength(1);- expect(notices[0]).toContain("not supported by this renderer");- expect(session.send).not.toHaveBeenCalled();+describe("parsePromptCommand", () => {+ it.each([+ ["/reset", { type: "reset" }],+ ["/new", { type: "clear" }],+ ["/exit", { type: "exit" }],+ ["/quit", { type: "exit" }],+ ["/deploy", { type: "extension", name: "deploy", argument: "" }],+ [" /channels ", null],+ ["/vercel", null],+ ["/links", null],+ ["deploy", null],+ ["tell me about /channels", null],+ ] as const)("parses %j as %j", (prompt, expected) => {+ expect(parsePromptCommand(prompt)).toEqual(expected);});});@@ -3296,7 +462,6 @@ describe("EveTUIRunner remote authentication", () => {resolveDeployment?: NonNullable<RemoteConnectionControllerOptions["resolveDeployment"]>;}): Promise<void> {await new EveTUIRunner({- session: input.client.sessions.attach("session_test"),client: input.client,renderer: fakeRenderer({ setupFlow: idleSetupFlow(), ...input.renderer }),serverUrl: target.serverUrl,@@ -3327,14 +492,14 @@ describe("EveTUIRunner remote authentication", () => {completedMutations: [],};});- const commandInvocations: Array<string> = [];+ const commandInvocations: Array<{ text: string; status: "failed" | undefined }> = [];await runRemoteAuth({client,flow,resolveDeployment: async () => ({ kind: "not-found" }),renderer: {- renderCommandInvocation: (text) => commandInvocations.push(text),+ renderCommandInvocation: (text) => commandInvocations.push({ text, status: undefined }),},});@@ -3350,7 +515,7 @@ describe("EveTUIRunner remote authentication", () => {async (challenge) => {const client = stubClient();vi.spyOn(client, "info").mockRejectedValueOnce(challenge).mockResolvedValueOnce(AGENT_INFO);- const commandInvocations: Array<string> = [];+ const commandInvocations: Array<{ text: string; status: "failed" | undefined }> = [];const flow = successfulAuth();const statuses: string[] = [];const renderAgentHeader = vi.fn();@@ -3359,7 +524,7 @@ describe("EveTUIRunner remote authentication", () => {client,flow,renderer: {- renderCommandInvocation: (text) => commandInvocations.push(text),+ renderCommandInvocation: (text) => commandInvocations.push({ text, status: undefined }),setRemoteConnectionStatus: (snapshot) => statuses.push(snapshot.connection.state),renderAgentHeader,},@@ -3392,38 +557,6 @@ describe("EveTUIRunner remote authentication", () => {expect(setupFlow.begin).not.toHaveBeenCalled();});- it("sends the first message after the repaired connection is verified", async () => {- const client = stubClient();- const order: string[] = [];- vi.spyOn(client, "info")- .mockRejectedValueOnce(new ClientError(302, "Redirecting...", { location: VERCEL_SSO_URL }))- .mockImplementationOnce(async () => {- order.push("verified");- return AGENT_INFO;- });- const session = sessionYielding([{ type: "session.waiting" }]);- const renderer = fakeRenderer({- setupFlow: idleSetupFlow(),- readPrompt: vi- .fn()- .mockImplementationOnce(async () => {- order.push("prompt");- return "Hello Alice";- })- .mockResolvedValueOnce(undefined),- });- await new EveTUIRunner({- session,- client,- renderer,- serverUrl: target.serverUrl,- remote: { ...remoteOptions(), runAuthFlow: successfulAuth() },- }).run();- expect(order).toEqual(["verified", "prompt"]);- expect(session.send).toHaveBeenCalledWith("Hello Alice", expect.any(Object));- expect(renderer.renderStream).toHaveBeenCalledOnce();- });-it.each(["cancelled", "failed"] as const)("preserves the draft and closes %s remote setup without retrying",async (kind) => {@@ -3442,18 +575,18 @@ describe("EveTUIRunner remote authentication", () => {},);const setupFlow = idleSetupFlow();- const readPrompt = vi.fn(async () => undefined);+ const readInput = vi.fn(async () => undefined);const finishCommand = vi.fn();await runRemoteAuth({client,flow,initialInput: "Hello Alice",- renderer: { setupFlow, readPrompt, finishCommand },+ renderer: { setupFlow, readInput, finishCommand },});expect(flow).toHaveBeenCalledOnce();expect(client.info).toHaveBeenCalledOnce();expect(setupFlow.end).toHaveBeenCalledWith({ preserveDiagnostics: false });- expect(readPrompt).toHaveBeenCalledWith(+ expect(readInput).toHaveBeenCalledWith(expect.objectContaining({ initialDraft: "Hello Alice" }),);if (kind === "cancelled") expect(finishCommand).not.toHaveBeenCalled();@@ -3461,7 +594,6 @@ describe("EveTUIRunner remote authentication", () => {expect(finishCommand).toHaveBeenCalledWith({kind: "result",message: expect.stringContaining("Check project permissions"),- summary: undefined,});},);@@ -3486,343 +618,47 @@ describe("EveTUIRunner remote authentication", () => {});expect(flow).toHaveBeenCalledOnce();expect(client.info).toHaveBeenCalledTimes(2);- expect(statuses.at(-1)).toBe("auth-failed");- expect(finishCommand).toHaveBeenCalledWith({- kind: "result",- message: expect.stringContaining("updated Trusted Sources for inbound"),- summary: undefined,- });- });-- it("aborts remote setup during an idle wait and waits for cleanup before releasing input", async () => {- const client = stubClient();- vi.spyOn(client, "info").mockRejectedValue(- new ClientError(302, "Redirecting...", { location: VERCEL_SSO_URL }),- );- const interrupt = Promise.withResolvers<"escape" | "ctrl-c">();- let cleanedUp = false;- const flow = vi.fn<RemoteAuthFlow>(async ({ signal }) => {- interrupt.resolve("escape");- await new Promise<void>((resolve) =>- signal!.addEventListener("abort", () => resolve(), { once: true }),- );- cleanedUp = true;- return { kind: "cancelled", completedMutations: [] };- });- const dispose = vi.fn();- const setupFlow = createFakeSetupFlowRenderer({- waitForInterrupt: () => ({ promise: interrupt.promise, dispose }),- end: () => expect(cleanedUp).toBe(true),- });- await runRemoteAuth({ client, flow, renderer: { setupFlow } });- expect(cleanedUp).toBe(true);- expect(dispose).toHaveBeenCalledOnce();- expect(client.info).toHaveBeenCalledOnce();- });-- it("does not start authentication for an ordinary remote HTTP failure", async () => {- const client = stubClient();- vi.spyOn(client, "info").mockRejectedValue(new ClientError(503, "Unavailable"));- const flow = successfulAuth();-- await runRemoteAuth({ client, flow });-- expect(flow).not.toHaveBeenCalled();- });-- it("demotes a ready remote after turn dispatch fails", async () => {- const client = stubClient();- vi.spyOn(client, "info").mockResolvedValue(AGENT_INFO);- const session = client.sessions.attach("session_test");- vi.spyOn(session, "send").mockRejectedValue(new Error("socket down"));- const statuses: string[] = [];- const readPrompt = vi.fn().mockResolvedValueOnce("hello").mockResolvedValueOnce(undefined);-- await new EveTUIRunner({- session,- client,- renderer: fakeRenderer({- readPrompt,- setRemoteConnectionStatus: (snapshot) => statuses.push(snapshot.connection.state),- }),- serverUrl: target.serverUrl,- remote: remoteOptions(),- }).run();-- expect(statuses.at(-1)).toBe("unavailable");- });-- it("keeps a ready remote connected after an agent session failure", async () => {- const client = stubClient();- vi.spyOn(client, "info").mockResolvedValue(AGENT_INFO);- const session = sessionYielding([- {- type: "session.failed",- data: { code: "HookConflictError", message: "HookConflictError: token in use" },- },- ]);- const statuses: string[] = [];- const readPrompt = vi.fn().mockResolvedValueOnce("hello").mockResolvedValueOnce(undefined);-- await new EveTUIRunner({- session,- client,- renderer: fakeRenderer({- readPrompt,- renderStream: vi.fn(async (result) => {- for await (const event of result.events as AsyncIterable<unknown>) void event;- }),- setRemoteConnectionStatus: (snapshot) => statuses.push(snapshot.connection.state),- }),- serverUrl: target.serverUrl,- remote: remoteOptions(),- }).run();-- expect(statuses.at(-1)).toBe("ready");- expect(statuses).not.toContain("unavailable");- });-});--describe("EveTUIRunner renderer teardown", () => {- it("shuts the renderer down when the run loop exits with an error", async () => {- // The terminal renderer's shutdown restores the captured stdout/stderr- // writes; without it a fatal error would be reported into the capture- // and the process would die silently.- const shutdown = vi.fn();- const session = sessionYielding([]);- const renderer = fakeRenderer({- readPrompt: vi.fn(async () => "hello"),- renderStream: vi.fn(async () => {- throw new Error("renderer exploded");- }),- shutdown,- });-- const runner = new EveTUIRunner({ session, renderer, name: "Weather Agent" });-- await expect(runner.run()).rejects.toThrow("renderer exploded");- expect(shutdown).toHaveBeenCalledTimes(1);- });-- it("propagates command-handler errors after restoring the renderer", async () => {- const shutdown = vi.fn();- const renderer = fakeRenderer({- readPrompt: vi.fn(async () => "/model"),- shutdown,- });- const runner = new EveTUIRunner({- session: sessionYielding([]),- renderer,- name: "Weather Agent",- appRoot: "/tmp/weather-agent",- promptCommandHandler: {- handle: async () => {- throw new Error("command implementation failed");- },- },- });-- await expect(runner.run()).rejects.toThrow("command implementation failed");- expect(shutdown).toHaveBeenCalledTimes(1);- });-- it("shuts the renderer down once when /exit ends the run loop", async () => {- const shutdown = vi.fn();- const controller = new AbortController();- const requestStop = vi.fn(() => controller.abort());- const renderer = fakeRenderer({- readPrompt: vi.fn(async () => "/exit"),- shutdown,- });- const runner = new EveTUIRunner({- session: sessionYielding([]),- renderer,- name: "Weather Agent",- lifecycle: {- signal: controller.signal,- stopped: new Promise<NodeJS.Signals | undefined>(() => {}),- requestStop,- dispose: () => {},- },- });-- await runner.run();-- expect(shutdown).toHaveBeenCalledTimes(1);- expect(requestStop).toHaveBeenCalledOnce();- });-- it("follows the child to its own turn boundary, before task.settled", async () => {- const client = stubClient();- vi.stubGlobal(- "fetch",- vi.fn<typeof fetch>().mockResolvedValue(- messageStreamResponseOf([- stampTestEvent(- {- type: "message.completed",- data: {- finishReason: "stop",- message: "final answer",- sequence: 0,- stepIndex: 0,- turnId: "turn-child",- },- } as UnstampedMessageStreamEvent,- 0,- ),- stampTestEvent(- {- type: "session.waiting",- data: { continuationToken: "session-id", wait: "next-user-message" },- } as UnstampedMessageStreamEvent,- 1,- ),- ]),- ),- );-- const upsertStep = vi.fn();- const completed = createDeferred<void>();- const runner = new EveTUIRunner({- client,- name: "Weather Agent",- renderer: fakeRenderer({- // Hold the second prompt open until the child's final message lands- // — exiting the run loop aborts the child pump.- readPrompt: vi- .fn()- .mockResolvedValueOnce("delegate")- .mockImplementationOnce(async () => {- await completed.promise;- return undefined;- }),- renderStream: vi.fn(async (result) => {- for await (const event of result.events as AsyncIterable<unknown>) void event;- }),- subagents: {- begin: vi.fn(),- end: vi.fn(),- upsertStep: (update) => {- upsertStep(update);- if (update.finalized) completed.resolve();- },- upsertTool: vi.fn(),- removeTool: vi.fn(),- markChildToolCallId: vi.fn(),- },- }),- session: sessionYielding([- {- type: "task.started",- data: {- callId: "call-child",- kind: "agent",- name: "weather-child",- taskId: "weather-child-call-child",- turnId: "turn-parent",- },- },- {- type: "agent.started",- data: {- callId: "call-child",- name: "weather-child",- sessionId: "child-session",- streamPath: "/eve/v1/session/child-session/stream",- taskId: "weather-child-call-child",- turnId: "turn-parent",- },- },- // The parent stream never reports task.settled — the child's own- // stream still delivers its final message.- { type: "turn.completed", data: { sequence: 0, turnId: "turn-parent" } },- {- type: "session.waiting",- data: { continuationToken: "session-id", wait: "next-user-message" },- },- ]),+ expect(statuses.at(-1)).toBe("auth-failed");+ expect(finishCommand).toHaveBeenCalledWith({+ kind: "result",+ message: expect.stringContaining("updated Trusted Sources for inbound"),});-- await runner.run();- await completed.promise;-- expect(upsertStep).toHaveBeenCalledWith(- expect.objectContaining({ callId: "call-child", message: "final answer", finalized: true }),- );});- it("aborts child-session streams when Ctrl-C exits the runner", async () => {+ it("aborts remote setup during an idle wait and waits for cleanup before releasing input", async () => {const client = stubClient();- let childSignal: AbortSignal | undefined;- const fetchChild = vi.fn<typeof fetch>(async (_input, init) => {- const signal = init?.signal ?? undefined;- if (signal === undefined) {- throw new Error("Expected the child stream to receive an abort signal.");- }- childSignal = signal;- return new Response(- new ReadableStream<Uint8Array>({- start(controller) {- signal.addEventListener(- "abort",- () => controller.error(new DOMException("Aborted", "AbortError")),- { once: true },- );- },- }),- {- headers: { [EVE_STREAM_VERSION_HEADER]: EVE_MESSAGE_STREAM_VERSION },- },+ vi.spyOn(client, "info").mockRejectedValue(+ new ClientError(302, "Redirecting...", { location: VERCEL_SSO_URL }),+ );+ const interrupt = Promise.withResolvers<"escape" | "ctrl-c">();+ let cleanedUp = false;+ const flow = vi.fn<RemoteAuthFlow>(async ({ signal }) => {+ interrupt.resolve("escape");+ await new Promise<void>((resolve) =>+ signal!.addEventListener("abort", () => resolve(), { once: true }),);+ cleanedUp = true;+ return { kind: "cancelled", completedMutations: [] };});- vi.stubGlobal("fetch", fetchChild);-- const runner = new EveTUIRunner({- client,- name: "Weather Agent",- renderer: fakeRenderer({- readPrompt: vi- .fn()- .mockResolvedValueOnce("delegate")- .mockRejectedValueOnce(interruptedError()),- renderStream: vi.fn(async (result) => {- for await (const event of result.events as AsyncIterable<unknown>) void event;- }),- }),- session: sessionYielding([- {- type: "task.started",- data: {- callId: "call-child",- kind: "agent",- name: "weather-child",- taskId: "weather-child-call-child",- turnId: "turn-parent",- },- },- {- type: "agent.started",- data: {- callId: "call-child",- name: "weather-child",- sessionId: "child-session",- streamPath: "/eve/v1/session/child-session/stream",- taskId: "weather-child-call-child",- turnId: "turn-parent",- },- },- { type: "turn.completed", data: { sequence: 0, turnId: "turn-parent" } },- {- type: "session.waiting",- data: { continuationToken: "session-id", wait: "next-user-message" },- },- ]),+ const dispose = vi.fn();+ const setupFlow = createFakeSetupFlowRenderer({+ waitForInterrupt: () => ({ promise: interrupt.promise, dispose }),+ end: () => expect(cleanedUp).toBe(true),});+ await runRemoteAuth({ client, flow, renderer: { setupFlow } });+ expect(cleanedUp).toBe(true);+ expect(dispose).toHaveBeenCalledOnce();+ expect(client.info).toHaveBeenCalledOnce();+ });- await runner.run();+ it("does not start authentication for an ordinary remote HTTP failure", async () => {+ const client = stubClient();+ vi.spyOn(client, "info").mockRejectedValue(new ClientError(503, "Unavailable"));+ const flow = successfulAuth();++ await runRemoteAuth({ client, flow });- expect(childSignal?.aborted).toBe(true);+ expect(flow).not.toHaveBeenCalled();});});@@ -3836,7 +672,7 @@ describe("EveTUIRunner Vercel status line", () => {const renderer = fakeRenderer({// Hold the prompt open until the async probe lands, so the run loop// cannot exit (and dispose the tracker) before the push arrives.- readPrompt: vi.fn(async () => {+ readInput: submitting(async () => {await firstPush.promise;return undefined;}),@@ -3847,7 +683,7 @@ describe("EveTUIRunner Vercel status line", () => {});const runner = new EveTUIRunner({- session: stubSession(),+ client: stubClient(),renderer,name: "Weather Agent",appRoot: "/tmp/weather-agent",@@ -3874,7 +710,7 @@ describe("EveTUIRunner Vercel status line", () => {const prompts: Array<string | undefined> = ["/deploy"];const renderer = fakeRenderer({renderNotice: vi.fn(),- readPrompt: vi.fn(async () => {+ readInput: submitting(async () => {const next = prompts.shift();if (next !== undefined) return next;await settled.promise;@@ -3890,7 +726,7 @@ describe("EveTUIRunner Vercel status line", () => {};const runner = new EveTUIRunner({- session: stubSession(),+ client: stubClient(),renderer,name: "Weather Agent",appRoot: "/tmp/weather-agent",@@ -3924,7 +760,7 @@ describe("EveTUIRunner Vercel status line", () => {const prompts: Array<string | undefined> = ["/deploy", "/model", undefined];const infoCallsAtPrompt: number[] = [];const renderer = fakeRenderer({- readPrompt: vi.fn(async () => {+ readInput: submitting(async () => {infoCallsAtPrompt.push(info.mock.calls.length);return prompts.shift();}),@@ -3939,7 +775,6 @@ describe("EveTUIRunner Vercel status line", () => {};const runner = new EveTUIRunner({- session: stubSession(),client,renderer,serverUrl: "http://localhost:3000",@@ -3972,7 +807,7 @@ describe("EveTUIRunner Vercel status line", () => {const renderer = fakeRenderer({ setVercelStatus });const runner = new EveTUIRunner({- session: stubSession(),+ client: stubClient(),renderer,name: "Weather Agent",});@@ -3994,58 +829,52 @@ describe("EveTUIRunner gateway-auth failure rendering", () => {},};- async function errorEventsFor(- appRoot?: string,- ): Promise<Array<{ errorText: string; hint?: string }>> {- const prompts: Array<string | undefined> = ["hello", undefined];- const emitted: AgentTUIStreamEvent[] = [];- const session = sessionYielding([- { type: "step.failed", data: { ...gatewayFailure, sequence: 0, stepIndex: 0, turnId: "t0" } },- {- type: "session.waiting",- data: { continuationToken: "session-id", wait: "next-user-message" },- },+ async function failuresFor(appRoot?: string): Promise<readonly AgentTUIFailure[]> {+ const server = new FakeEveServer(({ turnId }) => [+ { type: "step.failed", data: { ...gatewayFailure, sequence: 0, stepIndex: 0, turnId } },+ createSessionWaitingEvent(),]);-+ vi.stubGlobal("fetch", server.fetch);+ const views: AgentTUIConversationView[] = [];+ const failed = createDeferred<void>();const renderer: AgentTUIRenderer = {- readPrompt: vi.fn(async () => prompts.shift()),- renderNotice: vi.fn(),- renderStream: vi.fn(async (result) => {- for await (const event of result.events as AsyncIterable<AgentTUIStreamEvent>) {- emitted.push(event);- }- }),+ readInput: vi+ .fn<NonNullable<AgentTUIRenderer["readInput"]>>()+ .mockResolvedValueOnce({ type: "submit", text: "hello" })+ .mockImplementationOnce(async () => {+ await failed.promise;+ return undefined;+ }),+ renderConversation: (view) => {+ views.push(view);+ if (view.failures.length > 0) failed.resolve();+ },};-const options: ConstructorParameters<typeof EveTUIRunner>[0] = {- session,+ client: stubClient(),renderer,name: "Weather Agent",};if (appRoot !== undefined) options.appRoot = appRoot;- const runner = new EveTUIRunner(options);- await runner.run();-- return emitted- .filter((event) => event.type === "error")- .map((event) => event as { errorText: string; hint?: string });+ await new EveTUIRunner(options).run();+ return views.at(-1)?.failures ?? [];}it("swaps the hint for the local /model fix when setup commands are available", async () => {- const errors = await errorEventsFor("/tmp/weather-agent");- expect(errors).toHaveLength(1);- expect(errors[0]!.errorText).toContain("MODEL_CALL_FAILED");- expect(errors[0]!.hint).toBe(+ const failures = await failuresFor("/tmp/weather-agent");+ expect(failures).toHaveLength(1);+ expect(failures[0]!.message).toContain("MODEL_CALL_FAILED");+ expect(failures[0]!.hint).toBe("Run /model to connect this to a project and refresh AI Gateway credentials, or set AI_GATEWAY_API_KEY manually in .env.local.",);});it("keeps the harness hint when the TUI has no local project to link", async () => {- const errors = await errorEventsFor(undefined);- expect(errors).toHaveLength(1);- expect(errors[0]!.errorText).toContain("MODEL_CALL_FAILED");- expect(errors[0]!.hint).toContain("eve link");- expect(errors[0]!.hint).not.toContain("/model");+ const failures = await failuresFor(undefined);+ expect(failures).toHaveLength(1);+ expect(failures[0]!.message).toContain("MODEL_CALL_FAILED");+ expect(failures[0]!.hint).toContain("eve link");+ expect(failures[0]!.hint).not.toContain("/model");});});@@ -4064,14 +893,12 @@ describe("EveTUIRunner boot setup detection", () => {function bootRunner(input: { appRoot?: string; issues: SetupIssue[] }) {const warnings: string[] = [];- const session = sessionYielding([]);const renderer: AgentTUIRenderer = {- readPrompt: vi.fn(async () => undefined),+ readInput: submitting(async () => undefined),renderSetupWarning: (text) => warnings.push(text),- renderStream: vi.fn(async () => {}),};const options: ConstructorParameters<typeof EveTUIRunner>[0] = {- session,+ client: stubClient(),renderer,name: "Weather Agent",bootDetections: [{ id: "test", detect: () => input.issues }],@@ -4095,7 +922,6 @@ describe("EveTUIRunner boot setup detection", () => {...input.renderer,});const runner = new EveTUIRunner({- session: stubSession(),client,renderer,serverUrl: "http://localhost:3000",@@ -4135,354 +961,865 @@ describe("EveTUIRunner boot setup detection", () => {},});- return { client, runner };- }+ return { client, runner };+ }++ it("surfaces detected issues as the attention line at boot", async () => {+ const { runner, warnings } = bootRunner({+ appRoot: "/tmp/weather-agent",+ issues: [{ kind: "attention", label: "AI Gateway credentials", command: "/model" }],+ });+ await runner.run();++ expect(warnings).toEqual(["1 setup issue: AI Gateway credentials · /model"]);+ });++ it("clears a startup warning when a later agent-info probe reports connected OAuth", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn(async () => Response.json({ revision: "snapshot-a" })),+ );+ const connectedGatewayInfo: AgentInfoResult = {+ ...AGENT_INFO,+ agent: {+ ...AGENT_INFO.agent,+ model: {+ id: "gpt-5",+ routing: { kind: "gateway", target: "openai" },+ endpoint: {+ kind: "gateway",+ connected: true,+ credential: "oauth",+ team: "alice",+ },+ },+ },+ };+ const client = stubClient();+ vi.spyOn(client, "info")+ .mockRejectedValueOnce(new Error("server not ready"))+ .mockResolvedValue(connectedGatewayInfo);+ const warningCleared = createDeferred<void>();+ const renderSetupWarning = vi.fn();+ const clearSetupWarning = vi.fn(() => warningCleared.resolve());+ const detect = vi.fn(({ info }: BootDetectionContext) =>+ info === undefined+ ? [{ kind: "attention" as const, label: "connect a model", command: "/login" }]+ : [],+ );+ const runner = new EveTUIRunner({+ client,+ renderer: fakeRenderer({+ renderSetupWarning,+ clearSetupWarning,+ readInput: submitting(async () => {+ await warningCleared.promise;+ return undefined;+ }),+ }),+ serverUrl: "http://localhost:3000",+ name: "Weather Agent",+ appRoot: "/tmp/weather-agent",+ bootDetections: [{ id: "test", detect }],+ detectProjectIdentity: vi.fn(async () => undefined),+ });++ await runner.run();++ expect(renderSetupWarning).toHaveBeenCalledWith("1 setup issue: connect a model · /login");+ expect(clearSetupWarning).toHaveBeenCalled();+ expect(client.info).toHaveBeenCalledTimes(2);+ expect(detect.mock.calls.at(-1)?.[0].info).toBe(connectedGatewayInfo);+ });++ it("releases the composer while /info is still pending and ignores its result after exit", async () => {+ const refreshed = createDeferred<AgentInfoResult>();+ const renderAgentHeader = vi.fn();+ const finishCommand = vi.fn();+ const renderSetupWarning = vi.fn();+ const readInput = vi.fn(async () => undefined);+ const setStartupPhase = vi.fn();+ const { client, runner } = providerSetupRefreshRunner({+ refreshInfo: () => refreshed.promise,+ bootDetections: [],+ renderer: {+ renderAgentHeader,+ finishCommand,+ renderSetupWarning,+ readInput,+ setStartupPhase,+ },+ });+ const run = runner.run();+ await vi.waitFor(() => expect(readInput).toHaveBeenCalledOnce());+ expect(client.info).toHaveBeenCalledTimes(2);+ expect(finishCommand).not.toHaveBeenCalled();+ expect(renderSetupWarning).not.toHaveBeenCalled();+ expect(setStartupPhase).toHaveBeenLastCalledWith(undefined);+ await run;+ const paints = renderAgentHeader.mock.calls.length;+ refreshed.resolve(AGENT_INFO);+ await Promise.resolve();+ expect(renderAgentHeader).toHaveBeenCalledTimes(paints);+ });++ it("releases the composer without waiting on unrelated setup diagnostics", async () => {+ const diagnostics = createDeferred<Awaited<ReturnType<BootDetection["detect"]>>>();+ const detect = vi.fn(() => diagnostics.promise);+ const readInput = vi.fn(async () => undefined);+ const { runner } = providerSetupRefreshRunner({+ refreshInfo: async () => AGENT_INFO,+ bootDetections: [{ id: "slow", detect }],+ renderer: { readInput },+ });+ const run = runner.run();+ try {+ await vi.waitFor(() => expect(readInput).toHaveBeenCalledOnce());+ expect(detect).toHaveBeenCalledOnce();+ } finally {+ diagnostics.resolve([]);+ await run;+ }+ });++ it("normalizes a committed local key after automatic provider setup", async () => {+ const clearSetupWarning = vi.fn();+ const headers: AgentTUIAgentHeader[] = [];+ const detect = vi.fn(({ info }: { info?: AgentInfoResult }) =>+ info?.agent.model.endpoint?.kind === "gateway" && !info.agent.model.endpoint.connected+ ? [+ {+ kind: "attention" as const,+ label: "model provider not linked",+ command: "/model" as const,+ },+ ]+ : [],+ );+ const { client, runner } = providerSetupRefreshRunner({+ refreshInfo: async () => {+ vi.stubEnv("AI_GATEWAY_API_KEY", "test-key");+ return disconnectedGatewayInfo;+ },+ bootDetections: [{ id: "test", detect }],+ renderer: {+ clearSetupWarning,+ renderAgentHeader: (header) => headers.push(header),+ },+ });++ await runner.run();+ await vi.waitFor(() => expect(clearSetupWarning).toHaveBeenCalled());++ expect(client.info).toHaveBeenCalledTimes(2);+ expect(detect.mock.calls.at(-1)?.[0].info?.agent.model.endpoint).toEqual({+ kind: "gateway",+ connected: true,+ credential: "api-key",+ });+ expect(headers.map((header) => header.info?.agent.model.endpoint)).toEqual([+ { kind: "gateway", connected: true, credential: "api-key" },+ ]);+ });++ it("drops stale disconnected evidence when the post-setup info refresh fails", async () => {+ const clearSetupWarning = vi.fn();+ const finishCommand = vi.fn();+ const headers: AgentTUIAgentHeader[] = [];+ const detect = vi.fn(({ info }: { info?: AgentInfoResult }) =>+ info?.agent.model.endpoint?.kind === "gateway" && !info.agent.model.endpoint.connected+ ? [+ {+ kind: "attention" as const,+ label: "model provider not linked",+ command: "/model" as const,+ },+ ]+ : [],+ );+ const { client, runner } = providerSetupRefreshRunner({+ refreshInfo: async () => {+ throw new Error("info unavailable");+ },+ bootDetections: [{ id: "test", detect }],+ renderer: {+ clearSetupWarning,+ finishCommand,+ renderAgentHeader: (header) => headers.push(header),+ },+ });++ await runner.run();+ await vi.waitFor(() => expect(clearSetupWarning).toHaveBeenCalled());++ expect(finishCommand).not.toHaveBeenCalled();+ expect(client.info).toHaveBeenCalledTimes(2);+ expect(detect).not.toHaveBeenCalled();+ expect(headers.at(-1)?.info?.agent.model.endpoint).toMatchObject({+ kind: "gateway",+ connected: true,+ });+ });++ it("stays quiet without a local setup context, even with issues", async () => {+ const { runner, warnings } = bootRunner({+ issues: [{ kind: "attention", label: "AI Gateway credentials", command: "/model" }],+ });+ await runner.run();- it("surfaces detected issues as the attention line at boot", async () => {+ expect(warnings).toEqual([]);+ });++ it("stays quiet when detection finds nothing", async () => {const { runner, warnings } = bootRunner({appRoot: "/tmp/weather-agent",- issues: [{ kind: "attention", label: "AI Gateway credentials", command: "/model" }],+ issues: [],});await runner.run();- expect(warnings).toEqual(["1 setup issue: AI Gateway credentials · /model"]);+ expect(warnings).toEqual([]);});+});- it("clears a startup warning when a later agent-info probe reports connected OAuth", async () => {- vi.stubGlobal(- "fetch",- vi.fn(async () => Response.json({ revision: "snapshot-a" })),- );- const connectedGatewayInfo: AgentInfoResult = {- ...AGENT_INFO,- agent: {- ...AGENT_INFO.agent,- model: {- id: "gpt-5",- routing: { kind: "gateway", target: "openai" },- endpoint: {- kind: "gateway",- connected: true,- credential: "oauth",- team: "alice",- },- },- },- };+describe("EveTUIRunner command shutdown", () => {+ it("unwinds a blocked prompt", async () => {const client = stubClient();- vi.spyOn(client, "info")- .mockRejectedValueOnce(new Error("server not ready"))- .mockResolvedValue(connectedGatewayInfo);- const warningCleared = createDeferred<void>();- const renderSetupWarning = vi.fn();- const clearSetupWarning = vi.fn(() => warningCleared.resolve());- const detect = vi.fn(({ info }: BootDetectionContext) =>- info === undefined- ? [{ kind: "attention" as const, label: "connect a model", command: "/login" }]- : [],- );+ vi.spyOn(client, "info").mockResolvedValue(AGENT_INFO);+ const prompt = createDeferred<AgentTUIInput | undefined>();+ const controller = new AbortController();+ const renderer: AgentTUIRenderer = {+ readInput: vi.fn(() => prompt.promise),+ renderAgentHeader: vi.fn(),+ requestInterrupt: vi.fn(() => prompt.reject(interruptedError())),+ };const runner = new EveTUIRunner({- session: stubSession(),client,- renderer: fakeRenderer({- renderSetupWarning,- clearSetupWarning,- readPrompt: vi.fn(async () => {- await warningCleared.promise;- return undefined;- }),- }),- serverUrl: "http://localhost:3000",- name: "Weather Agent",- appRoot: "/tmp/weather-agent",- bootDetections: [{ id: "test", detect }],- detectProjectIdentity: vi.fn(async () => undefined),+ renderer,+ lifecycle: {+ signal: controller.signal,+ stopped: new Promise<NodeJS.Signals | undefined>(() => {}),+ requestStop: () => controller.abort(),+ dispose: () => {},+ },});- await runner.run();+ const run = runner.run();+ await settleAsyncWork();+ controller.abort();- expect(renderSetupWarning).toHaveBeenCalledWith("1 setup issue: connect a model · /login");- expect(clearSetupWarning).toHaveBeenCalled();- expect(client.info).toHaveBeenCalledTimes(2);- expect(detect.mock.calls.at(-1)?.[0].info).toBe(connectedGatewayInfo);+ await expect(run).resolves.toBeUndefined();+ expect(renderer.requestInterrupt).toHaveBeenCalledOnce();});+});- it("does not auto-open /model outside the prefilled onboarding launch", async () => {- const handle = vi.fn(async () => ({ message: "/model dismissed." }));- const runner = new EveTUIRunner({- session: sessionYielding([]),- renderer: fakeRenderer({ setupFlow: createFakeSetupFlowRenderer() }),- name: "Weather Agent",- appRoot: "/tmp/weather-agent",- bootDetections: [- {- id: "test",- detect: () => [- {- kind: "attention",- label: "model provider not linked",- command: "/model",- },+/** Serves session routes from an in-memory eve; other routes use `fallback`. */+function serve(respond?: FakeEveTurn, fallback?: typeof fetch): FakeEveServer {+ const server = new FakeEveServer(respond, fallback);+ vi.stubGlobal("fetch", server.fetch);+ return server;+}++/**+ * A composer that submits each text once the previous turn settles, then+ * leaves. It closes when the runner needs the keyboard for something else.+ */+function turnTaking(texts: Array<string | undefined>, overrides: Partial<AgentTUIRenderer> = {}) {+ const views: AgentTUIConversationView[] = [];+ const renderer: AgentTUIRenderer = {+ renderConversation: (view) => views.push(view),+ readInput: vi.fn(async (options?: AgentTUISessionOptions) => {+ const closed = new Promise<"closed">((resolve) =>+ options?.signal?.addEventListener("abort", () => resolve("closed"), { once: true }),+ );+ const idle = vi+ .waitFor(() => {+ if (views.at(-1)?.working === true) throw new Error("A turn is still running.");+ })+ .then(() => "idle" as const);+ if ((await Promise.race([closed, idle])) === "closed") return undefined;+ const text = texts.shift();+ return text === undefined ? undefined : ({ type: "submit", text } as const);+ }),+ ...overrides,+ };+ return { renderer, views };+}++function registryResult(callId: string, address: string, toolName = "selfmod__registry_add") {+ return [+ createActionsRequestedEvent({+ actions: [{ callId, input: { address }, kind: "tool-call", toolName }],+ sequence: 1,+ stepIndex: 0,+ turnId: "turn_1",+ }),+ createActionResultEvent({+ result: {+ callId,+ kind: "tool-result",+ output: { status: "needs-terminal", address },+ toolName,+ },+ sequence: 2,+ stepIndex: 0,+ turnId: "turn_1",+ }),+ ];+}++describe("EveTUIRunner registry handoffs", () => {+ const localOptions = {+ name: "Weather Agent",+ appRoot: "/tmp/weather-agent",+ bootDetections: [],+ detectProjectIdentity: vi.fn(async () => undefined),+ };++ it("opens every distinct registry handoff in result order", async () => {+ serve(({ turnId }) => [+ createTurnStartedEvent({ sequence: 0, turnId }),+ ...registryResult("slack-add", "channel/slack"),+ ...registryResult("linear-add", "connection/linear"),+ createSessionWaitingEvent(),+ ]);+ const handle = vi.fn(async (_command: { name: string; argument: string }) => ({+ message: "done",+ }));+ await new EveTUIRunner({+ ...localOptions,+ client: stubClient(),+ renderer: turnTaking(["Add integrations.", undefined]).renderer,+ promptCommandHandler: { handle },+ }).run();++ expect(handle.mock.calls.map(([command]) => command)).toEqual([+ { type: "extension", name: "add", argument: "channel/slack" },+ { type: "extension", name: "add", argument: "connection/linear" },+ ]);+ });++ it("answers an approval before opening setup queued by the same turn", async () => {+ const order: string[] = [];+ const server = serve(({ body, turnId }) =>+ body?.inputResponses !== undefined+ ? (order.push("respond"), [createSessionWaitingEvent()])+ : [+ createTurnStartedEvent({ sequence: 0, turnId }),+ ...registryResult("registry-add", "channel/slack"),+ createInputRequestedEvent({+ requests: [+ {+ action: {+ callId: "write-file",+ input: { path: "agent.ts" },+ kind: "tool-call",+ toolName: "write_file",+ },+ kind: "tool-approval",+ prompt: "Approve write_file",+ requestId: "approval-1",+ },+ ],+ sequence: 3,+ stepIndex: 0,+ turnId,+ }),+ createSessionWaitingEvent(),],+ );+ await new EveTUIRunner({+ ...localOptions,+ client: stubClient(),+ renderer: turnTaking(["Add Slack.", undefined], {+ readToolApproval: vi.fn(async () => ({ approved: true })),+ }).renderer,+ promptCommandHandler: {+ handle: async () => {+ order.push("setup");+ return { message: "done" };},- ],- promptCommandHandler: { handle },+ },+ }).run();++ expect(order).toEqual(["respond", "setup"]);+ expect(server.requestsTo("POST", "/session_1")[0]?.body).toMatchObject({+ inputResponses: [{ requestId: "approval-1", optionId: "approve" }],});+ });- await runner.run();+ it("opens a registry handoff that a subagent reports on its own stream", async () => {+ const server = serve(({ turnId }) => [+ createTurnStartedEvent({ sequence: 0, turnId }),+ createTaskStartedEvent({+ callId: "selfmod-call",+ kind: "agent",+ name: "self-modification__agent",+ taskId: "task_1",+ turnId,+ }),+ createAgentStartedEvent({+ callId: "selfmod-call",+ name: "self-modification__agent",+ parentSessionId: "session_1",+ sessionId: "child_1",+ taskId: "task_1",+ turnId,+ }),+ ]);+ const handle = vi.fn(async () => ({ message: "Slack setup completed." }));+ const run = new EveTUIRunner({+ ...localOptions,+ client: stubClient(),+ renderer: turnTaking(["Add Slack.", undefined]).renderer,+ promptCommandHandler: { handle },+ }).run();+ await vi.waitFor(() => expect(server.requestsTo("GET", "/child_1/stream")).toHaveLength(1));+ server.emit(+ [+ createTurnStartedEvent({ sequence: 0, turnId: "child_turn" }),+ ...registryResult("registry-add", "channel/slack", "registry_add"),+ createSessionWaitingEvent(),+ ],+ undefined,+ "child_1",+ );+ server.emit(+ [+ createTaskSettledEvent({+ callId: "selfmod-call",+ output: "Registry item added.",+ status: "completed",+ taskId: "task_1",+ turnId: "turn_1",+ }),+ createSessionWaitingEvent(),+ ],+ "delivery_1",+ "session_1",+ );+ await run;- expect(handle).not.toHaveBeenCalled();+ expect(handle).toHaveBeenCalledWith(+ { type: "extension", name: "add", argument: "channel/slack" },+ expect.objectContaining({ title: "Add to your agent" }),+ );});+});- it("keeps a prefilled /model editable without a local app root", async () => {- const handle = vi.fn(async () => ({ message: "/model dismissed." }));- const readPrompt = vi.fn(async (options?: AgentTUISessionOptions) => {- expect(options?.initialDraft).toBe("/model");- return undefined;- });- const runner = new EveTUIRunner({- session: sessionYielding([]),- renderer: fakeRenderer({ readPrompt, setupFlow: createFakeSetupFlowRenderer() }),- name: "Weather Agent",- initialInput: "/model",- promptCommandHandler: { handle },- });+describe("EveTUIRunner session commands", () => {+ function results() {+ const outcomes: string[] = [];+ return {+ outcomes,+ finishCommand: (outcome: Parameters<NonNullable<AgentTUIRenderer["finishCommand"]>>[0]) => {+ outcomes.push(+ outcome.kind === "result" ? (outcome.summary ?? outcome.message ?? "") : "dismissed",+ );+ },+ };+ }- await runner.run();+ it("compacts and clears the active session without sending a message", async () => {+ const server = serve();+ const { outcomes, finishCommand } = results();+ await new EveTUIRunner({+ client: stubClient(),+ renderer: turnTaking(["Hello.", "/compact", "/clear", undefined], { finishCommand }).renderer,+ }).run();- expect(handle).not.toHaveBeenCalled();+ expect(outcomes).toEqual(["Compaction requested", "dismissed"]);+ expect(server.requestsTo("POST", "/session_1/compact")).toHaveLength(1);+ expect(server.requestsTo("POST", "/session_1/clear")).toHaveLength(1);+ expect(server.requestsTo("POST", "/session_1")).toHaveLength(0);});- it("releases the composer while /info is still pending and ignores its result after exit", async () => {- const refreshed = createDeferred<AgentInfoResult>();- const renderAgentHeader = vi.fn();- const finishCommand = vi.fn();- const renderSetupWarning = vi.fn();- const readPrompt = vi.fn(async () => undefined);- const setStartupPhase = vi.fn();- const { client, runner } = providerSetupRefreshRunner({- refreshInfo: () => refreshed.promise,- bootDetections: [],- renderer: {- renderAgentHeader,- finishCommand,- renderSetupWarning,- readPrompt,- setStartupPhase,- },- });- const run = runner.run();- await vi.waitFor(() => expect(readPrompt).toHaveBeenCalledOnce());- expect(client.info).toHaveBeenCalledTimes(2);- expect(finishCommand).not.toHaveBeenCalled();- expect(renderSetupWarning).not.toHaveBeenCalled();- expect(setStartupPhase).toHaveBeenLastCalledWith(undefined);- await run;- const paints = renderAgentHeader.mock.calls.length;- refreshed.resolve(AGENT_INFO);- await Promise.resolve();- expect(renderAgentHeader).toHaveBeenCalledTimes(paints);+ it("keeps the conversation when /reset cannot retire the session", async () => {+ const server = new FakeEveServer();+ vi.stubGlobal("fetch", async (input: string | URL | Request, init?: RequestInit) =>+ String(input).endsWith("/reset")+ ? new Response("unavailable", { status: 503 })+ : await server.fetch(input, init),+ );+ const { outcomes, finishCommand } = results();+ const reset = vi.fn();+ await new EveTUIRunner({+ client: stubClient(),+ renderer: turnTaking(["Hello.", "/reset", "Still here?", undefined], { finishCommand, reset })+ .renderer,+ }).run();++ expect(reset).not.toHaveBeenCalled();+ expect(outcomes[0]).toContain("Couldn't reset the session");+ expect(server.requestsTo("POST", "/session_1")).toHaveLength(1);});- it("sends the first message while post-login info is pending", async () => {- const refreshed = createDeferred<AgentInfoResult>();- const client = stubClient();- vi.spyOn(client, "info")- .mockResolvedValueOnce(disconnectedGatewayInfo)- .mockImplementation(() => refreshed.promise);- vi.stubGlobal(- "fetch",- vi.fn(async () => Response.json({ revision: "snapshot-a" })),+ it("keeps the last session id for the parting line across /reset", async () => {+ serve();+ const reported: string[] = [];+ await new EveTUIRunner({+ client: stubClient(),+ renderer: turnTaking(["Hello.", "/reset", undefined], {+ setSessionId: (sessionId) => reported.push(sessionId),+ }).renderer,+ }).run();++ expect(new Set(reported)).toEqual(new Set(["session_1"]));+ });++ it("keeps the session across an HMR runtime revision", async () => {+ const revisions = ["revision-a", "revision-a", "revision-b", "revision-b"];+ const server = serve(undefined, async () =>+ Response.json({ revision: revisions.shift() ?? "revision-b" }),);- const session = sessionYielding([]);- const prompts = ["Hello", undefined];- const runner = new EveTUIRunner({+ const client = stubClient();+ vi.spyOn(client, "info").mockResolvedValue(AGENT_INFO);+ await new EveTUIRunner({client,- session,- name: "Weather Agent",+ renderer: turnTaking(["First.", "Second.", undefined]).renderer,serverUrl: "http://localhost:3000",+ }).run();++ expect(+ server.requests.filter((request) => request.method === "POST").map((request) => request.path),+ ).toEqual(["/eve/v1/session", "/eve/v1/session/session_1"]);+ });++ it("flushes delayed dev build errors before sending a message, not for slash commands", async () => {+ const calls: string[] = [];+ const server = new FakeEveServer();+ vi.stubGlobal("fetch", async (input: string | URL | Request, init?: RequestInit) => {+ if (init?.method === "POST") calls.push("send");+ return await server.fetch(input, init);+ });+ await new EveTUIRunner({+ client: stubClient(),+ renderer: turnTaking(["/help", "Hello.", undefined], {+ renderNotice: vi.fn(),+ flushDelayedDevBuildErrors: () => calls.push("flush"),+ }).renderer,+ }).run();++ expect(calls).toEqual(["flush", "send"]);+ });++ it("opens the trace viewer for the current session", async () => {+ serve();+ const open = vi.fn(async () => {});+ await new EveTUIRunner({+ client: stubClient(),appRoot: "/tmp/weather-agent",- onboard: true,bootDetections: [],detectProjectIdentity: vi.fn(async () => undefined),- renderer: fakeRenderer({- readPrompt: vi.fn(async () => prompts.shift()),- setupFlow: createFakeSetupFlowRenderer(),- }),- promptCommandHandler: {- handle: async () => ({- message: "Connected.",- effect: {- kind: "model-access-changed",- reload: false,- model: {- id: "gpt-5",- routing: { kind: "gateway", target: "openai" },- endpoint: { kind: "gateway", connected: true, credential: "oauth", team: "alice" },- },- },- }),- },+ renderer: turnTaking(["Hello.", "/traces abc123", undefined], { traceViewer: { open } })+ .renderer,+ }).run();++ expect(open).toHaveBeenCalledWith({+ appRoot: "/tmp/weather-agent",+ sessionId: "session_1",+ reference: "abc123",});- const run = runner.run();- try {- await vi.waitFor(() => expect(session.send).toHaveBeenCalled());- } finally {- refreshed.resolve(AGENT_INFO);- await run;- }});+});- it("releases the composer without waiting on unrelated setup diagnostics", async () => {- const diagnostics = createDeferred<Awaited<ReturnType<BootDetection["detect"]>>>();- const detect = vi.fn(() => diagnostics.promise);- const readPrompt = vi.fn(async () => undefined);- const { runner } = providerSetupRefreshRunner({- refreshInfo: async () => AGENT_INFO,- bootDetections: [{ id: "slow", detect }],- renderer: { readPrompt },+describe("EveTUIRunner requests", () => {+ it("submits the chosen session-limit continuation", async () => {+ const server = serve(({ body, turnId }) =>+ body?.inputResponses !== undefined+ ? [createSessionWaitingEvent()]+ : [+ createTurnStartedEvent({ sequence: 0, turnId }),+ createInputRequestedEvent({+ requests: [+ {+ action: {+ callId: "limit",+ input: {},+ kind: "tool-call",+ toolName: "eve:session-limit",+ },+ kind: "session-limit",+ options: [+ { id: "continue", label: "Continue" },+ { id: "stop", label: "Stop" },+ ],+ prompt: "Alice's session reached its step limit. Continue?",+ requestId: "limit-1",+ },+ ],+ sequence: 1,+ stepIndex: 0,+ turnId,+ }),+ createSessionWaitingEvent(),+ ],+ );+ const readInputQuestion = vi.fn(async () => ({ optionId: "continue" }));+ await new EveTUIRunner({+ client: stubClient(),+ renderer: turnTaking(["Keep going.", undefined], { readInputQuestion }).renderer,+ }).run();++ expect(readInputQuestion).toHaveBeenCalledWith(+ expect.objectContaining({ requestId: "limit-1", display: "select" }),+ expect.any(Object),+ );+ expect(server.requestsTo("POST", "/session_1")[0]?.body).toMatchObject({+ inputResponses: [{ requestId: "limit-1", optionId: "continue" }],});- const run = runner.run();- try {- await vi.waitFor(() => expect(readPrompt).toHaveBeenCalledOnce());- expect(detect).toHaveBeenCalledOnce();- } finally {- diagnostics.resolve([]);- await run;- }});- it("normalizes a committed local key after automatic provider setup", async () => {- const clearSetupWarning = vi.fn();- const headers: AgentTUIAgentHeader[] = [];- const detect = vi.fn(({ info }: { info?: AgentInfoResult }) =>- info?.agent.model.endpoint?.kind === "gateway" && !info.agent.model.endpoint.connected- ? [- {- kind: "attention" as const,- label: "model provider not linked",- command: "/model" as const,- },- ]- : [],- );- const { client, runner } = providerSetupRefreshRunner({- refreshInfo: async () => {- vi.stubEnv("AI_GATEWAY_API_KEY", "test-key");- return disconnectedGatewayInfo;- },- bootDetections: [{ id: "test", detect }],- renderer: {- clearSetupWarning,- renderAgentHeader: (header) => headers.push(header),+ it("leaves a skipped question open without asking it again", async () => {+ const server = serve(({ turnId }) => [+ createTurnStartedEvent({ sequence: 0, turnId }),+ createInputRequestedEvent({+ requests: [+ {+ action: { callId: "ask", input: {}, kind: "tool-call", toolName: "ask_question" },+ kind: "question",+ prompt: "Which of Bob's reports?",+ requestId: "question-1",+ },+ ],+ sequence: 1,+ stepIndex: 0,+ turnId,+ }),+ createSessionWaitingEvent(),+ ]);+ const readInputQuestion = vi.fn(async () => undefined);+ const readInput = vi.fn().mockResolvedValueOnce({ type: "submit", text: "Summarize." });+ const { renderer } = turnTaking([undefined], { readInputQuestion });+ const scripted = renderer.readInput!;+ renderer.readInput = (options) =>+ readInput.mock.calls.length === 0 ? readInput(options) : scripted(options);+ await new EveTUIRunner({ client: stubClient(), renderer }).run();++ expect(readInputQuestion).toHaveBeenCalledOnce();+ expect(server.requestsTo("POST", "/session_1")).toHaveLength(0);+ });+});++describe("EveTUIRunner startup input", () => {+ it.each(["cancelled", "error"] as const)(+ "keeps startup input through login and restores queued messages on %s",+ async (result) => {+ const server = serve();+ const login = createDeferred<void>();+ const startup = {+ finish: vi.fn(() => ({ draft: "still editing", queuedPrompt: "Hello Alice" })),+ };+ const handle = vi.fn(async () => {+ await login.promise;+ return result === "cancelled"+ ? { cancelled: true as const, message: "Connect a model with /login when you’re ready." }+ : { failed: true as const, message: "Could not connect. Retry with /login." };+ });+ const renderer = fakeRenderer({+ setupFlow: createFakeSetupFlowRenderer(),+ renderCommandInvocation: vi.fn(),+ finishCommand: vi.fn(),+ });+ const run = new EveTUIRunner({+ client: stubClient(),+ renderer,+ startup,+ appRoot: "/tmp/agent",+ onboard: true,+ bootDetections: [],+ promptCommandHandler: { handle },+ }).run();+ await vi.waitFor(() => expect(handle).toHaveBeenCalledOnce());+ expect(startup.finish).not.toHaveBeenCalled();+ login.resolve();+ await run;+ expect(server.requests).toEqual([]);+ expect(renderer.readInput).toHaveBeenCalledWith(+ expect.objectContaining({ initialDraft: "Hello Alice\n\nstill editing" }),+ );+ expect(renderer.renderCommandInvocation).not.toHaveBeenCalled();+ },+ );++ it("sends startup messages queued while the agent builds, then restores the draft", async () => {+ const server = serve();+ const client = stubClient();+ vi.spyOn(client, "info").mockResolvedValue(AGENT_INFO);+ const { renderer } = turnTaking([undefined]);+ await new EveTUIRunner({+ client,+ renderer,+ serverUrl: "http://localhost:3000",+ startup: {+ finish: () => ({ draft: "still editing", queuedPrompt: "first message\n\nsecond message" }),},+ }).run();++ expect(server.requestsTo("POST", "/eve/v1/session")[0]?.body).toMatchObject({+ message: "first message\n\nsecond message",});+ expect(renderer.readInput).toHaveBeenCalledWith(+ expect.objectContaining({ initialDraft: "still editing" }),+ );+ });- await runner.run();- await vi.waitFor(() => expect(clearSetupWarning).toHaveBeenCalled());+ it("seeds only the first prompt's draft with --input text", async () => {+ const server = serve();+ const { renderer } = turnTaking(["edited and sent", undefined]);+ await new EveTUIRunner({ client: stubClient(), renderer, initialInput: "draft me" }).run();- expect(client.info).toHaveBeenCalledTimes(2);- expect(detect.mock.calls.at(-1)?.[0].info?.agent.model.endpoint).toEqual({- kind: "gateway",- connected: true,- credential: "api-key",+ expect(+ vi.mocked(renderer.readInput!).mock.calls.map(([options]) => options?.initialDraft),+ ).toEqual(["draft me", undefined]);+ expect(server.requestsTo("POST", "/eve/v1/session")[0]?.body).toMatchObject({+ message: "edited and sent",});- expect(headers.map((header) => header.info?.agent.model.endpoint)).toEqual([- { kind: "gateway", connected: true, credential: "api-key" },- ]);});+});- it("drops stale disconnected evidence when the post-setup info refresh fails", async () => {- const clearSetupWarning = vi.fn();- const finishCommand = vi.fn();- const headers: AgentTUIAgentHeader[] = [];- const detect = vi.fn(({ info }: { info?: AgentInfoResult }) =>- info?.agent.model.endpoint?.kind === "gateway" && !info.agent.model.endpoint.connected- ? [- {- kind: "attention" as const,- label: "model provider not linked",- command: "/model" as const,- },- ]- : [],- );- const { client, runner } = providerSetupRefreshRunner({- refreshInfo: async () => {- throw new Error("info unavailable");- },- bootDetections: [{ id: "test", detect }],- renderer: {- clearSetupWarning,- finishCommand,- renderAgentHeader: (header) => headers.push(header),+describe("EveTUIRunner remote session failures", () => {+ const target = {+ kind: "remote",+ serverUrl: "https://vpoke.playground-vercel.tools",+ workspaceRoot: "/tmp/weather-agent",+ } as const;+ const remote = {+ target,+ credentials: createDevelopmentCredentialGate(target.serverUrl),+ resolveDeployment: async (): Promise<VercelDeploymentResolution> => ({+ kind: "failed",+ failure: {+ cause: "vercel",+ failure: { code: null, message: "lookup failed", stderr: "", stdout: "" },},- });+ }),+ resolveOidcToken: async () => ({ kind: "resolution-failed" as const, message: "none" }),+ };- await runner.run();- await vi.waitFor(() => expect(clearSetupWarning).toHaveBeenCalled());+ it("demotes a ready remote after a send fails", async () => {+ vi.stubGlobal("fetch", async () => new Response("socket down", { status: 502 }));+ const client = stubClient();+ vi.spyOn(client, "info").mockResolvedValue(AGENT_INFO);+ const statuses: string[] = [];+ await new EveTUIRunner({+ client,+ renderer: turnTaking(["Hello.", undefined], {+ renderError: vi.fn(),+ setRemoteConnectionStatus: (snapshot) => statuses.push(snapshot.connection.state),+ }).renderer,+ serverUrl: target.serverUrl,+ remote,+ }).run();- expect(finishCommand).not.toHaveBeenCalled();- expect(client.info).toHaveBeenCalledTimes(2);- expect(detect).not.toHaveBeenCalled();- expect(headers.at(-1)?.info?.agent.model.endpoint).toMatchObject({- kind: "gateway",- connected: true,- });+ expect(statuses.at(-1)).toBe("unavailable");});- it("stays quiet without a local setup context, even with issues", async () => {- const { runner, warnings } = bootRunner({- issues: [{ kind: "attention", label: "AI Gateway credentials", command: "/model" }],+ it("keeps a ready remote connected after an agent session failure", async () => {+ serve(({ turnId }) => [+ createTurnStartedEvent({ sequence: 0, turnId }),+ createSessionFailedEvent({+ code: "HookConflictError",+ message: "HookConflictError: token in use",+ sessionId: "session_1",+ }),+ ]);+ const client = stubClient();+ vi.spyOn(client, "info").mockResolvedValue(AGENT_INFO);+ const statuses: string[] = [];+ await new EveTUIRunner({+ client,+ renderer: turnTaking(["Hello.", undefined], {+ setRemoteConnectionStatus: (snapshot) => statuses.push(snapshot.connection.state),+ }).renderer,+ serverUrl: target.serverUrl,+ remote,+ }).run();++ expect(statuses.at(-1)).toBe("ready");+ expect(statuses).not.toContain("unavailable");+ });+});++describe("EveTUIRunner teardown", () => {+ it("shuts the renderer down when the run loop exits with an error", async () => {+ const shutdown = vi.fn();+ const runner = new EveTUIRunner({+ client: stubClient(),+ renderer: fakeRenderer({+ readInput: vi.fn(async () => {+ throw new Error("renderer exploded");+ }),+ shutdown,+ }),});- await runner.run();- expect(warnings).toEqual([]);+ await expect(runner.run()).rejects.toThrow("renderer exploded");+ expect(shutdown).toHaveBeenCalledTimes(1);});- it("stays quiet when detection finds nothing", async () => {- const { runner, warnings } = bootRunner({+ it("propagates command-handler errors after restoring the renderer", async () => {+ const shutdown = vi.fn();+ const runner = new EveTUIRunner({+ client: stubClient(),+ renderer: fakeRenderer({ readInput: inputs(["/model"]), shutdown }),appRoot: "/tmp/weather-agent",- issues: [],+ bootDetections: [],+ detectProjectIdentity: vi.fn(async () => undefined),+ promptCommandHandler: {+ handle: async () => {+ throw new Error("command implementation failed");+ },+ },});- await runner.run();- expect(warnings).toEqual([]);+ await expect(runner.run()).rejects.toThrow("command implementation failed");+ expect(shutdown).toHaveBeenCalledTimes(1);+ });++ it("shuts the renderer down once when /exit ends the run loop", async () => {+ const shutdown = vi.fn();+ const controller = new AbortController();+ const requestStop = vi.fn(() => controller.abort());+ await new EveTUIRunner({+ client: stubClient(),+ renderer: fakeRenderer({ readInput: inputs(["/exit"]), shutdown }),+ lifecycle: {+ signal: controller.signal,+ stopped: new Promise<NodeJS.Signals | undefined>(() => {}),+ requestStop,+ dispose: () => {},+ },+ }).run();++ expect(shutdown).toHaveBeenCalledTimes(1);+ expect(requestStop).toHaveBeenCalledOnce();});});-describe("EveTUIRunner command outcome rendering", () => {- it("answers /help with the command table even without a command handler", async () => {- const results: string[] = [];- const prompts: Array<string | undefined> = ["/help", undefined];- const session = sessionYielding([]);-- const renderer: AgentTUIRenderer = {- readPrompt: vi.fn(async () => prompts.shift()),- renderNotice: vi.fn(),+describe("EveTUIRunner local commands", () => {+ function recorder(prompts: Array<string | undefined>, overrides: Partial<AgentTUIRenderer> = {}) {+ const outcomes: string[] = [];+ const renderer = fakeRenderer({+ readInput: inputs(prompts),finishCommand: (outcome) => {- if (outcome.kind === "result") results.push(outcome.message ?? "");+ if (outcome.kind === "result") outcomes.push(outcome.message ?? outcome.summary ?? "");},- renderStream: vi.fn(async () => {}),- };-- const runner = new EveTUIRunner({- session,- renderer,- name: "Weather Agent",+ ...overrides,});- await runner.run();+ return { renderer, outcomes };+ }++ it("answers /help with the command table even without a command handler", async () => {+ const { renderer, outcomes } = recorder(["/help", undefined]);+ await new EveTUIRunner({ client: stubClient(), renderer }).run();- expect(results).toHaveLength(1);- expect(results[0]).toContain("/model");- expect(results[0]).not.toContain("/channels");- expect(session.send).not.toHaveBeenCalled();+ expect(outcomes).toHaveLength(1);+ expect(outcomes[0]).toContain("/model");+ expect(outcomes[0]).not.toContain("/channels");});it("renders /info from the local application inspector", async () => {- const results: string[] = [];- const prompts: Array<string | undefined> = ["/info", undefined];- const session = sessionYielding([]);+ const { renderer, outcomes } = recorder(["/info", undefined]);const inspectApplication = vi.fn(async () => ({application: getApplicationInfo("/tmp/weather-agent"),compiledState: null,@@ -4492,101 +1829,48 @@ describe("EveTUIRunner command outcome rendering", () => {streamRoutePattern: "/eve/v1/session/:sessionId/stream",},}));-- const runner = new EveTUIRunner({+ await new EveTUIRunner({+ client: stubClient(),+ renderer,appRoot: "/tmp/weather-agent",+ bootDetections: [],+ detectProjectIdentity: vi.fn(async () => undefined),inspectApplication,- name: "Weather Agent",- renderer: {- readPrompt: vi.fn(async () => prompts.shift()),- finishCommand: (outcome) => {- if (outcome.kind === "result") results.push(outcome.message ?? "");- },- renderStream: vi.fn(async () => {}),- },- session,- });- await runner.run();+ }).run();expect(inspectApplication).toHaveBeenCalledWith("/tmp/weather-agent");- expect(results).toHaveLength(1);- expect(results[0]).toMatch(/^Application\n/u);- expect(session.send).not.toHaveBeenCalled();+ expect(outcomes[0]).toMatch(/^Application\n/u);});it("dispatches /loglevel to the renderer and reports the outcome", async () => {- const results: Array<{ text: string; summary?: string }> = [];const modes: string[] = [];- const prompts: Array<string | undefined> = [- "/loglevel none",- "/loglevel bogus",- "/loglevel sandbox",- undefined,- ];- const session = sessionYielding([]);-- const renderer: AgentTUIRenderer = {- readPrompt: vi.fn(async () => prompts.shift()),- finishCommand: (outcome) => {- if (outcome.kind === "result")- results.push({ text: outcome.message ?? "", summary: outcome.summary });- },- renderStream: vi.fn(async () => {}),- logDisplayMode: () => "all",- setLogDisplayMode: (mode) => modes.push(mode),- };-- const runner = new EveTUIRunner({ session, renderer, name: "Weather Agent" });- await runner.run();+ const { renderer, outcomes } = recorder(+ ["/loglevel none", "/loglevel bogus", "/loglevel sandbox", undefined],+ { logDisplayMode: () => "all", setLogDisplayMode: (mode) => modes.push(mode) },+ );+ await new EveTUIRunner({ client: stubClient(), renderer }).run();expect(modes).toEqual(["none", "sandbox"]);- expect(results).toHaveLength(3);- expect(results[0]?.summary).toContain("hidden");- expect(results[1]?.summary).toBeUndefined();- expect(results[1]?.text).toContain('Unknown log level "bogus"');- expect(results[2]?.summary).toContain("sandbox");- expect(session.send).not.toHaveBeenCalled();+ expect(outcomes[0]).toContain("hidden");+ expect(outcomes[1]).toContain('Unknown log level "bogus"');+ expect(outcomes[2]).toContain("sandbox");});it("reports /loglevel as unavailable when the renderer cannot toggle logs", async () => {- const results: string[] = [];- const prompts: Array<string | undefined> = ["/loglevel none", undefined];- const session = sessionYielding([]);-- const renderer: AgentTUIRenderer = {- readPrompt: vi.fn(async () => prompts.shift()),- finishCommand: (outcome) => {- if (outcome.kind === "result") results.push(outcome.message ?? "");- },- renderStream: vi.fn(async () => {}),- };-- const runner = new EveTUIRunner({ session, renderer, name: "Weather Agent" });- await runner.run();+ const { renderer, outcomes } = recorder(["/loglevel none", undefined]);+ await new EveTUIRunner({ client: stubClient(), renderer }).run();- expect(results).toEqual(["/loglevel is not available in this session."]);- expect(session.send).not.toHaveBeenCalled();+ expect(outcomes).toEqual(["/loglevel is not available in this session."]);});it("prefers the elbow-styled command result over a plain notice", async () => {const notices: string[] = [];- const results: string[] = [];- const prompts: Array<string | undefined> = ["/deploy", undefined];- const session = sessionYielding([]);-- const renderer: AgentTUIRenderer = {- readPrompt: vi.fn(async () => prompts.shift()),+ const { renderer, outcomes } = recorder(["/deploy", undefined], {renderNotice: (text) => notices.push(text),- finishCommand: (outcome) => {- if (outcome.kind === "result") results.push(outcome.message ?? "");- },- renderStream: vi.fn(async () => {}),- };-- const runner = new EveTUIRunner({- session,+ });+ await new EveTUIRunner({+ client: stubClient(),renderer,- name: "Weather Agent",promptCommandHandler: createPromptCommandHandler({target: {kind: "remote",@@ -4594,546 +1878,89 @@ describe("EveTUIRunner command outcome rendering", () => {serverUrl: "https://example.com/",},}),- });- await runner.run();+ }).run();- expect(results).toHaveLength(1);- expect(results[0]).toContain("remote agent");+ expect(outcomes[0]).toContain("remote agent");expect(notices).toEqual([]);});});-describe("EveTUIRunner mid-turn message queue", () => {- it("submits the queued prompt as the next turn without reading the prompt", async () => {- const session = sessionYielding([{ type: "session.waiting" }]);- const queued: Array<string | undefined> = ["queued follow-up", undefined];- const prompts: Array<string | undefined> = ["hello", undefined];- const renderer = fakeRenderer({- readPrompt: vi.fn(async () => prompts.shift()),- renderStream: vi.fn(async (result) => {- for await (const event of result.events as AsyncIterable<unknown>) {- void event;- }- }),- takeQueuedPrompt: vi.fn(() => queued.shift()),- });-- const runner = new EveTUIRunner({ session, renderer, name: "Weather Agent" });- await runner.run();-- expect(session.send).toHaveBeenCalledTimes(2);- expect(session.send).toHaveBeenNthCalledWith(1, "hello", expect.any(Object));- expect(session.send).toHaveBeenNthCalledWith(- 2,- "queued follow-up",- expect.objectContaining({ turnPolicy: "queue" }),- );- // The drained prompt bypasses the interactive prompt read entirely.- expect(renderer.readPrompt).toHaveBeenCalledTimes(2);- });-- it("does not drain the queue when the stream ends without a turn boundary", async () => {- const session = sessionYielding([]);- const takeQueuedPrompt = vi.fn(() => "should stay queued");- const prompts: Array<string | undefined> = ["hello", undefined];- const renderer = fakeRenderer({- readPrompt: vi.fn(async () => prompts.shift()),- renderStream: vi.fn(async (result) => {- for await (const event of result.events as AsyncIterable<unknown>) {- void event;- }- }),- takeQueuedPrompt,- });-- const runner = new EveTUIRunner({ session, renderer, name: "Weather Agent" });- await runner.run();-- // The lost-stream turn keeps queued input for the prompt's draft restore.- expect(takeQueuedPrompt).not.toHaveBeenCalled();- expect(session.send).toHaveBeenCalledTimes(1);- });-- it("retries a cancel that raced turn dispatch and scopes it once the turn id is known", async () => {- const gate = createDeferred<void>();- const session = stubSession();- vi.spyOn(session, "send").mockImplementation(- async () =>- new MessageResponse({- cancelTurn: async (turnId) => await session.cancel({ turnId }),- createStream: async function* () {- yield stampTestEvent(- {- type: "turn.started",- data: { turnId: "turn-1", sequence: 1 },- } as UnstampedMessageStreamEvent,- 0,- );- // Hold the stream mid-turn until the retry loop has proven both- // attempts, then settle the turn as cancelled.- await gate.promise;- yield stampTestEvent(- {- type: "turn.cancelled",- data: { turnId: "turn-1", sequence: 2 },- } as UnstampedMessageStreamEvent,- 1,- );- yield stampTestEvent({ type: "session.waiting" } as UnstampedMessageStreamEvent, 2);- },- sessionId: "session_test",- }),- );- const cancelCalls: Array<{ turnId?: string } | undefined> = [];- vi.spyOn(session, "cancel").mockImplementation(async (options?: { turnId?: string }) => {- cancelCalls.push(options);- if (cancelCalls.length >= 2) {- gate.resolve();- return { sessionId: "session_test", status: "accepted" as const };- }- // The first request arrived before the owner began the turn.- return { status: "no_active_turn" as const };- });- const prompts: Array<string | undefined> = ["hello", undefined];- const seen: string[] = [];- const renderer = fakeRenderer({- readPrompt: vi.fn(async () => prompts.shift()),- renderStream: vi.fn(async (result) => {- // Esc lands before the first stream event arrives.- result.cancel?.();- for await (const event of result.events as AsyncIterable<AgentTUIStreamEvent>) {- seen.push(event.type);- }- }),- });-- const runner = new EveTUIRunner({ session, renderer, name: "Weather Agent" });- await runner.run();-- // `turn.cancelled` reaches the renderer as its own stream event.- expect(seen).toContain("turn-cancelled");- expect(cancelCalls).toHaveLength(2);- // First attempt fired before `turn.started` named the turn; the retry- // carries the observed id so it can never cancel a later turn.- expect(cancelCalls[0]).toBeUndefined();- expect(cancelCalls[1]).toEqual({ turnId: "turn-1" });- });-- it("drops a cancel request that arrives after the turn boundary", async () => {- const session = sessionYielding([- { type: "turn.started", data: { turnId: "turn-1", sequence: 1 } },- { type: "session.waiting" },- ]);- const cancel = vi- .spyOn(session, "cancel")- .mockResolvedValue({ sessionId: "session_test", status: "accepted" });- const prompts: Array<string | undefined> = ["hello", undefined];- const renderer = fakeRenderer({- readPrompt: vi.fn(async () => prompts.shift()),- renderStream: vi.fn(async (result) => {- for await (const event of result.events as AsyncIterable<unknown>) {- void event;- }- // An Esc landing exactly as the boundary settles has nothing left- // to cancel — and must not reach the next turn.- result.cancel?.();- }),- });-- const runner = new EveTUIRunner({ session, renderer, name: "Weather Agent" });- await runner.run();-- expect(cancel).not.toHaveBeenCalled();- });-});--describe("EveTUIRunner session id reporting", () => {- it("pushes the accepted session id and keeps it sticky across /reset", async () => {- const session = sessionYielding([{ type: "session.waiting" }]);- vi.spyOn(session, "state", "get").mockReturnValue({- sessionId: "session_test",- streamIndex: 0,- });- const reported: string[] = [];- const prompts: Array<string | undefined> = ["hello", "/reset", undefined];- const renderer = fakeRenderer({- readPrompt: vi.fn(async () => prompts.shift()),- renderStream: vi.fn(async (result) => {- for await (const event of result.events as AsyncIterable<unknown>) {- void event;- }- }),- setSessionId: vi.fn((sessionId: string) => reported.push(sessionId)),- });-- const runner = new EveTUIRunner({ session, renderer, name: "Weather Agent" });- await runner.run();-- // Named once the turn's send is accepted. `/reset` (and interrupt- // recovery, which shares #startNewSession) must NOT clear it: the- // parting line names the last session this TUI talked to, and the- // replacement session has no id until its first turn is accepted.- expect(reported).toEqual(["session_test"]);- });-- it("keeps the interrupted session's id for the parting line after Ctrl-C recovery", async () => {- // A stream that never settles: the user interrupts it client-side.- const gate = createDeferred<void>();- const session = stubSession();- vi.spyOn(session, "send").mockImplementation(- async () =>- new MessageResponse({- cancelTurn: async (turnId) => await session.cancel({ turnId }),- createStream: async function* () {- yield { type: "turn.started", data: { turnId: "turn-1", sequence: 1 } } as never;- await gate.promise;- },- sessionId: "session_interrupted",- }),- );- vi.spyOn(session, "state", "get").mockReturnValue({- sessionId: "session_interrupted",- streamIndex: 0,- });- const reported: string[] = [];- const notices: string[] = [];- const prompts: Array<string | undefined> = ["hello", undefined];+describe("EveTUIRunner onboarding", () => {+ it("starts onboarding without login history and preserves the input draft", async () => {+ const order: string[] = [];const renderer = fakeRenderer({- readPrompt: vi.fn(async () => prompts.shift()),- renderStream: vi.fn(async (result) => {- // Ctrl-C: abort the turn without draining the stream.- result.abort?.();- gate.resolve();+ setupFlow: createFakeSetupFlowRenderer(),+ renderCommandInvocation: vi.fn(),+ finishCommand: vi.fn(),+ readInput: vi.fn(async (options?: AgentTUISessionOptions) => {+ order.push("prompt");+ expect(options?.initialDraft).toBe("Hello Alice");+ return undefined;}),- renderNotice: (text) => notices.push(text),- setSessionId: vi.fn((sessionId: string) => reported.push(sessionId)),});-- const runner = new EveTUIRunner({ session, renderer, name: "Weather Agent" });- await runner.run();-- // The abort recovery replaces the session but the reported id — what- // the parting line prints — survives.- expect(reported).toEqual(["session_interrupted"]);- expect(notices.some((text) => text.includes("started a new session"))).toBe(true);- });-});--describe("EveTUIRunner cancelled-turn subagent settling", () => {- it("stops following only the cancelled turn's agents", async () => {- // A child stream that never ends on its own — it only stops when the- // pump aborts it (the scoped cancellation path under test).- const client = stubClient();- const childSignals = new Map<string, AbortSignal | undefined>();- vi.stubGlobal(- "fetch",- vi.fn<typeof fetch>(async (input, init) => {- childSignals.set(new URL(String(input)).pathname, init?.signal ?? undefined);- return new Response(- new ReadableStream<Uint8Array>({- start(controller) {- init?.signal?.addEventListener(- "abort",- () => controller.error(new DOMException("Aborted", "AbortError")),- { once: true },- );- },- }),- {- headers: { [EVE_STREAM_VERSION_HEADER]: EVE_MESSAGE_STREAM_VERSION },- },- );- }),- );-- const session = sessionYielding([- {- type: "task.started",- data: {- callId: "call-a",- kind: "agent",- name: "researcher",- taskId: "researcher-call-a",- turnId: "turn-a",- },- },- {- type: "agent.started",- data: {- callId: "call-a",- name: "researcher",- sessionId: "child-a",- streamPath: "/eve/v1/session/child-a/stream",- taskId: "researcher-call-a",- turnId: "turn-a",- },- },- {- type: "task.started",- data: {- callId: "call-1",- kind: "agent",- name: "researcher",- taskId: "researcher-call-1",- turnId: "turn-1",- },- },- {- type: "agent.started",- data: {- callId: "call-1",- name: "researcher",- sessionId: "child-1",- streamPath: "/eve/v1/session/child-1/stream",- taskId: "researcher-call-1",- turnId: "turn-1",+ await new EveTUIRunner({+ client: stubClient(),+ renderer,+ name: "Agent",+ appRoot: "/tmp/agent",+ onboard: true,+ initialInput: "Hello Alice",+ bootDetections: [],+ promptCommandHandler: {+ handle: async (command) => {+ order.push(command.name);+ return { message: "Connected." };},},- { type: "turn.cancelled", data: { turnId: "turn-1", sequence: 2 } },- { type: "session.waiting" },- ]);- const view = {- begin: vi.fn(),- end: vi.fn(),- upsertStep: vi.fn(),- upsertTool: vi.fn(),- removeTool: vi.fn(),- markChildToolCallId: vi.fn(),- };- const prompts: Array<string | undefined> = ["hello", undefined];- let abortedAtNextPrompt: Record<string, boolean | undefined> = {};- const renderer = fakeRenderer({- readPrompt: vi.fn(async () => {- if (prompts.length === 1) {- await vi.waitFor(() => expect(childSignals.size).toBe(2));- abortedAtNextPrompt = Object.fromEntries(- [...childSignals].map(([path, signal]) => [path, signal?.aborted]),- );- }- return prompts.shift();- }),- renderStream: vi.fn(async (result) => {- for await (const event of result.events as AsyncIterable<unknown>) {- void event;- }- }),- subagents: view,- });-- const runner = new EveTUIRunner({ session, client, renderer, name: "Weather Agent" });- await runner.run();+ }).run();- // A cancelled turn stops following its own agents without waiting for a- // later `task.settled`; another turn's agent keeps streaming.- expect(abortedAtNextPrompt).toEqual({- "/eve/v1/session/child-1/stream": true,- "/eve/v1/session/child-a/stream": false,- });+ expect(order).toEqual(["login", "prompt"]);+ expect(renderer.renderCommandInvocation).not.toHaveBeenCalled();+ expect(renderer.finishCommand).not.toHaveBeenCalled();});-});-describe("EveTUIRunner command shutdown", () => {- it("unwinds a blocked prompt", async () => {- const client = stubClient();- vi.spyOn(client, "info").mockResolvedValue(AGENT_INFO);- const prompt = createDeferred<string | undefined>();- const controller = new AbortController();- const renderer: AgentTUIRenderer = {- readPrompt: vi.fn(() => prompt.promise),- renderAgentHeader: vi.fn(),- renderStream: vi.fn(async () => {}),- requestInterrupt: vi.fn(() => prompt.reject(interruptedError())),- };- const runner = new EveTUIRunner({- session: stubSession(),- client,- renderer,- lifecycle: {- signal: controller.signal,- stopped: new Promise<NodeJS.Signals | undefined>(() => {}),- requestStop: () => controller.abort(),- dispose: () => {},- },+ it("keeps the result of an explicit login command after onboarding", async () => {+ const handle = vi.fn(async () => ({ message: "Connected." }));+ const renderer = fakeRenderer({+ setupFlow: createFakeSetupFlowRenderer(),+ finishCommand: vi.fn(),+ readInput: inputs(["/login", undefined]),});+ await new EveTUIRunner({+ client: stubClient(),+ renderer,+ appRoot: "/tmp/agent",+ onboard: true,+ bootDetections: [],+ promptCommandHandler: { handle },+ }).run();- const run = runner.run();- await settleAsyncWork();- controller.abort();-- await expect(run).resolves.toBeUndefined();- expect(renderer.requestInterrupt).toHaveBeenCalledOnce();- });-});--it("starts onboarding without login history and preserves the input draft", async () => {- const order: string[] = [];- const handle = vi.fn(async (command: { name: string }) => {- order.push(command.name);- return { message: "Connected." };- });- const renderer = fakeRenderer({- setupFlow: createFakeSetupFlowRenderer(),- renderCommandInvocation: vi.fn(),- finishCommand: vi.fn(),- readPrompt: vi.fn(async (options?: AgentTUISessionOptions) => {- order.push("prompt");- expect(options?.initialDraft).toBe("Hello Alice");- return undefined;- }),- });- const runner = new EveTUIRunner({- session: sessionYielding([]),- renderer,- name: "Agent",- appRoot: "/tmp/agent",- onboard: true,- initialInput: "Hello Alice",- bootDetections: [],- promptCommandHandler: { handle },- });- await runner.run();- expect(order).toEqual(["login", "prompt"]);- expect(renderer.renderCommandInvocation).not.toHaveBeenCalled();- expect(renderer.finishCommand).not.toHaveBeenCalled();-});--it("keeps the result of an explicit login command after onboarding", async () => {- const prompts = ["/login", undefined];- const handle = vi.fn(async () => ({ message: "Connected." }));- const renderer = fakeRenderer({- setupFlow: createFakeSetupFlowRenderer(),- finishCommand: vi.fn(),- readPrompt: vi.fn(async () => prompts.shift()),- });- const runner = new EveTUIRunner({- session: sessionYielding([]),- renderer,- appRoot: "/tmp/agent",- onboard: true,- bootDetections: [],- promptCommandHandler: { handle },- });-- await runner.run();-- expect(handle).toHaveBeenCalledTimes(2);- expect(renderer.finishCommand).toHaveBeenCalledExactlyOnceWith({- kind: "result",- message: "Connected.",- summary: undefined,+ expect(handle).toHaveBeenCalledTimes(2);+ expect(renderer.finishCommand).toHaveBeenCalledExactlyOnceWith({+ kind: "result",+ message: "Connected.",+ summary: undefined,+ });});-});-describe("EveTUIRunner task activity", () => {- it("shows people their tasks and keeps the model's task bookkeeping out of view", async () => {- const turn = { sequence: 1, stepIndex: 0, turnId: "turn-1" };- const inputDelta = (callId: string, toolName: string) => ({- type: "action.input.appended",- data: { ...turn, callId, inputTextDelta: "{}", toolName },- });- const toolResult = (- callId: string,- toolName: string,- output: unknown,- status = "completed",- ) => ({- type: "action.result",- data: { ...turn, result: { callId, kind: "tool-result", output, toolName }, status },- });- const session = sessionYielding([- { type: "turn.started", data: { sequence: 0, turnId: "turn-1" } },- inputDelta("deploy-call", "deploy"),- inputDelta("deploy-call", "deploy"),- inputDelta("wait-call", "task_wait"),- {- type: "actions.requested",- data: {- ...turn,- actions: [- {- callId: "deploy-call",- input: { env: "preview" },- kind: "tool-call",- toolName: "deploy",- },- { callId: "retry-call", input: {}, kind: "tool-call", toolName: "report" },- { callId: "lookup-call", input: {}, kind: "tool-call", toolName: "lookup" },- { callId: "wait-call", input: {}, kind: "tool-call", toolName: "task_wait" },- {- callId: "cancel-call",- input: { taskId: "t0" },- kind: "tool-call",- toolName: "task_cancel",- },+ it("does not auto-open /model outside the prefilled onboarding launch", async () => {+ const handle = vi.fn(async () => ({ message: "/model dismissed." }));+ await new EveTUIRunner({+ client: stubClient(),+ renderer: fakeRenderer({ setupFlow: createFakeSetupFlowRenderer() }),+ appRoot: "/tmp/weather-agent",+ bootDetections: [+ {+ id: "test",+ detect: () => [+ { kind: "attention", label: "model provider not linked", command: "/model" },],- presentation: { "deploy-call": { label: "Deploy to preview" } },- },- },- {- type: "task.started",- data: {- callId: "deploy-call",- kind: "tool",- name: "deploy",- taskId: "t1",- turnId: "turn-1",- },- },- toolResult("deploy-call", "deploy", "receipt written for the model"),- toolResult("retry-call", "report", { code: "TOO_MANY_TASKS", message: "wait" }, "failed"),- // An authored tool's own result can carry the same code; only a refusal fails.- toolResult("lookup-call", "lookup", { code: "UNKNOWN_TASK", ticket: "T-1" }),- toolResult("cancel-call", "task_cancel", "t0 had no work to stop."),- {- type: "task.settled",- data: {- callId: "deploy-call",- output: { url: "https://preview.example" },- status: "completed",- taskId: "t1",- turnId: "turn-1",},- },- toolResult("wait-call", "task_wait", "t1 completed; its result follows."),- { type: "session.waiting", data: { continuationToken: "c", wait: "next-user-message" } },- ]);- const seen: AgentTUIStreamEvent[] = [];- const prompts: Array<string | undefined> = ["deploy it", undefined];- const renderer = fakeRenderer({- readPrompt: vi.fn(async () => prompts.shift()),- renderStream: vi.fn(async (result) => {- for await (const event of result.events as AsyncIterable<AgentTUIStreamEvent>) {- seen.push(event);- }- }),- });-- await new EveTUIRunner({ session, renderer, name: "Weather Agent" }).run();+ ],+ detectProjectIdentity: vi.fn(async () => undefined),+ promptCommandHandler: { handle },+ }).run();- expect(seen.filter((event) => event.type !== "turn-start" && event.type !== "finish")).toEqual([- { type: "tool-call-preparing", toolCallId: "deploy-call", toolName: "deploy" },- {- type: "tool-call",- toolCallId: "deploy-call",- toolName: "deploy",- input: { env: "preview" },- label: "Deploy to preview",- },- { type: "tool-call", toolCallId: "retry-call", toolName: "report", input: {} },- { type: "tool-call", toolCallId: "lookup-call", toolName: "lookup", input: {} },- { type: "task-started", toolCallId: "deploy-call", kind: "tool", toolName: "deploy" },- { type: "tool-withdrawn", toolCallId: "retry-call", reason: expect.any(String) },- {- type: "tool-result",- toolCallId: "lookup-call",- output: { code: "UNKNOWN_TASK", ticket: "T-1" },- },- {- type: "task-settled",- toolCallId: "deploy-call",- status: "completed",- output: { url: "https://preview.example" },- },- ]);+ expect(handle).not.toHaveBeenCalled();});});diff --git a/packages/eve/src/cli/dev/tui/runner.ts b/packages/eve/src/cli/dev/tui/runner.tsindex e98c6e14a..08b8994b5 100644--- a/packages/eve/src/cli/dev/tui/runner.ts+++ b/packages/eve/src/cli/dev/tui/runner.ts@@ -1,54 +1,53 @@-import type { ModelAccessChange } from "#shared/model-connection.js";-import { SteeringStream } from "#cli/dev/tui/steering-stream.js";import {- type ActionResultStreamEvent,- type ActionsRequestedStreamEvent,- type AgentInfoResult,- type AuthorizationCompletedStreamEvent,- type ConnectionAuthorizationOutcome,- type AuthorizationRequiredStreamEvent,- type InputOption,- type InputRequest,- type InputRequestedStreamEvent,- type InputResponse,- type MessageAppendedStreamEvent,- type ReasoningAppendedStreamEvent,- type SessionFailedStreamEvent,- type StepCompletedStreamEvent,- type MessageStreamEvent,- type AgentStartedStreamEvent,- type TaskStartedStreamEvent,+ openConversationInputs,+ type ConversationInput,+ type ConversationState,+} from "#client/conversation-state.js";+import {+ attachEveAgentStore,+ detachEveAgentStore,+ EveAgentStore,+} from "#client/eve-agent-store.js";+import { isAbortError } from "#client/eve-agent-store-helpers.js";+import { normalizeActionRequest, normalizeActionResult } from "#client/message-action-parts.js";+import { isTerminalToolCallPart } from "./terminal-tool-part.js";+import { userText } from "./transcript-parts.js";+import { isTaskRetryRefusal } from "#protocol/task-tools.js";+import type { SendTurnPayload } from "#client/types.js";+import type { ModelAccessChange } from "#shared/model-connection.js";+import type {+ AgentInfoResult,Client,- ClientSession,+ InputOption,+ InputRequest,+ InputResponse,+ MessageStreamEvent,} from "#client/index.js";import { renderApplicationInfo } from "#cli/commands/info.js";import type { EveCliSetupStepEvent, EveCliSetupTerminalEvent } from "#cli/telemetry/index.js";import type { OnboardingScreenEvent } from "./setup-commands.js";import { loadDevelopmentEnvironmentFiles } from "#cli/dev/environment.js";-import { createEventDeduper } from "#protocol/event-dedupe.js";-import { isCurrentTurnBoundaryEvent } from "#protocol/message.js";-import { isTaskControlTool, isTaskRetryRefusal } from "#protocol/task-tools.js";import {createDevelopmentRuntimeArtifactRefresher,type DevelopmentRuntimeArtifactRefresher,} from "#services/dev-client.js";import { inspectApplication } from "#services/inspect-application.js";import { toErrorMessage } from "#shared/errors.js";-import { SubagentPump, type SubagentPumpOptions, type SubagentView } from "./subagent-pump.js";-export type {- SubagentRun,- SubagentStepUpdate,- SubagentToolUpdate,- SubagentView,-} from "./subagent-pump.js";+import {+ conversationView,+ isWorking,+ tuiSessionReducer,+ type AgentTUIConversationView,+ type TuiSessionData,+} from "./conversation-view.js";import { devBootPhase, type DevBootProgressReporter } from "#internal/dev-boot-progress.js";import {- type FailureStreamEvent,failureKey,formatFailureDetail,formatFailureHint,formatFailureMessage,+ interruptedError,isInterruptedError,localFailureHint,} from "./errors.js";@@ -89,14 +88,8 @@ import {import type { SetupFlowRenderer } from "./setup-flow.js";import type { TraceViewerRenderer } from "./traces/trace-viewer-session.js";import type { RemoteDevelopmentTarget } from "./target.js";-import type {- AssistantResponseStatsMode,- LogDisplayMode,- TerminalPartDisplayMode,- TuiDisplayOptions,-} from "./types.js";+import type { LogDisplayMode, TuiDisplayOptions } from "./types.js";import { TerminalRenderer, type TerminalInput, type TerminalOutput } from "./terminal-renderer.js";-import { SELF_MODIFICATION_AGENT_NAME } from "./tool-presentation.js";import {createVercelStatusTracker,type VercelStatusEffect,@@ -114,129 +107,37 @@ import { getVercelAuthStatus, type VercelAuthStatus } from "#setup/vercel-projecimport type { DevDiagnostics } from "../diagnostics.js";import type { CommandLifecycle } from "../../shutdown.js";-const defaultAssistantResponseStats: AssistantResponseStatsMode = "tokensPerSecond";const idleRuntimeArtifactPollMs = 500;const idleChatGptAuthPollMs = 5_000;-const idleSessionReconnectBaseDelayMs = 100;-const idleSessionReconnectMaxDelayMs = 2_000;-/**- * Cooperative-cancel retry cadence: 8 × 250ms covers the turn-dispatch- * window (locally the cancel hook is claimed well under a second after the- * send is accepted) without hammering the cancel route.- */-const turnCancelRetryDelayMs = 250;-const turnCancelAttempts = 8;--async function delayMs(ms: number): Promise<void> {- await new Promise<void>((resolve) => {- const timer = setTimeout(resolve, ms);- timer.unref?.();- });-}--async function abortableDelay(ms: number, signal: AbortSignal): Promise<void> {- if (signal.aborted) return;- await new Promise<void>((resolve) => {- const timer = setTimeout(done, ms);- timer.unref?.();- signal.addEventListener("abort", done, { once: true });- function done() {- clearTimeout(timer);- signal.removeEventListener("abort", done);- resolve();- }- });-}--export type AgentTUIStreamResult = {- steer?: (message: string) => Promise<void>;- events: AsyncIterable<AgentTUIStreamEvent> | ReadableStream<AgentTUIStreamEvent>;- abort?: () => void;- /**- * Requests cooperative server-side cancellation of the streaming turn- * (`/cancel`, Esc, or Ctrl+C; the keys steer when a message is queued). Unlike- * {@link abort} — which drops the client stream and forces a fresh session —- * the server settles the turn as `turn.cancelled` → `session.waiting`, so- * the stream reaches its boundary normally and the session keeps its context.- * Best-effort and idempotent; scoped to the turn the user observed when its id is known.- */- cancel?: () => void;- turnState?: AgentTUITurnState;-};--export type AgentTUIStreamUsage = {- inputTokens?: number;- outputTokens?: number;-};--export type AgentTUIStreamEvent =- | { type: "turn-start"; turnId: string }- | { type: "step-start"; modelId?: string }- | { type: "step-finish"; usage?: AgentTUIStreamUsage }- | { type: "assistant-delta"; id: string; delta: string }- | { type: "assistant-complete"; id: string; text?: string | null }- | { type: "reasoning-delta"; id: string; delta: string }- | { type: "reasoning-complete"; id: string }- | { type: "tool-call-preparing"; toolCallId: string; toolName: string }- | {- type: "tool-call";- toolCallId: string;- toolName: string;- input: unknown;- /** The tool's own `label.start` copy, when it defines one. */- label?: string;- }- | { type: "tool-approval-request"; approvalId: string; toolCallId: string }- | {- type: "tool-result";- toolCallId: string;- output: unknown;- /** The tool's own `label.complete` copy, when it defines one. */- label?: string;- }- | { type: "tool-error"; toolCallId: string; errorText: string }- | { type: "tool-rejected"; toolCallId: string; reason: string }- /** A call the session refused for the model to retry; it leaves no trace in the transcript. */- | { type: "tool-withdrawn"; toolCallId: string; reason: string }- /** A call became a task that keeps working while the turn goes on. */- | { type: "task-started"; toolCallId: string; kind: "agent" | "tool"; toolName: string }- | {- type: "task-settled";- toolCallId: string;- status: "completed" | "failed" | "cancelled";- output?: unknown;- errorText?: string;- }- | { type: "error"; errorText: string; hint?: string; detail?: string }- | { type: "turn-cancelled" }- | { type: "finish"; usage?: AgentTUIStreamUsage };--export type AgentTUITurnState = {- aborted?: boolean;- boundaryEvent?: "session.completed" | "session.failed" | "session.waiting" | "turn.waiting";- pendingApprovals: AgentTUIToolApprovalRequest[];- pendingQuestions: InputRequest[];- sawSessionFailure: boolean;- /** Id of the streaming turn, once `turn.started` names it. Scopes cancels. */- turnId?: string;- /** True while a cooperative-cancel request loop is running for this turn. */- cancelInFlight?: boolean;-};export type AgentTUISessionOptions = {title?: string;/**- * Text to seed the editable prompt buffer with before the user types.- * Set by the runner for the first prompt when `eve dev --input` is used.+ * Text to seed the composer's draft with before the user types. Set by the+ * runner for the first prompt when `eve dev --input` is used.*/initialDraft?: string;- submittedPrompt?: string;- continueSession?: boolean;- tools?: TerminalPartDisplayMode;- reasoning?: TerminalPartDisplayMode;- connectionAuth?: TerminalPartDisplayMode;- assistantResponseStats?: AssistantResponseStatsMode;- contextSize?: number;+ /** Closes the composer without discarding its draft. */+ signal?: AbortSignal;+};++/** One user action from the composer. */+export type AgentTUIInput =+ /** A message or slash command. Messages sent while work runs steer it. */+ | { type: "submit"; text: string }+ /** `Esc` or `Ctrl+C` while work runs. */+ | { type: "cancel" }+ /** `Ctrl+C` again while cancellation is pending: stop following the turn. */+ | { type: "interrupt" };++/** Where a prompt sits among the requests being answered, and who asked, when that helps. */+export type AgentTUIInputContext = {+ /** 1-based position among the requests answered in a row; the total grows as more arrive. */+ position?: { index: number; total: number };+ /** The task that asked, named as its transcript lines are. */+ requester?: string;+ /** The task whose run asked; the renderer names it as its task lines do. */+ taskId?: string;};export type AgentTUIToolApprovalRequest = {@@ -245,6 +146,7 @@ export type AgentTUIToolApprovalRequest = {toolName: string;title?: string;input: unknown;+ context?: AgentTUIInputContext;};export type AgentTUIToolApprovalResponse = {@@ -265,6 +167,7 @@ export type AgentTUIInputQuestion = {display: "select" | "text";options?: ReadonlyArray<AgentTUIInputOption>;allowFreeform?: boolean;+ context?: AgentTUIInputContext;};export type AgentTUIInputQuestionResponse = {@@ -293,10 +196,16 @@ export type AgentTUIRenderer = {* recovery and slash-command results. Optional.*/renderNotice?(text: string): void;+ /**+ * Puts back a message whose turn was cancelled from outside this prompt, such as `/cancel` from+ * another client, when the composer is empty. Optional.+ */+ restoreDraft?(text: string): void;/*** Commits the session boundary (`┌── Session restarted, clear context.`)- * when a dead session is replaced mid-conversation. Optional; renderers- * without it get the plain notice.+ * when a dead session is replaced mid-conversation. The old conversation's+ * transcript settles as shown; the next `renderConversation` starts fresh.+ * Optional; renderers without it get the plain notice.*/renderSessionBoundary?(): void;/**@@ -317,15 +226,15 @@ export type AgentTUIRenderer = {* The returned promise resolves when the user closes the viewer.*/readonly traceViewer?: TraceViewerRenderer;- readPrompt?(options?: AgentTUISessionOptions): Promise<string | undefined>;/**- * Consumes the next prompt produced by mid-turn input: the Esc-popped- * steering message when one is staged, otherwise every message queued- * during the turn coalesced into one. The runner calls this at a clean- * turn boundary and submits the result as the next turn without reading- * the prompt. Optional — renderers without mid-turn input never queue.+ * Reads the next composer action. Resolves `undefined` when `signal`+ * aborts and rejects with an interrupt when the user leaves.*/- takeQueuedPrompt?(): string | undefined;+ readInput?(options?: AgentTUISessionOptions): Promise<AgentTUIInput | undefined>;+ /** Draws the session's transcript from one conversation snapshot. */+ renderConversation?(view: AgentTUIConversationView): void;+ /** Commits one error block, such as a message the session did not accept. */+ renderError?(title: string, message: string): void;/*** Reports the server session id backing the conversation — pushed by the* runner once a send is accepted, and overwritten when a later session's@@ -344,36 +253,6 @@ export type AgentTUIRenderer = {question: AgentTUIInputQuestion,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- * members: a renderer either has a subagent view or it doesn't, and a- * type-legal partial implementation (which would ghost placeholders or- * duplicate parent tool rows) cannot exist.- */- readonly subagents?: SubagentView;- /**- * Out-of-band update for one MCP connection authorization lifecycle.- * Called by the runner as `authorization.*` events arrive.- * The renderer renders this as a persistent body section per- * connection that transitions through `required` → `pending` →- * one of the terminal `ConnectionAuthorizationOutcome` states.- */- upsertConnectionAuth?(update: ConnectionAuthUpdate): void;- /**- * Sets the number of connections currently awaiting an OAuth- * callback. The renderer overrides its bottom status bar with a- * "waiting for connection authorization" hint while this is > 0,- * so the user understands the agent is parked, not hung.- */- setConnectionAuthPendingCount?(count: number): void;/*** The log display mode currently in effect. Paired with* {@link setLogDisplayMode}; both are absent on renderers that do not@@ -412,8 +291,6 @@ 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;};@@ -462,27 +339,19 @@ type TuiStartup = {};export type EveTUIRunnerOptions = TuiDisplayOptions & {- session?: ClientSession;/** Production TUI probe injected by the launcher; omitted in hermetic runners. */probeMcpConnection?: McpConnectionProbe;- /**- * Optional client used to attach to child sessions for live subagent- * stream observation. When omitted, the TUI still shows the subagent- * section but cannot surface the subagent's reasoning / response /- * intermediate events — only the parent-stream `called` and- * `completed` transitions.- */- client?: Client;+ /** Configured client for the conversation's sessions and their subagent streams. */+ client: Client;renderer?: AgentTUIRenderer;screen?: TerminalOutput;userInput?: TerminalInput;/**- * Formats an error thrown while dispatching a turn (the initial- * `session.send()` POST — e.g. a transport failure or a Vercel- * Deployment Protection challenge) into the text rendered in the- * inline error region. Defaults to the error's message. Callers that- * know about transport-specific challenges (the `eve dev` glue) inject- * a richer formatter here.+ * Formats a session error (a failed send — e.g. a transport failure or a+ * Vercel Deployment Protection challenge) into the text rendered in the+ * inline error region. Defaults to the error's message. Callers that know+ * about transport-specific challenges (the `eve dev` glue) inject a richer+ * formatter here.*/formatTransportError?: (error: unknown) => string;/**@@ -544,15 +413,12 @@ function authIssueForStatus(status: VercelAuthStatus): SetupIssue | undefined {}export class EveTUIRunner {- #session: ClientSession | undefined;- readonly #client?: Client;+ readonly #client: Client;+ /** Owns the conversation's sessions, root stream, turns, and subagent streams. */+ readonly #store: EveAgentStore<TuiSessionData>;readonly #renderer: AgentTUIRenderer;+ readonly #diagnostics?: DevDiagnostics;readonly #name: string;- readonly #tools: TerminalPartDisplayMode;- readonly #reasoning: TerminalPartDisplayMode;- readonly #connectionAuth: TerminalPartDisplayMode;- readonly #assistantResponseStats: AssistantResponseStatsMode;- readonly #contextSize?: number;readonly #formatTransportError: (error: unknown) => string;readonly #runtimeArtifacts?: DevelopmentRuntimeArtifactRefresher;readonly #serverUrl?: string;@@ -578,6 +444,10 @@ export class EveTUIRunner {#onBootProgress?: DevBootProgressReporter;/** Set when the run loop unwinds, so a late boot login probe cannot paint into a torn-down terminal. */#disposed = false;+ /** The message this TUI last sent, until its turn settles. */+ #sentMessage?: string;+ /** Whether this TUI asked to cancel the turn of {@link #sentMessage}. */+ #cancelRequested = false;/** Aborts the off-critical-path boot auth probe when the run loop unwinds. */readonly #authProbeAbort = new AbortController();/**@@ -600,72 +470,41 @@ export class EveTUIRunner {readonly #vercelStatus?: VercelStatusTracker;readonly #mcpConnectionStatus?: McpConnectionStatusTracker;#agentInfo?: AgentInfoResult;- /**- * approval-id → input-request map populated as `input.requested` events- * stream in. Used to translate the renderer's approval responses back into- * 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;+ /** Closes the composer when something else needs the keyboard. */+ #inputController?: AbortController;+ /** Questions the user skipped; they stay open for the server to resolve. */+ readonly #dismissedInputs = new Set<string>();/** Registry setups queued by tool results on root or child streams. */readonly #pendingRegistrySetups: string[] = [];#activeRegistrySetup?: string;- /** True only while the idle prompt owns terminal input. */- #readingPrompt = false;- /**- * callId → live state for one call to an agent task. Persists across turn- * boundaries because a call made in one turn may not settle until a later- * turn (e.g. after a HITL approval). Each run holds per-step text- * accumulators (so reasoning + message land in the same section per child- * step) and per-tool state.- */- readonly #subagentPump: SubagentPump;- /**- * name → latest known state for one MCP connection- * authorization lifecycle. Persists across turns because a turn that- * suspends on a webhook callback resumes in a later turn — the- * `_required`/`_pending` events fire in turn N and the `_completed`- * event may not arrive until turn N+1. Each entry holds enough- * context to re-render the body section idempotently from any- * single event.- */- readonly #connectionAuthRuns = new Map<string, ConnectionAuthRun>();- /**- * Set of connection names currently in the `pending` state — i.e.- * the workflow is suspended waiting on the framework-owned OAuth- * callback. Used to drive the renderer's bottom-bar hint.- */- readonly #pendingConnectionAuths = new Set<string>();- /**- * 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.- */- #failedSession?: ClientSession;+ /** Tool calls whose registry handoff was already queued. */+ readonly #handledHandoffs = new Set<string>();+ /** The last session error shown, so each renders once. */+ #reportedError?: Error;+ /** Failure cascades already recorded in diagnostics this turn. */+ readonly #recordedFailures = new Set<string>();+ readonly #recordedAgentToolFailures = new Set<string>();readonly #lifecycle?: CommandLifecycle;constructor(options: EveTUIRunnerOptions) {- this.#session = options.session;- if (options.client !== undefined) this.#client = options.client;+ this.#client = options.client;if (options.lifecycle !== undefined) this.#lifecycle = options.lifecycle;+ if (options.diagnostics !== undefined) this.#diagnostics = options.diagnostics;this.#renderer = createRenderer(options);- const pumpOptions: SubagentPumpOptions = { formatActionResultError };- if (this.#client !== undefined) pumpOptions.client = this.#client;- if (this.#renderer.subagents !== undefined) pumpOptions.view = this.#renderer.subagents;- if (options.appRoot !== undefined) {- pumpOptions.onToolCompleted = async (subagentName, toolName, output) => {- const address = registryHandoffAddress(subagentName, toolName, output);- if (address !== undefined) this.#queueRegistrySetup(address);- };- }- this.#subagentPump = new SubagentPump(pumpOptions);+ this.#store = new EveAgentStore({+ client: options.client,+ followSubagents: true,+ reducer: tuiSessionReducer,+ });+ this.#store.setCallbacks({+ onEvent: (event) => this.#recordDiagnostics(event),+ onSessionChange: (session) => {+ if (session !== undefined) this.#renderer.setSessionId?.(session.sessionId);+ },+ prepareSend: (input) => this.#prepareSend(input),+ });this.#name = options.name ?? "eve";this.#withExclusiveTerminal = options.withExclusiveTerminal;- this.#tools = options.tools ?? "full";- this.#reasoning = options.reasoning ?? "full";- this.#connectionAuth = options.connectionAuth ?? "full";- this.#assistantResponseStats = options.assistantResponseStats ?? defaultAssistantResponseStats;- this.#contextSize = options.contextSize;this.#formatTransportError = options.formatTransportError ?? toErrorMessage;if (options.initialInput !== undefined) this.#initialInput = options.initialInput;if (options.startup !== undefined) this.#startup = options.startup;@@ -695,9 +534,6 @@ export class EveTUIRunner {this.#availablePromptCommands = options.availablePromptCommands ?? PROMPT_COMMANDS;if (options.remote !== undefined) {this.#remoteAuthFlow = options.remote.runAuthFlow;- if (this.#client === undefined) {- throw new Error("A remote TUI requires a configured development client.");- }this.#remoteConnection = createRemoteConnectionController({client: this.#client,credentials: options.remote.credentials,@@ -789,13 +625,19 @@ export class EveTUIRunner {const onStop = () => this.#renderer.requestInterrupt?.();if (this.#lifecycle?.signal.aborted === true) onStop();else this.#lifecycle?.signal.addEventListener("abort", onStop, { once: true });+ const unsubscribe = this.#store.subscribe(() => this.#renderSnapshot());+ attachEveAgentStore(this.#store);try {await this.#run();+ } catch (error) {+ if (!isInterruptedError(error)) throw error;} finally {this.#lifecycle?.signal.removeEventListener("abort", onStop);this.#disposed = true;this.#authProbeAbort.abort();- this.#subagentPump.abortAll();+ this.#inputController?.abort();+ unsubscribe();+ detachEveAgentStore(this.#store);// Restore captured stdout/stderr before a fatal error reaches the CLI.this.#renderer.shutdown?.();// Drops any in-flight link probe so a late resolution cannot paint@@ -809,10 +651,6 @@ export class EveTUIRunner {async #run() {const title = this.#name;let prompt: string | undefined;- let pendingInputResponses: readonly InputResponse[] | undefined;- let hasRunTurn = false;- let followCurrentSession = false;- let streamWithoutPrompt = false;this.#renderer.setStartupPhase?.("starting");await this.#loadInitialAgentInfo();// Fire-and-forget: the link identity is network-bound to resolve, and the@@ -870,387 +708,324 @@ export class EveTUIRunner {this.#finishCommand({ kind: "result", message: startupOutcome.message });}- while (true) {- if (this.#lifecycle?.signal.aborted === true || this.#renderer.exitRequested?.() === true) {- return;+ // One loop for everything that takes the keyboard. The store streams the+ // session throughout, so the composer stays open while work runs.+ while (this.#lifecycle?.signal.aborted !== true && this.#renderer.exitRequested?.() !== true) {+ if (this.#store.snapshot.data.sessionFailed) {+ this.#replaceSession();+ continue;}- const pendingRegistrySetup = this.#pendingRegistrySetups[0];- if (- pendingRegistrySetup !== undefined &&- pendingInputResponses === undefined &&- this.#idleInputResult === undefined- ) {- this.#pendingRegistrySetups.shift();- this.#activeRegistrySetup = pendingRegistrySetup;+ // Answering first lets the agent continue while setup owns the terminal.+ if (this.#answerableInputs().length > 0) {+ await this.#answerInputs(title);+ continue;+ }+ // Setup takes the terminal, so it waits for the session to settle.+ const registrySetup = isWorking(this.#store.snapshot.status)+ ? undefined+ : this.#pendingRegistrySetups.shift();+ if (registrySetup !== undefined) {+ this.#activeRegistrySetup = registrySetup;try {- await this.#openRegistrySetup(pendingRegistrySetup);+ await this.#openRegistrySetup(registrySetup);} finally {this.#activeRegistrySetup = undefined;}- followCurrentSession = false;- streamWithoutPrompt = false;- prompt = undefined;continue;}- if (!streamWithoutPrompt) {- if (prompt == null) {- if (!this.#renderer.readPrompt) {- if (hasRunTurn) {- return;- }-- throw new Error(- "No prompt was provided and the renderer does not support prompt input.",- );- }-- const promptOptions: AgentTUISessionOptions = { title };- if (initialDraft !== undefined) {- promptOptions.initialDraft = initialDraft;- initialDraft = undefined;- }-- try {- this.#readingPrompt = true;- prompt = await this.#readPromptFollowingSession(promptOptions);- } catch (error) {- if (isInterruptedError(error)) {- if (this.#idleInputResult === undefined && this.#pendingRegistrySetups.length === 0) {- return;- }- streamWithoutPrompt = true;- prompt = "";- } else {- throw error;- }- } finally {- this.#readingPrompt = false;- }-- if (this.#pendingRegistrySetups.length > 0 && this.#idleInputResult === undefined) {- prompt = undefined;- continue;- }- if (prompt == null && this.#idleInputResult === undefined) {- return;- }- }-- const command = this.#idleInputResult === undefined ? parsePromptCommand(prompt!) : null;-- if (command?.type === "exit") {- this.#finishCommand({ kind: "dismiss" });- this.#lifecycle?.requestStop();- return;- }-- if (command?.type === "cancel") {- followCurrentSession = await this.#runSessionCommand({- absent: "No active turn to cancel",- accepted: "Cancellation requested",- failed: "Couldn't cancel the turn",- invoke: (session) => session.cancel(),- });- pendingInputResponses = undefined;- streamWithoutPrompt = false;- prompt = undefined;- if (!followCurrentSession) continue;- }-- if (command?.type === "reset") {- if (!(await this.#resetCurrentSession())) {- pendingInputResponses = undefined;- streamWithoutPrompt = false;- prompt = undefined;- continue;- }- this.#finishCommand({ kind: "dismiss" });- pendingInputResponses = undefined;- streamWithoutPrompt = false;- prompt = undefined;+ if (prompt === undefined) {+ const input = await this.#readInput({ title, initialDraft });+ initialDraft = undefined;+ if (input === undefined) continue;+ if (input.type === "cancel") {+ this.#cancelTurn();continue;}-- if (command?.type === "compact") {- followCurrentSession = await this.#runSessionCommand({- absent: "No active session to compact",- accepted: "Compaction requested",- failed: "Couldn't compact the session",- invoke: (session) => session.compact(),- });- pendingInputResponses = undefined;- streamWithoutPrompt = false;- prompt = undefined;- if (!followCurrentSession) continue;- }-- if (command?.type === "clear") {- followCurrentSession = await this.#runSessionCommand({- absent: "No active session to clear",- failed: "Couldn't clear the session",- dismissOnAccepted: true,- invoke: (session) => session.clear(),- });- pendingInputResponses = undefined;- streamWithoutPrompt = false;- prompt = undefined;- if (!followCurrentSession) continue;- }-- // Help renders locally; unlike extension commands it must work even- // without a prompt-command handler (e.g. remote --url sessions).- if (command?.type === "help") {- if (this.#renderer.choosePromptCommand !== undefined) {- const selected = await this.#renderer.choosePromptCommand!(- this.#availablePromptCommands,- );- if (selected !== undefined) initialDraft = selected;- } else- this.#finishCommand({- kind: "result",- message: formatPromptCommandHelp(this.#availablePromptCommands),- });- pendingInputResponses = undefined;- streamWithoutPrompt = false;- prompt = undefined;- continue;- }-- if (command?.type === "info") {- await this.#showApplicationInfo();- pendingInputResponses = undefined;- streamWithoutPrompt = false;- prompt = undefined;- continue;- }-- // Like /help, /loglevel renders locally: it adjusts the renderer's- // own log filter, so it works without a prompt-command handler.- if (command?.type === "loglevel") {- const outcome = this.#applyLogLevelCommand(command.argument);- const error =- outcome.startsWith("/loglevel is not available") ||- outcome.startsWith("Unknown log level");- this.#finishCommand(- error ? { kind: "result", message: outcome } : { kind: "result", summary: outcome },+ if (input.type === "interrupt") {+ this.#replaceSession(+ "Stopped following the turn and started a new session. Earlier context was cleared; the interrupted turn may still be running on the server.",);- pendingInputResponses = undefined;- streamWithoutPrompt = false;- prompt = undefined;- continue;- }-- // /traces is renderer-local too: the viewer reads the local spool- // from disk and owns the screen until the user closes it.- if (command?.type === "traces") {- await this.#openTraceViewer(command.argument);- pendingInputResponses = undefined;- streamWithoutPrompt = false;- prompt = undefined;continue;}-- if (command?.type === "extension") {- try {- await this.#executeExtensionCommand(command, title, { trigger: "command" });- } catch (error) {- if (isInterruptedError(error)) return;- throw error;- }- pendingInputResponses = undefined;- prompt = undefined;- streamWithoutPrompt = false;- continue;- }-- hasRunTurn = true;+ prompt = input.text;}-- 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;- if (acceptedSessionId !== undefined) {- this.#renderer.setSessionId?.(acceptedSessionId);+ const text = prompt;+ prompt = undefined;+ const command = parsePromptCommand(text);+ if (command === null) {+ this.#submitMessage(text);+ continue;}- let submittedPrompt = prompt;- let respondedToInputRequest = false;+ const outcome = await this.#runCommand(command, title);+ if (outcome === "exit") return;+ if (outcome !== undefined) initialDraft = outcome.draft;+ }+ }- try {- while (true) {- await this.#renderer.renderStream(result, {- title,- submittedPrompt,- continueSession: Boolean(this.#renderer.readPrompt),- tools: this.#tools,- reasoning: this.#reasoning,- connectionAuth: this.#connectionAuth,- assistantResponseStats: this.#assistantResponseStats,- contextSize: this.#contextSize,+ /** Runs one slash command; returns `"exit"` or a draft for the next prompt. */+ async #runCommand(+ command: PromptCommand,+ title: string,+ ): Promise<"exit" | { draft: string } | undefined> {+ switch (command.type) {+ case "exit":+ this.#finishCommand({ kind: "dismiss" });+ this.#lifecycle?.requestStop();+ return "exit";+ case "cancel": {+ const working = isWorking(this.#store.snapshot.status);+ if (working) this.#cancelTurn();+ this.#finishCommand({+ kind: "result",+ summary: working ? "Cancellation requested" : "No active turn to cancel",+ });+ return;+ }+ case "reset":+ await this.#resetSession();+ return;+ case "compact":+ await this.#runSessionCommand({+ absent: "No active session to compact",+ accepted: "Compaction requested",+ failed: "Couldn't compact the session",+ invoke: () => this.#store.compact(),+ });+ return;+ case "clear":+ await this.#runSessionCommand({+ absent: "No active session to clear",+ failed: "Couldn't clear the session",+ dismissOnAccepted: true,+ invoke: () => this.#store.clear(),+ });+ return;+ // Help renders locally; unlike extension commands it must work even+ // without a prompt-command handler (e.g. remote --url sessions).+ case "help": {+ if (this.#renderer.choosePromptCommand === undefined) {+ this.#finishCommand({+ kind: "result",+ message: formatPromptCommandHelp(this.#availablePromptCommands),});-- const approvalRequests = result.turnState?.pendingApprovals ?? [];- const questionRequests = result.turnState?.pendingQuestions ?? [];-- if (approvalRequests.length > 0 || questionRequests.length > 0) {- const responses: InputResponse[] = [];-- if (approvalRequests.length > 0) {- if (!this.#renderer.readToolApproval) {- throw new Error(- "Tool approval was requested, but the renderer does not support tool approval input.",- );- }-- for (const request of approvalRequests) {- const response = await this.#renderer.readToolApproval(request, { title });- responses.push({- requestId: request.approvalId,- optionId: response.approved ? "approve" : "cancel",- });- }- }-- if (questionRequests.length > 0) {- if (!this.#renderer.readInputQuestion) {- throw new Error(- "An interactive question was requested, but the renderer does not support input questions.",- );- }-- for (const inputRequest of questionRequests) {- const question = toAgentTUIInputQuestion(inputRequest);- const response = await this.#renderer.readInputQuestion(question, { title });- if (response === undefined) {- continue;- }- const inputResponse: InputResponse = { requestId: inputRequest.requestId };- if (response.optionId !== undefined) inputResponse.optionId = response.optionId;- if (response.text !== undefined) inputResponse.text = response.text;- responses.push(inputResponse);- }- }-- if (responses.length === 0) {- // Every pending question was skipped without an answer. Fall- // back to the prompt rather than sending an empty response set:- // the questions stay open, and the server decides whether the- // user's next message answers them or steers the turn.- break;- }-- streamWithoutPrompt = true;- pendingInputResponses = responses;- prompt = undefined;- respondedToInputRequest = true;- break;- }-- if (this.#enterPendingConnectionAuthorization(result)) {- result = this.#streamCurrentSession();- submittedPrompt = undefined;- continue;- }-- if (result.turnState && result.turnState.boundaryEvent === undefined) {- if (!result.turnState.aborted) {- const strandedSessionId = this.#session?.state.sessionId;- this.#renderer.renderNotice?.(- strandedSessionId- ? `Lost the event stream — the turn may still be running on the server (session ${strandedSessionId}). Your next message resumes this session; use /cancel to stop the turn.`- : "Lost the connection to the running turn.",- );- }- }- break;- }- } catch (error) {- if (isInterruptedError(error)) {return;}-- throw error;+ const selected = await this.#renderer.choosePromptCommand(this.#availablePromptCommands);+ return selected === undefined ? undefined : { draft: selected };}-- if (respondedToInputRequest) {- continue;+ case "info":+ await this.#showApplicationInfo();+ return;+ // Like /help, /loglevel renders locally: it adjusts the renderer's own+ // log filter, so it works without a prompt-command handler.+ case "loglevel": {+ const outcome = this.#applyLogLevelCommand(command.argument);+ const error =+ outcome.startsWith("/loglevel is not available") ||+ outcome.startsWith("Unknown log level");+ this.#finishCommand(+ error ? { kind: "result", message: outcome } : { kind: "result", summary: outcome },+ );+ return;}+ // /traces is renderer-local too: the viewer reads the local spool from+ // disk and owns the screen until the user closes it.+ case "traces":+ await this.#openTraceViewer(command.argument);+ return;+ case "extension":+ await this.#executeExtensionCommand(command, title, { trigger: "command" });+ return;+ }+ }- followCurrentSession = false;- streamWithoutPrompt = false;- pendingInputResponses = undefined;- prompt = undefined;+ /** Sends a message; while work runs it steers the active turn instead. */+ #submitMessage(message: string): void {+ const snapshot = this.#store.snapshot;+ const steering = isWorking(snapshot.status);+ this.#sentMessage = message;+ if (!steering) this.#cancelRequested = false;+ const input: SendTurnPayload = steering+ ? { message, turnPolicy: "steer" }+ : snapshot.session === undefined+ ? { message }+ : { message, turnPolicy: "queue" };+ void this.#store.send(input).catch((error: unknown) => {+ if (this.#disposed || isAbortError(error)) return;+ this.#renderer.renderError?.(+ steering ? "Steering failed" : "Error",+ this.#formatTransportError(error),+ );+ });+ }- // A staged key-driven steer message, or messages queued during the turn,- // submit immediately as the next turn — but only across a clean turn- // boundary. A failed session or a lost stream keeps them; the renderer- // 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 (- !currentSessionFailed &&- (boundaryEvent === "session.waiting" || boundaryEvent === "session.completed")- ) {- prompt = this.#renderer.takeQueuedPrompt?.();- }+ /** Refreshes local dev artifacts so a new turn runs the latest authored code. */+ async #prepareSend(input: SendTurnPayload): Promise<SendTurnPayload> {+ // A steered message joins the running turn, which keeps its artifacts.+ if (input.turnPolicy === "steer") return input;+ if (this.#runtimeArtifacts !== undefined) {+ await this.#runtimeArtifacts.refresh({+ inputResponses: input.inputResponses,+ message: typeof input.message === "string" ? input.message : undefined,+ onRuntimeArtifactsChanged: () => this.#handleRuntimeArtifactsChanged(),+ });+ }+ if (input.message !== undefined) this.#renderer.flushDelayedDevBuildErrors?.();+ return input;+ }- // The session ended terminally this turn (session.failed, a dispatch- // 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.- this.#recoverFailedSession(result.turnState?.aborted === true);+ #renderSnapshot(): void {+ const snapshot = this.#store.snapshot;+ this.#renderer.renderConversation?.(+ conversationView(snapshot, this.#appRoot === undefined ? undefined : localFailureHint),+ );+ this.#reportSessionError(snapshot.error, snapshot.data.sessionFailed);+ this.#recordAgentToolFailures(snapshot.conversation);+ this.#reportFirstResponse(snapshot.conversation);+ this.#queueRegistryHandoffs(snapshot.conversation);+ this.#restoreCancelledMessage(snapshot.conversation);+ if (+ snapshot.data.sessionFailed ||+ this.#answerableInputs().length > 0 ||+ (!isWorking(snapshot.status) && this.#pendingRegistrySetups.length > 0)+ ) {+ this.#inputController?.abort();}}+ /** A turn cancelled from outside this prompt hands its message back instead of losing it. */+ #restoreCancelledMessage(conversation: ConversationState): void {+ const sent = this.#sentMessage;+ if (sent === undefined) return;+ const message = conversation.messages.findLast((candidate) => candidate.role === "user");+ const turnId = message?.metadata?.turnId;+ if (message === undefined || turnId === undefined || userText(message) !== sent) return;+ const status = conversation.turns[turnId]?.status;+ if (status === undefined || status === "active") return;+ this.#sentMessage = undefined;+ if (status === "cancelled" && !this.#cancelRequested) this.#renderer.restoreDraft?.(sent);+ }++ /** Session failures render from the conversation; other errors get one block each. */+ #reportSessionError(error: Error | undefined, sessionFailed: boolean): void {+ if (error === undefined || error === this.#reportedError) return;+ this.#reportedError = error;+ if (sessionFailed) return;+ this.#remoteConnection?.reportFailure(error);+ this.#renderer.renderError?.("Error", this.#formatTransportError(error));+ }++ #reportFirstResponse(conversation: ConversationState): void {+ if (!this.#onboard || this.#reportedFirstResponse) return;+ const responded = conversation.messages.some(+ (message) =>+ message.role === "assistant" &&+ message.parts.some((part) => part.type === "text" && part.text.length > 0),+ );+ if (!responded) return;+ this.#reportedFirstResponse = true;+ this.#onOnboardingStep?.({ flow: "onboarding", step: "first_response" });+ }++ /** Open requests the user can answer now, including while other work runs. */+ #answerableInputs(): readonly ConversationInput[] {+ return openConversationInputs(this.#store.snapshot.conversation).filter(+ (input) => !this.#dismissedInputs.has(input.request.requestId),+ );+ }+/**- * Resets all per-conversation runner state and, when a client is- * available, replaces the active session with a fresh one so the next- * turn starts a new server-side conversation. Backs the `/reset` command.- * In-flight subagent child-session streams are aborted.+ * Prompts for open requests one at a time and sends each answer as it is given, so an agent+ * waiting on one answer resumes without waiting for the rest.*/- #startNewSession(): void {- this.#subagentPump.abortAll();- this.#pendingInputRequests.clear();- this.#connectionAuthRuns.clear();- this.#pendingConnectionAuths.clear();- this.#renderer.setConnectionAuthPendingCount?.(0);-- this.#session = undefined;- this.#runtimeArtifacts?.clear();+ async #answerInputs(title: string): Promise<void> {+ for (let answered = 0; ; answered += 1) {+ const inputs = this.#answerableInputs();+ const input = inputs[0];+ if (input === undefined) return;+ const context = inputContext(input, answered + 1, answered + inputs.length);+ const response = await this.#readInputResponse(input.request, context, title);+ if (response === undefined) {+ // A skipped question stays open; the server decides whether the+ // user's next message answers, dismisses, or leaves it.+ this.#dismissedInputs.add(input.request.requestId);+ continue;+ }+ void this.#store.send({ inputResponses: [response] }).catch((error: unknown) => {+ if (this.#disposed || isAbortError(error)) return;+ this.#renderer.renderError?.("Error", this.#formatTransportError(error));+ });+ }}- /** 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.",+ async #readInputResponse(+ request: InputRequest,+ context: AgentTUIInputContext | undefined,+ title: string,+ ): Promise<InputResponse | undefined> {+ if (request.kind === "tool-approval") {+ if (!this.#renderer.readToolApproval) {+ throw new Error(+ "Tool approval was requested, but the renderer does not support tool approval input.",+ );+ }+ const response = await this.#renderer.readToolApproval(+ toAgentTUIToolApprovalRequest(request, context),+ { title },+ );+ return { requestId: request.requestId, optionId: response.approved ? "approve" : "cancel" };+ }+ if (!this.#renderer.readInputQuestion) {+ throw new Error(+ "An interactive question was requested, but the renderer does not support input questions.",);- } else if (this.#renderer.renderSessionBoundary !== undefined) {+ }+ const response = await this.#renderer.readInputQuestion(+ toAgentTUIInputQuestion(request, context),+ { title },+ );+ if (response === undefined) return undefined;+ const inputResponse: InputResponse = { requestId: request.requestId };+ if (response.optionId !== undefined) inputResponse.optionId = response.optionId;+ if (response.text !== undefined) inputResponse.text = response.text;+ return inputResponse;+ }++ /**+ * Starts a fresh session after the current one ended or was abandoned. The+ * transcript stays on screen; server-side context is gone with the old+ * session.+ */+ #replaceSession(notice?: string): void {+ if (this.#renderer.renderSessionBoundary !== undefined) {this.#renderer.renderSessionBoundary();- } else {+ } else if (notice === undefined) {this.#renderer.renderNotice?.("Session ended — started a new session. Earlier context was cleared.",);}+ if (notice !== undefined) this.#renderer.renderNotice?.(notice);+ this.#resetConversation();+ }++ #resetConversation(): void {+ this.#store.reset();+ this.#clearRunnerState();+ }++ #clearRunnerState(): void {+ this.#dismissedInputs.clear();+ this.#handledHandoffs.clear();+ this.#recordedFailures.clear();+ this.#runtimeArtifacts?.clear();+ }++ /** Cancels the running turn without holding the composer; the store waits for its turn ID. */+ #cancelTurn(): void {+ this.#cancelRequested = true;+ void this.#store.cancel().catch((error: unknown) => {+ this.#renderer.renderNotice?.(`Couldn't cancel the turn: ${toErrorMessage(error)}`);+ });}/** Runs a session mutation and gives every control command one completion policy. */@@ -1259,63 +1034,72 @@ export class EveTUIRunner {readonly accepted?: string;readonly failed: string;readonly dismissOnAccepted?: boolean;- readonly invoke: (session: ClientSession) => Promise<{ status: string }>;- }): Promise<boolean> {- const session = this.#session;- if (session === undefined) {+ readonly invoke: () => Promise<{ status: string }>;+ }): Promise<void> {+ if (this.#store.snapshot.session === undefined) {this.#finishCommand({ kind: "result", summary: input.absent });- return false;+ return;}try {- const result = await input.invoke(session);+ const result = await input.invoke();if (result.status !== "accepted") {this.#finishCommand({ kind: "result", summary: input.absent });- return false;+ return;}this.#finishCommand(input.dismissOnAccepted === true? { kind: "dismiss" }: { kind: "result", summary: input.accepted },);- return true;} catch (error) {this.#finishCommand({kind: "result",message: toErrorMessage(error),summary: input.failed,});- return false;}}- /** Resets the durable owner before clearing the local conversation view. */- async #resetCurrentSession(): Promise<boolean> {- if (this.#session === undefined) {- this.#startNewSession();- this.#renderer.reset?.();- return true;- }+ /** Retires the durable session before clearing the local conversation view. */+ async #resetSession(): Promise<void> {try {- await this.#session.reset();+ await this.#store.retire();} catch (error) {this.#finishCommand({kind: "result",message: `Couldn't reset the session: ${toErrorMessage(error)}`,});- return false;+ return;}-- this.#startNewSession();+ this.#clearRunnerState();this.#renderer.reset?.();- return true;+ this.#finishCommand({ kind: "dismiss" });}- async #readPromptWithIdleRefresh(options: AgentTUISessionOptions): Promise<string | undefined> {- if (!this.#renderer.readPrompt) {- return undefined;+ /**+ * Reads the composer, closing it when a request or setup needs the keyboard.+ * Resolves `undefined` only for that runner-owned close; a renderer that+ * ends input on its own ends the session.+ */+ async #readInput(options: AgentTUISessionOptions): Promise<AgentTUIInput | undefined> {+ if (!this.#renderer.readInput) {+ throw new Error("The renderer does not support prompt input.");+ }+ const controller = new AbortController();+ this.#inputController = controller;+ try {+ const input = await this.#withIdleRefresh(+ this.#renderer.readInput({ ...options, signal: controller.signal }),+ );+ if (input === undefined && !controller.signal.aborted) throw interruptedError();+ return input;+ } finally {+ if (this.#inputController === controller) this.#inputController = undefined;}+ }- const prompt = this.#renderer.readPrompt(options);+ /** Polls local dev artifacts while the composer is open, so HMR stays current. */+ async #withIdleRefresh<T>(prompt: Promise<T>): Promise<T> {const runtimeArtifacts = this.#runtimeArtifacts;if (runtimeArtifacts === undefined) {return await prompt;@@ -1389,287 +1173,17 @@ 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;- let reconnectDelayMs = idleSessionReconnectBaseDelayMs;- while (!signal.aborted) {- const source = sourceSession.stream({ signal })[Symbol.asyncIterator]();- let deliveredEvent = false;- 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;- deliveredEvent = 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 (- result.turnState?.boundaryEvent === "session.completed" ||- result.turnState?.boundaryEvent === "session.failed"- ) {- return;- }- if (!consumed) break;- }- } finally {- await source.return?.();- }- reconnectDelayMs = deliveredEvent- ? idleSessionReconnectBaseDelayMs- : Math.min(reconnectDelayMs * 2, idleSessionReconnectMaxDelayMs);- if (!signal.aborted) await abortableDelay(reconnectDelayMs, signal);- }- }-- async #streamTurn(input: {- prompt: string | undefined;- inputResponses: readonly InputResponse[] | undefined;- }): Promise<AgentTUIStreamResult> {- // Backs the result's `abort`: lifecycle interruption fires it so the- // in-flight stream read settles instead of dangling until server close.- const abortController = new AbortController();- const sendInput: {- message?: string;- inputResponses?: readonly InputResponse[];- signal?: AbortSignal;- } = { signal: abortController.signal };- if (input.prompt !== undefined) sendInput.message = input.prompt;- if (input.inputResponses !== undefined && input.inputResponses.length > 0) {- sendInput.inputResponses = input.inputResponses;- }-- let response: Awaited<ReturnType<ClientSession["send"]>>;- const sourceSession = this.#session;- try {- if (this.#runtimeArtifacts !== undefined) {- await this.#runtimeArtifacts.refresh({- inputResponses: sendInput.inputResponses,- message: sendInput.message,- onRuntimeArtifactsChanged: () => this.#handleRuntimeArtifactsChanged(),- });- }-- if (sendInput.message !== undefined && (sendInput.inputResponses?.length ?? 0) === 0) {- this.#renderer.flushDelayedDevBuildErrors?.();- }-- if (this.#session === undefined) {- if (this.#client === undefined) {- throw new Error("Cannot create a session without an eve client.");- }- if (sendInput.message === undefined) {- throw new Error("Cannot answer an input request before the session starts.");- }- const created = await this.#client.sessions.create({- ...sendInput,- message: sendInput.message,- });- this.#session = created.session;- response = created.response;- } else {- response =- sendInput.inputResponses === undefined- ? await this.#session.send(sendInput.message!, {- signal: sendInput.signal,- turnPolicy: "queue",- })- : await this.#session.respond(sendInput.inputResponses, { signal: sendInput.signal });- }- } catch (error) {- if (isInterruptedError(error)) throw error;- // Dispatching the turn failed before any stream opened (transport- // error, auth challenge, …). Surface it through the same error path- // as in-stream failures so it renders as an inline region right- // 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.#failedSession = sourceSession;- return {- events: errorOnlyTUIStream({- errorText: this.#formatTransportError(error),- }),- turnState: createTurnState(),- };- }-- return this.#createTUIStreamResult(response, () => abortController.abort(), this.#session);- }-- /**- * Requests cooperative cancellation of the streaming turn and retries- * while the turn stays live. A key-driven cancel that lands before the owner- * begins the turn (i.e. before `turn.started` reaches the client) resolves as a- * benign `no_active_turn` and would otherwise be silently lost, leaving- * the TUI showing "Cancelling…" while the turn runs to completion.- * Retrying until the stream reaches its boundary closes that window.- *- * Once `turn.started` names the turn, each retry carries its id, so a- * GUARDED retry that outlives the boundary is a benign no-op. An- * UNGUARDED attempt (turnId not yet known) has a residual race: if this- * turn's boundary, the queue drain, and the next turn's dispatch all- * complete while the request is in flight, the cancel can land on the- * next turn. Closing it needs turn-scoped cancel admission server-side- * (the #867 ledger); until then the renderer backstops it — a- * `turn.cancelled` arriving without a local cancel request in that stream- * 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,- sourceSession: ClientSession | undefined,- ): Promise<void> {- if (turnState.cancelInFlight === true) return;- turnState.cancelInFlight = true;- try {- for (let attempt = 0; attempt < turnCancelAttempts; attempt += 1) {- if (turnState.boundaryEvent !== undefined || turnState.aborted === true) return;- const turnId = turnState.turnId;- try {- 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;- } catch {- // No accepted session yet or a transport failure — retry below;- // lifecycle interruption remains the hard client-side escape hatch.- }- await delayMs(turnCancelRetryDelayMs);+ /** Queues setup for registry items whose install needs the terminal. */+ #queueRegistryHandoffs(conversation: ConversationState): void {+ if (this.#appRoot === undefined) return;+ for (const { callId, address } of registryHandoffs(conversation)) {+ if (this.#handledHandoffs.has(callId)) continue;+ this.#handledHandoffs.add(callId);+ if (this.#activeRegistrySetup === address || this.#pendingRegistrySetups.includes(address)) {+ continue;}- } finally {- turnState.cancelInFlight = false;- }- }-- /** Follows the current session without dispatching another turn. */- #streamCurrentSession(): AgentTUIStreamResult {- if (this.#session === undefined) {- throw new Error("Cannot stream a session before its first turn is accepted.");+ this.#pendingRegistrySetups.push(address);}- const abortController = new AbortController();- const sourceSession = this.#session;- return this.#createTUIStreamResult(- sourceSession.stream({ signal: abortController.signal }),- () => abortController.abort(),- sourceSession,- );- }-- #createTUIStreamResult(- events: AsyncIterable<MessageStreamEvent>,- abort: () => void,- sourceSession: ClientSession | undefined,- ): AgentTUIStreamResult {- const turnState = createTurnState();- const steering =- sourceSession === undefined ? undefined : new SteeringStream(events, sourceSession);- return {- steer: steering === undefined ? undefined : (message) => steering.send(message),- abort: () => {- turnState.aborted = true;- this.#failedSession = sourceSession;- steering?.abort();- abort();- },- cancel: () => {- void this.#requestTurnCancellation(turnState, sourceSession);- },- events: eveEventsToTUIStream({- onAssistantResponse: () => {- if (this.#onboard && !this.#reportedFirstResponse) {- this.#reportedFirstResponse = true;- this.#onOnboardingStep?.({ flow: "onboarding", step: "first_response" });- }- },- events: steering ?? events,- pendingInputRequests: this.#pendingInputRequests,- turnState,- onTaskStarted: (event) =>- this.#subagentPump.taskStarted(event, sourceSession?.state.sessionId),- onAgentStarted: (event) =>- this.#subagentPump.agentStarted(event, sourceSession?.state.sessionId),- onTurnCancelled: (turnId) => this.#subagentPump.settleCancelledTurn(turnId),- onConnectionAuthRequired: (event) => this.#handleConnectionAuthRequired(event),- onConnectionAuthCompleted: (event) => this.#handleConnectionAuthCompleted(event),- onRegistryHandoff:- this.#appRoot === undefined- ? undefined- : async (address) => this.#queueRegistrySetup(address),- onTerminalFailure: () => {- this.#failedSession = sourceSession;- },- failureHintOverride: this.#appRoot === undefined ? undefined : localFailureHint,- }),- turnState,- };- }-- #queueRegistrySetup(address: string): void {- if (this.#activeRegistrySetup === address || this.#pendingRegistrySetups.includes(address)) {- return;- }- this.#pendingRegistrySetups.push(address);- if (this.#readingPrompt) this.#renderer.suspendPromptForInput?.();}async #openRegistrySetup(address: string): Promise<void> {@@ -1900,7 +1414,7 @@ export class EveTUIRunner {try {await this.#renderer.traceViewer.open({appRoot: this.#appRoot,- sessionId: this.#session?.state.sessionId,+ sessionId: this.#store.snapshot.session?.sessionId,reference: argument === "" ? undefined : argument,});} catch (error) {@@ -2011,73 +1525,79 @@ export class EveTUIRunner {void this.#refreshAgentInfo(true);}- #handleConnectionAuthRequired(event: AuthorizationRequiredStreamEvent): void {- const run: ConnectionAuthRun = {- name: event.data.name,- description: event.data.description,- state: "required",- };- if (event.data.authorization !== undefined) {- run.challenge = event.data.authorization;- }- if (event.data.webhookUrl !== undefined) {- run.webhookUrl = event.data.webhookUrl;- }- this.#connectionAuthRuns.set(event.data.name, run);- this.#emitConnectionAuthUpdate(run);- }-- /**- * Marks framework-owned OAuth challenges as parked only after the current- * turn has reached its `session.waiting` boundary. A `webhookUrl` is the- * runtime's proof that a later callback turn can complete the challenge.- */- #enterPendingConnectionAuthorization(result: AgentTUIStreamResult): boolean {- if (result.turnState?.boundaryEvent !== "session.waiting") {- return false;- }-- let added = false;- for (const run of this.#connectionAuthRuns.values()) {- if (run.state !== "required" || run.webhookUrl === undefined) continue;- run.state = "pending";- this.#pendingConnectionAuths.add(run.name);- this.#emitConnectionAuthUpdate(run);- added = true;- }-- if (added) {- this.#renderer.setConnectionAuthPendingCount?.(this.#pendingConnectionAuths.size);+ /** Agents' own tool failures reach the diagnostics log whatever the subagent display mode. */+ #recordAgentToolFailures(conversation: ConversationState): void {+ const diagnostics = this.#diagnostics;+ if (diagnostics === undefined) return;+ for (const agent of Object.values(conversation.agents)) {+ if (agent.observation.status === "not-followed") continue;+ for (const message of agent.observation.conversation?.messages ?? []) {+ for (const part of message.parts) {+ if (part.type !== "dynamic-tool" || part.state !== "output-error") continue;+ if (this.#recordedAgentToolFailures.has(part.toolCallId)) continue;+ this.#recordedAgentToolFailures.add(part.toolCallId);+ diagnostics.append({+ source: "tool",+ summary: `${part.toolName} failed (subagent ${agent.name})`,+ detail: part.errorText,+ });+ }+ }}- return this.#pendingConnectionAuths.size > 0;}- #handleConnectionAuthCompleted(event: AuthorizationCompletedStreamEvent): void {- const existing = this.#connectionAuthRuns.get(event.data.name);- const run: ConnectionAuthRun = existing ?? {- name: event.data.name,- description: "",- state: event.data.outcome,- };- run.state = event.data.outcome;- if (event.data.reason !== undefined) {- run.reason = event.data.reason;+ /** Records session activity that the diagnostics log keeps regardless of display. */+ #recordDiagnostics(event: MessageStreamEvent): void {+ const diagnostics = this.#diagnostics;+ if (diagnostics === undefined) return;+ switch (event.type) {+ case "turn.started":+ this.#recordedFailures.clear();+ break;+ case "actions.requested":+ for (const action of event.data.actions) {+ const descriptor = normalizeActionRequest(action);+ if (descriptor.kind === "tool-call") diagnostics.recordToolCall(descriptor.toolName);+ }+ break;+ case "action.result":+ if (isTaskRetryRefusal(event)) {+ diagnostics.append({+ source: "tool",+ summary: `${normalizeActionResult(event.data.result).toolName} was refused for the model to retry`,+ detail: event.data.error?.message ?? "Refused.",+ });+ } else if (event.data.status === "failed") {+ diagnostics.append({+ source: "tool",+ summary: `${normalizeActionResult(event.data.result).toolName} failed`,+ detail: event.data.error?.message ?? "Tool failed.",+ });+ }+ break;+ case "agent.started":+ diagnostics.recordSubagentDispatch(event.data.callId);+ break;+ case "step.completed":+ diagnostics.recordStepUsage(event.data.usage);+ break;+ case "step.failed":+ case "turn.failed":+ case "session.failed": {+ const key = failureKey(event);+ if (this.#recordedFailures.has(key)) break;+ this.#recordedFailures.add(key);+ const message = formatFailureMessage(event);+ const detail = formatFailureDetail(event) ?? message;+ const hint = formatFailureHint(event);+ diagnostics.append(+ hint === undefined+ ? { source: "workflow", summary: `Error: ${message}`, detail }+ : { source: "workflow", summary: `Error: ${message}`, detail, hint },+ );+ break;+ }}- this.#connectionAuthRuns.set(event.data.name, run);- this.#pendingConnectionAuths.delete(event.data.name);- this.#emitConnectionAuthUpdate(run);- this.#renderer.setConnectionAuthPendingCount?.(this.#pendingConnectionAuths.size);- }-- #emitConnectionAuthUpdate(run: ConnectionAuthRun): void {- const update: ConnectionAuthUpdate = {- name: run.name,- description: run.description,- state: run.state,- };- if (run.challenge !== undefined) update.challenge = run.challenge;- if (run.reason !== undefined) update.reason = run.reason;- this.#renderer.upsertConnectionAuth?.(update);}}@@ -2120,26 +1640,30 @@ function formatAgentUpdateNotice(return "Agent updated.";}-type EveStreamTranslatorInput = {- events: AsyncIterable<MessageStreamEvent>;- onAssistantResponse?: () => void;- pendingInputRequests: Map<string, InputRequest>;- turnState: AgentTUITurnState;- onTaskStarted?: (event: TaskStartedStreamEvent) => void;- onAgentStarted?: (event: AgentStartedStreamEvent) => void;- onTurnCancelled?: (turnId: string) => void;- onConnectionAuthRequired?: (event: AuthorizationRequiredStreamEvent) => void;- onConnectionAuthCompleted?: (event: AuthorizationCompletedStreamEvent) => void;- /** Opens a setup-bearing registry item in the existing `/add` flow. */- onRegistryHandoff?: (address: string) => Promise<void>;- onTerminalFailure?: (event: SessionFailedStreamEvent) => void;- /**- * Replaces a failure's structured hint with a surface-local one (the- * local TUI swaps gateway-auth remediation for the in-session `/model`- * fix). Returning `undefined` keeps the hint the harness attached.- */- failureHintOverride?: (event: FailureStreamEvent) => string | undefined;-};+/** Tool results in the conversation that hand a registry install to the terminal. */+function registryHandoffs(+ conversation: ConversationState,+): Array<{ readonly callId: string; readonly address: string }> {+ const handoffs: Array<{ callId: string; address: string }> = [];+ const collect = (state: ConversationState, subagentName: string | undefined) => {+ for (const message of state.messages) {+ for (const part of message.parts) {+ if (!isTerminalToolCallPart(part) || part.state !== "output-available" || part.partial) {+ continue;+ }+ const address = registryHandoffAddress(subagentName, part.toolName, part.output);+ if (address !== undefined) handoffs.push({ callId: part.toolCallId, address });+ }+ }+ };+ collect(conversation, undefined);+ for (const agent of Object.values(conversation.agents)) {+ if (agent.observation.status === "not-followed") continue;+ const child = agent.observation.conversation;+ if (child !== undefined) collect(child, agent.name);+ }+ return handoffs;+}/** Returns the registry address carried by a packaged self-modification terminal handoff. */export function registryHandoffAddress(@@ -2148,7 +1672,7 @@ export function registryHandoffAddress(output: unknown,): string | undefined {const isPackagedChild =- subagentName === SELF_MODIFICATION_AGENT_NAME && toolName === "registry_add";+ subagentName === "self-modification__agent" && toolName === "registry_add";const isLegacyRoot = subagentName === undefined && toolName === "selfmod__registry_add";if ((!isPackagedChild && !isLegacyRoot) || typeof output !== "object" || output === null) {return undefined;@@ -2159,675 +1683,35 @@ export function registryHandoffAddress(: undefined;}-/**- * Reduces one eve session-stream turn into renderer-native TUI events.- * eve events name assistant/reasoning sections by `turnId` + `stepIndex`;- * those ids become stable block ids in the terminal renderer.- */-async function* eveEventsToTUIStream(- input: EveStreamTranslatorInput,-): AsyncIterable<AgentTUIStreamEvent> {- const {- events,- pendingInputRequests,- turnState,- onTaskStarted,- onAgentStarted,- onTurnCancelled,- onConnectionAuthRequired,- onConnectionAuthCompleted,- onRegistryHandoff,- onTerminalFailure,- failureHintOverride,- } = input;- const textParts = new Map<string, StreamPartState>();- const reasoningParts = new Map<string, StreamPartState>();- const toolNames = new Map<string, string>();- // Dropping re-delivered events here means every case below is a new emission.- const seenEvents = createEventDeduper();- // Counts `step.started` and tool events. A part key alone cannot distinguish- // a new message from a re-emission: the harness reuses `stepIndex` across- // the model calls of one turn (e.g. the post-subagent call restarts at the- // same index), and one model call can write text, run a provider-executed- // tool, then write more text under the same key. A new step or tool event- // since the part completed is the discriminator.- let partEpoch = 0;- const knownToolCalls = new Set<string>();- const preparingToolCalls = new Set<string>();- // A task's `action.result` is only its start receipt, written for the- // model; the call settles with `task.settled`.- const taskCallIds = new Set<string>();- const seenInputRequestIds = new Set<string>();- // The harness reports one underlying failure as a cascade (`step.failed` →- // `turn.failed` → `session.failed`) with an identical payload on each- // event. Render it once, not three times.- const emittedFailures = new Set<string>();- let sentFinish = false;- let visibleTurnCompleted = false;- let latestStepUsage: StepCompletedStreamEvent["data"]["usage"] | undefined;-- for await (const event of events) {- if (!seenEvents.admit(event)) {- continue;- }-- if (visibleTurnCompleted && isPostTurnVisibleEvent(event)) {- continue;- }-- switch (event.type) {- case "session.started":- case "message.received":- // Boundary / metadata events with no direct UI surface.- break;-- case "turn.started":- // Recorded so key-driven cancellation can scope its request to the- // turn the user is watching; a cancel that arrives after the- // boundary then no-ops instead of hitting the next turn.- if (event.data.turnId !== turnState.turnId) visibleTurnCompleted = false;- turnState.turnId = event.data.turnId;- yield { type: "turn-start", turnId: event.data.turnId };- break;-- case "step.started":- partEpoch += 1;- yield { type: "step-start", modelId: event.data.modelId };- break;-- case "step.completed": {- const stepEvent = event as StepCompletedStreamEvent;- latestStepUsage = stepEvent.data.usage;- yield* closeOpenParts(textParts, "assistant-complete", partEpoch);- yield* closeOpenParts(reasoningParts, "reasoning-complete", partEpoch);- yield { type: "step-finish", usage: stepEvent.data.usage };- break;- }-- case "message.appended": {- const appended = event as MessageAppendedStreamEvent;- const base = textPartId(appended.data.turnId, appended.data.stepIndex);- const state = partStateFor(textParts, base);-- if (state.completed) {- // No intervening step or tool: a retry of the same model call.- if (partEpoch <= state.completedEpoch) break;- // A fresh model call reusing this part key (the harness restarts- // `stepIndex` after a park/resume, e.g. post-subagent), or text- // after a tool in the same call: open a new message generation so- // it renders as its own block.- state.generation += 1;- state.text = "";- state.completed = false;- }-- const delta = appended.data.messageDelta;- if (delta.length === 0) break;- state.text += delta;- if (delta) input.onAssistantResponse?.();- yield { type: "assistant-delta", id: partGenerationId(base, state.generation), delta };- break;- }-- case "message.completed": {- const base = textPartId(event.data.turnId, event.data.stepIndex);- const state = partStateFor(textParts, base);- const message = event.data.message;-- if (state.completed) {- if (partEpoch <= state.completedEpoch) break;- // Channels that skip per-delta events: a new full message under a- // reused key after a fresh model call.- state.generation += 1;- state.text = message;- state.completedEpoch = partEpoch;- yield {- type: "assistant-complete",- id: partGenerationId(base, state.generation),- text: message,- };- break;- }-- const id = partGenerationId(base, state.generation);- if (state.text.length === 0) {- state.text = message;- state.completed = true;- state.completedEpoch = partEpoch;- yield { type: "assistant-complete", id, text: message };- } else if (message.startsWith(state.text)) {- const suffix = message.slice(state.text.length);- if (suffix.length > 0) {- if (suffix) input.onAssistantResponse?.();- yield { type: "assistant-delta", id, delta: suffix };- }- state.text = message;- state.completed = true;- state.completedEpoch = partEpoch;- yield { type: "assistant-complete", id };- } else {- state.text = message;- state.completed = true;- state.completedEpoch = partEpoch;- yield { type: "assistant-complete", id, text: message };- }- break;- }-- case "reasoning.appended": {- const appended = event as ReasoningAppendedStreamEvent;- const base = reasoningPartId(appended.data.turnId, appended.data.stepIndex);- const state = partStateFor(reasoningParts, base);-- if (state.completed) {- if (partEpoch <= state.completedEpoch) break;- state.generation += 1;- state.text = "";- state.completed = false;- }-- const delta = appended.data.reasoningDelta;- if (delta.length === 0) break;- state.text += delta;- yield { type: "reasoning-delta", id: partGenerationId(base, state.generation), delta };- break;- }-- case "reasoning.completed": {- const base = reasoningPartId(event.data.turnId, event.data.stepIndex);- const state = partStateFor(reasoningParts, base);- const next = event.data.reasoning;-- if (state.completed) {- if (next.length === 0) break;- if (partEpoch <= state.completedEpoch) break;- state.generation += 1;- state.text = next;- state.completedEpoch = partEpoch;- const id = partGenerationId(base, state.generation);- yield { type: "reasoning-delta", id, delta: next };- yield { type: "reasoning-complete", id };- break;- }-- const id = partGenerationId(base, state.generation);- if (state.text.length === 0 && next.length > 0) {- state.text = next;- yield { type: "reasoning-delta", id, delta: next };- } else if (next.length > 0 && !next.startsWith(state.text)) {- yield { type: "reasoning-complete", id };- state.generation += 1;- state.text = next;- state.completed = true;- state.completedEpoch = partEpoch;- const replacementId = partGenerationId(base, state.generation);- yield { type: "reasoning-delta", id: replacementId, delta: next };- yield { type: "reasoning-complete", id: replacementId };- break;- }-- state.completed = true;- state.completedEpoch = partEpoch;- yield { type: "reasoning-complete", id };- break;- }-- case "action.input.appended": {- const { callId, toolName } = event.data;- if (knownToolCalls.has(callId) || preparingToolCalls.has(callId)) break;- if (isTaskControlTool(toolName)) break;- preparingToolCalls.add(callId);- yield { type: "tool-call-preparing", toolCallId: callId, toolName };- break;- }-- case "actions.requested": {- const data = (event as ActionsRequestedStreamEvent).data;- // Nested actions render through their parent call's row and label.- const actions = data.actions.flatMap((action) =>- action.kind === "tool-call" &&- action.parentCallId === undefined &&- !isTaskControlTool(action.toolName)- ? [action]- : [],- );- if (actions.length === 0) break;- partEpoch += 1;-- for (const action of actions) {- toolNames.set(action.callId, action.toolName);- if (knownToolCalls.has(action.callId)) continue;- knownToolCalls.add(action.callId);- const toolCall: Extract<AgentTUIStreamEvent, { type: "tool-call" }> = {- type: "tool-call",- toolCallId: action.callId,- toolName: action.toolName,- input: action.input,- };- const label = data.presentation?.[action.callId]?.label;- if (label !== undefined) toolCall.label = label;- yield toolCall;- }- break;- }-- case "input.requested": {- const data = (event as InputRequestedStreamEvent).data;- const requests = data.requests.filter(- (request) =>- request.action.kind === "tool-call" && !isTaskControlTool(request.action.toolName),- );- if (requests.length === 0) break;-- for (const request of requests) {- const toolCallId = request.action.callId;- toolNames.set(toolCallId, request.action.toolName);-- // The session-limit continuation is harness-authored — no model- // tool call exists behind it, so fabricating a transcript entry- // would render a phantom call. Its question rendering already- // carries the prompt copy.- if (request.kind !== "session-limit" && !knownToolCalls.has(toolCallId)) {- knownToolCalls.add(toolCallId);- yield {- type: "tool-call",- toolCallId,- toolName: request.action.toolName,- input: request.action.input,- };- }-- if (seenInputRequestIds.has(request.requestId)) continue;- seenInputRequestIds.add(request.requestId);- pendingInputRequests.set(request.requestId, request);-- if (request.kind !== "tool-approval") {- upsertPendingQuestion(turnState, request);- continue;- }-- upsertPendingApproval(turnState, request);- yield {- type: "tool-approval-request",- approvalId: request.requestId,- toolCallId,- };- }- break;- }-- case "approval.candidate": {- if (event.data.outcome === "pending") break;- const request = pendingInputRequests.get(event.data.requestId);- if (request !== undefined) upsertPendingApproval(turnState, request);- break;- }-- case "approval.settled":- case "input.resolved": {- const requestIds = new Set(- event.type === "input.resolved"- ? event.data.resolutions.map((resolution) => resolution.requestId)- : [event.data.requestId],- );- for (const requestId of requestIds) pendingInputRequests.delete(requestId);- turnState.pendingApprovals = turnState.pendingApprovals.filter(- (request) => !requestIds.has(request.approvalId),- );- turnState.pendingQuestions = turnState.pendingQuestions.filter(- (request) => !requestIds.has(request.requestId),- );- break;- }-- case "action.result": {- const resultEvent = event as ActionResultStreamEvent;- if (resultEvent.data.result.kind !== "tool-result") {- break;- }- const callId = resultEvent.data.result.callId;- // Results for calls this turn never announced (task control calls,- // or a call first announced to another stream) have no tool block.- if (!knownToolCalls.has(callId) || taskCallIds.has(callId)) break;- if (isTaskRetryRefusal(resultEvent)) {- yield {- type: "tool-withdrawn",- toolCallId: callId,- reason: formatActionResultError(resultEvent),- };- break;- }- partEpoch += 1;- switch (resultEvent.data.status) {- case "completed": {- const output = resultEvent.data.result.output;- const toolResult: Extract<AgentTUIStreamEvent, { type: "tool-result" }> = {- type: "tool-result",- toolCallId: callId,- output,- };- const label = resultEvent.data.presentation?.[callId]?.label;- if (label !== undefined) toolResult.label = label;- yield toolResult;- const address = registryHandoffAddress(undefined, toolNames.get(callId), output);- if (address !== undefined) await onRegistryHandoff?.(address);- break;- }- case "failed":- yield {- type: "tool-error",- toolCallId: callId,- errorText: formatActionResultError(resultEvent),- };- break;- case "rejected":- yield {- type: "tool-rejected",- toolCallId: callId,- reason: formatActionResultError(resultEvent),- };- break;- }- break;- }-- case "step.failed":- case "turn.failed": {- const failure = toFailureEvent(event, emittedFailures, failureHintOverride);- if (failure) yield failure;- break;- }-- case "session.failed": {- // Terminal: the server session is dead. Flag the runner so it can- // recover onto a fresh session before the next prompt.- turnState.sawSessionFailure = true;- onTerminalFailure?.(event as SessionFailedStreamEvent);- const failure = toFailureEvent(event, emittedFailures, failureHintOverride);- if (failure) yield failure;- turnState.boundaryEvent = event.type;- yield* closeOpenParts(textParts, "assistant-complete", partEpoch);- yield* closeOpenParts(reasoningParts, "reasoning-complete", partEpoch);- yield {- type: "finish",- usage: latestStepUsage,- };- sentFinish = true;- return;- }-- case "session.waiting":- case "session.completed":- turnState.boundaryEvent = event.type;- yield* closeOpenParts(textParts, "assistant-complete", partEpoch);- yield* closeOpenParts(reasoningParts, "reasoning-complete", partEpoch);- yield {- type: "finish",- usage: latestStepUsage,- };- sentFinish = true;- return;-- case "turn.waiting":- // The turn stays open; it ends this stream only when a call it runs- // asked something the person must answer first.- if (turnState.pendingApprovals.length === 0 && turnState.pendingQuestions.length === 0) {- break;- }- turnState.boundaryEvent = event.type;- yield* closeOpenParts(textParts, "assistant-complete", partEpoch);- yield* closeOpenParts(reasoningParts, "reasoning-complete", partEpoch);- yield {- type: "finish",- usage: latestStepUsage,- };- sentFinish = true;- return;-- case "turn.completed":- visibleTurnCompleted = true;- yield* closeOpenParts(textParts, "assistant-complete", partEpoch);- yield* closeOpenParts(reasoningParts, "reasoning-complete", partEpoch);- break;-- case "turn.cancelled":- // Explicit cooperative cancellation preserves the session.- // `session.waiting` follows and finishes the stream normally.- onTurnCancelled?.(event.data.turnId);- yield* closeOpenParts(textParts, "assistant-complete", partEpoch);- yield* closeOpenParts(reasoningParts, "reasoning-complete", partEpoch);- yield { type: "turn-cancelled" };- break;-- // Re-delivery within this translator was filtered above; run creation- // and re-entry from a later translator live in the pump. The agent's- // content is observed through its session's stream.- case "task.started":- taskCallIds.add(event.data.callId);- onTaskStarted?.(event);- yield {- type: "task-started",- toolCallId: event.data.callId,- kind: event.data.kind,- toolName: event.data.name,- };- break;-- case "agent.started":- onAgentStarted?.(event);- break;-- case "task.settled": {- const { callId, error, output, status } = event.data;- const settled: Extract<AgentTUIStreamEvent, { type: "task-settled" }> = {- type: "task-settled",- toolCallId: callId,- status,- };- if (output !== undefined) settled.output = output;- if (error !== undefined) settled.errorText = error.message;- yield settled;- break;- }-- case "authorization.required":- onConnectionAuthRequired?.(event as AuthorizationRequiredStreamEvent);- break;-- case "authorization.completed":- onConnectionAuthCompleted?.(event as AuthorizationCompletedStreamEvent);- break;-- default:- // compaction.* — ignored for v1.- break;- }- }-- if (!sentFinish) {- yield* closeOpenParts(textParts, "assistant-complete", partEpoch);- yield* closeOpenParts(reasoningParts, "reasoning-complete", partEpoch);- yield { type: "finish", usage: latestStepUsage };- }-}--/**- * A single-turn stream that carries only an error. Used when dispatching- * the turn throws before any real stream opens, so the failure flows- * through the renderer's normal error path and renders as one inline- * region in transcript order.- */-async function* errorOnlyTUIStream(input: {- errorText: string;-}): AsyncIterable<AgentTUIStreamEvent> {- yield { type: "error", errorText: input.errorText };- yield { type: "finish" };-}--function createTurnState(): AgentTUITurnState {- return {- aborted: false,- pendingApprovals: [],- pendingQuestions: [],- sawSessionFailure: false,- };+function inputContext(+ input: ConversationInput,+ index: number,+ total: number,+): AgentTUIInputContext | undefined {+ const context: AgentTUIInputContext = {};+ if (total > 1) context.position = { index, total };+ if (input.taskId !== undefined) context.taskId = input.taskId;+ return context.position === undefined && context.taskId === undefined ? undefined : context;}-function upsertPendingApproval(state: AgentTUITurnState, request: InputRequest): void {- const approval = toAgentTUIToolApprovalRequest(request);- const index = state.pendingApprovals.findIndex(- (candidate) => candidate.approvalId === approval.approvalId,- );- if (index === -1) {- state.pendingApprovals.push(approval);- } else {- state.pendingApprovals[index] = approval;- }-}--function toAgentTUIToolApprovalRequest(request: InputRequest): AgentTUIToolApprovalRequest {- return {+function toAgentTUIToolApprovalRequest(+ request: InputRequest,+ context: AgentTUIInputContext | undefined,+): AgentTUIToolApprovalRequest {+ const approval: AgentTUIToolApprovalRequest = {approvalId: request.requestId,toolCallId: request.action.callId,toolName: request.action.toolName,input: request.action.input,};+ if (context !== undefined) approval.context = context;+ return approval;}-function upsertPendingQuestion(state: AgentTUITurnState, request: InputRequest): void {- const index = state.pendingQuestions.findIndex(- (candidate) => candidate.requestId === request.requestId,- );- if (index === -1) {- state.pendingQuestions.push(request);- } else {- state.pendingQuestions[index] = request;- }-}--function textPartId(turnId: string, stepIndex: number): string {- return `text:${turnId}:${stepIndex}`;-}--function reasoningPartId(turnId: string, stepIndex: number): string {- return `reasoning:${turnId}:${stepIndex}`;-}--/**- * Per-part-key accumulation state for one assistant text or reasoning trace.- *- * eve names parts by `turnId:stepIndex`, but the harness reuses `stepIndex`- * across the model calls of one turn (the post-park call restarts at the same- * index). `generation` disambiguates: each fresh model call that reuses a- * completed key opens generation N+1, which renders as its own block.- */-type StreamPartState = {- generation: number;- /** Accumulated text of the current generation. */- text: string;- completed: boolean;- /** Value of the part epoch when the current generation completed. */- completedEpoch: number;-};--function partStateFor(parts: Map<string, StreamPartState>, base: string): StreamPartState {- let state = parts.get(base);- if (state === undefined) {- state = {- generation: 0,- text: "",- completed: false,- completedEpoch: 0,- };- parts.set(base, state);- }- return state;-}--/** Generation 0 keeps the bare key so block ids stay stable for the common case. */-function partGenerationId(base: string, generation: number): string {- return generation === 0 ? base : `${base}#${generation}`;-}--/** Closes every still-open generation at a step or turn boundary. */-function* closeOpenParts(- parts: Map<string, StreamPartState>,- type: "assistant-complete" | "reasoning-complete",- partEpoch: number,-): Generator<AgentTUIStreamEvent> {- for (const [base, state] of parts) {- if (state.completed || state.text.length === 0) continue;- state.completed = true;- state.completedEpoch = partEpoch;- yield { type, id: partGenerationId(base, state.generation) };- }-}--function isPostTurnVisibleEvent(event: MessageStreamEvent): boolean {- switch (event.type) {- case "actions.requested":- case "authorization.completed":- case "authorization.required":- case "input.requested":- case "message.appended":- case "message.completed":- case "reasoning.appended":- case "reasoning.completed":- case "result.completed":- case "step.completed":- case "step.failed":- case "step.started":- case "agent.started":- case "task.settled":- case "task.started":- case "turn.completed":- case "turn.failed":- return true;- default:- return false;- }-}--function formatActionResultError(event: ActionResultStreamEvent): string {- if (event.data.error?.message) return event.data.error.message;- const output = event.data.result.output;- if (typeof output === "string") return output;- try {- return JSON.stringify(output);- } catch {- return "Tool execution failed.";- }-}--/**- * Projects one failure event into a renderable `error` stream event, or- * `undefined` when the same underlying failure was already emitted earlier in- * the cascade. Carries the failure as a structured entity: headline, the- * catalog's remediation hint (surface overrides win), and the diagnostic- * dump when the failure carries one — i.e. for unrecognized errors escaping- * user code.- */-function toFailureEvent(- event: FailureStreamEvent,- emittedFailures: Set<string>,- failureHintOverride?: (event: FailureStreamEvent) => string | undefined,-): AgentTUIStreamEvent | undefined {- const key = failureKey(event);- if (emittedFailures.has(key)) return undefined;- emittedFailures.add(key);-- const failure: AgentTUIStreamEvent = {- type: "error",- errorText: formatFailureMessage(event),- };- const hint = failureHintOverride?.(event) ?? formatFailureHint(event);- if (hint !== undefined) failure.hint = hint;- const detail = formatFailureDetail(event);- if (detail !== undefined) failure.detail = detail;- return failure;-}--function toAgentTUIInputQuestion(request: InputRequest): AgentTUIInputQuestion {+function toAgentTUIInputQuestion(+ request: InputRequest,+ context: AgentTUIInputContext | undefined,+): AgentTUIInputQuestion {const display: "select" | "text" =request.display === "text"? "text"@@ -2855,32 +1739,7 @@ function toAgentTUIInputQuestion(request: InputRequest): AgentTUIInputQuestion {if (request.allowFreeform !== undefined) {question.allowFreeform = request.allowFreeform;}+ if (context !== undefined) question.context = context;return question;}--export type ConnectionAuthChallenge = {- url?: string;- userCode?: string;- expiresAt?: string;- instructions?: string;-};--export type ConnectionAuthState = "required" | "pending" | ConnectionAuthorizationOutcome;--export type ConnectionAuthUpdate = {- name: string;- description: string;- state: ConnectionAuthState;- challenge?: ConnectionAuthChallenge;- reason?: string;-};--type ConnectionAuthRun = {- name: string;- description: string;- state: ConnectionAuthState;- challenge?: ConnectionAuthChallenge;- webhookUrl?: string;- reason?: string;-};diff --git a/packages/eve/src/cli/dev/tui/setup-issues.integration.test.ts b/packages/eve/src/cli/dev/tui/setup-issues.integration.test.tsindex e966e7b32..72b3ec017 100644--- a/packages/eve/src/cli/dev/tui/setup-issues.integration.test.ts+++ b/packages/eve/src/cli/dev/tui/setup-issues.integration.test.ts@@ -86,13 +86,12 @@ describe("BOOT_DETECTIONS against a real directory", () => {order.push(command.name);return { message: `/${command.name} dismissed.` };});- const readPrompt = vi.fn(async () => {+ const readInput = vi.fn(async () => {order.push("prompt");return undefined;});const renderer: AgentTUIRenderer = {- readPrompt,- renderStream: vi.fn(async () => {}),+ readInput,setupFlow: createFakeSetupFlowRenderer(),};const runner = new EveTUIRunner({@@ -103,7 +102,6 @@ describe("BOOT_DETECTIONS against a real directory", () => {promptCommandHandler: { handle },renderer,serverUrl: "http://localhost:3000",- session: client.sessions.attach("session_test"),onboard: true,});@@ -113,7 +111,7 @@ describe("BOOT_DETECTIONS against a real directory", () => {{ type: "extension", name: "login", argument: "" },expect.objectContaining({ renderer, title: "eve", initialModelStep: "provider" }),);- expect(readPrompt).toHaveBeenCalledOnce();+ expect(readInput).toHaveBeenCalledOnce();expect(order).toEqual(["login", "prompt"]);});});diff --git a/packages/eve/src/cli/dev/tui/setup-panel.test.ts b/packages/eve/src/cli/dev/tui/setup-panel.test.tsindex 08a5dc28f..da5b71df8 100644--- a/packages/eve/src/cli/dev/tui/setup-panel.test.ts+++ b/packages/eve/src/cli/dev/tui/setup-panel.test.ts@@ -8,7 +8,7 @@ import {renderSelectQuestion,renderTextQuestion,} from "./setup-panel.js";-import { renderFlowDrawer } from "./flow-drawer.js";+import { renderFlowDrawer, renderTransientDrawer } from "./flow-drawer.js";import { stripAnsi } from "#cli/ui/terminal-text.js";import { createTheme } from "./theme.js";@@ -227,6 +227,18 @@ describe("renderFlowDrawer", () => {expect(rows.rows.join("\n").split("add to your agent")).toHaveLength(2);});+ it("clips a corner label so the top rule keeps the terminal width", () => {+ const { rows } = renderTransientDrawer(+ [" Approve random_number?"],+ [],+ theme,+ 30,+ "subagent(number_picker:13) · 2 of 10",+ );++ expect(rows[0]).toBe("── subagent(number_picker:… ──");+ });+it("places question controls below the drawer boundary", () => {const drawer = renderFlowDrawer({diff --git a/packages/eve/src/cli/dev/tui/steering-stream.test.ts b/packages/eve/src/cli/dev/tui/steering-stream.test.tsdeleted file mode 100644index e66f9f0c8..000000000--- a/packages/eve/src/cli/dev/tui/steering-stream.test.ts+++ /dev/null@@ -1,101 +0,0 @@-import { describe, expect, it, vi } from "vitest";-import { SteeringStream } from "#cli/dev/tui/steering-stream.js";-import { stampTestEvents } from "#internal/testing/events.js";-import { createMessageReceivedEvent, createSessionWaitingEvent } from "#protocol/message.js";--describe("SteeringStream", () => {- it("submits steering immediately without cancelling or waiting for the active stream", async () => {- const admitted = Promise.withResolvers<AsyncIterable<never>>();- const session = { cancel: vi.fn(), send: vi.fn(() => admitted.promise) };- const stream = new SteeringStream(iterate([]), session);- const sending = stream.send("Actually 2025");- expect(session.send).toHaveBeenCalledWith("Actually 2025", {- turnPolicy: "steer",- signal: expect.any(AbortSignal),- });- expect(session.cancel).not.toHaveBeenCalled();- admitted.resolve(iterate([]));- await sending;- stream.abort();- });- it("deduplicates a steering response on the same turn and emits its boundary once", async () => {- const events = stampTestEvents([- createMessageReceivedEvent({ message: "first", sequence: 0, turnId: "turn_0" }),- createMessageReceivedEvent({ message: "steer", sequence: 0, turnId: "turn_0" }),- createSessionWaitingEvent(),- ]);- const session = { send: vi.fn(async () => iterate(events.slice(1))) };- const stream = new SteeringStream(iterate(events), session);- await stream.send("steer");- expect(await collect(stream)).toEqual(events);- expect(session.send).toHaveBeenCalledWith("steer", {- turnPolicy: "steer",- signal: expect.any(AbortSignal),- });- });-- it("follows a message accepted after the original turn settled", async () => {- const events = stampTestEvents([- createMessageReceivedEvent({ message: "first", sequence: 0, turnId: "turn_0" }),- createSessionWaitingEvent(),- createMessageReceivedEvent({ message: "later", sequence: 1, turnId: "turn_1" }),- createSessionWaitingEvent(),- ]);- const stream = new SteeringStream(iterate(events.slice(0, 2)), {- send: async () => iterate(events.slice(2)),- });- await stream.send("later");- expect(await collect(stream)).toEqual([events[0], events[2], events[3]]);- });-- it("skips an overlapping settled boundary before following the accepted turn", async () => {- const events = stampTestEvents([- createMessageReceivedEvent({ message: "first", sequence: 0, turnId: "turn_0" }),- createSessionWaitingEvent(),- createMessageReceivedEvent({ message: "later", sequence: 1, turnId: "turn_1" }),- createSessionWaitingEvent(),- ]);- const stream = new SteeringStream(iterate(events.slice(0, 2)), {- send: async () => iterate(events.slice(1)),- });- await stream.send("later");- expect(await collect(stream)).toEqual([events[0], events[2], events[3]]);- });-- it("aborts all accepted follow-up responses when the consumer detaches", async () => {- const signals: AbortSignal[] = [];- const stream = new SteeringStream(iterate([]), {- send: async (_message, options) => {- signals.push(options.signal);- return iterate([]);- },- });- await stream.send("first");- await stream.send("second");- stream.abort();- expect(signals.every((signal) => signal.aborted)).toBe(true);- await expect(stream.send("late")).rejects.toThrow("active stream ended");- });-- it("reports failed admission without losing the original stream boundary", async () => {- const events = stampTestEvents([createSessionWaitingEvent()]);- const stream = new SteeringStream(iterate(events), {- send: async () => {- throw new Error("send failed");- },- });- await expect(stream.send("steer")).rejects.toThrow("send failed");- expect(await collect(stream)).toEqual(events);- await expect(stream.send("late")).rejects.toThrow("active stream ended");- });-});--async function* iterate<T>(values: readonly T[]): AsyncGenerator<T> {- yield* values;-}--async function collect<T>(values: AsyncIterable<T>): Promise<T[]> {- const result: T[] = [];- for await (const value of values) result.push(value);- return result;-}diff --git a/packages/eve/src/cli/dev/tui/steering-stream.ts b/packages/eve/src/cli/dev/tui/steering-stream.tsdeleted file mode 100644index acfa81ea5..000000000--- a/packages/eve/src/cli/dev/tui/steering-stream.ts+++ /dev/null@@ -1,66 +0,0 @@-import { createEventDeduper } from "#protocol/event-dedupe.js";-import { isCurrentTurnBoundaryEvent, type MessageStreamEvent } from "#protocol/message.js";--/**- * Follows accepted messages through their boundary, including a send racing- * settlement. Delivery responses may overlap; stream event IDs deduplicate them.- */-export class SteeringStream implements AsyncIterable<MessageStreamEvent> {- private readonly session: {- send(- message: string,- options: { turnPolicy: "steer"; signal: AbortSignal },- ): Promise<AsyncIterable<MessageStreamEvent>>;- };- private readonly streams: Promise<AsyncIterable<MessageStreamEvent> | undefined>[];- private closed = false;- private readonly controller = new AbortController();-- constructor(initial: AsyncIterable<MessageStreamEvent>, session: SteeringStream["session"]) {- this.session = session;- this.streams = [Promise.resolve(initial)];- }-- async send(message: string): Promise<void> {- if (this.closed) throw new Error("The active stream ended before steering was sent.");- const response = this.session.send(message, {- turnPolicy: "steer",- signal: this.controller.signal,- });- // Handle failure immediately even if the initial stream has not finished.- this.streams.push(- response.then(- (value) => value,- () => undefined,- ),- );- await response;- }-- abort(): void {- this.closed = true;- this.controller.abort();- }-- async *[Symbol.asyncIterator](): AsyncGenerator<MessageStreamEvent> {- const seen = createEventDeduper();- let boundary: MessageStreamEvent | undefined;- try {- while (this.streams.length > 0) {- const stream = await this.streams.shift()!;- if (stream === undefined) continue;- for await (const event of stream) {- if (!seen.admit(event)) continue;- if (isCurrentTurnBoundaryEvent(event)) {- boundary = event;- break;- }- yield event;- }- }- if (boundary !== undefined) yield boundary;- } finally {- this.abort();- }- }-}diff --git a/packages/eve/src/cli/dev/tui/subagent-pump.test.ts b/packages/eve/src/cli/dev/tui/subagent-pump.test.tsdeleted file mode 100644index 0c9dcc4cd..000000000--- a/packages/eve/src/cli/dev/tui/subagent-pump.test.ts+++ /dev/null@@ -1,606 +0,0 @@-import { afterEach, describe, expect, it, vi } from "vitest";--import { Client, type MessageStreamEvent } from "#client/index.js";-import { stampTestEvent } from "#internal/testing/events.js";-import {- EVE_MESSAGE_STREAM_VERSION,- EVE_STREAM_VERSION_HEADER,- type AgentStartedStreamEvent,- type UnstampedMessageStreamEvent,-} from "#protocol/message.js";--import { SubagentPump, type SubagentView } from "./subagent-pump.js";--afterEach(() => {- vi.useRealTimers();- vi.restoreAllMocks();-});--function fakeView(): SubagentView {- return {- begin: vi.fn(),- end: vi.fn(),- upsertStep: vi.fn(),- upsertTool: vi.fn(),- removeTool: vi.fn(),- markChildToolCallId: vi.fn(),- };-}--interface ChildRequest {- readonly url: URL;- readonly path: string;- readonly startIndex: number;- readonly signal: AbortSignal | undefined;-}--/** Serves every child stream request the client opens through `fetch`. */-function serveChildStreams(respond: (request: ChildRequest) => Response | Promise<Response>) {- const requests: ChildRequest[] = [];- vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => {- const url = new URL(String(input));- const request: ChildRequest = {- path: url.pathname,- signal: init?.signal ?? undefined,- startIndex: Number(url.searchParams.get("startIndex") ?? 0),- url,- };- requests.push(request);- return await respond(request);- });- return requests;-}--/** A durable child log that honors the requested cursor, like the stream route. */-function durableChild(events: readonly MessageStreamEvent[]) {- return (request: ChildRequest) => responseOf(events.slice(request.startIndex));-}--function createPump(options: { host?: string; onToolCompleted?: () => Promise<void> } = {}) {- const view = fakeView();- const pump = new SubagentPump({- client: new Client({ host: options.host ?? "http://localhost:3000" }),- view,- formatActionResultError: () => "failed",- onToolCompleted: options.onToolCompleted,- });- return { pump, view };-}--/**- * A hand-pumped child response: events pushed after scoped cancellation aborts- * the pump must never reach the view.- */-function pushableChildStream() {- let controller: ReadableStreamDefaultController<Uint8Array> | undefined;- let aborted = false;- const encoder = new TextEncoder();-- return {- push(event: MessageStreamEvent) {- if (aborted) return;- controller?.enqueue(encoder.encode(`${JSON.stringify(event)}\n`));- },- response(signal?: AbortSignal): Response {- return new Response(- new ReadableStream<Uint8Array>({- start(nextController) {- controller = nextController;- signal?.addEventListener(- "abort",- () => {- aborted = true;- nextController.error(signal.reason);- },- { once: true },- );- },- }),- {- headers: { [EVE_STREAM_VERSION_HEADER]: EVE_MESSAGE_STREAM_VERSION },- },- );- },- get aborted() {- return aborted;- },- };-}--interface AgentTaskOptions {- readonly name?: string;- readonly remote?: AgentStartedStreamEvent["data"]["remote"];- readonly sessionId?: string;- readonly streamPath?: string;- readonly turnId?: string;-}--/** Starts an agent task the way the parent stream announces it: the call, then its session. */-function startAgentTask(- pump: SubagentPump,- callId: string,- options: AgentTaskOptions = {},-): { readonly name: string; readonly taskId: string } {- const name = options.name ?? "researcher";- const taskId = `${name}-${callId}`;- const turnId = options.turnId ?? "turn-1";- callAgentTask(pump, { name, taskId }, callId, turnId);- const data: AgentStartedStreamEvent["data"] = {- callId,- name,- sessionId: options.sessionId ?? `child_${callId}`,- streamPath: options.streamPath ?? `/eve/v1/children/${callId}/stream`,- taskId,- turnId,- };- if (options.remote !== undefined) data.remote = options.remote;- pump.agentStarted({ data, type: "agent.started" }, "parent");- return { name, taskId };-}--/** A later call to a task reaches the session the task already opened. */-function callAgentTask(- pump: SubagentPump,- task: { readonly name: string; readonly taskId: string },- callId: string,- turnId = "turn-1",-): void {- pump.taskStarted(- {- data: { callId, kind: "agent", name: task.name, taskId: task.taskId, turnId },- type: "task.started",- },- "parent",- );-}--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();- },- }),- {- headers: { [EVE_STREAM_VERSION_HEADER]: EVE_MESSAGE_STREAM_VERSION },- },- );-}--function reasoningEvent(delta: string, index = 0): MessageStreamEvent {- return stampTestEvent(- {- type: "reasoning.appended",- data: {- reasoningDelta: delta,- sequence: 2,- stepIndex: 0,- turnId: "child-turn",- },- } as UnstampedMessageStreamEvent,- index,- );-}--function boundaryEvent(index: number): MessageStreamEvent {- return stampTestEvent(- {- type: "session.waiting",- data: { continuationToken: "session-id", wait: "next-user-message" },- } as UnstampedMessageStreamEvent,- index,- );-}--function failedBoundaryEvent(index: number): MessageStreamEvent {- return stampTestEvent(- {- type: "session.failed",- data: { code: "SESSION_FAILED", message: "child failed", sessionId: "child_call-1" },- } as UnstampedMessageStreamEvent,- index,- );-}--function completedEvent(index: number): MessageStreamEvent {- return stampTestEvent({ type: "session.completed" } as UnstampedMessageStreamEvent, index);-}--describe("SubagentPump.settleCancelledTurn", () => {- it("cancels only descendants of the exact turn", async () => {- const childA = pushableChildStream();- const childB = pushableChildStream();- const streams = new Map([- ["/eve/v1/children/child-a/stream", childA],- ["/eve/v1/children/child-b/stream", childB],- ]);- const requests = serveChildStreams(({ path, signal }) => {- const child = streams.get(path);- if (child === undefined) throw new Error(`Unexpected child path: ${path}`);- return child.response(signal);- });- const { pump } = createPump();-- startAgentTask(pump, "child-a", { turnId: "turn-a" });- startAgentTask(pump, "child-b", { turnId: "turn-b" });- await vi.waitFor(() => expect(requests).toHaveLength(2));-- pump.settleCancelledTurn("turn-b");-- expect(childB.aborted).toBe(true);- expect(childA.aborted).toBe(false);- pump.abortAll();- });-- it("finalizes the live step and stops stale child output after cancellation", async () => {- const child = pushableChildStream();- const requests = serveChildStreams(({ signal }) => child.response(signal));- const { pump, view } = createPump();-- startAgentTask(pump, "call-1");- await vi.waitFor(() => expect(requests).toHaveLength(1));- child.push(reasoningEvent("**Searching for current events**", 0));- await vi.waitFor(() =>- expect(view.upsertStep).toHaveBeenCalledWith(- expect.objectContaining({ callId: "call-1", finalized: false }),- ),- );-- // The parent turn is cancelled: the live step finalizes and the stream stops.- pump.settleCancelledTurn("turn-1");- expect(view.upsertStep).toHaveBeenCalledWith(- expect.objectContaining({ callId: "call-1", finalized: true }),- );-- // A child still flushing output after the cancel paints nothing.- const updatesAfterSettle = vi.mocked(view.upsertStep).mock.calls.length;- child.push(reasoningEvent("stale output", 1));- await new Promise((resolve) => setTimeout(resolve, 10));- expect(vi.mocked(view.upsertStep).mock.calls.length).toBe(updatesAfterSettle);- });-});--describe("SubagentPump task bookkeeping", () => {- it("keeps the child's task bookkeeping out of its activity", async () => {- const action = (callId: string, toolName: string) => ({- callId,- input: toolName === "task_wait" ? {} : { message: "Check the filings" },- kind: "tool-call" as const,- toolName,- });- const result = (callId: string, toolName: string, output: unknown, status = "completed") => ({- type: "action.result",- data: {- result: { callId, kind: "tool-result", output, toolName },- sequence: 2,- status,- stepIndex: 0,- turnId: "child-turn",- },- });- serveChildStreams(- durableChild(- [- {- type: "actions.requested",- data: {- actions: [- action("analyst-call", "analyst"),- action("deploy-call", "deploy"),- action("wait-call", "task_wait"),- ],- sequence: 1,- stepIndex: 0,- turnId: "child-turn",- },- },- {- type: "task.started",- data: {- callId: "analyst-call",- kind: "agent",- name: "analyst",- taskId: "t1",- turnId: "child-turn",- },- },- result("analyst-call", "analyst", "model-facing receipt"),- result("deploy-call", "deploy", { code: "TOO_MANY_TASKS", message: "wait" }, "failed"),- result("wait-call", "task_wait", "t1 completed; its result follows."),- {- type: "task.settled",- data: {- callId: "analyst-call",- output: "Revenue grew 12%",- status: "completed",- taskId: "t1",- turnId: "child-turn",- },- },- { type: "session.waiting", data: { continuationToken: "c", wait: "next-user-message" } },- ].map((event, index) => stampTestEvent(event as UnstampedMessageStreamEvent, index)),- ),- );- const { pump, view } = createPump();-- startAgentTask(pump, "call-1");- await vi.waitFor(() => expect(view.removeTool).toHaveBeenCalledOnce());- await vi.waitFor(() =>- expect(view.upsertTool).toHaveBeenLastCalledWith(- expect.objectContaining({ childCallId: "analyst-call", status: "done" }),- ),- );-- const updates = vi.mocked(view.upsertTool).mock.calls.map(([update]) => update);- expect(updates.some((update) => update.toolName === "task_wait")).toBe(false);- // The agent call reads as a delegation and ends with its task, not its receipt.- expect(- updates- .filter((update) => update.childCallId === "analyst-call")- .map(({ status, agentTask, output }) => ({ status, agentTask, output })),- ).toEqual([- { status: "executing", agentTask: undefined, output: undefined },- { status: "executing", agentTask: true, output: undefined },- { status: "done", agentTask: true, output: "Revenue grew 12%" },- ]);- // A call refused for the model to retry leaves the activity, with why.- expect(view.removeTool).toHaveBeenCalledWith({- callId: "call-1",- childCallId: "deploy-call",- reason: "failed",- });- // The task's end waits for the child's own boundary, which it reached.- expect(view.begin).toHaveBeenCalledWith({ callId: "call-1" });- await vi.waitFor(() => expect(view.end).toHaveBeenCalledWith({ callId: "call-1" }));- });-});--describe("SubagentPump child stream transport", () => {- it.each([boundaryEvent(0), completedEvent(0), failedBoundaryEvent(0)])(- "aborts a cloned open child stream at $type",- async (boundary) => {- const tracingError = vi.fn();- let signal: AbortSignal | undefined;- let closeStream = () => {};- let tracingDone: Promise<unknown> | undefined;- const requests = serveChildStreams((request) => {- signal = request.signal;- const response = new Response(- new ReadableStream<Uint8Array>({- start(controller) {- closeStream = () => controller.error(new DOMException("Aborted", "AbortError"));- signal?.addEventListener("abort", closeStream, { once: true });- controller.enqueue(new TextEncoder().encode(`${JSON.stringify(boundary)}\n`));- },- }),- { headers: { [EVE_STREAM_VERSION_HEADER]: EVE_MESSAGE_STREAM_VERSION } },- );- tracingDone = response.clone().text().catch(tracingError);- return response;- });- const { pump } = createPump();-- try {- startAgentTask(pump, "call-1");- await vi.waitFor(() => expect(signal?.aborted).toBe(true));- await tracingDone;-- expect(tracingError).toHaveBeenCalledWith(expect.objectContaining({ name: "AbortError" }));- expect(requests).toHaveLength(1);- } finally {- closeStream();- pump.abortAll();- await tracingDone;- }- },- );-- it("resumes from the prior cursor when a conversation subagent is called again", async () => {- const requests = serveChildStreams(- durableChild([- boundaryEvent(0),- stampTestEvent(- {- type: "actions.requested",- data: {- actions: [- {- callId: "registry-add",- input: { address: "channel/slack" },- kind: "tool-call",- toolName: "registry_add",- },- ],- sequence: 1,- stepIndex: 0,- turnId: "child-turn-2",- },- } as UnstampedMessageStreamEvent,- 1,- ),- stampTestEvent(- {- type: "action.result",- data: {- result: {- callId: "registry-add",- kind: "tool-result",- output: { status: "needs-terminal", address: "channel/slack" },- toolName: "registry_add",- },- sequence: 2,- status: "completed",- stepIndex: 0,- turnId: "child-turn-2",- },- } as UnstampedMessageStreamEvent,- 2,- ),- completedEvent(3),- ]),- );- const onToolCompleted = vi.fn(async () => {});- const { pump } = createPump({ onToolCompleted });- const task = startAgentTask(pump, "call-1", {- name: "self-modification__agent",- sessionId: "conversation-child",- });- await vi.waitFor(() => expect(requests[0]?.signal?.aborted).toBe(true));- callAgentTask(pump, task, "call-2", "turn-2");- await vi.waitFor(() => expect(onToolCompleted).toHaveBeenCalledOnce());-- expect(requests[1]).toMatchObject({ path: "/eve/v1/children/call-1/stream", startIndex: 1 });- expect(onToolCompleted).toHaveBeenCalledWith("self-modification__agent", "registry_add", {- status: "needs-terminal",- address: "channel/slack",- });- });-- it("does not let a repeated call consume the previous call's trailing boundary", async () => {- const firstStream = pushableChildStream();- const requests = serveChildStreams((request) =>- request.startIndex === 0- ? firstStream.response(request.signal)- : responseOf([reasoningEvent("second turn", 1), completedEvent(2)]),- );- const { pump, view } = createPump();- const task = startAgentTask(pump, "call-1", { sessionId: "conversation-child" });- await vi.waitFor(() => expect(requests).toHaveLength(1));- callAgentTask(pump, task, "call-2", "turn-2");- await new Promise((resolve) => setTimeout(resolve, 10));-- expect(requests).toHaveLength(1);-- firstStream.push(boundaryEvent(0));- await vi.waitFor(() =>- expect(view.upsertStep).toHaveBeenCalledWith(- expect.objectContaining({ callId: "call-2", reasoning: "second turn" }),- ),- );- expect(requests[1]).toMatchObject({ path: "/eve/v1/children/call-1/stream", startIndex: 1 });- });-- it("leaves connection authorization events to the parent runner", async () => {- const authRequests = serveChildStreams(- durableChild([- 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 { pump, view } = createPump();-- startAgentTask(pump, "call-1");- await vi.waitFor(() => expect(authRequests[0]?.signal?.aborted).toBe(true));-- expect(view.upsertStep).not.toHaveBeenCalled();- expect(view.upsertTool).not.toHaveBeenCalled();- });-- it("reopens an exhausted source at its cursor", async () => {- vi.useFakeTimers();- const log = [- reasoningEvent("looked up ", 0),- reasoningEvent("the forecast", 1),- boundaryEvent(2),- ];- const requests = serveChildStreams((request) =>- // The first connection ends after one event, before the child finishes.- responseOf(request.startIndex === 0 ? log.slice(0, 1) : log.slice(request.startIndex)),- );- const { pump, view } = createPump();-- startAgentTask(pump, "call-1");- await vi.waitFor(() => expect(requests[1]?.signal?.aborted).toBe(true));-- expect(requests.map(({ path, startIndex }) => ({ path, startIndex }))).toEqual([- { path: "/eve/v1/children/call-1/stream", startIndex: 0 },- { path: "/eve/v1/children/call-1/stream", startIndex: 1 },- ]);- expect(view.upsertStep).toHaveBeenLastCalledWith(- expect.objectContaining({ reasoning: "looked up the forecast" }),- );- });-- it("keeps following a silent child past the default idle budget", async () => {- vi.useFakeTimers();- const requests = serveChildStreams((request) =>- responseOf(requests.length > 8 ? [boundaryEvent(request.startIndex)] : []),- );- const { pump } = createPump();-- startAgentTask(pump, "call-1");- await vi.advanceTimersByTimeAsync(60_000);-- expect(requests).toHaveLength(9);- expect(requests.at(-1)?.signal?.aborted).toBe(true);- });-- it("stops following when the child stream is refused", async () => {- const requests = serveChildStreams(() => new Response("forbidden", { status: 403 }));- const { pump, view } = createPump();-- startAgentTask(pump, "call-1");- await vi.waitFor(() => expect(requests).toHaveLength(1));- await new Promise((resolve) => setTimeout(resolve, 10));-- expect(requests).toHaveLength(1);- // Nothing more will come, so the task's end must not wait for it.- expect(view.end).toHaveBeenCalledWith({ callId: "call-1" });- });-- it("uses the parent-authored child path and never the remote URL", async () => {- const requests = serveChildStreams(durableChild([boundaryEvent(0)]));- const { pump } = createPump({ host: "https://parent.example" });- const streamPath = "/eve/v1/session/parent/subagents/remote-call/child/stream";- startAgentTask(pump, "remote-call", {- remote: { url: "https://remote.example/private" },- streamPath,- });- await vi.waitFor(() => expect(requests[0]?.signal?.aborted).toBe(true));-- expect(requests[0]!.url.origin).toBe("https://parent.example");- expect(requests[0]!.path).toBe(streamPath);- expect(requests.map(({ url }) => url.href).join(" ")).not.toContain("remote.example");- });-- it("does not reopen after abortAll", async () => {- vi.useFakeTimers();- const requests = serveChildStreams(() => responseOf([]));- const { pump } = createPump();-- startAgentTask(pump, "call-1");- await vi.waitFor(() => expect(requests).toHaveLength(1));- pump.abortAll();- await vi.advanceTimersByTimeAsync(10_000);-- expect(requests).toHaveLength(1);- });-});diff --git a/packages/eve/src/cli/dev/tui/subagent-pump.ts b/packages/eve/src/cli/dev/tui/subagent-pump.tsdeleted file mode 100644index ef99bf3cf..000000000--- a/packages/eve/src/cli/dev/tui/subagent-pump.ts+++ /dev/null@@ -1,674 +0,0 @@-/**- * The subagent child-stream subsystem: for every call to an agent task on- * the parent stream, a parallel pump over the agent's session folds its- * events into the renderer's view of what that agent is doing. Extracted- * from the runner — the subsystem touches nothing but its own run state, the- * client, and the {@link SubagentView} seam.- */--import type { Client, StreamReconnectPolicy } from "#client/index.js";-import {- isCurrentTurnBoundaryEvent,- type ActionPresentationByCallId,- type ActionResultStreamEvent,- type AgentStartedStreamEvent,- type MessageStreamEvent,- type TaskStartedStreamEvent,-} from "#protocol/message.js";-import { isTaskControlTool, isTaskRetryRefusal } from "#protocol/task-tools.js";--/**- * Pumps end on the child boundary or abort, never on a retry budget: a child- * parked for HITL can stay silent indefinitely, and the dev server can restart- * underneath an open follower.- */-const childStreamReconnectPolicy = {- streamIdleReconnectPolicy: { maxAttempts: Infinity },- streamOpenReconnectPolicy: { maxAttempts: Infinity },-} as const satisfies StreamReconnectPolicy;--/**- * The renderer's view of each agent task's own activity. One cohesive- * capability: a renderer that implements it shows what every working agent- * is doing, and a renderer without it simply shows none. Individually- * optional methods would let a renderer implement a type-legal subset that- * ghosts placeholders or duplicates parent tool rows. The task's start and- * end reach the renderer on the parent stream, not through this view.- */-export interface SubagentView {- /**- * The pump follows the agent a call reaches. The agent's last events can- * trail the parent's `task.settled`, so the task's end waits for {@link end}.- */- begin(update: { callId: string }): void;- /** The followed agent's own stream ended, or the pump stopped following it. */- end(update: { callId: string }): void;- upsertStep(update: SubagentStepUpdate): void;- upsertTool(update: SubagentToolUpdate): void;- /**- * Drops a child tool call that never materialized, or one the session- * refused for the model to retry (`reason` says why).- */- removeTool(update: { callId: string; childCallId: string; reason?: string }): void;- /** Suppresses the parent-level tool row for a child-owned call id. */- markChildToolCallId(callId: string): void;-}--type SubagentChildStep = {- reasoning: string;- message: string;- finalized: boolean;-};--type SubagentToolStatus =- | "preparing"- | "approval-requested"- | "executing"- | "done"- | "failed"- | "rejected";--type SubagentToolState = {- toolName: string;- input: unknown;- status: SubagentToolStatus;- output?: unknown;- errorText?: string;- label?: string;- /** The child's call started an agent task of its own. */- agentTask?: boolean;-};--export type SubagentRun = {- name: string;- childSessionId: string;- /** Parent turn that originated this dispatch; cancellation is scoped to it. */- parentTurnId: string;- /** Only the child's own boundary ends the run: its last events can trail the parent's. */- done: boolean;- /** The parent session, whose client follows the child stream. */- parentSessionId: string;- /** The agent task's session, whose stream this run follows. */- started: AgentStartedStreamEvent;- /**- * One entry per logical "child message" — independent of the child's- * `stepIndex` field, which the harness can reuse across multiple- * assistant messages within a turn (e.g. a message before a tool call- * and another message after the tool result both arrive under- * `stepIndex: 0`). The key is a monotonic counter so each- * `message.completed` opens a new box on the next inbound delta.- */- steps: Map<number, SubagentChildStep>;- /**- * Section currently accepting reasoning/message deltas. `null` means- * the next delta opens a new section.- */- currentSectionKey: number | null;- /** Monotonic counter for new section keys. */- nextSectionKey: number;- tools: Map<string, SubagentToolState>;- /** Child calls that started tasks: their `action.result` is only a receipt. */- taskCallIds: Set<string>;-};--export type SubagentStepUpdate = {- callId: string;- subagentName: string;- sectionKey: number;- reasoning: string;- message: string;- finalized: boolean;-};--export type SubagentToolUpdate = {- callId: string;- subagentName: string;- childCallId: string;- toolName: string;- input: unknown;- status: SubagentToolStatus;- output?: unknown;- errorText?: string;- /** The tool's own label copy, when it defines one. */- label?: string;- /** The call started an agent task, so it reads as a delegation. */- agentTask?: boolean;-};--export interface SubagentPumpOptions {- client?: Client;- view?: SubagentView;- formatActionResultError: (event: ActionResultStreamEvent) => string;- /** Runs TUI-owned handling after a child tool result becomes visible. */- onToolCompleted?: (subagentName: string, toolName: string, output: unknown) => Promise<void>;-}--/** An agent task: its session is announced once, and every call to the task reaches it. */-interface AgentTask {- started?: AgentStartedStreamEvent;-}--export class SubagentPump {- readonly #client: Client | undefined;- readonly #view: SubagentView | undefined;- readonly #formatActionResultError: (event: ActionResultStreamEvent) => string;- readonly #onToolCompleted:- | ((subagentName: string, toolName: string, output: unknown) => Promise<void>)- | undefined;- readonly #runs = new Map<string, SubagentRun>();- readonly #tasks = new Map<string, AgentTask>();- readonly #pumps = new Map<string, AbortController>();- /** Durable child cursor shared by repeated calls into one conversation subagent. */- readonly #childStreamIndices = new Map<string, number>();- /** One stream follower owns a conversation child session through its boundary. */- readonly #activeChildCalls = new Map<string, string>();- readonly #queuedChildCalls = new Map<string, string[]>();-- constructor(options: SubagentPumpOptions) {- this.#client = options.client;- this.#view = options.view;- this.#formatActionResultError = options.formatActionResultError;- this.#onToolCompleted = options.onToolCompleted;- }-- /** A call started or reached a task. A call to an agent task starts following it at once. */- taskStarted(event: TaskStartedStreamEvent, parentSessionId: string | undefined): void {- const { callId, kind, taskId, turnId } = event.data;- if (kind !== "agent") return;- const task = this.#tasks.get(taskId);- if (task === undefined) {- this.#tasks.set(taskId, {});- return;- }- if (task.started !== undefined && parentSessionId !== undefined) {- this.#begin({ callId, parentSessionId, parentTurnId: turnId, started: task.started });- }- }-- /**- * A run opened a session. The session an agent task opens is its agent's;- * sessions other tools open are not followed.- */- agentStarted(started: AgentStartedStreamEvent, parentSessionId: string | undefined): void {- const { callId, taskId, turnId } = started.data;- const task = taskId === undefined ? undefined : this.#tasks.get(taskId);- if (task === undefined) return;- task.started ??= started;- if (parentSessionId === undefined) return;- this.#begin({ callId, parentSessionId, parentTurnId: turnId, started: task.started });- }-- /**- * The moment a call is known to reach an agent, the pump follows the- * agent's session and claims the call id, so no parent-level tool row- * duplicates it. A later parent-stream translator may replay the call;- * re-entry only refreshes the name.- */- #begin(input: {- readonly callId: string;- readonly parentSessionId: string;- readonly parentTurnId: string;- readonly started: AgentStartedStreamEvent;- }): void {- const { callId, started } = input;- const existing = this.#runs.get(callId);- if (existing === undefined) {- this.#runs.set(callId, {- name: started.data.name,- childSessionId: started.data.sessionId,- parentSessionId: input.parentSessionId,- parentTurnId: input.parentTurnId,- done: false,- started,- steps: new Map(),- currentSectionKey: null,- nextSectionKey: 0,- tools: new Map(),- taskCallIds: new Set(),- });- } else {- existing.name = started.data.name;- }- this.#view?.markChildToolCallId(callId);- if (existing !== undefined) return;- this.#view?.begin({ callId });- this.#activateOrQueue(callId);- }-- abortAll(): void {- for (const controller of this.#pumps.values()) {- controller.abort();- }- this.#pumps.clear();- this.#runs.clear();- this.#tasks.clear();- this.#childStreamIndices.clear();- this.#activeChildCalls.clear();- this.#queuedChildCalls.clear();- }-- /** Settles and aborts the descendants of the cancelled parent turn. */- settleCancelledTurn(turnId: string): void {- for (const [callId, run] of this.#runs) {- if (run.parentTurnId !== turnId) continue;- this.#finalizeRun(callId);- this.#pumps.get(callId)?.abort();- this.#pumps.delete(callId);- }- }-- /**- * Opens a parallel stream over the child session and folds its events into- * nested subagent blocks.- *- * Pumps are fire-and-forget and must never be awaited at a turn boundary:- * a child session parks instead of ending, so its stream stays open and- * blocking on it would stall the prompt. Pumps stay open across HITL prompts- * and resume rendering when the subagent unparks; they end on the child's- * own boundary or via abort.- */- #activateOrQueue(callId: string): void {- const run = this.#runs.get(callId);- if (run === undefined || run.done) return;- const activeCallId = this.#activeChildCalls.get(run.childSessionId);- if (activeCallId === undefined) {- this.#activeChildCalls.set(run.childSessionId, callId);- this.#startPump(callId);- return;- }- if (activeCallId === callId) return;- const queued = this.#queuedChildCalls.get(run.childSessionId) ?? [];- if (!queued.includes(callId)) queued.push(callId);- this.#queuedChildCalls.set(run.childSessionId, queued);- }-- #startPump(callId: string) {- if (this.#pumps.has(callId)) return;- const client = this.#client;- if (!client) return;- const run = this.#runs.get(callId);- if (run === undefined || run.done) return;-- const controller = new AbortController();- this.#pumps.set(callId, controller);-- void (async () => {- const { childSessionId } = run;- let cursor = this.#childStreamIndices.get(childSessionId) ?? 0;- try {- const events = client.sessions.attach(run.parentSessionId).agent(run.started).stream({- signal: controller.signal,- startIndex: cursor,- streamReconnectPolicy: childStreamReconnectPolicy,- });- for await (const event of events) {- if (controller.signal.aborted) return;- this.#childStreamIndices.set(childSessionId, (cursor += 1));- const childEventWork = this.#applyChildEvent(callId, event);- if (childEventWork !== undefined) await childEventWork;- if (!isCurrentTurnBoundaryEvent(event)) continue;- // A proxied child approval parks at an intermediate- // `session.waiting`. Keep following so the approved tool result- // can still update the nested view.- if (event.type === "session.waiting" && hasPendingChildApproval(run)) continue;- this.#finalizeRun(callId);- return;- }- } catch {- // Only a non-retryable failure ends the follower early; nothing more- // will come, so the task's end need not wait for it.- if (!controller.signal.aborted) this.#view?.end({ callId });- } finally {- controller.abort();- if (this.#pumps.get(callId) === controller) this.#pumps.delete(callId);- }- })();- }-- #registerChildTool(- callId: string,- run: SubagentRun,- request: {- childCallId: string;- toolName: string;- input: unknown;- status: SubagentToolState["status"];- label?: string;- },- ): void {- const existing = run.tools.get(request.childCallId);- const tool: SubagentToolState = existing ?? {- toolName: request.toolName,- input: request.input,- status: request.status,- };- if (request.label !== undefined) tool.label = request.label;- if (existing) {- const terminal =- existing.status === "done" ||- existing.status === "failed" ||- existing.status === "rejected";- if (request.status === "approval-requested" && !terminal) {- // Some providers announce the action before eve parks it for- // approval. The later input request is the live state, not a demotion.- existing.status = request.status;- } else {- const priority: Record<SubagentToolState["status"], number> = {- preparing: 0,- "approval-requested": 1,- executing: 2,- done: 3,- failed: 3,- rejected: 3,- };- if (priority[request.status] > priority[existing.status]) {- existing.status = request.status;- }- }- // A late `preparing` announcement must not wipe input the full call- // already delivered.- if (request.input !== undefined) {- existing.input = request.input;- }- } else {- run.tools.set(request.childCallId, tool);- }- this.#view?.markChildToolCallId(request.childCallId);- this.#emitTool(callId, run, request.childCallId, tool);- }-- #emitTool(callId: string, run: SubagentRun, childCallId: string, tool: SubagentToolState): void {- const update: SubagentToolUpdate = {- callId,- subagentName: run.name,- childCallId,- toolName: tool.toolName,- input: tool.input,- status: tool.status,- };- if (tool.output !== undefined) update.output = tool.output;- if (tool.errorText !== undefined) update.errorText = tool.errorText;- if (tool.label !== undefined) update.label = tool.label;- if (tool.agentTask === true) update.agentTask = true;- this.#view?.upsertTool(update);- }-- /**- * Ends a run on the child's own boundary: re-emits a finalized snapshot- * for any still-streaming step, sweeps preparing ghosts, and releases the- * child session to the next queued call. `done` is the idempotency- * authority.- */- #finalizeRun(callId: string): void {- const run = this.#runs.get(callId);- if (!run || run.done) return;- run.done = true;- for (const [sectionKey, step] of run.steps) {- if (!step.finalized) {- step.finalized = true;- this.#view?.upsertStep({- callId,- subagentName: run.name,- sectionKey,- reasoning: step.reasoning,- message: step.message,- finalized: true,- });- }- }- run.currentSectionKey = null;- this.#sweepPreparingTools(callId, run);- this.#view?.end({ callId });- this.#releaseChildSession(callId, run.childSessionId);- }-- #releaseChildSession(callId: string, childSessionId: string): void {- const queued = this.#queuedChildCalls.get(childSessionId) ?? [];- const remaining = queued.filter((queuedCallId) => queuedCallId !== callId);- if (this.#activeChildCalls.get(childSessionId) !== callId) {- if (remaining.length === 0) this.#queuedChildCalls.delete(childSessionId);- else this.#queuedChildCalls.set(childSessionId, remaining);- return;- }-- this.#activeChildCalls.delete(childSessionId);- while (remaining.length > 0) {- const nextCallId = remaining.shift()!;- const nextRun = this.#runs.get(nextCallId);- if (nextRun === undefined || nextRun.done) continue;- if (remaining.length === 0) this.#queuedChildCalls.delete(childSessionId);- else this.#queuedChildCalls.set(childSessionId, remaining);- this.#activeChildCalls.set(childSessionId, nextCallId);- this.#startPump(nextCallId);- return;- }- this.#queuedChildCalls.delete(childSessionId);- }-- /**- * Drops child tool placeholders that never left `preparing` — their input- * never parsed (the child model emitted bad JSON, or the stream ended- * mid-generation), so no upgrade is coming and the row would linger as a- * `Search …` ghost inside the section.- */- #sweepPreparingTools(callId: string, run: SubagentRun): void {- for (const [childCallId, tool] of run.tools) {- if (tool.status !== "preparing") continue;- run.tools.delete(childCallId);- this.#view?.removeTool({ callId, childCallId });- }- }-- #applyChildEvent(callId: string, event: MessageStreamEvent): Promise<void> | undefined {- const run = this.#runs.get(callId);- if (!run) return;- const view = this.#view;-- const emit = (key: number, step: SubagentChildStep) => {- view?.upsertStep({- callId,- subagentName: run.name,- sectionKey: key,- reasoning: step.reasoning,- message: step.message,- finalized: step.finalized,- });- };-- const finalizeCurrent = () => {- if (run.currentSectionKey === null) return;- const step = run.steps.get(run.currentSectionKey);- if (step) {- step.finalized = true;- emit(run.currentSectionKey, step);- }- run.currentSectionKey = null;- };-- switch (event.type) {- case "reasoning.appended": {- const { key, step } = openCurrentSubagentSection(run);- step.reasoning = step.reasoning + event.data.reasoningDelta;- emit(key, step);- break;- }- case "reasoning.completed":- // Reasoning closes within a section but does not close the section- // itself — a following `message.appended` should land in the same- // box. The section closes on `message.completed` or- // `step.completed`.- break;- case "message.appended": {- const { key, step } = openCurrentSubagentSection(run);- step.message = step.message + event.data.messageDelta;- emit(key, step);- break;- }- case "message.completed": {- const { key, step } = openCurrentSubagentSection(run);- if (step.message.length === 0) {- // Some channels emit only `message.completed` without per-delta- // `message.appended` events. Capture the full text in that case.- step.message = event.data.message;- }- step.finalized = true;- emit(key, step);- run.currentSectionKey = null;- break;- }- case "step.completed":- finalizeCurrent();- // A valid child call upgrades from `preparing` within its own step;- // one still preparing at the boundary never parsed and would linger- // as a placeholder ghost in the section.- this.#sweepPreparingTools(callId, run);- break;- case "action.input.appended": {- const { callId: childCallId, toolName } = event.data;- if (run.tools.has(childCallId) || isTaskControlTool(toolName)) break;- this.#registerChildTool(callId, run, {- childCallId,- toolName,- input: undefined,- status: "preparing",- });- break;- }- case "actions.requested": {- // Close any pending text section before the tool call so the- // tool box renders below it — and the next post-tool message- // opens a fresh section.- finalizeCurrent();- for (const action of event.data.actions) {- if (action.kind !== "tool-call" || isTaskControlTool(action.toolName)) continue;- if (action.parentCallId !== undefined) continue;- this.#registerChildTool(callId, run, {- childCallId: action.callId,- toolName: action.toolName,- input: action.input,- status: "executing",- ...labelOf(event.data.presentation, action.callId),- });- }- break;- }- case "input.requested": {- // Tools that need approval skip `actions.requested` and arrive- // here as `input.requested` with the action embedded. Register- // the tool section the same way (status: "approval-requested")- // so the parent's stale tool box can be suppressed and the- // child tool appears under the subagent flow.- finalizeCurrent();- for (const request of event.data.requests) {- if (request.action.kind !== "tool-call") continue;- if (isTaskControlTool(request.action.toolName)) continue;- this.#registerChildTool(callId, run, {- childCallId: request.action.callId,- toolName: request.action.toolName,- input: request.action.input,- status: "approval-requested",- });- }- break;- }- case "action.result": {- const result = event.data.result;- if (result.kind !== "tool-result") break;- if (run.taskCallIds.has(result.callId)) break;- const tool = run.tools.get(result.callId);- if (!tool) break;- if (isTaskRetryRefusal(event)) {- run.tools.delete(result.callId);- view?.removeTool({- callId,- childCallId: result.callId,- reason: this.#formatActionResultError(event),- });- break;- }- const label = labelOf(event.data.presentation, result.callId).label;- if (label !== undefined) tool.label = label;- switch (event.data.status) {- case "completed":- tool.status = "done";- tool.output = result.output;- break;- case "failed":- tool.status = "failed";- tool.errorText = this.#formatActionResultError(event);- break;- case "rejected":- tool.status = "rejected";- tool.errorText = this.#formatActionResultError(event);- break;- }- this.#emitTool(callId, run, result.callId, tool);- if (event.data.status === "completed") {- return this.#onToolCompleted?.(run.name, tool.toolName, result.output);- }- break;- }- case "task.started": {- // The child's call started a task of its own: its result arrives- // with `task.settled`, and an agent task reads as a delegation.- run.taskCallIds.add(event.data.callId);- const tool = run.tools.get(event.data.callId);- if (tool === undefined || event.data.kind !== "agent") break;- tool.agentTask = true;- this.#emitTool(callId, run, event.data.callId, tool);- break;- }- case "task.settled": {- const tool = run.tools.get(event.data.callId);- if (tool === undefined) break;- switch (event.data.status) {- case "completed":- tool.status = "done";- if (event.data.output !== undefined) tool.output = event.data.output;- break;- case "failed":- tool.status = "failed";- tool.errorText = event.data.error?.message ?? "Failed.";- break;- case "cancelled":- tool.status = "rejected";- tool.errorText = "Stopped.";- break;- }- this.#emitTool(callId, run, event.data.callId, tool);- break;- }- default:- // Other events (session.*, turn.*, step.started, etc.) carry no- // visible text — ignore.- break;- }- }-}--function labelOf(- presentation: ActionPresentationByCallId | undefined,- callId: string,-): { label?: string } {- const label = presentation?.[callId]?.label;- return label === undefined ? {} : { label };-}--function hasPendingChildApproval(run: SubagentRun): boolean {- return [...run.tools.values()].some((tool) => tool.status === "approval-requested");-}--function openCurrentSubagentSection(run: SubagentRun): {- key: number;- step: SubagentChildStep;-} {- if (run.currentSectionKey === null) {- run.currentSectionKey = run.nextSectionKey++;- run.steps.set(run.currentSectionKey, { reasoning: "", message: "", finalized: false });- }- const step = run.steps.get(run.currentSectionKey);- if (!step) {- throw new Error("invariant: subagent section state missing for current key");- }- return { key: run.currentSectionKey, step };-}diff --git a/packages/eve/src/cli/dev/tui/task-activity.ts b/packages/eve/src/cli/dev/tui/task-activity.tsindex d251943c4..9dde0ac24 100644--- a/packages/eve/src/cli/dev/tui/task-activity.ts+++ b/packages/eve/src/cli/dev/tui/task-activity.ts@@ -103,6 +103,14 @@ export function waitingLabel(entries: readonly TaskEntry[]): string {return `Waiting for ${String(names.length)} tasks`;}+/** Names the connections a parked session waits on: `Waiting for sign-in to Linear`. */+export function signInLabel(names: readonly string[]): string {+ const unique = [...new Set(names)];+ if (unique.length === 1) return `Waiting for sign-in to ${unique[0]!}`;+ if (unique.length === 2) return `Waiting for sign-in to ${unique[0]!} and ${unique[1]!}`;+ return `Waiting for ${String(unique.length)} sign-ins`;+}+/** What a working task is doing right now, in one short line. */function currentActivity(entry: TaskEntry): { text: string; attention: boolean } {if (entry.finishing === true) return { text: "Finishing", attention: false };diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.test.tsindex ef530c098..86839b70f 100644--- a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts@@ -11,23 +11,52 @@ import {formatChangeDetectedLogLine,} from "#internal/nitro/host/dev-watcher-log.js";-import type { AgentTUIStreamEvent, AgentTUIStreamResult, SubagentToolUpdate } from "./runner.js";+import { initialConversationState, reduceConversation } from "#client/conversation-reducer.js";+import type { EveAgentReducerEvent } from "#client/reducer.js";+import { stampTestEvent } from "#internal/testing/events.js";+import {+ createActionsRequestedEvent,+ createMessageAppendedEvent,+ createMessageCompletedEvent,+ createMessageReceivedEvent,+ createTaskStartedEvent,+ createTurnStartedEvent,+ createTurnWaitingEvent,+ createTaskSettledEvent,+ type UnstampedMessageStreamEvent,+} from "#protocol/message.js";+import {+ tuiSessionReducer,+ type AgentTUIConversationView,+ type TuiSessionData,+} from "./conversation-view.js";+import type { AgentTUISessionOptions } from "./runner.js";import { PROMPT_COMMANDS, promptCommandsFor } from "./prompt-commands.js";import { TerminalRenderer } from "./terminal-renderer.js";-import { stripAnsi } from "#cli/ui/terminal-text.js";import { MockScreen, MockUserInput } from "./test/mock-terminal.js";-function streamOf(events: AgentTUIStreamEvent[]): AgentTUIStreamResult {+/** A session view over the conversation these events produce. */+function conversationOf(+ events: readonly EveAgentReducerEvent[],+ options: { working?: boolean; data?: Partial<TuiSessionData> } = {},+): AgentTUIConversationView {return {- events: new ReadableStream<AgentTUIStreamEvent>({- start(controller) {- for (const event of events) controller.enqueue(event);- controller.close();- },- }),+ conversation: events.reduce(reduceConversation, initialConversationState()),+ working: options.working ?? false,+ data: { ...tuiSessionReducer.initial(), ...options.data },+ failures: [],};}+/** The composer's next submitted text, as the runner reads it. */+async function readPrompt(+ renderer: TerminalRenderer,+ options?: AgentTUISessionOptions,+): Promise<string | undefined> {+ const input = await renderer.readInput(options);+ return input?.type === "submit" ? input.text : undefined;+}+function agentInfoWithDynamicModel(): AgentInfoResult {const info = createTestAgentInfoResult({ name: "Weather Agent" });return {@@ -51,6 +80,59 @@ function agentInfoWithDynamicModel(): AgentInfoResult {};}+/** A local agent with the self-modification extension, which earns the composer's local cue. */+function selfModificationHeader() {+ const info = createTestAgentInfoResult();+ return {+ name: "Orders",+ serverUrl: "http://localhost:3000",+ localDevelopment: true,+ info: {+ ...info,+ instructions: {+ dynamic: [],+ static: [+ {+ ...info.agent.config,+ name: "instructions",+ role: "system" as const,+ content: "Help with orders.",+ },+ ],+ },+ subagents: {+ total: 1,+ local: [+ {+ ...info.agent.config,+ owner: {+ kind: "extension" as const,+ mountId: "extensions/self-modification",+ namespace: "self-modification",+ packageName: "eve",+ },+ name: "self-modification__agent",+ entryPath: "subagents/agent/agent.ts",+ rootPath: "/eve/self-modification",+ nodeId: "self-modification__agent",+ parentNodeId: "__root__",+ summary: {+ channels: 0,+ connections: 0,+ hooks: 0,+ instructions: 1,+ memories: 0,+ schedules: 0,+ skills: 0,+ tools: 1,+ },+ },+ ],+ },+ },+ };+}+function makeRenderer(columns = 80, rows = 30) {const screen = new MockScreen({ columns, rows });const input = new MockUserInput();@@ -127,7 +209,7 @@ function agentInfoWithModel(describe("TerminalRenderer (inline scrollback)", () => {it("prints the dim wordmark tag as the parting line after a Ctrl-C exit", async () => {const { screen, input, renderer } = makeRenderer();- const prompt = renderer.readPrompt();+ const prompt = readPrompt(renderer);// Ctrl-C at the prompt restores the terminal inside the reader itself;// the runner's teardown-time shutdown() must still print the tag.input.ctrlC();@@ -151,7 +233,7 @@ describe("TerminalRenderer (inline scrollback)", () => {it("names the session in the parting line once the runner reports it", async () => {const { screen, input, renderer } = makeRenderer();renderer.setSessionId("ses_0123456789");- const prompt = renderer.readPrompt();+ const prompt = readPrompt(renderer);input.ctrlC();input.ctrlC();await expect(prompt).rejects.toThrow("Interrupted");@@ -165,7 +247,7 @@ describe("TerminalRenderer (inline scrollback)", () => {const latest = makeRenderer();latest.renderer.setSessionId("ses_first");latest.renderer.setSessionId("ses_second");- const latestPrompt = latest.renderer.readPrompt();+ const latestPrompt = readPrompt(latest.renderer);latest.input.ctrlC();latest.input.ctrlC();await expect(latestPrompt).rejects.toThrow("Interrupted");@@ -177,7 +259,7 @@ describe("TerminalRenderer (inline scrollback)", () => {it("restores the terminal when a forced process exit preempts teardown", async () => {const before = process.listeners("exit");const { screen, input, renderer } = makeRenderer();- const prompt = renderer.readPrompt();+ const prompt = readPrompt(renderer);const added = process.listeners("exit").filter((listener) => !before.includes(listener));expect(added).toHaveLength(1);@@ -212,459 +294,6 @@ describe("TerminalRenderer (inline scrollback)", () => {expect(snapshot).not.toContain("http://localhost:3000");});- it("updates the status model without repeating an unchanged agent card", async () => {- const { screen, renderer } = makeRenderer();- renderer.renderAgentHeader({- info: agentInfoWithModel("old-model"),- name: "Weather Agent",- serverUrl: "http://localhost:3000",- });- await renderer.renderStream(- streamOf([- { type: "assistant-delta", id: "t1", delta: "still here" },- { type: "assistant-complete", id: "t1" },- { type: "finish" },- ]),- { submittedPrompt: "hello", continueSession: true },- );-- renderer.renderAgentHeader({- info: agentInfoWithModel("new-model"),- name: "Weather Agent",- serverUrl: "http://localhost:3000",- });-- const snapshot = screen.snapshot();- expect(snapshot).toContain("new-model");- expect(snapshot).not.toContain("old-model");- expect(snapshot.match(/☰eve v\d/gu)).toHaveLength(1);- expect(snapshot).toContain("hello");- expect(snapshot).toContain("still here");- renderer.shutdown();- });-- it("streams an assistant message and a tool call into scrollback", async () => {- const { screen, renderer } = makeRenderer();- await renderer.renderStream(- streamOf([- {- type: "step-start",- },- {- type: "tool-call",- toolCallId: "c1",- toolName: "get_weather",- input: { city: "SF" },- },- { type: "tool-result", toolCallId: "c1", output: { tempF: 73 } },- { type: "assistant-delta", id: "t1", delta: "It's **73°F** in SF." },- { type: "assistant-complete", id: "t1" },- { type: "finish" },- ]),- { submittedPrompt: "weather in SF?", continueSession: false },- );-- const snapshot = screen.snapshot();- expect(snapshot).toContain("weather in SF?");- expect(snapshot).toContain("get_weather");- expect(snapshot).toContain("It's 73°F in SF.");- });-- it("replaces discarded retry text with the authoritative completed message", async () => {- const { screen, renderer } = makeRenderer();- await renderer.renderStream(- streamOf([- { type: "assistant-delta", id: "t1", delta: "Discard this partial response." },- { type: "assistant-delta", id: "t1", delta: "Recovered answer." },- { type: "assistant-complete", id: "t1", text: "Recovered answer." },- { type: "finish" },- ]),- { submittedPrompt: "continue", continueSession: false },- );-- const snapshot = screen.snapshot();- expect(snapshot).not.toContain("Discard this partial response.");- expect(snapshot.match(/Recovered answer\./gu)).toHaveLength(1);- });-- it("renders rejected tools as denied", async () => {- const { screen, renderer } = makeRenderer();- await renderer.renderStream(- streamOf([- {- type: "tool-call",- toolCallId: "c1",- toolName: "bash",- input: { command: "rm something" },- },- { type: "tool-rejected", toolCallId: "c1", reason: "Denied by user." },- { type: "finish" },- ]),- { submittedPrompt: "remove it", continueSession: false },- );-- const snapshot = screen.snapshot();- expect(snapshot).toContain("Run rm something");- expect(snapshot).toContain("denied");- expect(snapshot).not.toContain("✓ Run");- renderer.shutdown();- });-- it("renders web_fetch as a concise semantic activity", async () => {- const { screen, renderer } = makeRenderer();- await renderer.renderStream(- streamOf([- {- type: "tool-call",- toolCallId: "fetch-1",- toolName: "web_fetch",- input: {- format: "markdown",- url: "https://github.com/vercel/eve/issues/648",- },- },- {- type: "tool-result",- toolCallId: "fetch-1",- output: { content: "large fetched page" },- },- { type: "finish" },- ]),- { submittedPrompt: "fetch the issue", continueSession: false },- );-- const snapshot = screen.snapshot();- expect(snapshot).toContain("Fetched https://github.com/vercel/eve/issues/648");- expect(snapshot).not.toContain("format=markdown");- expect(snapshot).not.toContain("large fetched page");- renderer.shutdown();- });-- it("coalesces a same-status fetch cohort without merging call state", async () => {- const { screen, renderer } = makeRenderer();- await renderer.renderStream(- streamOf([- {- type: "tool-call",- toolCallId: "fetch-1",- toolName: "web_fetch",- input: { url: "https://one.example" },- },- {- type: "tool-call",- toolCallId: "fetch-2",- toolName: "web_fetch",- input: { url: "https://two.example" },- },- { type: "tool-result", toolCallId: "fetch-1", output: { content: "one" } },- { type: "tool-result", toolCallId: "fetch-2", output: { content: "two" } },- { type: "finish" },- ]),- { submittedPrompt: "call fetch twice in parallel", continueSession: false },- );-- const snapshot = screen.snapshot();- // A fully settled batch collapses to one past-tense line; the item rail- // is gone from the transcript.- expect(snapshot).toContain("│ call fetch twice in parallel\n\n ▪ Fetched 2 URLs");- expect(snapshot).not.toContain("https://one.example");- expect(snapshot).not.toContain("https://two.example");- renderer.shutdown();- });-- it("partitions a fetch cohort with interleaved failures into per-outcome groups", async () => {- const { screen, renderer } = makeRenderer();- await renderer.renderStream(- streamOf([- {- type: "tool-call",- toolCallId: "fetch-1",- toolName: "web_fetch",- input: { url: "https://one.example" },- },- {- type: "tool-call",- toolCallId: "fetch-2",- toolName: "web_fetch",- input: { url: "https://two.example" },- },- {- type: "tool-call",- toolCallId: "fetch-3",- toolName: "web_fetch",- input: { url: "https://three.example" },- },- {- type: "tool-call",- toolCallId: "fetch-4",- toolName: "web_fetch",- input: { url: "https://four.example" },- },- { type: "tool-result", toolCallId: "fetch-1", output: { content: "one" } },- { type: "tool-error", toolCallId: "fetch-2", errorText: "status 403" },- { type: "tool-result", toolCallId: "fetch-3", output: { content: "three" } },- { type: "tool-error", toolCallId: "fetch-4", errorText: "status 429" },- { type: "finish" },- ]),- { submittedPrompt: "fetch four urls", continueSession: false },- );- renderer.shutdown();-- const snapshot = screen.snapshot();- // Successes collapse to a counted past-tense line; failures keep their- // itemized rail, newest call first, closed by the corner.- expect(snapshot).toContain("▪ Fetched 2 URLs");- expect(snapshot).not.toContain("https://one.example");- expect(snapshot).toContain(- " ⨯ Fetch 2 URLs\n │ https://four.example status 429\n │ https://two.example status 403\n └",- );- });-- it("renders a write as an all-added diff for a new file and a real diff after a read", async () => {- const { screen, renderer } = makeRenderer(120, 60);- await renderer.renderStream(- streamOf([- {- type: "tool-call",- toolCallId: "write-1",- toolName: "write_file",- input: { filePath: "/workspace/knicks.txt", content: "knicks\n" },- },- {- type: "tool-result",- toolCallId: "write-1",- output: { existed: false, path: "/workspace/knicks.txt" },- },- {- type: "tool-call",- toolCallId: "write-2",- toolName: "write_file",- input: { filePath: "/workspace/knicks.txt", content: "knicks\nnets\n" },- },- {- type: "tool-result",- toolCallId: "write-2",- output: { existed: true, path: "/workspace/knicks.txt" },- },- { type: "finish" },- ]),- { submittedPrompt: "write the teams", continueSession: false },- );- renderer.shutdown();-- const snapshot = screen.snapshot();- // First write: the file did not exist, so its content is all additions.- expect(snapshot).toContain(" ▪ Wrote /workspace/knicks.txt\n │+ knicks\n └");- // Second write diffs against the first write's cached content.- expect(snapshot).toContain(" │ knicks\n │+ nets\n └");- });-- it("renders interleaved tool lifecycles in arrival order", async () => {- const { screen, renderer } = makeRenderer();- await renderer.renderStream(- streamOf([- {- type: "tool-call",- toolCallId: "first",- toolName: "first_search",- input: { query: "first" },- },- { type: "tool-result", toolCallId: "first", output: { result: "first result" } },- {- type: "tool-call",- toolCallId: "second",- toolName: "second_search",- input: { query: "second" },- },- { type: "tool-result", toolCallId: "second", output: { result: "second result" } },- { type: "finish" },- ]),- { submittedPrompt: "run both searches", continueSession: false },- );-- const snapshot = screen.snapshot();- expect(snapshot).toContain("▪ first_search");- expect(snapshot).toContain("first result");- expect(snapshot).toContain("▪ second_search");- expect(snapshot).toContain("second result");- expect(snapshot.indexOf("first_search")).toBeLessThan(snapshot.indexOf("second_search"));- renderer.shutdown();- });-- it("renders a concurrent tool batch before any result arrives", async () => {- const { screen, renderer } = makeRenderer(120, 140);- let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;- const rendering = renderer.renderStream(- {- events: new ReadableStream<AgentTUIStreamEvent>({- start(controller) {- streamController = controller;- },- }),- },- { submittedPrompt: "search the tri-state area", continueSession: true },- );-- const controller = streamController;- expect(controller).toBeDefined();- controller?.enqueue({ type: "step-start" });- for (let index = 1; index <= 100; index += 1) {- controller?.enqueue({- type: "tool-call",- toolCallId: `search-${index}`,- toolName: "web_search",- input: { query: `tri-state-${index}` },- });- }-- await screen.waitForText("Search 100 queries");-- const snapshot = screen.snapshot();- // Semantic copy coalesces the running batch into one counted row that- // lists the newest calls first and elides the rest; nothing may render- // as completed yet.- expect(snapshot.match(/tri-state-\d+/g)).toHaveLength(5);- expect(snapshot).toContain("tri-state-100");- expect(snapshot).toContain("(95 more)");- expect(snapshot).not.toContain("Searched");- expect(snapshot).not.toContain("web_search");-- controller?.close();- await rendering;- renderer.shutdown();- });-- it("shows a placeholder while a call's input streams, then upgrades it in place", async () => {- const { screen, renderer } = makeRenderer();- let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;- const rendering = renderer.renderStream(- {- events: new ReadableStream<AgentTUIStreamEvent>({- start(controller) {- streamController = controller;- },- }),- },- { submittedPrompt: "fetch the page", continueSession: true },- );-- const controller = streamController;- controller?.enqueue({ type: "step-start" });- controller?.enqueue({ type: "tool-call-preparing", toolCallId: "c1", toolName: "web_fetch" });- await screen.waitForText("Fetch …");-- controller?.enqueue({- type: "tool-call",- toolCallId: "c1",- toolName: "web_fetch",- input: { url: "https://example.com" },- });- await screen.waitForText("Fetch https://example.com");-- const snapshot = screen.snapshot();- // The placeholder upgraded in place: one block, no leftover "Fetch …" row.- expect(snapshot).not.toContain("Fetch …");- expect(countOccurrences(snapshot, "Fetch https://example.com")).toBe(1);-- controller?.close();- await rendering;- renderer.shutdown();- });-- it("omits the interrupt hint while waiting for the first stream event", async () => {- const { screen, renderer } = makeRenderer();- let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;- const rendering = renderer.renderStream(- {- events: new ReadableStream<AgentTUIStreamEvent>({- start(controller) {- streamController = controller;- },- }),- },- { submittedPrompt: "hello", continueSession: true },- );-- await Promise.resolve();- expect(screen.snapshot()).toContain("Thinking (0s)");- expect(screen.snapshot()).not.toContain("Ctrl+C to interrupt");-- streamController?.close();- await rendering;- renderer.shutdown();- });-- it("keeps the authorization wait status while consuming a callback stream", async () => {- const { screen, renderer } = makeRenderer();- renderer.setConnectionAuthPendingCount(1);- let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;- const rendering = renderer.renderStream(- {- events: new ReadableStream<AgentTUIStreamEvent>({- start(controller) {- streamController = controller;- },- }),- },- { continueSession: true },- );-- await Promise.resolve();- // The bar renders; connection state lives in its own section.- expect(screen.snapshot()).toContain("Thinking (0s)");-- streamController?.close();- await rendering;- renderer.shutdown();- });-- it("shows the live turn bar while waiting for the first stream event", async () => {- vi.useFakeTimers();- try {- const { screen, renderer } = makeRenderer();- renderer.renderAgentHeader({- name: "Weather Agent",- serverUrl: "http://localhost:3000",- info: agentInfoWithModel("gpt-5"),- });- let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;- const rendering = renderer.renderStream(- {- events: new ReadableStream<AgentTUIStreamEvent>({- start(controller) {- streamController = controller;- },- }),- },- { submittedPrompt: "hello", continueSession: true },- );-- await Promise.resolve();- let lines = screen.snapshot().split("\n");- let barRow = lines.findIndex((line) => line === "• Thinking (0s)");- expect(barRow).toBeGreaterThan(-1);- // The pending prompt row wears the same default-color `❯` as the idle one- // beneath the bar; the status line follows it.- expect(lines[barRow + 1]).toBe("");- expect(lines[barRow + 2]).toContain("❯");- expect(lines[barRow + 4]).toContain("gpt-5");-- // Advance past the second boundary so the shared paint ticker catches it.- await vi.advanceTimersByTimeAsync(2_100);- lines = screen.snapshot().split("\n");- barRow = lines.findIndex((line) => line.includes("Thinking (2s)"));- expect(barRow).toBeGreaterThan(-1);- expect(lines[barRow + 2]).toContain("❯");- expect(lines[barRow + 4]).toContain("gpt-5");-- streamController?.close();- await rendering;- renderer.shutdown();- } finally {- vi.useRealTimers();- }- });-it("uses an ASCII fallback for the turn pulse", async () => {const screen = new MockScreen({ columns: 80, rows: 30 });const input = new MockUserInput();@@ -674,73 +303,23 @@ describe("TerminalRenderer (inline scrollback)", () => {captureForeignOutput: false,unicode: false,});- const prompt = renderer.readPrompt();+ const prompt = readPrompt(renderer);input.type("hello");input.enter();expect(await prompt).toBe("hello");+ renderer.renderConversation(conversationOf([], { working: true }));expect(screen.snapshot()).toContain("* Thinking (0s)");expect(screen.snapshot()).not.toContain("⊙");renderer.shutdown();});- it("cooperatively cancels a running response on Ctrl+C and preserves the prompt", async () => {- const { screen, input, renderer } = makeRenderer();- let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;- const abort = vi.fn();- const cancel = vi.fn();- const rendering = renderer.renderStream(- {- abort,- cancel,- events: new ReadableStream<AgentTUIStreamEvent>({- start(controller) {- streamController = controller;- },- }),- },- { submittedPrompt: "start a long response", continueSession: true },- );-- streamController?.enqueue({- type: "assistant-delta",- id: "t1",- delta: "partial response",- });- await vi.waitFor(() => {- expect(screen.snapshot()).toContain("partial response");- });-- input.ctrlC();- expect(cancel).toHaveBeenCalledOnce();- expect(abort).not.toHaveBeenCalled();- expect(screen.snapshot()).toContain("Cancelling turn…");-- streamController?.enqueue({ type: "turn-cancelled" });- streamController?.close();- await expect(rendering).resolves.toBeUndefined();-- expect(screen.snapshot()).toContain("Cancelled");- expect(input.rawModes).toEqual([true]);- expect(screen.rawOutput()).toContain("\x1b[?2004h");-- // Control returns to the prompt rather than exiting; the next prompt works.- const nextPrompt = renderer.readPrompt();- input.type("still here");- input.enter();- await expect(nextPrompt).resolves.toBe("still here");-- renderer.shutdown();- expect(input.rawModes).toEqual([true, false]);- expect(screen.rawOutput()).toContain("\x1b[?2004l");- });-it("reassembles and renders a byte-split multi-line paste", async () => {const { screen, input, renderer } = makeRenderer();const text = "first 😀\nsecond 界";- const prompt = renderer.readPrompt();+ const prompt = readPrompt(renderer);for (const byte of Buffer.from(`\x1b[200~${text}\x1b[201~`)) {input.emit("data", Buffer.of(byte));}@@ -760,7 +339,7 @@ describe("TerminalRenderer (inline scrollback)", () => {it("clears and arms on the first idle Ctrl+C, then exits on a second press", async () => {const { screen, input, renderer } = makeRenderer();- const prompt = renderer.readPrompt();+ const prompt = readPrompt(renderer);input.type("draft message");input.ctrlC();expect(renderer.exitRequested()).toBe(false);@@ -773,7 +352,7 @@ describe("TerminalRenderer (inline scrollback)", () => {expect(await prompt).toBe("real message");// Consecutive Ctrl+C presses on the now-empty prompt quit.- const second = renderer.readPrompt();+ const second = readPrompt(renderer);input.ctrlC();expect(renderer.exitRequested()).toBe(false);expect(screen.snapshot()).toContain("Press Ctrl+C again to exit");@@ -787,7 +366,7 @@ describe("TerminalRenderer (inline scrollback)", () => {it("does not yank-pop after a controller-owned repaint key", async () => {const { input, renderer } = makeRenderer();- const prompt = renderer.readPrompt();+ const prompt = readPrompt(renderer);input.type("one");input.send("\u0015"); // Ctrl+Uinput.type("two");@@ -804,7 +383,7 @@ describe("TerminalRenderer (inline scrollback)", () => {it("windows a line longer than the terminal around the caret", async () => {const { screen, input, renderer } = makeRenderer(20); // narrow terminal- const prompt = renderer.readPrompt();+ const prompt = readPrompt(renderer);input.type("abcdefghijklmnopqrstuvwxyz"); // 26 chars into ~18 columns of roomconst snapshot = screen.snapshot();@@ -820,7 +399,7 @@ describe("TerminalRenderer (inline scrollback)", () => {it("draws the block cursor over the character under it without inserting a cell", async () => {const { screen, input, renderer } = makeRenderer();- const prompt = renderer.readPrompt();+ const prompt = readPrompt(renderer);input.type("hello");input.left();input.left(); // caret between "hel" and "lo"@@ -841,7 +420,7 @@ describe("TerminalRenderer (inline scrollback)", () => {vi.useFakeTimers();try {const { input, renderer } = makeRenderer();- const prompt = renderer.readPrompt();+ const prompt = readPrompt(renderer);input.send("\x1b[200~first\nsecond"); // paste start, closing marker never arrivesvi.advanceTimersByTime(1_100); // past the incomplete-paste flushinput.type("X"); // input still works rather than being wedged@@ -856,7 +435,7 @@ describe("TerminalRenderer (inline scrollback)", () => {it("inserts a newline on Shift+Enter and submits the whole multi-line buffer", async () => {const { input, renderer } = makeRenderer();- const prompt = renderer.readPrompt();+ const prompt = readPrompt(renderer);input.type("line one");input.send("\x1b[27;2;13~"); // Shift+Enter (xterm modifyOtherKeys)input.type("line two");@@ -869,7 +448,7 @@ describe("TerminalRenderer (inline scrollback)", () => {it("moves the caret into the line above on ↑, then edits it", async () => {const { input, renderer } = makeRenderer();- const prompt = renderer.readPrompt();+ const prompt = readPrompt(renderer);input.send("\x1b[200~ab\ncd\x1b[201~"); // caret lands after "cd"input.up(); // to the end of "ab"input.type("X");@@ -883,7 +462,7 @@ describe("TerminalRenderer (inline scrollback)", () => {const { screen, input, renderer } = makeRenderer(40, 8);const lines = Array.from({ length: 20 }, (_, index) => `line ${index + 1}`);- const prompt = renderer.readPrompt();+ const prompt = readPrompt(renderer);input.send(`\x1b[200~${lines.join("\n")}\x1b[201~`);expect(screen.snapshot().split("\n").length).toBeLessThanOrEqual(8);@@ -902,697 +481,39 @@ describe("TerminalRenderer (inline scrollback)", () => {renderer.shutdown();});- it("renders reused stream block ids across separate prompt turns", async () => {+ it("commits the one-line session boundary", () => {const { screen, renderer } = makeRenderer();-- await renderer.renderStream(- streamOf([- { type: "tool-call", toolCallId: "call_get_weather", toolName: "get_weather", input: {} },- { type: "tool-result", toolCallId: "call_get_weather", output: { tempF: 72 } },- { type: "assistant-delta", id: "text:turn-0:0", delta: "first answer" },- { type: "assistant-complete", id: "text:turn-0:0" },- { type: "finish" },- ]),- { submittedPrompt: "first prompt", continueSession: true },- );-- await renderer.renderStream(- streamOf([- { type: "tool-call", toolCallId: "call_get_weather", toolName: "get_weather", input: {} },- { type: "tool-result", toolCallId: "call_get_weather", output: { tempF: 73 } },- { type: "assistant-delta", id: "text:turn-0:0", delta: "second answer" },- { type: "assistant-complete", id: "text:turn-0:0" },- { type: "finish" },- ]),- { submittedPrompt: "second prompt", continueSession: true },- );+ renderer.renderNotice("anchor");+ renderer.renderSessionBoundary();renderer.shutdown();const snapshot = screen.snapshot();- expect(snapshot).toContain("first answer");- expect(snapshot).toContain("second answer");- expect(countOccurrences(snapshot, "get_weather")).toBe(2);+ expect(snapshot).toContain("┌── Session restarted, clear context.");});- it("settles a tool block when its result arrives in a later stream pass", async () => {- const { screen, renderer } = makeRenderer();-- await renderer.renderStream(- streamOf([- { type: "tool-call", toolCallId: "call_bash", toolName: "bash", input: { command: "ls" } },- { type: "finish" },- ]),- { submittedPrompt: "list files", continueSession: true },- );- expect(screen.snapshot()).toContain("Run ls");- expect(screen.snapshot()).not.toContain("Ran ls");+ it("never submits an empty or whitespace-only prompt", async () => {+ const { input, renderer } = makeRenderer();- await renderer.renderStream(- streamOf([- {- type: "tool-result",- toolCallId: "call_bash",- output: { exitCode: 0, stderr: "", stdout: "weather-codes.md\n" },- },- { type: "finish" },- ]),- { continueSession: true },- );- renderer.shutdown();-- const snapshot = screen.snapshot();- expect(snapshot).toContain("▪ Ran ls");- });-- 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.upsertConnectionAuth({- name: "linear",- description: "Authorization required for linear",- state: "required",- challenge: { url: "https://connect.vercel.com/authorize/linear" },- });-- await renderer.renderStream(streamOf([{ type: "finish" }]), { continueSession: true });-- renderer.upsertConnectionAuth({- name: "linear",- description: "Authorization required for linear",- state: "pending",- challenge: { url: "https://connect.vercel.com/authorize/linear" },- });- expect(screen.snapshot()).toContain("linear · authorization · pending");-- await renderer.renderStream(streamOf([{ type: "finish" }]), { continueSession: true });-- renderer.upsertConnectionAuth({- name: "linear",- description: "Authorization required for linear",- state: "authorized",- challenge: { url: "https://connect.vercel.com/authorize/linear" },- });- 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");- expect(snapshot).not.toContain("linear · authorization · pending");- expect(snapshot).not.toContain("Authorization required for linear");- expect(snapshot).not.toContain("https://connect.vercel.com/authorize/linear");- });-- it("does not commit partial live assistant rows while streaming over the viewport", async () => {- const { screen, renderer } = makeRenderer(34, 8);- const words = Array.from(- { length: 44 },- (_, index) => `word-${String(index + 1).padStart(2, "0")}`,- );- await renderer.renderStream(- streamOf([- ...words.map((word) => ({- type: "assistant-delta" as const,- id: "t1",- delta: `${word} `,- })),- { type: "assistant-complete", id: "t1" },- { type: "finish" },- ]),- { submittedPrompt: "overflow please", continueSession: false },- );-- const snapshot = screen.snapshot();- expect(countOccurrences(snapshot, "word-01")).toBe(1);- expect(countOccurrences(snapshot, "word-22")).toBe(1);- expect(countOccurrences(snapshot, "word-44")).toBe(1);- });-- it("strips terminal controls from streamed and out-of-band content", async () => {- const { screen, renderer } = makeRenderer(100, 40);- const osc = "\x1b]52;c;cGFzdGU=\x07";- const dcs = "\x1bPqpayload\x1b\\";- const c1Osc = "\u009d0;title\u009c";-- renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });- renderer.upsertConnectionAuth({- name: `conn${osc}`,- description: `desc ${osc}`,- state: "required",- challenge: {- url: `https://example.com/${osc}`,- userCode: `code${dcs}`,- instructions: `follow ${c1Osc}`,- },- reason: `because ${osc}`,- });-- await renderer.renderStream(- streamOf([- { type: "reasoning-delta", id: "r1", delta: `safe reason ${osc}` },- { type: "reasoning-complete", id: "r1" },- {- type: "tool-call",- toolCallId: "c1",- toolName: `get_weather${osc}`,- input: { [`city${osc}`]: `SF${dcs}` },- },- { type: "tool-result", toolCallId: "c1", output: { text: `done ${c1Osc}` } },- { type: "assistant-delta", id: "t1", delta: `safe assistant ${osc}` },- { type: "assistant-complete", id: "t1" },- { type: "task-started", toolCallId: "s1", kind: "agent", toolName: `researcher${osc}` },- { type: "error", errorText: `session failed ${dcs}`, detail: `detail ${osc}` },- { type: "finish" },- ]),- { continueSession: true, reasoning: "full", tools: "full" },- );-- renderer.upsertSubagentStep({- callId: "s1",- subagentName: `researcher${osc}`,- sectionKey: 0,- reasoning: `child reason ${osc}`,- message: `child message ${dcs}`,- finalized: true,- });- renderer.upsertSubagentTool({- callId: "s1",- subagentName: `researcher${osc}`,- childCallId: "cc1",- toolName: `lookup${osc}`,- input: { query: `weather${dcs}` },- status: "done",- output: { result: `clear${c1Osc}` },- });-- const raw = screen.rawOutput();- expect(raw).toContain("safe assistant");- expect(raw).toContain("safe reason");- expect(raw).toContain("get_weather");- expect(raw).toContain("session failed");- expect(raw).toContain("researcher");- expect(raw).toContain("conn");- expect(raw).not.toContain("\x1b]");- expect(raw).not.toContain("\x1bP");- expect(raw).not.toContain("\x1b\\");- expect(raw).not.toContain("\x07");- expect(raw).not.toContain("\u009d");- expect(raw).not.toContain("\u009c");- renderer.shutdown();- });-- describe("tasks", () => {- function taskStream() {- let controller: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;- const result: AgentTUIStreamResult = {- events: new ReadableStream<AgentTUIStreamEvent>({- start(next) {- controller = next;- },- }),- };- return {- result,- push: (...events: AgentTUIStreamEvent[]) => {- for (const event of events) controller?.enqueue(event);- },- close: () => controller?.close(),- };- }-- const delegate: AgentTUIStreamEvent[] = [- { type: "step-start" },- {- type: "tool-call",- toolCallId: "call-r",- toolName: "researcher",- input: { message: "Find the Q3 revenue numbers\nand cite sources" },- },- { type: "task-started", toolCallId: "call-r", kind: "agent", toolName: "researcher" },- { type: "assistant-delta", id: "t1", delta: "I asked the researcher to dig in." },- { type: "assistant-complete", id: "t1" },- { type: "step-finish" },- ];-- const childTool = (status: SubagentToolUpdate["status"], input?: unknown) => {- const update: SubagentToolUpdate = {- callId: "call-r",- subagentName: "researcher",- childCallId: "fetch-1",- toolName: "web_fetch",- input,- status,- };- if (status === "done") update.output = "<html>";- return update;- };-- it("writes the transcript once while the panel shows what each task is doing", async () => {- const { screen, renderer } = makeRenderer();- renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });- const stream = taskStream();- const rendering = renderer.renderStream(stream.result, { continueSession: true });-- stream.push(...delegate);- await screen.waitForText("Waiting for researcher");- // The call row became the start line in place; the model-facing- // delegation row is gone.- expect(screen.snapshot()).toContain("※ researcher Find the Q3 revenue numbers");- expect(screen.snapshot()).not.toContain("Delegate");- const writtenBeforeActivity = screen.rawOutput().length;-- renderer.upsertSubagentTool(childTool("preparing"));- expect(screen.snapshot()).toMatch(/※ researcher\s+Fetch …/u);- renderer.upsertSubagentTool(childTool("executing", { url: "https://ir.example" }));- expect(screen.snapshot()).toMatch(/※ researcher\s+Fetch https:\/\/ir\.example/u);- renderer.upsertSubagentTool(childTool("done", { url: "https://ir.example" }));-- stream.push({ type: "task-settled", toolCallId: "call-r", status: "completed" });- await screen.waitForText("✓ researcher");- stream.close();- await rendering;- renderer.shutdown();-- // The start line and the reply were already in scrollback: live rows- // repaint on every update, but nothing the agent did rewrote them.- const writtenSince = stripAnsi(screen.rawOutput().slice(writtenBeforeActivity));- expect(writtenSince).not.toContain("Find the Q3 revenue numbers");- expect(writtenSince).not.toContain("I asked the researcher to dig in.");- expect(screen.snapshot()).toMatch(/✓ researcher {2}finished in \d+s · Fetched 1 URL/u);- });-- it("names a self-modification task as the agent editor modifying your agent", async () => {- const { screen, renderer } = makeRenderer();- renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });- const stream = taskStream();- const rendering = renderer.renderStream(stream.result, { continueSession: true });-- stream.push(- { type: "step-start" },- {- type: "tool-call",- toolCallId: "call-s",- toolName: "self-modification__agent",- input: { message: "Add a tool that reports the forecast" },- },- {- type: "task-started",- toolCallId: "call-s",- kind: "agent",- toolName: "self-modification__agent",- },- { type: "step-finish" },- );- await screen.waitForText("Modifying your agent");- expect(screen.snapshot()).toContain("※ agent editor Add a tool that reports the forecast");- expect(screen.snapshot()).not.toContain("self-modification__agent");-- stream.push({ type: "task-settled", toolCallId: "call-s", status: "completed" });- await screen.waitForText("✓ agent editor");- stream.close();- await rendering;- renderer.shutdown();- });-- it("waits for an agent's own last events before writing its end line", async () => {- const { screen, renderer } = makeRenderer();- renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });- const stream = taskStream();- const rendering = renderer.renderStream(stream.result, { continueSession: true });- stream.push(...delegate);- await screen.waitForText("Waiting for researcher");- renderer.subagents.begin({ callId: "call-r" });-- stream.push({ type: "task-settled", toolCallId: "call-r", status: "completed" });- await screen.waitForText("Finishing");- expect(screen.snapshot()).not.toContain("✓ researcher");-- // The agent's last call reaches the TUI after its parent settled the task.- renderer.upsertSubagentTool(childTool("done", { url: "https://ir.example" }));- renderer.subagents.end({ callId: "call-r" });- expect(screen.snapshot()).toMatch(/✓ researcher {2}finished in \d+s · Fetched 1 URL/u);-- stream.close();- await rendering;- renderer.shutdown();- });-- it("writes a waiting end line once the turn's stream ends", async () => {- const { screen, renderer } = makeRenderer();- renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });- renderer.subagents.begin({ callId: "call-r" });- await renderer.renderStream(- streamOf([- ...delegate,- { type: "task-settled", toolCallId: "call-r", status: "completed" },- { type: "finish" },- ]),- { continueSession: true },- );- renderer.shutdown();-- expect(screen.snapshot()).toMatch(/✓ researcher {2}finished in \d+s/u);- expect(screen.snapshot()).not.toContain("Finishing");- });-- it("closes working tasks before a session restart", async () => {- const { screen, renderer } = makeRenderer();- renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });- await renderer.renderStream(streamOf([...delegate, { type: "finish" }]), {- continueSession: true,- });- renderer.renderSessionBoundary();- renderer.shutdown();-- const snapshot = screen.snapshot();- const stopped = snapshot.indexOf("▪ researcher stopped");- expect(stopped).toBeGreaterThan(-1);- expect(stopped).toBeLessThan(snapshot.indexOf("Session restarted"));- });-- it("names an agent task's request even when tool rows are hidden", async () => {- const screen = new MockScreen({ columns: 80, rows: 30 });- const renderer = new TerminalRenderer({- input: new MockUserInput(),- output: screen,- captureForeignOutput: false,- unicode: true,- tools: "hidden",- });- renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });- await renderer.renderStream(streamOf([...delegate, { type: "finish" }]), {- continueSession: true,- });- renderer.shutdown();-- expect(screen.snapshot()).toContain("※ researcher Find the Q3 revenue numbers");- });-- it("logs why an agent's own call was refused for its model to retry", async () => {- const screen = new MockScreen({ columns: 80, rows: 30 });- const stub = stubDiagnostics();- const renderer = new TerminalRenderer({- input: new MockUserInput(),- output: screen,- captureForeignOutput: false,- unicode: true,- diagnostics: stub.diagnostics,- });- await renderer.renderStream(streamOf([...delegate, { type: "finish" }]), {- continueSession: true,- });- renderer.upsertSubagentTool(childTool("executing", { url: "https://ir.example" }));- renderer.removeSubagentTool({- callId: "call-r",- childCallId: "fetch-1",- reason: "8 tasks are already working",- });- renderer.shutdown();-- expect(stub.append).toHaveBeenCalledWith({- source: "tool",- summary: "web_fetch was refused for the model to retry",- detail: "8 tasks are already working",- });- });-- it("ends a stopped or failed task with what happened, not Done", async () => {- const { screen, renderer } = makeRenderer();- renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });- await renderer.renderStream(- streamOf([- ...delegate,- { type: "task-started", toolCallId: "call-d", kind: "tool", toolName: "deploy" },- { type: "task-settled", toolCallId: "call-r", status: "cancelled" },- {- type: "task-settled",- toolCallId: "call-d",- status: "failed",- errorText: "Preview build failed\nstack…",- },- { type: "finish" },- ]),- { continueSession: true },- );- renderer.shutdown();-- const snapshot = screen.snapshot();- expect(snapshot).toContain("▪ researcher stopped");- expect(snapshot).toContain("⨯ deploy failed · Preview build failed");- expect(snapshot).not.toContain("stack…");- });-- it("reads a cancelled turn's unfinished tasks as stopped", async () => {- const { screen, renderer } = makeRenderer();- renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });- await renderer.renderStream(- streamOf([...delegate, { type: "turn-cancelled" }, { type: "finish" }]),- { continueSession: true },- );- renderer.shutdown();-- expect(screen.snapshot()).toContain("▪ researcher stopped");- expect(screen.snapshot()).not.toContain("Waiting for researcher");- });-- it("tells parallel calls to one agent apart without renaming the first", async () => {- const { screen, renderer } = makeRenderer();- renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });- const stream = taskStream();- const rendering = renderer.renderStream(stream.result, { continueSession: true });- stream.push(...delegate, {- type: "task-started",- toolCallId: "call-r2",- kind: "agent",- toolName: "researcher",- });- await screen.waitForText("Waiting for researcher and researcher #2");- stream.close();- await rendering;- renderer.shutdown();-- expect(screen.snapshot()).toContain("※ researcher Find the Q3 revenue numbers");- expect(screen.snapshot()).toContain("※ researcher #2");- });-- it("writes an agent's finished messages under --subagents full", async () => {- const screen = new MockScreen({ columns: 80, rows: 30 });- const renderer = new TerminalRenderer({- input: new MockUserInput(),- output: screen,- captureForeignOutput: false,- unicode: true,- subagents: "full",- });- renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });- const stream = taskStream();- const rendering = renderer.renderStream(stream.result, { continueSession: true });- stream.push(...delegate);- await screen.waitForText("Waiting for researcher");-- const step = {- callId: "call-r",- subagentName: "researcher",- sectionKey: 0,- reasoning: "",- message: "Revenue grew 12% year over year.",- };- renderer.upsertSubagentStep({ ...step, finalized: false });- renderer.upsertSubagentStep({ ...step, finalized: true });- renderer.upsertSubagentStep({ ...step, finalized: true });- stream.close();- await rendering;- renderer.shutdown();-- expect(screen.snapshot()).toContain("※ researcher\n │ Revenue grew 12% year over year.");- expect(countOccurrences(stripAnsi(screen.rawOutput()), "│ Revenue grew 12%")).toBe(1);- });-- it("shows neither lines nor panel rows for agents under --subagents hidden", async () => {- const screen = new MockScreen({ columns: 80, rows: 30 });- const renderer = new TerminalRenderer({- input: new MockUserInput(),- output: screen,- captureForeignOutput: false,- unicode: true,- subagents: "hidden",- });- renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });- await renderer.renderStream(streamOf([...delegate, { type: "finish" }]), {- continueSession: true,- });- renderer.shutdown();-- expect(screen.snapshot()).not.toContain("※");- expect(screen.snapshot()).not.toContain("Find the Q3");- });-- it("leaves no trace of a call refused for the model to retry", async () => {- const { screen, renderer } = makeRenderer();- await renderer.renderStream(- streamOf([- { type: "tool-call", toolCallId: "c1", toolName: "deploy", input: { env: "preview" } },- { type: "tool-withdrawn", toolCallId: "c1", reason: "8 tasks are already working" },- { type: "assistant-delta", id: "t1", delta: "Queued the deploy." },- { type: "assistant-complete", id: "t1" },- { type: "finish" },- ]),- { submittedPrompt: "deploy", continueSession: true },- );- renderer.shutdown();-- expect(screen.snapshot()).not.toContain("deploy ");- expect(screen.snapshot()).not.toContain("already working");- });-- it("titles a tool by its own label instead of its raw arguments", async () => {- const { screen, renderer } = makeRenderer();- await renderer.renderStream(- streamOf([- {- type: "tool-call",- toolCallId: "c1",- toolName: "deploy",- input: { project: "storefront", environment: "production" },- label: "Deploy storefront to production",- },- {- type: "tool-result",- toolCallId: "c1",- output: { url: "https://storefront.example" },- label: "Deployed storefront",- },- { type: "finish" },- ]),- { submittedPrompt: "ship it", continueSession: true },- );- renderer.shutdown();-- expect(screen.snapshot()).toContain("Deployed storefront");- expect(screen.snapshot()).not.toContain("environment=");- });- });-- it("commits the one-line session boundary", () => {- const { screen, renderer } = makeRenderer();- renderer.renderNotice("anchor");- renderer.renderSessionBoundary();- renderer.shutdown();-- const snapshot = screen.snapshot();- expect(snapshot).toContain("┌── Session restarted, clear context.");- });-- it("closes the dying turn's coda at the boundary", async () => {- const { screen, input, renderer } = makeRenderer();- const prompt = renderer.readPrompt();- input.type("hey agent");- input.enter();- expect(await prompt).toBe("hey agent");-- await renderer.renderStream(- streamOf([- { type: "step-start" },- { type: "assistant-delta", id: "m1", delta: "working" },- { type: "assistant-complete", id: "m1" },- { type: "step-finish", usage: { inputTokens: 25_000, outputTokens: 40 } },- { type: "finish", usage: { inputTokens: 25_000, outputTokens: 40 } },- ]),- { continueSession: true },- );-- renderer.renderSessionBoundary();- const snapshot = screen.snapshot();- // The dead turn's stats close before the boundary, not after it.- expect(snapshot.indexOf("Done in")).toBeGreaterThan(-1);- expect(snapshot.indexOf("Done in")).toBeLessThan(snapshot.indexOf("┌── Session restarted"));-- // Control returning to the prompt must not add a second coda.- const second = renderer.readPrompt();- expect(countOccurrences(screen.snapshot(), "Done in")).toBe(1);- input.ctrlC();- expect(screen.snapshot()).toContain("❯");- input.ctrlC();- await expect(second).rejects.toThrow();- renderer.shutdown();- });-- it("shows a typed mid-stream draft behind a dim inert prompt mark", async () => {- const { screen, input, renderer } = makeRenderer();- let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;- const rendering = renderer.renderStream(- {- events: new ReadableStream<AgentTUIStreamEvent>({- start(controller) {- streamController = controller;- },- }),- },- { submittedPrompt: "hello", continueSession: true },- );- await Promise.resolve();-- // Empty: the default-color prompt mark.- expect(screen.snapshot()).toContain("❯");-- // A typed draft dims the mark — Enter is inert, so- // the cyan ready state would overclaim.- input.type("next question");- await screen.waitForText("❯ next question");- expect(screen.rawOutput()).toContain("\x1b[2m❯\x1b[22m");- expect(screen.rawOutput()).not.toContain("\x1b[36m❯");-- streamController?.close();- await rendering;- 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: "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();-- const prompt = renderer.readPrompt();- input.enter();- input.type(" ");- input.enter();- // The reader is still armed: only real content resolves it.- input.type("hello");- input.enter();- expect(await prompt).toBe(" hello");+ const prompt = readPrompt(renderer);+ input.enter();+ input.type(" ");+ input.enter();+ // The reader is still armed: only real content resolves it.+ input.type("hello");+ input.enter();+ expect(await prompt).toBe(" hello");renderer.shutdown();});it("recalls a previous prompt with the up arrow", async () => {const { input, renderer } = makeRenderer();- const first = renderer.readPrompt();+ const first = readPrompt(renderer);input.type("first message");input.enter();expect(await first).toBe("first message");- const second = renderer.readPrompt();+ const second = readPrompt(renderer);input.type("draft");input.up();input.enter();@@ -1694,22 +615,6 @@ describe("TerminalRenderer (inline scrollback)", () => {renderer.shutdown();});- it("keeps a running command pending when an idle session stream closes", async () => {- const { screen, renderer } = makeRenderer();- renderer.renderCommandInvocation("/model anthropic/claude-opus-4.6 default");- await renderer.renderIdleStream(streamOf([]));- renderer.finishCommand({- kind: "result",- message: "",- summary: "Model set to anthropic/claude-opus-4.6 default",- });- renderer.shutdown();-- const snapshot = screen.snapshot();- expect(snapshot).toMatch(/^\* Model set to anthropic\/claude-opus-4.6 default$/m);- expect(snapshot).not.toContain("/model anthropic");- });-it("replaces a settled command with its dimmed summary", () => {const { screen, renderer } = makeRenderer();renderer.renderCommandInvocation("/add connection/notion");@@ -1727,840 +632,108 @@ describe("TerminalRenderer (inline scrollback)", () => {const { screen, renderer } = makeRenderer();renderer.renderCommandInvocation("/add channel/slack");renderer.finishCommand({- kind: "result",- message: "Finish with `eve add channel/slack --skip-install`",- summary: "Added channel/slack · setup not finished",- });- renderer.shutdown();-- expect(screen.snapshot()).toMatch(- /^\* Added channel\/slack · setup not finished\n {3}⎿ {2}Finish with `eve add channel\/slack --skip-install`$/m,- );- });-- it("keeps the invocation when a settled command has no summary", () => {- const { screen, renderer } = makeRenderer();- renderer.renderCommandInvocation("/deploy");- renderer.finishCommand({ kind: "result", message: "Deployed: https://example.vercel.app" });- renderer.shutdown();-- expect(screen.snapshot()).toMatch(- /^\* \/deploy\n {3}⎿ {2}Deployed: https:\/\/example.vercel.app$/m,- );- });-- it("marks a failed automatic command and keeps its multiline outcome in one result block", () => {- const { screen, renderer } = makeRenderer();- renderer.renderCommandInvocation("/deploy");- renderer.finishCommand({- kind: "result",- message:- "Authentication was refreshed, but example.vercel.app is unavailable: Access denied.\n\n" +- "TRUSTED_SOURCES_ENVIRONMENT_MISMATCH",- });- renderer.shutdown();-- const snapshot = screen.snapshot();- expect(snapshot).toMatch(/^\* \/deploy$/m);- expect(snapshot).toContain("⎿ Authentication was refreshed");- expect(snapshot).toContain("TRUSTED_SOURCES_ENVIRONMENT_MISMATCH");- expect(snapshot).not.toContain("· Authentication was refreshed");- });-- it("invites with a quiet placeholder until typing starts", async () => {- const { screen, input, renderer } = makeRenderer();-- const prompt = renderer.readPrompt();- // A bare prompt before any info/turn has no status row (no ↑ 0 ↓ 0 counter).- expect(screen.snapshot()).not.toContain("↑ 0");- // Empty buffer: the default-color `❯` gutter with the message invitation.- expect(screen.snapshot()).toContain("❯ Send a message…");- expect(screen.rawOutput()).not.toContain("\x1b[48;5;");-- input.type("hello");- // Typing colors the prompt mark and clears the invitation.- expect(screen.snapshot()).toContain("❯ hello");- expect(screen.snapshot()).not.toContain("Send a message…");- input.enter();- expect(screen.snapshot()).toContain("Thinking (0s)");- expect(await prompt).toBe("hello");- renderer.shutdown();- });-- it("shows the live turn bar as soon as the prompt is submitted", async () => {- vi.useFakeTimers();- try {- const { screen, input, renderer } = makeRenderer();- const prompt = renderer.readPrompt();-- input.type("hello");- input.enter();-- expect(await prompt).toBe("hello");- expect(screen.snapshot()).toContain("• Thinking (0s)");-- let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;- const rendering = renderer.renderStream(- {- events: new ReadableStream<AgentTUIStreamEvent>({- start(controller) {- streamController = controller;- },- }),- },- { continueSession: true },- );- await Promise.resolve();- // The stream keeps the same bar — one working indicator end to end.- expect(screen.snapshot()).not.toContain("⊙");- expect(screen.snapshot()).toContain("Thinking (0s)");-- streamController?.close();- await rendering;- renderer.shutdown();- } finally {- vi.useRealTimers();- }- });-- it("commits an end-of-turn stats coda when control returns to the prompt", async () => {- const { screen, input, renderer } = makeRenderer();-- const prompt = renderer.readPrompt();- input.type("hey agent");- input.enter();- expect(await prompt).toBe("hey agent");-- await renderer.renderStream(- streamOf([- { type: "step-start" },- { type: "assistant-delta", id: "m1", delta: "Hello!" },- { type: "step-finish", usage: { inputTokens: 18_000, outputTokens: 40 } },- { type: "step-start" },- { type: "assistant-complete", id: "m1" },- { type: "step-finish", usage: { inputTokens: 2_500, outputTokens: 3 } },- // The finish event repeats the last step's usage; it must not- // double-count into the turn total.- { type: "finish", usage: { inputTokens: 2_500, outputTokens: 3 } },- ]),- { continueSession: true },- );- // Mid-turn (before control returns to the prompt) there is no coda —- // multi-pass turns must end with exactly one.- expect(screen.snapshot()).not.toContain("\n└ ");-- const second = renderer.readPrompt();- // Tokens are the turn's summed step usage, not the last report; the sum- // crossing the 20K input threshold is what earns the row.- expect(screen.snapshot()).toContain("Done in 1s (↑ 20.5K ↓ 43)");- input.ctrlC();- expect(screen.snapshot()).toContain("❯");- input.ctrlC();- await expect(second).rejects.toThrow();- renderer.shutdown();- });-- it("closes a quick, cheap turn without a stats coda", async () => {- const { screen, input, renderer } = makeRenderer();-- const prompt = renderer.readPrompt();- input.type("hey");- input.enter();- expect(await prompt).toBe("hey");-- await renderer.renderStream(- streamOf([- { type: "step-start" },- { type: "assistant-delta", id: "m1", delta: "Hi!" },- { type: "assistant-complete", id: "m1" },- { type: "step-finish", usage: { inputTokens: 4_500, outputTokens: 43 } },- { type: "finish", usage: { inputTokens: 4_500, outputTokens: 43 } },- ]),- { continueSession: true },- );-- // Under 10s and under 20K turn input: no coda row.- const second = renderer.readPrompt();- expect(screen.snapshot()).not.toContain("\nDone in ");- input.ctrlC();- expect(screen.snapshot()).toContain("❯");- input.ctrlC();- await expect(second).rejects.toThrow();- renderer.shutdown();- });-- it("retires a local cue after the first user message, including after a header refresh", async () => {- const { screen, input, renderer } = makeRenderer();- const info = createTestAgentInfoResult();- const header = {- name: "Orders",- serverUrl: "http://localhost:3000",- localDevelopment: true,- info: {- ...info,- instructions: {- dynamic: [],- static: [- {- ...info.agent.config,- name: "instructions",- role: "system" as const,- content: "Help with orders.",- },- ],- },- subagents: {- total: 1,- local: [- {- ...info.agent.config,- owner: {- kind: "extension" as const,- mountId: "extensions/self-modification",- namespace: "self-modification",- packageName: "eve",- },- name: "self-modification__agent",- entryPath: "subagents/agent/agent.ts",- rootPath: "/eve/self-modification",- nodeId: "self-modification__agent",- parentNodeId: "__root__",- summary: {- channels: 0,- connections: 0,- hooks: 0,- instructions: 1,- memories: 0,- schedules: 0,- skills: 0,- tools: 1,- },- },- ],- },- },- };- renderer.renderAgentHeader(header);-- const first = renderer.readPrompt();- expect(screen.snapshot()).toContain("❯ Send a message, or ask me to add a channel…");- input.type("hello");- input.enter();- expect(await first).toBe("hello");- await renderer.renderStream(streamOf([]), { continueSession: true, submittedPrompt: "hello" });-- renderer.renderAgentHeader(header);- const second = renderer.readPrompt();- expect(screen.snapshot()).toContain("❯");- expect(screen.snapshot()).not.toContain("ask me to add a channel");- input.type("again");- expect(screen.snapshot()).toContain("❯ again");- input.ctrlC();- expect(screen.snapshot()).toContain("❯");- input.ctrlC();- await expect(second).rejects.toThrow();- renderer.shutdown();-- const queued = makeRenderer();- queued.renderer.beginStartupDraft({ title: "Orders" });- queued.input.type("hello from startup");- queued.input.enter();- const startup = queued.renderer.finishStartupDraft();- expect(startup.queuedPrompt).toBe("hello from startup");- queued.renderer.renderAgentHeader(header);- await queued.renderer.renderStream(streamOf([]), {- continueSession: true,- submittedPrompt: startup.queuedPrompt,- });- const afterQueuedMessage = queued.renderer.readPrompt();- expect(queued.screen.snapshot()).not.toContain("ask me to add a channel");- queued.input.ctrlC();- queued.input.ctrlC();- await expect(afterQueuedMessage).rejects.toThrow();- queued.renderer.shutdown();- });-- it("keeps collapsed reasoning out of the transcript behind the turn bar", async () => {- const { screen, renderer } = makeRenderer();- renderer.renderAgentHeader({- name: "Weather Agent",- serverUrl: "http://localhost:3000",- info: agentInfoWithModel("gpt-5"),- });- let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;- const rendering = renderer.renderStream(- {- events: new ReadableStream<AgentTUIStreamEvent>({- start(controller) {- streamController = controller;- },- }),- },- { submittedPrompt: "weather in SF", continueSession: true },- );-- await vi.waitFor(() => {- expect(screen.snapshot()).toContain("Thinking (0s)");- });- streamController?.enqueue({- type: "reasoning-delta",- id: "r1",- delta: "the plan is to check the forecast",- });- await Promise.resolve();- // The trace never reaches the screen; the bar carries the turn.- const lines = screen.snapshot().split("\n");- const barRow = lines.findIndex((line) => line.includes("Thinking (0s)"));- expect(barRow).toBeGreaterThan(-1);- expect(screen.snapshot()).not.toContain("the plan is to check the forecast");- // The pending prompt row holds its place below, then the status line.- expect(lines[barRow + 2]).toContain("❯");- expect(lines[barRow + 4]).toContain("gpt-5");-- streamController?.enqueue({ type: "reasoning-complete", id: "r1" });- streamController?.close();- await rendering;- expect(screen.snapshot()).not.toContain("the plan is to check the forecast");- expect(screen.snapshot()).not.toContain("Thought for");- renderer.shutdown();- });-- it("closes a long thinking turn with the coda, not a thought bar", async () => {- vi.useFakeTimers();- try {- const { screen, input, renderer } = makeRenderer();- const prompt = renderer.readPrompt();- input.type("hard question");- input.enter();- expect(await prompt).toBe("hard question");-- let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;- const rendering = renderer.renderStream(- {- events: new ReadableStream<AgentTUIStreamEvent>({- start(controller) {- streamController = controller;- },- }),- },- { continueSession: true },- );- streamController?.enqueue({ type: "reasoning-delta", id: "r1", delta: "hm" });- await vi.advanceTimersByTimeAsync(12_000);- streamController?.enqueue({ type: "reasoning-complete", id: "r1" });- streamController?.close();- await rendering;-- // 12s of wall clock qualifies the coda; the thought itself leaves no- // separate transcript bar.- const second = renderer.readPrompt();- expect(screen.snapshot()).toContain("Done in 12s");- expect(screen.snapshot()).not.toContain("Thought for");- input.ctrlC();- input.ctrlC();- await expect(second).rejects.toThrow();- renderer.shutdown();- } finally {- vi.useRealTimers();- }- });-- it("queues a mid-turn Enter into the pinned panel and drains it as the next prompt", async () => {- const { screen, input, renderer } = makeRenderer();- let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;- const rendering = renderer.renderStream(- {- events: new ReadableStream<AgentTUIStreamEvent>({- start(controller) {- streamController = controller;- },- }),- },- { submittedPrompt: "long task", continueSession: true },- );-- await vi.waitFor(() => {- // Empty draft: the pending prompt wears the same default-color `❯` as idle- // (readiness is signalled by the turn bar's absence, not the glyph).- expect(screen.snapshot()).toContain("❯");- });- input.type("follow-up question");- // Enter mid-turn queues the draft into the panel and clears the buffer.- input.enter();- await vi.waitFor(() => {- expect(screen.snapshot()).toContain("Queue 1/5");- expect(screen.snapshot()).toContain("└ follow-up question");- });-- streamController?.close();- await rendering;-- // The runner drains the queue as the next turn's prompt.- expect(renderer.takeQueuedPrompt()).toBe("follow-up question");- expect(renderer.takeQueuedPrompt()).toBeUndefined();- renderer.shutdown();- });-- it("runs a mid-turn /cancel as a control instead of queueing it", async () => {- const { screen, input, renderer } = makeRenderer();- let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;- const cancel = vi.fn();- const rendering = renderer.renderStream(- {- cancel,- events: new ReadableStream<AgentTUIStreamEvent>({- start(controller) {- streamController = controller;- },- }),- },- { submittedPrompt: "long task", continueSession: true },- );-- await vi.waitFor(() => {- expect(screen.snapshot()).toContain("❯");- });- input.type("/cancel");- input.enter();-- await vi.waitFor(() => {- expect(cancel).toHaveBeenCalledOnce();- expect(screen.snapshot()).toContain("* Cancellation requested");- expect(screen.snapshot()).not.toContain("/cancel");- expect(screen.snapshot()).toContain("Cancelling turn…");- });-- streamController?.enqueue({ type: "turn-cancelled" });- streamController?.close();- await rendering;-- expect(renderer.takeQueuedPrompt()).toBeUndefined();- expect(screen.snapshot()).toContain("Cancelled");- renderer.shutdown();- });-- it("interrupts a pending /cancel on Ctrl+C and arms the next press to exit", async () => {- const { screen, input, renderer } = makeRenderer();- const abort = vi.fn();- const cancel = vi.fn();- const rendering = renderer.renderStream(- {- abort,- cancel,- events: new ReadableStream<AgentTUIStreamEvent>(),- },- { submittedPrompt: "long task", continueSession: true },- );-- await vi.waitFor(() => {- expect(screen.snapshot()).toContain("❯");- });- input.type("/cancel");- input.enter();- await vi.waitFor(() => {- expect(cancel).toHaveBeenCalledOnce();- expect(screen.snapshot()).toContain("Cancelling turn…");- });-- input.ctrlC();- await expect(rendering).resolves.toBeUndefined();-- expect(abort).toHaveBeenCalledOnce();- expect(cancel).toHaveBeenCalledOnce();- expect(screen.snapshot()).toContain("Interrupted");-- const prompt = renderer.readPrompt();- expect(screen.snapshot()).toContain("Press Ctrl+C again to exit");- input.ctrlC();- await expect(prompt).rejects.toThrow();- expect(renderer.exitRequested()).toBe(true);- renderer.shutdown();- });-- it("steers each Enter message without cancelling the turn", async () => {- const { screen, input, renderer } = makeRenderer();- let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;- const cancel = vi.fn();- const accepted = Promise.withResolvers<void>();- const steer = vi.fn(() => accepted.promise);- const rendering = renderer.renderStream(- {- cancel,- steer,- events: new ReadableStream<AgentTUIStreamEvent>({- start(controller) {- streamController = controller;- },- }),- },- { submittedPrompt: "long task", continueSession: true },- );-- await vi.waitFor(() => {- expect(screen.snapshot()).toContain("❯");- });- input.type("go north");- input.enter();- input.type("go south");- input.enter();- expect(cancel).not.toHaveBeenCalled();- expect(steer).toHaveBeenNthCalledWith(1, "go north");- expect(steer).toHaveBeenNthCalledWith(2, "go south");- expect(screen.snapshot()).not.toContain("Queue");-- accepted.resolve();- streamController?.enqueue({ type: "finish" });- streamController?.close();- await rendering;-- expect(renderer.takeQueuedPrompt()).toBeUndefined();- renderer.shutdown();- });-- it("cancels the turn on the first empty-queue Esc", async () => {- const { screen, input, renderer } = makeRenderer();- const escape = async () => {- input.send("\x1b");- await new Promise((resolve) => setTimeout(resolve, 50));- };- let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;- const cancel = vi.fn();- const rendering = renderer.renderStream(- {- cancel,- events: new ReadableStream<AgentTUIStreamEvent>({- start(controller) {- streamController = controller;- },- }),- },- { submittedPrompt: "long task", continueSession: true },- );- await vi.waitFor(() => {- expect(screen.snapshot()).toContain("❯");- });-- await escape();- expect(cancel).toHaveBeenCalledTimes(1);- expect(screen.snapshot()).toContain("Cancelling turn…");-- streamController?.enqueue({ type: "turn-cancelled" });- streamController?.close();- await rendering;- expect(screen.snapshot()).toContain("Cancelled");- renderer.shutdown();- });-- it("restores the submitted message when the turn is cancelled without an Esc", async () => {- const { screen, input, renderer } = makeRenderer();- let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;- const rendering = renderer.renderStream(- {- events: new ReadableStream<AgentTUIStreamEvent>({- start(controller) {- streamController = controller;- },- }),- },- { submittedPrompt: "go north", continueSession: true },- );- await vi.waitFor(() => {- expect(screen.snapshot()).toContain("│ go north");- });-- // A stale cancel from a previous turn (or /cancel from another client)- // lands on this turn — no Esc was pressed in this stream.- streamController?.enqueue({ type: "turn-cancelled" });- streamController?.close();- await rendering;-- expect(screen.snapshot()).toContain("cancelled from outside this prompt");- const prompt = renderer.readPrompt();- await vi.waitFor(() => {- expect(screen.snapshot()).toContain("❯ go north");- });- input.enter();- expect(await prompt).toBe("go north");- renderer.shutdown();- });-- it("does not restore the message when the user's own Esc cancelled the turn", async () => {- const { screen, input, renderer } = makeRenderer();- const escape = async () => {- input.send("\x1b");- await new Promise((resolve) => setTimeout(resolve, 50));- };- let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;- const rendering = renderer.renderStream(- {- cancel: vi.fn(),- events: new ReadableStream<AgentTUIStreamEvent>({- start(controller) {- streamController = controller;- },- }),- },- { submittedPrompt: "go north", continueSession: true },- );- await vi.waitFor(() => {- expect(screen.snapshot()).toContain("│ go north");- });-- await escape();- await escape();- streamController?.enqueue({ type: "turn-cancelled" });- streamController?.close();- await rendering;-- expect(screen.snapshot()).not.toContain("cancelled from outside this prompt");- renderer.shutdown();- });-- it("renders steered and queued prompts without provenance arrow rows", async () => {- const { screen, input, renderer } = makeRenderer();- const closedStream = () =>- new ReadableStream<AgentTUIStreamEvent>({- start(controller) {- controller.close();- },- });-- // Enter steers immediately without a cancellation key.- const steer = vi.fn(async () => {});- let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;- const first = renderer.renderStream(- {- steer,- events: new ReadableStream<AgentTUIStreamEvent>({- start(controller) {- streamController = controller;- },- }),- },- { submittedPrompt: "long task", continueSession: true },- );- await vi.waitFor(() => {- expect(screen.snapshot()).toContain("❯");- });- input.type("go north");- input.enter();- expect(steer).toHaveBeenCalledWith("go north");- expect(screen.snapshot()).not.toContain("Queue 1/5");- streamController?.enqueue({ type: "finish" });- streamController?.close();- await first;-- expect(renderer.takeQueuedPrompt()).toBeUndefined();- let lines = screen.snapshot().split("\n");- const steerIndex = lines.findIndex((line) => line.includes("│ go north"));- expect(lines[steerIndex - 1]?.trim()).not.toBe("↑");-- // Queue: a message that waited for the natural boundary.- let secondController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;- const second = renderer.renderStream(- {- events: new ReadableStream<AgentTUIStreamEvent>({- start(controller) {- secondController = controller;- },- }),- },- { submittedPrompt: "another task", continueSession: true },- );- await vi.waitFor(() => {- expect(screen.snapshot()).toContain("Thinking (");- });- input.type("go south");- input.enter();- await vi.waitFor(() => {- expect(screen.snapshot()).toContain("Queue 1/5");+ kind: "result",+ message: "Finish with `eve add channel/slack --skip-install`",+ summary: "Added channel/slack · setup not finished",});- secondController?.close();- await second;-- const queued = renderer.takeQueuedPrompt();- expect(queued).toBe("go south");- await renderer.renderStream(- { events: closedStream() },- { submittedPrompt: queued, continueSession: true },- );- lines = screen.snapshot().split("\n");- const queueIndex = lines.findIndex((line) => line.includes("│ go south"));- expect(lines[queueIndex + 1]?.trim()).not.toBe("↑");-- // The ordinary typed prompts carry no arrow.- const typedIndex = lines.findIndex((line) => line.includes("│ long task"));- expect(lines[typedIndex - 1]?.trim()).not.toBe("↑");- expect(lines[typedIndex + 1]?.trim()).not.toBe("↑");renderer.shutdown();- });- it("preserves a rejected Enter steering message for recovery", async () => {- const { screen, input, renderer } = makeRenderer();- const steer = vi.fn(async () => {- throw new Error("Session unavailable");- });- let controller: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;- const rendering = renderer.renderStream(- {- steer,- events: new ReadableStream<AgentTUIStreamEvent>({- start(value) {- controller = value;- },- }),- },- { submittedPrompt: "long task", continueSession: true },+ expect(screen.snapshot()).toMatch(+ /^\* Added channel\/slack · setup not finished\n {3}⎿ {2}Finish with `eve add channel\/slack --skip-install`$/m,);- await screen.waitForText("❯");- input.type("change direction");- input.enter();- await screen.waitForText("Steering failed");- expect(steer).toHaveBeenCalledWith("change direction");- controller?.enqueue({ type: "finish" });- controller?.close();- await rendering;- expect(renderer.takeQueuedPrompt()).toBe("change direction");- renderer.shutdown();});- it("keeps slash commands out of the steering message", async () => {- const { screen, input, renderer } = makeRenderer();- const steer = vi.fn(async () => {});- let controller: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;- const rendering = renderer.renderStream(- {- steer,- events: new ReadableStream<AgentTUIStreamEvent>({- start(value) {- controller = value;- },- }),- },- { submittedPrompt: "long task", continueSession: true },- );- await screen.waitForText("❯");- input.type("/model");- input.enter();- expect(steer).not.toHaveBeenCalled();- controller?.enqueue({ type: "finish" });- controller?.close();- await rendering;- expect(renderer.takeQueuedPrompt()).toBe("/model");+ it("keeps the invocation when a settled command has no summary", () => {+ const { screen, renderer } = makeRenderer();+ renderer.renderCommandInvocation("/deploy");+ renderer.finishCommand({ kind: "result", message: "Deployed: https://example.vercel.app" });renderer.shutdown();- });- it("keeps the draft in place when the queue is full", async () => {- const { screen, input, renderer } = makeRenderer();- let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;- const rendering = renderer.renderStream(- {- events: new ReadableStream<AgentTUIStreamEvent>({- start(controller) {- streamController = controller;- },- }),- },- { submittedPrompt: "long task", continueSession: true },+ expect(screen.snapshot()).toMatch(+ /^\* \/deploy\n {3}⎿ {2}Deployed: https:\/\/example.vercel.app$/m,);- await vi.waitFor(() => {- expect(screen.snapshot()).toContain("❯");- });+ });- for (let index = 1; index <= 5; index += 1) {- input.type(`message ${index}`);- input.enter();- }- await vi.waitFor(() => {- expect(screen.snapshot()).toContain("Queue 5/5");- expect(screen.snapshot()).toContain("queue full");+ it("marks a failed automatic command and keeps its multiline outcome in one result block", () => {+ const { screen, renderer } = makeRenderer();+ renderer.renderCommandInvocation("/deploy");+ renderer.finishCommand({+ kind: "result",+ message:+ "Authentication was refreshed, but example.vercel.app is unavailable: Access denied.\n\n" ++ "TRUSTED_SOURCES_ENVIRONMENT_MISMATCH",});-- input.type("overflow");- input.enter();- // The sixth message is refused, not swallowed — it stays as the draft.- expect(screen.snapshot()).toContain("overflow");-- streamController?.close();- await rendering;- expect(renderer.takeQueuedPrompt()).toBe(- "message 1\n\nmessage 2\n\nmessage 3\n\nmessage 4\n\nmessage 5",- );renderer.shutdown();++ const snapshot = screen.snapshot();+ expect(snapshot).toMatch(/^\* \/deploy$/m);+ expect(snapshot).toContain("⎿ Authentication was refreshed");+ expect(snapshot).toContain("TRUSTED_SOURCES_ENVIRONMENT_MISMATCH");+ expect(snapshot).not.toContain("· Authentication was refreshed");});- it("restores undrained queued messages into the next prompt's buffer", async () => {+ it("invites with a quiet placeholder until typing starts", async () => {const { screen, input, renderer } = makeRenderer();- let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;- const abort = vi.fn();- const rendering = renderer.renderStream(- {- abort,- events: new ReadableStream<AgentTUIStreamEvent>({- start(controller) {- streamController = controller;- },- }),- },- { submittedPrompt: "long task", continueSession: true },- );- await vi.waitFor(() => {- expect(screen.snapshot()).toContain("❯");- });- input.type("first");- input.enter();- input.type("second");- input.enter();- await vi.waitFor(() => {- expect(screen.snapshot()).toContain("Queue 2/5");- });- // A lifecycle interruption skips the runner's queue drain…- renderer.requestInterrupt();- await rendering;- expect(abort).toHaveBeenCalledTimes(1);- void streamController;+ const prompt = readPrompt(renderer);+ // A bare prompt before any info/turn has no status row (no ↑ 0 ↓ 0 counter).+ expect(screen.snapshot()).not.toContain("↑ 0");+ // Empty buffer: the default-color `❯` gutter with the message invitation.+ expect(screen.snapshot()).toContain("❯ Send a message…");+ expect(screen.rawOutput()).not.toContain("\x1b[48;5;");- // …so the prompt folds the undelivered messages back into the buffer.- const prompt = renderer.readPrompt();- await vi.waitFor(() => {- expect(screen.snapshot()).toContain("first");- expect(screen.snapshot()).toContain("second");- });+ input.type("hello");+ // Typing colors the prompt mark and clears the invitation.+ expect(screen.snapshot()).toContain("❯ hello");+ expect(screen.snapshot()).not.toContain("Send a message…");input.enter();- expect(await prompt).toBe("first\n\nsecond");+ expect(await prompt).toBe("hello");renderer.shutdown();});- it("waitForIdlePrompt ignores the pending prompt and resolves only at idle", async () => {+ it("retires a local cue after the first user message, including after a header refresh", async () => {const { screen, input, renderer } = makeRenderer();- let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;- const rendering = renderer.renderStream(- {- events: new ReadableStream<AgentTUIStreamEvent>({- start(controller) {- streamController = controller;- },- }),- },- { submittedPrompt: "long task", continueSession: true },- );+ const header = selfModificationHeader();+ renderer.renderAgentHeader(header);- await vi.waitFor(() => {- // The pending prompt already shows `❯` — but the live bar keeps the- // idle predicate false.- expect(screen.snapshot()).toContain("❯");- });- await expect(screen.waitForIdlePrompt(200)).rejects.toThrow(/idle prompt/u);+ const first = readPrompt(renderer);+ expect(screen.snapshot()).toContain("❯ Send a message, or ask me to add a channel…");+ input.type("hello");+ input.enter();+ expect(await first).toBe("hello");- streamController?.close();- await rendering;- const prompt = renderer.readPrompt();- await screen.waitForIdlePrompt(1_000);+ renderer.renderAgentHeader(header);+ const second = readPrompt(renderer);+ expect(screen.snapshot()).toContain("❯");+ expect(screen.snapshot()).not.toContain("ask me to add a channel");+ input.type("again");+ expect(screen.snapshot()).toContain("❯ again");input.ctrlC();+ expect(screen.snapshot()).toContain("❯");input.ctrlC();- await expect(prompt).rejects.toThrow();+ await expect(second).rejects.toThrow();renderer.shutdown();++ const queued = makeRenderer();+ queued.renderer.beginStartupDraft({ title: "Orders" });+ queued.input.type("hello from startup");+ queued.input.enter();+ const startup = queued.renderer.finishStartupDraft();+ expect(startup.queuedPrompt).toBe("hello from startup");+ queued.renderer.renderAgentHeader(header);+ queued.renderer.renderConversation(+ conversationOf([+ stampTestEvent(+ createMessageReceivedEvent({ message: "hello from startup", sequence: 0, turnId: "t1" }),+ ),+ ]),+ );+ const afterQueuedMessage = readPrompt(queued.renderer);+ expect(queued.screen.snapshot()).not.toContain("ask me to add a channel");+ queued.input.ctrlC();+ queued.input.ctrlC();+ await expect(afterQueuedMessage).rejects.toThrow();+ queued.renderer.shutdown();});it("queues startup messages until the agent is ready", async () => {@@ -2604,7 +777,7 @@ describe("TerminalRenderer (inline scrollback)", () => {queuedPrompt: "weather tomorrow\n\nand next week",});- const prompt = startupRenderer.readPrompt();+ const prompt = readPrompt(startupRenderer);expect(screen.snapshot()).not.toContain("Queue 1/5");input.ctrlC();input.ctrlC();@@ -2730,7 +903,7 @@ describe("TerminalRenderer (inline scrollback)", () => {it("seeds the editable buffer with an initial draft without auto-submitting", async () => {const { screen, input, renderer } = makeRenderer();- const prompt = renderer.readPrompt({ initialDraft: "hello world" });+ const prompt = readPrompt(renderer, { initialDraft: "hello world" });// The seed is shown and the placeholder is suppressed — but no submit// happens until the user presses Enter, so they can edit it first.expect(screen.snapshot()).toContain("hello world");@@ -2745,7 +918,7 @@ describe("TerminalRenderer (inline scrollback)", () => {it("strips control characters from an initial draft", async () => {const { input, renderer } = makeRenderer();- const prompt = renderer.readPrompt({+ const prompt = readPrompt(renderer, {initialDraft: "safe\u001b[2Jafter\nnext\tvalue\u007f",});input.enter();@@ -2766,38 +939,7 @@ describe("TerminalRenderer (inline scrollback)", () => {input.type("no");input.enter();await answer;- expect(screen.snapshot()).toContain("Thinking (0s)");- renderer.shutdown();- });-- it("breathes between an answered question and the next tool block", async () => {- const { screen, input, renderer } = makeRenderer();-- const answer = renderer.readInputQuestion({- requestId: "q1",- prompt: "Which framework do you mean?",- display: "text",- });- input.type("eve");- input.enter();- await answer;-- await renderer.renderStream(- streamOf([- { type: "step-start" },- {- type: "tool-call",- toolCallId: "t1",- toolName: "web_search",- input: { query: "eve framework" },- },- { type: "finish" },- ]),- { continueSession: true },- );-- // The answered question and the following tool are separated by air.- expect(screen.snapshot()).toContain("⎿ eve\n\n");+ expect(screen.snapshot()).not.toContain("Send a message…");renderer.shutdown();});@@ -2929,56 +1071,6 @@ describe("TerminalRenderer (inline scrollback)", () => {renderer.shutdown();});- it("sweeps a preparing placeholder whose call never parses", async () => {- const { screen, renderer } = makeRenderer();- await renderer.renderStream(- streamOf([- { type: "step-start" },- // Announced, but no tool-call ever follows (the model emitted- // unparsable input and retried under a fresh id next step).- { type: "tool-call-preparing", toolCallId: "ghost-1", toolName: "web_search" },- { type: "step-finish", usage: { inputTokens: 10, outputTokens: 5 } },- { type: "step-start" },- {- type: "tool-call",- toolCallId: "retry-1",- toolName: "web_search",- input: { query: "eve framework" },- },- { type: "tool-result", toolCallId: "retry-1", output: { results: [] } },- { type: "step-finish", usage: { inputTokens: 10, outputTokens: 5 } },- { type: "finish" },- ]),- { submittedPrompt: "search", continueSession: false },- );- renderer.shutdown();-- const snapshot = screen.snapshot();- // The retry renders; the ghost placeholder never commits.- expect(snapshot).toContain("Searched eve framework");- expect(snapshot).not.toContain("Search …");- });-- it("suppresses the tool block for ask_question calls", async () => {- const { screen, renderer } = makeRenderer();- await renderer.renderStream(- streamOf([- {- type: "tool-call",- toolCallId: "ask-1",- toolName: "ask_question",- input: { prompt: "Pick a color." },- },- { type: "finish" },- ]),- { submittedPrompt: "ask me", continueSession: false },- );- renderer.shutdown();-- // The question surface is the call's representation; no `Ask …` block.- expect(screen.snapshot()).not.toContain("Ask Pick a color.");- });-it("focuses the freeform editor when the cursor reaches its row", async () => {const { screen, input, renderer } = makeRenderer();@@ -3076,7 +1168,7 @@ describe("TerminalRenderer (inline scrollback)", () => {it("leaves a fully typed known command as plain text in the input line", async () => {const { screen, input, renderer } = makeRenderer();- const prompt = renderer.readPrompt();+ const prompt = readPrompt(renderer);input.type("/add");expect(screen.rawOutput()).not.toContain("[1m/add");expect(screen.rawOutput()).not.toContain("[34m/add");@@ -3088,7 +1180,7 @@ describe("TerminalRenderer (inline scrollback)", () => {it("leaves unknown input unstyled in the input line", async () => {const { screen, input, renderer } = makeRenderer();- const prompt = renderer.readPrompt();+ const prompt = readPrompt(renderer);// Never passes through a known command, even if painted per keystroke// ("/li…" is not a known command).input.type("/lin is not a command");@@ -3101,7 +1193,7 @@ describe("TerminalRenderer (inline scrollback)", () => {it("echoes slash commands as command lines, never as user messages", async () => {const { screen, input, renderer } = makeRenderer();- const prompt = renderer.readPrompt();+ const prompt = readPrompt(renderer);input.type("/reset");input.enter();expect(await prompt).toBe("/reset");@@ -3116,12 +1208,12 @@ describe("TerminalRenderer (inline scrollback)", () => {it("reassembles an arrow key split across reads", async () => {const { input, renderer } = makeRenderer();- const first = renderer.readPrompt();+ const first = readPrompt(renderer);input.type("remembered");input.enter();await first;- const second = renderer.readPrompt();+ const second = readPrompt(renderer);input.send("\x1b"); // ESC arrives on its own…input.send("[A"); // …and the CSI tail follows in a later read.input.enter();@@ -3131,7 +1223,7 @@ describe("TerminalRenderer (inline scrollback)", () => {it("inserts text at the caret after moving left", async () => {const { input, renderer } = makeRenderer();- const prompt = renderer.readPrompt();+ const prompt = readPrompt(renderer);input.type("helo");input.left();input.type("l");@@ -3237,222 +1329,40 @@ describe("TerminalRenderer (inline scrollback)", () => {expect(screen.snapshot()).toContain("details: .eve/logs/dev.log");expect(screen.snapshot()).not.toContain("at fourth");- renderer.setLogDisplayMode("all");- expect(screen.snapshot()).toContain("at fourth");- expect(screen.snapshot()).not.toContain("details: .eve/logs/dev.log");-- process.stdout.write("server listening on 3000\n");- expect(append).toHaveBeenCalledWith({ source: "stdout", detail: "server listening on 3000" });- renderer.shutdown();- });-- it("shows Workflow SDK stderr only when every log is shown and still records it", () => {- const screen = new MockScreen({ columns: 140, rows: 30 });- const input = new MockUserInput();- const stub = stubDiagnostics();- const renderer = new TerminalRenderer({- input,- output: screen,- captureForeignOutput: true,- logs: "stderr",- unicode: true,- diagnostics: stub.diagnostics,- });- renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });- const detail = [- "[workflow-sdk] Step execution already in flight in this process; awaiting its settlement instead of executing again",- " run wrun_01",- "[workflow-sdk] Encountered FatalError while executing step",- "FatalError: step body threw",- " at releaseStep (release-step.ts:1:1)",- "[eve:dev] agent reloaded",- ].join("\n");- // Pipe chunks from the server process can carry several records and can- // split one record, even mid-line.- const split = detail.indexOf("body threw");-- process.stderr.write(detail.slice(0, split));- process.stderr.write(`${detail.slice(split)}\n`);-- const recorded = stub.append.mock.calls- .map(([entry]) => entry as { source: string; detail?: string })- .filter((entry) => entry.source === "stderr")- .map((entry) => entry.detail);- expect(recorded.join("\n")).toBe(detail);- const hidden = screen.snapshot();- expect(hidden).toContain("[eve:dev] agent reloaded");- expect(hidden).not.toContain("[workflow-sdk]");- expect(hidden).not.toContain("wrun_01");- expect(hidden).not.toContain("step body threw");-- renderer.setLogDisplayMode("all");- // Adjacent log blocks collapse to the newest, so the split record's tail- // proves the hidden segments are revealed.- const shown = screen.snapshot();- expect(shown).toContain("FatalError: step body threw");- expect(shown).toContain("[eve:dev] agent reloaded");- renderer.shutdown();- });-- it("subscribes the recorder to log records, displays them, and releases on shutdown", () => {- const screen = new MockScreen({ columns: 120, rows: 30 });- const input = new MockUserInput();- const stub = stubDiagnostics();- const renderer = new TerminalRenderer({- input,- output: screen,- captureForeignOutput: true,- logs: "stderr",- unicode: true,- diagnostics: stub.diagnostics,- });- renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });-- expect(stub.subscribed).toBe(true);- stub.emitLogRecord({- level: "error",- namespace: "harness.tool-loop",- message: "tool execution failed",- fields: { toolName: "always_fail" },- });- expect(screen.snapshot()).toContain("[eve:harness.tool-loop] tool execution failed");-- renderer.shutdown();- expect(stub.subscribed).toBe(false);- });-- it("records tool failures in the diagnostic log even when tools are hidden", async () => {- const screen = new MockScreen({ columns: 80, rows: 30 });- const input = new MockUserInput();- const stub = stubDiagnostics();- const append = stub.append;- const renderer = new TerminalRenderer({- input,- output: screen,- captureForeignOutput: false,- tools: "hidden",- unicode: true,- diagnostics: stub.diagnostics,- });-- await renderer.renderStream(- streamOf([- {- type: "tool-call",- toolCallId: "c1",- toolName: "bash",- input: { command: "curl https://example.com" },- },- { type: "tool-error", toolCallId: "c1", errorText: "exit code 7: connection refused" },- { type: "error", errorText: "Turn failed." },- { type: "finish" },- ]),- { submittedPrompt: "fetch it", continueSession: false },- );-- expect(append).toHaveBeenCalledWith({- source: "tool",- summary: expect.stringContaining("failed"),- detail: "exit code 7: connection refused",- });- expect(append).toHaveBeenCalledWith({- source: "workflow",- summary: "Error: Turn failed.",- detail: "Turn failed.",- });- renderer.shutdown();- });-- it("renders a cataloged summary for a recognized stream error and logs the raw dump", async () => {- const screen = new MockScreen({ columns: 100, rows: 30 });- const input = new MockUserInput();- const stub = stubDiagnostics();- const append = stub.append;- const renderer = new TerminalRenderer({- input,- output: screen,- captureForeignOutput: false,- unicode: true,- diagnostics: stub.diagnostics,- });-- const failure = new TypeError("fetch failed", {- cause: Object.assign(new Error("connect ECONNREFUSED 127.0.0.1:3000"), {- code: "ECONNREFUSED",- }),- });- await renderer.renderStream(- {- events: new ReadableStream<AgentTUIStreamEvent>({- start(controller) {- controller.error(failure);- },- }),- },- { submittedPrompt: "hello", continueSession: false },- );+ renderer.setLogDisplayMode("all");+ expect(screen.snapshot()).toContain("at fourth");+ expect(screen.snapshot()).not.toContain("details: .eve/logs/dev.log");- // Transcript: curated headline, the structured hint, and the log- // pointer — no stack dump.- expect(screen.snapshot()).toContain("Network request failed");- expect(screen.snapshot()).toContain("Check your internet connection");- expect(screen.snapshot()).toContain("details: .eve/logs/dev.log");- expect(screen.snapshot()).not.toContain(" at ");- // Log: the raw inspection, cause chain included, hint structured.- expect(append).toHaveBeenCalledWith({- source: "workflow",- summary: expect.stringContaining("Network request failed"),- detail: expect.stringContaining("ECONNREFUSED"),- hint: expect.stringContaining("Check your internet connection"),- });+ process.stdout.write("server listening on 3000\n");+ expect(append).toHaveBeenCalledWith({ source: "stdout", detail: "server listening on 3000" });renderer.shutdown();});- it("records session stats past display guards and reports at the turn boundary", async () => {- const screen = new MockScreen({ columns: 80, rows: 30 });+ it("subscribes the recorder to log records, displays them, and releases on shutdown", () => {+ const screen = new MockScreen({ columns: 120, rows: 30 });const input = new MockUserInput();const stub = stubDiagnostics();const renderer = new TerminalRenderer({input,output: screen,- captureForeignOutput: false,- tools: "hidden",- subagents: "hidden",+ captureForeignOutput: true,+ logs: "stderr",unicode: true,diagnostics: stub.diagnostics,});+ renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });- renderer.upsertSubagentTool({- callId: "sub-1",- subagentName: "echo-marker",- childCallId: "child-1",- toolName: "echo",- input: {},- status: "executing",+ expect(stub.subscribed).toBe(true);+ stub.emitLogRecord({+ level: "error",+ namespace: "harness.tool-loop",+ message: "tool execution failed",+ fields: { toolName: "always_fail" },});- await renderer.renderStream(- streamOf([- { type: "tool-call", toolCallId: "c1", toolName: "bash", input: {} },- { type: "tool-call", toolCallId: "c2", toolName: "bash", input: {} },- { type: "tool-call", toolCallId: "c3", toolName: "weather", input: {} },- { type: "step-finish", usage: { inputTokens: 100, outputTokens: 20 } },- { type: "step-finish", usage: { inputTokens: 40, outputTokens: 5 } },- // `finish` replays the last step's usage; only step-finish records.- { type: "finish", usage: { inputTokens: 40, outputTokens: 5 } },- ]),- { submittedPrompt: "run it", continueSession: false },- );+ expect(screen.snapshot()).toContain("[eve:harness.tool-loop] tool execution failed");- expect(stub.recordPrompt).toHaveBeenCalledTimes(1);- expect(stub.recordSubagentDispatch).toHaveBeenCalledWith("sub-1");- expect(stub.recordToolCall.mock.calls.map(([name]) => name)).toEqual([- "bash",- "bash",- "weather",- ]);- expect(stub.recordStepUsage).toHaveBeenCalledTimes(2);- expect(stub.reportStats).toHaveBeenCalled();renderer.shutdown();+ expect(stub.subscribed).toBe(false);});it("records captured sandbox log lines in the diagnostic log", () => {@@ -3690,7 +1600,7 @@ describe("TerminalRenderer (inline scrollback)", () => {const input = new MockUserInput();const renderer = new TerminalRenderer({ input, output: screen, unicode: true });// Abandoned on purpose; shutdown() rejects it with InterruptedError.- renderer.readPrompt().catch(() => {});+ readPrompt(renderer).catch(() => {});// Ctrl+R only redraws — it must not cycle the mode or show the hint.input.type("\u0012");@@ -3798,47 +1708,6 @@ describe("TerminalRenderer (inline scrollback)", () => {expect(snapshot).not.toContain("Nitro worker");});- it("settles a live rebuild cycle at stream end and starts the next one fresh", async () => {- const screen = new MockScreen({ columns: 100, rows: 40 });- const input = new MockUserInput();- const renderer = new TerminalRenderer({- input,- output: screen,- captureForeignOutput: true,- logs: "all",- unicode: true,- });- renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });-- // The rebuild line lands mid-stream, after the assistant block opened.- async function* events(): AsyncGenerator<AgentTUIStreamEvent> {- yield { type: "assistant-delta", id: "t1", delta: "hello there" };- process.stdout.write(- `${formatChangeDetectedLogLine("/app", [{ event: "change", path: "/app/agent/agent.ts" }])}\n`,- );- yield { type: "finish" };- }- await renderer.renderStream(- { events: events() },- { submittedPrompt: "hi", continueSession: true },- );-- // Stream-end finalize froze the cycle mid-"rebuilding"; the next change- // detected after it opens a fresh row instead of rewriting the old one.- process.stdout.write(- `${formatChangeDetectedLogLine("/app", [- { event: "change", path: "/app/agent/tools/lookup.ts" },- ])}\n`,- );- renderer.shutdown();-- const snapshot = screen.snapshot();- expect(snapshot.indexOf("agent/agent.ts changed · rebuilding…")).toBeGreaterThan(-1);- expect(snapshot.indexOf("agent/agent.ts changed · rebuilding…")).toBeLessThan(- snapshot.indexOf("tools/lookup.ts changed · rebuilding…"),- );- });-it("settles the in-place rebuild status when other output interleaves", () => {const screen = new MockScreen({ columns: 100, rows: 40 });const input = new MockUserInput();@@ -3996,6 +1865,24 @@ describe("TerminalRenderer (inline scrollback)", () => {renderer.shutdown();});+ it("shows where an approval sits among the open ones and who asked for it", async () => {+ const { screen, input, renderer } = makeRenderer();+ const approval = renderer.readToolApproval({+ approvalId: "a2",+ toolCallId: "c2",+ toolName: "random_number",+ input: {},+ context: { position: { index: 2, total: 10 }, requester: "subagent(number_picker:13)" },+ });++ expect(screen.snapshot()).toMatch(+ /─ subagent\(number_picker:13\) · 2 of 10 ──\n\n\s+Approve random_number\?/,+ );+ input.enter();+ await expect(approval).resolves.toEqual({ approved: true });+ renderer.shutdown();+ });+it("clears a pending approval drawer when interrupted externally", async () => {const { screen, renderer } = makeRenderer();const approval = renderer.readToolApproval({@@ -4009,39 +1896,13 @@ describe("TerminalRenderer (inline scrollback)", () => {renderer.requestInterrupt();await expect(approval).rejects.toThrow();- const prompt = renderer.readPrompt();+ const prompt = readPrompt(renderer);expect(screen.snapshot()).not.toContain("Approve random_color?");renderer.requestInterrupt();await expect(prompt).rejects.toThrow();renderer.shutdown();});- it("marks a tool block denied when the user rejects the approval", async () => {- const { screen, input, renderer } = makeRenderer();- await renderer.renderStream(- streamOf([- { type: "tool-call", toolCallId: "c1", toolName: "delete_files", input: { path: "/" } },- { type: "tool-approval-request", approvalId: "a1", toolCallId: "c1" },- ]),- { submittedPrompt: "clean up", continueSession: true },- );-- const approval = renderer.readToolApproval({- approvalId: "a1",- toolCallId: "c1",- toolName: "delete_files",- input: { path: "/" },- });- input.type("n");- expect(await approval).toEqual({ approved: false, reason: "Denied by user." });- expect(screen.snapshot()).toContain("Thinking (0s)");- renderer.shutdown();-- const snapshot = screen.snapshot();- expect(snapshot).toContain("delete_files");- expect(snapshot).toContain("→ denied");- });-it("stops the turn ticker while a later human-input request is open", async () => {vi.useFakeTimers();try {@@ -4592,28 +2453,6 @@ describe("TerminalRenderer setup flow session", () => {renderer.shutdown();});- it("does not repaint while inherited stdio owns the terminal", async () => {- vi.useFakeTimers();- try {- const { screen, renderer } = makeRenderer();- renderer.setupFlow.begin("Add integration");- let release!: () => void;- const inherited = renderer.setupFlow.withInheritedStdio(- () => new Promise<void>((resolve) => (release = resolve)),- );- const outputDuringHandoff = screen.rawOutput().length;- await vi.advanceTimersByTimeAsync(180);- expect(screen.rawOutput()).toHaveLength(outputDuringHandoff);-- release();- await inherited;- renderer.setupFlow.end();- renderer.shutdown();- } finally {- vi.useRealTimers();- }- });-it("discards inherited subprocess output when restoring the transcript", async () => {const { screen, input, renderer } = makeRenderer();@@ -5245,15 +3084,15 @@ describe("TerminalRenderer command echo spacing", () => {const { screen, input, renderer } = makeRenderer();renderer.renderNotice("assistant said something");- const prompt = renderer.readPrompt();- input.type("/connect");+ const prompt = readPrompt(renderer);+ input.type("/info");input.enter();await prompt;renderer.finishCommand({ kind: "result", message: "Project linked." });renderer.shutdown();const lines = screen.snapshot().split("\n");- const echoIndex = lines.findIndex((line) => line.includes("│ /connect"));+ const echoIndex = lines.findIndex((line) => line.includes("/info"));expect(echoIndex).toBeGreaterThan(0);expect(lines[echoIndex - 1]).toBe("");const resultIndex = lines.findIndex((line) => line.includes("⎿ Project linked."));@@ -5265,7 +3104,7 @@ describe("TerminalRenderer command typeahead", () => {it("offers command suggestions while the draft is a lone slash token", async () => {const { screen, input, renderer } = makeRenderer();- const prompt = renderer.readPrompt();+ const prompt = readPrompt(renderer);input.type("/");const snapshot = screen.snapshot();expect(snapshot).toContain("/help");@@ -5284,7 +3123,7 @@ describe("TerminalRenderer command typeahead", () => {it("keeps the suggestion visible for a complete command alongside its argument hint", async () => {const { screen, input, renderer } = makeRenderer();- const prompt = renderer.readPrompt();+ const prompt = readPrompt(renderer);input.type("/model");const snapshot = screen.snapshot();expect(snapshot).toContain("│ /model");@@ -5316,7 +3155,7 @@ describe("TerminalRenderer command typeahead", () => {argumentSuggestions: async () => suggestions.promise,});- const prompt = renderer.readPrompt();+ const prompt = readPrompt(renderer);input.type("/model ");expect(screen.snapshot()).not.toContain("Loading models…");@@ -5346,7 +3185,7 @@ describe("TerminalRenderer command typeahead", () => {argumentSuggestions: async () => [{ value: "openai/gpt-5", label: "GPT-5" }],});- const prompt = renderer.readPrompt();+ const prompt = readPrompt(renderer);input.type("/model ");await vi.advanceTimersByTimeAsync(499);expect(screen.snapshot()).toContain("openai/gpt-5");@@ -5376,7 +3215,7 @@ describe("TerminalRenderer command typeahead", () => {],});- const prompt = renderer.readPrompt();+ const prompt = readPrompt(renderer);input.type("/model sol");await vi.waitFor(() => expect(screen.snapshot()).toContain("openai/gpt-6-sol"));input.enter();@@ -5408,7 +3247,7 @@ describe("TerminalRenderer command typeahead", () => {: [],});- const prompt = renderer.readPrompt();+ const prompt = readPrompt(renderer);input.type("/model claude");await vi.waitFor(() => expect(screen.snapshot()).toContain("anthropic/claude-sonnet-5"));input.enter();@@ -5431,7 +3270,7 @@ describe("TerminalRenderer command typeahead", () => {: [],});- const prompt = renderer.readPrompt();+ const prompt = readPrompt(renderer);input.type("/add slack");await vi.waitFor(() => expect(screen.snapshot()).toContain("channel/slack"));input.send("\t");@@ -5444,7 +3283,7 @@ describe("TerminalRenderer command typeahead", () => {it("tab completes the highlighted command without submitting", async () => {const { input, renderer } = makeRenderer();- const prompt = renderer.readPrompt();+ const prompt = readPrompt(renderer);input.type("/mo");input.send("\t");input.type("anthropic/claude-opus-4.8");@@ -5457,7 +3296,7 @@ describe("TerminalRenderer command typeahead", () => {it("enter completes and submits the highlighted command from a prefix", async () => {const { screen, input, renderer } = makeRenderer();- const prompt = renderer.readPrompt();+ const prompt = readPrompt(renderer);input.type("/ad");input.enter();expect(await prompt).toBe("/add");@@ -5470,7 +3309,7 @@ describe("TerminalRenderer command typeahead", () => {it("submits an alias as typed instead of canonicalizing it", async () => {const { screen, input, renderer } = makeRenderer();- const prompt = renderer.readPrompt();+ const prompt = readPrompt(renderer);input.type("/quit");input.enter();expect(await prompt).toBe("/quit");@@ -5481,7 +3320,7 @@ describe("TerminalRenderer command typeahead", () => {it("keeps a submitted /help invocation above its transient drawer", async () => {const { input, renderer, screen } = makeRenderer();- const prompt = renderer.readPrompt();+ const prompt = readPrompt(renderer);input.type("/help");input.enter();expect(await prompt).toBe("/help");@@ -5536,7 +3375,7 @@ describe("TerminalRenderer command typeahead", () => {input.enter();const selection = await help;expect(selection).toBe("/model ");- const prompt = renderer.readPrompt({ initialDraft: selection });+ const prompt = readPrompt(renderer, { initialDraft: selection });await vi.waitFor(() => expect(screen.snapshot()).toContain("openai/gpt-5"));expect(screen.snapshot()).toContain("│ /model");expect(screen.snapshot()).not.toContain("❯ /model");@@ -5558,7 +3397,7 @@ describe("TerminalRenderer command typeahead", () => {it("keeps a submitted /info invocation above its transient drawer", async () => {const { input, renderer, screen } = makeRenderer();- const prompt = renderer.readPrompt();+ const prompt = readPrompt(renderer);input.type("/info");input.enter();expect(await prompt).toBe("/info");@@ -5628,12 +3467,12 @@ describe("TerminalRenderer command typeahead", () => {it("moves the suggestion highlight with arrows instead of recalling history", async () => {const { input, renderer } = makeRenderer();- const first = renderer.readPrompt();+ const first = readPrompt(renderer);input.type("an earlier prompt");input.enter();await first;- const second = renderer.readPrompt();+ const second = readPrompt(renderer);input.type("/");input.down();input.enter();@@ -5656,13 +3495,13 @@ describe("TerminalRenderer command typeahead", () => {"/loglevel all","/traces",]) {- const prompt = renderer.readPrompt();+ const prompt = readPrompt(renderer);input.type(text);input.enter();await prompt;}- const recalled = renderer.readPrompt();+ const recalled = readPrompt(renderer);input.up();input.enter();expect(await recalled).toBe("an earlier prompt");@@ -5672,7 +3511,7 @@ describe("TerminalRenderer command typeahead", () => {it("escape dismisses the suggestions until the draft changes", async () => {const { screen, input, renderer } = makeRenderer();- const prompt = renderer.readPrompt();+ const prompt = readPrompt(renderer);input.type("/");expect(screen.snapshot()).toContain("Show available commands");@@ -5715,7 +3554,7 @@ describe("TerminalRenderer command typeahead", () => {availablePromptCommands: promptCommandsFor("remote"),});- const prompt = renderer.readPrompt();+ const prompt = readPrompt(renderer);input.type("/");const snapshot = screen.snapshot();expect(snapshot).not.toContain("Authenticate with Vercel");@@ -5736,7 +3575,7 @@ describe("TerminalRenderer command typeahead", () => {availablePromptCommands: promptCommandsFor("remote"),});- const prompt = renderer.readPrompt();+ const prompt = readPrompt(renderer);input.type("/model");input.enter();@@ -5763,7 +3602,7 @@ describe("TerminalRenderer status line", () => {}),});- const prompt = renderer.readPrompt();+ const prompt = readPrompt(renderer);renderer.setVercelStatus(vercelStatus);expect(screen.snapshot()).toContain("⚠ ai-gateway");@@ -5798,111 +3637,6 @@ describe("TerminalRenderer status line", () => {renderer.shutdown();});- it("shows dynamic model below the prompt after replacing a static model", async () => {- const { screen, input, renderer } = makeRenderer();- const info = agentInfoWithModel("openai/gpt-5.6-sol");- const header = { name: "Weather Agent", serverUrl: "http://localhost:3000", info };- renderer.renderAgentHeader(header);- const prompt = renderer.readPrompt();- renderer.renderAgentHeader({ ...header, info: agentInfoWithDynamicModel() });- const lines = screen.snapshot().split("\n");- const promptRow = lines.findIndex((line) => line.includes("❯"));- expect(promptRow).toBeGreaterThan(-1);- const footer = lines.slice(promptRow + 1).join("\n");- expect(footer).toContain("dynamic model");- expect(footer).not.toContain("gpt-5.6-sol");- expect(footer).not.toContain("⚠ ai-gateway");- input.type("done");- input.enter();- await prompt;- await renderer.renderStream(- {- events: (async function* (): AsyncIterable<AgentTUIStreamEvent> {- yield { type: "step-start", modelId: "openai/gpt-6-luna-fast" };- expect(screen.snapshot()).toContain("dynamic model · gpt-6-luna · ⚡︎");- yield { type: "step-start", modelId: "openai/gpt-5.6-sol" };- expect(screen.snapshot()).toContain("dynamic model · gpt-5.6-sol");- expect(screen.snapshot()).not.toContain("gpt-6-luna");- yield { type: "finish" };- })(),- },- { submittedPrompt: "hi", continueSession: true },- );- expect(screen.snapshot()).toContain("dynamic model · gpt-5.6-sol");- await renderer.renderStream(- {- events: (async function* (): AsyncIterable<AgentTUIStreamEvent> {- yield { type: "turn-start", turnId: "next-turn" };- expect(screen.snapshot()).toContain("dynamic model");- expect(screen.snapshot()).not.toContain("gpt-5.6-sol");- yield { type: "step-start", modelId: "openai/gpt-5.6-luna" };- yield { type: "finish" };- })(),- },- { submittedPrompt: "hello again", continueSession: true },- );- expect(screen.snapshot()).toContain("dynamic model · gpt-5.6-luna");- renderer.renderSessionBoundary();- expect(screen.snapshot()).toContain("dynamic model");- expect(screen.snapshot()).not.toContain("gpt-5.6-luna");- renderer.shutdown();- });-- it("clears an idle turn's model before resolution and preserves same-turn continuations", async () => {- const { screen, renderer } = makeRenderer();- renderer.renderAgentHeader({- name: "Weather Agent",- serverUrl: "http://localhost:3000",- info: agentInfoWithDynamicModel(),- });- await renderer.renderIdleStream(- streamOf([- { type: "turn-start", turnId: "first" },- { type: "step-start", modelId: "openai/gpt-5.6-sol" },- ]),- );- expect(screen.snapshot()).toContain("dynamic model · gpt-5.6-sol");- await renderer.renderIdleStream(streamOf([{ type: "turn-start", turnId: "first" }]));- expect(screen.snapshot()).toContain("dynamic model · gpt-5.6-sol");- await renderer.renderIdleStream(- streamOf([- { type: "turn-start", turnId: "wake" },- { type: "error", errorText: "Model selection failed" },- ]),- );- expect(screen.snapshot()).toContain("dynamic model");- expect(screen.snapshot()).not.toContain("gpt-5.6-sol");- expect(screen.snapshot()).toContain("Model selection failed");- renderer.shutdown();- });-- it.each([null, 42, {}, "x".repeat(10_000)])(- "bounds model display data without interrupting the stream (%#)",- async (modelId) => {- const { screen, renderer } = makeRenderer(320);- renderer.renderAgentHeader({- name: "Weather Agent",- serverUrl: "http://localhost:3000",- info: agentInfoWithDynamicModel(),- });- await renderer.renderIdleStream(- streamOf([- { type: "step-start", modelId } as AgentTUIStreamEvent,- { type: "assistant-complete", id: "answer", text: "Hello Alice." },- ]),- );- expect(screen.snapshot()).toContain("Hello Alice.");- expect(screen.snapshot()).toContain("dynamic model");- if (typeof modelId === "string") {- expect(screen.snapshot()).toContain("x".repeat(256));- expect(screen.snapshot()).not.toContain("x".repeat(257));- } else {- expect(screen.snapshot()).not.toContain("dynamic model ·");- }- renderer.shutdown();- },- );-it("suppresses the status line while a setup flow panel is open", () => {const { screen, renderer } = makeRenderer();renderer.renderNotice("anchor");@@ -5966,27 +3700,6 @@ describe("TerminalRenderer status line", () => {renderer.shutdown();});- it("keeps the token flow off the status line after a turn reports usage", async () => {- const { screen, renderer } = makeRenderer();- await renderer.renderStream(- streamOf([- { type: "step-start" },- { type: "assistant-delta", id: "t1", delta: "Hi." },- { type: "assistant-complete", id: "t1" },- { type: "step-finish", usage: { inputTokens: 500, outputTokens: 300 } },- { type: "finish", usage: { inputTokens: 500, outputTokens: 300 } },- ]),- { submittedPrompt: "hello", continueSession: true },- );-- // Token flow belongs to the end-of-turn coda; the settled footer keeps- // only the quiet `· Ready` row and its turn-scoped stats.- const snapshot = screen.snapshot();- expect(snapshot).not.toContain("↑ 500");- expect(snapshot).not.toContain("↓ 300");- renderer.shutdown();- });-it.each([{model: "xai/grok-4.5",@@ -6043,42 +3756,6 @@ describe("TerminalRenderer status line", () => {expect(snapshot).not.toContain("⚡︎");renderer.shutdown();});-- it("keeps the model and Vercel segments across reset while tokens stay clear", async () => {- // 100 columns: all four segments fit at full fidelity, no drop order.- const { screen, renderer } = makeRenderer(100);- renderer.renderAgentHeader({- name: "Weather Agent",- serverUrl: "http://localhost:3000",- info: agentInfoWithModel("anthropic/claude-sonnet-5", {- kind: "gateway",- connected: true,- credential: "oidc",- }),- });- renderer.setVercelStatus({ ...vercelStatus });- await renderer.renderStream(- streamOf([- { type: "step-start" },- { type: "assistant-delta", id: "t1", delta: "Hi." },- { type: "assistant-complete", id: "t1" },- { type: "finish", usage: { inputTokens: 500, outputTokens: 300 } },- ]),- { submittedPrompt: "hello", continueSession: true },- );- expect(screen.snapshot()).not.toContain("↑ 500 ↓ 300");-- renderer.reset();-- const snapshot = screen.snapshot();- expect(snapshot).toContain("claude-sonnet-5");- expect(snapshot).toContain("· ai-gateway(oidc:my-agent)");- // A fresh conversation clears the token flow entirely (↑ 0 ↓ 0 is noise).- expect(snapshot).not.toContain("↑ 0");- expect(snapshot).not.toContain("↑ 500");- expect(snapshot).not.toContain("hello");- renderer.shutdown();- });});describe("setup interaction transitions", () => {@@ -6118,3 +3795,226 @@ describe("setup interaction transitions", () => {},);});++describe("TerminalRenderer conversation", () => {+ let sequence = 0;+ const stamped = (event: UnstampedMessageStreamEvent) => stampTestEvent(event, ++sequence);++ it("writes a task's start and end lines and shows it in the panel while it works", async () => {+ const { screen, renderer } = makeRenderer(100, 30);+ const prompt = readPrompt(renderer);+ const call = {+ callId: "pick_1",+ kind: "agent" as const,+ name: "number_picker",+ taskId: "task_1",+ turnId: "turn_1",+ };+ const working = [+ stamped(createTurnStartedEvent({ sequence: 0, turnId: "turn_1" })),+ stamped(+ createActionsRequestedEvent({+ actions: [+ {+ callId: "pick_1",+ input: { message: "Pick a number for Alice." },+ kind: "tool-call",+ toolName: "number_picker",+ },+ ],+ sequence: 1,+ stepIndex: 0,+ turnId: "turn_1",+ }),+ ),+ stamped(createTaskStartedEvent(call)),+ stamped(+ createActionsRequestedEvent({+ actions: [{ callId: "wait_1", input: {}, kind: "tool-call", toolName: "task_wait" }],+ sequence: 2,+ stepIndex: 1,+ turnId: "turn_1",+ }),+ ),+ stamped(createTurnWaitingEvent({ sequence: 3, turnId: "turn_1" })),+ ];+ renderer.renderConversation(conversationOf(working, { working: true }));+ const during = screen.snapshot();+ expect(during).toContain("※ number_picker Pick a number for Alice.");+ expect(during).toMatch(/※ number_picker +Starting/);+ expect(during).toContain("Waiting for number_picker");+ expect(during).not.toContain("task_wait");++ renderer.renderConversation(+ conversationOf(+ [+ ...working,+ stamped(createTaskSettledEvent({ ...call, output: "7", status: "completed" })),+ ],+ { working: true },+ ),+ );+ const after = screen.snapshot();+ expect(after).toMatch(/✓ number_picker +finished in/);+ expect(after).not.toMatch(/※ number_picker +Starting/);+ renderer.requestInterrupt();+ await prompt.catch(() => {});+ });++ it("keeps a command's details under it while the agent streams", () => {+ const { screen, renderer } = makeRenderer(100, 30);+ renderer.renderCommandInvocation("/add channel/web");+ renderer.renderConversation(+ conversationOf([turn("turn_1"), appended("turn_1", "Reading Alice's notes")], {+ working: true,+ }),+ );+ renderer.finishCommand({+ kind: "result",+ message: "Start locally with `pnpm dev:services`.",+ summary: "Added channel/web",+ });+ renderer.shutdown();++ expect(screen.snapshot()).toMatch(+ /^\* Added channel\/web\n {3}⎿ {2}Start locally with `pnpm dev:services`\.$/m,+ );+ });+ const turn = (turnId: string) => stamped(createTurnStartedEvent({ sequence: 0, turnId }));+ const appended = (turnId: string, messageDelta: string) =>+ stamped(createMessageAppendedEvent({ messageDelta, sequence: 1, stepIndex: 0, turnId }));+ const completed = (turnId: string, message: string) =>+ stamped(createMessageCompletedEvent({ message, sequence: 2, stepIndex: 0, turnId }));++ it("streams prose in the live region and commits it whole once it settles", async () => {+ const { screen, renderer } = makeRenderer(34, 8);+ const prompt = readPrompt(renderer);+ const words = Array.from(+ { length: 44 },+ (_, index) => `word-${String(index + 1).padStart(2, "0")}`,+ );+ const streaming = [turn("turn_1"), ...words.map((word) => appended("turn_1", `${word} `))];++ renderer.renderConversation(conversationOf(streaming, { working: true }));+ expect(screen.snapshot()).toContain("earlier rows hidden");+ expect(screen.snapshot()).not.toContain("word-01");++ renderer.renderConversation(+ conversationOf([...streaming, completed("turn_1", words.join(" "))]),+ );+ const snapshot = screen.snapshot();+ expect(countOccurrences(snapshot, "word-01")).toBe(1);+ expect(countOccurrences(snapshot, "word-44")).toBe(1);+ expect(snapshot).not.toContain("earlier rows hidden");+ renderer.requestInterrupt();+ await prompt.catch(() => {});+ });++ it("rides the turn bar above an open composer and closes a long turn with a coda", async () => {+ vi.useFakeTimers();+ try {+ const { screen, renderer } = makeRenderer();+ const first = readPrompt(renderer);+ renderer.renderConversation(conversationOf([turn("turn_1")], { working: true }));+ let lines = screen.snapshot().split("\n");+ const bar = lines.findIndex((line) => line === "• Thinking (0s)");+ expect(bar).toBeGreaterThan(-1);+ expect(lines[bar + 2]).toContain("❯");++ await vi.advanceTimersByTimeAsync(12_000);+ renderer.renderConversation(+ conversationOf([turn("turn_1"), completed("turn_1", "Alice's summary is ready.")], {+ data: { usage: { inputTokens: 1_200, outputTokens: 300 } },+ }),+ );+ lines = screen.snapshot().split("\n");+ expect(lines.some((line) => line.includes("Thinking ("))).toBe(false);+ expect(screen.snapshot()).toMatch(/Done in 12s/u);+ renderer.requestInterrupt();+ await first.catch(() => {});+ } finally {+ vi.useRealTimers();+ }+ });++ it("asks to cancel on Esc while work runs, then stops following on a second Ctrl+C", async () => {+ const { screen, input, renderer } = makeRenderer();+ renderer.renderConversation(conversationOf([turn("turn_1")], { working: true }));++ const cancel = renderer.readInput();+ input.send("\x1b");+ await expect(cancel).resolves.toEqual({ type: "cancel" });+ const interrupt = renderer.readInput();+ expect(screen.snapshot()).toContain("Cancelling turn…");+ input.ctrlC();+ await expect(interrupt).resolves.toEqual({ type: "interrupt" });++ // The interrupt counts as the first exit press at the next idle prompt.+ renderer.renderConversation(conversationOf([]));+ const idle = renderer.readInput();+ expect(screen.snapshot()).toContain("Press Ctrl+C again to exit");+ input.ctrlC();+ await expect(idle).rejects.toThrow("Interrupted");+ });++ it("submits a message typed while work runs", async () => {+ const { input, renderer } = makeRenderer();+ renderer.renderConversation(conversationOf([turn("turn_1")], { working: true }));+ const submitted = renderer.readInput();+ input.type("Include Bob's note.");+ input.enter();+ await expect(submitted).resolves.toEqual({ type: "submit", text: "Include Bob's note." });+ renderer.shutdown();+ });++ it("keeps the draft when the composer closes for another surface", async () => {+ const { screen, input, renderer } = makeRenderer();+ const controller = new AbortController();+ const closed = renderer.readInput({ signal: controller.signal });+ input.type("half a thought");+ controller.abort();+ await expect(closed).resolves.toBeUndefined();++ const reopened = readPrompt(renderer);+ expect(screen.snapshot()).toContain("❯ half a thought");+ input.enter();+ await expect(reopened).resolves.toBe("half a thought");+ renderer.shutdown();+ });++ it("settles the old conversation at a session boundary so a new session can reuse its ids", async () => {+ const { screen, renderer } = makeRenderer();+ const prompt = readPrompt(renderer);+ renderer.renderConversation(+ conversationOf([turn("turn_1"), appended("turn_1", "Alice's draft")], { working: true }),+ );+ renderer.renderSessionBoundary();+ renderer.renderConversation(conversationOf([]));+ renderer.renderConversation(+ conversationOf([turn("turn_1"), completed("turn_1", "Bob's fresh start.")]),+ );+ const snapshot = screen.snapshot();+ expect(countOccurrences(snapshot, "Alice's draft")).toBe(1);+ expect(countOccurrences(snapshot, "Bob's fresh start.")).toBe(1);+ expect(snapshot.indexOf("Alice's draft")).toBeLessThan(snapshot.indexOf("Session restarted"));+ renderer.requestInterrupt();+ await prompt.catch(() => {});+ });++ it("names the dynamic model the running turn resolved", async () => {+ const { screen, renderer } = makeRenderer();+ renderer.renderAgentHeader({+ name: "Weather Agent",+ serverUrl: "http://localhost:3000",+ info: agentInfoWithDynamicModel(),+ });+ const prompt = readPrompt(renderer);+ expect(screen.snapshot()).toContain("dynamic model");+ renderer.renderConversation(+ conversationOf([turn("turn_1")], { data: { modelId: "openai/gpt-6-luna-fast" } }),+ );+ expect(screen.snapshot()).toContain("dynamic model · gpt-6-luna · ⚡︎");+ renderer.requestInterrupt();+ await prompt.catch(() => {});+ });+});diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.tsindex da419cec5..e56e46b1b 100644--- a/packages/eve/src/cli/dev/tui/terminal-renderer.ts+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.ts@@ -2,22 +2,25 @@ import { StringDecoder } from "node:string_decoder";import type { DevDiagnostics } from "../diagnostics.js";import type {+ AgentTUIInput,+ AgentTUIInputContext,AgentTUIInputOption,AgentTUIInputQuestion,AgentTUIInputQuestionResponse,AgentTUIRenderer,AgentTUISessionOptions,- AgentTUIStreamEvent,- AgentTUIStreamUsage,- AgentTUIStreamResult,AgentTUIToolApprovalRequest,AgentTUIToolApprovalResponse,CommandPresentation,- ConnectionAuthUpdate,- SubagentStepUpdate,- SubagentView,- SubagentToolUpdate,} from "./runner.js";+import type { AgentTUIConversationView, TokenUsage } from "./conversation-view.js";+import {+ ConversationTranscript,+ TASK_END_GRACE_MS,+ turnActivity,+ type TranscriptOptions,+} from "./transcript.js";+import { renderTaskPanelRows } from "./task-activity.js";import { interruptedError } from "./errors.js";import {argumentTypeaheadCompletion,@@ -88,8 +91,7 @@ import type {} from "./types.js";import type { AgentInfoResult } from "#client/index.js";import { initialPromptPlaceholder } from "./prompt-placeholder.js";-import { summarizeKnownError } from "#harness/semantic-errors/index.js";-import { inspectError, type LogRecord } from "#internal/logging.js";+import type { LogRecord } from "#internal/logging.js";import {parseDevRebuildLogLine,type DevRebuildLogUpdate,@@ -99,7 +101,6 @@ import {type Block,type DisplayBlock,type BlockKind,- type ToolStatus,renderAttentionRows,renderBlockLines,} from "./blocks.js";@@ -141,24 +142,8 @@ import {} from "#cli/ui/terminal-text.js";import type { VercelStatusSnapshot } from "./vercel-status.js";import type { RemoteConnectionSnapshot } from "./remote-connection.js";-import {- agentDisplayName,- isPanelRoutedTool,- presentPreparingTool,- presentTool,- readWriteFileInput,- toolBaseName,- type ToolPresentationContext,-} from "./tool-presentation.js";-import { FileContentCache } from "./file-content-cache.js";-import { groupToolBlocksForDisplay, summarizeChildTools } from "./tool-block-groups.js";-import {- renderTaskPanelRows,- TaskActivity,- waitingLabel,- type TaskEntry,-} from "./task-activity.js";-import { renderQuestionChoices, renderQuestionPanel } from "./question-panel.js";+import { groupToolBlocksForDisplay } from "./tool-block-groups.js";+import { inputContextLabel, renderQuestionChoices, renderQuestionPanel } from "./question-panel.js";import { TurnClock } from "./turn-clock.js";import { MessageQueue, renderMessageQueueRows } from "./message-queue.js";import {@@ -184,7 +169,6 @@ import {sanitizePastedText,stripPasteStart,stripPromptControlCharacters,- takeUntil,type TerminalKey,} from "./stream-format.js";import {@@ -236,21 +220,8 @@ function moveActionCursor(return (cursor + delta + actionCount) % actionCount;}-function completedTurnStatus(input: {- interrupted: boolean;- cancelled: boolean;- continueSession: boolean;-}): string {- if (input.interrupted) return "Interrupted";- if (input.cancelled) return "Cancelled";- if (input.continueSession) return "Ready";- return "Done";-}-type SetupFlowStatusState = { text: string; startedAtMs: number };-type TurnIndicatorState = { kind: "idle" } | { kind: "waiting"; startedAtMs: number };-type SetupFlowState = {title: string;navigation?: PlannerNavigation;@@ -319,86 +290,6 @@ type AgentHeaderOptions = {localDevelopment?: boolean;};-type DisplayModes = {- tools: TerminalPartDisplayMode;- reasoning: TerminalPartDisplayMode;- assistantResponseStats: AssistantResponseStatsMode;-};--type RenderTurnState = {- text: Map<string, string>;- reasoning: Map<string, string>;- tools: Map<string, NativeToolState>;- modelActivity: "Thinking" | "Generating";- /** True between a model step's start and finish. */- inStep: boolean;- runningTools: Set<string>;- cancelled: boolean;- restoreCancelledPrompt: boolean;-};--/**- * Between model steps with tasks working, the turn is waiting on them — the- * model called `task_wait` or ended its reply — so the bar names the tasks.- */-function turnActivityLabel(- state: RenderTurnState | undefined,- tasks: readonly TaskEntry[],-): string {- if (state === undefined) return "Thinking";- if (state.runningTools.size > 0) return "Running";- if (!state.inStep && tasks.length > 0) return waitingLabel(tasks);- return state.modelActivity;-}--function updateTurnActivity(state: RenderTurnState, event: AgentTUIStreamEvent): void {- switch (event.type) {- case "step-start":- state.inStep = true;- state.modelActivity = "Thinking";- break;- case "step-finish":- state.inStep = false;- break;- case "turn-start":- case "reasoning-delta":- state.modelActivity = "Thinking";- break;- case "assistant-delta":- case "tool-call-preparing":- state.modelActivity = "Generating";- break;- case "assistant-complete":- if (event.text?.trim()) state.modelActivity = "Generating";- break;- case "tool-call":- state.runningTools.add(event.toolCallId);- state.modelActivity = "Thinking";- break;- case "tool-result":- case "tool-error":- case "tool-rejected":- case "tool-withdrawn":- // A task keeps working past its call; the task panel tracks it instead.- case "task-started":- state.runningTools.delete(event.toolCallId);- break;- }-}--type NativeToolState = {- toolCallId: string;- toolName: string;- input: unknown;- status: ToolStatus;- /** True while the model is still streaming this call's input. */- preparing?: boolean;- output?: unknown;- errorText?: string;- label?: string | undefined;- completeLabel?: string | undefined;-};-const caretBlinkMs = 500;const tickMs = 90;// How long to wait on a lone `ESC` before treating it as the Escape key, so a@@ -416,11 +307,6 @@ const logLevelHintMs = 5_000;const devBuildProgressDelayMs = 250;const devBuildLoadedStatusMs = 4_000;-const STATUS = {- processing: "Thinking",- connectionAuth: "Waiting for connection authorization…",-} as const;-/*** The end-of-turn stats coda renders only for turns that were long or* expensive: past this wall-clock duration, or past this many input tokens@@ -463,28 +349,20 @@ export class TerminalRenderer implements AgentTUIRenderer {*/readonly #transcriptBlocks: Block[] = [];- readonly #childToolCallIds = new Set<string>();- readonly #parentToolBlockIds = new Map<string, string>();/** Monotonic counter behind every block's `updateSeq` activity stamp. */#updateSequence = 0;- /** Working tasks, shown in the task panel between their start and end lines. */- readonly #tasks = new TaskActivity();- /** An agent's own rows already written under `--subagents full`. */- readonly #writtenAgentRows = new Set<string>();- /** Calls whose start line is written; a replayed start must not write another. */- readonly #startedTaskCallIds = new Set<string>();- /** Agent calls whose own stream the pump follows, and those whose stream ended. */- readonly #followedAgentCallIds = new Set<string>();- readonly #endedAgentCallIds = new Set<string>();- /** Settled agent tasks whose end line waits for the agent's own end. */- readonly #pendingTaskEnds = new Map<- string,- { event: TaskSettledEvent; endedAtMs: number; timer: ReturnType<typeof setTimeout> }- >();- /** Session-local file contents, so write blocks can render real diffs. */- readonly #fileContents = new FileContentCache();+ /** Projects the current session's conversation; reset at every context cut. */+ readonly #transcript = new ConversationTranscript();+ #taskEndGraceTimer?: ReturnType<typeof setTimeout>;+ #view?: AgentTUIConversationView;+ /** Live blocks whose content the conversation projection owns. */+ #conversationBlockIds = new Set<string>();+ /** Texts submitted while a turn ran, so their echoes use the steering gutter. */+ readonly #steeredMessages: string[] = [];#agentHeader?: AgentHeaderOptions;#initialPromptPlaceholder = "Send a message…";+ /** The agent's local subagents, whose tools render as delegations. */+ #subagentNames?: readonly string[];#startupPhase?: "starting" | "connecting" | "updating";#startupEditor?: LineState;#startupConsumer?: (key: TerminalKey) => void;@@ -508,7 +386,6 @@ export class TerminalRenderer implements AgentTUIRenderer {*/#lastCommitted?: PreviousBlock;- #connectionAuthPendingCount = 0;/** Vercel segment of the bottom status line; pushed by the runner. */#vercelStatus?: VercelStatusSnapshot;/** Remote target and connection/authentication state; pushed by the runner. */@@ -519,7 +396,7 @@ export class TerminalRenderer implements AgentTUIRenderer {readonly #killRing = new KillRing();#inputActive = false;/**- * Command suggestions for the prompt draft. Only `readPrompt` sets this —+ * Command suggestions for the prompt draft. Only `readInput` sets this —* `readInputQuestion` shares `#inputActive` and the footer's input row, and* a `/`-prefixed freeform answer must never sprout suggestions.*/@@ -543,26 +420,17 @@ export class TerminalRenderer implements AgentTUIRenderer {#promptPlaceholderActive = false;/** Placeholder retires for good once the user has sent a first message. */#hasUserMessage = false;- /** Armed by a chat submit; the end-of-turn stats line consumes it. */+ /** Armed when work starts; the end-of-turn stats line consumes it. */readonly #turnClock = new TurnClock();- #activeTurnState?: RenderTurnState;- /**- * Draft typed while a turn streams. The prompt row stays in place with- * Enter inert (no mid-turn submits yet); the draft seeds the next prompt.- */- #streamDraft: LineState = EMPTY_LINE;- /** True while renderStream owns the keyboard — gates the inert prompt row. */- #streamDraftActive = false;- /**- * Token usage summed across the turn's steps — what this message actually- * cost, unlike the last step's report (whose input restates the whole- * context). Accumulated on `step-finish` only: the `finish` event repeats- * the final step's usage and would double-count it.- */- #turnIndicator: TurnIndicatorState = { kind: "idle" };+ #lastTurnStats?: { elapsedMs: number } & TokenUsage;+ /** The composer's draft, kept while other input surfaces own the keyboard. */+ #draft: LineState = EMPTY_LINE;+ /** Replaces the open composer's line; set while {@link readInput} reads. */+ #applyDraft?: (next: LineState) => void;+ /** Set by a cancel key while work runs; a second Ctrl+C stops following. */+ #cancelRequested = false;/** Rejects the reader currently awaiting keys, so #stop never strands it. */#rejectActiveReader?: (error: Error) => void;- #status: string = STATUS.processing;/*** A flowless setup spinner's text ("Checking the project…"). Rendered as* its own status row — the text is the information — instead of the live@@ -578,7 +446,6 @@ export class TerminalRenderer implements AgentTUIRenderer {*/#everInteractive = false;#partingLinePrinted = false;- #interrupted = false;#exitRequested = false;/** True after the first consecutive Ctrl+C at the idle chat prompt. */#exitArmed = false;@@ -600,18 +467,9 @@ export class TerminalRenderer implements AgentTUIRenderer {#inputDecoder = new StringDecoder("utf8");#keyFlushTimer?: ReturnType<typeof setTimeout>;#onResize?: () => void;- #resolveStreamInterrupt?: () => void;#painting = false;#paintAgain = false;-- #totalTokens?: number;- /** Input (prompt) tokens from the latest usage report — the ↑ side. */- #promptTokens?: number;#contextSize?: number;- #assistantOutputTokens?: number;- #assistantTokensPerSecond?: number;- /** Wall-clock start of the current stream, for the tok/s status stat. */- #streamStartedAt?: number;#restoreLogCapture?: () => void;#stdoutLogBuffer = "";@@ -632,7 +490,6 @@ export class TerminalRenderer implements AgentTUIRenderer {#devBuildStatusTimer?: ReturnType<typeof setTimeout>;/** Monotonic id source — committed cycle ids must never be reused. */#devRebuildSequence = 0;- #pendingEchoedPrompt?: string;/** The open HITL drawer, painted above the input area. */#hitlDrawer?: (width: number) => ReturnType<typeof renderTransientDrawer>;#transientPanel?: (width: number) => ReturnType<typeof renderTransientDrawer>;@@ -641,33 +498,10 @@ export class TerminalRenderer implements AgentTUIRenderer {#setupFlow?: SetupFlowState;/** The clearable setup attention line (`⚠ … · /deploy`), rendered in the live footer. */#setupAttention?: string;- #resolvedModelId?: string;- #modelTurnId?: string;- /**- * Messages submitted while a turn streams, pinned in a panel directly- * above the input when steering is unavailable. `/cancel` cancels directly, and Esc or- * Ctrl+C pops-to-steer or cancels immediately when empty; the runner drains- * via {@link takeQueuedPrompt} at a clean turn boundary and- * {@link readPrompt} restores any leftovers as a draft.- */- readonly #messageQueue = new MessageQueue();- /** The streaming result's cooperative cancel, available to Esc and Ctrl+C. */- #requestTurnCancel?: () => void;- #sendSteering?: (message: string) => Promise<void>;- /** Set by the `turn-cancelled` stream event: settle in-flight tool blocks. */- #turnCancelled = false;+ /** Messages submitted while the agent starts, delivered once it is ready. */+ readonly #startupQueue = new MessageQueue();/** Server session id backing the conversation; named in the parting line. */#sessionId?: string;- /**- * Provenance of the next runner-submitted prompt, remembered between- * {@link takeQueuedPrompt} and the echo in {@link #addSubmittedPrompt} so- * the user block can use the steering gutter color.- */- #nextSubmittedPromptOrigin?: "steer" | "queue";- /** True once this stream's prompt requested cancellation. */- #cancelRequestedByUser = false;- /** The prompt submitted for the streaming turn, for external-cancel recovery. */- #currentSubmittedPrompt?: string;/** Armed by {@link SetupFlowRenderer.waitForInterrupt}; fired by the idle key trap. */#flowInterrupt?: (interrupt: SetupFlowInterrupt) => void;/** The installed working-state key consumer, so re-arming and disposal can recognize it. */@@ -814,13 +648,8 @@ export class TerminalRenderer implements AgentTUIRenderer {renderAgentHeader(options: AgentHeaderOptions): void {this.#startupHeader = undefined;this.#title = options.name;- if (- this.#agentHeader?.info?.agent.model.routing.kind !== "dynamic" ||- options.info?.agent.model.routing.kind !== "dynamic"- ) {- this.#resolvedModelId = undefined;- }this.#agentHeader = options;+ this.#subagentNames = options.info?.subagents.local.map((subagent) => subagent.name);this.#initialPromptPlaceholder = initialPromptPlaceholder(options.info,options.localDevelopment === true,@@ -879,7 +708,7 @@ export class TerminalRenderer implements AgentTUIRenderer {return;}if (key.type === "enter" && editor.text.trim().length > 0) {- if (this.#messageQueue.enqueue(editor.text)) apply(EMPTY_LINE);+ if (this.#startupQueue.enqueue(editor.text)) apply(EMPTY_LINE);return;}if (key.type === "ctrl-c") this.#onExitRequest?.();@@ -899,7 +728,7 @@ export class TerminalRenderer implements AgentTUIRenderer {finishStartupDraft(): { draft: string; queuedPrompt: string | undefined } {const result = {draft: this.#startupEditor?.text ?? this.#inputText,- queuedPrompt: this.#messageQueue.takePrompt(),+ queuedPrompt: this.#startupQueue.takePrompt(),};this.#startupEditor = undefined;this.#startupConsumer = undefined;@@ -910,37 +739,23 @@ export class TerminalRenderer implements AgentTUIRenderer {return result;}- async readPrompt(options?: AgentTUISessionOptions): Promise<string> {+ /**+ * Opens the composer until the user submits, cancels work, or leaves. The+ * composer stays usable while work runs: `Enter` submits (the runner steers),+ * and `Esc` or `Ctrl+C` asks to cancel. Aborting `signal` keeps the draft for+ * the next read, so other input surfaces can briefly take the keyboard.+ */+ async readInput(options?: AgentTUISessionOptions): Promise<AgentTUIInput | undefined> {this.#start(options);- this.#syncTaskTicker();- this.#commitTurnStats();+ if (this.#view?.working !== true) this.#commitTurnStats();this.#inputActive = true;this.#promptPlaceholderActive = true;- this.#turnIndicator = { kind: "idle" };- this.#status = "";this.#exitArmed = this.#armExitOnNextPrompt;this.#armExitOnNextPrompt = false;- // A draft typed during the turn carries into the prompt; an explicit- // initial draft (`eve dev --input`) wins over it. Queued messages the- // runner never drained (an interrupted or failed turn) fold back in- // ahead of the draft instead of vanishing — sanitized per line so the- // blank-line seams between restored messages survive.- const undelivered = this.#messageQueue- .restoreDraft()- ?.split("\n")- .map(stripPromptControlCharacters)- .join("\n");- const carriedDraft = stripPromptControlCharacters(- options?.initialDraft ?? this.#streamDraft.text,- );- const seededDraft =- undelivered === undefined- ? carriedDraft- : carriedDraft.length === 0- ? undelivered- : `${undelivered}\n\n${carriedDraft}`;- let editor: LineState = lineOf(seededDraft);- this.#streamDraft = EMPTY_LINE;+ let editor: LineState =+ options?.initialDraft === undefined+ ? this.#draft+ : lineOf(stripPromptControlCharacters(options.initialDraft));this.#promptHistory.begin(editor.text);this.#syncInput(editor);this.#syncTypeahead(editor.text);@@ -948,14 +763,40 @@ export class TerminalRenderer implements AgentTUIRenderer {this.#paint();return await new Promise((resolve, reject) => {- this.#rejectActiveReader = reject;+ const signal = options?.signal;+ const release = () => {+ this.#applyDraft = undefined;+ signal?.removeEventListener("abort", onAbort);+ this.#typeahead = undefined;+ this.#argumentTypeahead = undefined;+ this.#inputActive = false;+ this.#stopCaretBlink();+ this.#detachInput();+ this.#paint();+ };+ const finish = (input: AgentTUIInput | undefined) => {+ release();+ resolve(input);+ };+ const onAbort = () => finish(undefined);+ signal?.addEventListener("abort", onAbort, { once: true });+ if (signal?.aborted) {+ onAbort();+ return;+ }+ this.#rejectActiveReader = (error) => {+ signal?.removeEventListener("abort", onAbort);+ reject(error);+ };const apply = (next: LineState) => {editor = next;+ this.#draft = next;this.#showCaret();this.#syncInput(editor);this.#syncTypeahead(next.text);this.#paint();};+ this.#applyDraft = apply;const recall = (entry: string | undefined) => {if (entry !== undefined) apply(lineOf(entry));};@@ -965,6 +806,10 @@ export class TerminalRenderer implements AgentTUIRenderer {this.#stop();reject(interruptedError());};+ const cancel = () => {+ this.#cancelRequested = true;+ finish({ type: "cancel" });+ };const suggestions = () =>this.#typeahead !== undefined && isTypeaheadOpen(this.#typeahead)? this.#typeahead@@ -988,6 +833,7 @@ export class TerminalRenderer implements AgentTUIRenderer {apply(edited);return;}+ const working = this.#view?.working === true;switch (key.type) {case "up":case "ctrl-p": {@@ -1051,7 +897,9 @@ export class TerminalRenderer implements AgentTUIRenderer {if (open !== undefined) {this.#typeahead = dismissTypeahead(open);this.#paint();+ break;}+ if (working && !this.#cancelRequested) cancel();break;}case "enter": {@@ -1092,27 +940,23 @@ export class TerminalRenderer implements AgentTUIRenderer {: editor.text;// An empty (or whitespace-only) buffer never submits.if (prompt.trim().length === 0) break;- this.#typeahead = undefined;- this.#argumentTypeahead = undefined;if (promptCommandSpec(prompt)?.spec.history !== "omit") this.#promptHistory.add(prompt);- this.#inputActive = false;- this.#stopCaretBlink();- this.#status = STATUS.processing;+ this.#draft = EMPTY_LINE;+ this.#syncInput(EMPTY_LINE);if (isPromptControlCommand(prompt)) {// Commands echo as their own line so the elbow-connected// outcome has an invocation to hang under — never as a user// chat message.this.#pushCommandEcho(stripTerminalControls(prompt.trim()));+ if (working && parsePromptCommand(prompt)?.type === "cancel") {+ this.#cancelRequested = true;+ }} else {- this.#startWorking();- this.#addUserBlock(prompt);- this.#pendingEchoedPrompt = prompt;- this.#turnClock.arm();+ this.#hasUserMessage = true;+ this.#diagnostics?.recordPrompt();+ if (working) this.#steeredMessages.push(prompt);}- this.#syncInput(EMPTY_LINE);- this.#paint();- this.#detachInput();- resolve(prompt);+ finish({ type: "submit", text: prompt });break;}case "ctrl-d":@@ -1131,6 +975,17 @@ export class TerminalRenderer implements AgentTUIRenderer {this.#paint();break;case "ctrl-c":+ if (working) {+ // Once cancellation is pending, Ctrl+C is the hard escape hatch.+ if (!this.#cancelRequested) {+ cancel();+ break;+ }+ this.#cancelRequested = false;+ this.#armExitOnNextPrompt = true;+ finish({ type: "interrupt" });+ break;+ }if (this.#exitArmed) {this.#requestExit();interrupt();@@ -1148,192 +1003,103 @@ export class TerminalRenderer implements AgentTUIRenderer {});}- #syncInput(state: LineState): void {- this.#inputText = state.text;- this.#inputCursor = state.cursor;- }-/**- * Consumes the next prompt produced by mid-turn input — the staged Esc- * steer message, or the whole queue coalesced into one. The runner calls- * this at a clean turn boundary and submits the result directly; the- * remembered origin determines the echoed user block's gutter color.+ * Reconciles the session's transcript with one conversation snapshot. Blocks+ * keep their position once shown; a block leaves the live region when its+ * part can no longer change.*/- takeQueuedPrompt(): string | undefined {- const steering = this.#messageQueue.view().steering;- const prompt = this.#messageQueue.takePrompt();- if (prompt !== undefined) {- this.#nextSubmittedPromptOrigin = steering ? "steer" : "queue";+ renderConversation(view: AgentTUIConversationView): void {+ const wasWorking = this.#view?.working === true;+ this.#view = view;+ // A message queued during startup reaches the conversation without passing the prompt.+ if (view.conversation.messages.some((message) => message.role === "user")) {+ this.#hasUserMessage = true;}- return prompt;- }-- async renderStream(- result: AgentTUIStreamResult,- options?: AgentTUISessionOptions,- ): Promise<void> {- this.#start(options);- // Stream event ids are stable only within one streamed turn. Fresh- // sessions in tests and dev can reuse tool call / turn ids, so committed- // ids from prior turns must not suppress the next prompt's blocks.- this.#committedIds.clear();- this.#inputActive = false;- if (this.#turnIndicator.kind !== "waiting") {- this.#turnIndicator = { kind: "waiting", startedAtMs: Date.now() };- }- this.#status = this.#connectionAuthPendingCount > 0 ? STATUS.connectionAuth : STATUS.processing;- this.#addSubmittedPrompt(options?.submittedPrompt);- if (options?.submittedPrompt !== undefined) this.#diagnostics?.recordPrompt();- // A turn not born at the prompt (`eve dev --input`) arms its own clock;- // continuation passes (no submitted prompt) keep the original.- if (options?.submittedPrompt !== undefined && !this.#turnClock.armed) {- this.#turnClock.arm();- }- this.#interrupted = false;- this.#turnCancelled = false;- this.#cancelRequestedByUser = false;- this.#currentSubmittedPrompt = options?.submittedPrompt;- this.#messageQueue.beginTurn();- this.#requestTurnCancel = result.cancel;- this.#sendSteering = result.steer;- this.#totalTokens = undefined;- this.#promptTokens = undefined;- this.#assistantOutputTokens = undefined;- this.#assistantTokensPerSecond = undefined;- this.#streamStartedAt = Date.now();- const turnState: RenderTurnState = {- text: new Map(),- reasoning: new Map(),- tools: new Map(),- modelActivity: "Thinking",- inStep: false,- runningTools: new Set(),- cancelled: false,- restoreCancelledPrompt: true,- };- this.#activeTurnState = turnState;- const displayModes: DisplayModes = {- tools: options?.tools ?? this.#tools,- reasoning: options?.reasoning ?? this.#reasoning,- assistantResponseStats: options?.assistantResponseStats ?? this.#assistantResponseStats,- };- this.#startTicker();- this.#streamDraftActive = true;- this.#paint();-- const streamInterrupted = new Promise<void>((resolve) => {- this.#resolveStreamInterrupt = resolve;- });- this.#consumeKey = (key) => this.#handleStreamingKey(key);- this.#attachInput();- try {- for await (const event of takeUntil(iterateTUIStream(result.events), streamInterrupted)) {- if (this.#interrupted) break;- this.#applyStreamEvent(event, displayModes, turnState);- }- } catch (error) {- // Cataloged failures render their curated headline; either way the- // raw inspection travels as detail so the diagnostic log keeps the- // evidence and the transcript shows only the pointer.- 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.#resolveStreamInterrupt = undefined;- if (this.#interrupted) result.abort?.();- this.#requestTurnCancel = undefined;- this.#sendSteering = undefined;- this.#detachInput();- this.#streamDraftActive = false;- this.#activeTurnState = undefined;- if (this.#turnIndicator.kind === "waiting") {- this.#turnIndicator = { kind: "idle" };- }- this.#syncTaskTicker();- this.#status = completedTurnStatus({- interrupted: this.#interrupted,- cancelled: this.#turnCancelled,- continueSession: options?.continueSession === true,- });- // Placeholders whose call never materialized (interrupted mid-input)- // must vanish rather than commit.- this.#sweepPreparingToolBlocks(turnState);- // 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.- this.#flushTaskEnds();- if (this.#interrupted || turnState.cancelled) {- this.#settleCurrentTurnToolBlocks(turnState);- this.#stopWorkingTasks();+ const projected = this.#transcript.project(view, this.#transcriptOptions());+ this.#scheduleTaskEndGrace();+ const ids = new Set<string>();+ for (const [index, block] of projected.entries()) {+ const id = block.id!;+ if (this.#committedIds.has(id)) continue;+ ids.add(id);+ const existing = this.#blockById.get(id);+ if (existing === block) continue;+ block.updateSeq = ++this.#updateSequence;+ if (existing !== undefined) {+ this.#blocks[this.#blocks.indexOf(existing)] = block;+ this.#blockById.set(id, block);+ continue;}- this.#finalizeAllBlocks();- this.#syncTaskTicker();- this.#diagnostics?.reportStats();- this.#paint();-- if (!options?.continueSession) {- this.#stop();+ if (block.kind === "user") {+ const steered = this.#steeredMessages.indexOf(block.body ?? "");+ if (steered !== -1) {+ this.#steeredMessages.splice(steered, 1);+ block.promptOrigin = "steer";+ }}+ this.#insertConversationBlock(block, projected.slice(index + 1));+ }+ for (const id of this.#conversationBlockIds) {+ if (!ids.has(id)) this.#removeBlock(id);+ }+ this.#conversationBlockIds = ids;+ if (view.working && !wasWorking) {+ if (!this.#turnClock.armed) this.#turnClock.arm(view.data.usage);+ } else if (!view.working && wasWorking) {+ this.#cancelRequested = false;+ if (this.#inputActive) this.#commitTurnStats();}+ this.#syncActivityTicker();+ this.#paint();}/**- * 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.+ * New conversation blocks go before the next transcript block still on screen, or join the+ * live edge.*/- 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(),- modelActivity: "Thinking",- inStep: false,- runningTools: new Set(),- cancelled: false,- restoreCancelledPrompt: false,+ #insertConversationBlock(block: Block, following: readonly Block[]): void {+ const next = following.find((candidate) => this.#blockById.has(candidate.id!));+ const index = next === undefined ? -1 : this.#blocks.indexOf(this.#blockById.get(next.id!)!);+ if (index === -1) {+ this.#pushBlock(block);+ return;+ }+ if (block.id !== this.#devRebuild?.id) this.#settleDevRebuildStatus();+ this.#blocks.splice(index, 0, block);+ this.#blockById.set(block.id!, block);+ }++ #transcriptOptions(): TranscriptOptions {+ return {+ tools: this.#tools,+ reasoning: this.#reasoning,+ subagents: this.#subagents,+ connectionAuth: this.#connectionAuth,+ subagentNames: this.#subagentNames,+ diagnosticsPath: this.#diagnostics?.displayPath,+ dot: this.#theme.glyph.dot,};+ }- 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);- this.#flushTaskEnds();- if (turnState.cancelled) {- this.#settleCurrentTurnToolBlocks(turnState);- this.#stopWorkingTasks();- }- this.#finalizeAllBlocks();- this.#syncTaskTicker();- this.#diagnostics?.reportStats();- this.#paint();+ /** Names the task that asked as its task lines do. */+ #inputContextLabel(context: AgentTUIInputContext | undefined): string | undefined {+ if (+ context?.taskId === undefined ||+ context.requester !== undefined ||+ this.#view === undefined+ ) {+ return inputContextLabel(context, this.#theme);}+ const requester = this.#transcript.taskLabel(this.#view.conversation, context.taskId);+ return inputContextLabel(+ requester === undefined ? context : { ...context, requester },+ this.#theme,+ );+ }++ #syncInput(state: LineState): void {+ this.#inputText = state.text;+ this.#inputCursor = state.cursor;}async readToolApproval(@@ -1341,10 +1107,7 @@ export class TerminalRenderer implements AgentTUIRenderer {options?: AgentTUISessionOptions,): Promise<AgentTUIToolApprovalResponse> {this.#start(options);- this.#stopTicker();this.#inputActive = false;- this.#turnIndicator = { kind: "idle" };- this.#interrupted = false;let approvalCursor = 0;this.#hitlDrawer = (width) =>renderTransientDrawer(@@ -1363,23 +1126,19 @@ export class TerminalRenderer implements AgentTUIRenderer {["y yes · n no · Ctrl-C cancel"],this.#theme,width,+ this.#inputContextLabel(request.context),);this.#paint();return await new Promise((resolve, reject) => {const approve = () => {this.#hitlDrawer = undefined;- this.#startWorking();- this.#status = STATUS.processing;this.#detachInput();this.#paint();resolve({ approved: true });};const deny = () => {this.#hitlDrawer = undefined;- this.#startWorking();- this.#status = STATUS.processing;- this.#markToolDenied(request.toolCallId);this.#detachInput();this.#paint();resolve({ approved: false, reason: "Denied by user." });@@ -1414,7 +1173,6 @@ export class TerminalRenderer implements AgentTUIRenderer {this.#paint();break;case "ctrl-c":- this.#interrupted = true;this.#hitlDrawer = undefined;this.#stop();reject(interruptedError());@@ -1433,11 +1191,8 @@ export class TerminalRenderer implements AgentTUIRenderer {options?: AgentTUISessionOptions,): Promise<AgentTUIInputQuestionResponse | undefined> {this.#start(options);- this.#stopTicker();this.#inputActive = false;this.#promptPlaceholderActive = false;- this.#turnIndicator = { kind: "idle" };- this.#interrupted = false;const optionList = question.options ?? [];const hasOptions = optionList.length > 0;@@ -1460,21 +1215,24 @@ export class TerminalRenderer implements AgentTUIRenderer {// so key handlers only update it and repaint.const selectDrawer = (width: number) =>renderTransientDrawer(- renderQuestionPanel(- {- prompt: stripTerminalControls(question.prompt),- options: optionList,- cursor: cursorIndex,- allowFreeform: hasFreeformRow,- editor,- caretVisible: this.#caretVisible,- },- this.#theme,- width,- ),+ [+ ...renderQuestionPanel(+ {+ prompt: stripTerminalControls(question.prompt),+ options: optionList,+ cursor: cursorIndex,+ allowFreeform: hasFreeformRow,+ editor,+ caretVisible: this.#caretVisible,+ },+ this.#theme,+ width,+ ),+ ],["↑/↓ move · enter to select · esc to dismiss"],this.#theme,width,+ this.#inputContextLabel(question.context),);const textPanel = (width: number) => {@@ -1497,6 +1255,7 @@ export class TerminalRenderer implements AgentTUIRenderer {["Enter submit · Esc dismiss"],this.#theme,width,+ this.#inputContextLabel(question.context),);};@@ -1514,7 +1273,6 @@ export class TerminalRenderer implements AgentTUIRenderer {this.#inputActive = false;this.#removeBlock(sectionKey);this.#hitlDrawer = selectDrawer;- this.#status = "";syncFreeformCaret();this.#paint();};@@ -1524,7 +1282,6 @@ export class TerminalRenderer implements AgentTUIRenderer {this.#hitlDrawer = textPanel;this.#inputActive = true;this.#syncInput(editor);- this.#status = "";this.#startCaretBlink();this.#paint();};@@ -1547,8 +1304,6 @@ export class TerminalRenderer implements AgentTUIRenderer {live: false,});this.#inputActive = false;- this.#startWorking();- this.#status = STATUS.processing;this.#stopCaretBlink();this.#detachInput();this.#paint();@@ -1571,7 +1326,6 @@ export class TerminalRenderer implements AgentTUIRenderer {live: false,});this.#inputActive = false;- this.#status = "";this.#stopCaretBlink();this.#detachInput();this.#paint();@@ -1605,7 +1359,6 @@ export class TerminalRenderer implements AgentTUIRenderer {this.#paint();return;}- this.#interrupted = true;this.#hitlDrawer = undefined;this.#stopCaretBlink();this.#stop();@@ -1715,193 +1468,6 @@ export class TerminalRenderer implements AgentTUIRenderer {});}- /**- * An agent's words or thinking. The task panel shows the latest line;- * `--subagents full` also writes each finished message, in order.- */- upsertSubagentStep(update: SubagentStepUpdate): void {- this.#diagnostics?.recordSubagentDispatch(update.callId);- if (this.#subagents === "hidden") return;- const reasoningText = stripTerminalControls(update.reasoning ?? "").trim();- const messageText = stripTerminalControls(update.message ?? "").trim();- if (reasoningText.length === 0 && messageText.length === 0) return;-- const entry = this.#tasks.get(update.callId);- if (entry !== undefined) {- entry.step = firstLine(messageText) ?? "Thinking";- }- if (this.#subagents === "full" && update.finalized) {- const id = subagentStepRowId(update.callId, update.sectionKey);- if (!this.#writtenAgentRows.has(id)) {- this.#writtenAgentRows.add(id);- const block: Block = {- kind: "subagent-step",- subagentCallId: update.callId,- agentName: entry?.name ?? agentDisplayName(stripTerminalControls(update.subagentName)),- depth: 1,- body: messageText,- live: false,- };- if (reasoningText.length > 0) block.reasoning = reasoningText;- this.#pushBlock(block);- }- }- this.#paint();- }-- /**- * An agent's own tool call. The task panel shows what is running and counts- * finished calls for the task's end line; `--subagents full` also writes each- * finished call, in order.- */- upsertSubagentTool(update: SubagentToolUpdate): void {- this.#diagnostics?.recordSubagentDispatch(update.callId);- if (update.status === "failed" && update.errorText !== undefined) {- // Captured before the display guards: a hidden agent view must not- // keep tool failures out of the diagnostic log.- this.#diagnostics?.append({- source: "tool",- summary: `${update.toolName} failed (subagent ${update.subagentName})`,- detail: update.errorText,- });- }- if (this.#subagents === "hidden") return;-- const status = subagentToolStatus(update.status);- // Subagents reuse the session's sandbox, so their reads and writes feed- // the same file-content cache and their write blocks diff the same way.- const context = this.#toolPresentationContext({- input: update.input,- output: update.output,- toolCallId: update.childCallId,- toolName: update.toolName,- label: update.label,- agentTask: update.agentTask,- });- const presentation =- update.status === "preparing"- ? presentPreparingTool(update.toolName, context)- : presentTool(update.toolName, update.input, context);- const entry = this.#tasks.get(update.callId);- const block: Block = {- kind: "subagent-tool",- subagentCallId: update.callId,- agentName: entry?.name ?? agentDisplayName(stripTerminalControls(update.subagentName)),- depth: 1,- title: stripTerminalControls(presentation.title),- subtitle: stripTerminalControls(presentation.subtitle),- status,- live: false,- toolName: update.toolName,- toolGroup: presentation.group,- toolInput: update.input,- };- if (presentation.doneTitle !== undefined) {- block.doneTitle = stripTerminalControls(presentation.doneTitle);- }- if (presentation.detail !== undefined) {- block.detailLines = presentation.detail;- block.keepDetailWhenDone = presentation.keepDetailWhenDone === true;- }- if (update.output !== undefined) {- block.result = presentation.summarizeResult(update.output);- block.toolOutput = update.output;- } else if (update.errorText !== undefined) {- block.result = stripTerminalControls(update.errorText);- }- entry?.childTools.set(update.childCallId, block);-- const settled = status === "done" || status === "error" || status === "denied";- const id = subagentToolRowId(update.callId, update.childCallId);- if (this.#subagents === "full" && settled && !this.#writtenAgentRows.has(id)) {- this.#writtenAgentRows.add(id);- this.#pushBlock(block);- }- this.#paint();- }-- removeSubagentTool(update: { callId: string; childCallId: string; reason?: string }): void {- const childTools = this.#tasks.get(update.callId)?.childTools;- if (update.reason !== undefined) {- // The same record a refused top-level call leaves; see `tool-withdrawn`.- const toolName = childTools?.get(update.childCallId)?.toolName ?? update.childCallId;- this.#diagnostics?.append({- source: "tool",- summary: `${toolName} was refused for the model to retry`,- detail: update.reason,- });- }- childTools?.delete(update.childCallId);- this.#paint();- }-- /**- * The runner-facing subagent surface (see {@link SubagentView}); the- * public methods below are its implementation and the unit tests' seam.- */- readonly subagents: SubagentView = {- begin: ({ callId }) => {- this.#followedAgentCallIds.add(callId);- },- end: ({ callId }) => {- this.#endedAgentCallIds.add(callId);- this.#flushTaskEnd(callId);- },- upsertStep: (update) => this.upsertSubagentStep(update),- upsertTool: (update) => this.upsertSubagentTool(update),- removeTool: (update) => this.removeSubagentTool(update),- markChildToolCallId: (callId) => this.markChildToolCallId(callId),- };-- markChildToolCallId(callId: string): void {- this.#childToolCallIds.add(callId);- const staleId = this.#parentToolBlockIds.get(callId);- if (staleId === undefined) return;- this.#removeBlock(staleId);- this.#parentToolBlockIds.delete(callId);- this.#paint();- }-- /**- * Flips the tool block for a denied approval to its terminal `denied`- * state. Called at the moment the user answers `n` — the server never- * executes the call, so no `action.result` will arrive to settle it.- */- #markToolDenied(toolCallId: string): void {- const block = this.#blockById.get(toolSectionId(toolCallId));- if (block === undefined) return;- block.status = "denied";- block.live = false;- }-- upsertConnectionAuth(update: ConnectionAuthUpdate): void {- if (this.#connectionAuth === "hidden") return;- const terminalMessage = connectionAuthTerminalMessage(update.state);- this.#upsertBlock({- id: connectionAuthSectionId(update.name),- kind: "connection-auth",- title: `${stripTerminalControls(update.name)} · authorization · ${update.state}`,- body: formatConnectionAuthContent(update, terminalMessage),- preformatted: true,- live: terminalMessage === undefined,- });- this.#paint();- }-- setConnectionAuthPendingCount(count: number): void {- const next = Math.max(0, count);- if (next === this.#connectionAuthPendingCount) return;- const wasPending = this.#connectionAuthPendingCount > 0;- this.#connectionAuthPendingCount = next;- if (next > 0) {- this.#status = STATUS.connectionAuth;- this.#paint();- } else if (wasPending) {- this.#status = STATUS.processing;- this.#paint();- }- }-setVercelStatus(status: VercelStatusSnapshot): void {this.#vercelStatus = status;// #paint self-guards on #isInteractive, so a probe resolving after@@ -1931,14 +1497,7 @@ export class TerminalRenderer implements AgentTUIRenderer {this.#clearConversationState();// A fresh conversation gets the invitation back.this.#hasUserMessage = false;- this.#pendingEchoedPrompt = undefined;this.#devRebuild = undefined;- this.#connectionAuthPendingCount = 0;- this.#totalTokens = undefined;- this.#promptTokens = undefined;- this.#assistantOutputTokens = undefined;- this.#assistantTokensPerSecond = undefined;- this.#streamStartedAt = undefined;if (this.#isInteractive) {this.#live.clearAll();this.#paint();@@ -1954,7 +1513,19 @@ export class TerminalRenderer implements AgentTUIRenderer {// to the session that ended, not the fresh one.this.#commitTurnStats();// Tasks die with the session; close their lines before the boundary.- this.#stopWorkingTasks();+ const stopped = this.#transcript.stopWorking(this.#transcriptOptions());+ // The old conversation's blocks settle as they are; a fresh session may+ // reuse their ids, so they leave the projection anonymously.+ for (const id of this.#conversationBlockIds) {+ const block = this.#blockById.get(id);+ if (block === undefined) continue;+ this.#blockById.delete(id);+ const index = this.#blocks.indexOf(block);+ const { id: _id, ...settled } = block;+ this.#blocks[index] = { ...settled, live: false };+ }+ for (const { id: _id, ...line } of stopped) this.#pushBlock(line);+ this.#committedIds.clear();this.#clearConversationState();const c = this.#theme.colors;@@ -1974,22 +1545,14 @@ export class TerminalRenderer implements AgentTUIRenderer {* not count across a cut), tool-call ownership maps, and the turn clock.*/#clearConversationState(): void {- this.#resolvedModelId = undefined;- this.#modelTurnId = undefined;- this.#childToolCallIds.clear();- this.#parentToolBlockIds.clear();- for (const pending of this.#pendingTaskEnds.values()) clearTimeout(pending.timer);- this.#pendingTaskEnds.clear();- this.#tasks.clear();- this.#writtenAgentRows.clear();- this.#startedTaskCallIds.clear();- this.#followedAgentCallIds.clear();- this.#endedAgentCallIds.clear();- this.#messageQueue.reset();- this.#nextSubmittedPromptOrigin = undefined;- this.#fileContents.clear();+ this.#transcript.reset();+ this.#clearTaskEndGrace();+ this.#view = undefined;+ this.#conversationBlockIds = new Set();+ this.#steeredMessages.length = 0;+ this.#cancelRequested = false;this.#turnClock.reset();- this.#syncTaskTicker();+ this.#syncActivityTicker();}/**@@ -2005,6 +1568,18 @@ export class TerminalRenderer implements AgentTUIRenderer {this.#paint();}+ /** Puts a cancelled turn's message back into an empty composer, with a notice. */+ restoreDraft(text: string): void {+ const apply = this.#inputActive ? this.#applyDraft : undefined;+ if ((apply === undefined ? this.#draft.text : this.#inputText).length > 0) return;+ const line = lineOf(stripPromptControlCharacters(text));+ if (apply === undefined) this.#draft = line;+ else apply(line);+ this.renderNotice(+ "The turn was cancelled from outside this prompt, so its message is back in the input.",+ );+ }+/*** Sets the setup attention line (yellow `⚠`, commands blue) as a live footer* element above the prompt. Unlike committed scrollback, it can be cleared:@@ -2059,7 +1634,6 @@ export class TerminalRenderer implements AgentTUIRenderer {width,);};- this.#status = "";this.#paint();return await new Promise((resolve) => {this.#transientPanelClose = () => resolve(undefined);@@ -2106,7 +1680,6 @@ export class TerminalRenderer implements AgentTUIRenderer {width,);};- this.#status = "";this.#paint();await new Promise<void>((resolve) => {this.#transientPanelClose = resolve;@@ -2150,7 +1723,14 @@ export class TerminalRenderer implements AgentTUIRenderer {return;}this.#start();- this.#pushBlock({ kind: "result", body: content, live: false });+ const result: Block = { kind: "result", body: content, live: false };+ this.#pushBlock(result);+ // Work that streamed in while the command ran must not come between it and its result.+ const echoIndex = echo === undefined ? -1 : this.#blocks.indexOf(echo);+ if (echoIndex !== -1) {+ this.#blocks.pop();+ this.#blocks.splice(echoIndex + 1, 0, result);+ }this.#paint();}@@ -2190,8 +1770,6 @@ export class TerminalRenderer implements AgentTUIRenderer {#beginSetupFlow(title: string): void {this.#start();if (this.#startupEditor === undefined) this.#inputActive = false;- this.#turnIndicator = { kind: "idle" };- this.#status = "";this.#setupFlow = {title: stripTerminalControls(title),startedAtMs: Date.now(),@@ -2865,8 +2443,6 @@ export class TerminalRenderer implements AgentTUIRenderer {#beginSetupQuestion(title: string): SetupFlowState {this.#start();this.#inputActive = false;- this.#turnIndicator = { kind: "idle" };- this.#status = "";const flow = this.#requireSetupFlow();flow.questionTitle = stripTerminalControls(title);// A standard question means the preceding background operation settled.@@ -3041,20 +2617,20 @@ export class TerminalRenderer implements AgentTUIRenderer {this.#paint();return;}- if (this.#inputActive || this.#streamDraftActive) {- // The prompt or a streaming turn owns the footer; a flowless spinner+ if (this.#inputActive || this.#view?.working === true) {+ // The prompt or a running turn owns the footer; a flowless spinner// must not steal its ticker or indicator.return;}if (content === undefined) {- this.#turnIndicator = { kind: "idle" };this.#flowlessStatus = undefined;this.#stopTicker();this.#paint();return;}this.#start();- this.#startWorking();+ this.#activityPulseStartedAtMs = Date.now();+ this.#startTicker();this.#flowlessStatus = content.text;this.#paint();}@@ -3162,7 +2738,7 @@ export class TerminalRenderer implements AgentTUIRenderer {this.#startTicker();this.#armFlowIdleTrap();} else {- this.#syncTaskTicker();+ this.#syncActivityTicker();}this.#live.reset();this.#paint();@@ -3192,15 +2768,8 @@ 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" });- this.#resolveStreamInterrupt?.();this.#stop();}@@ -3277,7 +2846,6 @@ export class TerminalRenderer implements AgentTUIRenderer {#start(options?: AgentTUISessionOptions) {this.#title = options?.title ?? this.#title;- if (options?.contextSize !== undefined) this.#contextSize = options.contextSize;if (this.#isInteractive) return;@@ -3510,91 +3078,6 @@ export class TerminalRenderer implements AgentTUIRenderer {}}- #handleStreamingKey(key: TerminalKey) {- switch (key.type) {- case "ctrl-l":- case "ctrl-r":- this.#paint();- break;- case "enter": {- const message = this.#streamDraft.text;- if (message.trim().length === 0) break;- if (- parsePromptCommand(message)?.type === "cancel" &&- this.#requestTurnCancel !== undefined- ) {- this.#streamDraft = EMPTY_LINE;- this.#messageQueue.requestCancellation();- this.#cancelRequestedByUser = true;- this.renderCommandInvocation(message.trim());- this.finishCommand({ kind: "result", summary: "Cancellation requested" });- this.#requestTurnCancel();- this.#paint();- break;- }- const send = this.#sendSteering;- if (send !== undefined && parsePromptCommand(message) === null) {- this.#streamDraft = EMPTY_LINE;- this.#submitSteering(message, send);- } else if (this.#messageQueue.enqueue(message)) {- this.#streamDraft = EMPTY_LINE;- }- this.#paint();- break;- }- case "ctrl-c":- case "escape": {- // Once a direct cancellation is pending, Ctrl+C is the hard escape- // hatch. Esc remains cooperative and repeated Ctrl+C presses can still- // pop queued messages into a steer payload.- if (key.type === "ctrl-c" && this.#messageQueue.view().cancelling) {- this.#interrupted = true;- this.#armExitOnNextPrompt = true;- this.#turnIndicator = { kind: "idle" };- this.#status = "Interrupted";- this.#resolveStreamInterrupt?.();- this.#paint();- break;- }- // Send queued input through the active session. With nothing queued,- // the same keys request explicit cancellation.- // Without a cancel capability an empty queue leaves either key inert.- if (this.#messageQueue.idle && this.#requestTurnCancel === undefined) break;- const outcome = this.#messageQueue.handleEscape();- if (outcome === "steer") {- const send = this.#sendSteering;- if (send !== undefined) {- const message = this.#messageQueue.takeSteering()!;- this.#submitSteering(message, send);- }- } else {- this.#cancelRequestedByUser = true;- this.#requestTurnCancel?.();- }- this.#paint();- break;- }- default: {- const edited = this.#killRing.apply(this.#streamDraft, key, { multiline: true });- if (edited !== undefined) {- this.#streamDraft = edited;- this.#paint();- }- break;- }- }- }-- #submitSteering(message: string, send: (message: string) => Promise<void>): void {- this.#nextSubmittedPromptOrigin = "steer";- this.#addSubmittedPrompt(message);- void send(message).catch((error) => {- this.#messageQueue.restoreSteering(message);- this.#addErrorBlock("Steering failed", toErrorMessage(error));- this.#paint();- });- }-#startCaretBlink() {this.#stopCaretBlink();this.#showCaret();@@ -3626,15 +3109,8 @@ export class TerminalRenderer implements AgentTUIRenderer {this.#tickTimer.unref?.();}- #startWorking(): void {- const startedAtMs = Date.now();- this.#activityPulseStartedAtMs = startedAtMs;- this.#turnIndicator = { kind: "waiting", startedAtMs };- this.#startTicker();- }-#stopTicker() {- if (this.#tasks.working().length > 0) return;+ if (this.#hasLiveSessionActivity()) return;this.#clearTicker();}@@ -3645,11 +3121,55 @@ export class TerminalRenderer implements AgentTUIRenderer {}}- /** Keeps the task panel's elapsed times ticking while any task works, even between streams. */- #syncTaskTicker(): void {- if (this.#tasks.working().length > 0) {- this.#startTicker();- } else if (!this.#streamDraftActive && this.#turnIndicator.kind === "idle") {+ /** Running work, or tasks still working after their turn ended; the task panel ticks. */+ #hasLiveSessionActivity(): boolean {+ return this.#view?.working === true || this.#transcript.tasks.length > 0;+ }++ /**+ * A settled agent task waits for its own last events before writing its end line, but not past+ * a short grace period; the next projection after it writes the line.+ */+ #scheduleTaskEndGrace(): void {+ if (!this.#transcript.finishing || this.#taskEndGraceTimer !== undefined) return;+ this.#taskEndGraceTimer = setTimeout(() => {+ this.#taskEndGraceTimer = undefined;+ if (this.#view !== undefined) this.renderConversation(this.#view);+ }, TASK_END_GRACE_MS);+ this.#taskEndGraceTimer.unref?.();+ }++ #clearTaskEndGrace(): void {+ if (this.#taskEndGraceTimer === undefined) return;+ clearTimeout(this.#taskEndGraceTimer);+ this.#taskEndGraceTimer = undefined;+ }++ #taskPanelRows(width: number): string[] {+ const working = this.#transcript.tasks;+ if (working.length === 0) return [];+ return renderTaskPanelRows(working, {+ width,+ theme: this.#theme,+ nowMs: Date.now(),+ pulse: this.#progressPulseGlyph(+ this.#activityPulseStartedAtMs,+ this.#theme.unicode ? PROGRESS_PULSE_GLYPH : PROGRESS_PULSE_ASCII_GLYPH,+ ),+ });+ }++ #syncActivityTicker(): void {+ if (this.#hasLiveSessionActivity()) {+ if (this.#tickTimer === undefined) {+ this.#activityPulseStartedAtMs = Date.now();+ this.#startTicker();+ }+ } else if (+ this.#setupFlow === undefined &&+ this.#startupPhase === undefined &&+ this.#flowlessStatus === undefined+ ) {this.#clearTicker();}}@@ -3670,22 +3190,16 @@ export class TerminalRenderer implements AgentTUIRenderer {if (block.id) this.#blockById.set(block.id, block);}- #addUserBlock(prompt: string) {- this.#hasUserMessage = true;- this.#pushBlock({ kind: "user", body: stripTerminalControls(prompt), live: false });- this.#paint();- }-/*** Commits the end-of-turn coda — wall-clock duration plus token flow —- * when control returns to the prompt after a chat turn. Consuming the- * armed timestamp here (not at stream end) spans multi-pass turns:- * question answers and connection authorizations re-stream without- * re-arming, so one turn gets one line.+ * when control returns to the composer. Approvals and questions answered+ * mid-turn do not return to the composer, so one turn gets one line.*/#commitTurnStats(): void {- const settled = this.#turnClock.settle();+ const settled = this.#turnClock.settle(this.#usage());if (settled === undefined) return;+ this.#lastTurnStats = settled;+ this.#diagnostics?.reportStats();// Quick, cheap turns close silently — the coda earns its row only when// the turn was long or expensive.@@ -3696,10 +3210,10 @@ export class TerminalRenderer implements AgentTUIRenderer {return;}- let body = `Done in ${this.#turnStatsBody(settled.elapsedMs)}`;+ let body = `Done in ${this.#turnStatsBody(settled)}`;// Context fill is a different measurement than the turn's summed flow —// it reads off the last step's absolute input — so it rides separately.- const contextTokens = this.#promptTokens ?? 0;+ const contextTokens = this.#view?.data.lastStepUsage?.inputTokens ?? 0;if (this.#contextSize !== undefined && this.#contextSize > 0 && contextTokens > 0) {const fill = Math.round((contextTokens / this.#contextSize) * 100);body += ` ${this.#theme.glyph.dot} ${fill}% context`;@@ -3707,18 +3221,14 @@ export class TerminalRenderer implements AgentTUIRenderer {this.#pushBlock({ kind: "turn-stats", body, live: false });}- #addSubmittedPrompt(prompt: string | undefined) {- if (prompt == null) return;- this.#hasUserMessage = true;- const origin = this.#nextSubmittedPromptOrigin;- this.#nextSubmittedPromptOrigin = undefined;- if (this.#pendingEchoedPrompt === prompt) {- this.#pendingEchoedPrompt = undefined;- return;- }- const block: Block = { kind: "user", body: stripTerminalControls(prompt), live: false };- if (origin !== undefined) block.promptOrigin = origin;- this.#pushBlock(block);+ #usage(): TokenUsage {+ return this.#view?.data.usage ?? { inputTokens: 0, outputTokens: 0 };+ }++ /** Commits one error block, such as a message the session did not accept. */+ renderError(title: string, message: string): void {+ this.#start();+ this.#addErrorBlock(title, message);}#addErrorBlock(@@ -3775,641 +3285,6 @@ export class TerminalRenderer implements AgentTUIRenderer {this.#blockById.delete(id);}- #finalizeAllBlocks() {- for (const block of this.#blocks) {- // Blocks awaiting an approval decision, action.result, or OAuth callback- // stay live past this stream boundary so their later terminal update can- // replace the same transcript block.- if (- block.status === "approval" ||- block.status === "running" ||- (block.kind === "connection-auth" && block.live) ||- // A command's echo settles only with its own outcome.- block === this.#pendingCommandEcho- ) {- continue;- }- block.live = false;- }- }-- #applyStreamEvent(- event: AgentTUIStreamEvent,- displayModes: DisplayModes,- turnState: RenderTurnState,- ): void {- const previousActivity = turnActivityLabel(turnState, this.#tasks.working());- updateTurnActivity(turnState, event);- switch (event.type) {- case "turn-start":- if (event.turnId !== this.#modelTurnId) {- this.#modelTurnId = event.turnId;- this.#resolvedModelId = undefined;- this.#paint();- }- break;-- case "step-start":- this.#resolvedModelId =- typeof event.modelId === "string"- ? stripTerminalControls(event.modelId.slice(0, 256)).replace(/\s+/gu, " ").trim() ||- undefined- : undefined;- this.#paint();- break;-- case "step-finish":- // Step usage reports are per-step deltas (extractStepUsage in the- // harness), so summing them yields true session totals. The- // `finish` event replays the last step's usage — don't sum there.- this.#diagnostics?.recordStepUsage(event.usage);- if (event.usage !== undefined) {- this.#turnClock.addUsage(event.usage);- }- // A valid call upgrades from its `preparing` placeholder within its- // own step; one still preparing at the boundary never parsed (the- // model emitted bad JSON and will retry under a fresh call id) and- // must not linger as a `Search …` ghost.- this.#sweepPreparingToolBlocks(turnState);- this.#applyUsage(event.usage);- this.#paint();- break;-- case "assistant-delta": {- const text = (turnState.text.get(event.id) ?? "") + stripTerminalControls(event.delta);- turnState.text.set(event.id, text);- this.#upsertAssistantBlock(event.id, text, true);- break;- }-- case "assistant-complete": {- const existing = turnState.text.get(event.id) ?? "";- const text = typeof event.text === "string" ? stripTerminalControls(event.text) : existing;- turnState.text.set(event.id, text);- this.#upsertAssistantBlock(event.id, text, false);- break;- }-- case "reasoning-delta": {- if (displayModes.reasoning === "hidden") break;- const text = (turnState.reasoning.get(event.id) ?? "") + stripTerminalControls(event.delta);- turnState.reasoning.set(event.id, text);- if (displayModes.reasoning === "full") {- this.#upsertReasoningBlock(event.id, text, true, displayModes);- break;- }- // Collapsed modes: the trace never reaches the transcript — the live- // turn bar and the end-of-turn coda carry the turn's progress.- break;- }-- case "reasoning-complete": {- if (displayModes.reasoning === "hidden") break;- const text = turnState.reasoning.get(event.id) ?? "";- if (displayModes.reasoning === "full") {- this.#upsertReasoningBlock(event.id, text, false, displayModes);- break;- }- break;- }-- case "tool-call-preparing":- if (displayModes.tools === "hidden") break;- // Panel-routed tools render from the real input, never a placeholder.- if (isPanelRoutedTool(event.toolName)) break;- this.#upsertNativeTool(- {- input: undefined,- preparing: true,- status: "running",- toolCallId: event.toolCallId,- toolName: event.toolName,- },- displayModes,- turnState,- );- break;-- case "tool-call":- this.#diagnostics?.recordToolCall(event.toolName);- if (displayModes.tools === "hidden") {- // No row, but a call that becomes a task still names its request.- turnState.tools.set(event.toolCallId, {- input: event.input,- label: event.label,- status: "running",- toolCallId: event.toolCallId,- toolName: event.toolName,- });- break;- }- this.#upsertNativeTool(- {- input: event.input,- status: "running",- toolCallId: event.toolCallId,- toolName: event.toolName,- label: event.label,- },- displayModes,- turnState,- );- break;-- case "tool-approval-request": {- if (displayModes.tools === "hidden") break;- const existing = turnState.tools.get(event.toolCallId);- if (existing === undefined) break;- this.#upsertNativeTool({ ...existing, status: "approval" }, displayModes, turnState);- break;- }-- case "tool-result": {- if (displayModes.tools === "hidden") break;- const existing = this.#resolveNativeToolState(event.toolCallId, turnState);- if (existing === undefined) break;- this.#upsertNativeTool(- {- ...existing,- output: event.output,- status: "done",- completeLabel: event.label,- },- displayModes,- turnState,- );- break;- }-- case "tool-error": {- const existing = this.#resolveNativeToolState(event.toolCallId, turnState);- // Tool failures reach the log even when tool display is hidden.- this.#diagnostics?.append({- source: "tool",- summary: `${existing?.toolName ?? event.toolCallId} failed`,- detail: event.errorText,- });- if (displayModes.tools === "hidden") break;- if (existing === undefined) break;- this.#upsertNativeTool(- { ...existing, errorText: event.errorText, status: "error" },- displayModes,- turnState,- );- break;- }-- case "tool-rejected": {- if (displayModes.tools === "hidden") break;- const existing = this.#resolveNativeToolState(event.toolCallId, turnState);- if (existing === undefined) break;- this.#upsertNativeTool(- { ...existing, errorText: event.reason, status: "denied" },- displayModes,- turnState,- );- break;- }-- case "tool-withdrawn": {- // The model reads why and retries; the person only sees the retry.- const withdrawn = turnState.tools.get(event.toolCallId);- this.#diagnostics?.append({- source: "tool",- summary: `${withdrawn?.toolName ?? event.toolCallId} was refused for the model to retry`,- detail: event.reason,- });- turnState.tools.delete(event.toolCallId);- this.#removeBlock(- this.#parentToolBlockIds.get(event.toolCallId) ?? toolSectionId(event.toolCallId),- );- this.#parentToolBlockIds.delete(event.toolCallId);- this.#paint();- break;- }-- case "task-started":- this.#startTask(event, displayModes, turnState);- break;-- case "task-settled":- this.#endTask(event);- break;-- case "error":- this.#addErrorBlock("Error", event.errorText, { detail: event.detail, hint: event.hint });- break;-- 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 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- // dispatch-window race), or `/cancel` from another client — must- // not eat the submitted message: hand it back as the next draft.- if (- !this.#cancelRequestedByUser &&- this.#currentSubmittedPrompt !== undefined &&- this.#streamDraft.text.length === 0- ) {- this.#streamDraft = lineOf(this.#currentSubmittedPrompt);- this.renderNotice(- "The turn was cancelled from outside this prompt — the message was restored to the input.",- );- }- break;-- case "finish":- this.#applyUsage(event.usage);- this.#paint();- break;- }- // Activity is independent of transcript visibility and idle streams.- if (- turnState === this.#activeTurnState &&- turnActivityLabel(turnState, this.#tasks.working()) !== previousActivity- ) {- this.#paint();- }- }-- #upsertAssistantBlock(id: string, text: string, live: boolean): void {- const content = stripTerminalControls(text).trim();- if (content.length === 0) return;- this.#upsertBlock({ id, kind: "assistant", body: content, live });- this.#paint();- }-- #upsertReasoningBlock(id: string, text: string, live: boolean, displayModes: DisplayModes): void {- const content = stripTerminalControls(text).trim();- if (content.length === 0) return;- this.#upsertBlock({- id,- kind: "reasoning",- body: content,- collapsed: collapseReasoning(displayModes.reasoning, live),- live,- });- this.#paint();- }-- #upsertNativeTool(- tool: NativeToolState,- displayModes: DisplayModes,- turnState: RenderTurnState,- ): void {- turnState.tools.set(tool.toolCallId, tool);- if (this.#childToolCallIds.has(tool.toolCallId)) return;- // The question surface — overlay while open, `? … ⎿ …` once answered —- // is the whole story of an ask_question call; a tool block beside it- // would narrate the same thing twice.- if (isPanelRoutedTool(tool.toolName)) return;-- const id = toolSectionId(tool.toolCallId);- this.#parentToolBlockIds.set(tool.toolCallId, id);- const context = this.#toolPresentationContext(tool);- this.#upsertBlock(renderNativeToolBlock(tool, id, displayModes.tools === "full", context));- this.#syncNativeToolBlockLiveness(turnState);- this.#paint();- }-- /**- * A call became a task: its row turns into the task's start line, in- * place, and the task joins the panel above the prompt. The line is- * written once and never changes, so nothing in the transcript moves while- * the task works.- */- #startTask(- event: Extract<AgentTUIStreamEvent, { type: "task-started" }>,- displayModes: DisplayModes,- turnState: RenderTurnState,- ): void {- const { kind, toolCallId, toolName } = event;- const rowId = this.#parentToolBlockIds.get(toolCallId) ?? toolSectionId(toolCallId);- const tool = turnState.tools.get(toolCallId);- turnState.tools.delete(toolCallId);- this.#parentToolBlockIds.delete(toolCallId);- const visible =- kind === "agent" ? this.#subagents !== "hidden" : displayModes.tools !== "hidden";- if (!visible || this.#startedTaskCallIds.has(toolCallId)) {- this.#removeBlock(rowId);- this.#syncNativeToolBlockLiveness(turnState);- this.#paint();- return;- }- this.#startedTaskCallIds.add(toolCallId);-- const input = tool?.input;- const label = tool?.label;- let baseName = agentDisplayName(stripTerminalControls(toolName));- let summary = agentTaskSummary(input);- if (kind === "tool") {- const presentation = presentTool(- toolName,- input,- this.#toolPresentationContext({ input, toolCallId, toolName, label }),- );- baseName = stripTerminalControls(presentation.title);- summary = stripTerminalControls(presentation.subtitle);- }- const entry = this.#tasks.start({- callId: toolCallId,- kind,- baseName,- toolName,- input,- label,- nowMs: Date.now(),- });- this.#replaceBlock(rowId, {- id: taskLineId(toolCallId, "start"),- kind: "task",- taskKind: kind,- title: entry.name,- subtitle: summary,- live: false,- });- this.#syncNativeToolBlockLiveness(turnState);- this.#syncTaskTicker();- this.#paint();- }-- /**- * A task settled. An agent's own last events can trail its parent's- * `task.settled` on a separate stream, so while the pump follows that- * agent, its end line waits for the agent's own end — or, if that never- * comes, for a short grace period or the end of the turn's stream — and- * counts all of its work.- */- #endTask(event: TaskSettledEvent): void {- const { toolCallId } = event;- const entry = this.#tasks.get(toolCallId);- if (entry === undefined || this.#pendingTaskEnds.has(toolCallId)) return;- const endedAtMs = Date.now();- const awaitsAgent =- entry.kind === "agent" &&- this.#followedAgentCallIds.has(toolCallId) &&- !this.#endedAgentCallIds.has(toolCallId);- if (!awaitsAgent) {- this.#writeTaskEnd(event, endedAtMs);- return;- }- entry.finishing = true;- const timer = setTimeout(() => this.#flushTaskEnd(toolCallId), TASK_END_GRACE_MS);- timer.unref?.();- this.#pendingTaskEnds.set(toolCallId, { event, endedAtMs, timer });- this.#paint();- }-- #flushTaskEnd(callId: string): void {- const pending = this.#pendingTaskEnds.get(callId);- if (pending === undefined) return;- clearTimeout(pending.timer);- this.#pendingTaskEnds.delete(callId);- this.#writeTaskEnd(pending.event, pending.endedAtMs);- }-- #flushTaskEnds(): void {- for (const callId of this.#pendingTaskEnds.keys()) this.#flushTaskEnd(callId);- }-- /** A task ended: it leaves the panel and writes its end line once. */- #writeTaskEnd(event: TaskSettledEvent, endedAtMs: number): void {- const entry = this.#tasks.finish(event.toolCallId);- if (entry === undefined) return;- const dot = ` ${this.#theme.glyph.dot} `;- const elapsed = `finished in ${formatTurnDuration(endedAtMs - entry.startedAtMs)}`;- const line: Block = {- id: taskLineId(event.toolCallId, "end"),- kind: "task",- taskKind: entry.kind,- title: entry.name,- live: false,- };- switch (event.status) {- case "completed": {- const outcome =- entry.kind === "agent"- ? summarizeChildTools([...entry.childTools.values()])- : presentTool(- entry.toolName,- entry.input,- this.#toolPresentationContext({- input: entry.input,- toolCallId: event.toolCallId,- toolName: entry.toolName,- label: entry.label,- }),- ).summarizeResult(event.output);- line.status = "done";- line.body =- outcome === undefined || outcome.length === 0 ? elapsed : `${elapsed}${dot}${outcome}`;- break;- }- case "failed": {- const reason = firstLine(stripTerminalControls(event.errorText ?? ""));- line.status = "error";- line.body = reason === undefined ? "failed" : `failed${dot}${reason}`;- break;- }- case "cancelled":- line.status = "denied";- line.body = "stopped";- break;- }- this.#pushBlock(line);- this.#syncTaskTicker();- this.#paint();- }-- /**- * A cancelled, dropped, or failed session gets no end for its unsettled- * tasks; they read as stopped. Settled ones keep their real outcome.- */- #stopWorkingTasks(): void {- this.#flushTaskEnds();- const endedAtMs = Date.now();- for (const entry of this.#tasks.working()) {- this.#writeTaskEnd(- { type: "task-settled", toolCallId: entry.callId, status: "cancelled" },- endedAtMs,- );- }- }-- /** Swaps a live row for its successor at the same position, so nothing below it moves. */- #replaceBlock(id: string, block: Block): void {- const index = this.#blocks.findIndex((candidate) => candidate.id === id);- if (index === -1) {- this.#pushBlock(block);- return;- }- this.#blockById.delete(id);- block.updateSeq = ++this.#updateSequence;- this.#blocks[index] = block;- if (block.id !== undefined) this.#blockById.set(block.id, block);- }-- #taskPanelRows(width: number): string[] {- const working = this.#tasks.working();- if (working.length === 0) return [];- return renderTaskPanelRows(working, {- width,- theme: this.#theme,- nowMs: Date.now(),- pulse: this.#progressPulseGlyph(- this.#activityPulseStartedAtMs,- this.#theme.unicode ? PROGRESS_PULSE_GLYPH : PROGRESS_PULSE_ASCII_GLYPH,- ),- });- }-- /**- * Feeds the file-content cache from the call and derives the presentation- * context a write needs for its diff. Read results (full-file only) and- * write inputs are the two exact sources the session has.- */- #toolPresentationContext(tool: {- readonly input?: unknown;- readonly output?: unknown;- readonly toolCallId: string;- readonly toolName: string;- readonly label?: string | undefined;- readonly completeLabel?: string | undefined;- /** The call started an agent task of its own. */- readonly agentTask?: boolean | undefined;- }): ToolPresentationContext | undefined {- if (tool.output !== undefined) this.#fileContents.observeRead(tool.output);-- const context: {- previousContent?: string;- existed?: boolean;- isSubagent?: boolean;- label?: string;- completeLabel?: string;- } = {};- if (tool.agentTask === true || this.#isSubagentToolName(tool.toolName)) {- context.isSubagent = true;- }- if (tool.label !== undefined) context.label = tool.label;- if (tool.completeLabel !== undefined) context.completeLabel = tool.completeLabel;-- const write = readWriteFileInput(tool.toolName, tool.input);- if (write === undefined) {- return Object.keys(context).length > 0 ? context : undefined;- }- const previous = this.#fileContents.observeWrite({- path: write.path,- content: write.content,- callId: tool.toolCallId,- });- if (previous !== undefined) context.previousContent = previous;- const existed = writeExistedFlag(tool.output);- if (existed !== undefined) context.existed = existed;- return context;- }-- /** True when a tool name matches a subagent from the agent's roster. */- #isSubagentToolName(toolName: string): boolean {- const local = this.#agentHeader?.info?.subagents.local;- if (local === undefined || local.length === 0) return false;- const baseName = toolBaseName(toolName);- return local.some((subagent) => subagent.name === baseName);- }-- /**- * Flips this pass's still-running top-level tool blocks to a terminal state.- * Approval-parked and out-of-band subagent blocks remain mutable.- */- #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";- block.live = false;- }- }-- /**- * Removes tool blocks that never left their `preparing` placeholder. Runs- * at step boundaries and at stream teardown: an announced call whose input- * never parsed (invalid JSON, an interrupted generation) has no- * `actions.requested` coming and would otherwise commit as a `… ` ghost.- */- #sweepPreparingToolBlocks(turnState: RenderTurnState): void {- for (const [toolCallId, tool] of turnState.tools) {- if (tool.preparing !== true) continue;- turnState.tools.delete(toolCallId);- const id = this.#parentToolBlockIds.get(toolCallId) ?? toolSectionId(toolCallId);- this.#removeBlock(id);- this.#parentToolBlockIds.delete(toolCallId);- }- }-- /** Keeps one parallel tool cohort mutable until every independent call settles. */- #syncNativeToolBlockLiveness(turnState: RenderTurnState): void {- const entries: Array<{ block: Block; active: boolean }> = [];- for (const tool of turnState.tools.values()) {- if (this.#childToolCallIds.has(tool.toolCallId)) continue;- const id = this.#parentToolBlockIds.get(tool.toolCallId) ?? toolSectionId(tool.toolCallId);- const block = this.#blockById.get(id);- if (block?.kind !== "tool") continue;- entries.push({ block, active: isActiveToolStatus(tool.status) });- }- applyCohortLiveness(entries);- }-- #resolveNativeToolState(- toolCallId: string,- turnState: RenderTurnState,- ): NativeToolState | undefined {- const active = turnState.tools.get(toolCallId);- if (active !== undefined) {- return active;- }-- const id = this.#parentToolBlockIds.get(toolCallId) ?? toolSectionId(toolCallId);- const block = this.#blockById.get(id);- if (block === undefined || block.kind !== "tool") {- return undefined;- }-- return {- errorText:- block.status === "error" && typeof block.result === "string" ? block.result : undefined,- input: block.toolInput,- output: block.toolOutput,- status: block.status ?? "running",- toolCallId,- toolName: block.toolName ?? block.title ?? "tool",- };- }-- #applyUsage(usage: AgentTUIStreamUsage | undefined): void {- if (usage === undefined) return;- const { inputTokens, outputTokens } = usage;- if (inputTokens != null || outputTokens != null) {- this.#totalTokens = (inputTokens ?? 0) + (outputTokens ?? 0);- }- this.#promptTokens = inputTokens ?? this.#promptTokens;- this.#assistantOutputTokens = outputTokens ?? this.#assistantOutputTokens;-- if (this.#assistantOutputTokens != null && this.#streamStartedAt !== undefined) {- const elapsedSeconds = (Date.now() - this.#streamStartedAt) / 1000;- if (elapsedSeconds > 0) {- this.#assistantTokensPerSecond = this.#assistantOutputTokens / elapsedSeconds;- }- }- }-// ---------------------------------------------------------------------------// Painting// ---------------------------------------------------------------------------@@ -4759,17 +3634,31 @@ export class TerminalRenderer implements AgentTUIRenderer {if (this.#inputActive) rows.push("");}- // The message-queue panel takes the slot directly above the input- // because it holds the user's own undelivered words and carries the- // steering/cancel affordance.+ // Messages typed while the agent starts wait in a panel directly above+ // the input because they hold the user's own undelivered words.const queueRows = renderMessageQueueRows({- view: this.#messageQueue.view(),+ view: this.#startupQueue.view(),width,theme: this.#theme,- working: this.#streamDraftActive,});if (queueRows.length > 0) rows.push(...queueRows, "");+ // While work runs, the one live turn bar rides above the composer. The+ // `Done in … (↑ … ↓ …)` coda is this bar's settled form.+ const working = this.#view?.working === true && this.#flowlessStatus === undefined;+ if (working) {+ rows.push(this.#streamingTurnBar(width));+ if (this.#cancelRequested) {+ rows.push(+ clip(+ `${c.yellow(this.#theme.glyph.dotActive)} ${c.dim("Cancelling turn… · Ctrl+C to stop waiting, then again to exit")}`,+ width,+ ),+ );+ }+ rows.push("");+ }+if (this.#inputActive) {// A complete command can show its argument hint beside the caret while// its matching suggestion remains visible beneath the prompt.@@ -4810,7 +3699,7 @@ export class TerminalRenderer implements AgentTUIRenderer {promptRows.placeholder =this.#startupEditor !== undefined? "Message · Enter to queue"- : this.#hasUserMessage+ : this.#hasUserMessage || working? "": this.#initialPromptPlaceholder;}@@ -4828,35 +3717,17 @@ export class TerminalRenderer implements AgentTUIRenderer {return rows;}- const turnIndicator = this.#turnIndicator;- // Every waiting state — a streaming turn, a just-submitted prompt, a- // question answer or approval resuming — shows the one live turn bar,- // with the inert prompt anchored beneath it while a stream owns the- // turn. The `Done in … (↑ … ↓ …)` coda is this bar's settled form.- const waitingOnStream = turnIndicator.kind === "waiting" && this.#flowlessStatus === undefined;- if (this.#streamDraftActive || waitingOnStream) {- rows.push(this.#streamingTurnBar(width));- this.#pushStreamingPrompt(rows, width);- const statusRows: string[] = [];- this.#pushStatusLine(statusRows, width);- if (!this.#streamDraftActive && statusRows.length > 0) rows.push("");- rows.push(...statusRows);- return rows;- }-- // A draft carried out of a finished turn renders ACTIVE immediately —- // the dim inert mark must not linger once the agent has returned. Keys- // pressed in this gap buffer and replay into the next prompt, so the- // cyan mark is honest.- if (this.#streamDraft.text.length > 0) {- this.#pushDraftPrompt(rows, width, { inert: false });+ // The composer is closed while a command or other surface runs. A kept+ // draft stays visible so keys typed in this gap have somewhere to land.+ if (working || this.#draft.text.length > 0) {+ this.#pushDraftPrompt(rows, width, { inert: working });this.#pushStatusLine(rows, width);return rows;}- // Interactive prompts (approvals, connection auth), the flowless setup- // spinner, and transitional states render as a quiet dot-led status row.- const statusText = this.#flowlessStatus ?? (this.#status.length > 0 ? this.#status : "Ready");+ // Interactive prompts, the flowless setup spinner, and transitional states+ // render as a quiet dot-led status row.+ const statusText = this.#flowlessStatus ?? "Ready";const meta = this.#statusMeta();const icon = c.dim(this.#theme.glyph.dot);const line = meta@@ -4869,19 +3740,15 @@ export class TerminalRenderer implements AgentTUIRenderer {#streamingTurnBar(width: number): string {const c = this.#theme.colors;- // A waiting state without an armed turn clock (a /command flash, an- // isolated approval) still gets a ticking duration from its own start.- const turnIndicator = this.#turnIndicator;- const startedAtMs =- this.#turnClock.startedAtMs ??- this.#streamStartedAt ??- (turnIndicator.kind === "waiting" ? turnIndicator.startedAtMs : Date.now());+ const startedAtMs = this.#turnClock.startedAtMs ?? Date.now();const elapsedMs = Math.max(0, Date.now() - startedAtMs);const marker = elapsedMs % 1000 < 500 ? (this.#theme.unicode ? "•" : "*") : " ";const elapsed =elapsedMs < 1000 ? "0s" : formatTurnDuration(Math.floor(elapsedMs / 1000) * 1000);- const label = `${turnActivityLabel(this.#activeTurnState, this.#tasks.working())} (${elapsed})`;- const { inputTokens, outputTokens } = this.#turnClock.usage;+ const activity =+ this.#view === undefined ? "Thinking" : turnActivity(this.#view, this.#transcript.tasks);+ const label = `${activity} (${elapsed})`;+ const { inputTokens, outputTokens } = this.#turnClock.usage(this.#usage());const tokens =inputTokens > 0 || outputTokens > 0? c.dim(` (${formatTokenFlow({ inputTokens, outputTokens }, this.#theme.glyph)})`)@@ -4890,36 +3757,21 @@ export class TerminalRenderer implements AgentTUIRenderer {}/** The settled coda's duration and optional token flow. */- #turnStatsBody(elapsedMs: number): string {- const { inputTokens, outputTokens } = this.#turnClock.usage;+ #turnStatsBody(settled: { elapsedMs: number } & TokenUsage): string {+ const { inputTokens, outputTokens } = settled;const flow =inputTokens === 0 && outputTokens === 0? "": ` (${formatTokenFlow({ inputTokens, outputTokens }, this.#theme.glyph)})`;- return `${formatTurnDuration(elapsedMs)}${flow}`;+ return `${formatTurnDuration(settled.elapsedMs)}${flow}`;}- /**- * The prompt row held in place while a turn streams: the draft under a- * live caret, Enter inert. Keeps the input anchored instead of vanishing- * for the duration of the turn.- */- #pushStreamingPrompt(rows: string[], width: number): void {- if (!this.#streamDraftActive) return;- // An empty pending prompt wears the same `❯` as the idle one; a- // typed draft dims the `❯` (inert — Enter does nothing yet).- // Readiness is therefore NOT detectable from the glyph — MockScreen's- // `waitForIdlePrompt` discriminates by the live turn bar's absence.- this.#pushDraftPrompt(rows, width, { inert: true });- }-- /** The `#streamDraft` rendered as a prompt row — inert mid-turn, active in- * the gap between the turn ending and the next prompt arming. */+ /** The kept draft as a prompt row, inert while work runs without the composer. */#pushDraftPrompt(rows: string[], width: number, options: { inert: boolean }): void {- rows.push("");+ if (rows.at(-1) !== "") rows.push("");const prompt: Parameters<typeof promptInputRows>[0] = {- text: this.#streamDraft.text,- cursor: this.#streamDraft.cursor,+ text: this.#draft.text,+ cursor: this.#draft.cursor,width,theme: this.#theme,caretVisible: true,@@ -4927,7 +3779,7 @@ export class TerminalRenderer implements AgentTUIRenderer {maxRows: 4,inert: options.inert,};- if (options.inert && this.#streamDraft.text.length === 0) prompt.placeholder = "";+ if (options.inert && this.#draft.text.length === 0) prompt.placeholder = "";rows.push(...promptInputRows(prompt));}@@ -4959,8 +3811,9 @@ export class TerminalRenderer implements AgentTUIRenderer {if (this.#logLevelHintActive) input.logLevel = this.#logs;const agentModel = this.#agentHeader?.info?.agent.model;if (agentModel?.routing.kind === "dynamic") {+ const modelId = this.#view?.data.modelId;input.dynamicModel = true;- if (this.#resolvedModelId !== undefined) input.model = this.#resolvedModelId;+ if (modelId !== undefined) input.model = modelId;} else if (agentModel?.id !== undefined) input.model = agentModel.id;// "provider-default" is the absent-setting sentinel, not a level worth showing.if (agentModel?.reasoning !== undefined && agentModel.reasoning !== "provider-default") {@@ -4999,14 +3852,19 @@ export class TerminalRenderer implements AgentTUIRenderer {const parts: string[] = [];// The running token total lives on the persistent status line below;// this row keeps only the turn-scoped stats.- const stats = formatAssistantResponseStats(- {- totalTokens: this.#totalTokens,- outputTokens: this.#assistantOutputTokens,- tokensPerSecond: this.#assistantTokensPerSecond,- },- this.#assistantResponseStats,- );+ const turn = this.#lastTurnStats;+ const stats =+ turn === undefined+ ? undefined+ : formatAssistantResponseStats(+ {+ totalTokens: turn.inputTokens + turn.outputTokens,+ outputTokens: turn.outputTokens,+ tokensPerSecond:+ turn.elapsedMs > 0 ? turn.outputTokens / (turn.elapsedMs / 1000) : undefined,+ },+ this.#assistantResponseStats,+ );if (stats) parts.push(stats);return parts.length > 0 ? c.dim(parts.join(` ${this.#theme.glyph.dot} `)) : "";}@@ -5369,26 +4227,6 @@ function chunkToString(chunk: string | Uint8Array, encoding?: BufferEncoding): sreturn typeof chunk === "string" ? chunk : Buffer.from(chunk).toString(encoding);}-async function* iterateTUIStream(- stream: AsyncIterable<AgentTUIStreamEvent> | ReadableStream<AgentTUIStreamEvent>,-): AsyncIterable<AgentTUIStreamEvent> {- if (stream instanceof ReadableStream) {- const reader = stream.getReader();- try {- while (true) {- const { done, value } = await reader.read();- if (done) return;- yield value;- }- } finally {- reader.releaseLock();- }- return;- }-- yield* stream;-}-function clip(line: string, width: number): string {return clipVisible(line, width);}@@ -5520,24 +4358,6 @@ function previousBlockOf(block: Block): PreviousBlock {* closed `○ <source> … └` section, so consecutive writes get air between* their corners and headers.*/-/** A call still holding the cohort open: executing, or parked on approval. */-function isActiveToolStatus(status: ToolStatus | undefined): boolean {- return status === "running" || status === "approval";-}--/**- * One parallel cohort stays mutable until every independent call settles:- * while any member is active, settled siblings stay live so an in-flight- * batch accumulates as one group instead of fragmenting per status flip.- * Used by the top-level tool cohort.- */-function applyCohortLiveness(entries: ReadonlyArray<{ block: Block; active: boolean }>): void {- const cohortActive = entries.some((entry) => entry.active);- for (const entry of entries) {- entry.block.live = cohortActive || entry.active;- }-}-function leadsWithGap(block: Block, previous: PreviousBlock | undefined): boolean {// A tool run breathes after whoever spoke last — the prompt, the agent's// own prose, or an answered question — and stays tight within the run.@@ -5626,165 +4446,14 @@ function hiddenRowsMarker(hidden: number, theme: Theme): string {);}-function collapseReasoning(mode: TerminalPartDisplayMode, isLastPart: boolean): boolean {- switch (mode) {- case "collapsed":- return true;- case "auto-collapsed":- return !isLastPart;- default:- return false;- }-}--function renderNativeToolBlock(- tool: NativeToolState,- id: string,- expanded: boolean,- context?: ToolPresentationContext,-): Block {- const presentation =- tool.preparing === true- ? presentPreparingTool(tool.toolName, context)- : presentTool(tool.toolName, tool.input, context);- const block: Block = {- id,- kind: "tool",- title: stripTerminalControls(presentation.title),- subtitle: stripTerminalControls(presentation.subtitle),- status: tool.status,- live: tool.status === "running" || tool.status === "approval",- expanded,- toolInput: tool.input,- toolName: tool.toolName,- toolGroup: presentation.group,- };- if (presentation.doneTitle !== undefined) {- block.doneTitle = stripTerminalControls(presentation.doneTitle);- }- if (presentation.detail !== undefined) {- block.detailLines = presentation.detail;- block.keepDetailWhenDone = presentation.keepDetailWhenDone === true;- }-- if (tool.output !== undefined) {- block.result = presentation.summarizeResult(tool.output);- block.toolOutput = tool.output;- } else if (tool.errorText !== undefined) {- block.result = stripTerminalControls(tool.errorText);- }-- return block;-}--/** Reads the shared write-file result's `existed` flag, whatever the tool. */-function writeExistedFlag(output: unknown): boolean | undefined {- if (output === null || typeof output !== "object" || Array.isArray(output)) return undefined;- const existed = (output as Record<string, unknown>)["existed"];- return typeof existed === "boolean" ? existed : undefined;-}--function subagentToolStatus(status: SubagentToolUpdate["status"]): ToolStatus {- switch (status) {- case "preparing":- return "running";- case "approval-requested":- return "approval";- case "executing":- return "running";- case "done":- return "done";- case "failed":- return "error";- case "rejected":- return "denied";- }-}-function formatToolApprovalTitle(request: AgentTUIToolApprovalRequest): string {return stripTerminalControls(request.title ?? request.toolName);}-function toolSectionId(toolCallId: string): string {- return `tool:${toolCallId}`;-}-function questionSectionId(requestId: string): string {return `question:${requestId}`;}-type TaskSettledEvent = Extract<AgentTUIStreamEvent, { type: "task-settled" }>;--/** How long a settled agent task waits for its own stream's end before writing its end line. */-const TASK_END_GRACE_MS = 2_000;--function taskLineId(callId: string, edge: "start" | "end"): string {- return `task:${callId}:${edge}`;-}--function subagentStepRowId(callId: string, sectionKey: number): string {- return `subagent:${callId}:step:${sectionKey}`;-}--function subagentToolRowId(callId: string, childCallId: string): string {- return `subagent:${callId}:tool:${childCallId}`;-}--/** The first line of an agent call's message: what the agent was asked to do. */-function agentTaskSummary(input: unknown): string {- if (input === null || typeof input !== "object") return "";- const message: unknown = Reflect.get(input, "message");- return typeof message === "string" ? (firstLine(stripTerminalControls(message)) ?? "") : "";-}--function firstLine(text: string): string | undefined {- const line = text.split(/\r?\n/u).find((candidate) => candidate.trim().length > 0);- return line?.trim();-}--function connectionAuthSectionId(connectionName: string): string {- return `connection-auth:${connectionName}`;-}--function connectionAuthTerminalMessage(state: ConnectionAuthUpdate["state"]): string | undefined {- switch (state) {- case "authorized":- return "Authorization complete";- case "declined":- return "Authorization declined";- case "failed":- return "Authorization failed";- case "timed-out":- return "Authorization timed out";- case "required":- case "pending":- return undefined;- }-}--function formatConnectionAuthContent(- update: ConnectionAuthUpdate,- terminalMessage: string | undefined,-): string {- const lines: string[] = [];- if (terminalMessage !== undefined) {- lines.push(terminalMessage);- } else {- const description = stripTerminalControls(update.description);- if (description.length > 0) lines.push(description);- const challenge = update.challenge;- if (challenge?.url) lines.push(`URL: ${stripTerminalControls(challenge.url)}`);- if (challenge?.userCode) lines.push(`Code: ${stripTerminalControls(challenge.userCode)}`);- if (challenge?.expiresAt) lines.push(`Expires: ${stripTerminalControls(challenge.expiresAt)}`);- if (challenge?.instructions) lines.push(stripTerminalControls(challenge.instructions));- }- if (update.reason !== undefined) {- const reason = stripTerminalControls(update.reason);- if (reason.length > 0) lines.push(`Reason: ${reason}`);- }- return lines.join("\n");-}-function resolveQuestionText(rawText: string,question: AgentTUIInputQuestion,diff --git a/packages/eve/src/cli/dev/tui/terminal-tool-part.ts b/packages/eve/src/cli/dev/tui/terminal-tool-part.tsnew file mode 100644index 000000000..3eea15082--- /dev/null+++ b/packages/eve/src/cli/dev/tui/terminal-tool-part.ts@@ -0,0 +1,5 @@+import type { EveDynamicToolPart, EveMessagePart } from "#client/message-reducer-types.js";++export function isTerminalToolCallPart(part: EveMessagePart): part is EveDynamicToolPart {+ return part.type === "dynamic-tool" && part.toolMetadata?.eve?.kind === "tool-call";+}diff --git a/packages/eve/src/cli/dev/tui/test/fake-eve-server.ts b/packages/eve/src/cli/dev/tui/test/fake-eve-server.tsnew file mode 100644index 000000000..3edc9e273--- /dev/null+++ b/packages/eve/src/cli/dev/tui/test/fake-eve-server.ts@@ -0,0 +1,196 @@+import {+ createMessageCompletedEvent,+ createMessageReceivedEvent,+ createSessionWaitingEvent,+ createTurnCompletedEvent,+ createTurnStartedEvent,+ EVE_MESSAGE_STREAM_VERSION,+ EVE_STREAM_VERSION_HEADER,+ type MessageStreamEvent,+ type UnstampedMessageStreamEvent,+} from "#protocol/message.js";++export interface FakeEveRequest {+ readonly method: string;+ readonly path: string;+ readonly sessionId?: string;+ readonly body?: Record<string, unknown>;+}++/** Events a fake agent streams after it accepts one delivery. */+export type FakeEveTurn = (+ request: FakeEveRequest & { readonly deliveryId: string; readonly turnId: string },+) => readonly UnstampedMessageStreamEvent[];++interface FakeSession {+ readonly log: MessageStreamEvent[];+ readonly streams: Set<ReadableStreamDefaultController<Uint8Array>>;+}++const encoder = new TextEncoder();++/**+ * An in-memory eve HTTP server for driving real clients through `fetch`.+ * Sessions keep a durable event log; streams replay from their cursor and then+ * follow live emissions, so reconnects and late subscribers behave like eve.+ */+export class FakeEveServer {+ readonly requests: FakeEveRequest[] = [];+ readonly #sessions = new Map<string, FakeSession>();+ readonly #respond: FakeEveTurn;+ readonly #fallback?: typeof fetch;+ #sessionCount = 0;+ #deliveryCount = 0;+ #eventCount = 0;+ #currentSessionId?: string;++ /** `fallback` serves routes outside the session API, such as dev runtime artifacts. */+ constructor(respond: FakeEveTurn = reply("Done."), fallback?: typeof fetch) {+ this.#respond = respond;+ if (fallback !== undefined) this.#fallback = fallback;+ }++ get sessionId(): string | undefined {+ return this.#currentSessionId;+ }++ /** Requests to one route, such as `POST /cancel`. */+ requestsTo(method: string, suffix: string): FakeEveRequest[] {+ return this.requests.filter(+ (request) => request.method === method && request.path.endsWith(suffix),+ );+ }++ /** Appends events to a session's durable stream; the current session by default. */+ emit(+ events: readonly UnstampedMessageStreamEvent[],+ deliveryId?: string,+ sessionId = this.#currentSessionId,+ ): void {+ if (sessionId === undefined) throw new Error("No fake eve session exists yet.");+ const session = this.#session(sessionId);+ for (const event of events) {+ this.#eventCount += 1;+ const at = new Date(Date.UTC(2026, 0, 1) + this.#eventCount).toISOString();+ const id = `evt_fake_${String(this.#eventCount).padStart(4, "0")}`;+ const stamped = {+ ...event,+ meta: deliveryId === undefined ? { at, id } : { at, id, deliveryIds: [deliveryId] },+ } as MessageStreamEvent;+ session.log.push(stamped);+ const line = encoder.encode(`${JSON.stringify(stamped)}\n`);+ for (const stream of session.streams) stream.enqueue(line);+ }+ }++ readonly fetch = async (input: string | URL | Request, init?: RequestInit): Promise<Response> => {+ const url = new URL(typeof input === "string" || input instanceof URL ? input : input.url);+ const method = init?.method ?? "GET";+ const body =+ typeof init?.body === "string"+ ? (JSON.parse(init.body) as Record<string, unknown>)+ : undefined;+ const match = /^\/eve\/v1\/session(?:\/([^/]+))?(?:\/([a-z]+))?$/u.exec(url.pathname);+ if (match === null && this.#fallback !== undefined) return await this.#fallback(input, init);+ const sessionId = match?.[1];+ const request: { -readonly [Key in keyof FakeEveRequest]: FakeEveRequest[Key] } = {+ method,+ path: url.pathname,+ };+ if (sessionId !== undefined) request.sessionId = sessionId;+ if (body !== undefined) request.body = body;+ this.requests.push(request);+ if (match === null) return new Response("Not found", { status: 404 });++ const action = match[2];+ if (method === "GET" && action === "stream" && sessionId !== undefined) {+ return this.#stream(sessionId, Number(url.searchParams.get("startIndex") ?? "0"));+ }+ if (method === "POST" && action === undefined) {+ const id = sessionId ?? this.#createSession();+ this.#currentSessionId = id;+ const deliveryId = `delivery_${String(++this.#deliveryCount)}`;+ const turnId = `turn_${String(this.#deliveryCount)}`;+ queueMicrotask(() =>+ this.emit(this.#respond({ ...request, deliveryId, turnId }), deliveryId),+ );+ return Response.json(+ { ok: true, status: "accepted", sessionId: id, deliveryId },+ { status: 202 },+ );+ }+ if (method === "POST" && action === "reset" && sessionId !== undefined) {+ return Response.json({ ok: true, status: "reset", previousSessionId: sessionId });+ }+ if (method === "POST" && sessionId !== undefined) {+ return Response.json({ ok: true, status: "accepted", sessionId });+ }+ return new Response("Not found", { status: 404 });+ };++ close(): void {+ for (const session of this.#sessions.values()) {+ for (const stream of session.streams) stream.close();+ session.streams.clear();+ }+ }++ #createSession(): string {+ const id = `session_${String(++this.#sessionCount)}`;+ this.#session(id);+ return id;+ }++ #session(id: string): FakeSession {+ let session = this.#sessions.get(id);+ if (session === undefined) {+ session = { log: [], streams: new Set() };+ this.#sessions.set(id, session);+ }+ return session;+ }++ #stream(sessionId: string, startIndex: number): Response {+ const session = this.#session(sessionId);+ let controller!: ReadableStreamDefaultController<Uint8Array>;+ return new Response(+ new ReadableStream<Uint8Array>({+ start(streamController) {+ controller = streamController;+ for (const event of session.log.slice(startIndex)) {+ controller.enqueue(encoder.encode(`${JSON.stringify(event)}\n`));+ }+ session.streams.add(controller);+ },+ cancel() {+ session.streams.delete(controller);+ },+ }),+ { headers: { [EVE_STREAM_VERSION_HEADER]: EVE_MESSAGE_STREAM_VERSION } },+ );+ }+}++/** A fake agent that answers every message with the same completed reply. */+export function reply(text: string): FakeEveTurn {+ return ({ body, turnId }) => [+ ...(typeof body?.message === "string"+ ? [createMessageReceivedEvent({ message: body.message, sequence: 0, turnId })]+ : ([] as UnstampedMessageStreamEvent[])),+ createTurnStartedEvent({ sequence: 1, turnId }),+ createMessageCompletedEvent({+ finishReason: "stop",+ message: text,+ sequence: 2,+ stepIndex: 0,+ turnId,+ }),+ createTurnCompletedEvent({ sequence: 3, turnId }),+ createSessionWaitingEvent(),+ ];+}++/** A fake agent that accepts deliveries and leaves their events to the test. */+export function silent(): FakeEveTurn {+ return () => [];+}diff --git a/packages/eve/src/cli/dev/tui/test/index.ts b/packages/eve/src/cli/dev/tui/test/index.tsindex d719fa331..a8ea5bd21 100644--- a/packages/eve/src/cli/dev/tui/test/index.ts+++ b/packages/eve/src/cli/dev/tui/test/index.ts@@ -11,6 +11,7 @@ export { createPromptCommandHandler } from "../prompt-command-handler.js";export { promptCommandsFor } from "../prompt-commands.js";export { TerminalRenderer } from "../terminal-renderer.js";export { MockScreen, MockUserInput } from "./mock-terminal.js";+export { FakeEveServer } from "./fake-eve-server.js";// The dev watcher's real log-line formatter, so smoke tests can drive the// TUI's rebuild-status condensation with producer-authentic lines.export {diff --git a/packages/eve/src/cli/dev/tui/transcript-parts.ts b/packages/eve/src/cli/dev/tui/transcript-parts.tsnew file mode 100644index 000000000..f83fe0b58--- /dev/null+++ b/packages/eve/src/cli/dev/tui/transcript-parts.ts@@ -0,0 +1,340 @@+/** Pure pieces of the transcript projection: tool rows, task lines, and agent steps. */++import type {+ ConversationState,+ ConversationTaskCall,+ ConversationTask,+} from "#client/conversation-state.js";+import type {+ EveAuthorizationPart,+ EveDynamicToolPart,+ EveMessage,+ EveMessagePart,+} from "#client/message-reducer-types.js";+import { stripTerminalControls } from "#cli/ui/terminal-text.js";+import type { Block, ToolStatus } from "./blocks.js";+import { formatTurnDuration } from "./stream-format.js";+import { isTerminalToolCallPart } from "./terminal-tool-part.js";+import { summarizeChildTools } from "./tool-block-groups.js";+import {+ presentPreparingTool,+ presentTool,+ type ToolPresentationContext,+} from "./tool-presentation.js";++export type ToolState = {+ readonly status: ToolStatus;+ readonly output?: unknown;+ readonly errorText?: string;+};++/** A task whose start line is written, named once and never renamed. */+export interface TaskRecord {+ readonly callId: string;+ readonly kind: "agent" | "tool";+ readonly name: string;+ readonly toolName: string;+ readonly input: unknown;+ readonly label: string | undefined;+ readonly startedAtMs: number;+ settledAtMs?: number;+ ended: boolean;+}++export function toolState(+ part: EveDynamicToolPart,+ conversation: ConversationState,+ working: boolean,+ taskWorking: boolean,+): ToolState {+ // A task call's receipt closes the tool part; the call runs until its task.settled, even after+ // its turn ends, as a root approval ends it.+ if (taskWorking) return { status: "running" };+ const state = settledToolState(part, conversation);+ return state.status === "running" && !working+ ? { status: "error", errorText: "interrupted" }+ : state;+}++function settledToolState(part: EveDynamicToolPart, conversation: ConversationState): ToolState {+ switch (part.state) {+ case "approval-requested": {+ const input = conversation.inputs[part.approval.id];+ if (input?.status !== "responded") return { status: "approval" };+ return input.response?.optionId === "approve"+ ? { status: "running" }+ : { status: "denied", errorText: "Denied by user." };+ }+ case "approval-responded":+ return part.approval.approved === false+ ? { status: "denied", errorText: part.approval.reason ?? "Denied by user." }+ : { status: "running" };+ case "output-available":+ return part.partial === true+ ? { status: "running" }+ : { status: "done", output: part.output };+ case "output-error":+ return { status: "error", errorText: part.errorText };+ case "output-denied":+ return {+ status: "denied",+ errorText: part.approval.reason ?? "Tool execution was cancelled.",+ };+ default:+ return { status: "running" };+ }+}++export function isActive(status: ToolStatus): boolean {+ return status === "running" || status === "approval";+}++export function toolBlock(+ part: EveDynamicToolPart,+ state: ToolState,+ context: ToolPresentationContext | undefined,+): Omit<Block, "kind"> {+ const { toolName, input } = part;+ const presentation =+ part.state === "input-streaming"+ ? presentPreparingTool(toolName, context)+ : presentTool(toolName, input, context);+ const block: Omit<Block, "kind"> = {+ title: stripTerminalControls(presentation.title),+ subtitle: stripTerminalControls(presentation.subtitle),+ status: state.status,+ toolInput: input,+ toolName,+ toolGroup: presentation.group,+ };+ if (presentation.doneTitle !== undefined) {+ block.doneTitle = stripTerminalControls(presentation.doneTitle);+ }+ if (presentation.detail !== undefined) {+ block.detailLines = presentation.detail;+ block.keepDetailWhenDone = presentation.keepDetailWhenDone === true;+ }+ if (state.output !== undefined) {+ block.result = presentation.summarizeResult(state.output);+ block.toolOutput = state.output;+ } else if (state.errorText !== undefined) {+ block.result = stripTerminalControls(state.errorText);+ }+ return block;+}++/** A task's end line: how long it took and what it did, or why it failed, or that it stopped. */+export function endLine(+ record: TaskRecord,+ call: Pick<ConversationTaskCall, "status" | "output" | "error">,+ childTools: readonly Block[] | undefined,+ /** The theme's `·`, which separates the line's facts. */+ separator: string,+): Block {+ const dot = ` ${separator} `;+ const line: Block = {+ id: `task:${record.callId}:end`,+ kind: "task",+ taskKind: record.kind,+ title: record.name,+ live: false,+ };+ switch (call.status) {+ case "completed": {+ const elapsed = `finished in ${formatTurnDuration((record.settledAtMs ?? Date.now()) - record.startedAtMs)}`;+ const outcome =+ record.kind === "agent"+ ? summarizeChildTools(childTools ?? [])+ : presentTool(record.toolName, record.input, labelContext(record.label)).summarizeResult(+ call.output,+ );+ line.status = "done";+ line.body =+ outcome === undefined || outcome.length === 0 ? elapsed : `${elapsed}${dot}${outcome}`;+ break;+ }+ case "failed": {+ const reason = firstLine(stripTerminalControls(call.error?.message ?? ""));+ line.status = "error";+ line.body = reason === undefined ? "failed" : `failed${dot}${reason}`;+ break;+ }+ default:+ line.status = "denied";+ line.body = "stopped";+ }+ return line;+}++export function labelContext(label: string | undefined): ToolPresentationContext | undefined {+ return label === undefined ? undefined : { label };+}++/** The first line of an agent call's message: what the agent was asked to do. */+export function agentTaskSummary(input: unknown): string {+ if (input === null || typeof input !== "object") return "";+ const message: unknown = Reflect.get(input, "message");+ return typeof message === "string" ? (firstLine(stripTerminalControls(message)) ?? "") : "";+}++export function firstLine(text: string): string | undefined {+ const line = text.split(/\r?\n/u).find((candidate) => candidate.trim().length > 0);+ return line?.trim();+}++export type SubagentStep = {+ readonly key: string;+ /** Where the step ends among its messages' parts, to order it among the agent's tool calls. */+ readonly order: number;+ readonly reasoning: string;+ readonly message: string;+ readonly finalized: boolean;+};++/** Pairs each child reply with the reasoning that preceded it. */+export function subagentSteps(messages: readonly EveMessage[]): SubagentStep[] {+ const steps: SubagentStep[] = [];+ let order = 0;+ for (const message of messages) {+ let reasoning = "";+ for (const [index, part] of message.parts.entries()) {+ order += 1;+ if (part.type === "reasoning") reasoning += part.text;+ if (part.type === "text") {+ steps.push({+ key: part.id ?? `${message.id}:${index}`,+ order,+ reasoning,+ message: part.text,+ finalized: part.state === "done",+ });+ reasoning = "";+ }+ if (part.type === "dynamic-tool" && reasoning) {+ steps.push({+ key: `${message.id}:${index}:reasoning`,+ order: order - 0.5,+ reasoning,+ message: "",+ finalized: true,+ });+ reasoning = "";+ }+ }+ if (reasoning) {+ steps.push({+ key: `${message.id}:reasoning:${message.parts.length}`,+ order,+ reasoning,+ message: "",+ finalized: message.metadata?.status === "complete",+ });+ }+ }+ return steps+ .map((step) => ({+ ...step,+ reasoning: stripTerminalControls(step.reasoning).trim(),+ message: stripTerminalControls(step.message).trim(),+ }))+ .filter((step) => step.reasoning.length > 0 || step.message.length > 0);+}++export function childToolCallIds(conversation: ConversationState): Set<string> {+ const ids = new Set<string>();+ for (const agent of Object.values(conversation.agents)) {+ if (agent.observation.status === "not-followed") continue;+ for (const message of agent.observation.conversation?.messages ?? []) {+ for (const part of message.parts) {+ if (part.type === "dynamic-tool") ids.add(part.toolCallId);+ }+ }+ }+ return ids;+}++/** A tool call, including one whose input is still streaming and so has no kind yet. */+export function isToolCallRow(part: EveMessagePart): part is EveDynamicToolPart {+ return (+ part.type === "dynamic-tool" &&+ (part.state === "input-streaming" || isTerminalToolCallPart(part))+ );+}++/** Every call that started or reached a task, by call ID. */+export function taskCallsById(+ conversation: ConversationState,+): Map<string, { task: ConversationTask; call: ConversationTaskCall }> {+ const calls = new Map<string, { task: ConversationTask; call: ConversationTaskCall }>();+ for (const task of Object.values(conversation.tasks)) {+ for (const call of Object.values(task.calls)) calls.set(call.callId, { task, call });+ }+ return calls;+}++/** Tools a step runs in parallel settle together, so a finished one waits for its siblings. */+export function activeToolSteps(+ states: ReadonlyMap<EveDynamicToolPart, ToolState>,+): Set<number | undefined> {+ const steps = new Set<number | undefined>();+ for (const [part, state] of states) if (isActive(state.status)) steps.add(part.stepIndex);+ return steps;+}++export function userText(message: EveMessage): string {+ return message.parts+ .map((part) =>+ part.type === "text"+ ? part.text+ : part.type === "file"+ ? `[file${part.filename === undefined ? "" : `: ${part.filename}`}]`+ : "",+ )+ .filter((text) => text.length > 0)+ .join("\n");+}++export function authorizationTerminalMessage(state: string): string | undefined {+ switch (state) {+ case "authorized":+ return "Authorization complete";+ case "declined":+ return "Authorization declined";+ case "failed":+ return "Authorization failed";+ case "timed-out":+ return "Authorization timed out";+ default:+ return undefined;+ }+}++export function formatAuthorization(+ part: EveAuthorizationPart,+ terminalMessage: string | undefined,+): string {+ const lines: string[] = [];+ if (terminalMessage !== undefined) {+ lines.push(terminalMessage);+ } else {+ const description = stripTerminalControls(part.description);+ if (description.length > 0) lines.push(description);+ const challenge = part.authorization;+ if (challenge?.url) lines.push(`URL: ${stripTerminalControls(challenge.url)}`);+ if (challenge?.userCode) lines.push(`Code: ${stripTerminalControls(challenge.userCode)}`);+ if (challenge?.expiresAt) lines.push(`Expires: ${stripTerminalControls(challenge.expiresAt)}`);+ if (challenge?.instructions) lines.push(stripTerminalControls(challenge.instructions));+ }+ if (part.state === "completed" && part.reason !== undefined) {+ const reason = stripTerminalControls(part.reason);+ if (reason.length > 0) lines.push(`Reason: ${reason}`);+ }+ return lines.join("\n");+}++/** Reads the shared write-file result's `existed` flag, whatever the tool. */+export function writeExistedFlag(output: unknown): boolean | undefined {+ if (output === null || typeof output !== "object" || Array.isArray(output)) return undefined;+ const existed = (output as Record<string, unknown>)["existed"];+ return typeof existed === "boolean" ? existed : undefined;+}diff --git a/packages/eve/src/cli/dev/tui/transcript.test.ts b/packages/eve/src/cli/dev/tui/transcript.test.tsnew file mode 100644index 000000000..c5f6b355f--- /dev/null+++ b/packages/eve/src/cli/dev/tui/transcript.test.ts@@ -0,0 +1,588 @@+import { describe, expect, it, onTestFinished, vi } from "vitest";+import {+ initialConversationState,+ reduceConversation,+ type ConversationEvent,+} from "#client/conversation-reducer.js";+import type { ConversationState } from "#client/conversation-state.js";+import { stampTestEvent } from "#internal/testing/events.js";+import {+ createActionInputAppendedEvent,+ createActionResultEvent,+ createActionsRequestedEvent,+ createAuthorizationCompletedEvent,+ createAuthorizationRequiredEvent,+ createInputRequestedEvent,+ createMessageAppendedEvent,+ createMessageCompletedEvent,+ createMessageReceivedEvent,+ createAgentStartedEvent,+ createTaskSettledEvent,+ createTaskStartedEvent,+ createTurnCancelledEvent,+ createTurnCompletedEvent,+ createTurnFailedEvent,+ createTurnStartedEvent,+ createTurnWaitingEvent,+ type MessageStreamEvent,+ type UnstampedMessageStreamEvent,+} from "#protocol/message.js";+import type { Block } from "./blocks.js";+import { tuiSessionReducer, type AgentTUIConversationView } from "./conversation-view.js";+import { ConversationTranscript, turnActivity, type TranscriptOptions } from "./transcript.js";++const options: TranscriptOptions = {+ tools: "full",+ reasoning: "full",+ subagents: "full",+ connectionAuth: "full",+};++let stamp = 0;+function event(value: UnstampedMessageStreamEvent): MessageStreamEvent {+ return stampTestEvent(value, ++stamp);+}++function conversation(+ events: readonly ConversationEvent[],+ state: ConversationState = initialConversationState(),+): ConversationState {+ return events.reduce(reduceConversation, state);+}++function view(state: ConversationState, working: boolean): AgentTUIConversationView {+ return { conversation: state, working, data: tuiSessionReducer.initial(), failures: [] };+}++function byId(blocks: readonly Block[], id: string): Block | undefined {+ return blocks.find((block) => block.id === id);+}++const turn = event(createTurnStartedEvent({ sequence: 0, turnId: "turn_1" }));++function toolCall(callId: string, toolName = "read_file") {+ return event(+ createActionsRequestedEvent({+ actions: [{ callId, input: { path: `${callId}.md` }, kind: "tool-call", toolName }],+ sequence: 1,+ stepIndex: 0,+ turnId: "turn_1",+ }),+ );+}++function toolResult(callId: string, toolName = "read_file") {+ return event(+ createActionResultEvent({+ result: { callId, kind: "tool-result", output: "ok", toolName },+ sequence: 2,+ stepIndex: 0,+ turnId: "turn_1",+ }),+ );+}++function taskStarted(callId: string, name: string, taskId = "task_1") {+ return event(createTaskStartedEvent({ callId, kind: "agent", name, taskId, turnId: "turn_1" }));+}++function agentStarted(callId: string) {+ return event(+ createAgentStartedEvent({+ callId,+ name: "research",+ parentSessionId: "session_1",+ sessionId: "child_1",+ taskId: "task_1",+ turnId: "turn_1",+ }),+ );+}++function settled(callId: string) {+ return event(+ createTaskSettledEvent({+ callId,+ output: "done",+ status: "completed",+ taskId: "task_1",+ turnId: "turn_1",+ }),+ );+}++function parentText(message: string) {+ return event(+ createMessageCompletedEvent({ message, sequence: 4, stepIndex: 1, turnId: "turn_1" }),+ );+}++function observe(events: readonly UnstampedMessageStreamEvent[]): ConversationEvent[] {+ return events.map((childEvent) => ({+ type: "client.agent.observed" as const,+ data: { sessionId: "child_1", event: event(childEvent) },+ }));+}++function childReply(turnId: string, message: string): ConversationEvent[] {+ return observe([+ createTurnStartedEvent({ sequence: 0, turnId }),+ createMessageReceivedEvent({ message: `Question for ${turnId}`, sequence: 0, turnId }),+ createMessageCompletedEvent({ message, sequence: 0, stepIndex: 0, turnId }),+ ]);+}++/** Kind, task or agent name, and the line's detail, for reading placement at a glance. */+function summarize(blocks: readonly Block[]) {+ return blocks.map((block) => [block.kind, block.title ?? block.agentName, block.body]);+}++describe("ConversationTranscript", () => {+ it("keeps streaming prose live until its run completes", () => {+ const transcript = new ConversationTranscript();+ const streaming = conversation([+ turn,+ event(+ createMessageAppendedEvent({+ messageDelta: "Alice's report",+ sequence: 1,+ stepIndex: 0,+ turnId: "turn_1",+ }),+ ),+ ]);+ expect(transcript.project(view(streaming, true), options)).toEqual([+ expect.objectContaining({ kind: "assistant", body: "Alice's report", live: true }),+ ]);++ const completed = conversation(+ [+ event(+ createMessageCompletedEvent({+ message: "Alice's report is ready.",+ sequence: 2,+ stepIndex: 0,+ turnId: "turn_1",+ }),+ ),+ ],+ streaming,+ );+ expect(transcript.project(view(completed, true), options)).toEqual([+ expect.objectContaining({ kind: "assistant", body: "Alice's report is ready.", live: false }),+ ]);+ });++ it("settles a stream that ended without its run completing", () => {+ const state = conversation([+ turn,+ event(+ createMessageAppendedEvent({+ messageDelta: "Partial",+ sequence: 1,+ stepIndex: 0,+ turnId: "turn_1",+ }),+ ),+ toolCall("call_1"),+ ]);+ const blocks = new ConversationTranscript().project(view(state, false), options);+ expect(blocks.map((block) => block.live)).toEqual([false, false]);+ expect(byId(blocks, "tool:call_1")).toMatchObject({ status: "error", result: "interrupted" });+ });++ it("marks a cancelled turn after whatever it streamed", () => {+ const state = conversation([+ turn,+ event(+ createMessageAppendedEvent({+ messageDelta: "Half",+ sequence: 1,+ stepIndex: 0,+ turnId: "turn_1",+ }),+ ),+ event(createTurnCancelledEvent({ sequence: 2, turnId: "turn_1" })),+ ]);+ expect(new ConversationTranscript().project(view(state, false), options)).toEqual([+ expect.objectContaining({ kind: "assistant", body: "Half", live: false }),+ expect.objectContaining({ kind: "notice", body: "Cancelled.", live: false }),+ ]);+ });++ it("holds a parallel tool cohort open until every call settles", () => {+ const transcript = new ConversationTranscript();+ const state = conversation([+ turn,+ toolCall("call_1"),+ toolCall("call_2"),+ toolResult("call_1"),+ ]);+ const blocks = transcript.project(view(state, true), options);+ expect(byId(blocks, "tool:call_1")).toMatchObject({ status: "done", live: true });+ expect(byId(blocks, "tool:call_2")).toMatchObject({ status: "running", live: true });++ const settled = transcript.project(+ view(conversation([toolResult("call_2")], state), true),+ options,+ );+ expect(settled.map((block) => [block.status, block.live])).toEqual([+ ["done", false],+ ["done", false],+ ]);+ });++ it("shows an approval as live until the user's answer, then denied without a result", () => {+ const requested = conversation([+ turn,+ event(+ createInputRequestedEvent({+ requests: [+ {+ action: {+ callId: "call_1",+ input: { path: "notes.md" },+ kind: "tool-call",+ toolName: "write_file",+ },+ kind: "tool-approval",+ prompt: "Approve write_file?",+ requestId: "approval_1",+ },+ ],+ sequence: 1,+ stepIndex: 0,+ turnId: "turn_1",+ }),+ ),+ ]);+ const transcript = new ConversationTranscript();+ expect(byId(transcript.project(view(requested, false), options), "tool:call_1")).toMatchObject({+ status: "approval",+ live: true,+ });++ const denied = conversation(+ [+ {+ type: "client.input.responded",+ data: { createdAt: 0, responses: [{ requestId: "approval_1", optionId: "cancel" }] },+ },+ ],+ requested,+ );+ expect(byId(transcript.project(view(denied, true), options), "tool:call_1")).toMatchObject({+ status: "denied",+ live: false,+ });+ });++ it("settles a finished step's tools while a later step runs", () => {+ const state = conversation([+ turn,+ toolCall("call_1"),+ toolResult("call_1"),+ event(+ createActionsRequestedEvent({+ actions: [+ { callId: "call_2", input: { path: "b.md" }, kind: "tool-call", toolName: "read_file" },+ ],+ sequence: 3,+ stepIndex: 1,+ turnId: "turn_1",+ }),+ ),+ ]);+ const blocks = new ConversationTranscript().project(view(state, true), options);+ expect(byId(blocks, "tool:call_1")).toMatchObject({ status: "done", live: false });+ expect(byId(blocks, "tool:call_2")).toMatchObject({ status: "running", live: true });+ });++ it("writes a task's start line at its call and names the tasks a waiting turn holds on", () => {+ const state = conversation([+ turn,+ toolCall("call_1", "summarize"),+ taskStarted("call_1", "summarize"),+ toolResult("call_1", "summarize"),+ toolCall("wait_1", "task_wait"),+ event(createTurnWaitingEvent({ sequence: 3, turnId: "turn_1" })),+ ]);+ const transcript = new ConversationTranscript();+ const working = view(state, true);+ expect(transcript.project(working, options)).toEqual([+ expect.objectContaining({+ id: "task:call_1:start",+ kind: "task",+ taskKind: "agent",+ title: "summarize",+ live: false,+ }),+ ]);+ expect(turnActivity(working, transcript.tasks)).toBe("Waiting for summarize");+ // A root approval in the same step ends the turn while the task keeps working.+ expect(transcript.project(view(state, false), options)).toHaveLength(1);+ expect(transcript.tasks.map((task) => task.name)).toEqual(["summarize"]);+ });++ it("names the connection a session parked on a sign-in waits for", () => {+ const state = conversation([+ turn,+ event(+ createAuthorizationRequiredEvent({+ attemptId: "attempt_1",+ description: "Sign in to Linear",+ name: "linear",+ sequence: 1,+ stepIndex: 0,+ turnId: "turn_1",+ webhookUrl: "https://example.com/callback",+ }),+ ),+ event(createTurnCompletedEvent({ sequence: 2, turnId: "turn_1" })),+ ]);+ expect(turnActivity(view(state, true), [])).toBe("Waiting for sign-in to Linear");+ });++ it("writes an agent's finished rows and end line where the transcript had reached, after its last events", () => {+ vi.useFakeTimers({ now: 0 });+ onTestFinished(() => void vi.useRealTimers());+ const called = conversation([+ turn,+ toolCall("call_1", "research"),+ taskStarted("call_1", "research"),+ agentStarted("call_1"),+ { type: "client.agent.following", data: { sessionId: "child_1" } },+ ...childReply("child_turn_1", "Bob's notes found."),+ ]);+ const transcript = new ConversationTranscript();+ expect(summarize(transcript.project(view(called, true), options))).toEqual([+ ["task", "research", undefined],+ ["subagent-step", "research", "Bob's notes found."],+ ]);+ expect(transcript.tasks[0]).toMatchObject({ name: "research", step: "Bob's notes found." });++ // The call can settle on the root before the agent's turn ends on its own stream.+ vi.setSystemTime(72_000);+ const reported = conversation([settled("call_1")], called);+ expect(transcript.project(view(reported, true), options)).toHaveLength(2);+ expect(transcript.tasks[0]).toMatchObject({ finishing: true });+ const ended = conversation(+ [+ ...observe([createTurnCompletedEvent({ sequence: 1, turnId: "child_turn_1" })]),+ parentText("Bob found his notes."),+ ],+ reported,+ );+ expect(summarize(transcript.project(view(ended, true), options))).toEqual([+ ["task", "research", undefined],+ ["subagent-step", "research", "Bob's notes found."],+ ["assistant", undefined, "Bob found his notes."],+ ["task", "research", "finished in 1min 12s"],+ ]);+ expect(transcript.tasks).toEqual([]);++ // A later call continuing the task writes its own lines after everything so far.+ const continued = conversation(+ [+ toolCall("call_2", "research"),+ taskStarted("call_2", "research"),+ ...childReply("child_turn_2", "Bob's summary is attached."),+ event(+ createTaskSettledEvent({+ callId: "call_2",+ error: { message: "The agent's session ended." },+ status: "failed",+ taskId: "task_1",+ turnId: "turn_1",+ }),+ ),+ ...observe([+ createTurnFailedEvent({+ code: "MODEL_CALL_FAILED",+ message: "Unavailable.",+ sequence: 1,+ turnId: "child_turn_2",+ }),+ ]),+ ],+ ended,+ );+ expect(summarize(transcript.project(view(continued, true), options)).slice(3)).toEqual([+ ["task", "research", "finished in 1min 12s"],+ ["task", "research", undefined],+ ["subagent-step", "research", "Bob's summary is attached."],+ ["task", "research", "failed · The agent's session ended."],+ ]);+ });++ it("names parallel calls apart, stops tasks a cancelled turn leaves working, and hides hidden ones", () => {+ const state = conversation([+ turn,+ toolCall("call_1", "research"),+ taskStarted("call_1", "research"),+ toolCall("call_2", "research"),+ taskStarted("call_2", "research", "task_2"),+ ]);+ const transcript = new ConversationTranscript();+ transcript.project(view(state, true), options);+ expect(transcript.tasks.map((task) => task.name)).toEqual(["research", "research #2"]);+ // An input request names the task that asked as its lines do.+ expect(transcript.taskLabel(state, "task_2")).toBe("research #2");++ const cancelled = conversation(+ [event(createTurnCancelledEvent({ sequence: 3, turnId: "turn_1" }))],+ state,+ );+ const ends = transcript+ .project(view(cancelled, false), options)+ .filter((block) => block.id?.endsWith(":end"));+ expect(ends.map((block) => [block.title, block.status, block.body])).toEqual([+ ["research", "denied", "stopped"],+ ["research #2", "denied", "stopped"],+ ]);+ expect(transcript.tasks).toEqual([]);++ const hidden = new ConversationTranscript();+ expect(hidden.project(view(state, true), { ...options, subagents: "hidden" })).toEqual([]);+ expect(hidden.tasks).toEqual([]);+ });++ it("hides refused calls, shows authored labels, and holds a placeholder while input streams", () => {+ const events = [+ turn,+ event(+ createActionsRequestedEvent({+ actions: [+ { callId: "call_1", input: { city: "Paris" }, kind: "tool-call", toolName: "weather" },+ ],+ presentation: { call_1: { label: "Checking the weather" } },+ sequence: 1,+ stepIndex: 0,+ turnId: "turn_1",+ }),+ ),+ toolCall("call_2", "research"),+ event(+ createActionResultEvent({+ result: {+ callId: "call_2",+ isError: true,+ kind: "tool-result",+ output: { code: "TOO_MANY_TASKS", message: "Wait for a task to finish." },+ toolName: "research",+ },+ sequence: 2,+ stepIndex: 0,+ turnId: "turn_1",+ }),+ ),+ event(+ createActionInputAppendedEvent({+ callId: "call_3",+ inputTextDelta: "{",+ sequence: 3,+ stepIndex: 1,+ toolName: "read_file",+ turnId: "turn_1",+ }),+ ),+ ];+ const state = conversation(events);+ const data = events.reduce(tuiSessionReducer.reduce, tuiSessionReducer.initial());+ const project = (working: boolean) =>+ new ConversationTranscript()+ .project({ conversation: state, working, data, failures: [] }, options)+ .map((block) => [block.id, block.title]);+ expect(project(true)).toEqual([+ ["tool:call_1", "Checking the weather"],+ ["tool:call_3", "Read …"],+ ]);+ expect(project(false)).toEqual([["tool:call_1", "Checking the weather"]]);+ });++ it("keeps same-name authorization attempts distinct and live until completed", () => {+ const required = (attemptId: string) =>+ event(+ createAuthorizationRequiredEvent({+ attemptId,+ authorization: { url: `https://idp.example.com/${attemptId}` },+ description: "Connect Linear",+ name: "linear",+ sequence: 1,+ stepIndex: 0,+ turnId: "turn_1",+ webhookUrl: "https://agent.example.com/callback",+ }),+ );+ const state = conversation([+ turn,+ required("attempt_1"),+ required("attempt_2"),+ event(+ createAuthorizationCompletedEvent({+ attemptId: "attempt_1",+ name: "linear",+ outcome: "authorized",+ sequence: 2,+ stepIndex: 0,+ turnId: "turn_1",+ }),+ ),+ ]);+ expect(new ConversationTranscript().project(view(state, true), options)).toEqual([+ expect.objectContaining({ title: "linear · authorization · authorized", live: false }),+ expect.objectContaining({ title: "linear · authorization · required", live: true }),+ ]);+ });++ it("keeps an optimistic message's block when the server confirms it", () => {+ const transcript = new ConversationTranscript();+ const optimistic = conversation([+ {+ type: "client.message.submitted",+ data: { createdAt: 0, message: "Summarize Alice's notes.", submissionId: "submission_1" },+ },+ ]);+ const [echo] = transcript.project(view(optimistic, true), options);+ const received = event(+ createMessageReceivedEvent({+ message: "Summarize Alice's notes.",+ sequence: 0,+ turnId: "turn_1",+ }),+ );+ const echoOnly = [expect.objectContaining({ kind: "user", id: echo!.id })];++ // The server's copy can arrive before the store swaps out the optimistic message.+ expect(transcript.project(view(conversation([received], optimistic), true), options)).toEqual(+ echoOnly,+ );+ expect(transcript.project(view(conversation([received]), true), options)).toEqual(echoOnly);+ });++ it("renders each failure once with its hint and a pointer to the full detail", () => {+ const failures = [+ { message: "ModelError: rate limited", hint: "Retry later.", detail: "stack" },+ ];+ const blocks = new ConversationTranscript().project(+ { ...view(initialConversationState(), false), failures },+ { ...options, diagnosticsPath: ".eve/logs/dev.log" },+ );+ expect(blocks).toEqual([+ expect.objectContaining({+ kind: "error",+ body: "ModelError: rate limited",+ hint: "Retry later.",+ detail: "details: .eve/logs/dev.log",+ }),+ ]);+ });++ it("reuses unchanged blocks so the renderer can skip them", () => {+ const transcript = new ConversationTranscript();+ const state = conversation([turn, toolCall("call_1"), toolResult("call_1")]);+ const first = transcript.project(view(state, true), options);+ const again = transcript.project(view({ ...state }, true), options);+ expect(again[0]).toBe(first[0]);+ });+});diff --git a/packages/eve/src/cli/dev/tui/transcript.ts b/packages/eve/src/cli/dev/tui/transcript.tsnew file mode 100644index 000000000..e392ae09b--- /dev/null+++ b/packages/eve/src/cli/dev/tui/transcript.ts@@ -0,0 +1,657 @@+import {+ agentCallTurns,+ agentToolSession,+ conversationAuthorizations,+ isAgentCallContentPending,+ type ConversationState,+ type ConversationTask,+ type ConversationTaskCall,+} from "#client/conversation-state.js";+import type {+ EveAuthorizationPart,+ EveDynamicToolPart,+ EveMessage,+} from "#client/message-reducer-types.js";+import { authorizationKey } from "#client/session-utils.js";+import { stripTerminalControls } from "#cli/ui/terminal-text.js";+import { isTaskControlTool } from "#protocol/task-tools.js";+import type { Block } from "./blocks.js";+import type { AgentTUIConversationView, AgentTUIFailure, ToolLabels } from "./conversation-view.js";+import { FileContentCache } from "./file-content-cache.js";+import { signInLabel, waitingLabel, type TaskEntry } from "./task-activity.js";+import { isTerminalToolCallPart } from "./terminal-tool-part.js";+import {+ agentDisplayName,+ isPanelRoutedTool,+ presentTool,+ readWriteFileInput,+ toolBaseName,+ type ToolPresentationContext,+} from "./tool-presentation.js";+import {+ activeToolSteps,+ agentTaskSummary,+ authorizationTerminalMessage,+ childToolCallIds,+ endLine,+ firstLine,+ formatAuthorization,+ isActive,+ isToolCallRow,+ labelContext,+ subagentSteps,+ taskCallsById,+ toolBlock,+ toolState,+ userText,+ writeExistedFlag,+ type TaskRecord,+ type ToolState,+} from "./transcript-parts.js";+import type { SubagentDisplayMode, TerminalPartDisplayMode } from "./types.js";++export interface TranscriptOptions {+ readonly tools: TerminalPartDisplayMode;+ readonly reasoning: TerminalPartDisplayMode;+ readonly subagents: SubagentDisplayMode;+ readonly connectionAuth: TerminalPartDisplayMode;+ /** Names of the agent's local subagents, whose tools read as delegations. */+ readonly subagentNames?: readonly string[];+ /** Where full failure detail is recorded, shown instead of the raw dump. */+ readonly diagnosticsPath?: string;+ /** Separates a task end line's facts; the theme's `·`. */+ readonly dot?: string;+}++/**+ * A block written when it first appeared rather than where its part sits: a task's end line, or+ * an agent's own finished row. It stays after the blocks that preceded it then, as `main`'s+ * append-only transcript would have written it.+ */+interface PlacedBlock {+ readonly block: Block;+ /** The blocks it followed, newest last; the newest still projected anchors it. */+ readonly after: readonly string[];+}++/** How long a settled agent task waits for its own last events before writing its end line. */+export const TASK_END_GRACE_MS = 2_000;++const PLACEMENT_ANCHORS = 8;++/**+ * Projects one session's conversation into transcript blocks. Each block's+ * `live` flag says whether its part can still change; the renderer commits a+ * settled prefix to scrollback. Built blocks are reused while their inputs are+ * unchanged, so file-diff bases observe each tool call once, in order.+ *+ * A task writes one line when it starts, at its call, and one when it ends, where the transcript+ * had reached by then; what it does in between is {@link ConversationTranscript.tasks}, which the+ * renderer shows in the task panel above the prompt.+ */+export class ConversationTranscript {+ #memo = new Map<string, { readonly key: readonly unknown[]; readonly block: Block }>();+ readonly #fileContents = new FileContentCache();+ /** Server user messages that confirmed an optimistic message keep its block. */+ readonly #aliases = new Map<string, string>();+ #optimistic = new Map<string, string>();+ readonly #confirmed = new Set<string>();+ readonly #tasks = new Map<string, TaskRecord>();+ #placed: PlacedBlock[] = [];+ readonly #placedIds = new Set<string>();+ #working: readonly TaskEntry[] = [];++ reset(): void {+ this.#memo = new Map();+ this.#fileContents.clear();+ this.#aliases.clear();+ this.#optimistic = new Map();+ this.#confirmed.clear();+ this.#tasks.clear();+ this.#placed = [];+ this.#placedIds.clear();+ this.#working = [];+ }++ /** The tasks between their start and end lines as of the last projection, in start order. */+ get tasks(): readonly TaskEntry[] {+ return this.#working;+ }++ /** Whether a settled agent task is waiting for its own last events. */+ get finishing(): boolean {+ return this.#working.some((entry) => entry.finishing === true);+ }++ /** How input requests name the task that asked: as its task lines do. */+ taskLabel(conversation: ConversationState, taskId: string): string | undefined {+ const task = conversation.tasks[taskId];+ if (task === undefined) return undefined;+ const calls = Object.values(task.calls);+ const call = calls.findLast((candidate) => candidate.status === "working") ?? calls.at(-1);+ const record = call === undefined ? undefined : this.#tasks.get(call.callId);+ if (record !== undefined) return record.name;+ return task.kind === "agent"+ ? agentDisplayName(stripTerminalControls(task.name))+ : stripTerminalControls(task.name);+ }++ /** End lines for the tasks still working when their session ends; they read as stopped. */+ stopWorking(options: TranscriptOptions): Block[] {+ const lines: Block[] = [];+ for (const record of this.#tasks.values()) {+ if (record.ended) continue;+ record.ended = true;+ lines.push(endLine(record, { status: "cancelled" }, undefined, options.dot ?? "·"));+ }+ this.#working = [];+ return lines;+ }++ project(view: AgentTUIConversationView, options: TranscriptOptions): Block[] {+ const { conversation, working } = view;+ const now = Date.now();+ const blocks: Block[] = [];+ this.#aliasConfirmedMessages(conversation.messages);+ const childToolIds = childToolCallIds(conversation);+ const taskCalls = taskCallsById(conversation);+ const withdrawn = new Set(view.data.withdrawnCallIds);+ const labels = view.data.toolLabels;++ for (const message of conversation.messages) {+ if (message.role === "user") {+ const block = this.#userBlock(message);+ if (block !== undefined) blocks.push(block);+ continue;+ }+ const tools = message.parts.filter(+ (part): part is EveDynamicToolPart =>+ isToolCallRow(part) &&+ // A call still streaming its input shows a placeholder only while the turn runs.+ (part.state !== "input-streaming" || working) &&+ !isTaskControlTool(part.toolName) &&+ !withdrawn.has(part.toolCallId) &&+ part.toolMetadata?.eve?.inputRequest?.kind !== "session-limit" &&+ !taskCalls.has(part.toolCallId) &&+ !childToolIds.has(part.toolCallId) &&+ !isPanelRoutedTool(part.toolName),+ );+ const states = new Map(+ tools.map((part) => [part, toolState(part, conversation, working, false)]),+ );+ const activeSteps = activeToolSteps(states);++ for (const [index, part] of message.parts.entries()) {+ if (part.type === "text" || part.type === "reasoning") {+ const block = this.#contentBlock(message, index, options, working);+ if (block !== undefined) blocks.push(block);+ } else if (part.type === "authorization") {+ if (options.connectionAuth !== "hidden") blocks.push(this.#authorizationBlock(part));+ } else if (part.type === "dynamic-tool") {+ const taskCall = taskCalls.get(part.toolCallId);+ if (taskCall !== undefined) {+ const start = this.#taskStartLine(part, taskCall.task, labels, options, now);+ if (start !== undefined) blocks.push(start);+ continue;+ }+ const state = states.get(part);+ if (state === undefined || options.tools === "hidden") continue;+ const toolLabels = labels[part.toolCallId];+ blocks.push(+ this.#toolBlock(part, state, activeSteps.has(part.stepIndex), toolLabels, options),+ );+ }+ }+ const turnId = message.metadata?.turnId;+ if (turnId !== undefined && conversation.turns[turnId]?.status === "cancelled") {+ blocks.push(+ this.#memoize(`cancelled:${turnId}`, [], () => ({+ kind: "notice",+ body: "Cancelled.",+ live: false,+ })),+ );+ }+ }+ for (const [index, failure] of view.failures.entries()) {+ blocks.push(this.#failureBlock(index, failure, options));+ }++ const placed = this.#placeBlocks(blocks);+ const arrivals = this.#taskActivity(view, taskCalls, options, now);+ for (const block of arrivals) {+ const after = placed.slice(-PLACEMENT_ANCHORS).map((candidate) => candidate.id!);+ this.#placed.push({ block, after });+ this.#placedIds.add(block.id!);+ placed.push(block);+ }+ return placed;+ }++ /** Interleaves placed blocks after the blocks they first followed. */+ #placeBlocks(blocks: readonly Block[]): Block[] {+ const placed = [...blocks];+ for (const { block, after } of this.#placed) {+ let index = placed.length;+ for (let anchor = after.length - 1; anchor >= 0; anchor -= 1) {+ const found = placed.findIndex((candidate) => candidate.id === after[anchor]);+ if (found !== -1) {+ index = found + 1;+ break;+ }+ }+ placed.splice(index, 0, block);+ }+ return placed;+ }++ /** A call became a task: its row is now the task's start line, written once. */+ #taskStartLine(+ part: EveDynamicToolPart,+ task: ConversationTask,+ labels: Readonly<Record<string, ToolLabels>>,+ options: TranscriptOptions,+ now: number,+ ): Block | undefined {+ const visible =+ task.kind === "agent" ? options.subagents !== "hidden" : options.tools !== "hidden";+ if (!visible) return undefined;+ const callId = part.toolCallId;+ const label = labels[callId]?.start;+ let record = this.#tasks.get(callId);+ let summary = agentTaskSummary(part.input);+ let baseName = agentDisplayName(stripTerminalControls(part.toolName));+ if (task.kind === "tool") {+ const presentation = presentTool(part.toolName, part.input, labelContext(label));+ baseName = stripTerminalControls(presentation.title);+ summary = stripTerminalControls(presentation.subtitle);+ }+ if (record === undefined) {+ record = {+ callId,+ kind: task.kind,+ name: this.#uniqueName(baseName),+ toolName: part.toolName,+ input: part.input,+ label,+ startedAtMs: now,+ ended: false,+ };+ this.#tasks.set(callId, record);+ }+ const { name } = record;+ return this.#memoize(`task:${callId}:start`, [name, summary, task.kind], () => ({+ kind: "task",+ taskKind: task.kind,+ title: name,+ subtitle: summary,+ live: false,+ }));+ }++ /** Parallel calls to one agent read `researcher`, `researcher #2`, …; a name is never renamed. */+ #uniqueName(baseName: string): string {+ const taken = new Set(+ [...this.#tasks.values()].filter((record) => !record.ended).map((record) => record.name),+ );+ if (!taken.has(baseName)) return baseName;+ for (let ordinal = 2; ; ordinal += 1) {+ const candidate = `${baseName} #${String(ordinal)}`;+ if (!taken.has(candidate)) return candidate;+ }+ }++ /**+ * Updates the working tasks and returns the blocks that appeared since the last projection:+ * `--subagents full` rows as an agent finishes each, and end lines as tasks end.+ */+ #taskActivity(+ view: AgentTUIConversationView,+ taskCalls: ReadonlyMap<string, { task: ConversationTask; call: ConversationTaskCall }>,+ options: TranscriptOptions,+ now: number,+ ): Block[] {+ const { conversation, working } = view;+ const lastTurn = Object.values(conversation.turns).at(-1);+ // A cancelled or failed turn gets no end for the tasks still working; they read as stopped.+ const stopping =+ !working &&+ (view.data.sessionFailed ||+ lastTurn?.status === "cancelled" ||+ lastTurn?.status === "failed");+ const arrivals: Block[] = [];+ const entries: TaskEntry[] = [];+ for (const record of this.#tasks.values()) {+ if (record.ended) continue;+ const taskCall = taskCalls.get(record.callId);+ if (taskCall === undefined) continue;+ const { task, call } = taskCall;+ const activity = this.#agentActivity(record, task, call, conversation, options);+ if (options.subagents === "full") {+ for (const row of activity.rows) {+ if (!this.#placedIds.has(row.id!)) arrivals.push(row);+ }+ }+ const settled = call.status !== "working";+ if (settled) record.settledAtMs ??= now;+ const finishing =+ settled &&+ activity.pending &&+ working &&+ now - (record.settledAtMs ?? now) < TASK_END_GRACE_MS;+ if ((settled && !finishing) || (!settled && stopping)) {+ record.ended = true;+ arrivals.push(+ endLine(+ record,+ settled ? call : { status: "cancelled" },+ activity.tools,+ options.dot ?? "·",+ ),+ );+ continue;+ }+ const entry: TaskEntry = {+ callId: record.callId,+ kind: record.kind,+ name: record.name,+ toolName: record.toolName,+ input: record.input,+ label: record.label,+ startedAtMs: record.startedAtMs,+ childTools: new Map(activity.tools.map((block) => [block.id!, block])),+ };+ if (activity.step !== undefined) entry.step = activity.step;+ if (finishing) entry.finishing = true;+ entries.push(entry);+ }+ this.#working = entries;+ return arrivals;+ }++ /** What an agent task has done for this call: its tool calls, latest words, and finished rows. */+ #agentActivity(+ record: TaskRecord,+ task: ConversationTask,+ call: ConversationTaskCall,+ conversation: ConversationState,+ options: TranscriptOptions,+ ): { tools: Block[]; rows: Block[]; step?: string; pending: boolean } {+ const agent = task.kind === "agent" ? agentToolSession(conversation, task) : undefined;+ const child =+ agent === undefined || agent.observation.status === "not-followed"+ ? undefined+ : agent.observation.conversation;+ if (agent === undefined || child === undefined) return { tools: [], rows: [], pending: false };+ const pending =+ agent.observation.status === "following" && isAgentCallContentPending(task, call, child);+ const turnIds = new Set(agentCallTurns(task, child).get(call.callId) ?? []);+ const messages = child.messages.filter(+ (message) =>+ message.role === "assistant" &&+ message.metadata?.turnId !== undefined &&+ turnIds.has(message.metadata.turnId),+ );+ const running = call.status === "working" || pending;+ const childTasks = taskCallsById(child);+ const ordered: Array<{ order: number; block: Block; settled: boolean }> = [];+ const tools: Block[] = [];+ let order = 0;+ for (const message of messages) {+ for (const part of message.parts) {+ order += 1;+ if (!isToolCallRow(part) || isTaskControlTool(part.toolName)) continue;+ const childTask = childTasks.get(part.toolCallId);+ const state = toolState(part, child, running, childTask?.call.status === "working");+ const id = `subagent:${record.callId}:tool:${part.toolCallId}`;+ const block = this.#memoize(id, [part, state.status, record.name], () => {+ const context = this.#presentationContext(part.toolCallId, part, state, options, {+ isSubagent: childTask?.task.kind === "agent",+ });+ return {+ ...toolBlock(part, state, context),+ kind: "subagent-tool",+ subagentCallId: record.callId,+ agentName: record.name,+ depth: 1,+ live: false,+ };+ });+ tools.push(block);+ ordered.push({ order, block, settled: !isActive(state.status) });+ }+ }+ const steps = subagentSteps(messages);+ for (const step of steps) {+ if (!step.finalized) continue;+ const id = `subagent:${record.callId}:step:${step.key}`;+ const block = this.#memoize(id, [step.reasoning, step.message, record.name], () => {+ const row: Block = {+ kind: "subagent-step",+ subagentCallId: record.callId,+ agentName: record.name,+ depth: 1,+ body: step.message,+ live: false,+ };+ if (step.reasoning.length > 0) row.reasoning = step.reasoning;+ return row;+ });+ ordered.push({ order: step.order, block, settled: true });+ }+ const rows = ordered+ .filter((row) => row.settled)+ .sort((left, right) => left.order - right.order)+ .map((row) => row.block);+ const latest = steps.at(-1);+ const result: { tools: Block[]; rows: Block[]; step?: string; pending: boolean } = {+ tools,+ rows,+ pending,+ };+ if (latest !== undefined) result.step = firstLine(latest.message) ?? "Thinking";+ return result;+ }++ #memoize(id: string, key: readonly unknown[], build: () => Block): Block {+ const cached = this.#memo.get(id);+ if (cached !== undefined && sameKey(cached.key, key)) return cached.block;+ const block = { ...build(), id };+ this.#memo.set(id, { key, block });+ return block;+ }++ #aliasConfirmedMessages(messages: readonly EveMessage[]): void {+ const optimistic = new Map<string, string>();+ for (const message of messages) {+ if (message.role === "user" && message.metadata?.optimistic === true) {+ optimistic.set(message.id, userText(message));+ }+ }+ const vanished = [...this.#optimistic].filter(([id]) => !optimistic.has(id));+ const pendingTexts = new Set(optimistic.values());+ for (const message of messages) {+ if (message.role !== "user" || message.metadata?.optimistic === true) continue;+ if (this.#confirmed.has(message.id)) continue;+ const text = userText(message);+ const match = vanished.findIndex(([, candidate]) => candidate === text);+ // An early server echo can share a snapshot with its optimistic twin; wait for the swap.+ if (match === -1 && pendingTexts.has(text)) continue;+ this.#confirmed.add(message.id);+ if (match === -1) continue;+ this.#aliases.set(message.id, vanished[match]![0]);+ vanished.splice(match, 1);+ }+ this.#optimistic = optimistic;+ }++ #userBlock(message: EveMessage): Block | undefined {+ // A server copy waiting on its optimistic twin's swap would otherwise print twice.+ if (message.metadata?.optimistic !== true && !this.#confirmed.has(message.id)) return undefined;+ const body = stripTerminalControls(userText(message));+ if (body.trim().length === 0) return undefined;+ const id = `user:${this.#aliases.get(message.id) ?? message.id}`;+ return this.#memoize(id, [body], () => ({ kind: "user", body, live: false }));+ }++ #contentBlock(+ message: EveMessage,+ index: number,+ options: TranscriptOptions,+ working: boolean,+ ): Block | undefined {+ const part = message.parts[index];+ if (part?.type !== "text" && part?.type !== "reasoning") return undefined;+ if (part.type === "reasoning" && options.reasoning !== "full") return undefined;+ const body = stripTerminalControls(part.text).trim();+ if (body.length === 0) return undefined;+ const live = part.state === "streaming" && working;+ const id = `${part.type}:${part.id ?? `${message.id}:${index}`}`;+ return this.#memoize(id, [body, live], () =>+ part.type === "text"+ ? { kind: "assistant", body, live }+ : { kind: "reasoning", body, collapsed: false, live },+ );+ }++ #authorizationBlock(part: EveAuthorizationPart): Block {+ return this.#memoize(`connection-auth:${authorizationKey(part)}`, [part], () => {+ const state = part.state === "completed" ? part.outcome : part.state;+ const terminalMessage = authorizationTerminalMessage(state);+ return {+ kind: "connection-auth",+ title: `${stripTerminalControls(part.name)} · authorization · ${state}`,+ body: formatAuthorization(part, terminalMessage),+ preformatted: true,+ live: terminalMessage === undefined,+ };+ });+ }++ #toolBlock(+ part: EveDynamicToolPart,+ state: ToolState,+ cohortActive: boolean,+ labels: ToolLabels | undefined,+ options: TranscriptOptions,+ ): Block {+ const live = cohortActive || isActive(state.status);+ return this.#memoize(+ `tool:${part.toolCallId}`,+ [part, state.status, live, options.tools, options.subagentNames, labels],+ () => {+ const context = this.#presentationContext(part.toolCallId, part, state, options, {+ label: labels?.start,+ completeLabel: labels?.complete,+ });+ return {+ ...toolBlock(part, state, context),+ kind: "tool",+ live,+ expanded: options.tools === "full",+ };+ },+ );+ }++ #failureBlock(index: number, failure: AgentTUIFailure, options: TranscriptOptions): Block {+ const { message, hint, detail } = failure;+ return this.#memoize(`failure:${index}`, [message, hint, detail], () => {+ const block: Block = {+ kind: "error",+ title: "Error",+ body: stripTerminalControls(message),+ live: false,+ };+ if (hint !== undefined) block.hint = stripTerminalControls(hint);+ if (detail !== undefined) {+ block.detail =+ options.diagnosticsPath === undefined+ ? stripTerminalControls(detail)+ : `details: ${options.diagnosticsPath}`;+ }+ return block;+ });+ }++ /** Feeds the file-content cache and derives the context a write needs for its diff. */+ #presentationContext(+ callId: string,+ part: EveDynamicToolPart,+ state: ToolState,+ options: TranscriptOptions,+ extra: {+ readonly isSubagent?: boolean;+ readonly label?: string | undefined;+ readonly completeLabel?: string | undefined;+ } = {},+ ): ToolPresentationContext | undefined {+ if (state.output !== undefined) this.#fileContents.observeRead(state.output);+ const context: {+ previousContent?: string;+ existed?: boolean;+ isSubagent?: boolean;+ label?: string;+ completeLabel?: string;+ } = {};+ if (+ extra.isSubagent === true ||+ options.subagentNames?.includes(toolBaseName(part.toolName)) === true+ ) {+ context.isSubagent = true;+ }+ if (extra.label !== undefined) context.label = extra.label;+ if (extra.completeLabel !== undefined) context.completeLabel = extra.completeLabel;+ const write = readWriteFileInput(part.toolName, part.input);+ if (write !== undefined) {+ const previous = this.#fileContents.observeWrite({ ...write, callId });+ if (previous !== undefined) context.previousContent = previous;+ const existed = writeExistedFlag(state.output);+ if (existed !== undefined) context.existed = existed;+ }+ return Object.keys(context).length > 0 ? context : undefined;+ }+}++/**+ * Running tools and the live turn's model activity, for the turn bar. A session parked on a+ * sign-in names its connections, and a turn parked on its tasks names them.+ */+export function turnActivity(view: AgentTUIConversationView, tasks: readonly TaskEntry[]): string {+ const { conversation } = view;+ const turn =+ conversation.activeTurnId === undefined+ ? undefined+ : conversation.turns[conversation.activeTurnId];+ const message = view.conversation.messages.findLast(+ (candidate) => candidate.role === "assistant",+ );+ const taskCalls = taskCallsById(conversation);+ if (+ message?.parts.some(+ (part) =>+ isTerminalToolCallPart(part) &&+ !isTaskControlTool(part.toolName) &&+ !taskCalls.has(part.toolCallId) &&+ (part.state === "input-available" || part.state === "approval-responded"),+ ) === true+ )+ return "Running";+ if (turn === undefined || turn.waiting === true) {+ const signIns = conversationAuthorizations(conversation).filter(+ (part) => part.state === "required" && part.awaitsCallback === true,+ );+ if (signIns.length > 0) return signInLabel(signIns.map((part) => part.displayName));+ }+ if (turn?.waiting === true && tasks.length > 0) return waitingLabel(tasks);+ if (message === undefined) return "Thinking";+ const last = message.parts.findLast((part) => part.type !== "step-start");+ return (last?.type === "text" && last.state === "streaming") ||+ (last?.type === "dynamic-tool" && last.state === "input-streaming")+ ? "Generating"+ : "Thinking";+}++function sameKey(left: readonly unknown[], right: readonly unknown[]): boolean {+ return left.length === right.length && left.every((value, index) => value === right[index]);+}diff --git a/packages/eve/src/cli/dev/tui/tui.test.ts b/packages/eve/src/cli/dev/tui/tui.test.tsindex 95df9698d..87d3bab38 100644--- a/packages/eve/src/cli/dev/tui/tui.test.ts+++ b/packages/eve/src/cli/dev/tui/tui.test.ts@@ -39,8 +39,6 @@ describe("runDevelopmentTui", () => {throw new Error("Expected two TUI runner invocations.");}expect(first.client).not.toBe(second.client);- expect(first.session).toBeUndefined();- expect(second.session).toBeUndefined();});it("offers default but no incompatible effort for toggle-only models", async () => {diff --git a/packages/eve/src/cli/dev/tui/turn-clock.ts b/packages/eve/src/cli/dev/tui/turn-clock.tsindex e7cccb558..22593078e 100644--- a/packages/eve/src/cli/dev/tui/turn-clock.ts+++ b/packages/eve/src/cli/dev/tui/turn-clock.ts@@ -1,19 +1,18 @@+import type { TokenUsage } from "./conversation-view.js";+/**- * One turn's wall clock and summed token flow. "When did this turn start"- * is a single fact; this object is its single representation — armed once- * per turn (a prompt submit, or an `--input` turn arming itself), fed by- * step usage reports, and consumed exactly once by the end-of-turn coda.- * Multi-pass turns (question answers, connection authorizations) re-stream- * without re-arming, so one turn gets one coda.+ * One turn's wall clock and token flow, measured against the session's summed+ * step usage when work started. Armed when work starts and consumed once by+ * the end-of-turn coda, so answering an approval or question mid-turn does+ * not split the turn.*/export class TurnClock {#startedAtMs?: number;- #usage = { inputTokens: 0, outputTokens: 0 };+ #baseline: TokenUsage = { inputTokens: 0, outputTokens: 0 };- /** Starts the turn: resets the summed flow and stamps the clock. */- arm(): void {+ arm(usage: TokenUsage): void {this.#startedAtMs = Date.now();- this.#usage = { inputTokens: 0, outputTokens: 0 };+ this.#baseline = usage;}get armed(): boolean {@@ -24,31 +23,25 @@ export class TurnClock {return this.#startedAtMs;}- get usage(): { readonly inputTokens: number; readonly outputTokens: number } {- return this.#usage;- }-- addUsage(usage: { inputTokens?: number; outputTokens?: number }): void {- this.#usage.inputTokens += usage.inputTokens ?? 0;- this.#usage.outputTokens += usage.outputTokens ?? 0;+ /** Token flow since the clock was armed. */+ usage(current: TokenUsage): TokenUsage {+ return {+ inputTokens: Math.max(0, current.inputTokens - this.#baseline.inputTokens),+ outputTokens: Math.max(0, current.outputTokens - this.#baseline.outputTokens),+ };}- /**- * Consumes the armed clock, returning the turn's elapsed time and summed- * flow — or `undefined` when no turn was armed (the coda's "already- * settled" signal). The flow survives the settle so a repaint between the- * coda and the next arm still reads the last turn's numbers.- */- settle(): { elapsedMs: number; inputTokens: number; outputTokens: number } | undefined {+ /** Consumes the armed clock, or returns `undefined` when no turn was armed. */+ settle(current: TokenUsage): ({ elapsedMs: number } & TokenUsage) | undefined {const startedAtMs = this.#startedAtMs;if (startedAtMs === undefined) return undefined;this.#startedAtMs = undefined;- return { elapsedMs: Date.now() - startedAtMs, ...this.#usage };+ return { elapsedMs: Date.now() - startedAtMs, ...this.usage(current) };}/** Drops the clock without a coda (conversation boundaries). */reset(): void {this.#startedAtMs = undefined;- this.#usage = { inputTokens: 0, outputTokens: 0 };+ this.#baseline = { inputTokens: 0, outputTokens: 0 };}}diff --git a/packages/eve/src/client/agent-stream-follower.test.ts b/packages/eve/src/client/agent-stream-follower.test.tsnew file mode 100644index 000000000..38c267970--- /dev/null+++ b/packages/eve/src/client/agent-stream-follower.test.ts@@ -0,0 +1,218 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { Client, type MessageStreamEvent } from "#client/index.js";+import { AgentStreamFollower } from "#client/agent-stream-follower.js";+import {+ conversationReducer,+ reduceConversation,+ type ConversationEvent,+} from "#client/conversation-reducer.js";+import type { ConversationState } from "#client/conversation-state.js";+import { stampTestEvent } from "#internal/testing/events.js";+import {+ createAgentStartedEvent,+ createMessageCompletedEvent,+ createMessageReceivedEvent,+ createTaskSettledEvent,+ createTaskStartedEvent,+ createTurnCompletedEvent,+ createTurnStartedEvent,+ EVE_MESSAGE_STREAM_VERSION,+ EVE_STREAM_VERSION_HEADER,+ type UnstampedMessageStreamEvent,+} from "#protocol/message.js";++afterEach(() => {+ vi.restoreAllMocks();+});++let stamped = 0;+const stamp = (event: UnstampedMessageStreamEvent) => stampTestEvent(event, stamped++);++/** One reply turn, as a researcher session produces it for a call's message. */+function reply(turnId: string, message: string): MessageStreamEvent[] {+ return [+ createTurnStartedEvent({ sequence: 0, turnId }),+ createMessageReceivedEvent({ message: `Question for ${turnId}`, sequence: 0, turnId }),+ createMessageCompletedEvent({+ finishReason: "stop",+ message,+ sequence: 0,+ stepIndex: 0,+ turnId,+ }),+ createTurnCompletedEvent({ sequence: 0, turnId }),+ ].map(stamp);+}++/** Serves the child's stream from each request's cursor, holding it open until aborted. */+function serveChild(events: MessageStreamEvent[]) {+ const requests: { path: string; cursor: number; signal?: AbortSignal }[] = [];+ const openStreams = new Set<ReadableStreamDefaultController<Uint8Array>>();+ let delivered = 0;+ const encode = (event: MessageStreamEvent) =>+ new TextEncoder().encode(`${JSON.stringify(event)}\n`);+ vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => {+ const url = new URL(String(input));+ const cursor = Number(url.searchParams.get("startIndex") ?? "0");+ const signal = init?.signal ?? undefined;+ requests.push({ path: url.pathname, cursor, signal });+ const body = new ReadableStream<Uint8Array>({+ start(controller) {+ for (const event of events.slice(cursor, delivered)) controller.enqueue(encode(event));+ openStreams.add(controller);+ signal?.addEventListener(+ "abort",+ () => {+ openStreams.delete(controller);+ controller.error(signal.reason);+ },+ { once: true },+ );+ },+ });+ return new Response(body, {+ headers: { [EVE_STREAM_VERSION_HEADER]: EVE_MESSAGE_STREAM_VERSION },+ });+ });+ return {+ requests,+ /** Makes the child's next events durable and pushes them to open subscribers. */+ deliver(count = events.length - delivered) {+ const next = events.slice(delivered, delivered + count);+ delivered += next.length;+ for (const controller of openStreams)+ for (const event of next) controller.enqueue(encode(event));+ },+ };+}++function setup() {+ let state: ConversationState = conversationReducer.initial();+ const apply = (event: ConversationEvent) => {+ state = reduceConversation(state, event);+ };+ const follower = new AgentStreamFollower({+ session: new Client({ host: "http://localhost:3000" }).sessions.attach("root"),+ cursors: new Map(),+ getState: () => state,+ onFollowing: (sessionId) => apply({ type: "client.agent.following", data: { sessionId } }),+ onEvent: (sessionId, event) =>+ apply({ type: "client.agent.observed", data: { sessionId, event } }),+ onIdle: (sessionId) => apply({ type: "client.agent.idle", data: { sessionId } }),+ onUnavailable: (sessionId) => apply({ type: "client.agent.unavailable", data: { sessionId } }),+ });+ return {+ get state() {+ return state;+ },+ /** Admits a root event the way the conversation client does. */+ root(event: UnstampedMessageStreamEvent) {+ const accepted = stamp(event);+ apply(accepted);+ follower.acceptParentEvent(accepted);+ follower.reconcile();+ },+ follower,+ };+}++const call = (callId: string, kind: "agent" | "tool" = "agent") =>+ createTaskStartedEvent({+ callId,+ kind,+ name: kind === "agent" ? "researcher" : "triage",+ taskId: "task_1",+ turnId: "root-turn",+ });+const settle = (callId: string) =>+ createTaskSettledEvent({+ callId,+ output: "done",+ status: "completed",+ taskId: "task_1",+ turnId: "root-turn",+ });+const agentStarted = () =>+ createAgentStartedEvent({+ callId: "call_a",+ name: "researcher",+ parentSessionId: "root",+ sessionId: "child",+ taskId: "task_1",+ turnId: "root-turn",+ });+const replyText = (state: ConversationState) => {+ const observation = state.agents.child?.observation;+ return observation === undefined || observation.status === "not-followed"+ ? []+ : (observation.conversation?.messages ?? []).flatMap((message) =>+ message.role === "assistant"+ ? message.parts.flatMap((part) => (part.type === "text" ? [part.text] : []))+ : [],+ );+};++describe("agent session following", () => {+ it("follows an agent tool's session until its settled calls' replies arrive", async () => {+ const child = serveChild(reply("t1", "Alice's incidents are in the report."));+ const owner = setup();+ owner.root(call("call_a"));+ owner.root(agentStarted());+ await vi.waitFor(() => expect(child.requests).toHaveLength(1));+ // The root settles the call before the child's reply reaches this subscriber.+ owner.root(settle("call_a"));+ expect(owner.state.agents.child?.observation.status).toBe("following");+ child.deliver();+ await vi.waitFor(() => expect(owner.state.agents.child?.observation.status).toBe("idle"));+ expect(replyText(owner.state)).toEqual(["Alice's incidents are in the report."]);+ expect(child.requests[0]).toMatchObject({ path: "/eve/v1/session/child/stream", cursor: 0 });+ expect(child.requests[0]?.signal?.aborted).toBe(true);+ });++ it("resumes from its cursor when a later call reaches the task", async () => {+ const child = serveChild([+ ...reply("t1", "Alice's incidents are in the report."),+ ...reply("t2", "Bob's summary is attached."),+ ]);+ const owner = setup();+ owner.root(call("call_a"));+ owner.root(agentStarted());+ child.deliver(4);+ owner.root(settle("call_a"));+ await vi.waitFor(() => expect(owner.state.agents.child?.observation.status).toBe("idle"));+ owner.root(call("call_b"));+ await vi.waitFor(() => expect(child.requests).toHaveLength(2));+ owner.root(settle("call_b"));+ child.deliver();+ await vi.waitFor(() => expect(owner.state.agents.child?.observation.status).toBe("idle"));+ expect(child.requests.map((request) => request.cursor)).toEqual([0, 4]);+ expect(replyText(owner.state)).toEqual([+ "Alice's incidents are in the report.",+ "Bob's summary is attached.",+ ]);+ });++ it("leaves sessions other tools open to the caller", () => {+ const child = serveChild([]);+ const owner = setup();+ owner.root(call("call_a", "tool"));+ owner.root(agentStarted());+ expect(child.requests).toHaveLength(0);+ expect(owner.state.agents.child?.observation.status).toBe("not-followed");+ });++ it("reports a failed stream without retrying it or attributing it to the agent", async () => {+ const fetch = vi+ .spyOn(globalThis, "fetch")+ .mockResolvedValue(new Response("forbidden", { status: 403 }));+ const owner = setup();+ owner.root(call("call_a"));+ owner.root(agentStarted());+ await vi.waitFor(() =>+ expect(owner.state.agents.child?.observation.status).toBe("unavailable"),+ );+ owner.root(call("call_b"));+ expect(fetch).toHaveBeenCalledTimes(1);+ expect(owner.state.tasks.task_1?.calls.call_a?.status).toBe("working");+ });+});diff --git a/packages/eve/src/client/agent-stream-follower.ts b/packages/eve/src/client/agent-stream-follower.tsnew file mode 100644index 000000000..a89e1b01e--- /dev/null+++ b/packages/eve/src/client/agent-stream-follower.ts@@ -0,0 +1,104 @@+import {+ agentToolTask,+ isAgentSessionCaughtUp,+ type ConversationState,+} from "#client/conversation-state.js";+import type { ClientSession } from "#client/session.js";+import type { StreamReconnectPolicy } from "#client/types.js";+import type { AgentStartedStreamEvent, MessageStreamEvent } from "#protocol/message.js";++/**+ * A followed session can stay silent while a person answers its question, and the dev server can+ * restart underneath it, so only an abort or a non-retryable failure ends a subscription.+ */+const agentStreamReconnectPolicy = {+ streamIdleReconnectPolicy: { maxAttempts: Infinity },+ streamOpenReconnectPolicy: { maxAttempts: Infinity },+} as const satisfies StreamReconnectPolicy;++export interface AgentStreamFollowerOptions {+ /** The session whose stream announced the agents; reads use its host and credentials. */+ readonly session: ClientSession;+ readonly getState: () => ConversationState;+ readonly onFollowing: (sessionId: string) => void;+ readonly onEvent: (sessionId: string, event: MessageStreamEvent) => void;+ readonly onIdle: (sessionId: string) => void;+ readonly onUnavailable: (sessionId: string) => void;+ /** Retained by the transport owner across detach and reattach. */+ readonly cursors: Map<string, number>;+}++/**+ * Follows each agent tool's session while its task has content the conversation has not shown.+ * The conversation decides when a session is caught up; this class only owns transport.+ */+export class AgentStreamFollower {+ readonly #options: AgentStreamFollowerOptions;+ readonly #started = new Map<string, AgentStartedStreamEvent>();+ readonly #controllers = new Map<string, AbortController>();+ /** Sessions whose stream failed stay unavailable until the owner follows again. */+ readonly #failed = new Set<string>();+ #disposed = false;++ constructor(options: AgentStreamFollowerOptions) {+ this.#options = options;+ }++ acceptParentEvent(event: MessageStreamEvent): void {+ if (event.type === "agent.started") this.#started.set(event.data.sessionId, event);+ }++ /** Starts, resumes, or pauses subscriptions to match the conversation. */+ reconcile(): void {+ if (this.#disposed) return;+ const state = this.#options.getState();+ for (const agent of Object.values(state.agents)) {+ if (agentToolTask(state, agent) === undefined) continue;+ const controller = this.#controllers.get(agent.sessionId);+ const caughtUp = isAgentSessionCaughtUp(state, agent);+ if (controller !== undefined && caughtUp) {+ this.#controllers.delete(agent.sessionId);+ controller.abort();+ this.#options.onIdle(agent.sessionId);+ } else if (controller === undefined && !caughtUp && !this.#failed.has(agent.sessionId)) {+ this.#follow(agent.sessionId);+ }+ }+ }++ abortAll(): void {+ this.#disposed = true;+ for (const controller of this.#controllers.values()) controller.abort();+ this.#controllers.clear();+ }++ #follow(sessionId: string): void {+ const started = this.#started.get(sessionId);+ if (started === undefined) return;+ const controller = new AbortController();+ this.#controllers.set(sessionId, controller);+ this.#options.onFollowing(sessionId);+ const { cursors } = this.#options;+ void (async () => {+ let cursor = cursors.get(sessionId) ?? 0;+ try {+ for await (const event of this.#options.session.agent(started).stream({+ signal: controller.signal,+ startIndex: cursor,+ streamReconnectPolicy: agentStreamReconnectPolicy,+ })) {+ if (controller.signal.aborted) return;+ cursors.set(sessionId, ++cursor);+ this.#options.onEvent(sessionId, event);+ this.reconcile();+ }+ } catch {+ // Reported below unless the subscription was deliberately aborted.+ }+ if (controller.signal.aborted || this.#controllers.get(sessionId) !== controller) return;+ this.#controllers.delete(sessionId);+ this.#failed.add(sessionId);+ this.#options.onUnavailable(sessionId);+ })();+ }+}diff --git a/packages/eve/src/client/authorization-message-parts.ts b/packages/eve/src/client/authorization-message-parts.tsindex 2398c4477..95282e770 100644--- a/packages/eve/src/client/authorization-message-parts.ts+++ b/packages/eve/src/client/authorization-message-parts.ts@@ -4,13 +4,17 @@ import type {} from "#protocol/message.js";import type { EveAuthorizationPart } from "#client/message-reducer-types.js";+type MutableAuthorizationPart<T extends EveAuthorizationPart> = {+ -readonly [K in keyof T]: T[K];+};+export function createAuthorizationRequiredPart(event: AuthorizationRequiredStreamEvent,): EveAuthorizationPart {const displayName =event.data.authorization?.displayName ?? formatAuthorizationDisplayName(event.data.name);- return {+ const part: MutableAuthorizationPart<Extract<EveAuthorizationPart, { state: "required" }>> = {authorization: event.data.authorization,description: normalizeAuthorizationDescription(event.data.description,@@ -24,6 +28,9 @@ export function createAuthorizationRequiredPart(turnId: event.data.turnId,type: "authorization",};+ if (event.data.attemptId !== undefined) part.attemptId = event.data.attemptId;+ if (event.data.webhookUrl !== undefined) part.awaitsCallback = true;+ return part;}export function createAuthorizationCompletedPart(@@ -35,7 +42,7 @@ export function createAuthorizationCompletedPart(existing?.displayName ??formatAuthorizationDisplayName(event.data.name);- return {+ const part: MutableAuthorizationPart<Extract<EveAuthorizationPart, { state: "completed" }>> = {authorization:existing?.authorization || event.data.authorization? { ...existing?.authorization, ...event.data.authorization }@@ -46,12 +53,16 @@ export function createAuthorizationCompletedPart(displayName,name: event.data.name,outcome: event.data.outcome,- reason: event.data.reason,state: "completed",stepIndex: existing?.stepIndex ?? event.data.stepIndex,turnId: existing?.turnId ?? event.data.turnId,type: "authorization",};+ const attemptId = event.data.attemptId ?? existing?.attemptId;+ if (attemptId !== undefined) part.attemptId = attemptId;+ if (existing?.awaitsCallback) part.awaitsCallback = true;+ if (event.data.reason !== undefined) part.reason = event.data.reason;+ return part;}function buildCompletedAuthorizationDescription(diff --git a/packages/eve/src/client/conversation-client.ts b/packages/eve/src/client/conversation-client.tsnew file mode 100644index 000000000..81c13d71a--- /dev/null+++ b/packages/eve/src/client/conversation-client.ts@@ -0,0 +1,196 @@+import type { ConversationState } from "#client/conversation-state.js";+import { AgentStreamFollower } from "#client/agent-stream-follower.js";+import {+ canonicalConversationReducer,+ conversationReducer,+ type ClientAgentEvent,+ type ConversationEvent,+} from "#client/conversation-reducer.js";+import { EveAgentProjection, type EveAgentEventLog } from "#client/eve-agent-projection.js";+import { assertAnswerable } from "#client/eve-agent-store-helpers.js";+import type { SendTurnPayload } from "#client/types.js";+import type { EveAgentReducerEvent } from "#client/reducer.js";+import { createEventDeduper } from "#protocol/event-dedupe.js";+import type { MessageStreamEvent } from "#protocol/message.js";+import type { InputResponse } from "#shared/input.js";+import {+ SessionEventStream,+ type SessionEventStreamOptions,+} from "#client/session-event-stream.js";+import type { ClientSession } from "#client/session.js";++/** Owns the canonical conversation and its root and agent-session transports for one client session. */+export class ConversationClient<TData = ConversationState> {+ readonly projection: EveAgentProjection<TData>;+ readonly #conversation: EveAgentProjection<ConversationState, ConversationEvent>;+ readonly #cursors = new Map<string, number>();+ #seenEvents = createEventDeduper();+ #follower?: AgentStreamFollower;+ #stream?: SessionEventStream;+ readonly #onChange: (data: TData, previous: TData) => void;+ readonly #onConversationChange?: (state: ConversationState, previous: ConversationState) => void;++ constructor(+ projection: EveAgentProjection<TData>,+ onChange: (data: TData, previous: TData) => void,+ onConversationChange?: (state: ConversationState, previous: ConversationState) => void,+ ) {+ this.projection = projection;+ // The default reducer is the canonical one, so `data` and `conversation` share one projection.+ this.#conversation =+ projection.reducer === conversationReducer+ ? (projection as EveAgentProjection<ConversationState, ConversationEvent>)+ : new EveAgentProjection(canonicalConversationReducer, []);+ this.#onChange = onChange;+ this.#onConversationChange = onConversationChange;+ }++ get data(): TData {+ return this.projection.data;+ }++ get conversation(): ConversationState {+ return this.#conversation.data;+ }++ get projections(): readonly EveAgentEventLog[] {+ return this.#conversation === this.projection+ ? [this.projection]+ : [this.#conversation, this.projection];+ }++ get following(): boolean {+ return this.#follower !== undefined;+ }++ append(event: EveAgentReducerEvent): void {+ const previous = this.data;+ const previousConversation = this.conversation;+ this.#appendRoot(event);+ if (previous !== this.data) this.#onChange(this.data, previous);+ else if (previousConversation !== this.conversation)+ this.#onConversationChange?.(this.conversation, previousConversation);+ }++ /** Projects submitted answers; the returned callback withdraws them if the server never accepts. */+ projectResponses(responses: readonly InputResponse[] | undefined): (() => void) | undefined {+ if (!responses?.length) return undefined;+ const event: EveAgentReducerEvent = {+ data: { createdAt: Date.now(), responses },+ type: "client.input.responded",+ };+ this.append(event);+ return () => this.#retract(event);+ }++ /** Swaps projected answers for a prepared payload's, which must still be answerable. */+ replaceResponses(+ retract: (() => void) | undefined,+ input: SendTurnPayload,+ ): (() => void) | undefined {+ retract?.();+ assertAnswerable(input, this.conversation);+ return this.projectResponses(input.inputResponses);+ }++ #retract(event: EveAgentReducerEvent): void {+ const previous = this.data;+ const previousConversation = this.conversation;+ for (const projection of this.projections) projection.remove((entry) => entry === event);+ if (previous !== this.data) this.#onChange(this.data, previous);+ else if (previousConversation !== this.conversation)+ this.#onConversationChange?.(this.conversation, previousConversation);+ }++ /** Admit and project a root event before the agent sessions it announces are followed. */+ observe(+ event: MessageStreamEvent,+ options: {+ /** The store reconciles optimistic messages instead of directly appending the event. */+ project?: (event: MessageStreamEvent) => void;+ /** Record the accepted event before projection or child notifications. */+ onAccepted?: (event: MessageStreamEvent) => void;+ /** The store publishes after updating its event log and status. */+ notify?: boolean;+ } = {},+ ): boolean {+ if (!this.#seenEvents.admit(event)) return false;+ options.onAccepted?.(event);+ const previous = this.data;+ const previousConversation = this.conversation;+ if (options.project) options.project(event);+ else this.#appendRoot(event);+ if (options.notify !== false) {+ if (previous !== this.data) this.#onChange(this.data, previous);+ else if (previousConversation !== this.conversation)+ this.#onConversationChange?.(this.conversation, previousConversation);+ }+ this.#follower?.acceptParentEvent(event);+ this.#follower?.reconcile();+ return true;+ }++ /** Admit and project a hydrated root event without notifying subscribers. */+ hydrate(event: MessageStreamEvent): boolean {+ if (!this.#seenEvents.admit(event)) return false;+ this.#appendRoot(event);+ return true;+ }++ /** Start following the agent sessions the root stream has announced so far. */+ follow(session: ClientSession, events: readonly MessageStreamEvent[] = []): void {+ this.#follower?.abortAll();+ const follower = new AgentStreamFollower({+ session,+ cursors: this.#cursors,+ getState: () => this.conversation,+ onFollowing: (sessionId) =>+ this.#appendChild({ type: "client.agent.following", data: { sessionId } }),+ onEvent: (sessionId, event) =>+ this.#appendChild({ type: "client.agent.observed", data: { sessionId, event } }),+ onIdle: (sessionId) => this.#appendChild({ type: "client.agent.idle", data: { sessionId } }),+ onUnavailable: (sessionId) =>+ this.#appendChild({ type: "client.agent.unavailable", data: { sessionId } }),+ });+ this.#follower = follower;+ for (const event of events) follower.acceptParentEvent(event);+ follower.reconcile();+ }++ #appendRoot(event: EveAgentReducerEvent): void {+ for (const projection of this.projections) projection.append(event);+ }++ #appendChild(event: ClientAgentEvent): void {+ const previous = this.data;+ const previousConversation = this.conversation;+ this.#conversation.append(event);+ if (previous !== this.data) this.#onChange(this.data, previous);+ else if (previousConversation !== this.conversation)+ this.#onConversationChange?.(this.conversation, previousConversation);+ }++ /** Follows the root session continuously; operation readers subscribe to this one stream. */+ stream(session: ClientSession, options: SessionEventStreamOptions): SessionEventStream {+ if (this.#stream !== undefined && !this.#stream.ended) {+ this.#stream.setOptions(options);+ return this.#stream;+ }+ this.#stream = new SessionEventStream(session, options);+ return this.#stream;+ }++ stop(): void {+ this.#follower?.abortAll();+ this.#follower = undefined;+ this.#stream?.close();+ this.#stream = undefined;+ }++ reset(): void {+ this.stop();+ this.#cursors.clear();+ this.#seenEvents = createEventDeduper();+ for (const projection of this.projections) projection.reset();+ }+}diff --git a/packages/eve/src/client/conversation-reducer.test.ts b/packages/eve/src/client/conversation-reducer.test.tsnew file mode 100644index 000000000..8208f0177--- /dev/null+++ b/packages/eve/src/client/conversation-reducer.test.ts@@ -0,0 +1,194 @@+import { describe, expect, it } from "vitest";+import {+ conversationReducer,+ reduceConversation,+ type ConversationEvent,+} from "#client/conversation-reducer.js";+import { openConversationInputs, type ConversationState } from "#client/conversation-state.js";+import { stampTestEvent } from "#internal/testing/events.js";+import {+ createAgentStartedEvent,+ createInputRequestedEvent,+ createStepStartedEvent,+ createTaskSettledEvent,+ createTaskStartedEvent,+ createTurnCompletedEvent,+ createTurnStartedEvent,+ createTurnWaitingEvent,+ type UnstampedMessageStreamEvent,+} from "#protocol/message.js";++let stamped = 0;++function reduce(+ events: readonly (UnstampedMessageStreamEvent | ConversationEvent)[],+ state: ConversationState = conversationReducer.initial(),+): ConversationState {+ let current = state;+ for (const event of events) {+ current = reduceConversation(+ current,+ event.type.startsWith("client.")+ ? (event as ConversationEvent)+ : stampTestEvent(event as UnstampedMessageStreamEvent, stamped++),+ );+ }+ return current;+}++function approval(requestId: string, turnId: string, taskId?: string) {+ return createInputRequestedEvent({+ requests: [+ {+ action: { callId: `tool-${requestId}`, input: {}, kind: "tool-call", toolName: "lookup" },+ kind: "tool-approval",+ prompt: "Approve Alice's lookup?",+ requestId,+ },+ ],+ sequence: 0,+ stepIndex: 0,+ taskId,+ turnId,+ });+}++const started = createAgentStartedEvent({+ callId: "call_1",+ name: "researcher",+ parentSessionId: "root",+ sessionId: "child",+ taskId: "task_1",+ turnId: "root-turn",+});++describe("conversation reducer tasks and agent sessions", () => {+ it("records each call to a task in order and settles it once", () => {+ const state = reduce([+ createTaskStartedEvent({+ callId: "call_1",+ kind: "agent",+ name: "researcher",+ taskId: "task_1",+ turnId: "t1",+ }),+ createTaskStartedEvent({+ callId: "call_2",+ kind: "agent",+ name: "researcher",+ taskId: "task_1",+ turnId: "t2",+ }),+ createTaskSettledEvent({+ callId: "call_1",+ output: "Bob's summary.",+ status: "completed",+ taskId: "task_1",+ turnId: "t1",+ }),+ createTaskSettledEvent({+ callId: "call_1",+ status: "cancelled",+ taskId: "task_1",+ turnId: "t1",+ }),+ createTaskSettledEvent({+ callId: "call_2",+ error: { message: "The agent's session ended." },+ status: "failed",+ taskId: "task_1",+ turnId: "t2",+ }),+ approval("req_1", "t2", "task_1"),+ ]);+ expect(state.tasks.task_1).toEqual({+ taskId: "task_1",+ name: "researcher",+ kind: "agent",+ calls: {+ call_1: { callId: "call_1", turnId: "t1", status: "completed", output: "Bob's summary." },+ call_2: {+ callId: "call_2",+ turnId: "t2",+ status: "failed",+ error: { message: "The agent's session ended." },+ },+ },+ });+ expect(Object.keys(state.tasks.task_1!.calls)).toEqual(["call_1", "call_2"]);+ expect(state.inputs.req_1).toMatchObject({ taskId: "task_1", status: "open" });+ });++ it("scopes session inputs apart from root inputs and keeps observed detail across pauses", () => {+ let state = reduce([+ started,+ approval("same-id", "root-turn"),+ { type: "client.agent.following", data: { sessionId: "child" } },+ {+ type: "client.agent.observed",+ data: { sessionId: "child", event: stampTestEvent(approval("same-id", "child-turn")) },+ },+ ]);+ expect(state.agents.child).toMatchObject({+ callId: "call_1",+ name: "researcher",+ taskId: "task_1",+ turnId: "root-turn",+ observation: { status: "following" },+ });+ expect(openConversationInputs(state)).toHaveLength(1);+ state = reduce(+ [+ {+ type: "approval.settled",+ data: {+ outcome: "approved",+ requestId: "same-id",+ responderPrincipalId: "alice",+ sequence: 0,+ stepIndex: 0,+ turnId: "root-turn",+ },+ },+ { type: "client.agent.idle", data: { sessionId: "child" } },+ ],+ state,+ );+ expect(openConversationInputs(state)).toHaveLength(0);+ const detail = { inputs: { "same-id": { status: "open" } } };+ expect(state.agents.child?.observation).toMatchObject({ status: "idle", conversation: detail });+ state = reduce([{ type: "client.agent.unavailable", data: { sessionId: "child" } }], state);+ expect(state.agents.child?.observation).toMatchObject({+ status: "unavailable",+ conversation: detail,+ });+ state = reduce([{ type: "client.agent.following", data: { sessionId: "child" } }], state);+ expect(state.agents.child?.observation).toMatchObject({+ status: "following",+ conversation: detail,+ });+ });++ it("marks a parked turn waiting until it resumes or ends", () => {+ const parked = reduce([+ createTurnStartedEvent({ sequence: 0, turnId: "t1" }),+ createTurnWaitingEvent({ sequence: 0, turnId: "t1" }),+ ]);+ expect(parked.turns.t1).toEqual({ turnId: "t1", status: "active", waiting: true });+ expect(parked.activeTurnId).toBe("t1");+ const resumed = reduce(+ [createStepStartedEvent({ modelId: "mock", sequence: 0, stepIndex: 1, turnId: "t1" })],+ parked,+ );+ expect(resumed.turns.t1).toEqual({ turnId: "t1", status: "active" });+ const ended = reduce(+ [+ createTurnWaitingEvent({ sequence: 0, turnId: "t1" }),+ createTurnCompletedEvent({ sequence: 0, turnId: "t1" }),+ ],+ resumed,+ );+ expect(ended.turns.t1).toEqual({ turnId: "t1", status: "completed" });+ expect(ended.activeTurnId).toBeUndefined();+ });+});diff --git a/packages/eve/src/client/conversation-reducer.ts b/packages/eve/src/client/conversation-reducer.tsnew file mode 100644index 000000000..da5bccef0--- /dev/null+++ b/packages/eve/src/client/conversation-reducer.ts@@ -0,0 +1,288 @@+import type {+ AgentObservation,+ ConversationAgentSession,+ ConversationInput,+ ConversationState,+ ConversationTask,+ ConversationTurn,+} from "#client/conversation-state.js";+import { defaultMessageReducer } from "#client/message-reducer.js";+import type { EveAgentReducer, EveAgentReducerEvent } from "#client/reducer.js";+import type { MessageStreamEvent } from "#protocol/message.js";++/**+ * Transport facts about followed agent sessions. Only the canonical conversation receives them;+ * custom reducers see their results in `conversation.agents`.+ */+export type ClientAgentEvent =+ | {+ readonly data: { readonly sessionId: string };+ readonly type: "client.agent.following" | "client.agent.idle" | "client.agent.unavailable";+ }+ | {+ readonly data: { readonly event: MessageStreamEvent; readonly sessionId: string };+ readonly type: "client.agent.observed";+ };++export type ConversationEvent = EveAgentReducerEvent | ClientAgentEvent;++type Mutable<T> = { -readonly [K in keyof T]: T[K] };++export function initialConversationState(): ConversationState {+ return { messages: [], turns: {}, inputs: {}, tasks: {}, agents: {} };+}++function updateTurn(+ state: ConversationState,+ turnId: string,+ update: (turn: ConversationTurn) => ConversationTurn,+): ConversationState {+ const turn = state.turns[turnId];+ if (turn === undefined) return state;+ const next = update(turn);+ return next === turn ? state : { ...state, turns: { ...state.turns, [turnId]: next } };+}++function updateTask(+ state: ConversationState,+ taskId: string,+ update: (task: ConversationTask) => ConversationTask,+): ConversationState {+ const task = state.tasks[taskId];+ if (task === undefined) return state;+ const next = update(task);+ return next === task ? state : { ...state, tasks: { ...state.tasks, [taskId]: next } };+}++function updateObservation(+ state: ConversationState,+ sessionId: string,+ update: (observation: AgentObservation) => AgentObservation,+): ConversationState {+ const agent = state.agents[sessionId];+ if (agent === undefined) return state;+ const observation = update(agent.observation);+ if (observation === agent.observation) return state;+ return { ...state, agents: { ...state.agents, [sessionId]: { ...agent, observation } } };+}++function observedConversation(observation: AgentObservation): ConversationState | undefined {+ return observation.status === "not-followed" ? undefined : observation.conversation;+}++/** Applies lifecycle identity and closure to an already projected message state. */+function reduceConversationLifecycle(+ state: ConversationState,+ event: EveAgentReducerEvent,+): ConversationState {+ switch (event.type) {+ case "turn.started":+ return {+ ...state,+ activeTurnId: event.data.turnId,+ turns: {+ ...state.turns,+ [event.data.turnId]: { turnId: event.data.turnId, status: "active" },+ },+ };+ case "turn.waiting":+ return updateTurn(state, event.data.turnId, (turn) =>+ turn.status === "active" && !turn.waiting ? { ...turn, waiting: true } : turn,+ );+ case "step.started":+ return updateTurn(state, event.data.turnId, (turn) =>+ turn.waiting ? { turnId: turn.turnId, status: turn.status } : turn,+ );+ case "turn.completed":+ case "turn.cancelled":+ case "turn.failed": {+ const { turnId } = event.data;+ return {+ ...state,+ activeTurnId: state.activeTurnId === turnId ? undefined : state.activeTurnId,+ turns: {+ ...state.turns,+ [turnId]: {+ turnId,+ status:+ event.type === "turn.completed"+ ? "completed"+ : event.type === "turn.failed"+ ? "failed"+ : "cancelled",+ },+ },+ };+ }+ // Only a turn's end reaches a session boundary, so no turn stays open across one.+ case "session.waiting":+ case "session.completed":+ case "session.failed":+ return state.activeTurnId === undefined ? state : { ...state, activeTurnId: undefined };+ case "task.started": {+ const { callId, kind, name, taskId, turnId } = event.data;+ const task = state.tasks[taskId] ?? { taskId, name, kind, calls: {} };+ if (task.calls[callId] !== undefined) return state;+ return {+ ...state,+ tasks: {+ ...state.tasks,+ [taskId]: {+ ...task,+ calls: { ...task.calls, [callId]: { callId, turnId, status: "working" } },+ },+ },+ };+ }+ case "task.settled": {+ const { callId, error, output, status, taskId } = event.data;+ return updateTask(state, taskId, (task) => {+ const call = task.calls[callId];+ if (call === undefined || call.status !== "working") return task;+ const settled = { callId, turnId: call.turnId, status };+ return {+ ...task,+ calls: {+ ...task.calls,+ [callId]:+ status === "completed" && output !== undefined+ ? { ...settled, output }+ : status === "failed" && error !== undefined+ ? { ...settled, error }+ : settled,+ },+ };+ });+ }+ case "agent.started": {+ const { callId, name, sessionId, taskId, turnId } = event.data;+ if (state.agents[sessionId] !== undefined) return state;+ const agent: Mutable<ConversationAgentSession> = {+ sessionId,+ name,+ callId,+ turnId,+ observation: { status: "not-followed" },+ };+ if (taskId !== undefined) agent.taskId = taskId;+ return { ...state, agents: { ...state.agents, [sessionId]: agent } };+ }+ case "input.requested": {+ const inputs = { ...state.inputs };+ for (const request of event.data.requests) {+ if (inputs[request.requestId] !== undefined) continue;+ const input: Mutable<ConversationInput> = {+ request,+ turnId: event.data.turnId,+ stepIndex: event.data.stepIndex,+ status: "open",+ };+ if (event.data.taskId !== undefined) input.taskId = event.data.taskId;+ inputs[request.requestId] = input;+ }+ return { ...state, inputs };+ }+ case "client.input.responded": {+ const inputs = { ...state.inputs };+ for (const response of event.data.responses) {+ const current = inputs[response.requestId];+ if (current?.status !== "open") continue;+ inputs[response.requestId] = { ...current, response, status: "responded" };+ }+ return { ...state, inputs };+ }+ case "approval.candidate": {+ const current = state.inputs[event.data.requestId];+ if (current === undefined || current.status === "settled") return state;+ if (event.data.outcome === "pending") return state;+ return {+ ...state,+ inputs: {+ ...state.inputs,+ [event.data.requestId]: { ...current, status: "open", response: undefined },+ },+ };+ }+ case "approval.settled": {+ const current = state.inputs[event.data.requestId];+ if (current === undefined || current.status === "settled") return state;+ return {+ ...state,+ inputs: {+ ...state.inputs,+ [event.data.requestId]: { ...current, status: "settled", outcome: event.data.outcome },+ },+ };+ }+ case "input.resolved": {+ const inputs = { ...state.inputs };+ for (const resolution of event.data.resolutions) {+ const current = inputs[resolution.requestId];+ if (current === undefined || current.status === "settled") continue;+ inputs[resolution.requestId] = {+ ...current,+ status: "settled",+ outcome: resolution.outcome,+ response: resolution.response ?? current.response,+ };+ }+ return { ...state, inputs };+ }+ default:+ return state;+ }+}++const messageReducer = defaultMessageReducer();++/** Pure reduction of accepted root and agent-session observations; followers own transport. */+export function reduceConversation(+ state: ConversationState,+ event: ConversationEvent,+): ConversationState {+ switch (event.type) {+ case "client.agent.following":+ return updateObservation(state, event.data.sessionId, (observation) =>+ observation.status === "following"+ ? observation+ : {+ status: "following",+ conversation: observedConversation(observation) ?? initialConversationState(),+ },+ );+ case "client.agent.observed":+ return updateObservation(state, event.data.sessionId, (observation) =>+ observation.status === "following"+ ? {+ status: "following",+ conversation: reduceConversation(observation.conversation, event.data.event),+ }+ : observation,+ );+ case "client.agent.idle":+ return updateObservation(state, event.data.sessionId, (observation) =>+ observation.status === "following"+ ? { status: "idle", conversation: observation.conversation }+ : observation,+ );+ case "client.agent.unavailable":+ return updateObservation(state, event.data.sessionId, (observation) => {+ const conversation = observedConversation(observation);+ return conversation === undefined+ ? { status: "unavailable" }+ : { status: "unavailable", conversation };+ });+ default: {+ const projected = messageReducer.reduce(state, event);+ return reduceConversationLifecycle({ ...state, ...projected }, event);+ }+ }+}++/** The canonical conversation's reducer, which also folds in followed agent sessions. */+export const canonicalConversationReducer = {+ initial: initialConversationState,+ reduce: reduceConversation,+};++export const conversationReducer: EveAgentReducer<ConversationState> = canonicalConversationReducer;diff --git a/packages/eve/src/client/conversation-state.test.ts b/packages/eve/src/client/conversation-state.test.tsnew file mode 100644index 000000000..e5d3e94a1--- /dev/null+++ b/packages/eve/src/client/conversation-state.test.ts@@ -0,0 +1,183 @@+import { describe, expect, it } from "vitest";+import {+ conversationReducer,+ reduceConversation,+ type ConversationEvent,+} from "#client/conversation-reducer.js";+import {+ agentCallTurns,+ isAgentSessionCaughtUp,+ type ConversationState,+} from "#client/conversation-state.js";+import { stampTestEvent } from "#internal/testing/events.js";+import {+ createAgentStartedEvent,+ createAuthorizationCompletedEvent,+ createAuthorizationRequiredEvent,+ createInputRequestedEvent,+ createMessageReceivedEvent,+ createSessionWaitingEvent,+ createTaskSettledEvent,+ createTaskStartedEvent,+ createTurnCompletedEvent,+ createTurnStartedEvent,+ type UnstampedMessageStreamEvent,+} from "#protocol/message.js";++let stamped = 0;+const stamp = (event: UnstampedMessageStreamEvent) => stampTestEvent(event, stamped++);++function reduce(+ state: ConversationState,+ events: readonly (UnstampedMessageStreamEvent | ConversationEvent)[],+): ConversationState {+ let current = state;+ for (const event of events) {+ current = reduceConversation(+ current,+ event.type.startsWith("client.")+ ? (event as ConversationEvent)+ : stamp(event as UnstampedMessageStreamEvent),+ );+ }+ return current;+}++/** Child events as the root's follower observes them. */+function observe(state: ConversationState, events: readonly UnstampedMessageStreamEvent[]) {+ return reduce(+ state,+ events.map((event) => ({+ type: "client.agent.observed" as const,+ data: { sessionId: "child", event: stamp(event) },+ })),+ );+}++const received = (turnId: string, message: string) =>+ createMessageReceivedEvent({ message, sequence: 0, turnId });+const turnStarted = (turnId: string) => createTurnStartedEvent({ sequence: 0, turnId });+const turnCompleted = (turnId: string) => createTurnCompletedEvent({ sequence: 0, turnId });+const call = (callId: string) =>+ createTaskStartedEvent({+ callId,+ kind: "agent",+ name: "researcher",+ taskId: "task_1",+ turnId: "root-turn",+ });+const settle = (callId: string) =>+ createTaskSettledEvent({+ callId,+ output: "done",+ status: "completed",+ taskId: "task_1",+ turnId: "root-turn",+ });++function followedResearcher(callIds: readonly string[]): ConversationState {+ return reduce(conversationReducer.initial(), [+ ...callIds.map(call),+ createAgentStartedEvent({+ callId: callIds[0]!,+ name: "researcher",+ parentSessionId: "root",+ sessionId: "child",+ taskId: "task_1",+ turnId: "root-turn",+ }),+ { type: "client.agent.following", data: { sessionId: "child" } },+ ]);+}++function child(state: ConversationState): ConversationState {+ const observation = state.agents.child?.observation;+ if (observation === undefined || observation.status === "not-followed") throw new Error();+ return observation.conversation!;+}++describe("agent tool sessions", () => {+ it("attributes each received message's turn to the task's calls in order", () => {+ const state = observe(followedResearcher(["a", "b", "c"]), [+ turnStarted("t1"),+ received("t1", "Find the March incidents."),+ received("t1", "Include the April ones too."),+ turnCompleted("t1"),+ // Resumed after an approval: no message of its own.+ turnStarted("t2"),+ turnCompleted("t2"),+ turnStarted("t3"),+ received("t3", "Now summarize them for Bob."),+ ]);+ expect(agentCallTurns(state.tasks.task_1!, child(state))).toEqual(+ new Map([+ ["a", ["t1", "t2"]],+ ["b", []],+ ["c", ["t3"]],+ ]),+ );+ });++ it("is caught up only once every call settled and its reply arrived", () => {+ let state = followedResearcher(["a"]);+ const caughtUp = () => isAgentSessionCaughtUp(state, state.agents.child!);+ expect(caughtUp()).toBe(false);+ // The root can report the call settled before the child's stream delivers the reply.+ state = reduce(state, [settle("a")]);+ expect(caughtUp()).toBe(false);+ state = observe(state, [turnStarted("t1"), received("t1", "Find the March incidents.")]);+ expect(caughtUp()).toBe(false);+ state = observe(state, [+ createInputRequestedEvent({+ requests: [+ {+ action: { callId: "lookup", input: {}, kind: "tool-call", toolName: "lookup" },+ kind: "tool-approval",+ prompt: "Approve Alice's lookup?",+ requestId: "q1",+ },+ ],+ sequence: 0,+ stepIndex: 0,+ turnId: "t1",+ }),+ turnCompleted("t1"),+ ]);+ expect(caughtUp()).toBe(false);+ state = observe(state, [+ {+ type: "input.resolved",+ data: {+ resolutions: [{ kind: "tool-approval", outcome: "approved", requestId: "q1" }],+ sequence: 0,+ stepIndex: 0,+ turnId: "t1",+ },+ },+ ]);+ expect(caughtUp()).toBe(true);+ // A sign-in parked after the reply resumes the agent's work once its callback arrives.+ const signIn = {+ attemptId: "attempt_1",+ name: "notes",+ sequence: 0,+ stepIndex: 0,+ turnId: "t1",+ };+ state = observe(state, [+ createAuthorizationRequiredEvent({+ ...signIn,+ description: "Connect Alice's notes",+ webhookUrl: "https://example.com/callback",+ }),+ createSessionWaitingEvent(),+ ]);+ expect(caughtUp()).toBe(false);+ state = observe(state, [+ createAuthorizationCompletedEvent({ ...signIn, outcome: "authorized" }),+ ]);+ expect(caughtUp()).toBe(true);+ state = reduce(state, [call("b")]);+ expect(caughtUp()).toBe(false);+ });+});diff --git a/packages/eve/src/client/conversation-state.ts b/packages/eve/src/client/conversation-state.tsnew file mode 100644index 000000000..05df8babe--- /dev/null+++ b/packages/eve/src/client/conversation-state.ts@@ -0,0 +1,195 @@+import type { EveAuthorizationPart, EveMessageData } from "#client/message-reducer-types.js";+import type { InputRequest, InputResponse } from "#shared/input.js";+import type { JsonValue } from "#shared/json.js";++export interface ConversationTurn {+ readonly turnId: string;+ readonly status: "active" | "completed" | "cancelled" | "failed";+ /** The open turn is parked, holding on its tasks or on a question one of its calls asked. */+ readonly waiting?: boolean;+}++export interface ConversationInput {+ readonly request: InputRequest;+ readonly turnId: string;+ readonly stepIndex: number;+ /** The task whose run asks, when a task asks. */+ readonly taskId?: string;+ readonly status: "open" | "responded" | "settled";+ readonly response?: InputResponse;+ readonly outcome?: string;+}++/** One call that started or reached a task, settled by its `task.settled`. */+export interface ConversationTaskCall {+ readonly callId: string;+ readonly turnId: string;+ readonly status: "working" | "completed" | "failed" | "cancelled";+ /** The call's result; present only when `status` is `"completed"`. */+ readonly output?: JsonValue;+ /** Why the call failed; present only when `status` is `"failed"`. */+ readonly error?: { readonly message: string };+}++export interface ConversationTask {+ readonly taskId: string;+ /** The tool whose call started the task. */+ readonly name: string;+ /**+ * `"agent"` when a subagent's tool, local or remote, started the task; `"tool"` for an authored+ * tool, including one that opens sessions with `ctx.agent`.+ */+ readonly kind: "agent" | "tool";+ /** Calls in the order they started or reached the task. */+ readonly calls: Readonly<Record<string, ConversationTaskCall>>;+}++export type AgentObservation =+ | { readonly status: "not-followed" }+ | { readonly status: "following"; readonly conversation: ConversationState }+ /** Every call so far has shown its content; a later call to the task resumes following. */+ | { readonly status: "idle"; readonly conversation: ConversationState }+ | {+ /** The stream failed; this does not mean the agent failed. */+ readonly status: "unavailable";+ readonly conversation?: ConversationState;+ };++/** A session a run opened with `ctx.agent`, as its `agent.started` announced it. */+export interface ConversationAgentSession {+ readonly sessionId: string;+ readonly name: string;+ /** The call whose invocation opened the session. */+ readonly callId: string;+ readonly turnId: string;+ /** The task whose run opened the session; absent when an `execute` call opened it. */+ readonly taskId?: string;+ readonly observation: AgentObservation;+}++/** Renderable conversation state. Root and agent-session input IDs occupy separate scopes. */+export interface ConversationState extends EveMessageData {+ readonly activeTurnId?: string;+ readonly turns: Readonly<Record<string, ConversationTurn>>;+ readonly inputs: Readonly<Record<string, ConversationInput>>;+ readonly tasks: Readonly<Record<string, ConversationTask>>;+ /** Sessions opened by this session's runs, by session ID. */+ readonly agents: Readonly<Record<string, ConversationAgentSession>>;+}++/** Inputs awaiting an answer, including requests introduced in earlier turns. */+export function openConversationInputs(state: ConversationState): readonly ConversationInput[] {+ return Object.values(state.inputs).filter((input) => input.status === "open");+}++/** Authorization attempts remain visible across turns, including parked callbacks. */+export function conversationAuthorizations(+ state: ConversationState,+): readonly EveAuthorizationPart[] {+ return state.messages.flatMap((message) =>+ message.role === "assistant"+ ? message.parts.filter((part): part is EveAuthorizationPart => part.type === "authorization")+ : [],+ );+}++/** A sign-in the session still waits on, which resumes its work when the callback arrives. */+export function hasPendingAuthorizations(state: ConversationState): boolean {+ return conversationAuthorizations(state).some(+ (part) => part.state === "required" && part.awaitsCallback === true,+ );+}++/**+ * The agent task whose calls a session receives, when the session is that agent's own. eve's agent+ * tools send each call as one message, in call order, which is what lets a client attribute the+ * session's turns to calls. A session an authored tool opens with `ctx.agent` has no such task.+ */+export function agentToolTask(+ state: ConversationState,+ agent: ConversationAgentSession,+): ConversationTask | undefined {+ const task = agent.taskId === undefined ? undefined : state.tasks[agent.taskId];+ return task?.kind === "agent" ? task : undefined;+}++/** The session an agent tool forwards its task's calls to. */+export function agentToolSession(+ state: ConversationState,+ task: ConversationTask,+): ConversationAgentSession | undefined {+ return Object.values(state.agents).find(+ (agent) => agentToolTask(state, agent)?.taskId === task.taskId,+ );+}++/**+ * Whether a followed agent tool session has shown everything its task's calls produced so far:+ * no call is working, the session has no open turn, question, or sign-in, and every completed call's+ * message has arrived. The last check covers a child stream that lags the root stream.+ */+export function isAgentSessionCaughtUp(+ state: ConversationState,+ agent: ConversationAgentSession,+): boolean {+ if (agent.observation.status !== "following" && agent.observation.status !== "idle") {+ return false;+ }+ const task = agentToolTask(state, agent);+ if (task === undefined) return false;+ const calls = Object.values(task.calls);+ if (calls.some((call) => call.status === "working")) return false;+ const child = agent.observation.conversation;+ if (child.activeTurnId !== undefined) return false;+ if (Object.values(child.inputs).some((input) => input.status !== "settled")) return false;+ if (hasPendingAuthorizations(child)) return false;+ const received = child.messages.filter((message) => message.role === "user").length;+ return received >= calls.filter((call) => call.status === "completed").length;+}++/**+ * Attributes an agent tool session's turns to the calls that produced them. The k-th message the+ * session received came from the task's k-th call; a turn without a message of its own, such as+ * one resumed after an approval, continues the previous call. A call whose message joined a+ * running turn owns no turn.+ */+export function agentCallTurns(+ task: ConversationTask,+ conversation: ConversationState,+): ReadonlyMap<string, readonly string[]> {+ const callIds = Object.keys(task.calls);+ const owners = new Map<string, string>();+ let index = 0;+ for (const message of conversation.messages) {+ if (message.role !== "user") continue;+ const callId = callIds[index++];+ const turnId = message.metadata?.turnId;+ if (callId !== undefined && turnId !== undefined && !owners.has(turnId)) {+ owners.set(turnId, callId);+ }+ }+ const turns = new Map<string, string[]>(callIds.map((callId) => [callId, []]));+ let owner: string | undefined;+ for (const turnId of Object.keys(conversation.turns)) {+ owner = owners.get(turnId) ?? owner;+ if (owner !== undefined) turns.get(owner)?.push(turnId);+ }+ return turns;+}++/**+ * Whether a call's content may still arrive on its agent tool session: one of the call's turns is+ * still open there, or the call completed before its message reached the session.+ */+export function isAgentCallContentPending(+ task: ConversationTask,+ call: ConversationTaskCall,+ conversation: ConversationState,+): boolean {+ const turnIds = agentCallTurns(task, conversation).get(call.callId) ?? [];+ const { activeTurnId } = conversation;+ if (activeTurnId !== undefined && turnIds.includes(activeTurnId)) return true;+ if (call.status !== "completed") return false;+ const received = conversation.messages.filter((message) => message.role === "user").length;+ return received <= Object.keys(task.calls).indexOf(call.callId);+}diff --git a/packages/eve/src/client/eve-agent-projection.ts b/packages/eve/src/client/eve-agent-projection.tsindex a9d2a8de0..b1be87615 100644--- a/packages/eve/src/client/eve-agent-projection.ts+++ b/packages/eve/src/client/eve-agent-projection.ts@@ -1,14 +1,34 @@-import type { EveAgentReducer, EveAgentReducerEvent } from "#client/reducer.js";+import type { ConversationEvent } from "#client/conversation-reducer.js";+import type { EveAgentReducerEvent } from "#client/reducer.js";-/** Owns reducer replay when optimistic events are replaced by server events. */-export class EveAgentProjection<TData> {- readonly #reducer: EveAgentReducer<TData>;- #events: readonly EveAgentReducerEvent[];+interface ProjectionReducer<TData, TEvent> {+ initial(): TData;+ reduce(data: TData, event: TEvent): TData;+}++/**+ * The part of a projection that root-stream bookkeeping writes. Its entries can include the+ * canonical conversation's agent-session events, so predicates see the wider event type.+ */+export interface EveAgentEventLog {+ append(event: EveAgentReducerEvent): void;+ remove(predicate: (event: ConversationEvent) => boolean): void;+ replace(+ predicate: (event: ConversationEvent) => boolean,+ replacement: EveAgentReducerEvent,+ ): void;+ reset(): void;+}++/** Owns chronological reducer replay when optimistic events are replaced by server events. */+export class EveAgentProjection<TData, TEvent = EveAgentReducerEvent> {+ readonly #reducer: ProjectionReducer<TData, TEvent>;+ #events: TEvent[];#data: TData;- constructor(reducer: EveAgentReducer<TData>, events: readonly EveAgentReducerEvent[]) {+ constructor(reducer: ProjectionReducer<TData, TEvent>, events: readonly TEvent[]) {this.#reducer = reducer;- this.#events = events;+ this.#events = [...events];this.#data = this.#reduce();}@@ -16,30 +36,29 @@ export class EveAgentProjection<TData> {return this.#data;}+ get reducer(): ProjectionReducer<TData, TEvent> {+ return this.#reducer;+ }+reset(): void {this.#events = [];this.#data = this.#reducer.initial();}- append(event: EveAgentReducerEvent): void {- this.#events = [...this.#events, event];+ append(event: TEvent): void {+ this.#events.push(event);this.#data = this.#reducer.reduce(this.#data, event);}- remove(predicate: (event: EveAgentReducerEvent) => boolean): void {+ remove(predicate: (event: TEvent) => boolean): void {this.#events = this.#events.filter((event) => !predicate(event));this.#data = this.#reduce();}- replace(- predicate: (event: EveAgentReducerEvent) => boolean,- replacement: EveAgentReducerEvent,- ): void {+ replace(predicate: (event: TEvent) => boolean, replacement: TEvent): void {const index = this.#events.findIndex(predicate);- this.#events =- index === -1- ? [...this.#events, replacement]- : this.#events.map((event, i) => (i === index ? replacement : event));+ if (index === -1) this.#events.push(replacement);+ else this.#events[index] = replacement;this.#data = this.#reduce();}diff --git a/packages/eve/src/client/eve-agent-store-helpers.ts b/packages/eve/src/client/eve-agent-store-helpers.tsindex 08c6dc9bb..be0425f88 100644--- a/packages/eve/src/client/eve-agent-store-helpers.ts+++ b/packages/eve/src/client/eve-agent-store-helpers.ts@@ -1,27 +1,79 @@-import {- isTurnSegmentBoundary,- updatePendingAuthorizations,- updatePendingInputRequests,-} from "#client/session-utils.js";+import { hasPendingAuthorizations, type ConversationState } from "#client/conversation-state.js";import type { ActiveTurn } from "#client/eve-agent-store-state.js";import type { MessageResponse } from "#client/message-response.js";+import { endsTurnSegment, TurnSegment } from "#client/session-utils.js";import type { CancelSessionResult, SendTurnPayload } from "#client/types.js";-import type { MessageStreamEvent } from "#protocol/message.js";+import { isCurrentTurnBoundaryEvent, type MessageStreamEvent } from "#protocol/message.js";import type { UserContent } from "ai";-export function isSettledSessionTail(events: readonly MessageStreamEvent[]): boolean {+export function activeTurnForOptimisticFollowUp(+ events: readonly MessageStreamEvent[],+): string | undefined {+ const lastTurn = events.findLast(+ (event) =>+ event.type === "turn.started" ||+ event.type === "turn.completed" ||+ event.type === "turn.failed" ||+ event.type === "turn.cancelled" ||+ isCurrentTurnBoundaryEvent(event),+ );+ return lastTurn?.type === "turn.started" ? lastTurn.data.turnId : undefined;+}++/**+ * Where catch-up stops following and when an idle session counts as settled. These reads have no+ * response to scope them, so the {@link endsTurnSegment} rule reads the whole conversation.+ */+export function isResponseBoundary(+ event: MessageStreamEvent,+ conversation: ConversationState,+): boolean {+ return endsTurnSegment(event, {+ callbacks: hasPendingAuthorizations(conversation),+ requests: Object.values(conversation.inputs).some((input) => input.status !== "settled"),+ });+}++/** A turn parked on a question stays open, so its session is still streaming. */+export function settledStatus(+ error: Error | undefined,+ conversation: ConversationState,+): "error" | "ready" | "streaming" {+ if (error !== undefined) return "error";+ return conversation.activeTurnId === undefined ? "ready" : "streaming";+}++export function isSettledSessionTail(+ events: readonly MessageStreamEvent[],+ conversation: ConversationState,+): boolean {const tail = events.at(-1);- if (tail === undefined) return false;- const pendingAuthorizations = new Set<string>();- const pendingInputRequests = new Set<string>();- for (const event of events) {- updatePendingAuthorizations(pendingAuthorizations, event);- updatePendingInputRequests(pendingInputRequests, event);+ return tail !== undefined && isResponseBoundary(tail, conversation);+}++/** A server ignores answers to requests it already settled, so the store never sends them. */+export function assertAnswerable(input: SendTurnPayload, conversation: ConversationState): void {+ for (const { requestId } of input.inputResponses ?? []) {+ const status = conversation.inputs[requestId]?.status;+ if (status !== undefined && status !== "open") {+ throw new Error(`Input request ${requestId} was already answered.`);+ }}- return (- isTurnSegmentBoundary(tail, pendingInputRequests) &&- (tail.type !== "session.waiting" || pendingAuthorizations.size === 0)- );+}++export function assertInFlightFollowUp(input: SendTurnPayload): void {+ if (input.inputResponses !== undefined) return;+ if (input.message === undefined || input.turnPolicy !== "steer") {+ throw new Error(+ 'eve session is already processing a turn. Send a message with turnPolicy: "steer" to guide it at the next boundary, or answer an open input request.',+ );+ }+}++export function validateFollowUp<T extends SendTurnPayload>(input: T): T {+ assertExclusiveTurnInput(input);+ assertInFlightFollowUp(input);+ return input;}export function assertExclusiveTurnInput(input: SendTurnPayload): void {@@ -98,6 +150,28 @@ export function createActiveTurn(return turn;}+/** Counts confirmed steered messages toward the active turn's accepted follow-ups. */+export function countFollowUpDeliveries(+ turn: ActiveTurn,+ reconciliation: {+ readonly alreadyProjected: boolean;+ readonly event: MessageStreamEvent;+ readonly ids: readonly string[];+ },+): void {+ let followed = 0;+ for (const id of reconciliation.ids) {+ if (turn.followUpSubmissionIds.delete(id)) followed += 1;+ }+ if (followed === 0) return;+ if (reconciliation.alreadyProjected) {+ turn.receivedFollowUps += followed;+ } else {+ const previous = turn.receivedFollowUpEvents.get(reconciliation.event) ?? 0;+ turn.receivedFollowUpEvents.set(reconciliation.event, previous + followed);+ }+}+export async function followSteeredTurns(turn: ActiveTurn,events: AsyncIterable<MessageStreamEvent>,@@ -107,13 +181,12 @@ export async function followSteeredTurns(await Promise.allSettled(turn.followUpDispatches);}if (turn.receivedFollowUps >= turn.acceptedFollowUps) return;- const pendingInputRequests = new Set<string>();+ const segment = new TurnSegment({ followCallbacks: true });for await (const event of events) {if (!isActive()) return;turn.receivedFollowUps += turn.receivedFollowUpEvents.get(event) ?? 0;turn.receivedFollowUpEvents.delete(event);- updatePendingInputRequests(pendingInputRequests, event);- if (isTurnSegmentBoundary(event, pendingInputRequests)) {+ if (segment.observe(event)) {while (turn.followUpDispatches.size > 0) {await Promise.allSettled(turn.followUpDispatches);}diff --git a/packages/eve/src/client/eve-agent-store-state.ts b/packages/eve/src/client/eve-agent-store-state.tsindex c28ac6929..e53cba301 100644--- a/packages/eve/src/client/eve-agent-store-state.ts+++ b/packages/eve/src/client/eve-agent-store-state.ts@@ -1,5 +1,7 @@+import type { Client } from "#client/client.js";import type { MessageResponse } from "#client/message-response.js";import type { EveAgentReducer } from "#client/reducer.js";+import type { ConversationState } from "#client/conversation-state.js";import type { ClientSession } from "#client/session.js";import type { MessageStreamEvent } from "#protocol/message.js";import type {@@ -27,6 +29,8 @@ export type PrepareSend = (input: SendTurnPayload) => SendTurnPayload | Promise</** Immutable projected state of an eve frontend session store. */export interface EveAgentStoreSnapshot<TData> {readonly data: TData;+ /** Canonical session facts, independent of the caller's data projection. */+ readonly conversation: ConversationState;/** The latest session creation, stream, resume, or turn failure. */readonly error: Error | undefined;readonly events: readonly MessageStreamEvent[];@@ -47,12 +51,14 @@ export interface EveAgentStoreCallbacks<TData> {}/**- * Configuration for constructing an eve frontend session store. Pass either- * connection options for a store-owned session or an existing `ClientSession`.- * Saved events must be an ordered prefix of the same session stream.+ * Configuration for constructing an eve frontend session store. Pass connection+ * options or a configured `Client` for store-owned sessions, or an existing+ * `ClientSession`. Saved events must be an ordered prefix of the same session stream.*/export interface EveAgentStoreInit<TData> {readonly prewarm?: boolean;+ /** Configured client for store-owned sessions; replaces `host`, `auth`, and `headers`. */+ readonly client?: Client;readonly auth?: ClientAuth;readonly headers?: HeadersValue;readonly host?: string;@@ -60,6 +66,11 @@ export interface EveAgentStoreInit<TData> {readonly initialEvents?: readonly MessageStreamEvent[];readonly initialSession?: ClientSessionState;readonly optimistic?: boolean;+ /**+ * Follow each agent tool's session into `conversation.agents`, regardless of the data reducer,+ * while the store streams its session or a framework binding has it mounted.+ */+ readonly followSubagents?: boolean;readonly reducer: EveAgentReducer<TData>;readonly session?: ClientSession;}@@ -69,6 +80,7 @@ export interface PendingMessageSubmission {readonly eventStartIndex: number;readonly id: string;readonly message: string;+ readonly turnId?: string;readonly requiresDeliveryId: boolean;readonly deliveryId?: string;}diff --git a/packages/eve/src/client/eve-agent-store.test.ts b/packages/eve/src/client/eve-agent-store.test.tsindex ec2acd609..73fecbeec 100644--- a/packages/eve/src/client/eve-agent-store.test.ts+++ b/packages/eve/src/client/eve-agent-store.test.ts@@ -1,11 +1,17 @@import { afterEach, describe, expect, it, vi } from "vitest";-import { detachEveAgentStore, EveAgentStore } from "#client/eve-agent-store.js";+import {+ attachEveAgentStore,+ detachEveAgentStore,+ EveAgentStore,+} from "#client/eve-agent-store.js";+import { Client } from "#client/client.js";import { defaultMessageReducer } from "#client/message-reducer.js";-import { stampTestEvents } from "#internal/testing/events.js";+import { conversationReducer } from "#client/conversation-reducer.js";+import type { ConversationState } from "#client/conversation-state.js";+import { stampTestEvent, stampTestEvents } from "#internal/testing/events.js";import {- createApprovalCandidateEvent,- createInputRequestedEvent,+ createApprovalSettledEvent,createAuthorizationCompletedEvent,createAuthorizationRequiredEvent,createMessageAppendedEvent,@@ -13,8 +19,14 @@ import {createMessageReceivedEvent,createSessionFailedEvent,createSessionWaitingEvent,+ createAgentStartedEvent,+ createInputRequestedEvent,+ createTaskSettledEvent,+ createTaskStartedEvent,+ createTurnCompletedEvent,createTurnCancelledEvent,createTurnStartedEvent,+ createTurnWaitingEvent,EVE_MESSAGE_STREAM_VERSION,EVE_SESSION_ID_HEADER,EVE_STREAM_VERSION_HEADER,@@ -188,6 +200,34 @@ function preV20MessageCompletedEvent(): MessageStreamEvent {}const cleanupStores: Array<() => void> = [];+function colorApprovalRequested(requestId: string): MessageStreamEvent {+ return stampTestEvents([+ {+ type: "input.requested",+ data: {+ requests: [+ {+ action: {+ callId: `${requestId}-call`,+ input: {},+ kind: "tool-call",+ toolName: "random_color",+ },+ display: "confirmation",+ kind: "tool-approval",+ options: [{ id: "approve", label: "Approve" }],+ prompt: "Approve color?",+ requestId,+ },+ ],+ sequence: 0,+ stepIndex: 0,+ turnId: "turn_1",+ },+ } as UnstampedMessageStreamEvent,+ ])[0]!;+}+function createStore<TData>(init: ConstructorParameters<typeof EveAgentStore<TData>>[0],): EveAgentStore<TData> {@@ -196,22 +236,8 @@ function createStore<TData>(return store;}-/**- * Runs client reconnect backoff (250ms per attempt) on a fake clock. Call- * `fastForwardTimers` once no stream is held open: auto-advancing while a- * held stream is open would also fire its read-idle timeout.- */-function useFakeBackoffClock(): void {- vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });-}--function fastForwardTimers(): void {- vi.setTimerTickMode("nextTimerAsync");-}-afterEach(() => {for (const cleanup of cleanupStores.splice(0)) cleanup();- vi.useRealTimers();vi.restoreAllMocks();vi.unstubAllGlobals();});@@ -273,7 +299,13 @@ describe("EveAgentStore lifecycle", () => {metadata: { status: "complete", turnId: "turn_1" },parts: [{ type: "step-start" },- { state: "done", stepIndex: 0, text: "Hi there.", type: "text" },+ {+ id: expect.stringMatching(/^evt_/),+ state: "done",+ stepIndex: 0,+ text: "Hi there.",+ type: "text",+ },],role: "assistant",},@@ -282,6 +314,36 @@ describe("EveAgentStore lifecycle", () => {expect(seenStreamIndexes).toEqual([0, 1, 2, 3, 3]);});+ it("reconciles optimistic conversation messages while a custom reducer counts server events", async () => {+ const live = controlledStreamResponse();+ vi.spyOn(globalThis, "fetch")+ .mockResolvedValueOnce(startedResponse("delivery_1"))+ .mockResolvedValueOnce(live.response);+ const store = createStore({+ reducer: {+ initial: () => 0,+ reduce: (count: number, event: { type: string }) =>+ event.type === "message.received" ? count + 1 : count,+ },+ });+ const sending = store.send({ message: "Hello" });+ await vi.waitFor(() =>+ expect(store.snapshot.conversation.messages[0]?.metadata?.optimistic).toBe(true),+ );+ expect(store.snapshot.data).toBe(0);+ const events = turnEvents().map((event) => ({+ ...event,+ meta: { ...event.meta, deliveryIds: ["delivery_1"] },+ }));+ for (const event of events) live.emit(event);+ await sending;+ expect(store.snapshot.data).toBe(1);+ expect(+ store.snapshot.conversation.messages.filter((message) => message.role === "user"),+ ).toHaveLength(1);+ expect(store.snapshot.conversation.messages[0]?.metadata?.optimistic).toBeUndefined();+ });+it("surfaces transport errors", async () => {vi.spyOn(globalThis, "fetch").mockRejectedValueOnce(new Error("Network failed"));const store = createStore({ reducer: defaultMessageReducer() });@@ -305,6 +367,7 @@ describe("EveAgentStore lifecycle", () => {store.reset();expect(store.snapshot.status).toBe("ready");expect(store.snapshot.data.messages).toEqual([]);+ expect(store.snapshot.conversation.messages).toEqual([]);expect(store.snapshot.error).toBeUndefined();expect(store.snapshot.events).toEqual([]);});@@ -344,6 +407,7 @@ describe("EveAgentStore lifecycle", () => {expect(store.snapshot.status).toBe("submitted");expect(store.snapshot.data).toEqual(["client.input.responded"]);+ expect(store.snapshot.conversation.inputs).toEqual({});start.resolve(startedResponse());await sending;@@ -353,6 +417,249 @@ describe("EveAgentStore lifecycle", () => {});});+describe("EveAgentStore held turns", () => {+ it("resolves a send where its open turn waits on a question and streams until the turn ends", async () => {+ const live = controlledStreamResponse();+ vi.spyOn(globalThis, "fetch")+ .mockResolvedValueOnce(live.response)+ .mockResolvedValueOnce(startedResponse("delivery_1"));+ const store = createStore({+ initialSession: { sessionId: "session_1", streamIndex: 0 },+ reducer: conversationReducer,+ });+ const sending = store.send({ message: "Ask the researcher about Alice's region." });+ const parked = stampTestEvents([+ createMessageReceivedEvent({+ message: "Ask the researcher about Alice's region.",+ sequence: 0,+ turnId: "turn_1",+ }),+ createTurnStartedEvent({ sequence: 0, turnId: "turn_1" }),+ createTaskStartedEvent({+ callId: "call_1",+ kind: "agent",+ name: "researcher",+ taskId: "task_1",+ turnId: "turn_1",+ }),+ createInputRequestedEvent({+ requests: [+ {+ action: { callId: "lookup", input: {}, kind: "tool-call", toolName: "lookup" },+ kind: "tool-approval",+ prompt: "Approve the researcher's lookup?",+ requestId: "req_1",+ },+ ],+ sequence: 0,+ stepIndex: 0,+ taskId: "task_1",+ turnId: "turn_1",+ }),+ createTurnWaitingEvent({ sequence: 0, turnId: "turn_1" }),+ ]).map((event) => ({ ...event, meta: { ...event.meta, deliveryIds: ["delivery_1"] } }));+ for (const event of parked) live.emit(event);+ await sending;+ expect(store.snapshot.status).toBe("streaming");+ expect(store.snapshot.data.turns.turn_1).toMatchObject({ status: "active", waiting: true });+ expect(store.snapshot.data.inputs.req_1).toMatchObject({ status: "open", taskId: "task_1" });++ const resumed = stampTestEvents([+ {+ type: "input.resolved",+ data: {+ resolutions: [{ kind: "tool-approval", outcome: "approved", requestId: "req_1" }],+ sequence: 0,+ stepIndex: 0,+ turnId: "turn_1",+ },+ },+ createTaskSettledEvent({+ callId: "call_1",+ output: "Alice works in the west region.",+ status: "completed",+ taskId: "task_1",+ turnId: "turn_1",+ }),+ createTurnCompletedEvent({ sequence: 1, turnId: "turn_1" }),+ createSessionWaitingEvent(),+ ]).map((event) => ({ ...event, meta: { ...event.meta, id: `resumed-${event.meta.id}` } }));+ live.emit(resumed[0]!);+ await vi.waitFor(() => expect(store.snapshot.data.inputs.req_1?.status).toBe("settled"));+ expect(store.snapshot.status).toBe("streaming");+ for (const event of resumed.slice(1)) live.emit(event);+ await vi.waitFor(() => expect(store.snapshot.status).toBe("ready"));+ });+});++describe("EveAgentStore agent-session following", () => {+ /** The root's history of one researcher call, already settled. */+ const researcherCall = (settled = true, ended = false) =>+ stampTestEvents([+ createTaskStartedEvent({+ callId: "call_1",+ kind: "agent",+ name: "research",+ taskId: "task_1",+ turnId: "turn_1",+ }),+ createAgentStartedEvent({+ callId: "call_1",+ name: "research",+ parentSessionId: "session_1",+ sessionId: "child_1",+ taskId: "task_1",+ turnId: "turn_1",+ }),+ ...(settled+ ? [+ createTaskSettledEvent({+ callId: "call_1",+ output: "Alice's notes are filed.",+ status: "completed",+ taskId: "task_1",+ turnId: "turn_1",+ }),+ ]+ : []),+ ...(ended+ ? [createTurnCompletedEvent({ sequence: 1, turnId: "turn_1" }), createSessionWaitingEvent()]+ : []),+ ]);++ /** The researcher session's reply to that call. */+ const researcherReply = (...deltas: string[]) =>+ stampTestEvents([+ createTurnStartedEvent({ sequence: 0, turnId: "child_turn" }),+ createMessageReceivedEvent({+ message: "File Alice's notes.",+ sequence: 0,+ turnId: "child_turn",+ }),+ ...deltas.map((messageDelta, sequence) =>+ createMessageAppendedEvent({ messageDelta, sequence, stepIndex: 0, turnId: "child_turn" }),+ ),+ createTurnCompletedEvent({ sequence: 1, turnId: "child_turn" }),+ ]);++ const childText = (conversation: ConversationState) => {+ const observation = conversation.agents.child_1?.observation;+ if (observation === undefined || observation.status === "not-followed") return undefined;+ return observation.conversation?.messages+ .flatMap((message) => (message.role === "assistant" ? message.parts : []))+ .flatMap((part) => (part.type === "text" ? [part.text] : []))+ .join("");+ };++ const childStore = (parent: readonly MessageStreamEvent[], followSubagents = true) =>+ createStore({+ host: "http://localhost",+ initialSession: { sessionId: "session_1", streamIndex: parent.length },+ initialEvents: parent,+ reducer: conversationReducer,+ followSubagents,+ });++ it("follows agent sessions from a streamed session without changing a custom view", async () => {+ const parent = researcherCall(true, true);+ vi.spyOn(globalThis, "fetch").mockImplementation(async (input) =>+ String(input).includes("child_1")+ ? streamResponse(researcherReply("Filed."))+ : boundedStreamResponse([], parent.length - 1),+ );+ const store = createStore({+ host: "http://localhost",+ initialSession: { sessionId: "session_1", streamIndex: parent.length },+ initialEvents: parent,+ followSubagents: true,+ reducer: { initial: () => 0, reduce: (count: number) => count + 1 },+ });+ const statuses: string[] = [];+ store.subscribe(() =>+ statuses.push(store.snapshot.conversation.agents.child_1?.observation.status ?? "missing"),+ );+ await store.resume();+ await vi.waitFor(() =>+ expect(store.snapshot.conversation.agents.child_1?.observation.status).toBe("idle"),+ );+ expect(store.snapshot.data).toBe(parent.length);+ expect(statuses).toContain("following");+ expect(childText(store.snapshot.conversation)).toBe("Filed.");+ });++ it("records agent sessions without subscribing when following is disabled", () => {+ const fetchMock = vi.spyOn(globalThis, "fetch");+ const store = childStore(researcherCall(), false);+ attachEveAgentStore(store);+ expect(store.snapshot.data.agents.child_1).toMatchObject({+ callId: "call_1",+ taskId: "task_1",+ observation: { status: "not-followed" },+ });+ expect(store.snapshot.data.tasks.task_1?.calls.call_1?.status).toBe("completed");+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it("resumes a partially observed session after detach without replaying its events", async () => {+ const parent = researcherCall();+ const reply = researcherReply("First ", "second");+ const first = controlledStreamResponse();+ const childCursors: number[] = [];+ vi.spyOn(globalThis, "fetch").mockImplementation(async (input) => {+ const url = new URL(String(input), "http://localhost");+ if (url.pathname.includes("child_1")) {+ const index = Number(url.searchParams.get("startIndex") ?? 0);+ childCursors.push(index);+ return index === 0 ? first.response : streamResponse(reply.slice(index));+ }+ return boundedStreamResponse([], 0);+ });+ const store = childStore(parent);+ attachEveAgentStore(store);+ await vi.waitFor(() => expect(childCursors).toEqual([0]));+ for (const event of reply.slice(0, 3)) first.emit(event);+ await vi.waitFor(() => expect(childText(store.snapshot.data)).toBe("First "));+ detachEveAgentStore(store);+ attachEveAgentStore(store);+ await vi.waitFor(() =>+ expect(store.snapshot.data.agents.child_1?.observation.status).toBe("idle"),+ );+ expect(childCursors).toEqual([0, 3]);+ expect(childText(store.snapshot.data)).toBe("First second");+ expect(store.snapshot.events).toEqual(parent);+ detachEveAgentStore(store);+ attachEveAgentStore(store);+ await new Promise((resolve) => setTimeout(resolve, 10));+ expect(childCursors).toEqual([0, 3]);+ });++ it("keeps followed session detail through optimistic root reconciliation", async () => {+ const parent = researcherCall(false);+ const live = controlledStreamResponse();+ vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => {+ if (String(input).includes("child_1")) return streamResponse(researcherReply("Filed."));+ if (init?.method === "POST") return startedResponse("delivery_1");+ return live.response;+ });+ const store = childStore(parent);+ attachEveAgentStore(store);+ await vi.waitFor(() => expect(childText(store.snapshot.data)).toBe("Filed."));+ const sending = store.send({ message: "New question" });+ const confirmation = stampTestEvents([+ createMessageReceivedEvent({ message: "New question", sequence: 1, turnId: "turn_2" }),+ createSessionWaitingEvent(),+ ]).map((event, index) => ({+ ...event,+ meta: { ...event.meta, id: `confirmation_${index}`, deliveryIds: ["delivery_1"] },+ }));+ for (const event of confirmation) live.emit(event);+ await sending;+ expect(childText(store.snapshot.data)).toBe("Filed.");+ expect(store.snapshot.data.agents.child_1?.observation.status).toBe("following");+ expect(store.snapshot.events).toEqual([...parent, ...confirmation]);+ });+});+describe("EveAgentStore prewarming", () => {it("settles a send aborted during preparation without creating a session", async () => {const fetchMock = vi.spyOn(globalThis, "fetch");@@ -596,94 +903,6 @@ describe("EveAgentStore prewarming", () => {expect(store.snapshot.session?.streamIndex).toBe(6);});- it("keeps following an unsolicited turn after a refused approval returns to waiting", async () => {- const live = controlledStreamResponse();- const fetchMock = vi- .spyOn(globalThis, "fetch")- .mockResolvedValueOnce(live.response)- .mockResolvedValueOnce(startedResponse("approval-delivery"));- const initialEvents = stampTestEvents([- createInputRequestedEvent({- requests: [- {- action: { kind: "tool-call", callId: "save-note", toolName: "save_note", input: {} },- kind: "tool-approval",- requestId: "approval-1",- prompt: "Approve Alice's note?",- },- ],- sequence: 0,- stepIndex: 0,- turnId: "turn-note",- }),- createSessionWaitingEvent(),- ]);- const store = createStore({- initialSession: { sessionId: "session_1", streamIndex: initialEvents.length },- initialEvents,- reducer: defaultMessageReducer(),- });- const onEvent = vi.fn();- store.setCallbacks({ onEvent });- const sending = store.send({- inputResponses: [{ requestId: "approval-1", optionId: "approve" }],- });- await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));- const refusal = stampTestEvents([- createApprovalCandidateEvent({- candidateId: "alice-attempt",- requestId: "approval-1",- responderPrincipalId: "alice",- outcome: "rejected",- sequence: 0,- stepIndex: 0,- turnId: "turn-note",- }),- createSessionWaitingEvent(),- ]).map((event) => ({- ...event,- meta: { ...event.meta, id: `refusal-${event.meta.id}`, deliveryIds: ["approval-delivery"] },- }));- for (const event of refusal) live.emit(event);- await sending;- expect(store.snapshot.status).toBe("ready");- expect(store.snapshot.data.messages.flatMap((message) => message.parts)).toEqual(- expect.arrayContaining([- expect.objectContaining({ type: "dynamic-tool", state: "approval-requested" }),- ]),- );-- const unsolicited = stampTestEvents([- createTurnStartedEvent({ sequence: 1, turnId: "turn-report" }),- createMessageCompletedEvent({- finishReason: "stop",- message: "Bob's report is complete.",- sequence: 1,- stepIndex: 0,- turnId: "turn-report",- }),- createSessionWaitingEvent(),- ]).map((event) => ({- ...event,- meta: { ...event.meta, id: `unsolicited-${event.meta.id}`, deliveryIds: ["report-delivery"] },- }));- live.emit(unsolicited[0]!);- await vi.waitFor(() => expect(store.snapshot.status).toBe("streaming"));- for (const event of unsolicited.slice(1)) live.emit(event);- await vi.waitFor(() =>- expect(store.snapshot.events).toEqual([...initialEvents, ...refusal, ...unsolicited]),- );- expect(store.snapshot.status).toBe("ready");- expect(store.snapshot.data.messages.flatMap((message) => message.parts)).toEqual(- expect.arrayContaining([- expect.objectContaining({ type: "text", text: "Bob's report is complete." }),- ]),- );- expect(onEvent).toHaveBeenCalledTimes(5);- expect(fetchMock).toHaveBeenCalledTimes(2);- expect(fetchMock.mock.calls[0]![1]?.signal?.aborted).toBe(false);- });-it("projects an unsolicited turn that arrives while another message is being accepted", async () => {const live = controlledStreamResponse();const accepted = Promise.withResolvers<Response>();@@ -811,8 +1030,6 @@ describe("EveAgentStore prewarming", () => {describe("EveAgentStore stream overlap", () => {it("reconstructs a split message across an in-memory stream reconnect", async () => {- useFakeBackoffClock();- fastForwardTimers();const events = streamingTurnEvents();const fetchMock = vi.spyOn(globalThis, "fetch")@@ -830,12 +1047,14 @@ describe("EveAgentStore stream overlap", () => {expect(streamingText).toContain("Hel");expect(streamingText).toContain("Hello");- expect(store.snapshot.data.messages.at(-1)?.parts).toContainEqual({- state: "done",- stepIndex: 0,- text: "Hello",- type: "text",- });+ expect(store.snapshot.data.messages.at(-1)?.parts).toContainEqual(+ expect.objectContaining({+ state: "done",+ stepIndex: 0,+ text: "Hello",+ type: "text",+ }),+ );expect(fetchMock.mock.calls.slice(1)@@ -848,8 +1067,6 @@ describe("EveAgentStore stream overlap", () => {it.each(["21", "24"] as const)("reconstructs a split message across a v%s-to-v25 reconnect",async (legacyVersion) => {- useFakeBackoffClock();- fastForwardTimers();const current = streamingTurnEvents();const received = current[0]!;const started = current[1]!;@@ -887,12 +1104,14 @@ describe("EveAgentStore stream overlap", () => {expect(streamingText).toContain("Hel");expect(streamingText).toContain("Hello");- expect(store.snapshot.data.messages.at(-1)?.parts).toContainEqual({- state: "done",- stepIndex: 0,- text: "Hello",- type: "text",- });+ expect(store.snapshot.data.messages.at(-1)?.parts).toContainEqual(+ expect.objectContaining({+ state: "done",+ stepIndex: 0,+ text: "Hello",+ type: "text",+ }),+ );expect(fetchMock.mock.calls.slice(1)@@ -959,7 +1178,13 @@ describe("EveAgentStore stream overlap", () => {expect(assistant).toHaveLength(1);expect(assistant[0]?.parts).toEqual([{ type: "step-start" },- { state: "done", stepIndex: 0, text: "Hi there.", type: "text" },+ {+ id: expect.stringMatching(/^evt_/),+ state: "done",+ stepIndex: 0,+ text: "Hi there.",+ type: "text",+ },]);});@@ -981,7 +1206,13 @@ describe("EveAgentStore stream overlap", () => {const assistant = store.snapshot.data.messages.find((message) => message.role === "assistant");expect(assistant?.parts).toEqual([{ type: "step-start" },- { state: "done", stepIndex: 0, text: "Legacy response.", type: "text" },+ {+ id: "turn_legacy:assistant:text:1",+ state: "done",+ stepIndex: 0,+ text: "Legacy response.",+ type: "text",+ },]);});@@ -1140,41 +1371,6 @@ describe("EveAgentStore session resume", () => {},);- it("publishes a replayed session once after catch-up instead of once per event", async () => {- // Regression for #3862: a notification per replayed event forces one React commit per- // event inside a single task, which trips React's nested update limit past ~50 events.- const events = stampTestEvents(- Array.from({ length: 25 }, (_, index) => [- createMessageReceivedEvent({- message: `Question ${index}`,- sequence: 0,- turnId: `turn_${index}`,- }),- createMessageCompletedEvent({- finishReason: "stop",- message: `Answer ${index}`,- sequence: 1,- stepIndex: 0,- turnId: `turn_${index}`,- }),- createSessionWaitingEvent(),- ]).flat() as UnstampedMessageStreamEvent[],- );- vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(boundedStreamResponse(events));- const store = createStore({- initialSession: { sessionId: "session_1", streamIndex: events.length },- reducer: defaultMessageReducer(),- });- const published: string[] = [];- store.subscribe(() => {- published.push(`${store.snapshot.status}:${store.snapshot.events.length}`);- });-- await store.resume();-- expect(published).toEqual(["resuming:0", `ready:${events.length}`]);- });-it("finishes a settled replay without waiting for the probe stream to idle", async () => {const events = turnEvents();const probe = controlledStreamResponse();@@ -1194,8 +1390,6 @@ describe("EveAgentStore session resume", () => {});it("continues a split message from a complete hydrated prefix", async () => {- useFakeBackoffClock();- fastForwardTimers();const events = streamingTurnEvents();const prefix = events.slice(0, 3);const fetchMock = vi@@ -1221,17 +1415,17 @@ describe("EveAgentStore session resume", () => {),).toBe(String(prefix.length));expect(streamingText).toContain("Hello");- expect(store.snapshot.data.messages.at(-1)?.parts).toContainEqual({- state: "done",- stepIndex: 0,- text: "Hello",- type: "text",- });+ expect(store.snapshot.data.messages.at(-1)?.parts).toContainEqual(+ expect.objectContaining({+ state: "done",+ stepIndex: 0,+ text: "Hello",+ type: "text",+ }),+ );});it("replays a split message from index zero when only its cursor was retained", async () => {- useFakeBackoffClock();- fastForwardTimers();const events = streamingTurnEvents();const fetchMock = vi.spyOn(globalThis, "fetch")@@ -1255,12 +1449,14 @@ describe("EveAgentStore session resume", () => {),).toBeNull();expect(streamingText).toContain("Hello");- expect(store.snapshot.data.messages.at(-1)?.parts).toContainEqual({- state: "done",- stepIndex: 0,- text: "Hello",- type: "text",- });+ expect(store.snapshot.data.messages.at(-1)?.parts).toContainEqual(+ expect.objectContaining({+ state: "done",+ stepIndex: 0,+ text: "Hello",+ type: "text",+ }),+ );});it("keeps a settled hydrated snapshot resuming until catch-up returns ready", async () => {@@ -1315,7 +1511,6 @@ describe("EveAgentStore session resume", () => {});it("moves an unsettled hydrated snapshot to streaming before following it", async () => {- useFakeBackoffClock();const [received, started, completed, waiting] = stampTestEvents([createMessageReceivedEvent({ message: "Hello", sequence: 0, turnId: "turn_1" }),createTurnStartedEvent({ sequence: 1, turnId: "turn_1" }),@@ -1352,7 +1547,6 @@ describe("EveAgentStore session resume", () => {live.emit(completed!);live.emit(waiting!);live.close();- fastForwardTimers();await resuming;expect(store.snapshot.status).toBe("ready");@@ -1461,12 +1655,14 @@ describe("EveAgentStore session resume", () => {"message.completed","session.waiting",]);- expect(store.snapshot.data.messages.at(-1)?.parts).toContainEqual({- state: "done",- stepIndex: 0,- text: "A second reply.",- type: "text",- });+ expect(store.snapshot.data.messages.at(-1)?.parts).toContainEqual(+ expect.objectContaining({+ state: "done",+ stepIndex: 0,+ text: "A second reply.",+ type: "text",+ }),+ );});it("reads past intermediate boundaries before following the latest turn", async () => {@@ -1500,11 +1696,113 @@ describe("EveAgentStore session resume", () => {expect(store.snapshot.session?.streamIndex).toBe(events.length);});- it("keeps following when catch-up ends with pending authorization", async () => {- const events = stampTestEvents([- createMessageReceivedEvent({ message: "Hello", sequence: 0, turnId: "turn_1" }),- createMessageCompletedEvent({- finishReason: "stop",+ it("settles callback authorization independently of the custom view", async () => {+ const [required, waiting, completed, settled] = stampTestEvents([+ createAuthorizationRequiredEvent({+ attemptId: "attempt_1",+ description: "Linear",+ name: "linear",+ sequence: 0,+ stepIndex: 0,+ turnId: "turn_1",+ webhookUrl: "https://agent.example.com/callback",+ }),+ createSessionWaitingEvent(),+ createAuthorizationCompletedEvent({+ attemptId: "attempt_1",+ name: "linear",+ outcome: "authorized",+ sequence: 1,+ stepIndex: 0,+ turnId: "turn_1",+ }),+ createSessionWaitingEvent(),+ ] as UnstampedMessageStreamEvent[]);+ const live = controlledStreamResponse();+ live.response.headers.set("x-eve-stream-tail-index", "1");+ vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(live.response);+ const store = createStore({+ initialSession: { sessionId: "session_1", streamIndex: 0 },+ reducer: { initial: () => 0, reduce: (count: number) => count + 1 },+ });+ const resuming = store.resume();+ live.emit(required!);+ live.emit(waiting!);+ await vi.waitFor(() => expect(store.snapshot.status).toBe("streaming"));+ expect(store.snapshot.data).toBe(2);+ expect(store.snapshot.conversation.messages[0]?.parts).toContainEqual(+ expect.objectContaining({ awaitsCallback: true, state: "required", type: "authorization" }),+ );+ live.emit(completed!);+ live.emit(settled!);+ await resuming;+ expect(store.snapshot.status).toBe("ready");+ expect(store.snapshot.data).toBe(4);+ });++ it("keeps a custom view streaming until both same-name callback attempts settle", async () => {+ const [first, second, waiting, firstCompleted, stillWaiting, secondCompleted, settled] =+ stampTestEvents([+ ...["first", "second"].map((attemptId, sequence) =>+ createAuthorizationRequiredEvent({+ attemptId,+ description: "Linear",+ name: "linear",+ sequence,+ stepIndex: 0,+ turnId: "turn_1",+ webhookUrl: `https://agent.example.com/callback/${attemptId}`,+ }),+ ),+ createSessionWaitingEvent(),+ createAuthorizationCompletedEvent({+ attemptId: "first",+ name: "linear",+ outcome: "authorized",+ sequence: 2,+ stepIndex: 0,+ turnId: "turn_1",+ }),+ createSessionWaitingEvent(),+ createAuthorizationCompletedEvent({+ attemptId: "second",+ name: "linear",+ outcome: "authorized",+ sequence: 3,+ stepIndex: 0,+ turnId: "turn_1",+ }),+ createSessionWaitingEvent(),+ ] as UnstampedMessageStreamEvent[]);+ const live = controlledStreamResponse();+ live.response.headers.set("x-eve-stream-tail-index", "2");+ vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(live.response);+ const store = createStore({+ initialSession: { sessionId: "session_1", streamIndex: 0 },+ reducer: { initial: () => 0, reduce: (count: number) => count + 1 },+ });+ const resuming = store.resume();+ for (const event of [first, second, waiting]) live.emit(event!);+ await vi.waitFor(() => expect(store.snapshot.status).toBe("streaming"));+ for (const event of [firstCompleted, stillWaiting]) live.emit(event!);+ await vi.waitFor(() => expect(store.snapshot.events).toHaveLength(5));+ expect(store.snapshot.status).toBe("streaming");+ expect(+ store.snapshot.conversation.messages.flatMap((message) =>+ message.parts.filter((part) => part.type === "authorization" && part.state === "required"),+ ),+ ).toHaveLength(1);+ for (const event of [secondCompleted, settled]) live.emit(event!);+ await resuming;+ expect(store.snapshot.status).toBe("ready");+ expect(store.snapshot.data).toBe(7);+ });++ it("keeps following when catch-up ends with pending authorization", async () => {+ const events = stampTestEvents([+ createMessageReceivedEvent({ message: "Hello", sequence: 0, turnId: "turn_1" }),+ createMessageCompletedEvent({+ finishReason: "stop",message: "Hi there.",sequence: 1,stepIndex: 0,@@ -1547,7 +1845,6 @@ describe("EveAgentStore session resume", () => {});it("replays history and follows an interrupted turn through its boundary", async () => {- useFakeBackoffClock();const [received, started, completed, waiting] = stampTestEvents([createMessageReceivedEvent({ message: "Hello", sequence: 0, turnId: "turn_1" }),createTurnStartedEvent({ sequence: 1, turnId: "turn_1" }),@@ -1584,22 +1881,115 @@ describe("EveAgentStore session resume", () => {live.emit(completed!);live.emit(waiting!);live.close();- fastForwardTimers();await resuming;expect(store.snapshot.status).toBe("ready");- expect(store.snapshot.data.messages.at(-1)?.parts).toContainEqual({- state: "done",- stepIndex: 0,- text: "Hi there.",- type: "text",- });+ expect(store.snapshot.data.messages.at(-1)?.parts).toContainEqual(+ expect.objectContaining({+ state: "done",+ stepIndex: 0,+ text: "Hi there.",+ type: "text",+ }),+ );expect(new URL(requests[0]!, "http://localhost").searchParams.get("startIndex")).toBeNull();expect(new URL(requests[1]!, "http://localhost").searchParams.get("startIndex")).toBe("2");});});describe("EveAgentStore steering", () => {+ it("answers an approval while a turn is active and settles it through that turn", async () => {+ const live = controlledStreamResponse();+ const fetchMock = vi+ .spyOn(globalThis, "fetch")+ .mockResolvedValueOnce(startedResponse())+ .mockResolvedValueOnce(live.response)+ .mockResolvedValueOnce(startedResponse("delivery_2"));+ const store = createStore({ reducer: defaultMessageReducer() });+ const first = store.send({ message: "Alice asks for two colors" });+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));+ live.emit(colorApprovalRequested("color-a"));+ await vi.waitFor(() =>+ expect(store.snapshot.conversation.inputs["color-a"]?.status).toBe("open"),+ );++ const answering = store.send({+ inputResponses: [{ requestId: "color-a", optionId: "approve" }],+ });+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(3));+ expect(JSON.parse(String(fetchMock.mock.calls[2]![1]!.body))).toMatchObject({+ inputResponses: [{ requestId: "color-a", optionId: "approve" }],+ });+ expect(store.snapshot.conversation.inputs["color-a"]?.status).toBe("responded");+ await expect(+ store.send({ inputResponses: [{ requestId: "color-a", optionId: "approve" }] }),+ ).rejects.toThrow("Input request color-a was already answered.");+ expect(fetchMock).toHaveBeenCalledTimes(3);++ live.emit(+ stampTestEvent(+ createApprovalSettledEvent({+ outcome: "approved",+ requestId: "color-a",+ responderPrincipalId: "alice",+ sequence: 1,+ stepIndex: 0,+ turnId: "turn_1",+ }),+ 1,+ ),+ );+ live.emit(stampTestEvent(createSessionWaitingEvent(), 2));+ await Promise.all([first, answering]);+ expect(store.snapshot.status).toBe("ready");+ expect(store.snapshot.conversation.inputs["color-a"]?.status).toBe("settled");+ });++ it("leaves a request answerable when its answer never reaches the server", async () => {+ vi.spyOn(globalThis, "fetch").mockImplementation(async (_request, init) => {+ if (init?.method === "POST") throw new TypeError("fetch failed");+ return streamResponse([]);+ });+ const store = createStore({+ initialEvents: [colorApprovalRequested("color-a")],+ initialSession: { sessionId: "session_1", streamIndex: 1 },+ reducer: defaultMessageReducer(),+ });++ await store.send({ inputResponses: [{ requestId: "color-a", optionId: "approve" }] });+ expect(store.snapshot.error?.message).toBe("fetch failed");+ expect(store.snapshot.conversation.inputs["color-a"]?.status).toBe("open");+ });++ it("steers a first turn that is still creating its session", async () => {+ const live = controlledStreamResponse();+ const created = Promise.withResolvers<Response>();+ const fetchMock = vi+ .spyOn(globalThis, "fetch")+ .mockReturnValueOnce(created.promise)+ .mockResolvedValueOnce(live.response)+ .mockResolvedValueOnce(startedResponse("delivery_2"));+ const store = createStore({ reducer: defaultMessageReducer() });+ const first = store.send({ message: "Write Alice a story." });+ const steering = store.send({ message: "Make it short.", turnPolicy: "steer" });+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledOnce());++ created.resolve(startedResponse());+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(3));+ expect(JSON.parse(String(fetchMock.mock.calls[2]![1]!.body))).toMatchObject({+ message: "Make it short.",+ turnPolicy: "steer",+ });+ for (const event of turnEvents()) live.emit(event);+ for (const event of turnEvents())+ live.emit({+ ...event,+ meta: { ...event.meta, id: `steer-${event.meta.id}`, deliveryIds: ["delivery_2"] },+ });+ await Promise.all([first, steering]);+ expect(store.snapshot.status).toBe("ready");+ });+it("prepares a steering message once when the active turn finishes during preparation", async () => {const live = controlledStreamResponse();const fetchMock = vi@@ -1662,6 +2052,49 @@ describe("EveAgentStore steering", () => {expect(store.snapshot.error).toBeUndefined();});+ it("keeps a failed steered send ahead of the active reply after replay", async () => {+ const active = controlledStreamResponse();+ const failedSend = Promise.withResolvers<Response>();+ const fetchMock = vi+ .spyOn(globalThis, "fetch")+ .mockResolvedValueOnce(startedResponse())+ .mockResolvedValueOnce(active.response)+ .mockReturnValueOnce(failedSend.promise);+ const store = createStore({ reducer: defaultMessageReducer() });+ const first = store.send({ message: "First" });+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));+ const events = stampTestEvents([+ createTurnStartedEvent({ sequence: 0, turnId: "turn_1" }),+ createMessageReceivedEvent({ message: "First", sequence: 1, turnId: "turn_1" }),+ createMessageCompletedEvent({+ finishReason: "stop",+ message: "Reply",+ sequence: 2,+ stepIndex: 0,+ turnId: "turn_1",+ }),+ createSessionWaitingEvent(),+ ]);+ for (const event of events.slice(0, 3)) active.emit(event);+ await vi.waitFor(() =>+ expect(store.snapshot.data.messages.some((message) => message.role === "assistant")).toBe(+ true,+ ),+ );+ const steering = store.send({ message: "Second", turnPolicy: "steer" });+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(3));+ failedSend.reject(new Error("Steering failed"));+ await expect(steering).rejects.toThrow("Steering failed");+ expect(store.snapshot.data.messages.map((message) => message.role)).toEqual([+ "user",+ "user",+ "assistant",+ ]);+ expect(store.snapshot.data.messages[1]?.metadata?.status).toBe("failed");+ active.emit(events[3]!);+ await first;+ });+it.each([true, false])("completes steering received in the active turn (optimistic=%s)",async (optimistic) => {@@ -1703,6 +2136,62 @@ describe("EveAgentStore steering", () => {},);+ it.each([true, false])(+ "groups a late steered message before its turn's assistant response (optimistic=%s)",+ async (optimistic) => {+ const activeStream = controlledStreamResponse();+ const events = stampTestEvents([+ createMessageReceivedEvent({ message: "First", sequence: 0, turnId: "turn_1" }),+ createTurnStartedEvent({ sequence: 1, turnId: "turn_1" }),+ createMessageCompletedEvent({+ finishReason: "stop",+ message: "Reply",+ sequence: 2,+ stepIndex: 0,+ turnId: "turn_1",+ }),+ createMessageReceivedEvent({ message: "Second", sequence: 3, turnId: "turn_1" }),+ createSessionWaitingEvent(),+ ] as UnstampedMessageStreamEvent[]).map((event, index) => ({+ ...event,+ meta: { ...event.meta, deliveryIds: [index === 3 ? "second" : "first"] },+ }));+ const fetchMock = vi+ .spyOn(globalThis, "fetch")+ .mockResolvedValueOnce(startedResponse("first"))+ .mockResolvedValueOnce(activeStream.response)+ .mockResolvedValueOnce(startedResponse("second"));+ const store = createStore({ optimistic, reducer: defaultMessageReducer() });+ const initial = store.send({ message: "First" });+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));+ for (const event of events.slice(0, 3)) activeStream.emit(event);+ await vi.waitFor(() => expect(store.snapshot.events).toHaveLength(3));+ const followUp = store.send({ message: "Second", turnPolicy: "steer" });+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(3));+ if (optimistic) {+ expect(store.snapshot.data.messages.map((message) => message.role)).toEqual([+ "user",+ "user",+ "assistant",+ ]);+ expect(store.snapshot.data.messages[1]?.metadata?.optimistic).toBe(true);+ }+ for (const event of events.slice(3)) activeStream.emit(event);+ await Promise.all([initial, followUp]);+ expect(store.snapshot.data.messages.map((message) => message.role)).toEqual([+ "user",+ "user",+ "assistant",+ ]);+ expect(store.snapshot.data.messages[1]?.parts).toContainEqual({+ state: "done",+ text: "Second",+ type: "text",+ });+ activeStream.close();+ },+ );+it("settles steering whose delivery event arrives before its response", async () => {const activeStream = controlledStreamResponse();const steeringAccepted = Promise.withResolvers<Response>();@@ -1752,6 +2241,63 @@ describe("EveAgentStore steering", () => {);});+ it("follows a late steering delivery across its sign-in callback", async () => {+ const activeStream = controlledStreamResponse();+ const events = stampTestEvents([+ createMessageReceivedEvent({ message: "First", sequence: 0, turnId: "turn_1" }),+ createTurnStartedEvent({ sequence: 1, turnId: "turn_1" }),+ createSessionWaitingEvent(),+ createMessageReceivedEvent({ message: "Use Linear", sequence: 0, turnId: "turn_2" }),+ createTurnStartedEvent({ sequence: 1, turnId: "turn_2" }),+ createAuthorizationRequiredEvent({+ attemptId: "attempt_1",+ description: "Linear",+ name: "linear",+ sequence: 2,+ stepIndex: 0,+ turnId: "turn_2",+ webhookUrl: "https://agent.example.com/callback",+ }),+ createSessionWaitingEvent(),+ createAuthorizationCompletedEvent({+ attemptId: "attempt_1",+ name: "linear",+ outcome: "authorized",+ sequence: 3,+ stepIndex: 0,+ turnId: "turn_2",+ }),+ createSessionWaitingEvent(),+ ] as UnstampedMessageStreamEvent[]).map((event, index) => ({+ ...event,+ meta: { ...event.meta, deliveryIds: [index < 3 ? "first-delivery" : "delivery_1"] },+ }));+ const fetchMock = vi+ .spyOn(globalThis, "fetch")+ .mockResolvedValueOnce(startedResponse("first-delivery"))+ .mockResolvedValueOnce(activeStream.response)+ .mockResolvedValueOnce(startedResponse());+ const store = createStore({ reducer: defaultMessageReducer() });++ const firstSend = store.send({ message: "First" });+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));+ activeStream.emit(events[0]!);+ activeStream.emit(events[1]!);+ const steering = store.send({ message: "Use Linear", turnPolicy: "steer" });+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(3));+ let settled = false;+ const finished = Promise.all([firstSend, steering]).then(() => {+ settled = true;+ });+ for (const event of events.slice(2, 7)) activeStream.emit(event);+ await vi.waitFor(() => expect(store.snapshot.events).toHaveLength(7));+ expect(settled).toBe(false);++ for (const event of events.slice(7)) activeStream.emit(event);+ await finished;+ expect(store.snapshot.status).toBe("ready");+ });+it("follows a late steering delivery after the active turn settles", async () => {const activeStream = controlledStreamResponse();const [@@ -1833,12 +2379,14 @@ describe("EveAgentStore steering", () => {secondCompleted,secondWaiting,]);- expect(store.snapshot.data.messages.at(-1)?.parts).toContainEqual({- state: "done",- stepIndex: 0,- text: "Follow-up reply.",- type: "text",- });+ expect(store.snapshot.data.messages.at(-1)?.parts).toContainEqual(+ expect.objectContaining({+ state: "done",+ stepIndex: 0,+ text: "Follow-up reply.",+ type: "text",+ }),+ );});});@@ -1962,3 +2510,160 @@ describe("EveAgentStore cancellation", () => {expect(store.snapshot.status).toBe("ready");});});++describe("EveAgentStore session controls", () => {+ const initialSession = { sessionId: "session_1", streamIndex: 0 };++ it("echoes a message while caller preparation is still pending", async () => {+ vi.spyOn(globalThis, "fetch");+ const store = createStore({ reducer: conversationReducer, host: "http://localhost:3000" });+ const preparation = Promise.withResolvers<never>();+ store.setCallbacks({ prepareSend: () => preparation.promise });+ const controller = new AbortController();+ const send = store.send({ message: "Ask Bob about the release.", signal: controller.signal });++ expect(store.snapshot.status).toBe("submitted");+ expect(store.snapshot.conversation.messages).toEqual([+ expect.objectContaining({+ role: "user",+ metadata: expect.objectContaining({ optimistic: true }),+ parts: [expect.objectContaining({ text: "Ask Bob about the release." })],+ }),+ ]);+ controller.abort();+ await send;+ });++ it("re-echoes a payload that preparation replaced, for both kinds of turn", async () => {+ const approval = (requestId: string) => ({+ action: {+ callId: `call_${requestId}`,+ input: {},+ kind: "tool-call" as const,+ toolName: "save",+ },+ kind: "tool-approval" as const,+ prompt: "Save Alice's notes?",+ requestId,+ });+ const initialEvents = stampTestEvents([+ createInputRequestedEvent({+ requests: [approval("req_1"), approval("req_2")],+ sequence: 0,+ stepIndex: 0,+ turnId: "turn_1",+ }),+ createSessionWaitingEvent(),+ ]);+ vi.spyOn(globalThis, "fetch").mockImplementation(async (_input, init) =>+ init?.method === "POST"+ ? new Promise<Response>((_resolve, reject) =>+ init.signal?.addEventListener("abort", () => reject(init.signal?.reason), {+ once: true,+ }),+ )+ : controlledStreamResponse().response,+ );+ const store = createStore({+ reducer: conversationReducer,+ host: "http://localhost:3000",+ initialEvents,+ initialSession: { sessionId: "session_1", streamIndex: initialEvents.length },+ });+ const optimisticText = () =>+ store.snapshot.conversation.messages.flatMap((message) =>+ message.metadata?.optimistic === true+ ? message.parts.flatMap((part) => (part.type === "text" ? [part.text] : []))+ : [],+ );+ store.setCallbacks({+ prepareSend: (input) =>+ input.message === undefined+ ? { message: "Bob will decide instead.", turnPolicy: "steer" }+ : { inputResponses: [{ optionId: "approve", requestId: "req_1" }] },+ });++ const first = store.send({ message: "Approve the first save." });+ await vi.waitFor(() =>+ expect(store.snapshot.conversation.inputs.req_1?.status).toBe("responded"),+ );+ expect(optimisticText()).toEqual([]);++ const second = store.send({ inputResponses: [{ optionId: "approve", requestId: "req_2" }] });+ await vi.waitFor(() => expect(optimisticText()).toEqual(["Bob will decide instead."]));+ expect(store.snapshot.conversation.inputs.req_2?.status).toBe("open");+ detachEveAgentStore(store);+ await Promise.allSettled([first, second]);+ });++ it("reports compaction and clearing without a session instead of sending requests", async () => {+ const fetchMock = vi.spyOn(globalThis, "fetch");+ const store = createStore({ reducer: conversationReducer, host: "http://localhost:3000" });++ await expect(store.compact()).resolves.toEqual({ status: "no_active_session" });+ await expect(store.clear()).resolves.toEqual({ status: "no_active_session" });+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it("compacts the current session through the configured client", async () => {+ const fetchMock = vi+ .spyOn(globalThis, "fetch")+ .mockResolvedValue(Response.json({ ok: true, sessionId: "session_1", status: "accepted" }));+ const store = createStore({+ reducer: conversationReducer,+ client: new Client({ host: "http://agent.example.com" }),+ initialSession,+ });++ await expect(store.compact()).resolves.toEqual({ sessionId: "session_1", status: "accepted" });+ expect(String(fetchMock.mock.calls[0]![0])).toBe(+ "http://agent.example.com/eve/v1/session/session_1/compact",+ );+ });++ it("retires the server session before the next send starts fresh", async () => {+ vi.spyOn(globalThis, "fetch").mockResolvedValue(+ Response.json({ ok: true, previousSessionId: "session_1", status: "reset" }),+ );+ const store = createStore({+ reducer: conversationReducer,+ host: "http://localhost:3000",+ initialSession,+ initialEvents: turnEvents(),+ });++ await expect(store.retire()).resolves.toEqual({+ previousSessionId: "session_1",+ status: "reset",+ });+ expect(store.snapshot.session).toBeUndefined();+ expect(store.snapshot.conversation.messages).toEqual([]);+ });++ it("keeps the session and conversation when retiring fails", async () => {+ vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response("unavailable", { status: 503 }));+ const store = createStore({+ reducer: conversationReducer,+ host: "http://localhost:3000",+ initialSession,+ initialEvents: turnEvents(),+ });++ await expect(store.retire()).rejects.toThrow();+ expect(store.snapshot.session?.sessionId).toBe("session_1");+ expect(store.snapshot.conversation.messages).not.toEqual([]);+ });++ it("leaves a caller-supplied session to its owner instead of retiring it", async () => {+ const fetchMock = vi.spyOn(globalThis, "fetch");+ const store = createStore({+ reducer: conversationReducer,+ session: new Client({ host: "http://localhost:3000" }).sessions.attach("session_1"),+ initialEvents: turnEvents(),+ });++ await expect(store.retire()).rejects.toThrow("retire() needs a store-owned session");+ expect(fetchMock).not.toHaveBeenCalled();+ expect(store.snapshot.conversation.messages).not.toEqual([]);+ });+});diff --git a/packages/eve/src/client/eve-agent-store.ts b/packages/eve/src/client/eve-agent-store.tsindex 231b57b76..01230be7a 100644--- a/packages/eve/src/client/eve-agent-store.ts+++ b/packages/eve/src/client/eve-agent-store.ts@@ -12,33 +12,42 @@ import {getMessageResponseDeliveryId,type MessageResponse,} from "#client/message-response.js";-import {+import type {+ SessionEventReader,SessionEventStream,- type SessionEventReader,- type SessionEventStreamOptions,+ SessionEventStreamOptions,} from "#client/session-event-stream.js";import { EveAgentProjection } from "#client/eve-agent-projection.js";import { OptimisticMessageSubmissions } from "#client/optimistic-message-submissions.js";+import { ConversationClient } from "#client/conversation-client.js";import type { ClientSession } from "#client/session.js";-import { createEventDeduper } from "#protocol/event-dedupe.js";+import { dispatchSessionTurn } from "#client/session-turn-dispatch.js";import type { MessageStreamEvent } from "#protocol/message.js";import {+ activeTurnForOptimisticFollowUp,+ assertAnswerable,assertExclusiveTurnInput,+ assertInFlightFollowUp,+ validateFollowUp,+ countFollowUpDeliveries,createAbortSignal,createActiveTurn,followSteeredTurns,isAbortError,+ isResponseBoundary,isSettledSessionTail,+ settledStatus,toTerminalStreamFailureError,waitWithSignal,} from "#client/eve-agent-store-helpers.js";-import {- isTurnSegmentBoundary,- updatePendingAuthorizations,- updatePendingInputRequests,-} from "#client/session-utils.js";import { toError } from "#shared/errors.js";-import type { CancelSessionResult, SendTurnPayload } from "#client/types.js";+import type {+ CancelSessionResult,+ ClearResult,+ CompactResult,+ ResetResult,+ SendTurnPayload,+} from "#client/types.js";export type {EveAgentStoreCallbacks,@@ -60,22 +69,15 @@ export class EveAgentStore<TData> {readonly #client: Client | undefined;readonly #autoPrewarm: boolean;#attached = false;- #stream: SessionEventStream | undefined;- readonly #pendingAuthorizations = new Set<string>();- readonly #pendingInputRequests = new Set<string>();+ readonly #conversationClient: ConversationClient<TData>;+ readonly #followChildStreams: boolean;readonly #externalSession: boolean;- readonly #optimistic: boolean;- readonly #projection: EveAgentProjection<TData>;readonly #subscribers = new Set<() => void>();-- /** Ids already folded into the projection: `initialEvents` and a reconnect can overlap. */- #seenEvents = createEventDeduper();-#activeTurn: ActiveTurn | undefined;#callbacks: EveAgentStoreCallbacks<TData> = {};#error: Error | undefined;#events: readonly MessageStreamEvent[];- readonly #messageSubmissions: OptimisticMessageSubmissions<TData>;+ readonly #messageSubmissions: OptimisticMessageSubmissions;#prewarmGeneration = 0;#prewarmPromise: Promise<void> | undefined;#prewarmController: AbortController | undefined;@@ -86,25 +88,28 @@ export class EveAgentStore<TData> {constructor(init: EveAgentStoreInit<TData>) {this.#autoPrewarm = init.prewarm ?? false;+ this.#followChildStreams = init.followSubagents ?? false;this.#externalSession = init.session !== undefined;this.#client = this.#externalSession? undefined- : new Client({+ : (init.client ??+ new Client({auth: init.auth,headers: init.headers,host: init.host ?? "",- });- // Seed the deduper from the saved log so a live stream that replays the- // same prefix does not double-apply it.- const initialEvents: MessageStreamEvent[] = [];- for (const event of init.initialEvents ?? []) {- if (this.#seenEvents.admit(event)) initialEvents.push(event);- this.#trackPendingRequests(event);- }- this.#events = initialEvents;- this.#projection = new EveAgentProjection(init.reducer, this.#events);- this.#optimistic = init.optimistic ?? true;- this.#messageSubmissions = new OptimisticMessageSubmissions(this.#projection, this.#optimistic);+ }));+ this.#conversationClient = new ConversationClient(+ new EveAgentProjection(init.reducer, []),+ () => this.#publish(),+ () => this.#publish(),+ );+ this.#events = (init.initialEvents ?? []).filter((event) =>+ this.#conversationClient.hydrate(event),+ );+ this.#messageSubmissions = new OptimisticMessageSubmissions(+ this.#conversationClient.projections,+ init.optimistic ?? true,+ );this.#session =init.session ??(init.initialSession === undefined@@ -126,9 +131,7 @@ export class EveAgentStore<TData> {subscribe(callback: () => void): () => void {this.#subscribers.add(callback);- return () => {- this.#subscribers.delete(callback);- };+ return () => void this.#subscribers.delete(callback);}/** Creates this store's owned session without starting a turn. */@@ -154,11 +157,9 @@ export class EveAgentStore<TData> {try {const created = await client.sessions.create({ signal: controller.signal });if (generation !== this.#prewarmGeneration) return;- this.#session = created.session;this.#error = undefined;if (this.#status === "error") this.#status = "ready";- this.#callbacks.onSessionChange?.(created.session.state);- this.#publish();+ this.#adoptSession(created.session);this.#ensureStream();} catch (error) {if (@@ -166,10 +167,7 @@ export class EveAgentStore<TData> {this.#activeTurn === undefined &&this.#error === undefined) {- this.#error = toError(error);- this.#status = "error";- this.#callbacks.onError?.(this.#error);- this.#publish();+ this.#fail(error);}throw error;}@@ -193,6 +191,7 @@ export class EveAgentStore<TData> {input: SendTurnPayload<TOutput>,prepareSend?: PrepareSend,): Promise<void> {+ assertAnswerable(input, this.#conversationClient.conversation);if (this.#activeTurn !== undefined) {if (this.#status === "resuming") {throw new Error("eve session is resuming.");@@ -210,10 +209,16 @@ export class EveAgentStore<TData> {this.#activeTurn = turn;this.#error = undefined;this.#status = "submitted";- this.#publish();let reader: SessionEventReader | undefined;+ let submissionId: string | undefined;+ let retractResponses: (() => void) | undefined;try {+ assertExclusiveTurnInput(input);+ // Echo the submission before preparation, which may wait on caller-owned work.+ submissionId = this.#messageSubmissions.submit(input, this.#events.length);+ retractResponses = this.#conversationClient.projectResponses(input.inputResponses);+ this.#publish();const preparedInput = await (prepareSend === undefined? input: waitWithSignal(@@ -221,63 +226,52 @@ export class EveAgentStore<TData> {createAbortSignal(input.signal, turn.abortController.signal),));assertExclusiveTurnInput(preparedInput);-- if (!this.#isActiveTurn(turn)) {- return;+ if (!this.#isActiveTurn(turn)) return;+ if (preparedInput !== input) {+ submissionId = this.#messageSubmissions.resubmit(submissionId, preparedInput);+ retractResponses = this.#conversationClient.replaceResponses(+ retractResponses,+ preparedInput,+ );+ this.#publish();}- const submissionId = this.#messageSubmissions.submit(preparedInput, this.#events.length);- this.#projectInputResponses(preparedInput);- this.#publish();-const turnInput = {...preparedInput,signal: createAbortSignal(preparedInput.signal, turn.abortController.signal),};const dispatched = await this.#dispatchTurn(turnInput);+ retractResponses = undefined;const response = dispatched.response;reader = dispatched.reader;if (!this.#isActiveTurn(turn)) return;turn.resolveResponse(response);- if (- this.#handleReconciliation(- this.#messageSubmissions.correlate(- submissionId,- getMessageResponseDeliveryId(response),- this.#events,- ),- )- ) {- this.#publish();- }+ this.#correlate(submissionId, response);for await (const event of consumeMessageResponse(response, reader)) {if (!this.#isActiveTurn(turn)) return;turn.receivedFollowUps += turn.receivedFollowUpEvents.get(event) ?? 0;turn.receivedFollowUpEvents.delete(event);}- if (!this.#isActiveTurn(turn)) {- return;- }+ if (!this.#isActiveTurn(turn)) return;await followSteeredTurns(turn, reader, () => this.#isActiveTurn(turn));if (!this.#isActiveTurn(turn)) return;- this.#status = this.#error === undefined ? "ready" : "error";+ this.#status = settledStatus(this.#error, this.#conversationClient.conversation);} catch (error) {- if (!this.#isActiveTurn(turn)) {- return;- }+ if (!this.#isActiveTurn(turn)) return;+ retractResponses?.();if (isAbortError(error)) {this.#status = "ready";- this.#messageSubmissions.fail(toError(error));+ this.#messageSubmissions.fail(toError(error), submissionId);} else {const reported = this.#error !== undefined;this.#error ??= toError(error);this.#status = "error";- this.#messageSubmissions.fail(this.#error);+ this.#messageSubmissions.fail(this.#error, submissionId);if (!reported) this.#callbacks.onError?.(this.#error);}} finally {@@ -300,11 +294,7 @@ export class EveAgentStore<TData> {}async #resume(): Promise<void> {- if (- this.#status === "resuming" ||- this.#status === "streaming" ||- this.#status === "submitted"- ) {+ if (this.#status !== "ready" && this.#status !== "error") {throw new Error("eve session is already processing a turn.");}if (this.#session === undefined) {@@ -332,18 +322,23 @@ export class EveAgentStore<TData> {reader.discard();const tail = this.#events.at(-1);if (tail !== undefined) this.#applyTerminalStreamFailure(tail);- if (tail !== undefined && this.#error === undefined && !isSettledSessionTail(this.#events)) {+ if (+ tail &&+ !this.#error &&+ !isSettledSessionTail(this.#events, this.#conversationClient.conversation)+ ) {this.#status = "streaming";this.#publish();for await (const event of reader) {if (!this.#isActiveTurn(turn)) return;turn.receivedFollowUps += turn.receivedFollowUpEvents.get(event) ?? 0;turn.receivedFollowUpEvents.delete(event);- if (this.#isSettledAt(event)) break;+ if (isResponseBoundary(event, this.#conversationClient.conversation)) break;}}await followSteeredTurns(turn, reader, () => this.#isActiveTurn(turn));- if (this.#isActiveTurn(turn)) this.#status = this.#error === undefined ? "ready" : "error";+ if (this.#isActiveTurn(turn))+ this.#status = settledStatus(this.#error, this.#conversationClient.conversation);} catch (error) {if (!this.#isActiveTurn(turn)) return;if (isAbortError(error)) {@@ -375,25 +370,47 @@ export class EveAgentStore<TData> {return turn.cancel();}+ /** Queues server-side compaction of the current session's context. */+ async compact(): Promise<CompactResult> {+ return (await this.#session?.compact()) ?? { status: "no_active_session" };+ }++ /** Clears the current session's model-message history on the server. */+ async clear(): Promise<ClearResult> {+ return (await this.#session?.clear()) ?? { status: "no_active_session" };+ }++ /**+ * Terminally retires the store-owned server session, then resets local state so the next+ * send starts a fresh session. A failed request leaves both intact.+ */+ async retire(): Promise<ResetResult> {+ if (this.#externalSession) {+ throw new Error(+ "retire() needs a store-owned session. Call reset() on the session you supplied, then create a new store for the next session.",+ );+ }+ const result = (await this.#session?.reset()) ?? { status: "no_active_session" };+ this.reset();+ return result;+ }+[attachStore](): void {this.#attached = true;+ if (this.#followChildStreams && !this.#conversationClient.following) this.#followSubagents();if (this.#autoPrewarm && this.#session === undefined) void this.prewarm().catch(() => {});}[detachStore](): void {this.#attached = false;- this.#stream?.close();- this.#stream = undefined;+ this.#conversationClient.stop();this.#activeTurn?.abortController.abort();this.#resetPrewarm();this.#resumePromise = undefined;}reset(): void {- this.#stream?.close();- this.#stream = undefined;- this.#pendingAuthorizations.clear();- this.#pendingInputRequests.clear();+ this.#conversationClient.stop();const turn = this.#activeTurn;this.#activeTurn = undefined;turn?.resolveResponse(undefined);@@ -403,9 +420,9 @@ export class EveAgentStore<TData> {this.#resumePromise = undefined;if (!this.#externalSession) this.#session = undefined;this.#events = [];- this.#seenEvents = createEventDeduper();+ this.#conversationClient.reset();this.#messageSubmissions.reset();- this.#projection.reset();+ if (this.#followChildStreams && this.#attached) this.#followSubagents();this.#error = undefined;this.#status = "ready";this.#callbacks.onSessionChange?.(this.#session?.state);@@ -418,56 +435,64 @@ export class EveAgentStore<TData> {input: SendTurnPayload<TOutput>,prepareSend?: PrepareSend,): Promise<void> {- if (input.message === undefined || input.turnPolicy !== "steer") {- throw new Error(- 'eve session is already processing a turn. Send a message with turnPolicy: "steer" to guide it at the next boundary.',- );- }-+ assertInFlightFollowUp(input);const generation = this.#prewarmGeneration;const signal = createAbortSignal(input.signal, turn.abortController.signal);- const preparedInput =- (await waitWithSignal(Promise.resolve(prepareSend?.(input)), signal)) ?? input;+ // Answers close their requests before preparation so no one answers them twice.+ let retractResponses = this.#conversationClient.projectResponses(input.inputResponses);+ const preparedInput = await waitWithSignal(Promise.resolve(prepareSend?.(input)), signal)+ .then((prepared) => {+ const next = validateFollowUp(prepared ?? input);+ if (next === input) return next;+ retractResponses = this.#conversationClient.replaceResponses(retractResponses, next);+ return next;+ })+ .catch((error: unknown) => {+ retractResponses?.();+ throw error;+ });if (generation !== this.#prewarmGeneration) return;- assertExclusiveTurnInput(preparedInput);- if (preparedInput.message === undefined || preparedInput.turnPolicy !== "steer") {- throw new Error('An in-flight follow-up requires a message with turnPolicy: "steer".');+ if (!this.#isActiveTurn(turn)) {+ retractResponses?.();+ return await this.#submit(preparedInput);}- if (!this.#isActiveTurn(turn)) return await this.#submit(preparedInput);- const submissionId = this.#messageSubmissions.submit(preparedInput, this.#events.length);+ const submissionId = this.#messageSubmissions.submit(+ preparedInput,+ this.#events.length,+ activeTurnForOptimisticFollowUp(this.#events),+ );if (submissionId !== undefined) turn.followUpSubmissionIds.add(submissionId);this.#publish();- this.#ensureStream({- headers: preparedInput.headers,- streamReconnectPolicy: preparedInput.streamReconnectPolicy,- });let dispatch!: Promise<void>;dispatch = (async () => {try {const signal = createAbortSignal(preparedInput.signal, turn.abortController.signal);+ // The active turn may still be creating the session this follow-up steers.await waitWithSignal(turn.response, signal);if (!this.#isActiveTurn(turn) || this.#session === undefined) {throw new Error("The active eve turn ended before the follow-up could be sent.");}- const { message, ...options } = preparedInput;- const response = await this.#session.send(message, { ...options, signal });+ this.#ensureStream({+ headers: preparedInput.headers,+ streamReconnectPolicy: preparedInput.streamReconnectPolicy,+ });+ const response = (+ await dispatchSessionTurn({+ session: this.#session,+ turn: { ...preparedInput, signal },+ })+ ).response;+ retractResponses = undefined;+ // Answers settle through the active turn's stream; only steered messages extend it.+ if (preparedInput.message === undefined) return;turn.acceptedFollowUps += 1;- if (- this.#handleReconciliation(- this.#messageSubmissions.correlate(- submissionId,- getMessageResponseDeliveryId(response),- this.#events,- ),- )- ) {- this.#publish();- }+ this.#correlate(submissionId, response);} catch (error) {if (this.#isActiveTurn(turn)) {this.#messageSubmissions.fail(toError(error), submissionId);+ retractResponses?.();this.#publish();}throw error;@@ -481,9 +506,10 @@ export class EveAgentStore<TData> {await turn.completion;}- async #dispatchTurn<TOutput>(- input: SendTurnPayload<TOutput>,- ): Promise<{ readonly response: MessageResponse<TOutput>; readonly reader: SessionEventReader }> {+ async #dispatchTurn<TOutput>(input: SendTurnPayload<TOutput>): Promise<{+ readonly response: MessageResponse<TOutput>;+ readonly reader: SessionEventReader;+ }> {const streamOptions = {headers: input.headers,streamReconnectPolicy: input.streamReconnectPolicy,@@ -498,33 +524,24 @@ export class EveAgentStore<TData> {);input.signal?.throwIfAborted();}- if (this.#session === undefined) {- if (this.#client === undefined) {- throw new Error("An external eve session is required before sending.");- }- if (input.message === undefined) {- throw new Error("Cannot answer an input request before the session starts.");- }- const created = await this.#client.sessions.create({ ...input, message: input.message });- input.signal?.throwIfAborted();- this.#session = created.session;- this.#callbacks.onSessionChange?.(created.session.state);- this.#publish();- return {- response: created.response,- reader: this.#ensureStream(streamOptions).subscribe(input.signal),- };- }- const reader = this.#ensureStream(streamOptions).subscribe(input.signal);+ const session = this.#session;+ let reader: SessionEventReader | undefined;try {- if (input.inputResponses === undefined) {- const { message, ...options } = input;- return { response: await this.#session.send(message, options), reader };+ const dispatched = await dispatchSessionTurn({+ client: this.#client,+ session,+ turn: input,+ beforeSend: () => {+ reader = this.#ensureStream(streamOptions).subscribe(input.signal);+ },+ });+ if (dispatched.created) {+ this.#adoptSession(dispatched.session);+ reader = this.#ensureStream(streamOptions).subscribe(input.signal);}- const { inputResponses, ...options } = input;- return { response: await this.#session.respond(inputResponses, options), reader };+ return { response: dispatched.response, reader: reader! };} catch (error) {- reader[Symbol.dispose]();+ reader?.[Symbol.dispose]();throw error;}}@@ -532,30 +549,38 @@ export class EveAgentStore<TData> {#ensureStream(options: Omit<SessionEventStreamOptions, "onEvent" | "onError"> = {},): SessionEventStream {- if (this.#stream !== undefined && !this.#stream.ended) {- this.#stream.setOptions(options);- return this.#stream;- }if (this.#session === undefined)throw new Error("A session is required before opening its stream.");- const session = this.#session;const generation = this.#prewarmGeneration;- this.#stream = new SessionEventStream(session, {+ if (this.#followChildStreams && !this.#conversationClient.following) this.#followSubagents();+ return this.#conversationClient.stream(this.#session, {...options,onEvent: (event) => {if (generation === this.#prewarmGeneration) this.#acceptServerEvent(event);},onError: (error) => {- if (generation !== this.#prewarmGeneration) return;- this.#stream = undefined;- if (this.#activeTurn !== undefined) return;- this.#error = toError(error);- this.#status = "error";- this.#callbacks.onError?.(this.#error);- this.#publish();+ if (generation !== this.#prewarmGeneration || this.#activeTurn !== undefined) return;+ this.#fail(error);},});- return this.#stream;+ }++ #adoptSession(session: ClientSession): void {+ this.#session = session;+ if (this.#followChildStreams && this.#attached) this.#followSubagents();+ this.#callbacks.onSessionChange?.(session.state);+ this.#publish();+ }++ #fail(error: unknown): void {+ this.#error = toError(error);+ this.#status = "error";+ this.#callbacks.onError?.(this.#error);+ this.#publish();+ }++ #followSubagents(): void {+ if (this.#session) this.#conversationClient.follow(this.#session, this.#events);}#resetPrewarm(): void {@@ -582,29 +607,25 @@ export class EveAgentStore<TData> {return this.#activeTurn === turn;}- #projectInputResponses(input: SendTurnPayload): void {- if (input.inputResponses === undefined || input.inputResponses.length === 0) {- return;- }-- this.#projection.append({- data: {- createdAt: Date.now(),- responses: input.inputResponses,- },- type: "client.input.responded",- });- }-- #acceptServerEvent(event: MessageStreamEvent): void {- if (!this.#seenEvents.admit(event)) return;+ #acceptServerEvent(event: MessageStreamEvent): boolean {const wasStreaming = this.#status === "streaming";- this.#trackPendingRequests(event);- this.#events = [...this.#events, event];- this.#handleReconciliation(this.#messageSubmissions.apply(event));+ if (+ !this.#conversationClient.observe(event, {+ onAccepted: () => {+ this.#events = [...this.#events, event];+ },+ project: (accepted) => {+ this.#handleReconciliation(this.#messageSubmissions.apply(accepted));+ },+ notify: false,+ })+ )+ return false;this.#callbacks.onEvent?.(event);this.#applyTerminalStreamFailure(event);- const settled = this.#isSettledAt(event);+ const { conversation } = this.#conversationClient;+ const settled =+ isSettledSessionTail(this.#events, conversation) && conversation.activeTurnId === undefined;if (this.#status !== "resuming" && this.#error === undefined) {if ("data" in event && "turnId" in event.data) this.#status = "streaming";if (this.#activeTurn === undefined && settled) this.#status = "ready";@@ -616,45 +637,27 @@ export class EveAgentStore<TData> {if (this.#activeTurn === undefined && wasStreaming && settled) {this.#callbacks.onFinish?.(this.#snapshot);}+ return true;}- #trackPendingRequests(event: MessageStreamEvent): void {- updatePendingAuthorizations(this.#pendingAuthorizations, event);- updatePendingInputRequests(this.#pendingInputRequests, event);- }-- #isSettledAt(event: MessageStreamEvent): boolean {- return (- isTurnSegmentBoundary(event, this.#pendingInputRequests) &&- this.#pendingAuthorizations.size === 0- );+ /** Pairs a submission's echo with the server's copy once its delivery ID is known. */+ #correlate(submissionId: string | undefined, response: MessageResponse<unknown>): void {+ const deliveryId = getMessageResponseDeliveryId(response);+ const reconciled = this.#messageSubmissions.correlate(submissionId, deliveryId, this.#events);+ if (this.#handleReconciliation(reconciled)) this.#publish();}#handleReconciliation(- reconciliation: ReturnType<OptimisticMessageSubmissions<TData>["apply"]>,+ reconciliation: ReturnType<OptimisticMessageSubmissions["apply"]>,): boolean {if (reconciliation === undefined) return false;- let followed = 0;- for (const id of reconciliation.ids) {- if (this.#activeTurn?.followUpSubmissionIds.delete(id)) followed += 1;- }- if (followed > 0 && this.#activeTurn !== undefined) {- if (reconciliation.alreadyProjected) {- this.#activeTurn.receivedFollowUps += followed;- } else {- const previous = this.#activeTurn.receivedFollowUpEvents.get(reconciliation.event) ?? 0;- this.#activeTurn.receivedFollowUpEvents.set(reconciliation.event, previous + followed);- }- }+ if (this.#activeTurn !== undefined) countFollowUpDeliveries(this.#activeTurn, reconciliation);return true;}#applyTerminalStreamFailure(event: MessageStreamEvent): void {const error = toTerminalStreamFailureError(event);- if (error === undefined) {- return;- }-+ if (error === undefined) return;this.#status = "error";this.#messageSubmissions.failAll(error);@@ -666,7 +669,8 @@ export class EveAgentStore<TData> {#createSnapshot(): EveAgentStoreSnapshot<TData> {return {- data: this.#projection.data,+ data: this.#conversationClient.data,+ conversation: this.#conversationClient.conversation,error: this.#error,events: this.#events,session: this.#session?.state,@@ -676,9 +680,7 @@ export class EveAgentStore<TData> {#publish(): void {this.#snapshot = this.#createSnapshot();- for (const subscriber of this.#subscribers) {- subscriber();- }+ for (const subscriber of this.#subscribers) subscriber();}}diff --git a/packages/eve/src/client/index.ts b/packages/eve/src/client/index.tsindex f309012a4..a50230c12 100644--- a/packages/eve/src/client/index.ts+++ b/packages/eve/src/client/index.ts@@ -8,6 +8,17 @@ export { AgentInfoResponseError } from "#client/agent-info-error.js";export { HealthResponseError } from "#client/health-response-error.js";export { ClientError } from "#client/client-error.js";export { defaultMessageReducer } from "#client/message-reducer.js";+export { conversationReducer } from "#client/conversation-reducer.js";+export { openConversationInputs } from "#client/conversation-state.js";+export type {+ AgentObservation,+ ConversationAgentSession,+ ConversationInput,+ ConversationState,+ ConversationTask,+ ConversationTaskCall,+ ConversationTurn,+} from "#client/conversation-state.js";export { createDataUrlFilePart, createTextWithFileContent } from "#client/file-parts.js";export { MessageResponse } from "#client/message-response.js";export { ClientAgentSession } from "#client/agent-session.js";diff --git a/packages/eve/src/client/message-reducer-primitives.ts b/packages/eve/src/client/message-reducer-primitives.tsindex d221bb8f7..7707b5a12 100644--- a/packages/eve/src/client/message-reducer-primitives.ts+++ b/packages/eve/src/client/message-reducer-primitives.ts@@ -31,41 +31,40 @@ export function partKey(part: EveMessagePart): string {case "step-start":return "step-start";case "authorization":- return `authorization:${part.turnId}:${part.stepIndex}:${part.name}`;+ return part.attemptId === undefined+ ? `authorization:${part.turnId}:${part.stepIndex}:${part.name}`+ : `authorization:${part.attemptId}`;case "dynamic-tool":return `dynamic-tool:${part.toolCallId}`;}}-export function upsertMessage(data: EveMessageData, next: EveMessage): EveMessageData {+export function upsertMessage(+ data: EveMessageData,+ next: EveMessage,+ beforeAssistantTurnId?: string,+): EveMessageData {const index = data.messages.findIndex((message) => message.id === next.id);- if (index === -1) {- return { messages: [...data.messages, next] };+ if (index !== -1) {+ return {+ ...data,+ messages: [...data.messages.slice(0, index), next, ...data.messages.slice(index + 1)],+ };}-+ const before =+ beforeAssistantTurnId === undefined+ ? -1+ : data.messages.findIndex(+ (message) =>+ message.role === "assistant" && message.metadata?.turnId === beforeAssistantTurnId,+ );+ if (before === -1) return { ...data, messages: [...data.messages, next] };return {- messages: [...data.messages.slice(0, index), next, ...data.messages.slice(index + 1)],+ ...data,+ messages: [...data.messages.slice(0, before), next, ...data.messages.slice(before)],};}-export function removeStreamingToolPartsForTurn(- data: EveMessageData,- turnId: string,-): EveMessageData {- const index = data.messages.findIndex(- (message) => message.role === "assistant" && message.metadata?.turnId === turnId,- );- const message = data.messages[index];- if (message === undefined) return data;-- return upsertMessage(data, {- ...message,- parts: message.parts.filter(- (part) => part.type !== "dynamic-tool" || part.state !== "input-streaming",- ),- });-}-export function optimisticUserMessageId(submissionId: string): string {return `optimistic:${submissionId}:user`;}diff --git a/packages/eve/src/client/message-reducer-types.ts b/packages/eve/src/client/message-reducer-types.tsindex b74269850..16695f3ac 100644--- a/packages/eve/src/client/message-reducer-types.ts+++ b/packages/eve/src/client/message-reducer-types.ts@@ -42,10 +42,13 @@ export interface EveMessageMetadata {* or `"done"`; `file` carries user-attachment metadata; `step-start` marks the* boundary of an agent step; and `dynamic-tool` ({@link EveDynamicToolPart})* holds the tool call and its lifecycle state. `stepIndex` ties a part to the- * agent step that produced it.+ * agent step that produced it. Assistant text and reasoning parts carry an+ * `id` from the event that created the run. It survives appends and completion;+ * a null completion removes the part. User text may not have an `id`.*/export type EveMessagePart =| {+ readonly id?: string;readonly providerMetadata?: Record<string, unknown>;readonly state?: "done" | "streaming";readonly stepIndex?: number;@@ -53,6 +56,7 @@ export type EveMessagePart =readonly type: "text";}| {+ readonly id?: string;readonly providerMetadata?: Record<string, unknown>;readonly state?: "done" | "streaming";readonly stepIndex?: number;@@ -93,7 +97,7 @@ export type EveAuthorizationOutcome = AuthorizationOutcome;/*** An authorization prompt or result. The default reducer projects- * `authorization.required` into a pending part so browser chat UIs can render a+ * `authorization.required` into a `required` part so browser chat UIs can render a* sign-in affordance, then updates it when `authorization.completed` arrives.*/export type EveAuthorizationPart = {@@ -101,6 +105,9 @@ export type EveAuthorizationPart = {readonly description: string;readonly displayName: string;readonly name: string;+ readonly attemptId?: string;+ /** The sign-in's callback settles this attempt and resumes the parked turn. */+ readonly awaitsCallback?: boolean;readonly stepIndex: number;readonly turnId: string;readonly type: "authorization";diff --git a/packages/eve/src/client/message-reducer.test.ts b/packages/eve/src/client/message-reducer.test.tsindex 04d4b4844..bf5d7634f 100644--- a/packages/eve/src/client/message-reducer.test.ts+++ b/packages/eve/src/client/message-reducer.test.ts@@ -1,12 +1,13 @@import { describe, expect, it } from "vitest";import { defaultMessageReducer } from "#client/message-reducer.js";-import { stampTestEvents } from "#internal/testing/events.js";+import { stampTestEvent, stampTestEvents } from "#internal/testing/events.js";import {createActionInputAppendedEvent,createActionPartialEvent,createActionResultEvent,createActionsRequestedEvent,+ createApprovalSettledEvent,createAuthorizationCompletedEvent,createAuthorizationRequiredEvent,createInputResolvedEvent,@@ -18,6 +19,7 @@ import {createReasoningCompletedEvent,createResultCompletedEvent,createStepStartedEvent,+ createTaskSettledEvent,createTurnCancelledEvent,createTurnCompletedEvent,createTurnFailedEvent,@@ -39,6 +41,92 @@ function reduceServerEvents(}describe("defaultMessageReducer", () => {+ it("groups late received messages before the response for their turn", () => {+ const reducer = defaultMessageReducer();+ const data = reduceServerEvents(reducer, reducer.initial(), [+ createMessageReceivedEvent({ message: "First", sequence: 0, turnId: "turn_1" }),+ createMessageCompletedEvent({+ finishReason: "stop",+ message: "Response",+ sequence: 1,+ stepIndex: 0,+ turnId: "turn_1",+ }),+ createMessageReceivedEvent({ message: "Second", sequence: 2, turnId: "turn_1" }),+ createMessageReceivedEvent({ message: "Third", sequence: 3, turnId: "turn_1" }),+ createMessageReceivedEvent({ message: "Next turn", sequence: 0, turnId: "turn_2" }),+ ]);++ expect(+ data.messages.map((message) => (message.role === "user" ? message.parts[0] : "assistant")),+ ).toEqual([+ { state: "done", text: "First", type: "text" },+ { state: "done", text: "Second", type: "text" },+ { state: "done", text: "Third", type: "text" },+ "assistant",+ { state: "done", text: "Next turn", type: "text" },+ ]);+ });++ it("places an optimistic steered message before the active reply, then keeps its place when confirmed", () => {+ const reducer = defaultMessageReducer();+ let data = reduceServerEvents(reducer, reducer.initial(), [+ createMessageReceivedEvent({ message: "First", sequence: 0, turnId: "turn_1" }),+ createMessageAppendedEvent({+ messageDelta: "Reply so far",+ sequence: 1,+ stepIndex: 0,+ turnId: "turn_1",+ }),+ ]);+ data = reducer.reduce(data, {+ data: { createdAt: 1, message: "Correction", submissionId: "follow-up", turnId: "turn_1" },+ type: "client.message.submitted",+ });+ expect(data.messages.map((message) => message.role)).toEqual(["user", "user", "assistant"]);+ data = reducer.reduce(+ data,+ stampTestEvent(+ createMessageReceivedEvent({ message: "Correction", sequence: 2, turnId: "turn_1" }),+ 2,+ ),+ );+ expect(data.messages.map((message) => message.role)).toEqual([+ "user",+ "user",+ "user",+ "assistant",+ ]);+ });++ it("leaves a failed optimistic follow-up ahead of the active reply", () => {+ const reducer = defaultMessageReducer();+ let data = reduceServerEvents(reducer, reducer.initial(), [+ createMessageCompletedEvent({+ finishReason: "stop",+ message: "Reply",+ sequence: 0,+ stepIndex: 0,+ turnId: "turn_1",+ }),+ ]);+ data = reducer.reduce(data, {+ type: "client.message.submitted",+ data: { createdAt: 1, submissionId: "failed", message: "Correction", turnId: "turn_1" },+ });+ data = reducer.reduce(data, {+ type: "client.message.failed",+ data: {+ createdAt: 1,+ submissionId: "failed",+ message: "Correction",+ error: { message: "No connection" },+ },+ });+ expect(data.messages.map((message) => message.role)).toEqual(["user", "assistant"]);+ expect(data.messages[0]?.metadata?.status).toBe("failed");+ });+it("accumulates message and reasoning deltas without a start marker", () => {const reducer = defaultMessageReducer();const data = reduceServerEvents(reducer, reducer.initial(), [@@ -70,55 +158,44 @@ describe("defaultMessageReducer", () => {expect(data.messages[0]?.parts).toEqual([{ type: "step-start" },- { state: "streaming", stepIndex: 0, text: "I can", type: "reasoning" },- { state: "streaming", stepIndex: 0, text: "Hello", type: "text" },+ { id: "evt_test_0000", state: "streaming", stepIndex: 0, text: "I can", type: "reasoning" },+ { id: "evt_test_0002", state: "streaming", stepIndex: 0, text: "Hello", type: "text" },]);});it("uses the canonical completion after an interrupted attempt", () => {const reducer = defaultMessageReducer();- let data = reduceServerEvents(reducer, reducer.initial(), [- createMessageAppendedEvent({- messageDelta: "abandoned",- sequence: 0,- stepIndex: 0,- turnId: "turn_1",- }),- createMessageAppendedEvent({- messageDelta: "replacement",- sequence: 0,- stepIndex: 0,- turnId: "turn_1",- }),- createMessageAppendedEvent({- messageDelta: " complete",+ const [first, ...rest] = stampTestEvents([+ ...["abandoned", "replacement", " complete"].map((messageDelta) =>+ createMessageAppendedEvent({ messageDelta, sequence: 0, stepIndex: 0, turnId: "turn_1" }),+ ),+ createMessageCompletedEvent({+ message: "replacement complete",sequence: 0,stepIndex: 0,turnId: "turn_1",}),]);+ const completion = rest.pop()!;+ let data = [first!, ...rest].reduce(reducer.reduce, reducer.initial());expect(data.messages[0]?.parts).toContainEqual({state: "streaming",stepIndex: 0,text: "abandonedreplacement complete",type: "text",+ id: first!.meta.id,});- data = reduceServerEvents(reducer, data, [- createMessageCompletedEvent({- message: "replacement complete",- sequence: 0,- stepIndex: 0,- turnId: "turn_1",- }),- ]);+ data = reducer.reduce(data, completion);+ expect(completion.meta.id).not.toBe(first!.meta.id);expect(data.messages[0]?.parts).toContainEqual({state: "done",stepIndex: 0,text: "replacement complete",type: "text",+ id: first!.meta.id,});});@@ -257,6 +334,50 @@ describe("defaultMessageReducer", () => {expect(data.messages[0]?.parts).toEqual([{ type: "step-start" }]);});+ it("closes partial content and drops unfinished tool input on a failed turn", () => {+ const reducer = defaultMessageReducer();+ const data = reduceServerEvents(reducer, reducer.initial(), [+ createMessageAppendedEvent({+ messageDelta: "Partial answer",+ sequence: 1,+ stepIndex: 0,+ turnId: "turn_1",+ }),+ createReasoningAppendedEvent({+ reasoningDelta: "Partial thought",+ sequence: 2,+ stepIndex: 0,+ turnId: "turn_1",+ }),+ createActionInputAppendedEvent({+ callId: "unfinished",+ inputTextDelta: "{",+ sequence: 3,+ stepIndex: 0,+ toolName: "lookup",+ turnId: "turn_1",+ }),+ createTurnFailedEvent({+ code: "MODEL_FAILED",+ message: "model failed",+ sequence: 4,+ turnId: "turn_1",+ }),+ ]);+ expect(data.messages[0]?.metadata?.status).toBe("complete");+ expect(data.messages[0]?.parts).toEqual([+ { type: "step-start" },+ { id: "evt_test_0000", type: "text", stepIndex: 0, text: "Partial answer", state: "done" },+ {+ id: "evt_test_0001",+ type: "reasoning",+ stepIndex: 0,+ text: "Partial thought",+ state: "done",+ },+ ]);+ });+it("does not create an assistant message when a turn fails before streaming", () => {const reducer = defaultMessageReducer();const data = reduceServerEvents(reducer, reducer.initial(), [@@ -271,6 +392,75 @@ describe("defaultMessageReducer", () => {expect(data.messages).toEqual([]);});+ it("does not reopen a settled approval on repeated request and call events", () => {+ const reducer = defaultMessageReducer();+ const call = createActionsRequestedEvent({+ actions: [{ callId: "call_1", input: {}, kind: "tool-call", toolName: "color" }],+ sequence: 0,+ stepIndex: 0,+ turnId: "turn_1",+ });+ const request = createInputRequestedEvent({+ requests: [+ {+ action: { callId: "call_1", input: {}, kind: "tool-call", toolName: "color" },+ display: "confirmation",+ kind: "tool-approval",+ options: [{ id: "approve", label: "Approve" }],+ prompt: "Approve color?",+ requestId: "approval_1",+ },+ ],+ sequence: 1,+ stepIndex: 0,+ turnId: "turn_1",+ });+ const result = createActionResultEvent({+ result: { callId: "call_1", kind: "tool-result", output: "blue", toolName: "color" },+ sequence: 2,+ stepIndex: 0,+ turnId: "turn_1",+ });+ const data = reduceServerEvents(reducer, reducer.initial(), [+ call,+ request,+ result,+ request,+ call,+ ]);+ expect(findToolPart(data, "call_1")).toMatchObject({+ state: "output-available",+ output: "blue",+ });+ });++ it("projects a rejected action result as denied rather than a successful output", () => {+ const reducer = defaultMessageReducer();+ const data = reduceServerEvents(reducer, reducer.initial(), [+ createActionsRequestedEvent({+ actions: [{ callId: "call_rejected", input: {}, kind: "tool-call", toolName: "bash" }],+ sequence: 0,+ stepIndex: 0,+ turnId: "turn_1",+ }),+ {+ type: "action.result",+ data: {+ error: { code: "USER_REJECTED", message: "Denied by user." },+ result: { callId: "call_rejected", kind: "tool-result", output: null, toolName: "bash" },+ sequence: 1,+ status: "rejected",+ stepIndex: 0,+ turnId: "turn_1",+ },+ },+ ]);+ expect(findToolPart(data, "call_rejected")).toMatchObject({+ approval: { approved: false, reason: "Denied by user." },+ state: "output-denied",+ });+ });+it("replaces tool-generator snapshots and ignores a late partial after the terminal result", () => {const reducer = defaultMessageReducer();let data = reduceServerEvents(reducer, reducer.initial(), [@@ -418,6 +608,7 @@ describe("defaultMessageReducer", () => {stepIndex: 0,text: "Need the weather tool.",type: "reasoning",+ id: "evt_test_0000",},{input: { city: "Vienna" },@@ -429,8 +620,11 @@ describe("defaultMessageReducer", () => {eve: {kind: "tool-call",name: "get_weather",+ inputRequest: undefined,+ inputResponse: undefined,},},+ approval: undefined,toolName: "get_weather",type: "dynamic-tool",},@@ -497,6 +691,39 @@ describe("defaultMessageReducer", () => {]);});+ it("settles a task call on its original tool part after later turns", () => {+ const reducer = defaultMessageReducer();+ const receipt = createActionResultEvent({+ result: {+ callId: "call_1",+ kind: "tool-result",+ output: "Started task task_1.",+ toolName: "research",+ },+ sequence: 0,+ stepIndex: 0,+ turnId: "turn_1",+ });+ const settled = createTaskSettledEvent({+ callId: "call_1",+ output: "Alice's report is ready.",+ status: "completed",+ taskId: "task_1",+ turnId: "turn_1",+ });+ const after = reduceServerEvents(reducer, reducer.initial(), [+ receipt,+ createMessageReceivedEvent({ message: "Continue", sequence: 0, turnId: "turn_2" }),+ settled,+ ]);+ const part = after.messages[0]?.parts.find((candidate) => candidate.type === "dynamic-tool");+ expect(part).toMatchObject({ output: "Alice's report is ready.", state: "output-available" });+ expect(after.messages.map((message) => message.id)).toEqual([+ "turn_1:assistant",+ expect.any(String),+ ]);+ });+it("projects denied tool output distinctly from generic failures", () => {const reducer = defaultMessageReducer();const data = reduceServerEvents(reducer, reducer.initial(), [@@ -615,6 +842,7 @@ describe("defaultMessageReducer", () => {description: "Authorization required for Notion",displayName: "Notion",name: "notion",+ awaitsCallback: true,state: "required",stepIndex: 0,turnId: "turn_1",@@ -626,6 +854,42 @@ describe("defaultMessageReducer", () => {]);});+ it("completes only the authorization attempt that a later callback settles", () => {+ const reducer = defaultMessageReducer();+ const required = (attemptId: string) =>+ createAuthorizationRequiredEvent({+ name: "linear",+ attemptId,+ description: "Connect linear",+ sequence: 0,+ stepIndex: 0,+ turnId: "turn_1",+ });+ const data = reduceServerEvents(reducer, reducer.initial(), [+ required("alice"),+ required("bob"),+ createAuthorizationCompletedEvent({+ name: "linear",+ attemptId: "alice",+ outcome: "authorized",+ sequence: 1,+ stepIndex: 0,+ turnId: "turn_2",+ }),+ ]);++ expect(+ data.messages.flatMap((message) =>+ message.role === "assistant"+ ? message.parts.filter((part) => part.type === "authorization")+ : [],+ ),+ ).toEqual([+ expect.objectContaining({ attemptId: "alice", state: "completed", outcome: "authorized" }),+ expect.objectContaining({ attemptId: "bob", state: "required" }),+ ]);+ });+it("updates the pending authorization part when authorization completes", () => {const reducer = defaultMessageReducer();const data = reduceServerEvents(reducer, reducer.initial(), [@@ -673,6 +937,7 @@ describe("defaultMessageReducer", () => {description: "Sign in to Notion to continue.",displayName: "Notion",name: "notion",+ awaitsCallback: true,outcome: "authorized",state: "completed",stepIndex: 0,@@ -1032,6 +1297,108 @@ describe("defaultMessageReducer", () => {},);+ it("keeps a settled approval's decision when its batch resolution repeats the answer", () => {+ const reducer = defaultMessageReducer();+ const response = { optionId: "approve", requestId: "approval_1" };+ const data = reduceServerEvents(reducer, reducer.initial(), [+ createInputRequestedEvent({+ requests: [+ {+ action: { callId: "call_1", input: {}, kind: "tool-call", toolName: "save_note" },+ kind: "tool-approval",+ prompt: "Save Alice's note?",+ requestId: "approval_1",+ },+ ],+ sequence: 0,+ stepIndex: 0,+ turnId: "turn_1",+ }),+ {+ type: "approval.settled",+ data: {+ outcome: "approved",+ requestId: "approval_1",+ responderPrincipalId: "alice",+ sequence: 0,+ stepIndex: 0,+ turnId: "turn_1",+ },+ },+ {+ type: "input.resolved",+ data: {+ resolutions: [+ { kind: "tool-approval", outcome: "approved", requestId: "approval_1", response },+ ],+ sequence: 0,+ stepIndex: 0,+ turnId: "turn_1",+ },+ },+ ]);+ expect(findToolPart(data, "call_1")).toMatchObject({+ state: "approval-responded",+ approval: { approved: true },+ });+ });++ it("retains a completed workflow result when approval arrives afterward", () => {+ const reducer = defaultMessageReducer();+ const request = {+ action: { callId: "call_1", input: {}, kind: "tool-call" as const, toolName: "color" },+ display: "confirmation" as const,+ kind: "tool-approval" as const,+ options: [+ { id: "approve", label: "Approve" },+ { id: "cancel", label: "Cancel" },+ ],+ prompt: "Approve color?",+ requestId: "approval_1",+ };+ const events = [+ createInputRequestedEvent({+ requests: [request],+ sequence: 0,+ stepIndex: 0,+ turnId: "turn_0",+ }),+ createActionResultEvent({+ result: { callId: "call_1", kind: "tool-result", output: "#123456", toolName: "color" },+ sequence: 1,+ stepIndex: 0,+ turnId: "turn_0",+ }),+ createApprovalSettledEvent({+ outcome: "approved",+ requestId: "approval_1",+ responderPrincipalId: "alice",+ sequence: 2,+ stepIndex: 0,+ turnId: "turn_0",+ }),+ createInputResolvedEvent({+ resolutions: [+ {+ kind: "tool-approval",+ outcome: "approved",+ requestId: "approval_1",+ response: { optionId: "approve", requestId: "approval_1" },+ },+ ],+ sequence: 3,+ stepIndex: 0,+ turnId: "turn_0",+ }),+ ];+ const data = reduceServerEvents(reducer, reducer.initial(), events);+ expect(findToolPart(data, "call_1")).toMatchObject({+ approval: { approved: true },+ output: "#123456",+ state: "output-available",+ });+ });+it("merges resumed approval results back into the requested tool part", () => {const reducer = defaultMessageReducer();let data = reduceServerEvents(reducer, reducer.initial(), [@@ -1167,6 +1534,7 @@ describe("defaultMessageReducer", () => {stepIndex: 0,text: "First step.",type: "text",+ id: "evt_test_0000",},{ type: "step-start" },{@@ -1174,6 +1542,7 @@ describe("defaultMessageReducer", () => {stepIndex: 1,text: "Second step.",type: "text",+ id: "evt_test_0001",},],role: "assistant",@@ -1268,12 +1637,14 @@ describe("defaultMessageReducer", () => {stepIndex: 0,text: "Thinking",type: "reasoning",+ id: "evt_test_0000",},{state: "done",stepIndex: 0,text: "Partial",type: "text",+ id: "evt_test_0001",},],role: "assistant",diff --git a/packages/eve/src/client/message-reducer.ts b/packages/eve/src/client/message-reducer.tsindex d3cddaa84..c40d432d6 100644--- a/packages/eve/src/client/message-reducer.ts+++ b/packages/eve/src/client/message-reducer.ts@@ -8,7 +8,6 @@ import type {EveMessageData,EveDynamicToolPart,EveMessage,- EveMessageMetadata,EveMessagePart,} from "#client/message-reducer-types.js";import {@@ -24,7 +23,6 @@ import {optimisticUserMessageId,partKey,projectReceivedParts,- removeStreamingToolPartsForTurn,upsertMessage,} from "#client/message-reducer-primitives.js";import { messageRun } from "#client/message-run-parts.js";@@ -75,26 +73,20 @@ export function defaultMessageReducer(): EveAgentReducer<EveMessageData> {function reduceMessageData(data: EveMessageData, event: EveAgentReducerEvent): EveMessageData {switch (event.type) {case "client.message.submitted":- return upsertMessage(data, {- id: optimisticUserMessageId(event.data.submissionId),- metadata: {- optimistic: true,- status: "submitted",- },- parts: [{ type: "text", text: event.data.message }],- role: "user",- });-case "client.message.failed":- return upsertMessage(data, {- id: optimisticUserMessageId(event.data.submissionId),- metadata: {- optimistic: true,- status: "failed",+ return upsertMessage(+ data,+ {+ id: optimisticUserMessageId(event.data.submissionId),+ metadata: {+ optimistic: true,+ status: event.type === "client.message.failed" ? "failed" : "submitted",+ },+ parts: [{ type: "text", text: event.data.message }],+ role: "user",},- parts: [{ type: "text", text: event.data.message }],- role: "user",- });+ event.data.turnId,+ );case "input.resolved": {let next = data;@@ -105,25 +97,42 @@ function reduceMessageData(data: EveMessageData, event: EveAgentReducerEvent): E}case "message.received":- return upsertMessage(data, {- id: `${receivedMessageEventId(event)}:user`,- metadata: {- status: "complete",- turnId: event.data.turnId,+ return upsertMessage(+ data,+ {+ id: `${receivedMessageEventId(event)}:user`,+ metadata: {+ status: "complete",+ turnId: event.data.turnId,+ },+ parts: projectReceivedParts(event.data.parts, event.data.message),+ role: "user",},- parts: projectReceivedParts(event.data.parts, event.data.message),- role: "user",- });+ event.data.turnId,+ );case "step.started":return updateAssistantMessage(data, event.data.turnId, (message) =>ensureStepStartPart(message, event.data.stepIndex),);+ case "step.completed": {+ const existing = data.messages.find(+ (message) => message.role === "assistant" && message.metadata?.turnId === event.data.turnId,+ );+ if (existing === undefined) return data;+ return updateAssistantMessage(data, event.data.turnId, (message) => ({+ ...message,+ parts: closeStreamingRuns(message.parts, event.data.stepIndex),+ }));+ }+case "reasoning.appended":return updateAssistantMessage(data, event.data.turnId, (message) =>- messageRun.append(ensureStepStartPart(message, event.data.stepIndex), {+ messageRun.transition(ensureStepStartPart(message, event.data.stepIndex), {+ kind: "append",delta: event.data.reasoningDelta,+ id: event.meta?.id,stepIndex: event.data.stepIndex,type: "reasoning",}),@@ -131,10 +140,11 @@ function reduceMessageData(data: EveMessageData, event: EveAgentReducerEvent): Ecase "reasoning.completed":return updateAssistantMessage(data, event.data.turnId, (message) =>- messageRun.upsert(ensureStepStartPart(message, event.data.stepIndex), {- state: "done",+ messageRun.transition(ensureStepStartPart(message, event.data.stepIndex), {+ kind: "complete",stepIndex: event.data.stepIndex,text: event.data.reasoning,+ id: event.meta?.id,type: "reasoning",}),);@@ -163,18 +173,14 @@ function reduceMessageData(data: EveMessageData, event: EveAgentReducerEvent): Etype: "dynamic-tool",};- if (existing !== undefined) {- return updateToolPart(data, event.data.callId, nextPart);- }-- return updateAssistantMessage(data, event.data.turnId, (message) =>- upsertPart(ensureStepStartPart(message, event.data.stepIndex), nextPart),- );+ return upsertToolPart(data, event.data.turnId, event.data.stepIndex, nextPart);}case "actions.requested": {let next = data;for (const action of event.data.actions) {+ const existing = findToolPart(next, action.callId);+ if (existing !== undefined && existing.state !== "input-streaming") continue;const descriptor = normalizeActionRequest(action);next = updateAssistantMessage(next, event.data.turnId, (message) =>upsertPart(ensureStepStartPart(message, event.data.stepIndex), {@@ -194,6 +200,12 @@ function reduceMessageData(data: EveMessageData, event: EveAgentReducerEvent): Ecase "input.requested": {let next = data;for (const request of event.data.requests) {+ const existing = findToolPart(next, request.action.callId);+ if (+ existing?.approval?.id === request.requestId ||+ (existing !== undefined && isSettledToolPart(existing))+ )+ continue;const descriptor = normalizeActionRequest(request.action);next = updateAssistantMessage(next, event.data.turnId, (message) =>upsertPart(ensureStepStartPart(message, event.data.stepIndex), {@@ -224,37 +236,32 @@ function reduceMessageData(data: EveMessageData, event: EveAgentReducerEvent): Econst existing = findToolPartByApprovalId(data, event.data.requestId);if (existing === undefined) return data;if (event.data.outcome === "approved") {- return updateToolPart(data, existing.toolCallId, {- approval: { approved: true, id: event.data.requestId, reason: undefined },- input: existing.input,- state: "approval-responded",- stepIndex: existing.stepIndex,- toolCallId: existing.toolCallId,- toolMetadata: existing.toolMetadata,- toolName: existing.toolName,- type: "dynamic-tool",- });+ const approval = { approved: true as const, id: event.data.requestId, reason: undefined };+ return updateToolPart(+ data,+ existing.toolCallId,+ existing.state === "output-available"+ ? { ...existing, approval }+ : { ...toolPartIdentity(existing), approval, state: "approval-responded" },+ );}+ if (existing.state === "output-available") return data;return updateToolPart(data, existing.toolCallId, {+ ...toolPartIdentity(existing),approval: {approved: false,id: event.data.requestId,reason: "Tool execution was cancelled.",},- input: existing.input,state: "output-denied",- stepIndex: existing.stepIndex,- toolCallId: existing.toolCallId,- toolMetadata: existing.toolMetadata,- toolName: existing.toolName,- type: "dynamic-tool",});}case "action.result": {const descriptor = normalizeActionResult(event.data.result);const existing = findToolPart(data, event.data.result.callId);- const denied = event.data.error?.code === "TOOL_EXECUTION_DENIED";+ const denied =+ event.data.status === "rejected" || event.data.error?.code === "TOOL_EXECUTION_DENIED";const failed = event.data.status === "failed" && !denied;const approvalId = existing?.approval?.id ?? event.data.result.callId;const toolMetadata = mergeToolMetadata(@@ -297,15 +304,7 @@ function reduceMessageData(data: EveMessageData, event: EveAgentReducerEvent): E};}- if (existing !== undefined) {- // Approved tool results can arrive on a later runtime turn; keep- // the UI lifecycle anchored to the original tool call.- return updateToolPart(data, event.data.result.callId, nextPart);- }-- return updateAssistantMessage(data, event.data.turnId, (message) =>- upsertPart(ensureStepStartPart(message, event.data.stepIndex), nextPart),- );+ return upsertToolPart(data, event.data.turnId, event.data.stepIndex, nextPart);}case "action.partial": {@@ -328,13 +327,7 @@ function reduceMessageData(data: EveMessageData, event: EveAgentReducerEvent): Etype: "dynamic-tool",};- if (existing !== undefined) {- return updateToolPart(data, event.data.result.callId, nextPart);- }-- return updateAssistantMessage(data, event.data.turnId, (message) =>- upsertPart(ensureStepStartPart(message, event.data.stepIndex), nextPart),- );+ return upsertToolPart(data, event.data.turnId, event.data.stepIndex, nextPart);}case "task.settled": {@@ -356,31 +349,37 @@ function reduceMessageData(data: EveMessageData, event: EveAgentReducerEvent): Ecase "message.appended":return updateAssistantMessage(data, event.data.turnId, (message) =>- messageRun.append(ensureStepStartPart(message, event.data.stepIndex), {+ messageRun.transition(ensureStepStartPart(message, event.data.stepIndex), {+ kind: "append",delta: event.data.messageDelta,+ id: event.meta?.id,stepIndex: event.data.stepIndex,type: "text",}),);case "message.completed":- return updateAssistantMessage(data, event.data.turnId, (message) => {- return messageRun.upsert(ensureStepStartPart(message, event.data.stepIndex), {- state: "done",+ return updateAssistantMessage(data, event.data.turnId, (message) =>+ messageRun.transition(ensureStepStartPart(message, event.data.stepIndex), {+ kind: "complete",stepIndex: event.data.stepIndex,text: event.data.message,+ id: event.meta?.id,type: "text",- });- });+ }),+ );case "result.completed":- return updateAssistantMetadata(data, event.data.turnId, { result: event.data.result });+ return updateAssistantMessage(data, event.data.turnId, (message) => ({+ ...message,+ metadata: { ...message.metadata, result: event.data.result },+ }));case "turn.completed":return updateAssistantMessage(data, event.data.turnId, (message) => ({...message,metadata: { ...message.metadata, status: "complete" },- parts: removeStreamingToolParts(message.parts),+ parts: removeStreamingToolParts(closeStreamingRuns(message.parts)),}));case "turn.cancelled":@@ -389,17 +388,20 @@ function reduceMessageData(data: EveMessageData, event: EveAgentReducerEvent): Ereturn updateAssistantMessage(data, event.data.turnId, (message) => ({...message,metadata: { ...message.metadata, status: "complete" },- parts: removeStreamingToolParts(- message.parts.map((part) =>- (part.type === "text" || part.type === "reasoning") && part.state === "streaming"- ? { ...part, state: "done" }- : part,- ),- ),+ parts: removeStreamingToolParts(closeStreamingRuns(message.parts)),}));- case "turn.failed":- return removeStreamingToolPartsForTurn(data, event.data.turnId);+ case "turn.failed": {+ const existing = data.messages.find(+ (message) => message.role === "assistant" && message.metadata?.turnId === event.data.turnId,+ );+ if (existing === undefined) return data;+ return updateAssistantMessage(data, event.data.turnId, (message) => ({+ ...message,+ metadata: { ...message.metadata, status: "complete" },+ parts: removeStreamingToolParts(closeStreamingRuns(message.parts)),+ }));+ }case "session.failed":return data;@@ -409,6 +411,19 @@ function reduceMessageData(data: EveMessageData, event: EveAgentReducerEvent): E}}+function closeStreamingRuns(+ parts: readonly EveMessagePart[],+ stepIndex?: number,+): readonly EveMessagePart[] {+ return parts.map((part) =>+ (part.type === "text" || part.type === "reasoning") &&+ part.state === "streaming" &&+ (stepIndex === undefined || part.stepIndex === stepIndex)+ ? { ...part, state: "done" }+ : part,+ );+}+function removeStreamingToolParts(parts: readonly EveMessagePart[]): readonly EveMessagePart[] {return parts.filter((part) => part.type !== "dynamic-tool" || part.state !== "input-streaming");}@@ -424,44 +439,50 @@ function respondToInputRequest(data: EveMessageData, response: InputResponse): Eapproval.reason = response.text;}- return updateToolPart(data, existing.toolCallId, {- approval,- input: existing.input,- state: "approval-responded",- stepIndex: existing.stepIndex,- toolCallId: existing.toolCallId,- toolMetadata: mergeToolMetadata(existing.toolMetadata, {- eve: {- inputResponse: response,- kind: existing.toolMetadata?.eve?.kind ?? "unknown",- name: existing.toolMetadata?.eve?.name ?? existing.toolName,- },- }),- toolName: existing.toolName,- type: "dynamic-tool",+ const toolMetadata = mergeToolMetadata(existing.toolMetadata, {+ eve: {+ inputResponse: response,+ kind: existing.toolMetadata?.eve?.kind ?? "unknown",+ name: existing.toolMetadata?.eve?.name ?? existing.toolName,+ },});+ return updateToolPart(+ data,+ existing.toolCallId,+ existing.state === "output-available"+ ? { ...existing, approval: { ...approval, approved: true }, toolMetadata }+ : { ...toolPartIdentity(existing), approval, state: "approval-responded", toolMetadata },+ );}function resolveInputRequest(data: EveMessageData, resolution: InputResolution): EveMessageData {if (resolution.response !== undefined) {- return respondToInputRequest(data, resolution.response);+ // A batch's resolution repeats answers that `approval.settled` already decided.+ const decided = findToolPartByApprovalId(data, resolution.requestId)?.approval?.approved;+ return decided === undefined ? respondToInputRequest(data, resolution.response) : data;}const existing = findToolPartByApprovalId(data, resolution.requestId);if (!existing) return data;return updateToolPart(data, existing.toolCallId, {- input: existing.input,+ ...toolPartIdentity(existing),output: { status: resolution.outcome },state: "output-available",- stepIndex: existing.stepIndex,- toolCallId: existing.toolCallId,- toolMetadata: existing.toolMetadata,- toolName: existing.toolName,- type: "dynamic-tool",});}+function toolPartIdentity(part: EveDynamicToolPart) {+ return {+ input: part.input,+ stepIndex: part.stepIndex,+ toolCallId: part.toolCallId,+ toolMetadata: part.toolMetadata,+ toolName: part.toolName,+ type: part.type,+ };+}+function updateAssistantMessage(data: EveMessageData,turnId: string,@@ -476,20 +497,6 @@ function updateAssistantMessage(return upsertMessage(data, update(message));}-function updateAssistantMetadata(- data: EveMessageData,- turnId: string,- metadata: EveMessageMetadata,-): EveMessageData {- return updateAssistantMessage(data, turnId, (message) => ({- ...message,- metadata: {- ...message.metadata,- ...metadata,- },- }));-}-function createAssistantMessage(turnId: string): EveAssistantMessage {return {id: `${turnId}:assistant`,@@ -535,6 +542,21 @@ function upsertPart(message: EveAssistantMessage, next: EveMessagePart): EveAssi};}+function upsertToolPart(+ data: EveMessageData,+ turnId: string,+ stepIndex: number,+ part: EveDynamicToolPart,+): EveMessageData {+ // A later result still belongs to the turn that opened the call.+ const updated = updateToolPart(data, part.toolCallId, part);+ return updated !== data+ ? updated+ : updateAssistantMessage(data, turnId, (message) =>+ upsertPart(ensureStepStartPart(message, stepIndex), part),+ );+}+function updateToolPart(data: EveMessageData,toolCallId: string,@@ -577,35 +599,15 @@ function completeAuthorization(data: EveMessageData,event: AuthorizationCompletedStreamEvent,): EveMessageData {- const existing = findLatestPendingAuthorizationPart(data, event.data.name);+ const existing = findPendingAuthorizationPart(data, event.data.name, event.data.attemptId);const next = createAuthorizationCompletedPart(event, existing);- if (existing !== undefined) {- return updateAuthorizationPart(data, existing, next);- }-- return updateAssistantMessage(data, event.data.turnId, (message) =>- upsertPart(ensureStepStartPart(message, event.data.stepIndex), next),+ const turnId = existing?.turnId ?? event.data.turnId;+ return updateAssistantMessage(data, turnId, (message) =>+ upsertPart(ensureStepStartPart(message, next.stepIndex), next),);}-function updateAuthorizationPart(- data: EveMessageData,- existing: EveAuthorizationPart,- next: EveAuthorizationPart,-): EveMessageData {- const message = data.messages.find(- (candidate): candidate is EveAssistantMessage =>- candidate.role === "assistant" && candidate.parts.some((part) => part === existing),- );-- if (!message) {- return data;- }-- return upsertMessage(data, upsertPart(message, next));-}-function findToolPart(data: EveMessageData, toolCallId: string): EveDynamicToolPart | undefined {for (const message of data.messages) {for (const part of message.parts) {@@ -625,9 +627,10 @@ function isSettledToolPart(part: EveDynamicToolPart): boolean {);}-function findLatestPendingAuthorizationPart(+function findPendingAuthorizationPart(data: EveMessageData,name: string,+ attemptId: string | undefined,): EveAuthorizationPart | undefined {for (let messageIndex = data.messages.length - 1; messageIndex >= 0; messageIndex -= 1) {const message = data.messages[messageIndex];@@ -637,7 +640,13 @@ function findLatestPendingAuthorizationPart(for (let partIndex = message.parts.length - 1; partIndex >= 0; partIndex -= 1) {const part = message.parts[partIndex];- if (part?.type === "authorization" && part.state === "required" && part.name === name) {+ if (+ part?.type === "authorization" &&+ part.state === "required" &&+ (attemptId === undefined+ ? part.attemptId === undefined && part.name === name+ : part.attemptId === attemptId)+ ) {return part;}}diff --git a/packages/eve/src/client/message-run-parts.ts b/packages/eve/src/client/message-run-parts.tsindex 36fdfc772..275b01c2b 100644--- a/packages/eve/src/client/message-run-parts.ts+++ b/packages/eve/src/client/message-run-parts.ts@@ -3,63 +3,41 @@ import type { EveMessage, EveMessagePart } from "#client/message-reducer-types.jtype EveAssistantMessage = EveMessage & { readonly role: "assistant" };type EveRunPart = Extract<EveMessagePart, { readonly type: "text" | "reasoning" }>;-function append(+function transition(message: EveAssistantMessage,- append: {- readonly delta: string;+ input: {readonly stepIndex: number;readonly type: EveRunPart["type"];- },+ readonly id?: string;+ } & (+ | { readonly kind: "append"; readonly delta: string }+ | { readonly kind: "complete"; readonly text: string }+ ),): EveAssistantMessage {- const current = latestStreamingRun(message, append.type, append.stepIndex);- return upsert(message, {- state: "streaming",- stepIndex: append.stepIndex,- text: (current?.text ?? "") + append.delta,- type: append.type,- });-}--function latestStreamingRun(- message: EveAssistantMessage,- type: EveRunPart["type"],- stepIndex: number,-): EveRunPart | undefined {- for (let index = message.parts.length - 1; index >= 0; index -= 1) {- const part = message.parts[index];- if (part?.type === type && part.stepIndex === stepIndex) {- return part.state === "streaming" ? part : undefined;- }- }- return undefined;-}--// One step can produce text, call tools, then produce more text. Replace its-// open run in place; after completion, append a new run in arrival order.-function upsert(message: EveAssistantMessage, next: EveRunPart): EveAssistantMessage {- let lastIndex = -1;- for (let index = message.parts.length - 1; index >= 0; index -= 1) {- const part = message.parts[index];- if (part?.type === next.type && part.stepIndex === next.stepIndex) {- lastIndex = index;- break;- }- }-- const openRun =- lastIndex !== -1 && (message.parts[lastIndex] as EveRunPart).state === "streaming";- const parts = openRun- ? [...message.parts.slice(0, lastIndex), next, ...message.parts.slice(lastIndex + 1)]- : [...message.parts, next];-+ const index = message.parts.findLastIndex(+ (part) => part.type === input.type && part.stepIndex === input.stepIndex,+ );+ const previous = index === -1 ? undefined : (message.parts[index] as EveRunPart);+ if (input.kind === "append" && !input.delta) return message;+ const current = previous?.state === "streaming" ? previous : undefined;+ const part: EveRunPart = {+ id: current?.id ?? input.id ?? `${message.id}:${input.type}:${message.parts.length}`,+ state: input.kind === "append" ? "streaming" : "done",+ stepIndex: input.stepIndex,+ text: input.kind === "append" ? (current?.text ?? "") + input.delta : input.text,+ type: input.type,+ };+ const parts = current+ ? [...message.parts.slice(0, index), part, ...message.parts.slice(index + 1)]+ : [...message.parts, part];return {...message,metadata: {...message.metadata,- status: next.type === "text" && next.state === "done" ? "complete" : "streaming",+ status: input.type === "text" && part.state === "done" ? "complete" : "streaming",},parts,};}-export const messageRun = { append, upsert } as const;+export const messageRun = { transition } as const;diff --git a/packages/eve/src/client/optimistic-message-submissions.test.ts b/packages/eve/src/client/optimistic-message-submissions.test.tsindex d36643e74..c1fe3cba7 100644--- a/packages/eve/src/client/optimistic-message-submissions.test.ts+++ b/packages/eve/src/client/optimistic-message-submissions.test.ts@@ -3,7 +3,11 @@ import { EveAgentProjection } from "#client/eve-agent-projection.js";import { defaultMessageReducer } from "#client/message-reducer.js";import { OptimisticMessageSubmissions } from "#client/optimistic-message-submissions.js";import { stampTestEvents } from "#internal/testing/events.js";-import { createMessageReceivedEvent, type MessageStreamEvent } from "#protocol/message.js";+import {+ createMessageCompletedEvent,+ createMessageReceivedEvent,+ type MessageStreamEvent,+} from "#protocol/message.js";function received(message: string,@@ -22,7 +26,7 @@ function received(function setup(optimistic = true) {const projection = new EveAgentProjection(defaultMessageReducer(), []);- return { projection, submissions: new OptimisticMessageSubmissions(projection, optimistic) };+ return { projection, submissions: new OptimisticMessageSubmissions([projection], optimistic) };}describe("OptimisticMessageSubmissions", () => {@@ -72,6 +76,152 @@ describe("OptimisticMessageSubmissions", () => {});});+ it("places a coalesced follow-up before an already streamed reply", () => {+ const { projection, submissions } = setup();+ const first = submissions.submit({ message: "First" }, 0)!;+ submissions.correlate(first, "first", []);+ submissions.apply(received("First", ["first"]));+ const turnId = "turn_first";+ const reply = stampTestEvents([+ createMessageCompletedEvent({+ finishReason: "stop",+ message: "Reply",+ sequence: 1,+ stepIndex: 0,+ turnId,+ }),+ ])[0]!;+ submissions.apply(reply);++ const followUp = submissions.submit({ message: "Second" }, 2)!;+ submissions.correlate(followUp, "second", []);+ const secondReceived = received("Second", ["second"]);+ submissions.apply({+ ...secondReceived,+ data: { ...secondReceived.data, turnId },+ });++ expect(projection.data.messages.map((message) => message.role)).toEqual([+ "user",+ "user",+ "assistant",+ ]);+ expect(projection.data.messages[1]?.parts).toContainEqual({+ state: "done",+ text: "Second",+ type: "text",+ });+ });++ it("keeps the active-turn optimistic correction above the reply through reconciliation", () => {+ const { projection, submissions } = setup();+ submissions.apply(received("First", ["first"]));+ const reply = stampTestEvents([+ createMessageCompletedEvent({+ finishReason: "stop",+ message: "Reply",+ sequence: 1,+ stepIndex: 0,+ turnId: "turn_first",+ }),+ ])[0]!;+ submissions.apply(reply);+ const followUp = submissions.submit({ message: "Second" }, 2, "turn_first")!;+ expect(projection.data.messages.map((message) => message.role)).toEqual([+ "user",+ "user",+ "assistant",+ ]);+ submissions.correlate(followUp, "second", []);+ const secondReceived = received("Second", ["second"]);+ submissions.apply({+ ...secondReceived,+ data: { ...secondReceived.data, turnId: "turn_first" },+ });+ expect(projection.data.messages.map((message) => message.role)).toEqual([+ "user",+ "user",+ "assistant",+ ]);+ expect(projection.data.messages[1]?.metadata?.optimistic).toBeUndefined();+ });++ it("keeps a failed steered message ahead of its reply after replay", () => {+ const { projection, submissions } = setup();+ submissions.apply(received("First", ["first"]));+ submissions.apply(+ stampTestEvents([+ createMessageCompletedEvent({+ finishReason: "stop",+ message: "Reply",+ sequence: 1,+ stepIndex: 0,+ turnId: "turn_first",+ }),+ ])[0]!,+ );+ const id = submissions.submit({ message: "Second" }, 2, "turn_first")!;+ submissions.fail(new Error("Send failed"), id);+ expect(projection.data.messages.map((message) => message.role)).toEqual([+ "user",+ "user",+ "assistant",+ ]);+ expect(projection.data.messages[1]?.metadata?.status).toBe("failed");+ });++ it("replaces a coalesced pair with one server bubble before the reply", () => {+ const { projection, submissions } = setup();+ submissions.apply(received("First", ["first"]));+ submissions.apply(+ stampTestEvents([+ createMessageCompletedEvent({+ finishReason: "stop",+ message: "Reply",+ sequence: 1,+ stepIndex: 0,+ turnId: "turn_first",+ }),+ ])[0]!,+ );+ const a = submissions.submit({ message: "Second" }, 2, "turn_first")!;+ const b = submissions.submit({ message: "Third" }, 2, "turn_first")!;+ submissions.correlate(a, "second", []);+ submissions.correlate(b, "third", []);+ const coalesced = received("Second\n\nThird", ["second", "third"]);+ submissions.apply({ ...coalesced, data: { ...coalesced.data, turnId: "turn_first" } });+ expect(projection.data.messages.map((message) => message.role)).toEqual([+ "user",+ "user",+ "assistant",+ ]);+ expect(projection.data.messages[1]?.parts).toContainEqual({+ state: "done",+ text: "Second\n\nThird",+ type: "text",+ });+ });++ it("keeps the confirmed user message at its server position after an unrelated assistant", () => {+ const { projection, submissions } = setup();+ const followUp = submissions.submit({ message: "Second" }, 0)!;+ submissions.correlate(followUp, "second", []);+ submissions.apply(+ stampTestEvents([+ createMessageCompletedEvent({+ finishReason: "stop",+ message: "Other reply",+ sequence: 0,+ stepIndex: 0,+ turnId: "other",+ }),+ ])[0]!,+ );+ submissions.apply(received("Second", ["second"]));+ expect(projection.data.messages.map((message) => message.role)).toEqual(["assistant", "user"]);+ expect(projection.data.messages[1]?.metadata?.optimistic).toBeUndefined();+ });+it("reconciles structured file input without comparing summaries", () => {const { projection, submissions } = setup();const input = {diff --git a/packages/eve/src/client/optimistic-message-submissions.ts b/packages/eve/src/client/optimistic-message-submissions.tsindex 10eaed786..f9116de1c 100644--- a/packages/eve/src/client/optimistic-message-submissions.ts+++ b/packages/eve/src/client/optimistic-message-submissions.ts@@ -1,4 +1,4 @@-import { EveAgentProjection } from "#client/eve-agent-projection.js";+import type { EveAgentEventLog } from "#client/eve-agent-projection.js";import type { PendingMessageSubmission } from "#client/eve-agent-store-state.js";import { createSubmissionId, summarizeUserContent } from "#client/eve-agent-store-helpers.js";import type { MessageStreamEvent } from "#protocol/message.js";@@ -11,13 +11,13 @@ interface ReconciledSubmissions {}/** Owns optimistic message projection and server-delivery reconciliation. */-export class OptimisticMessageSubmissions<TData> {+export class OptimisticMessageSubmissions {readonly #optimistic: boolean;- readonly #projection: EveAgentProjection<TData>;+ readonly #projections: readonly EveAgentEventLog[];#pending: readonly PendingMessageSubmission[] = [];- constructor(projection: EveAgentProjection<TData>, optimistic: boolean) {- this.#projection = projection;+ constructor(projections: readonly EveAgentEventLog[], optimistic: boolean) {+ this.#projections = projections;this.#optimistic = optimistic;}@@ -25,33 +25,50 @@ export class OptimisticMessageSubmissions<TData> {this.#pending = [];}- submit(input: SendTurnPayload, eventStartIndex: number): string | undefined {+ submit(input: SendTurnPayload, eventStartIndex: number, turnId?: string): string | undefined {if (input.message === undefined) return undefined;const pending = {createdAt: Date.now(),eventStartIndex,id: createSubmissionId(),message: summarizeUserContent(input.message),+ turnId,requiresDeliveryId: true,};this.#pending = [...this.#pending, pending];if (this.#optimistic) {- this.#projection.append({- data: { createdAt: pending.createdAt, message: pending.message, submissionId: pending.id },- type: "client.message.submitted",- });+ for (const projection of this.#projections) {+ projection.append({+ data: {+ createdAt: pending.createdAt,+ message: pending.message,+ submissionId: pending.id,+ turnId,+ },+ type: "client.message.submitted",+ });+ }}return pending.id;}+ /** Re-echoes a submission whose payload `prepareSend` replaced, keeping its place in the stream. */+ resubmit(submissionId: string | undefined, input: SendTurnPayload): string | undefined {+ const pending = this.#pending.find((candidate) => candidate.id === submissionId);+ const message = input.message === undefined ? undefined : summarizeUserContent(input.message);+ if (pending?.message === message) return submissionId;+ if (pending !== undefined) this.#withdraw([pending.id]);+ return this.submit(input, pending?.eventStartIndex ?? 0, pending?.turnId);+ }+apply(event: MessageStreamEvent): ReconciledSubmissions | undefined {if (event.type !== "message.received") {- this.#projection.append(event);+ for (const projection of this.#projections) projection.append(event);return undefined;}const matching = this.#matching(event);if (matching.length === 0) {- this.#projection.append(event);+ for (const projection of this.#projections) projection.append(event);return undefined;}return this.#reconcile(matching, event, false);@@ -87,19 +104,22 @@ export class OptimisticMessageSubmissions<TData> {: this.#pending.find((candidate) => candidate.id === submissionId);if (pending === undefined) return;this.#pending = this.#pending.filter((candidate) => candidate.id !== pending.id);- this.#projection.replace(- (event) =>- event.type === "client.message.submitted" && event.data.submissionId === pending.id,- {- data: {- createdAt: pending.createdAt,- error: { message: error.message },- message: pending.message,- submissionId: pending.id,+ for (const projection of this.#projections) {+ projection.replace(+ (event) =>+ event.type === "client.message.submitted" && event.data.submissionId === pending.id,+ {+ data: {+ createdAt: pending.createdAt,+ error: { message: error.message },+ message: pending.message,+ submissionId: pending.id,+ turnId: pending.turnId,+ },+ type: "client.message.failed",},- type: "client.message.failed",- },- );+ );+ }}failAll(error: Error): void {@@ -120,24 +140,19 @@ export class OptimisticMessageSubmissions<TData> {alreadyProjected: boolean,): ReconciledSubmissions {const ids = submissions.map((pending) => pending.id);+ this.#withdraw(ids);+ if (!alreadyProjected) for (const projection of this.#projections) projection.append(event);+ return { alreadyProjected, event, ids };+ }++ #withdraw(ids: readonly string[]): void {const idSet = new Set(ids);this.#pending = this.#pending.filter((pending) => !idSet.has(pending.id));- if (alreadyProjected) {- this.#projection.remove(- (candidate) =>- candidate.type === "client.message.submitted" && idSet.has(candidate.data.submissionId),- );- } else {- this.#projection.replace(- (candidate) =>- candidate.type === "client.message.submitted" && candidate.data.submissionId === ids[0],- event,- );- this.#projection.remove(+ for (const projection of this.#projections) {+ projection.remove((candidate) =>candidate.type === "client.message.submitted" && idSet.has(candidate.data.submissionId),);}- return { alreadyProjected, event, ids };}}diff --git a/packages/eve/src/client/reducer.ts b/packages/eve/src/client/reducer.tsindex 529368613..06f2eb1e5 100644--- a/packages/eve/src/client/reducer.ts+++ b/packages/eve/src/client/reducer.ts@@ -10,6 +10,8 @@ export interface ClientMessageSubmittedEvent {readonly createdAt: number;readonly message: string;readonly submissionId: string;+ /** Active turn receiving a steered follow-up, when known. */+ readonly turnId?: string;};readonly type: "client.message.submitted";}@@ -26,6 +28,8 @@ export interface ClientMessageFailedEvent {};readonly message: string;readonly submissionId: string;+ /** Active turn receiving a steered follow-up, when known. */+ readonly turnId?: string;};readonly type: "client.message.failed";}@@ -47,7 +51,7 @@ export interface ClientInputRespondedEvent {** Server events are authoritative eve stream events. They include text,* reasoning, tool/action requests and results, HITL input requests, connection- * authorization events, subagent events, and session lifecycle events. Client+ * authorization events, task and agent-session events, and session lifecycle events. Client* events are projection-only events created by client state machines for local* UI state such as optimistic user messages and submitted HITL responses.*/diff --git a/packages/eve/src/client/session-turn-dispatch.ts b/packages/eve/src/client/session-turn-dispatch.tsnew file mode 100644index 000000000..09f4d2528--- /dev/null+++ b/packages/eve/src/client/session-turn-dispatch.ts@@ -0,0 +1,31 @@+import type { Client } from "#client/client.js";+import type { MessageResponse } from "#client/message-response.js";+import type { ClientSession } from "#client/session.js";+import type { SendTurnPayload } from "#client/types.js";++/** Send one turn through an owned or attached session, without choosing how to consume its stream. */+export async function dispatchSessionTurn<TOutput>(input: {+ client?: Client;+ session?: ClientSession;+ turn: SendTurnPayload<TOutput>;+ beforeSend?: () => void;+}): Promise<{ session: ClientSession; response: MessageResponse<TOutput>; created: boolean }> {+ const { client, session, turn, beforeSend } = input;+ if (session === undefined) {+ if (client === undefined)+ throw new Error("An external eve session is required before sending.");+ if (turn.message === undefined)+ throw new Error("Cannot answer an input request before the session starts.");+ const created = await client.sessions.create({ ...turn, message: turn.message });+ turn.signal?.throwIfAborted();+ return { ...created, created: true };+ }++ beforeSend?.();+ if (turn.inputResponses === undefined) {+ const { message, ...options } = turn;+ return { session, response: await session.send(message, options), created: false };+ }+ const { inputResponses, ...options } = turn;+ return { session, response: await session.respond(inputResponses, options), created: false };+}diff --git a/packages/eve/src/client/session-utils.test.ts b/packages/eve/src/client/session-utils.test.tsindex 99b00dfe4..c55fda665 100644--- a/packages/eve/src/client/session-utils.test.ts+++ b/packages/eve/src/client/session-utils.test.ts@@ -49,6 +49,82 @@ describe("summarizeTurnEvents", () => {});});+ it("reports only unresolved requests after approval settlement or input resolution", () => {+ const request = (requestId: string) => ({+ action: {+ callId: `call_${requestId}`,+ input: {},+ kind: "tool-call" as const,+ toolName: "bash",+ },+ display: "confirmation" as const,+ kind: "tool-approval" as const,+ options: [{ id: "approve", label: "Approve" }],+ prompt: "Approve?",+ requestId,+ });+ const events = [+ {+ type: "input.requested",+ data: {+ ...eventData,+ requests: [request("settled"), request("resolved"), request("open")],+ },+ },+ {+ type: "approval.settled",+ data: {+ ...eventData,+ outcome: "approved",+ requestId: "settled",+ responderPrincipalId: "alice",+ },+ },+ {+ type: "input.resolved",+ data: {+ ...eventData,+ resolutions: [{ kind: "tool-approval", outcome: "denied", requestId: "resolved" }],+ },+ },+ {+ type: "session.waiting",+ data: { continuationToken: "session-id", wait: "next-user-message" },+ },+ ] satisfies UnstampedMessageStreamEvent[];+ expect(summarizeTurnEvents(events).inputRequests).toEqual([request("open")]);+ });++ it("keeps an independent same-name attempt pending until its own completion", () => {+ const required = (attemptId: string) => ({+ type: "authorization.required" as const,+ data: { ...eventData, attemptId, description: "Sign in", name: "linear" },+ });+ const events = [+ required("alice"),+ required("bob"),+ {+ type: "authorization.completed",+ data: { ...eventData, attemptId: "alice", name: "linear", outcome: "authorized" },+ },+ ] satisfies UnstampedMessageStreamEvent[];+ expect(summarizeTurnEvents(events).pendingAuthorizations).toEqual([required("bob").data]);+ });++ it("does not clear a legacy name-only attempt with an unrelated identified completion", () => {+ const events = [+ {+ type: "authorization.required",+ data: { ...eventData, description: "Sign in", name: "linear" },+ },+ {+ type: "authorization.completed",+ data: { ...eventData, attemptId: "alice", name: "linear", outcome: "authorized" },+ },+ ] satisfies UnstampedMessageStreamEvent[];+ expect(summarizeTurnEvents(events).pendingAuthorizations).toEqual([events[0]!.data]);+ });+it("removes completed authorizations and retains the final turn failure", () => {const events = [{diff --git a/packages/eve/src/client/session-utils.ts b/packages/eve/src/client/session-utils.tsindex 71b2ce8bd..9d8af0d25 100644--- a/packages/eve/src/client/session-utils.ts+++ b/packages/eve/src/client/session-utils.ts@@ -1,7 +1,6 @@import type {AuthorizationRequiredStreamEvent,MessageCompletedStreamEvent,- MessageStreamEvent,TurnFailureStreamEvent,UnstampedMessageStreamEvent,} from "#protocol/message.js";@@ -13,6 +12,7 @@ interface PendingAuthorization {readonly authorization?: AuthorizationRequiredStreamEvent["data"]["authorization"];readonly description: string;readonly name: string;+ readonly attemptId?: string;readonly webhookUrl?: string;}@@ -30,35 +30,25 @@ interface TurnEventSummary {export function summarizeTurnEvents(events: readonly UnstampedMessageStreamEvent[],): TurnEventSummary {+ const segment = new TurnSegment();let boundary: UnstampedMessageStreamEvent | undefined;let failure: TurnFailureStreamEvent | undefined;let message: string | undefined;- const inputRequests: InputRequest[] = [];- const pendingInputRequests = new Set<string>();- const pendingAuthorizations = new Map<string, PendingAuthorization>();for (const event of events) {- updatePendingInputRequests(pendingInputRequests, event);- if (isTurnSegmentBoundary(event, pendingInputRequests)) boundary = event;+ if (segment.observe(event)) boundary = event;if (isTurnFailureEvent(event)) failure = event;if (isFinalMessageCompleted(event)) message = event.data.message ?? undefined;// Text completed before the turn parked was interim; the reply comes after it resumes.if (event.type === "turn.waiting") message = undefined;- if (event.type === "input.requested") inputRequests.push(...event.data.requests);- if (event.type === "authorization.required") {- pendingAuthorizations.set(event.data.name, event.data);- }- if (event.type === "authorization.completed") {- pendingAuthorizations.delete(event.data.name);- }}return {boundary,failure,- inputRequests,+ inputRequests: segment.inputRequests,message,- pendingAuthorizations: [...pendingAuthorizations.values()],+ pendingAuthorizations: segment.pendingAuthorizations,status: summarizeBoundaryStatus(boundary),};}@@ -76,39 +66,76 @@ export async function collectTurnEvents(stream: AsyncIterable<UnstampedMessageStreamEvent>,): Promise<readonly UnstampedMessageStreamEvent[]> {const events: UnstampedMessageStreamEvent[] = [];- const pendingInputRequests = new Set<string>();+ const segment = new TurnSegment();for await (const event of stream) {events.push(event);- updatePendingInputRequests(pendingInputRequests, event);- if (isTurnSegmentBoundary(event, pendingInputRequests)) break;+ if (segment.observe(event)) break;}return events;}/**- * Returns true when one segment of a turn's events ends at `event`: at a- * current-turn boundary, or at `turn.waiting` while an input request read in- * the segment is unanswered. The turn stays open there until a person answers;- * without a pending request, `turn.waiting` is informational and reading goes- * on to the turn's real end.+ * Returns true when a read of a session's events ends at `event`: at a current-turn boundary, or+ * at `turn.waiting` while a request is unanswered. The turn stays open there until a person+ * answers; otherwise `turn.waiting` is informational and reading goes on to the turn's real end.+ * A reader that follows sign-in callbacks also reads past `session.waiting` while one is+ * outstanding, because the callback resumes the same turn.*/-export function isTurnSegmentBoundary(+export function endsTurnSegment(event: UnstampedMessageStreamEvent,- pendingInputRequests: ReadonlySet<string>,+ open: { readonly callbacks: boolean; readonly requests: boolean },): boolean {- if (event.type === "turn.waiting") return pendingInputRequests.size > 0;- return isCurrentTurnBoundaryEvent(event);+ if (event.type === "turn.waiting") return open.requests;+ return isCurrentTurnBoundaryEvent(event) && (event.type !== "session.waiting" || !open.callbacks);}-/** Tracks the input requests read in a segment that no `input.resolved` has answered yet. */-export function updatePendingInputRequests(- pending: Set<string>,- event: UnstampedMessageStreamEvent,-): void {- if (event.type === "input.requested") {- for (const request of event.data.requests) pending.add(request.requestId);- } else if (event.type === "input.resolved") {- for (const resolution of event.data.resolutions) pending.delete(resolution.requestId);+/** The requests and sign-ins one segment of a session's events leaves open. */+export class TurnSegment {+ readonly #authorizations = new Map<string, PendingAuthorization>();+ readonly #followCallbacks: boolean;+ readonly #requests = new Map<string, InputRequest>();++ constructor(options: { readonly followCallbacks?: boolean } = {}) {+ this.#followCallbacks = options.followCallbacks === true;+ }++ get inputRequests(): readonly InputRequest[] {+ return [...this.#requests.values()];+ }++ get pendingAuthorizations(): readonly PendingAuthorization[] {+ return [...this.#authorizations.values()];+ }++ /** Records `event` and returns true when it ends the segment. */+ observe(event: UnstampedMessageStreamEvent): boolean {+ switch (event.type) {+ case "input.requested":+ for (const request of event.data.requests) this.#requests.set(request.requestId, request);+ break;+ case "approval.settled":+ this.#requests.delete(event.data.requestId);+ break;+ case "input.resolved":+ for (const resolution of event.data.resolutions) {+ this.#requests.delete(resolution.requestId);+ }+ break;+ case "authorization.required":+ this.#authorizations.set(authorizationKey(event.data), event.data);+ break;+ case "authorization.completed":+ this.#authorizations.delete(authorizationKey(event.data));+ break;+ }+ return endsTurnSegment(event, {+ callbacks:+ this.#followCallbacks &&+ [...this.#authorizations.values()].some(+ (authorization) => authorization.webhookUrl !== undefined,+ ),+ requests: this.#requests.size > 0,+ });}}@@ -118,10 +145,9 @@ function isFinalMessageCompleted(return event.type === "message.completed" && event.data.finishReason !== "tool-calls";}-export function updatePendingAuthorizations(pending: Set<string>, event: MessageStreamEvent): void {- if (event.type === "authorization.required" && event.data.webhookUrl !== undefined) {- pending.add(event.data.name);- } else if (event.type === "authorization.completed") {- pending.delete(event.data.name);- }+export function authorizationKey(data: {+ readonly name: string;+ readonly attemptId?: string;+}): string {+ return data.attemptId === undefined ? `name:${data.name}` : `attempt:${data.attemptId}`;}diff --git a/packages/eve/src/client/session.ts b/packages/eve/src/client/session.tsindex 95401f4d0..75928736d 100644--- a/packages/eve/src/client/session.ts+++ b/packages/eve/src/client/session.ts@@ -1,8 +1,4 @@-import {- isTurnSegmentBoundary,- updatePendingAuthorizations,- updatePendingInputRequests,-} from "#client/session-utils.js";+import { TurnSegment } from "#client/session-utils.js";import type { AgentStartedStreamEvent, MessageStreamEvent } from "#protocol/message.js";import { EVE_SESSION_ID_HEADER } from "#protocol/message.js";import {@@ -253,8 +249,7 @@ export class ClientSession {let eventCount = 0;let started = deliveryId === undefined;let reachedBoundary = false;- const pendingAuthorizations = new Set<string>();- const pendingInputRequests = new Set<string>();+ const segment = new TurnSegment({ followCallbacks: true });try {for await (const event of source ??this.#readStream({@@ -277,11 +272,7 @@ export class ClientSession {if (!terminal && event.meta?.deliveryIds !== undefined && !matches) continue;started = true;}- updatePendingAuthorizations(pendingAuthorizations, event);- updatePendingInputRequests(pendingInputRequests, event);- reachedBoundary =- isTurnSegmentBoundary(event, pendingInputRequests) &&- (event.type !== "session.waiting" || pendingAuthorizations.size === 0);+ reachedBoundary = segment.observe(event);yield event;if (reachedBoundary) {break;diff --git a/packages/eve/src/client/types.ts b/packages/eve/src/client/types.tsindex 8e95a00e0..57adc9883 100644--- a/packages/eve/src/client/types.ts+++ b/packages/eve/src/client/types.ts@@ -294,7 +294,8 @@ export interface MessageResult<TOutput = unknown> {readonly events: MessageStreamEvent[];/**- * HITL input requests emitted during this turn.+ * HITL input requests emitted in this response and still open at its boundary.+ * Earlier requests may remain open in the same session.*/readonly inputRequests: readonly InputRequest[];diff --git a/packages/eve/src/evals/session.ts b/packages/eve/src/evals/session.tsindex 8c6917664..f33e7d59e 100644--- a/packages/eve/src/evals/session.ts+++ b/packages/eve/src/evals/session.ts@@ -18,11 +18,7 @@ import type {TurnFailureStreamEvent,} from "#protocol/message.js";import { isTurnFailureEvent } from "#protocol/message.js";-import {- isTurnSegmentBoundary,- summarizeTurnEvents,- updatePendingInputRequests,-} from "#client/session-utils.js";+import { summarizeTurnEvents, TurnSegment } from "#client/session-utils.js";import { extractCompletedResult } from "#client/output-schema.js";import type { InputRequest, InputResponse } from "#shared/input.js";import { deriveRunFacts } from "#evals/runner/derive-run-facts.js";@@ -451,10 +447,10 @@ class EvalLiveTurn implements EveEvalLiveTurn {): Promise<EveEvalTurn> {try {let sawBoundary = false;- const pendingInputRequests = new Set<string>();+ const segment = new TurnSegment();for await (const event of source) {this.#events.push(event);- updatePendingInputRequests(pendingInputRequests, event);+ const endsSegment = segment.observe(event);observe(event);this.#resolveWaiters(event);@@ -466,7 +462,7 @@ class EvalLiveTurn implements EveEvalLiveTurn {);}- if (isTurnSegmentBoundary(event, pendingInputRequests)) {+ if (endsSegment) {sawBoundary = true;this.#closeWaiters(new Error(`Session ${this.sessionId} reached ${event.type} before the expected event.`),diff --git a/packages/eve/src/harness/issue-3494-adversarial.integration.test.ts b/packages/eve/src/harness/issue-3494-adversarial.integration.test.tsindex 16306e9ce..e17f3f154 100644--- a/packages/eve/src/harness/issue-3494-adversarial.integration.test.ts+++ b/packages/eve/src/harness/issue-3494-adversarial.integration.test.ts@@ -667,6 +667,47 @@ it("does not announce waiting while a candidate needs sign-in, then completes onexpect(f.pending()).toHaveLength(1);});+it("announces a candidate's sign-in with the attempt its completion will name", async () => {+ const f = fixture("candidate-sign-in-attempt", () => ({ status: "allowed" as const }));+ await f.gate("gateA");+ await f.step({+ attributedInputResponses: f.respond("gateA").inputResponses!.map((response) => ({+ response,+ auth: {+ attributes: {},+ authenticator: "test",+ issuer: "test",+ principalId: "alice",+ principalType: "user" as const,+ },+ })),+ });+ const candidate = getApprovalAuditState(f.session.state).activeCandidates[0]!;+ f.updateSession((session) => ({+ ...session,+ state: markApprovalCandidateAuthorizationRequired({+ state: session.state,+ candidateId: candidate.candidateId,+ authorizationChallenges: [+ {+ attemptId: "attempt_alice",+ candidateId: candidate.candidateId,+ name: "notes",+ hookUrl: "https://example.com/callback",+ challenge: { url: "https://example.com/sign-in" },+ },+ ],+ }),+ }));+ const start = f.events.length;+ await f.drive();+ expect(+ f.events.slice(start).find((event) => event.type === "authorization.required"),+ ).toMatchObject({+ data: { attemptId: "attempt_alice", candidateId: candidate.candidateId, name: "notes" },+ });+});+it("uses the normal turn boundary for a mixed accepted and refused delivery", async () => {const f = fixture("mixed-response", ({ request }) =>request.toolName === "gateA"diff --git a/packages/eve/src/internal/testing/events.ts b/packages/eve/src/internal/testing/events.tsindex 4025c5575..5314c916d 100644--- a/packages/eve/src/internal/testing/events.ts+++ b/packages/eve/src/internal/testing/events.ts@@ -1,5 +1,5 @@import type { UnstampedMessageStreamEvent, MessageStreamEvent } from "#protocol/message.js";-import { isTurnSegmentBoundary, updatePendingInputRequests } from "#client/session-utils.js";+import { TurnSegment } from "#client/session-utils.js";/*** Minimal, duck-typed handle to one workflow `Run`'s readable stream.@@ -65,7 +65,8 @@ export function captureTurnEvents(return {async nextTurn() {- return await readUntil(createTurnSegmentBoundary());+ const segment = new TurnSegment();+ return await readUntil((event) => segment.observe(event));},async nextUntil(matches) {return await readUntil(matches);@@ -157,14 +158,6 @@ interface StreamState {buffer: string;}-function createTurnSegmentBoundary(): (event: MessageStreamEvent) => boolean {- const pendingInputRequests = new Set<string>();- return (event) => {- updatePendingInputRequests(pendingInputRequests, event);- return isTurnSegmentBoundary(event, pendingInputRequests);- };-}-async function readUntilMatch(reader: ReadableStreamDefaultReader<Uint8Array>,state: StreamState,diff --git a/packages/eve/src/protocol/message.ts b/packages/eve/src/protocol/message.tsindex da0d4008d..2895611f9 100644--- a/packages/eve/src/protocol/message.ts+++ b/packages/eve/src/protocol/message.ts@@ -1428,12 +1428,12 @@ export function createTaskStartedEvent(/** Creates the `task.settled` event for one settled task call. */export function createTaskSettledEvent(- input: TaskSettledStreamEvent["data"] & Pick<TaskStartedStreamEvent["data"], "kind" | "name">,+ input: TaskSettledStreamEvent["data"],): TaskSettledStreamEvent {const data: TaskSettledStreamEvent["data"] = {callId: input.callId,- kind: input.kind,- name: input.name,+ ...(input.kind !== undefined && { kind: input.kind }),+ ...(input.name !== undefined && { name: input.name }),status: input.status,taskId: input.taskId,turnId: input.turnId,diff --git a/packages/eve/src/react/index.ts b/packages/eve/src/react/index.tsindex 1cfa9f740..f0b62804e 100644--- a/packages/eve/src/react/index.ts+++ b/packages/eve/src/react/index.ts@@ -14,6 +14,17 @@ export {type ClientMessageFailedEvent,type ClientMessageSubmittedEvent,} from "#client/reducer.js";+export { conversationReducer } from "#client/conversation-reducer.js";+export { openConversationInputs } from "#client/conversation-state.js";+export type {+ AgentObservation,+ ConversationAgentSession,+ ConversationInput,+ ConversationState,+ ConversationTask,+ ConversationTaskCall,+ ConversationTurn,+} from "#client/conversation-state.js";export {defaultMessageReducer,type EveAuthorizationChallenge,diff --git a/packages/eve/src/react/use-eve-agent.test.ts b/packages/eve/src/react/use-eve-agent.test.tsindex 92ebc0934..75d2f7b93 100644--- a/packages/eve/src/react/use-eve-agent.test.ts+++ b/packages/eve/src/react/use-eve-agent.test.ts@@ -4,6 +4,7 @@ import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitestimport { useEveAgent, type UseEveAgentHelpers } from "#react/use-eve-agent.js";import type { EveMessageData } from "#client/message-reducer.js";+import type { ConversationState } from "#client/conversation-state.js";import {EVE_MESSAGE_STREAM_VERSION,EVE_SESSION_ID_HEADER,@@ -76,6 +77,10 @@ function createAbortError(): Error {function optimisticUserData(message: string, status: "failed" | "submitted") {return {+ tasks: {},+ agents: {},+ inputs: {},+ turns: {},messages: [{id: expect.stringMatching(/^optimistic:/),@@ -94,8 +99,12 @@ function completedTurnData(input: {readonly assistantMessage?: string;readonly turnId: string;readonly userMessage: string;-}): EveMessageData {+}): ConversationState {return {+ tasks: {},+ agents: {},+ inputs: {},+ turns: {},messages: [{id: expect.stringMatching(/^evt_.+:user$/),@@ -118,6 +127,7 @@ function completedTurnData(input: {parts: [{ type: "step-start" as const },{+ id: expect.stringMatching(/^evt_/),state: "done" as const,stepIndex: 0,text: input.assistantMessage,diff --git a/packages/eve/src/react/use-eve-agent.ts b/packages/eve/src/react/use-eve-agent.tsindex 82bad1b02..88d6151b7 100644--- a/packages/eve/src/react/use-eve-agent.ts+++ b/packages/eve/src/react/use-eve-agent.ts@@ -12,7 +12,8 @@ import {import { resolveEveAgentHost } from "#client/agent-host.js";import type { EveAgentReducer } from "#client/reducer.js";import type { ClientSession } from "#client/session.js";-import { defaultMessageReducer, type EveMessageData } from "#client/message-reducer.js";+import { conversationReducer } from "#client/conversation-reducer.js";+import type { ConversationState } from "#client/conversation-state.js";import type { MessageStreamEvent } from "#protocol/message.js";import type { UserContent } from "ai";import type {@@ -38,9 +39,9 @@ export type { PrepareSend };export type UseEveAgentStatus = EveAgentStoreStatus;/**- * Snapshot of an eve agent session: `data` (the reducer projection), `events`- * (the authoritative server stream), `session` (resumable cursor), `status`,- * and `error`.+ * Snapshot of an eve agent session: `conversation` (canonical state), `data`+ * (the selected view), `events` (the authoritative server stream), `session`+ * (resumable cursor), `status`, and `error`.*/export type UseEveAgentSnapshot<TData> = EveAgentStoreSnapshot<TData>;@@ -111,6 +112,8 @@ export interface UseEveAgentOptions<TData> extends EveAgentStoreCallbacks<TData>* @default true*/readonly optimistic?: boolean;+ /** Follow each subagent call's session into `conversation.agents` while mounted. @default false */+ readonly followSubagents?: boolean;/*** Prewarm an owned session when true. React observes this value across renders;* changing it from false to true prepares the current session, and reset checks@@ -134,8 +137,8 @@ export interface UseEveAgentOptions<TData> extends EveAgentStoreCallbacks<TData>}export function useEveAgent(- options?: UseEveAgentOptions<EveMessageData>,-): UseEveAgentHelpers<EveMessageData>;+ options?: UseEveAgentOptions<ConversationState>,+): UseEveAgentHelpers<ConversationState>;export function useEveAgent<TData>(options: UseEveAgentOptions<TData> & { readonly reducer: EveAgentReducer<TData> },@@ -146,8 +149,8 @@ export function useEveAgent<TData>(** Returns the current snapshot (`data`, `events`, `session`, `status`, `error`)* plus the commands `prewarm`, `send`, `respond`, `resume`, `cancel`, and `reset`. With no reducer, `data` is the- * built-in `UIMessage` projection from {@link defaultMessageReducer} (`TData`- * is {@link EveMessageData}); pass a reducer to project into your own shape and+ * built-in conversation projection (including UIMessage-compatible `messages`);+ * pass a reducer to project into your own shape and* infer `TData`.** Session-shaping options (`host`, `reducer`, `session`, `initialEvents`,@@ -173,7 +176,7 @@ export function useEveAgent<TData>() {throw new Error("useEveAgent({ resume: true }) requires initialSession or session.");}- const reducer = options.reducer ?? (defaultMessageReducer() as EveAgentReducer<TData>);+ const reducer = options.reducer ?? (conversationReducer as EveAgentReducer<TData>);storeRef.current = new EveAgentStore({auth: options.auth,headers: options.headers,@@ -181,6 +184,7 @@ export function useEveAgent<TData>(initialEvents: options.initialEvents,initialSession: options.initialSession,optimistic: options.optimistic,+ followSubagents: options.followSubagents,reducer,session: options.session,});diff --git a/packages/eve/src/setup/scaffold/create/web-template.ts b/packages/eve/src/setup/scaffold/create/web-template.tsindex 08f2f9f39..3d3101ccb 100644--- a/packages/eve/src/setup/scaffold/create/web-template.ts+++ b/packages/eve/src/setup/scaffold/create/web-template.ts@@ -3,9 +3,9 @@export const WEB_APP_TEMPLATE_FILES = {"app/_components/agent-chat.tsx":- '"use client";\n\nimport type { UserContent } from "ai";\nimport { useEveAgent } from "eve/react";\nimport { AlertCircleIcon, BrainIcon, PlusIcon, SquareIcon } from "lucide-react";\nimport { useState } from "react";\nimport {\n Conversation,\n ConversationContent,\n ConversationScrollButton,\n ConversationTopFade,\n} from "@/components/ai-elements/conversation";\nimport { Message, MessageContent } from "@/components/ai-elements/message";\nimport {\n PromptInput,\n PromptInputButton,\n type PromptInputMessage,\n PromptInputSubmit,\n PromptInputTextarea,\n usePromptInputAttachments,\n} from "@/components/ai-elements/prompt-input";\nimport { Shimmer } from "@/components/ai-elements/shimmer";\nimport { Button } from "@/components/ui/button";\nimport { cn } from "@/lib/utils";\nimport { AgentMessage } from "./agent-message";\nimport { WEB_CHAT_AGENT } from "@/app/eve-agent";\n\nconst DEFAULT_AGENT_NAME = "__EVE_INIT_APP_NAME__";\nconst AGENT_NAME = WEB_CHAT_AGENT ?? DEFAULT_AGENT_NAME;\n\nexport function AgentChat({\n sessionId,\n sessionless = false,\n}: {\n readonly sessionId?: string;\n readonly sessionless?: boolean;\n}) {\n const [cancellationError, setCancellationError] = useState<string>();\n const [hasInputText, setHasInputText] = useState(false);\n const agent = useEveAgent({\n agent: WEB_CHAT_AGENT,\n initialSession:\n sessionId === undefined\n ? undefined\n : {\n sessionId,\n streamIndex: 0,\n },\n resume: sessionId !== undefined,\n onSessionChange(session) {\n if (sessionId === undefined && session !== undefined) {\n // Next patches window.history to navigate, which would detach the active stream.\n History.prototype.replaceState.call(\n window.history,\n window.history.state,\n "",\n `/s/${encodeURIComponent(session.sessionId)}`,\n );\n }\n },\n });\n\n const isBusy = agent.status === "submitted" || agent.status === "streaming";\n const isResuming = agent.status === "resuming";\n const isEmpty = agent.data.messages.length === 0;\n const lastMessage = agent.data.messages.at(-1);\n const isPendingAssistantShell =\n lastMessage?.role === "assistant" &&\n lastMessage.parts.every((part) => part.type === "step-start");\n const showPendingThinking =\n isBusy &&\n (agent.status === "submitted" || lastMessage?.role !== "assistant" || isPendingAssistantShell);\n const turnFailure = isBusy || isResuming ? undefined : getLatestTurnFailure(agent.events);\n const errorMessage = cancellationError ?? agent.error?.message ?? turnFailure;\n const hasConversationContent = sessionless || !isEmpty || errorMessage !== undefined;\n const showConversationLayout = isResuming || hasConversationContent;\n const activeSessionId = sessionId ?? agent.session?.sessionId;\n\n const requestCancellation = () => {\n setCancellationError(undefined);\n void agent.cancel().catch((error: unknown) => {\n setCancellationError(toErrorMessage(error));\n });\n };\n\n const handleSubmit = async (message: PromptInputMessage) => {\n const text = message.text.trim();\n if ((text.length === 0 && message.files.length === 0) || isResuming) return;\n\n setHasInputText(false);\n setCancellationError(undefined);\n const options = isBusy ? { turnPolicy: "steer" as const } : undefined;\n\n if (message.files.length === 0) {\n await agent.send(text, options);\n return;\n }\n\n const parts: UserContent = [];\n if (text.length > 0) {\n parts.push({ text, type: "text" });\n }\n for (const file of message.files) {\n parts.push({\n data: file.url,\n filename: file.filename,\n mediaType: file.mediaType,\n type: "file",\n });\n }\n\n await agent.send(parts, options);\n };\n\n const composer = (\n <PromptInput onSubmit={handleSubmit}>\n <PromptInputTextarea\n disabled={isResuming}\n onChange={(event) => setHasInputText(event.currentTarget.value.trim().length > 0)}\n placeholder="Send a message…"\n />\n <ComposerAction\n hasInputText={hasInputText}\n isBusy={isBusy}\n isResuming={isResuming}\n onCancel={requestCancellation}\n />\n </PromptInput>\n );\n\n return (\n <main className="flex h-dvh flex-col overflow-hidden bg-background text-foreground">\n {showConversationLayout ? (\n <ChatHeader canStartNewChat={activeSessionId !== undefined} />\n ) : null}\n\n {showConversationLayout ? (\n <Conversation\n className="min-h-0 flex-1"\n initial={sessionId === undefined ? undefined : false}\n resize={activeSessionId === undefined ? "smooth" : "instant"}\n scrollRestorationKey={\n isEmpty || activeSessionId === undefined\n ? undefined\n : `eve:web-chat-scroll:${activeSessionId}`\n }\n >\n <ConversationTopFade className="top-14" />\n <ConversationContent className="mx-auto w-full max-w-3xl gap-6 px-4 pt-20 pb-36 sm:px-6">\n {agent.data.messages.map((message, index) =>\n showPendingThinking &&\n isPendingAssistantShell &&\n message.id === lastMessage.id ? null : (\n <AgentMessage\n canRespond={!isBusy && !isResuming}\n isStreaming={\n agent.status === "streaming" && index === agent.data.messages.length - 1\n }\n key={message.id}\n message={message}\n onInputResponses={(inputResponses) => {\n setCancellationError(undefined);\n return agent.respond(inputResponses);\n }}\n />\n ),\n )}\n {showPendingThinking ? <PendingThinking /> : null}\n {errorMessage ? <ErrorMessage message={errorMessage} /> : null}\n </ConversationContent>\n <ConversationScrollButton />\n </Conversation>\n ) : null}\n\n <div\n className={cn(\n "mx-auto w-full px-4 sm:px-6",\n showConversationLayout\n ? "fixed bottom-0 left-1/2 z-20 max-w-3xl -translate-x-1/2 bg-gradient-to-t from-background via-background to-transparent pt-4 pb-6"\n : "flex max-w-xl flex-1 flex-col items-center justify-center gap-8 pb-[10vh]",\n )}\n >\n {showConversationLayout ? null : (\n <div className="flex flex-col items-center gap-3 text-center">\n <h1 className="font-medium text-5xl tracking-tighter">{AGENT_NAME}</h1>\n </div>\n )}\n <div className="w-full">{composer}</div>\n </div>\n </main>\n );\n}\n\nfunction ComposerAction({\n hasInputText,\n isBusy,\n isResuming,\n onCancel,\n}: {\n readonly hasInputText: boolean;\n readonly isBusy: boolean;\n readonly isResuming: boolean;\n readonly onCancel: () => void;\n}) {\n const attachments = usePromptInputAttachments();\n const canSubmit = hasInputText || attachments.files.length > 0;\n\n if (!isBusy || canSubmit) {\n return <PromptInputSubmit disabled={isResuming} />;\n }\n\n return (\n <PromptInputButton\n aria-label="Stop"\n className="absolute right-2.5 bottom-2.5"\n onClick={onCancel}\n variant="outline"\n >\n <SquareIcon className="size-3 fill-current" />\n </PromptInputButton>\n );\n}\n\nfunction ErrorMessage({ message }: { readonly message: string }) {\n return (\n <Message className="max-w-full" from="assistant">\n <MessageContent>\n <div\n className="flex w-full items-start gap-3 rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2.5 text-sm"\n role="alert"\n >\n <AlertCircleIcon className="mt-0.5 size-4 shrink-0 text-destructive" />\n <div>\n <p className="font-medium">Request failed</p>\n <p className="mt-0.5 text-muted-foreground">{message}</p>\n </div>\n </div>\n </MessageContent>\n </Message>\n );\n}\n\nfunction ChatHeader({ canStartNewChat }: { readonly canStartNewChat: boolean }) {\n return (\n <header className="pointer-events-none fixed top-0 right-0 left-0 z-20 h-14">\n <div className="relative mx-auto flex h-full w-full max-w-3xl items-center justify-center bg-background px-24">\n <span className="truncate text-muted-foreground text-sm">{AGENT_NAME}</span>\n {canStartNewChat ? (\n <Button\n aria-label="Start a new chat"\n className="pointer-events-auto fixed top-3 right-6 pr-4"\n onClick={() => window.location.assign("/s")}\n size="sm"\n type="button"\n variant="ghost"\n >\n <PlusIcon className="size-4" />\n <span className="hidden font-normal text-sm sm:inline">New chat</span>\n </Button>\n ) : null}\n </div>\n </header>\n );\n}\n\nfunction PendingThinking() {\n return (\n <Message aria-live="polite" from="assistant">\n <MessageContent>\n <div className="mb-4 flex w-full items-center gap-2 text-muted-foreground text-sm">\n <BrainIcon className="size-4" />\n <Shimmer duration={1}>Thinking</Shimmer>\n </div>\n </MessageContent>\n </Message>\n );\n}\n\nfunction toErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : "Unable to cancel the response.";\n}\n\nfunction getLatestTurnFailure(\n events: ReturnType<typeof useEveAgent>["events"],\n): string | undefined {\n for (let index = events.length - 1; index >= 0; index -= 1) {\n const event = events[index];\n\n if (event.type === "turn.failed") {\n return event.data.code === "MODEL_CALL_FAILED"\n ? "The model is temporarily unavailable. Please try again."\n : event.data.message;\n }\n\n if (event.type === "turn.completed" || event.type === "turn.cancelled") {\n return undefined;\n }\n\n if (event.type === "message.received") {\n return undefined;\n }\n }\n\n return undefined;\n}\n',+ '"use client";\n\nimport type { UserContent } from "ai";\nimport { useEveAgent } from "eve/react";\nimport { AlertCircleIcon, BrainIcon, PlusIcon, SquareIcon } from "lucide-react";\nimport { useState } from "react";\nimport {\n Conversation,\n ConversationContent,\n ConversationScrollButton,\n ConversationTopFade,\n} from "@/components/ai-elements/conversation";\nimport { Message, MessageContent } from "@/components/ai-elements/message";\nimport {\n PromptInput,\n PromptInputButton,\n type PromptInputMessage,\n PromptInputSubmit,\n PromptInputTextarea,\n usePromptInputAttachments,\n} from "@/components/ai-elements/prompt-input";\nimport { Shimmer } from "@/components/ai-elements/shimmer";\nimport { Button } from "@/components/ui/button";\nimport { cn } from "@/lib/utils";\nimport { AgentMessage } from "./agent-message";\nimport { WEB_CHAT_AGENT } from "@/app/eve-agent";\n\nconst DEFAULT_AGENT_NAME = "__EVE_INIT_APP_NAME__";\nconst AGENT_NAME = WEB_CHAT_AGENT ?? DEFAULT_AGENT_NAME;\n\nexport function AgentChat({\n sessionId,\n sessionless = false,\n}: {\n readonly sessionId?: string;\n readonly sessionless?: boolean;\n}) {\n const [cancellationError, setCancellationError] = useState<string>();\n const [hasInputText, setHasInputText] = useState(false);\n const agent = useEveAgent({\n agent: WEB_CHAT_AGENT,\n initialSession:\n sessionId === undefined\n ? undefined\n : {\n sessionId,\n streamIndex: 0,\n },\n resume: sessionId !== undefined,\n onSessionChange(session) {\n if (sessionId === undefined && session !== undefined) {\n // Next patches window.history to navigate, which would detach the active stream.\n History.prototype.replaceState.call(\n window.history,\n window.history.state,\n "",\n `/s/${encodeURIComponent(session.sessionId)}`,\n );\n }\n },\n });\n\n const isBusy = agent.status === "submitted" || agent.status === "streaming";\n const isResuming = agent.status === "resuming";\n const isEmpty = agent.data.messages.length === 0;\n const lastMessage = agent.data.messages.at(-1);\n const isPendingAssistantShell =\n lastMessage?.role === "assistant" &&\n lastMessage.parts.every((part) => part.type === "step-start");\n const showPendingThinking =\n isBusy &&\n (agent.status === "submitted" || lastMessage?.role !== "assistant" || isPendingAssistantShell);\n const turnFailure = isBusy || isResuming ? undefined : getLatestTurnFailure(agent.events);\n const errorMessage = cancellationError ?? agent.error?.message ?? turnFailure;\n const hasConversationContent = sessionless || !isEmpty || errorMessage !== undefined;\n const showConversationLayout = isResuming || hasConversationContent;\n const activeSessionId = sessionId ?? agent.session?.sessionId;\n // Answers are accepted while work runs; the server\'s settlement closes each request.\n const canRespond = (requestId: string) =>\n !isResuming && agent.data.inputs[requestId]?.status === "open";\n\n const requestCancellation = () => {\n setCancellationError(undefined);\n void agent.cancel().catch((error: unknown) => {\n setCancellationError(toErrorMessage(error));\n });\n };\n\n const handleSubmit = async (message: PromptInputMessage) => {\n const text = message.text.trim();\n if ((text.length === 0 && message.files.length === 0) || isResuming) return;\n\n setHasInputText(false);\n setCancellationError(undefined);\n const options = isBusy ? { turnPolicy: "steer" as const } : undefined;\n\n if (message.files.length === 0) {\n await agent.send(text, options);\n return;\n }\n\n const parts: UserContent = [];\n if (text.length > 0) {\n parts.push({ text, type: "text" });\n }\n for (const file of message.files) {\n parts.push({\n data: file.url,\n filename: file.filename,\n mediaType: file.mediaType,\n type: "file",\n });\n }\n\n await agent.send(parts, options);\n };\n\n const composer = (\n <PromptInput onSubmit={handleSubmit}>\n <PromptInputTextarea\n disabled={isResuming}\n onChange={(event) => setHasInputText(event.currentTarget.value.trim().length > 0)}\n placeholder="Send a message…"\n />\n <ComposerAction\n hasInputText={hasInputText}\n isBusy={isBusy}\n isResuming={isResuming}\n onCancel={requestCancellation}\n />\n </PromptInput>\n );\n\n return (\n <main className="flex h-dvh flex-col overflow-hidden bg-background text-foreground">\n {showConversationLayout ? (\n <ChatHeader canStartNewChat={activeSessionId !== undefined} />\n ) : null}\n\n {showConversationLayout ? (\n <Conversation\n className="min-h-0 flex-1"\n initial={sessionId === undefined ? undefined : false}\n resize={activeSessionId === undefined ? "smooth" : "instant"}\n scrollRestorationKey={\n isEmpty || activeSessionId === undefined\n ? undefined\n : `eve:web-chat-scroll:${activeSessionId}`\n }\n >\n <ConversationTopFade className="top-14" />\n <ConversationContent className="mx-auto w-full max-w-3xl gap-6 px-4 pt-20 pb-36 sm:px-6">\n {agent.data.messages.map((message, index) =>\n showPendingThinking &&\n isPendingAssistantShell &&\n message.id === lastMessage.id ? null : (\n <AgentMessage\n canRespond={canRespond}\n isStreaming={\n agent.status === "streaming" && index === agent.data.messages.length - 1\n }\n key={message.id}\n message={message}\n onInputResponses={(inputResponses) => {\n setCancellationError(undefined);\n return agent.respond(inputResponses);\n }}\n />\n ),\n )}\n {showPendingThinking ? <PendingThinking /> : null}\n {errorMessage ? <ErrorMessage message={errorMessage} /> : null}\n </ConversationContent>\n <ConversationScrollButton />\n </Conversation>\n ) : null}\n\n <div\n className={cn(\n "mx-auto w-full px-4 sm:px-6",\n showConversationLayout\n ? "fixed bottom-0 left-1/2 z-20 max-w-3xl -translate-x-1/2 bg-gradient-to-t from-background via-background to-transparent pt-4 pb-6"\n : "flex max-w-xl flex-1 flex-col items-center justify-center gap-8 pb-[10vh]",\n )}\n >\n {showConversationLayout ? null : (\n <div className="flex flex-col items-center gap-3 text-center">\n <h1 className="font-medium text-5xl tracking-tighter">{AGENT_NAME}</h1>\n </div>\n )}\n <div className="w-full">{composer}</div>\n </div>\n </main>\n );\n}\n\nfunction ComposerAction({\n hasInputText,\n isBusy,\n isResuming,\n onCancel,\n}: {\n readonly hasInputText: boolean;\n readonly isBusy: boolean;\n readonly isResuming: boolean;\n readonly onCancel: () => void;\n}) {\n const attachments = usePromptInputAttachments();\n const canSubmit = hasInputText || attachments.files.length > 0;\n\n if (!isBusy || canSubmit) {\n return <PromptInputSubmit disabled={isResuming} />;\n }\n\n return (\n <PromptInputButton\n aria-label="Stop"\n className="absolute right-2.5 bottom-2.5"\n onClick={onCancel}\n variant="outline"\n >\n <SquareIcon className="size-3 fill-current" />\n </PromptInputButton>\n );\n}\n\nfunction ErrorMessage({ message }: { readonly message: string }) {\n return (\n <Message className="max-w-full" from="assistant">\n <MessageContent>\n <div\n className="flex w-full items-start gap-3 rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2.5 text-sm"\n role="alert"\n >\n <AlertCircleIcon className="mt-0.5 size-4 shrink-0 text-destructive" />\n <div>\n <p className="font-medium">Request failed</p>\n <p className="mt-0.5 text-muted-foreground">{message}</p>\n </div>\n </div>\n </MessageContent>\n </Message>\n );\n}\n\nfunction ChatHeader({ canStartNewChat }: { readonly canStartNewChat: boolean }) {\n return (\n <header className="pointer-events-none fixed top-0 right-0 left-0 z-20 h-14">\n <div className="relative mx-auto flex h-full w-full max-w-3xl items-center justify-center bg-background px-24">\n <span className="truncate text-muted-foreground text-sm">{AGENT_NAME}</span>\n {canStartNewChat ? (\n <Button\n aria-label="Start a new chat"\n className="pointer-events-auto fixed top-3 right-6 pr-4"\n onClick={() => window.location.assign("/s")}\n size="sm"\n type="button"\n variant="ghost"\n >\n <PlusIcon className="size-4" />\n <span className="hidden font-normal text-sm sm:inline">New chat</span>\n </Button>\n ) : null}\n </div>\n </header>\n );\n}\n\nfunction PendingThinking() {\n return (\n <Message aria-live="polite" from="assistant">\n <MessageContent>\n <div className="mb-4 flex w-full items-center gap-2 text-muted-foreground text-sm">\n <BrainIcon className="size-4" />\n <Shimmer duration={1}>Thinking</Shimmer>\n </div>\n </MessageContent>\n </Message>\n );\n}\n\nfunction toErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : "Unable to cancel the response.";\n}\n\nfunction getLatestTurnFailure(\n events: ReturnType<typeof useEveAgent>["events"],\n): string | undefined {\n for (let index = events.length - 1; index >= 0; index -= 1) {\n const event = events[index];\n\n if (event.type === "turn.failed") {\n return event.data.code === "MODEL_CALL_FAILED"\n ? "The model is temporarily unavailable. Please try again."\n : event.data.message;\n }\n\n if (event.type === "turn.completed" || event.type === "turn.cancelled") {\n return undefined;\n }\n\n if (event.type === "message.received") {\n return undefined;\n }\n }\n\n return undefined;\n}\n',"app/_components/agent-message.tsx":- '"use client";\n\nimport type {\n EveAuthorizationPart,\n EveDynamicToolPart,\n EveMessage,\n EveMessageInputRequest,\n EveMessagePart,\n} from "eve/react";\nimport { useState } from "react";\nimport {\n ArrowRightIcon,\n CheckCircleIcon,\n CheckIcon,\n ExternalLinkIcon,\n FileIcon,\n ImageIcon,\n KeyRoundIcon,\n XCircleIcon,\n} from "lucide-react";\nimport { Message, MessageContent, MessageResponse } from "@/components/ai-elements/message";\nimport {\n Question,\n QuestionInput,\n QuestionOption,\n QuestionOptions,\n QuestionPrompt,\n type QuestionResponse,\n QuestionSubmit,\n type QuestionValue,\n} from "@/components/ai-elements/question";\nimport { Reasoning, ReasoningContent, ReasoningTrigger } from "@/components/ai-elements/reasoning";\nimport {\n BashToolContent,\n Tool,\n ToolContent,\n ToolHeader,\n ToolInput,\n ToolOutput,\n} from "@/components/ai-elements/tool";\nimport { Button } from "@/components/ui/button";\nimport { cn } from "@/lib/utils";\n\nexport type AgentInputResponse = {\n readonly optionId?: string;\n readonly requestId: string;\n readonly text?: string;\n};\n\ntype EveFilePart = Extract<EveMessagePart, { type: "file" }>;\n\nexport function AgentMessage({\n canRespond,\n isStreaming,\n message,\n onInputResponses,\n}: {\n readonly canRespond: boolean;\n readonly isStreaming: boolean;\n readonly message: EveMessage;\n readonly onInputResponses: (responses: readonly AgentInputResponse[]) => void | Promise<void>;\n}) {\n const lastTextIndex = message.parts.reduce(\n (last, part, index) => (part.type === "text" ? index : last),\n -1,\n );\n const hasAssistantText =\n message.role === "assistant" &&\n message.parts.some((part) => part.type === "text" && part.text.length > 0);\n\n return (\n <Message\n data-optimistic={message.metadata?.optimistic ? "true" : undefined}\n from={message.role}\n >\n <MessageContent>\n {message.parts.map((part, index) =>\n hasAssistantText && part.type === "reasoning" ? null : (\n <AgentMessagePart\n canRespond={canRespond}\n key={partKey(part, index)}\n onInputResponses={onInputResponses}\n part={part}\n showCaret={isStreaming && message.role === "assistant" && index === lastTextIndex}\n />\n ),\n )}\n </MessageContent>\n </Message>\n );\n}\n\nfunction AgentMessagePart({\n canRespond,\n onInputResponses,\n part,\n showCaret,\n}: {\n readonly canRespond: boolean;\n readonly onInputResponses: (responses: readonly AgentInputResponse[]) => void | Promise<void>;\n readonly part: EveMessagePart;\n readonly showCaret: boolean;\n}) {\n switch (part.type) {\n case "step-start":\n return null;\n case "text":\n return (\n <MessageResponse caret="block" isAnimating={showCaret}>\n {part.text}\n </MessageResponse>\n );\n case "reasoning":\n return (\n <Reasoning defaultOpen isStreaming={part.state === "streaming"}>\n <ReasoningTrigger />\n <ReasoningContent>{part.text}</ReasoningContent>\n </Reasoning>\n );\n case "file":\n return <AttachmentPart part={part} />;\n case "authorization":\n return <AuthorizationPrompt part={part} />;\n case "dynamic-tool": {\n const inputRequest = part.toolMetadata?.eve?.inputRequest;\n if (inputRequest?.kind === "question") {\n return (\n <QuestionRequest\n canRespond={canRespond}\n inputRequest={inputRequest}\n inputResponse={part.toolMetadata?.eve?.inputResponse}\n onInputResponses={onInputResponses}\n />\n );\n }\n\n return (\n <Tool\n defaultOpen={part.state === "approval-requested" || part.state === "approval-responded"}\n >\n <ToolHeader\n state={part.state}\n title={part.toolName}\n toolName={part.toolName}\n type="dynamic-tool"\n />\n <ToolContent>\n {part.toolName === "bash" ? (\n <BashToolContent errorText={part.errorText} input={part.input} output={part.output} />\n ) : (\n <ToolInput input={part.input} />\n )}\n <InputRequestActions\n canRespond={canRespond}\n part={part}\n onInputResponses={onInputResponses}\n />\n {part.toolName === "bash" ? null : (\n <ToolOutput errorText={part.errorText} output={part.output} />\n )}\n </ToolContent>\n </Tool>\n );\n }\n }\n}\n\nfunction QuestionRequest({\n canRespond,\n inputRequest,\n inputResponse,\n onInputResponses,\n}: {\n readonly canRespond: boolean;\n readonly inputRequest: EveMessageInputRequest;\n readonly inputResponse?: AgentInputResponse;\n readonly onInputResponses: (responses: readonly AgentInputResponse[]) => void | Promise<void>;\n}) {\n const hasOptions = (inputRequest.options?.length ?? 0) > 0;\n const acceptsFreeform = inputRequest.allowFreeform === true || !hasOptions;\n const [questionValue, setQuestionValue] = useState<QuestionValue>({\n selectedValues: inputResponse?.optionId ? [inputResponse.optionId] : [],\n text: inputResponse?.text ?? "",\n });\n\n const submitOption = (optionId: string) => {\n setQuestionValue((value) => ({ ...value, selectedValues: [optionId] }));\n return onInputResponses([\n {\n optionId,\n requestId: inputRequest.requestId,\n },\n ]);\n };\n\n const submitResponse = ({ selectedValues, text }: QuestionResponse) =>\n onInputResponses([\n {\n optionId: selectedValues[0],\n requestId: inputRequest.requestId,\n text,\n },\n ]);\n\n return (\n <Question\n disabled={!canRespond || inputResponse !== undefined}\n onSubmit={submitResponse}\n onValueChange={setQuestionValue}\n value={questionValue}\n >\n <QuestionPrompt>{inputRequest.prompt}</QuestionPrompt>\n {hasOptions ? (\n <QuestionOptions className="flex-col items-stretch" aria-label={inputRequest.prompt}>\n {inputRequest.options?.map((option, index) => (\n <QuestionOption\n className="justify-start px-3 py-2 text-left"\n key={option.id}\n onClick={() => void submitOption(option.id)}\n value={option.id}\n >\n <span className="min-w-0 flex-1">\n <span className="block text-foreground text-sm leading-tight">{option.label}</span>\n {option.description ? (\n <span className="block text-sm text-muted-foreground leading-tight">\n {option.description}\n </span>\n ) : null}\n </span>\n {inputResponse === undefined ? (\n <span aria-hidden="true" className="relative size-6 shrink-0">\n <span className="absolute inset-0 flex items-center justify-center rounded-full bg-foreground/8 text-xs text-muted-foreground transition-opacity group-hover/option:opacity-0 group-focus-visible/option:opacity-0">\n {index + 1}\n </span>\n <ArrowRightIcon className="absolute top-1/2 left-1/2 size-4 -translate-x-1/2 -translate-y-1/2 text-muted-foreground opacity-0 transition-[color,opacity] group-hover/option:text-foreground group-hover/option:opacity-100 group-focus-visible/option:opacity-100" />\n </span>\n ) : (\n <CheckIcon className="size-4 shrink-0 opacity-0 transition-opacity group-data-[state=checked]/option:opacity-100" />\n )}\n </QuestionOption>\n ))}\n </QuestionOptions>\n ) : null}\n {acceptsFreeform ? (\n <div className="relative">\n <QuestionInput\n aria-label="Answer"\n className={inputResponse === undefined ? "pr-12 pb-12" : undefined}\n placeholder="Type your answer…"\n />\n {inputResponse === undefined && questionValue.text.trim().length > 0 ? (\n <QuestionSubmit\n aria-label="Answer"\n className="absolute right-2 bottom-2"\n size="icon-sm"\n >\n <ArrowRightIcon />\n </QuestionSubmit>\n ) : null}\n </div>\n ) : null}\n </Question>\n );\n}\n\nfunction AttachmentPart({ part }: { readonly part: EveFilePart }) {\n const label = part.filename ?? "Attachment";\n const detail = [part.mediaType, formatBytes(part.size)].filter(Boolean).join(" - ");\n const isImage = part.mediaType.startsWith("image/") && part.url !== undefined;\n const Icon = isImage ? ImageIcon : FileIcon;\n const body = (\n <span className="flex max-w-sm items-center gap-3 rounded-md border bg-background/60 p-2 text-sm">\n {isImage ? (\n <img alt={label} className="size-12 shrink-0 rounded-sm object-cover" src={part.url} />\n ) : (\n <span className="flex size-10 shrink-0 items-center justify-center rounded-sm bg-muted text-muted-foreground">\n <Icon className="size-4" />\n </span>\n )}\n <span className="min-w-0 flex-1">\n <span className="block truncate font-medium">{label}</span>\n {detail ? <span className="block truncate text-muted-foreground">{detail}</span> : null}\n </span>\n {part.url ? <ExternalLinkIcon className="size-4 shrink-0 text-muted-foreground" /> : null}\n </span>\n );\n\n return part.url ? (\n <a href={part.url} rel="noreferrer" target="_blank">\n {body}\n </a>\n ) : (\n body\n );\n}\n\nfunction AuthorizationPrompt({ part }: { readonly part: EveAuthorizationPart }) {\n const isAuthorized = part.state === "completed" && part.outcome === "authorized";\n const isCompleted = part.state === "completed";\n const Icon = isAuthorized ? CheckCircleIcon : isCompleted ? XCircleIcon : KeyRoundIcon;\n const instructions = part.authorization?.instructions;\n const shouldShowInstructions = instructions !== undefined && instructions !== part.description;\n\n return (\n <div\n className={cn(\n "space-y-3 rounded-md border p-3",\n isAuthorized\n ? "border-emerald-500/30 bg-emerald-500/5"\n : isCompleted\n ? "border-destructive/30 bg-destructive/5"\n : "border-blue-500/30 bg-blue-500/5",\n )}\n >\n <div className="flex items-start gap-3">\n <span\n className={cn(\n "mt-0.5 flex size-8 shrink-0 items-center justify-center rounded-full",\n isAuthorized\n ? "bg-emerald-500/10 text-emerald-700 dark:text-emerald-300"\n : isCompleted\n ? "bg-destructive/10 text-destructive"\n : "bg-blue-500/10 text-blue-700 dark:text-blue-300",\n )}\n >\n <Icon className="size-4" />\n </span>\n <div className="min-w-0 flex-1 space-y-2">\n <p className="font-medium text-sm">{authorizationTitle(part)}</p>\n <p className="text-muted-foreground text-sm">{authorizationDescription(part)}</p>\n {shouldShowInstructions ? (\n <p className="text-muted-foreground text-sm">{instructions}</p>\n ) : null}\n {part.state === "required" && part.authorization?.userCode ? (\n <div className="flex flex-wrap items-center gap-2 text-sm">\n <span className="text-muted-foreground">Code</span>\n <code className="rounded-md bg-background px-2 py-1 font-mono">\n {part.authorization.userCode}\n </code>\n </div>\n ) : null}\n {part.state === "required" && part.authorization?.url ? (\n <Button asChild size="sm">\n <a href={part.authorization.url} rel="noreferrer" target="_blank">\n <ExternalLinkIcon className="size-4" />\n Sign in with {part.displayName}\n </a>\n </Button>\n ) : null}\n </div>\n </div>\n </div>\n );\n}\n\nfunction authorizationTitle(part: EveAuthorizationPart): string {\n if (part.state === "required") {\n return `Connect ${part.displayName}`;\n }\n if (part.outcome === "authorized") {\n return `${part.displayName} connected`;\n }\n return `${part.displayName} authorization ${formatAuthorizationOutcome(part.outcome)}`;\n}\n\nfunction authorizationDescription(part: EveAuthorizationPart): string {\n if (part.state === "required") {\n return part.description;\n }\n if (part.outcome === "authorized") {\n return `${part.displayName} connected.`;\n }\n const tail = part.reason !== undefined ? ` (${part.reason})` : "";\n return `${part.displayName} authorization ${formatAuthorizationOutcome(part.outcome)}${tail}.`;\n}\n\nfunction formatAuthorizationOutcome(outcome: NonNullable<EveAuthorizationPart["outcome"]>): string {\n switch (outcome) {\n case "authorized":\n return "authorized";\n case "declined":\n return "declined";\n case "failed":\n return "failed";\n case "timed-out":\n return "timed out";\n }\n}\n\nfunction formatBytes(size: number | undefined): string | undefined {\n if (size === undefined) {\n return undefined;\n }\n if (size < 1024) {\n return `${size} B`;\n }\n if (size < 1024 * 1024) {\n return `${(size / 1024).toFixed(1)} KB`;\n }\n return `${(size / (1024 * 1024)).toFixed(1)} MB`;\n}\n\nfunction InputRequestActions({\n canRespond,\n onInputResponses,\n part,\n}: {\n readonly canRespond: boolean;\n readonly onInputResponses: (responses: readonly AgentInputResponse[]) => void | Promise<void>;\n readonly part: EveDynamicToolPart;\n}) {\n const inputRequest = part.toolMetadata?.eve?.inputRequest;\n if (!inputRequest) {\n return null;\n }\n\n const inputResponse = part.toolMetadata?.eve?.inputResponse;\n const selectedOption = inputRequest.options?.find(\n (option) => option.id === inputResponse?.optionId,\n );\n\n return (\n <div className="space-y-3 rounded-md border border-yellow-500/30 bg-yellow-500/5 p-3">\n <p className="text-muted-foreground text-sm">{inputRequest.prompt}</p>\n {inputResponse ? (\n <p className="font-medium text-sm">\n Responded: {selectedOption?.label ?? inputResponse.text ?? inputResponse.optionId}\n </p>\n ) : (\n <div className="flex flex-wrap gap-2">\n {inputRequest.options?.map((option) => (\n <Button\n disabled={!canRespond}\n key={option.id}\n onClick={() => {\n void onInputResponses([\n {\n optionId: option.id,\n requestId: inputRequest.requestId,\n },\n ]);\n }}\n size="sm"\n type="button"\n variant={option.style === "danger" ? "destructive" : "default"}\n >\n {option.label}\n </Button>\n ))}\n </div>\n )}\n </div>\n );\n}\n\nfunction partKey(part: EveMessagePart, index: number): string {\n switch (part.type) {\n case "authorization":\n return `authorization:${part.turnId}:${part.stepIndex}:${part.name}`;\n case "dynamic-tool":\n return part.toolCallId;\n default:\n return `${part.type}:${index}`;\n }\n}\n',+ '"use client";\n\nimport type {\n EveAuthorizationPart,\n EveDynamicToolPart,\n EveMessage,\n EveMessageInputRequest,\n EveMessagePart,\n} from "eve/react";\nimport { useState } from "react";\nimport {\n ArrowRightIcon,\n CheckCircleIcon,\n CheckIcon,\n ExternalLinkIcon,\n FileIcon,\n ImageIcon,\n KeyRoundIcon,\n XCircleIcon,\n} from "lucide-react";\nimport { Message, MessageContent, MessageResponse } from "@/components/ai-elements/message";\nimport {\n Question,\n QuestionInput,\n QuestionOption,\n QuestionOptions,\n QuestionPrompt,\n type QuestionResponse,\n QuestionSubmit,\n type QuestionValue,\n} from "@/components/ai-elements/question";\nimport { Reasoning, ReasoningContent, ReasoningTrigger } from "@/components/ai-elements/reasoning";\nimport {\n BashToolContent,\n Tool,\n ToolContent,\n ToolHeader,\n ToolInput,\n ToolOutput,\n} from "@/components/ai-elements/tool";\nimport { Button } from "@/components/ui/button";\nimport { cn } from "@/lib/utils";\n\nexport type AgentInputResponse = {\n readonly optionId?: string;\n readonly requestId: string;\n readonly text?: string;\n};\n\ntype EveFilePart = Extract<EveMessagePart, { type: "file" }>;\n\nexport function AgentMessage({\n canRespond,\n isStreaming,\n message,\n onInputResponses,\n}: {\n readonly canRespond: (requestId: string) => boolean;\n readonly isStreaming: boolean;\n readonly message: EveMessage;\n readonly onInputResponses: (responses: readonly AgentInputResponse[]) => void | Promise<void>;\n}) {\n const lastTextIndex = message.parts.reduce(\n (last, part, index) => (part.type === "text" ? index : last),\n -1,\n );\n const hasAssistantText =\n message.role === "assistant" &&\n message.parts.some((part) => part.type === "text" && part.text.length > 0);\n\n return (\n <Message\n data-optimistic={message.metadata?.optimistic ? "true" : undefined}\n from={message.role}\n >\n <MessageContent>\n {message.parts.map((part, index) =>\n hasAssistantText && part.type === "reasoning" ? null : (\n <AgentMessagePart\n canRespond={canRespond}\n key={partKey(part, index)}\n onInputResponses={onInputResponses}\n part={part}\n showCaret={isStreaming && message.role === "assistant" && index === lastTextIndex}\n />\n ),\n )}\n </MessageContent>\n </Message>\n );\n}\n\nfunction AgentMessagePart({\n canRespond,\n onInputResponses,\n part,\n showCaret,\n}: {\n readonly canRespond: (requestId: string) => boolean;\n readonly onInputResponses: (responses: readonly AgentInputResponse[]) => void | Promise<void>;\n readonly part: EveMessagePart;\n readonly showCaret: boolean;\n}) {\n switch (part.type) {\n case "step-start":\n return null;\n case "text":\n return (\n <MessageResponse caret="block" isAnimating={showCaret}>\n {part.text}\n </MessageResponse>\n );\n case "reasoning":\n return (\n <Reasoning defaultOpen isStreaming={part.state === "streaming"}>\n <ReasoningTrigger />\n <ReasoningContent>{part.text}</ReasoningContent>\n </Reasoning>\n );\n case "file":\n return <AttachmentPart part={part} />;\n case "authorization":\n return <AuthorizationPrompt part={part} />;\n case "dynamic-tool": {\n const inputRequest = part.toolMetadata?.eve?.inputRequest;\n if (inputRequest?.kind === "question") {\n return (\n <QuestionRequest\n canRespond={canRespond(inputRequest.requestId)}\n inputRequest={inputRequest}\n inputResponse={part.toolMetadata?.eve?.inputResponse}\n onInputResponses={onInputResponses}\n />\n );\n }\n\n return (\n <Tool\n defaultOpen={part.state === "approval-requested" || part.state === "approval-responded"}\n >\n <ToolHeader\n state={part.state}\n title={part.toolName}\n toolName={part.toolName}\n type="dynamic-tool"\n />\n <ToolContent>\n {part.toolName === "bash" ? (\n <BashToolContent errorText={part.errorText} input={part.input} output={part.output} />\n ) : (\n <ToolInput input={part.input} />\n )}\n <InputRequestActions\n canRespond={canRespond}\n part={part}\n onInputResponses={onInputResponses}\n />\n {part.toolName === "bash" ? null : (\n <ToolOutput errorText={part.errorText} output={part.output} />\n )}\n </ToolContent>\n </Tool>\n );\n }\n }\n}\n\nfunction QuestionRequest({\n canRespond,\n inputRequest,\n inputResponse,\n onInputResponses,\n}: {\n readonly canRespond: boolean;\n readonly inputRequest: EveMessageInputRequest;\n readonly inputResponse?: AgentInputResponse;\n readonly onInputResponses: (responses: readonly AgentInputResponse[]) => void | Promise<void>;\n}) {\n const hasOptions = (inputRequest.options?.length ?? 0) > 0;\n const acceptsFreeform = inputRequest.allowFreeform === true || !hasOptions;\n const [questionValue, setQuestionValue] = useState<QuestionValue>({\n selectedValues: inputResponse?.optionId ? [inputResponse.optionId] : [],\n text: inputResponse?.text ?? "",\n });\n\n const submitOption = (optionId: string) => {\n setQuestionValue((value) => ({ ...value, selectedValues: [optionId] }));\n return onInputResponses([\n {\n optionId,\n requestId: inputRequest.requestId,\n },\n ]);\n };\n\n const submitResponse = ({ selectedValues, text }: QuestionResponse) =>\n onInputResponses([\n {\n optionId: selectedValues[0],\n requestId: inputRequest.requestId,\n text,\n },\n ]);\n\n return (\n <Question\n disabled={!canRespond || inputResponse !== undefined}\n onSubmit={submitResponse}\n onValueChange={setQuestionValue}\n value={questionValue}\n >\n <QuestionPrompt>{inputRequest.prompt}</QuestionPrompt>\n {hasOptions ? (\n <QuestionOptions className="flex-col items-stretch" aria-label={inputRequest.prompt}>\n {inputRequest.options?.map((option, index) => (\n <QuestionOption\n className="justify-start px-3 py-2 text-left"\n key={option.id}\n onClick={() => void submitOption(option.id)}\n value={option.id}\n >\n <span className="min-w-0 flex-1">\n <span className="block text-foreground text-sm leading-tight">{option.label}</span>\n {option.description ? (\n <span className="block text-sm text-muted-foreground leading-tight">\n {option.description}\n </span>\n ) : null}\n </span>\n {inputResponse === undefined ? (\n <span aria-hidden="true" className="relative size-6 shrink-0">\n <span className="absolute inset-0 flex items-center justify-center rounded-full bg-foreground/8 text-xs text-muted-foreground transition-opacity group-hover/option:opacity-0 group-focus-visible/option:opacity-0">\n {index + 1}\n </span>\n <ArrowRightIcon className="absolute top-1/2 left-1/2 size-4 -translate-x-1/2 -translate-y-1/2 text-muted-foreground opacity-0 transition-[color,opacity] group-hover/option:text-foreground group-hover/option:opacity-100 group-focus-visible/option:opacity-100" />\n </span>\n ) : (\n <CheckIcon className="size-4 shrink-0 opacity-0 transition-opacity group-data-[state=checked]/option:opacity-100" />\n )}\n </QuestionOption>\n ))}\n </QuestionOptions>\n ) : null}\n {acceptsFreeform ? (\n <div className="relative">\n <QuestionInput\n aria-label="Answer"\n className={inputResponse === undefined ? "pr-12 pb-12" : undefined}\n placeholder="Type your answer…"\n />\n {inputResponse === undefined && questionValue.text.trim().length > 0 ? (\n <QuestionSubmit\n aria-label="Answer"\n className="absolute right-2 bottom-2"\n size="icon-sm"\n >\n <ArrowRightIcon />\n </QuestionSubmit>\n ) : null}\n </div>\n ) : null}\n </Question>\n );\n}\n\nfunction AttachmentPart({ part }: { readonly part: EveFilePart }) {\n const label = part.filename ?? "Attachment";\n const detail = [part.mediaType, formatBytes(part.size)].filter(Boolean).join(" - ");\n const isImage = part.mediaType.startsWith("image/") && part.url !== undefined;\n const Icon = isImage ? ImageIcon : FileIcon;\n const body = (\n <span className="flex max-w-sm items-center gap-3 rounded-md border bg-background/60 p-2 text-sm">\n {isImage ? (\n <img alt={label} className="size-12 shrink-0 rounded-sm object-cover" src={part.url} />\n ) : (\n <span className="flex size-10 shrink-0 items-center justify-center rounded-sm bg-muted text-muted-foreground">\n <Icon className="size-4" />\n </span>\n )}\n <span className="min-w-0 flex-1">\n <span className="block truncate font-medium">{label}</span>\n {detail ? <span className="block truncate text-muted-foreground">{detail}</span> : null}\n </span>\n {part.url ? <ExternalLinkIcon className="size-4 shrink-0 text-muted-foreground" /> : null}\n </span>\n );\n\n return part.url ? (\n <a href={part.url} rel="noreferrer" target="_blank">\n {body}\n </a>\n ) : (\n body\n );\n}\n\nfunction AuthorizationPrompt({ part }: { readonly part: EveAuthorizationPart }) {\n const isAuthorized = part.state === "completed" && part.outcome === "authorized";\n const isCompleted = part.state === "completed";\n const Icon = isAuthorized ? CheckCircleIcon : isCompleted ? XCircleIcon : KeyRoundIcon;\n const instructions = part.authorization?.instructions;\n const shouldShowInstructions = instructions !== undefined && instructions !== part.description;\n\n return (\n <div\n className={cn(\n "space-y-3 rounded-md border p-3",\n isAuthorized\n ? "border-emerald-500/30 bg-emerald-500/5"\n : isCompleted\n ? "border-destructive/30 bg-destructive/5"\n : "border-blue-500/30 bg-blue-500/5",\n )}\n >\n <div className="flex items-start gap-3">\n <span\n className={cn(\n "mt-0.5 flex size-8 shrink-0 items-center justify-center rounded-full",\n isAuthorized\n ? "bg-emerald-500/10 text-emerald-700 dark:text-emerald-300"\n : isCompleted\n ? "bg-destructive/10 text-destructive"\n : "bg-blue-500/10 text-blue-700 dark:text-blue-300",\n )}\n >\n <Icon className="size-4" />\n </span>\n <div className="min-w-0 flex-1 space-y-2">\n <p className="font-medium text-sm">{authorizationTitle(part)}</p>\n <p className="text-muted-foreground text-sm">{authorizationDescription(part)}</p>\n {shouldShowInstructions ? (\n <p className="text-muted-foreground text-sm">{instructions}</p>\n ) : null}\n {part.state === "required" && part.authorization?.userCode ? (\n <div className="flex flex-wrap items-center gap-2 text-sm">\n <span className="text-muted-foreground">Code</span>\n <code className="rounded-md bg-background px-2 py-1 font-mono">\n {part.authorization.userCode}\n </code>\n </div>\n ) : null}\n {part.state === "required" && part.authorization?.url ? (\n <Button asChild size="sm">\n <a href={part.authorization.url} rel="noreferrer" target="_blank">\n <ExternalLinkIcon className="size-4" />\n Sign in with {part.displayName}\n </a>\n </Button>\n ) : null}\n </div>\n </div>\n </div>\n );\n}\n\nfunction authorizationTitle(part: EveAuthorizationPart): string {\n if (part.state === "required") {\n return `Connect ${part.displayName}`;\n }\n if (part.outcome === "authorized") {\n return `${part.displayName} connected`;\n }\n return `${part.displayName} authorization ${formatAuthorizationOutcome(part.outcome)}`;\n}\n\nfunction authorizationDescription(part: EveAuthorizationPart): string {\n if (part.state === "required") {\n return part.description;\n }\n if (part.outcome === "authorized") {\n return `${part.displayName} connected.`;\n }\n const tail = part.reason !== undefined ? ` (${part.reason})` : "";\n return `${part.displayName} authorization ${formatAuthorizationOutcome(part.outcome)}${tail}.`;\n}\n\nfunction formatAuthorizationOutcome(outcome: NonNullable<EveAuthorizationPart["outcome"]>): string {\n switch (outcome) {\n case "authorized":\n return "authorized";\n case "declined":\n return "declined";\n case "failed":\n return "failed";\n case "timed-out":\n return "timed out";\n }\n}\n\nfunction formatBytes(size: number | undefined): string | undefined {\n if (size === undefined) {\n return undefined;\n }\n if (size < 1024) {\n return `${size} B`;\n }\n if (size < 1024 * 1024) {\n return `${(size / 1024).toFixed(1)} KB`;\n }\n return `${(size / (1024 * 1024)).toFixed(1)} MB`;\n}\n\nfunction InputRequestActions({\n canRespond,\n onInputResponses,\n part,\n}: {\n readonly canRespond: (requestId: string) => boolean;\n readonly onInputResponses: (responses: readonly AgentInputResponse[]) => void | Promise<void>;\n readonly part: EveDynamicToolPart;\n}) {\n const inputRequest = part.toolMetadata?.eve?.inputRequest;\n if (!inputRequest) {\n return null;\n }\n\n const inputResponse = part.toolMetadata?.eve?.inputResponse;\n const selectedOption = inputRequest.options?.find(\n (option) => option.id === inputResponse?.optionId,\n );\n // An approval can settle before its batch resolves, without an input response.\n const settledApproval =\n part.approval?.approved === undefined\n ? undefined\n : part.approval.approved\n ? "Approved"\n : "Denied";\n\n return (\n <div className="space-y-3 rounded-md border border-yellow-500/30 bg-yellow-500/5 p-3">\n <p className="text-muted-foreground text-sm">{inputRequest.prompt}</p>\n {inputResponse || settledApproval ? (\n <p className="font-medium text-sm">\n Responded:{" "}\n {selectedOption?.label ??\n inputResponse?.text ??\n inputResponse?.optionId ??\n settledApproval}\n </p>\n ) : (\n <div className="flex flex-wrap gap-2">\n {inputRequest.options?.map((option) => (\n <Button\n disabled={!canRespond(inputRequest.requestId)}\n key={option.id}\n onClick={() => {\n void onInputResponses([\n {\n optionId: option.id,\n requestId: inputRequest.requestId,\n },\n ]);\n }}\n size="sm"\n type="button"\n variant={option.style === "danger" ? "destructive" : "default"}\n >\n {option.label}\n </Button>\n ))}\n </div>\n )}\n </div>\n );\n}\n\nfunction partKey(part: EveMessagePart, index: number): string {\n switch (part.type) {\n case "authorization":\n return part.attemptId === undefined\n ? `authorization:${part.turnId}:${part.stepIndex}:${part.name}`\n : `authorization:${part.attemptId}`;\n case "dynamic-tool":\n return part.toolCallId;\n case "reasoning":\n case "text":\n return `${part.type}:${part.id ?? index}`;\n default:\n return `${part.type}:${index}`;\n }\n}\n',"app/apple-icon.tsx":'import { ImageResponse } from "next/og";\n\nexport const size = {\n width: 180,\n height: 180,\n};\n\nexport const contentType = "image/png";\n\nexport default function AppleIcon() {\n return new ImageResponse(\n <svg fill="none" viewBox="0 0 102 102" xmlns="http://www.w3.org/2000/svg">\n <path d="M0 0h102v102H0z" fill="#000" />\n <path\n d="M49.28 66.94 75.03 34.96h-6.89L47.91 60.11l-5.49 6.83h6.86ZM0 34.96h42.4v5.11H0zm0 13.32h27.66v5.11H0zm0 13.54h27.66v5.11H0zm69.63-26.86H102v5.11H69.63zm4.71 13.32H102v5.11H74.34zm0 13.54H102v5.11H74.34z"\n fill="#fff"\n />\n </svg>,\n size,\n );\n}\n',"app/eve-agent.ts":diff --git a/packages/eve/src/setup/scaffold/index.integration.test.ts b/packages/eve/src/setup/scaffold/index.integration.test.tsindex 0c3952fd3..dd021143e 100644--- a/packages/eve/src/setup/scaffold/index.integration.test.ts+++ b/packages/eve/src/setup/scaffold/index.integration.test.ts@@ -272,7 +272,9 @@ describe("ensureChannel", () => {expect(agentChatSource).toMatch(/<PromptInputTextarea\s+disabled=\{isResuming\}/);expect(agentChatSource).toContain('turnPolicy: "steer"');expect(agentChatSource).toContain('const isResuming = agent.status === "resuming"');- expect(agentChatSource).toContain("canRespond={!isBusy && !isResuming}");+ expect(agentChatSource).toContain(+ '!isResuming && agent.data.inputs[requestId]?.status === "open"',+ );expect(agentChatSource).toContain("{showPendingThinking ? <PendingThinking /> : null}");expect(agentChatSource).not.toContain("StatusDot");await expect(readFile(join(projectRoot, "app/icon.svg"), "utf8")).resolves.toContain(diff --git a/packages/eve/src/svelte/index.ts b/packages/eve/src/svelte/index.tsindex 433749389..3f3ba35a7 100644--- a/packages/eve/src/svelte/index.ts+++ b/packages/eve/src/svelte/index.ts@@ -14,6 +14,17 @@ export {type ClientMessageFailedEvent,type ClientMessageSubmittedEvent,} from "#client/reducer.js";+export { conversationReducer } from "#client/conversation-reducer.js";+export { openConversationInputs } from "#client/conversation-state.js";+export type {+ AgentObservation,+ ConversationAgentSession,+ ConversationInput,+ ConversationState,+ ConversationTask,+ ConversationTaskCall,+ ConversationTurn,+} from "#client/conversation-state.js";export {defaultMessageReducer,type EveAuthorizationChallenge,diff --git a/packages/eve/src/svelte/use-eve-agent.ts b/packages/eve/src/svelte/use-eve-agent.tsindex b179d0b2e..afdcec020 100644--- a/packages/eve/src/svelte/use-eve-agent.ts+++ b/packages/eve/src/svelte/use-eve-agent.ts@@ -12,7 +12,8 @@ import {type PrepareSend,} from "#client/eve-agent-store.js";import { resolveEveAgentHost } from "#client/agent-host.js";-import { defaultMessageReducer, type EveMessageData } from "#client/message-reducer.js";+import { conversationReducer } from "#client/conversation-reducer.js";+import type { ConversationState } from "#client/conversation-state.js";import type { EveAgentReducer } from "#client/reducer.js";import type { ClientSession } from "#client/session.js";import type {@@ -53,6 +54,8 @@ export interface UseEveAgentReturn<TData> {readonly cancel: () => Promise<CancelSessionResult>;/** Projected state built by reducing every stream event through the reducer. */readonly data: TData;+ /** Canonical session state, regardless of the chosen data reducer. */+ readonly conversation: ConversationState;/** Last transport-level error, or `undefined` when healthy. */readonly error: Error | undefined;/** Raw server events received during this session (authoritative stream). */@@ -130,11 +133,12 @@ export interface UseEveAgentOptions<TData> extends EveAgentStoreCallbacks<TData>* @default true*/readonly optimistic?: boolean;+ /** Follow each subagent call's session into `conversation.agents` while mounted. @default false */+ readonly followSubagents?: boolean;/** Prewarm an owned session on mount and after reset. @default false */readonly prewarm?: boolean;/**- * Projects stream events into `TData`. Defaults to {@link defaultMessageReducer},- * which fixes `TData` to {@link EveMessageData}.+ * Projects stream events into `TData`. Defaults to the conversation reducer.*/readonly reducer?: EveAgentReducer<TData>;/** Replay the attached durable session after mount. Requires `initialSession` or `session`. */@@ -173,6 +177,11 @@ class SvelteEveAgent<TData> implements UseEveAgentReturn<TData> {return this.#snapshot.data;}+ get conversation(): ConversationState {+ this.#subscribe();+ return this.#snapshot.conversation;+ }+get error(): Error | undefined {this.#subscribe();return this.#snapshot.error;@@ -225,8 +234,8 @@ class SvelteEveAgent<TData> implements UseEveAgentReturn<TData> {}export function useEveAgent(- options?: UseEveAgentOptions<EveMessageData>,-): UseEveAgentReturn<EveMessageData>;+ options?: UseEveAgentOptions<ConversationState>,+): UseEveAgentReturn<ConversationState>;export function useEveAgent<TData>(options: UseEveAgentOptions<TData> & { readonly reducer: EveAgentReducer<TData> },@@ -236,8 +245,8 @@ export function useEveAgent<TData>(* Svelte 5 binding that drives an eve session and projects its events into* rune-friendly reactive data.*- * Without a `reducer`, projects to {@link EveMessageData} via- * {@link defaultMessageReducer}; pass a `reducer` for a different `TData`.+ * Without a `reducer`, projects conversation state including message parts;+ * pass a `reducer` for a different `TData`.* Configuration is read once; create a new binding to change host, reducer,* or session.*/@@ -247,7 +256,7 @@ export function useEveAgent<TData>(if (options.resume && options.initialSession === undefined && options.session === undefined) {throw new Error("useEveAgent({ resume: true }) requires initialSession or session.");}- const reducer = options.reducer ?? (defaultMessageReducer() as EveAgentReducer<TData>);+ const reducer = options.reducer ?? (conversationReducer as EveAgentReducer<TData>);const store = new EveAgentStore<TData>({auth: options.auth,headers: options.headers,@@ -255,6 +264,7 @@ export function useEveAgent<TData>(initialEvents: options.initialEvents,initialSession: options.initialSession,optimistic: options.optimistic,+ followSubagents: options.followSubagents,prewarm: options.prewarm,reducer,session: options.session,diff --git a/packages/eve/src/vue/index.ts b/packages/eve/src/vue/index.tsindex 1450e1ad8..db669c69c 100644--- a/packages/eve/src/vue/index.ts+++ b/packages/eve/src/vue/index.ts@@ -14,6 +14,17 @@ export {type ClientMessageFailedEvent,type ClientMessageSubmittedEvent,} from "#client/reducer.js";+export { conversationReducer } from "#client/conversation-reducer.js";+export { openConversationInputs } from "#client/conversation-state.js";+export type {+ AgentObservation,+ ConversationAgentSession,+ ConversationInput,+ ConversationState,+ ConversationTask,+ ConversationTaskCall,+ ConversationTurn,+} from "#client/conversation-state.js";export {defaultMessageReducer,type EveAuthorizationChallenge,diff --git a/packages/eve/src/vue/use-eve-agent.test.ts b/packages/eve/src/vue/use-eve-agent.test.tsindex 11e44e958..070357c52 100644--- a/packages/eve/src/vue/use-eve-agent.test.ts+++ b/packages/eve/src/vue/use-eve-agent.test.ts@@ -1,8 +1,16 @@import { afterEach, describe, expect, it, vi } from "vitest";import { effectScope } from "vue";+import {+ detachEveAgentStore,+ EveAgentStore,+ type EveAgentStoreSnapshot,+} from "#client/eve-agent-store.js";+import { defaultMessageReducer } from "#client/message-reducer.js";+import type { ClientSessionState } from "#client/types.js";import { useEveAgent } from "#vue/use-eve-agent.js";import type { EveMessageData } from "#client/message-reducer.js";+import type { ConversationState } from "#client/conversation-state.js";import {EVE_MESSAGE_STREAM_VERSION,EVE_SESSION_ID_HEADER,@@ -12,6 +20,7 @@ import {createMessageCompletedEvent,createMessageReceivedEvent,createSessionWaitingEvent,+ createSessionFailedEvent,type UnstampedMessageStreamEvent,} from "#protocol/message.js";import { stampTestEvents } from "#internal/testing/events.js";@@ -66,8 +75,12 @@ function completedTurnData(input: {readonly assistantMessage?: string;readonly turnId: string;readonly userMessage: string;-}): EveMessageData {+}): ConversationState {return {+ tasks: {},+ agents: {},+ inputs: {},+ turns: {},messages: [{id: expect.stringMatching(/^evt_.+:user$/),@@ -90,6 +103,7 @@ function completedTurnData(input: {parts: [{ type: "step-start" as const },{+ id: expect.stringMatching(/^evt_/),state: "done" as const,stepIndex: 0,text: input.assistantMessage,@@ -103,11 +117,251 @@ function completedTurnData(input: {};}+const cleanupStores: Array<() => void> = [];+function createStore<TData>(+ init: ConstructorParameters<typeof EveAgentStore<TData>>[0],+): EveAgentStore<TData> {+ const store = new EveAgentStore<TData>(init);+ cleanupStores.push(() => detachEveAgentStore(store));+ return store;+}+afterEach(() => {+ for (const cleanup of cleanupStores.splice(0)) cleanup();vi.restoreAllMocks();vi.unstubAllGlobals();});+describe("EveAgentStore (Vue composable backing store)", () => {+ it("starts in ready status with empty data", () => {+ const store = createStore({+ reducer: defaultMessageReducer(),+ });++ expect(store.snapshot.status).toBe("ready");+ expect(store.snapshot.data.messages).toEqual([]);+ expect(store.snapshot.error).toBeUndefined();+ expect(store.snapshot.events).toEqual([]);+ });++ it("notifies subscribers on state changes", async () => {+ const store = createStore({+ reducer: defaultMessageReducer(),+ });++ const snapshots: EveAgentStoreSnapshot<EveMessageData>[] = [];+ store.subscribe(() => {+ snapshots.push(store.snapshot);+ });++ vi.spyOn(globalThis, "fetch").mockRejectedValueOnce(new Error("Network failed"));++ await store.send({ message: "Hello" });++ expect(snapshots.length).toBeGreaterThan(0);+ expect(snapshots.at(-1)?.status).toBe("error");+ });++ it("sends a message and projects streamed events", async () => {+ const events = [+ createMessageReceivedEvent({+ message: "Hello",+ sequence: 0,+ turnId: "turn_1",+ }),+ createMessageCompletedEvent({+ message: "Hi there.",+ sequence: 1,+ stepIndex: 0,+ turnId: "turn_1",+ }),+ createSessionWaitingEvent(),+ ];++ const startResponse = createDeferred<Response>();+ vi.spyOn(globalThis, "fetch")+ .mockReturnValueOnce(startResponse.promise)+ .mockResolvedValueOnce(createEagerStreamResponse(events));++ const store = createStore({+ reducer: defaultMessageReducer(),+ });++ const seenEvents: UnstampedMessageStreamEvent[] = [];+ const seenSessions: Array<ClientSessionState | undefined> = [];+ store.setCallbacks({+ onEvent(event) {+ seenEvents.push(event);+ },+ onSessionChange(session) {+ seenSessions.push(session);+ },+ });++ const sendPromise = store.send({ message: "Hello" });+ await Promise.resolve();++ expect(store.snapshot.status).toBe("submitted");+ expect(store.snapshot.data).toEqual({+ messages: [+ {+ id: expect.stringMatching(/^optimistic:/),+ metadata: { optimistic: true, status: "submitted" },+ parts: [{ text: "Hello", type: "text" }],+ role: "user",+ },+ ],+ });++ startResponse.resolve(createStartedMessageResponse("session_1", "http:session_1"));+ await sendPromise;++ expect(seenEvents).toEqual(stampTestEvents(events));+ expect(store.snapshot.status).toBe("ready");+ expect(store.snapshot.data).toEqual({+ messages: completedTurnData({+ assistantMessage: "Hi there.",+ turnId: "turn_1",+ userMessage: "Hello",+ }).messages,+ });+ expect(seenSessions.map((session) => session?.streamIndex)).toEqual([0, 1, 2, 3, 3]);+ });++ it("surfaces transport errors", async () => {+ vi.spyOn(globalThis, "fetch").mockRejectedValueOnce(new Error("Network failed"));++ const store = createStore({+ reducer: defaultMessageReducer(),+ });++ const seenErrors: Error[] = [];+ store.setCallbacks({+ onError(error) {+ seenErrors.push(error);+ },+ });++ await store.send({ message: "Hello" });++ expect(seenErrors.map((e) => e.message)).toEqual(["Network failed"]);+ expect(store.snapshot.status).toBe("error");+ expect(store.snapshot.error?.message).toBe("Network failed");+ });++ it("surfaces terminal stream failures as store errors", async () => {+ const events = [+ createMessageReceivedEvent({+ message: "Hello",+ sequence: 0,+ turnId: "turn_1",+ }),+ createSessionFailedEvent({+ code: "MODEL_CALL_FAILED",+ message: "Bad Request",+ sessionId: "session_1",+ }),+ ];++ const startResponse = createDeferred<Response>();+ vi.spyOn(globalThis, "fetch")+ .mockReturnValueOnce(startResponse.promise)+ .mockResolvedValueOnce(createEagerStreamResponse(events));++ const store = createStore({+ reducer: defaultMessageReducer(),+ });++ const seenErrors: Error[] = [];+ store.setCallbacks({+ onError(error) {+ seenErrors.push(error);+ },+ });++ const sendPromise = store.send({ message: "Hello" });+ startResponse.resolve(createStartedMessageResponse("session_1", "http:session_1"));+ await sendPromise;++ expect(seenErrors.map((e) => e.message)).toEqual(["Bad Request"]);+ expect(store.snapshot.status).toBe("error");+ expect(store.snapshot.error?.message).toBe("Bad Request");+ });++ it("resets state and creates a new session", async () => {+ vi.spyOn(globalThis, "fetch").mockRejectedValueOnce(new Error("fail"));++ const store = createStore({+ reducer: defaultMessageReducer(),+ });++ await store.send({ message: "Hello" });+ expect(store.snapshot.status).toBe("error");++ store.reset();+ expect(store.snapshot.status).toBe("ready");+ expect(store.snapshot.data.messages).toEqual([]);+ expect(store.snapshot.error).toBeUndefined();+ expect(store.snapshot.events).toEqual([]);+ });++ it("unsubscribe removes the listener", () => {+ const store = createStore({+ reducer: defaultMessageReducer(),+ });++ let callCount = 0;+ const unsub = store.subscribe(() => {+ callCount += 1;+ });++ store.reset();+ expect(callCount).toBe(1);++ unsub();+ store.reset();+ expect(callCount).toBe(1);+ });++ it("projects input responses before the resumed stream returns", async () => {+ const startResponse = createDeferred<Response>();+ vi.spyOn(globalThis, "fetch").mockImplementation(async (_request, init) =>+ init?.method === "POST"+ ? await startResponse.promise+ : createEagerStreamResponse([createSessionWaitingEvent()]),+ );++ const store = createStore<readonly string[]>({+ initialSession: {+ sessionId: "session_1",+ streamIndex: 0,+ },+ reducer: {+ initial() {+ return [];+ },+ reduce(data, event) {+ return [...data, event.type];+ },+ },+ });++ const sendPromise = store.send({+ inputResponses: [{ optionId: "cancel", requestId: "approval_1" }],+ });+ await Promise.resolve();++ expect(store.snapshot.status).toBe("submitted");+ expect(store.snapshot.data).toEqual(["client.input.responded"]);++ startResponse.resolve(createStartedMessageResponse("session_1", "http:session_1"));+ await sendPromise;++ expect(store.snapshot.status).toBe("ready");+ expect(store.snapshot.data).toEqual(["client.input.responded", "session.waiting"]);+ });+});+describe("useEveAgent (Vue composable wiring)", () => {it("automatically replays an initial session when resume is enabled", async () => {vi.stubGlobal("window", {});diff --git a/packages/eve/src/vue/use-eve-agent.ts b/packages/eve/src/vue/use-eve-agent.tsindex e9d82989b..997001a76 100644--- a/packages/eve/src/vue/use-eve-agent.ts+++ b/packages/eve/src/vue/use-eve-agent.ts@@ -13,7 +13,8 @@ import {import { resolveEveAgentHost } from "#client/agent-host.js";import type { EveAgentReducer } from "#client/reducer.js";import type { ClientSession } from "#client/session.js";-import { defaultMessageReducer, type EveMessageData } from "#client/message-reducer.js";+import { conversationReducer } from "#client/conversation-reducer.js";+import type { ConversationState } from "#client/conversation-state.js";import type { MessageStreamEvent } from "#protocol/message.js";import type {CancelSessionResult,@@ -50,6 +51,8 @@ export interface UseEveAgentReturn<TData> {readonly cancel: () => Promise<CancelSessionResult>;/** Projected state: the reducer folds every stream event into this value. */readonly data: ComputedRef<TData>;+ /** Canonical session state, regardless of the chosen data reducer. */+ readonly conversation: ComputedRef<ConversationState>;/** Last transport-level error, or `undefined` when healthy. */readonly error: ComputedRef<Error | undefined>;/** Raw server events from this session (authoritative stream). */@@ -128,12 +131,14 @@ export interface UseEveAgentOptions<TData> extends EveAgentStoreCallbacks<TData>* @default true*/readonly optimistic?: boolean;+ /** Follow each subagent call's session into `conversation.agents` while mounted. @default false */+ readonly followSubagents?: boolean;/** Prewarm an owned session on mount and after reset. @default false */readonly prewarm?: boolean;/*** Projects stream events into `TData`.*- * @default defaultMessageReducer()+ * @default conversationReducer*/readonly reducer?: EveAgentReducer<TData>;/** Replay the attached durable session after mount. Requires `initialSession` or `session`. */@@ -147,8 +152,8 @@ export interface UseEveAgentOptions<TData> extends EveAgentStoreCallbacks<TData>}export function useEveAgent(- options?: UseEveAgentOptions<EveMessageData>,-): UseEveAgentReturn<EveMessageData>;+ options?: UseEveAgentOptions<ConversationState>,+): UseEveAgentReturn<ConversationState>;export function useEveAgent<TData>(options: UseEveAgentOptions<TData> & { readonly reducer: EveAgentReducer<TData> },@@ -158,8 +163,8 @@ export function useEveAgent<TData>(* Vue composable that drives one eve session and projects its event stream into* reactive UI state.*- * Without a `reducer`, events project into `EveMessageData` via- * `defaultMessageReducer()`; pass `reducer` to project into a custom `TData`.+ * Without a `reducer`, events project into conversation state including message parts;+ * pass `reducer` to project into a custom `TData`.* Returns reactive refs (`data`, `error`, `events`, `session`, `status`) plus* `prewarm`, `send`, `respond`, `resume`, `cancel`, and `reset`. Configuration is read once on store creation;* remount to change it. On scope dispose, the in-flight request is detached and@@ -171,7 +176,7 @@ export function useEveAgent<TData>(if (options.resume && options.initialSession === undefined && options.session === undefined) {throw new Error("useEveAgent({ resume: true }) requires initialSession or session.");}- const reducer = options.reducer ?? (defaultMessageReducer() as EveAgentReducer<TData>);+ const reducer = options.reducer ?? (conversationReducer as EveAgentReducer<TData>);const store = new EveAgentStore<TData>({auth: options.auth,@@ -180,6 +185,7 @@ export function useEveAgent<TData>(initialEvents: options.initialEvents,initialSession: options.initialSession,optimistic: options.optimistic,+ followSubagents: options.followSubagents,prewarm: options.prewarm,reducer,session: options.session,@@ -211,6 +217,7 @@ export function useEveAgent<TData>(return {cancel: () => store.cancel(),data: computed(() => snapshot.value.data),+ conversation: computed(() => snapshot.value.conversation),error: computed(() => snapshot.value.error),events: computed(() => snapshot.value.events),prewarm: () => store.prewarm(),diff --git a/packages/eve/test/tui-client/lib/tui.ts b/packages/eve/test/tui-client/lib/tui.tsindex 814d7c5ac..177be7d9e 100644--- a/packages/eve/test/tui-client/lib/tui.ts+++ b/packages/eve/test/tui-client/lib/tui.ts@@ -9,6 +9,7 @@export {AUTHORED_ARTIFACTS_UPDATED_LOG_LINE,EveTUIRunner,+ FakeEveServer,createPromptCommandHandler,promptCommandsFor,type EveTUIRunnerOptions,diff --git a/packages/eve/test/tui-client/tui-connection-auth-states.ts b/packages/eve/test/tui-client/tui-connection-auth-states.tsindex b1f400bac..01c760b0a 100644--- a/packages/eve/test/tui-client/tui-connection-auth-states.ts+++ b/packages/eve/test/tui-client/tui-connection-auth-states.ts@@ -1,8 +1,8 @@import { setTimeout as sleep } from "node:timers/promises";-import { ClientSession, MessageResponse, type MessageStreamEvent } from "eve/client";+import { Client } from "eve/client";import type { UnstampedMessageStreamEvent } from "#protocol/message.js";-import { EveTUIRunner, MockScreen, MockUserInput } from "./lib/tui.ts";+import { EveTUIRunner, FakeEveServer, MockScreen, MockUserInput } from "./lib/tui.ts";import { theme } from "./lib/theme.ts";@@ -13,86 +13,22 @@ import { theme } from "./lib/theme.ts";* path through a live runtime, but the live runtime cannot easily* emit `_completed` in this repo (interactive auth* requires a `principalType: "user"` session, which apps/fixtures/agent-tui-client- * doesn't currently provide). This smoke fills that gap with a- * `FakeSession` that separates the parked request stream from the callback- * continuation stream, so we get- * deterministic coverage of:+ * doesn't currently provide). This smoke fills that gap with an in-memory+ * eve server whose callback continuation the smoke emits after asserting the+ * parked challenge, so we get deterministic coverage of:** 1. `_required` with a populated challenge (URL, user code,* instructions). That proves the renderer surfaces all three* challenge fields, which the live smoke can't show.* 2. `_completed` with `outcome: "authorized"` after `session.waiting`.- * That proves the root TUI follows `session.stream()` until the OAuth- * callback resumes the durable workflow, flips the right-title, clears- * the status-bar override, and settles the section.+ * That proves the TUI keeps following the session until the OAuth+ * callback resumes the durable workflow, flips the right-title, and+ * settles the section.* 3. A second turn with `outcome: "failed"` + a reason. That* proves the failure path renders distinctly and the reason* string surfaces in the section content.*/-class FakeSession extends ClientSession {- readonly #turns: ReadonlyArray<readonly UnstampedMessageStreamEvent[]>;- readonly #continuations: ReadonlyArray<readonly UnstampedMessageStreamEvent[]>;- #turnIndex = 0;- #continuationIndex = 0;-- constructor(input: {- turns: ReadonlyArray<readonly UnstampedMessageStreamEvent[]>;- continuations: ReadonlyArray<readonly UnstampedMessageStreamEvent[]>;- }) {- super(- {- host: "http://fake.invalid",- resolveHeaders: async () => new Headers(),- },- { sessionId: "fake-session", streamIndex: 0 },- );- this.#turns = input.turns;- this.#continuations = input.continuations;- }-- override async send<TOutput = unknown>(): Promise<MessageResponse<TOutput>> {- const events = this.#turns[this.#turnIndex] ?? [];- this.#turnIndex += 1;- return new MessageResponse<TOutput>({- cancelTurn: async () => ({ status: "no_active_turn" }),- sessionId: "fake-session",- createStream: () => pacedEvents(events),- });- }-- 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);- }-}--let nextEventIndex = 0;--/** Stamps a fixture event the way an emit seam does before it hits the wire. */-function stamp(event: UnstampedMessageStreamEvent): MessageStreamEvent {- nextEventIndex += 1;- return {- ...event,- meta: { at: new Date().toISOString(), id: `evt_smoke_${nextEventIndex}` },- } as MessageStreamEvent;-}--async function* pacedEvents(- events: readonly UnstampedMessageStreamEvent[],-): AsyncGenerator<MessageStreamEvent> {- for (const event of events) {- yield stamp(event);- // Pacing gives the renderer and smoke assertions a chance to observe- // each lifecycle state between events, as the HTTP transport does live.- await sleep(200);- }-}-const turnId = "turn-0";const stepIndex = 0;@@ -210,14 +146,14 @@ const secondCallbackTurn: UnstampedMessageStreamEvent[] = [process.env.EVE_TUI_UNICODE = "1";void (async () => {- const session = new FakeSession({- turns: [firstTurn, secondTurn],- continuations: [firstCallbackTurn, secondCallbackTurn],- });+ const server = new FakeEveServer(({ deliveryId }) =>+ deliveryId === "delivery_1" ? firstTurn : secondTurn,+ );+ globalThis.fetch = server.fetch;const screen = new MockScreen({ columns: 100, rows: 40 });const input = new MockUserInput();const runner = new EveTUIRunner({- session,+ client: new Client({ host: "http://fake.invalid" }),screen,userInput: input,name: "TUI states smoke",@@ -258,6 +194,9 @@ void (async () => {);console.log(theme.muted("[states] URL, code, and instructions all rendered"));+ // The browser completes the grant; the callback resumes the parked session.+ server.emit(firstCallbackTurn);+await waitForCondition(() => screen.snapshot().includes("authorized"), {timeoutMs: 10_000,label: "authorized right-title",@@ -284,33 +223,9 @@ void (async () => {);console.log(theme.muted("[states] completed authorization body replaced the challenge"));- await waitForCondition(- () => !screen.snapshot().includes("Waiting for connection authorization"),- {- timeoutMs: 5_000,- label: "status-bar override cleared after completed",- onTimeout: () => screen.snapshot(),- },- );- console.log(theme.muted("[states] status-bar override cleared after authorized"));-- // Wait for the runner to loop back into `readPrompt` before typing- // the next message. Without this, `MockUserInput.type` emits onto an- // event emitter that no listener is currently subscribed to (the- // first turn's data handler was detached when the stream finished),- // and the input event is silently dropped. The bottom-bar status- // text changes to "Type a prompt and press Enter" exactly when- // `readPrompt` attaches a fresh handler.- // Wait for the first turn's stream to fully drain (events after the- // last asserted state, `step.completed`, `session.waiting`, plus- // the renderStream finally and the runner's loop-back into- // `readPrompt`). 1s is comfortable headroom over the empirical- // ~600ms needed for the synthetic stream's per-event pacing. The- // "Type a prompt and press Enter" status text the renderer sets in- // `readPrompt` is NOT visible in the snapshot, when input is- // active, the bottom line shows the `> █` input prompt instead of- // `#status`, so a sleep is the simplest reliable barrier.- await sleep(1000);+ // Let the first turn settle so the next message starts a new turn+ // instead of steering this one.+ await screen.waitForIdlePrompt(5_000);// ---- Turn 2: other-mcp, ends in `failed` with a reason ----@@ -319,6 +234,7 @@ void (async () => {await screen.waitForText("● other-mcp · authorization", 10_000);console.log(theme.muted("[states] other-mcp section header rendered"));+ server.emit(secondCallbackTurn);await waitForCondition(() => screen.snapshot().includes("failed"), {timeoutMs: 10_000,@@ -339,6 +255,7 @@ void (async () => {input.ctrlC();input.ctrlC();await runPromise;+ server.close();} catch (error) {input.ctrlC();input.ctrlC();diff --git a/packages/eve/test/tui-client/tui-steer.ts b/packages/eve/test/tui-client/tui-steer.tsindex 9ce088e44..23865807a 100644--- a/packages/eve/test/tui-client/tui-steer.ts+++ b/packages/eve/test/tui-client/tui-steer.ts@@ -12,9 +12,9 @@ import { theme } from "./lib/theme.ts";* and double-Ctrl+C exit against a live server:** 1. Start a long turn, then press Enter on a follow-up while it streams.- * The message steers immediately without entering the queue panel.+ * The message steers the running turn immediately.* 2. The steered message is answered and the runner returns to an idle prompt.- * 3. With no message queued, one Esc cancels another long turn, then a+ * 3. One Esc cancels another long turn, then a* follow-up succeeds on the preserved session.** The tokens prove delivery order end-to-end: each must appear twice@@ -67,7 +67,7 @@ run({ app: "agent-tui-client", kind: "local-build" }, async (target) => {input.enter();await waitForActiveTurn(screen, 30_000);- // With no queued message, the first Esc cooperatively cancels the turn.+ // The first Esc cooperatively cancels the turn.input.emit("data", Buffer.from("\x1b"));await sleep(60);await waitForRawOutput(@@ -78,7 +78,7 @@ run({ app: "agent-tui-client", kind: "local-build" }, async (target) => {"single-Esc cancellation",);await screen.waitForIdlePrompt(30_000);- console.log(theme.muted("[tui-steer] one empty-queue Esc cancelled the turn"));+ console.log(theme.muted("[tui-steer] one Esc cancelled the turn"));input.type(`Reply with one short sentence containing the token ${CANCEL_FOLLOW_UP_TOKEN}.`);input.enter();