Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

perf(web,server): a conversation opens without waiting for the sidebar (#984)

lmlihengdeb1e3d9ba6a
diff --git a/changelog/unreleased/2026-10-15-faster-session-open.md b/changelog/unreleased/2026-10-15-faster-session-open.md
new file mode 100644
index 00000000..e5f40d0c
--- /dev/null
+++ b/changelog/unreleased/2026-10-15-faster-session-open.md
@@ -0,0 +1,46 @@
+# A historical conversation opens without waiting for the sidebar
+
+- **Date:** 2026-10-15
+- **Type:** fix
+- **Scope:** `server`, `web`
+
+[中文版](2026-10-15-faster-session-open.zh.md)
+
+Ported from upstream PenguinHarness (#984, commit `74efa5aa`).
+
+Opening a conversation queued behind the sidebar's Session list. The chat page would not look up
+the routed Session until that list had loaded, and the list asked each server once per Agent and
+page — requests the browser serialises, so the conversation's own reads waited behind them.
+
+## The conversation no longer waits for the sidebar
+
+- The chat page's direct lookup of the routed Session no longer waits for the list to finish
+ loading (`features/chat/chat-page.tsx`, `features/chat/route-probe.ts`).
+- A lookup that fails while the list is still loading decides nothing: a Session created a moment
+ ago may not be listed or answerable yet. The route stays pending and the lookup runs once more
+ when the list settles. The page reads whether the list is still loading when the lookup
+ **settles**, not when it was sent, so a lookup sent during the first load that fails after it
+ still redirects.
+- One lookup per Session is in flight at a time. It is no longer cancelled and re-issued on every
+ list change, which used to send a dozen identical requests for one deep link, and an answer
+ about a Session the route has since left is dropped.
+- The lookup usually answers before the list's first load. When it does, the conversation shows
+ the fetched row at once; the row joins the sidebar list only after the list has settled, and
+ only if the list did not bring it itself (a row beyond the first page, or an organization's
+ row).
+
+## The sidebar's list fan-out is one request per server
+
+- `POST /api/projects/:projectId/sessions/batch` carries up to 256 entries in one request, each
+ asking for one page of one Agent's list. An entry takes the parameters of
+ `GET /api/projects/:projectId/agents/:agentId/sessions` (`limit`, `order`, `offset` or an
+ activity-order `before` cursor, `category`, `workspaceGroup`, `withCounts`, `excludeOrg`) and is
+ checked by the same rules; one malformed entry makes the whole request a 400.
+- `results` answers the entries in request order. An Agent this server does not host comes back as
+ `ok: false, reason: "absent"`, which is a real answer; any other failure comes back as
+ `reason: "error"`, and the sidebar never reads that as "no conversations".
+- `reload()` and `loadMoreFor()` send one request per source — this server and each connected
+ machine — so Workspace grouping's per-group pages go out as one request per server too.
+
+The history read (`GET /api/sessions/:id/messages`) is unchanged: it is already bounded in bytes
+server-side, and a windowed page is capped at 4 MiB with its images served by reference.
diff --git a/changelog/unreleased/2026-10-15-faster-session-open.zh.md b/changelog/unreleased/2026-10-15-faster-session-open.zh.md
new file mode 100644
index 00000000..728f6e22
--- /dev/null
+++ b/changelog/unreleased/2026-10-15-faster-session-open.zh.md
@@ -0,0 +1,39 @@
+# 打开历史对话不再等待侧栏
+
+- **Date:** 2026-10-15
+- **Type:** fix
+- **Scope:** `server`, `web`
+
+[English](2026-10-15-faster-session-open.md)
+
+移植自上游 PenguinHarness(#984,提交 `74efa5aa`)。
+
+打开对话此前排在侧栏的 Session 列表后面:对话页要等那个列表加载完成才去查证路由指向的 Session,而该列表
+按「每个 Agent 每页一次」向每台服务器各发一次请求 —— 浏览器会把这些请求串行化,于是对话自己要读的东西
+就排在它们后面。
+
+## 对话不再等待侧栏
+
+- 对话页对路由指向的 Session 的直接查证,不再等待列表加载完成(`features/chat/chat-page.tsx`、
+ `features/chat/route-probe.ts`)。
+- 列表仍在加载时查证失败,不构成任何判定:刚创建的 Session 可能还没进列表、也还不作答。路由保持待定,
+ 列表落定后再查证一次。页面读的是查证**落定那一刻**列表是否仍在加载,而不是发出请求时 —— 因此在首次加载
+ 期间发出、加载完成后才失败的查证,仍然照旧重定向。
+- 同一个 Session 同时只有一个查证在途。它不再随列表每次变动被取消并重新发起(那会让一次深链发出十来个
+ 相同的请求);路由已经离开的 Session 的查证结果被丢弃。
+- 查证通常在列表首次加载之前就有答案,此时对话立刻显示取回的那一行;该行要等列表落定后才并入侧栏列表,
+ 且只在列表自己没带回来时才并(首页之外的行,或组织自己的行)。
+
+## 侧栏的列表请求改为每台服务器一次
+
+- 新增 `POST /api/projects/:projectId/sessions/batch`,一次请求最多携带 256 个条目,每个条目请求一个
+ Agent 的一页。条目接受与 `GET /api/projects/:projectId/agents/:agentId/sessions` 相同的参数
+ (`limit`、`order`、`offset` 或活动序的 `before` 游标、`category`、`workspaceGroup`、`withCounts`、
+ `excludeOrg`),并按相同规则校验;任一条目不合法,整个请求返回 400。
+- `results` 按请求顺序作答。服务器上不存在的 Agent 回 `ok: false, reason: "absent"`,这是一个真实答案;
+ 其余失败回 `reason: "error"`,侧栏绝不会把它读成「没有对话」。
+- `reload()` 与 `loadMoreFor()` 每个来源(本服务器与每台已连接机器)只发一次请求,按工作区分组时各分组的
+ 分页请求因此也合为每台服务器一次。
+
+历史读取(`GET /api/sessions/:id/messages`)未改:它在服务端本来就是有界的,一页窗口上限 4 MiB,图片按
+引用下发。
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index ec97a76c..50d1f631 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -2017,6 +2017,50 @@ export interface SessionsResponse {
workspaceLatest?: Record<string, string>;
}
+/**
+ * One page request inside POST /api/projects/:p/sessions/batch — the same knobs the
+ * Agent-level list takes, carried per entry so one call can stand in for a whole sidebar
+ * reload (one first page per Agent, plus every other page pair already open).
+ */
+export interface SessionBatchPageRequest {
+ agentId: string;
+ /** Rows per page, 1–1000. */
+ limit: number;
+ /** `activity`: last activity first — the sidebar's order. Omitted: creation order. */
+ order?: "created" | "activity";
+ /** Rows to skip from the top (default 0). Not beside `before`. */
+ offset?: number;
+ /**
+ * Activity order only: rows strictly below this cursor — the last row of the previous page
+ * (`lastActiveAt` + `sessionId`, the pair the list endpoint's `before` param carries).
+ */
+ before?: { lastActiveAt: string; sessionId: string };
+ category?: SessionCategory;
+ workspaceGroup?: string;
+ /** Totals per category over the Agent's whole list, as the collapsed folders' labels. */
+ withCounts?: boolean;
+ /** The user's own rows only: leave an organization's own sessions out of page and totals. */
+ excludeOrg?: boolean;
+}
+
+/**
+ * One entry's answer. `ok: false` is a real answer about THAT Agent, never about the batch:
+ * `absent` is an Agent this server does not host (its rows come from the machine that does),
+ * `error` is a failure to answer at all — which the caller must not read as "no rows".
+ */
+export type SessionBatchResult =
+ | ({ agentId: string; ok: true } & SessionsResponse)
+ | { agentId: string; ok: false; reason: "absent" | "error" };
+
+export interface SessionsBatchRequest {
+ requests: SessionBatchPageRequest[];
+}
+
+export interface SessionsBatchResponse {
+ /** One entry per requested page, in request order (repeated Agent ids stay repeated). */
+ results: SessionBatchResult[];
+}
+
/** Server directory browsing (the Workspace picker): starts from the home directory by default, can navigate up to the root. */
export interface DirEntryInfo {
name: string;
diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.ts
index bcff3ba3..382c6fd5 100644
--- a/packages/server/src/http/routes/sessions.ts
+++ b/packages/server/src/http/routes/sessions.ts
@@ -13,6 +13,7 @@ import type { Context } from "hono";
import {
THINKING_LEVEL_NAMES,
imageUrlMessage,
+ isValidId,
scratchpadDir,
sessionScratchpadDir,
stripLeadingMarkerBlocks,
@@ -30,12 +31,14 @@ import type {
RecalledMessageResponse,
ServerEvent,
SessionCategory,
+ SessionBatchResult,
SessionContextResponse,
SessionCreateResponse,
SessionForkResponse,
SessionProcessesResponse,
SessionResponse,
SessionsResponse,
+ SessionsBatchResponse,
SubagentMessageResponse,
RetryNowResponse,
TaskCreateResponse,
@@ -71,7 +74,12 @@ import type { ChannelHub } from "../../runtime/channel.js";
import type { MessagingBridge } from "../../runtime/messaging/bridge.js";
import type { SessionManager, RecallStore } from "../../runtime/session-manager.js";
import type { PreviewTokenSigner } from "../../services/preview-token.js";
-import type { SessionListOrder, SessionService } from "../../services/session-service.js";
+import type {
+ ActivityCursor,
+ SessionListOrder,
+ SessionListPaging,
+ SessionService,
+} from "../../services/session-service.js";
/** What this route group reaches — bound by its module (src/modules). */
export interface SessionsRouteDeps {
@@ -514,6 +522,147 @@ function parseGoalField(body: Record<string, unknown>): { budget: number } | nul
return { budget: (budget as number | undefined) ?? -1 };
}
+/** How many page requests one batch may carry — the sidebar's whole reload, with room. */
+const MAX_BATCH_REQUESTS = 256;
+
+/** One batch entry, parsed: the Agent it asks about and the list options it asks with. */
+interface BatchPage {
+ agentId: string;
+ paging: SessionListPaging;
+ order: SessionListOrder;
+ category?: SessionCategory;
+ workspaceGroup?: string;
+ withCounts?: true;
+ excludeOrg?: true;
+}
+
+/**
+ * Parse one batch entry under the rules the Agent-level list applies to its query: a limit of
+ * 1–1000, an offset of 0 or more, a cursor only in activity order and never beside an offset,
+ * a known order and category, a non-empty Workspace group. A batch must never serve a page the
+ * single list would have refused, so each of these is the same 400 there and here.
+ */
+function batchPage(entry: unknown, i: number): BatchPage {
+ const at = `requests[${i}]`;
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) {
+ throw badRequest(`${at} must be an object.`);
+ }
+ const item = entry as Record<string, unknown>;
+ // An Agent id becomes a path fragment on the reads below: checked before any of them runs.
+ if (typeof item.agentId !== "string" || !isValidId(item.agentId)) {
+ throw badRequest(`${at}.agentId must be a valid id.`);
+ }
+ if (item.order !== undefined && !SESSION_LIST_ORDERS.includes(item.order as SessionListOrder)) {
+ throw badRequest(`${at}.order must be one of ${SESSION_LIST_ORDERS.join(" / ")}.`);
+ }
+ const order = (item.order ?? "created") as SessionListOrder;
+ const limit = item.limit;
+ if (typeof limit !== "number" || !Number.isInteger(limit) || limit < 1 || limit > 1000) {
+ throw badRequest(`${at}.limit must be an integer between 1 and 1000.`);
+ }
+ let paging: SessionListPaging;
+ if (item.before !== undefined) {
+ if (order !== "activity") throw badRequest(`${at}.before requires order activity.`);
+ if (item.offset !== undefined) throw badRequest(`${at}.before and offset are exclusive.`);
+ const cursor = item.before as Partial<Record<keyof ActivityCursor, unknown>> | null;
+ const lastActiveAt = cursor?.lastActiveAt;
+ const sessionId = cursor?.sessionId;
+ if (
+ typeof lastActiveAt !== "string" ||
+ Number.isNaN(Date.parse(lastActiveAt)) ||
+ typeof sessionId !== "string" ||
+ !isValidId(sessionId)
+ ) {
+ throw badRequest(`${at}.before must be an activity cursor { lastActiveAt, sessionId }.`);
+ }
+ paging = { before: { lastActiveAt, sessionId }, limit };
+ } else {
+ const offset = item.offset ?? 0;
+ if (typeof offset !== "number" || !Number.isInteger(offset) || offset < 0) {
+ throw badRequest(`${at}.offset must be a non-negative integer.`);
+ }
+ paging = { offset, limit };
+ }
+ if (
+ item.category !== undefined &&
+ !SESSION_CATEGORIES.includes(item.category as SessionCategory)
+ ) {
+ throw badRequest(`${at}.category must be one of ${SESSION_CATEGORIES.join(" / ")}.`);
+ }
+ if (
+ item.workspaceGroup !== undefined &&
+ (typeof item.workspaceGroup !== "string" || item.workspaceGroup.trim() === "")
+ ) {
+ throw badRequest(`${at}.workspaceGroup must be a non-empty string.`);
+ }
+ for (const flag of ["withCounts", "excludeOrg"] as const) {
+ if (item[flag] !== undefined && typeof item[flag] !== "boolean") {
+ throw badRequest(`${at}.${flag} must be a boolean.`);
+ }
+ }
+ return {
+ agentId: item.agentId,
+ paging,
+ order,
+ ...(item.category !== undefined ? { category: item.category as SessionCategory } : {}),
+ ...(item.workspaceGroup !== undefined ? { workspaceGroup: item.workspaceGroup as string } : {}),
+ ...(item.withCounts === true ? { withCounts: true as const } : {}),
+ ...(item.excludeOrg === true ? { excludeOrg: true as const } : {}),
+ };
+}
+
+/**
+ * Project-level entry: POST /api/projects/:p/sessions/batch.
+ *
+ * The sidebar's first paint asks every Agent on this server — and every machine it holds a
+ * connection to — for its own first page, plus the other page pairs already open. As one
+ * request per (Agent, pair) that is dozens of round trips fired at once, and HTTP/1.1's six
+ * connections per host serialise them: the conversation pane's own /messages call queued
+ * behind them and the page opened seconds late. One request carrying every page turns that
+ * fan-out into one round trip; the answers stay per-Agent so a missing Agent (404) is still
+ * an ANSWER rather than a failure of the whole batch.
+ */
+export function sessionsBatchRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {
+ const app = new Hono<AppEnv>();
+
+ app.post("/", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
+ const body = await readJson(c);
+ const raw = body.requests;
+ if (!Array.isArray(raw)) throw badRequest("requests must be an array.");
+ if (raw.length > MAX_BATCH_REQUESTS) {
+ throw badRequest(`requests must hold at most ${MAX_BATCH_REQUESTS} entries.`);
+ }
+ // Every entry is checked BEFORE the first query runs: one bad entry fails the whole
+ // request rather than being discovered halfway through a batch.
+ const wanted = raw.map(batchPage);
+ // Sequential on purpose: these are the same in-memory index reads one-per-Agent already
+ // performed, and running them concurrently would only re-introduce the interleaving this
+ // endpoint exists to remove.
+ const results: SessionBatchResult[] = [];
+ for (const { agentId, ...options } of wanted) {
+ try {
+ await deps.agentConfigService.requireExists(projectId, agentId);
+ const out = await deps.sessionService.listSessions(projectId, agentId, options);
+ results.push({ agentId, ok: true, ...out });
+ } catch (err) {
+ // An Agent this server does not host answers 404 — an ANSWER (see the sidebar's own
+ // handling); anything else is a failure to answer, which must not be dressed up as
+ // "no rows" and blank the sidebar.
+ results.push({
+ agentId,
+ ok: false,
+ reason: err instanceof HttpError && err.status === 404 ? "absent" : "error",
+ });
+ }
+ }
+ return c.json({ results } satisfies SessionsBatchResponse);
+ });
+
+ return app;
+}
+
/** Agent-level entry: /api/projects/:p/agents/:a/sessions. */
export function agentSessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
@@ -1665,6 +1814,12 @@ export function sessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {
auth: "user",
order: 250,
},
+ {
+ id: "session-api.sessions-batch",
+ prefix: "/api/projects/:projectId/sessions/batch",
+ auth: "user",
+ order: 255,
+ },
{
id: "session-api.usage",
prefix: "/api/projects/:projectId/usage",
@@ -1727,6 +1882,7 @@ export class SessionApiRoutes {
@Bind("session-api.agent-config") agentConfigRoutes!: Hono<AppEnv>;
@Bind("session-api.vault") vaultRoutes!: Hono<AppEnv>;
@Bind("session-api.agent-sessions") agentSessionsRoutes!: Hono<AppEnv>;
+ @Bind("session-api.sessions-batch") sessionsBatchRoutes!: Hono<AppEnv>;
@Bind("session-api.usage") usageRoutes!: Hono<AppEnv>;
@Bind("session-api.workspace-files") workspaceFilesRoutes!: Hono<AppEnv>;
@Bind("session-api.sessions") sessionsRoutes!: Hono<AppEnv>;
@@ -1813,6 +1969,7 @@ export class SessionApiRoutes {
userVault: this.userVault,
});
this.agentSessionsRoutes = agentSessionsRoutes(sessionsDeps);
+ this.sessionsBatchRoutes = sessionsBatchRoutes(sessionsDeps);
this.usageRoutes = usageRoutes({ access, usageService: this.usage });
this.workspaceFilesRoutes = workspaceFilesRoutes({
access,
diff --git a/packages/server/test/sessions-batch.test.ts b/packages/server/test/sessions-batch.test.ts
new file mode 100644
index 00000000..220eb0e8
--- /dev/null
+++ b/packages/server/test/sessions-batch.test.ts
@@ -0,0 +1,281 @@
+/**
+ * POST /api/projects/:projectId/sessions/batch: the sidebar's whole reload in one request,
+ * every (Agent, page) pair answered on its own.
+ *
+ * One app and one Project serve the file; two Agents hold a handful of rows, and an Agent
+ * that does not exist stands in for one this server does not host.
+ *
+ * Scenarios:
+ * - Given entries for several Agents, the answers come back one per entry in request order
+ * (a repeated Agent stays repeated), each the page the Agent-level list serves for the
+ * same order, cursor, offset, filters and counts.
+ * - Given an Agent this server does not host, its entry is `absent` and the others are still
+ * answered.
+ * - Given an Agent whose index cannot be read, its entry is `error` (never an empty page) and
+ * the others are still answered.
+ * - Given one malformed entry among good ones — a bad Agent id, a limit outside 1–1000, a
+ * cursor outside activity order, beside an offset or malformed, an unknown order or
+ * category, an empty Workspace group, a flag that is not a boolean — or a body with no
+ * entry list, the whole request is a 400.
+ * - Given 256 entries, every one is answered; 257 is a 400.
+ * - Given no session, the request is a 401; given a user with no access to the Project, it
+ * is the 404 a Project that does not exist answers.
+ */
+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
+import type {
+ ProjectCreateResponse,
+ SessionBatchPageRequest,
+ SessionsBatchResponse,
+ SessionsResponse,
+} from "../src/api/types.js";
+import { apiClient, createTestApp, provisionUser } from "./helpers.js";
+import type { TestApp } from "./helpers.js";
+
+const A1 = "batch_a1";
+const A2 = "batch_a2";
+const GHOST = "batch_ghost";
+const STAMP = "2026-07-01T08:00:00.000Z";
+
+describe("POST /api/projects/:projectId/sessions/batch", () => {
+ let t: TestApp;
+ let api: ReturnType<typeof apiClient>;
+ let projectId: string;
+ const batchPath = () => `/api/projects/${projectId}/sessions/batch`;
+
+ /** Inserted straight into the index: the list reads only the stored rows. */
+ const seed = (agentId: string, sessionId: string, createdAt: string, lastActiveAt: string) =>
+ t.deps.sessionsRepo.insert({
+ sessionId,
+ projectId,
+ agentId,
+ provider: "custom",
+ modelId: "m-x",
+ workspace: `/tmp/ws-${agentId}`,
+ approvalMode: "allow-all",
+ title: null,
+ createdAt,
+ lastActiveAt,
+ });
+
+ beforeAll(async () => {
+ t = await createTestApp();
+ const { cookie } = await provisionUser(t.app, "alice");
+ api = apiClient(t.app, cookie);
+ const created = (await (
+ await api.post("/api/projects", { projectId: "alice-batch", name: "batch project" })
+ ).json()) as ProjectCreateResponse;
+ projectId = created.project.projectId;
+ for (const agentId of [A1, A2]) {
+ expect((await api.post(`/api/projects/${projectId}/agents`, { agentId })).status).toBe(201);
+ }
+ // a1: created in one order, run in another, one of them archived; a2: two rows.
+ seed(A1, "session-b1-old", "2026-07-01T08:00:00.000Z", "2026-07-09T08:00:00.000Z");
+ seed(A1, "session-b1-mid", "2026-07-02T08:00:00.000Z", "2026-07-05T08:00:00.000Z");
+ seed(A1, "session-b1-new", "2026-07-03T08:00:00.000Z", "2026-07-03T08:00:00.000Z");
+ seed(A1, "session-b1-arch", "2026-07-04T08:00:00.000Z", "2026-07-04T08:00:00.000Z");
+ t.deps.sessionsRepo.setArchived("session-b1-arch", "2026-07-10T08:00:00.000Z");
+ seed(A2, "session-b2-one", "2026-07-01T09:00:00.000Z", "2026-07-01T09:00:00.000Z");
+ seed(A2, "session-b2-two", "2026-07-02T09:00:00.000Z", "2026-07-02T09:00:00.000Z");
+ });
+ afterAll(async () => {
+ await t.cleanup();
+ });
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ async function batch(requests: unknown): Promise<SessionsBatchResponse> {
+ const res = await api.post(batchPath(), { requests });
+ expect(res.status).toBe(200);
+ return (await res.json()) as SessionsBatchResponse;
+ }
+
+ /** The Agent-level list's answer for the same knobs, in its query form. */
+ async function listed(agentId: string, qs: string): Promise<SessionsResponse> {
+ const res = await api.get(`/api/projects/${projectId}/agents/${agentId}/sessions?${qs}`);
+ expect(res.status, qs).toBe(200);
+ return (await res.json()) as SessionsResponse;
+ }
+
+ it("answers one entry per page in request order, each the page the Agent-level list serves", async () => {
+ const cursor = { lastActiveAt: "2026-07-09T08:00:00.000Z", sessionId: "session-b1-old" };
+ const { results } = await batch([
+ {
+ agentId: A1,
+ limit: 2,
+ order: "activity",
+ category: "active",
+ withCounts: true,
+ excludeOrg: true,
+ },
+ { agentId: A2, limit: 1, offset: 1 },
+ { agentId: A1, limit: 5, order: "activity", before: cursor, category: "active" },
+ { agentId: A1, limit: 5, order: "activity", category: "archived" },
+ ] satisfies SessionBatchPageRequest[]);
+ const below = encodeURIComponent(`${cursor.lastActiveAt},${cursor.sessionId}`);
+ expect(results).toEqual([
+ {
+ agentId: A1,
+ ok: true,
+ ...(await listed(A1, "limit=2&order=activity&category=active&counts=1&excludeOrg=1")),
+ },
+ { agentId: A2, ok: true, ...(await listed(A2, "limit=1&offset=1")) },
+ {
+ agentId: A1,
+ ok: true,
+ ...(await listed(A1, `limit=5&order=activity&before=${below}&category=active`)),
+ },
+ { agentId: A1, ok: true, ...(await listed(A1, "limit=5&order=activity&category=archived")) },
+ ]);
+ // The pages are real ones, not empty agreements: the run-last row leads the activity order,
+ // the cursor continues below it, and the archived folder holds its one row.
+ const ids = results.map((r) => (r.ok ? r.sessions.map((s) => s.sessionId) : null));
+ expect(ids).toEqual([
+ ["session-b1-old", "session-b1-mid"],
+ ["session-b2-one"],
+ ["session-b1-mid", "session-b1-new"],
+ ["session-b1-arch"],
+ ]);
+ });
+
+ it("answers an Agent this server does not host as absent, and still answers the rest", async () => {
+ const { results } = await batch([
+ { agentId: A1, limit: 1 },
+ { agentId: GHOST, limit: 1 },
+ { agentId: A2, limit: 1 },
+ ]);
+ expect(results.map((r) => (r.ok ? r.agentId : `${r.agentId}:${r.reason}`))).toEqual([
+ A1,
+ `${GHOST}:absent`,
+ A2,
+ ]);
+ expect(results[1]).toEqual({ agentId: GHOST, ok: false, reason: "absent" });
+ });
+
+ it("answers an Agent whose index cannot be read as an error, never as an empty page", async () => {
+ const index = t.deps.sessionsRepo;
+ const read = index.listByAgent.bind(index);
+ vi.spyOn(index, "listByAgent").mockImplementation((p, agentId) => {
+ if (agentId === A2) throw new Error("database disk image is malformed");
+ return read(p, agentId);
+ });
+ const { results } = await batch([
+ { agentId: A1, limit: 1 },
+ { agentId: A2, limit: 1 },
+ { agentId: A1, limit: 1, offset: 1 },
+ ]);
+ expect(results[1]).toEqual({ agentId: A2, ok: false, reason: "error" });
+ expect(results.filter((r) => r.ok).map((r) => r.agentId)).toEqual([A1, A1]);
+ });
+
+ const good = { agentId: A1, limit: 1 };
+ it.each([
+ ["no entry list", { batch: [good] }],
+ ["an entry list that is not an array", { requests: A1 }],
+ ["an entry that is not an object", { requests: [good, null] }],
+ ["an Agent id that is a path", { requests: [good, { agentId: "../a", limit: 1 }] }],
+ ["no Agent id", { requests: [good, { limit: 1 }] }],
+ ["no limit", { requests: [good, { agentId: A1 }] }],
+ ["a limit of 0", { requests: [good, { agentId: A1, limit: 0 }] }],
+ ["a limit over 1000", { requests: [good, { agentId: A1, limit: 1001 }] }],
+ ["a limit that is not an integer", { requests: [good, { agentId: A1, limit: 1.5 }] }],
+ ["a negative offset", { requests: [good, { agentId: A1, limit: 1, offset: -1 }] }],
+ ["an unknown order", { requests: [good, { agentId: A1, limit: 1, order: "recent" }] }],
+ [
+ "a cursor in creation order",
+ {
+ requests: [
+ good,
+ { agentId: A1, limit: 1, before: { lastActiveAt: STAMP, sessionId: "s" } },
+ ],
+ },
+ ],
+ [
+ "a cursor beside an offset",
+ {
+ requests: [
+ good,
+ {
+ agentId: A1,
+ limit: 1,
+ order: "activity",
+ offset: 0,
+ before: { lastActiveAt: STAMP, sessionId: "s" },
+ },
+ ],
+ },
+ ],
+ [
+ "a cursor whose stamp is not a date",
+ {
+ requests: [
+ good,
+ {
+ agentId: A1,
+ limit: 1,
+ order: "activity",
+ before: { lastActiveAt: "yesterday", sessionId: "s" },
+ },
+ ],
+ },
+ ],
+ [
+ "a cursor whose id is not a valid id",
+ {
+ requests: [
+ good,
+ {
+ agentId: A1,
+ limit: 1,
+ order: "activity",
+ before: { lastActiveAt: STAMP, sessionId: "../s" },
+ },
+ ],
+ },
+ ],
+ [
+ "a cursor in the query's string form",
+ {
+ requests: [good, { agentId: A1, limit: 1, order: "activity", before: `${STAMP},s` }],
+ },
+ ],
+ ["an unknown category", { requests: [good, { agentId: A1, limit: 1, category: "all" }] }],
+ [
+ "an empty Workspace group",
+ { requests: [good, { agentId: A1, limit: 1, workspaceGroup: " " }] },
+ ],
+ [
+ "a flag that is not a boolean",
+ { requests: [good, { agentId: A1, limit: 1, withCounts: "1" }] },
+ ],
+ ])("refuses the whole request with a 400 for %s", async (_, body) => {
+ const res = await api.post(batchPath(), body);
+ expect(res.status).toBe(400);
+ expect(((await res.json()) as { error: { code: string } }).error.code).toBe("bad_request");
+ });
+
+ it("answers 256 entries, and refuses 257 with a 400", async () => {
+ const full = await batch(Array.from({ length: 256 }, () => ({ agentId: A2, limit: 1 })));
+ expect(full.results).toHaveLength(256);
+ expect(full.results.every((r) => r.ok && r.sessions.length === 1)).toBe(true);
+ const over = await api.post(batchPath(), {
+ requests: Array.from({ length: 257 }, () => ({ agentId: A2, limit: 1 })),
+ });
+ expect(over.status).toBe(400);
+ });
+
+ it("is a 401 without a session, and a 404 project_not_found for a user outside the Project", async () => {
+ const anonymous = await t.app.request(batchPath(), {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ requests: [good] }),
+ });
+ expect(anonymous.status).toBe(401);
+ const { cookie } = await provisionUser(t.app, "bob");
+ const outsider = await apiClient(t.app, cookie).post(batchPath(), { requests: [good] });
+ expect(outsider.status).toBe(404);
+ expect(((await outsider.json()) as { error: { code: string } }).error.code).toBe(
+ "project_not_found",
+ );
+ });
+});
diff --git a/packages/ui-gallery/src/app/mock/routes.ts b/packages/ui-gallery/src/app/mock/routes.ts
index 6eb6524a..e186173a 100644
--- a/packages/ui-gallery/src/app/mock/routes.ts
+++ b/packages/ui-gallery/src/app/mock/routes.ts
@@ -85,16 +85,7 @@ import type {
SchedulesResponse,
SemanticIdSuggestResponse,
ServerSettingsResponse,
- StorageApplyResponse,
- StoragePlanEntryView,
- StoragePlanResponse,
- StoragePlansResponse,
- StoragePlanView,
- StoragePurgeResponse,
- StorageReportResponse,
- StorageRestoreResponse,
- StorageSettingsResponse,
- StorageTrashResponse,
+ SessionBatchResult,
SessionCategory,
SessionCategoryCounts,
SessionContextResponse,
@@ -103,8 +94,20 @@ import type {
SessionInfo,
SessionProcessesResponse,
SessionResponse,
+ SessionsBatchResponse,
+ SessionsResponse,
SessionTracesResponse,
SshHostResponse,
+ StorageApplyResponse,
+ StoragePlanEntryView,
+ StoragePlanResponse,
+ StoragePlansResponse,
+ StoragePlanView,
+ StoragePurgeResponse,
+ StorageReportResponse,
+ StorageRestoreResponse,
+ StorageSettingsResponse,
+ StorageTrashResponse,
SubagentMessageResponse,
TaskCreateResponse,
TraceAnalysisResponse,
@@ -1073,65 +1076,116 @@ function byActivity(
return a.sessionId > b.sessionId ? -1 : a.sessionId < b.sessionId ? 1 : 0;
}
+/** One page of an Agent's list, as the GET route's query and the batch route's entries both ask. */
+interface ListAsk {
+ ownOnly: boolean;
+ activity: boolean;
+ category: SessionCategory | null;
+ group: string | null;
+ counts: boolean;
+ /** Activity order only: the rows strictly below the last one the sidebar holds. */
+ before: { lastActiveAt: string; sessionId: string } | null;
+ /** Absent (or not positive): the whole list. */
+ limit: number;
+ offset: number;
+}
+
+/** One Agent's list page from the fixtures, under the server's rules. */
+function listPage(store: DemoStore, agentId: string, ask: ListAsk): SessionsResponse {
+ // `ownOnly` (excludeOrg) asks for the user's own rows: an organization's Sessions leave the
+ // page and the totals alike. A request for a category, a Workspace group or counts leaves
+ // the company Sessions out too, which no category holds.
+ const { ownOnly, activity, category, group, before, limit, offset } = ask;
+ const classified = category !== null || group !== null || ask.counts;
+ const all = store.f.sessions
+ .filter(
+ (s) =>
+ s.agentId === agentId &&
+ !(ownOnly && isOrgRow(s)) &&
+ !(classified && categoryOf(s) === null),
+ )
+ .sort(activity ? byActivity : byCreated);
+ let rows = category ? all.filter((s) => categoryOf(s) === category) : all;
+ if (group !== null) {
+ rows = rows.filter((s) => (group === "temp" ? isTemp(s.workspace) : s.workspace === group));
+ }
+ if (before !== null) {
+ if (!activity) fail(400, "bad_request", "before requires order=activity.");
+ if (!Number.isFinite(Date.parse(before.lastActiveAt)) || !before.sessionId)
+ fail(400, "bad_request", "before must be <lastActiveAt>,<sessionId>.");
+ rows = rows.filter((s) => byActivity(s, before) > 0);
+ }
+ const page = Number.isFinite(limit) && limit > 0 ? rows.slice(offset, offset + limit) : rows;
+ const response: SessionsResponse = { sessions: page };
+ if (ask.counts) {
+ response.counts = countsOf(all);
+ const byWorkspace: Record<string, SessionInfo[]> = {};
+ for (const row of all) (byWorkspace[row.workspace] ??= []).push(row);
+ response.workspaceCounts = Object.fromEntries(
+ Object.entries(byWorkspace).map(([path, list]) => [path, countsOf(list)]),
+ );
+ // The newest CREATION per path, whatever order the page is in.
+ response.workspaceLatest = Object.fromEntries(
+ Object.entries(byWorkspace).map(([path, list]) => [
+ path,
+ list.reduce((latest, row) => (row.createdAt > latest ? row.createdAt : latest), ""),
+ ]),
+ );
+ }
+ return response;
+}
+
router
- .get("/api/projects/:projectId/agents/:agentId/sessions", (ctx): unknown => {
+ .get("/api/projects/:projectId/agents/:agentId/sessions", (ctx): SessionsResponse => {
const { store, params, query } = ctx;
- // `excludeOrg=1` asks for the user's own rows: an organization's Sessions leave the page
- // and the totals alike. A request for a category, a Workspace group or counts leaves the
- // company Sessions out too, which no category holds.
- const ownOnly = query.get("excludeOrg") === "1";
- const activity = query.get("order") === "activity";
- const category = query.get("category") as SessionCategory | null;
- const group = query.get("workspaceGroup");
- const classified = category !== null || group !== null || query.get("counts") === "1";
- const all = store.f.sessions
- .filter(
- (s) =>
- s.agentId === params.agentId &&
- !(ownOnly && isOrgRow(s)) &&
- !(classified && categoryOf(s) === null),
- )
- .sort(activity ? byActivity : byCreated);
- let rows = category ? all.filter((s) => categoryOf(s) === category) : all;
- if (group !== null) {
- rows = rows.filter((s) => (group === "temp" ? isTemp(s.workspace) : s.workspace === group));
- }
- // `before=<lastActiveAt>,<sessionId>`: the rows strictly below the last one the sidebar
- // holds, in activity order only.
- const before = query.get("before");
- if (before !== null) {
- if (!activity) fail(400, "bad_request", "before requires order=activity.");
- const comma = before.indexOf(",");
- const cursor = { lastActiveAt: before.slice(0, comma), sessionId: before.slice(comma + 1) };
- if (comma < 0 || !Number.isFinite(Date.parse(cursor.lastActiveAt)) || !cursor.sessionId)
- fail(400, "bad_request", "before must be <lastActiveAt>,<sessionId>.");
- rows = rows.filter((s) => byActivity(s, cursor) > 0);
- }
- const limit = Number(query.get("limit"));
- const offset = Number(query.get("offset")) || 0;
- const page = Number.isFinite(limit) && limit > 0 ? rows.slice(offset, offset + limit) : rows;
- const response: { sessions: SessionInfo[] } & Partial<
- Pick<
- import("@lmliheng/penguin-server/api").SessionsResponse,
- "counts" | "workspaceCounts" | "workspaceLatest"
- >
- > = { sessions: page };
- if (query.get("counts") === "1") {
- response.counts = countsOf(all);
- const byWorkspace: Record<string, SessionInfo[]> = {};
- for (const row of all) (byWorkspace[row.workspace] ??= []).push(row);
- response.workspaceCounts = Object.fromEntries(
- Object.entries(byWorkspace).map(([path, list]) => [path, countsOf(list)]),
- );
- // The newest CREATION per path, whatever order the page is in.
- response.workspaceLatest = Object.fromEntries(
- Object.entries(byWorkspace).map(([path, list]) => [
- path,
- list.reduce((latest, row) => (row.createdAt > latest ? row.createdAt : latest), ""),
- ]),
- );
- }
- return response;
+ // `before=<lastActiveAt>,<sessionId>`: split at the first comma.
+ const rawBefore = query.get("before");
+ const comma = rawBefore?.indexOf(",") ?? -1;
+ if (rawBefore !== null && comma < 0)
+ fail(400, "bad_request", "before must be <lastActiveAt>,<sessionId>.");
+ return listPage(store, str(params.agentId), {
+ ownOnly: query.get("excludeOrg") === "1",
+ activity: query.get("order") === "activity",
+ category: query.get("category") as SessionCategory | null,
+ group: query.get("workspaceGroup"),
+ counts: query.get("counts") === "1",
+ before:
+ rawBefore === null
+ ? null
+ : { lastActiveAt: rawBefore.slice(0, comma), sessionId: rawBefore.slice(comma + 1) },
+ limit: Number(query.get("limit")),
+ offset: Number(query.get("offset")) || 0,
+ });
+ })
+ // The sidebar's whole reload in one request: each entry answered as the GET route would,
+ // and an Agent the demo does not have is an answer about that Agent (`absent`), never a
+ // failure of the batch.
+ .post("/api/projects/:projectId/sessions/batch", ({ store, body }): SessionsBatchResponse => {
+ const requests = record(body).requests;
+ if (!Array.isArray(requests)) fail(400, "bad_request", "requests must be an array.");
+ const results = requests.map((entry): SessionBatchResult => {
+ const ask = record(entry);
+ const agentId = str(ask.agentId);
+ if (!store.f.agents.some((a) => a.agentId === agentId)) {
+ return { agentId, ok: false, reason: "absent" };
+ }
+ const before = record(ask.before);
+ const page = listPage(store, agentId, {
+ ownOnly: ask.excludeOrg === true,
+ activity: ask.order === "activity",
+ category: (ask.category as SessionCategory | undefined) ?? null,
+ group: typeof ask.workspaceGroup === "string" ? ask.workspaceGroup : null,
+ counts: ask.withCounts === true,
+ before:
+ ask.before === undefined
+ ? null
+ : { lastActiveAt: str(before.lastActiveAt), sessionId: str(before.sessionId) },
+ limit: Number(ask.limit),
+ offset: Number(ask.offset) || 0,
+ });
+ return { agentId, ok: true, ...page };
+ });
+ return { results };
})
.get("/api/projects/:projectId/dirs", ({ store, query }): DirListResponse => {
const path = query.get("path") || "/home/demo";
diff --git a/packages/ui-gallery/test/mock-api.test.ts b/packages/ui-gallery/test/mock-api.test.ts
index c9513b02..eec077c6 100644
--- a/packages/ui-gallery/test/mock-api.test.ts
+++ b/packages/ui-gallery/test/mock-api.test.ts
@@ -140,6 +140,27 @@ describe("the mocked API", () => {
expect(stamps).toEqual([...stamps].sort().reverse());
});
+ it("answers the sidebar's batch entry by entry as the list would, an unknown Agent absent", async () => {
+ const store = resetStore({ lang: "en", signedIn: true });
+ const project = store.f.project.projectId;
+ const agent = store.f.agents[0]!.agentId;
+ const opts = {
+ limit: 3,
+ order: "activity" as const,
+ category: "active" as const,
+ excludeOrg: true,
+ };
+ const listed = await api.listSessions(project, agent, { ...opts, withCounts: true });
+ const batch = await api.batchSessions(project, [
+ { agentId: agent, ...opts, withCounts: true },
+ { agentId: "no_such_agent", ...opts },
+ ]);
+ expect(batch.results).toEqual([
+ { agentId: agent, ok: true, ...listed },
+ { agentId: "no_such_agent", ok: false, reason: "absent" },
+ ]);
+ });
+
it("serves a running Session's history with its live tail, and a finished one without", async () => {
const store = resetStore({ lang: "en", signedIn: true });
const running = store.f.sessions.find((s) => s.status === "running")!;
diff --git a/packages/web/e2e/reload-midstream.spec.mjs b/packages/web/e2e/reload-midstream.spec.mjs
index c5c701f5..9d0bb7b8 100644
--- a/packages/web/e2e/reload-midstream.spec.mjs
+++ b/packages/web/e2e/reload-midstream.spec.mjs
@@ -99,6 +99,9 @@ test("in-progress tool output survives a reload: prefix back promptly, still gro
timeout: 30_000,
});
const controlPre = await openToolOutput(page);
+ // The output's reveal is paced by the theme (StreamText), and the reply after it can land
+ // in the same frame: compare the output once it has settled, not the instant the reply shows.
+ await expect(controlPre).toHaveAttribute("data-state", "done");
const controlOutput = await controlPre.textContent();
expect(controlOutput).toContain("line 40");
@@ -121,7 +124,9 @@ test("in-progress tool output survives a reload: prefix back promptly, still gro
await expect(page.getByText("Command finished; the result looks as expected.")).toBeVisible({
timeout: 30_000,
});
- const reloadedOutput = await (await openToolOutput(page)).textContent();
+ const reloadedPre = await openToolOutput(page);
+ await expect(reloadedPre).toHaveAttribute("data-state", "done");
+ const reloadedOutput = await reloadedPre.textContent();
expect(reloadedOutput).toBe(controlOutput);
});
diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.ts
index f4c8bbe8..45b4f5bd 100644
--- a/packages/web/src/api/endpoints.ts
+++ b/packages/web/src/api/endpoints.ts
@@ -183,6 +183,9 @@ import type {
PluginReadmeResponse,
SessionsResponse,
SessionSwitchModelRequest,
+ SessionBatchPageRequest,
+ SessionsBatchRequest,
+ SessionsBatchResponse,
SessionTracesResponse,
SkillArchiveInstallRequest,
SteerRequest,
@@ -852,6 +855,28 @@ export const listSessions = (
);
};
+/**
+ * A whole sidebar reload in one round trip: every (Agent, page) pair the sidebar wants,
+ * asked in a single POST instead of one GET each.
+ *
+ * The split matters on a Project with several Agents (and several machines): as individual
+ * requests they were fired all at once and serialised by the browser's six-connections-per-host
+ * limit, so the conversation pane's own message read queued behind dozens of list calls.
+ * One request keeps every answer separate — `results` lines up with `requests`, and an Agent
+ * this server does not host comes back as `ok: false, reason: "absent"` rather than failing
+ * the batch.
+ */
+export const batchSessions = (
+ projectId: string,
+ requests: SessionBatchPageRequest[],
+ machineId?: string | null,
+) =>
+ apiFetch<SessionsBatchResponse>(`/api/projects/${encodeURIComponent(projectId)}/sessions/batch`, {
+ method: "POST",
+ body: { requests } satisfies SessionsBatchRequest,
+ server: machineId ?? null,
+ });
+
/** Server directory browsing: `path` is an absolute path; empty means start from the server's home directory. */
/**
* Browses directories. With no machine, this server's own filesystem; with one, THAT
diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsx
index d0badee0..8826e14c 100644
--- a/packages/web/src/features/chat/chat-page.tsx
+++ b/packages/web/src/features/chat/chat-page.tsx
@@ -120,6 +120,7 @@ import {
sessionForProject,
sessionProbeKey,
} from "./session-project";
+import { RouteProbe } from "./route-probe";
import { machineForSession } from "../../lib/session-machines";
import { nameOnMachine } from "../../lib/workspace-machines";
import { CHAT_DEFAULTS_CHANGED_EVENT, chatDefaultsChangedDetail } from "./chat-defaults-event";
@@ -842,8 +843,17 @@ export function ChatPage() {
* connection is back (state/sessions.tsx: OFFLINE_RECHECK_MS).
*/
const routeSessionOffline = routeSessionPending && probeFailedKey === probeKey;
+ /** The direct lookup of the routed Session, one per page (route-probe.ts). */
+ const [routeProbe] = useState(() => new RouteProbe());
+ /** A row the lookup found while the Session list was still loading, to add once it settles. */
+ const addWhenListed = useRef<SessionInfo | null>(null);
useEffect(() => {
- if (draft || !projectId || !routeSessionId || !probeKey || sessionsLoading) return;
+ routeProbe.track(draft ? null : probeKey, sessionsLoading);
+ // NOT gated on `sessionsLoading`: the direct lookup is what opens the conversation, and
+ // holding it behind the sidebar's list fan-out (one first page per Agent per machine)
+ // put seconds of sidebar work in front of the conversation the reader asked for. The
+ // failure path below is the one place the list still matters, and it is handled there.
+ if (draft || !projectId || !routeSessionId || !probeKey) return;
// Settled (row loaded, or the lookup already failed): nothing to probe — and a failed
// key must not be re-probed just because the list's identity churned.
if (!routeSessionPending) return;
@@ -856,26 +866,31 @@ export function ChatPage() {
setProbeFailedKey(probeKey);
return;
}
- let cancelled = false;
- api.getSession(routeSessionId).then(
- (res) => {
- if (cancelled) return;
- const session = sessionForProject(res.session, projectId);
- if (session) {
+ // Deliberately NOT cancelled on re-run: this lookup is keyed by the routed Session, and
+ // its answer stays valid across the list churn that re-runs this effect. Tying its
+ // lifetime to one run is what made a deep link issue a dozen identical requests. One
+ // lookup per Session in flight, the list's loading read when it settles, and an answer
+ // about a Session the route has left dropped: see route-probe.ts.
+ routeProbe.run(
+ probeKey,
+ async () => sessionForProject((await api.getSession(routeSessionId)).session, projectId),
+ {
+ found: (session, listLoading) => {
setFetchedSession(session);
- addSession(session);
+ // add() invalidates a reload in flight. During the sidebar's first load that threw
+ // the whole load away, leaving the list on this one row and still loading; the
+ // conversation needs only the fetched row, so the list gets it once it has settled.
+ if (listLoading) addWhenListed.current = session;
+ else addSession(session);
// A Session of an Agent the list has not loaded (company mode creates Agents
// server-side): fetch the list, or the page has no Agent to render under.
if (!agents.some((a) => a.agentId === session.agentId)) void reloadAgents();
- } else setProbeFailedKey(probeKey);
- },
- () => {
- if (!cancelled) setProbeFailedKey(probeKey);
+ },
+ // Only once the list has settled: a failure while it loads is not a verdict, and
+ // this effect re-runs when it settles and asks again.
+ gone: () => setProbeFailedKey(probeKey),
},
);
- return () => {
- cancelled = true;
- };
// `selected` rather than `sessions`: while the routed row stays unloaded, list churn
// (status flips, new pages) keeps it null and leaves the in-flight lookup alone —
// depending on the array identity cancelled and re-issued it on every user event.
@@ -890,6 +905,17 @@ export function ChatPage() {
addSession,
isSessionDeleted,
]);
+ // The row found during the list's first load, added once the list has settled and only if
+ // it did not bring the row itself (one beyond the first page, or an organization's row,
+ // which no list page serves and whose status and title events reach only listed rows).
+ useEffect(() => {
+ const row = addWhenListed.current;
+ if (sessionsLoading || row === null) return;
+ addWhenListed.current = null;
+ if (row.sessionId !== routeSessionId || sessions.some((s) => s.sessionId === row.sessionId))
+ return;
+ addSession(row);
+ }, [sessionsLoading, sessions, routeSessionId, addSession]);
// Auto-select the last conversation when the route doesn't select one: the most recently
// ACTIVE loaded conversation of the user's own (`user` source), the same rule the collapsed
diff --git a/packages/web/src/features/chat/route-probe.ts b/packages/web/src/features/chat/route-probe.ts
new file mode 100644
index 00000000..a08eecc2
--- /dev/null
+++ b/packages/web/src/features/chat/route-probe.ts
@@ -0,0 +1,66 @@
+/**
+ * The chat page's direct lookup of the routed Session: what opens a deep-linked conversation
+ * without waiting for the sidebar's list, and what decides that a Session the list does not
+ * hold is gone.
+ *
+ * The page drives it from one effect, which re-runs on every list change. Three things follow
+ * from that, and this keeps all three out of the effect's closure:
+ *
+ * - One lookup per Session is in flight at a time. Re-issuing it on every re-run fired a dozen
+ * identical requests for one deep link.
+ * - Whether the list is still loading is read when a lookup SETTLES, not when it left. A lookup
+ * that fails while the list's first load is still running decides nothing (a Session created
+ * a moment ago can be neither listed nor answered for yet): the slot is freed, and the page
+ * asks again once the list settles. But a lookup that left during that load and fails after
+ * it is a verdict; read from the closure that sent it, it was taken for a mid-load failure,
+ * and since nothing re-runs the effect for it, a deep link to a deleted Session stayed on the
+ * skeleton.
+ * - An answer about a Session the page has since left is dropped.
+ * - A row found while the list is still loading is handed over with that fact: the page shows
+ * it at once, but must not add it to the list until the list has settled (see chat-page.tsx).
+ */
+export interface RouteProbeHandlers<T> {
+ /** The lookup found the routed Session; `listLoading`: the Session list had not settled yet. */
+ found(row: T, listLoading: boolean): void;
+ /**
+ * The lookup settled it after the list had: the Session is not there. `cause` is the lookup's
+ * rejection, or null when it answered with a row the page may not show.
+ */
+ gone(cause: unknown): void;
+}
+
+export class RouteProbe {
+ private inFlight: string | null = null;
+ private routed: string | null = null;
+ private listLoading = true;
+
+ /**
+ * What the page shows now: the routed Session's probe key (null on none) and whether the
+ * Session list is still loading. Called on every run of the page's effect, before anything
+ * else, so a lookup settling later reads the page as it is then.
+ */
+ track(routeKey: string | null, listLoading: boolean): void {
+ this.routed = routeKey;
+ this.listLoading = listLoading;
+ }
+
+ /**
+ * Look up the Session `key` names, unless a lookup for it is already in flight. `lookup`
+ * resolves to the row, or to null when the answer is not one the page may show (a Session of
+ * another Project); a null or a rejection is a failure.
+ */
+ run<T>(key: string, lookup: () => Promise<T | null>, on: RouteProbeHandlers<T>): void {
+ if (this.inFlight === key) return;
+ this.inFlight = key;
+ const settle = (row: T | null, cause: unknown) => {
+ if (this.inFlight === key) this.inFlight = null;
+ if (this.routed !== key) return;
+ if (row !== null) on.found(row, this.listLoading);
+ else if (!this.listLoading) on.gone(cause);
+ };
+ lookup().then(
+ (row) => settle(row, null),
+ (err: unknown) => settle(null, err),
+ );
+ }
+}
diff --git a/packages/web/src/state/sessions.tsx b/packages/web/src/state/sessions.tsx
index 6904bfbb..62bd7a8f 100644
--- a/packages/web/src/state/sessions.tsx
+++ b/packages/web/src/state/sessions.tsx
@@ -55,6 +55,7 @@ import type { ReactNode } from "react";
import type {
ServerEvent,
SessionBackgroundTasks,
+ SessionBatchResult,
SessionCategory,
SessionCategoryCounts,
SessionInfo,
@@ -445,6 +446,69 @@ function rememberStatus(
return next;
}
+/** One (Agent, page) pair the sidebar's reload wants from a given source. */
+type WantedPage = {
+ agentId: string;
+ category: SessionCategory;
+ scope: string;
+ counts: boolean;
+};
+
+/** What the reload merge consumes per answered page. */
+type PageAnswer = {
+ agentId: string;
+ source: string | null;
+ pages: Array<{
+ category: SessionCategory;
+ scope: string;
+ counts?: SessionCategoryCounts;
+ workspaceCounts?: Record<string, SessionCategoryCounts>;
+ workspaceLatest?: Record<string, string>;
+ items: SessionInfo[];
+ hasMore: boolean;
+ }>;
+ answered: boolean;
+};
+
+/**
+ * One batch entry → the answer shape the merge expects.
+ *
+ * `ok: false` is a real answer about THAT Agent, and the two reasons are not the same thing:
+ * `absent` (this server does not host the Agent — its rows come from the machine that does)
+ * is the ordinary case, while `error` is a failure to answer at all. Treating them alike is
+ * what emptied the sidebar once already: an empty result standing in for a failure replaces
+ * rows that are perfectly alive.
+ */
+function oneAnswer(
+ want: WantedPage,
+ source: string | null,
+ result: SessionBatchResult | undefined,
+): PageAnswer {
+ if (result === undefined || !result.ok) {
+ return {
+ agentId: want.agentId,
+ source,
+ pages: [],
+ answered: result?.reason === "absent",
+ };
+ }
+ return {
+ agentId: want.agentId,
+ source,
+ pages: [
+ {
+ category: want.category,
+ scope: want.scope,
+ counts: result.counts,
+ workspaceCounts: result.workspaceCounts,
+ workspaceLatest: result.workspaceLatest,
+ ...splitPage(result.sessions, SIDEBAR_PAGE_SIZE),
+ },
+ ],
+ answered: true,
+ };
+}
+
/**
* Builds one Provider's store. Exported as a test seam: vitest runs this package in Node with
* no DOM, so the list's own behaviour is exercised against the store directly rather than
@@ -580,62 +644,72 @@ export function createSessionsStore() {
: [...new Set([...agentIds, ...(agentIdsByMachine[source] ?? [])])];
return ids.map((agentId) => ({ agentId, source }));
});
+ // One request per SOURCE, carrying every (Agent, page) pair that source owes us.
+ // These were one GET each — with several Agents and machines that is dozens fired at
+ // once, serialised by the browser's six-connections-per-host limit, and the
+ // conversation pane's own message read queued behind all of them.
+ const bySource = new Map<string | null, WantedPage[]>();
+ for (const { agentId, source } of jobs) {
+ // The Agent's whole-stream active first page (with per-category totals)
+ // always; plus the first page of every other pair already on screen — an
+ // open folder, and each Workspace group paging its own stream — because a
+ // reload triggered by a server event must refresh them, not blank them.
+ const pairs: { category: SessionCategory; scope: string }[] = [
+ { category: "active", scope: "" },
+ ];
+ for (const key of get().pageState.keys()) {
+ const parsed = parsePageKey(key);
+ if (parsed === null || parsed.agentId !== agentId || parsed.source !== source) continue;
+ if (parsed.category === "active" && parsed.scope === "") continue;
+ pairs.push({ category: parsed.category, scope: parsed.scope });
+ }
+ const list = bySource.get(source) ?? [];
+ for (const { category, scope } of pairs) {
+ list.push({
+ agentId,
+ category,
+ scope,
+ counts: category === "active" && scope === "",
+ });
+ }
+ bySource.set(source, list);
+ }
try {
- const results = await Promise.all(
- jobs.map(async ({ agentId, source }) => {
- // The Agent's whole-stream active first page (with per-category totals)
- // always; plus the first page of every other pair already on screen — an
- // open folder, and each Workspace group paging its own stream — because a
- // reload triggered by a server event must refresh them, not blank them.
- const pairs: { category: SessionCategory; scope: string }[] = [
- { category: "active", scope: "" },
- ];
- for (const key of get().pageState.keys()) {
- const parsed = parsePageKey(key);
- if (parsed === null || parsed.agentId !== agentId || parsed.source !== source)
- continue;
- if (parsed.category === "active" && parsed.scope === "") continue;
- pairs.push({ category: parsed.category, scope: parsed.scope });
- }
- try {
- const pages = await Promise.all(
- pairs.map(async ({ category, scope }) => {
- const res = await api.listSessions(
- projectId,
- agentId,
- {
- limit: SIDEBAR_PAGE_SIZE + 1,
- order: "activity",
- category,
- excludeOrg: true,
- ...(scope === "" ? {} : { workspaceGroup: scope }),
- ...(category === "active" && scope === "" ? { withCounts: true } : {}),
- },
- source,
- );
- return {
- category,
- scope,
- counts: res.counts,
- workspaceCounts: res.workspaceCounts,
- workspaceLatest: res.workspaceLatest,
- ...splitPage(res.sessions, SIDEBAR_PAGE_SIZE),
- };
- }),
- );
- return { agentId, source, pages, answered: true };
- } catch (err) {
- // Two very different things arrive here, and treating them alike is what
- // emptied the sidebar. An Agent is per-server, so a server simply not
- // having this one answers 404: an ANSWER, and the ordinary case. Anything
- // else — this server mid-swap, a connection held to a server that is not
- // serving, the network — is a failure to answer at all, and an empty
- // result standing in for it replaces rows that are perfectly alive.
- const absent = err instanceof ApiError && err.status === 404;
- return { agentId, source, pages: [], answered: absent };
- }
- }),
- );
+ const results = (
+ await Promise.all(
+ [...bySource].map(async ([source, wanted]) => {
+ let answered: PageAnswer[];
+ try {
+ const res = await api.batchSessions(
+ projectId,
+ wanted.map((w) => ({
+ agentId: w.agentId,
+ limit: SIDEBAR_PAGE_SIZE + 1,
+ order: "activity",
+ category: w.category,
+ excludeOrg: true,
+ ...(w.scope === "" ? {} : { workspaceGroup: w.scope }),
+ ...(w.counts ? { withCounts: true } : {}),
+ })),
+ source,
+ );
+ answered = wanted.map((w, i) => oneAnswer(w, source, res.results[i]));
+ } catch {
+ // The whole SOURCE failed to answer — this server mid-swap, a connection
+ // held to a server that is not serving, the network. Nothing is applied
+ // for it below, which is the point: an empty result standing in for a
+ // failure replaces rows that are perfectly alive (see oneAnswer).
+ answered = wanted.map((w) => ({
+ agentId: w.agentId,
+ source,
+ pages: [],
+ answered: false,
+ }));
+ }
+ return answered;
+ }),
+ )
+ ).flat();
if (g !== gen) return;
// Agents this server did not answer about. Per Agent, not per server: a damaged
// index or a 500 on ONE Agent is a different event from this server being
@@ -896,32 +970,57 @@ export function createSessionsStore() {
}
if (targets.length === 0 && settled.length === 0) return;
const g = gen;
- const results = await Promise.all(
- targets.map(async ({ agentId, source, before }) => {
- try {
- const fetched = (
- await api.listSessions(
+ // One request per SOURCE, carrying every (Agent, cursor) it owes that source — the
+ // same fan-out as reload(), and for the same reason: workspace grouping asks for one
+ // page per group per Agent on first paint, which as individual requests was a second
+ // dozen-request wave behind the conversation.
+ const pagesBySource = new Map<string | null, typeof targets>();
+ for (const target of targets) {
+ pagesBySource.set(target.source, [...(pagesBySource.get(target.source) ?? []), target]);
+ }
+ const results = (
+ await Promise.all(
+ [...pagesBySource].map(async ([source, wants]) => {
+ let fetched: Array<{ target: (typeof targets)[number]; rows: SessionInfo[] } | null>;
+ try {
+ const res = await api.batchSessions(
projectId,
- agentId,
- {
+ wants.map((w) => ({
+ agentId: w.agentId,
limit: SIDEBAR_PAGE_SIZE + 1,
order: "activity",
- ...(before === null ? {} : { before }),
+ ...(w.before === null ? {} : { before: w.before }),
category,
excludeOrg: true,
...(scope === "" ? {} : { workspaceGroup: scope }),
- },
+ })),
source,
- )
- ).sessions;
- return { agentId, source, before, ...splitPage(fetched, SIDEBAR_PAGE_SIZE) };
- } catch {
- // Transient failure: leave the pair's state untouched (still unloaded / still
- // has-more), so the affordance stays and the user can retry.
- return null;
- }
- }),
- );
+ );
+ fetched = wants.map((w, i) => {
+ const answer = res.results[i];
+ // An Agent this server does not host, or one that failed to answer, is
+ // nothing to append — the pair's own state is left untouched below, so the
+ // affordance stays and the user can retry.
+ if (answer === undefined || !answer.ok) return null;
+ return { target: w, rows: answer.sessions };
+ });
+ } catch {
+ // Transient failure: same as above, for the whole source.
+ fetched = wants.map(() => null);
+ }
+ return fetched.map((f) =>
+ f === null
+ ? null
+ : {
+ agentId: f.target.agentId,
+ source,
+ before: f.target.before,
+ ...splitPage(f.rows, SIDEBAR_PAGE_SIZE),
+ },
+ );
+ }),
+ )
+ ).flat();
if (g !== gen) return; // Project switch / reload raced this page: drop it.
const ok = results.filter((r) => r !== null);
const prev = get().sessions;
diff --git a/packages/web/test/route-probe.test.ts b/packages/web/test/route-probe.test.ts
new file mode 100644
index 00000000..baf49621
--- /dev/null
+++ b/packages/web/test/route-probe.test.ts
@@ -0,0 +1,149 @@
+/**
+ * The chat page's direct lookup of the routed Session (features/chat/route-probe.ts), driven
+ * the way the page's effect drives it: each run first tells the probe which Session the route
+ * names and whether the Session list is still loading, then asks for a lookup.
+ *
+ * - Given a lookup in flight, when the effect re-runs (the list churning), no second lookup is
+ * sent for the same Session.
+ * - Given the lookup finds the Session, the page receives the row, told whether the list was
+ * still loading when it arrived (the page then holds the row back from the list).
+ * - Given a lookup that fails while the list is still loading, nothing is decided; when the
+ * list settles, the effect asks again, and that failure says the Session is gone.
+ * - Given a lookup sent while the list was loading that fails after the list settled, the
+ * Session is gone: a deep link to a deleted Session leaves the skeleton.
+ * - Given an answer the page may not show (a Session of another Project) after the list
+ * settled, the Session is gone.
+ * - Given the Session is gone, the page is told why: the lookup's rejection (a 404 there is
+ * what makes the page say the Session does not exist), or none for an answer it may not show.
+ * - Given the route moved to another Session before a lookup settled, its answer changes
+ * nothing.
+ */
+import { describe, expect, it } from "vitest";
+import { RouteProbe } from "../src/features/chat/route-probe";
+
+interface Lookup {
+ key: string;
+ resolve(row: string | null): void;
+ reject(err: unknown): void;
+}
+
+/** A page with the probe: `effect` is one run of its effect, `lookups` what it sent. */
+function page() {
+ const probe = new RouteProbe();
+ const lookups: Lookup[] = [];
+ const found: { row: string; listLoading: boolean }[] = [];
+ const gone: string[] = [];
+ const causes: unknown[] = [];
+ const effect = (key: string | null, listLoading: boolean) => {
+ probe.track(key, listLoading);
+ if (key === null) return;
+ probe.run(
+ key,
+ () => new Promise<string | null>((resolve, reject) => lookups.push({ key, resolve, reject })),
+ {
+ found: (row, listLoading) => found.push({ row, listLoading }),
+ gone: (cause) => {
+ gone.push(key);
+ causes.push(cause);
+ },
+ },
+ );
+ };
+ return { effect, lookups, found, gone, causes };
+}
+
+/** Lets a settled lookup's handlers run. */
+const flush = () => new Promise<void>((resolve) => setTimeout(resolve, 0));
+
+const notFound = new Error("404 not_found");
+
+describe("the routed Session's direct lookup", () => {
+ it("sends one lookup per Session however often the effect re-runs while it is in flight", () => {
+ const p = page();
+ p.effect("p:s1", true);
+ p.effect("p:s1", true);
+ p.effect("p:s1", false);
+ expect(p.lookups.map((l) => l.key)).toEqual(["p:s1"]);
+ });
+
+ it("hands the page the row the lookup found, and whether the list was still loading", async () => {
+ const p = page();
+ p.effect("p:s1", true);
+ p.lookups[0]!.resolve("row s1");
+ await flush();
+ expect(p.found).toEqual([{ row: "row s1", listLoading: true }]);
+ expect(p.gone).toEqual([]);
+ const q = page();
+ q.effect("p:s1", true);
+ q.effect("p:s1", false);
+ q.lookups[0]!.resolve("row s1");
+ await flush();
+ expect(q.found).toEqual([{ row: "row s1", listLoading: false }]);
+ });
+
+ it("decides nothing on a failure while the list loads, and asks again once it has settled", async () => {
+ const p = page();
+ p.effect("p:s1", true);
+ p.lookups[0]!.reject(notFound);
+ await flush();
+ expect(p.gone).toEqual([]);
+ // The list settles: the effect re-runs, and a second lookup goes out.
+ p.effect("p:s1", false);
+ expect(p.lookups).toHaveLength(2);
+ p.lookups[1]!.reject(notFound);
+ await flush();
+ expect(p.gone).toEqual(["p:s1"]);
+ });
+
+ it("takes a failure that arrives after the list settled as gone, though the lookup left while it loaded", async () => {
+ const p = page();
+ p.effect("p:s1", true);
+ // The list settles while the lookup is still out: the effect re-runs and sends nothing.
+ p.effect("p:s1", false);
+ p.lookups[0]!.reject(notFound);
+ await flush();
+ // Nothing re-runs the effect after this, so a verdict missed here is never reached.
+ expect(p.gone).toEqual(["p:s1"]);
+ expect(p.lookups).toHaveLength(1);
+ });
+
+ it("takes an answer the page may not show, once the list has settled, as gone", async () => {
+ const p = page();
+ p.effect("p:s1", false);
+ p.lookups[0]!.resolve(null);
+ await flush();
+ expect(p.found).toEqual([]);
+ expect(p.gone).toEqual(["p:s1"]);
+ });
+
+ it("tells the page why the Session is gone: the lookup's rejection, or none for a row it may not show", async () => {
+ const p = page();
+ p.effect("p:s1", false);
+ p.lookups[0]!.reject(notFound);
+ await flush();
+ expect(p.causes).toEqual([notFound]);
+ const q = page();
+ q.effect("p:s1", false);
+ q.lookups[0]!.resolve(null);
+ await flush();
+ expect(q.causes).toEqual([null]);
+ });
+
+ it("drops the answer about a Session the route has since left", async () => {
+ const p = page();
+ p.effect("p:s1", false);
+ p.effect("p:s2", false);
+ p.lookups[0]!.reject(notFound);
+ p.lookups[1]!.resolve("row s2");
+ await flush();
+ expect(p.gone).toEqual([]);
+ expect(p.found.map((f) => f.row)).toEqual(["row s2"]);
+ // And a found row for the Session left behind is not shown in place of the routed one.
+ const q = page();
+ q.effect("p:s1", false);
+ q.effect(null, false);
+ q.lookups[0]!.resolve("row s1");
+ await flush();
+ expect(q.found).toEqual([]);
+ });
+});
diff --git a/packages/web/test/sessions-store.test.ts b/packages/web/test/sessions-store.test.ts
index da6fcc12..bbd0de7a 100644
--- a/packages/web/test/sessions-store.test.ts
+++ b/packages/web/test/sessions-store.test.ts
@@ -1,5 +1,5 @@
/**
- * The sessions store's list (state/sessions.tsx), driven through the real `listSessions`
+ * The sessions store's list (state/sessions.tsx), driven through the real `batchSessions`
* wrapper against the fetch fake: each server pages its own rows, counts are summed, and a
* source that could not answer is never read as a source that answered nothing.
*
@@ -8,6 +8,8 @@
* - A refresh over rows already on screen does not raise loading.
*
* Several machines:
+ * - A reload asks each server once: every Agent's first page and every open folder's, in one
+ * request.
* - Every source is merged newest first, each row remembers the machine it lives on, the
* counts are summed, and what a machine answered is cached for the next restart.
* - A machine is asked about its own Agents too, and this server only about its own.
@@ -60,6 +62,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type {
ServerEvent,
+ SessionBatchPageRequest,
SessionCategory,
SessionCategoryCounts,
SessionInfo,
@@ -82,7 +85,7 @@ import {
import { forgetSessionMachines, machineForSession } from "../src/lib/session-machines";
import { cachedMachineSessions, rememberMachineSessions } from "../src/lib/machine-cache";
import { apiError, json, stubFetch } from "./helpers/fetch";
-import type { FakeFetch, FetchHandler } from "./helpers/fetch";
+import type { FakeFetch, FetchHandler, FetchRequest } from "./helpers/fetch";
import { stubLocalStorage } from "./helpers/storage";
/** A server's answer for one Agent: its list, or an HTTP failure. */
@@ -110,6 +113,31 @@ const serve: FetchHandler = (request) => {
.find((s) => s.sessionId === sessionId);
return row ? json({ session: row }) : apiError(404, "not_found");
}
+ // The whole sidebar reload in one POST: the same per-(Agent, source) answers, one entry each.
+ if (request.method === "POST" && /^\/api\/projects\/[^/]+\/sessions\/batch$/.test(request.path)) {
+ const entries = (request.body as { requests?: BatchEntry[] }).requests ?? [];
+ const results = entries.map((entry) => {
+ const k = key(request.machine, entry.agentId);
+ const rows = served.get(k);
+ if (rows !== undefined) {
+ const page = servedBody(rows, entryQuery(entry));
+ if ("error" in page) return { agentId: entry.agentId, ok: false, reason: "error" };
+ return { agentId: entry.agentId, ok: true, ...page.body };
+ }
+ const answer = answers.get(k);
+ // The transport never throws for one entry: an Agent this server does not host (404) is
+ // an ANSWER, and anything else is a failure to answer — neither may become "no rows".
+ if (answer === undefined) throw new TypeError("fetch failed");
+ if ("status" in answer)
+ return {
+ agentId: entry.agentId,
+ ok: false,
+ reason: answer.status === 404 ? "absent" : "error",
+ };
+ return { agentId: entry.agentId, ok: true, ...answer };
+ });
+ return json({ results });
+ }
const agentId = /\/agents\/([^/]+)\/sessions$/.exec(request.path)?.[1] ?? "";
const k = key(request.machine, decodeURIComponent(agentId));
const rows = served.get(k);
@@ -126,6 +154,15 @@ beforeEach(() => {
fetch = stubFetch(serve);
});
+/** A batch entry's activity cursor in the list route's `before` param form. */
+const entryCursor = (entry: BatchEntry | undefined): string | undefined =>
+ entry?.before === undefined
+ ? undefined
+ : `${entry.before.lastActiveAt},${entry.before.sessionId}`;
+
+/** The page requests the batch calls carried, in order (their params live in the body). */
+const batchEntries = (): BatchEntry[] => fetch.requests.flatMap(batchEntriesOf);
+
/** The server's activity order, written out on its own (plain `<` / `>`, as the route compares). */
const serverRecent = (
a: Pick<SessionInfo, "lastActiveAt" | "sessionId">,
@@ -143,12 +180,42 @@ const serverRecent = (
const zeroCounts = (): SessionCategoryCounts => ({ active: 0, background: 0, archived: 0 });
+/** One page request as the batch endpoint carries it. */
+type BatchEntry = SessionBatchPageRequest;
+
+/** One batch entry → the query the single-Agent list route would have been asked with. */
+function entryQuery(entry: BatchEntry): URLSearchParams {
+ const query = new URLSearchParams();
+ query.set("limit", String(entry.limit));
+ if (entry.order !== undefined) query.set("order", entry.order);
+ if (entry.before !== undefined) {
+ query.set("before", `${entry.before.lastActiveAt},${entry.before.sessionId}`);
+ }
+ if (entry.category !== undefined) query.set("category", entry.category);
+ if (entry.workspaceGroup !== undefined) query.set("workspaceGroup", entry.workspaceGroup);
+ if (entry.withCounts === true) query.set("counts", "1");
+ if (entry.excludeOrg === true) query.set("excludeOrg", "1");
+ return query;
+}
+
/** One page of an Agent's rows as the list route answers it: order, cursor, filters, counts. */
function servedPage(rows: readonly SessionInfo[], query: URLSearchParams): Response {
+ const page = servedBody(rows, query);
+ return "error" in page ? apiError(400, "bad_request") : json(page.body);
+}
+
+/**
+ * The page the list route answers with, computed apart from the Response so the batch
+ * endpoint's per-entry answers can reuse it verbatim.
+ */
+function servedBody(
+ rows: readonly SessionInfo[],
+ query: URLSearchParams,
+): { body: SessionsResponse } | { error: true } {
const activity = query.get("order") === "activity";
const before = query.get("before");
if (before !== null && (!activity || query.has("offset") || !query.has("limit")))
- return apiError(400, "bad_request");
+ return { error: true };
let list = [...rows].sort(
activity ? serverRecent : (a, b) => (a.createdAt < b.createdAt ? 1 : -1),
);
@@ -175,17 +242,23 @@ function servedPage(rows: readonly SessionInfo[], query: URLSearchParams): Respo
}
Object.assign(body, { counts, workspaceCounts });
}
- return json(body);
+ return { body };
}
afterEach(() => forgetSessionMachines());
-/** Which servers were asked, and for which Workspace group. */
+/** What the sidebar asked, per request: the machine it went to and each page it wanted. */
const asked = () =>
- fetch.requests.map((r) => ({
- machineId: r.machine,
- ...(r.query.has("workspaceGroup") ? { workspaceGroup: r.query.get("workspaceGroup") } : {}),
- }));
+ fetch.requests.flatMap((r) =>
+ batchEntriesOf(r).map((e) => ({
+ machineId: r.machine,
+ ...(e.workspaceGroup !== undefined ? { workspaceGroup: e.workspaceGroup } : {}),
+ })),
+ );
+
+/** The page requests one recorded request carried (its params live in a batch body). */
+const batchEntriesOf = (request: FetchRequest): BatchEntry[] =>
+ request.method === "POST" ? ((request.body as { requests?: BatchEntry[] }).requests ?? []) : [];
function session(sessionId: string, over: Partial<SessionInfo> = {}): SessionInfo {
return {
@@ -274,6 +347,30 @@ describe("the list across machines", () => {
expect(cachedMachineSessions("p", "M1").map((s) => s.sessionId)).toEqual(["there"]);
});
+ it("a reload asks each server once, carrying every Agent's first page and every open folder's", async () => {
+ // One request per (Agent, page) was dozens fired at once on a Project with several Agents
+ // and machines, serialised behind the browser's per-host connection limit — and the open
+ // conversation's own read queued behind them.
+ const withArchived = { sessions: [], counts: { active: 0, background: 0, archived: 2 } };
+ for (const source of [null, "M1"]) {
+ answers.set(key(source, "a1"), withArchived);
+ answers.set(key(source, "a2"), { sessions: [], counts: COUNTS });
+ }
+ const store = boot(["M1"], [], ["a1", "a2"]);
+ await store.getState().reload();
+ await store.getState().loadMoreFor(["a1"], "archived");
+ fetch.requests.length = 0;
+ await store.getState().reload();
+ expect(fetch.requests.map((r) => r.machine)).toEqual([null, "M1"]);
+ for (const request of fetch.requests) {
+ expect(batchEntriesOf(request).map((e) => [e.agentId, e.category])).toEqual([
+ ["a1", "active"],
+ ["a1", "archived"],
+ ["a2", "active"],
+ ]);
+ }
+ });
+
it("asks a machine about ITS Agents too — an Agent that exists only there", async () => {
// A new chat started from a machine's Agent card belongs to an Agent this server has
// never heard of: asked only about this Project's Agents, the machine answers nothing
@@ -395,14 +492,13 @@ describe("the list fetches the user's own rows only", () => {
answers.set(key(null, "default_agent"), { sessions: [], counts: COUNTS });
answers.set(key(null, "acme_dev"), { sessions: [], counts: COUNTS });
await boot([], [], ["default_agent", "acme_dev"]).getState().reload();
- expect(fetch.requests.map((r) => r.path)).toEqual([
- "/api/projects/p/agents/default_agent/sessions",
- "/api/projects/p/agents/acme_dev/sessions",
- ]);
- for (const { query } of fetch.requests) {
- expect(query.get("category")).toBe("active");
- expect(query.get("counts")).toBe("1");
- expect(query.get("excludeOrg")).toBe("1");
+ // One request for the whole reload, carrying both Agents' first pages.
+ expect(fetch.requests.map((r) => r.path)).toEqual(["/api/projects/p/sessions/batch"]);
+ expect(batchEntries().map((e) => e.agentId)).toEqual(["default_agent", "acme_dev"]);
+ for (const entry of batchEntries()) {
+ expect(entry.category).toBe("active");
+ expect(entry.withCounts).toBe(true);
+ expect(entry.excludeOrg).toBe(true);
}
});
@@ -413,8 +509,7 @@ describe("the list fetches the user's own rows only", () => {
fetch.requests.length = 0;
await store.getState().loadMoreFor(["a1"], "background");
expect(fetch.requests).toHaveLength(1);
- expect(fetch.requests[0]!.query.get("category")).toBe("background");
- expect(fetch.requests[0]!.query.get("excludeOrg")).toBe("1");
+ expect(batchEntries()[0]).toMatchObject({ category: "background", excludeOrg: true });
});
});
@@ -525,20 +620,18 @@ describe("the list pages in activity order, under a cursor", () => {
served.set(key(null, "a1"), rows);
const store = boot();
await store.getState().reload();
- const first = fetch.requests[0]!.query;
- expect(first.get("order")).toBe("activity");
- expect(first.has("before")).toBe(false);
- expect(first.has("offset")).toBe(false);
+ const first = batchEntries()[0]!;
+ expect(first.order).toBe("activity");
+ expect(first.before).toBeUndefined();
// The conversations used last lead, though they were created first.
expect(ids(store)).toEqual(rows.slice(0, 10).map((s) => s.sessionId));
fetch.requests.length = 0;
await store.getState().loadMoreFor(["a1"], "active");
- const next = fetch.requests[0]!.query;
- expect(next.get("order")).toBe("activity");
+ const next = batchEntries()[0]!;
+ expect(next.order).toBe("activity");
// The tenth row, the last one shown — not the overflow row that only said "more".
- expect(next.get("before")).toBe(cursorOf(rows[9]!));
- expect(next.has("offset")).toBe(false);
+ expect(entryCursor(next)).toBe(cursorOf(rows[9]!));
expect(ids(store)).toEqual(rows.slice(0, 20).map((s) => s.sessionId));
});
@@ -550,8 +643,8 @@ describe("the list pages in activity order, under a cursor", () => {
fetch.requests.length = 0;
await store.getState().loadMoreFor(["a1"], "active", "/w");
expect(fetch.requests).toHaveLength(1);
- expect(fetch.requests[0]!.query.get("workspaceGroup")).toBe("/w");
- expect(fetch.requests[0]!.query.get("before")).toBe(cursorOf(rows[9]!));
+ expect(batchEntries()[0]!.workspaceGroup).toBe("/w");
+ expect(entryCursor(batchEntries()[0]!)).toBe(cursorOf(rows[9]!));
// Nothing re-read, nothing skipped: the group holds its every row, in order.
const inW = (s: SessionInfo) => s.workspace === "/w";
expect(shown(store, ["a1"], "active", "/w", inW)).toEqual(
@@ -622,11 +715,11 @@ describe("the list pages in activity order, under a cursor", () => {
await store.getState().reload();
fetch.requests.length = 0;
await store.getState().loadMoreFor(["a1"], "archived");
- expect(fetch.requests[0]!.query.get("category")).toBe("archived");
- expect(fetch.requests[0]!.query.get("order")).toBe("activity");
+ expect(batchEntries()[0]).toMatchObject({ category: "archived", order: "activity" });
expect(shown(store, ["a1"], "archived")).toEqual(archived.slice(0, 10).map((s) => s.sessionId));
await store.getState().loadMoreFor(["a1"], "archived");
- expect(fetch.requests[1]!.query.get("before")).toBe(cursorOf(archived[9]!));
+ // The second request continues below the tenth row — its cursor, not the overflow row's.
+ expect(entryCursor(batchEntries()[1]!)).toBe(cursorOf(archived[9]!));
expect(shown(store, ["a1"], "archived")).toEqual(archived.map((s) => s.sessionId));
});
});