Multiplayer agent harness for work.
$fix: resume approved runs in the visible chat\n\nCo-Authored-By: QM <qm@localhost> (#686)
Joshua Francea1e5ab8469a3
diff --git a/plugins/web-ui/src/chat.ts b/plugins/web-ui/src/chat.tsindex e5dbc950b..20f22d9e4 100644--- a/plugins/web-ui/src/chat.ts+++ b/plugins/web-ui/src/chat.ts@@ -50,7 +50,7 @@ import {makeCoreStreamFn,makeOpenerStreamFn,makeRunResumeStreamFn,- runApprovalTurn,+ queueApprovalTurn,TAIL_TURNS,type ApprovalDecision,type AssistantWork,@@ -519,15 +519,10 @@ export function createChatSurface(ctx.composer.state.error = "";drawActiveChat(agent);try {- await runApprovalTurn(- chatState.threadRef,- agent,- decision,- currentTurnOptions,- chatState.onWork ?? undefined,- undefined,- runSlot,- );+ const threadRef = chatState.threadRef;+ await queueApprovalTurn(threadRef, agent, decision, currentTurnOptions);+ if (chatState.normalStreamFn && chatState.onWork)+ await resumeTrackedRun(agent, threadRef, chatState.normalStreamFn, chatState.onWork);} catch (err) {if (agent === chatState.agent) {ctx.composer.state.error = err instanceof Error ? err.message : "Could not send the approval.";@@ -559,7 +554,7 @@ export function createChatSurface(for (const m of agent.state.messages) {if ((m as { role?: string }).role !== "assistant") continue;for (const approval of (m as AssistantWork).work?.pendingApprovals ?? []) {- byId.set(approval.requestId, approval);+ if (!chatState.resolvingApprovals.has(approval.requestId)) byId.set(approval.requestId, approval);}}return [...byId.values()];diff --git a/plugins/web-ui/src/composer.ts b/plugins/web-ui/src/composer.tsindex 158afe69a..0ad48362a 100644--- a/plugins/web-ui/src/composer.ts+++ b/plugins/web-ui/src/composer.ts@@ -756,9 +756,8 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {}function composerApprovalPanel(approvals: PendingApproval[]): TemplateResult {- const busy = ctx.chat.state.resolvingApprovals.size > 0;const decide = (decision: ApprovalDecision): void => {- if (!busy) ctx.chat.resolveCommandApproval(decision);+ if (!ctx.chat.state.resolvingApprovals.has(decision.requestId)) ctx.chat.resolveCommandApproval(decision);};return html`<div class="composer-approval-panel" role="group" aria-label="Command approval">${approvals.map(@@ -769,7 +768,7 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {<buttonclass="approval-btn deny"type="button"- ?disabled=${busy}+ ?disabled=${ctx.chat.state.resolvingApprovals.has(a.requestId)}@click=${() => decide({ requestId: a.requestId, approved: false })}>Deny@@ -777,7 +776,7 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {<buttonclass="approval-btn"type="button"- ?disabled=${busy}+ ?disabled=${ctx.chat.state.resolvingApprovals.has(a.requestId)}@click=${() => decide({ requestId: a.requestId, approved: true, scope: "once" })}>Allow once@@ -788,7 +787,7 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {: html`<buttonclass="approval-btn primary"type="button"- ?disabled=${busy}+ ?disabled=${ctx.chat.state.resolvingApprovals.has(a.requestId)}@click=${() => decide({ requestId: a.requestId, approved: true, scope: "session" })}>Allow for session@@ -800,7 +799,7 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {: html`<buttonclass="approval-btn"type="button"- ?disabled=${busy}+ ?disabled=${ctx.chat.state.resolvingApprovals.has(a.requestId)}@click=${() => decide({ requestId: a.requestId, approved: true, scope: "always" })}>Allow alwaysdiff --git a/plugins/web-ui/src/core-bridge.ts b/plugins/web-ui/src/core-bridge.tsindex 3b32ed110..d52446ba5 100644--- a/plugins/web-ui/src/core-bridge.ts+++ b/plugins/web-ui/src/core-bridge.ts@@ -646,19 +646,22 @@ export function makeRunResumeStreamFn(return fn as unknown as StreamFn;}-export async function runApprovalTurn(+export async function queueApprovalTurn(threadRef: string,agent: Agent,decision: ApprovalDecision,- getTurnOptions: (() => TurnOptions) | undefined,- onWork: WorkObserver | undefined,- signal?: AbortSignal,- slot?: RunSlot,-): Promise<void> {- const stream = createAssistantMessageEventStream();- await drive(stream, agent.state.model, threadRef, agent, getTurnOptions, signal, onWork, decision, false, slot);- const outcome = await stream.result();- if (outcome.stopReason === "error") throw new Error(outcome.errorMessage || "Could not send the approval.");+ getTurnOptions?: () => TurnOptions,+): Promise<QueuedRun> {+ const { text, attachments } = await latestUserTurn(agent);+ const submit = await api<{ runId?: string }>("/api/turn", {+ method: "POST",+ body: JSON.stringify({+ ...turnRequestBody(threadRef, text, agent.state.model, agent, getTurnOptions, attachments),+ approval: decision,+ }),+ });+ if (!submit.runId) throw new Error("Could not continue after the approval.");+ return { runId: submit.runId, text };}export function makeOpenerStreamFn(diff --git a/plugins/web-ui/test/approval-continuation-source.test.ts b/plugins/web-ui/test/approval-continuation-source.test.tsnew file mode 100644index 000000000..d3f8f706a--- /dev/null+++ b/plugins/web-ui/test/approval-continuation-source.test.ts@@ -0,0 +1,13 @@+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";++const chat = readFileSync(new URL("../src/chat.ts", import.meta.url), "utf8");+const composer = readFileSync(new URL("../src/composer.ts", import.meta.url), "utf8");++test("approval continuations attach to the visible run while sibling cards stay independent", () => {+ assert.match(chat, /await queueApprovalTurn[\s\S]{0,300}await resumeTrackedRun/);+ assert.match(chat, /!chatState\.resolvingApprovals\.has\(approval\.requestId\)/);+ assert.match(composer, /resolvingApprovals\.has\(a\.requestId\)/);+ assert.doesNotMatch(composer, /const busy = ctx\.chat\.state\.resolvingApprovals\.size > 0/);+});diff --git a/plugins/web-ui/test/approval-refusal-feedback.test.ts b/plugins/web-ui/test/approval-refusal-feedback.test.tsindex 8825d3b82..bdb44ab1c 100644--- a/plugins/web-ui/test/approval-refusal-feedback.test.ts+++ b/plugins/web-ui/test/approval-refusal-feedback.test.ts@@ -1,63 +1,26 @@-import { test, afterEach } from "node:test";+import { afterEach, test } from "node:test";import assert from "node:assert/strict";import type { Api, Model } from "@earendil-works/pi-ai";import type { Agent } from "@earendil-works/pi-agent-core";-import { runApprovalTurn } from "../src/core-bridge.ts";+import { queueApprovalTurn } from "../src/core-bridge.ts";const MODEL = { id: "m", api: "anthropic", provider: "anthropic" } as unknown as Model<Api>;--function fakeAgent(): Agent {- return {- state: {- model: MODEL,- messages: [{ role: "user", content: "resolve merge conflicts on this branch" }],- isStreaming: false,- },- } as unknown as Agent;-}--function jsonResponse(body: unknown): Response {- return { ok: true, status: 200, text: async () => JSON.stringify(body) } as unknown as Response;-}--function stubTurn(result: Record<string, unknown>): void {- globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {- const url = String(input);- if (url.endsWith("/api/turn") && init?.method === "POST") {- return jsonResponse({ status: "queued", runId: "r-1" });- }- if (url.includes("/api/runs/r-1")) {- return jsonResponse({ status: "done", result, partial: "" });- }- throw new Error(`unexpected fetch: ${url}`);- }) as typeof fetch;-}-+const agent = {+ state: { model: MODEL, messages: [{ role: "user", content: "resolve conflicts" }], isStreaming: false },+} as unknown as Agent;const realFetch = globalThis.fetch;-afterEach(() => {- globalThis.fetch = realFetch;-});--test("a refused approval resume rejects with the refusal reason", async () => {- stubTurn({ status: "refused", reason: "session busy (another turn is in progress)" });- await assert.rejects(- runApprovalTurn("web:u:t", fakeAgent(), { requestId: "a-1", approved: true, scope: "once" }, undefined, undefined),- /session busy/,- );-});+afterEach(() => (globalThis.fetch = realFetch));-test("a completed approval resume resolves quietly", async () => {- stubTurn({ status: "ok", reply: "done — pushed." });- await runApprovalTurn(- "web:u:t",- fakeAgent(),- { requestId: "a-1", approved: true, scope: "session" },- undefined,- undefined,- );-});+test("an approval returns its continuation run without polling it", async () => {+ let body: { approval?: unknown } = {};+ globalThis.fetch = (async (_input, init) => {+ body = JSON.parse(String(init?.body));+ return { ok: true, status: 200, text: async () => JSON.stringify({ runId: "r-1" }) } as Response;+ }) as typeof fetch;-test("a denied approval's refusal is a clean outcome, not an error", async () => {- stubTurn({ status: "refused", reason: "approval denied for git push --force" });- await runApprovalTurn("web:u:t", fakeAgent(), { requestId: "a-1", approved: false }, undefined, undefined);+ assert.deepEqual(await queueApprovalTurn("web:u:t", agent, { requestId: "a-1", approved: true, scope: "once" }), {+ runId: "r-1",+ text: "resolve conflicts",+ });+ assert.deepEqual(body.approval, { requestId: "a-1", approved: true, scope: "once" });});