Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

fix: keep restored conversation load failures retryable (#1603)

Joshua France30c5069e3944
diff --git a/plugins/web-ui/src/chat.ts b/plugins/web-ui/src/chat.ts
index 618efe64f..8ec2325f2 100644
--- a/plugins/web-ui/src/chat.ts
+++ b/plugins/web-ui/src/chat.ts
@@ -969,9 +969,11 @@ export function createChatSurface(
}
}
- function mountLoadingPane(): void {
+ function mountLoadingPane(): () => boolean {
+ dropAbandonedNewChat(null);
+ teardownActiveChat();
const container = ctx.container();
- if (!container || !ctx.visible()) return;
+ if (!container || !ctx.visible()) return () => false;
const host = document.createElement("div");
host.className = "custom-chat";
render(
@@ -981,6 +983,20 @@ export function createChatSurface(
host,
);
container.replaceChildren(host);
+ return () => container.contains(host);
+ }
+
+ function mountLoadError(retry: () => void): void {
+ const container = ctx.container();
+ if (!container) return;
+ const host = document.createElement("div");
+ host.className = "empty compact";
+ render(
+ html`<p role="alert">Couldn't load this conversation.</p>
+ <button class="btn" @click=${retry}>Retry</button>`,
+ host,
+ );
+ container.replaceChildren(host);
}
function mountReadOnly(
@@ -3007,6 +3023,7 @@ export function createChatSurface(
mountContinuable,
mountReadOnly,
mountLoadingPane,
+ mountLoadError,
scrollToBottom,
revealEntry: (seq: number) => {
if (chatState.inheritedMessages.some((message) => messageEntrySeqs(message).includes(seq))) {
diff --git a/plugins/web-ui/src/conv-types.ts b/plugins/web-ui/src/conv-types.ts
index 736d3be96..4760e53ef 100644
--- a/plugins/web-ui/src/conv-types.ts
+++ b/plugins/web-ui/src/conv-types.ts
@@ -91,7 +91,8 @@ export interface ChatSurface {
anchorSeq?: number | null,
inheritedMessages?: ReturnType<typeof entriesToMessages>,
): void;
- mountLoadingPane(): void;
+ mountLoadingPane(): () => boolean;
+ mountLoadError(retry: () => void): void;
scrollToBottom(): void;
revealEntry(seq: number): boolean;
drawActiveChat(agent?: Agent | null, opts?: { forceScroll?: boolean }): void;
diff --git a/plugins/web-ui/src/sessions.ts b/plugins/web-ui/src/sessions.ts
index ab147c66c..cc3686d9c 100644
--- a/plugins/web-ui/src/sessions.ts
+++ b/plugins/web-ui/src/sessions.ts
@@ -81,14 +81,7 @@ import {
} from "./contexts";
import { groupDmLabel, groupDmText } from "./group-dm-label";
import { transcriptModel } from "./model-options";
-import {
- appState,
- closeSidebarOnNarrowView,
- renderSidebarTop,
- showMainEmpty,
- syncDocumentTitle,
- syncUrlFromState,
-} from "./shell";
+import { appState, closeSidebarOnNarrowView, renderSidebarTop, syncDocumentTitle, syncUrlFromState } from "./shell";
import { allConversations, isLiveConversation, mainConversation } from "./conversations";
import type { Conversation } from "./conv-types";
import {
@@ -1648,7 +1641,8 @@ export async function openSessionInto(
sessionsState.openingKey = opening;
renderList();
}
- if (isLiveConversation(conv) && (!tracked || sessionsState.openingKey === opening)) conv.mountLoadingPane();
+ if (!isLiveConversation(conv)) return;
+ const isCurrent = conv.mountLoadingPane();
const fetchEntries = (): Promise<TranscriptPage | null> =>
fetchTranscript(s.id, { tailTurns: TAIL_TURNS }).catch(() => null);
@@ -1657,7 +1651,7 @@ export async function openSessionInto(
entriesPrefetch ? entriesPrefetch.then((r) => r ?? fetchEntries()) : fetchEntries(),
continuable ? (approvalsPrefetch ?? fetchSessionApprovals(s.id)) : Promise.resolve(null),
]);
- if (!isLiveConversation(conv)) return;
+ if (!isLiveConversation(conv) || !isCurrent()) return;
if (tracked) {
if (sessionsState.openingKey !== opening) return;
@@ -1669,7 +1663,7 @@ export async function openSessionInto(
}
if (!entriesRes) {
- if (tracked) showMainEmpty("Couldn't load this conversation. Check your connection and click it again.");
+ conv.mountLoadError(() => void openSessionInto(conv, s, undefined, undefined, tracked));
renderList();
return;
}
diff --git a/plugins/web-ui/src/split.ts b/plugins/web-ui/src/split.ts
index 57d09f4bd..d15ab6b0d 100644
--- a/plugins/web-ui/src/split.ts
+++ b/plugins/web-ui/src/split.ts
@@ -1021,27 +1021,27 @@ class PaneContent implements IContentRenderer {
conversation.newChat(context ? { scopeId: context.scopeId, name: context.name ?? null } : undefined);
return;
}
- conversation.mountLoadingPane();
+ const isCurrent = conversation.mountLoadingPane();
let session = sessionsState.list.find((s) => s.id === wanted);
if (!session) {
await sessionsReady();
- if (this.disposed) return;
+ if (this.disposed || !isCurrent()) return;
session = sessionsState.list.find((s) => s.id === wanted);
}
if (!session) {
await refreshSessions({ silent: true });
- if (this.disposed) return;
+ if (this.disposed || !isCurrent()) return;
session = sessionsState.list.find((s) => s.id === wanted);
}
if (!session) {
const page = await fetchTranscript(wanted, { tailTurns: TAIL_TURNS }).catch(() => null);
- if (this.disposed) return;
+ if (this.disposed || !isCurrent()) return;
session = page?.session;
if (!session) {
- conversation.mountReadOnly(
- { id: wanted, threadRef: threadRef ?? "", scopeId: "", title: "" } as CoreSession,
- [],
- );
+ conversation.mountLoadError(() => {
+ this.loaded = false;
+ void this.load();
+ });
return;
}
await openSessionInto(conversation, session, Promise.resolve(page));
diff --git a/plugins/web-ui/test/deep-link-boot-fixture.ts b/plugins/web-ui/test/deep-link-boot-fixture.ts
index 2a860f7d9..6487c56f1 100644
--- a/plugins/web-ui/test/deep-link-boot-fixture.ts
+++ b/plugins/web-ui/test/deep-link-boot-fixture.ts
@@ -1,8 +1,11 @@
import { JSDOM } from "jsdom";
import { createServer } from "vite";
+import type { CoreSession, TranscriptPage } from "../src/core-bridge.ts";
export interface Harness {
requests: string[];
+ setTranscriptStatus: (status: number) => void;
+ openSession: (session: CoreSession, prefetch?: Promise<TranscriptPage | null>) => Promise<void>;
setConnections: (items: unknown[], status?: number) => void;
releaseSessions: () => void;
releaseTranscript: () => void;
@@ -18,6 +21,7 @@ export interface Harness {
interface HarnessOptions {
path: string;
+ session?: CoreSession;
messageLink?: boolean;
transcriptStatus?: number;
transcriptFailures?: number;
@@ -40,6 +44,8 @@ export const SESSION = {
};
export async function harness(opts: HarnessOptions): Promise<Harness> {
+ const session = opts.session ?? SESSION;
+ let transcriptStatus = opts.transcriptStatus;
const dom = new JSDOM('<!doctype html><div id="app"></div>', {
url: `http://localhost${opts.path}`,
pretendToBeVisual: true,
@@ -87,6 +93,7 @@ export async function harness(opts: HarnessOptions): Promise<Harness> {
dom.window.HTMLElement.prototype.scrollIntoView = function () {
this.setAttribute("data-scrolled", "true");
};
+ dom.window.HTMLElement.prototype.getAnimations = () => [];
const timers = new Set<ReturnType<typeof setTimeout>>();
const realSetTimeout = globalThis.setTimeout;
const realSetInterval = globalThis.setInterval;
@@ -133,17 +140,17 @@ export async function harness(opts: HarnessOptions): Promise<Harness> {
if (opts.holdApprovals) await approvalsHeld;
return Response.json({ approvals: [] });
}
- if (path.startsWith(`/api/sessions/${SESSION.id}`)) {
+ if (path.startsWith(`/api/sessions/${session.id}`)) {
if (opts.holdTranscript) await transcriptHeld;
if (failuresLeft > 0) {
failuresLeft--;
- return Response.json({ error: "not_found" }, { status: opts.transcriptStatus ?? 500 });
+ return Response.json({ error: "not_found" }, { status: transcriptStatus ?? 500 });
}
if (opts.messageLink) {
const older = path.includes("beforeSeq=");
const seqs = older ? [10, 11] : [80, 81];
return Response.json({
- session: SESSION,
+ session,
entries: seqs.map((seq) => ({
seq,
type: seq % 2 ? "assistant" : "user",
@@ -153,7 +160,7 @@ export async function harness(opts: HarnessOptions): Promise<Harness> {
earlierEntries: older ? 0 : 80,
});
}
- return Response.json({ session: SESSION, entries: opts.entries ?? [] });
+ return Response.json({ session, entries: opts.entries ?? [] });
}
if (path === "/api/sessions") {
await sessionsHeld;
@@ -223,6 +230,11 @@ export async function harness(opts: HarnessOptions): Promise<Harness> {
const split = await vite.ssrLoadModule("/src/split.ts");
return {
requests,
+ setTranscriptStatus: (status) => {
+ transcriptStatus = status;
+ failuresLeft = status === 200 ? 0 : Number.POSITIVE_INFINITY;
+ },
+ openSession: sessions.openSession as Harness["openSession"],
setConnections: (items, status = 200) => {
connectedItems = items;
connectedStatus = status;
diff --git a/plugins/web-ui/test/loading-pane-centered.test.ts b/plugins/web-ui/test/loading-pane-centered.test.ts
index c17b869a2..5949af8e3 100644
--- a/plugins/web-ui/test/loading-pane-centered.test.ts
+++ b/plugins/web-ui/test/loading-pane-centered.test.ts
@@ -7,7 +7,7 @@ const chat = readFileSync(new URL("../src/chat.ts", import.meta.url), "utf8");
const sessions = readFileSync(new URL("../src/sessions.ts", import.meta.url), "utf8");
test("the loading pane renders chat-loading as the shell's only child", () => {
- const fn = chat.match(/function mountLoadingPane\(\): void \{[\s\S]*?\n {2}\}/)?.[0] ?? "";
+ const fn = chat.match(/function mountLoadingPane\(\): \(\) => boolean \{[\s\S]*?\n {2}\}/)?.[0] ?? "";
assert.match(fn, /custom-chat-shell/);
assert.match(fn, /chat-loading/);
});
diff --git a/plugins/web-ui/test/restored-pane-load.test.ts b/plugins/web-ui/test/restored-pane-load.test.ts
new file mode 100644
index 000000000..639da8d5c
--- /dev/null
+++ b/plugins/web-ui/test/restored-pane-load.test.ts
@@ -0,0 +1,66 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { harness, SESSION } from "./deep-link-boot-fixture.ts";
+import type { CoreSession, TranscriptPage } from "../src/core-bridge.ts";
+
+const session: CoreSession = { ...SESSION, threadRef: "dm:sample", type: "dm", createdAt: 1 };
+const entries = [{ seq: 1, type: "assistant", createdAt: 1, payload: { text: "Stored response" } }];
+async function waitFor(predicate: () => boolean): Promise<void> {
+ for (let i = 0; i < 200 && !predicate(); i++) await new Promise((resolve) => setTimeout(resolve, 10));
+ assert.ok(predicate());
+}
+function restore(): void {
+ localStorage.setItem(
+ "web-ui:split-canvas:v1",
+ JSON.stringify({
+ v: 1,
+ active: true,
+ root: {
+ kind: "split",
+ a: { kind: "leaf", sessionId: session.id, threadRef: session.threadRef },
+ b: { kind: "leaf", threadRef: "web:tester:other" },
+ },
+ }),
+ );
+}
+
+test("restored transcript failure offers retry in the same pane, distinct from empty success", async () => {
+ const h = await harness({ path: "/", session, entries, transcriptStatus: 500 });
+ try {
+ restore();
+ h.releaseSessions();
+ await h.boot();
+ await waitFor(() => h.mainText().includes("Couldn't load this conversation."));
+ assert.doesNotMatch(h.mainText(), /No readable messages/);
+ const failedRequests = h.requests.filter((p) => p.startsWith(`/api/sessions/${session.id}?`)).length;
+ const panes = document.querySelectorAll(".split-pane-content").length;
+ const retry = [...document.querySelectorAll("button")].find((el) => el.textContent?.trim() === "Retry");
+ assert.ok(retry);
+ retry.click();
+ await waitFor(
+ () =>
+ h.requests.filter((p) => p.startsWith(`/api/sessions/${session.id}?`)).length > failedRequests &&
+ h.mainText().includes("Couldn't load this conversation."),
+ );
+ h.setTranscriptStatus(200);
+ const nextRetry = [...document.querySelectorAll("button")].find((el) => el.textContent?.trim() === "Retry");
+ assert.ok(nextRetry);
+ nextRetry.click();
+ await waitFor(() => h.mainText().includes("Stored response"));
+ assert.equal(document.querySelectorAll(".split-pane-content").length, panes);
+ assert.doesNotMatch(h.mainText(), /Couldn't load|No readable messages/);
+ await h.openSession(session, Promise.resolve({ session, entries: [] } as TranscriptPage));
+ assert.match(h.mainText(), /No readable messages/);
+ assert.doesNotMatch(h.mainText(), /Couldn't load/);
+
+ h.sessionsState.list = [session];
+ h.setTranscriptStatus(500);
+ await h.openSession(session, Promise.resolve(null));
+ assert.match(h.mainText(), /Couldn't load this conversation/);
+ h.setTranscriptStatus(200);
+ await h.openSession(session);
+ assert.match(h.mainText(), /Stored response/);
+ } finally {
+ await h.close();
+ }
+});
diff --git a/plugins/web-ui/test/restored-pane-navigation.test.ts b/plugins/web-ui/test/restored-pane-navigation.test.ts
new file mode 100644
index 000000000..c1525c37a
--- /dev/null
+++ b/plugins/web-ui/test/restored-pane-navigation.test.ts
@@ -0,0 +1,41 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { harness, SESSION } from "./deep-link-boot-fixture.ts";
+import type { CoreSession } from "../src/core-bridge.ts";
+
+test("a restored load cannot overwrite a newer open of the same session", async () => {
+ const session: CoreSession = { ...SESSION, type: "dm", createdAt: 1, threadRef: "dm:sample" };
+ const h = await harness({ path: "/", session, holdTranscript: true });
+ try {
+ localStorage.setItem(
+ "web-ui:split-canvas:v1",
+ JSON.stringify({
+ v: 1,
+ active: true,
+ root: {
+ kind: "split",
+ a: { kind: "leaf", sessionId: session.id, threadRef: session.threadRef },
+ b: { kind: "leaf", threadRef: "web:tester:other" },
+ },
+ }),
+ );
+ h.releaseSessions();
+ await h.boot();
+ for (let i = 0; i < 100 && !h.requests.some((p) => p.startsWith(`/api/sessions/${session.id}?`)); i++)
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ assert.ok(h.requests.some((p) => p.startsWith(`/api/sessions/${session.id}?`)));
+ await h.openSession(
+ session,
+ Promise.resolve({
+ session,
+ entries: [{ seq: 2, type: "assistant", createdAt: 2, payload: { text: "Newer response" } }],
+ }),
+ );
+ h.releaseTranscript();
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ assert.match(h.mainText(), /Newer response/);
+ assert.doesNotMatch(h.mainText(), /No readable messages/);
+ } finally {
+ await h.close();
+ }
+});