Multiplayer agent harness for work.
Page the sidebar session list and load subagents on demand (#2517)
Regan Bella101ae677d80
diff --git a/plugins/web-ui/server/index.ts b/plugins/web-ui/server/index.tsindex 63bab56c1..1c4194577 100644--- a/plugins/web-ui/server/index.ts+++ b/plugins/web-ui/server/index.ts@@ -1533,10 +1533,38 @@ const apiRoutes: readonly WebRoute[] = [method: "GET",path: "/api/sessions",handle: async (c) => {- const { res, user } = c;- return relayCore(res, "GET", `/v1/sessions?principalId=${encodeURIComponent(user)}`);+ const { res, url, user } = c;+ const qs = new URLSearchParams({ principalId: user });+ for (const p of ["limit", "before", "status", "surface", "scope", "q"] as const) {+ const v = url.searchParams.get(p);+ if (v !== null) qs.set(p, v.slice(0, 500));+ }+ return relayCore(res, "GET", `/v1/sessions?${qs.toString()}`);},},+ {+ method: "GET",+ path: "/api/sessions/row",+ handle: async (c) => {+ const { res, url, user } = c;+ const qs = new URLSearchParams({ principalId: user });+ for (const p of ["id", "threadRef"] as const) {+ const v = url.searchParams.get(p);+ if (v !== null) qs.set(p, v);+ }+ return relayCore(res, "GET", `/v1/sessions/row?${qs.toString()}`);+ },+ },+ {+ method: "GET",+ path: "/api/sessions/:id/children",+ handle: async (c) =>+ relayCore(+ c.res,+ "GET",+ `/v1/sessions/${encodeURIComponent(c.params.id!)}/children?principalId=${encodeURIComponent(c.user)}`,+ ),+ },{method: "GET",path: "/api/contexts",diff --git a/plugins/web-ui/src/contexts.ts b/plugins/web-ui/src/contexts.tsindex 323bd640c..6ac59233d 100644--- a/plugins/web-ui/src/contexts.ts+++ b/plugins/web-ui/src/contexts.ts@@ -25,13 +25,13 @@ import {fileContentUrl,} from "./core-bridge";import { UI_BASE } from "./deep-link";-import { errMessage } from "../../chassis/src/errors";+import { errMessage, swallowAs } from "../../chassis/src/errors";import { actionSnippet, avatarTpl, fieldSelect, formatBytes, menuSelect, relTime } from "./ui";import { slackMark } from "./slack-mark";import { icon } from "./icons";import { appState, replacePanePreservingFocus, switchView, syncUrlFromState } from "./shell";import { startNewChat } from "./sessions";-import { groupDmTitle, openSession, refreshSessions, sessionsState } from "./sessions";+import { groupDmTitle, loadScopeSessions, openSession, refreshSessions, sessionsState } from "./sessions";import { activityOf, sidebarSessions, surfaceOf } from "./session-list";import type { WebhookView } from "./webhooks";import type { CronView } from "./crons";@@ -172,7 +172,11 @@ export async function renderContexts(): Promise<void> {contextsLoading = true;drawContexts();try {- await Promise.all([fetchContexts(), refreshSessions({ silent: true })]);+ await Promise.all([+ fetchContexts(),+ refreshSessions({ silent: true }),+ contextsState.selected ? loadScopeSessions(contextsState.selected) : null,+ ]);if (seq !== appState.viewRenderSeq || appState.currentView !== "contexts") return;} catch (e) {if (seq !== appState.viewRenderSeq || appState.currentView !== "contexts") return;@@ -1420,6 +1424,7 @@ function selectContext(scopeId: string | null): void {syncUrlFromState();drawContexts();if (scopeId) {+ void loadScopeSessions(scopeId).then(drawContexts).catch(swallowAs("web-ui: load context chats", undefined));void loadScopeResources(scopeId);void loadAmbientPolicy(scopeId, drawContexts);void loadContextModel(scopeId, drawContexts);diff --git a/plugins/web-ui/src/core-bridge.ts b/plugins/web-ui/src/core-bridge.tsindex c61db3885..e17701237 100644--- a/plugins/web-ui/src/core-bridge.ts+++ b/plugins/web-ui/src/core-bridge.ts@@ -5,6 +5,7 @@ import { streamedAnswer } from "./timeline.ts";import { fetchServerSentEvents } from "@tanstack/ai-client";import { postCallText, postResultOk } from "./surface-post.ts";import type { RuntimeChange, RuntimeConfig } from "./runtime-config-cache.ts";+import type { ChatBrowseStatus } from "./session-list.ts";import { createAssistantMessageEventStream } from "@earendil-works/pi-ai";import type { Attachment } from "@earendil-works/pi-web-ui";import type { Api, AssistantMessage, AssistantMessageEventStream, Context, Model, Usage } from "@earendil-works/pi-ai";@@ -151,6 +152,52 @@ export interface CoreSession {forkBoundarySeq?: number;parentSessionId?: string;surface?: string;+ subagents?: { running: number; waiting: number };+}++export interface SessionPageQuery {+ limit: number;+ before?: string | null;+ status?: ChatBrowseStatus;+ surface?: string;+ scope?: string | null;+ q?: string;+}++export interface SessionPage {+ sessions: CoreSession[];+ pinned?: CoreSession[];+ nextCursor: string | null;+ hasArchived?: boolean;+}++export function fetchSessionPage(query: SessionPageQuery): Promise<SessionPage> {+ const qs = new URLSearchParams({ limit: String(query.limit) });+ if (query.before) qs.set("before", query.before);+ if (query.status && query.status !== "active") qs.set("status", query.status);+ if (query.surface) qs.set("surface", query.surface);+ if (query.scope) qs.set("scope", query.scope);+ if (query.q?.trim()) qs.set("q", query.q.trim());+ return api<SessionPage>(`/api/sessions?${qs.toString()}`);+}++export async function fetchSessionChildren(id: string): Promise<CoreSession[] | null> {+ try {+ return (await api<{ sessions: CoreSession[] }>(`/api/sessions/${encodeURIComponent(id)}/children`)).sessions;+ } catch (err) {+ if (err instanceof ApiError && err.status === 404) return null;+ throw err;+ }+}++export async function fetchSessionRow(ref: { id: string } | { threadRef: string }): Promise<CoreSession | null> {+ const qs = new URLSearchParams("id" in ref ? { id: ref.id } : { threadRef: ref.threadRef });+ try {+ return (await api<{ session: CoreSession }>(`/api/sessions/row?${qs.toString()}`)).session;+ } catch (err) {+ if (err instanceof ApiError && err.status === 404) return null;+ throw err;+ }}export function inheritedTranscript(diff --git a/plugins/web-ui/src/inbox-chat.ts b/plugins/web-ui/src/inbox-chat.tsindex 0297b3cb0..e1cb2f4a0 100644--- a/plugins/web-ui/src/inbox-chat.ts+++ b/plugins/web-ui/src/inbox-chat.ts@@ -1,6 +1,6 @@import { html, LitElement, type TemplateResult } from "lit";import { ref } from "lit/directives/ref.js";-import { api, type CoreSession } from "./core-bridge";+import { fetchSessionRow } from "./core-bridge";import type { Conversation } from "./conv-types";import { createConversation, disposeConversation, ensureDeliveryStream } from "./conversations";import { openSessionInto } from "./sessions";@@ -53,8 +53,7 @@ class InboxChat extends LitElement {const current = conversation.mountLoadingPane();const threadRef = `web:${user}:inbox`;try {- const { sessions } = await api<{ sessions: CoreSession[] }>("/api/sessions");- const session = sessions.find((entry) => entry.threadRef === threadRef);+ const session = await fetchSessionRow({ threadRef });if (this.conversation !== conversation || !current()) return;if (session) await openSessionInto(conversation, session, undefined, undefined, false);else conversation.mountContinuable(threadRef, null, null, [], "Inbox");diff --git a/plugins/web-ui/src/search.ts b/plugins/web-ui/src/search.tsindex f3be45476..b55448a50 100644--- a/plugins/web-ui/src/search.ts+++ b/plugins/web-ui/src/search.ts@@ -1,16 +1,16 @@import { html, nothing, render, type TemplateResult } from "lit";import { CornerDownLeft, Search } from "lucide";-import { api, userSendMessage, type CoreSession } from "./core-bridge";+import { api, fetchSessionRow, userSendMessage, type CoreSession } from "./core-bridge";import { startNewChat } from "./sessions";import { recencyGroup } from "./session-list";import { searchGroup } from "./search-group";import { slackWireToPlain, stripSlackDirectives } from "./slack-text";-import { openSession, refreshSessions, sessionsState, sessionTitle } from "./sessions";+import { openSession, sessionsState, sessionTitle } from "./sessions";import { destinations } from "./browse";import { UI_BASE } from "./deep-link";import { resourceResults, matchResources, type ResourceHit, type ResourceSearchResponse } from "./search-resources";import { icon } from "./icons";-import { swallow } from "../../chassis/src/errors.ts";+import { swallow, swallowAs } from "../../chassis/src/errors.ts";interface ChatSearchHit {sessionId: string;@@ -258,11 +258,8 @@ function scrollSelectedIntoView(): void {async function openHit(hit: ChatSearchHit): Promise<void> {const find = (): CoreSession | undefined => sessionsState.list.find((s) => s.id === hit.sessionId);- let session = find();- if (!session) {- await refreshSessions({ silent: true });- session = find();- }+ const session =+ find() ?? (await fetchSessionRow({ id: hit.sessionId }).catch(swallowAs("web-ui: open search hit", null)));if (!session) return;closeChatSearch();await openSession(session);diff --git a/plugins/web-ui/src/session-list.ts b/plugins/web-ui/src/session-list.tsindex 09f452d47..f116e4687 100644--- a/plugins/web-ui/src/session-list.ts+++ b/plugins/web-ui/src/session-list.ts@@ -5,7 +5,7 @@ import {type CoreSession,type SessionBackgroundView,} from "./core-bridge.ts";-import { subagentCounts } from "./subagent-activity.ts";+import { descendantsOf, subagentCounts } from "./subagent-activity.ts";import { goalFloorLabel, goalWorkedLabel } from "./goal-strip.ts";import { relTime } from "./ui.ts";@@ -150,17 +150,50 @@ export function bumpActivity(list: CoreSession[], threadRef: string, at: number)return list.map((s) => (s.threadRef === threadRef ? { ...s, lastActivityAt: at } : s));}-export function reconcileSessions(- server: CoreSession[],+export function upsertSessions(prev: CoreSession[], rows: readonly CoreSession[]): CoreSession[] {+ if (!rows.length) return prev;+ const incoming = new Map(rows.map((row) => [row.id, row]));+ const threads = new Set(rows.map((row) => row.threadRef));+ const kept = prev.filter((row) => !incoming.has(row.id) && !threads.has(row.threadRef));+ return [...kept, ...rows];+}++export interface PageWindow {+ archived: boolean;+ surface?: string;+ floor: number | null;+}++function inPageClass(row: CoreSession, window: PageWindow): boolean {+ if (!row.id || row.parentSessionId || automationRunLabel(row)) return false;+ if (Boolean(row.archived) !== window.archived) return false;+ if (window.surface && row.surface !== window.surface) return false;+ return true;+}++export function mergeFirstPage(prev: CoreSession[],+ page: { sessions: readonly CoreSession[]; pinned?: readonly CoreSession[] },+ window: PageWindow,openIds: readonly string[] = [],): CoreSession[] {- const known = new Set(server.map((s) => s.threadRef));- const pending = prev.filter((s) => !s.id && !known.has(s.threadRef));- const served = new Set(server.map((s) => s.id));- const dropped = new Set(openIds.filter((id) => !served.has(id)));- const stillOpen = dropped.size ? prev.filter((s) => dropped.has(s.id) && !known.has(s.threadRef)) : [];- return [...pending, ...stillOpen, ...server];+ const served = new Set([...page.sessions, ...(page.pinned ?? [])].map((row) => row.id));+ const open = new Set(openIds);+ const kept = prev.filter((row) => {+ if (served.has(row.id) || open.has(row.id) || !inPageClass(row, window)) return true;+ if (row.pinned && !window.archived) return false;+ return window.floor !== null && activityOf(row) < window.floor;+ });+ return upsertSessions(kept, [...(page.pinned ?? []), ...page.sessions]);+}++export function mergeChildren(prev: CoreSession[], rootId: string, children: readonly CoreSession[]): CoreSession[] {+ const below = new Set(descendantsOf(prev, rootId).map(({ session }) => session.id));+ const served = new Set(children.map((row) => row.id));+ return upsertSessions(+ prev.filter((row) => !below.has(row.id) || served.has(row.id)),+ children,+ );}export function markWorking(list: CoreSession[], threadRef: string): CoreSession[] {@@ -248,7 +281,7 @@ export function rowIndicators(list: readonly CoreSession[] = [],): RowIndicators {const live = typeof liveThreads === "string" ? new Set([liveThreads]) : (liveThreads ?? new Set<string>());- const children = subagentCounts(list, s.id);+ const children = !s.subagents || descendantsOf(list, s.id).length ? subagentCounts(list, s.id) : s.subagents;return {working: Boolean(s.working) || (Boolean(s.threadRef) && live.has(s.threadRef)),awaiting: Boolean(s.awaitingInput) || children.waiting > 0,diff --git a/plugins/web-ui/src/sessions.ts b/plugins/web-ui/src/sessions.tsindex 385f260d7..83d422615 100644--- a/plugins/web-ui/src/sessions.ts+++ b/plugins/web-ui/src/sessions.ts@@ -34,8 +34,10 @@ import {type IconNode,} from "lucide";import {- api,fetchSessionApprovals,+ fetchSessionChildren,+ fetchSessionPage,+ fetchSessionRow,fetchTranscript,currentEarlierCount,detachSession,@@ -61,10 +63,12 @@ import {groupProjectSessions,recencyGroup,recentProjectSeeds,- reconcileSessions,+ mergeChildren,+ mergeFirstPage,rowIndicators,surfaceOf,splitPinned,+ upsertSessions,withPendingSession,withoutUnsentPending,type RecentItem,@@ -72,7 +76,7 @@ import {} from "./session-list";import { tip } from "./tooltip";import { errMessage, swallow, swallowAs } from "../../chassis/src/errors";-import { copyText, menuSelect, relTime, workingWave } from "./ui";+import { copyText, menuSelect, relTime, sheenLabel, workingWave } from "./ui";import { slackMark } from "./slack-mark";import { icon } from "./icons";import { listPageTpl } from "./list-page";@@ -114,6 +118,7 @@ export const sessionsState = {renamingId: null as string | null,openingKey: null as string | null,webOnly: false,+ hasArchived: false,collapsedProjectScopes: new Set<string>(),};@@ -177,9 +182,16 @@ 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 activeCursor: string | null = null;+let activePaged = false;+let archivedCursor: string | null = null;+let archivedLoaded = false;+let pageLoading: "active" | "archived" | null = null;+let chatsPageRows: CoreSession[] = [];+let chatsPageCursor: string | null = null;+let chatsPageLoading = false;+let chatsPageSeq = 0;+let chatsPageQueryTimer: ReturnType<typeof setTimeout> | null = null;let chatsPageScope: string | null = null;let chatsPageQuery = "";@@ -208,9 +220,18 @@ export function resetSessionsState(): void {renameDraft = "";refreshingTitleIds.clear();showArchived = false;- recentLimit = SESSION_BATCH_SIZE;- archivedLimit = SESSION_BATCH_SIZE;- chatsPageLimit = SESSION_BATCH_SIZE;+ sessionsState.hasArchived = false;+ activeCursor = null;+ activePaged = false;+ archivedCursor = null;+ archivedLoaded = false;+ pageLoading = null;+ chatsPageRows = [];+ chatsPageCursor = null;+ chatsPageLoading = false;+ chatsPageSeq++;+ if (chatsPageQueryTimer) clearTimeout(chatsPageQueryTimer);+ chatsPageQueryTimer = null;chatsPageScope = null;chatsPageQuery = "";chatsPageStatus = "active";@@ -315,20 +336,7 @@ 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 shownThreads = new Set(visible.map((session) => session.threadRef));const activeItems = recentItemsFor(rest);const archivedItems: RecentItem[] = archived.map((session) => ({kind: "session",@@ -356,42 +364,39 @@ export function renderList(): void {}${groupedRows(activeItems, shownThreads)}${- rest.some((session) => !shownThreads.has(session.threadRef))+ activeCursor? html`<buttonclass="archived-toggle"type="button"- @click=${() => {- recentLimit += SESSION_BATCH_SIZE;- renderList();- }}+ ?disabled=${pageLoading === "active"}+ aria-busy=${pageLoading === "active" ? "true" : "false"}+ @click=${() => void loadMoreSessions("active")}>- Show more conversations+ ${sheenLabel("Show more conversations", pageLoading === "active")}</button>`: nothing}${- archived.length+ archived.length || sessionsState.hasArchived? html`<button class="archived-toggle ${showArchived ? "open" : ""}" @click=${toggleShowArchived}>${icon(showArchived ? ChevronDown : ChevronRight, 14)}- <span>Archived</span>- <span class="archived-count">${archived.length}</span>+ ${sheenLabel("Archived", pageLoading === "archived" && !archivedLoaded)}</button>${showArchived? html`<div class="archived-children">${groupedRows(archivedItems, shownThreads)}${- archived.some((session) => !shownThreads.has(session.threadRef))+ archivedCursor? html`<buttonclass="archived-toggle"type="button"- @click=${() => {- archivedLimit += SESSION_BATCH_SIZE;- renderList();- }}+ ?disabled=${pageLoading === "archived"}+ aria-busy=${pageLoading === "archived" ? "true" : "false"}+ @click=${() => void loadMoreSessions("archived")}>- Show more archived conversations+ ${sheenLabel("Show more archived conversations", pageLoading === "archived")}</button>`: nothing}@@ -464,7 +469,6 @@ function recentItem(item: RecentItem, shownThreads: ReadonlySet<string>): Templa<span class="recent-project-name" dir="auto">${name.replace(/^#/, "")}</span></button><div class="session-menu recent-project-menu ${menuOpen ? "menu-open" : ""}">- <span class="recent-project-count">${item.sessions.length}</span><buttonclass="session-menu-btn"data-menu-id=${menuKey}@@ -593,14 +597,49 @@ export async function renderChatsPage(): Promise<void> {if (appState.currentView !== "chats") return;await ensureContexts();drawChatsPage();- await refreshSessions({ showLoading: sessionsState.list.length === 0, silent: sessionsState.list.length > 0 });- if (appState.currentView === "chats") drawChatsPage();+ await loadChatsPage(false);}function chatsPageShowing(): boolean {return Boolean(chatsPageHost && appState.mainEl && chatsPageHost.parentElement === appState.mainEl);}+async function loadChatsPage(append: boolean): Promise<void> {+ if (append && !chatsPageCursor) return;+ const seq = ++chatsPageSeq;+ chatsPageLoading = true;+ if (!append) chatsPageCursor = null;+ drawChatsPage();+ try {+ const page = await fetchSessionPage({+ limit: SESSION_BATCH_SIZE,+ before: append ? chatsPageCursor : null,+ status: chatsPageStatus,+ scope: chatsPageScope,+ q: chatsPageQuery,+ ...(chatsPageSurface === "all" ? {} : { surface: chatsPageSurface }),+ });+ if (seq !== chatsPageSeq) return;+ chatsPageRows = append ? [...chatsPageRows, ...page.sessions] : [...(page.pinned ?? []), ...page.sessions];+ chatsPageCursor = page.nextCursor;+ sessionsState.list = upsertSessions(sessionsState.list, [...(page.pinned ?? []), ...page.sessions]);+ sessionsNotice = "";+ } catch (e) {+ if (seq !== chatsPageSeq) return;+ sessionsNotice = errMessage(e, "Failed to load conversations.");+ } finally {+ if (seq === chatsPageSeq) {+ chatsPageLoading = false;+ drawChatsPage();+ }+ }+}++function reloadChatsPage(): void {+ chatsPageRows = [];+ void loadChatsPage(false);+}+export function drawChatsPage(): void {if (appState.currentView !== "chats" || !appState.mainEl || splitState.active) return;mainConversation().state.host = null;@@ -609,32 +648,28 @@ export function drawChatsPage(): void {chatsPageHost.className = "pane chats-page";appState.mainEl.replaceChildren(chatsPageHost);}- const q = chatsPageQuery.trim().toLowerCase();- const matches = sidebarSessions(sessionsState.list)+ const cached = new Map(sessionsState.list.map((s) => [s.id, s]));+ const rows = chatsPageRows+ .map((s) => cached.get(s.id) ?? s).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));- const rows = matches.slice(0, chatsPageLimit).map((s) => chatPageRow(s));- if (matches.length > chatsPageLimit)+ .map((s) => chatPageRow(s));+ if (chatsPageCursor)rows.push(html`<div class="list-footer"><buttonclass="btn"type="button"- @click=${() => {- chatsPageLimit += SESSION_BATCH_SIZE;- drawChatsPage();- }}+ ?disabled=${chatsPageLoading}+ aria-busy=${chatsPageLoading ? "true" : "false"}+ @click=${() => void loadChatsPage(true)}>- Show more conversations+ ${sheenLabel("Show more conversations", chatsPageLoading)}</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") {+ if (chatsPageLoading && chatsPageRows.length === 0) empty = "Loading conversations…";+ else if (chatsPageScope || chatsPageQuery.trim() || chatsPageStatus !== "active" || chatsPageSurface !== "all") {empty = "No conversations match.";}render(@@ -643,8 +678,7 @@ export function drawChatsPage(): void {scope: chatsPageScope,onScope: (s) => {chatsPageScope = s;- chatsPageLimit = SESSION_BATCH_SIZE;- drawChatsPage();+ reloadChatsPage();},action: { label: "New chat", onClick: () => startNewChat() },search: {@@ -652,7 +686,11 @@ export function drawChatsPage(): void {placeholder: "Search chats…",onInput: (v) => {chatsPageQuery = v;- chatsPageLimit = SESSION_BATCH_SIZE;+ if (chatsPageQueryTimer) clearTimeout(chatsPageQueryTimer);+ chatsPageQueryTimer = setTimeout(() => {+ chatsPageQueryTimer = null;+ reloadChatsPage();+ }, 250);drawChatsPage();},},@@ -673,13 +711,10 @@ export function drawChatsPage(): void {class=${chatsPageStatus === value ? "active" : ""}@click=${() => {chatsPageStatus = value;- chatsPageLimit = SESSION_BATCH_SIZE;- drawChatsPage();+ reloadChatsPage();}}>- ${label}<span- >${sidebarSessions(sessionsState.list).filter((session) => chatBrowseStatusMatches(session, value)).length}</span- >+ ${label}</button>`,)}</div>@@ -689,8 +724,7 @@ export function drawChatsPage(): void {ariaLabel: "Filter by surface",onSelect: (value) => {chatsPageSurface = (value ?? "all") as typeof chatsPageSurface;- chatsPageLimit = SESSION_BATCH_SIZE;- drawChatsPage();+ reloadChatsPage();},options: [{ value: "all", label: "All surfaces" },@@ -707,11 +741,6 @@ export function drawChatsPage(): void {);}-function chatMatches(s: CoreSession, q: string): boolean {- const context = sharedContextLabel(s.scopeId, s.channelName ?? null) ?? "Personal";- return [sessionTitle(s), s.channelName ?? "", context].join(" ").toLowerCase().includes(q);-}-export const syncWorkingPulse = (el?: Element): void => {if (!(el instanceof Element)) return;const running = (): Animation[] => el.getAnimations({ subtree: true });@@ -1292,17 +1321,57 @@ function renameInput(menuKey: string, ariaLabel: string, commit: () => Promise<vfunction toggleShowArchived(): void {showArchived = !showArchived;+ if (showArchived && !archivedLoaded) void loadMoreSessions("archived");renderList();}+async function loadMoreSessions(kind: "active" | "archived"): Promise<void> {+ if (pageLoading) return;+ const archived = kind === "archived";+ const before = archived ? archivedCursor : activeCursor;+ if (!archived && !before) return;+ pageLoading = kind;+ const epoch = sessionPatchEpoch;+ renderList();+ try {+ const page = await fetchSessionPage({+ limit: SESSION_BATCH_SIZE,+ before,+ status: kind,+ ...(sessionsState.webOnly ? { surface: "web" } : {}),+ });+ if (epoch !== sessionPatchEpoch) return;+ sessionsState.list = upsertSessions(sessionsState.list, page.sessions);+ if (archived) {+ archivedCursor = page.nextCursor;+ archivedLoaded = true;+ } else {+ activeCursor = page.nextCursor;+ activePaged = true;+ }+ } catch (e) {+ sessionsNotice = errMessage(e, "Failed to load conversations.");+ } finally {+ pageLoading = null;+ renderList();+ }+}+export function setWebOnly(webOnly: boolean): void {+ if (sessionsState.webOnly === webOnly) return;sessionsState.webOnly = webOnly;try {localStorage.setItem(WEB_ONLY_KEY, webOnly ? "1" : "0");} catch {void 0;}+ activeCursor = null;+ activePaged = false;+ archivedCursor = null;+ archivedLoaded = false;+ if (showArchived) void loadMoreSessions("archived");renderList();+ void refreshSessions({ silent: true });}export function revealSessionSurface(s: CoreSession): void {@@ -1725,13 +1794,36 @@ async function runSessionsRefresh(}listRequestedAt = Date.now();try {- const r = await api<{ sessions: CoreSession[] }>("/api/sessions");+ const surface = sessionsState.webOnly ? "web" : undefined;+ const roots = [...new Set(openConversationIds())];+ const [page, children] = await Promise.all([+ fetchSessionPage({ limit: SESSION_BATCH_SIZE, ...(surface ? { surface } : {}) }),+ Promise.all(+ roots.map(+ async (id) => [id, await fetchSessionChildren(id).catch(swallowAs("web-ui: load subagents", null))] as const,+ ),+ ),+ ]);if (seq !== sessionRefreshSeq) return sessionsState.loaded || ((await newerRun()) ?? false);if (patchEpoch !== sessionPatchEpoch) {listDiscards++;return false;}- sessionsState.list = reconcileSessions(r.sessions ?? [], sessionsState.list, openConversationIds());+ const last = page.sessions[page.sessions.length - 1];+ let list = mergeFirstPage(+ sessionsState.list,+ page,+ {+ archived: false,+ ...(surface ? { surface } : {}),+ floor: page.nextCursor && last ? activityOf(last) : null,+ },+ openConversationIds(),+ );+ for (const [id, rows] of children) if (rows) list = mergeChildren(list, id, rows);+ sessionsState.list = list;+ sessionsState.hasArchived = Boolean(page.hasArchived);+ if (!activePaged) activeCursor = page.nextCursor;sessionsState.loaded = true;listCurrent = true;sessionsNotice = "";@@ -1752,6 +1844,31 @@ async function runSessionsRefresh(}}+export async function loadScopeSessions(scopeId: string): Promise<void> {+ const page = await fetchSessionPage({ limit: SESSION_BATCH_SIZE, scope: scopeId });+ sessionsState.list = upsertSessions(sessionsState.list, page.sessions);+}++async function loadSessionNeighbors(s: CoreSession): Promise<void> {+ const parentId = s.parentSessionId;+ const needsParent = Boolean(parentId) && !sessionsState.list.some((row) => row.id === parentId);+ const [children, parent] = await Promise.all([+ fetchSessionChildren(s.id).catch(swallowAs("web-ui: load subagents", null)),+ needsParent && parentId+ ? fetchSessionRow({ id: parentId }).catch(swallowAs("web-ui: load parent chat", null))+ : Promise.resolve(null),+ ]);+ let list = sessionsState.list.some((row) => row.id === s.id)+ ? sessionsState.list+ : upsertSessions(sessionsState.list, [s]);+ if (children) list = mergeChildren(list, s.id, children);+ if (parent) list = upsertSessions(list, [parent]);+ if (list === sessionsState.list) return;+ sessionsState.list = list;+ renderList();+ for (const conversation of allConversations()) conversation.redraw();+}+export async function openSession(s: CoreSession,entriesPrefetch?: Promise<TranscriptPage | null>,@@ -1793,6 +1910,7 @@ export async function openSessionInto(if (s.id === conv.state.sessionId && !entriesPrefetch) return;refreshSessionsOnOpen();+ void loadSessionNeighbors(s);const opening = s.id;if (tracked) {diff --git a/plugins/web-ui/src/shell.css b/plugins/web-ui/src/shell.cssindex 45df5fbf7..4943ac15b 100644--- a/plugins/web-ui/src/shell.css+++ b/plugins/web-ui/src/shell.css@@ -461,7 +461,6 @@ a.chat-row-open {white-space: nowrap;font-size: var(--font-12-5);}-.recent-project-count,.archived-toggle .archived-count {flex: 0 0 auto;min-width: 16px;@@ -469,9 +468,6 @@ a.chat-row-open {font-weight: 400;text-align: center;}-.recent-project-count {- color: var(--muted-foreground);-}.recent-project-new-chat {display: inline-flex;align-items: center;@@ -502,23 +498,10 @@ a.chat-row-open {width: 26px;height: 26px;}-.recent-project-head .recent-project-count {- position: absolute;- inset: 0;- display: flex;- align-items: center;- justify-content: center;- transition: opacity 0.12s ease;-}.recent-project-head .session-menu-btn {position: absolute;inset: 0;}-.recent-project-head:hover .recent-project-count,-.recent-project-head .session-menu.menu-open .recent-project-count,-.recent-project-head .session-menu:focus-within .recent-project-count {- opacity: 0;-}.recent-project-head:hover .session-menu-btn,.recent-project-head .session-menu.menu-open .session-menu-btn {opacity: 1;@@ -1033,6 +1016,10 @@ a.chat-row-open {.archived-toggle:hover {color: var(--foreground);}+.archived-toggle:disabled {+ color: var(--muted-foreground);+ cursor: progress;+}.archived-toggle:focus-visible {background: var(--secondary);}@@ -5229,9 +5216,6 @@ a.connector-widget:focus-visible {.sidebar .session-menu-btn {opacity: 1;}- .recent-project-head .recent-project-count {- opacity: 0;- }}@media (max-width: 560px) {diff --git a/plugins/web-ui/src/shell.ts b/plugins/web-ui/src/shell.tsindex 06f92cd44..0025c8d26 100644--- a/plugins/web-ui/src/shell.ts+++ b/plugins/web-ui/src/shell.ts@@ -44,9 +44,10 @@ import {type PendingApproval,type TranscriptPage,loadChatPrefs,+ fetchSessionRow,} from "./core-bridge";import { seedRuntimeConfig } from "./runtime-config-store";-import { errMessage, swallow } from "../../chassis/src/errors";+import { errMessage, swallow, swallowAs } from "../../chassis/src/errors";import { brandMark, brandName } from "./ui";import { icon } from "./icons";import { PHONE_MAX_WIDTH, trackVisualViewport } from "./viewport";@@ -998,11 +999,13 @@ function warmDeferredChunks(): void {else setTimeout(warm, 1500);}-function openAppEditChat(slug: string): void {+async function openAppEditChat(slug: string): Promise<void> {const user = appState.me?.user ?? "anon";const threadRef = `web:${user}:app-edit:${slug}`;if (storedDraft(threadRef) === `Update my deployed app "${slug}": `) saveDraft(threadRef, "");- const existing = sessionsState.list.find((s) => s.threadRef === threadRef);+ const existing =+ sessionsState.list.find((s) => s.threadRef === threadRef) ??+ (await fetchSessionRow({ threadRef }).catch(swallowAs("web-ui: find app edit chat", null)));if (existing) {void openSession(existing);return;@@ -1208,7 +1211,7 @@ export async function boot(): Promise<void> {if (wanted === "app-edit") {const slug = (params.get("slug") ?? "").toLowerCase();if (/^[a-z0-9-]{1,63}$/.test(slug)) {- openAppEditChat(slug);+ await openAppEditChat(slug);if (params.get("embed") === "1")watchAppAnnotations(slug, (text, files, id, remove) =>mainConversation().composer.addAnnotations(text, files, id, remove),diff --git a/plugins/web-ui/test/activity-folding.test.ts b/plugins/web-ui/test/activity-folding.test.tsindex 16ab469ad..ef270df4f 100644--- a/plugins/web-ui/test/activity-folding.test.ts+++ b/plugins/web-ui/test/activity-folding.test.ts@@ -36,11 +36,9 @@ for (const count of [1, 2]) {}test("a subagent header includes its parent title in the breadcrumb", async () => {- const parent = { ...SESSION, id: "parent", title: "Build report" };- const h = await harness({- path: `/s/${SESSION.id}`,- listSessions: [parent, { ...SESSION, parentSessionId: parent.id }],- });+ const parent = { ...SESSION, id: "parent", threadRef: "web:tester:parent", title: "Build report" };+ const child = { ...SESSION, type: "dm" as const, createdAt: 1, parentSessionId: parent.id };+ const h = await harness({ path: `/s/${SESSION.id}`, session: child, listSessions: [parent, child] });try {h.releaseSessions();await h.boot();diff --git a/plugins/web-ui/test/approval-handoff.test.ts b/plugins/web-ui/test/approval-handoff.test.tsindex 1ee8e7208..1821c1dc6 100644--- a/plugins/web-ui/test/approval-handoff.test.ts+++ b/plugins/web-ui/test/approval-handoff.test.ts@@ -114,7 +114,7 @@ test("approval handoff unlocks queue and steer without losing pending decisions"await refreshGate?.promise;return Response.json({ session: row, entries, earlierEntries: 0 });}- if (path === "/api/sessions") return Response.json({ sessions: [row] });+ if (path.startsWith("/api/sessions?")) return Response.json({ sessions: [row] });if (path === "/api/contexts") return Response.json({ contexts: [] });throw new Error(`Unexpected request: ${path}`);};diff --git a/plugins/web-ui/test/completed-run-recovery-ui.test.ts b/plugins/web-ui/test/completed-run-recovery-ui.test.tsindex 9769d7a47..13690c9e8 100644--- a/plugins/web-ui/test/completed-run-recovery-ui.test.ts+++ b/plugins/web-ui/test/completed-run-recovery-ui.test.ts@@ -194,7 +194,7 @@ test("the mounted conversation recovers a saved answer after a local polling timlet releaseList!: () => void;const listHeld = new Promise<void>((resolve) => (releaseList = resolve));globalThis.fetch = async (...args) => {- if (String(args[0]) === "/api/sessions") await listHeld;+ if (String(args[0]).startsWith("/api/sessions?")) await listHeld;return originalFetch(...args);};const originalStream = agent.streamFn;diff --git a/plugins/web-ui/test/deep-link-boot-fixture.ts b/plugins/web-ui/test/deep-link-boot-fixture.tsindex 675b9746f..ba5684c4f 100644--- a/plugins/web-ui/test/deep-link-boot-fixture.ts+++ b/plugins/web-ui/test/deep-link-boot-fixture.ts@@ -18,6 +18,7 @@ export interface Harness {switchView: (view: "chats" | "settings") => void;renderList: () => void;drawChatsPage: () => void;+ renderChatsPage: () => Promise<void>;appState: { currentView: string };sessionsState: { list: Array<{ id: string }>; loaded: boolean; openingKey: string | null };visibleConversation: () => Conversation;@@ -173,6 +174,26 @@ export async function harness(opts: HarnessOptions): Promise<Harness> {const sessionId = decodeURIComponent(path.split("/")[3] ?? "");return Response.json({ approvals: opts.approvals?.(sessionId) ?? [] });}+ if (path.startsWith("/api/sessions/") && path.endsWith("/children")) {+ const all = (opts.listSessions ?? []) as CoreSession[];+ const below = new Set([decodeURIComponent(path.split("/")[3] ?? "")]);+ for (let grew = true; grew;) {+ grew = false;+ for (const row of all)+ if (row.parentSessionId && below.has(row.parentSessionId) && !below.has(row.id)) {+ below.add(row.id);+ grew = true;+ }+ }+ return Response.json({ sessions: all.filter((row) => row.parentSessionId && below.has(row.id)) });+ }+ if (path.startsWith("/api/sessions/row?")) {+ const params = new URL(path, "http://test").searchParams;+ const row = ((opts.listSessions ?? []) as CoreSession[]).find(+ (candidate) => candidate.id === params.get("id") || candidate.threadRef === params.get("threadRef"),+ );+ return row ? Response.json({ session: row }) : Response.json({ error: "not_found" }, { status: 404 });+ }if (path.startsWith(`/api/sessions/${session.id}`)) {if (opts.holdTranscript) await transcriptHeld;if (failuresLeft > 0) {@@ -195,9 +216,11 @@ export async function harness(opts: HarnessOptions): Promise<Harness> {}return Response.json({ session, entries: opts.entries ?? [] });}- if (path === "/api/sessions") {+ if (path.startsWith("/api/sessions?")) {await sessionsHeld;- return Response.json({ sessions: opts.listSessions ?? [] });+ return Response.json(+ sessionPage((opts.listSessions ?? []) as CoreSession[], new URL(path, "http://test").searchParams),+ );}return Response.json({ contexts: opts.contexts ?? [], items: [], crons: [] });};@@ -228,6 +251,7 @@ export async function harness(opts: HarnessOptions): Promise<Harness> {switchView: shell.switchView as Harness["switchView"],renderList: sessions.renderList as () => void,drawChatsPage: sessions.drawChatsPage as () => void,+ renderChatsPage: sessions.renderChatsPage as () => Promise<void>,appState: shell.appState as Harness["appState"],sessionsState: sessions.sessionsState as Harness["sessionsState"],visibleConversation: () =>@@ -252,3 +276,30 @@ export async function harness(opts: HarnessOptions): Promise<Harness> {},};}++function sessionPage(all: CoreSession[], params: URLSearchParams) {+ const activity = (row: CoreSession): number => row.lastActivityAt ?? row.createdAt ?? 0;+ const archived = params.get("status") === "archived";+ const before = params.get("before");+ const limit = Number(params.get("limit") ?? 50);+ let rows = all+ .filter((row) => !row.parentSessionId && Boolean(row.archived) === archived)+ .filter((row) => !params.get("q") || (row.title ?? "").toLowerCase().includes(params.get("q")!.toLowerCase()))+ .filter((row) => !params.get("scope") || row.scopeId === params.get("scope"))+ .filter((row) => params.get("status") !== "waiting" || row.awaitingInput)+ .sort((a, b) => activity(b) - activity(a) || (b.id < a.id ? -1 : 1));+ const pinned = !before && !archived ? rows.filter((row) => row.pinned) : undefined;+ if (!archived) rows = rows.filter((row) => !row.pinned);+ if (before) {+ const dot = before.indexOf(".");+ const [at, id] = [Number(before.slice(0, dot)), before.slice(dot + 1)];+ rows = rows.filter((row) => activity(row) < at || (activity(row) === at && row.id < id));+ }+ const sessions = rows.slice(0, limit);+ const last = sessions[sessions.length - 1];+ return {+ sessions,+ ...(pinned ? { pinned, hasArchived: all.some((row) => row.archived) } : {}),+ nextCursor: rows.length > limit && last ? `${activity(last)}.${last.id}` : null,+ };+}diff --git a/plugins/web-ui/test/deep-link-boot.test.ts b/plugins/web-ui/test/deep-link-boot.test.tsindex 8cffe754f..ae73acbd3 100644--- a/plugins/web-ui/test/deep-link-boot.test.ts+++ b/plugins/web-ui/test/deep-link-boot.test.ts@@ -16,7 +16,7 @@ test("a share link paints its conversation from the transcript, without waiting);assert.match(h.mainText(), /Deep linked chat/);assert.equal(- h.requests.filter((p) => p === "/api/sessions").length,+ h.requests.filter((p) => p.startsWith("/api/sessions?")).length,1,"boot must not stampede the expensive list route",);@@ -194,9 +194,12 @@ test("the sidebar request overlaps runtime settings and paints if it finishes ficonst 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++)+ for (let i = 0; i < 100 && !h.requests.some((p) => p.startsWith("/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");+ assert.ok(+ h.requests.some((p) => p.startsWith("/api/sessions?")),+ "the list must start while runtime settings are pending",+ );h.releaseSessions();await h.sessionsReady();h.releaseRuntimeConfig();diff --git a/plugins/web-ui/test/fork-feedback.test.ts b/plugins/web-ui/test/fork-feedback.test.tsindex 62e2c7aa8..761711ae5 100644--- a/plugins/web-ui/test/fork-feedback.test.ts+++ b/plugins/web-ui/test/fork-feedback.test.ts@@ -69,7 +69,7 @@ test("fork feedback survives delayed success, failure, and navigation", async ()forkedFrom: { sessionId: source.id, title: source.title },forkBoundarySeq: 0,};- const refreshes = h.requests.filter((path) => path === "/api/sessions").length;+ const refreshes = h.requests.filter((path) => path.startsWith("/api/sessions?")).length;finish(outcome === "failure"? Response.json({ error: "Could not copy history" }, { status: 500 })@@ -87,7 +87,7 @@ test("fork feedback survives delayed success, failure, and navigation", async ()assert.match(h.mainText(), /Could not copy history/);} else {assert.equal(h.sessionsState.list.filter((session) => session.id === fork.id).length, 1);- assert.equal(h.requests.filter((path) => path === "/api/sessions").length, refreshes);+ assert.equal(h.requests.filter((path) => path.startsWith("/api/sessions?")).length, refreshes);if (outcome === "navigate") assert.equal(conv.state.threadRef, newThread);else assert.equal(conv.state.sessionId, fork.id);}diff --git a/plugins/web-ui/test/inbox-index-chat.test.ts b/plugins/web-ui/test/inbox-index-chat.test.tsindex be328f460..985c350ac 100644--- a/plugins/web-ui/test/inbox-index-chat.test.ts+++ b/plugins/web-ui/test/inbox-index-chat.test.ts@@ -28,7 +28,7 @@ test("inbox sidebar restores its conversation and releases it on native navigatiif (path.includes("runtime-config")) return Response.json(inboxRuntime);if (path.includes("/approvals")) return Response.json({ approvals: [] });if (path.includes("/sessions/inbox-session")) return Response.json({ session, entries: [], earlierEntries: 4 });- if (path.endsWith("/sessions")) return Response.json({ sessions: [session] });+ if (path.includes("/sessions/row?")) return Response.json({ session });if (path.includes("/runs")) return Response.json({ runs: [] });return Response.json({});};diff --git a/plugins/web-ui/test/post-reply-recovery.test.ts b/plugins/web-ui/test/post-reply-recovery.test.tsindex 05fa29f50..99c40246b 100644--- a/plugins/web-ui/test/post-reply-recovery.test.ts+++ b/plugins/web-ui/test/post-reply-recovery.test.ts@@ -139,7 +139,7 @@ test("post replies remain visible in new and continuing conversations", async (treturn transcriptFails? Response.json({ error: "temporary synthetic outage" }, { status: 503 }): Response.json({ session: row, entries, earlierEntries: 0 });- if (path === "/api/sessions") return Response.json({ sessions: [row] });+ if (path.startsWith("/api/sessions?")) return Response.json({ sessions: [row] });if (path === "/api/contexts") return Response.json({ contexts: [] });throw new Error(`Unexpected request: ${path}`);};diff --git a/plugins/web-ui/test/project-interactions.test.ts b/plugins/web-ui/test/project-interactions.test.tsindex 752739566..2263e872e 100644--- a/plugins/web-ui/test/project-interactions.test.ts+++ b/plugins/web-ui/test/project-interactions.test.ts@@ -71,7 +71,7 @@ test("project interactions preserve focus and successful local mutations", async}return Response.json({ contexts: [personal] });}- if (path === "/api/sessions") return Response.json({ sessions: [] });+ if (path.startsWith("/api/sessions?")) return Response.json({ sessions: [] });if (path === "/api/projects" && init?.method === "POST") {projectCreated();return Response.json({ project });diff --git a/plugins/web-ui/test/search-race.test.ts b/plugins/web-ui/test/search-race.test.tsindex 875bf5f60..f4b93de2a 100644--- a/plugins/web-ui/test/search-race.test.ts+++ b/plugins/web-ui/test/search-race.test.ts@@ -38,7 +38,7 @@ const env = await browserEnv({if (id) opened.push(id);if (path.startsWith("/api/runtime-config")) return Promise.resolve(Response.json(runtimeConfig));if (path.endsWith("/approvals")) return Promise.resolve(Response.json({ approvals: [] }));- if (path === "/api/sessions") return Promise.resolve(Response.json({ sessions }));+ if (path.startsWith("/api/sessions?")) return Promise.resolve(Response.json({ sessions }));if (id) return Promise.resolve(Response.json({ session: sessions.find((s) => s.id === id), entries: [] }));return Promise.resolve(Response.json({}));},diff --git a/plugins/web-ui/test/session-list.test.ts b/plugins/web-ui/test/session-list.test.tsindex 3c42fb081..9cfee801d 100644--- a/plugins/web-ui/test/session-list.test.ts+++ b/plugins/web-ui/test/session-list.test.ts@@ -19,7 +19,9 @@ import {recencyGroup,rowIndicators,recentProjectSeeds,- reconcileSessions,+ mergeChildren,+ mergeFirstPage,+ upsertSessions,splitPinned,watchActivityLabel,withPendingSession,@@ -107,45 +109,102 @@ test("re-adding the same threadRef dedupes rather than duplicating", () => {assert.equal(list.length, 2);});-test("reconcile keeps saved sessions and re-adds unsent pending chats", () => {- const prev = [pending("web:u:a"), pending("web:u:b"), saved("1", "web:u:x")];- const server = [saved("1", "web:u:x")];- const out = reconcileSessions(server, prev);- assert.deepEqual(new Set(out.map((s) => s.threadRef)), new Set(["web:u:a", "web:u:b", "web:u:x"]));-});--test("reconcile drops a pending chat once the server knows its threadRef", () => {- const prev = [pending("web:u:a")];- const server = [saved("9", "web:u:a", "Bubble waffle order")];- const out = reconcileSessions(server, prev);- assert.equal(out.length, 1);- assert.equal(out[0]!.id, "9");- assert.equal(out[0]!.title, "Bubble waffle order");+function at(id: string, threadRef: string, lastActivityAt: number, extra: Partial<CoreSession> = {}): CoreSession {+ return { ...saved(id, threadRef), lastActivityAt, ...extra };+}+const firstPage = { archived: false, floor: null };++test("a first page keeps unsent pending chats and replaces one once the server knows its thread", () => {+ const prev = [pending("web:u:a"), pending("web:u:b"), at("1", "web:u:x", 5)];+ const kept = mergeFirstPage(prev, { sessions: [at("1", "web:u:x", 5)] }, firstPage);+ assert.deepEqual(new Set(kept.map((s) => s.threadRef)), new Set(["web:u:a", "web:u:b", "web:u:x"]));+ const replaced = mergeFirstPage(+ [pending("web:u:a")],+ { sessions: [at("9", "web:u:a", 7, { title: "Bubble waffle order" })] },+ firstPage,+ );+ assert.deepEqual(+ replaced.map((s) => [s.id, s.title]),+ [["9", "Bubble waffle order"]],+ );});-test("reconcile keeps the rows of conversations still on screen when the server omits them", () => {- const prev = [saved("1", "web:u:x"), saved("2", "web:u:y"), saved("3", "web:u:z")];- const server = [saved("3", "web:u:z")];+test("a first page drops rows it covers but no longer returns, and keeps older loaded rows", () => {+ const prev = [at("new", "web:u:new", 30), at("gone", "web:u:gone", 20), at("old", "web:u:old", 5)];+ const page = { sessions: [at("new", "web:u:new", 30), at("mid", "web:u:mid", 10)] };+ assert.deepEqual(+ mergeFirstPage(prev, page, { ...firstPage, floor: 10 })+ .map((s) => s.id)+ .sort(),+ ["mid", "new", "old"],+ "a row older than the page floor was loaded by paging and stays",+ );assert.deepEqual(- reconcileSessions(server, prev, ["1", "2"]).map((s) => s.id),- ["1", "2", "3"],- "every open pane keeps its row, not just one",+ mergeFirstPage(prev, page, firstPage)+ .map((s) => s.id)+ .sort(),+ ["mid", "new"],+ "a page that reached the end covers everything",);+});++test("a first page keeps open conversations, children and archived rows it doesn't cover", () => {+ const prev = [+ at("open", "web:u:open", 20),+ at("child", "subagent:root:1", 20, { parentSessionId: "open" }),+ at("archived", "web:u:archived", 20, { archived: true }),+ at("pinned", "web:u:pinned", 1, { pinned: true }),+ ];assert.deepEqual(- reconcileSessions(server, prev).map((s) => s.id),- ["3"],- "a row nobody is reading still goes when the server drops it",+ mergeFirstPage(prev, { sessions: [], pinned: [] }, firstPage, ["open"])+ .map((s) => s.id)+ .sort(),+ ["archived", "child", "open"],+ "a pinned row the pinned list no longer has is stale; the rest are outside the page",);+});++test("a thread the server now answers for under a new id doesn't render twice", () => {+ const prev = [at("1", "web:u:x", 5), at("2", "web:u:y", 5)];assert.deepEqual(- reconcileSessions([saved("9", "web:u:x")], prev, ["1"]).map((s) => s.id),- ["9"],- "a threadRef the server now answers for under a new id must not render twice",+ mergeFirstPage(prev, { sessions: [at("9", "web:u:x", 6), at("2", "web:u:y", 5)] }, firstPage, ["1"])+ .map((s) => s.id)+ .sort(),+ ["2", "9"],);});-test("reconcile against an empty prev is just the server list", () => {- const server = [saved("1", "web:u:x"), saved("2", "web:u:y")];- assert.deepEqual(reconcileSessions(server, []), server);+test("children of a root are replaced by what the server returns", () => {+ const prev = [+ at("root", "web:u:root", 9),+ at("a", "subagent:root:a", 1, { parentSessionId: "root" }),+ at("a1", "subagent:a:1", 1, { parentSessionId: "a" }),+ at("other", "subagent:other:1", 1, { parentSessionId: "elsewhere" }),+ ];+ const next = mergeChildren(prev, "root", [at("b", "subagent:root:b", 2, { parentSessionId: "root", working: true })]);+ assert.deepEqual(next.map((s) => s.id).sort(), ["b", "other", "root"]);+});++test("a row uses the server's subagent counts until its children are loaded", () => {+ const row = at("root", "web:u:root", 9, { subagents: { running: 2, waiting: 1 } });+ assert.equal(rowIndicators(row, null, [row]).awaiting, true);+ assert.equal(rowIndicators(row, null, [row]).background?.subagents, 3);+ const loaded = [row, at("c", "subagent:root:c", 1, { parentSessionId: "root", working: true })];+ assert.equal(rowIndicators(row, null, loaded).awaiting, false, "loaded children are fresher than the rollup");+ assert.equal(rowIndicators(row, null, loaded).background?.subagents, 1);+});++test("upsertSessions replaces rows by id and keeps the rest", () => {+ const prev = [at("1", "web:u:x", 1), at("2", "web:u:y", 1)];+ const next = upsertSessions(prev, [at("2", "web:u:y", 3, { title: "Renamed" })]);+ assert.deepEqual(+ next.map((s) => [s.id, s.title ?? null]),+ [+ ["1", null],+ ["2", "Renamed"],+ ],+ );+ assert.equal(upsertSessions(prev, []), prev);});test("bumpActivity stamps lastActivityAt on the matching row only", () => {@@ -245,9 +304,9 @@ test("applySessionState: frames without `at` (and rows fresh from a snapshot) stassert.equal(out[0]!.working, true, "an unstamped frame applies unconditionally");});-test("reconcile replaces a pushed working state with server truth", () => {+test("a first page replaces a pushed working state with server truth", () => {const { list: prev } = applySessionState([saved("1", "web:u:x")], { threadRef: "web:u:x", state: "working" });- const out = reconcileSessions([saved("1", "web:u:x")], prev);+ const out = mergeFirstPage(prev, { sessions: [saved("1", "web:u:x")] }, firstPage);assert.equal(out[0]!.working, undefined, "server row (no working flag) supersedes the pushed state");});@@ -304,9 +363,9 @@ test("recencyGroup treats a future timestamp (optimistic bump) as Today", () =>assert.equal(recencyGroup(now + 60_000, now), "Today");});-test("reconcile replaces an optimistic working stamp with server truth", () => {+test("a first page replaces an optimistic working stamp with server truth", () => {const prev = markWorking([saved("1", "web:u:x")], "web:u:x");- const out = reconcileSessions([saved("1", "web:u:x")], prev);+ const out = mergeFirstPage(prev, { sessions: [saved("1", "web:u:x")] }, firstPage);assert.equal(out[0]!.working, undefined, "server row (no working flag) supersedes the stamp");});diff --git a/plugins/web-ui/test/sessions-refresh-race.test.ts b/plugins/web-ui/test/sessions-refresh-race.test.tsindex 70d25ad44..dd0940729 100644--- a/plugins/web-ui/test/sessions-refresh-race.test.ts+++ b/plugins/web-ui/test/sessions-refresh-race.test.ts@@ -36,7 +36,7 @@ test("session refresh bursts share one trailing read and observe its fresh list"const pending: Array<(r: Response) => void> = [];globalThis.fetch = async (input) => {const path = String(input);- if (path === "/api/sessions") return new Promise<Response>((resolve) => pending.push(resolve));+ if (path.startsWith("/api/sessions?")) return new Promise<Response>((resolve) => pending.push(resolve));if (path === "/api/contexts") return Response.json({ contexts: [] });throw new Error(`Unexpected request: ${path}`);};@@ -144,7 +144,7 @@ test("opening a conversation joins the first list load and leaves a current listconst pending: Array<(r: Response) => void> = [];globalThis.fetch = async (input) => {const path = String(input);- if (path === "/api/sessions") return new Promise<Response>((resolve) => pending.push(resolve));+ if (path.startsWith("/api/sessions?")) return new Promise<Response>((resolve) => pending.push(resolve));if (path === "/api/contexts") return Response.json({ contexts: [] });throw new Error(`Unexpected request: ${path}`);};@@ -239,7 +239,7 @@ test("an open that joined a refresh whose answer was discarded asks again itselfconst pending: Array<(r: Response) => void> = [];globalThis.fetch = async (input) => {const path = String(input);- if (path === "/api/sessions") return new Promise<Response>((resolve) => pending.push(resolve));+ if (path.startsWith("/api/sessions?")) return new Promise<Response>((resolve) => pending.push(resolve));if (path === "/api/contexts") return Response.json({ contexts: [] });throw new Error(`Unexpected request: ${path}`);};diff --git a/plugins/web-ui/test/sidebar-surface-default.test.ts b/plugins/web-ui/test/sidebar-surface-default.test.tsindex 8fcf0787d..47ac1419b 100644--- a/plugins/web-ui/test/sidebar-surface-default.test.ts+++ b/plugins/web-ui/test/sidebar-surface-default.test.ts@@ -55,7 +55,7 @@ for (const stored of [null, "1", "0", "unavailable"] as const) {];const env = await browserEnv({fetch: async (input) => {- if (String(input) === "/api/sessions") return Response.json({ sessions });+ if (String(input).startsWith("/api/sessions?")) return Response.json({ sessions });if (String(input) === "/api/contexts") return Response.json({ contexts: [] });throw new Error(`Unexpected request: ${input}`);},@@ -86,10 +86,12 @@ for (const stored of [null, "1", "0", "unavailable"] as const) {assert.equal(document.querySelector('[data-view="inbox"]'), null);assert.equal(document.querySelector('[data-view="calendar"]'), null);sidebar.setWebOnly(true);+ await sidebar.refreshSessions();assert.deepEqual(rowIds(), ["web"]);sidebar.revealSessionSurface(sessions.find((s) => s.id === "cron-run"));assert.equal(sidebar.sessionsState.webOnly, true);sidebar.setWebOnly(false);+ await sidebar.refreshSessions();assert.deepEqual(rowIds(), ["web", "slack", "group"]);assert.ok(slackRow()?.querySelector(".slack-mark"));assert.equal(slackRow()?.querySelector(".ro-lock"), null);diff --git a/plugins/web-ui/test/sidebar-window.test.ts b/plugins/web-ui/test/sidebar-window.test.tsindex 552c3f7cc..f12827526 100644--- a/plugins/web-ui/test/sidebar-window.test.ts+++ b/plugins/web-ui/test/sidebar-window.test.ts@@ -22,7 +22,7 @@ function button(root: Element, label: string): HTMLButtonElement {return found;}-test("sidebar batches retain pinned, open and selected chats, full counts and archived expansion", async () => {+test("the sidebar pages chats from the server and keeps pinned, open and selected chats and archived expansion", async () => {const list = sessions(230);list[148]!.pinned = true;list[149]!.pinned = true;@@ -42,14 +42,19 @@ test("sidebar batches retain pinned, open and selected chats, full counts and arawait 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);+ const loading = button(sidebar, "Show more conversations");+ assert.ok(loading.disabled && loading.getAttribute("aria-busy") === "true");+ assert.ok(loading.querySelector(".thinking-sheen"));+ await until(+ () => sidebar.querySelectorAll(".session-row").length === 103,+ () => sidebar.querySelectorAll(".session-row").length,+ );for (const [id, shift] of [["chat-90", false],["chat-92", true],@@ -73,7 +78,7 @@ test("sidebar batches retain pinned, open and selected chats, full counts and arthreadRef: `new-${item.threadRef}`,createdAt: item.createdAt + 10_000,})),- ...list,+ ...h.sessionsState.list,];h.renderList();assert.deepEqual(@@ -81,19 +86,26 @@ test("sidebar batches retain pinned, open and selected chats, full counts and ar["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);+ const archivedToggle = button(sidebar, "Archived");+ archivedToggle.click();+ await until(+ () => sidebar.querySelectorAll(".archived-children .session-row").length === 50,+ () => sidebar.querySelectorAll(".archived-children .session-row").length,+ );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();+ await until(+ () => sidebar.querySelectorAll(".archived-children .session-row").length === 80,+ () => sidebar.querySelectorAll(".archived-children .session-row").length,+ );+ assert.equal(sidebar.querySelector(".archived-count"), null);+ button(sidebar, "Archived").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 () => {+test("chat browsing pages rows from the server and searches the complete history", async () => {const list = sessions(125);list[124]!.title = "Older matching conversation";const h = await harness({ path: "/settings", listSessions: list });@@ -102,73 +114,25 @@ test("chat browsing batches rows while search still covers the complete history"await h.boot();await h.sessionsReady();h.appState.currentView = "chats";- h.drawChatsPage();+ void h.renderChatsPage();const main = document.querySelector("#main")!;- assert.equal(main.querySelectorAll(".chat-row").length, 50);+ await until(() => main.querySelectorAll(".chat-row").length === 50);button(main, "Show more conversations").click();- assert.equal(main.querySelectorAll(".chat-row").length, 100);+ await until(() => 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);+ await until(() => 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);+ await until(() => main.querySelectorAll(".chat-row").length === 50);} 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();- }-});+async function until(check: () => boolean, describe: () => unknown = () => ""): Promise<void> {+ for (let i = 0; i < 200 && !check(); i++) await new Promise((resolve) => setTimeout(resolve, 10));+ assert.ok(check(), `condition never held ${String(describe())}`);+}diff --git a/plugins/web-ui/test/single-view-navigation.test.ts b/plugins/web-ui/test/single-view-navigation.test.tsindex 5010e2df6..bb15e93fb 100644--- a/plugins/web-ui/test/single-view-navigation.test.ts+++ b/plugins/web-ui/test/single-view-navigation.test.ts@@ -23,7 +23,7 @@ const env = await browserEnv({effective: { harnessId: "pi", modelId: "m" },});if (path.endsWith("/approvals")) return Response.json({ approvals: [] });- if (path === "/api/sessions") return Response.json({ sessions: known });+ if (path.startsWith("/api/sessions?")) return Response.json({ sessions: known });const id = path.match(/^\/api\/sessions\/([^/?]+)/)?.[1];if (id) return Response.json({ session: known.find((s) => s.id === id), entries: [] });return Response.json({ contexts: [], items: [], crons: [] });diff --git a/plugins/web-ui/test/swarm-approvals.test.ts b/plugins/web-ui/test/swarm-approvals.test.tsindex d0cd290a6..78bf647bc 100644--- a/plugins/web-ui/test/swarm-approvals.test.ts+++ b/plugins/web-ui/test/swarm-approvals.test.ts@@ -92,7 +92,7 @@ test("worker transcripts allow approvals without enabling the composer", async (if (path.startsWith("/api/sessions/s1")) {return Response.json({ session: row, entries, earlierEntries: 0 });}- if (path === "/api/sessions") return Response.json({ sessions: [row] });+ if (path.startsWith("/api/sessions?")) return Response.json({ sessions: [row] });if (path === "/api/contexts") return Response.json({ contexts: [] });throw new Error(`Unexpected request: ${path}`);};diff --git a/src/api/app-sessions.ts b/src/api/app-sessions.tsindex 2a28d4979..bdadbd21c 100644--- a/src/api/app-sessions.ts+++ b/src/api/app-sessions.ts@@ -3,7 +3,8 @@ import { createCurrentScopeMembers } from "../resolution/scope-membership.ts";import { notifyDeploymentShared } from "../deploy/share-notice.ts";import { deploymentShareScope } from "../deploy/email-access.ts";import { workingSessionThreadRefs } from "../sessions/session-syscalls.ts";-import type { PendingApprovalRecord } from "../types.ts";+import type { ParticipantPageQuery } from "../sessions/session-store.ts";+import type { PendingApprovalRecord, Session } from "../types.ts";import { orgId as orgIdOf } from "../config.ts";import { parseScopeId, scopeId } from "../types.ts";import { fileArtifactId, artifactPath } from "../files/file-artifact-store.ts";@@ -59,6 +60,8 @@ function coversTailWindow(entries: readonly { type: string }[], tailTurns: numbeconst GOAL_CANCEL_LEASE_WAIT_MS = 30_000;+const MAX_LISTED_CHILDREN = 500;+export function createSessionMethods(deps: AppDeps,h: AppHelpers,@@ -75,6 +78,9 @@ export function createSessionMethods(| "uploadFileForViewer"| "openFileForViewer"| "listSessions"+ | "listSessionPage"+ | "sessionChildren"+ | "sessionRow"| "searchSessions"| "sessionBackground"| "readSessionBackgroundOutput"@@ -247,6 +253,127 @@ export function createSessionMethods(}));};+ async function decorateSessions(principalId: string, all: Session[]): Promise<Session[]> {+ const visibleById = new Map(all.map((session) => [session.id, session]));+ const roots = all.filter((session) => !session.parentSessionId).map((session) => session.id);+ const descendants = roots.length ? await deps.sessions.descendantsOf(roots) : [];+ const descendantIds = new Set(descendants.map((d) => d.id));+ const approvalRows: PendingApprovalRecord[] = [];+ const approvalIds = [...visibleById.keys(), ...descendantIds];+ const approvals = approvalIds.length+ ? await deps.approvals?.selectEntries({ where: { field: "sessionId", anyOfFold: approvalIds } })+ : [];+ for (const [, record] of approvals ?? []) {+ const session = visibleById.get(record.sessionId);+ if (+ session+ ? await approvalRecordIsCurrent(record, session)+ : descendantIds.has(record.sessionId) && (await approvalRecordIsCurrent(record))+ )+ approvalRows.push(record);+ }+ const waiting = new Set(approvalRows.filter((r) => r.blocksInput !== false).map((r) => r.sessionId));+ const workingThreadRefs = await workingSessionThreadRefs(deps.sessions, deps.runs, waiting);+ const sharedAccess = new Map<string, Promise<boolean>>(+ all+ .filter((s) => {+ const { kind, ref } = parseScopeId(s.scopeId);+ return kind === "group" && projectIdFromGroupRef(ref);+ })+ .map((s) => [s.scopeId, Promise.resolve(true)]),+ );+ const sessions = await Promise.all(+ all+ .filter(+ (s) =>+ s.hasEntries !== false ||+ Boolean(s.title?.trim()) ||+ workingThreadRefs.has(s.threadRef) ||+ waiting.has(s.id),+ )+ .map(async ({ hasEntries: _hasEntries, ...s }) => ({+ ...s,+ canContinue: await canContinueOnWeb(principalId, s, sharedAccess),+ })),+ );+ const now = Date.now();+ const jobCounts = new Map<string, number>();+ for (const rec of (await deps.processes?.listLive(now)) ?? []) {+ if (rec.kind !== "background" || !rec.sessionRef) continue;+ jobCounts.set(rec.sessionRef, (jobCounts.get(rec.sessionRef) ?? 0) + 1);+ }+ const watchCounts = new Map<string, number>();+ for (const m of (await deps.monitors?.enabled()) ?? []) {+ if (m.expiresAt <= now) continue;+ watchCounts.set(m.threadRef, (watchCounts.get(m.threadRef) ?? 0) + 1);+ }+ const cronCounts = new Map<string, number>();+ for (const c of await deps.crons.list()) {+ if (!cronIsActive(c)) continue;+ for (const ref of new Set([c.destination?.target, c.sessionRef])) {+ if (ref) cronCounts.set(ref, (cronCounts.get(ref) ?? 0) + 1);+ }+ }+ const working = sessions.filter((s) => workingThreadRefs.has(s.threadRef));+ const idleChildren = sessions.filter(+ (s) => s.parentSessionId && !workingThreadRefs.has(s.threadRef) && !waiting.has(s.id),+ );+ const [latestRuns, sessionGoals] = await Promise.all([+ deps.runs.latestForThreads([...working, ...idleChildren].map((s) => s.threadRef)),+ deps.sessions.goals(working.map((s) => s.id)),+ ]);+ const failedChildren = new Set<string>();+ for (const s of idleChildren) {+ const run = latestRuns.get(s.threadRef);+ if (run?.status === "failed" || run?.result?.status === "failed") failedChildren.add(s.id);+ }+ const goals = new Map<+ string,+ { objective: string; activeMs: number; runningSince?: number; floor?: Record<string, number> }+ >();+ for (const s of working) {+ const goal = openGoal(sessionGoals.get(s.id));+ if (!goal) continue;+ const runningSince = latestRuns.get(s.threadRef)?.startedAt ?? undefined;+ if (goal.status === "active")+ goals.set(s.id, {+ objective: goal.objective,+ activeMs: goal.activeMs ?? 0,+ ...(runningSince ? { runningSince: Math.max(runningSince, goal.activeSince ?? goal.createdAt) } : {}),+ ...(goal.floor ? { floor: { ...goal.floor } } : {}),+ });+ }+ const subagents = new Map<string, { running: number; waiting: number }>();+ for (const d of descendants) {+ const isWaiting = waiting.has(d.id);+ if (!isWaiting && !workingThreadRefs.has(d.threadRef)) continue;+ const counts = subagents.get(d.rootId) ?? { running: 0, waiting: 0 };+ counts[isWaiting ? "waiting" : "running"]++;+ subagents.set(d.rootId, counts);+ }+ if (+ subagents.size === 0 &&+ workingThreadRefs.size === 0 &&+ waiting.size === 0 &&+ failedChildren.size === 0 &&+ jobCounts.size === 0 &&+ watchCounts.size === 0 &&+ cronCounts.size === 0+ )+ return sessions;+ return sessions.map((s) => ({+ ...s,+ ...(workingThreadRefs.has(s.threadRef) ? { working: true } : {}),+ ...(waiting.has(s.id) ? { awaitingInput: true } : {}),+ ...(failedChildren.has(s.id) ? { lastTurnFailed: true } : {}),+ ...(jobCounts.has(s.threadRef) ? { backgroundJobs: jobCounts.get(s.threadRef)! } : {}),+ ...(watchCounts.has(s.threadRef) ? { watches: watchCounts.get(s.threadRef)! } : {}),+ ...(cronCounts.has(s.threadRef) ? { crons: cronCounts.get(s.threadRef)! } : {}),+ ...(goals.has(s.id) ? { goal: goals.get(s.id)! } : {}),+ ...(subagents.has(s.id) ? { subagents: subagents.get(s.id)! } : {}),+ }));+ }+return {async getSession(sessionId, window) {const session = await deps.sessions.get(sessionId);@@ -443,106 +570,64 @@ export function createSessionMethods(},async listSessions(principalId) {- const all = await sessionsForViewer(principalId);- const visibleById = new Map(all.map((session) => [session.id, session]));- const approvalRows: PendingApprovalRecord[] = [];- const approvals = visibleById.size- ? await deps.approvals?.selectEntries({ where: { field: "sessionId", anyOfFold: [...visibleById.keys()] } })- : [];- for (const [, record] of approvals ?? []) {- const session = visibleById.get(record.sessionId);- if (session && (await approvalRecordIsCurrent(record, session))) approvalRows.push(record);- }- const waiting = new Set(approvalRows.filter((r) => r.blocksInput !== false).map((r) => r.sessionId));- const workingThreadRefs = await workingSessionThreadRefs(deps.sessions, deps.runs, waiting);- const sharedAccess = new Map<string, Promise<boolean>>(- all- .filter((s) => {- const { kind, ref } = parseScopeId(s.scopeId);- return kind === "group" && projectIdFromGroupRef(ref);- })- .map((s) => [s.scopeId, Promise.resolve(true)]),- );- const sessions = await Promise.all(- all- .filter(- (s) =>- s.hasEntries !== false ||- Boolean(s.title?.trim()) ||- workingThreadRefs.has(s.threadRef) ||- waiting.has(s.id),- )- .map(async ({ hasEntries: _hasEntries, ...s }) => ({- ...s,- canContinue: await canContinueOnWeb(principalId, s, sharedAccess),- })),- );- const now = Date.now();- const jobCounts = new Map<string, number>();- for (const rec of (await deps.processes?.listLive(now)) ?? []) {- if (rec.kind !== "background" || !rec.sessionRef) continue;- jobCounts.set(rec.sessionRef, (jobCounts.get(rec.sessionRef) ?? 0) + 1);- }- const watchCounts = new Map<string, number>();- for (const m of (await deps.monitors?.enabled()) ?? []) {- if (m.expiresAt <= now) continue;- watchCounts.set(m.threadRef, (watchCounts.get(m.threadRef) ?? 0) + 1);- }- const cronCounts = new Map<string, number>();- for (const c of await deps.crons.list()) {- if (!cronIsActive(c)) continue;- for (const ref of new Set([c.destination?.target, c.sessionRef])) {- if (ref) cronCounts.set(ref, (cronCounts.get(ref) ?? 0) + 1);- }+ return decorateSessions(principalId, await sessionsForViewer(principalId));+ },++ async listSessionPage(principalId, query) {+ const filter: ParticipantPageQuery = {+ limit: Math.max(1, Math.min(query.limit, 200)),+ archived: query.status === "archived",+ ...(query.before ? { before: query.before } : {}),+ ...(query.surface ? { surface: query.surface } : {}),+ ...(query.scopeId ? { scopeId: query.scopeId } : {}),+ ...(query.titleQuery ? { titleQuery: query.titleQuery } : {}),+ };+ if (query.status === "waiting") {+ const pending = ((await deps.approvals?.all()) ?? []).filter((record) => record.blocksInput !== false);+ filter.sessionIds = [...new Set(pending.map((record) => record.sessionId))];}- const working = sessions.filter((s) => workingThreadRefs.has(s.threadRef));- const idleChildren = sessions.filter(- (s) => s.parentSessionId && !workingThreadRefs.has(s.threadRef) && !waiting.has(s.id),- );- const [latestRuns, sessionGoals] = await Promise.all([- deps.runs.latestForThreads([...working, ...idleChildren].map((s) => s.threadRef)),- deps.sessions.goals(working.map((s) => s.id)),+ const firstPage = !query.before && query.status !== "archived";+ const [page, pinned, archived] = await Promise.all([+ deps.sessions.listParticipantPage(principalId, {+ ...filter,+ ...(query.status === "archived" ? {} : { pinned: false }),+ }),+ firstPage ? deps.sessions.listParticipantPage(principalId, { ...filter, pinned: true, limit: 200 }) : null,+ firstPage ? deps.sessions.listParticipantPage(principalId, { ...filter, archived: true, limit: 1 }) : null,]);- const failedChildren = new Set<string>();- for (const s of idleChildren) {- const run = latestRuns.get(s.threadRef);- if (run?.status === "failed" || run?.result?.status === "failed") failedChildren.add(s.id);- }- const goals = new Map<- string,- { objective: string; activeMs: number; runningSince?: number; floor?: Record<string, number> }- >();- for (const s of working) {- const goal = openGoal(sessionGoals.get(s.id));- if (!goal) continue;- const runningSince = latestRuns.get(s.threadRef)?.startedAt ?? undefined;- if (goal.status === "active")- goals.set(s.id, {- objective: goal.objective,- activeMs: goal.activeMs ?? 0,- ...(runningSince ? { runningSince: Math.max(runningSince, goal.activeSince ?? goal.createdAt) } : {}),- ...(goal.floor ? { floor: { ...goal.floor } } : {}),- });- }- if (- workingThreadRefs.size === 0 &&- waiting.size === 0 &&- failedChildren.size === 0 &&- jobCounts.size === 0 &&- watchCounts.size === 0 &&- cronCounts.size === 0- )- return sessions;- return sessions.map((s) => ({- ...s,- ...(workingThreadRefs.has(s.threadRef) ? { working: true } : {}),- ...(waiting.has(s.id) ? { awaitingInput: true } : {}),- ...(failedChildren.has(s.id) ? { lastTurnFailed: true } : {}),- ...(jobCounts.has(s.threadRef) ? { backgroundJobs: jobCounts.get(s.threadRef)! } : {}),- ...(watchCounts.has(s.threadRef) ? { watches: watchCounts.get(s.threadRef)! } : {}),- ...(cronCounts.has(s.threadRef) ? { crons: cronCounts.get(s.threadRef)! } : {}),- ...(goals.has(s.id) ? { goal: goals.get(s.id)! } : {}),- }));+ const viewable = async (rows: Session[]) => {+ const allowed = await Promise.all(+ rows.map(async (row) => (await managedProjectMembership(row.scopeId, principalId)) !== false),+ );+ return rows.filter((_, index) => allowed[index]);+ };+ const rows = await viewable([...(pinned?.sessions ?? []), ...page.sessions]);+ let decorated = await decorateSessions(principalId, rows);+ if (query.status === "waiting") decorated = decorated.filter((s) => s.awaitingInput);+ const pinnedIds = new Set(pinned?.sessions.map((s) => s.id) ?? []);+ return {+ sessions: decorated.filter((s) => !pinnedIds.has(s.id)),+ ...(pinned ? { pinned: decorated.filter((s) => pinnedIds.has(s.id)) } : {}),+ ...(archived ? { hasArchived: archived.sessions.length > 0 } : {}),+ next: page.next,+ };+ },++ async sessionChildren(principalId, sessionId) {+ const root = await sessionForViewer(sessionId, principalId);+ if (!root) return null;+ const children = await deps.sessions.listDescendantsForParticipant(root.id, principalId, MAX_LISTED_CHILDREN);+ return decorateSessions(principalId, children);+ },++ async sessionRow(principalId, ref) {+ const id = ref.id ?? (ref.threadRef ? (await deps.sessions.getByThread(ref.threadRef))?.id : undefined);+ if (!id) return null;+ const session = await sessionForViewer(id, principalId);+ if (!session) return null;+ const { spawnMeta: _spawnMeta, clientTools: _clientTools, ...row } = session;+ const [decorated] = await decorateSessions(principalId, [row]);+ return decorated ?? null;},async searchSessions(principalId, query, limit = SEARCH_HIT_LIMIT): Promise<SessionSearchHit[]> {diff --git a/src/api/app-types.ts b/src/api/app-types.tsindex 7357c8b31..d4d5df76a 100644--- a/src/api/app-types.ts+++ b/src/api/app-types.ts@@ -367,6 +367,9 @@ export interface App {listConversationPins(threadRef: string, reader: string): Promise<SessionPinView[] | null>;unpinConversationItem(threadRef: string, pinId: string): Promise<boolean | null>;listSessions(principalId: string): Promise<Session[]>;+ listSessionPage(principalId: string, query: SessionPageQuery): Promise<SessionPageResult>;+ sessionChildren(principalId: string, sessionId: string): Promise<Session[] | null>;+ sessionRow(principalId: string, ref: { id?: string; threadRef?: string }): Promise<Session | null>;searchResources(principalId: string,query: string,@@ -793,3 +796,21 @@ export class SoulVersionConflictError extends Error {export const CONTEXT_REQUEST_EXPIRY_MS = 2 * 60_000;export const STALE_LEASE_GRACE_MS = 30_000;++interface SessionPageQuery {+ limit: number;+ before?: { activity: number; id: string };+ status?: SessionPageStatus;+ surface?: string;+ scopeId?: ScopeId;+ titleQuery?: string;+}++export type SessionPageStatus = "active" | "archived" | "waiting";++interface SessionPageResult {+ sessions: Session[];+ pinned?: Session[];+ next: { activity: number; id: string } | null;+ hasArchived?: boolean;+}diff --git a/src/api/routes/surface.ts b/src/api/routes/surface.tsindex 7627e9e25..57b385eeb 100644--- a/src/api/routes/surface.ts+++ b/src/api/routes/surface.ts@@ -19,7 +19,7 @@ import {} from "../../model/pi-models.ts";import { builtInModelCatalog, selectableCatalogForHarness, selectableModelCatalog } from "../../model/model-catalog.ts";import { errMessage } from "../../util/errors.ts";-import { SoulUpdateDeniedError } from "../app-types.ts";+import { SoulUpdateDeniedError, type SessionPageStatus } from "../app-types.ts";import { parsePinnedSkills } from "../../skills/materialize.ts";import { renderAgentApis } from "../agent-api-catalog.ts";import { mintCapabilityToken, CAPABILITY_TTL_MS } from "../../auth/capability-token.ts";@@ -484,11 +484,67 @@ async function patchAgentConversation(ctx: ApiCtx): Promise<void> {});}+const DEFAULT_SESSION_PAGE = 50;+async function listSessions(ctx: ApiCtx): Promise<void> {const { res, app, url } = ctx;const principalId = url.searchParams.get("principalId");if (!principalId) return sendJson(res, 400, { error: "bad_request", message: "principalId required" });- return sendJson(res, 200, { sessions: await app.listSessions(principalId) });+ const n = Number(url.searchParams.get("limit") ?? DEFAULT_SESSION_PAGE);+ const before = parseSessionCursor(url.searchParams.get("before"));+ const status = url.searchParams.get("status") ?? "active";+ if (!Number.isInteger(n) || n < 1 || before === null || !isSessionPageStatus(status))+ return sendJson(res, 400, {+ error: "bad_request",+ message: "limit must be a positive integer, before a cursor, status active, archived or waiting",+ });+ const page = await app.listSessionPage(principalId, {+ limit: n,+ ...(before ? { before } : {}),+ status,+ ...(url.searchParams.get("surface") ? { surface: url.searchParams.get("surface")! } : {}),+ ...(url.searchParams.get("scope") ? { scopeId: url.searchParams.get("scope")! } : {}),+ ...(url.searchParams.get("q")?.trim() ? { titleQuery: url.searchParams.get("q")!.trim() } : {}),+ });+ return sendJson(res, 200, {+ sessions: page.sessions,+ ...(page.pinned ? { pinned: page.pinned } : {}),+ ...(page.hasArchived !== undefined ? { hasArchived: page.hasArchived } : {}),+ nextCursor: page.next ? `${page.next.activity}.${page.next.id}` : null,+ });+}++function isSessionPageStatus(value: string): value is SessionPageStatus {+ return value === "active" || value === "archived" || value === "waiting";+}++function parseSessionCursor(raw: string | null): { activity: number; id: string } | undefined | null {+ if (raw === null || raw === "") return undefined;+ const dot = raw.indexOf(".");+ const activity = Number(raw.slice(0, dot));+ const id = raw.slice(dot + 1);+ return dot > 0 && Number.isSafeInteger(activity) && id ? { activity, id } : null;+}++async function listSessionChildren(ctx: ApiCtx): Promise<void> {+ const { res, app, url, params } = ctx;+ const principalId = url.searchParams.get("principalId");+ if (!principalId) return sendJson(res, 400, { error: "bad_request", message: "principalId required" });+ const children = await app.sessionChildren(principalId, params.id!);+ if (!children) return sendJson(res, 404, { error: "not_found" });+ return sendJson(res, 200, { sessions: children });+}++async function getSessionRow(ctx: ApiCtx): Promise<void> {+ const { res, app, url } = ctx;+ const principalId = url.searchParams.get("principalId");+ const id = url.searchParams.get("id") ?? undefined;+ const threadRef = url.searchParams.get("threadRef") ?? undefined;+ if (!principalId || (!id && !threadRef))+ return sendJson(res, 400, { error: "bad_request", message: "principalId and id or threadRef required" });+ const session = await app.sessionRow(principalId, id ? { id } : { threadRef });+ if (!session) return sendJson(res, 404, { error: "not_found" });+ return sendJson(res, 200, { session: session });}async function searchResources(ctx: ApiCtx): Promise<void> {@@ -1405,6 +1461,8 @@ export const surfaceRoutes: ReadonlyArray<Route<ApiCtx>> = [{ method: "GET", path: "/v1/resources/search", auth: "source", handle: searchResources },{ method: "GET", path: "/v1/sessions/search", auth: "source", handle: searchSessions },{ method: "GET", path: "/v1/sessions", auth: "source", handle: listSessions },+ { method: "GET", path: "/v1/sessions/row", auth: "source", handle: getSessionRow },+ { method: "GET", path: "/v1/sessions/:id/children", auth: "source", handle: listSessionChildren },{ method: "GET", path: "/v1/contexts", auth: "source", handle: listContexts },{ method: "GET", path: "/v1/scope-resources", auth: "source", handle: listScopeResources },{ method: "GET", path: "/v1/memory", auth: "source", handle: selfMemory },diff --git a/src/sessions/items.ts b/src/sessions/items.tsindex 399821dda..4ab0e209f 100644--- a/src/sessions/items.ts+++ b/src/sessions/items.ts@@ -240,7 +240,8 @@ export function entryFromItem(};}-export const USER_KINDS = "('UserMessage', 'SteeringMessage')";+export const USER_ITEM_KINDS: readonly string[] = ["UserMessage", "SteeringMessage"];+export const USER_KINDS = `(${USER_ITEM_KINDS.map((kind) => `'${kind}'`).join(", ")})`;export const AGENT_REPLY_ITEM = (col: string): string => `${col}.kind = 'AgentMessage'`;export const SEARCHABLE_ITEM = (col: string): string =>`(${col}.kind IN ('UserMessage','SteeringMessage','AgentMessage') AND ${col}.variant IS DISTINCT FROM 'files_delivered' AND ${col}.text IS NOT NULL)`;diff --git a/src/sessions/memory-session-store.ts b/src/sessions/memory-session-store.tsindex f68c0962f..7c1306f3c 100644--- a/src/sessions/memory-session-store.ts+++ b/src/sessions/memory-session-store.ts@@ -15,7 +15,9 @@ import type {NewLlmRequest,NewSearchEntry,NewSessionPin,+ ParticipantPage,ParticipantScope,+ SessionDescendant,ParticipantWindow,SessionPage,SessionStore,@@ -521,6 +523,77 @@ export function createMemorySessionStore(opts: StoreOptions = {}): SessionStorereturn [...byScope.values()];},+ async listParticipantPage(principalId, query): Promise<ParticipantPage> {+ const automation = new Set(["cron", "webhook", "loop"]);+ const title = query.titleQuery?.trim().toLowerCase();+ const ids = query.sessionIds ? new Set(query.sessionIds) : null;+ const key = (s: Session): [number, string] => [s.lastActivityAt ?? s.createdAt, s.id];+ const after = (s: Session): boolean => {+ if (!query.before) return true;+ const [activity, id] = key(s);+ return activity < query.before.activity || (activity === query.before.activity && id < query.before.id);+ };+ const rows = [...(participants.get(principalId) ?? [])]+ .map((id) => participantSession(id, principalId))+ .filter((s): s is Session => s !== null)+ .filter(+ (s) =>+ !s.parentSessionId &&+ !(s.surface && automation.has(s.surface)) &&+ ((entries.get(s.id)?.length ?? 0) > 0 || Boolean(s.title?.trim())) &&+ Boolean(s.archived) === (query.archived === true) &&+ (query.pinned === undefined || Boolean(s.pinned) === query.pinned) &&+ (query.surface === undefined || s.surface === query.surface) &&+ (query.scopeId === undefined || s.scopeId === query.scopeId) &&+ (!ids || ids.has(s.id)) &&+ (!title || `${s.title ?? ""} ${s.channelName ?? ""}`.toLowerCase().includes(title)) &&+ after(s),+ )+ .sort((a, b) => {+ const [aa, ai] = key(a);+ const [ba, bi] = key(b);+ if (ba !== aa) return ba - aa;+ if (bi === ai) return 0;+ return bi < ai ? -1 : 1;+ })+ .map(({ spawnMeta: _spawnMeta, clientTools: _clientTools, ...listed }) => listed);+ const limit = Math.max(1, Math.min(Math.floor(query.limit), 200));+ const page = rows.slice(0, limit);+ const last = page[page.length - 1];+ return {+ sessions: page,+ next: rows.length > limit && last ? { activity: key(last)[0], id: last.id } : null,+ };+ },++ async descendantsOf(rootIds): Promise<SessionDescendant[]> {+ const out: SessionDescendant[] = [];+ const seen = new Set(rootIds);+ let frontier = rootIds.map((id) => ({ id, rootId: id }));+ while (frontier.length) {+ const next: { id: string; rootId: string }[] = [];+ for (const s of sessions.values()) {+ const parent = frontier.find((f) => f.id === s.parentSessionId);+ if (!parent || seen.has(s.id)) continue;+ seen.add(s.id);+ out.push({ id: s.id, rootId: parent.rootId, threadRef: s.threadRef });+ next.push({ id: s.id, rootId: parent.rootId });+ }+ frontier = next;+ }+ return out;+ },++ async listDescendantsForParticipant(rootId, principalId, limit) {+ const ids = (await this.descendantsOf([rootId])).map((d) => d.id).slice(0, Math.max(0, Math.floor(limit)));+ return ids+ .filter((id) => participants.get(principalId)?.has(id))+ .map((id) => participantSession(id, principalId))+ .filter((s): s is Session => s !== null)+ .map(({ spawnMeta: _spawnMeta, clientTools: _clientTools, ...listed }) => listed)+ .sort((a, b) => a.createdAt - b.createdAt || (a.id < b.id ? -1 : 1));+ },+async getForParticipant(sessionId, principalId) {if (!participants.get(principalId)?.has(sessionId)) return null;return participantSession(sessionId, principalId);diff --git a/src/sessions/postgres-session-store.ts b/src/sessions/postgres-session-store.tsindex e1ccc0cce..cdd5d18e0 100644--- a/src/sessions/postgres-session-store.ts+++ b/src/sessions/postgres-session-store.ts@@ -1,6 +1,7 @@import { DIRECTORY_MIGRATIONS } from "../directory/postgres-directory-store.ts";import { randomUUID } from "node:crypto";import { jsonbStringify } from "../persistence/durable-map.ts";+import { likeContains } from "../persistence/like.ts";import { createPgPool, type PoolClient, withPgTransaction } from "../persistence/pg-pool.ts";import { jsonbSafeStringify, pgTextSafe } from "../util/text.ts";import { reportFailure } from "../util/errors.ts";@@ -13,7 +14,10 @@ import type {EntrySearchHit,ScopeActivity,DistinctScope,+ ParticipantPage,+ ParticipantPageQuery,ParticipantScope,+ SessionDescendant,GetEntriesOptions,Lease,LeaseAttempt,@@ -57,6 +61,7 @@ import {AGENT_REPLY_ITEM,SEARCHABLE_ITEM,searchTypeExpr,+ USER_ITEM_KINDS,USER_KINDS,} from "./items.ts";import { SECURITY_SCREEN_STEP, screenPayloadFromEnvelope } from "../security/security-posture.ts";@@ -203,6 +208,32 @@ const ITEM_FROM = "items i JOIN sessions ts ON ts.id = i.session_id";const TENANT = "qm_tenant_id()";const LIST_COLUMNS = `s.id, s.type, s.scope_id, s.thread_ref, s.surface, s.created_at, s.title, s.channel_name,s.forked_from_session_id, s.forked_from_title, s.fork_boundary_seq, s.parent_session_id`;+const USER_ACTIVITY = "COALESCE(s.last_user_activity, s.created_at)";+const AUTOMATION_SURFACES = "('cron', 'webhook', 'loop')";++const LAST_USER_ACTIVITY_BACKFILL_SQL = `DO $last_user_activity_backfill$+DECLARE+ batch text[];+ after text := '';+BEGIN+ LOOP+ SELECT array_agg(id ORDER BY id) INTO batch+ FROM (SELECT id FROM sessions WHERE id > after ORDER BY id LIMIT 2000) candidates;+ EXIT WHEN batch IS NULL;+ WITH latest AS MATERIALIZED (+ SELECT b.id, (SELECT ${msOf("MAX(e.created_at)")} FROM items e+ WHERE e.tenant_id = ${TENANT} AND e.session_id = b.id AND e.kind IN ${USER_KINDS}) AS at+ FROM unnest(batch) AS b(id))+ UPDATE sessions s+ SET last_user_activity = latest.at+ FROM latest+ WHERE s.id = latest.id AND latest.at IS NOT NULL+ AND (s.last_user_activity IS NULL OR s.last_user_activity < latest.at);+ after := batch[cardinality(batch)];+ COMMIT;+ PERFORM pg_sleep(0.1);+ END LOOP;+END $last_user_activity_backfill$`;const tsOf = (ms: string): string => `to_timestamp((${ms})::double precision / 1000)`;function rowToSpendRow(r: Record<string, unknown>): SpendRow {@@ -282,17 +313,12 @@ export function createPostgresSessionStore(connectionString: string, opts: StoreTHEN COALESCE(s.messages, 0) > p.valid_from_seqELSE EXISTS (${participantPresenceSql}) END`;const HAS_CONTENT = `(NULLIF(btrim(COALESCE(p.title, s.title)), '') IS NOT NULL OR ${SEES_ITEMS})`;- const latestUserItem = (kind: string): string =>- `(SELECT ${msOf("e.created_at")} FROM items e WHERE e.tenant_id = ${TENANT} AND e.session_id = s.id- AND e.kind = '${kind}' ORDER BY e.created_at DESC LIMIT 1)`;- const USER_ACTIVITY = `GREATEST(s.created_at, ${latestUserItem("UserMessage")}, ${latestUserItem("SteeringMessage")})`;const participantSessionsSql = (extraWhere: string, columns = "s.*"): string =>`SELECT ${columns}, p.title AS p_title, p.archived AS p_archived, p.pinned AS p_pinned, p.color AS p_color,p.read_at AS p_read_at,(SELECT ${msOf("MAX(e.created_at)")} FROM items eWHERE e.tenant_id = ${TENANT} AND e.session_id = s.id AND ${AGENT_REPLY_ITEM("e")}) AS agent_last_reply,- COALESCE((SELECT ${msOf("MAX(e.created_at)")} FROM items e- WHERE e.tenant_id = ${TENANT} AND e.session_id = s.id AND e.kind IN ${USER_KINDS}), s.created_at) AS user_last_activity,+ ${USER_ACTIVITY} AS user_last_activity,${SEES_ITEMS} AS has_entriesFROM sessions sJOIN participants p ON p.session_id = s.id@@ -324,6 +350,62 @@ export function createPostgresSessionStore(connectionString: string, opts: StorelastActivityAt: r.last_activity == null ? null : Number(r.last_activity),}));};+ const participantPage = async (principalId: string, query: ParticipantPageQuery): Promise<ParticipantPage> => {+ const params: unknown[] = [principalId];+ const where: string[] = [+ "p.principal_id = $1",+ "s.parent_session_id IS NULL",+ `(s.surface IS NULL OR s.surface NOT IN ${AUTOMATION_SURFACES})`,+ HAS_CONTENT,+ ];+ const param = (value: unknown): string => {+ params.push(value);+ return `$${params.length}`;+ };+ where.push(`COALESCE(p.archived, false) = ${param(query.archived === true)}`);+ if (query.pinned !== undefined) where.push(`COALESCE(p.pinned, false) = ${param(query.pinned)}`);+ if (query.surface !== undefined) where.push(`s.surface = ${param(query.surface)}`);+ if (query.scopeId !== undefined) where.push(`s.scope_id = ${param(query.scopeId)}`);+ if (query.sessionIds !== undefined) where.push(`s.id = ANY(${param([...query.sessionIds])}::text[])`);+ if (query.titleQuery?.trim()) {+ const pattern = param(likeContains(query.titleQuery.trim()));+ where.push(`(COALESCE(p.title, s.title) ILIKE ${pattern} OR s.channel_name ILIKE ${pattern})`);+ }+ if (query.before)+ where.push(`(${USER_ACTIVITY}, s.id) < (${param(query.before.activity)}::bigint, ${param(query.before.id)})`);+ const limit = Math.max(1, Math.min(Math.floor(query.limit), 200));+ const page = await q(+ `SELECT s.id, ${USER_ACTIVITY} AS activity+ FROM participants p JOIN sessions s ON s.id = p.session_id+ WHERE ${where.join(" AND ")}+ ORDER BY ${USER_ACTIVITY} DESC, s.id DESC+ LIMIT ${param(limit + 1)}`,+ params,+ );+ const more = page.length > limit;+ const ids = page.slice(0, limit).map((row) => row.id as string);+ if (!ids.length) return { sessions: [], next: null };+ const rows = await q(participantSessionsSql(" AND s.id = ANY($2::text[])", LIST_COLUMNS), [principalId, ids]);+ const byId = new Map(rows.map((row) => [row.id as string, rowToParticipantSession(row)]));+ const last = page[limit - 1];+ return {+ sessions: ids.flatMap((id) => byId.get(id) ?? []),+ next: more && last ? { activity: Number(last.activity), id: last.id as string } : null,+ };+ };+ const descendantsOf = async (rootIds: readonly string[]): Promise<SessionDescendant[]> => {+ if (!rootIds.length) return [];+ const rows = await q(+ `WITH RECURSIVE tree(id, root_id, thread_ref) AS (+ SELECT id, parent_session_id, thread_ref FROM sessions WHERE parent_session_id = ANY($1::text[])+ UNION+ SELECT s.id, t.root_id, s.thread_ref FROM sessions s JOIN tree t ON s.parent_session_id = t.id+ )+ SELECT id, root_id, thread_ref FROM tree`,+ [[...rootIds]],+ );+ return rows.map((r) => ({ id: r.id as string, rootId: r.root_id as string, threadRef: r.thread_ref as string }));+ };const participantSession = async (sessionId: string, principalId: string): Promise<Session | null> => {const rows = await q(participantSessionsSql(" AND s.id = $2"), [principalId, sessionId]);return rows[0] ? rowToParticipantSession(rows[0]) : null;@@ -971,6 +1053,18 @@ export function createPostgresSessionStore(connectionString: string, opts: StoreON llm_prompt_envelopes(created_at)`,],},+ {+ id: "sessions/store/0043-last-user-activity",+ statements: [+ `SET LOCAL lock_timeout = '3s'`,+ `ALTER TABLE sessions ADD COLUMN IF NOT EXISTS last_user_activity BIGINT`,+ ],+ },+ {+ id: "sessions/store/0044-last-user-activity-backfill",+ prepare: [LAST_USER_ACTIVITY_BACKFILL_SQL],+ statements: [],+ },],[{@@ -1076,7 +1170,9 @@ export function createPostgresSessionStore(connectionString: string, opts: StoreELSE turns + $4 END,first_user_preview = CASE WHEN first_user_preview IS NULL AND turns = 0 AND messages = $5THEN $6 ELSE first_user_preview END,- last_user_preview = COALESCE($7, last_user_preview)+ last_user_preview = COALESCE($7, last_user_preview),+ last_user_activity = CASE WHEN $8::boolean THEN GREATEST(COALESCE(last_user_activity, 0), $2::bigint)+ ELSE last_user_activity ENDWHERE id = $1`,[sessionId,@@ -1086,6 +1182,7 @@ export function createPostgresSessionStore(connectionString: string, opts: StorestartSeq,firstUser ? storedPreview(firstUser.payload, FIRST_PREVIEW_LEN) : null,lastUser ? storedPreview(lastUser.payload, LAST_PREVIEW_LEN) : null,+ items.some((item) => USER_ITEM_KINDS.includes(item.kind)),],);return full;@@ -1579,6 +1676,24 @@ export function createPostgresSessionStore(connectionString: string, opts: Storereturn participantScopes(principalId);},+ async listParticipantPage(principalId, query): Promise<ParticipantPage> {+ return participantPage(principalId, query);+ },++ async descendantsOf(rootIds): Promise<SessionDescendant[]> {+ return descendantsOf(rootIds);+ },++ async listDescendantsForParticipant(rootId, principalId, limit): Promise<Session[]> {+ const ids = (await descendantsOf([rootId])).map((d) => d.id).slice(0, Math.max(0, Math.floor(limit)));+ if (!ids.length) return [];+ const rows = await q(+ participantSessionsSql(" AND s.id = ANY($2::text[])", LIST_COLUMNS) + " ORDER BY s.created_at, s.id",+ [principalId, ids],+ );+ return rows.map(rowToParticipantSession);+ },+async getForParticipant(sessionId, principalId): Promise<Session | null> {return participantSession(sessionId, principalId);},diff --git a/src/sessions/session-store.ts b/src/sessions/session-store.tsindex b03c448f6..475afe1d6 100644--- a/src/sessions/session-store.ts+++ b/src/sessions/session-store.ts@@ -364,6 +364,28 @@ export interface DistinctScope {channelName?: string;}+export interface ParticipantPageQuery {+ limit: number;+ before?: { activity: number; id: string };+ archived?: boolean;+ pinned?: boolean;+ surface?: string;+ scopeId?: ScopeId;+ titleQuery?: string;+ sessionIds?: readonly string[];+}++export interface ParticipantPage {+ sessions: Session[];+ next: { activity: number; id: string } | null;+}++export interface SessionDescendant {+ id: string;+ rootId: string;+ threadRef: string;+}+export interface ParticipantScope {scopeId: ScopeId;channelName?: string;@@ -587,6 +609,9 @@ export interface SessionStore {removeParticipant(sessionId: string, principalId: string): Promise<void>;listByParticipant(principalId: string, opts?: { limit: number }): Promise<Session[]>;participantScopes(principalId: string): Promise<ParticipantScope[]>;+ listParticipantPage(principalId: string, query: ParticipantPageQuery): Promise<ParticipantPage>;+ descendantsOf(rootIds: readonly string[]): Promise<SessionDescendant[]>;+ listDescendantsForParticipant(rootId: string, principalId: string, limit: number): Promise<Session[]>;getForParticipant(sessionId: string, principalId: string): Promise<Session | null>;deleteSession(sessionId: string): Promise<void>;diff --git a/src/types.ts b/src/types.tsindex 46c51ec06..405c4fb6d 100644--- a/src/types.ts+++ b/src/types.ts@@ -127,6 +127,7 @@ export interface Session {crons?: number;/** Set while a working session pursues a goal: banked active time, the running turn's start, and the floor. */goal?: { objective: string; activeMs: number; runningSince?: number; floor?: Record<string, number> };+ subagents?: { running: number; waiting: number };}export type EntryType =diff --git a/test/postgres-store.test.ts b/test/postgres-store.test.tsindex 55f567885..d732d749e 100644--- a/test/postgres-store.test.ts+++ b/test/postgres-store.test.ts@@ -3209,3 +3209,64 @@ test("pg LLM capture retention drops old prompt envelopes and keeps request rowsawait raw.end();}});++test(+ "pg session pages sort by the person's last message, which appends keep and the migration backfills",+ { skip },+ async () => {+ const s = createPostgresSessionStore(URL!);+ const me = `paging-${randomUUID()}`;+ const personal = scopeId("personal", me);+ const ids: string[] = [];+ for (let i = 0; i < 3; i++) {+ const session = await s.getOrCreateByThread(`web:${me}:${i}`, "dm", personal, undefined, "web");+ await s.addParticipant(session.id, me, `Chat ${i}`);+ ids.push(session.id);+ }+ const say = async (sessionId: string, type: "user" | "assistant") => {+ const { lease } = await s.acquireLease(sessionId);+ assert.ok(lease);+ await s.append(lease, { type, payload: { text: type }, scopeLabel: personal });+ await s.releaseLease(lease);+ };+ await say(ids[0]!, "user");+ await say(ids[2]!, "assistant");+ const order = async () => {+ const first = await s.listParticipantPage(me, { limit: 2 });+ const rest = first.next ? await s.listParticipantPage(me, { limit: 2, before: first.next }) : null;+ assert.equal(rest?.next, null);+ return [...first.sessions, ...(rest?.sessions ?? [])].map((row) => row.id);+ };+ assert.deepEqual(await order(), [ids[0], ids[2], ids[1]], "a reply doesn't move a chat; the person's message does");++ const pg = (await import("pg")).default;+ const raw = new pg.Pool({ connectionString: URL });+ try {+ const stored = await raw.query("SELECT id, last_user_activity FROM sessions WHERE id = ANY($1) ORDER BY id", [+ ids,+ ]);+ await raw.query("UPDATE sessions SET last_user_activity = NULL WHERE id = ANY($1)", [ids]);+ await raw.query("DELETE FROM qm_schema_migrations WHERE id = 'sessions/store/0044-last-user-activity-backfill'");+ await applyPgMigrations(raw, registeredPgMigrations(URL!));+ assert.deepEqual(+ (await raw.query("SELECT id, last_user_activity FROM sessions WHERE id = ANY($1) ORDER BY id", [ids])).rows,+ stored.rows,+ "the backfill derives what appends wrote",+ );+ } finally {+ await raw.end();+ }++ const child = await s.getOrCreateByThread(`subagent:${me}:1`, "dm", personal, undefined, "web");+ await s.setParentSession(child.id, ids[0]!);+ const grandchild = await s.getOrCreateByThread(`subagent:${me}:2`, "dm", personal, undefined, "web");+ await s.setParentSession(grandchild.id, child.id);+ assert.deepEqual(+ (await s.descendantsOf([ids[0]!])).map((d) => [d.id, d.rootId]).sort(),+ [+ [child.id, ids[0]],+ [grandchild.id, ids[0]],+ ].sort(),+ );+ },+);diff --git a/test/session-list-paging.test.ts b/test/session-list-paging.test.tsnew file mode 100644index 000000000..9f4900091--- /dev/null+++ b/test/session-list-paging.test.ts@@ -0,0 +1,139 @@+import "./support/auto-fake-sprites.ts";++import { test } from "node:test";+import assert from "node:assert/strict";+import { mkdtempSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import type { AddressInfo } from "node:net";+import { createInsecureTestServer } from "../src/api/server.ts";+import { buildApp } from "../src/wiring.ts";+import type { Principal, Session } from "../src/types.ts";+import type { OrchestratorInput } from "../src/core/orchestrator.ts";+import { testConfig } from "./support/test-config.ts";++type Page = { sessions: Session[]; pinned?: Session[]; nextCursor: string | null; hasArchived?: boolean };++async function withServer<T>(+ fn: (+ built: ReturnType<typeof buildApp>,+ get: (path: string) => Promise<{ status: number; body: unknown }>,+ ) => Promise<T>,+): Promise<T> {+ const built = buildApp(testConfig({ dataDir: mkdtempSync(join(tmpdir(), "paging-")) }));+ const server = createInsecureTestServer(built.app);+ server.listen(0);+ const base = `http://localhost:${(server.address() as AddressInfo).port}`;+ try {+ return await fn(built, async (path) => {+ const res = await fetch(base + path);+ return { status: res.status, body: await res.json() };+ });+ } finally {+ await new Promise<void>((resolve) => server.close(() => resolve()));+ }+}++async function chat(built: ReturnType<typeof buildApp>, threadRef: string, title: string, owner = "U1") {+ const session = await built.sessions.getOrCreateByThread(threadRef, "dm", `personal:${owner}`, undefined, "web");+ await built.sessions.addParticipant(session.id, owner, title);+ return session;+}++function enqueueRequest(threadRef: string): OrchestratorInput {+ const principal: Principal = { id: "internal:U1", type: "internal" };+ return {+ actor: principal,+ conversation: { kind: "dm", threadRef, audience: [principal] },+ origin: { kind: "direct" },+ text: "working",+ };+}++test("the session list pages top-level chats newest first and keeps pinned, archived, children and automation runs out", async () => {+ await withServer(async (built, get) => {+ const chats = [];+ for (let i = 0; i < 5; i++) chats.push(await chat(built, `web:U1:c${i}`, `Chat ${i}`));+ const pinned = await chat(built, "web:U1:pinned", "Pinned");+ await built.sessions.updateParticipantView(pinned.id, "U1", { pinned: true });+ const archived = await chat(built, "web:U1:archived", "Archived");+ await built.sessions.updateParticipantView(archived.id, "U1", { archived: true });+ const child = await chat(built, "subagent:c0:1", "Child");+ await built.sessions.setParentSession(child.id, chats[0]!.id);+ const cron = await built.sessions.getOrCreateByThread("cron:job:1", "dm", "personal:U1", undefined, "cron");+ await built.sessions.addParticipant(cron.id, "U1", "Cron run");+ await chat(built, "web:U2:theirs", "Someone else's", "U2");++ const seen: Session[] = [];+ let page = (await get("/v1/sessions?principalId=U1&limit=2")).body as Page;+ assert.deepEqual(+ page.pinned?.map((s) => s.id),+ [pinned.id],+ );+ assert.equal(page.hasArchived, true);+ seen.push(...page.sessions);+ for (let guard = 0; page.nextCursor && guard < 5; guard++) {+ page = (await get(`/v1/sessions?principalId=U1&limit=2&before=${encodeURIComponent(page.nextCursor)}`))+ .body as Page;+ assert.equal(page.pinned, undefined, "only the first page carries pinned chats");+ seen.push(...page.sessions);+ }+ assert.equal(page.nextCursor, null);+ assert.deepEqual(+ seen.map((s) => s.id).sort(),+ chats.map((s) => s.id).sort(),+ "every top-level chat once; no pinned, archived, child, automation or foreign rows",+ );+ const activity = seen.map((s) => s.lastActivityAt ?? s.createdAt);+ assert.deepEqual(+ activity,+ [...activity].sort((a, b) => b - a),+ );+ for (const row of seen) assert.equal("hasEntries" in row, false);++ const archivedPage = (await get("/v1/sessions?principalId=U1&status=archived")).body as Page;+ assert.deepEqual(+ archivedPage.sessions.map((s) => s.id),+ [archived.id],+ );+ assert.equal((await get("/v1/sessions?principalId=U1&before=nonsense")).status, 400);+ assert.equal((await get("/v1/sessions?principalId=U1&status=deleted")).status, 400);+ });+});++test("a parent row counts its running subagents and its children load on demand", async () => {+ await withServer(async (built, get) => {+ const parent = await chat(built, "web:U1:parent", "Parent");+ const child = await chat(built, "subagent:parent:1", "Researcher");+ await built.sessions.setParentSession(child.id, parent.id);+ const grandchild = await chat(built, "subagent:child:1", "Helper");+ await built.sessions.setParentSession(grandchild.id, child.id);+ await built.runs.enqueue({ sessionId: grandchild.threadRef, request: enqueueRequest(grandchild.threadRef) });++ const page = (await get("/v1/sessions?principalId=U1")).body as Page;+ const row = page.sessions.find((s) => s.id === parent.id);+ assert.equal(row?.working, true);+ assert.deepEqual(row?.subagents, { running: 2, waiting: 0 }, "the child is working on behalf of its child");++ const children = (await get(`/v1/sessions/${parent.id}/children?principalId=U1`)).body as { sessions: Session[] };+ assert.deepEqual(children.sessions.map((s) => s.id).sort(), [child.id, grandchild.id].sort());+ assert.equal(children.sessions.find((s) => s.id === grandchild.id)?.working, true);+ assert.equal((await get(`/v1/sessions/${parent.id}/children?principalId=U2`)).status, 404);+ });+});++test("one row can be looked up by id or thread, and only by someone who can see it", async () => {+ await withServer(async (built, get) => {+ const session = await chat(built, "web:U1:inbox", "Inbox");+ const byThread = (await get("/v1/sessions/row?principalId=U1&threadRef=web%3AU1%3Ainbox")).body as {+ session: Session;+ };+ assert.equal(byThread.session.id, session.id);+ assert.equal(byThread.session.canContinue, true);+ const byId = (await get(`/v1/sessions/row?principalId=U1&id=${session.id}`)).body as { session: Session };+ assert.equal(byId.session.threadRef, "web:U1:inbox");+ assert.equal("spawnMeta" in byId.session, false);+ assert.equal((await get(`/v1/sessions/row?principalId=U2&id=${session.id}`)).status, 404);+ assert.equal((await get("/v1/sessions/row?principalId=U1")).status, 400);+ });+});