Multiplayer agent harness for work.
Improve web navigation responsiveness (#1646)
Joshua France32831c654d3a
diff --git a/plugins/web-ui/src/sessions.ts b/plugins/web-ui/src/sessions.tsindex cc3686d9c..774760b4d 100644--- a/plugins/web-ui/src/sessions.ts+++ b/plugins/web-ui/src/sessions.ts@@ -164,6 +164,10 @@ const RECENT_CONTEXT_MAX_AGE_MS = 30_000;let renameDraft = "";const refreshingTitleIds = new Set<string>();let showArchived = false;+const SESSION_BATCH_SIZE = 50;+let recentLimit = SESSION_BATCH_SIZE;+let archivedLimit = SESSION_BATCH_SIZE;+let chatsPageLimit = SESSION_BATCH_SIZE;let chatsPageScope: string | null = null;let chatsPageQuery = "";@@ -181,6 +185,9 @@ export function resetSessionsState(): void {sessionsState.list = [];sessionsState.loaded = false;listRequestedAt = 0;+ sessionsRefreshRunning = false;+ queuedSessionsRefresh = null;+ sessionRefreshSeq++;sessionsState.openMenuId = null;sessionsState.renamingId = null;sessionsState.openingKey = null;@@ -188,6 +195,9 @@ export function resetSessionsState(): void {renameDraft = "";refreshingTitleIds.clear();showArchived = false;+ recentLimit = SESSION_BATCH_SIZE;+ archivedLimit = SESSION_BATCH_SIZE;+ chatsPageLimit = SESSION_BATCH_SIZE;chatsPageScope = null;chatsPageQuery = "";chatsPageStatus = "active";@@ -321,6 +331,20 @@ export function renderList(): void {const active = visible.filter((s) => !s.archived);const archived = visible.filter((s) => s.archived);const { pinned, rest } = splitPinned(active);+ const keptIds = new Set([+ ...openConversationIds(),+ ...selection.ids,+ selection.anchor,+ sessionsState.openMenuId,+ sessionsState.renamingId,+ ]);+ const shownThreads = new Set(+ [+ ...rest.slice(0, recentLimit),+ ...archived.slice(0, archivedLimit),+ ...visible.filter((session) => !session.id || keptIds.has(session.id)),+ ].map((session) => session.threadRef),+ );const activeItems = recentItemsFor(rest);const archivedItems: RecentItem[] = archived.map((session) => ({kind: "session",@@ -346,7 +370,21 @@ export function renderList(): void {`: nothing}- ${groupedRows(activeItems)}+ ${groupedRows(activeItems, shownThreads)}+ ${+ rest.some((session) => !shownThreads.has(session.threadRef))+ ? html`<button+ class="archived-toggle"+ type="button"+ @click=${() => {+ recentLimit += SESSION_BATCH_SIZE;+ renderList();+ }}+ >+ Show more conversations+ </button>`+ : nothing+ }${archived.length? html`@@ -355,7 +393,27 @@ export function renderList(): void {<span>Archived</span><span class="archived-count">${archived.length}</span></button>- ${showArchived ? html`<div class="archived-children">${groupedRows(archivedItems)}</div>` : nothing}+ ${+ showArchived+ ? html`<div class="archived-children">+ ${groupedRows(archivedItems, shownThreads)}+ ${+ archived.some((session) => !shownThreads.has(session.threadRef))+ ? html`<button+ class="archived-toggle"+ type="button"+ @click=${() => {+ archivedLimit += SESSION_BATCH_SIZE;+ renderList();+ }}+ >+ Show more archived conversations+ </button>`+ : nothing+ }+ </div>`+ : nothing+ }`: nothing}@@ -388,7 +446,7 @@ function newChatHint(name: string): string {return `Start a new chat in ${name}`;}-function recentItem(item: RecentItem): TemplateResult {+function recentItem(item: RecentItem, shownThreads: ReadonlySet<string>): TemplateResult {if (item.kind === "session") return sessionRow(item.session);const collapsed = sessionsState.collapsedProjectScopes.has(item.scopeId);let glyph: IconNode | null = Folder;@@ -449,11 +507,15 @@ function recentItem(item: RecentItem): TemplateResult {</div>`}<div class="recent-project-children" id=${childrenId} ?hidden=${collapsed}>- ${repeat(- item.sessions,- (session) => session.threadRef,- (session) => sessionRow(session, true),- )}+ ${+ collapsed+ ? nothing+ : repeat(+ item.sessions.filter((session) => shownThreads.has(session.threadRef)),+ (session) => session.threadRef,+ (session) => sessionRow(session, true),+ )+ }</div></section>`;@@ -564,13 +626,28 @@ export function drawChatsPage(): void {appState.mainEl.replaceChildren(chatsPageHost);}const q = chatsPageQuery.trim().toLowerCase();- const rows = sidebarSessions(sessionsState.list)+ const matches = sidebarSessions(sessionsState.list).filter((s) => chatBrowseStatusMatches(s, chatsPageStatus)).filter((s) => chatsPageSurface === "all" || surfaceOf(s) === chatsPageSurface).filter((s) => (chatsPageScope ? s.scopeId === chatsPageScope : true)).filter((s) => !q || chatMatches(s, q))- .sort((a, b) => activityOf(b) - activityOf(a))- .map((s) => chatPageRow(s));+ .sort((a, b) => activityOf(b) - activityOf(a));+ const rows = matches.slice(0, chatsPageLimit).map((s) => chatPageRow(s));+ if (matches.length > chatsPageLimit)+ rows.push(+ html`<div class="list-footer">+ <button+ class="btn"+ type="button"+ @click=${() => {+ chatsPageLimit += SESSION_BATCH_SIZE;+ drawChatsPage();+ }}+ >+ Show more conversations+ </button>+ </div>`,+ );let empty = "No conversations yet. Start a new chat.";if (sessionsLoading && sessionsState.list.length === 0) empty = "Loading conversations…";else if (chatsPageScope || q || chatsPageStatus !== "active" || chatsPageSurface !== "all") {@@ -582,6 +659,7 @@ export function drawChatsPage(): void {scope: chatsPageScope,onScope: (s) => {chatsPageScope = s;+ chatsPageLimit = SESSION_BATCH_SIZE;drawChatsPage();},action: { label: "New chat", onClick: () => startNewChat() },@@ -590,6 +668,7 @@ export function drawChatsPage(): void {placeholder: "Search chats…",onInput: (v) => {chatsPageQuery = v;+ chatsPageLimit = SESSION_BATCH_SIZE;drawChatsPage();},},@@ -610,6 +689,7 @@ export function drawChatsPage(): void {class=${chatsPageStatus === value ? "active" : ""}@click=${() => {chatsPageStatus = value;+ chatsPageLimit = SESSION_BATCH_SIZE;drawChatsPage();}}>@@ -625,6 +705,7 @@ export function drawChatsPage(): void {ariaLabel: "Filter by surface",onSelect: (value) => {chatsPageSurface = (value ?? "all") as typeof chatsPageSurface;+ chatsPageLimit = SESSION_BATCH_SIZE;drawChatsPage();},options: [@@ -806,19 +887,28 @@ export function bumpSessionActivity(threadRef: string): void {renderList();}-function groupedRows(list: RecentItem[]): TemplateResult {+function groupedRows(list: RecentItem[], shownThreads: ReadonlySet<string>): TemplateResult {const now = Date.now();const items: { key: string; tpl: TemplateResult }[] = [];let group: string | null = null;for (const item of list) {+ const key = item.kind === "session" ? item.session.threadRef : projectMenuKey(item.scopeId);+ if (+ item.kind === "session"+ ? !shownThreads.has(item.session.threadRef)+ : item.sessions.length > 0 &&+ sessionsState.openMenuId !== key &&+ sessionsState.renamingId !== key &&+ !item.sessions.some((session) => shownThreads.has(session.threadRef))+ )+ continue;const dateless = item.kind === "project" && item.sessions.length === 0;const g = recencyGroup(recentItemActivity(item), now);if (!dateless && g !== group) {group = g;items.push({ key: `group:${g}`, tpl: html`<div class="recents-group">${g}</div>` });}- const key = item.kind === "session" ? item.session.threadRef : `project:${item.scopeId}`;- items.push({ key, tpl: recentItem(item) });+ items.push({ key, tpl: recentItem(item, shownThreads) });}return html`${repeat(items,@@ -1525,14 +1615,22 @@ function openConversationIds(): string[] {return [...opening, ...allConversations().flatMap((conv) => (conv.state.sessionId ? [conv.state.sessionId] : []))];}+type SessionsRefreshOptions = {+ showLoading?: boolean;+ silent?: boolean;+ refreshContexts?: boolean;+ patchEpoch?: number;+};let latestSessionsRefresh: Promise<boolean> | null = null;+let queuedSessionsRefresh: SessionsRefreshOptions | null = null;+let sessionsRefreshRunning = false;let listRequestedAt = 0;-let listInFlight = 0;let listDiscards = 0;const LIST_STALL_MS = 10_000;export function refreshSessionsOnOpen(): void {- const joinable = listInFlight > 0 && Date.now() - listRequestedAt < LIST_STALL_MS ? latestSessionsRefresh : null;+ const joinable =+ sessionsRefreshRunning && Date.now() - listRequestedAt < LIST_STALL_MS ? latestSessionsRefresh : null;if (!joinable) {void refreshSessions({ silent: true });return;@@ -1547,18 +1645,39 @@ export function refreshSessionsOnOpen(): void {);}-export function refreshSessions(- opts: { showLoading?: boolean; silent?: boolean; refreshContexts?: boolean; patchEpoch?: number } = {},-): Promise<boolean> {- const run: Promise<boolean> = runSessionsRefresh(opts, () =>- latestSessionsRefresh === run ? null : latestSessionsRefresh,- );+export function refreshSessions(opts: SessionsRefreshOptions = {}): Promise<boolean> {+ if (sessionsRefreshRunning && Date.now() - listRequestedAt < LIST_STALL_MS && latestSessionsRefresh) {+ queuedSessionsRefresh = {+ ...opts,+ showLoading: queuedSessionsRefresh?.showLoading || opts.showLoading,+ refreshContexts: queuedSessionsRefresh?.refreshContexts || opts.refreshContexts,+ silent: queuedSessionsRefresh ? queuedSessionsRefresh.silent && opts.silent : opts.silent,+ };+ sessionRefreshSeq++;+ return latestSessionsRefresh;+ }+ sessionsRefreshRunning = true;+ const isLatest = (): boolean => latestSessionsRefresh === run;+ const run: Promise<boolean> = (async () => {+ try {+ let next: SessionsRefreshOptions | null = opts;+ let applied: boolean;+ do {+ queuedSessionsRefresh = null;+ applied = await runSessionsRefresh(next, () => (isLatest() ? null : latestSessionsRefresh));+ next = isLatest() ? queuedSessionsRefresh : null;+ } while (next);+ return applied;+ } finally {+ if (isLatest()) sessionsRefreshRunning = false;+ }+ })();latestSessionsRefresh = run;return run;}async function runSessionsRefresh(- opts: { showLoading?: boolean; silent?: boolean; refreshContexts?: boolean; patchEpoch?: number },+ opts: SessionsRefreshOptions,newerRun: () => Promise<boolean> | null,): Promise<boolean> {loadRecentContexts(opts.refreshContexts === true);@@ -1570,7 +1689,6 @@ async function runSessionsRefresh(renderList();}listRequestedAt = Date.now();- listInFlight++;try {const r = await api<{ sessions: CoreSession[] }>("/api/sessions");if (seq !== sessionRefreshSeq) return sessionsState.loaded || ((await newerRun()) ?? false);@@ -1587,7 +1705,6 @@ async function runSessionsRefresh(if (!opts.silent) sessionsNotice = errMessage(e, "Failed to load conversations.");return false;} finally {- listInFlight--;if (seq === sessionRefreshSeq) {listSettled?.();listSettled = null;diff --git a/plugins/web-ui/src/shell.ts b/plugins/web-ui/src/shell.tsindex e77d78ace..b2bf2ed1a 100644--- a/plugins/web-ui/src/shell.ts+++ b/plugins/web-ui/src/shell.ts@@ -134,6 +134,7 @@ function signOutFromMenu(): void {let authMode: AuthMode = "portal";let shellMounted = false;+let pendingCanvasRestore: Promise<void> | null = null;setSigninRequiredHandler((detail) => {authMode = detail.mode ?? authMode;@@ -699,11 +700,22 @@ export function switchView(v: View): void {syncUrlFromState();resetActiveDetail(v);switch (v) {- case "chats":- if (mountRestoredCanvas()) drawCanvas();- else void renderChatsPage();- renderList();+ case "chats": {+ const seq = appState.viewRenderSeq;+ const showChats = () => {+ if (appState.currentView !== "chats" || appState.viewRenderSeq !== seq) return;+ if (mountRestoredCanvas()) drawCanvas();+ else void renderChatsPage();+ renderList();+ };+ if (pendingCanvasRestore) {+ appState.mainEl?.replaceChildren(+ Object.assign(document.createElement("div"), { className: "empty", textContent: "Loading conversations…" }),+ );+ void pendingCanvasRestore.then(showChats);+ } else showChats();break;+ }case "inbox":void renderInbox();break;@@ -1053,6 +1065,7 @@ export async function boot(): Promise<void> {renderModelConnectGate();return;}+ const sessions = refreshSessions({ showLoading: true });const personalScope = `personal:${appState.me.user}`;const prefetchedConfig = await runtimeConfigFetch;const runtimeConfig =@@ -1062,22 +1075,29 @@ export async function boot(): Promise<void> {}resyncModelSelection();mountShell();+ renderList();shellMounted = true;ensureDeliveryStream();warmDeferredChunks();void refreshInbox({ silent: true });- loadPersistedSplit();- await adoptRemoteSplit(remoteSplitFetch);-const connectedProvider = params.get("status") === "connected" ? params.get("connector") : null;if (connectedProvider) markConnectorConnected(connectedProvider);const viewIntent = isView(wanted) && canView(wanted) && wanted !== "chats";+ loadPersistedSplit();+ if (!wantedSession && wanted !== "app-edit") {+ const restore = adoptRemoteSplit(remoteSplitFetch).then(async () => {+ if (viewIntent && restoredCanvasNeedsSessionList()) await sessions;+ });+ pendingCanvasRestore = restore;+ void restore.then(() => {+ if (pendingCanvasRestore === restore) pendingCanvasRestore = null;+ });+ if (!viewIntent) await restore;+ }const bareEntry = !viewIntent && !wantedSession && wanted !== "app-edit" && !connectedProvider;if (bareEntry && !restoredCanvasNeedsSessionList()) mountRestoredCanvas(true);- const sessions = refreshSessions({ showLoading: true });-if (wantedSession && !viewIntent && wanted !== "app-edit") {const transcript = entriesPrefetch ?? loadLinkedTranscript(wantedSession);const linked = (await transcript)?.session;@@ -1105,24 +1125,12 @@ export async function boot(): Promise<void> {return;}- await sessions;-- if (wanted === "app-edit") {- const slug = (params.get("slug") ?? "").toLowerCase();- if (/^[a-z0-9-]{1,63}$/.test(slug)) {- openAppEditChat(slug);- return;+ if (viewIntent) {+ if (wanted === "keychain") {+ const provider = params.get("connector");+ const status = params.get("status");+ if (provider && status) noteConnectorResult(provider, status);}- showMainEmpty("This edit link is missing a valid app name.");- return;- }-- if (wanted === "keychain") {- const provider = params.get("connector");- const status = params.get("status");- if (provider && status) noteConnectorResult(provider, status);- switchView("keychain");- } else if (viewIntent) {if (wanted === "contexts" || wanted === "files" || wanted === "deploys") {const scope =params.get("scope") ?? (wantedItem ? resolveProjectScope(await ensureContexts(), wantedItem) : null);@@ -1134,7 +1142,22 @@ export async function boot(): Promise<void> {if (wanted === "skills" && wantedItem) openSkillById(wantedItem);switchView(wanted as View);if (wanted === "inbox") routeInboxHistory(wantedItem);- } else if (connectedProvider && sessionsState.list.length) {+ return;+ }++ await sessions;++ if (wanted === "app-edit") {+ const slug = (params.get("slug") ?? "").toLowerCase();+ if (/^[a-z0-9-]{1,63}$/.test(slug)) {+ openAppEditChat(slug);+ return;+ }+ showMainEmpty("This edit link is missing a valid app name.");+ return;+ }++ if (connectedProvider && sessionsState.list.length) {const recent = [...sessionsState.list].sort((a, b) => activityOf(b) - activityOf(a))[0]!;exitSplitIfActive();await openSession(recent);diff --git a/plugins/web-ui/src/stable-markdown.ts b/plugins/web-ui/src/stable-markdown.tsindex ef16f1444..50952024c 100644--- a/plugins/web-ui/src/stable-markdown.ts+++ b/plugins/web-ui/src/stable-markdown.ts@@ -93,11 +93,14 @@ export class StableMarkdown extends ReactiveElement {ranges.push({ start: this.renderedText.length, end: text.length, active: true });} else this.clearFades();offset = 0;+ let rangeIndex = 0;for (const node of nodes) {const end = offset + node.length;const fragments: Node[] = [];let consumed = 0;- for (const range of ranges) {+ while (rangeIndex < ranges.length && ranges[rangeIndex]!.end <= offset) rangeIndex++;+ for (let i = rangeIndex; i < ranges.length && ranges[i]!.start < end; i++) {+ const range = ranges[i]!;const start = Math.max(offset, range.start) - offset;const stop = Math.min(end, range.end) - offset;if (stop <= start) continue;diff --git a/plugins/web-ui/test/deep-link-boot-fixture.ts b/plugins/web-ui/test/deep-link-boot-fixture.tsindex 36ba0a6fe..8a3b03444 100644--- a/plugins/web-ui/test/deep-link-boot-fixture.ts+++ b/plugins/web-ui/test/deep-link-boot-fixture.ts@@ -1,7 +1,7 @@import { JSDOM } from "jsdom";import { createServer } from "vite";import type { Conversation } from "../src/conv-types.ts";-import type { CoreSession, TranscriptPage } from "../src/core-bridge.ts";+import type { CoreContext, CoreSession, TranscriptPage } from "../src/core-bridge.ts";export interface Harness {requests: string[];@@ -11,9 +11,14 @@ export interface Harness {releaseSessions: () => void;releaseTranscript: () => void;releaseApprovals: () => void;+ releaseRuntimeConfig: () => void;+ releaseRemoteSplit: () => void;sessionsReady: () => Promise<void>;refreshSessions: () => Promise<boolean>;boot: () => Promise<void>;+ switchView: (view: "chats" | "settings") => void;+ renderList: () => void;+ drawChatsPage: () => void;appState: { currentView: string };sessionsState: { list: Array<{ id: string }>; loaded: boolean; openingKey: string | null };visibleConversation: () => Conversation;@@ -29,7 +34,11 @@ interface HarnessOptions {transcriptFailures?: number;holdTranscript?: boolean;holdApprovals?: boolean;+ holdRuntimeConfig?: boolean;+ holdRemoteSplit?: boolean;+ remoteCanvas?: unknown;listSessions?: unknown[];+ contexts?: CoreContext[];entries?: unknown[];savedCanvas?: boolean;welcome?: boolean;@@ -104,6 +113,10 @@ export async function harness(opts: HarnessOptions): Promise<Harness> {let releaseSessions = (): void => {};let releaseTranscript = (): void => {};let releaseApprovals = (): void => {};+ let releaseRuntimeConfig = (): void => {};+ let releaseRemoteSplit = (): void => {};+ const runtimeHeld = new Promise<void>((resolve) => (releaseRuntimeConfig = resolve));+ const remoteSplitHeld = new Promise<void>((resolve) => (releaseRemoteSplit = resolve));const approvalsHeld = new Promise<void>((resolve) => (releaseApprovals = resolve));const sessionsHeld = new Promise<void>((resolve) => (releaseSessions = resolve));const transcriptHeld = new Promise<void>((resolve) => (releaseTranscript = resolve));@@ -126,6 +139,7 @@ export async function harness(opts: HarnessOptions): Promise<Harness> {if (path.startsWith("/api/composio/toolkits"))return Response.json({ items: [{ id: "gmail", name: "Gmail", description: "Email" }], nextCursor: null });if (path.startsWith("/api/runtime-config")) {+ if (opts.holdRuntimeConfig) await runtimeHeld;return Response.json({scopeId: "personal:tester",approvedHarnesses: [],@@ -137,7 +151,10 @@ export async function harness(opts: HarnessOptions): Promise<Harness> {upgradeAvailable: false,});}- if (path.startsWith("/api/ui-state")) return Response.json({ value: null, updatedAt: 0 });+ if (path.startsWith("/api/ui-state")) {+ if (opts.holdRemoteSplit) await remoteSplitHeld;+ return Response.json({ value: opts.remoteCanvas ?? null, updatedAt: opts.remoteCanvas ? 1 : 0 });+ }if (path.startsWith("/api/sessions/") && path.includes("/approvals")) {if (opts.holdApprovals) await approvalsHeld;return Response.json({ approvals: [] });@@ -168,7 +185,7 @@ export async function harness(opts: HarnessOptions): Promise<Harness> {await sessionsHeld;return Response.json({ sessions: opts.listSessions ?? [] });}- return Response.json({ contexts: [], items: [], crons: [] });+ return Response.json({ contexts: opts.contexts ?? [], items: [], crons: [] });};const globals = {@@ -244,9 +261,14 @@ export async function harness(opts: HarnessOptions): Promise<Harness> {releaseSessions,releaseTranscript,releaseApprovals,+ releaseRuntimeConfig,+ releaseRemoteSplit,sessionsReady: sessions.sessionsReady as () => Promise<void>,refreshSessions: sessions.refreshSessions as () => Promise<boolean>,boot: shell.boot as () => Promise<void>,+ switchView: shell.switchView as Harness["switchView"],+ renderList: sessions.renderList as () => void,+ drawChatsPage: sessions.drawChatsPage as () => void,appState: shell.appState as Harness["appState"],sessionsState: sessions.sessionsState as Harness["sessionsState"],visibleConversation: () =>@@ -261,6 +283,8 @@ export async function harness(opts: HarnessOptions): Promise<Harness> {releaseSessions();releaseTranscript();releaseApprovals();+ releaseRuntimeConfig();+ releaseRemoteSplit();for (let drain = 0; drain < 5 && inFlight.size; drain++) {await Promise.allSettled(inFlight);await new Promise((resolve) => realSetTimeout(resolve, 0));diff --git a/plugins/web-ui/test/deep-link-boot.test.ts b/plugins/web-ui/test/deep-link-boot.test.tsindex 015e553e0..355058f26 100644--- a/plugins/web-ui/test/deep-link-boot.test.ts+++ b/plugins/web-ui/test/deep-link-boot.test.ts@@ -152,15 +152,117 @@ test("a bare entry still mints a new chat once the list lands", async () => {}});-test("a view deep link still waits for the list and never fetches a transcript", async () => {- const h = await harness({ path: "/crons" });+test("an explicit view opens without the sidebar list or remote canvas", async () => {+ const h = await harness({ path: "/crons", holdRemoteSplit: true });+ const booted = h.boot();try {- const booted = h.boot();- h.releaseSessions();- await booted;+ for (let i = 0; i < 100 && h.appState.currentView !== "crons"; i++)+ await new Promise((resolve) => setTimeout(resolve, 5));assert.equal(h.appState.currentView, "crons");- assert.equal(h.sessionsState.loaded, true);+ assert.equal(h.sessionsState.loaded, false);assert.equal(h.requests.filter((p) => p.startsWith(`/api/sessions/${SESSION.id}`)).length, 0);+ } finally {+ h.releaseRemoteSplit();+ h.releaseSessions();+ await booted;+ await h.close();+ }+});++test("the sidebar request overlaps runtime settings and paints if it finishes first", async () => {+ const h = await harness({ path: "/settings", holdRuntimeConfig: true, listSessions: [SESSION] });+ const booted = h.boot();+ try {+ for (let i = 0; i < 100 && !h.requests.includes("/api/sessions"); i++)+ await new Promise((resolve) => setTimeout(resolve, 5));+ assert.ok(h.requests.includes("/api/sessions"), "the list must start while runtime settings are pending");+ h.releaseSessions();+ await h.sessionsReady();+ h.releaseRuntimeConfig();+ await booted;+ assert.equal(h.appState.currentView, "settings");+ assert.ok(document.querySelector(`[data-session-id="${SESSION.id}"]`));+ } finally {+ h.releaseRuntimeConfig();+ h.releaseSessions();+ await booted;+ await h.close();+ }+});++test("returning from Settings waits for the saved remote canvas before creating a pane", async () => {+ const h = await harness({+ path: "/settings",+ holdRemoteSplit: true,+ listSessions: [SESSION],+ remoteCanvas: {+ v: 1,+ active: true,+ root: {+ kind: "split",+ a: { kind: "leaf", sessionId: SESSION.id, threadRef: SESSION.threadRef },+ b: { kind: "leaf" },+ },+ },+ });+ try {+ await h.boot();+ assert.equal(h.appState.currentView, "settings");+ h.releaseSessions();+ await h.sessionsReady();+ h.switchView("chats");+ assert.equal(document.querySelectorAll(".split-pane-content").length, 0);+ assert.equal(localStorage.getItem("web-ui:split-canvas:v1"), null);+ h.releaseRemoteSplit();+ for (let i = 0; i < 100 && document.querySelectorAll(".split-pane-content").length !== 2; i++)+ await new Promise((resolve) => setTimeout(resolve, 5));+ assert.equal(document.querySelectorAll(".split-pane-content").length, 2);+ assert.equal(h.appState.currentView, "chats");+ await waitForText(h, /Deep linked chat/);+ } finally {+ await h.close();+ }+});++test("a delayed legacy canvas waits for its session lookup and respects later navigation", async () => {+ const h = await harness({+ path: "/settings",+ holdRemoteSplit: true,+ listSessions: [SESSION],+ remoteCanvas: {+ v: 1,+ active: true,+ root: {+ kind: "split",+ a: { kind: "leaf", threadRef: SESSION.threadRef },+ b: { kind: "leaf" },+ },+ },+ });+ try {+ await h.boot();+ h.switchView("chats");+ assert.equal(document.querySelector(".settings-page"), null);+ h.switchView("settings");+ assert.ok(document.querySelector(".settings-page"));+ h.switchView("chats");+ assert.equal(document.querySelector(".settings-page"), null);+ assert.match(h.mainText(), /Loading conversations/);+ h.releaseRemoteSplit();+ for (let i = 0; i < 100 && !localStorage.getItem("web-ui:split-canvas:v1"); i++)+ await new Promise((resolve) => setTimeout(resolve, 5));+ assert.ok(localStorage.getItem("web-ui:split-canvas:v1"));+ assert.equal(document.querySelectorAll(".split-pane-content").length, 0);+ h.switchView("settings");+ h.releaseSessions();+ await h.sessionsReady();+ await new Promise((resolve) => setTimeout(resolve, 0));+ assert.equal(h.appState.currentView, "settings");+ assert.ok(document.querySelector(".settings-page"));+ assert.equal(document.querySelectorAll(".split-pane-content").length, 0);+ h.switchView("chats");+ assert.equal(document.querySelectorAll(".split-pane-content").length, 2);+ await waitForText(h, /Deep linked chat/);} finally {await h.close();}diff --git a/plugins/web-ui/test/sessions-refresh-race.test.ts b/plugins/web-ui/test/sessions-refresh-race.test.tsindex 8e6e89ac5..d53c8285a 100644--- a/plugins/web-ui/test/sessions-refresh-race.test.ts+++ b/plugins/web-ui/test/sessions-refresh-race.test.ts@@ -2,7 +2,7 @@ import assert from "node:assert/strict";import { test } from "node:test";import { JSDOM } from "jsdom";import { createServer } from "vite";-test("superseded session refreshes observe the winning refresh's list", async () => {+test("session refresh bursts share one trailing read and observe its fresh list", async () => {const dom = new JSDOM('<!doctype html><div id="app"></div><main id="main"></main>', {url: "http://localhost/web-ui/",});@@ -58,13 +58,12 @@ test("superseded session refreshes observe the winning refresh's list", async ()ready = true;});- assert.equal(pending.length, 3, "three /api/sessions requests in flight");- const body = () => Response.json({ sessions: [sessionA] });- pending[0]!(body());- pending[1]!(body());+ assert.equal(pending.length, 1, "a burst must not run overlapping session reads");+ pending[0]!(Response.json({ sessions: [] }));await new Promise((resolve) => setTimeout(resolve, 20));- assert.equal(ready, false, "sessionsReady() must wait for a winning refresh");- pending[2]!(body());+ assert.equal(pending.length, 2, "one trailing read observes changes newer than the first snapshot");+ assert.equal(ready, false, "sessionsReady() must wait for the fresh read");+ pending[1]!(Response.json({ sessions: [sessionA] }));assert.equal(await pane2, true, "the winning refresh reports success");assert.equal(await boot, true, "a superseded refresh resolves with the winner's outcome");const p1 = await pane1;@@ -259,3 +258,72 @@ test("an open that joined a refresh that simply failed does not double the load"dom.window.close();}});++test("queued refreshes recover a failed read and retain the latest patch epoch", async () => {+ const dom = jsdomGlobals();+ const pending: Array<(r: Response) => void> = [];+ globalThis.fetch = async (input) => {+ if (String(input) === "/api/contexts") return Response.json({ contexts: [] });+ return new Promise<Response>((resolve) => pending.push(resolve));+ };+ const vite = await createServer({ server: { middlewareMode: true, hmr: false, ws: false }, appType: "custom" });+ try {+ const { refreshSessions, sessionsState } = await vite.ssrLoadModule("/src/sessions.ts");+ const first = refreshSessions({ silent: true });+ const outdated = refreshSessions({ silent: true, patchEpoch: -1 });+ const current = refreshSessions({ silent: true });+ assert.equal(pending.length, 1);+ pending[0]!(Response.json({ error: "unavailable" }, { status: 503 }));+ await new Promise((resolve) => setTimeout(resolve, 0));+ assert.equal(pending.length, 2);+ const session = { id: "s", threadRef: "web:alex:s", scopeId: "personal:alex", title: "Current" };+ pending[1]!(Response.json({ sessions: [session] }));+ assert.deepEqual(await Promise.all([first, outdated, current]), [true, true, true]);+ assert.equal(sessionsState.list[0]?.title, "Current");++ const started = refreshSessions({ silent: true });+ const stale = refreshSessions({ silent: true, patchEpoch: -1 });+ pending[2]!(Response.json({ sessions: [] }));+ await new Promise((resolve) => setTimeout(resolve, 0));+ pending[3]!(Response.json({ sessions: [{ ...session, title: "Stale" }] }));+ assert.deepEqual(await Promise.all([started, stale]), [false, false]);+ assert.equal(sessionsState.list[0]?.title, "Current", "a queued obsolete patch recovery cannot overwrite state");+ } finally {+ await vite.close();+ dom.window.close();+ }+});++test("a stalled refresh can be replaced without old requests trapping later refreshes", async (t) => {+ const dom = jsdomGlobals();+ const pending: Array<(r: Response) => void> = [];+ globalThis.fetch = async (input) => {+ if (String(input) === "/api/contexts") return Response.json({ contexts: [] });+ return new Promise<Response>((resolve) => pending.push(resolve));+ };+ const vite = await createServer({ server: { middlewareMode: true, hmr: false, ws: false }, appType: "custom" });+ try {+ const { refreshSessions, sessionsState } = await vite.ssrLoadModule("/src/sessions.ts");+ let now = Date.now();+ t.mock.method(Date, "now", () => now);+ const stalled = refreshSessions({ silent: true });+ const queued = refreshSessions({ silent: true });+ now += 10_001;+ const replacement = refreshSessions({ silent: true });+ assert.equal(pending.length, 2, "a stalled request must not hold every caller indefinitely");+ const session = { id: "s", threadRef: "web:alex:s", scopeId: "personal:alex", title: "Replacement" };+ pending[1]!(Response.json({ sessions: [session] }));+ assert.equal(await replacement, true);+ const fresh = refreshSessions({ silent: true });+ assert.equal(pending.length, 3, "the stalled request cannot make a finished replacement look active");+ pending[2]!(Response.json({ sessions: [{ ...session, title: "Fresh" }] }));+ assert.equal(await fresh, true);+ pending[0]!(Response.json({ sessions: [] }));+ assert.deepEqual(await Promise.all([stalled, queued]), [true, true]);+ assert.equal(sessionsState.list[0]?.title, "Fresh");+ assert.equal(pending.length, 3, "the abandoned queued refresh must not run after its replacement");+ } finally {+ await vite.close();+ dom.window.close();+ }+});diff --git a/plugins/web-ui/test/sidebar-window.test.ts b/plugins/web-ui/test/sidebar-window.test.tsnew file mode 100644index 000000000..552c3f7cc--- /dev/null+++ b/plugins/web-ui/test/sidebar-window.test.ts@@ -0,0 +1,174 @@+import assert from "node:assert/strict";+import test from "node:test";+import type { CoreSession } from "../src/core-bridge.ts";+import { harness } from "./deep-link-boot-fixture.ts";++function sessions(count: number): CoreSession[] {+ return Array.from({ length: count }, (_, i) => ({+ id: `chat-${i}`,+ threadRef: `web:tester:${i}`,+ scopeId: "personal:tester",+ type: "dm",+ title: `Chat ${i}`,+ createdAt: 1_000_000 - i,+ }));+}++function button(root: Element, label: string): HTMLButtonElement {+ const found = [...root.querySelectorAll<HTMLButtonElement>("button")].find(+ (candidate) => candidate.textContent?.trim() === label,+ );+ assert.ok(found, `missing button: ${label}`);+ return found;+}++test("sidebar batches retain pinned, open and selected chats, full counts and archived expansion", async () => {+ const list = sessions(230);+ list[148]!.pinned = true;+ list[149]!.pinned = true;+ for (const item of list.slice(150)) item.archived = true;+ const opened = list[147]!;+ const h = await harness({+ path: `/s/${opened.id}`,+ session: opened,+ listSessions: list,+ contexts: [+ { scopeId: "personal:tester", kind: "personal", name: "Personal", sessionCount: 230, lastActivityAt: null },+ ],+ });+ try {+ await h.boot();+ h.releaseSessions();+ await h.sessionsReady();+ const sidebar = document.querySelector("#sidebar-body")!;+ assert.equal(sidebar.querySelectorAll(".session-row").length, 53);+ assert.equal(sidebar.querySelector(".recent-project-count")?.textContent, "148");+ for (const id of [opened.id, "chat-148", "chat-149"]) assert.ok(sidebar.querySelector(`[data-session-id="${id}"]`));+ const projectToggle = sidebar.querySelector<HTMLButtonElement>(".recent-project-toggle")!;+ projectToggle.click();+ assert.equal(sidebar.querySelectorAll(".recent-project-children .session-row").length, 0);+ projectToggle.click();+ button(sidebar, "Show more conversations").click();+ assert.equal(sidebar.querySelectorAll(".session-row").length, 103);+ for (const [id, shift] of [+ ["chat-90", false],+ ["chat-92", true],+ ] as const)+ sidebar.querySelector(`[data-session-id="${id}"] .session`)!.dispatchEvent(+ new window.KeyboardEvent("keydown", {+ key: " ",+ ctrlKey: !shift,+ shiftKey: shift,+ bubbles: true,+ cancelable: true,+ }),+ );+ const selected = () =>+ [...sidebar.querySelectorAll<HTMLElement>(".session-row.selected")].map((row) => row.dataset.sessionId);+ assert.deepEqual(selected(), ["chat-90", "chat-91", "chat-92"]);+ h.sessionsState.list = [+ ...sessions(120).map((item) => ({+ ...item,+ id: `new-${item.id}`,+ threadRef: `new-${item.threadRef}`,+ createdAt: item.createdAt + 10_000,+ })),+ ...list,+ ];+ h.renderList();+ assert.deepEqual(+ selected(),+ ["chat-90", "chat-91", "chat-92"],+ "newer rows must not discard the current selection",+ );+ assert.equal(sidebar.querySelector(".archived-count")?.textContent, "80");+ sidebar.querySelector<HTMLButtonElement>(".archived-count")!.closest("button")!.click();+ assert.equal(sidebar.querySelectorAll(".archived-children .session-row").length, 50);+ button(sidebar, "Show more archived conversations").click();+ assert.equal(sidebar.querySelectorAll(".archived-children .session-row").length, 80);+ sidebar.querySelector<HTMLButtonElement>(".archived-count")!.closest("button")!.click();+ assert.equal(sidebar.querySelectorAll(".archived-children .session-row").length, 0);+ } finally {+ await h.close();+ }+});++test("chat browsing batches rows while search still covers the complete history", async () => {+ const list = sessions(125);+ list[124]!.title = "Older matching conversation";+ const h = await harness({ path: "/settings", listSessions: list });+ try {+ h.releaseSessions();+ await h.boot();+ await h.sessionsReady();+ h.appState.currentView = "chats";+ h.drawChatsPage();+ const main = document.querySelector("#main")!;+ assert.equal(main.querySelectorAll(".chat-row").length, 50);+ button(main, "Show more conversations").click();+ assert.equal(main.querySelectorAll(".chat-row").length, 100);+ const input = main.querySelector<HTMLInputElement>('input[type="search"]')!;+ input.value = "Older matching";+ input.dispatchEvent(new window.Event("input", { bubbles: true }));+ assert.equal(main.querySelectorAll(".chat-row").length, 1);+ assert.match(main.querySelector(".chat-row")?.textContent ?? "", /Older matching conversation/);+ input.value = "";+ input.dispatchEvent(new window.Event("input", { bubbles: true }));+ assert.equal(main.querySelectorAll(".chat-row").length, 50);+ assert.equal(h.sessionsState.list.length, 125);+ } finally {+ await h.close();+ }+});++test("an open project menu and rename survive the last project row leaving the batch", async () => {+ const list = sessions(50);+ const scopeId = "group:web-project-target";+ list[49]!.scopeId = scopeId;+ const h = await harness({+ path: `/s/${list[0]!.id}`,+ session: list[0],+ listSessions: list,+ contexts: [+ {+ scopeId,+ kind: "group",+ name: "Target",+ sessionCount: 1,+ lastActivityAt: null,+ project: {+ id: "target",+ scopeId,+ name: "Target",+ ownerId: "tester",+ memberIds: ["tester"],+ members: [],+ },+ },+ ],+ });+ try {+ await h.boot();+ h.releaseSessions();+ await h.sessionsReady();+ const sidebar = document.querySelector("#sidebar-body")!;+ sidebar.querySelector<HTMLButtonElement>('[aria-label="Options for Target"]')!.click();+ h.sessionsState.list = [+ { ...list[0]!, id: "newer-chat", threadRef: "web:tester:newer", createdAt: 2_000_000 },+ ...list,+ ];+ h.renderList();+ assert.ok(sidebar.querySelector('[aria-label="Target project"] [role="menu"]'));+ button(sidebar, "Rename").click();+ const input = sidebar.querySelector<HTMLInputElement>('[aria-label="Rename project"]')!;+ input.value = "Unfinished name";+ input.dispatchEvent(new window.Event("input", { bubbles: true }));+ h.renderList();+ assert.equal(sidebar.querySelector('[aria-label="Rename project"]'), input);+ assert.equal(input.value, "Unfinished name");+ input.dispatchEvent(new window.KeyboardEvent("keydown", { key: "Escape", bubbles: true }));+ assert.equal(sidebar.querySelector('[aria-label="Target project"]'), null);+ } finally {+ await h.close();+ }+});diff --git a/plugins/web-ui/test/split-canvas-entry.test.ts b/plugins/web-ui/test/split-canvas-entry.test.tsindex 1c6345115..1d48673b8 100644--- a/plugins/web-ui/test/split-canvas-entry.test.ts+++ b/plugins/web-ui/test/split-canvas-entry.test.ts@@ -125,7 +125,8 @@ test("boot mounts a restored canvas before it awaits the session list", () => {const listAwait = boot.lastIndexOf("await sessions;");assert.ok(early > 0, "boot must offer the canvas its head start");assert.ok(listStart > 0, "boot still loads the session list");- assert.ok(early < listStart, "the mount must come BEFORE the list fetch the panes never read");+ assert.ok(listStart < early, "the list overlaps runtime settings and remote layout reads");+ assert.ok(early < listAwait, "the restored canvas must not wait for the sidebar list");assert.match(boot, /const bareEntry = !viewIntent && !wantedSession && wanted !== "app-edit" && !connectedProvider;/);diff --git a/plugins/web-ui/test/stable-markdown.test.ts b/plugins/web-ui/test/stable-markdown.test.tsindex 46aa2d296..8ebfe5232 100644--- a/plugins/web-ui/test/stable-markdown.test.ts+++ b/plugins/web-ui/test/stable-markdown.test.ts@@ -561,3 +561,28 @@ test("oversized Mermaid sources are rejected before parsing", async () => {/Diagram is too large/,);});++test("fade ranges preserve selected text across many formatted nodes and paragraphs", async () => {+ const block = await mount("Before");+ block.isStreaming = true;+ block.content += " first **bold** word\n\nSecond _italic_ line\n\nThird";+ await block.updateComplete;+ const oldSpans = [...block.querySelectorAll(".tok-in")];+ const selected = block.querySelector("strong .stream-chunk")!.firstChild!;+ const selection = window.getSelection()!;+ selection.setBaseAndExtent(selected, 0, selected, 4);+ for (const span of oldSpans) span.dispatchEvent(new dom.window.Event("animationend"));+ block.content += " tail\n\nFourth **new** paragraph";+ await block.updateComplete;+ assert.equal(selection.toString(), "bold");+ assert.ok(oldSpans.every((span) => span.isConnected));+ assert.deepEqual(+ [...block.querySelectorAll(".tok-in")].map((span) => span.textContent),+ [" tail", "Fourth ", "new", " paragraph"],+ );+ assert.deepEqual(+ [...block.querySelectorAll("p")].map((paragraph) => paragraph.textContent),+ ["Before first bold word", "Second italic line", "Third tail", "Fourth new paragraph"],+ );+ block.remove();+});