An open-source, faster Devin alternative
TypeScript
react: send options with a caller-retained key and payload; turns reduced from the log
Igor Zalutski005fa6d03ab5
diff --git a/react/README.md b/react/README.mdindex fae60cff..cc3bfb4d 100644--- a/react/README.md+++ b/react/README.md@@ -23,6 +23,17 @@ interrupt routes, which your server proxies under its own authentication; theAPI key never reaches the browser. See the[React integration guide](https://opencomputer.dev/agents/react).+`send(text, { idempotencyKey, payload })` takes a key the caller keeps for+that submission's retries and a structured payload the agent reads beside+the text. `turns` lists the session's turns with their status, messages,+tool calls, result and failure, reduced from the same log as `messages`:++```tsx+const { turns, send } = useAgent({ sessionId, basePath: "/api/agent" });+await send("Fix the login page", { idempotencyKey: submissionId, payload: { repo: "acme/web" } });+turns.at(-1)?.toolCalls.map((call) => `${call.title}: ${call.status}`);+```+Run `npm run deploy -- --watch` for the agent project to configure the localauthenticated bridge, then start the React application separately with its owndevelopment command, such as `npm run dev:web`.diff --git a/react/package-lock.json b/react/package-lock.jsonindex bdefebe0..45e06652 100644--- a/react/package-lock.json+++ b/react/package-lock.json@@ -1,12 +1,12 @@{"name": "@opencomputer/react",- "version": "0.2.0",+ "version": "0.3.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@opencomputer/react",- "version": "0.2.0",+ "version": "0.3.0","devDependencies": {"@types/jsdom": "^21.1.7","@types/node": "^24.13.4",diff --git a/react/package.json b/react/package.jsonindex cdbce980..b80106ea 100644--- a/react/package.json+++ b/react/package.json@@ -1,6 +1,6 @@{"name": "@opencomputer/react",- "version": "0.2.0",+ "version": "0.3.0","description": "React hooks for OpenComputer agents.","type": "module","main": "./dist/index.js",diff --git a/react/src/events.test.ts b/react/src/events.test.tsindex 89dcf2ce..47a5d8ab 100644--- a/react/src/events.test.ts+++ b/react/src/events.test.ts@@ -8,7 +8,9 @@ import {inputMessageId,isSettledTurn,memorySaveFromEvent,+ turnsOf,type AgentEvent,+ type Turn,} from "./events.js";const turn: AgentEvent[] = [@@ -29,11 +31,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(queued.turns.t1?.status, "queued");+ assert.equal(queued.turns.t1?.input, "hi");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.equal(partial.turns.t1?.status, "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 },@@ -42,7 +45,7 @@ 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(complete.turns.t1?.status, "completed");assert.equal(isSettledTurn(complete, "t1"), true);assert.equal(isSettledTurn(complete, "t2"), false);assert.deepEqual(complete.messages, [@@ -127,3 +130,73 @@ test("only memory.saved events describe a save", () => {bytes: 0,});});++// A recorded log of a coding turn: a clone, a check that failed, and the+// result tool reporting twice, the second call replacing the first.+const activity: AgentEvent[] = [+ { seq: 1, turnId: "t1", type: "message.received", data: { input: "Fix the login page", mode: "queue", payload: { repo: "acme/web" } } },+ { seq: 2, turnId: "t1", type: "turn.started", data: {} },+ { seq: 3, turnId: "t1", type: "tool.started", data: { tool: "shell", callId: "c1", title: "git clone", input: { command: "git clone acme/web" } } },+ { seq: 4, turnId: "t1", type: "tool.completed", data: { tool: "shell", callId: "c1", title: "git clone", output: { exitCode: 0 } } },+ { seq: 5, turnId: "t1", type: "tool.started", data: { tool: "report", callId: "c2", title: "report", input: { baseSha: "abc" } } },+ { seq: 6, turnId: "t1", type: "tool.completed", data: { tool: "report", callId: "c2", title: "report", output: { baseSha: "abc" }, result: true } },+ { seq: 7, turnId: "t1", type: "tool.started", data: { tool: "shell", callId: "c3", title: "npm test" } },+ { seq: 8, turnId: "t1", type: "tool.failed", data: { tool: "shell", callId: "c3", message: "exit 1" } },+ { seq: 9, turnId: "t1", type: "tool.started", data: { tool: "report", callId: "c4", title: "report" } },+ { seq: 10, turnId: "t1", type: "tool.completed", data: { tool: "report", callId: "c4", output: { baseSha: "abc", branch: "task/1" }, result: true } },+ { seq: 11, turnId: "t1", type: "message.delta", data: { text: "Opened a draft PR." } },+ { seq: 12, turnId: "t1", type: "message.completed", data: { text: "Opened a draft PR." } },+ { seq: 13, turnId: "t1", type: "turn.completed", data: {} },+ { seq: 14, turnId: "t2", type: "message.received", data: { input: "Also fix signup" } },+ { seq: 15, turnId: "t2", type: "turn.started", data: {} },+ { seq: 16, turnId: "t2", type: "turn.failed", data: { code: "tool_failed", message: "A tool failed", tool: "shell" } },+];++test("turns are reduced from the log with tool calls keyed on callId, the result from the result tool, and failures", () => {+ const turns = turnsOf(applyEvents(emptyTimeline(), activity));+ assert.equal(turns.length, 2);+ const [first, second] = turns as [Turn, Turn];+ assert.equal(first.id, "t1");+ assert.equal(first.status, "completed");+ assert.equal(first.input, "Fix the login page");+ assert.deepEqual(first.messages.map((message) => [message.role, message.text]), [+ ["user", "Fix the login page"],+ ["assistant", "Opened a draft PR."],+ ]);+ assert.deepEqual(first.toolCalls, [+ { callId: "c1", tool: "shell", title: "git clone", input: { command: "git clone acme/web" }, output: { exitCode: 0 }, status: "completed" },+ { callId: "c2", tool: "report", title: "report", input: { baseSha: "abc" }, output: { baseSha: "abc" }, status: "completed" },+ { callId: "c3", tool: "shell", title: "npm test", status: "failed" },+ { callId: "c4", tool: "report", title: "report", output: { baseSha: "abc", branch: "task/1" }, status: "completed" },+ ]);+ // The later committed call replaces the result.+ assert.deepEqual(first.result, { baseSha: "abc", branch: "task/1" });+ assert.equal(first.failure, undefined);+ assert.equal(second.id, "t2");+ assert.equal(second.status, "failed");+ assert.deepEqual(second.failure, { code: "tool_failed", message: "A tool failed" });+ assert.deepEqual(second.toolCalls, []);+ assert.equal(second.result, undefined);+});++test("replaying the whole log and applying it live in pages produce the same turns", () => {+ const replayed = turnsOf(applyEvents(emptyTimeline(), activity));+ let live = emptyTimeline();+ for (let start = 0; start < activity.length; start += 3) {+ live = applyEvents(live, activity.slice(start, start + 3));+ }+ assert.deepEqual(turnsOf(live), replayed);+ // A page that overlaps changes nothing.+ assert.deepEqual(turnsOf(applyEvents(live, activity.slice(4, 9))), replayed);+});++test("a tool event without a callId still gets a stable id from its position", () => {+ const turns = turnsOf(+ applyEvents(emptyTimeline(), [+ { seq: 1, turnId: "t1", type: "turn.started", data: {} },+ { seq: 2, turnId: "t1", type: "tool.started", data: { tool: "shell" } },+ ]),+ );+ assert.equal(turns[0]?.input, "");+ assert.deepEqual(turns[0]?.toolCalls, [{ callId: "event:2", tool: "shell", title: "shell", status: "running" }]);+});diff --git a/react/src/events.ts b/react/src/events.tsindex 58815a94..5f3f4792 100644--- a/react/src/events.ts+++ b/react/src/events.ts@@ -1,7 +1,10 @@// The durable session event log as the hook reads it, and the pure reduction-// of that log into what a chat renders. No React and no network here: the-// same function replays history and applies live events, so a reconnect that-// resumes from a cursor produces the same messages as an uninterrupted stream.+// of that log into what a chat renders: messages, and turns with their tool+// activity and result. No React and no network here: the same function+// replays history and applies live events, so a reconnect that resumes from+// a cursor produces the same messages and turns as an uninterrupted stream.+// Every id is derived from the log (turn ids, tool call ids), never minted,+// which is what makes replay and live agree./** One entry of `GET /sessions/<id>/events`. */export interface AgentEvent {@@ -14,6 +17,9 @@ export interface AgentEvent {data: Record<string, unknown>;}+/** A JSON value: what a turn payload, a tool input or output, and a result carry. */+export type DataValue = string | number | boolean | null | DataValue[] | { [key: string]: DataValue };+export interface AgentMessage {id: string;role: "user" | "assistant";@@ -42,13 +48,58 @@ export type TurnStatus =| "failed"| "cancelled";+export type ToolCallStatus = "running" | "completed" | "failed";++/** One tool call of a turn, keyed on the runtime's `callId`. */+export interface ToolCall {+ callId: string;+ tool: string;+ title: string;+ input?: DataValue;+ output?: DataValue;+ status: ToolCallStatus;+}++/** The public failure a `turn.failed` event carries. */+export interface TurnFailure {+ code: string;+ message: string;+}++/** A turn as the log has recorded it so far. */+export interface Turn {+ id: string;+ status: TurnStatus;+ /** The user text the turn was admitted with; `""` until `message.received` is seen. */+ input: string;+ /** The turn's messages, in log order. */+ messages: AgentMessage[];+ /** Tool calls in the order they started. */+ toolCalls: ToolCall[];+ /** The output of the result tool's call, from `tool.completed` with `data.result`. */+ result?: DataValue;+ failure?: TurnFailure;+}++/** What the timeline keeps per turn; `Turn` adds the messages. */+export interface TurnRecord {+ id: string;+ status: TurnStatus;+ input: string;+ toolCalls: ToolCall[];+ result?: DataValue;+ failure?: TurnFailure;+ /** The `seq` of the first event that named the turn; orders the turns. */+ seq: number;+}+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>;+ /** Every turn the log has recorded, by id, as of the cursor. */+ turns: Record<string, TurnRecord>;isRunning: boolean;ended: boolean;}@@ -69,10 +120,20 @@ export function isSettledTurn(timeline: SessionTimeline,turnId: string,): boolean {- const status = timeline.turns[turnId];+ const status = timeline.turns[turnId]?.status;return status === "completed" || status === "failed" || status === "cancelled";}+/** The turns of a timeline in log order, each with its messages. */+export function turnsOf(timeline: SessionTimeline): Turn[] {+ return Object.values(timeline.turns)+ .sort((a, b) => a.seq - b.seq)+ .map(({ seq: _seq, ...record }) => ({+ ...record,+ messages: timeline.messages.filter((message) => message.turnId === record.id),+ }));+}+/** 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`;@@ -86,18 +147,22 @@ function text(value: unknown): string {return typeof value === "string" ? value : "";}+function data(value: unknown): DataValue | undefined {+ return value === undefined ? undefined : (value as DataValue);+}+/** The save a `memory.saved` event reports; undefined for any other event. */export function memorySaveFromEvent(event: AgentEvent): MemorySave | undefined {if (event.type !== "memory.saved") return undefined;- const data = event.data ?? {};+ const fields = event.data ?? {};return {seq: event.seq,...(event.turnId ? { turnId: event.turnId } : {}),...(event.timestamp ? { timestamp: event.timestamp } : {}),- resource: text(data.resource),- documentId: text(data.documentId),- revision: text(data.revision),- bytes: typeof data.bytes === "number" ? data.bytes : 0,+ resource: text(fields.resource),+ documentId: text(fields.documentId),+ revision: text(fields.revision),+ bytes: typeof fields.bytes === "number" ? fields.bytes : 0,};}@@ -112,6 +177,115 @@ function upsert(return next;}+function upsertToolCall(calls: ToolCall[], call: ToolCall): ToolCall[] {+ const index = calls.findIndex((candidate) => candidate.callId === call.callId);+ if (index < 0) return [...calls, call];+ const next = [...calls];+ next[index] = { ...next[index], ...call };+ return next;+}++function toolCallId(event: AgentEvent): string {+ const callId = event.data?.callId;+ return typeof callId === "string" && callId ? callId : `event:${String(event.seq)}`;+}++/**+ * Applies one event to the turn records: the turn it names is created on+ * first sight and moved along its lifecycle; tool events attach to it. Pure,+ * and shared by attach mode (through `applyEvent`) and create mode.+ */+export function applyTurnEvent(+ turns: Record<string, TurnRecord>,+ event: AgentEvent,+): Record<string, TurnRecord> {+ const turnId = event.turnId;+ if (!turnId) return turns;+ const fields = event.data ?? {};+ const current: TurnRecord = turns[turnId] ?? {+ id: turnId,+ status: "queued",+ input: "",+ toolCalls: [],+ seq: event.seq,+ };+ let next: TurnRecord;+ switch (event.type) {+ case "message.received":+ next = { ...current, input: text(fields.input) };+ break;+ case "turn.queued":+ next = { ...current, status: "queued" };+ break;+ case "turn.started":+ next = { ...current, status: "running" };+ break;+ case "turn.completed":+ next = { ...current, status: "completed" };+ break;+ case "turn.failed":+ next = {+ ...current,+ status: "failed",+ failure: { code: text(fields.code) || "agent_failed", message: text(fields.message) },+ };+ break;+ case "turn.cancelled":+ next = { ...current, status: "cancelled" };+ break;+ case "tool.started": {+ const tool = text(fields.tool);+ next = {+ ...current,+ toolCalls: upsertToolCall(current.toolCalls, {+ callId: toolCallId(event),+ tool,+ title: text(fields.title) || tool,+ ...(fields.input !== undefined ? { input: data(fields.input) } : {}),+ status: "running",+ }),+ };+ break;+ }+ case "tool.completed": {+ const tool = text(fields.tool);+ const callId = toolCallId(event);+ const started = current.toolCalls.find((call) => call.callId === callId);+ next = {+ ...current,+ toolCalls: upsertToolCall(current.toolCalls, {+ callId,+ tool: tool || started?.tool || "",+ title: text(fields.title) || started?.title || tool,+ ...(fields.output !== undefined ? { output: data(fields.output) } : {}),+ status: "completed",+ }),+ ...(fields.result === true ? { result: data(fields.output) ?? null } : {}),+ };+ break;+ }+ case "tool.failed": {+ const tool = text(fields.tool);+ const callId = toolCallId(event);+ const started = current.toolCalls.find((call) => call.callId === callId);+ next = {+ ...current,+ toolCalls: upsertToolCall(current.toolCalls, {+ callId,+ tool: tool || started?.tool || "",+ title: text(fields.title) || started?.title || tool,+ status: "failed",+ }),+ };+ break;+ }+ default:+ if (turns[turnId]) return turns;+ next = current;+ }+ return { ...turns, [turnId]: next };+}+/*** Applies one event. Events at or below the cursor are ignored, so a page* that overlaps an earlier one is harmless.@@ -121,26 +295,24 @@ export function applyEvent(event: AgentEvent,): SessionTimeline {if (event.seq <= timeline.cursor) return timeline;- const next: SessionTimeline = { ...timeline, cursor: event.seq };- const data = event.data ?? {};+ const next: SessionTimeline = {+ ...timeline,+ cursor: event.seq,+ turns: applyTurnEvent(timeline.turns, event),+ };+ const fields = event.data ?? {};switch (event.type) {case "message.received": {next.messages = upsert(timeline.messages, {id: event.turnId ? inputMessageId(event.turnId) : `event:${String(event.seq)}`,role: "user",- text: text(data.input),+ text: text(fields.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);@@ -148,7 +320,7 @@ export function applyEvent(next.messages = upsert(timeline.messages, {id,role: "assistant",- text: (existing?.text ?? "") + text(data.text),+ text: (existing?.text ?? "") + text(fields.text),...(event.turnId ? { turnId: event.turnId } : {}),streaming: true,});@@ -158,7 +330,7 @@ export function applyEvent(next.messages = upsert(timeline.messages, {id: replyMessageId(event),role: "assistant",- text: text(data.text),+ text: text(fields.text),...(event.turnId ? { turnId: event.turnId } : {}),streaming: false,});@@ -168,17 +340,6 @@ 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 }@@ -219,7 +380,7 @@ export function failureMessage(event: AgentEvent): string | undefined {) {return undefined;}- const data = event.data ?? {};- const message = text(data.message) || text(data.reason);+ const fields = event.data ?? {};+ const message = text(fields.message) || text(fields.reason);return message || `${event.type.replace(".", " ")}`;}diff --git a/react/src/index.ts b/react/src/index.tsindex 32d2026a..de9bdcac 100644--- a/react/src/index.ts+++ b/react/src/index.ts@@ -1,26 +1,38 @@-import { useCallback, useEffect, useRef, useState } from "react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";import {applyEvents,+ applyTurnEvent,emptyTimeline,failureMessage,inputMessageId,isSettledTurn,memorySaveFromEvent,+ turnsOf,type AgentEvent,type AgentMessage,+ type DataValue,type MemorySave,type SessionTimeline,+ type Turn,} from "./events.js";export {applyEvent,applyEvents,+ applyTurnEvent,emptyTimeline,isSettledTurn,+ turnsOf,type AgentEvent,type AgentMessage,+ type DataValue,type MemorySave,type SessionTimeline,+ type ToolCall,+ type ToolCallStatus,+ type Turn,+ type TurnFailure,+ type TurnRecord,type TurnStatus,} from "./events.js";@@ -70,6 +82,19 @@ export interface SendReceipt {status: "queued" | "running";}+/** The options of one `send`. */+export interface SendOptions {+ /**+ * The turn's idempotency key. Generate one per submission and keep it for+ * that submission's retries: the same key returns the same turn, so a+ * retried send after a lost reply admits nothing twice. Without one the+ * hook generates a key for the request, and a retry is a new turn.+ */+ idempotencyKey?: string;+ /** Structured input the agent reads as `useInput().payload`, beside the text. */+ payload?: DataValue;+}+/*** What `send` rejects with. `code` is the platform's error code when the* request was answered (`session_ended`, `memory_admission_unconfirmed`,@@ -91,13 +116,18 @@ export class SendError extends Error {export interface UseAgentResult {messages: AgentMessage[];+ /**+ * The session's turns in log order, each with its status, input, messages,+ * tool calls, result and failure, reduced from the same log as `messages`.+ */+ turns: Turn[];/*** 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>;+ send: (value: string, options?: SendOptions) => Promise<SendReceipt>;/** Interrupts the running turn. */stop: () => Promise<void>;sessionId: string | undefined;@@ -302,14 +332,21 @@ export function useAgent(}, [attachedSessionId, after, basePath, commit, ingest, request]);const admitTurn = useCallback(- async (activeSession: string, prompt: string): Promise<SendReceipt> => {+ async (+ activeSession: string,+ prompt: string,+ sendOptions: SendOptions,+ ): Promise<SendReceipt> => {const admission = await request<TurnAdmission>(`/sessions/${encodeURIComponent(activeSession)}/turns`,{method: "POST",body: JSON.stringify({input: prompt,- idempotencyKey: crypto.randomUUID(),+ idempotencyKey: sendOptions.idempotencyKey ?? crypto.randomUUID(),+ ...(sendOptions.payload !== undefined+ ? { payload: sendOptions.payload }+ : {}),}),},);@@ -323,7 +360,11 @@ export function useAgent();const sendAttached = useCallback(- async (activeSession: string, prompt: string): Promise<SendReceipt> => {+ async (+ activeSession: string,+ prompt: string,+ sendOptions: SendOptions,+ ): 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@@ -334,7 +375,7 @@ export function useAgent(attachmentRef.current === attachment;setError(undefined);try {- const receipt = await admitTurn(activeSession, prompt);+ const receipt = await admitTurn(activeSession, prompt, sendOptions);if (current()) {// The log's message.received for this turn carries the same id,// so it confirms this message instead of duplicating it. Whether@@ -368,7 +409,7 @@ export function useAgent();const sendCreated = useCallback(- async (prompt: string): Promise<SendReceipt> => {+ async (prompt: string, sendOptions: SendOptions): Promise<SendReceipt> => {if (timelineRef.current.isRunning) {throw new SendError("A turn is already running.", "busy");}@@ -429,10 +470,14 @@ export function useAgent(for (const event of result.events) {cursorRef.current = Math.max(cursorRef.current, event.seq);optionsRef.current.onEvent?.(event);+ // Turn activity is reduced from the log here as in attach mode;+ // the messages are streamed into the two local placeholders.+ const current = timelineRef.current;+ commit({ ...current, turns: applyTurnEvent(current.turns, event) });if (event.type === "message.delta") {streamed += String(event.data.text ?? "");- updateMessages((current) =>- current.map((message) =>+ updateMessages((messages) =>+ messages.map((message) =>message.id === assistantId? { ...message, text: streamed }: message,@@ -440,18 +485,18 @@ export function useAgent();} else if (event.type === "message.completed" && !streamed) {const text = String(event.data.text ?? "");- updateMessages((current) =>- current.map((message) =>+ updateMessages((messages) =>+ messages.map((message) =>message.id === assistantId ? { ...message, text } : message,),);} else {const save = memorySaveFromEvent(event);if (save) {- const current = timelineRef.current;+ const latest = timelineRef.current;commit({- ...current,- memorySaves: [...current.memorySaves, save],+ ...latest,+ memorySaves: [...latest.memorySaves, save],});optionsRef.current.onMemorySaved?.(save);}@@ -465,7 +510,17 @@ export function useAgent(}};await waitFor((event) => event.type === "runtime.connected");- receipt = await admitTurn(activeSession, prompt);+ receipt = await admitTurn(activeSession, prompt, sendOptions);+ // The placeholders belong to the admitted turn from here on, so the+ // turn's messages are its own.+ const { turnId } = receipt;+ updateMessages((messages) =>+ messages.map((message) =>+ message.id === userMessage.id || message.id === assistantId+ ? { ...message, turnId }+ : message,+ ),+ );const completed = await waitFor((event) =>event.type === "turn.completed" ||@@ -517,12 +572,12 @@ export function useAgent();const send = useCallback(- async (value: string): Promise<SendReceipt> => {+ async (value: string, sendOptions: SendOptions = {}): Promise<SendReceipt> => {const prompt = value.trim();if (!prompt) throw new SendError("Nothing to send.", "empty_input");return attachedSessionId- ? sendAttached(attachedSessionId, prompt)- : sendCreated(prompt);+ ? sendAttached(attachedSessionId, prompt, sendOptions)+ : sendCreated(prompt, sendOptions);},[attachedSessionId, sendAttached, sendCreated],);@@ -540,8 +595,11 @@ export function useAgent(}}, [request]);+ const turns = useMemo(() => turnsOf(timeline), [timeline]);+return {messages: timeline.messages,+ turns,send,stop,sessionId,diff --git a/react/src/use-agent.test.ts b/react/src/use-agent.test.tsindex 047bb422..59ff431f 100644--- a/react/src/use-agent.test.ts+++ b/react/src/use-agent.test.ts@@ -593,3 +593,78 @@ test("create mode still creates the session on the first send and streams the reassert.deepEqual(calls[0].body, { agentId: "hello-world@development", source: "local-react" });await view.unmount();});++test("send carries a caller-retained key and a payload, and generates a key when given none", async (t) => {+ const session = fakeSession("ses-keys");+ const view = mount(t, { sessionId: "ses-keys", basePath: "/app/agent", fetch: session.fetch, pollIntervalMs: 5 });+ await view.render();+ await view.until((result) => !result.isReplaying, "empty history");++ await act(async () => {+ await view.result().send("Fix the login page", {+ idempotencyKey: "task_1/1",+ payload: { repo: "acme/web", ref: "main" },+ });+ });+ await act(async () => {+ await view.result().send("Also fix signup");+ });+ const turns = session.calls.filter((call) => call.method === "POST" && call.path.endsWith("/turns"));+ assert.equal(turns.length, 2);+ assert.deepEqual(turns[0]?.body, {+ input: "Fix the login page",+ idempotencyKey: "task_1/1",+ payload: { repo: "acme/web", ref: "main" },+ });+ assert.equal(turns[1]?.body?.input, "Also fix signup");+ assert.equal(typeof turns[1]?.body?.idempotencyKey, "string");+ assert.notEqual(turns[1]?.body?.idempotencyKey, "task_1/1");+ assert.equal("payload" in (turns[1]?.body ?? {}), false);+ await view.unmount();+});++test("attach exposes turns with their tool activity and result, the same after a replay", async (t) => {+ const session = fakeSession("ses-turns");+ session.append({ turnId: "t0", type: "message.received", data: { input: "Clone and report" } });+ session.append({ turnId: "t0", type: "turn.started", data: {} });+ session.append({ turnId: "t0", type: "tool.started", data: { tool: "shell", callId: "c1", title: "git clone" } });+ session.append({ turnId: "t0", type: "tool.completed", data: { tool: "shell", callId: "c1", title: "git clone", output: { exitCode: 0 } } });+ session.append({ turnId: "t0", type: "tool.started", data: { tool: "report", callId: "c2", title: "report" } });+ session.append({ turnId: "t0", type: "tool.completed", data: { tool: "report", callId: "c2", title: "report", output: { baseSha: "abc" }, result: true } });+ session.append({ turnId: "t0", type: "message.completed", data: { text: "Done." } });+ session.append({ turnId: "t0", type: "turn.completed", data: {} });++ const view = mount(t, { sessionId: "ses-turns", basePath: "/app/agent", fetch: session.fetch, pollIntervalMs: 5 });+ await view.render();+ const replayed = await view.until((result) => !result.isReplaying, "history replay");+ assert.equal(replayed.turns.length, 1);+ const [turn] = replayed.turns;+ assert.equal(turn?.id, "t0");+ assert.equal(turn?.status, "completed");+ assert.equal(turn?.input, "Clone and report");+ assert.deepEqual(turn?.toolCalls.map((call) => [call.callId, call.title, call.status]), [+ ["c1", "git clone", "completed"],+ ["c2", "report", "completed"],+ ]);+ assert.deepEqual(turn?.result, { baseSha: "abc" });+ assert.deepEqual(turn?.messages.map((message) => message.text), ["Clone and report", "Done."]);++ // A live turn appears with its activity as the log grows.+ await act(async () => {+ await view.result().send("Run the checks");+ });+ session.append({ turnId: "turn-1", type: "tool.started", data: { tool: "shell", callId: "c3", title: "npm test" } });+ const live = await view.until((result) => result.turns[1]?.toolCalls.length === 1, "live tool call");+ assert.equal(live.turns[1]?.id, "turn-1");+ assert.equal(live.turns[1]?.status, "running");+ assert.equal(live.turns[1]?.input, "Run the checks");+ assert.deepEqual(live.turns[1]?.toolCalls, [{ callId: "c3", tool: "shell", title: "npm test", status: "running" }]);++ // A second hook reading the same log from the start agrees with what the first saw live.+ const again = mount(t, { sessionId: "ses-turns", basePath: "/app/agent", fetch: session.fetch, pollIntervalMs: 5 });+ await again.render();+ const fresh = await again.until((result) => !result.isReplaying && result.turns.length === 2, "second replay");+ assert.deepEqual(fresh.turns, live.turns);+ await again.unmount();+ await view.unmount();+});