An open-source, faster Devin alternative
TypeScript
react: one question lifecycle in both modes; held messages from the log; dismiss
Igor Zalutski626886e67a97
diff --git a/react/src/events.test.ts b/react/src/events.test.tsindex 502a2660..1afb3f0d 100644--- a/react/src/events.test.ts+++ b/react/src/events.test.ts@@ -302,3 +302,64 @@ test("a turn that asks completes with outcome question and opens the question un]);assert.equal(closed.question, null);});++test("held inputs come from the log and follow it to delivered or discarded", () => {+ const asked: AgentEvent[] = [+ { seq: 1, turnId: "t1", type: "question.asked", data: { questionId: "q1", text: "Go?", options: [] } },+ { seq: 2, turnId: "t1", type: "turn.completed", data: { outcome: "question", questionId: "q1" } },+ { seq: 3, type: "message.held", data: { heldId: "h1", questionId: "q1", input: "Keep the old endpoint" } },+ { seq: 4, type: "message.held", data: { heldId: "h2", questionId: "q1", input: "And the tests" } },+ ];+ const held = applyEvents(emptyTimeline(), asked);+ assert.deepEqual(held.messages, [+ { id: "held:h1", role: "user", text: "Keep the old endpoint", held: { questionId: "q1", status: "held" } },+ { id: "held:h2", role: "user", text: "And the tests", held: { questionId: "q1", status: "held" } },+ ]);+ // A replay of the same page changes nothing.+ assert.deepEqual(applyEvents(held, asked), held);++ const answered = applyEvents(held, [+ { seq: 5, turnId: "t2", type: "question.answered", data: { questionId: "q1", answer: { questionId: "q1", text: "go" } } },+ { seq: 6, type: "message.delivered", data: { heldId: "h1", questionId: "q1", answerTurnId: "t2" } },+ { seq: 7, type: "message.delivered", data: { heldId: "h2", questionId: "q1", answerTurnId: "t3" } },+ ]);+ assert.equal(answered.question, null);+ assert.deepEqual(+ answered.messages.map((message) => [message.id, message.held]),+ [+ ["held:h1", { questionId: "q1", status: "delivered", answerTurnId: "t2" }],+ ["held:h2", { questionId: "q1", status: "delivered", answerTurnId: "t3" }],+ ],+ );++ // An event that names no held input settles every one still held under its question.+ const stopped = applyEvents(held, [+ { seq: 5, type: "question.closed", data: { questionId: "q1", reason: "stopped" } },+ { seq: 6, type: "message.discarded", data: { questionId: "q1", reason: "stopped" } },+ ]);+ assert.equal(stopped.question, null);+ assert.deepEqual(+ stopped.messages.map((message) => message.held),+ [+ { questionId: "q1", status: "discarded", reason: "stopped" },+ { questionId: "q1", status: "discarded", reason: "stopped" },+ ],+ );+});++test("a question closes for every documented reason, only for its own id", () => {+ const asked = applyEvents(emptyTimeline(), [+ { seq: 1, turnId: "t1", type: "question.asked", data: { questionId: "q1", text: "Go?", options: [] } },+ ]);+ for (const reason of ["stopped", "dismissed", "ended", "undeliverable"]) {+ assert.equal(+ applyEvents(asked, [{ seq: 2, type: "question.closed", data: { questionId: "q1", reason } }]).question,+ null,+ reason,+ );+ }+ assert.equal(+ applyEvents(asked, [{ seq: 2, type: "question.closed", data: { questionId: "q0", reason: "dismissed" } }]).question?.id,+ "q1",+ );+});diff --git a/react/src/events.ts b/react/src/events.tsindex cf52ec7f..4ff90bf5 100644--- a/react/src/events.ts+++ b/react/src/events.ts@@ -28,6 +28,29 @@ export interface AgentMessage {turnId?: string;/** Set on an assistant message while its turn is still producing text. */streaming?: boolean;+ /**+ * Set on a user message held behind an open question, from `message.held`;+ * its `status` follows the log to `delivered` or `discarded`.+ */+ held?: HeldInput;+}++/**+ * Where a held input stands: `held` while its question is open, `delivered`+ * once it reached the agent (with the answer, or as its own turn after a+ * dismiss), `discarded` when a stop or the session's end dropped it.+ */+export type HeldStatus = "held" | "delivered" | "discarded";++/** A user message sent while a question was open, without answering it. */+export interface HeldInput {+ /** The question the input waited on. */+ questionId: string;+ status: HeldStatus;+ /** The turn that carried the input to the agent, once `delivered`. */+ answerTurnId?: string;+ /** Why it was `discarded`, as the log gives it. */+ reason?: string;}/** A `memory.saved` event: a save the session observed succeeding. */@@ -407,27 +430,13 @@ export function applyEvent(: message,);return next;- case "question.asked": {- const options = Array.isArray(fields.options)- ? fields.options.flatMap((option: unknown) => {- const entry = option as { label?: unknown; value?: unknown } | null;- return entry && typeof entry.label === "string" && typeof entry.value === "string"- ? [{ label: entry.label, value: entry.value }]- : [];- })- : [];- next.question = {- id: text(fields.questionId),- text: text(fields.text),- options,- ...(event.turnId ? { turnId: event.turnId } : {}),- };- return next;- }+ case "question.asked":case "question.answered":case "question.closed":- if (timeline.question?.id === text(fields.questionId)) next.question = null;- return next;+ case "message.held":+ case "message.delivered":+ case "message.discarded":+ return applyQuestionEvent(next, event);case "memory.saved": {const save = memorySaveFromEvent(event);if (save) next.memorySaves = [...timeline.memorySaves, save];@@ -446,6 +455,95 @@ export function applyEvent(}}+function heldMessageId(event: AgentEvent, heldId: string): string {+ if (heldId) return `held:${heldId}`;+ return event.id ? `held:${event.id}` : `event:${String(event.seq)}`;+}++/**+ * The question lifecycle and the inputs held behind it: `question.asked`+ * opens the question, `question.answered` and `question.closed` for the same+ * id clear it; `message.held` adds the held input to the conversation and+ * `message.delivered` / `message.discarded` move it along. The one reduction+ * of these events, applied by `applyEvent` and by the hook in create mode,+ * so both modes agree. Ignores every other event; does not move the cursor.+ */+export function applyQuestionEvent(+ timeline: SessionTimeline,+ event: AgentEvent,+): SessionTimeline {+ const fields = event.data ?? {};+ switch (event.type) {+ case "question.asked": {+ const options = Array.isArray(fields.options)+ ? fields.options.flatMap((option: unknown) => {+ const entry = option as { label?: unknown; value?: unknown } | null;+ return entry && typeof entry.label === "string" && typeof entry.value === "string"+ ? [{ label: entry.label, value: entry.value }]+ : [];+ })+ : [];+ return {+ ...timeline,+ question: {+ id: text(fields.questionId),+ text: text(fields.text),+ options,+ ...(event.turnId ? { turnId: event.turnId } : {}),+ },+ };+ }+ case "question.answered":+ case "question.closed":+ return timeline.question?.id === text(fields.questionId)+ ? { ...timeline, question: null }+ : timeline;+ case "message.held":+ return {+ ...timeline,+ messages: upsert(timeline.messages, {+ id: heldMessageId(event, text(fields.heldId)),+ role: "user",+ text: text(fields.input),+ held: { questionId: text(fields.questionId), status: "held" },+ }),+ };+ case "message.delivered":+ case "message.discarded": {+ const heldId = text(fields.heldId);+ const questionId = text(fields.questionId);+ const delivered = event.type === "message.delivered";+ const answerTurnId = text(fields.answerTurnId) || event.turnId || "";+ const reason = text(fields.reason);+ // The event names its held input; without a name it settles every+ // input still held under its question.+ const matches = (message: AgentMessage) =>+ heldId+ ? message.id === `held:${heldId}`+ : message.held?.status === "held" && (!questionId || message.held.questionId === questionId);+ if (!timeline.messages.some(matches)) return timeline;+ return {+ ...timeline,+ messages: timeline.messages.map((message) =>+ matches(message) && message.held+ ? {+ ...message,+ held: {+ questionId: message.held.questionId,+ status: delivered ? "delivered" : "discarded",+ ...(delivered && answerTurnId ? { answerTurnId } : {}),+ ...(!delivered && reason ? { reason } : {}),+ },+ }+ : message,+ ),+ };+ }+ default:+ return timeline;+ }+}+export function applyEvents(timeline: SessionTimeline,events: readonly AgentEvent[],diff --git a/react/src/index.ts b/react/src/index.tsindex ea044bb8..56670f86 100644--- a/react/src/index.ts+++ b/react/src/index.ts@@ -1,6 +1,7 @@import { useCallback, useEffect, useMemo, useRef, useState } from "react";import {applyEvents,+ applyQuestionEvent,applyTurnEvent,emptyTimeline,failureMessage,@@ -30,6 +31,8 @@ export {type AgentEvent,type AgentMessage,type DataValue,+ type HeldInput,+ type HeldStatus,type MemorySave,type Question,type QuestionOption,@@ -169,6 +172,14 @@ export interface UseAgentResult {question: Question | null;/** Answers the question with that id: `send(text, { answers: questionId })`. */answer: (questionId: string, text: string, options?: Omit<SendOptions, "answers">) => Promise<SendReceipt>;+ /**+ * Closes the question with that id without answering it. Inputs held+ * behind it then run as ordinary turns, in order. Rejects with a+ * `SendError` (`question_stale` when it is no longer the open question)+ * after setting `error`; the question clears when the log's+ * `question.closed` arrives.+ */+ dismiss: (questionId: string) => Promise<void>;sessionId: string | undefined;/** A turn is running in the log, or a locally admitted turn has not settled. Queued replay alone is false. */isRunning: boolean;@@ -436,22 +447,12 @@ export function useAgent(setError(undefined);try {const receipt = await admitTurn(activeSession, prompt, sendOptions);- if (current() && receipt.turnId === undefined) {- // Held behind the open question: no turn will echo it back, so the- // message stays in the conversation as sent. It reaches the agent- // with the answer.- const timeline = timelineRef.current;- commit({- ...timeline,- messages: upsert(timeline.messages, {- id: `held:${receipt.questionId}:${timeline.messages.length}`,- role: "user",- text: prompt,- }),- });+ if (receipt.turnId === undefined) {+ // Held behind the open question: the log's `message.held` puts+ // the message in the conversation, and its later state.return receipt;}- if (current() && receipt.turnId !== undefined) {+ if (current()) {const turnId = receipt.turnId;// The log's message.received for this turn carries the same id,// so it confirms this message instead of duplicating it. Whether@@ -543,18 +544,28 @@ export function useAgent();}let streamed = "";- const waitFor = async (terminal: (event: AgentEvent) => boolean) => {+ // Reads the log from the cursor until `terminal` matches, or, without+ // one, until a page comes back empty.+ const waitFor = async (terminal?: (event: AgentEvent) => boolean) => {for (;;) {const result = await request<{ events: AgentEvent[] }>(`/sessions/${encodeURIComponent(activeSession!)}/events?after=${String(cursorRef.current)}`,);+ if (!terminal && !result.events.length) return undefined;for (const event of result.events) {+ if (event.seq <= cursorRef.current) continue;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.+ // Turn activity and the question lifecycle are reduced from the+ // log here as in attach mode; the turn's messages are streamed+ // into the two local placeholders.const current = timelineRef.current;- commit({ ...current, turns: applyTurnEvent(current.turns, event) });+ commit(+ applyQuestionEvent(+ { ...current, turns: applyTurnEvent(current.turns, event) },+ event,+ ),+ );if (event.type === "message.delta") {streamed += String(event.data.text ?? "");updateMessages((messages) =>@@ -582,38 +593,46 @@ export function useAgent(optionsRef.current.onMemorySaved?.(save);}}- if (terminal(event)) return event;+ if (terminal?.(event)) return event;}if (result.events.length) {commit({ ...timelineRef.current, cursor: cursorRef.current });}- await new Promise((done) => setTimeout(done, 500));+ if (terminal) await new Promise((done) => setTimeout(done, 500));}};await waitFor((event) => event.type === "runtime.connected");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;- if (!turnId) {- // A new session has no question, so nothing can be held.- throw new SendError("The admission reply was not a turn receipt.", "invalid_response");- }- updateMessages((messages) =>- messages.map((message) =>- message.id === userMessage.id || message.id === assistantId- ? { ...message, turnId }- : message,- ),- );- const completed = await waitFor(- (event) =>- event.type === "turn.completed" ||- event.type === "turn.failed" ||- event.type === "turn.cancelled",- );- if (completed.type === "turn.failed") {- throw new Error(String(completed.data.message ?? "Agent failed"));+ if (turnId === undefined) {+ // Held behind the session's open question: no turn runs, so the+ // placeholders go; the log's `message.held` puts the message in+ // the conversation.+ updateMessages((messages) =>+ messages.filter(+ (message) => message.id !== userMessage.id && message.id !== assistantId,+ ),+ );+ await waitFor();+ } else {+ // The placeholders belong to the admitted turn from here on, so the+ // turn's messages are its own.+ updateMessages((messages) =>+ messages.map((message) =>+ message.id === userMessage.id || message.id === assistantId+ ? { ...message, turnId }+ : message,+ ),+ );+ const completed = await waitFor(+ (event) =>+ event.type === "turn.completed" ||+ event.type === "turn.failed" ||+ event.type === "turn.cancelled",+ );+ if (completed?.type === "turn.failed") {+ throw new Error(String(completed.data.message ?? "Agent failed"));+ }}await request(`/sessions/${encodeURIComponent(activeSession)}/suspend`,@@ -688,6 +707,25 @@ export function useAgent([send],);+ const dismiss = useCallback(+ async (questionId: string) => {+ const activeSession = sessionRef.current;+ if (!activeSession) return;+ setError(undefined);+ try {+ await request(+ `/sessions/${encodeURIComponent(activeSession)}/questions/${encodeURIComponent(questionId)}/dismiss`,+ { method: "POST" },+ );+ } catch (cause) {+ const failure = asSendError(cause);+ if (sessionRef.current === activeSession) setError(failure.message);+ throw failure;+ }+ },+ [request],+ );+const turns = useMemo(() => turnsOf(timeline), [timeline]);return {@@ -697,6 +735,7 @@ export function useAgent(stop,question: timeline.question,answer,+ dismiss,sessionId,isRunning: timeline.isRunning || admitted.length > 0,isReplaying,diff --git a/react/src/use-agent.test.ts b/react/src/use-agent.test.tsindex a30e6d37..ece8fb3b 100644--- a/react/src/use-agent.test.ts+++ b/react/src/use-agent.test.ts@@ -759,28 +759,191 @@ test("attach exposes turns with their tool activity and result, the same after aawait view.unmount();});-test("attach keeps a message held behind an open question in the conversation", async (t) => {+// A session with an open question: the turns route holds input sent+// without `answers` and records it in the log; dismiss closes the question+// and runs what was held.+function questionSession(prefix: string) {+ const log: AgentEvent[] = [];+ const calls: Call[] = [];+ const append = (event: Omit<AgentEvent, "seq">) => {+ log.push({ ...event, seq: log.length + 1 });+ };+ let held = 0;+ let turns = 0;+ let dismissFails = false;const fetch: typeof globalThis.fetch = async (input, init) => {const url = new URL(String(input), "http://app.test");- if ((init?.method ?? "GET") === "GET" && url.pathname.endsWith("/events")) {- return Response.json({ events: [] });+ const call: Call = {+ method: init?.method ?? "GET",+ path: `${url.pathname}${url.search}`,+ headers: Object.fromEntries(new Headers(init?.headers).entries()),+ ...(typeof init?.body === "string" ? { body: JSON.parse(init.body) as Record<string, unknown> } : {}),+ };+ calls.push(call);+ const path = url.pathname.slice(prefix.length);+ if (call.method === "POST" && path === "/sessions") {+ append({ type: "runtime.connected", data: {} });+ return Response.json({ session: { id: "ses-q" } }, { status: 201 });}- if (init?.method === "POST" && url.pathname.endsWith("/turns")) {- return Response.json({ status: "held", questionId: "q-1", duplicate: false }, { status: 202 });+ if (call.method === "GET" && path === "/sessions/ses-q/events") {+ const after = Number(url.searchParams.get("after") ?? "0");+ return Response.json({ events: log.filter((event) => event.seq > after).slice(0, 3) });}- return Response.json({}, { status: 404 });+ if (call.method === "POST" && path === "/sessions/ses-q/resume") {+ append({ type: "runtime.connected", data: {} });+ return Response.json({ id: "ses-q", status: "idle" });+ }+ if (call.method === "POST" && path === "/sessions/ses-q/suspend") {+ return Response.json({ id: "ses-q", status: "suspended" });+ }+ if (call.method === "POST" && path === "/sessions/ses-q/turns") {+ const open = [...log].reverse().find((event) => event.type.startsWith("question."));+ const questionId = open?.type === "question.asked" ? String(open.data.questionId) : undefined;+ if (questionId && call.body?.answers === undefined) {+ held += 1;+ append({ type: "message.held", data: { heldId: `h${String(held)}`, questionId, input: call.body?.input } });+ return Response.json({ status: "held", questionId, duplicate: false }, { status: 202 });+ }+ turns += 1;+ const turnId = `t${String(turns)}`;+ append({ turnId, type: "message.received", data: { input: call.body?.input, mode: "queue" } });+ append({ turnId, type: "turn.started", data: {} });+ if (questionId) {+ append({ turnId, type: "question.answered", data: { questionId, answer: { questionId, text: call.body?.input } } });+ for (let index = 1; index <= held; index += 1) {+ append({ type: "message.delivered", data: { heldId: `h${String(index)}`, questionId, answerTurnId: turnId } });+ }+ append({ turnId, type: "message.completed", data: { text: "On it." } });+ append({ turnId, type: "turn.completed", data: {} });+ } else {+ append({ turnId, type: "question.asked", data: { questionId: `q${String(turns)}`, text: "Plan first, or go?", options: [] } });+ append({ turnId, type: "turn.completed", data: { outcome: "question", questionId: `q${String(turns)}` } });+ }+ return Response.json({ turnId, status: "running", duplicate: false }, { status: 202 });+ }+ const dismissed = /^\/sessions\/ses-q\/questions\/([^/]+)\/dismiss$/.exec(path);+ if (call.method === "POST" && dismissed) {+ if (dismissFails) {+ return Response.json({ error: { code: "question_stale", message: "That question is no longer open." } }, { status: 409 });+ }+ const questionId = decodeURIComponent(dismissed[1]!);+ append({ type: "question.closed", data: { questionId, reason: "dismissed" } });+ for (let index = 1; index <= held; index += 1) {+ turns += 1;+ append({ type: "message.delivered", data: { heldId: `h${String(index)}`, questionId, answerTurnId: `t${String(turns)}` } });+ }+ return Response.json({ id: "ses-q", status: "idle" });+ }+ return Response.json({ error: { code: "not_found", message: `no route ${call.method} ${path}` } }, { status: 404 });};- const view = mount(t, { sessionId: "ses-held", basePath: "/app/agent", fetch, pollIntervalMs: 5 });+ return {+ log,+ calls,+ fetch,+ append,+ failDismiss: () => {+ dismissFails = true;+ },+ };+}++test("attach shows a held message from the log, then its delivery after a dismiss", async (t) => {+ const session = questionSession("/app/agent");+ session.append({ turnId: "t0", type: "question.asked", data: { questionId: "q0", text: "Go?", options: [] } });+ session.append({ turnId: "t0", type: "turn.completed", data: { outcome: "question", questionId: "q0" } });+ const view = mount(t, { sessionId: "ses-q", basePath: "/app/agent", fetch: session.fetch, pollIntervalMs: 5 });await view.render();- await view.until((result) => !result.isReplaying, "empty history");+ await view.until((result) => !result.isReplaying && result.question?.id === "q0", "open question");let receipt: SendReceipt | undefined;await act(async () => {receipt = await view.result().send("Keep the old endpoint");});- assert.deepEqual(receipt, { sessionId: "ses-held", questionId: "q-1", status: "held", duplicate: false });- const held = view.result();+ assert.deepEqual(receipt, { sessionId: "ses-q", questionId: "q0", status: "held", duplicate: false });+ // Nothing is minted locally: the message appears when the log says so.+ assert.equal(view.result().messages.some((message) => message.id.startsWith("held:q0")), false);+ const held = await view.until((result) => result.messages.length === 1, "held message");+ assert.deepEqual(held.messages, [+ { id: "held:h1", role: "user", text: "Keep the old endpoint", held: { questionId: "q0", status: "held" } },+ ]);assert.equal(held.isRunning, false);- assert.deepEqual(held.messages, [{ id: "held:q-1:0", role: "user", text: "Keep the old endpoint" }]);++ await act(async () => {+ await view.result().dismiss("q0");+ });+ assert.equal(+ session.calls.some((call) => call.method === "POST" && call.path === "/app/agent/sessions/ses-q/questions/q0/dismiss"),+ true,+ );+ const dismissed = await view.until((result) => result.question === null, "question closed");+ const delivered = await view.until((result) => result.messages[0]?.held?.status === "delivered", "delivered");+ assert.deepEqual(delivered.messages[0]?.held, { questionId: "q0", status: "delivered", answerTurnId: "t1" });+ assert.equal(dismissed.error, undefined);+ await view.unmount();+});++test("dismiss rejects with the platform's code and sets error", async (t) => {+ const session = questionSession("/app/agent");+ session.append({ turnId: "t0", type: "question.asked", data: { questionId: "q0", text: "Go?", options: [] } });+ session.failDismiss();+ const view = mount(t, { sessionId: "ses-q", basePath: "/app/agent", fetch: session.fetch, pollIntervalMs: 5 });+ await view.render();+ await view.until((result) => result.question?.id === "q0", "open question");+ let failure: unknown;+ await act(async () => {+ failure = await view.result().dismiss("q0").catch((cause: unknown) => cause);+ });+ assert.ok(failure instanceof SendError);+ assert.equal(failure.code, "question_stale");+ assert.equal(failure.status, 409);+ assert.equal(view.result().error, "That question is no longer open.");+ assert.equal(view.result().question?.id, "q0");+ await view.unmount();+});++test("create mode follows the question: asked, a held send, then the answer", async (t) => {+ const session = questionSession("/api/opencomputer/managed-agents");+ const view = mount(t, { agent: "planner@development", fetch: session.fetch });+ await view.render();++ await act(async () => {+ await view.result().send("Fix the login page");+ });+ assert.deepEqual(view.result().question, { id: "q1", text: "Plan first, or go?", options: [], turnId: "t1" });+ assert.equal(view.result().turns[0]?.outcome, "question");++ // A held receipt on the existing session is a receipt, not a failure.+ let receipt: SendReceipt | undefined;+ await act(async () => {+ receipt = await view.result().send("Keep the old endpoint");+ });+ assert.deepEqual(receipt, { sessionId: "ses-q", questionId: "q1", status: "held", duplicate: false });+ let result = view.result();+ assert.equal(result.error, undefined);+ assert.equal(result.isRunning, false);+ assert.equal(result.question?.id, "q1");+ assert.deepEqual(+ result.messages.map((message) => [message.role, message.text, message.held?.status]),+ [+ ["user", "Fix the login page", undefined],+ ["assistant", "", undefined],+ ["user", "Keep the old endpoint", "held"],+ ],+ );+ assert.equal(result.messages[2]?.id, "held:h1");++ await act(async () => {+ await view.result().answer("q1", "go");+ });+ result = view.result();+ assert.equal(result.question, null);+ assert.equal(result.error, undefined);+ assert.deepEqual(result.messages[2]?.held, { questionId: "q1", status: "delivered", answerTurnId: "t2" });+ assert.deepEqual(result.messages.slice(3).map((message) => [message.role, message.text]), [+ ["user", "go"],+ ["assistant", "On it."],+ ]);+ const answerTurn = session.calls.find((call) => call.method === "POST" && call.body?.answers === "q1");+ assert.equal(answerTurn?.body?.input, "go");await view.unmount();});