A local-first multi-agent app development platform, built on PenguinHarness
feat(web,server): the sidebar pages by last activity, so 「加载更多会话」 only appends below (上游 #960 移植)
lmliheng0945d91ab51b
diff --git a/changelog/unreleased/2026-10-10-sidebar-activity-paging.md b/changelog/unreleased/2026-10-10-sidebar-activity-paging.mdnew file mode 100644index 00000000..34fe8a6f--- /dev/null+++ b/changelog/unreleased/2026-10-10-sidebar-activity-paging.md@@ -0,0 +1,19 @@+# Sidebar lists page by last activity and only ever append++- **Date:** 2026-10-10+- **Type:** fix+- **Scope:** `web`, `server`, `ui-gallery`, `docs`++[中文版](2026-10-10-sidebar-activity-paging.zh.md)++This is ported from upstream PenguinHarness (#960, commit `929abb33`).++In the sidebar's time grouping, "Load more chats" stopped moving rows from "Earlier" up into "Past day". The list was displayed by last activity but paged by creation time, and each Agent was paged on its own, so a later page could hold rows that belonged above rows already on screen. Every sidebar list was made to page in its display order, and a list merged from several streams to show only the rows all of them had reached. The same fix applied to the Agent and Workspace groupings and to the Subagents / Scheduled / Evaluations / Archived folders.++## Details++- `GET /api/projects/:projectId/agents/:agentId/sessions` gained `order=activity` (`lastActiveAt` descending, ties by `sessionId` descending, both compared by code point) and `before=<lastActiveAt>,<sessionId>`, which returns the rows strictly below that key. `before` required `order=activity` and `limit` and could not be combined with `offset`; a malformed value was answered with a 400. Without `order` the list kept its creation order and offset paging, and `counts=1` totals still covered the whole list.+- The Web App requested every sidebar page with `order=activity` and continued each stream from the key of the last row read from it, recorded when the page arrived. A Workspace group's first page of its own continued from its Agent's cursor on that machine, and was skipped when that Agent's list was already exhausted.+- Each list the sidebar drew — time mode before bucketing, each Agent and Workspace group, and each folder — was cut at its watermark: the most recent cursor among the streams (Agents, machines) that still had more. Rows below it stayed in memory until a later page lowered the watermark, so "Show N more chats" and "Load more chats" only added rows below the ones shown. Rows were drawn in the same code-point order, ties included, so a revealed row that shared a stamp with a shown one also landed below it. The open conversation always showed, and a search still covered every loaded row. The folders were ordered by last activity instead of creation time.+- The `session_state` user-channel event gained `projectId`. A Session of the current Project that the list did not hold was fetched once from the machine that announced it and shown at the top, with the newest state applied; flips of one run shared one lookup; organization rows and Sessions found missing were not asked about again, and Sessions deleted in the tab were not asked about at all.+- The gallery's mock list route was given the same `order` and `before` handling.diff --git a/changelog/unreleased/2026-10-10-sidebar-activity-paging.zh.md b/changelog/unreleased/2026-10-10-sidebar-activity-paging.zh.mdnew file mode 100644index 00000000..e3d8786d--- /dev/null+++ b/changelog/unreleased/2026-10-10-sidebar-activity-paging.zh.md@@ -0,0 +1,19 @@+# 侧栏列表按最后活动分页,只在底部追加++- **Date:** 2026-10-10+- **Type:** fix+- **Scope:** `web`, `server`, `ui-gallery`, `docs`++[English](2026-10-10-sidebar-activity-paging.md)++本条移植自上游 PenguinHarness(#960,提交 `929abb33`)。++侧栏按时间分组时,点击「加载更多会话」不再把行从「更早」跳进「近一天」。此前列表按最后活动显示、却按创建时间分页,且每个 Agent 各自分页,后一页的行可能本应排在已显示的行之上。侧栏的每个列表改为按显示顺序分页,由多条流合并的列表只显示各流都已覆盖的部分。同一修正也用于按 Agent、按 Workspace 分组,以及子智能体 / 定时任务 / 评估任务 / 已归档子夹。++## 细节++- `GET /api/projects/:projectId/agents/:agentId/sessions` 新增 `order=activity`(按 `lastActiveAt` 降序,相同时按 `sessionId` 降序,均按码点比较)与 `before=<lastActiveAt>,<sessionId>`(返回严格位于该键之后的行)。`before` 须配合 `order=activity` 与 `limit`,不能与 `offset` 同用;格式不对返回 400。不带 `order` 时仍按创建时间排序、用 offset 分页,`counts=1` 的计数仍覆盖整个列表。+- Web App 的侧栏请求一律带 `order=activity`,每条流都从上次从中读到的最后一行的键接着取,该键在页面返回时记下。Workspace 分组沿本组流取首页时,从该 Agent 在同一机器上的游标接着取;该 Agent 的列表已取完时不再发请求。+- 侧栏绘制的每个列表——按时间分组(在分桶之前)、每个 Agent 与 Workspace 分组、每个子夹——都在其水位线处截断:水位线取仍有剩余的各条流(Agent、机器)中最新的游标。水位线以下的行留在内存,待之后的页把水位线降下来再显示,因此「展开其余 N 个对话」与「加载更多会话」只在已显示的行之下追加。行的显示顺序同样按码点比较(时间相同者亦然),与已显示行时间相同的新行也排在其下。当前打开的对话始终显示,搜索仍覆盖所有已加载的行。子夹改为按最后活动排序,不再按创建时间。+- 用户频道的 `session_state` 事件新增 `projectId`。列表中没有的当前 Project 的 Session 开始运行时,从发出事件的机器取回这一行一次、显示在顶部,并套用最新的状态;同一次运行的多次状态切换共用一次查询;组织的会话与查无此行的 Session 不再查询,本页已删除的 Session 则根本不查询。+- 画廊的模拟列表接口同样支持 `order` 与 `before`。diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.mdindex 7c603e5a..431ee4fd 100644--- a/packages/docs/content/server-api.en.md+++ b/packages/docs/content/server-api.en.md@@ -628,7 +628,8 @@ The paths below omit the `/api/projects/:projectId` prefix.| GET | `/workspace-files/search?workspace=&q=` | Searches that directory by entry name || POST | `/workspace-files/reveal?workspace=&path=` | Shows the file in the machine's own file manager |-- The Session list accepts optional query parameters. `limit` and `offset` page the list (`offset` requires `limit`). `category` (`active`, `subagent`, `schedule`, `benchmark` or `archived`) filters it before paging, and `workspaceGroup` filters it to one Workspace. `counts=1` adds `counts` (totals per category over the whole list), `workspaceCounts` (the same totals per Workspace path) and `workspaceLatest` (each Workspace's newest Session). Without paging parameters, the full list is returned.+- The Session list accepts optional query parameters. `limit` and `offset` page the list (`offset` requires `limit`). `category` (`active`, `subagent`, `schedule`, `benchmark` or `archived`) filters it before paging, and `workspaceGroup` filters it to one Workspace. `counts=1` adds `counts` (totals per category over the whole list, whatever the page), `workspaceCounts` (the same totals per Workspace path) and `workspaceLatest` (each Workspace's newest Session). Without paging parameters, the full list is returned.+- `order` picks the list's order: `created` (the default) is newest creation first; `activity` is most recent `lastActiveAt` first, equal stamps by `sessionId` descending, both compared by code point rather than by locale. Under `order=activity`, `before=<lastActiveAt>,<sessionId>` with `limit` pages by cursor instead of offset: it returns the rows strictly below that key, typically the last row the client already shows. A Session that becomes active between two pages moves above the cursor, so it is not served again and no other row goes missing. `before` without `order=activity`, together with `offset`, without `limit`, or not a date and a valid id split at the first comma is a 400.- `excludeOrg=1` leaves an organization's desk, ticket and subagent Sessions out of the page and out of the `counts=1` totals together, which is what development mode's list asks for. Any other value is a 400.- On creation, `modelId` and `provider` go together: send the complete pair to pick a model, or omit both to use the Project's default model. Sending only one is a 400.- An explicit `workspace` must be an existing directory; it is never created. When omitted, the Workspace is a temporary one created automatically. The approval mode defaults to `allow-all`.@@ -1090,7 +1091,7 @@ export type ServerEvent =subagents?: SubagentRuntimeInfo[];}| { type: "session_title"; sessionId: string; title: string }- | { type: "session_state"; sessionId: string; state: "idle" | "running" | "compacting"; lastActiveAt: string; hasTrace: boolean }+ | { type: "session_state"; sessionId: string; projectId: string; state: "idle" | "running" | "compacting"; lastActiveAt: string; hasTrace: boolean }| { type: "session_background"; sessionId: string; processes: number; subagents: number }| { type: "resync_required" }| { type: "credentials_updated" }@@ -1133,7 +1134,7 @@ export type ServerEvent =- `approval_request` covers every call under `always-ask`, and calls with `rw` or unknown permission under `read-only`. Pending approvals are sent again on reconnect.- `task_state` also carries the number of queued follow-ups (`queued`), the steering messages still waiting for delivery (`pendingSteering`), steering that the run ended without delivering (`returnedSteering`), the queued follow-ups themselves (`pendingFollowUps`) and the live subagent children (`subagents`). An absent field means none.- `session_title` is sent on the Session's channel and on the user channels of the Project's owner and members.-- `session_state` names the Session by `sessionId`, so every row of a Session list stays live, not only the conversation a client has open. It carries the row fields needed to redraw the row without refetching: `lastActiveAt` as just stamped, and `hasTrace`, which is true whenever the state is `running` or `compacting`, because a running Session has by definition started a Task. It is sent to the user channels of the Project's owner and members.+- `session_state` names the Session by `sessionId` and its Project by `projectId`, so every row of a Session list stays live, not only the conversation a client has open, and a list can tell a Session of its own Project that it holds no row for, which it can then fetch by id. It carries the row fields needed to redraw the row without refetching: `lastActiveAt` as just stamped, and `hasTrace`, which is true whenever the state is `running` or `compacting`, because a running Session has by definition started a Task. It is sent to the user channels of the Project's owner and members.- `session_background` fires when a command moves to the background past its yield window or starts with `run_in_background`, when a process exits or is stopped, and when a background subagent starts, settles or is released. It carries `SessionInfo.backgroundTasks` as it now stands (`processes` = background command sessions still running, `subagents` = subagent Sessions moved to the background and mid-round), zeros included, so a list can clear its mark without refetching. The list rows and the single-Session GET omit the field when both counts are zero. Its audience is the same as for `session_state`.- `credentials_updated` follows `PUT /models` or a completed key-minting flow. Cached runtimes were invalidated, so the client clears any composer state disabled by an auth failure.- `web_updated` carries the new web revision as `rev` and is sent to every user channel.diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.mdindex 1e695310..cce5dca7 100644--- a/packages/docs/content/server-api.zh.md+++ b/packages/docs/content/server-api.zh.md@@ -628,7 +628,8 @@ Benchmark 属于 Project,不属于某个 Agent:一个 Benchmark 可以评估| GET | `/workspace-files/search?workspace=&q=` | 按条目名搜索该目录 || POST | `/workspace-files/reveal?workspace=&path=` | 在机器自带的文件管理器中显示文件 |-- Session 列表接受可选查询参数。`limit` 和 `offset` 用于分页(`offset` 必须搭配 `limit`)。`category`(`active`、`subagent`、`schedule`、`benchmark` 或 `archived`)先过滤再分页;`workspaceGroup` 只保留一个 Workspace 的会话。`counts=1` 会在响应里附加 `counts`(整个列表按类别的总数)、`workspaceCounts`(按 Workspace 路径统计的同类总数)和 `workspaceLatest`(每个 Workspace 最新的 Session)。不带分页参数时,返回完整列表。+- Session 列表接受可选查询参数。`limit` 和 `offset` 用于分页(`offset` 必须搭配 `limit`)。`category`(`active`、`subagent`、`schedule`、`benchmark` 或 `archived`)先过滤再分页;`workspaceGroup` 只保留一个 Workspace 的会话。`counts=1` 会在响应里附加 `counts`(整个列表按类别的总数,与取哪一页无关)、`workspaceCounts`(按 Workspace 路径统计的同类总数)和 `workspaceLatest`(每个 Workspace 最新的 Session)。不带分页参数时,返回完整列表。+- `order` 决定列表顺序:`created`(默认)按创建时间从新到旧;`activity` 按 `lastActiveAt` 从新到旧,时间相同时按 `sessionId` 降序,两者都按码点比较而非按区域设置排序。在 `order=activity` 下,`before=<lastActiveAt>,<sessionId>` 搭配 `limit` 以游标代替 `offset` 分页:只返回严格排在这个键之后的行,通常就是客户端已显示的最后一行。两页之间变为活跃的 Session 会移到游标之前,因此不会被再次返回,也不会让其他行漏掉。`before` 未搭配 `order=activity`、与 `offset` 同时出现、缺少 `limit`,或在第一个逗号处拆开后不是日期加合法 id,均返回 400。- `excludeOrg=1` 会把组织的工位会话、工单会话和子 Session 一并移出这一页以及 `counts=1` 的总数,这正是开发模式的列表所要的。取其他值返回 400。- 创建时 `modelId` 和 `provider` 必须成对出现:要指定模型就传完整一对,两个都省略则使用 Project 的默认模型。只传一个返回 400。- 显式传入的 `workspace` 必须是已存在的目录,永远不会自动创建。省略时自动创建一个临时 Workspace。审批模式默认 `allow-all`。@@ -1090,7 +1091,7 @@ export type ServerEvent =subagents?: SubagentRuntimeInfo[];}| { type: "session_title"; sessionId: string; title: string }- | { type: "session_state"; sessionId: string; state: "idle" | "running" | "compacting"; lastActiveAt: string; hasTrace: boolean }+ | { type: "session_state"; sessionId: string; projectId: string; state: "idle" | "running" | "compacting"; lastActiveAt: string; hasTrace: boolean }| { type: "session_background"; sessionId: string; processes: number; subagents: number }| { type: "resync_required" }| { type: "credentials_updated" }@@ -1133,7 +1134,7 @@ export type ServerEvent =- `approval_request` 覆盖 `always-ask` 模式下的每个调用,以及 `read-only` 模式下带 `rw` 或未知权限的调用。待处理的审批会在重连时重新发送。- `task_state` 还携带排队的后续消息数量(`queued`)、仍在等待投递的插话消息(`pendingSteering`)、运行结束时没能投递的插话消息(`returnedSteering`)、排队的后续消息本身(`pendingFollowUps`)以及活跃的子 Agent(`subagents`)。字段缺失表示没有。- `session_title` 发送到 Session 的通道,以及 Project 所有者和成员的用户通道。-- `session_state` 用 `sessionId` 指明是哪个 Session,因此 Session 列表的每一行都能保持实时,而不只是客户端当前打开的那个会话。事件携带重绘这一行所需的字段,无需重新拉取:刚写入的 `lastActiveAt`,以及 `hasTrace`。状态为 `running` 或 `compacting` 时 `hasTrace` 必为 true,因为正在运行的 Session 必然已经启动过 Task。它发送到 Project 所有者和成员的用户通道。+- `session_state` 用 `sessionId` 指明是哪个 Session、用 `projectId` 指明所属 Project,因此 Session 列表的每一行都能保持实时,而不只是客户端当前打开的那个会话;列表还能据此认出本 Project 中自己尚未持有的 Session,再按 id 单独拉取。事件携带重绘这一行所需的字段,无需重新拉取:刚写入的 `lastActiveAt`,以及 `hasTrace`。状态为 `running` 或 `compacting` 时 `hasTrace` 必为 true,因为正在运行的 Session 必然已经启动过 Task。它发送到 Project 所有者和成员的用户通道。- 以下情况会触发 `session_background`:命令超过让出窗口转入后台,或以 `run_in_background` 启动;进程退出或停止;后台子 Agent 开始一轮、结束一轮或释放。事件携带 `SessionInfo.backgroundTasks` 的当前值(`processes` = 仍在运行的后台命令会话数,`subagents` = 已转入后台、正处于一轮中的子 Agent Session 数),归零时同样发送,列表无需重新拉取就能撤下标记。两个计数都为零时,列表行和单个 Session 的 GET 会省略这个字段。受众与 `session_state` 相同。- `credentials_updated` 在 `PUT /models` 或签发 API key 的流程完成之后发送。缓存的运行时已失效,客户端应清除因认证失败而禁用的输入框状态。- `web_updated` 以 `rev` 携带新的 web 修订号,发送到每个用户通道。diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex 1deea8c9..8bff6f0a 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -1719,6 +1719,23 @@ export type SessionCategory = "active" | SessionSource | "archived";/** Per-category totals across an Agent's whole Session list (returned when the list is requested with counts). */export type SessionCategoryCounts = Record<SessionCategory, number>;+/**+ * GET /api/projects/:projectId/agents/:agentId/sessions. Every query parameter is optional:+ *+ * - `order`: `created` (the default) lists newest creation first; `activity` lists most recent+ * `lastActiveAt` first, ties broken by `sessionId` descending, both compared as plain strings+ * (code points, never locale collation) so a client can compute the same order.+ * - `limit` (1–1000) with `offset` (≥ 0): an offset page, in either order. Offsets suit only the+ * `created` order, which activity never reshuffles.+ * - `before=<lastActiveAt>,<sessionId>` with `limit`: under `order=activity` only, the rows+ * strictly below that cursor — the key of the last row the client holds. A row that becomes+ * active between pages moves above the cursor and is not served again, and no other row is+ * skipped (`session_state` tells the client about the moved one). 400 without+ * `order=activity`, beside `offset`, without `limit`, or when not a parseable stamp and a+ * valid id split at the first comma.+ * - `category`, `workspaceGroup`, `excludeOrg=1` filter before paging; `counts=1` adds the+ * whole-list totals below, which no cursor or offset narrows.+ */export interface SessionsResponse {/*** The page. With `excludeOrg=1` on the request, the rows an organization owns — its desk@@ -2841,11 +2858,17 @@ export type ServerEvent =* that has now run from one that never has — a first run would otherwise settle back into the* blank "never ran" row the client still believes in.*+ * `projectId` names the Session's Project: a list showing one Project ignores another's flips+ * without a request, and a flip for a Session of its own Project that it holds no row for is a+ * row it is missing — one that became active below its activity cursor (see SessionsResponse) —+ * which it fetches by id.+ ** Published only to the user channels of the Project's owner and members.*/| {type: "session_state";sessionId: string;+ projectId: string;state: SessionStatus;lastActiveAt: string;hasTrace: boolean;diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.tsindex 2004c3f0..849ffc4f 100644--- a/packages/server/src/http/routes/sessions.ts+++ b/packages/server/src/http/routes/sessions.ts@@ -55,7 +55,7 @@ import { sseEndpoint, streamRevocation } from "../sse.js";import {badRequest,optionalEnum,- optionalPagingQuery,+ optionalSessionListPagingQuery,optionalString,paginationQuery,parseNonNegativeInt,@@ -71,7 +71,7 @@ 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 { SessionService } from "../../services/session-service.js";+import type { SessionListOrder, SessionService } from "../../services/session-service.js";/** What this route group reaches — bound by its module (src/modules). */export interface SessionsRouteDeps {@@ -291,6 +291,9 @@ const SESSION_CATEGORIES: readonly SessionCategory[] = ["archived",];+/** Accepted `order` query values of the list endpoint (SessionListOrder, spelled out for validation). */+const SESSION_LIST_ORDERS: readonly SessionListOrder[] = ["created", "activity"];+/*** A base64 `data:` URL of an image, in the exact shape core parses it back out of* (`imagesToScratchpadPaths`): one mime type, the `;base64,` marker, a non-empty base64 body.@@ -530,9 +533,18 @@ export function agentSessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {const agentId = requireValidId(c, "agentId");deps.access.requireProjectAccess(c.var.user.userId, projectId);await deps.agentConfigService.requireExists(projectId, agentId);+ // Optional order: `created` (the default, newest creation first) or `activity` (most recent+ // lastActiveAt first, ties by id) — the order the sidebar displays, and so the one it pages.+ const rawOrder = c.req.query("order");+ if (rawOrder !== undefined && !SESSION_LIST_ORDERS.includes(rawOrder as SessionListOrder)) {+ throw badRequest(`order must be one of ${SESSION_LIST_ORDERS.join(" / ")}.`);+ }+ const order = (rawOrder ?? "created") as SessionListOrder;// Optional paging (absent = full list, the pre-paging contract): the sidebar requests- // limit+1 and shows limit, detecting "has more" without a response-envelope change.- const paging = optionalPagingQuery(c);+ // limit+1 and shows limit, detecting "has more" without a response-envelope change. Under+ // `order=activity` it pages by cursor (`before=<lastActiveAt>,<sessionId>`) instead of+ // offset, since activity moves rows across an offset; see SessionService.listSessions.+ const paging = optionalSessionListPagingQuery(c, order);// Optional category filter (paging then applies within the category) and per-category// totals — the sidebar loads active rows only and labels the collapsed folders from counts.const rawCategory = c.req.query("category");@@ -557,6 +569,7 @@ export function agentSessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {const { sessions, counts, workspaceCounts, workspaceLatest } =await deps.sessionService.listSessions(projectId, agentId, {...(paging ? { paging } : {}),+ order,...(rawCategory !== undefined ? { category: rawCategory as SessionCategory } : {}),...(rawWorkspaceGroup !== undefined ? { workspaceGroup: rawWorkspaceGroup } : {}),...(rawCounts !== undefined ? { withCounts: true } : {}),diff --git a/packages/server/src/http/validate.ts b/packages/server/src/http/validate.tsindex 4a5c543a..91e1d4a7 100644--- a/packages/server/src/http/validate.ts+++ b/packages/server/src/http/validate.ts@@ -8,6 +8,11 @@ import fs from "node:fs/promises";import path from "node:path";import type { Context } from "hono";import { isValidId } from "@lmliheng/penguin-core";+import type {+ ActivityCursor,+ SessionListOrder,+ SessionListPaging,+} from "../services/session-service.js";import { HttpError } from "./errors.js";export function badRequest(message: string): HttpError {@@ -103,6 +108,43 @@ export function optionalPagingQuery(c: Context): { offset: number; limit: numberreturn { offset, limit };}+/**+ * Parse an activity cursor, `<lastActiveAt>,<sessionId>`, or null when the text is not one.+ * Split at the FIRST comma — an ISO stamp holds none and a valid id holds none, so the split is+ * unambiguous; the stamp must parse as a date and the id must be a valid id. The stamp is kept+ * as sent: the list compares it as a string against the rows' own stamps, which is where the+ * client read it from.+ */+function parseActivityCursor(raw: string): ActivityCursor | null {+ const comma = raw.indexOf(",");+ if (comma === -1) return null;+ const lastActiveAt = raw.slice(0, comma);+ const sessionId = raw.slice(comma + 1);+ if (Number.isNaN(Date.parse(lastActiveAt)) || !isValidId(sessionId)) return null;+ return { lastActiveAt, sessionId };+}++/**+ * The Session list's OPTIONAL paging: {@link optionalPagingQuery}'s offset form, or — under+ * `order=activity` — the cursor form `before=<lastActiveAt>,<sessionId>&limit=N`, which serves+ * the rows strictly below the cursor. A cursor in another order, beside an offset or without a+ * limit is a 400, never a silently different page.+ */+export function optionalSessionListPagingQuery(+ c: Context,+ order: SessionListOrder,+): SessionListPaging | null {+ const rawBefore = c.req.query("before");+ if (rawBefore === undefined) return optionalPagingQuery(c);+ if (order !== "activity") throw badRequest("before requires order=activity.");+ if (c.req.query("offset") !== undefined) throw badRequest("before and offset are exclusive.");+ const rawLimit = c.req.query("limit");+ if (rawLimit === undefined) throw badRequest("before requires limit.");+ const before = parseActivityCursor(rawBefore);+ if (!before) throw badRequest("before must be <lastActiveAt>,<sessionId>.");+ return { before, limit: limitQuery(rawLimit) };+}+/** Read the JSON request body (parse failure / non-object -> 400). */export async function readJson(c: Context): Promise<Record<string, unknown>> {let body: unknown;diff --git a/packages/server/src/runtime/session-manager.ts b/packages/server/src/runtime/session-manager.tsindex ae67f15d..1e3b2a72 100644--- a/packages/server/src/runtime/session-manager.ts+++ b/packages/server/src/runtime/session-manager.ts@@ -2425,6 +2425,7 @@ export class SessionManager {notify(entry.projectId, {type: "session_state",sessionId: entry.sessionId,+ projectId: entry.projectId,state,lastActiveAt,hasTrace,diff --git a/packages/server/src/services/session-service.ts b/packages/server/src/services/session-service.tsindex 1a94e724..87a4b0ac 100644--- a/packages/server/src/services/session-service.ts+++ b/packages/server/src/services/session-service.ts@@ -153,6 +153,44 @@ export function sessionIdCreatedAt(sessionId: string): string | null {return Number.isNaN(date.getTime()) ? null : date.toISOString();}+/**+ * The order a Session list is served in: `created` (the default) is newest creation first;+ * `activity` is most recent `lastActiveAt` first — the order the sidebar displays, and the only+ * one an {@link ActivityCursor} pages.+ */+export type SessionListOrder = "created" | "activity";++/** A row's place in the activity order; as a `before` cursor, the last row the client holds. */+export interface ActivityCursor {+ lastActiveAt: string;+ sessionId: string;+}++/**+ * The activity order: `lastActiveAt` descending, ties broken by `sessionId` descending; negative+ * when `a` is the more recent. Plain `<` / `>` on both fields, never `localeCompare`: the client+ * derives the cursor from a row and the server slices on it, so both sides must agree on one+ * total order, and ICU collation (case, punctuation) is not one they can share. Stamps are ISO+ * 8601 and ids ASCII, so this is code-point order.+ */+export function compareActivityDesc(a: ActivityCursor, b: ActivityCursor): number {+ if (a.lastActiveAt !== b.lastActiveAt) return a.lastActiveAt > b.lastActiveAt ? -1 : 1;+ if (a.sessionId !== b.sessionId) return a.sessionId > b.sessionId ? -1 : 1;+ return 0;+}++/** The `created` order, unchanged since before the activity order existed. */+function compareCreatedDesc(a: SessionRow, b: SessionRow): number {+ return b.createdAt.localeCompare(a.createdAt) || b.sessionId.localeCompare(a.sessionId);+}++/**+ * A slice of a Session list: `offset` rows skipped (the `created` contract, also accepted under+ * `activity`), or every row strictly below `before` in the activity order.+ */+export type SessionListPaging =+ { offset: number; limit: number } | { before: ActivityCursor; limit: number };+export interface SessionServiceDeps {root: string;sessions: SessionIndex;@@ -389,9 +427,10 @@ export class SessionService {}/**- * List, sorted by createdAt descending. Every row is served **straight from the DB**,- * whichever client created it, with no Trace directory scanning — the answer to- * many-session sidebar reloads re-walking the filesystem on every request (#139).+ * List, sorted by createdAt descending — or, with `order: "activity"`, by lastActiveAt+ * descending (ties by sessionId, see {@link compareActivityDesc}). Every row is served+ * **straight from the DB**, whichever client created it, with no Trace directory scanning —+ * the answer to many-session sidebar reloads re-walking the filesystem on every request (#139).* Sessions living only in the Trace directory were adopted into the index by the* boot-time sweep (`adoptUnmanagedTraceSessions`), so listing never discovers. One* lazy discovery walk still runs for a list call that contains rows this process has@@ -403,13 +442,19 @@ export class SessionService {* "has more"); slicing happens before toInfo, so per-request source derivation (lazy* Trace-head reads) stays bounded by the page size.*+ * The `before` form pages the activity order by cursor: only rows strictly below it are+ * walked and served. An offset cannot page that order, because a row below the offset that+ * becomes active moves above it and the next page would skip a row; a cursor stays put — the+ * moved row is simply not served again (the client learns of it from `session_state`). The+ * offset form keeps serving the `created` order exactly as before.+ ** `category` filters to one sidebar bucket **before** paging, so offset/limit page* within the category. Filtering needs each walked row's category (a possible* Trace-head read per row, cached in the sources registry); without `withCounts`* the walk stops as soon as the requested page is complete. `withCounts` classifies- * every row and returns per-category totals over the whole list — plus the same- * totals broken down by Workspace path, and each path's newest Session's `createdAt` —- * so the sidebar can label the collapsed folders, list every Workspace that holds+ * every row, a cursor or not, and returns per-category totals over the whole list — plus+ * the same totals broken down by Workspace path, and each path's newest Session's+ * `createdAt` — so the sidebar can label the collapsed folders, list every Workspace that holds* Sessions (not only the ones its loaded pages happen to touch) and place the groups* by recency, all without loading them.*@@ -431,7 +476,8 @@ export class SessionService {projectId: string,agentId: string,opts: {- paging?: { offset: number; limit: number };+ paging?: SessionListPaging;+ order?: SessionListOrder;category?: SessionCategory;workspaceGroup?: string;withCounts?: boolean;@@ -443,7 +489,7 @@ export class SessionService {workspaceCounts?: Record<string, SessionCategoryCounts>;workspaceLatest?: Record<string, string>;}> {- const { paging, category, workspaceGroup, withCounts, excludeOrg } = opts;+ const { paging, order = "created", category, workspaceGroup, withCounts, excludeOrg } = opts;const rows = new Map(this.deps.sessions.listByAgent(projectId, agentId).map((r) => [r.sessionId, r]),);@@ -474,8 +520,16 @@ export class SessionService {}const sorted = [...rows.values()].sort(- (a, b) => b.createdAt.localeCompare(a.createdAt) || b.sessionId.localeCompare(a.sessionId),+ order === "activity" ? compareActivityDesc : compareCreatedDesc,);+ // The rows a cursor leaves to serve are a suffix of the activity order: those from `start` on.+ const before = paging && "before" in paging ? paging.before : undefined;+ let start = 0;+ if (before) {+ const below = sorted.findIndex((row) => compareActivityDesc(row, before) > 0);+ start = below === -1 ? sorted.length : below;+ }+ const skip = paging && "offset" in paging ? paging.offset : 0;const rowHasTrace = (row: SessionRow): boolean =>traces ? traces.has(row.sessionId) : row.hasTrace === true;const toPage = (page: SessionRow[]) =>@@ -483,14 +537,13 @@ export class SessionService {// No classification asked for: slice straight away (the pre-category behavior).if (category === undefined && workspaceGroup === undefined && !withCounts) {+ const from = start + skip;return {- sessions: await toPage(- paging ? sorted.slice(paging.offset, paging.offset + paging.limit) : sorted,- ),+ sessions: await toPage(paging ? sorted.slice(from, from + paging.limit) : sorted),};}- const want = paging ? paging.offset + paging.limit : Infinity;+ const want = paging ? skip + paging.limit : Infinity;const counts: SessionCategoryCounts = {active: 0,subagent: 0,@@ -501,7 +554,11 @@ export class SessionService {const workspaceCounts: Record<string, SessionCategoryCounts> = {};const workspaceLatest: Record<string, string> = {};const matched: SessionRow[] = [];- for (const row of sorted) {+ for (const [i, row] of sorted.entries()) {+ // Rows above a cursor are the client's already: never served, and classified only for+ // the totals, which are whole-list.+ const servable = i >= start;+ if (!servable && !withCounts) continue;if (!withCounts && matched.length >= want) break;const cat = await this.categoryOf(row, rowHasTrace(row));counts[cat] += 1;@@ -514,15 +571,19 @@ export class SessionService {archived: 0,});ws[cat] += 1;- // The walk is newest-first, so a path's first row is its newest Session.- workspaceLatest[row.workspace] ??= row.createdAt;+ // A path's newest Session by creation, whichever order the walk is in.+ const latest = workspaceLatest[row.workspace];+ if (latest === undefined || row.createdAt.localeCompare(latest) > 0) {+ workspaceLatest[row.workspace] = row.createdAt;+ }}const wanted =+ servable &&(category === undefined || cat === category) &&(workspaceGroup === undefined || matchesWorkspaceGroup(row.workspace, workspaceGroup));if (wanted && matched.length < want) matched.push(row);}- const sessions = await toPage(paging ? matched.slice(paging.offset, want) : matched);+ const sessions = await toPage(paging ? matched.slice(skip, want) : matched);return withCounts ? { sessions, counts, workspaceCounts, workspaceLatest } : { sessions };}diff --git a/packages/server/test/session-index.test.ts b/packages/server/test/session-index.test.tsindex bd2d03e9..8d4ea27c 100644--- a/packages/server/test/session-index.test.ts+++ b/packages/server/test/session-index.test.ts@@ -16,6 +16,11 @@* Session, one only a Trace head knows after a restart, and adopted ones (junk narrowed).* - Given many rows, the list pages newest first, filters by sidebar category, by Workspace* group and by organization, and its counts stay whole-Agent; junk parameters are 400s.+ * - Given order=activity, the list runs by last activity (equal stamps by id, code points), and+ * a client that asks for no order keeps the creation order and its offsets.+ * - Given a before cursor, pages cover every row once; a row that runs mid-paging moves above+ * the cursor and is neither repeated nor makes another row go missing; the cursor composes+ * with the filters and leaves the totals whole-list; a cursor in the wrong form is a 400.* - Given an unmanaged Trace, the startup sweep adopts it once as a client:'cli' row.* - Given a client hint, 'cli' or 'web' is stored and listed; 'org' cannot be claimed.* - Given a PATCH, the answer is the row after the write; approval mode and thinking level@@ -556,6 +561,181 @@ describe("session-index", () => {expect((await api.get(`${base()}?workspaceGroup=`)).status).toBe(400);});+ describe("order=activity and the before cursor", () => {+ /** Inserted straight into the index: the order reads only the stored stamps. */+ const seed = (+ sessionId: string,+ createdAt: string,+ lastActiveAt: string,+ workspace = "/tmp/ws-activity",+ ) =>+ t.deps.sessionsRepo.insert({+ sessionId,+ projectId,+ agentId,+ provider: "custom",+ modelId: "m-x",+ workspace,+ approvalMode: "allow-all",+ title: null,+ createdAt,+ lastActiveAt,+ });+ /** `n` rows whose stamps repeat in fours, so a page of ten ends inside a run of equal stamps. */+ const seedMany = (n: number) => {+ for (let i = 0; i < n; i++) {+ const stamp = `2026-08-0${1 + Math.floor(i / 4)}T10:00:00.000Z`;+ seed(`session-act-${String(i).padStart(2, "0")}`, stamp, stamp);+ }+ };+ const list = async (qs: string) => {+ const res = await api.get(`${base()}${qs}`);+ expect(res.status, qs).toBe(200);+ return (await res.json()) as SessionsResponse;+ };+ const ids = async (qs: string) => (await list(qs)).sessions.map((s) => s.sessionId);+ const cursor = (row: { lastActiveAt: string; sessionId: string }) =>+ encodeURIComponent(`${row.lastActiveAt},${row.sessionId}`);+ /**+ * The sidebar's walk: pages of `shown + 1` rows, each next page asked for below the last+ * SHOWN row (the overflow row only says there is more). Starts below `from` when given.+ */+ const pageThrough = async (+ shown: number,+ scope = "",+ from?: { lastActiveAt: string; sessionId: string },+ ) => {+ const pages: string[][] = [];+ let below = from;+ for (;;) {+ const qs = `?order=activity&limit=${shown + 1}${below ? `&before=${cursor(below)}` : ""}${scope}`;+ const rows = (await list(qs)).sessions;+ pages.push(rows.slice(0, shown).map((s) => s.sessionId));+ if (rows.length <= shown) return pages;+ below = rows[shown - 1];+ }+ };++ it("lists by last activity, equal stamps by id descending in code-point order, while no order keeps the creation order and its offsets", async () => {+ // Created first but run last: leads the activity order, trails the creation order.+ seed("session-act-old", "2026-07-01T08:00:00.000Z", "2026-07-09T08:00:00.000Z");+ // Equal stamps, ids differing only in case: code points put "a" (0x61) above "B" (0x42)+ // where locale collation puts B first. The client sorts the same rows itself, so the+ // server must not collate.+ seed("session-act-tie-B", "2026-07-02T08:00:00.000Z", "2026-07-06T08:00:00.000Z");+ seed("session-act-tie-a", "2026-07-03T08:00:00.000Z", "2026-07-06T08:00:00.000Z");+ seed("session-act-new", "2026-07-05T08:00:00.000Z", "2026-07-05T08:00:00.000Z");++ expect(await ids("?order=activity")).toEqual([+ "session-act-old",+ "session-act-tie-a",+ "session-act-tie-B",+ "session-act-new",+ ]);+ // A client that sends no order (every client before this one) gets the creation order and+ // its offset pages, unchanged.+ const created = [+ "session-act-new",+ "session-act-tie-a",+ "session-act-tie-B",+ "session-act-old",+ ];+ expect(await ids("")).toEqual(created);+ expect(await ids("?order=created")).toEqual(created);+ expect(await ids("?limit=2&offset=1")).toEqual(created.slice(1, 3));+ expect((await api.get(`${base()}?order=recent`)).status).toBe(400);+ });++ it("pages below the last shown row cover every row exactly once, the overflow row opening the next page", async () => {+ seedMany(25);+ const pages = await pageThrough(10);+ expect(pages.map((p) => p.length)).toEqual([10, 10, 5]);+ expect(pages.flat()).toEqual(await ids("?order=activity"));+ });++ it("a row that runs mid-paging moves above the cursor: the later pages neither repeat it nor skip another row", async () => {+ seedMany(25);+ const whole = await ids("?order=activity");+ const first = (await list("?order=activity&limit=11")).sessions.slice(0, 10);+ // A row on the third page runs now and rises above everything already shown.+ const moved = whole[20]!;+ t.deps.sessionsRepo.touchLastActive(moved, "2026-09-01T10:00:00.000Z");+ expect(await ids("?order=activity&limit=1")).toEqual([moved]);++ const later = await pageThrough(10, "", first.at(-1));+ expect([...first.map((s) => s.sessionId), ...later.flat()]).toEqual(+ whole.filter((id) => id !== moved),+ );+ });++ it("a cursor composes with category and workspaceGroup, while counts stay whole-list and each path keeps its newest creation", async () => {+ const alpha = "/tmp/ws-act-alpha";+ const beta = "/tmp/ws-act-beta";+ // alpha: four active rows and an archived one; beta: one row, created and run last.+ seed("session-act-a1", "2026-07-01T08:00:00.000Z", "2026-07-08T08:00:00.000Z", alpha);+ seed("session-act-a2", "2026-07-02T08:00:00.000Z", "2026-07-07T08:00:00.000Z", alpha);+ seed("session-act-a3", "2026-07-03T08:00:00.000Z", "2026-07-03T08:00:00.000Z", alpha);+ seed("session-act-a4", "2026-07-04T08:00:00.000Z", "2026-07-06T08:00:00.000Z", alpha);+ seed("session-act-a5", "2026-07-05T08:00:00.000Z", "2026-07-05T08:00:00.000Z", alpha);+ t.deps.sessionsRepo.setArchived("session-act-a5", "2026-07-10T08:00:00.000Z");+ seed("session-act-b1", "2026-07-06T08:00:00.000Z", "2026-07-09T08:00:00.000Z", beta);++ const scope = `&category=active&workspaceGroup=${encodeURIComponent(alpha)}`;+ expect(await pageThrough(2, scope)).toEqual([+ ["session-act-a1", "session-act-a2"],+ ["session-act-a4", "session-act-a3"],+ ]);++ const below = cursor({+ lastActiveAt: "2026-07-07T08:00:00.000Z",+ sessionId: "session-act-a2",+ });+ const counted = await list(`?order=activity&limit=1&before=${below}&counts=1${scope}`);+ expect(counted.sessions.map((s) => s.sessionId)).toEqual(["session-act-a4"]);+ expect(counted.counts).toEqual({+ active: 5,+ subagent: 0,+ schedule: 0,+ benchmark: 0,+ archived: 1,+ });+ expect(counted.workspaceCounts?.[alpha]).toEqual({+ active: 4,+ subagent: 0,+ schedule: 0,+ benchmark: 0,+ archived: 1,+ });+ // Groups are still placed by their newest CREATION, not by the walk's first row.+ expect(counted.workspaceLatest).toEqual({+ [alpha]: "2026-07-05T08:00:00.000Z",+ [beta]: "2026-07-06T08:00:00.000Z",+ });+ });++ it("a cursor outside order=activity, beside an offset, without a limit, or malformed is a 400", async () => {+ const ok = cursor({ lastActiveAt: "2026-07-01T08:00:00.000Z", sessionId: "session-x" });+ const stamp = encodeURIComponent("2026-07-01T08:00:00.000Z");+ for (const qs of [+ `?before=${ok}&limit=2`,+ `?order=created&before=${ok}&limit=2`,+ `?order=activity&before=${ok}&limit=2&offset=0`,+ `?order=activity&before=${ok}`,+ "?order=activity&limit=2&before=",+ `?order=activity&limit=2&before=${stamp}`,+ `?order=activity&limit=2&before=${stamp}%2C`,+ "?order=activity&limit=2&before=yesterday%2Csession-x",+ `?order=activity&limit=2&before=${stamp}%2C..%2Fsession-x`,+ ]) {+ const res = await api.get(`${base()}${qs}`);+ expect(res.status, qs).toBe(400);+ expect(((await res.json()) as { error: { code: string } }).error.code, qs).toBe(+ "bad_request",+ );+ }+ });+ });+it("half a model reference is 400: the missing half is never inferred", async () => {await configureModels();// Only modelId: even though it names the one configured model, the provider is neverdiff --git a/packages/server/test/session-state-events.test.ts b/packages/server/test/session-state-events.test.tsindex 4a0e756c..ac739a60 100644--- a/packages/server/test/session-state-events.test.ts+++ b/packages/server/test/session-state-events.test.ts@@ -8,7 +8,8 @@** - A run's running → idle flips reach the Project's owner and its members, and no other user,* not even one with a live channel of their own.- * - The event names the Session and carries the row stamp a list fetch would return.+ * - The event names the Session and its Project, and carries the row stamp a list fetch would+ * return.* - It carries hasTrace true from the first flip of a Session that had never run.* - It carries none of the composer state the Session channel owns.* - A member removed from the Project stops hearing about its Sessions.@@ -97,8 +98,11 @@ describe("session_state on the user channel", () => {expect(stranger.events).toEqual([]);});- it("names the Session and carries the row stamp a list fetch would return", async () => {+ it("names the Session and its Project, and carries the row stamp a list fetch would return", async () => {await runTask();+ // Every flip names the Project: a list of another Project skips it without a request, and a+ // list of this one that holds no row for the Session knows it has a row to fetch.+ expect(boxes.owner.states().map((e) => e.projectId)).toEqual([PROJECT, PROJECT]);const settled = boxes.owner.states().at(-1)!;expect(settled.sessionId).toBe(SID);expect(settled.state).toBe("idle");diff --git a/packages/ui-gallery/src/app/mock/routes.ts b/packages/ui-gallery/src/app/mock/routes.tsindex eb5eecd9..f3e2f70d 100644--- a/packages/ui-gallery/src/app/mock/routes.ts+++ b/packages/ui-gallery/src/app/mock/routes.ts@@ -792,18 +792,43 @@ function countsOf(rows: readonly SessionInfo[]): SessionCategoryCounts {return counts;}+/** Newest creation first: the list's default order. */+const byCreated = (a: SessionInfo, b: SessionInfo) =>+ a.createdAt < b.createdAt ? 1 : a.createdAt > b.createdAt ? -1 : 0;++/** `order=activity`: last activity first, ties by id — both by code point, as the server compares. */+function byActivity(+ a: Pick<SessionInfo, "lastActiveAt" | "sessionId">,+ b: Pick<SessionInfo, "lastActiveAt" | "sessionId">,+): number {+ if (a.lastActiveAt !== b.lastActiveAt) return a.lastActiveAt > b.lastActiveAt ? -1 : 1;+ return a.sessionId > b.sessionId ? -1 : a.sessionId < b.sessionId ? 1 : 0;+}+router.get("/api/projects/:projectId/agents/:agentId/sessions", (ctx): unknown => {const { store, params, query } = ctx;+ const activity = query.get("order") === "activity";const all = store.f.sessions.filter((s) => s.agentId === params.agentId)- .sort((a, b) => (a.createdAt < b.createdAt ? 1 : a.createdAt > b.createdAt ? -1 : 0));+ .sort(activity ? byActivity : byCreated);const category = query.get("category") as SessionCategory | null;const group = query.get("workspaceGroup");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;@@ -820,8 +845,12 @@ routerresponse.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[0]!.createdAt]),+ Object.entries(byWorkspace).map(([path, list]) => [+ path,+ list.reduce((latest, row) => (row.createdAt > latest ? row.createdAt : latest), ""),+ ]),);}return response;diff --git a/packages/ui-gallery/src/app/mock/store.ts b/packages/ui-gallery/src/app/mock/store.tsindex a9ac3d5c..1f2997c7 100644--- a/packages/ui-gallery/src/app/mock/store.ts+++ b/packages/ui-gallery/src/app/mock/store.ts@@ -263,6 +263,7 @@ export class DemoStore {this.userChannel.event({type: "session_state",sessionId,+ projectId: row.projectId,state,lastActiveAt: row.lastActiveAt,hasTrace: true,diff --git a/packages/ui-gallery/test/mock-api.test.ts b/packages/ui-gallery/test/mock-api.test.tsindex 4d81e7c0..374cbcad 100644--- a/packages/ui-gallery/test/mock-api.test.ts+++ b/packages/ui-gallery/test/mock-api.test.ts@@ -109,6 +109,26 @@ describe("the mocked API", () => {expect(archived.sessions.every((s) => s.archived)).toBe(true);});+ it("pages the list by last activity with a cursor, as the sidebar asks for it", 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 };+ const first = await api.listSessions(project, agent, opts);+ const rest = await api.listSessions(project, agent, {+ ...opts,+ limit: 100,+ before: first.sessions.at(-1)!,+ });+ const all = await api.listSessions(project, agent, { ...opts, limit: 100 });+ // The two pages are the whole list, in one order and with no row twice.+ expect([...first.sessions, ...rest.sessions].map((s) => s.sessionId)).toEqual(+ all.sessions.map((s) => s.sessionId),+ );+ const stamps = all.sessions.map((s) => s.lastActiveAt);+ expect(stamps).toEqual([...stamps].sort().reverse());+ });+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/src/api/endpoints.ts b/packages/web/src/api/endpoints.tsindex 3b269377..f9a2de43 100644--- a/packages/web/src/api/endpoints.ts+++ b/packages/web/src/api/endpoints.ts@@ -244,6 +244,8 @@ import type { MCPServerConfig } from "@lmliheng/penguin-core/interfaces";import { apiFetch, apiFetchWithMeta } from "./client";import { machineForSession, rememberSessionMachine } from "../lib/session-machines";import { apiUrl } from "../lib/server-context";+import { activityCursorParam } from "../lib/session-grouping";+import type { ActivityKey } from "../lib/session-grouping";// Auth & user -----------------------------------------------------------------@@ -716,13 +718,23 @@ export const kernelUpdateAgentConfig = (projectId: string, agentId: string) =>* detect "has more". `category` filters server-side (paging applies within the category);* `workspaceGroup` narrows the same way to one Workspace group, so a group can page its own* stream; `withCounts` asks for per-category totals over the whole list alongside the page.+ *+ * The sidebar pages in activity order with a cursor (`order: "activity"` + `before`), never by+ * offset: activity reorders the list while it is being read, and an offset page would skip a row+ * that moved above it. A server that predates `order` ignores both parameters and answers in+ * creation order — the next page then repeats rows the pool already holds, deduplicated by id.*/export const listSessions = (projectId: string,agentId: string,opts?: {- offset: number;+ /** Rows to skip, in creation order. Exclusive with `before`. */+ offset?: number;limit: number;+ /** `activity`: last activity first, ties by id descending (code-point order) — the sidebar's order. Omitted: creation order. */+ order?: "created" | "activity";+ /** Activity order only: rows strictly below this key — the last row of the previous page. */+ before?: ActivityKey;category?: SessionCategory;/** One Workspace group's rows only: its path, or the merged temporary group's sentinel (session-grouping.ts). */workspaceGroup?: string;@@ -738,7 +750,10 @@ export const listSessions = (machineId?: string | null,) => {const qs = opts- ? `?limit=${opts.limit}&offset=${opts.offset}` ++ ? `?limit=${opts.limit}` ++ (opts.offset !== undefined ? `&offset=${opts.offset}` : "") ++ (opts.order ? `&order=${opts.order}` : "") ++ (opts.before ? `&before=${encodeURIComponent(activityCursorParam(opts.before))}` : "") +(opts.category ? `&category=${opts.category}` : "") +(opts.workspaceGroup ? `&workspaceGroup=${encodeURIComponent(opts.workspaceGroup)}` : "") +(opts.withCounts ? "&counts=1" : "") +@@ -852,8 +867,16 @@ export const forkSession = (sessionId: string, body: SessionForkRequest) =>body,});-export const getSession = (sessionId: string) =>- apiFetch<SessionResponse>(`/api/sessions/${encodeURIComponent(sessionId)}`);+/**+ * One Session's row. `machineId` names the server to ask when the caller knows and the id map+ * does not yet — a Session the list has never fetched, announced by a machine's own event+ * stream. Omitted, the id routes itself (lib/session-machines.ts).+ */+export const getSession = (sessionId: string, machineId?: string | null) =>+ apiFetch<SessionResponse>(+ `/api/sessions/${encodeURIComponent(sessionId)}`,+ machineId === undefined ? {} : { server: machineId },+ );export const patchSession = (sessionId: string, body: SessionPatchRequest) =>apiFetch<SessionResponse>(`/api/sessions/${encodeURIComponent(sessionId)}`, {diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsxindex 394a8644..a6eb1edc 100644--- a/packages/web/src/components/layout/sidebar.tsx+++ b/packages/web/src/components/layout/sidebar.tsx@@ -117,6 +117,7 @@ import {aggregateWorkspaceLatest,clampGroupPage,completeWorkspaceGroups,+ cutAtWatermark,foldedShare,groupPageCount,groupPageOf,@@ -421,6 +422,7 @@ export function Sidebar({machineLabels,isLoadedFor,hasMoreFor,+ activityWatermarkFor,loadMoreFor,loading,remove,@@ -938,15 +940,33 @@ export function Sidebar({* the same reason. Null outside time mode, so no other mode pays for the two passes.*/const timeParts = groupMode === "time" ? partitionSessions(filterRows(sessions)) : null;- const timeGroups = timeParts === null ? [] : groupSessionsByTime(timeParts.active, Date.now());- /** Time mode's exact server share, Project-wide: its buckets span every Agent, so the shared folders and the whole-list "More" read the summed counts. */+ /** Time mode's exact server share, Project-wide: its buckets span every Agent, so the shared folders read the summed counts. */const projectCounts = totalCategoryCounts(countsByAgent);/** Agents holding rows of a category anywhere in this Project — time mode's fetch fan-out (the counts are kept in step locally, so they cover freshly added rows too). */const projectAgentsFor = (category: SessionCategory) =>[...countsByAgent].filter(([, counts]) => counts[category] > 0).map(([agentId]) => agentId);+ /**+ * Time mode's rows, cut at the list's watermark BEFORE bucketing. Every Agent (on every+ * machine) pages its own stream, so only the rows above the most recent cursor that still+ * has more are a true prefix of the Project's activity order; the rows below it stay in+ * memory until "load more" lowers it. That is what makes the list grow only at its bottom —+ * a fetched page can no longer land rows in "Last day" above an "Earlier" the user is+ * reading. A search sees every loaded row (a hidden match would read as no match), and the+ * open conversation always shows.+ */+ const timeVisible =+ timeParts === null+ ? []+ : cutAtWatermark(+ timeParts.active,+ searching ? null : activityWatermarkFor(projectAgentsFor("active"), "active"),+ activeSessionId,+ );+ const timeGroups = timeParts === null ? [] : groupSessionsByTime(timeVisible, Date.now());+/** Agents with an unfetched active page left; the whole-list "More" of time mode pages all of them at once. */const timeMoreAgents = projectAgentsFor("active").filter((id) => hasMoreFor(id, "active"));@@ -1214,12 +1234,17 @@ export function Sidebar({for (const group of groupPageSlice(orderedWorkspaceGroups, shownGroupPage)) {const counts = workspaceGroupCounts.get(group.key);const total = counts?.totals.active ?? 0;- // Counts not in yet (0): nothing is known to be missing, so nothing is asked for.- const loaded = group.sessions.filter((s) => sessionCategory(s) === "active").length;- if (loaded >= Math.min(SIDEBAR_PAGE_SIZE, total)) continue;const agents = [...new Set([...(counts?.agents.active ?? []), ...group.sessions.map((s) => s.agentId)]),];+ // Counts not in yet (0): nothing is known to be missing, so nothing is asked for. What+ // the group SHOWS is what a first page has to fill: rows in memory below its watermark+ // (another Agent's stream reached further) are not on screen.+ const loaded = cutAtWatermark(+ group.sessions.filter((s) => sessionCategory(s) === "active"),+ activityWatermarkFor(agents, "active", group.key),+ ).length;+ if (loaded >= Math.min(SIDEBAR_PAGE_SIZE, total)) continue;const unloaded = agents.filter((id) => !isLoadedFor(id, "active", group.key));if (unloaded.length === 0) continue;const key = loadKey(group.key, "active");@@ -1240,6 +1265,7 @@ export function Sidebar({shownGroupPage,workspaceGroupCounts,isLoadedFor,+ activityWatermarkFor,loadMoreFor,pendingLoads,]);@@ -1699,7 +1725,7 @@ export function Sidebar({scheduled={scheduledSessions.has(s.sessionId)}pinned={pinnedSessions.has(s.sessionId)}// Pinning is an ACTIVE-list priority: folder rows (subagent / scheduled /- // evaluations / archived) are ordered chronologically inside their folder and+ // evaluations / archived) are ordered by last activity inside their folder and// never pass through orderSessionRows, so a pin there would write an id, light// the glyph, move nothing — and then shift the active list's drag partition.canPin={activeList}@@ -1798,7 +1824,17 @@ export function Sidebar({agentIds: string[],totals: SessionCategoryCounts | undefined,) => {- const rows = parts[category];+ const loadedRows = parts[category];+ // In last-activity order, cut at the folder's watermark: a folder spanning several+ // streams (Agents, machines) shows only what they have all reached, so its "More" adds+ // rows below the ones on screen and never above them (the active list's rule).+ const rows = cutAtWatermark(+ loadedRows,+ searching || agentIds.length === 0+ ? null+ : activityWatermarkFor(agentIds, category, fetchScope(groupKey)),+ activeSessionId,+ );// While searching the folder speaks for its loaded MATCHES only: a match hidden// behind a collapsed folder would look like a missing result (the models page's// search-forces-open rationale), so the folder is forced open, labelled by the@@ -1806,7 +1842,7 @@ export function Sidebar({// (the server cannot search unloaded rows, and every match is already on screen).if (searching && rows.length === 0) return null;// Loaded rows win a disagreement with the totals (counts refresh only on reload).- const total = searching ? rows.length : Math.max(totals?.[category] ?? 0, rows.length);+ const total = searching ? rows.length : Math.max(totals?.[category] ?? 0, loadedRows.length);if (total === 0) return null;const key = folderKey(groupKey, category);const cap = folderCaps.get(key) ?? SIDEBAR_PAGE_SIZE;@@ -1886,11 +1922,26 @@ export function Sidebar({// FETCHED: a pinned conversation that lives past the loaded pages does not surface// until "More" pulls its page in (the list has no server-side pin), so the pinned// cluster leads what is loaded, not the Agent's whole history. Folder rows keep- // their chronological order: pinning and manual order are active-list concerns.+ // their last-activity order: pinning and manual order are active-list concerns.// While searching, the display cap is bypassed — every loaded match shows, and// "More" hides (it pages the unfiltered list and would read as "more matches",// which the server cannot promise).- const orderedActive = orderSessionRows(parts.active, (s) => s.sessionId, {+ //+ // Before any of that, the rows are cut at the group's watermark: an Agent group on+ // several machines and a Workspace group spanning Agents both merge several streams,+ // and only the rows above the most recent cursor that still has more are a true prefix+ // of the group's activity order. The rest wait in memory, so "More" only ever adds rows+ // below the ones on screen. A time bucket has no streams of its own (its rows arrive+ // already cut), and a search sees every loaded row.+ const activeAgents = agentsFor("active");+ const visibleActive = cutAtWatermark(+ parts.active,+ searching || activeAgents.length === 0+ ? null+ : activityWatermarkFor(activeAgents, "active", fetchScope(groupKey)),+ activeSessionId,+ );+ const orderedActive = orderSessionRows(visibleActive, (s) => s.sessionId, {pinned: pinnedSessions,sortMode: effectiveSortMode,order: sessionOrder,@@ -1907,7 +1958,6 @@ export function Sidebar({// it is fetched out), which is when the loaded rows become the truth: server counts// refresh only on reload, so a count drifting above reality would otherwise leave a row// that reveals nothing behind it.- const activeAgents = agentsFor("active");const fullyLoaded =activeAgents.length > 0 &&!activeAgents.some((id) => hasMoreFor(id, "active", fetchScope(groupKey)));@@ -1916,7 +1966,7 @@ export function Sidebar({// every folder below.const plan = revealPlan({cap: groupCaps.get(groupKey) ?? SIDEBAR_PAGE_SIZE,- loaded: parts.active.length,+ loaded: visibleActive.length,total: totals?.active ?? 0,fullyLoaded,});@@ -1926,12 +1976,12 @@ export function Sidebar({const folders = FOLDER_CATEGORIES.map((category) =>renderFolder(groupKey, category, parts, withAgentHint, agentsFor(category), totals),);- const empty = parts.active.length === 0 && folders.every((f) => f === null);+ const empty = visibleActive.length === 0 && folders.every((f) => f === null);const activePending = pendingLoads.has(loadKey(groupKey, "active"));// Rows the server counts that no page has loaded yet — a Workspace group known from// the counts alone while its own first page is on its way (or, after a failed fetch,// waiting on the reveal row below to be asked for again). Not "no conversations".- const awaitingRows = !searching && parts.active.length === 0 && hiddenActive > 0;+ const awaitingRows = !searching && visibleActive.length === 0 && hiddenActive > 0;return (<>{empty ? (@@ -1947,7 +1997,7 @@ export function Sidebar({)) : (// Drag-reorder is offered on the active list under manual sort (folders keep- // chronological order), and never on a search-filtered view.+ // last-activity order), and never on a search-filtered view.renderRows(shownActive, withAgentHint, dragCtx, true))}@@ -1959,7 +2009,7 @@ export function Sidebar({label={S.chat.expandRestSessions(hiddenActive)}ariaLabel={S.chat.expandRestSessions(hiddenActive)}pending={activePending}- onClick={() => showMore(groupKey, activeAgents, parts.active.length)}+ onClick={() => showMore(groupKey, activeAgents, visibleActive.length)}className="mt-0.5"/>)}@@ -2945,8 +2995,8 @@ export function Sidebar({so a row can never sit under a bucket its own timestamp contradicts. Empty bucketsare dropped, and there are at most three, so this mode never paginates its groups.The buckets span every Agent and every Workspace: a bucket's "More" only reveals- further loaded rows, while fetching the next page and reaching the Subagents /- Scheduled / Archived rows happen once for the whole Project, below. */}+ further rows already shown in it, while fetching the next page and reaching the+ Subagents / Scheduled / Archived rows happen once for the whole Project, below. */}{groupMode !== "time" || timeParts === null ? null : loading && sessions.length === 0 ? (<SkeletonList rows={5} />) : (@@ -2984,22 +3034,20 @@ export function Sidebar({</p>)}- {/* Whole-list paging: a fetched page lands in whichever bucket its rows' activity- puts them, so the row that pulls one belongs to the list, not to a bucket —- and its label says "conversations" where a bucket's says "more". */}- {!searching &&- timeParts.active.length < projectCounts.active &&- timeMoreAgents.length > 0 && (- <MoreRow- label={S.chat.loadMoreSessions}- ariaLabel={S.chat.loadMoreSessions}- pending={pendingLoads.has(loadKey(TIME_FOLDERS_GROUP_KEY, "active"))}- onClick={() =>- trackedLoadMore(TIME_FOLDERS_GROUP_KEY, "active", timeMoreAgents)- }- className="mt-1"- />- )}+ {/* Whole-list paging: every Agent stream with more advances a page, which lowers+ the watermark and adds rows below the last one shown — in whichever bucket+ their activity puts them, so the row that pulls them belongs to the list, not+ to a bucket, and its label says "conversations" where a bucket's says "more".+ It stands while any stream has more (the server's limit+1 answer). */}+ {!searching && timeMoreAgents.length > 0 && (+ <MoreRow+ label={S.chat.loadMoreSessions}+ ariaLabel={S.chat.loadMoreSessions}+ pending={pendingLoads.has(loadKey(TIME_FOLDERS_GROUP_KEY, "active"))}+ onClick={() => trackedLoadMore(TIME_FOLDERS_GROUP_KEY, "active", timeMoreAgents)}+ className="mt-1"+ />+ )}{/* The shared, Project-wide folders (see timeFolders). */}<div className="pt-2.5">{timeFolders}</div>diff --git a/packages/web/src/lib/session-grouping.ts b/packages/web/src/lib/session-grouping.tsindex 38870bf7..4f8567ce 100644--- a/packages/web/src/lib/session-grouping.ts+++ b/packages/web/src/lib/session-grouping.ts@@ -106,7 +106,8 @@ export function workspaceLabel(workspace: string): string {* display cap step for active rows — 10 conversations show by default and every "More"* click reveals/loads 10 more. Fetches use limit = SIDEBAR_PAGE_SIZE + 1 (see splitPage)* so one request both fills a page and answers "is there more" without a- * response-envelope change.+ * response-envelope change. Pages run in activity order (compareActivityDesc), cut at the+ * watermark (cutAtWatermark) wherever several streams merge.*/export const SIDEBAR_PAGE_SIZE = 10;@@ -209,6 +210,85 @@ export function revealPlan({};}+/**+ * A row's place in the sidebar's activity order — the order every list of it is displayed+ * AND paged in (the server's `order=activity`): last activity first, ties broken by id.+ */+export interface ActivityKey {+ lastActiveAt: string;+ sessionId: string;+}++/**+ * The activity order: `lastActiveAt` descending, then `sessionId` descending, both compared by+ * code point (`<` / `>`, never `localeCompare`). Negative when `a` is more recent.+ *+ * Code point because the two ends must agree on one total order: the browser names a page's+ * cursor and the server slices on it, and a collation that ranks case or punctuation+ * differently from the server would skip or repeat a row at every page boundary it touches.+ * The stamps are uniform ISO-8601 UTC strings, so string order is time order.+ */+export function compareActivityDesc(a: ActivityKey, b: ActivityKey): number {+ if (a.lastActiveAt !== b.lastActiveAt) return a.lastActiveAt > b.lastActiveAt ? -1 : 1;+ if (a.sessionId !== b.sessionId) return a.sessionId > b.sessionId ? -1 : 1;+ return 0;+}++/** The key alone, detached from the row — what a page position stores, so a later live event that moves the row does not move the cursor with it. */+export const activityKeyOf = (row: ActivityKey): ActivityKey => ({+ lastActiveAt: row.lastActiveAt,+ sessionId: row.sessionId,+});++/** The `before=` query value of a cursor: `<lastActiveAt>,<sessionId>` (neither half can contain a comma). */+export const activityCursorParam = (key: ActivityKey): string =>+ `${key.lastActiveAt},${key.sessionId}`;++/** One server stream's position as the watermark sees it: the key of the last row read from it, and whether rows lie below that. */+export interface StreamPosition {+ hasMore: boolean;+ cursor: ActivityKey | null;+}++/**+ * The watermark of a list merged from several streams (Agents, machines): the most recent+ * cursor among the streams that still have more. Every row a stream has not served yet lies+ * below its own cursor, so nothing missing can sort above this key — the rows at or above it+ * are a true prefix of the merged order, and rows below it may still have unfetched rows+ * between them.+ *+ * Null when no stream has more (everything is fetched; every loaded row shows). A stream with+ * more but no cursor — nothing read from it yet — bounds nothing, so what is loaded still shows.+ */+export function activityWatermark(streams: readonly StreamPosition[]): ActivityKey | null {+ let mark: ActivityKey | null = null;+ for (const { hasMore, cursor } of streams) {+ if (!hasMore || cursor === null) continue;+ if (mark === null || compareActivityDesc(cursor, mark) < 0) mark = cursor;+ }+ return mark;+}++/**+ * The rows a merged list shows: those at or above `watermark`, in activity order. `keep` (the+ * open conversation) stays wherever it falls — a reader is never left looking at a chat its+ * own list does not show. A null watermark keeps every row.+ *+ * The rows below are fetched but held back: showing them now would let a later page insert+ * rows above them, and a list that grows anywhere but at its bottom reads as rows jumping.+ */+export function cutAtWatermark<T extends ActivityKey>(+ rows: readonly T[],+ watermark: ActivityKey | null,+ keep?: string | null,+): T[] {+ const kept =+ watermark === null+ ? [...rows]+ : rows.filter((r) => r.sessionId === keep || compareActivityDesc(r, watermark) <= 0);+ return kept.sort(compareActivityDesc);+}+/*** Applies the limit+1 fetch trick: `fetched` came from a request with `limit = pageSize + 1`;* the visible page is the first `pageSize` items, and an overflow item (never shown) proves@@ -551,11 +631,12 @@ export interface TimeGroup<T = SessionInfo> {/*** Buckets Sessions by their last activity into the three time groups, in TIME_BUCKETS* order. Empty buckets are dropped — a "Last day" header over nothing states an absence- * the list is not asked to report. Members are sorted by `lastActiveAt` desc (the flat- * store list concatenates per-Agent responses, so its order isn't globally chronological);- * the sidebar re-orders them again for pins and manual sort.+ * the list is not asked to report. Members are sorted in activity order (compareActivityDesc;+ * the flat store list merges per-Agent responses, so its order is not one to rely on); the+ * sidebar re-orders them again for pins and manual sort. The caller has already cut the rows at+ * the list's watermark, so a bucket only ever holds a prefix of the activity order.*/-export function groupSessionsByTime<T extends { lastActiveAt: string }>(+export function groupSessionsByTime<T extends ActivityKey>(sessions: readonly T[],nowMs: number,): TimeGroup<T>[] {@@ -570,9 +651,7 @@ export function groupSessionsByTime<T extends { lastActiveAt: string }>(for (const bucket of TIME_BUCKETS) {const rows = byBucket.get(bucket);if (rows === undefined) continue;- rows.sort((a, b) =>- a.lastActiveAt < b.lastActiveAt ? 1 : a.lastActiveAt > b.lastActiveAt ? -1 : 0,- );+ rows.sort(compareActivityDesc);groups.push({ key: timeGroupKey(bucket), bucket, sessions: rows });}return groups;diff --git a/packages/web/src/lib/session-merge.ts b/packages/web/src/lib/session-merge.tsindex 23723fe5..80aad700 100644--- a/packages/web/src/lib/session-merge.ts+++ b/packages/web/src/lib/session-merge.ts@@ -7,13 +7,16 @@* across the sources that answered; a source that could not answer contributes no count,* which is the truth — a count is a claim about what a server holds now.*/+import { compareActivityDesc } from "./session-grouping";+import type { ActivityKey } from "./session-grouping";-/** Newest first, by the field the server's own index orders on; ties by id, so the order is total. */-export function newestFirst<T extends { createdAt: string; sessionId: string }>(- a: T,- b: T,-): number {- return b.createdAt.localeCompare(a.createdAt) || b.sessionId.localeCompare(a.sessionId);+/**+ * Most recently active first: the order the sidebar displays its rows in and the order every+ * server pages them in (`order=activity`), so the merged pool and each source's pages agree.+ * Ties by id, so the order is total and equal stamps do not reshuffle between refreshes.+ */+export function mostRecentFirst<T extends ActivityKey>(a: T, b: T): number {+ return compareActivityDesc(a, b);}/**diff --git a/packages/web/src/lib/session-order.ts b/packages/web/src/lib/session-order.tsindex 0f2d229d..48c2c259 100644--- a/packages/web/src/lib/session-order.ts+++ b/packages/web/src/lib/session-order.ts@@ -23,7 +23,7 @@* Storage is injectable (model-group-expansion.ts convention: vitest runs in Node, no* localStorage); malformed values degrade to the defaults.*/-import { pinnedFirst } from "./session-grouping";+import { compareActivityDesc, pinnedFirst } from "./session-grouping";import type { GroupMode } from "../components/ui/group-list";export type SessionSortMode = "recent" | "manual";@@ -174,17 +174,21 @@ export function orderWithinPinPartitions<T>(* The full row-ordering pipeline of one group's active list:** 1. recency — newest `recencyOf` first (the Session's `lastActiveAt`: 「最近更新」 means- * last ACTIVITY, not creation), ties broken by key descending to match the store's- * stable tiebreaker. Applied in both modes: it IS the recent mode's order, and in- * manual mode it is the order rows not yet in the stored sequence arrive in.+ * last ACTIVITY, not creation), ties broken by key descending. Both compare by code+ * point (compareActivityDesc), the order the server pages in and the watermark cuts at:+ * under a collation, rows sharing a stamp could display in another order than the cut+ * reveals them, and a page that reveals a tied row would then insert it above one+ * already shown. Applied in both modes: it IS the recent mode's order, and in manual+ * mode it is the order rows not yet in the stored sequence arrive in.* 2. the pinned cluster first (pinnedFirst), then* 3. under manual sort, the stored order within the pinned cluster and within the rest* independently, so a drag can never move a row across the pin boundary.*- * Only rows already FETCHED are ordered. The server still pages by `created_at DESC`- * (listByAgent — there is no index on last_active_at), so a Session created long ago but- * active today sits on a later page and cannot climb into the sidebar's first page until- * "More" pulls that page in; fixing that needs a server-side ordering + index change.+ * Only rows already FETCHED — and shown: the sidebar cuts each merged list at its watermark+ * first (session-grouping.ts's cutAtWatermark) — are ordered. The server pages the list in this+ * same activity order (`order=activity`, sorted in memory per Agent; no index is involved), so+ * a Session created long ago but active today is on the first page, and "More" only ever adds+ * rows below the ones on screen.*/export function orderSessionRows<T>(rows: readonly T[],@@ -199,8 +203,11 @@ export function orderSessionRows<T>(): T[] {const recencyOf = opts.recencyOf;const byRecency = recencyOf- ? [...rows].sort(- (a, b) => recencyOf(b).localeCompare(recencyOf(a)) || keyOf(b).localeCompare(keyOf(a)),+ ? [...rows].sort((a, b) =>+ compareActivityDesc(+ { lastActiveAt: recencyOf(a), sessionId: keyOf(a) },+ { lastActiveAt: recencyOf(b), sessionId: keyOf(b) },+ ),): rows;// Recent mode passes an empty order, which is orderWithinPinPartitions's identity.diff --git a/packages/web/src/state/sessions.tsx b/packages/web/src/state/sessions.tsxindex f3b9effd..eaf1fa3a 100644--- a/packages/web/src/state/sessions.tsx+++ b/packages/web/src/state/sessions.tsx@@ -8,10 +8,18 @@* benchmark Sessions are not loaded until their collapsed folder is opened. Each pair fetches* SIDEBAR_PAGE_SIZE sessions per page (requesting one extra to detect "has more" — see* splitPage); `loadMoreFor` fetches a pair's first page when unloaded and the next page- * otherwise (deduplicated by sessionId — new sessions shift server offsets), so every- * category's paging is independent of the others. A reload resets each **loaded** pair- * back to its first page (an open folder must not blank on an event-triggered refresh)- * and leaves unopened folders unloaded.+ * otherwise, so every category's paging is independent of the others. A reload resets each+ * **loaded** pair back to its first page (an open folder must not blank on an event-triggered+ * refresh) and leaves unopened folders unloaded.+ *+ * **Activity order, cursor paging**: every page is asked for in the sidebar's own display order+ * (`order=activity`: last activity first) and continues from the key of the last row read+ * (`before=`), never from an offset — activity reorders the list while it is read, and an+ * offset would skip a row that moved above it. A row that moves above a cursor is not served+ * again; a loaded one moves in place on its `session_state`, and an unloaded one is fetched+ * on it (adoptLiveSession), which is what keeps the pages complete. A list merged from several+ * streams (Agents, machines) shows only the rows above its watermark (watermarkFor; the+ * sidebar cuts at it), so a later page can only ever add rows below the ones on screen.** **Own rows only**: every fetch asks the server for the user's own conversations* (`excludeOrg`), so an organization's desk, ticket and sub-sessions are in neither the rows@@ -63,7 +71,7 @@ import {publishBuiltinBrowserResync,} from "../features/builtin-browser/browser-events";import { WORKFLOW_UPDATED_EVENT } from "../lib/workflow-tabs";-import { mergeCounts, newestFirst } from "../lib/session-merge";+import { mergeCounts, mostRecentFirst } from "../lib/session-merge";import {forgetSessionMachines,machineForSession,@@ -80,6 +88,8 @@ import { machineIdOf } from "../lib/workspace-machines";import {FOLDER_CATEGORIES,SIDEBAR_PAGE_SIZE,+ activityKeyOf,+ activityWatermark,isOrgSession,sessionCategory,splitPage,@@ -87,13 +97,14 @@ import {workspaceGroupMachine,workspaceGroupQuery,} from "../lib/session-grouping";+import type { ActivityKey, StreamPosition } from "../lib/session-grouping";import { noteScheduleEvent } from "../features/schedules/schedule-store";import { useProject } from "./project";interface SessionsContextValue {- /** Loaded list (paged per Agent and category; each Agent's entries newest first). */+ /** Loaded list (paged per Agent and category, in activity order — most recently active first). */sessions: SessionInfo[];- /** agentId → that Agent's loaded Session list, newest first (empty array if none). */+ /** agentId → that Agent's loaded Session list, most recently active first (empty array if none). */byAgent: ReadonlyMap<string, SessionInfo[]>;/** agentId → per-category totals from the last list fetch (folder labels; kept in step locally on add / remove / archive toggles). */countsByAgent: ReadonlyMap<string, SessionCategoryCounts>;@@ -124,6 +135,16 @@ interface SessionsContextValue {isLoadedFor: (agentId: string, category: SessionCategory, workspaceGroup?: string) => boolean;/** Whether the server still holds unfetched Sessions of a category for an Agent (or for one of its Workspace groups) — an unloaded pair answers from the counts. */hasMoreFor: (agentId: string, category: SessionCategory, workspaceGroup?: string) => boolean;+ /**+ * The watermark of a list fed by these Agents' streams of `category` — scoped to one+ * Workspace group when given — on every source: the key a sidebar list is cut at, so it shows+ * a true prefix of its activity order (see watermarkFor). Null = show every loaded row.+ */+ activityWatermarkFor: (+ agentIds: readonly string[],+ category: SessionCategory,+ workspaceGroup?: string,+ ) => ActivityKey | null;/*** Whether the list has NOTHING to show yet — including the window where the Agent set it* is fetched for is itself being refetched (a Project switch clears it). Consumers gate@@ -252,17 +273,41 @@ const sourcesFor = (? [...allSources]: [workspaceGroupMachine(workspaceGroup)];-/** One pair's paging cursor. */-interface PagePosition {- /** Whether the server still has unfetched rows past `fetched`. */- hasMore: boolean;- /**- * Rows consumed from the server's category stream — the exact offset of the next- * page. Deliberately NOT derived from the loaded list: `add()` prepends rows that- * were never part of any page (deep-link self-heal), and counting those would skip- * a server row on the next fetch.- */- fetched: number;+/**+ * One pair's paging cursor: whether the server still has rows below it, and the activity key+ * of the last row read from the stream (null when it has yielded none). The key is stored when+ * the page lands and never re-derived from the pool — a live event moves the row's own key, and+ * the stream still continues below where it was READ; `add()` slips in rows no page served.+ */+type PagePosition = StreamPosition;++/**+ * The watermark of the list fed by `agentIds`' streams of `category` — each Agent's whole+ * stream, or one Workspace group's own — on every source the scope is about: the most recent+ * cursor among the streams that still have more (session-grouping.ts's activityWatermark).+ *+ * A group's own stream that has not been read yet stands on the Agent's whole stream instead:+ * that stream's loaded prefix, cut by Workspace, is a prefix of the group's, so it bounds the+ * group's rows exactly as far as it reached. A pair nothing has been read from bounds nothing —+ * the rows a machine out of reach left in the cache keep showing.+ */+export function watermarkFor(+ state: { pageState: ReadonlyMap<string, PagePosition>; machineIds: readonly string[] },+ agentIds: readonly string[],+ category: SessionCategory,+ workspaceGroup?: string,+): ActivityKey | null {+ const scope = scopeOf(workspaceGroup);+ const positions: PagePosition[] = [];+ for (const agentId of new Set(agentIds)) {+ for (const source of sourcesFor([null, ...state.machineIds], workspaceGroup)) {+ const position =+ state.pageState.get(pageKey(agentId, category, scope, source)) ??+ (scope === "" ? undefined : state.pageState.get(pageKey(agentId, category, "", source)));+ if (position !== undefined) positions.push(position);+ }+ }+ return activityWatermark(positions);}/** Store state: the context value's raw ingredients plus the mutation functions (byAgent / isLoadedFor / hasMoreFor are derived in the Provider). */@@ -331,6 +376,21 @@ interface SessionsStoreState {replace: (session: SessionInfo) => void;setStatus: (sessionId: string, status: SessionStatus, row?: LiveRowFields) => void;setTitle: (sessionId: string, title: string) => void;+ /**+ * A Session of this Project changed run state while no loaded page holds it — a conversation+ * resumed from the CLI, say. It is the most recently active row there is, so it belongs at the+ * top of the list, and no page will ever serve it: it moved above every cursor. One lookup on+ * `source` (where the event came from) fetches the row, and it joins the list when it is one+ * of the list's own — a user's conversation of a listed Agent, not deleted here. Flips that+ * arrive while the lookup runs share it, and the newest of them is applied to the row it+ * returns. Settles once the lookup has; never rejects.+ */+ adoptLiveSession: (+ sessionId: string,+ source: string | null,+ status: SessionStatus,+ row: LiveRowFields,+ ) => Promise<void>;/*** Live background-task counts of one row, from the user channel's `session_background`;* undefined clears the field the way the server omits it at zero. The row's mark and the@@ -355,6 +415,14 @@ const DELETED_IDS_MAX = 500;*/const LIVE_STATUS_MAX = 1000;+/**+ * Cap on remembered declined ids — Sessions a live event named, that were looked up once and+ * found not to be this list's (an organization's desk or ticket session, an id that is gone).+ * Company mode flips its Sessions all day long, and each would otherwise cost a lookup per flip.+ * Same eviction as DELETED_IDS_MAX; a dropped entry costs one more lookup.+ */+const DECLINED_IDS_MAX = 1000;+/** `live` with `sessionId` at `status` — the same map when nothing changed, so no render is spent on a repeat. */function rememberStatus(live: ReadonlyMap<string, SessionStatus>,@@ -378,6 +446,21 @@ export function createSessionsStore() {// Generation counter: invalidates any in-flight response once the Project/Agent set// changes or a reload happens.let gen = 0;+ /** Ids being looked up for adoption → the lookup, and the newest flip the channel reported meanwhile. */+ const adopting = new Map<+ string,+ { done: Promise<void>; latest: { status: SessionStatus; row: LiveRowFields } }+ >();+ /** Ids looked up and found not to be this list's — never asked about again (DECLINED_IDS_MAX). */+ const declined = new Set<string>();+ /**+ * Adoption order: each adopted id → its sequence number. A reload that STARTED before an+ * adoption may have been answered before that Session ran, so its pages can lack the row: it+ * carries over every row adopted since it started. Rows adopted earlier are the pages' to+ * decide — a reload that started after them read the server as it stands.+ */+ let adoptSeq = 0;+ const adoptedAt = new Map<string, number>();return createStore<SessionsStoreState>((set, get) => {/**@@ -419,6 +502,37 @@ export function createSessionsStore() {}};+ /**+ * Puts one row in the list (replacing an entry with its id), keeping the totals in step.+ * Counts the row only when the pair's fetched pages provably held its whole category+ * (loaded, no more): the row is then genuinely new to the server totals. Otherwise+ * (deep-link self-heal or a live adoption of an unfetched row) the counts already include+ * it — a possible one-off drift self-heals on the next reload.+ */+ const insert = (session: SessionInfo) => {+ const existed = get().sessions.some((s) => s.sessionId === session.sessionId);+ // Per SOURCE and stream: the row belongs to the machine it lives on, and the whole+ // stream (scope "") is the one the totals were fetched against.+ const source = machineForSession(session.sessionId);+ const category = sessionCategory(session);+ if (+ !existed &&+ get().pageState.get(pageKey(session.agentId, category, "", source))?.hasMore === false+ ) {+ adjustCount(session, category, 1);+ }+ set({+ sessions: [session, ...get().sessions.filter((s) => s.sessionId !== session.sessionId)],+ });+ };++ /** Remembers an id as not this list's (DECLINED_IDS_MAX bounds the set, oldest out first). */+ const decline = (sessionId: string) => {+ declined.delete(sessionId);+ declined.add(sessionId);+ while (declined.size > DECLINED_IDS_MAX) declined.delete(declined.values().next().value!);+ };+return {projectId: null,agentIds: [],@@ -443,6 +557,7 @@ export function createSessionsStore() {// once an Agent set exists, is what clears it.if (!projectId || agentIds.length === 0) return;const g = ++gen;+ const adoptMark = adoptSeq;// Only when there is nothing on screen. Rows already listed stay true while this// refetches — a machine appearing or dropping out changes which servers are asked,// not whether what is already shown is still so — and the chat page reads this flag@@ -486,8 +601,8 @@ export function createSessionsStore() {projectId,agentId,{- offset: 0,limit: SIDEBAR_PAGE_SIZE + 1,+ order: "activity",category,excludeOrg: true,...(scope === "" ? {} : { workspaceGroup: scope }),@@ -568,9 +683,10 @@ export function createSessionsStore() {const nextWorkspaceLatest = new Map<string, Readonly<Record<string, string>>>();for (const r of results) {for (const p of r.pages) {+ const last = p.items.at(-1);nextPageState.set(pageKey(r.agentId, p.category, p.scope, r.source), {hasMore: p.hasMore,- fetched: p.items.length,+ cursor: last === undefined ? null : activityKeyOf(last),});if (p.counts)countParts.set(r.agentId, [...(countParts.get(r.agentId) ?? []), p.counts]);@@ -683,9 +799,19 @@ export function createSessionsStore() {if (latest) nextWorkspaceLatest.set(agentId, latest);}}- // Newest first across every source: each answered sorted, and concatenating sorted- // lists does not give a sorted list.- nextSessions.sort(newestFirst);+ // A Session adopted from a live event after this reload started may have run after+ // its page was read, and no page will serve it again: it is carried over. Older+ // adoptions are the pages' to decide — those were read with the Session already+ // there, and one that missed them sits below its stream's cursor.+ for (const s of get().sessions) {+ if ((adoptedAt.get(s.sessionId) ?? 0) <= adoptMark || seen.has(s.sessionId)) continue;+ seen.add(s.sessionId);+ nextSessions.push(s);+ }+ for (const [sessionId, at] of adoptedAt) if (at <= adoptMark) adoptedAt.delete(sessionId);+ // Most recently active first across every source: each answered sorted, and+ // concatenating sorted lists does not give a sorted list.+ nextSessions.sort(mostRecentFirst);// No fetch returns an organization row (`excludeOrg`), so one held here entered// through add() for the page showing it (an open desk or ticket session) and no// reload can bring it back: carry it over, or that page's writes stop reaching it.@@ -710,76 +836,74 @@ export function createSessionsStore() {/*** Category page fetch for each given Agent: the first page when the pair is unloaded* (skipped unless the counts say the category holds anything), the next page when- * loaded with more. The offset is the pair's `fetched` cursor — rows actually- * consumed from the server's stream, never rows `add()` slipped in. A session- * created since the last page still shifts server offsets, so appended rows are- * deduplicated by sessionId (a short page is fine — `hasMore` comes from the server- * response, and the next click continues from the advanced cursor).+ * loaded with more — the rows strictly below the pair's cursor, in activity order.+ * Appended rows are still deduplicated by sessionId: a row can reach the pool down two+ * streams (the Agent's whole one and a group's own), and `add()` slips rows in too.** `workspaceGroup` pages ONE group's own server stream instead of the Agent's whole* one, under its own cursor: this is what keeps a Workspace group's "load more" from* consuming the page its siblings were about to read and moving their rows on screen.* Rows land in the same pool either way — a scope only decides which stream is being* walked, so the pool absorbs any overlap by sessionId.+ *+ * A group's FIRST page continues from the Agent's whole-stream cursor on that source:+ * the whole stream's loaded prefix, cut by Workspace, is a prefix of the group's, so the+ * group's rows above that cursor are already in the pool. Starting over would re-read+ * them and the click would appear to do nothing. When the whole stream is exhausted the+ * pool holds every row the group has there, and the pair is settled without a request.*/loadMoreFor: async (agentIds, category, workspaceGroup) => {const { projectId, machineIds } = get();if (!projectId) return;const sources = sourcesFor([null, ...machineIds], workspaceGroup);const scope = scopeOf(workspaceGroup);- // One target per (Agent, SOURCE): each server pages its own Sessions with its own- // offsets, so a shared cursor would ask one machine for rows only another had- // reached — silently skipping the rows in between.- const targets = [...new Set(agentIds)].flatMap((agentId) =>- sources- .filter((source) => {- const position = get().pageState.get(pageKey(agentId, category, scope, source));- // An unloaded pair: the Agent's own totals still decide whether asking is- // worth a request — they are the SUM over sources, so a machine with none- // still gets one first page, which is what discovers that it has none. A- // scoped pair cannot consult them (they are not broken down by group here),- // so it always gets its first page — the caller only asks for a group it has- // reason to believe holds rows.- if (position === undefined)- return scope !== "" || (get().countsByAgent.get(agentId)?.[category] ?? 0) > 0;- return position.hasMore;- })- .map((source) => ({ agentId, source })),- );- if (targets.length === 0) return;+ // One target per (Agent, SOURCE): each server pages its own Sessions under its own+ // cursor, and a cursor one machine reached says nothing about another's rows.+ const targets: { agentId: string; source: string | null; before: ActivityKey | null }[] =+ [];+ /** Group pairs the whole stream already answers for (see above): loaded with nothing more to read. */+ const settled: { agentId: string; source: string | null; cursor: ActivityKey | null }[] =+ [];+ const { pageState, countsByAgent } = get();+ for (const agentId of new Set(agentIds)) {+ for (const source of sources) {+ const position = pageState.get(pageKey(agentId, category, scope, source));+ if (position !== undefined) {+ if (position.hasMore) targets.push({ agentId, source, before: position.cursor });+ continue;+ }+ // An unloaded whole stream: the Agent's own totals still decide whether asking is+ // worth a request — they are the SUM over sources, so a machine with none still+ // gets one first page, which is what discovers that it has none.+ if (scope === "") {+ if ((countsByAgent.get(agentId)?.[category] ?? 0) > 0)+ targets.push({ agentId, source, before: null });+ continue;+ }+ // An unloaded group stream: it continues from the whole stream (see above). The+ // counts cannot gate it (they are not broken down by group here); the caller only+ // asks for a group it has reason to believe holds rows.+ const whole = pageState.get(pageKey(agentId, category, "", source));+ if (whole !== undefined && !whole.hasMore) {+ settled.push({ agentId, source, cursor: whole.cursor });+ continue;+ }+ targets.push({ agentId, source, before: whole?.cursor ?? null });+ }+ }+ if (targets.length === 0 && settled.length === 0) return;const g = gen;- /**- * Rows of this (Agent, category, group) already in the pool from ONE source. They- * arrived on pages of that source's whole stream, and a prefix of that stream cut by- * Workspace is a prefix of the group's stream — so the count doubles as the offset a- * FIRST scoped fetch starts from. Without it that fetch would re-read rows the group- * already shows and the click would appear to do nothing; counting every source's- * rows would instead skip rows only this source holds.- */- const loadedInScope = (agentId: string, source: string | null, group: string) =>- get().sessions.filter(- (s) =>- s.agentId === agentId &&- sessionCategory(s) === category &&- workspaceGroupKey(s.workspace, machineForSession(s.sessionId)) === group &&- machineForSession(s.sessionId) === source,- ).length;const results = await Promise.all(- targets.map(async ({ agentId, source }) => {- const position = get().pageState.get(pageKey(agentId, category, scope, source));- const offset =- position?.fetched ??- (workspaceGroup === undefined || workspaceGroup === ""- ? 0- : loadedInScope(agentId, source, workspaceGroup));+ targets.map(async ({ agentId, source, before }) => {try {const fetched = (await api.listSessions(projectId,agentId,{- offset,limit: SIDEBAR_PAGE_SIZE + 1,+ order: "activity",+ ...(before === null ? {} : { before }),category,excludeOrg: true,...(scope === "" ? {} : { workspaceGroup: scope }),@@ -787,7 +911,7 @@ export function createSessionsStore() {source,)).sessions;- return { agentId, source, offset, ...splitPage(fetched, SIDEBAR_PAGE_SIZE) };+ 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.@@ -808,17 +932,18 @@ export function createSessionsStore() {rememberSessionMachine(row.sessionId, r.source);}}- const prevPageState = get().pageState;- const nextPageState = new Map(prevPageState);+ const nextPageState = new Map(get().pageState);for (const r of ok) {- const key = pageKey(r.agentId, category, scope, r.source);- nextPageState.set(key, {+ const last = r.items.at(-1);+ nextPageState.set(pageKey(r.agentId, category, scope, r.source), {hasMore: r.hasMore,- // A first scoped fetch started at the rows the group already held (see- // loadedInScope), so the cursor advances from where it actually read.- fetched: (prevPageState.get(key)?.fetched ?? r.offset) + r.items.length,+ // An empty page leaves the stream where it was read from.+ cursor: last === undefined ? r.before : activityKeyOf(last),});}+ for (const { agentId, source, cursor } of settled) {+ nextPageState.set(pageKey(agentId, category, scope, source), { hasMore: false, cursor });+ }set({...(appended.length > 0 ? { sessions: [...prev, ...appended] } : {}),pageState: nextPageState,@@ -828,24 +953,67 @@ export function createSessionsStore() {add: (session) => {// Invalidate any in-flight reload: the newly created entry mustn't be wiped by a stale snapshot.gen += 1;- // Count the row only when the pair's fetched pages provably held its whole category- // (loaded, no more): the row is then genuinely new to the server totals. Otherwise- // (deep-link self-heal of an unfetched row) the counts already include it — a- // possible one-off drift self-heals on the next reload.- const existed = get().sessions.some((s) => s.sessionId === session.sessionId);- // Per SOURCE and stream: the row belongs to the machine it lives on, and the whole- // stream (scope "") is the one the totals were fetched against.- const source = machineForSession(session.sessionId);- const category = sessionCategory(session);+ insert(session);+ },++ adoptLiveSession: (sessionId, source, status, row) => {+ const running = adopting.get(sessionId);+ if (running !== undefined) {+ running.latest = { status, row };+ return running.done;+ }+ const state = get();+ const { projectId } = state;if (- !existed &&- get().pageState.get(pageKey(session.agentId, category, "", source))?.hasMore === false+ projectId === null ||+ declined.has(sessionId) ||+ state.deletedSessionIds.has(sessionId) ||+ state.sessions.some((s) => s.sessionId === sessionId)) {- adjustCount(session, category, 1);+ return Promise.resolve();}- set({- sessions: [session, ...get().sessions.filter((s) => s.sessionId !== session.sessionId)],- });+ const entry = { done: Promise.resolve(), latest: { status, row } };+ adopting.set(sessionId, entry);+ entry.done = (async () => {+ let fetched: SessionInfo | null = null;+ let gone = false;+ try {+ fetched = (await api.getSession(sessionId, source)).session;+ } catch (err) {+ // A 404 is an answer (the Session is gone, or was never this server's); anything+ // else may succeed on the next flip.+ gone = err instanceof ApiError && err.status === 404;+ }+ const { latest } = entry;+ adopting.delete(sessionId);+ const now = get();+ // The list moved on to another Project while this was asked: not its row.+ if (now.projectId !== projectId) return;+ if (fetched === null || isOrgSession(fetched) || fetched.projectId !== projectId) {+ if (fetched !== null || gone) decline(sessionId);+ return;+ }+ // An Agent no page of this list is asked about (reload's jobs) has no group to show+ // it in, and the next reload would drop it again. Not declined: the Agent set moves.+ const listed =+ now.agentIds.includes(fetched.agentId) ||+ (source !== null && (now.agentIdsByMachine[source] ?? []).includes(fetched.agentId));+ if (!listed) return;+ if (+ now.deletedSessionIds.has(sessionId) ||+ now.sessions.some((s) => s.sessionId === sessionId)+ ) {+ return;+ }+ rememberSessionMachine(sessionId, source);+ insert(fetched);+ adoptedAt.set(sessionId, ++adoptSeq);+ // The row is as the lookup read it; a flip reported after that read is newer.+ if (latest.row.lastActiveAt >= fetched.lastActiveAt) {+ get().setStatus(sessionId, latest.status, latest.row);+ }+ })();+ return entry.done;},remove: (sessionId) => {@@ -903,13 +1071,12 @@ export function createSessionsStore() {* half is what keeps the two callers consistent: the Session stream carries no flag, so* on its own it would settle a first run into a blank row until the next list fetch.*- * An id no loaded page holds is dropped rather than turned into a row: the event names a- * Session, it does not describe one, and a row invented from a status and a timestamp- * would have no title, Agent or Workspace to render. That same drop is what filters- * another Project's Sessions — this store only ever holds the current Project's rows.- * The STATUS is remembered either way (`liveStatuses`): the user channel is the one- * source that reports a run ending, and company mode reads it for the Sessions this- * list never fetches.+ * An id no loaded page holds is not turned into a row here: the event names a Session, it+ * does not describe one, and a row invented from a status and a timestamp would have no+ * title, Agent or Workspace to render. The user channel fetches such a row instead when+ * it is this Project's (applyUserEvent → adoptLiveSession). The STATUS is remembered+ * either way (`liveStatuses`): the user channel is the one source that reports a run+ * ending, and company mode reads it for the Sessions this list never fetches.*/setStatus: (sessionId, status, row) => {const remembered = rememberStatus(get().liveStatuses, sessionId, status);@@ -1031,11 +1198,21 @@ export function applyUserEvent(// badge. Everything else — the Session the user just navigated away from, a run started from// another tab, a schedule, a subagent — would otherwise sit on whatever status the last list// fetch happened to return.+ //+ // A Session of THIS Project that no loaded page holds is the most recently active row there+ // is, and the activity-ordered pages will never serve it — it moved above every cursor — so+ // it is fetched from where the event came from and joins the list at the top. Another+ // Project's flip is only remembered.if (ev.type === "session_state") {- store.getState().setStatus(ev.sessionId, ev.state, {- lastActiveAt: ev.lastActiveAt,- hasTrace: ev.hasTrace,- });+ const state = store.getState();+ const row = { lastActiveAt: ev.lastActiveAt, hasTrace: ev.hasTrace };+ state.setStatus(ev.sessionId, ev.state, row);+ if (+ ev.projectId === state.projectId &&+ !state.sessions.some((s) => s.sessionId === ev.sessionId)+ ) {+ void state.adoptLiveSession(ev.sessionId, source, ev.state, row);+ }return;}// A title landed. Titles generate at Task start, before the brand-new Session's own@@ -1353,15 +1530,25 @@ export function SessionsProvider({ children }: { children: ReactNode }) {);// More if ANY source has more — or if a source has not been asked at all and the counts,- // which are the sum over sources, say the category holds something.+ // which are the sum over sources, say the category holds something. A group's own stream+ // not asked yet has nothing more on a source whose whole stream is exhausted: every row the+ // group has there is already in the pool (loadMoreFor settles such a pair without asking).const hasMoreFor = useCallback((agentId: string, category: SessionCategory, workspaceGroup?: string) => {const scope = scopeOf(workspaceGroup);let anyUnloaded = false;for (const source of sourcesFor(sources, workspaceGroup)) {const position = pageState.get(pageKey(agentId, category, scope, source));- if (position === undefined) anyUnloaded = true;- else if (position.hasMore) return true;+ if (position !== undefined) {+ if (position.hasMore) return true;+ continue;+ }+ if (+ scope !== "" &&+ pageState.get(pageKey(agentId, category, "", source))?.hasMore === false+ )+ continue;+ anyUnloaded = true;}if (!anyUnloaded) return false;// Unloaded: the counts are the sum over sources, so anything they report is by@@ -1373,6 +1560,12 @@ export function SessionsProvider({ children }: { children: ReactNode }) {[pageState, countsByAgent, sources],);+ const activityWatermarkFor = useCallback(+ (agentIds: readonly string[], category: SessionCategory, workspaceGroup?: string) =>+ watermarkFor({ pageState, machineIds }, agentIds, category, workspaceGroup),+ [pageState, machineIds],+ );+// Reads the store directly rather than the subscribed snapshot: this answers "is this id// already dead", and a caller asking that inside an effect must get the newest answer even// when it runs before its own re-render. Stable identity, so it never re-triggers effects.@@ -1391,14 +1584,9 @@ export function SessionsProvider({ children }: { children: ReactNode }) {if (list) list.push(s);else map.set(s.agentId, [s]);}- // Encounter order is no longer reliable with paging (appended pages are older, but a- // deep-linked old session is prepended via add): sort each Agent's list newest first- // (same key the server sorts by).- for (const list of map.values()) {- list.sort(- (a, b) => b.createdAt.localeCompare(a.createdAt) || b.sessionId.localeCompare(a.sessionId),- );- }+ // Encounter order is not reliable (add() prepends, a live event moves a row's key in+ // place): sort each Agent's list in activity order, the key the server pages by.+ for (const list of map.values()) list.sort(mostRecentFirst);return map;}, [state.sessions]);@@ -1421,6 +1609,7 @@ export function SessionsProvider({ children }: { children: ReactNode }) {machineIds: state.machineIds,isLoadedFor,hasMoreFor,+ activityWatermarkFor,loading: state.loading,machinesUnreachable: state.offlineMachineIds.length > 0,offlineMachineIds: state.offlineMachineIds,@@ -1433,7 +1622,7 @@ export function SessionsProvider({ children }: { children: ReactNode }) {setStatus: state.setStatus,setTitle: state.setTitle,};- }, [state, byAgent, machineLabels, isLoadedFor, hasMoreFor, isDeleted]);+ }, [state, byAgent, machineLabels, isLoadedFor, hasMoreFor, activityWatermarkFor, isDeleted]);return <SessionsContext.Provider value={value}>{children}</SessionsContext.Provider>;}diff --git a/packages/web/test/session-grouping.test.ts b/packages/web/test/session-grouping.test.tsindex 77c33031..56f95fbc 100644--- a/packages/web/test/session-grouping.test.ts+++ b/packages/web/test/session-grouping.test.ts@@ -26,9 +26,19 @@* path or an Agent id.* - Every counted Workspace becomes a group (empty when none of its rows loaded), placed by* the newer of its stamp and its loaded rows, the temp group last; a count of zero forms none.+ * - The activity order is last activity, then id, both by code point — where a locale's+ * collation would rank case or punctuation the other way, it does not follow it.+ * - A merged list's watermark is the most recent cursor among the streams with more; a stream+ * with nothing read, or nothing left, bounds nothing. The cut keeps the rows at or above it+ * and the open conversation wherever it falls; no watermark keeps every row.+ * - Property (seeded, 200 runs): over 1–4 streams paged by cursor, with live flips moving rows+ * up (a loaded one in place, an unloaded one fetched), the cut list is always a prefix of the+ * true order; a load only appends below it, and loading every stream with more shows at+ * least a page more, or the rest.*/import { describe, expect, it } from "vitest";import type { SessionCategoryCounts, SessionInfo } from "@lmliheng/penguin-server/api";+import type { ActivityKey, StreamPosition } from "../src/lib/session-grouping";import {SIDEBAR_PAGE_SIZE,TEMP_WORKSPACE_GROUP_KEY,@@ -36,7 +46,11 @@ import {TIME_FOLDERS_GROUP_KEY,aggregateWorkspaceCounts,aggregateWorkspaceLatest,+ activityCursorParam,+ activityWatermark,+ compareActivityDesc,completeWorkspaceGroups,+ cutAtWatermark,matchesSessionQuery,groupSessionsByTime,groupSessionsByWorkspace,@@ -752,3 +766,186 @@ describe("completeWorkspaceGroups (every counted Workspace is a group, placed byexpect(groups[1]).toMatchObject({ label: "", fullPath: null, temp: true, sessions: [] });});});++describe("the activity order", () => {+ const key = (lastActiveAt: string, sessionId: string): ActivityKey => ({+ lastActiveAt,+ sessionId,+ });+ const ids = (keys: ActivityKey[]) => keys.map((k) => k.sessionId);++ it("puts the most recent activity first, then the higher id", () => {+ const rows = [+ key("2026-09-01T00:00:00.000Z", "s-b"),+ key("2026-09-02T00:00:00.000Z", "s-a"),+ key("2026-09-01T00:00:00.000Z", "s-c"),+ ];+ expect(ids([...rows].sort(compareActivityDesc))).toEqual(["s-a", "s-c", "s-b"]);+ });++ it("compares by code point where a locale's collation would order the pair the other way", () => {+ // The browser names the cursor and the server slices on it: both must agree on one order.+ const stamp = "2026-09-01T00:00:00.000Z";+ for (const [higher, lower] of [+ ["session-abcd", "session-ABCD"],+ ["session-a_b", "session-a-b"],+ ] as const) {+ expect(higher.localeCompare(lower, "en")).toBeLessThan(0);+ expect(compareActivityDesc(key(stamp, higher), key(stamp, lower))).toBeLessThan(0);+ }+ });++ it("names a cursor as <lastActiveAt>,<sessionId>", () => {+ expect(activityCursorParam(key("2026-09-01T00:00:00.000Z", "session-x"))).toBe(+ "2026-09-01T00:00:00.000Z,session-x",+ );+ });+});++describe("the watermark of a merged list", () => {+ const at = (day: number, sessionId = `s-${day}`): ActivityKey => ({+ lastActiveAt: `2026-09-${String(day).padStart(2, "0")}T00:00:00.000Z`,+ sessionId,+ });++ it("is the most recent cursor among the streams that still have more", () => {+ expect(+ activityWatermark([+ { hasMore: true, cursor: at(3) },+ { hasMore: true, cursor: at(7) },+ // Exhausted: everything it holds is already in hand, however recent its last row.+ { hasMore: false, cursor: at(9) },+ ]),+ ).toEqual(at(7));+ });++ it("is absent when no stream has more, and a stream with nothing read bounds nothing", () => {+ expect(activityWatermark([])).toBeNull();+ expect(activityWatermark([{ hasMore: false, cursor: at(3) }])).toBeNull();+ expect(+ activityWatermark([+ { hasMore: true, cursor: null },+ { hasMore: true, cursor: at(2) },+ ]),+ ).toEqual(at(2));+ });++ it("the cut keeps the rows at or above it, in order, and the open conversation wherever it falls", () => {+ const rows = [at(1), at(5), at(3), at(4), at(2)];+ expect(cutAtWatermark(rows, at(3)).map((r) => r.sessionId)).toEqual(["s-5", "s-4", "s-3"]);+ expect(cutAtWatermark(rows, at(3), "s-1").map((r) => r.sessionId)).toEqual([+ "s-5",+ "s-4",+ "s-3",+ "s-1",+ ]);+ expect(cutAtWatermark(rows, null).map((r) => r.sessionId)).toEqual([+ "s-5",+ "s-4",+ "s-3",+ "s-2",+ "s-1",+ ]);+ });+});++/** A seeded linear congruential generator: deterministic runs whose failures name their seed. */+function lcg(seed: number): () => number {+ let state = seed >>> 0;+ return () => {+ state = (Math.imul(state, 1664525) + 1013904223) >>> 0;+ return state / 2 ** 32;+ };+}++describe("property: a list merged from cursor-paged streams", () => {+ /** One server stream and the client's position in it. */+ interface Stream extends StreamPosition {+ rows: ActivityKey[];+ }++ it("is a prefix of the true order after any loads and flips, and loads only append", () => {+ const STAMPS = [1, 2, 3, 5, 8].map((d) => `2026-09-0${d}T00:00:00.000Z`);+ for (let seed = 1; seed <= 200; seed += 1) {+ const rand = lcg(seed);+ const int = (n: number) => Math.floor(rand() * n);+ let n = 0;+ const streams: Stream[] = Array.from({ length: 1 + int(4) }, () => ({+ hasMore: false,+ cursor: null,+ rows: Array.from({ length: int(26) }, () => ({+ lastActiveAt: STAMPS[int(STAMPS.length)]!,+ sessionId: `s${String(n++).padStart(3, "0")}`,+ })),+ }));+ /** What the client holds: its own copy of each row it was served or fetched. */+ const pool = new Map<string, ActivityKey>();+ let clock = Date.parse("2026-09-20T00:00:00.000Z");++ /** The server answering a page: the rows strictly below the cursor, one extra for "more". */+ const load = (stream: Stream) => {+ const below = [...stream.rows]+ .sort(compareActivityDesc)+ .filter((r) => stream.cursor === null || compareActivityDesc(r, stream.cursor) > 0);+ const { items, hasMore } = splitPage(+ below.slice(0, SIDEBAR_PAGE_SIZE + 1),+ SIDEBAR_PAGE_SIZE,+ );+ for (const r of items) pool.set(r.sessionId, { ...r });+ const last = items.at(-1);+ stream.hasMore = hasMore;+ if (last !== undefined) stream.cursor = { ...last };+ };+ const view = () => cutAtWatermark([...pool.values()], activityWatermark(streams));+ const truth = () =>+ streams+ .flatMap((s) => s.rows)+ .sort(compareActivityDesc)+ .map((r) => r.sessionId);+ const expectPrefix = (what: string) => {+ const shown = view().map((r) => r.sessionId);+ expect(shown, `seed ${seed}, ${what}`).toEqual(truth().slice(0, shown.length));+ };++ for (const stream of streams) load(stream);+ expectPrefix("first pages");+ for (let step = 1; step <= 30; step += 1) {+ const roll = rand();+ const withMore = streams.filter((s) => s.hasMore);+ if (roll < 0.65 && withMore.length > 0) {+ const every = roll < 0.25;+ const chosen = every ? withMore : withMore.filter(() => rand() < 0.5);+ if (chosen.length === 0) chosen.push(withMore[int(withMore.length)]!);+ const before = view();+ for (const stream of chosen) load(stream);+ const what = `step ${step}: load ${every ? "every stream" : "some streams"}`;+ expectPrefix(what);+ const after = view();+ expect(after.slice(0, before.length), `seed ${seed}, ${what}`).toEqual(before);+ const floor = before.at(-1);+ if (floor !== undefined) {+ for (const r of after.slice(before.length)) {+ expect(compareActivityDesc(r, floor), `seed ${seed}, ${what}`).toBeGreaterThan(0);+ }+ }+ if (every) {+ const remaining = truth().length - before.length;+ expect(after.length - before.length, `seed ${seed}, ${what}`).toBeGreaterThanOrEqual(+ Math.min(SIDEBAR_PAGE_SIZE, remaining),+ );+ }+ } else {+ const all = streams.flatMap((s) => s.rows);+ if (all.length === 0) continue;+ const row = all[int(all.length)]!;+ clock += 60_000;+ row.lastActiveAt = new Date(clock).toISOString();+ // Loaded: its own key rises in place. Not loaded: the event fetches it (it has moved+ // above every cursor, so no page will serve it again).+ pool.set(row.sessionId, { ...row });+ expectPrefix(`step ${step}: flip ${row.sessionId}`);+ }+ }+ }+ });+});diff --git a/packages/web/test/session-merge.test.ts b/packages/web/test/session-merge.test.tsindex 1aff798d..8d585397 100644--- a/packages/web/test/session-merge.test.ts+++ b/packages/web/test/session-merge.test.ts@@ -1,10 +1,10 @@/*** Merging what several machines answered (lib/session-merge.ts): counts are summed across the- * sources that answered, never zeroed by one that did not; the order is total, so equal- * timestamps do not reshuffle between refreshes.+ * sources that answered, never zeroed by one that did not; the merged rows are in activity+ * order, total, so equal timestamps do not reshuffle between refreshes.*/import { describe, expect, it } from "vitest";-import { mergeCounts, newestFirst } from "../src/lib/session-merge";+import { mergeCounts, mostRecentFirst } from "../src/lib/session-merge";describe("mergeCounts", () => {it("sums each category across the sources that reported", () => {@@ -22,20 +22,33 @@ describe("mergeCounts", () => {});});-describe("newestFirst", () => {- it("orders by createdAt descending, then by id, so the order is total", () => {+describe("mostRecentFirst", () => {+ it("orders by last activity, not creation, then by id, so the order is total", () => {const rows = [- { sessionId: "b", createdAt: "2026-01-01T00:00:00.000Z" },- { sessionId: "a", createdAt: "2026-01-01T00:00:00.000Z" },- { sessionId: "c", createdAt: "2026-01-02T00:00:00.000Z" },+ {+ sessionId: "b",+ createdAt: "2026-01-03T00:00:00.000Z",+ lastActiveAt: "2026-01-04T00:00:00.000Z",+ },+ {+ sessionId: "a",+ createdAt: "2026-01-02T00:00:00.000Z",+ lastActiveAt: "2026-01-04T00:00:00.000Z",+ },+ // Created first, used last: it leads.+ {+ sessionId: "c",+ createdAt: "2026-01-01T00:00:00.000Z",+ lastActiveAt: "2026-01-05T00:00:00.000Z",+ },];- expect([...rows].sort(newestFirst).map((r) => r.sessionId)).toEqual(["c", "b", "a"]);+ expect([...rows].sort(mostRecentFirst).map((r) => r.sessionId)).toEqual(["c", "b", "a"]);// The same input in another order lands the same way: equal stamps are not "stable// by source", they are decided.expect([...rows].reverse()- .sort(newestFirst)+ .sort(mostRecentFirst).map((r) => r.sessionId),).toEqual(["c", "b", "a"]);});diff --git a/packages/web/test/session-order.test.ts b/packages/web/test/session-order.test.tsindex a2327cfc..5b68adea 100644--- a/packages/web/test/session-order.test.ts+++ b/packages/web/test/session-order.test.ts@@ -10,7 +10,9 @@* getter throws degrades instead of escaping.* - Stored rows take their stored positions, unstored newcomers come first in recency order,* and stale stored ids are inert.- * - Recent mode sorts by last activity (ties by id descending) without mutating the input.+ * - Recent mode sorts by last activity (ties by id descending) without mutating the input;+ * stamps and ids compare by code point, the order the watermark cuts in, so rows revealed+ * by a page that tie with shown ones land below them.* - Manual mode applies the stored order inside each pin partition, newcomers on top of theirs.* - A drop moves one id before or after another, and a drop that moves nothing returns the* input so nothing is written; committing a partition fronts it and keeps the others'@@ -32,6 +34,7 @@ import {storeSessionSortMode,} from "../src/lib/session-order";import type { SessionOrderStorage } from "../src/lib/session-order";+import { cutAtWatermark } from "../src/lib/session-grouping";import { blockedStorage, memoryStorage } from "./helpers/storage";const id = (x: string) => x;@@ -169,6 +172,31 @@ describe("orderSessionRows recency (最近更新 = last ACTIVITY, not creation)"expect(tied.map((r) => r.id)).toEqual(["a", "c", "b"]); // input untouched});+ it("rows sharing a stamp keep the watermark's code-point order, so a page revealing a tied row appends it below", () => {+ // Four conversations touched in the same millisecond; ids a collation ranks the other way+ // round (case, `_` against `-`). The server pages them and the watermark cuts them by code+ // point, so the display must too.+ const stamp = "2026-08-14T09:00:00.000Z";+ const tied = ["session-ABCD", "session-a-b", "session-abcd", "session-a_b"].map(+ (sessionId) => ({ sessionId, lastActiveAt: stamp }),+ );+ const show = (rows: readonly { sessionId: string; lastActiveAt: string }[]) =>+ orderSessionRows(rows, (r) => r.sessionId, {+ ...plain,+ sortMode: "recent",+ recencyOf: (r) => r.lastActiveAt,+ }).map((r) => r.sessionId);++ // Before a load: the cursor stopped at `session-a_b`, so only the rows at or above it show.+ const before = show(cutAtWatermark(tied, { lastActiveAt: stamp, sessionId: "session-a_b" }));+ // After it: every stream is exhausted and all four show.+ const after = show(cutAtWatermark(tied, null));++ expect(before).toEqual(["session-abcd", "session-a_b"]);+ expect(after).toEqual(["session-abcd", "session-a_b", "session-a-b", "session-ABCD"]);+ expect(after.slice(0, before.length)).toEqual(before);+ });+it("recency also decides where manual-mode newcomers land, and never crosses the pin boundary", () => {const out = orderSessionRows(rows, key, {pinned: new Set(["new-but-idle"]),diff --git a/packages/web/test/session-status-events.test.ts b/packages/web/test/session-status-events.test.tsindex a54c2b73..1b371be3 100644--- a/packages/web/test/session-status-events.test.ts+++ b/packages/web/test/session-status-events.test.ts@@ -9,7 +9,8 @@* - session_background sets or clears the named row's counts, and moves neither the glyph nor* the status.* - session_title renames the named row in place.- * - An event for a Session no loaded page holds changes nothing, and one that matches the row+ * - An event for a Session no loaded page holds changes nothing (a status from another Project;+ * one of this Project's is fetched — sessions-store.test.ts), and one that matches the row* already is a no-op (the same array, so nothing re-renders).* - A first run settles into the unread dot, not a blank: the run itself proves the Session* has a Trace, from the server's flag or a live status, and a Session that ran never goes@@ -74,7 +75,8 @@ const stateEvent = (state: SessionStatus,lastActiveAt: string,hasTrace = true,-): ServerEvent => ({ type: "session_state", sessionId, state, lastActiveAt, hasTrace });+ projectId = "proj",+): ServerEvent => ({ type: "session_state", sessionId, projectId, state, lastActiveAt, hasTrace });const rowOf = (store: ReturnType<typeof storeWith>, sessionId: string) =>store.getState().sessions.find((s) => s.sessionId === sessionId)!;@@ -185,7 +187,7 @@ describe("session_title on the user channel", () => {describe("events that need no change", () => {const events: ServerEvent[] = [- stateEvent("not-loaded", "running", STARTED),+ stateEvent("not-loaded", "running", STARTED, true, "another-project"),{ type: "session_background", sessionId: "not-loaded", processes: 1, subagents: 0 },{ type: "session_title", sessionId: "not-loaded", title: "whatever" },];diff --git a/packages/web/test/sessions-store.test.ts b/packages/web/test/sessions-store.test.tsindex 9e86b7fb..e822be46 100644--- a/packages/web/test/sessions-store.test.ts+++ b/packages/web/test/sessions-store.test.ts@@ -25,6 +25,29 @@* - An organization row that enters by another door is held for its page, survives reloads,* and never moves the own-only totals; an own row added the same way still counts.*+ * Activity order and cursors:+ * - Every list fetch asks for the activity order; a first page sends no cursor, and the next+ * continues below the last row shown (never the overflow row).+ * - A Workspace group's first own page continues from its Agent's whole-stream cursor on that+ * machine; when that stream is exhausted, no request is sent.+ * - The watermark over two machines is the more recent cursor with more; a machine nothing was+ * read from bounds nothing; everything exhausted shows every row.+ * - A folder pages in activity order too: an archived conversation resumed yesterday lists+ * above one archived last month, and its next page continues below it.+ *+ * Sessions that become active:+ * - A loaded row moves up without a request.+ * - A Session of this Project no page holds is fetched from the machine that announced it and+ * shows at the top; one run's flips share one lookup and the newest flip lands on the row.+ * - Another Project's flip, an organization's Session, an id deleted here and an id that is+ * gone are not listed, and the last three are not asked about again.+ * - A reload that was already running when such a Session was fetched keeps it.+ *+ * Property (seeded, 100 runs): after any sequence of loads, live flips and reloads, every list+ * the sidebar draws — time mode's, each Agent group's, each Workspace group's — is a prefix of+ * its true activity order; a load only appends below what was shown, and a "More" over every+ * stream with more shows at least a page more (or the rest).+ ** Live statuses:* - A session_state for a Session no loaded page holds is remembered without inventing a* row, the run's end included; a loaded row's own status wins over an older remembered one.@@ -35,32 +58,130 @@* - A session_created for this Project reloads wherever it happened; another Project's never.*/import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import type { ServerEvent, SessionInfo, SessionsResponse } from "@lmliheng/penguin-server/api";-import { applyUserEvent, createSessionsStore, liveSessionStatuses } from "../src/state/sessions";+import type {+ ServerEvent,+ SessionCategory,+ SessionCategoryCounts,+ SessionInfo,+ SessionsResponse,+} from "@lmliheng/penguin-server/api";+import {+ applyUserEvent,+ createSessionsStore,+ liveSessionStatuses,+ watermarkFor,+} from "../src/state/sessions";+import {+ SIDEBAR_PAGE_SIZE,+ aggregateWorkspaceCounts,+ compareActivityDesc,+ cutAtWatermark,+ sessionCategory,+ workspaceGroupKey,+} from "../src/lib/session-grouping";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 } from "./helpers/fetch";+import type { FakeFetch, FetchHandler } from "./helpers/fetch";import { stubLocalStorage } from "./helpers/storage";/** A server's answer for one Agent: its list, or an HTTP failure. */type Answer = SessionsResponse | { status: number; code: string };/** What each (machine, Agent) answers; a missing entry is a server that cannot be reached. */const answers = new Map<string, Answer>();+/**+ * Each (machine, Agent)'s whole row set, for a server that pages it the way the real one does+ * (servedPage) — what the cursor tests read from instead of a fixed answer. Also what+ * `GET /api/sessions/:id` reads on that machine; a row in none of them is a 404.+ */+const served = new Map<string, SessionInfo[]>();const key = (machineId: string | null, agentId: string) => `${machineId ?? ""}|${agentId}`;let fetch: FakeFetch;+/** The servers behind `fetch`: `served` rows by id and by page, else the fixed `answers`. */+const serve: FetchHandler = (request) => {+ const one = /^\/api\/sessions\/([^/]+)$/.exec(request.path);+ if (one) {+ const sessionId = decodeURIComponent(one[1]!);+ const machine = request.machine ?? "";+ const row = [...served]+ .filter(([k]) => k.startsWith(`${machine}|`))+ .flatMap(([, rows]) => rows)+ .find((s) => s.sessionId === sessionId);+ return row ? json({ session: row }) : apiError(404, "not_found");+ }+ const agentId = /\/agents\/([^/]+)\/sessions$/.exec(request.path)?.[1] ?? "";+ const k = key(request.machine, decodeURIComponent(agentId));+ const rows = served.get(k);+ if (rows !== undefined) return servedPage(rows, request.query);+ const answer = answers.get(k);+ if (answer === undefined) throw new TypeError("fetch failed");+ return "status" in answer ? apiError(answer.status, answer.code) : json(answer);+};+beforeEach(() => {answers.clear();+ served.clear();stubLocalStorage();- fetch = stubFetch((request) => {- const agentId = /\/agents\/([^/]+)\/sessions$/.exec(request.path)?.[1] ?? "";- const answer = answers.get(key(request.machine, decodeURIComponent(agentId)));- if (answer === undefined) throw new TypeError("fetch failed");- return "status" in answer ? apiError(answer.status, answer.code) : json(answer);- });+ fetch = stubFetch(serve);});+/** The server's activity order, written out on its own (plain `<` / `>`, as the route compares). */+const serverRecent = (+ a: Pick<SessionInfo, "lastActiveAt" | "sessionId">,+ b: Pick<SessionInfo, "lastActiveAt" | "sessionId">,+) =>+ a.lastActiveAt < b.lastActiveAt+ ? 1+ : a.lastActiveAt > b.lastActiveAt+ ? -1+ : a.sessionId < b.sessionId+ ? 1+ : a.sessionId > b.sessionId+ ? -1+ : 0;++const zeroCounts = (): SessionCategoryCounts => ({+ active: 0,+ subagent: 0,+ schedule: 0,+ benchmark: 0,+ archived: 0,+});++/** 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 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");+ let list = [...rows].sort(+ activity ? serverRecent : (a, b) => (a.createdAt < b.createdAt ? 1 : -1),+ );+ const category = query.get("category");+ if (category !== null) list = list.filter((s) => sessionCategory(s) === category);+ const group = query.get("workspaceGroup");+ if (group !== null) list = list.filter((s) => s.workspace === group);+ if (before !== null) {+ const comma = before.indexOf(",");+ const cursor = { lastActiveAt: before.slice(0, comma), sessionId: before.slice(comma + 1) };+ list = list.filter((s) => serverRecent(s, cursor) > 0);+ }+ const offset = Number(query.get("offset") ?? 0);+ const limit = Number(query.get("limit") ?? list.length);+ const body: SessionsResponse = { sessions: list.slice(offset, offset + limit) };+ if (query.get("counts") === "1") {+ const counts = zeroCounts();+ const workspaceCounts: Record<string, SessionCategoryCounts> = {};+ for (const s of rows) {+ counts[sessionCategory(s)] += 1;+ (workspaceCounts[s.workspace] ??= zeroCounts())[sessionCategory(s)] += 1;+ }+ Object.assign(body, { counts, workspaceCounts });+ }+ return json(body);+}+afterEach(() => forgetSessionMachines());/** Which servers were asked, and for which Workspace group. */@@ -255,8 +376,9 @@ describe("the list across machines", () => {});it("a group's page is asked only of the machine that group is on, by path", async () => {- answers.set(key(null, "a1"), page([row("here", "2026-01-02T00:00:00Z")], 1));- answers.set(key("M1", "a1"), page([row("there", "2026-01-03T00:00:00Z")], 1));+ // Both hold more than a page, so a group's own stream has something left to ask for.+ served.set(key(null, "a1"), activeRun("here", 12));+ served.set(key("M1", "a1"), activeRun("there", 12));const store = boot(["M1"]);await store.getState().reload();@@ -339,21 +461,505 @@ describe("an organization row that enters by another door", () => {});});+/** A minute-spaced run of `n` rows, most recently active first; created in the REVERSE order, so creation order and activity order disagree on every pair. */+function activeRun(+ prefix: string,+ n: number,+ { day = 20, over = (_i: number): Partial<SessionInfo> => ({}) } = {},+): SessionInfo[] {+ const top = Date.parse(`2026-09-${day}T12:00:00.000Z`);+ return Array.from({ length: n }, (_, i) =>+ session(`${prefix}-${String(i).padStart(2, "0")}`, {+ lastActiveAt: new Date(top - i * 60_000).toISOString(),+ createdAt: new Date(Date.parse("2026-01-01T00:00:00.000Z") + i * 60_000).toISOString(),+ ...over(i),+ }),+ );+}++const cursorOf = (row: SessionInfo) => `${row.lastActiveAt},${row.sessionId}`;++/** The rows a sidebar list of `category` shows: the pool's rows it holds, cut at its watermark. */+function shown(+ store: ReturnType<typeof boot>,+ agentIds: string[],+ category: SessionCategory,+ workspaceGroup?: string,+ holds: (s: SessionInfo) => boolean = () => true,+): string[] {+ const state = store.getState();+ const rows = state.sessions.filter((s) => sessionCategory(s) === category && holds(s));+ return cutAtWatermark(rows, watermarkFor(state, agentIds, category, workspaceGroup)).map(+ (s) => s.sessionId,+ );+}++const sessionState = (+ sessionId: string,+ lastActiveAt: string,+ state: "running" | "idle" = "running",+ projectId = "p",+): ServerEvent => ({+ type: "session_state",+ sessionId,+ projectId,+ state,+ lastActiveAt,+ hasTrace: true,+});++/**+ * Waits for the lookup a session_state started: adoptLiveSession joins one in flight rather+ * than starting another. It would start one if none were running, so every test asserts the+ * EVENT issued its lookup (the request is sent synchronously) before waiting on it here.+ */+const adopted = (+ store: ReturnType<typeof boot>,+ sessionId: string,+ source: string | null,+ lastActiveAt: string,+ state: "running" | "idle" = "running",+) => store.getState().adoptLiveSession(sessionId, source, state, { lastActiveAt, hasTrace: true });++const sessionLookups = () => fetch.requests.filter((r) => r.path.startsWith("/api/sessions/"));++describe("the list pages in activity order, under a cursor", () => {+ it("asks for the activity order; the next page continues below the last row shown", async () => {+ const rows = activeRun("r", 25);+ 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);+ // 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");+ // 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(ids(store)).toEqual(rows.slice(0, 20).map((s) => s.sessionId));+ });++ it("a Workspace group's first own page continues from its Agent's cursor on that machine", async () => {+ const rows = activeRun("r", 15, { over: (i) => ({ workspace: i % 2 === 0 ? "/w" : "/x" }) });+ served.set(key(null, "a1"), rows);+ const store = boot();+ await store.getState().reload();+ 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]!));+ // 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(+ rows.filter(inW).map((s) => s.sessionId),+ );+ });++ it("a Workspace group whose Agent's stream is exhausted asks nothing: the pool holds it all", async () => {+ served.set(+ key(null, "a1"),+ activeRun("r", 5, { over: (i) => ({ workspace: i % 2 === 0 ? "/w" : "/x" }) }),+ );+ const store = boot();+ await store.getState().reload();+ fetch.requests.length = 0;+ await store.getState().loadMoreFor(["a1"], "active", "/w");+ await store.getState().loadMoreFor(["a1"], "active", "/w");+ expect(fetch.requests).toEqual([]);+ expect(watermarkFor(store.getState(), ["a1"], "active", "/w")).toBeNull();+ });++ it("the watermark over two machines is the more recent cursor with more", async () => {+ const here = activeRun("here", 12, { day: 20 });+ const there = activeRun("there", 25, { day: 10 });+ served.set(key(null, "a1"), here);+ served.set(key("M1", "a1"), there);+ // M3 is held but its server does not answer: nothing was read from it, so it bounds+ // nothing, and the rows it left in the cache keep showing.+ rememberMachineSessions("p", "M3", [+ session("cached", { lastActiveAt: "2026-09-25T00:00:00.000Z" }),+ ]);+ const store = boot(["M1", "M3"]);+ await store.getState().reload();+ expect(watermarkFor(store.getState(), ["a1"], "active")).toEqual({+ lastActiveAt: here[9]!.lastActiveAt,+ sessionId: here[9]!.sessionId,+ });+ // The older machine's first page waits below the line: M1's rows are all older than+ // this server's tenth, and this server still has more above them.+ expect(shown(store, ["a1"], "active")).toEqual([+ "cached",+ ...here.slice(0, 10).map((s) => s.sessionId),+ ]);++ // This server runs out; M1's cursor is the line now.+ await store.getState().loadMoreFor(["a1"], "active");+ expect(watermarkFor(store.getState(), ["a1"], "active")?.sessionId).toBe(there[19]!.sessionId);+ expect(shown(store, ["a1"], "active")).toEqual([+ "cached",+ ...here.map((s) => s.sessionId),+ ...there.slice(0, 20).map((s) => s.sessionId),+ ]);++ // Everything read: every row shows.+ await store.getState().loadMoreFor(["a1"], "active");+ expect(watermarkFor(store.getState(), ["a1"], "active")).toBeNull();+ expect(shown(store, ["a1"], "active")).toHaveLength(1 + 12 + 25);+ });++ it("a folder pages in activity order: an archived conversation resumed yesterday lists first", async () => {+ // archived-00 was created first and resumed last; creation order would bury it.+ const archived = activeRun("archived", 12, { over: () => ({ archived: true }) });+ served.set(key(null, "a1"), [+ session("own", { createdAt: "2026-09-30T00:00:00.000Z" }),+ ...archived,+ ]);+ const store = boot();+ 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(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]!));+ expect(shown(store, ["a1"], "archived")).toEqual(archived.map((s) => s.sessionId));+ });+});++describe("a Session that becomes active", () => {+ const NOW = "2026-09-30T08:00:00.000Z";+ const LATER = "2026-09-30T08:05:00.000Z";++ it("moves up in place, without a request, when its row is loaded", async () => {+ const rows = activeRun("r", 15);+ served.set(key(null, "a1"), rows);+ const store = boot();+ await store.getState().reload();+ fetch.requests.length = 0;+ applyUserEvent(store, sessionState("r-08", NOW), () => undefined);+ expect(fetch.requests).toEqual([]);+ expect(shown(store, ["a1"], "active")[0]).toBe("r-08");+ });++ it("is fetched from the machine that announced it, and shows at the top", async () => {+ const here = activeRun("here", 12, { day: 20 });+ const there = activeRun("there", 12, { day: 19 });+ served.set(key(null, "a1"), here);+ served.set(key("M1", "a1"), there);+ const store = boot(["M1"]);+ await store.getState().reload();+ expect(ids(store)).not.toContain("there-11");+ fetch.requests.length = 0;++ // Resumed from the CLI on M1: it moves above every cursor, so no page will serve it.+ there[11]!.lastActiveAt = NOW;+ applyUserEvent(store, sessionState("there-11", NOW), () => undefined, "M1");+ expect(sessionLookups().map((r) => [r.machine, r.path])).toEqual([+ ["M1", "/api/sessions/there-11"],+ ]);+ await adopted(store, "there-11", "M1", NOW);+ expect(machineForSession("there-11")).toBe("M1");+ expect(shown(store, ["a1"], "active")[0]).toBe("there-11");+ });++ it("one run's flips share one lookup, and the newest flip lands on the row", async () => {+ const rows = activeRun("r", 12);+ served.set(key(null, "a1"), rows);+ const store = boot();+ await store.getState().reload();+ fetch.requests.length = 0;+ // The lookup reads the row while it runs; the run ends before the answer arrives.+ rows[11]!.lastActiveAt = NOW;+ rows[11]!.status = "running";+ applyUserEvent(store, sessionState("r-11", NOW, "running"), () => undefined);+ applyUserEvent(store, sessionState("r-11", LATER, "idle"), () => undefined);+ expect(sessionLookups()).toHaveLength(1);+ await adopted(store, "r-11", null, LATER, "idle");+ expect(sessionLookups()).toHaveLength(1);+ const row = store.getState().sessions.find((s) => s.sessionId === "r-11");+ expect(row?.status).toBe("idle");+ expect(row?.lastActiveAt).toBe(LATER);+ });++ it("another Project's flip is only remembered", () => {+ const store = boot();+ applyUserEvent(store, sessionState("elsewhere", NOW, "running", "other"), () => undefined);+ expect(fetch.requests).toEqual([]);+ expect(store.getState().liveStatuses.get("elsewhere")).toBe("running");+ });++ it("an organization's Session, an id deleted here and an id that is gone are never listed, nor asked about twice", async () => {+ served.set(key(null, "a1"), [session("desk", { client: "org", lastActiveAt: NOW })]);+ const store = boot();+ store.setState({ sessions: [session("doomed")] });+ store.getState().remove("doomed");+ const all = ["desk", "doomed", "vanished"];+ for (const id of all) applyUserEvent(store, sessionState(id, NOW), () => undefined);+ expect(sessionLookups().map((r) => r.path)).toEqual([+ "/api/sessions/desk",+ "/api/sessions/vanished",+ ]);+ await Promise.all(all.map((id) => adopted(store, id, null, NOW)));+ for (const id of all) applyUserEvent(store, sessionState(id, LATER, "idle"), () => undefined);+ expect(sessionLookups()).toHaveLength(2);+ expect(ids(store)).toEqual([]);+ });++ it("a reload already running when it was fetched keeps it", async () => {+ const rows = activeRun("r", 3);+ served.set(key(null, "a1"), rows);+ const store = boot();+ await store.getState().reload();+ // The next reload's pages are read now, before the Session runs, and land only later.+ let release = () => {};+ const gate = new Promise<void>((resolve) => (release = resolve));+ fetch.answer(async (request) => {+ if (!request.path.endsWith("/sessions")) return serve(request);+ const page = await serve(request);+ await gate;+ return page;+ });+ const reloading = store.getState().reload();+ rows.push(session("fresh", { lastActiveAt: NOW }));+ applyUserEvent(store, sessionState("fresh", NOW), () => undefined);+ expect(sessionLookups()).toHaveLength(1);+ await adopted(store, "fresh", null, NOW);+ expect(ids(store)).toContain("fresh");+ release();+ await reloading;+ expect(ids(store)[0]).toBe("fresh");+ });+});++/** A seeded linear congruential generator: deterministic runs whose failures name their seed. */+function lcg(seed: number): () => number {+ let state = seed >>> 0;+ return () => {+ state = (Math.imul(state, 1664525) + 1013904223) >>> 0;+ return state / 2 ** 32;+ };+}++describe("property: every list is a prefix of its activity order, and loads only append", () => {+ /** One list the sidebar draws, as the sidebar builds it. */+ interface List {+ name: string;+ agents: string[];+ group?: string;+ /** Whether a row on `source` belongs to the list. */+ holds: (s: SessionInfo, source: string | null) => boolean;+ }++ const STAMPS = [1, 2, 3, 5, 8, 13].map(+ (d) => `2026-09-${String(d).padStart(2, "0")}T00:00:00.000Z`,+ );+ const WORKSPACES = ["/w1", "/w2", "/w3"];++ it(+ "holds over 100 seeded runs of loads, live flips and reloads",+ { timeout: 120_000 },+ async () => {+ for (let seed = 1; seed <= 100; seed += 1) {+ served.clear();+ forgetSessionMachines();+ fetch.requests.length = 0;+ const rand = lcg(seed);+ const int = (n: number) => Math.floor(rand() * n);+ const pick = <T>(xs: readonly T[]): T => xs[int(xs.length)]!;++ const agents = ["a1", "a2", "a3"].slice(0, 1 + int(3));+ const sources: (string | null)[] = rand() < 0.5 ? [null] : [null, "M1"];+ let n = 0;+ for (const source of sources) {+ for (const agentId of agents) {+ served.set(+ key(source, agentId),+ Array.from({ length: int(26) }, () =>+ session(`s${String(n++).padStart(3, "0")}${pick(["a", "B", "c", "D"])}`, {+ agentId,+ workspace: pick(WORKSPACES),+ lastActiveAt: pick(STAMPS),+ createdAt: pick(STAMPS),+ }),+ ),+ );+ }+ }+ /** Every server row with the machine it is on. */+ const serverRows = () =>+ sources.flatMap((source) =>+ agents.flatMap((agentId) =>+ (served.get(key(source, agentId)) ?? []).map((row) => ({ row, source })),+ ),+ );+ let clock = Date.parse("2026-09-20T00:00:00.000Z");++ const store = boot(sources.includes("M1") ? ["M1"] : [], [], agents);+ await store.getState().reload();++ /** The lists on screen in each grouping mode: time mode's, each Agent's, each Workspace's. */+ const lists = (): List[] => {+ const state = store.getState();+ const wsCounts = aggregateWorkspaceCounts(state.workspaceCountsByAgent);+ const out: List[] = [+ {+ name: "time",+ agents: [...state.countsByAgent]+ .filter(([, counts]) => counts.active > 0)+ .map(([agentId]) => agentId),+ holds: () => true,+ },+ ...agents.map((agentId) => ({+ name: `agent ${agentId}`,+ agents: [agentId],+ holds: (s: SessionInfo) => s.agentId === agentId,+ })),+ ];+ for (const source of sources) {+ for (const path of WORKSPACES) {+ const group = workspaceGroupKey(path, source);+ const contributing = state.sessions+ .filter(+ (s) => workspaceGroupKey(s.workspace, machineForSession(s.sessionId)) === group,+ )+ .map((s) => s.agentId);+ out.push({+ name: `workspace ${group.replace("\0", ":")}`,+ agents: [+ ...new Set([...(wsCounts.get(group)?.agents.active ?? []), ...contributing]),+ ],+ group,+ holds: (s, rowSource) => s.workspace === path && rowSource === source,+ });+ }+ }+ return out;+ };+ /** What a list shows. */+ const view = (list: List) => {+ const state = store.getState();+ const rows = state.sessions.filter(+ (s) => sessionCategory(s) === "active" && list.holds(s, machineForSession(s.sessionId)),+ );+ return cutAtWatermark(rows, watermarkFor(state, list.agents, "active", list.group));+ };+ /** The list's true order, from the servers' rows as they stand. */+ const truth = (list: List) =>+ serverRows()+ .filter(({ row, source }) => list.holds(row, source))+ .map(({ row }) => row)+ .sort(compareActivityDesc)+ .map((s) => s.sessionId);++ const say = (step: number, what: string, list: List) =>+ `seed ${seed}, step ${step} (${what}), list ${list.name}`;+ const expectPrefixes = (step: number, what: string) => {+ for (const list of lists()) {+ const shownIds = view(list).map((s) => s.sessionId);+ expect(shownIds, say(step, what, list)).toEqual(truth(list).slice(0, shownIds.length));+ }+ };++ expectPrefixes(0, "first load");+ for (let step = 1; step <= 25; step += 1) {+ const roll = rand();+ if (roll < 0.55) {+ const target = pick(lists());+ const before = new Map(lists().map((list) => [list.name, view(list)]));+ await store.getState().loadMoreFor(target.agents, "active", target.group);+ expectPrefixes(step, `load ${target.name}`);+ for (const list of lists()) {+ const was = before.get(list.name)!;+ const now = view(list);+ const message = say(step, `load ${target.name}`, list);+ // Append-only: what was shown still leads, and every new row sits below it.+ expect(+ now.slice(0, was.length).map((s) => s.sessionId),+ message,+ ).toEqual(was.map((s) => s.sessionId));+ const floor = was.at(-1);+ if (floor !== undefined) {+ for (const row of now.slice(was.length)) {+ expect(compareActivityDesc(row, floor), message).toBeGreaterThan(0);+ }+ }+ // Progress: the list asked shows a page more, or the rest.+ if (list.name === target.name) {+ const remaining = truth(list).length - was.length;+ expect(now.length - was.length, message).toBeGreaterThanOrEqual(+ Math.min(SIDEBAR_PAGE_SIZE, remaining),+ );+ }+ }+ } else if (roll < 0.95) {+ const all = serverRows();+ if (all.length === 0) continue;+ const { row, source } = pick(all);+ clock += 60_000;+ row.lastActiveAt = new Date(clock).toISOString();+ const loaded = store.getState().sessions.some((s) => s.sessionId === row.sessionId);+ const lookups = sessionLookups().length;+ applyUserEvent(+ store,+ sessionState(row.sessionId, row.lastActiveAt),+ () => undefined,+ source,+ );+ // A loaded row moves in place; an unloaded one is looked up, on its own machine.+ expect(sessionLookups().slice(lookups), `seed ${seed}, step ${step}`).toEqual(+ loaded+ ? []+ : [+ expect.objectContaining({+ machine: source,+ path: `/api/sessions/${row.sessionId}`,+ }),+ ],+ );+ await adopted(store, row.sessionId, source, row.lastActiveAt);+ expectPrefixes(step, `flip ${row.sessionId}`);+ } else {+ await store.getState().reload();+ expectPrefixes(step, "reload");+ }+ }+ }+ },+ );+});+describe("live statuses outlive the rows", () => {+ const STAMP = "2026-09-16T09:05:00.000Z";const stateEvent = (sessionId: string, state: "running" | "idle"): ServerEvent => ({type: "session_state",sessionId,+ projectId: "p",state,- lastActiveAt: "2026-09-16T09:05:00.000Z",+ lastActiveAt: STAMP,hasTrace: true,});const live = (store: ReturnType<typeof boot>) =>liveSessionStatuses(store.getState().sessions, store.getState().liveStatuses);- it("remembers a session_state for a Session no loaded page holds, without inventing a row", () => {+ it("remembers a session_state for a Session no loaded page holds, without inventing a row", async () => {+ // An organization's desk: this Project's, so it is looked up — and never listed.+ served.set(key(null, "a1"), [session("s-desk", { client: "org", orgId: "acme" })]);const store = boot();store.setState({ sessions: [session("own")] });applyUserEvent(store, stateEvent("s-desk", "running"), () => undefined);+ await store.getState().adoptLiveSession("s-desk", null, "running", {+ lastActiveAt: STAMP,+ hasTrace: true,+ });expect(ids(store)).toEqual(["own"]);expect(live(store).get("s-desk")).toBe("running");// The run ending is the fact no other channel reports: it must be kept, not dropped as