Skip to content

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

Each sidebar group pages and counts on its own; groups paginate ten at a time (#461)

Yaowei Zheng86defd077859
diff --git a/changelog/unreleased/2026-08-25-sidebar-group-paging.md b/changelog/unreleased/2026-08-25-sidebar-group-paging.md
new file mode 100644
index 00000000..97affcae
--- /dev/null
+++ b/changelog/unreleased/2026-08-25-sidebar-group-paging.md
@@ -0,0 +1,53 @@
+# Each sidebar group counts its own hidden chats, and the groups paginate
+
+- **Date:** 2026-08-25
+- **Type:** feature
+- **Scope:** `server`, `web`
+- **PR:** [#461](https://github.com/Prism-Shadow/penguin-harness/pull/461)
+
+[中文版](2026-08-25-sidebar-group-paging.zh.md)
+
+The chat sidebar's grouped list gains a reveal row that speaks for its own group, a way to fold a
+revealed group back, and real pagination over the groups themselves.
+
+## Details
+
+- **Each Workspace group pages its own server stream.** The list is fetched per Agent, and the
+ sidebar groups it by Workspace, so one cursor used to feed every group: the first page filled
+ them unevenly — whichever group owned the newest rows got most of it — and one group's "more"
+ consumed the page its siblings were about to read. Their rows appeared untouched, their counts
+ moved, and the group that asked could grow by less than a page, or by nothing. The list endpoint
+ takes a `workspaceGroup` filter (applied before paging, like `category`), each group carries its
+ own cursor, and every rendered group opens on its own first page.
+- A group's reveal row reads **Show N more chats** instead of a bare "More", where N is that
+ group's own hidden conversations: its exact server share minus the rows on screen. Nothing about
+ another group reaches the count.
+- Once every Agent that could hold one of the group's rows has been fetched out, the loaded rows
+ *are* the group's share. The stored totals refresh only on reload, so a count that drifted above
+ reality used to leave a row that revealed nothing; it now disappears with the last hidden row.
+- One click reveals one page more, and fetches the next page of that group's stream only when the
+ reveal runs past what is already loaded.
+- Sessions created without an explicit Workspace get a single-use temporary directory each, and the
+ sidebar has always merged those into one group; the server names that group `temp` so it pages
+ like any other.
+- A group's first scoped fetch starts at the rows it already holds, not at offset 0: those arrived
+ on pages of the Agent's whole stream, and a prefix of that stream cut by Workspace is a prefix of
+ the group's own — so the click reads new rows instead of re-reading the ones on screen.
+- A **Show less** row folds a revealed group back to its first page. Rows already fetched stay in
+ memory, so revealing them again costs no request.
+- The collapsed folders inside a group — Subagents, Scheduled, Archived — label their own reveal row
+ the same way, counted off each folder's own share.
+- The groups themselves now paginate: at most ten per page, stepped by a `‹ 1/3 ›` pager below the
+ list, replacing the row that revealed ten groups more. The window remains a display concern — no
+ group's data loading depends on the page it sits on.
+- Searching bypasses the pagination entirely, as it already bypassed the old cap: a match on page 3
+ would read as no match at all.
+- The manual group order still commits over the full group sequence rather than the page on screen,
+ so a drag on page 2 cannot drop the groups that are not rendered.
+- Adding a Workspace turns to the page that now holds it. An empty registered group is appended and
+ nothing pins or orders it yet, so past ten groups the new Workspace would otherwise land on a page
+ the user is not looking at and the click would read as a no-op.
+- Time mode has at most three buckets — last day / last month / earlier — so it does not paginate.
+- A Project switch or a grouping-mode switch clears the per-group reveal state: a cap keyed by an
+ Agent id means nothing to a Workspace group, and the other Project's groups are gone.
+- The Traces page's group tree is unaffected; this changes the chat sidebar only.
diff --git a/changelog/unreleased/2026-08-25-sidebar-group-paging.zh.md b/changelog/unreleased/2026-08-25-sidebar-group-paging.zh.md
new file mode 100644
index 00000000..099e6e85
--- /dev/null
+++ b/changelog/unreleased/2026-08-25-sidebar-group-paging.zh.md
@@ -0,0 +1,28 @@
+# 每个分组各自计算被折叠的对话数,分组本身改为分页
+
+- **Date:** 2026-08-25
+- **Type:** feature
+- **Scope:** `server`, `web`
+- **PR:** [#461](https://github.com/Prism-Shadow/penguin-harness/pull/461)
+
+[English](2026-08-25-sidebar-group-paging.md)
+
+对话侧边栏的分组列表新增了只为本组说话的展开行、把已展开分组收回的方式,以及对分组自身的真正分页。
+
+## 细节
+
+- **每个工作区分组各自翻自己的服务端数据流。**列表按 Agent 取数,而侧边栏按工作区分组,因此此前所有分组共用一个游标:首页把各分组填得参差不齐——谁占着最新的行谁就吃掉大半页——而某个分组点「更多」会消耗掉兄弟分组本该读到的那一页。结果是别的分组的行凭空出现、计数自行变动,而真正点击的那个分组增长不足一页、甚至一行都不增加。列表接口新增 `workspaceGroup` 过滤(与 `category` 一样在翻页前生效),每个分组持有自己的游标,且每个渲染出来的分组都从自己的第一页开始。
+- 分组的展开行由原先的「更多」改为 **展开其余 N 个对话**,其中 N 是该分组自己被折叠的对话数:它在服务端的确切份额减去已显示的行数。计数不受任何其他分组影响。
+- 一旦可能持有该分组行的每个 Agent 都已取完,已加载的行**就是**该分组的份额。存储的计数只在重新加载时刷新,此前计数高于实际时会留下一个点了也没有内容的展开行;现在它随最后一条被折叠的对话一同消失。
+- 一次点击展开一页,且仅当展开超出已加载的行时,才拉取该分组数据流的下一页。
+- 未显式指定工作区的会话各自获得一个一次性的临时目录,侧边栏一向把它们合并为一个分组;服务端将该分组命名为 `temp`,使其与其他分组一样可翻页。
+- 分组的首次带作用域拉取从它已持有的行数开始,而非从 0 开始:这些行来自 Agent 整体数据流的前缀,而整体数据流的前缀按工作区切分后仍是该分组数据流的前缀——因此这一次点击读到的是新行,而不是重读屏幕上已有的行。
+- 新增 **收起** 行,把已展开的分组折回第一页。已拉取的行保留在内存中,再次展开不产生请求。
+- 分组内折叠的文件夹——子智能体、定时任务、已归档——其展开行采用同样的写法,按各自的份额计数。
+- 分组本身改为分页:每页最多十个,列表下方以 `‹ 1/3 ›` 翻页控件切换,取代原先「再展开十个分组」的那一行。该窗口仍只是显示层面的事——任何分组的数据加载都不取决于它落在第几页。
+- 搜索完全绕过分页,与此前绕过显示上限一致:落在第 3 页的匹配项等同于没有匹配。
+- 手动分组顺序仍然按完整的分组序列提交,而非当前页面上的分组,因此在第 2 页拖动不会丢掉未渲染的分组。
+- 新建工作区会翻到该工作区所在的页。空的已登记分组追加在末尾且尚未被置顶或排序,超过十个分组后新建的工作区本会落在用户看不到的页上,那次点击就会像没有生效。
+- 按时间分组最多只有三个分桶——最近一天/最近一月/更早——因此不分页。
+- 切换 Project 或切换分组方式会清除各分组的展开状态:以 Agent id 为键的上限对工作区分组没有意义,而另一个 Project 的分组已经不复存在。
+- Trace 页面的分组目录树不受影响;本次改动只作用于对话侧边栏。
diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.ts
index 6c15a95e..ba046319 100644
--- a/packages/server/src/http/routes/sessions.ts
+++ b/packages/server/src/http/routes/sessions.ts
@@ -446,6 +446,13 @@ export function agentSessionsRoutes(deps: AppDeps): Hono<AppEnv> {
if (rawCategory !== undefined && !SESSION_CATEGORIES.includes(rawCategory as SessionCategory)) {
throw badRequest(`category must be one of ${SESSION_CATEGORIES.join(" / ")}.`);
}
+ // Optional Workspace-group filter (applied with the category, before paging): a
+ // sidebar grouped by Workspace pages each group down its own stream, so one group's
+ // "load more" cannot consume the page a sibling was about to read.
+ const rawWorkspaceGroup = c.req.query("workspaceGroup");
+ if (rawWorkspaceGroup !== undefined && rawWorkspaceGroup.trim() === "") {
+ throw badRequest("workspaceGroup must not be empty.");
+ }
const rawCounts = c.req.query("counts");
if (rawCounts !== undefined && rawCounts !== "1") throw badRequest("counts only accepts 1.");
const rawCli = c.req.query("cli");
@@ -456,6 +463,7 @@ export function agentSessionsRoutes(deps: AppDeps): Hono<AppEnv> {
{
...(paging ? { paging } : {}),
...(rawCategory !== undefined ? { category: rawCategory as SessionCategory } : {}),
+ ...(rawWorkspaceGroup !== undefined ? { workspaceGroup: rawWorkspaceGroup } : {}),
...(rawCounts !== undefined ? { withCounts: true } : {}),
...(rawCli !== undefined ? { includeCli: true } : {}),
},
diff --git a/packages/server/src/services/session-service.ts b/packages/server/src/services/session-service.ts
index 5813f8f7..61353804 100644
--- a/packages/server/src/services/session-service.ts
+++ b/packages/server/src/services/session-service.ts
@@ -30,6 +30,7 @@ import type { SessionManager } from "../runtime/session-manager.js";
import { asSessionSource } from "../runtime/session-sources.js";
import type { SessionSources } from "../runtime/session-sources.js";
import { TraceIndexService, traceFilePath } from "./trace-index.js";
+import { matchesWorkspaceGroup } from "./workspace-group.js";
import type { ProjectConfigService } from "./project-config-service.js";
const SESSION_ID_TS_RE = /^session-(\d{4})-(\d{2})-(\d{2})-(\d{2})-(\d{2})-(\d{2})-[0-9a-f]{8}$/;
@@ -149,6 +150,12 @@ export class SessionService {
* every row and returns per-category totals over the whole list — plus the same
* totals broken down by Workspace path — so the sidebar can label the collapsed
* folders (and a workspace group can know its own share) without loading them.
+ *
+ * `workspaceGroup` filters the same way, to one Workspace group (see workspace-group.ts),
+ * so a sidebar grouped by Workspace pages each group down its OWN stream instead of
+ * sharing one per-Agent cursor — without it, one group's "load more" consumes the page
+ * its siblings were about to read, and their rows move on screen untouched. The two
+ * filters compose; the returned counts stay whole-Agent either way.
*/
async listSessions(
projectId: string,
@@ -156,6 +163,7 @@ export class SessionService {
opts: {
paging?: { offset: number; limit: number };
category?: SessionCategory;
+ workspaceGroup?: string;
withCounts?: boolean;
includeCli?: boolean;
} = {},
@@ -164,7 +172,7 @@ export class SessionService {
counts?: SessionCategoryCounts;
workspaceCounts?: Record<string, SessionCategoryCounts>;
}> {
- const { paging, category, withCounts, includeCli } = opts;
+ const { paging, category, workspaceGroup, withCounts, includeCli } = opts;
const rows = new Map(
this.deps.sessions
.listByAgent(projectId, agentId, { webOnly: !includeCli })
@@ -205,7 +213,7 @@ export class SessionService {
Promise.all(page.map((row) => this.toInfo(row, rowHasTrace(row))));
// No classification asked for: slice straight away (the pre-category behavior).
- if (category === undefined && !withCounts) {
+ if (category === undefined && workspaceGroup === undefined && !withCounts) {
return {
sessions: await toPage(
paging ? sorted.slice(paging.offset, paging.offset + paging.limit) : sorted,
@@ -230,7 +238,10 @@ export class SessionService {
});
ws[cat] += 1;
}
- if ((category === undefined || cat === category) && matched.length < want) matched.push(row);
+ const wanted =
+ (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);
return withCounts ? { sessions, counts, workspaceCounts } : { sessions };
diff --git a/packages/server/src/services/workspace-group.ts b/packages/server/src/services/workspace-group.ts
new file mode 100644
index 00000000..c0d8d645
--- /dev/null
+++ b/packages/server/src/services/workspace-group.ts
@@ -0,0 +1,35 @@
+/**
+ * Workspace GROUPS of the session list — the unit the sidebar draws one folder per, and
+ * the unit its paging runs in.
+ *
+ * There is no Workspace entity: a Session carries the plain filesystem path locked in at
+ * creation, so a group is identified by that path. The one exception is the Sessions
+ * created without an explicit Workspace: core auto-creates a single-use directory shaped
+ * `<agentDir>/workspaces/tmp-<8hex>` for each of them (createTempWorkspace in
+ * packages/core/src/internal/session-support.ts), so per-path groups would be one-session
+ * noise — every such path belongs to ONE merged group, named by the sentinel below.
+ */
+
+/**
+ * Query value naming the merged temporary-workspace group. Stored Workspaces are realpath
+ * results and therefore absolute, so a bare word can never collide with one.
+ */
+export const TEMP_WORKSPACE_GROUP = "temp";
+
+/** Auto-created temporary Workspace tail: `workspaces/tmp-<8hex>` (either separator — core supports win32). */
+const TEMP_WORKSPACE_RE = /[/\\]workspaces[/\\]tmp-[0-9a-f]{8}$/;
+
+/** Whether a Session's Workspace is one of core's auto-created temporary directories. */
+export function isTempWorkspace(workspace: string): boolean {
+ const path = workspace.trim();
+ // An empty path counts as temporary: the resolved path is always backfilled, so this is
+ // defensive only.
+ return path === "" || TEMP_WORKSPACE_RE.test(path);
+}
+
+/** Whether a Session's Workspace belongs to the requested group (see TEMP_WORKSPACE_GROUP). */
+export function matchesWorkspaceGroup(workspace: string, group: string): boolean {
+ return group === TEMP_WORKSPACE_GROUP
+ ? isTempWorkspace(workspace)
+ : workspace.trim() === group.trim();
+}
diff --git a/packages/server/test/session-index.test.ts b/packages/server/test/session-index.test.ts
index f25b21be..0189bd6e 100644
--- a/packages/server/test/session-index.test.ts
+++ b/packages/server/test/session-index.test.ts
@@ -382,6 +382,94 @@ describe("session-index", () => {
expect((await api.get(`${base()}?counts=yes`)).status).toBe(400);
});
+ it("workspaceGroup pages one Workspace group's own stream, temporary workspaces as one group", async () => {
+ // Rows are inserted straight into the index: the group filter reads the stored path, and
+ // going through create() would only add realpath validation this has nothing to say about.
+ const agentDir = `${t.root}/${projectId}/agents/default_agent`;
+ const seed = async (sessionId: string, workspace: string, createdAt: string) =>
+ t.deps.sessionsRepo.insert({
+ sessionId,
+ projectId,
+ agentId: "default_agent",
+ provider: "custom",
+ modelId: "m-x",
+ workspace,
+ approvalMode: "allow-all",
+ title: null,
+ createdAt,
+ lastActiveAt: createdAt,
+ });
+ // Interleaved by creation time, so no single page of the Agent's whole stream can be
+ // one group's page: alpha, beta and two single-use temporary workspaces.
+ const alpha = "/tmp/ws-alpha";
+ const beta = "/tmp/ws-beta";
+ await seed("session-2026-07-03-09-00-00-aaaa0001", alpha, "2026-07-03T09:00:00.000Z");
+ await seed("session-2026-07-03-09-01-00-bbbb0001", beta, "2026-07-03T09:01:00.000Z");
+ await seed("session-2026-07-03-09-02-00-aaaa0002", alpha, "2026-07-03T09:02:00.000Z");
+ await seed("session-2026-07-03-09-03-00-bbbb0002", beta, "2026-07-03T09:03:00.000Z");
+ await seed(
+ "session-2026-07-03-09-04-00-cccc0001",
+ `${agentDir}/workspaces/tmp-0123abcd`,
+ "2026-07-03T09:04:00.000Z",
+ );
+ await seed(
+ "session-2026-07-03-09-05-00-cccc0002",
+ `${agentDir}/workspaces/tmp-89abcdef`,
+ "2026-07-03T09:05:00.000Z",
+ );
+
+ 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 = (body: SessionsResponse) => body.sessions.map((s) => s.sessionId);
+
+ // A group's stream holds its rows and nobody else's.
+ expect(ids(await list(`?category=active&workspaceGroup=${encodeURIComponent(alpha)}`))).toEqual(
+ ["session-2026-07-03-09-02-00-aaaa0002", "session-2026-07-03-09-00-00-aaaa0001"],
+ );
+ expect(ids(await list(`?category=active&workspaceGroup=${encodeURIComponent(beta)}`))).toEqual([
+ "session-2026-07-03-09-03-00-bbbb0002",
+ "session-2026-07-03-09-01-00-bbbb0001",
+ ]);
+
+ // Every auto-created temporary Workspace is ONE group (they are single-use, so a group
+ // per path would be one-session noise).
+ expect(ids(await list("?category=active&workspaceGroup=temp"))).toEqual([
+ "session-2026-07-03-09-05-00-cccc0002",
+ "session-2026-07-03-09-04-00-cccc0001",
+ ]);
+
+ // Paging runs within the group: offset/limit walk that group's stream, not the Agent's.
+ const first = await list(
+ `?category=active&workspaceGroup=${encodeURIComponent(alpha)}&limit=1&offset=0`,
+ );
+ const second = await list(
+ `?category=active&workspaceGroup=${encodeURIComponent(alpha)}&limit=1&offset=1`,
+ );
+ expect(ids(first)).toEqual(["session-2026-07-03-09-02-00-aaaa0002"]);
+ expect(ids(second)).toEqual(["session-2026-07-03-09-00-00-aaaa0001"]);
+ expect(
+ (await list(`?category=active&workspaceGroup=${encodeURIComponent(alpha)}&limit=1&offset=2`))
+ .sessions,
+ ).toEqual([]);
+
+ // A group nobody lives in is empty, not unfiltered.
+ expect((await list("?category=active&workspaceGroup=/tmp/ws-nobody")).sessions).toEqual([]);
+
+ // The counts stay whole-Agent under a group filter: the sidebar reads a group's share
+ // from the per-Workspace breakdown, and the folder labels need the Agent's totals.
+ const counted = await list(
+ `?category=active&counts=1&workspaceGroup=${encodeURIComponent(alpha)}`,
+ );
+ expect(ids(counted)).toHaveLength(2);
+ expect(counted.counts?.active).toBe(6);
+
+ // An empty group name is rejected, never silently unfiltered.
+ expect((await api.get(`${base()}?workspaceGroup=`)).status).toBe(400);
+ });
+
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 never
diff --git a/packages/web/e2e/paging.spec.mjs b/packages/web/e2e/paging.spec.mjs
index b1b0b4de..af232bc0 100644
--- a/packages/web/e2e/paging.spec.mjs
+++ b/packages/web/e2e/paging.spec.mjs
@@ -1,12 +1,13 @@
/**
- * Sidebar session paging: each group displays at most SIDEBAR_PAGE_SIZE (20) rows and the
- * store fetches per Agent with limit+1 pages — 21 seeded sessions must load as one page of
- * 20 plus a "更多" row; clicking it reveals the loaded rows AND fetches the next server
- * page, after which all 21 rows are visible and the "更多" row disappears (no more hidden
- * rows, no more server pages).
+ * Sidebar session paging: each group displays at most SIDEBAR_PAGE_SIZE (10) rows and the
+ * store fetches per Agent with limit+1 pages. 21 seeded sessions must load as one page of
+ * 10 plus a reveal row that counts THIS group's own remainder ("展开其余 11 个对话");
+ * each click reveals one page more and fetches the next server page when the reveal runs
+ * past what is loaded, so the count walks 11 → 1 → gone, and a "收起" row folds the whole
+ * group back to its first page.
*
* A list taller than the viewport must scroll INSIDE the sidebar: the document itself
- * stays unscrollable before and after "更多". Each row's sr-only Agent name is
+ * stays unscrollable before and after the reveal. Each row's sr-only Agent name is
* position:absolute, and without a positioned scroller those boxes anchored to the
* initial containing block, stretched the document, and let the whole page scroll (the
* composer could be pushed up, leaving blank space below).
@@ -21,9 +22,10 @@ const BASE = process.env.BASE_URL;
const MOCK = process.env.MOCK_URL;
const U = "pageuser";
const P = "password123";
-const TOTAL = 21; // one past the 20-row page
+const PAGE = 10; // SIDEBAR_PAGE_SIZE
+const TOTAL = 21; // two full pages plus one, so the reveal row must survive a click
-test("sidebar shows 20 sessions plus a More row; More loads the 21st and then disappears", async ({
+test("a group reveals its own remainder one page at a time, and 收起 folds it back", async ({
page,
}) => {
await provisionAndLogin(page.request, U, P);
@@ -59,25 +61,47 @@ test("sidebar shows 20 sessions plus a More row; More loads the 21st and then di
await page.goto(`${BASE}/chat`);
const sidebar = page.getByRole("complementary");
// Untitled rows all read "新对话" (distinct from the nav's "新建对话", which is not matched
- // by substring). One page: exactly 20 rows.
+ // by substring). One page: exactly 10 rows.
const rows = sidebar.getByText("新对话");
- await expect(rows).toHaveCount(20);
- const more = sidebar.getByRole("button", { name: "更多" });
- await expect(more).toBeVisible();
+ await expect(rows).toHaveCount(PAGE);
+ // The reveal row names the group's own hidden conversations, counted off its exact
+ // server share rather than a shared "there is more somewhere" signal.
+ const reveal = sidebar.getByRole("button", { name: `展开其余 ${TOTAL - PAGE} 个对话` });
+ await expect(reveal).toBeVisible();
+ // Exact: the sidebar's own "收起侧边栏" control would match a substring lookup.
+ const collapse = sidebar.getByRole("button", { name: "收起", exact: true });
+ await expect(collapse).toHaveCount(0);
- // The 20-row list already exceeds the 720px viewport: it must scroll inside the
- // sidebar, never stretch the document (the sr-only regression described up top).
+ // The 10-row list plus the group chrome already exceeds the 720px viewport: it must
+ // scroll inside the sidebar, never stretch the document (the sr-only regression up top).
const docScrollable = () =>
page.evaluate(
() => document.documentElement.scrollHeight > document.documentElement.clientHeight + 1,
);
- expect(await docScrollable(), "document scrollable before 更多").toBe(false);
+ expect(await docScrollable(), "document scrollable before the reveal").toBe(false);
- // More: raises the display cap and fetches the next server page → all 21 rows, no More left.
- await more.click();
+ // One click = one page: 20 rows, the remainder recounted to 1, and 收起 now offered.
+ await reveal.click();
+ await expect(rows).toHaveCount(PAGE * 2);
+ await expect(
+ sidebar.getByRole("button", { name: `展开其余 ${TOTAL - PAGE * 2} 个对话` }),
+ ).toBeVisible();
+ await expect(collapse).toBeVisible();
+
+ // The last click empties the group: every row on screen, no reveal row left (nothing
+ // hidden, no server page behind it), 收起 still there to fold it back.
+ await sidebar.getByRole("button", { name: `展开其余 ${TOTAL - PAGE * 2} 个对话` }).click();
await expect(rows).toHaveCount(TOTAL);
- await expect(more).toHaveCount(0);
+ await expect(sidebar.getByRole("button", { name: /展开其余/ })).toHaveCount(0);
+ await expect(collapse).toBeVisible();
// Still only the sidebar scrolls after the list grew past one page.
- expect(await docScrollable(), "document scrollable after 更多").toBe(false);
+ expect(await docScrollable(), "document scrollable after the reveal").toBe(false);
+
+ // 收起 returns the group to its first page — the fetched rows stay in memory, so the
+ // reveal row comes back naming the full remainder again.
+ await collapse.click();
+ await expect(rows).toHaveCount(PAGE);
+ await expect(reveal).toBeVisible();
+ await expect(collapse).toHaveCount(0);
});
diff --git a/packages/web/e2e/workspace-group-paging.spec.mjs b/packages/web/e2e/workspace-group-paging.spec.mjs
new file mode 100644
index 00000000..595f64cb
--- /dev/null
+++ b/packages/web/e2e/workspace-group-paging.spec.mjs
@@ -0,0 +1,101 @@
+/**
+ * Workspace groups page INDEPENDENTLY of one another.
+ *
+ * The session list is fetched per Agent, but the sidebar groups it by Workspace, so one
+ * per-Agent cursor used to feed every group: the first page filled them unevenly (whichever
+ * group owned the newest rows got most of it), and one group's "show more" consumed the page
+ * its siblings were about to read — their rows appeared on screen untouched, their reveal
+ * counts moved, and the group that asked could grow by less than a page. Each group now walks
+ * its own server stream (`workspaceGroup` on the list endpoint), so:
+ *
+ * - every group opens on its OWN first page, whatever the other groups hold;
+ * - revealing one group leaves the others exactly as they were.
+ *
+ * Two Workspaces on ONE Agent — the arrangement that shares a cursor — with the sessions
+ * interleaved so no single page of the Agent's whole stream could fill both.
+ *
+ * Standalone spec: shares one server with the other specs, so it registers its own user
+ * (auto-provisions a default Project) and seeds sessions via the API.
+ */
+import { test, expect } from "@playwright/test";
+import { mkdir, mkdtemp } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { provisionAndLogin } from "./auth.mjs";
+
+const BASE = process.env.BASE_URL;
+const MOCK = process.env.MOCK_URL;
+const U = "wsgroupuser";
+const P = "password123";
+const PAGE = 10; // SIDEBAR_PAGE_SIZE
+const ALPHA = 8; // under one page: this group must open complete
+const BETA = 14; // over one page: this group must open at exactly one page
+
+/** Conversation rows inside one group's block, located by the group's label. */
+const groupRows = (sidebar, label) =>
+ sidebar.locator('div[class*="relative pt-2.5"]').filter({ hasText: label }).locator("li");
+
+test("each Workspace group opens on its own page, and revealing one leaves the others alone", async ({
+ page,
+}) => {
+ // Real directories: a Workspace is validated by realpath and must exist.
+ const root = await mkdtemp(join(tmpdir(), "penguin-ws-"));
+ const alpha = join(root, "ws-alpha");
+ const beta = join(root, "ws-beta");
+ await Promise.all([mkdir(alpha), mkdir(beta)]);
+
+ await provisionAndLogin(page.request, U, P);
+ const projects = await (await page.request.get(`${BASE}/api/projects`)).json();
+ const projectId = projects.projects[0].projectId;
+ const put = await page.request.put(`${BASE}/api/projects/${projectId}/models`, {
+ data: {
+ defaultModel: { provider: "custom", modelId: "claude-4-8" },
+ models: [
+ {
+ provider: "custom",
+ modelId: "claude-4-8",
+ apiKey: "sk-mock",
+ baseUrl: MOCK,
+ contextWindow: 200000,
+ },
+ ],
+ },
+ });
+ expect(put.ok(), "put models").toBeTruthy();
+
+ const seed = async (workspace, n) => {
+ for (let i = 0; i < n; i++) {
+ const res = await page.request.post(
+ `${BASE}/api/projects/${projectId}/agents/default_agent/sessions`,
+ { data: { workspace } },
+ );
+ expect(res.ok(), `create in ${workspace}: ${await res.text()}`).toBeTruthy();
+ }
+ };
+ // Interleaved, oldest first: the Agent's newest page straddles both groups, so neither
+ // group's own first page can come out of one whole-stream read.
+ await seed(beta, 6);
+ await seed(alpha, 8);
+ await seed(beta, 8);
+
+ await page.setViewportSize({ width: 1280, height: 1400 });
+ await page.goto(`${BASE}/chat`);
+ const sidebar = page.getByRole("complementary");
+ await expect(sidebar.getByText("ws-alpha")).toBeVisible();
+
+ // Each group opens on its own first page: beta capped at one page, alpha complete.
+ await expect(groupRows(sidebar, "ws-beta")).toHaveCount(PAGE);
+ await expect(groupRows(sidebar, "ws-alpha")).toHaveCount(ALPHA);
+ // Only the group that actually has more offers to reveal it, and it counts its own rows.
+ const revealBeta = sidebar.getByRole("button", { name: `展开其余 ${BETA - PAGE} 个对话` });
+ await expect(revealBeta).toBeVisible();
+ await expect(sidebar.getByRole("button", { name: /展开其余/ })).toHaveCount(1);
+
+ // Revealing beta pulls beta's own next page and leaves alpha untouched.
+ await revealBeta.click();
+ await expect(groupRows(sidebar, "ws-beta")).toHaveCount(BETA);
+ await expect(groupRows(sidebar, "ws-alpha")).toHaveCount(ALPHA);
+ await expect(sidebar.getByRole("button", { name: /展开其余/ })).toHaveCount(0);
+ // Exact: the sidebar's own "收起侧栏" control would match a substring lookup.
+ await expect(sidebar.getByRole("button", { name: "收起", exact: true })).toHaveCount(1);
+});
diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.ts
index a3c80f81..90d0827b 100644
--- a/packages/web/src/api/endpoints.ts
+++ b/packages/web/src/api/endpoints.ts
@@ -426,7 +426,8 @@ export const getAgentTraces = (
/**
* Optional paging (absent = full unfiltered list): the store requests `limit+1` per page to
* detect "has more". `category` filters server-side (paging applies within the category);
- * `withCounts` asks for per-category totals over the whole list alongside the page.
+ * `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.
*/
export const listSessions = (
projectId: string,
@@ -435,6 +436,8 @@ export const listSessions = (
offset: number;
limit: number;
category?: SessionCategory;
+ /** One Workspace group's rows only: its path, or the merged temporary group's sentinel (session-grouping.ts). */
+ workspaceGroup?: string;
withCounts?: boolean;
/** Also list CLI-created Sessions (Trace discovery + adoption); default = web rows straight from the DB. */
cli?: boolean;
@@ -443,6 +446,7 @@ export const listSessions = (
const qs = opts
? `?limit=${opts.limit}&offset=${opts.offset}` +
(opts.category ? `&category=${opts.category}` : "") +
+ (opts.workspaceGroup ? `&workspaceGroup=${encodeURIComponent(opts.workspaceGroup)}` : "") +
(opts.withCounts ? "&counts=1" : "") +
(opts.cli ? "&cli=1" : "")
: "";
diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsx
index dfb40e79..c9872ce7 100644
--- a/packages/web/src/components/layout/sidebar.tsx
+++ b/packages/web/src/components/layout/sidebar.tsx
@@ -48,12 +48,16 @@ import { agentDisplayName, projectDisplayName, useProject } from "../../state/pr
import { useSessions } from "../../state/sessions";
import {
FOLDER_CATEGORIES,
- SIDEBAR_GROUP_PAGE_SIZE,
SIDEBAR_PAGE_SIZE,
TIME_FOLDERS_GROUP_KEY,
aggregateWorkspaceCounts,
+ clampGroupPage,
+ groupPageCount,
+ groupPageOf,
+ groupPageSlice,
groupSessionsByTime,
groupSessionsByWorkspace,
+ hiddenRowCount,
matchesSessionQuery,
partitionSessions,
sessionCategory,
@@ -124,6 +128,7 @@ import {
SORT_MODE_ICONS,
FolderSection,
GroupHeader,
+ GroupPager,
Icon,
MoreRow,
initialGroupMode,
@@ -447,7 +452,9 @@ export function Sidebar({
setSessionOrder(loadSessionOrder(currentProjectId, groupMode));
setGroupOrder(loadGroupOrder(currentProjectId, groupMode));
setRegisteredWorkspaces(loadWorkspaceRegistry(currentProjectId));
- setGroupCap(SIDEBAR_GROUP_PAGE_SIZE);
+ setGroupPage(0);
+ // The other Project's groups are gone, and so is any meaning their reveal state had.
+ setGroupCaps(new Map());
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [collapseStoreKey, pinStoreKey, currentProjectId]);
/** Expanded folders (subagent / scheduled / archived; collapsed by default), keyed by folderKey — each folder has its own open state. */
@@ -456,8 +463,8 @@ export function Sidebar({
const [pendingLoads, setPendingLoads] = useState<ReadonlySet<string>>(new Set());
/** Per-group display cap for active rows (keyed by group key; absent = SIDEBAR_PAGE_SIZE). "More" raises it a page at a time. */
const [groupCaps, setGroupCaps] = useState<ReadonlyMap<string, number>>(new Map());
- /** How many GROUPS render (#139: dozens of Agents/Workspaces made the list too tall to scan); "more groups" raises it a page at a time, reset per Project and on a mode switch. */
- const [groupCap, setGroupCap] = useState(SIDEBAR_GROUP_PAGE_SIZE);
+ /** Which PAGE of groups renders (#139: dozens of Agents/Workspaces made the list too tall to scan), 0-based; reset per Project and on a mode switch, and clamped at render to the pages that still exist. */
+ const [groupPage, setGroupPage] = useState(0);
/** Session pending delete confirmation (null = none). */
const [deletingSession, setDeletingSession] = useState<SessionInfo | null>(null);
const [deletingBusy, setDeletingBusy] = useState(false);
@@ -474,12 +481,14 @@ export function Sidebar({
const setGroupMode = (mode: GroupMode) => {
storeGroupMode(mode);
setGroupModeState(mode);
- // The modes have unrelated group lists: restart the reveal window, and swap in
- // this mode's own manual order (the stored sequence is read within partitions, whose
- // boundaries are exactly what the mode decides — one shared array would scramble).
+ // The modes have unrelated group lists: go back to the first page, drop the per-group
+ // reveal state (a cap keyed by an Agent id means nothing to a Workspace group), and
+ // swap in this mode's own manual order (the stored sequence is read within partitions,
+ // whose boundaries are exactly what the mode decides — one shared array would scramble).
setSessionOrder(loadSessionOrder(currentProjectId, mode));
setGroupOrder(loadGroupOrder(currentProjectId, mode));
- setGroupCap(SIDEBAR_GROUP_PAGE_SIZE);
+ setGroupPage(0);
+ setGroupCaps(new Map());
};
/** Collapse/expand the page-nav group (same store-then-set convention as setGroupMode). */
@@ -526,7 +535,7 @@ export function Sidebar({
);
// The FULL displayed group sequences a drop commits — every group of the mode, not the
- // `groupCap` slice on screen (see groupDragProps).
+ // page of groups on screen (see groupDragProps).
const agentGroupSequence = useMemo(() => orderedAgents.map((a) => a.agentId), [orderedAgents]);
const workspaceGroupSequence = useMemo(
() => orderedWorkspaceGroups.map((g) => g.key),
@@ -580,6 +589,33 @@ export function Sidebar({
/** Search active = a non-blank query is live-filtering the list. */
const searching = searchQuery.trim() !== "";
+ /**
+ * Group pagination (Workspace / Agent modes — time mode has at most three buckets and
+ * pages nothing). A pure display window: the manual group order still commits over the
+ * FULL sequence (see groupDragProps), and no group's data loading depends on which page
+ * it sits on. Search bypasses paging entirely — a match on page 3 would read as no match
+ * at all, which is the same reason a collapsed group is forced open while searching.
+ */
+ const pagedGroupTotal =
+ groupMode === "agent"
+ ? orderedAgents.length
+ : groupMode === "workspace"
+ ? orderedWorkspaceGroups.length
+ : 0;
+ const groupPageTotal = groupPageCount(pagedGroupTotal);
+ /** The page actually on screen: the stored one, pinned inside the pages that still exist. */
+ const shownGroupPage = clampGroupPage(groupPage, pagedGroupTotal);
+
+ /** The groups to render: this page's slice, or every match while searching. */
+ const groupsOnPage = <T,>(groups: T[]): T[] =>
+ searching ? groups : groupPageSlice(groups, shownGroupPage);
+
+ /** Pager below the group list — rendered only once the groups overflow a single page. */
+ const groupPagerRow = () =>
+ !searching && groupPageTotal > 1 ? (
+ <GroupPager page={shownGroupPage} pageCount={groupPageTotal} onChange={setGroupPage} />
+ ) : null;
+
/** The sort actually applied: a stored "manual" needs a drag-capable pointer to mean anything (see canDrag). */
const effectiveSortMode: SessionSortMode = sortMode === "manual" && canDrag ? "manual" : "recent";
@@ -641,7 +677,7 @@ export function Sidebar({
* Drop of a group drag: splice the dragged group in beside its target and persist.
*
* `sequence` is the mode's FULL rendered key list — every group of the mode, not the
- * `groupCap` slice on screen — and commitGroupOrder folds it into the stored array
+ * page of groups on screen — and commitGroupOrder folds it into the stored array
* where those groups already render, so a Workspace whose Sessions have not paged in
* yet keeps its stored place instead of being pushed behind the ones that have.
*
@@ -663,7 +699,7 @@ export function Sidebar({
/**
* Drag-reorder wiring of one group header, given the mode's FULL ordered key list
- * (not the `groupCap` slice on screen — committing only the visible groups would drop
+ * (not the page of groups on screen — committing only the visible groups would drop
* the hidden ones out of the stored sequence and bring them back as newcomers).
*
* Offered only where the groups have an order to change (isOrderableGroupMode: time
@@ -762,11 +798,25 @@ export function Sidebar({
/** In-flight key of one group's category "More" (folderKey shares the same composite for folder categories). */
const loadKey = (groupKey: string, category: SessionCategory) => `${category}\0${groupKey}`;
+ /**
+ * The server stream a group's fetches walk: its own, under Workspace grouping, or the
+ * Agent's whole one otherwise. Only Workspace groups need their own — an Agent group IS
+ * the whole stream, and a time bucket is cut from rows that are already loaded, so it
+ * fetches nothing of its own at all.
+ *
+ * This is what makes the groups independent. Sharing one per-Agent cursor meant a group's
+ * "load more" consumed the page its siblings were about to read: their rows appeared,
+ * their reveal counts moved, and the group that asked could grow by less than a page — or
+ * by nothing at all.
+ */
+ const fetchScope = (groupKey: string): string | undefined =>
+ groupMode === "workspace" ? groupKey : undefined;
+
/** loadMoreFor with an in-flight marker for the triggering "More" row (disable + loading text). */
const trackedLoadMore = (groupKey: string, category: SessionCategory, agentIds: string[]) => {
const key = loadKey(groupKey, category);
setPendingLoads((prev) => new Set(prev).add(key));
- void loadMoreFor(agentIds, category).finally(() => {
+ void loadMoreFor(agentIds, category, fetchScope(groupKey)).finally(() => {
setPendingLoads((prev) => {
const next = new Set(prev);
next.delete(key);
@@ -794,8 +844,9 @@ export function Sidebar({
return next;
});
if (opening) {
- const unloaded = agentIds.filter((id) => !isLoadedFor(id, category));
- if (unloaded.length > 0) void loadMoreFor(unloaded, category);
+ const scope = fetchScope(groupKey);
+ const unloaded = agentIds.filter((id) => !isLoadedFor(id, category, scope));
+ if (unloaded.length > 0) void loadMoreFor(unloaded, category, scope);
}
};
@@ -826,10 +877,47 @@ export function Sidebar({
const key = folderKey(groupKey, category);
setOpenFolders((prev) => (prev.has(key) ? prev : new Set(prev).add(key)));
// Same on-demand load a click-expand does, for this Session's own Agent (siblings of
- // other contributing Agents stay behind the folder's "More").
- if (!isLoadedFor(s.agentId, category)) void loadMoreFor([s.agentId], category);
+ // other contributing Agents stay behind the folder's "More"), down the same stream the
+ // folder itself pages.
+ const scope = groupMode === "workspace" ? groupKey : undefined;
+ if (!isLoadedFor(s.agentId, category, scope)) void loadMoreFor([s.agentId], category, scope);
}, [activeSessionId, sessions, groupMode, isLoadedFor, loadMoreFor]);
+ /**
+ * Workspace mode: give every rendered group its own first page. The initial load reads
+ * the Agent's whole stream, which is one stream cut by Workspace — it fills the groups
+ * unevenly, so a group can come up with two rows while the neighbour it shares an Agent
+ * with got eight. Any group left short of a full first page (or of its own total, if that
+ * is smaller) asks for one down its own stream, once: the scoped pair is loaded from then
+ * on and this is inert.
+ *
+ * Only the groups on screen ask — the pager bounds that to one page of groups — and a
+ * search is left alone, since it renders loaded matches only and fetching cannot find more.
+ */
+ useEffect(() => {
+ if (groupMode !== "workspace" || searching) return;
+ 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)]),
+ ];
+ const unloaded = agents.filter((id) => !isLoadedFor(id, "active", group.key));
+ if (unloaded.length > 0) void loadMoreFor(unloaded, "active", group.key);
+ }
+ }, [
+ groupMode,
+ searching,
+ orderedWorkspaceGroups,
+ shownGroupPage,
+ workspaceGroupCounts,
+ isLoadedFor,
+ loadMoreFor,
+ ]);
+
/**
* Manual server-update check, from the menu's update row: forces a lookup past the
* server's TTL cache and pushes the result into the shared version-info store, so the
@@ -995,15 +1083,18 @@ export function Sidebar({
/**
* 新建工作区: register the browsed pick so it surfaces as a group immediately, Sessions
- * or not. Empty registered groups sort after the session-backed ones, so widen the
- * group display cap to cover the whole list — otherwise, past ten groups, the freshly
- * added Workspace would land behind 更多分组 and the click would look like a no-op.
+ * or not. An empty registered group is appended and nothing pins or orders it yet, so it
+ * lands last — turn to the page that now holds it, or to the page of the group that was
+ * already there. Otherwise, past ten groups, the freshly added Workspace would sit on a
+ * page the user is not looking at and the click would read as a no-op.
*/
const addWorkspace = (path: string) => {
const next = registerWorkspace(registeredWorkspaces, path);
if (next === registeredWorkspaces) return;
applyRegistryChange(next);
- setGroupCap((c) => Math.max(c, workspaceGroups.length + 1));
+ const key = workspaceGroupKey(path);
+ const existing = orderedWorkspaceGroups.findIndex((g) => g.key === key);
+ setGroupPage(groupPageOf(existing >= 0 ? existing : orderedWorkspaceGroups.length));
};
/** Paths with a registry entry — only their groups offer the rename/remove overflow. */
@@ -1200,7 +1291,9 @@ export function Sidebar({
// More while the group's share isn't fully loaded AND somewhere is left to fetch from
// (counts drifting above reality would otherwise leave a dead button until reload).
const more =
- !searching && rows.length < total && agentIds.some((id) => hasMoreFor(id, category));
+ !searching &&
+ rows.length < total &&
+ agentIds.some((id) => hasMoreFor(id, category, fetchScope(groupKey)));
return (
<FolderSection
key={category}
@@ -1208,6 +1301,9 @@ export function Sidebar({
open={searching || openFolders.has(folderKey(groupKey, category))}
onToggle={() => toggleFolder(groupKey, category, agentIds)}
more={more}
+ // The folder shows every row it has loaded, so its remainder is its own share
+ // minus those — the same count the active list's reveal row names one level up.
+ moreLabel={S.chat.expandRestSessions(Math.max(total - rows.length, 0))}
pending={pendingLoads.has(loadKey(groupKey, category))}
onMore={() => trackedLoadMore(groupKey, category, agentIds)}
>
@@ -1216,14 +1312,31 @@ export function Sidebar({
);
};
- /** Active-list "More": reveal one more page of already-loaded active rows AND fetch the next active server page for every Agent that still has one. */
- const showMore = (groupKey: string, agentIds: string[]) => {
+ /**
+ * Active-list "Show N more chats": reveal one more page of this group's already-loaded
+ * active rows, and fetch the next active server page only when the reveal actually runs
+ * past what is loaded. A group whose next page is already in memory spends no request —
+ * in workspace mode a fetch fans out to every Agent contributing to the group and its
+ * rows may land in other groups entirely, so a pointless one is not free.
+ */
+ const showMore = (groupKey: string, agentIds: string[], loaded: number) => {
+ const nextCap = (groupCaps.get(groupKey) ?? SIDEBAR_PAGE_SIZE) + SIDEBAR_PAGE_SIZE;
setGroupCaps((prev) => {
const next = new Map(prev);
- next.set(groupKey, (prev.get(groupKey) ?? SIDEBAR_PAGE_SIZE) + SIDEBAR_PAGE_SIZE);
+ next.set(groupKey, nextCap);
+ return next;
+ });
+ if (agentIds.length > 0 && loaded < nextCap) trackedLoadMore(groupKey, "active", agentIds);
+ };
+
+ /** "Show less": drop one group's reveal back to the first page (rows already fetched stay in memory). */
+ const collapseRows = (groupKey: string) => {
+ setGroupCaps((prev) => {
+ if (!prev.has(groupKey)) return prev;
+ const next = new Map(prev);
+ next.delete(groupKey);
return next;
});
- if (agentIds.length > 0) trackedLoadMore(groupKey, "active", agentIds);
};
/**
@@ -1262,14 +1375,28 @@ export function Sidebar({
effectiveSortMode === "manual" && !searching
? { scope: groupKey, fullRows: orderedActive }
: undefined;
- // Only the outer active rows drive the group's "More" — the folders never feed it:
- // hidden loaded rows exist, or the group's own active share isn't fully loaded yet.
+ // The reveal row counts THIS group's own hidden conversations and nothing else — the
+ // folders never feed it, and no other group's numbers reach it. `fullyLoaded` says the
+ // group's whole active share is already in memory (every Agent that could hold a row of
+ // 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 activeTotal = Math.max(totals?.active ?? 0, parts.active.length);
- const hasMore =
- !searching &&
- (parts.active.length > cap ||
- (parts.active.length < activeTotal && activeAgents.some((id) => hasMoreFor(id, "active"))));
+ const fullyLoaded =
+ activeAgents.length > 0 &&
+ !activeAgents.some((id) => hasMoreFor(id, "active", fetchScope(groupKey)));
+ const hiddenActive = searching
+ ? 0
+ : hiddenRowCount({
+ shown: shownActive.length,
+ loaded: parts.active.length,
+ total: totals?.active ?? 0,
+ fullyLoaded,
+ });
+ // "Show less" appears once the group is revealed past its first page and there is
+ // something for it to hide again.
+ const canCollapse =
+ !searching && cap > SIDEBAR_PAGE_SIZE && parts.active.length > SIDEBAR_PAGE_SIZE;
const folders = FOLDER_CATEGORIES.map((category) =>
renderFolder(groupKey, category, parts, withAgentHint, agentsFor(category), totals),
);
@@ -1287,15 +1414,26 @@ export function Sidebar({
renderRows(shownActive, withAgentHint, dragCtx, true)
)}
- {/* Load/reveal more (kept adjacent to the active list it extends, above the folders) */}
- {hasMore && (
+ {/* Reveal / collapse this group's own conversations (kept adjacent to the active
+ list they extend, above the folders). Both rows can stand at once: a group
+ revealed part-way still has more to show AND something to fold back. */}
+ {hiddenActive > 0 && (
<MoreRow
- label={S.chat.loadMore}
+ label={S.chat.expandRestSessions(hiddenActive)}
+ ariaLabel={S.chat.expandRestSessions(hiddenActive)}
pending={activePending}
- onClick={() => showMore(groupKey, activeAgents)}
+ onClick={() => showMore(groupKey, activeAgents, parts.active.length)}
className="mt-0.5"
/>
)}
+ {canCollapse && (
+ <MoreRow
+ label={S.chat.showLess}
+ ariaLabel={S.chat.showLess}
+ onClick={() => collapseRows(groupKey)}
+ {...(hiddenActive > 0 ? {} : { className: "mt-0.5" })}
+ />
+ )}
{/* Folders (collapsed by default): subagent first — spawned from the conversations
at hand — then scheduled background runs, then archived (archived wins over the
@@ -1305,15 +1443,6 @@ export function Sidebar({
);
};
- /** Reveal-next-page-of-groups row (render cap only — data loading is untouched). */
- const moreGroupsRow = (total: number) => (
- <MoreRow
- label={S.chat.moreGroups(total - groupCap)}
- onClick={() => setGroupCap((c) => c + SIDEBAR_GROUP_PAGE_SIZE)}
- className="mt-1"
- />
- );
-
/**
* Time mode's one shared, Project-wide set of folders (rendered once below the buckets):
* their rows load only on first expand, so an unloaded Session has no known bucket and no
@@ -1756,10 +1885,10 @@ export function Sidebar({
loading && agents.length === 0 ? (
<SkeletonList rows={5} />
) : (
- // While searching: every group renders (cap bypassed), zero-match groups
+ // While searching: every group renders (paging bypassed), zero-match groups
// hide, and the rest are forced open — a hit inside a collapsed group would
// look like a missing result.
- orderedAgents.slice(0, searching ? orderedAgents.length : groupCap).map((agent) => {
+ groupsOnPage(orderedAgents).map((agent) => {
const groupRows = filterRows(byAgent.get(agent.agentId) ?? []);
if (searching && groupRows.length === 0) return null;
const parts = partitionSessions(groupRows);
@@ -1822,9 +1951,7 @@ export function Sidebar({
})
)
) : null}
- {groupMode === "agent" && !searching && orderedAgents.length > groupCap
- ? moreGroupsRow(orderedAgents.length)
- : null}
+ {groupMode === "agent" ? groupPagerRow() : null}
{groupMode !== "workspace" ? null : loading && sessions.length === 0 ? (
<SkeletonList rows={5} />
) : orderedWorkspaceGroups.length === 0 && !searching ? (
@@ -1832,95 +1959,91 @@ export function Sidebar({
{S.chat.noSessions}
</p>
) : (
- // Same search treatment as agent mode: cap bypassed, zero-match groups hidden, the rest forced open.
- orderedWorkspaceGroups
- .slice(0, searching ? orderedWorkspaceGroups.length : groupCap)
- .map((group) => {
- const groupRows = filterRows(group.sessions);
- if (searching && groupRows.length === 0) return null;
- const parts = partitionSessions(groupRows);
- const collapsed = !searching && collapsedGroups.has(group.key);
- const pinned = pinnedGroups.has(group.key);
- const drag = groupDragProps(group.key, workspaceGroupSequence);
- /** This group's exact server share (per-Workspace fold) and its per-category fetch fan-out. */
- const counts = workspaceGroupCounts.get(group.key);
- const contributingAgents = [...new Set(group.sessions.map((s) => s.agentId))];
- const agentsFor = (category: SessionCategory) => [
- ...new Set([...(counts?.agents[category] ?? []), ...contributingAgents]),
- ];
- return (
- <GroupBlock key={group.key} dropEdge={drag.dropEdge}>
- {/* Group header: collapse toggle (folder icon + directory basename + count, full
+ // Same search treatment as agent mode: paging bypassed, zero-match groups hidden, the rest forced open.
+ groupsOnPage(orderedWorkspaceGroups).map((group) => {
+ const groupRows = filterRows(group.sessions);
+ if (searching && groupRows.length === 0) return null;
+ const parts = partitionSessions(groupRows);
+ const collapsed = !searching && collapsedGroups.has(group.key);
+ const pinned = pinnedGroups.has(group.key);
+ const drag = groupDragProps(group.key, workspaceGroupSequence);
+ /** This group's exact server share (per-Workspace fold) and its per-category fetch fan-out. */
+ const counts = workspaceGroupCounts.get(group.key);
+ const contributingAgents = [...new Set(group.sessions.map((s) => s.agentId))];
+ const agentsFor = (category: SessionCategory) => [
+ ...new Set([...(counts?.agents[category] ?? []), ...contributingAgents]),
+ ];
+ return (
+ <GroupBlock key={group.key} dropEdge={drag.dropEdge}>
+ {/* Group header: collapse toggle (folder icon + directory basename + count, full
path in the tooltip; the count = the group's active conversations only, exact
server share, loaded rows win a disagreement — the folders never feed it) +
pin + new chat in this Workspace; also the group's drag handle. */}
- <GroupHeader
- {...drag.header}
- open={!collapsed}
- onToggle={() => toggleGroup(group.key)}
- icon={
- /* Folder opens and closes with the group */
- <span className="shrink-0 text-gray-400 dark:text-gray-500">
- <Icon
- d={collapsed ? FOLDER_ICON : FOLDER_OPEN_ICON}
- size={ICON_SIZE.groupHeaderGlyph}
- />
- </span>
- }
- label={group.temp ? S.chat.tempWorkspaces : group.label}
- count={
- searching
- ? parts.active.length
- : Math.max(counts?.totals.active ?? 0, parts.active.length)
- }
- {...(group.fullPath !== null ? { title: group.fullPath } : {})}
- actions={
- <>
- <GroupPinButton pinned={pinned} onToggle={() => togglePin(group.key)} />
- {/* New chat in this Workspace: pre-fills the group's path in the draft ("" = temporary workspace); the Agent is the current one, falling back to default_agent */}
- <button
- type="button"
- title={S.chat.newSessionInWorkspace}
- aria-label={S.chat.newSessionInWorkspace}
- onClick={() => newChat(workspaceNewChatAgentId, group.fullPath ?? "")}
- className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-gray-400 transition-colors duration-150 hover:bg-gray-200/70 hover:text-gray-800 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200"
- >
- <Icon d="M12 5v14M5 12h14" size={ICON_SIZE.groupHeaderAction} />
- </button>
- {/* Manually-added (registry-backed) Workspaces only: rename-alias /
+ <GroupHeader
+ {...drag.header}
+ open={!collapsed}
+ onToggle={() => toggleGroup(group.key)}
+ icon={
+ /* Folder opens and closes with the group */
+ <span className="shrink-0 text-gray-400 dark:text-gray-500">
+ <Icon
+ d={collapsed ? FOLDER_ICON : FOLDER_OPEN_ICON}
+ size={ICON_SIZE.groupHeaderGlyph}
+ />
+ </span>
+ }
+ label={group.temp ? S.chat.tempWorkspaces : group.label}
+ count={
+ searching
+ ? parts.active.length
+ : Math.max(counts?.totals.active ?? 0, parts.active.length)
+ }
+ {...(group.fullPath !== null ? { title: group.fullPath } : {})}
+ actions={
+ <>
+ <GroupPinButton pinned={pinned} onToggle={() => togglePin(group.key)} />
+ {/* New chat in this Workspace: pre-fills the group's path in the draft ("" = temporary workspace); the Agent is the current one, falling back to default_agent */}
+ <button
+ type="button"
+ title={S.chat.newSessionInWorkspace}
+ aria-label={S.chat.newSessionInWorkspace}
+ onClick={() => newChat(workspaceNewChatAgentId, group.fullPath ?? "")}
+ className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-gray-400 transition-colors duration-150 hover:bg-gray-200/70 hover:text-gray-800 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200"
+ >
+ <Icon d="M12 5v14M5 12h14" size={ICON_SIZE.groupHeaderAction} />
+ </button>
+ {/* Manually-added (registry-backed) Workspaces only: rename-alias /
remove-from-sidebar overflow, to the right of the "+" (session-
derived groups have no registry entry for these to act on). */}
- {registeredPaths.has(group.key) && (
- <GroupOverflowMenu
- onRename={() => openRenameWorkspace(group.key)}
- onDelete={() =>
- setDeletingWorkspace({ path: group.key, label: group.label })
- }
- />
- )}
- </>
- }
- />
+ {registeredPaths.has(group.key) && (
+ <GroupOverflowMenu
+ onRename={() => openRenameWorkspace(group.key)}
+ onDelete={() =>
+ setDeletingWorkspace({ path: group.key, label: group.label })
+ }
+ />
+ )}
+ </>
+ }
+ />
- {/* A workspace group can span Agents: the group body fans folder loads and "More"
+ {/* A workspace group can span Agents: the group body fans folder loads and "More"
out per category to the Agents whose share of THIS group is non-zero (plus the
Agents already contributing loaded rows) — the active list and each folder
page independently. */}
- {collapsed
- ? null
- : renderGroupBody(group.key, parts, true, counts?.totals, agentsFor)}
- </GroupBlock>
- );
- })
+ {collapsed
+ ? null
+ : renderGroupBody(group.key, parts, true, counts?.totals, agentsFor)}
+ </GroupBlock>
+ );
+ })
)}
- {groupMode === "workspace" && !searching && orderedWorkspaceGroups.length > groupCap
- ? moreGroupsRow(orderedWorkspaceGroups.length)
- : null}
+ {groupMode === "workspace" ? groupPagerRow() : null}
{/* Time mode: last day / last month / earlier, bucketed on each conversation's last
activity — the same stamp the rows' compact timestamps and the recency sort read,
so a row can never sit under a bucket its own timestamp contradicts. Empty buckets
- are dropped, and there are at most three, so this mode has no "more groups" row.
+ are 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. */}
diff --git a/packages/web/src/components/ui/group-list.tsx b/packages/web/src/components/ui/group-list.tsx
index 6574a1f5..d748f655 100644
--- a/packages/web/src/components/ui/group-list.tsx
+++ b/packages/web/src/components/ui/group-list.tsx
@@ -191,6 +191,69 @@ export function MoreRow({
);
}
+/** Chevrons of the group pager's step buttons (lucide chevron-left / chevron-right). */
+const PAGER_PREV_ICON = "M15 18 9 12l6-6";
+const PAGER_NEXT_ICON = "m9 18 6-6-6-6";
+
+/**
+ * Page stepper of a grouped list whose groups are paginated (the sidebar renders at most
+ * SIDEBAR_GROUP_PAGE_SIZE groups per page): two flat chevron buttons around the "2/5"
+ * position readout, no wider than the rows it sits under — this list is a drawer at phone
+ * width. `page` is 0-based; the readout and the accessible names count from 1.
+ *
+ * Rendered only by callers that already know there is more than one page; the buttons
+ * still disable at the ends so the control never offers a step that goes nowhere.
+ */
+export function GroupPager({
+ page,
+ pageCount,
+ onChange,
+}: {
+ page: number;
+ pageCount: number;
+ onChange: (page: number) => void;
+}) {
+ const step = (delta: number) => {
+ const next = page + delta;
+ if (next >= 0 && next < pageCount) onChange(next);
+ };
+ const buttonClass =
+ "flex h-6 w-6 shrink-0 items-center justify-center rounded text-gray-400 transition-colors duration-150 hover:bg-gray-200/50 hover:text-gray-700 disabled:pointer-events-none disabled:opacity-40 dark:text-gray-500 dark:hover:bg-gray-800/50 dark:hover:text-gray-300";
+ return (
+ <div className="mt-1 flex items-center justify-center gap-1.5 px-1.5 py-0.5">
+ <button
+ type="button"
+ title={S.chat.prevGroupPage}
+ aria-label={S.chat.prevGroupPage}
+ disabled={page <= 0}
+ onClick={() => step(-1)}
+ className={buttonClass}
+ >
+ <Icon d={PAGER_PREV_ICON} size={12} />
+ </button>
+ {/* The position doubles as the control's status: announced on change so a step is
+ audible without counting the rows that swapped underneath it. */}
+ <span
+ aria-live="polite"
+ aria-label={S.chat.groupPagePosition(page + 1, pageCount)}
+ className="min-w-[2.5rem] text-center text-[11px] font-medium tabular-nums text-gray-400 dark:text-gray-500"
+ >
+ {page + 1}/{pageCount}
+ </span>
+ <button
+ type="button"
+ title={S.chat.nextGroupPage}
+ aria-label={S.chat.nextGroupPage}
+ disabled={page >= pageCount - 1}
+ onClick={() => step(1)}
+ className={buttonClass}
+ >
+ <Icon d={PAGER_NEXT_ICON} size={12} />
+ </button>
+ </div>
+ );
+}
+
/**
* Collapsed-by-default lazy folder (subagent / scheduled / archived): the toggle row
* shows the label (typically with the group's exact server share), the body renders only
@@ -201,6 +264,7 @@ export function FolderSection({
open,
onToggle,
more = false,
+ moreLabel,
pending = false,
onMore,
children,
@@ -210,6 +274,12 @@ export function FolderSection({
onToggle: () => void;
/** Show the folder's own "More" row (its share isn't fully loaded and somewhere is left to fetch from). */
more?: boolean;
+ /**
+ * Wording of that row, when the caller can count what is still hidden in THIS folder
+ * ("Show 7 more chats"). Defaults to the bare shared "More" — the honest label where
+ * the caller has no per-folder remainder to name.
+ */
+ moreLabel?: string;
/** The folder's "More" fetch in flight. */
pending?: boolean;
onMore?: () => void;
@@ -223,7 +293,12 @@ export function FolderSection({
</button>
{open && children}
{open && more && (
- <MoreRow label={S.chat.loadMore} pending={pending} onClick={() => onMore?.()} />
+ <MoreRow
+ label={moreLabel ?? S.chat.loadMore}
+ {...(moreLabel !== undefined ? { ariaLabel: moreLabel } : {})}
+ pending={pending}
+ onClick={() => onMore?.()}
+ />
)}
</div>
);
diff --git a/packages/web/src/lib/session-grouping.ts b/packages/web/src/lib/session-grouping.ts
index 76ad2524..705404e8 100644
--- a/packages/web/src/lib/session-grouping.ts
+++ b/packages/web/src/lib/session-grouping.ts
@@ -37,6 +37,16 @@ export function workspaceGroupKey(workspace: string): string {
return isTempWorkspace(workspace) ? TEMP_WORKSPACE_GROUP_KEY : workspace.trim();
}
+/**
+ * Query value that names a Workspace group to the server's list endpoint — the group's
+ * path, or the sentinel the server merges every auto-created temporary Workspace under
+ * (its `TEMP_WORKSPACE_GROUP`; stored Workspaces are realpath results and therefore
+ * absolute, so the bare word cannot collide with one).
+ */
+export function workspaceGroupQuery(groupKey: string): string {
+ return groupKey === TEMP_WORKSPACE_GROUP_KEY ? "temp" : groupKey;
+}
+
/** Short display label: the last path segment (the filesystem root yields "/"). */
export function workspaceLabel(workspace: string): string {
const parts = workspace
@@ -56,12 +66,70 @@ export function workspaceLabel(workspace: string): string {
export const SIDEBAR_PAGE_SIZE = 10;
/**
- * Groups (Agents / Workspace groups) rendered per sidebar "page": the initial render cap,
- * raised by one page per "more groups" click. A pure display cap — with dozens of groups the
- * full list renders too tall to scan (#139); the groups' data loading is unchanged.
+ * Groups (Agents / Workspace groups) rendered per sidebar page. With dozens of groups the
+ * full list renders too tall to scan (#139), so the sidebar paginates them: one page at a
+ * time, stepped by the pager below the list. A pure display window — every group's data
+ * loading is unchanged, and the manual group order is committed over the whole sequence,
+ * not the page on screen.
*/
export const SIDEBAR_GROUP_PAGE_SIZE = 10;
+/** Pages `total` groups take (always at least one, so an empty list still has a page 1). */
+export function groupPageCount(total: number, pageSize = SIDEBAR_GROUP_PAGE_SIZE): number {
+ return Math.max(1, Math.ceil(total / pageSize));
+}
+
+/**
+ * A stored page number pinned inside the pages that currently exist. Groups come and go
+ * (a Workspace is removed, an Agent is deleted, a Project switch swaps the whole list),
+ * and a page that outlived its groups must land on the last real one rather than render
+ * an empty sidebar.
+ */
+export function clampGroupPage(
+ page: number,
+ total: number,
+ pageSize = SIDEBAR_GROUP_PAGE_SIZE,
+): number {
+ return Math.min(Math.max(page, 0), groupPageCount(total, pageSize) - 1);
+}
+
+/** The page a group at `index` of the ordered sequence renders on (0-based both ends). */
+export function groupPageOf(index: number, pageSize = SIDEBAR_GROUP_PAGE_SIZE): number {
+ return Math.floor(Math.max(index, 0) / pageSize);
+}
+
+/** The groups of one page, in the order given (the caller has already sorted them). */
+export function groupPageSlice<T>(
+ groups: readonly T[],
+ page: number,
+ pageSize = SIDEBAR_GROUP_PAGE_SIZE,
+): T[] {
+ const start = clampGroupPage(page, groups.length, pageSize) * pageSize;
+ return groups.slice(start, start + pageSize);
+}
+
+/**
+ * Conversations of one group that its reveal row still hides — what "Show N more chats"
+ * counts. Computed from the group's OWN numbers only: `loaded` rows are in memory,
+ * `shown` of them are past the display cap, and `total` is the group's exact server share
+ * — except once every Agent that could hold its rows is fully fetched (`fullyLoaded`),
+ * when the loaded rows ARE the share. That last clause is what keeps a count drifting
+ * above reality (totals refresh only on reload) from leaving a row that reveals nothing.
+ */
+export function hiddenRowCount({
+ shown,
+ loaded,
+ total,
+ fullyLoaded,
+}: {
+ shown: number;
+ loaded: number;
+ total: number;
+ fullyLoaded: boolean;
+}): number {
+ return Math.max((fullyLoaded ? loaded : Math.max(total, loaded)) - shown, 0);
+}
+
/**
* 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
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index a84d85c7..15c64ba8 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -1555,8 +1555,12 @@ Scenarios:
/** Visible label on the Memory panel's header link (not a tooltip-only glyph): says what the click does and where it lands. */
openAgentMemory: "Manage in agent settings",
memoryShowMore: (n: number) => `Show ${n} more`,
- /** Reveal the next page of sidebar groups (#139); n = groups still hidden. */
+ /** Reveal the next page of the Trace page's group tree; n = groups still hidden. */
moreGroups: (n: number) => `More groups (${n})`,
+ /** Sidebar group pagination (#139): the pager's step buttons and the "2/5" readout's accessible name. */
+ prevGroupPage: "Previous groups",
+ nextGroupPage: "Next groups",
+ groupPagePosition: (page: number, total: number) => `Page ${page} of ${total}`,
contextUsage: "Context usage",
contextUnknown: "Context usage: unknown until the next request reports it",
contextComposition: "Context composition",
@@ -1674,6 +1678,8 @@ Scenarios:
pinnedSession: "Pinned",
/** Sidebar group "reveal/load next page" row (display cap + server paging). */
loadMore: "More",
+ /** Per-group reveal row: n = conversations THIS group still hides (one click reveals/loads one page more). */
+ expandRestSessions: (n: number) => `Show ${n} more ${n === 1 ? "chat" : "chats"}`,
/** Time mode's whole-list paging row: its buckets span every Agent, so one row below them fetches the next page rather than each bucket claiming to. */
loadMoreSessions: "Load more chats",
/** Collapsed sidebar folders inside a group (lazy-loaded); the count is the group's exact server share. */
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index f9e02af0..a1c0cc44 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -1514,8 +1514,12 @@ Benchmark:
/** Visible label on the Memory panel's header link (not a tooltip-only glyph): says what the click does and where it lands. */
openAgentMemory: "在 Agent 设置中管理",
memoryShowMore: (n: number) => `显示其余 ${n} 条`,
- /** Reveal the next page of sidebar groups (#139); n = groups still hidden. */
+ /** Reveal the next page of the Trace page's group tree; n = groups still hidden. */
moreGroups: (n: number) => `更多分组(${n})`,
+ /** Sidebar group pagination (#139): the pager's step buttons and the "2/5" readout's accessible name. */
+ prevGroupPage: "上一页分组",
+ nextGroupPage: "下一页分组",
+ groupPagePosition: (page: number, total: number) => `第 ${page} 页,共 ${total} 页`,
contextUsage: "上下文占用",
contextUnknown: "上下文占用:压缩后待下次请求回报",
/** Context ring -> composition panel: the trigger's accessible name, the six part labels, the tool ranking, and the panel's empty / failed states. */
@@ -1629,6 +1633,8 @@ Benchmark:
pinnedSession: "已置顶",
/** Sidebar group "reveal/load next page" row (display cap + server paging). */
loadMore: "更多",
+ /** Per-group reveal row: n = conversations THIS group still hides (one click reveals/loads one page more). */
+ expandRestSessions: (n: number) => `展开其余 ${n} 个对话`,
/** Time mode's whole-list paging row: its buckets span every Agent, so one row below them fetches the next page rather than each bucket claiming to. */
loadMoreSessions: "加载更多会话",
/** Collapsed sidebar folders inside a group (lazy-loaded); the count is the group's exact server share. */
diff --git a/packages/web/src/state/sessions.tsx b/packages/web/src/state/sessions.tsx
index e1b63212..15d67146 100644
--- a/packages/web/src/state/sessions.tsx
+++ b/packages/web/src/state/sessions.tsx
@@ -41,6 +41,8 @@ import {
SIDEBAR_PAGE_SIZE,
sessionCategory,
splitPage,
+ workspaceGroupKey,
+ workspaceGroupQuery,
} from "../lib/session-grouping";
import { useProject } from "./project";
@@ -53,14 +55,22 @@ interface SessionsContextValue {
countsByAgent: ReadonlyMap<string, SessionCategoryCounts>;
/** agentId → the same totals broken down by Workspace path (workspace-mode groups read their own share from it; maintained like countsByAgent). */
workspaceCountsByAgent: ReadonlyMap<string, Readonly<Record<string, SessionCategoryCounts>>>;
- /** Whether a pair's first page has been fetched (false = the folder shows nothing because nothing was asked for yet). */
- isLoadedFor: (agentId: string, category: SessionCategory) => boolean;
- /** Whether the server still holds unfetched Sessions of a category for an Agent — an unloaded pair answers from the counts. */
- hasMoreFor: (agentId: string, category: SessionCategory) => boolean;
+ /**
+ * Whether a pair's first page has been fetched (false = the folder shows nothing because
+ * nothing was asked for yet). `workspaceGroup` asks about ONE group's own stream, which
+ * is paged separately from the Agent's whole one.
+ */
+ 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;
loading: boolean;
reload: () => Promise<void>;
- /** Fetches a category's first page for each given unloaded Agent and the next page for each loaded one with more (no-op otherwise). */
- loadMoreFor: (agentIds: string[], category: SessionCategory) => Promise<void>;
+ /** Fetches a category's first page for each given unloaded Agent and the next page for each loaded one with more (no-op otherwise); `workspaceGroup` pages that group's own stream instead of the Agent's whole one. */
+ loadMoreFor: (
+ agentIds: string[],
+ category: SessionCategory,
+ workspaceGroup?: string,
+ ) => Promise<void>;
/** Prepend to the list on success (draft materialized by the first message, or explicit creation via dialog). */
add: (session: SessionInfo) => void;
/** Remove from the list in place after deletion (also tombstones the id — see isDeleted). */
@@ -100,8 +110,34 @@ export interface LiveRowFields {
const SessionsContext = createContext<SessionsContextValue | null>(null);
-/** Page-state key of one (Agent, category) pair ("\0" never appears in Agent ids). */
-const pageKey = (agentId: string, category: SessionCategory) => `${agentId}\0${category}`;
+/**
+ * Page-state key of one (Agent, category, Workspace-group) triple. The scope is the
+ * server's query form of a group (workspaceGroupQuery) — a path or the temp sentinel —
+ * and "" means the Agent's whole stream, which is what Agent and time grouping page down.
+ * "\0" appears in none of the three (the merged temp group's own key does contain one,
+ * which is exactly why the query form is what gets stored).
+ */
+const pageKey = (agentId: string, category: SessionCategory, scope = "") =>
+ `${agentId}\0${category}\0${scope}`;
+
+/** Every list category, in the order the store loads them (active eagerly, the folders on demand). */
+const ALL_CATEGORIES: readonly string[] = ["active", ...FOLDER_CATEGORIES];
+
+/** The triple a page key names, or null if it is not one (never, in practice — a guard for the reload scan). */
+function parsePageKey(
+ key: string,
+): { agentId: string; category: SessionCategory; scope: string } | null {
+ const parts = key.split("\0");
+ if (parts.length !== 3) return null;
+ const [agentId, category, scope] = parts as [string, string, string];
+ return ALL_CATEGORIES.includes(category)
+ ? { agentId, category: category as SessionCategory, scope }
+ : null;
+}
+
+/** Scope string of a Workspace group (undefined / "" = the Agent's whole stream). */
+const scopeOf = (workspaceGroup?: string) =>
+ workspaceGroup === undefined || workspaceGroup === "" ? "" : workspaceGroupQuery(workspaceGroup);
/** One pair's paging cursor. */
interface PagePosition {
@@ -140,7 +176,11 @@ interface SessionsStoreState {
showCliSessions: boolean;
reload: () => Promise<void>;
- loadMoreFor: (agentIds: string[], category: SessionCategory) => Promise<void>;
+ loadMoreFor: (
+ agentIds: string[],
+ category: SessionCategory,
+ workspaceGroup?: string,
+ ) => Promise<void>;
add: (session: SessionInfo) => void;
remove: (sessionId: string) => void;
replace: (session: SessionInfo) => void;
@@ -211,25 +251,33 @@ export function createSessionsStore() {
try {
const results = await Promise.all(
agentIds.map(async (agentId) => {
- // Active first page (with per-category totals) always; plus the first page of
- // every folder category already on screen — a reload triggered by a server
- // event must refresh, not blank, an open folder.
- const categories: SessionCategory[] = [
- "active",
- ...FOLDER_CATEGORIES.filter((cat) => get().pageState.has(pageKey(agentId, cat))),
+ // The Agent's whole-stream active first page (with per-category totals)
+ // always; plus the first page of every other pair already on screen — an open
+ // folder, and each Workspace group paging its own stream — because a reload
+ // triggered by a server event must refresh them, not blank them.
+ const pairs: { category: SessionCategory; scope: string }[] = [
+ { category: "active", scope: "" },
];
+ for (const key of get().pageState.keys()) {
+ const parsed = parsePageKey(key);
+ if (parsed === null || parsed.agentId !== agentId) continue;
+ if (parsed.category === "active" && parsed.scope === "") continue;
+ pairs.push({ category: parsed.category, scope: parsed.scope });
+ }
try {
const pages = await Promise.all(
- categories.map(async (category) => {
+ pairs.map(async ({ category, scope }) => {
const res = await api.listSessions(projectId, agentId, {
offset: 0,
limit: SIDEBAR_PAGE_SIZE + 1,
category,
- ...(category === "active" ? { withCounts: true } : {}),
+ ...(scope === "" ? {} : { workspaceGroup: scope }),
+ ...(category === "active" && scope === "" ? { withCounts: true } : {}),
...(showCliSessions ? { cli: true } : {}),
});
return {
category,
+ scope,
counts: res.counts,
workspaceCounts: res.workspaceCounts,
...splitPage(res.sessions, SIDEBAR_PAGE_SIZE),
@@ -254,7 +302,7 @@ export function createSessionsStore() {
>();
for (const r of results) {
for (const p of r.pages) {
- nextPageState.set(pageKey(r.agentId, p.category), {
+ nextPageState.set(pageKey(r.agentId, p.category, p.scope), {
hasMore: p.hasMore,
fetched: p.items.length,
});
@@ -287,31 +335,62 @@ export function createSessionsStore() {
* 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).
+ *
+ * `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.
*/
- loadMoreFor: async (agentIds, category) => {
+ loadMoreFor: async (agentIds, category, workspaceGroup) => {
const { projectId, showCliSessions } = get();
if (!projectId) return;
+ const scope = scopeOf(workspaceGroup);
const targets = [...new Set(agentIds)].filter((agentId) => {
- const position = get().pageState.get(pageKey(agentId, category));
+ const position = get().pageState.get(pageKey(agentId, category, scope));
+ // An unloaded pair: the Agent's own totals still decide whether asking is worth a
+ // request. 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 (get().countsByAgent.get(agentId)?.[category] ?? 0) > 0;
+ return scope !== "" || (get().countsByAgent.get(agentId)?.[category] ?? 0) > 0;
return position.hasMore;
});
if (targets.length === 0) return;
const g = gen;
+ /**
+ * Rows of this (Agent, category, group) already in the pool. They arrived on pages of
+ * the Agent'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.
+ */
+ const loadedInScope = (agentId: string, group: string) =>
+ get().sessions.filter(
+ (s) =>
+ s.agentId === agentId &&
+ sessionCategory(s) === category &&
+ workspaceGroupKey(s.workspace) === group,
+ ).length;
const results = await Promise.all(
targets.map(async (agentId) => {
- const offset = get().pageState.get(pageKey(agentId, category))?.fetched ?? 0;
+ const position = get().pageState.get(pageKey(agentId, category, scope));
+ const offset =
+ position?.fetched ??
+ (workspaceGroup === undefined || workspaceGroup === ""
+ ? 0
+ : loadedInScope(agentId, workspaceGroup));
try {
const fetched = (
await api.listSessions(projectId, agentId, {
offset,
limit: SIDEBAR_PAGE_SIZE + 1,
category,
+ ...(scope === "" ? {} : { workspaceGroup: scope }),
...(showCliSessions ? { cli: true } : {}),
})
).sessions;
- return { agentId, ...splitPage(fetched, SIDEBAR_PAGE_SIZE) };
+ return { agentId, offset, ...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.
@@ -327,10 +406,12 @@ export function createSessionsStore() {
const prevPageState = get().pageState;
const nextPageState = new Map(prevPageState);
for (const r of ok) {
- const key = pageKey(r.agentId, category);
+ const key = pageKey(r.agentId, category, scope);
nextPageState.set(key, {
hasMore: r.hasMore,
- fetched: (prevPageState.get(key)?.fetched ?? 0) + r.items.length,
+ // 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,
});
}
set({
@@ -585,15 +666,19 @@ export function SessionsProvider({ children }: { children: ReactNode }) {
const { pageState, countsByAgent } = state;
const isLoadedFor = useCallback(
- (agentId: string, category: SessionCategory) => pageState.has(pageKey(agentId, category)),
+ (agentId: string, category: SessionCategory, workspaceGroup?: string) =>
+ pageState.has(pageKey(agentId, category, scopeOf(workspaceGroup))),
[pageState],
);
const hasMoreFor = useCallback(
- (agentId: string, category: SessionCategory) => {
- const position = pageState.get(pageKey(agentId, category));
+ (agentId: string, category: SessionCategory, workspaceGroup?: string) => {
+ const scope = scopeOf(workspaceGroup);
+ const position = pageState.get(pageKey(agentId, category, scope));
if (position !== undefined) return position.hasMore;
- // Unloaded pair: anything the counts report is by definition still unfetched.
+ // Unloaded pair: anything the counts report is by definition still unfetched. A group's
+ // own stream is not in those counts, so an unloaded scoped pair answers from the
+ // Agent's total for the category — the group's share of it cannot exceed that.
return (countsByAgent.get(agentId)?.[category] ?? 0) > 0;
},
[pageState, countsByAgent],
diff --git a/packages/web/test/group-paging.test.ts b/packages/web/test/group-paging.test.ts
new file mode 100644
index 00000000..47b66729
--- /dev/null
+++ b/packages/web/test/group-paging.test.ts
@@ -0,0 +1,101 @@
+/**
+ * session-grouping.ts unit tests for the sidebar's two display windows: the PAGE of
+ * groups the list shows at a time, and the count of conversations one group still hides
+ * behind its "Show N more chats" row.
+ *
+ * The invariants worth pinning: a page number always resolves to a page that exists
+ * (groups come and go under a stored page), search-free slicing never drops or repeats a
+ * group across pages, and the hidden count is computed from ONE group's own numbers —
+ * with the loaded rows overriding a server total that drifted above reality, so the
+ * reveal row can never promise conversations that are not there.
+ */
+import { describe, expect, it } from "vitest";
+import {
+ SIDEBAR_GROUP_PAGE_SIZE,
+ clampGroupPage,
+ groupPageCount,
+ groupPageOf,
+ groupPageSlice,
+ hiddenRowCount,
+} from "../src/lib/session-grouping";
+
+const seq = (n: number) => Array.from({ length: n }, (_, i) => i);
+
+describe("groupPageCount", () => {
+ it("gives an empty list one page, so page 1 always exists", () => {
+ expect(groupPageCount(0)).toBe(1);
+ });
+
+ it("rounds up a partial last page", () => {
+ expect(groupPageCount(1)).toBe(1);
+ expect(groupPageCount(SIDEBAR_GROUP_PAGE_SIZE)).toBe(1);
+ expect(groupPageCount(SIDEBAR_GROUP_PAGE_SIZE + 1)).toBe(2);
+ expect(groupPageCount(SIDEBAR_GROUP_PAGE_SIZE * 3)).toBe(3);
+ });
+});
+
+describe("clampGroupPage", () => {
+ it("keeps a page that exists", () => {
+ expect(clampGroupPage(2, 25)).toBe(2);
+ });
+
+ it("lands on the last real page when the groups shrank under a stored page", () => {
+ expect(clampGroupPage(7, 25)).toBe(2);
+ expect(clampGroupPage(7, 0)).toBe(0);
+ });
+
+ it("floors at the first page", () => {
+ expect(clampGroupPage(-3, 25)).toBe(0);
+ });
+});
+
+describe("groupPageSlice", () => {
+ it("cuts consecutive, non-overlapping pages that cover the whole sequence", () => {
+ const groups = seq(23);
+ const pages = seq(groupPageCount(groups.length)).map((p) => groupPageSlice(groups, p));
+ expect(pages.map((page) => page.length)).toEqual([10, 10, 3]);
+ expect(pages.flat()).toEqual(groups);
+ });
+
+ it("clamps an out-of-range page to the last one rather than rendering nothing", () => {
+ expect(groupPageSlice(seq(12), 9)).toEqual([10, 11]);
+ });
+
+ it("holds the order it was given (the caller has already sorted)", () => {
+ expect(groupPageSlice(["b", "a", "c"], 0)).toEqual(["b", "a", "c"]);
+ });
+});
+
+describe("groupPageOf", () => {
+ it("maps a group's index to the page it renders on", () => {
+ expect(groupPageOf(0)).toBe(0);
+ expect(groupPageOf(SIDEBAR_GROUP_PAGE_SIZE - 1)).toBe(0);
+ expect(groupPageOf(SIDEBAR_GROUP_PAGE_SIZE)).toBe(1);
+ expect(groupPageOf(SIDEBAR_GROUP_PAGE_SIZE * 2 + 4)).toBe(2);
+ });
+});
+
+describe("hiddenRowCount", () => {
+ it("counts the loaded rows the display cap hides", () => {
+ expect(hiddenRowCount({ shown: 10, loaded: 14, total: 14, fullyLoaded: true })).toBe(4);
+ });
+
+ it("counts unfetched rows too while the group's share is not fully loaded", () => {
+ expect(hiddenRowCount({ shown: 10, loaded: 10, total: 42, fullyLoaded: false })).toBe(32);
+ });
+
+ it("drops a stale total once every Agent of the group is fetched out", () => {
+ // The counts refresh only on reload: a total left above reality would otherwise keep a
+ // reveal row on screen with nothing behind it.
+ expect(hiddenRowCount({ shown: 12, loaded: 12, total: 42, fullyLoaded: true })).toBe(0);
+ });
+
+ it("trusts loaded rows over a total that lags behind them", () => {
+ expect(hiddenRowCount({ shown: 10, loaded: 13, total: 11, fullyLoaded: false })).toBe(3);
+ });
+
+ it("never goes negative when everything is on screen", () => {
+ expect(hiddenRowCount({ shown: 8, loaded: 8, total: 8, fullyLoaded: true })).toBe(0);
+ expect(hiddenRowCount({ shown: 20, loaded: 8, total: 3, fullyLoaded: false })).toBe(0);
+ });
+});
diff --git a/packages/web/test/workspace-registry.test.ts b/packages/web/test/workspace-registry.test.ts
index 94a003a8..87c1ae83 100644
--- a/packages/web/test/workspace-registry.test.ts
+++ b/packages/web/test/workspace-registry.test.ts
@@ -179,9 +179,9 @@ describe("persisted registry (per-Project localStorage)", () => {
});
describe("mergeRegisteredWorkspaces", () => {
- it("empty registered groups sort AFTER the session-backed ones, so real conversations keep the capped window", () => {
- // Fronting them pushed every group holding chats behind 更多分组 (10-group cap) as
- // soon as a few Workspaces were registered.
+ it("empty registered groups sort AFTER the session-backed ones, so real conversations keep the first page", () => {
+ // Fronting them pushed every group holding chats onto a later page of the sidebar's
+ // 10-group pagination as soon as a few Workspaces were registered.
const groups = [group("/srv/app", { sessions: [{ id: "s1" }] }), group("/srv/beta")];
const merged = mergeRegisteredWorkspaces(groups, [
{ path: "/new/ws", alias: "Fancy" },