Multiplayer agent harness for work.
refactor: keep failed sends on user messages (#696)
Joshua Francea8db2b48769e
diff --git a/plugins/web-ui/src/chat.ts b/plugins/web-ui/src/chat.tsindex 1b1d5efce..0d9089b6d 100644--- a/plugins/web-ui/src/chat.ts+++ b/plugins/web-ui/src/chat.ts@@ -115,6 +115,7 @@ interface SettledRowKey {stopReason: unknown;errorMessage: unknown;approvalDecision: unknown;+ sendFailure: unknown;forkable: boolean;tpl: TemplateResult | typeof nothing;}@@ -1203,8 +1204,11 @@ export function createChatSurface(async function retryFailedSend(message: AgentMessage, index: number): Promise<void> {const agent = chatState.agent;if (!agent || agent.state.isStreaming || agent.state.messages[index] !== message) return;- if (!(message as AssistantWork).retryableSend) return;- agent.state.messages = agent.state.messages.filter((_, current) => current !== index);+ const failed = message as AgentMessage & { sendFailure?: string };+ const error = agent.state.messages[index + 1] as AssistantWork | undefined;+ if (!failed.sendFailure || !error?.retryableSend) return;+ delete failed.sendFailure;+ agent.state.messages = agent.state.messages.filter((_, current) => current !== index + 1);ctx.composer.state.error = "";drawActiveChat(agent);try {@@ -1225,7 +1229,12 @@ export function createChatSurface(index: number,isStreaming: boolean,): TemplateResult | typeof nothing {- const msg = message as AssistantWork & { stopReason?: string; errorMessage?: string; approvalDecision?: string };+ const msg = message as AssistantWork & {+ stopReason?: string;+ errorMessage?: string;+ approvalDecision?: string;+ sendFailure?: string;+ };const work = msg.work;const cacheable =!isStreaming &&@@ -1243,6 +1252,7 @@ export function createChatSurface(hit.stopReason === msg.stopReason &&hit.errorMessage === msg.errorMessage &&hit.approvalDecision === msg.approvalDecision &&+ hit.sendFailure === msg.sendFailure &&hit.forkable === forkable) {return hit.tpl;@@ -1257,6 +1267,7 @@ export function createChatSurface(stopReason: msg.stopReason,errorMessage: msg.errorMessage,approvalDecision: msg.approvalDecision,+ sendFailure: msg.sendFailure,forkable,tpl,});@@ -1269,6 +1280,7 @@ export function createChatSurface(if (role === "user" || role === "user-with-attachments") {const attachments = ((message as UserMessageWithAttachments).attachments ?? []) as UserAttachmentView[];const steered = Boolean((message as { steered?: boolean }).steered);+ const sendFailure = (message as { sendFailure?: string }).sendFailure;return html`<article class="message-row user-row ${steered ? "steered-row" : ""}" data-index=${index}>${steered ? html`<div class="steer-label">↪ steered the running task</div>` : nothing}@@ -1276,12 +1288,23 @@ export function createChatSurface(${markdown(messageText(message))}${attachments.length ? html`<div class="message-files">${attachments.map(userAttachmentBadge)}</div>` : nothing}</div>+ ${+ sendFailure+ ? html`<div class="send-failure">+ <span>${sendFailure}</span>+ <button class="btn compact" type="button" @click=${() => void retryFailedSend(message, index)}>+ ${icon(RefreshCw, 12)} Retry+ </button>+ </div>`+ : nothing+ }${messageMeta(message, index)}</article>`;}if (role === "assistant") {const msg = message as AssistantMessage;+ if ((msg as AssistantWork).retryableSend) return nothing;const work = isStreaming ? null : (msg as AssistantWork).work;const text = messageText(msg).trim();const hasText = Boolean(text);@@ -1293,17 +1316,10 @@ export function createChatSurface(Boolean(deliveredFiles?.length) ||msg.content.some((chunk) => chunk.type === "thinking" && chunk.thinking.trim());if (!hasVisibleContent && msg.stopReason !== "error" && msg.stopReason !== "aborted") return nothing;- let errorTpl: TemplateResult | typeof nothing = nothing;- if (msg.stopReason === "error" && msg.errorMessage) {- errorTpl = (msg as AssistantWork).retryableSend- ? html`<div class="send-failure">- <span>${msg.errorMessage}</span>- <button class="btn compact" type="button" @click=${() => void retryFailedSend(message, index)}>- ${icon(RefreshCw, 12)} Retry- </button>- </div>`- : html`<div class="composer-error inline">${msg.errorMessage}</div>`;- }+ const errorTpl =+ msg.stopReason === "error" && msg.errorMessage+ ? html`<div class="composer-error inline">${msg.errorMessage}</div>`+ : nothing;return html`<article class="message-row assistant-row ${isStreaming ? "streaming" : ""}" data-index=${index}><div class="assistant-body">diff --git a/plugins/web-ui/src/core-bridge.ts b/plugins/web-ui/src/core-bridge.tsindex 68effdcfc..607f5f909 100644--- a/plugins/web-ui/src/core-bridge.ts+++ b/plugins/web-ui/src/core-bridge.ts@@ -37,6 +37,13 @@ interface CoreAttachment {sizeBytes: number;blobId: string;}+type WebUserMessage = AgentMessage & {+ role: "user" | "user-with-attachments";+ content: string | Array<{ type: string; text?: string }>;+ attachments?: PiAttachment[];+ clientTurnId?: string;+ sendFailure?: string;+};export interface DeliveredFile {name: string;@@ -392,28 +399,34 @@ function baseAssistant(model: Model<Api>): AssistantMessage {};}+function latestUserMessage(agent: Agent): WebUserMessage | undefined {+ const messages = agent.state.messages as WebUserMessage[];+ for (let i = messages.length - 1; i >= 0; i--) {+ const message = messages[i];+ if (message?.role === "user" || message?.role === "user-with-attachments") return message as WebUserMessage;+ }+ return undefined;+}+async function latestUserTurn(agent: Agent,): Promise<{ text: string; attachments: CoreAttachment[]; clientTurnId: string }> {- const messages = agent.state.messages as Array<AgentMessage & { attachments?: PiAttachment[] }>;- for (let i = messages.length - 1; i >= 0; i--) {- const m = messages[i];- if (m?.role !== "user" && m?.role !== "user-with-attachments") continue;- const text =- typeof m.content === "string"- ? m.content- : (m.content as Array<{ type: string; text?: string }>)- .filter((c) => c.type === "text")- .map((c) => c.text ?? "")- .join("\n");- const identified = m as AgentMessage & { attachments?: PiAttachment[]; clientTurnId?: string };- identified.clientTurnId ??= crypto.randomUUID();- const attachments = await Promise.all(- (m.attachments ?? []).filter((a) => typeof a.content === "string" && a.content.length > 0).map(toCoreAttachment),- );- return { text, attachments, clientTurnId: identified.clientTurnId };- }- return { text: "", attachments: [], clientTurnId: crypto.randomUUID() };+ const message = latestUserMessage(agent);+ if (!message) return { text: "", attachments: [], clientTurnId: crypto.randomUUID() };+ const text =+ typeof message.content === "string"+ ? message.content+ : (message.content as Array<{ type: string; text?: string }>)+ .filter((c) => c.type === "text")+ .map((c) => c.text ?? "")+ .join("\n");+ message.clientTurnId ??= crypto.randomUUID();+ const attachments = await Promise.all(+ (message.attachments ?? [])+ .filter((attachment) => typeof attachment.content === "string" && attachment.content.length > 0)+ .map(toCoreAttachment),+ );+ return { text, attachments, clientTurnId: message.clientTurnId };}function attachmentBytes(a: PiAttachment): Uint8Array {@@ -759,7 +772,10 @@ async function drive(work.finishedAt = Date.now();notify();if (e instanceof TypeError) {- fail(stream, partial, "Message wasn’t sent. Check your connection and try again.", true);+ const errorMessage = "Message wasn’t sent. Check your connection and try again.";+ const message = latestUserMessage(agent);+ if (message) message.sendFailure = errorMessage;+ fail(stream, partial, errorMessage, true);return;}fail(stream, partial, e instanceof Error ? e.message : String(e));diff --git a/plugins/web-ui/src/shell.css b/plugins/web-ui/src/shell.cssindex 6ecee76c5..3f62bd199 100644--- a/plugins/web-ui/src/shell.css+++ b/plugins/web-ui/src/shell.css@@ -2847,6 +2847,9 @@ a.chat-row-open {.send-failure .btn {color: var(--foreground);}+.user-row .send-failure {+ justify-content: flex-end;+}.stopped-note {display: inline-flex;align-items: center;diff --git a/plugins/web-ui/test/core-bridge-retry.test.ts b/plugins/web-ui/test/core-bridge-retry.test.tsindex 2f51b4f26..5537b0827 100644--- a/plugins/web-ui/test/core-bridge-retry.test.ts+++ b/plugins/web-ui/test/core-bridge-retry.test.ts@@ -184,8 +184,9 @@ test("a failed initial submission is retryable with the same client turn id", asif (submitted.length === 1) throw new TypeError("Failed to fetch");return Response.json({ status: "ok", reply: "delivered" });}) as typeof fetch;+ const userMessage = { role: "user", content: "hello" } as { role: "user"; content: string; sendFailure?: string };const agent = {- state: { model: MODEL, messages: [{ role: "user", content: "hello" }], tools: [] },+ state: { model: MODEL, messages: [userMessage], tools: [] },} as unknown as import("@earendil-works/pi-agent-core").Agent;const streamFn = makeCoreStreamFn("web:alice:one", agent);@@ -194,6 +195,7 @@ test("a failed initial submission is retryable with the same client turn id", asassert.equal(failed.stopReason, "error");assert.equal(failed.errorMessage, "Message wasn’t sent. Check your connection and try again.");assert.equal((failed as { retryableSend?: boolean }).retryableSend, true);+ assert.equal(userMessage.sendFailure, "Message wasn’t sent. Check your connection and try again.");const retriedStream = await streamFn(MODEL, {} as import("@earendil-works/pi-ai").Context);const retried = await retriedStream.result();diff --git a/plugins/web-ui/test/send-retry-source.test.ts b/plugins/web-ui/test/send-retry-source.test.tsindex 3b0192902..8ae69c2f1 100644--- a/plugins/web-ui/test/send-retry-source.test.ts+++ b/plugins/web-ui/test/send-retry-source.test.ts@@ -4,18 +4,29 @@ import { readFileSync } from "node:fs";const source = readFileSync(new URL("../src/chat.ts", import.meta.url), "utf8");-test("retryable send errors render an inline retry action", () => {- assert.match(source, /\(message as AssistantWork\)\.retryableSend/);- assert.match(source, /retryFailedSend\(message, index\)/);- assert.match(source, /Retry\s*<\/button>/);+test("failed sends render Retry on the optimistic user message", () => {+ const userBranch = source.slice(source.indexOf('if (role === "user"'), source.indexOf('if (role === "assistant"'));+ assert.match(userBranch, /sendFailure/);+ assert.match(userBranch, /retryFailedSend\(message, index\)/);+ assert.match(userBranch, /Retry\s*<\/button>/);});-test("retry removes only the failed assistant row and continues the original user turn", () => {+test("the synthetic retryable assistant error stays out of the transcript", () => {+ const assistantBranch = source.slice(+ source.indexOf('if (role === "assistant"'),+ source.indexOf("function messageMeta"),+ );+ assert.match(assistantBranch, /if \(\(msg as AssistantWork\)\.retryableSend\) return nothing/);+ assert.doesNotMatch(assistantBranch, /retryFailedSend/);+});++test("retry clears the user failure and removes only its synthetic assistant error", () => {const retry = source.slice(source.indexOf("async function retryFailedSend"),source.indexOf("function visibleMessages"),);- assert.match(retry, /agent\.state\.messages\.filter/);+ assert.match(retry, /delete .*sendFailure/);+ assert.match(retry, /current !== index \+ 1/);assert.match(retry, /await agent\.continue\(\)/);assert.doesNotMatch(retry, /agent\.prompt/);});