Multiplayer agent harness for work.
fix: recover saved responses after polling timeouts (#1640)
Joshua France4ac5b6c97a2d
diff --git a/plugins/web-ui/src/chat.ts b/plugins/web-ui/src/chat.tsindex 277021de8..ad1e2f347 100644--- a/plugins/web-ui/src/chat.ts+++ b/plugins/web-ui/src/chat.ts@@ -65,6 +65,7 @@ import {} from "lucide";import {continuableMessages,+ hasRecordedRunReply,messagesWithStreaming,userEntryMessage,appendConsumedSteers,@@ -824,19 +825,35 @@ export function createChatSurface(const sessionId = chatState.sessionId;if (!sessionId || agent !== chatState.agent || agent.state.isStreaming) return drawActiveChat(agent);const generation = ++transcriptRefreshGeneration;- const last = agent.state.messages[agent.state.messages.length - 1] as { stopReason?: string } | undefined;- if (last?.stopReason === "error") return drawActiveChat(agent);+ const originalMessages = agent.state.messages;+ const last = originalMessages.at(-1) as AssistantWork | undefined;+ const isCurrent = (): boolean =>+ generation === transcriptRefreshGeneration &&+ sessionId === chatState.sessionId &&+ agent === chatState.agent &&+ !agent.state.isStreaming &&+ agent.state.messages === originalMessages &&+ agent.state.messages.at(-1) === last;+ if (last?.stopReason === "error" && !last.interruptedRunId) return drawActiveChat(agent);if (last?.stopReason === "aborted") return drawActiveChat(agent);try {+ if (last?.stopReason === "error" && last.interruptedRunId) {+ const run = await api<RunPoll>(`/api/runs/${encodeURIComponent(last.interruptedRunId)}`, {+ signal: AbortSignal.timeout(15_000),+ });+ if (!isCurrent()) return;+ if (+ !runIsTerminal(run) ||+ run.status === "failed" ||+ !["ok", "silent", "react"].includes(run.result?.status ?? "")+ )+ return drawActiveChat(agent);+ }const anchor = chatState.transcriptAnchorSeq;const page = await transcriptFetcher(sessionId, anchor !== null ? { sinceSeq: anchor } : undefined);- if (- generation !== transcriptRefreshGeneration ||- sessionId !== chatState.sessionId ||- agent !== chatState.agent ||- agent.state.isStreaming- )- return;+ if (!isCurrent()) return;+ if (last?.stopReason === "error" && !hasRecordedRunReply(page.entries ?? [], last.interruptedRunId!))+ return drawActiveChat(agent);chatState.pins = page.pins ?? [];const split = inheritedTranscript(chatState.forkSession ?? {}, page.entries ?? []);const messages = entriesToMessages(split.current, transcriptModel());@@ -846,13 +863,7 @@ export function createChatSurface(chatState.inheritedLoaded,);await syncPendingApprovals(agent, messages);- if (- generation !== transcriptRefreshGeneration ||- sessionId !== chatState.sessionId ||- agent !== chatState.agent ||- agent.state.isStreaming- )- return;+ if (!isCurrent()) return;if (refreshedInherited) chatState.inheritedMessages = entriesToMessages(refreshedInherited, transcriptModel());agent.state.messages = messages;const rawEarlier = page.earlierEntries ?? 0;diff --git a/plugins/web-ui/src/core-bridge.ts b/plugins/web-ui/src/core-bridge.tsindex cb4c27c07..139fff672 100644--- a/plugins/web-ui/src/core-bridge.ts+++ b/plugins/web-ui/src/core-bridge.ts@@ -454,6 +454,7 @@ export type AssistantWork = AssistantMessage & {work?: WorkBlock;deliveredFiles?: DeliveredFile[];retryableSend?: boolean;+ interruptedRunId?: string;sendBlocked?: "pending_approval";sendFailed?: "attachments";droppedAttachmentIds?: string[];@@ -508,6 +509,19 @@ export function runIsTerminal(run: Pick<RunPoll, "status" | "result" | "replyComreturn run.status === "done" || run.status === "failed" || run.result != null || run.replyComplete === true;}+export function hasRecordedRunReply(entries: SessionEntry[], runId: string): boolean {+ let matchesRun = false;+ for (const entry of entries) {+ const payload = entry.payload as { runId?: string; steered?: boolean } | null;+ if (entry.type === "user") {+ if (!payload?.steered || payload.runId !== undefined) matchesRun = payload?.runId === runId;+ } else if (matchesRun && entry.type === "assistant") {+ return true;+ }+ }+ return false;+}+export function resumeAnchor(): AgentMessage {return { role: "user", content: "", resumeAnchor: true } as unknown as AgentMessage;}@@ -1408,6 +1422,10 @@ export async function pollRun(signal?: AbortSignal,notify?: () => void,): Promise<void> {+ const failIdle = (): void => {+ (partial as AssistantWork).interruptedRunId = runId;+ fail(stream, partial, "Timed out waiting for the agent to respond.");+ };let consecutiveFailures = 0;for (;;) {if (signal?.aborted) return abortStream(stream, partial);@@ -1422,8 +1440,7 @@ export async function pollRun(if (signal?.aborted) return abortStream(stream, partial);if (e instanceof ApiError && e.status >= 400 && e.status < 500) return fail(stream, partial, e.message);consecutiveFailures++;- if (now() - st.lastProgressAt > RUN_IDLE_MS)- return fail(stream, partial, "Timed out waiting for the agent to respond.");+ if (now() - st.lastProgressAt > RUN_IDLE_MS) return failIdle();await sleep(Math.min(POLL_MS * 2 ** Math.min(consecutiveFailures, 4), POLL_RETRY_MAX_MS));continue;}@@ -1432,8 +1449,7 @@ export async function pollRun(else st.staleSince = undefined;if (run.alive === true || (st.staleSince !== undefined && now() - st.staleSince < STALE_GRACE_MS))st.lastProgressAt = now();- if (now() - st.lastProgressAt > RUN_IDLE_MS)- return fail(stream, partial, "Timed out waiting for the agent to respond.");+ if (now() - st.lastProgressAt > RUN_IDLE_MS) return failIdle();await sleep(POLL_MS);}}diff --git a/plugins/web-ui/test/attachment-limits.test.ts b/plugins/web-ui/test/attachment-limits.test.tsindex b89c54f20..290948551 100644--- a/plugins/web-ui/test/attachment-limits.test.ts+++ b/plugins/web-ui/test/attachment-limits.test.ts@@ -154,7 +154,10 @@ test("Stop pressed before the run id arrives still stops core's run", () => {});test("confirmed aborted output is preserved during transcript refresh", () => {- assert.match(chat, /if \(last\?\.stopReason === "error"\) return drawActiveChat\(agent\);/);+ assert.match(+ chat,+ /if \(last\?\.stopReason === "error" && !last\.interruptedRunId\) return drawActiveChat\(agent\);/,+ );assert.match(chat, /if \(last\?\.stopReason === "aborted"\) return drawActiveChat\(agent\);/);});diff --git a/plugins/web-ui/test/completed-run-recovery-ui.test.ts b/plugins/web-ui/test/completed-run-recovery-ui.test.tsnew file mode 100644index 000000000..9769d7a47--- /dev/null+++ b/plugins/web-ui/test/completed-run-recovery-ui.test.ts@@ -0,0 +1,251 @@+import assert from "node:assert/strict";+import test from "node:test";+import { createAssistantMessageEventStream } from "@earendil-works/pi-ai";+import type { Conversation } from "../src/conv-types.ts";+import { entriesToMessages, type AssistantWork, type SessionEntry } from "../src/core-bridge.ts";+import { harness, SESSION } from "./deep-link-boot-fixture.ts";++async function settle(): Promise<void> {+ await new Promise((resolve) => setTimeout(resolve, 30));+}++test("the mounted conversation recovers a saved answer after a local polling timeout", async (t) => {+ const user: SessionEntry = {+ type: "user",+ seq: 1,+ createdAt: 100,+ payload: { text: "Compute the result", runId: "run-current" },+ };+ const answer: SessionEntry = {+ type: "assistant",+ seq: 2,+ createdAt: 200,+ payload: { text: "The saved result is 42." },+ };+ const entries = [user];+ const h = await harness({ path: `/s/${SESSION.id}`, entries });+ try {+ await h.boot();+ h.releaseSessions();+ await h.sessionsReady();+ const chat = h.visibleConversation() as Conversation;+ const agent = chat.state.agent!;+ const fixtureFetch = globalThis.fetch;+ let runStatus = "done";+ let runStatusCode = 200;+ let resultStatus: string | null = "ok";+ globalThis.fetch = async (...args) => {+ if (String(args[0]) === "/api/runs/run-current") {+ assert.ok(args[1]?.signal, "recovery status lookup has a request deadline");+ return Response.json(+ { status: runStatus, result: resultStatus ? { status: resultStatus } : null },+ { status: runStatusCode },+ );+ }+ return fixtureFetch(...args);+ };+ const timeout = (): AssistantWork => ({+ ...(entriesToMessages([answer])[0] as AssistantWork),+ content: [{ type: "text", text: "" }],+ stopReason: "error",+ errorMessage: "Timed out waiting for the agent to respond.",+ interruptedRunId: "run-current",+ });+ const reset = (last = timeout()): void => {+ agent.state.messages = [...entriesToMessages([user]), last];+ chat.drawActiveChat();+ };+ const refresh = async (): Promise<void> => {+ chat.onDelivery(SESSION.threadRef);+ await settle();+ };+ reset();+ assert.match(h.mainText(), /Timed out waiting for the agent/);++ await t.test("a transcript without the answer keeps the timeout visible", async () => {+ await refresh();+ assert.equal((agent.state.messages.at(-1) as AssistantWork)?.stopReason, "error");+ assert.match(h.mainText(), /Timed out waiting for the agent/);+ });++ await t.test("a late delivery replaces the timeout with the saved answer", async () => {+ entries.push(answer);+ await refresh();+ assert.equal((agent.state.messages.at(-1) as AssistantWork)?.stopReason, "stop");+ assert.match(h.mainText(), /The saved result is 42/);+ assert.doesNotMatch(h.mainText(), /Timed out waiting for the agent/);+ });++ await t.test("an old saved subturn does not hide an active or retrying run", async () => {+ for (const status of ["running", "pending"]) {+ reset();+ runStatus = status;+ resultStatus = null;+ await refresh();+ assert.equal((agent.state.messages.at(-1) as AssistantWork).stopReason, "error");+ }+ runStatus = "done";+ resultStatus = "ok";+ await refresh();+ assert.equal((agent.state.messages.at(-1) as AssistantWork).stopReason, "stop");+ });++ await t.test("failed or incomplete outcomes cannot be hidden by an earlier saved response", async () => {+ for (const outcome of ["failed", "refused", "pending_approval", null]) {+ reset();+ resultStatus = outcome;+ await refresh();+ assert.equal((agent.state.messages.at(-1) as AssistantWork).stopReason, "error");+ }+ resultStatus = "ok";+ runStatus = "failed";+ await refresh();+ assert.equal((agent.state.messages.at(-1) as AssistantWork).stopReason, "error");+ runStatus = "done";+ });++ await t.test("status lookup failure preserves the timeout until connectivity returns", async () => {+ reset();+ runStatusCode = 503;+ await refresh();+ assert.equal((agent.state.messages.at(-1) as AssistantWork).stopReason, "error");+ runStatusCode = 200;+ await refresh();+ assert.equal((agent.state.messages.at(-1) as AssistantWork).stopReason, "stop");+ });++ await t.test("another run's saved answer does not erase this run's timeout", async () => {+ reset();+ entries.splice(+ 0,+ entries.length,+ { ...user, payload: { text: "Compute the result", runId: "other-run" } },+ answer,+ );+ await refresh();+ assert.equal((agent.state.messages.at(-1) as AssistantWork)?.stopReason, "error");+ entries.splice(0, entries.length, user, answer);+ });++ await t.test("genuine failures and user cancellation remain visible", async () => {+ const backendFailure = timeout();+ delete backendFailure.interruptedRunId;+ backendFailure.errorMessage = "The backend failed.";+ reset(backendFailure);+ await refresh();+ assert.equal(agent.state.messages.at(-1), backendFailure);+ const aborted = { ...timeout(), stopReason: "aborted" as const };+ reset(aborted);+ await refresh();+ assert.equal(agent.state.messages.at(-1), aborted);+ });++ await t.test("a failed history read keeps the error and a later delivery can recover", async () => {+ reset();+ h.setTranscriptStatus(503);+ await refresh();+ assert.equal((agent.state.messages.at(-1) as AssistantWork)?.stopReason, "error");+ h.setTranscriptStatus(200);+ await refresh();+ assert.equal((agent.state.messages.at(-1) as AssistantWork)?.stopReason, "stop");+ });++ const holdRefresh = async (phase = "transcript"): Promise<() => Promise<void>> => {+ reset();+ const originalFetch = globalThis.fetch;+ let release!: () => void;+ const held = new Promise<void>((resolve) => (release = resolve));+ let started = false;+ globalThis.fetch = async (...args) => {+ if (+ phase === "status"+ ? String(args[0]) === "/api/runs/run-current"+ : String(args[0]).startsWith(`/api/sessions/${SESSION.id}`) &&+ String(args[0]).includes("/approvals") === (phase === "approvals")+ ) {+ started = true;+ await held;+ }+ return originalFetch(...args);+ };+ chat.onDelivery(SESSION.threadRef);+ await settle();+ assert.equal(started, true);+ return async () => {+ release();+ await settle();+ globalThis.fetch = originalFetch;+ };+ };++ await t.test("a late history response cannot overwrite a newly streaming turn", async () => {+ const release = await holdRefresh();+ const before = agent.state.messages;+ Object.assign(agent.state, { isStreaming: true });+ await release();+ assert.equal(agent.state.messages, before);+ Object.assign(agent.state, { isStreaming: false });+ });++ for (const phase of ["status", "transcript", "approvals"]) {+ await t.test(`a new prompt that fails during ${phase} fetch is preserved`, async () => {+ const release = await holdRefresh(phase);+ const originalFetch = globalThis.fetch;+ let releaseList!: () => void;+ const listHeld = new Promise<void>((resolve) => (releaseList = resolve));+ globalThis.fetch = async (...args) => {+ if (String(args[0]) === "/api/sessions") await listHeld;+ return originalFetch(...args);+ };+ const originalStream = agent.streamFn;+ const originalConvert = agent.convertToLlm;+ const originalModel = agent.state.model;+ Object.assign(agent.state, {+ model: { id: "synthetic", api: "anthropic-messages", provider: "anthropic" } as NonNullable<+ typeof originalModel+ >,+ });+ agent.convertToLlm = () => [{ role: "user", content: "New request", timestamp: 300 }];+ agent.streamFn = () => {+ const stream = createAssistantMessageEventStream();+ queueMicrotask(() => {+ const error = { ...timeout(), interruptedRunId: undefined, errorMessage: "New send failed" };+ stream.push({ type: "error", reason: "error", error });+ stream.end(error);+ });+ return stream;+ };+ try {+ await agent.prompt("New request");+ const messages = agent.state.messages;+ assert.equal(agent.state.isStreaming, false);+ assert.equal((messages.at(-1) as AssistantWork).errorMessage, "New send failed");+ await release();+ assert.equal(agent.state.messages, messages);+ assert.ok(+ agent.state.messages.some(+ (message) => message.role === "user" && JSON.stringify(message.content).includes("New request"),+ ),+ );+ } finally {+ releaseList();+ await settle();+ agent.streamFn = originalStream;+ agent.convertToLlm = originalConvert;+ Object.assign(agent.state, { model: originalModel });+ }+ });+ }++ await t.test("a late history response cannot overwrite the conversation after navigation", async () => {+ const release = await holdRefresh();+ const before = agent.state.messages;+ chat.resetChatState();+ await release();+ assert.equal(agent.state.messages, before);+ assert.equal(chat.state.agent, null);+ });+ } finally {+ await h.close();+ }+});diff --git a/plugins/web-ui/test/completed-run-recovery.test.ts b/plugins/web-ui/test/completed-run-recovery.test.tsnew file mode 100644index 000000000..82ae0b535--- /dev/null+++ b/plugins/web-ui/test/completed-run-recovery.test.ts@@ -0,0 +1,96 @@+import assert from "node:assert/strict";+import { afterEach, test } from "node:test";+import { createAssistantMessageEventStream } from "@earendil-works/pi-ai";+import {+ entriesToMessages,+ hasRecordedRunReply,+ pollRun,+ RUN_IDLE_MS,+ setClock,+ type AssistantWork,+ type SessionEntry,+} from "../src/core-bridge.ts";++const user = (runId: string): SessionEntry => ({+ type: "user",+ seq: 1,+ createdAt: 100,+ payload: { text: "Compute the result", runId },+});+const answer: SessionEntry = { type: "assistant", seq: 2, createdAt: 200, payload: { text: "The result is 42." } };+const fetch = globalThis.fetch;+afterEach(() => {+ globalThis.fetch = fetch;+ setClock(() => Date.now());+});++test("a poll timeout retains the exact run identity needed to recover its saved answer", async () => {+ setClock(() => RUN_IDLE_MS + 1);+ globalThis.fetch = async () => {+ throw new TypeError("connection interrupted");+ };+ const partial = entriesToMessages([answer])[0] as AssistantWork;+ partial.content = [{ type: "text", text: "" }];+ const stream = createAssistantMessageEventStream();+ await pollRun(stream, partial, "run-current", { acc: "", lastProgressAt: 0 });+ const error = (await stream.result()) as AssistantWork;+ assert.equal(error.stopReason, "error");+ assert.equal(error.interruptedRunId, "run-current");+ assert.equal(hasRecordedRunReply([user("run-current"), answer], error.interruptedRunId!), true);+});++test("an idle running snapshot timeout also retains the run identity", async () => {+ setClock(() => RUN_IDLE_MS + 1);+ globalThis.fetch = async () => new Response(JSON.stringify({ status: "running", result: null }));+ const stream = createAssistantMessageEventStream();+ await pollRun(stream, entriesToMessages([answer])[0] as AssistantWork, "run-idle", { acc: "", lastProgressAt: 0 });+ assert.equal(((await stream.result()) as AssistantWork).interruptedRunId, "run-idle");+});++test("definitive backend failures are not marked as interrupted polling", async () => {+ globalThis.fetch = async () =>+ new Response(JSON.stringify({ status: "failed", result: { status: "failed", reason: "backend error" } }));+ const stream = createAssistantMessageEventStream();+ await pollRun(stream, entriesToMessages([answer])[0] as AssistantWork, "run-failed", { acc: "", lastProgressAt: 0 });+ const error = (await stream.result()) as AssistantWork;+ assert.equal(error.stopReason, "error");+ assert.equal(error.interruptedRunId, undefined);+});++test("history must contain a saved assistant response for the exact interrupted run", () => {+ assert.equal(hasRecordedRunReply([user("other-run"), answer], "run-current"), false);+ assert.equal(hasRecordedRunReply([answer, user("run-current")], "run-current"), false);+ assert.equal(hasRecordedRunReply([user("run-current")], "run-current"), false);+ assert.equal(hasRecordedRunReply([answer], "run-current"), false);+ assert.equal(+ hasRecordedRunReply(+ [user("run-current"), { ...answer, type: "text", payload: { text: "Working…" } }],+ "run-current",+ ),+ false,+ );+ assert.equal(hasRecordedRunReply([user("run-current"), user("later-run"), answer], "run-current"), false);+ assert.equal(+ hasRecordedRunReply(+ [user("run-current"), { ...user("later-run"), payload: { hidden: true } }, answer],+ "run-current",+ ),+ false,+ );+});++test("steering within the same run does not hide its saved answer", () => {+ for (const payload of [{ steered: true }, { steered: true, runId: "run-current" }]) {+ assert.equal(+ hasRecordedRunReply([user("run-current"), { ...user("run-current"), payload }, answer], "run-current"),+ true,+ );+ }+ assert.equal(+ hasRecordedRunReply(+ [user("run-current"), { ...user("later-run"), payload: { steered: true, runId: "later-run" } }, answer],+ "run-current",+ ),+ false,+ );+});