Multiplayer agent harness for work.
Draw a chat's transcript without waiting for its approvals (#2421)
Regan Bell7417aa2a3f91
diff --git a/plugins/web-ui/src/chat.ts b/plugins/web-ui/src/chat.tsindex ba821948b..b4cd50031 100644--- a/plugins/web-ui/src/chat.ts+++ b/plugins/web-ui/src/chat.ts@@ -389,6 +389,9 @@ export function createChatSurface(</div>`;}let transcriptRefreshGeneration = 0;+ // Bumped whenever approval state is replaced or a decision starts, so a late+ // approvals result can tell it has been superseded.+ let approvalsEpoch = 0;const forkOriginController = createForkOriginController({state: chatState,load: async () => {@@ -808,6 +811,7 @@ export function createChatSurface(if (agent !== chatState.agent || !chatState.threadRef || agent.state.isStreaming) return;if (chatState.resolvingApprovals.size > 0) return;chatState.resolvingApprovals.add(decision.requestId);+ approvalsEpoch++;let resolving = true;const releaseSubmission = (): void => {if (!resolving) return;@@ -872,16 +876,67 @@ export function createChatSurface(return activePendingApprovals().some(approvalBlocksComposer);}- async function syncPendingApprovals(agent: Agent, messages = agent.state.messages): Promise<void> {+ async function syncPendingApprovals(+ agent: Agent,+ messages?: AgentMessage[],+ pending?: Promise<{ approvals: PendingApproval[] } | null>,+ isCurrent: () => boolean = () => true,+ ): Promise<boolean> {const id = chatState.sessionId;- if (!id || agent !== chatState.agent) return;- const r = await fetchSessionApprovals(id);- if (!r || id !== chatState.sessionId || agent !== chatState.agent) return;- for (const message of messages) delete (message as AssistantWork).work?.pendingApprovals;- attachPendingApprovals(messages, r.approvals ?? [], transcriptModel());+ if (!id || agent !== chatState.agent) return false;+ const r = await (pending ?? fetchSessionApprovals(id));+ if (!r || id !== chatState.sessionId || agent !== chatState.agent || !isCurrent()) return false;+ const target = messages ?? agent.state.messages;+ for (const message of target) delete (message as AssistantWork).work?.pendingApprovals;+ attachPendingApprovals(target, r.approvals ?? [], transcriptModel());+ if (target === agent.state.messages) approvalsEpoch++;+ return true;+ }++ // A chat's first draw doesn't wait for its approvals. They attach when the+ // request settles, unless a fresher approvals sync, a decision, a run, or a+ // pending send got there first (each of those re-syncs approvals itself).+ function attachApprovalsWhenLoaded(+ sessionId: string,+ pending: Promise<{ approvals: PendingApproval[] } | null>,+ ): void {+ const agent = chatState.agent;+ if (!agent || chatState.sessionId !== sessionId) return;+ const epoch = approvalsEpoch;+ const isCurrent = (): boolean =>+ epoch === approvalsEpoch &&+ !agent.state.isStreaming &&+ chatState.pendingSend === null &&+ chatState.resolvingApprovals.size === 0;+ // Wait out any refresh in flight: one that succeeds re-syncs approvals itself (and+ // moves the epoch), and attaching mid-refresh would make it discard its transcript.+ const nonEmpty = pending.then(async (r) => {+ await transcriptRefreshesSettled();+ return r?.approvals.length ? r : null;+ });+ void syncPendingApprovals(agent, undefined, nonEmpty, isCurrent).then((attached) => {+ if (attached) drawActiveChat(agent);+ });+ }++ let transcriptRefresh: Promise<void> = Promise.resolve();++ function refreshTranscriptFromEntries(agent: Agent): Promise<void> {+ const refresh = replaceTranscriptFromEntries(agent);+ transcriptRefresh = refresh;+ return refresh;+ }++ // Resolves once no transcript refresh is in flight, including ones that start while waiting.+ async function transcriptRefreshesSettled(): Promise<void> {+ let current: Promise<void>;+ do {+ current = transcriptRefresh;+ await current.catch(() => undefined);+ } while (current !== transcriptRefresh);}- async function refreshTranscriptFromEntries(agent: Agent): Promise<void> {+ async function replaceTranscriptFromEntries(agent: Agent): Promise<void> {const sessionId = chatState.sessionId;if (!sessionId || agent !== chatState.agent || agent.state.isStreaming) return drawActiveChat(agent);const generation = ++transcriptRefreshGeneration;@@ -928,6 +983,7 @@ export function createChatSurface(if (!isCurrent()) return;if (refreshedInherited) chatState.inheritedMessages = entriesToMessages(refreshedInherited, transcriptModel());agent.state.messages = messages;+ approvalsEpoch++;const rawEarlier = page.earlierEntries ?? 0;chatState.earlierCount = currentEarlierCount(chatState.forkSession ?? {}, rawEarlier);chatState.transcriptAnchorSeq = rawEarlier > 0 ? (page.entries?.[0]?.seq ?? null) : null;@@ -3540,6 +3596,7 @@ export function createChatSurface(resetChatState,mountContinuable,mountReadOnly,+ attachApprovalsWhenLoaded,mountLoadingPane,mountLoadError,scrollToBottom,diff --git a/plugins/web-ui/src/conv-types.ts b/plugins/web-ui/src/conv-types.tsindex 99f7c7c39..b707dcc56 100644--- a/plugins/web-ui/src/conv-types.ts+++ b/plugins/web-ui/src/conv-types.ts@@ -95,6 +95,7 @@ export interface ChatSurface {anchorSeq?: number | null,inheritedMessages?: ReturnType<typeof entriesToMessages>,): void;+ attachApprovalsWhenLoaded(sessionId: string, approvals: Promise<{ approvals: PendingApproval[] } | null>): void;mountLoadingPane(): () => boolean;mountLoadError(retry: () => void): void;scrollToBottom(): void;diff --git a/plugins/web-ui/src/sessions.ts b/plugins/web-ui/src/sessions.tsindex f8971ee27..23971c2c0 100644--- a/plugins/web-ui/src/sessions.ts+++ b/plugins/web-ui/src/sessions.ts@@ -35,7 +35,6 @@ import {} from "lucide";import {api,- attachPendingApprovals,fetchSessionApprovals,fetchTranscript,currentEarlierCount,@@ -1824,10 +1823,10 @@ export async function openSessionInto(const fetchEntries = (): Promise<TranscriptPage | null> =>fetchTranscript(s.id, { tailTurns: TAIL_TURNS }).catch(() => null);const continuable = s.canContinue === true;- const [entriesRes, approvalsRes] = await Promise.all([- entriesPrefetch ? entriesPrefetch.then((r) => r ?? fetchEntries()) : fetchEntries(),- continuable ? (approvalsPrefetch ?? fetchSessionApprovals(s.id)) : Promise.resolve(null),- ]);+ // Approvals load alongside the transcript but never hold up the first draw:+ // the chat mounts as soon as entries arrive, and cards attach when this settles.+ const approvals = continuable ? (approvalsPrefetch ?? fetchSessionApprovals(s.id)) : null;+ const entriesRes = await (entriesPrefetch ? entriesPrefetch.then((r) => r ?? fetchEntries()) : fetchEntries());if (!isLiveConversation(conv) || !isCurrent()) return;if (tracked) {@@ -1851,9 +1850,9 @@ export async function openSessionInto(const earlier = currentEarlierCount(s, entriesRes.earlierEntries ?? 0);const anchorSeq = entriesRes.entries?.[0]?.seq ?? null;if (continuable) {- attachPendingApprovals(messages, approvalsRes?.approvals ?? [], transcriptModel());conv.mountContinuable(s.threadRef, s.id, s.scopeId, messages, s.channelName ?? null, s, inheritedMessages);conv.setTranscriptWindow(anchorSeq, earlier, (entriesRes.earlierEntries ?? 0) > 0);+ if (approvals) conv.attachApprovalsWhenLoaded(s.id, approvals);} else {conv.mountReadOnly(s, messages, earlier, anchorSeq, inheritedMessages);}diff --git a/plugins/web-ui/test/deep-link-boot-fixture.ts b/plugins/web-ui/test/deep-link-boot-fixture.tsindex ec17cdb88..a08e60815 100644--- a/plugins/web-ui/test/deep-link-boot-fixture.ts+++ b/plugins/web-ui/test/deep-link-boot-fixture.ts@@ -26,7 +26,7 @@ export interface Harness {}interface HarnessOptions {- api?: (path: string, init?: RequestInit) => Response | undefined;+ api?: (path: string, init?: RequestInit) => Response | Promise<Response> | undefined;path: string;session?: CoreSession;messageLink?: boolean;@@ -34,6 +34,7 @@ interface HarnessOptions {transcriptFailures?: number;holdTranscript?: boolean;holdApprovals?: boolean;+ approvals?: (sessionId: string) => unknown[];holdRuntimeConfig?: boolean;holdRemoteSplit?: boolean;remoteCanvas?: unknown;@@ -167,7 +168,8 @@ export async function harness(opts: HarnessOptions): Promise<Harness> {}if (path.startsWith("/api/sessions/") && path.includes("/approvals")) {if (opts.holdApprovals) await approvalsHeld;- return Response.json({ approvals: [] });+ const sessionId = decodeURIComponent(path.split("/")[3] ?? "");+ return Response.json({ approvals: opts.approvals?.(sessionId) ?? [] });}if (path.startsWith(`/api/sessions/${session.id}`)) {if (opts.holdTranscript) await transcriptHeld;diff --git a/plugins/web-ui/test/deep-link-boot.test.ts b/plugins/web-ui/test/deep-link-boot.test.tsindex a0d96b170..8cffe754f 100644--- a/plugins/web-ui/test/deep-link-boot.test.ts+++ b/plugins/web-ui/test/deep-link-boot.test.ts@@ -1,5 +1,6 @@import assert from "node:assert/strict";import test from "node:test";+import type { CoreSession } from "../src/core-bridge.ts";import { harness, SESSION, type Harness } from "./deep-link-boot-fixture.ts";test("a share link paints its conversation from the transcript, without waiting for the session list", async () => {@@ -138,14 +139,16 @@ test("a list landing mid-open still keeps the row of the conversation being opentitle: "Other",canContinue: true,};- const h = await harness({ path: "/s/sess-deep", holdApprovals: true, listSessions: [other] });+ const h = await harness({ path: "/", holdTranscript: true, listSessions: [other] });try {- const booted = h.boot();+ void h.boot();+ h.sessionsState.list = [SESSION, ...h.sessionsState.list];+ const opened = h.openSession(SESSION as CoreSession);while (!h.sessionsState.openingKey) await new Promise((resolve) => setTimeout(resolve, 0));h.releaseSessions();await h.sessionsReady();- h.releaseApprovals();- await booted;+ h.releaseTranscript();+ await opened;assert.ok(h.sessionsState.list.some((s) => s.id === SESSION.id),"the row must survive a refresh that lands between the open starting and the mount finishing",diff --git a/plugins/web-ui/test/session-open-approvals.test.ts b/plugins/web-ui/test/session-open-approvals.test.tsnew file mode 100644index 000000000..5cfd61130--- /dev/null+++ b/plugins/web-ui/test/session-open-approvals.test.ts@@ -0,0 +1,136 @@+import assert from "node:assert/strict";+import test from "node:test";+import type { CoreSession } from "../src/core-bridge.ts";+import { harness, SESSION } from "./deep-link-boot-fixture.ts";++const entries = [{ seq: 1, type: "user", createdAt: Date.now(), payload: { text: "please run the deploy" } }];+const approval = { requestId: "a1", command: "deploy --prod", reason: "requires approval" };+const OTHER = { ...SESSION, id: "sess-other", threadRef: "web:tester:other", title: "Other chat" } as CoreSession;++const cards = (): number => document.querySelectorAll(".approval-btn").length;+const chatText = (): string => document.querySelector(".main")?.textContent ?? "";++// Opening must not wait on the held approvals request.+function promptly<T>(opening: Promise<T>): Promise<T> {+ const stalled = new Promise<never>((_, reject) =>+ setTimeout(() => reject(new Error("opening the chat waited for its approvals")), 3000),+ );+ return Promise.race([opening, stalled]);+}++async function until(check: () => boolean): Promise<void> {+ for (let i = 0; i < 200 && !check(); i++) await new Promise((resolve) => setTimeout(resolve, 10));+ assert.ok(check(), "condition did not settle");+}++test("a chat draws its transcript before its approvals arrive, then shows the card", async () => {+ const h = await harness({ path: "/s/sess-deep", entries, holdApprovals: true, approvals: () => [approval] });+ try {+ await promptly(h.boot());+ const conv = h.visibleConversation();+ assert.equal(conv.state.sessionId, SESSION.id);+ assert.match(chatText(), /please run the deploy/, "the transcript is drawn while approvals are in flight");+ assert.equal(cards(), 0);+ assert.equal(conv.hasUnresolvedApproval(), false, "nothing blocks the composer until an approval arrives");++ h.releaseApprovals();+ await until(() => cards() > 0);+ assert.match(chatText(), /please run the deploy/);+ assert.deepEqual(+ conv.activePendingApprovals().map((a) => a.requestId),+ ["a1"],+ );+ assert.equal(conv.hasUnresolvedApproval(), true, "a blocking approval locks the composer");+ } finally {+ await h.close();+ }+});++test("a transcript refresh that fails while approvals load doesn't lose the card", async () => {+ const h = await harness({ path: "/s/sess-deep", holdApprovals: true, approvals: () => [approval] });+ try {+ await promptly(h.boot());+ const conv = h.visibleConversation();+ h.setTranscriptStatus(503);+ const refreshes = h.requests.length;+ conv.onDelivery(SESSION.threadRef);+ await until(() => h.requests.slice(refreshes).some((p) => /^\/api\/sessions\/sess-deep($|\?)/.test(p)));+ await new Promise((resolve) => setTimeout(resolve, 20));++ h.releaseApprovals();+ await until(() => cards() > 0);+ assert.deepEqual(+ conv.activePendingApprovals().map((a) => a.requestId),+ ["a1"],+ );+ } finally {+ await h.close();+ }+});++test("approvals arriving mid-refresh wait for it instead of discarding its transcript", async () => {+ let refreshHeld: Promise<void> | null = null;+ let releaseRefresh = (): void => {};+ const reply = { seq: 2, type: "assistant", createdAt: Date.now(), payload: { text: "deployed to prod" } };+ const h = await harness({+ path: "/s/sess-deep",+ holdApprovals: true,+ approvals: () => [approval],+ api: (path) =>+ refreshHeld && path === `/api/sessions/${SESSION.id}`+ ? refreshHeld.then(() => Response.json({ session: SESSION, entries: [reply] }))+ : undefined,+ });+ try {+ await promptly(h.boot());+ const conv = h.visibleConversation();+ refreshHeld = new Promise((resolve) => (releaseRefresh = resolve));+ conv.onDelivery(SESSION.threadRef);+ await until(() => h.requests.includes(`/api/sessions/${SESSION.id}`));+ h.releaseApprovals();+ await new Promise((resolve) => setTimeout(resolve, 20));++ releaseRefresh();+ await until(() => cards() > 0);+ assert.ok(+ JSON.stringify(conv.state.agent?.state.messages).includes("deployed to prod"),+ "the refresh's new reply is kept",+ );+ assert.deepEqual(+ conv.activePendingApprovals().map((a) => a.requestId),+ ["a1"],+ );+ } finally {+ await h.close();+ }+});++test("approvals that land after switching chats stay out of the new chat", async () => {+ const h = await harness({+ path: "/",+ holdApprovals: true,+ listSessions: [SESSION, OTHER],+ approvals: (id) => (id === SESSION.id ? [approval] : []),+ api: (path) =>+ path.startsWith(`/api/sessions/${OTHER.id}?`) ? Response.json({ session: OTHER, entries: [] }) : undefined,+ });+ try {+ const booted = h.boot();+ h.releaseSessions();+ await booted;+ await promptly(h.openSession(SESSION as CoreSession));+ assert.equal(h.visibleConversation().state.sessionId, SESSION.id, "the chat opens without its approvals");+ await promptly(h.openSession(OTHER));+ assert.equal(h.visibleConversation().state.sessionId, OTHER.id);++ h.releaseApprovals();+ await new Promise((resolve) => setTimeout(resolve, 50));+ const conv = h.visibleConversation();+ assert.equal(conv.state.sessionId, OTHER.id);+ assert.equal(cards(), 0);+ assert.deepEqual(conv.activePendingApprovals(), []);+ assert.equal(conv.hasUnresolvedApproval(), false);+ } finally {+ await h.close();+ }+});