A local-first multi-agent app development platform, built on PenguinHarness
fix(web,server): the sidebar lists every Workspace, not only the ones its first pages touched (#663)
Yaowei Zheng73f515525a82
diff --git a/changelog/unreleased/2026-09-10-sidebar-workspace-groups-complete.md b/changelog/unreleased/2026-09-10-sidebar-workspace-groups-complete.mdnew file mode 100644index 00000000..b4fa1a24--- /dev/null+++ b/changelog/unreleased/2026-09-10-sidebar-workspace-groups-complete.md@@ -0,0 +1,16 @@+# The sidebar lists every Workspace, not only the ones its first pages touched++- **Date:** 2026-09-10+- **Type:** fix+- **Scope:** `web`, `server`+- **PR:** [#663](https://github.com/Prism-Shadow/penguin-harness/pull/663)++[中文版](2026-09-10-sidebar-workspace-groups-complete.zh.md)++Grouped by Workspace, the sidebar formed a group only for Workspaces that one of its loaded rows belonged to, and the initial load is each Agent's ten newest conversations. With dozens of Workspaces holding hundreds of conversations each, a Workspace whose newest conversation was older than an Agent's ten newest never appeared at all. The group list is now built from the server's per-Workspace counts as well: every Workspace that holds Sessions is a group, and the groups are placed by their newest Session whether or not any of its rows are loaded.++## Details++- The session list's `counts=1` response carries `workspaceLatest` beside `workspaceCounts`: each Workspace path's newest Session `createdAt`, taken in the same newest-first walk.+- A group known from the counts alone starts empty and asks for its own first page when its page of groups is on screen, as every group already did for its missing rows. While that page is on its way the group shows a loading skeleton, not "no conversations"; a failed fetch leaves the reveal row as the retry.+- Ordering: the newer of a group's newest loaded row and the server's stamp, temporary Workspaces merged last, manually-added empty Workspaces behind them — so a group does not move when its rows arrive.diff --git a/changelog/unreleased/2026-09-10-sidebar-workspace-groups-complete.zh.md b/changelog/unreleased/2026-09-10-sidebar-workspace-groups-complete.zh.mdnew file mode 100644index 00000000..dbf08c59--- /dev/null+++ b/changelog/unreleased/2026-09-10-sidebar-workspace-groups-complete.zh.md@@ -0,0 +1,16 @@+# 侧边栏列出全部工作区,而不只是首页触及的那几个++- **Date:** 2026-09-10+- **Type:** fix+- **Scope:** `web`, `server`+- **PR:** [#663](https://github.com/Prism-Shadow/penguin-harness/pull/663)++[English](2026-09-10-sidebar-workspace-groups-complete.md)++按 Workspace 分组时,侧边栏只为已加载行所属的 Workspace 成组,而初始加载只取每个 Agent 最新的 10 条对话。几十个 Workspace 各有几百条对话时,最新对话排不进某个 Agent 前 10 名的 Workspace 就根本不出现。现在分组清单同时取自服务端按 Workspace 细分的计数:凡持有 Session 的 Workspace 都成组,并按各自最新 Session 的时间就位,不论其行是否已加载。++## 细节++- 会话列表 `counts=1` 的响应在 `workspaceCounts` 之外新增 `workspaceLatest`:每个 Workspace 路径最新 Session 的 `createdAt`,在同一趟最新优先的遍历中取得。+- 仅由计数得知的组先以空组出现,所在的分组页上屏时沿本组流拉取自己的首页,与既有各组补齐缺行的做法一致。首页在途时该组显示加载骨架而非「暂无会话」;拉取失败则保留「更多」行作为重试入口。+- 排序取组内最新已加载行与服务端时间戳中较新者,临时工作区合并组恒在最后,手动添加的空工作区殿后——行到达时组不会挪位。diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex 4cbbcca7..721315d2 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -1289,6 +1289,13 @@ export interface SessionsResponse {* content that lives in other Workspaces.*/workspaceCounts?: Record<string, SessionCategoryCounts>;+ /**+ * Present with `counts`: each Workspace path's newest Session (any category), as its+ * `createdAt`. With `workspaceCounts` this is what lets the sidebar list every Workspace+ * that holds Sessions and place the groups by recency before — or without — loading any+ * of their rows.+ */+ workspaceLatest?: Record<string, string>;}/** Server directory browsing (advanced new-Workspace picker): starts from the home directory by default, can navigate up to the root. */diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.tsindex e1cc3a50..76f49b1e 100644--- a/packages/server/src/http/routes/sessions.ts+++ b/packages/server/src/http/routes/sessions.ts@@ -446,20 +446,18 @@ export function agentSessionsRoutes(deps: AppDeps): Hono<AppEnv> {}const rawCounts = c.req.query("counts");if (rawCounts !== undefined && rawCounts !== "1") throw badRequest("counts only accepts 1.");- const { sessions, counts, workspaceCounts } = await deps.sessionService.listSessions(- projectId,- agentId,- {+ const { sessions, counts, workspaceCounts, workspaceLatest } =+ await deps.sessionService.listSessions(projectId, agentId, {...(paging ? { paging } : {}),...(rawCategory !== undefined ? { category: rawCategory as SessionCategory } : {}),...(rawWorkspaceGroup !== undefined ? { workspaceGroup: rawWorkspaceGroup } : {}),...(rawCounts !== undefined ? { withCounts: true } : {}),- },- );+ });return c.json({sessions,...(counts ? { counts } : {}),...(workspaceCounts ? { workspaceCounts } : {}),+ ...(workspaceLatest ? { workspaceLatest } : {}),} satisfies SessionsResponse);});diff --git a/packages/server/src/services/session-service.ts b/packages/server/src/services/session-service.tsindex 0b79177d..d472ec73 100644--- a/packages/server/src/services/session-service.ts+++ b/packages/server/src/services/session-service.ts@@ -172,8 +172,10 @@ export class SessionService {* 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 — so the sidebar can label the collapsed- * folders (and a workspace group can know its own share) without loading them.+ * 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.** `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@@ -194,6 +196,7 @@ export class SessionService {sessions: SessionInfo[];counts?: SessionCategoryCounts;workspaceCounts?: Record<string, SessionCategoryCounts>;+ workspaceLatest?: Record<string, string>;}> {const { paging, category, workspaceGroup, withCounts } = opts;const rows = new Map(@@ -235,6 +238,7 @@ export class SessionService {const want = paging ? paging.offset + paging.limit : Infinity;const counts: SessionCategoryCounts = { active: 0, subagent: 0, schedule: 0, archived: 0 };const workspaceCounts: Record<string, SessionCategoryCounts> = {};+ const workspaceLatest: Record<string, string> = {};const matched: SessionRow[] = [];for (const row of sorted) {if (!withCounts && matched.length >= want) break;@@ -248,6 +252,8 @@ 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;}const wanted =(category === undefined || cat === category) &&@@ -255,7 +261,7 @@ export class SessionService {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 };+ 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 6e8be012..9beb8538 100644--- a/packages/server/test/session-index.test.ts+++ b/packages/server/test/session-index.test.ts@@ -361,6 +361,7 @@ describe("session-index", () => {expect(full.counts).toEqual({ active: 2, subagent: 1, schedule: 1, archived: 2 });expect((await list("")).counts).toBeUndefined();expect((await list("")).workspaceCounts).toBeUndefined();+ expect((await list("")).workspaceLatest).toBeUndefined();// The per-Workspace breakdown accompanies the totals and sums back to them: the// subagent Session sits alone in its path; every other row lives in its own@@ -466,6 +467,15 @@ describe("session-index", () => {);expect(ids(counted)).toHaveLength(2);expect(counted.counts?.active).toBe(6);+ // Each path's newest Session rides with the counts: what places a Workspace group the+ // sidebar has loaded no rows of. Keyed by the stored path — the client merges the+ // temporary ones — and whole-Agent under the group filter, like the counts.+ expect(counted.workspaceLatest).toEqual({+ [alpha]: "2026-07-03T09:02:00.000Z",+ [beta]: "2026-07-03T09:03:00.000Z",+ [`${agentDir}/workspaces/tmp-0123abcd`]: "2026-07-03T09:04:00.000Z",+ [`${agentDir}/workspaces/tmp-89abcdef`]: "2026-07-03T09:05:00.000Z",+ });// An empty group name is rejected, never silently unfiltered.expect((await api.get(`${base()}?workspaceGroup=`)).status).toBe(400);diff --git a/packages/web/e2e/workspace-groups-complete.spec.mjs b/packages/web/e2e/workspace-groups-complete.spec.mjsnew file mode 100644index 00000000..db6d1ee4--- /dev/null+++ b/packages/web/e2e/workspace-groups-complete.spec.mjs@@ -0,0 +1,111 @@+/**+ * Every Workspace that holds conversations is a sidebar group — not only the ones an+ * Agent's first page happened to touch.+ *+ * The list is fetched per Agent, ten newest conversations first, and the sidebar used to+ * form a Workspace group only around loaded rows: with dozens of Workspaces, every one+ * whose newest conversation was older than the Agent's ten newest simply never appeared.+ * The group list now comes from the server's per-Workspace counts (with each Workspace's+ * newest-Session stamp for ordering), and a group the first page never touched fetches its+ * own rows once its page of groups is on screen.+ *+ * Fifteen Workspaces on ONE Agent, three conversations each, seeded oldest Workspace+ * first: the Agent's ten newest rows reach four Workspaces, so eleven groups exist only+ * through the counts — spread over two pages of ten groups.+ *+ * 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 = "wscompleteuser";+const P = "password123";+const WORKSPACES = 15;+const PER_WORKSPACE = 3;+const GROUP_PAGE = 10; // SIDEBAR_GROUP_PAGE_SIZE++/** 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");++const name = (i) => `ws-${String(i).padStart(2, "0")}`;++test("every Workspace with conversations is a group, placed by recency across the group pages", async ({+ page,+}) => {+ // Real directories: a Workspace is validated by realpath and must exist.+ const root = await mkdtemp(join(tmpdir(), "penguin-wsall-"));+ const dirs = [];+ for (let i = 1; i <= WORKSPACES; i++) {+ const dir = join(root, name(i));+ await mkdir(dir);+ dirs.push(dir);+ }++ 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();++ // Oldest Workspace first, so the newest ten rows of the Agent's whole stream belong to+ // ws-15, ws-14, ws-13 and one row of ws-12: the other eleven Workspaces are known to the+ // sidebar through the counts alone.+ for (const dir of dirs) {+ for (let i = 0; i < PER_WORKSPACE; i++) {+ const res = await page.request.post(+ `${BASE}/api/projects/${projectId}/agents/default_agent/sessions`,+ { data: { workspace: dir } },+ );+ expect(res.ok(), `create in ${dir}: ${await res.text()}`).toBeTruthy();+ }+ }++ await page.setViewportSize({ width: 1280, height: 1600 });+ await page.goto(`${BASE}/chat`);+ const sidebar = page.getByRole("complementary");++ // Page 1 of groups: the ten newest Workspaces, including six the first page never+ // touched — each of those fetched its own rows once on screen.+ for (let i = WORKSPACES; i > WORKSPACES - GROUP_PAGE; i--) {+ await expect(sidebar.getByText(name(i), { exact: true })).toBeVisible();+ }+ await expect(groupRows(sidebar, name(6))).toHaveCount(PER_WORKSPACE);+ await expect(groupRows(sidebar, name(12))).toHaveCount(PER_WORKSPACE);+ await expect(groupRows(sidebar, name(15))).toHaveCount(PER_WORKSPACE);+ // Nothing is left to reveal in a group whose whole share is on screen.+ await expect(sidebar.getByRole("button", { name: /展开其余/ })).toHaveCount(0);+ await expect(sidebar.getByText(name(5), { exact: true })).toHaveCount(0);++ // The pager knows every group, loaded or not: two pages of ten.+ await expect(sidebar.getByLabel("第 1 页,共 2 页")).toBeVisible();+ await sidebar.getByRole("button", { name: "下一页分组" }).click();++ // Page 2: the five oldest Workspaces, by recency, each fetching its own rows on arrival.+ for (let i = 1; i <= WORKSPACES - GROUP_PAGE; i++) {+ await expect(sidebar.getByText(name(i), { exact: true })).toBeVisible();+ }+ await expect(groupRows(sidebar, name(1))).toHaveCount(PER_WORKSPACE);+ await expect(groupRows(sidebar, name(5))).toHaveCount(PER_WORKSPACE);+ await expect(sidebar.getByText(name(15), { exact: true })).toHaveCount(0);+ await expect(sidebar.getByRole("button", { name: /展开其余/ })).toHaveCount(0);+});diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsxindex f0a66924..15d2db1b 100644--- a/packages/web/src/components/layout/sidebar.tsx+++ b/packages/web/src/components/layout/sidebar.tsx@@ -51,7 +51,9 @@ import {SIDEBAR_PAGE_SIZE,TIME_FOLDERS_GROUP_KEY,aggregateWorkspaceCounts,+ aggregateWorkspaceLatest,clampGroupPage,+ completeWorkspaceGroups,groupPageCount,groupPageOf,groupPageSlice,@@ -336,6 +338,7 @@ export function Sidebar({byAgent,countsByAgent,workspaceCountsByAgent,+ workspaceLatestByAgent,isLoadedFor,hasMoreFor,loadMoreFor,@@ -500,18 +503,38 @@ export function Sidebar({setNavCollapsed(next);};- /** Workspace groups (workspace mode): computed from the flat list, temp directories merged last, plus the manually-added Workspaces as empty groups on top (newest registration first). */- const workspaceGroups = useMemo(- () => mergeRegisteredWorkspaces(groupSessionsByWorkspace(sessions), registeredWorkspaces),- [sessions, registeredWorkspaces],- );-/** Workspace-mode per-group exact server totals (folded from the per-Agent per-Workspace counts). */const workspaceGroupCounts = useMemo(() => aggregateWorkspaceCounts(workspaceCountsByAgent),[workspaceCountsByAgent],);+ /** Workspace-mode per-group newest-Session stamps (folded the same way): a group's recency before any of its rows are loaded. */+ const workspaceGroupLatest = useMemo(+ () => aggregateWorkspaceLatest(workspaceLatestByAgent),+ [workspaceLatestByAgent],+ );++ /**+ * Workspace groups (workspace mode): the loaded rows' groups, completed with every+ * Workspace the server's counts know (empty until their rows page in — the initial load+ * is each Agent's ten newest conversations, which touch only a few of dozens of+ * Workspaces), by recency with the temp group last, plus the manually-added Workspaces+ * as empty groups behind them (newest registration first).+ */+ const workspaceGroups = useMemo(+ () =>+ mergeRegisteredWorkspaces(+ completeWorkspaceGroups(+ groupSessionsByWorkspace(sessions),+ workspaceGroupCounts,+ workspaceGroupLatest,+ ),+ registeredWorkspaces,+ ),+ [sessions, workspaceGroupCounts, workspaceGroupLatest, registeredWorkspaces],+ );+// Pinned groups first within each mode, then the manual drag order within each pin// partition. Nothing dragged yet = an empty order = the automatic sort untouched// (recency for Workspace groups with the temp group last, the configured Agent order@@ -895,6 +918,13 @@ export function Sidebar({** 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.+ *+ * The ask is marked in flight like a "More" click (pendingLoads), for two reasons: a group+ * the counts know but no page has loaded rows of starts out empty, and its body must read+ * as loading rather than as having no conversations; and the marker is what keeps this+ * effect from asking twice — every landed page changes the group list and re-runs it, and+ * an in-flight pair is still unloaded, so a second request would start its cursor over and+ * the group would later skip a page.*/useEffect(() => {if (groupMode !== "workspace" || searching) return;@@ -908,7 +938,17 @@ export function Sidebar({...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);+ if (unloaded.length === 0) continue;+ const key = loadKey(group.key, "active");+ if (pendingLoads.has(key)) continue;+ setPendingLoads((prev) => new Set(prev).add(key));+ void loadMoreFor(unloaded, "active", group.key).finally(() => {+ setPendingLoads((prev) => {+ const next = new Set(prev);+ next.delete(key);+ return next;+ });+ });}}, [groupMode,@@ -918,6 +958,7 @@ export function Sidebar({workspaceGroupCounts,isLoadedFor,loadMoreFor,+ pendingLoads,]);/** Archive / unarchive: persists immediately and updates in place (fails silently; the next list refresh self-corrects). */@@ -1384,15 +1425,19 @@ export function Sidebar({);const empty = parts.active.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;return (<>{empty ? (- loading ? (+ loading || (awaitingRows && activePending) ? (// The same window the chat pane's skeleton covers: the Agent groups render as// soon as the Agents arrive, but the session pages are still being fetched —// "no Sessions yet" is not the honest answer until they land.<SkeletonList rows={2} />- ) : (+ ) : awaitingRows ? null : (<p className="px-2.5 py-1 text-xs text-gray-400 dark:text-gray-600">{S.chat.noSessions}</p>diff --git a/packages/web/src/lib/group-order.ts b/packages/web/src/lib/group-order.tsindex 355d3197..3cc687ae 100644--- a/packages/web/src/lib/group-order.ts+++ b/packages/web/src/lib/group-order.ts@@ -140,12 +140,12 @@ export function orderGroups<T>(* The rows' applyManualReorder moves the dropped partition's sequence to the FRONT of* the stored array, which is sound for Sessions because a partition is one group's own* list and the ids it displaces are read only within *other* partitions. That does not- * lift to the group axis: a Workspace group exists only once one of its Sessions has- * paged in, so the keys a group drop would displace are its own peers — not yet on- * screen, but ordered against the very groups being committed. Front-loading demoted- * every unloaded Workspace to the tail, and (because the two pin partitions share one- * array) it also flung a group the length of the sidebar the moment it was pinned or- * unpinned.+ * lift to the group axis: the Workspace sequence is only as complete as the last counts+ * fetch (a Workspace whose Sessions arrive later is absent until the next reload), so+ * the keys a group drop would displace can be peers not on screen, ordered against the+ * very groups being committed. Front-loading demoted every such Workspace to the tail,+ * and (because the two pin partitions share one array) it also flung a group the length+ * of the sidebar the moment it was pinned or unpinned.** So: materialise the rendered keys into the stored array where they already RENDER —* unlisted ones at the front, which is where applyManualOrder puts them — then move thediff --git a/packages/web/src/lib/session-grouping.ts b/packages/web/src/lib/session-grouping.tsindex 705404e8..20f1b15d 100644--- a/packages/web/src/lib/session-grouping.ts+++ b/packages/web/src/lib/session-grouping.ts@@ -252,6 +252,26 @@ export function latestConversation(sessions: readonly SessionInfo[]): SessionInfreturn best;}+/**+ * Folds the per-Agent per-Workspace-path newest-Session stamps+ * (SessionsResponse.workspaceLatest) into workspace-mode group keys: the newest across+ * Agents, and across every temporary path for the merged temp group. createdAt is uniform+ * ISO-8601 UTC, so the string maximum is the chronological one.+ */+export function aggregateWorkspaceLatest(+ byAgent: ReadonlyMap<string, Readonly<Record<string, string>>>,+): Map<string, string> {+ const out = new Map<string, string>();+ for (const byWorkspace of byAgent.values()) {+ for (const [workspace, createdAt] of Object.entries(byWorkspace)) {+ const key = workspaceGroupKey(workspace);+ const cur = out.get(key);+ if (cur === undefined || createdAt > cur) out.set(key, createdAt);+ }+ }+ return out;+}+export interface WorkspaceGroup<T = SessionInfo> {/** Stable group key: the Workspace path, or TEMP_WORKSPACE_GROUP_KEY for the merged temp group. */key: string;@@ -306,6 +326,56 @@ export function groupSessionsByWorkspace<T extends { workspace: string; createdAreturn groups;}+/**+ * Completes the session-derived grouping with every Workspace the server's counts know:+ * a group the loaded pages touched no row of is added EMPTY (its rows page in down its own+ * stream once it is on screen), and the named groups are re-sorted by recency — the newer+ * of the group's newest loaded row and the server's `latest` stamp — with the merged temp+ * group last, the order groupSessionsByWorkspace gives. Without this the group list was+ * only as complete as each Agent's first page: a Workspace whose newest conversation was+ * older than an Agent's ten newest never formed a group at all, which with dozens of+ * Workspaces holding hundreds of conversations each is most of them.+ *+ * A counted key with no rows left in any category (its last conversation was deleted+ * since the counts were taken) forms no group; a key already grouped keeps its loaded rows.+ */+export function completeWorkspaceGroups<T extends { createdAt: string }>(+ groups: readonly WorkspaceGroup<T>[],+ counts: ReadonlyMap<string, GroupCounts>,+ latest: ReadonlyMap<string, string>,+): WorkspaceGroup<T>[] {+ const out = [...groups];+ const existing = new Set(groups.map((g) => g.key));+ for (const [key, { totals }] of counts) {+ if (existing.has(key)) continue;+ if (!ALL_CATEGORIES.some((category) => totals[category] > 0)) continue;+ existing.add(key);+ const temp = key === TEMP_WORKSPACE_GROUP_KEY;+ out.push({+ key,+ label: temp ? "" : workspaceLabel(key),+ fullPath: temp ? null : key,+ temp,+ sessions: [],+ });+ }+ // A group's newest loaded row (groupSessionsByWorkspace sorts members newest first) or+ // the server's stamp, whichever is newer: a row added locally since the counts were+ // taken counts, and so does a stamp for rows not loaded.+ const recency = (g: WorkspaceGroup<T>): string => {+ const loaded = g.sessions[0]?.createdAt ?? "";+ const stamped = latest.get(g.key) ?? "";+ return loaded > stamped ? loaded : stamped;+ };+ out.sort((a, b) => {+ if (a.temp !== b.temp) return a.temp ? 1 : -1;+ const ra = recency(a);+ const rb = recency(b);+ return ra < rb ? 1 : ra > rb ? -1 : 0;+ });+ return out;+}+/*** The sidebar's time buckets, in render order: last day, last month, everything older.* Bucketing is on `lastActiveAt` — the same key the recency sort and each row's compactdiff --git a/packages/web/src/state/sessions.tsx b/packages/web/src/state/sessions.tsxindex efd8b7c5..c3e9d411 100644--- a/packages/web/src/state/sessions.tsx+++ b/packages/web/src/state/sessions.tsx@@ -57,6 +57,8 @@ 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>>>;+ /** agentId → each Workspace path's newest Session `createdAt` from the last list fetch: what places a workspace-mode group before any of its rows are loaded. */+ workspaceLatestByAgent: ReadonlyMap<string, Readonly<Record<string, string>>>;/*** 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@@ -173,6 +175,7 @@ interface SessionsStoreState {pageState: ReadonlyMap<string, PagePosition>;countsByAgent: ReadonlyMap<string, SessionCategoryCounts>;workspaceCountsByAgent: ReadonlyMap<string, Readonly<Record<string, SessionCategoryCounts>>>;+ workspaceLatestByAgent: ReadonlyMap<string, Readonly<Record<string, string>>>;loading: boolean;reload: () => Promise<void>;@@ -245,6 +248,7 @@ export function createSessionsStore() {pageState: new Map(),countsByAgent: new Map(),workspaceCountsByAgent: new Map(),+ workspaceLatestByAgent: new Map(),loading: true,reload: async () => {@@ -287,6 +291,7 @@ export function createSessionsStore() {scope,counts: res.counts,workspaceCounts: res.workspaceCounts,+ workspaceLatest: res.workspaceLatest,...splitPage(res.sessions, SIDEBAR_PAGE_SIZE),};}),@@ -307,6 +312,7 @@ export function createSessionsStore() {string,Readonly<Record<string, SessionCategoryCounts>>>();+ const nextWorkspaceLatest = new Map<string, Readonly<Record<string, string>>>();for (const r of results) {for (const p of r.pages) {nextPageState.set(pageKey(r.agentId, p.category, p.scope), {@@ -315,6 +321,7 @@ export function createSessionsStore() {});if (p.counts) nextCounts.set(r.agentId, p.counts);if (p.workspaceCounts) nextWorkspaceCounts.set(r.agentId, p.workspaceCounts);+ if (p.workspaceLatest) nextWorkspaceLatest.set(r.agentId, p.workspaceLatest);for (const s of p.items) {if (!seen.has(s.sessionId)) {seen.add(s.sessionId);@@ -328,6 +335,7 @@ export function createSessionsStore() {pageState: nextPageState,countsByAgent: nextCounts,workspaceCountsByAgent: nextWorkspaceCounts,+ workspaceLatestByAgent: nextWorkspaceLatest,});} finally {if (g === gen) set({ loading: false });@@ -674,6 +682,7 @@ export function SessionsProvider({ children }: { children: ReactNode }) {pageState: new Map(),countsByAgent: new Map(),workspaceCountsByAgent: new Map(),+ workspaceLatestByAgent: new Map(),// The pages were just cleared, so the list is loading from this instant — including// the window where the Agent set itself is still being refetched (a Project switch// empties it, which makes reload() below return without fetching or clearing the@@ -752,6 +761,7 @@ export function SessionsProvider({ children }: { children: ReactNode }) {byAgent,countsByAgent: state.countsByAgent,workspaceCountsByAgent: state.workspaceCountsByAgent,+ workspaceLatestByAgent: state.workspaceLatestByAgent,isLoadedFor,hasMoreFor,loading: state.loading,diff --git a/packages/web/test/session-grouping.test.ts b/packages/web/test/session-grouping.test.tsindex 89d438b8..bfedfff0 100644--- a/packages/web/test/session-grouping.test.ts+++ b/packages/web/test/session-grouping.test.ts@@ -18,6 +18,8 @@ import {TIME_BUCKETS,TIME_FOLDERS_GROUP_KEY,aggregateWorkspaceCounts,+ aggregateWorkspaceLatest,+ completeWorkspaceGroups,matchesSessionQuery,groupSessionsByTime,groupSessionsByWorkspace,@@ -483,3 +485,118 @@ describe("totalCategoryCounts", () => {});});});++describe("aggregateWorkspaceLatest (per-group newest-Session stamp)", () => {+ it("keeps the newest stamp per path across Agents, and the newest temporary path for the temp group", () => {+ const byAgent = new Map<string, Record<string, string>>([+ [+ "agent_a",+ {+ "/srv/alpha": "2026-07-03T09:00:00.000Z",+ [TEMP_A]: "2026-07-03T08:00:00.000Z",+ },+ ],+ [+ "agent_b",+ {+ "/srv/alpha": "2026-07-03T09:30:00.000Z",+ "/srv/beta": "2026-07-01T00:00:00.000Z",+ [TEMP_B]: "2026-07-03T08:30:00.000Z",+ },+ ],+ ]);+ const latest = aggregateWorkspaceLatest(byAgent);+ expect(latest.get("/srv/alpha")).toBe("2026-07-03T09:30:00.000Z");+ expect(latest.get("/srv/beta")).toBe("2026-07-01T00:00:00.000Z");+ expect(latest.get(TEMP_WORKSPACE_GROUP_KEY)).toBe("2026-07-03T08:30:00.000Z");+ expect(latest.size).toBe(3);+ expect(aggregateWorkspaceLatest(new Map()).size).toBe(0);+ });+});++describe("completeWorkspaceGroups (every counted Workspace is a group, placed by recency)", () => {+ const zero = { active: 0, subagent: 0, schedule: 0, archived: 0 };+ const counted = (totals: Partial<SessionCategoryCounts>) => ({+ totals: { ...zero, ...totals },+ agents: { active: [], subagent: [], schedule: [], archived: [] },+ });++ it("adds an empty group for a counted Workspace the loaded rows never touched, and orders every group by its newest stamp", () => {+ // Loaded: one Agent's first page reached only alpha (newest) and a temp workspace.+ const loaded = groupSessionsByWorkspace([+ session("/srv/alpha", "2026-07-03T09:00:00.000Z"),+ session(TEMP_A, "2026-07-02T12:00:00.000Z"),+ ]);+ const counts = new Map([+ ["/srv/alpha", counted({ active: 40 })],+ // Unloaded, newer than alpha's loaded row: the stamp places it first.+ ["/srv/beta", counted({ active: 300 })],+ // Unloaded, older: last among the named groups.+ ["/srv/gamma", counted({ active: 2, archived: 5 })],+ [TEMP_WORKSPACE_GROUP_KEY, counted({ active: 7 })],+ ]);+ const latest = new Map([+ ["/srv/alpha", "2026-07-03T09:00:00.000Z"],+ ["/srv/beta", "2026-07-03T10:00:00.000Z"],+ ["/srv/gamma", "2026-06-01T00:00:00.000Z"],+ [TEMP_WORKSPACE_GROUP_KEY, "2026-07-03T11:00:00.000Z"],+ ]);+ const groups = completeWorkspaceGroups(loaded, counts, latest);+ expect(groups.map((g) => g.key)).toEqual([+ "/srv/beta",+ "/srv/alpha",+ "/srv/gamma",+ TEMP_WORKSPACE_GROUP_KEY,+ ]);+ const beta = groups[0]!;+ expect(beta).toMatchObject({ label: "beta", fullPath: "/srv/beta", temp: false });+ expect(beta.sessions).toEqual([]);+ // Groups already formed keep their loaded rows.+ expect(groups[1]!.sessions).toHaveLength(1);+ // The temp group stays last however new its stamp is, and keeps its loaded row.+ expect(groups[3]!.sessions).toHaveLength(1);+ });++ it("places a group by its newest loaded row when that is newer than the stamp (a conversation added since the counts)", () => {+ const loaded = groupSessionsByWorkspace([+ session("/srv/alpha", "2026-07-03T12:00:00.000Z"),+ session("/srv/beta", "2026-07-03T09:00:00.000Z"),+ ]);+ const counts = new Map([+ ["/srv/alpha", counted({ active: 1 })],+ ["/srv/beta", counted({ active: 1 })],+ ]);+ // Stale stamps say beta is newer; alpha's loaded row is newer than both.+ const latest = new Map([+ ["/srv/alpha", "2026-07-01T00:00:00.000Z"],+ ["/srv/beta", "2026-07-02T00:00:00.000Z"],+ ]);+ expect(completeWorkspaceGroups(loaded, counts, latest).map((g) => g.key)).toEqual([+ "/srv/alpha",+ "/srv/beta",+ ]);+ });++ it("forms no group for a counted key with nothing left in any category, and none without counts", () => {+ const loaded = groupSessionsByWorkspace([session("/srv/alpha", "2026-07-03T09:00:00.000Z")]);+ const counts = new Map([+ ["/srv/alpha", counted({ active: 1 })],+ ["/srv/gone", counted({})],+ ]);+ expect(completeWorkspaceGroups(loaded, counts, new Map()).map((g) => g.key)).toEqual([+ "/srv/alpha",+ ]);+ expect(completeWorkspaceGroups(loaded, new Map(), new Map()).map((g) => g.key)).toEqual([+ "/srv/alpha",+ ]);+ expect(completeWorkspaceGroups([], new Map(), new Map())).toEqual([]);+ });++ it("forms the temp group from its counts alone, empty and last, when no temporary row is loaded", () => {+ const loaded = groupSessionsByWorkspace([session("/srv/alpha", "2026-07-03T09:00:00.000Z")]);+ const counts = new Map([[TEMP_WORKSPACE_GROUP_KEY, counted({ archived: 3 })]]);+ const groups = completeWorkspaceGroups(loaded, counts, new Map());+ expect(groups.map((g) => g.key)).toEqual(["/srv/alpha", TEMP_WORKSPACE_GROUP_KEY]);+ expect(groups[1]).toMatchObject({ label: "", fullPath: null, temp: true, sessions: [] });+ });+});