An open-source, faster Devin alternative
TypeScript
react: send resolves with an admission receipt or rejects, fenced by session
Igor Zalutskieb64cb281f2d
diff --git a/cli/src/project.ts b/cli/src/project.tsindex 8b563034..9962c1b5 100644--- a/cli/src/project.ts+++ b/cli/src/project.ts@@ -607,7 +607,9 @@ export default function App() {event.preventDefault();const prompt = input;setInput("");- void send(prompt);+ // send rejects when no turn was admitted; the hook shows the error and+ // the draft comes back.+ send(prompt).catch(() => setInput(prompt));}return (@@ -621,7 +623,7 @@ export default function App() {<section className="chat" aria-label="Agent conversation"><div className="messages">{messages.length === 0 ? (- <button className="suggestion" onClick={() => void send("Say hello and tell me what you can do.")}>+ <button className="suggestion" onClick={() => send("Say hello and tell me what you can do.").catch(() => undefined)}>Say hello and tell me what you can do →</button>) : (diff --git a/docs/agents/react.mdx b/docs/agents/react.mdxindex 9e3e26e4..cb44cd8d 100644--- a/docs/agents/react.mdx+++ b/docs/agents/react.mdx@@ -101,6 +101,7 @@ envelope `{ error: { message } }`.### 3. Attach in the browser```tsx+import { useState } from "react";import { useAgent } from "@opencomputer/react";export function WorkshopChat({ sessionId, onNotesChanged }: { sessionId: string; onNotesChanged: () => void }) {@@ -109,6 +110,12 @@ export function WorkshopChat({ sessionId, onNotesChanged }: { sessionId: string;basePath: "/api/agent",onMemorySaved: onNotesChanged,});+ const [draft, setDraft] = useState("");++ async function submit() {+ await send(draft); // rejects when no turn was admitted+ setDraft(""); // clear only once the platform has the input+ }return (<section>@@ -118,7 +125,8 @@ export function WorkshopChat({ sessionId, onNotesChanged }: { sessionId: string;<strong>{message.role}:</strong> {message.text}</p>))}- <button disabled={isRunning} onClick={() => void send("Book the venue")}>Send</button>+ <input value={draft} onChange={(event) => setDraft(event.target.value)} />+ <button onClick={() => submit().catch(() => undefined)}>Send</button><button disabled={!isRunning} onClick={() => void stop()}>Stop</button>{error ? <p role="alert">{error}</p> : null}</section>@@ -131,12 +139,41 @@ reduces it to messages, so a reopened page shows the conversation as itstands, including turns that ran while the tab was closed. It then keepspolling from its cursor. A failed poll sets `error`, backs off, and resumesfrom the same cursor; nothing is replayed twice, and `error` clears when the-log answers again. Changing `sessionId` replays the new session.--`send` starts a turn and shows the input at once; the log's own record of it-confirms that message rather than adding a second one. Turns sent while one-is running are queued by the platform. `stop` interrupts the running turn-without spending a model turn.+log answers again. Changing `sessionId` replays the new session; a `send`+still in flight for the previous session settles for its caller but never+changes what the new session shows.++`after` is a position, not a snapshot: the hook applies only events after+it, so messages and running state from before that position are not+reconstructed. Pass `after` to skip history you have already rendered from+your own store, otherwise start at `0`.++Turns sent while one is running are queued by the platform. `stop`+interrupts the running turn without spending a model turn.++### What `send` returns++`send(text)` resolves once the platform has admitted the input as a turn,+with a receipt `{ sessionId, turnId, status }` where `status` is `queued`+or `running`. The input appears in `messages` at that point; the log's own+record of it confirms that message rather than adding a second one.+`isRunning` is true from admission until the log settles the turn, and a+reply that arrives after the log has already shown the turn completed+changes nothing.++`send` rejects with a `SendError` when no turn was admitted, so a composer+can keep the draft:++| `code` | Cause | `status` |+| --- | --- | --- |+| The platform's error code, for example `session_ended`, `memory_admission_unconfirmed` or `insufficient_credits` | The request was answered with an error | The HTTP status |+| `network_error` | The request was not answered | none |+| `empty_input` | The text was blank; nothing was sent | none |+| `busy` | Create mode only: a turn is already running | none |++The hook's `error` is set to the same message either way. A turn that fails+after admission is not a rejection: the receipt was returned, the failure+arrives through the log as a `turn.failed` event and sets `error`.The hook never suspends, resumes or ends an attached session. Its lifecyclebelongs to the server that created it.@@ -175,7 +212,7 @@ export default function Chat() {))}<buttondisabled={isRunning}- onClick={() => void send("Hello")}+ onClick={() => send("Hello").catch(() => undefined)}>Send</button>@@ -186,8 +223,9 @@ export default function Chat() {}```-Each `send` resumes the session, streams one turn and suspends it again.-Sessions created this way have no memory bindings.+Each `send` resumes the session, streams one turn and suspends it again; the+promise settles when the turn ends, with the same receipt and rejections as+in attach mode. Sessions created this way have no memory bindings.Run the watched agent deployment and the web application separately:@@ -205,10 +243,10 @@ the web application. Credentials are not bundled into browser code.| Value | Purpose || --- | --- || `messages` | User and assistant messages, in log order |-| `send(text)` | Starts a turn; in create mode the first call creates the session |+| `send(text)` | Starts a turn; resolves with `{ sessionId, turnId, status }` or rejects with a `SendError`. In create mode the first call creates the session || `stop()` | Interrupts the running turn || `sessionId` | The attached session, or the created one after the first send |-| `isRunning` | Whether a turn is active |+| `isRunning` | A turn is admitted and not yet settled by the log || `isReplaying` | Attach mode: true until the existing history has been read || `error` | The most recent request or turn failure || `memorySaves` | `memory.saved` events seen so far |@@ -222,7 +260,7 @@ the web application. Credentials are not bundled into browser code.| `agent` | Create mode: `agent-id@alias` || `basePath` | Route prefix for the three routes; default `/api/opencomputer/managed-agents` || `fetch` | A fetch implementation, for example one that adds a CSRF header |-| `after` | Attach mode: replay from this cursor instead of the start |+| `after` | Attach mode: apply only events after this position; earlier history is not reconstructed || `pollIntervalMs` | Attach mode: interval between empty polls; default 1000, 500 while a turn runs || `onEvent` | Every applied event, including replayed history || `onMemorySaved` | Each `memory.saved` event |diff --git a/react/src/events.test.ts b/react/src/events.test.tsindex 74cea1c4..89dcf2ce 100644--- a/react/src/events.test.ts+++ b/react/src/events.test.ts@@ -6,6 +6,7 @@ import {emptyTimeline,failureMessage,inputMessageId,+ isSettledTurn,memorySaveFromEvent,type AgentEvent,} from "./events.js";@@ -27,8 +28,12 @@ const turn: AgentEvent[] = [];test("a turn reduces to one user and one assistant message", () => {+ const queued = applyEvents(emptyTimeline(), turn.slice(0, 1));+ assert.deepEqual(queued.turns, { t1: "queued" });+ assert.equal(isSettledTurn(queued, "t1"), false);const partial = applyEvents(emptyTimeline(), turn.slice(0, 4));assert.equal(partial.isRunning, true);+ assert.deepEqual(partial.turns, { t1: "running" });assert.deepEqual(partial.messages, [{ id: inputMessageId("t1"), role: "user", text: "hi", turnId: "t1" },{ id: "turn:t1:reply", role: "assistant", text: "hello", turnId: "t1", streaming: true },@@ -37,6 +42,9 @@ test("a turn reduces to one user and one assistant message", () => {const complete = applyEvents(partial, turn.slice(4));assert.equal(complete.isRunning, false);assert.equal(complete.cursor, 7);+ assert.deepEqual(complete.turns, { t1: "completed" });+ assert.equal(isSettledTurn(complete, "t1"), true);+ assert.equal(isSettledTurn(complete, "t2"), false);assert.deepEqual(complete.messages, [{ id: inputMessageId("t1"), role: "user", text: "hi", turnId: "t1" },{ id: "turn:t1:reply", role: "assistant", text: "hello", turnId: "t1", streaming: false },diff --git a/react/src/events.ts b/react/src/events.tsindex 35a10824..58815a94 100644--- a/react/src/events.ts+++ b/react/src/events.ts@@ -35,11 +35,20 @@ export interface MemorySave {bytes: number;}+export type TurnStatus =+ | "queued"+ | "running"+ | "completed"+ | "failed"+ | "cancelled";+export interface SessionTimeline {messages: AgentMessage[];memorySaves: MemorySave[];/** The highest `seq` applied so far. */cursor: number;+ /** Every turn the log has recorded, by id, with its status as of the cursor. */+ turns: Record<string, TurnStatus>;isRunning: boolean;ended: boolean;}@@ -49,11 +58,21 @@ export function emptyTimeline(): SessionTimeline {messages: [],memorySaves: [],cursor: 0,+ turns: {},isRunning: false,ended: false,};}+/** Whether the log has settled the turn: completed, failed or cancelled. */+export function isSettledTurn(+ timeline: SessionTimeline,+ turnId: string,+): boolean {+ const status = timeline.turns[turnId];+ return status === "completed" || status === "failed" || status === "cancelled";+}+/** The id of the user message that starts a turn; `send` uses the same id, so the event upserts it. */export function inputMessageId(turnId: string): string {return `turn:${turnId}:input`;@@ -112,10 +131,16 @@ export function applyEvent(text: text(data.input),...(event.turnId ? { turnId: event.turnId } : {}),});+ if (event.turnId && !timeline.turns[event.turnId]) {+ next.turns = { ...timeline.turns, [event.turnId]: "queued" };+ }return next;}case "turn.started":next.isRunning = true;+ if (event.turnId) {+ next.turns = { ...timeline.turns, [event.turnId]: "running" };+ }return next;case "message.delta": {const id = replyMessageId(event);@@ -143,6 +168,17 @@ export function applyEvent(case "turn.failed":case "turn.cancelled":next.isRunning = false;+ if (event.turnId) {+ next.turns = {+ ...timeline.turns,+ [event.turnId]:+ event.type === "turn.completed"+ ? "completed"+ : event.type === "turn.failed"+ ? "failed"+ : "cancelled",+ };+ }next.messages = timeline.messages.map((message) =>message.streaming && message.turnId === event.turnId? { ...message, streaming: false }diff --git a/react/src/index.ts b/react/src/index.tsindex 4b2fab71..32d2026a 100644--- a/react/src/index.ts+++ b/react/src/index.ts@@ -4,6 +4,7 @@ import {emptyTimeline,failureMessage,inputMessageId,+ isSettledTurn,memorySaveFromEvent,type AgentEvent,type AgentMessage,@@ -15,10 +16,12 @@ export {applyEvent,applyEvents,emptyTimeline,+ isSettledTurn,type AgentEvent,type AgentMessage,type MemorySave,type SessionTimeline,+ type TurnStatus,} from "./events.js";interface CommonOptions {@@ -59,13 +62,46 @@ export interface AttachAgentOptions extends CommonOptions {export type UseAgentOptions = CreateAgentOptions | AttachAgentOptions;+/** What `send` resolves with: the platform admitted the input as a turn. */+export interface SendReceipt {+ sessionId: string;+ turnId: string;+ /** `queued` behind earlier turns, or `running` at once. */+ status: "queued" | "running";+}++/**+ * What `send` rejects with. `code` is the platform's error code when the+ * request was answered (`session_ended`, `memory_admission_unconfirmed`,+ * `insufficient_credits`), `network_error` when it was not, `empty_input`+ * and `busy` when nothing was sent. `status` is the HTTP status when there+ * was one. The hook's `error` is set to the same message.+ */+export class SendError extends Error {+ readonly code: string;+ readonly status: number | undefined;++ constructor(message: string, code: string, status?: number) {+ super(message);+ this.name = "SendError";+ this.code = code;+ this.status = status;+ }+}+export interface UseAgentResult {messages: AgentMessage[];- /** Starts a turn. In create mode the first call creates the session. */- send: (value: string) => Promise<void>;+ /**+ * Starts a turn. Resolves with the admission receipt; rejects with a+ * `SendError` when no turn was admitted, so a draft can be kept. In create+ * mode the first call creates the session and the promise settles when the+ * turn ends.+ */+ send: (value: string) => Promise<SendReceipt>;/** Interrupts the running turn. */stop: () => Promise<void>;sessionId: string | undefined;+ /** A turn is admitted and not yet settled by the log. */isRunning: boolean;/** Attach mode: true until the existing history has been replayed. */isReplaying: boolean;@@ -105,6 +141,19 @@ function upsert(return next;}+function asSendError(cause: unknown): SendError {+ if (cause instanceof SendError) return cause;+ return new SendError(+ cause instanceof Error ? cause.message : String(cause),+ "network_error",+ );+}++interface TurnAdmission {+ turnId: string;+ status: "queued" | "running";+}+export function useAgent(agentOrOptions: string | UseAgentOptions,): UseAgentResult {@@ -124,13 +173,25 @@ export function useAgent(attachedSessionId,);const sessionRef = useRef<string | undefined>(attachedSessionId);+ // Bumped by every attach, so work started against an earlier attachment+ // of the same session id is fenced too.+ const attachmentRef = useRef(0);const cursorRef = useRef(0);const [isReplaying, setIsReplaying] = useState(Boolean(attachedSessionId));const [error, setError] = useState<string>();+ // Admission state, apart from the log: turns the platform admitted whose+ // settlement the log has not shown yet. The log's word wins as soon as it+ // arrives, and an admission the log already settled never counts.+ const [admitted, setAdmitted] = useState<string[]>([]);const commit = useCallback((next: SessionTimeline) => {timelineRef.current = next;setTimeline(next);+ setAdmitted((current) =>+ current.some((turnId) => isSettledTurn(next, turnId))+ ? current.filter((turnId) => !isSettledTurn(next, turnId))+ : current,+ );}, []);const request = useCallback(@@ -143,13 +204,22 @@ export function useAgent(const body: unknown =response.status === 204 ? undefined : await response.json();if (!response.ok) {- const problem = body as { error?: { message?: string } | string };+ const problem = body as {+ error?: { code?: string; message?: string } | string;+ };const message =typeof problem?.error === "string"? problem.error: problem?.error?.message;- throw new Error(+ const code =+ typeof problem?.error === "object" &&+ typeof problem.error?.code === "string"+ ? problem.error.code+ : "request_failed";+ throw new SendError(message ?? `Agent request failed (${String(response.status)})`,+ code,+ response.status,);}return body as T;@@ -190,10 +260,12 @@ export function useAgent(if (!attachedSessionId) return;const controller = new AbortController();const { signal } = controller;+ attachmentRef.current += 1;sessionRef.current = attachedSessionId;setSessionId(attachedSessionId);setError(undefined);setIsReplaying(true);+ setAdmitted([]);cursorRef.current = after;commit({ ...emptyTimeline(), cursor: after });void (async () => {@@ -229,43 +301,77 @@ export function useAgent(};}, [attachedSessionId, after, basePath, commit, ingest, request]);+ const admitTurn = useCallback(+ async (activeSession: string, prompt: string): Promise<SendReceipt> => {+ const admission = await request<TurnAdmission>(+ `/sessions/${encodeURIComponent(activeSession)}/turns`,+ {+ method: "POST",+ body: JSON.stringify({+ input: prompt,+ idempotencyKey: crypto.randomUUID(),+ }),+ },+ );+ return {+ sessionId: activeSession,+ turnId: admission.turnId,+ status: admission.status === "running" ? "running" : "queued",+ };+ },+ [request],+ );+const sendAttached = useCallback(- async (activeSession: string, prompt: string) => {+ async (activeSession: string, prompt: string): Promise<SendReceipt> => {+ // The target is fixed here. Whatever the hook is attached to when the+ // response arrives, this response belongs to that session and that+ // attachment only; if they have changed, the caller still gets the+ // outcome and the hook's state stays with the current session.+ const attachment = attachmentRef.current;+ const current = () =>+ sessionRef.current === activeSession &&+ attachmentRef.current === attachment;setError(undefined);try {- const result = await request<{ turnId: string }>(- `/sessions/${encodeURIComponent(activeSession)}/turns`,- {- method: "POST",- body: JSON.stringify({- input: prompt,- idempotencyKey: crypto.randomUUID(),+ const receipt = await admitTurn(activeSession, prompt);+ if (current()) {+ // The log's message.received for this turn carries the same id,+ // so it confirms this message instead of duplicating it. Whether+ // the turn is still running is the log's call, not this reply's.+ const timeline = timelineRef.current;+ commit({+ ...timeline,+ messages: upsert(timeline.messages, {+ id: inputMessageId(receipt.turnId),+ role: "user",+ text: prompt,+ turnId: receipt.turnId,}),- },- );- // The log's message.received for this turn carries the same id, so- // it confirms this message instead of duplicating it.- const current = timelineRef.current;- commit({- ...current,- isRunning: true,- messages: upsert(current.messages, {- id: inputMessageId(result.turnId),- role: "user",- text: prompt,- turnId: result.turnId,- }),- });+ });+ if (!isSettledTurn(timelineRef.current, receipt.turnId)) {+ setAdmitted((pending) =>+ pending.includes(receipt.turnId)+ ? pending+ : [...pending, receipt.turnId],+ );+ }+ }+ return receipt;} catch (cause) {- setError(cause instanceof Error ? cause.message : String(cause));+ const failure = asSendError(cause);+ if (current()) setError(failure.message);+ throw failure;}},- [commit, request],+ [admitTurn, commit],);const sendCreated = useCallback(- async (prompt: string) => {- if (timelineRef.current.isRunning) return;+ async (prompt: string): Promise<SendReceipt> => {+ if (timelineRef.current.isRunning) {+ throw new SendError("A turn is already running.", "busy");+ }const userMessage: AgentMessage = {id: crypto.randomUUID(),role: "user",@@ -288,6 +394,7 @@ export function useAgent({ isRunning: true },);setError(undefined);+ let receipt: SendReceipt | undefined;try {let activeSession = sessionRef.current;if (!activeSession) {@@ -358,13 +465,7 @@ export function useAgent(}};await waitFor((event) => event.type === "runtime.connected");- await request(`/sessions/${encodeURIComponent(activeSession)}/turns`, {- method: "POST",- body: JSON.stringify({- input: prompt,- idempotencyKey: crypto.randomUUID(),- }),- });+ receipt = await admitTurn(activeSession, prompt);const completed = await waitFor((event) =>event.type === "turn.completed" ||@@ -383,6 +484,18 @@ export function useAgent(} catch (cause) {const message = cause instanceof Error ? cause.message : String(cause);setError(message);+ if (!receipt) {+ // Nothing was admitted: the input was never sent, so it is not+ // part of the conversation, and the caller keeps it.+ updateMessages(+ (current) =>+ current.filter(+ (item) => item.id !== userMessage.id && item.id !== assistantId,+ ),+ { isRunning: false },+ );+ throw asSendError(cause);+ }updateMessages((current) =>current.map((item) =>item.id === assistantId && !item.text@@ -397,16 +510,19 @@ export function useAgent(isRunning: false,});}+ if (!receipt) throw new SendError("No turn was admitted.", "busy");+ return receipt;},- [commit, request],+ [admitTurn, commit, request],);const send = useCallback(- async (value: string) => {+ async (value: string): Promise<SendReceipt> => {const prompt = value.trim();- if (!prompt) return;- if (attachedSessionId) await sendAttached(attachedSessionId, prompt);- else await sendCreated(prompt);+ if (!prompt) throw new SendError("Nothing to send.", "empty_input");+ return attachedSessionId+ ? sendAttached(attachedSessionId, prompt)+ : sendCreated(prompt);},[attachedSessionId, sendAttached, sendCreated],);@@ -429,7 +545,7 @@ export function useAgent(send,stop,sessionId,- isRunning: timeline.isRunning,+ isRunning: timeline.isRunning || admitted.length > 0,isReplaying,error,memorySaves: timeline.memorySaves,diff --git a/react/src/use-agent.test.ts b/react/src/use-agent.test.tsindex 5784a8f3..047bb422 100644--- a/react/src/use-agent.test.ts+++ b/react/src/use-agent.test.ts@@ -5,8 +5,10 @@ import { act, createElement } from "react";import { createRoot, type Root } from "react-dom/client";import {+ SendError,useAgent,type AgentEvent,+ type SendReceipt,type UseAgentOptions,type UseAgentResult,} from "./index.js";@@ -33,6 +35,9 @@ function fakeSession(sessionId: string) {const calls: Call[] = [];let failNext = 0;let turns = 0;+ // While set, turn admissions are recorded in the log at once but their+ // responses wait until released: the reply is what arrives late.+ let held: Array<() => void> | undefined;const append = (event: Omit<AgentEvent, "seq">) => {log.push({ ...event, seq: log.length + 1 });};@@ -68,7 +73,11 @@ function fakeSession(sessionId: string) {data: { input: call.body?.input, mode: "queue" },});append({ turnId, type: "turn.started", data: {} });- return Response.json({ turnId, status: "queued", duplicate: false }, { status: 202 });+ const reply = () =>+ Response.json({ turnId, status: "queued", duplicate: false }, { status: 202 });+ if (!held) return reply();+ const gate = new Promise<void>((release) => held!.push(release));+ return gate.then(reply);}if (call.method === "POST" && url.pathname === `${prefix}/interrupt`) {return Response.json({ id: sessionId, status: "idle" });@@ -86,6 +95,14 @@ function fakeSession(sessionId: string) {failNext: (count: number) => {failNext = count;},+ holdTurns: () => {+ held = [];+ return () => {+ const pending = held ?? [];+ held = undefined;+ for (const release of pending) release();+ };+ },};}@@ -251,9 +268,11 @@ test("attach sends turns and interrupts through the app's routes without duplicaawait view.render();await view.until((result) => !result.isReplaying, "empty history");+ let receipt: SendReceipt | undefined;await act(async () => {- await view.result().send(" Book the venue ");+ receipt = await view.result().send(" Book the venue ");});+ assert.deepEqual(receipt, { sessionId: "ses-3", turnId: "turn-1", status: "queued" });const sent = view.result();assert.equal(sent.isRunning, true);assert.deepEqual(sent.messages, [@@ -297,15 +316,218 @@ test("attach reports a failed turn and a rejected send", async (t) => {pollIntervalMs: 5,});await rejecting.render();+ let rejection: unknown;await act(async () => {- await rejecting.result().send("anything");+ rejection = await rejecting.result().send("anything").catch((cause: unknown) => cause);});+ assert.ok(rejection instanceof SendError);+ assert.equal(rejection.status, 409);+ assert.equal(rejection.code, "session_ended");+ assert.equal(rejection.message, "Session has ended");assert.equal(rejecting.result().error, "Session has ended");assert.deepEqual(rejecting.result().messages, []);await rejecting.unmount();await view.unmount();});+// Review reproduction (U3): a send whose response arrives after the hook+// moved to another session must not land in that session.+test("a send admitted by one session never lands in the session attached later", async (t) => {+ const a = fakeSession("ses-a");+ const b = fakeSession("ses-b");+ b.append({ turnId: "b0", type: "message.received", data: { input: "B's own history" } });+ b.append({ turnId: "b0", type: "turn.completed", data: {} });+ const routes: typeof globalThis.fetch = (input, init) =>+ String(input).includes("/sessions/ses-b/") ? b.fetch(input, init) : a.fetch(input, init);+ const container = dom.window.document.createElement("div");+ const root: Root = createRoot(container);+ let latest: UseAgentResult | undefined;+ function Harness({ sessionId }: { sessionId: string }) {+ latest = useAgent({ sessionId, basePath: "/app/agent", fetch: routes, pollIntervalMs: 5 });+ return null;+ }+ t.after(async () => {+ await act(async () => {+ root.unmount();+ });+ });+ const tick = () =>+ act(async () => {+ await new Promise((resolve) => setTimeout(resolve, 5));+ });+ const until = async (predicate: () => boolean, label: string) => {+ for (let attempt = 0; attempt < 200; attempt += 1) {+ if (predicate()) return;+ await tick();+ }+ throw new Error(`timed out waiting for ${label}`);+ };++ await act(async () => {+ root.render(createElement(Harness, { sessionId: "ses-a" }));+ });+ await until(() => latest?.isReplaying === false, "A's replay");++ const release = a.holdTurns();+ let sent: Promise<SendReceipt> | undefined;+ await act(async () => {+ sent = latest!.send("Plan A's workshop");+ await new Promise((resolve) => setTimeout(resolve, 0));+ });+ // Switch to B while A's admission response is still outstanding.+ await act(async () => {+ root.render(createElement(Harness, { sessionId: "ses-b" }));+ });+ await until(() => latest?.isReplaying === false && latest.sessionId === "ses-b", "B's replay");+ assert.deepEqual(+ latest!.messages.map((message) => message.text),+ ["B's own history"],+ );++ // A's response lands now: A's caller gets A's receipt, B is untouched.+ release();+ const receipt = await sent!;+ assert.deepEqual(receipt, { sessionId: "ses-a", turnId: "turn-1", status: "queued" });+ await tick();+ await tick();+ assert.equal(latest!.sessionId, "ses-b");+ assert.deepEqual(+ latest!.messages.map((message) => message.text),+ ["B's own history"],+ );+ assert.equal(latest!.isRunning, false);+ assert.equal(latest!.error, undefined);++ // The same fence covers a late failure: it is not B's error.+ await act(async () => {+ root.render(createElement(Harness, { sessionId: "ses-a" }));+ });+ await until(() => latest?.isReplaying === false && latest.sessionId === "ses-a", "A again");+ let failed: Promise<SendReceipt> | undefined;+ const gate = new Promise<void>((resolve) => setTimeout(resolve, 20));+ const slowFailure: typeof globalThis.fetch = async (input, init) => {+ if (init?.method === "POST") {+ await gate;+ throw new TypeError("network down");+ }+ return routes(input, init);+ };+ function Slow({ sessionId }: { sessionId: string }) {+ latest = useAgent({ sessionId, basePath: "/app/agent", fetch: slowFailure, pollIntervalMs: 5 });+ return null;+ }+ await act(async () => {+ root.render(createElement(Slow, { sessionId: "ses-a" }));+ });+ await until(() => latest?.isReplaying === false, "A on the slow transport");+ await act(async () => {+ failed = latest!.send("This one fails late");+ failed.catch(() => undefined);+ });+ await act(async () => {+ root.render(createElement(Slow, { sessionId: "ses-b" }));+ });+ await until(() => latest?.isReplaying === false && latest.sessionId === "ses-b", "B again");+ const cause = await failed!.catch((error: unknown) => error);+ assert.ok(cause instanceof SendError);+ assert.equal(cause.code, "network_error");+ await tick();+ assert.equal(latest!.error, undefined);+ assert.equal(latest!.sessionId, "ses-b");+});++// Review reproduction (U4): the admission reply says nothing about+// execution; a turn the log already settled stays settled.+test("a late admission reply does not turn a completed turn back into a running one", async (t) => {+ const session = fakeSession("ses-late");+ const view = mount(t, { sessionId: "ses-late", basePath: "/app/agent", fetch: session.fetch, pollIntervalMs: 5 });+ await view.render();+ await view.until((result) => !result.isReplaying, "empty history");++ const release = session.holdTurns();+ let sent: Promise<SendReceipt> | undefined;+ await act(async () => {+ sent = view.result().send("Quick question");+ await new Promise((resolve) => setTimeout(resolve, 0));+ });+ // The admitted turn runs to completion in the log while the reply is held.+ session.append({ turnId: "turn-1", type: "message.completed", data: { text: "Quick answer" } });+ session.append({ turnId: "turn-1", type: "turn.completed", data: {} });+ const settled = await view.until((result) => result.cursor === 4, "the completed turn");+ assert.equal(settled.isRunning, false);+ assert.deepEqual(+ settled.messages.map((message) => [message.role, message.text]),+ [["user", "Quick question"], ["assistant", "Quick answer"]],+ );++ release();+ const receipt = await sent!;+ assert.equal(receipt.turnId, "turn-1");+ // Several empty polls later the hook still reports the log's verdict.+ for (let i = 0; i < 6; i += 1) {+ await act(async () => {+ await new Promise((resolve) => setTimeout(resolve, 5));+ });+ assert.equal(view.result().isRunning, false);+ }+ assert.equal(view.result().messages.length, 2);+ await view.unmount();+});++// Review reproduction (U9): an admission failure is a rejection the caller+// can act on, in attach and in create mode; the hook's error is set too.+test("send rejects on an unconfirmed admission and leaves nothing of the draft in the timeline", async (t) => {+ const unconfirmed = () =>+ Response.json(+ { error: { code: "memory_admission_unconfirmed", message: "Memory admission was not confirmed" } },+ { status: 503 },+ );+ const attached = mount(t, {+ sessionId: "ses-503",+ basePath: "/app/agent",+ fetch: async (_input, init) =>+ init?.method === "POST" ? unconfirmed() : Response.json({ events: [] }),+ pollIntervalMs: 5,+ });+ await attached.render();+ await attached.until((result) => !result.isReplaying, "empty history");+ let rejection: unknown;+ await act(async () => {+ rejection = await attached.result().send("Keep this draft").catch((cause: unknown) => cause);+ });+ assert.ok(rejection instanceof SendError);+ assert.equal(rejection.status, 503);+ assert.equal(rejection.code, "memory_admission_unconfirmed");+ assert.equal(attached.result().error, "Memory admission was not confirmed");+ assert.deepEqual(attached.result().messages, []);+ assert.equal(attached.result().isRunning, false);+ await attached.unmount();++ const created = mount(t, {+ agent: "hello-world@development",+ fetch: async (_input, init) =>+ init?.method === "POST" ? unconfirmed() : Response.json({ events: [] }),+ });+ await created.render();+ await act(async () => {+ rejection = await created.result().send("Keep this draft too").catch((cause: unknown) => cause);+ });+ assert.ok(rejection instanceof SendError);+ assert.equal(rejection.status, 503);+ assert.equal(rejection.code, "memory_admission_unconfirmed");+ assert.equal(created.result().error, "Memory admission was not confirmed");+ assert.deepEqual(created.result().messages, []);+ assert.equal(created.result().sessionId, undefined);+ assert.equal(created.result().isRunning, false);++ // Nothing to send is a rejection as well, without a request.+ const empty = await created.result().send(" ").catch((cause: unknown) => cause);+ assert.ok(empty instanceof SendError);+ assert.equal(empty.code, "empty_input");+ assert.equal(empty.status, undefined);+ await created.unmount();+});+test("create mode still creates the session on the first send and streams the reply", async (t) => {const calls: Call[] = [];const log: AgentEvent[] = [@@ -344,9 +566,11 @@ test("create mode still creates the session on the first send and streams the reassert.equal(view.result().isReplaying, false);assert.equal(view.result().sessionId, undefined);+ let receipt: SendReceipt | undefined;await act(async () => {- await view.result().send("Hi");+ receipt = await view.result().send("Hi");});+ assert.deepEqual(receipt, { sessionId: "ses-new", turnId: "t1", status: "queued" });const result = view.result();assert.equal(result.sessionId, "ses-new");assert.equal(result.isRunning, false);