feat(workspaces): title recent-activity rows from a bounded preview
The activity column's disk-only rows had no title: the recent feed carried file metadata only, so every session outside a live instance rendered "(unnamed)". recentSessions() now projects a display title for the rows it returns — the latest `session_info` name and the first user message — from a 128 KiB head + 32 KiB tail of each session file, cached by (mtime, size). Entries are never parsed into session state: the read is bounded, opt-in, and only paid for the ≤limit rows the caller renders, so the daemon stays a router. The web client keeps the disk title as a fallback under the live state, and the B4 e2e scenario asserts session-first rows with their links and titles.
This commit is contained in:
1 parent
086cac8c8e
commit
17fcf931c0
11 files changed
+431
-30
No files matched your search
@@ -43,8 +43,10 @@ Adding bulk to this file is a mistake, not a contribution.
|
|||||||
|
|
||||||
1. **`docs/protocol.md` is the contract.** Any wire change lands with the daemon, the web client
|
1. **`docs/protocol.md` is the contract.** Any wire change lands with the daemon, the web client
|
||||||
and the pi2.nvim bridge in view; `fixtures/` are regenerated via `scripts/gen-expected.ts`.
|
and the pi2.nvim bridge in view; `fixtures/` are regenerated via `scripts/gen-expected.ts`.
|
||||||
2. **The daemon is not an agent runtime.** No `pi` spawning, no JSONL session parsing, no session
|
2. **The daemon is not an agent runtime.** No `pi` spawning, no session state, no entry parsing.
|
||||||
state. Snapshots and mutations are relayed to the plugin, which stays the single authority.
|
The one JSONL read is the recent feed's bounded display-title preview (`name` + first user
|
||||||
|
message, 128 KiB head + 32 KiB tail, cached); snapshots and mutations are relayed to the plugin,
|
||||||
|
which stays the single authority.
|
||||||
3. **`dist/` and `web/dist/` are build output** — gitignored, never committed. They ship inside
|
3. **`dist/` and `web/dist/` are build output** — gitignored, never committed. They ship inside
|
||||||
the npm tarball through `prepack` + the `files` allowlist.
|
the npm tarball through `prepack` + the `files` allowlist.
|
||||||
4. **Two lockfiles.** Root `pnpm-lock.yaml` and `web/pnpm-lock.yaml` are independent: use
|
4. **Two lockfiles.** Root `pnpm-lock.yaml` and `web/pnpm-lock.yaml` are independent: use
|
||||||
|
|||||||
+8
-3
@@ -171,10 +171,14 @@ default; `secondary` rows belong behind a “show hidden” toggle. Lookups by
|
|||||||
|
|
||||||
Recent session row (`GET /api/v1/sessions/recent?limit=`): a **disk projection**, not
|
Recent session row (`GET /api/v1/sessions/recent?limit=`): a **disk projection**, not
|
||||||
session state. The daemon scans each known workspace's session directory, reads only
|
session state. The daemon scans each known workspace's session directory, reads only
|
||||||
session headers (id, timestamp, cwd), and sorts by file mtime. It never parses
|
session headers (id, timestamp, cwd), and sorts by file mtime. For the rows it returns
|
||||||
entries, never spawns an instance and never claims ownership of a live session. The
|
(≤ `limit`) it also projects a bounded **display title** — the latest `session_info.name`
|
||||||
|
and the first user message — by reading at most 128 KiB from the start plus 32 KiB from
|
||||||
|
the end of each file, cached by (mtime, size); entries are never parsed into session
|
||||||
|
state. It never spawns an instance and never claims ownership of a live session. The
|
||||||
console layers live names/statuses over these rows from
|
console layers live names/statuses over these rows from
|
||||||
`GET /api/v1/workspaces/:id/sessions` when that workspace has a connected instance.
|
`GET /api/v1/workspaces/:id/sessions` when that workspace has a connected instance,
|
||||||
|
falling back to the disk title for history rows.
|
||||||
|
|
||||||
| Field | Notes |
|
| Field | Notes |
|
||||||
|---|---|
|
|---|---|
|
||||||
@@ -182,6 +186,7 @@ console layers live names/statuses over these rows from
|
|||||||
| `workspaceId`, `workspaceName` | owning workspace, resolved from the daemon's registry/discovery |
|
| `workspaceId`, `workspaceName` | owning workspace, resolved from the daemon's registry/discovery |
|
||||||
| `timestamp` | session start from the JSONL header (file-name fallback), epoch ms |
|
| `timestamp` | session start from the JSONL header (file-name fallback), epoch ms |
|
||||||
| `modified` | file mtime, epoch ms — the recency sort key |
|
| `modified` | file mtime, epoch ms — the recency sort key |
|
||||||
|
| `name?`, `firstMessage?` | bounded display-title projection: latest `session_info.name`, first user message (flattened, ≤80 chars). Both absent when the preview windows contain neither. |
|
||||||
|
|
||||||
The `limit` defaults to 20 and is clamped to 1–200. Rows are deduped by `sessionId`
|
The `limit` defaults to 20 and is clamped to 1–200. Rows are deduped by `sessionId`
|
||||||
(two encoded directories can resolve to the same cwd) and returned newest first.
|
(two encoded directories can resolve to the same cwd) and returned newest first.
|
||||||
|
|||||||
+46
-11
@@ -244,6 +244,12 @@ async function listWorkspaces() {
|
|||||||
return Array.isArray(list) ? list : (list.workspaces ?? []);
|
return Array.isArray(list) ? list : (list.workspaces ?? []);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function listRecentSessions(limit = 20) {
|
||||||
|
const body = await api("GET", `/api/v1/sessions/recent?limit=${limit}`);
|
||||||
|
const rows = body?.sessions ?? (Array.isArray(body) ? body : []);
|
||||||
|
return Array.isArray(rows) ? rows : [];
|
||||||
|
}
|
||||||
|
|
||||||
async function createSession(workspaceId) {
|
async function createSession(workspaceId) {
|
||||||
const result = await cmd("session.create", { workspaceId });
|
const result = await cmd("session.create", { workspaceId });
|
||||||
if (result.status !== 202 && result.status !== 200) {
|
if (result.status !== 202 && result.status !== 200) {
|
||||||
@@ -1263,24 +1269,53 @@ scenario("B4", "Workspaces: seeded rows/order/counts, path validation, UI add +
|
|||||||
observed: await statusLine.locator("a").evaluateAll((nodes) => nodes.map((node) => node.getAttribute("href"))),
|
observed: await statusLine.locator("a").evaluateAll((nodes) => nodes.map((node) => node.getAttribute("href"))),
|
||||||
});
|
});
|
||||||
|
|
||||||
// --- recent-activity column (new in v0.1.1) ---------------------------
|
// --- recent-activity column (session-first since 0.1.1) ---------------
|
||||||
const activity = page.locator('[data-testid="workspaces-activity"]');
|
const activity = page.locator('[data-testid="workspaces-activity"]');
|
||||||
ctx.check("recent-activity column is present", (await activity.count()) === 1, { observed: await activity.count() });
|
ctx.check("recent-activity column is present", (await activity.count()) === 1, { observed: await activity.count() });
|
||||||
const activityRows = activity.locator('[data-testid="workspace-activity-row"]');
|
const activityRows = activity.locator('[data-testid="workspace-activity-row"]');
|
||||||
const activityIds = await activityRows.evaluateAll((nodes) => nodes.map((node) => node.getAttribute("data-workspace-id")));
|
const activityIds = await activityRows.evaluateAll((nodes) => nodes.map((node) => node.getAttribute("data-session-id")));
|
||||||
|
const activityWorkspaces = await activityRows.evaluateAll((nodes) => nodes.map((node) => node.getAttribute("data-workspace-id")));
|
||||||
|
const activityTitles = await activityRows.evaluateAll((nodes) =>
|
||||||
|
nodes.map((node) => node.querySelector(".ws-activity__name")?.textContent ?? ""),
|
||||||
|
);
|
||||||
const activityHrefs = await activityRows.evaluateAll((nodes) => nodes.map((node) => node.getAttribute("href")));
|
const activityHrefs = await activityRows.evaluateAll((nodes) => nodes.map((node) => node.getAttribute("href")));
|
||||||
const expectedActivity = rowIds
|
const recentFeed = await listRecentSessions(20);
|
||||||
.map((id) => apiList.find((item) => item.workspaceId === id))
|
const recentById = new Map(recentFeed.map((row) => [row.sessionId, row]));
|
||||||
.filter((item) => item && typeof item.lastActiveAt === "number" && Number.isFinite(item.lastActiveAt))
|
const visibleWorkspaces = new Set(expectedOrder.map((item) => item.workspaceId));
|
||||||
.sort((a, b) => (b.lastActiveAt ?? 0) - (a.lastActiveAt ?? 0))
|
ctx.check("recent activity lists at most the newest 5 sessions", activityIds.length <= 5 && activityIds.length === activityWorkspaces.length, {
|
||||||
.slice(0, 5)
|
expected: "≤ 5",
|
||||||
.map((item) => item.workspaceId);
|
observed: activityIds.length,
|
||||||
ctx.checkValue("recent activity lists the newest 5 workspaces", activityIds, expectedActivity);
|
});
|
||||||
ctx.check(
|
ctx.check(
|
||||||
"activity rows link into /chat?workspace=<id>",
|
"activity rows belong to visible workspaces",
|
||||||
activityHrefs.every((href, index) => href === `/chat?workspace=${activityIds[index]}`),
|
activityWorkspaces.every((id) => visibleWorkspaces.has(id)),
|
||||||
|
{ observed: { activityIds, activityWorkspaces } },
|
||||||
|
);
|
||||||
|
ctx.check(
|
||||||
|
"activity rows link into /chat/<session>?workspace=<id>",
|
||||||
|
activityHrefs.every(
|
||||||
|
(href, index) => href === `/chat/${activityIds[index]}?workspace=${activityWorkspaces[index]}`,
|
||||||
|
),
|
||||||
{ observed: activityHrefs },
|
{ observed: activityHrefs },
|
||||||
);
|
);
|
||||||
|
// Regression guard for the workspace-page bug: a session the daemon (or a
|
||||||
|
// live instance) can title must not render as `(unnamed)`/`(未命名)`.
|
||||||
|
const placeholder = /unnamed|未命名/i;
|
||||||
|
ctx.check(
|
||||||
|
"recent-activity titles use session metadata when available",
|
||||||
|
activityIds.every((id, index) => {
|
||||||
|
const feed = recentById.get(id);
|
||||||
|
const titled = Boolean(feed?.name || feed?.firstMessage);
|
||||||
|
return !titled || !placeholder.test(activityTitles[index] ?? "");
|
||||||
|
}),
|
||||||
|
{
|
||||||
|
observed: activityIds.map((id, index) => ({
|
||||||
|
id,
|
||||||
|
feed: recentById.get(id)?.name ?? recentById.get(id)?.firstMessage ?? null,
|
||||||
|
title: activityTitles[index],
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
// --- empty path validation (no POST must happen) ----------------------
|
// --- empty path validation (no POST must happen) ----------------------
|
||||||
const requestsBefore = ctx.cmdRequests.length;
|
const requestsBefore = ctx.cmdRequests.length;
|
||||||
|
|||||||
+11
-3
@@ -321,9 +321,10 @@ export type WorkspaceVisibilityReason = "hidden" | "ghost" | "temp" | "outside-r
|
|||||||
/**
|
/**
|
||||||
* One disk-projected session row for the cross-workspace recent-activity feed.
|
* One disk-projected session row for the cross-workspace recent-activity feed.
|
||||||
*
|
*
|
||||||
* This is file metadata only (header id/timestamp + mtime); the daemon never
|
* This is file metadata plus an optional bounded display title (latest
|
||||||
* parses entries or owns session state (docs/protocol.md §3.1). Live names and
|
* `session_info` name / first user message); the daemon never parses entries
|
||||||
* statuses are layered on by the client through `/workspaces/:id/sessions`.
|
* into session state (docs/protocol.md §3.1). Live names and statuses are
|
||||||
|
* layered on by the client through `/workspaces/:id/sessions`.
|
||||||
*/
|
*/
|
||||||
export interface RecentSessionInfo {
|
export interface RecentSessionInfo {
|
||||||
sessionId: string;
|
sessionId: string;
|
||||||
@@ -336,6 +337,13 @@ export interface RecentSessionInfo {
|
|||||||
timestamp: number;
|
timestamp: number;
|
||||||
/** File mtime, epoch ms — the recency sort key. */
|
/** File mtime, epoch ms — the recency sort key. */
|
||||||
modified: number;
|
modified: number;
|
||||||
|
/**
|
||||||
|
* Latest `session_info.name` from the session file's bounded preview
|
||||||
|
* windows. Display metadata only; absent when the file has no name yet.
|
||||||
|
*/
|
||||||
|
name?: string;
|
||||||
|
/** First user message preview (flattened, ≤80 chars), when readable. */
|
||||||
|
firstMessage?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type DaemonCommandMethod =
|
export type DaemonCommandMethod =
|
||||||
|
|||||||
+207
-4
@@ -8,8 +8,12 @@
|
|||||||
* and the separator), so the authoritative cwd is the first JSONL line:
|
* and the separator), so the authoritative cwd is the first JSONL line:
|
||||||
* {"type":"session","version":3,"id":"…","timestamp":"…","cwd":"/abs/path"}
|
* {"type":"session","version":3,"id":"…","timestamp":"…","cwd":"/abs/path"}
|
||||||
*
|
*
|
||||||
* Scanning is header-only (one read of up to 64 KiB per directory) and cached
|
* Workspace/session *listing* is header-only (one read of up to 64 KiB per
|
||||||
* per directory by (mtime, file count). The rest of a session file is never read.
|
* directory) and cached per directory by (mtime, file count). `previewSession()`
|
||||||
|
* is the one opt-in exception: it reads a bounded head/tail window for a display
|
||||||
|
* title (latest `session_info.name` + first user message) so the recent-activity
|
||||||
|
* feed can label a session that has no live instance. It never parses entries
|
||||||
|
* into session state and is cached by (mtime, size).
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { closeSync, openSync, readdirSync, readSync, statSync } from "node:fs";
|
import { closeSync, openSync, readdirSync, readSync, statSync } from "node:fs";
|
||||||
@@ -19,6 +23,30 @@ import { sessionsRoot, workspaceIdForCwd } from "../core/paths.js";
|
|||||||
/** Maximum bytes read to obtain the first JSONL line. Headers are ~150 bytes. */
|
/** Maximum bytes read to obtain the first JSONL line. Headers are ~150 bytes. */
|
||||||
export const HEADER_READ_LIMIT = 64 * 1024;
|
export const HEADER_READ_LIMIT = 64 * 1024;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Head window for a display title. The first user message and the auto-title
|
||||||
|
* `session_info` line both land in the first ~50 KiB of a real session (the
|
||||||
|
* system-prompt message is the bulk of it), so 128 KiB leaves generous room.
|
||||||
|
*/
|
||||||
|
export const PREVIEW_HEAD_LIMIT = 128 * 1024;
|
||||||
|
|
||||||
|
/** Tail window where a later `session_info.name` (rename / re-title) may live. */
|
||||||
|
export const PREVIEW_TAIL_LIMIT = 32 * 1024;
|
||||||
|
|
||||||
|
/** `firstMessage` is flattened and cut exactly like pi2.nvim's `history.parse`. */
|
||||||
|
export const PREVIEW_MESSAGE_CHARS = 80;
|
||||||
|
|
||||||
|
/** Bound the preview cache; a recent feed touches a few dozen files at most. */
|
||||||
|
const PREVIEW_CACHE_LIMIT = 512;
|
||||||
|
|
||||||
|
/** Bounded display metadata read from a session file. Never session state. */
|
||||||
|
export interface SessionPreview {
|
||||||
|
/** Latest non-empty `session_info.name`, when one is inside the windows. */
|
||||||
|
name?: string;
|
||||||
|
/** First user message, flattened to one line and cut to 80 characters. */
|
||||||
|
firstMessage?: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface DiscoveredWorkspace {
|
export interface DiscoveredWorkspace {
|
||||||
workspaceId: string;
|
workspaceId: string;
|
||||||
/** Authoritative cwd from the session header (not decoded from `dir`). */
|
/** Authoritative cwd from the session header (not decoded from `dir`). */
|
||||||
@@ -65,6 +93,13 @@ export interface Discovery {
|
|||||||
discover(): DiscoveredWorkspace[];
|
discover(): DiscoveredWorkspace[];
|
||||||
/** Session files for a cwd, newest first (header-only, cheap). */
|
/** Session files for a cwd, newest first (header-only, cheap). */
|
||||||
listSessions(cwd: string, limit?: number): SessionFile[];
|
listSessions(cwd: string, limit?: number): SessionFile[];
|
||||||
|
/**
|
||||||
|
* Opt-in display title for one session file: the latest `session_info`
|
||||||
|
* name and the first user message. Reads at most `PREVIEW_HEAD_LIMIT` from
|
||||||
|
* the start plus `PREVIEW_TAIL_LIMIT` from the end, and caches by
|
||||||
|
* (mtime, size); `undefined` means the windows contain no usable title.
|
||||||
|
*/
|
||||||
|
previewSession(file: string, modified?: number): SessionPreview | undefined;
|
||||||
/** Drop one directory's cache entry, or the whole cache when omitted. */
|
/** Drop one directory's cache entry, or the whole cache when omitted. */
|
||||||
invalidate(dir?: string): void;
|
invalidate(dir?: string): void;
|
||||||
/** The encoded directory used for a cwd, when it has been discovered. */
|
/** The encoded directory used for a cwd, when it has been discovered. */
|
||||||
@@ -91,6 +126,12 @@ interface SessionHeader {
|
|||||||
timestamp?: string;
|
timestamp?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface PreviewCacheEntry {
|
||||||
|
mtimeMs: number;
|
||||||
|
size: number;
|
||||||
|
preview: SessionPreview | undefined;
|
||||||
|
}
|
||||||
|
|
||||||
export function isSessionDirName(name: string): boolean {
|
export function isSessionDirName(name: string): boolean {
|
||||||
return name.length > 4 && name.startsWith("--") && name.endsWith("--");
|
return name.length > 4 && name.startsWith("--") && name.endsWith("--");
|
||||||
}
|
}
|
||||||
@@ -99,6 +140,7 @@ class DiskDiscovery implements Discovery {
|
|||||||
private readonly root: string;
|
private readonly root: string;
|
||||||
private readonly logger: DiscoveryLogger | undefined;
|
private readonly logger: DiscoveryLogger | undefined;
|
||||||
private readonly cache = new Map<string, CacheEntry>();
|
private readonly cache = new Map<string, CacheEntry>();
|
||||||
|
private readonly previews = new Map<string, PreviewCacheEntry>();
|
||||||
|
|
||||||
constructor(options: DiscoveryOptions = {}) {
|
constructor(options: DiscoveryOptions = {}) {
|
||||||
this.root = options.root ?? sessionsRoot();
|
this.root = options.root ?? sessionsRoot();
|
||||||
@@ -156,9 +198,45 @@ class DiskDiscovery implements Discovery {
|
|||||||
return sessions;
|
return sessions;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
previewSession(file: string, modified?: number): SessionPreview | undefined {
|
||||||
|
let size: number;
|
||||||
|
let mtimeMs: number;
|
||||||
|
try {
|
||||||
|
const stat = statSync(file);
|
||||||
|
size = stat.size;
|
||||||
|
mtimeMs = modified ?? stat.mtimeMs;
|
||||||
|
} catch {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
const cached = this.previews.get(file);
|
||||||
|
if (cached !== undefined && cached.mtimeMs === mtimeMs && cached.size === size) {
|
||||||
|
// Refresh insertion order so the LRU cap drops genuinely cold files.
|
||||||
|
this.previews.delete(file);
|
||||||
|
this.previews.set(file, cached);
|
||||||
|
return cached.preview;
|
||||||
|
}
|
||||||
|
|
||||||
|
const preview = readSessionPreview(file, size);
|
||||||
|
this.previews.set(file, { mtimeMs, size, preview });
|
||||||
|
if (this.previews.size > PREVIEW_CACHE_LIMIT) {
|
||||||
|
const oldest = this.previews.keys().next().value;
|
||||||
|
if (oldest !== undefined) this.previews.delete(oldest);
|
||||||
|
}
|
||||||
|
return preview;
|
||||||
|
}
|
||||||
|
|
||||||
invalidate(dir?: string): void {
|
invalidate(dir?: string): void {
|
||||||
if (dir === undefined) this.cache.clear();
|
if (dir === undefined) {
|
||||||
else this.cache.delete(dir);
|
this.cache.clear();
|
||||||
|
this.previews.clear();
|
||||||
|
} else {
|
||||||
|
this.cache.delete(dir);
|
||||||
|
const prefix = dir.endsWith("/") ? dir : `${dir}/`;
|
||||||
|
for (const file of this.previews.keys()) {
|
||||||
|
if (file.startsWith(prefix)) this.previews.delete(file);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
dirForCwd(cwd: string): string | undefined {
|
dirForCwd(cwd: string): string | undefined {
|
||||||
@@ -304,6 +382,131 @@ function readSessionHeader(file: string): SessionHeader | undefined {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bounded display-title projection for one session file.
|
||||||
|
*
|
||||||
|
* Reads the head window (first user message + any early `session_info` name)
|
||||||
|
* and, for longer files, the tail window (a later rename / auto-title). Lines
|
||||||
|
* are JSON-decoded only when a cheap substring prefilter hits, so multi-MB
|
||||||
|
* message or tool-output lines are never decoded. A partial trailing line (the
|
||||||
|
* window cut a line in half) fails the decode and is ignored; the tail window
|
||||||
|
* also drops its leading partial line before parsing.
|
||||||
|
*/
|
||||||
|
function readSessionPreview(file: string, size: number): SessionPreview | undefined {
|
||||||
|
let fd: number | undefined;
|
||||||
|
try {
|
||||||
|
fd = openSync(file, "r");
|
||||||
|
const headBytes = Math.min(size, PREVIEW_HEAD_LIMIT);
|
||||||
|
if (headBytes <= 0) return undefined;
|
||||||
|
const head = Buffer.allocUnsafe(headBytes);
|
||||||
|
const headRead = readSync(fd, head, 0, headBytes, 0);
|
||||||
|
if (headRead <= 0) return undefined;
|
||||||
|
|
||||||
|
const found = parsePreviewWindow(head.toString("utf8", 0, headRead), true);
|
||||||
|
let name = found.name;
|
||||||
|
let firstMessage = found.firstMessage;
|
||||||
|
|
||||||
|
if (size > headRead) {
|
||||||
|
const tailBytes = Math.min(size - headRead, PREVIEW_TAIL_LIMIT);
|
||||||
|
if (tailBytes > 0) {
|
||||||
|
const tail = Buffer.allocUnsafe(tailBytes);
|
||||||
|
const tailRead = readSync(fd, tail, 0, tailBytes, size - tailBytes);
|
||||||
|
if (tailRead > 0) {
|
||||||
|
const text = tail.toString("utf8", 0, tailRead);
|
||||||
|
// The first line is probably a partial one: drop it.
|
||||||
|
const newline = text.indexOf("\n");
|
||||||
|
const tailFound = parsePreviewWindow(newline >= 0 ? text.slice(newline + 1) : "", false);
|
||||||
|
if (tailFound.name !== undefined) name = tailFound.name;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (name === undefined && firstMessage === undefined) return undefined;
|
||||||
|
return {
|
||||||
|
...(name === undefined ? {} : { name }),
|
||||||
|
...(firstMessage === undefined ? {} : { firstMessage }),
|
||||||
|
};
|
||||||
|
} catch {
|
||||||
|
return undefined;
|
||||||
|
} finally {
|
||||||
|
if (fd !== undefined) {
|
||||||
|
try {
|
||||||
|
closeSync(fd);
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Parse one bounded window of JSONL lines into a display title. */
|
||||||
|
function parsePreviewWindow(text: string, findFirstMessage: boolean): SessionPreview {
|
||||||
|
let name: string | undefined;
|
||||||
|
let firstMessage: string | undefined;
|
||||||
|
for (const rawLine of text.split("\n")) {
|
||||||
|
const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
|
||||||
|
if (line.length === 0) continue;
|
||||||
|
|
||||||
|
if (line.includes('"type":"session_info"')) {
|
||||||
|
const entry = parseJsonLine(line);
|
||||||
|
if (entry?.type === "session_info") {
|
||||||
|
const candidate = typeof entry.name === "string" ? entry.name.trim() : "";
|
||||||
|
if (candidate !== "") name = candidate;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (findFirstMessage && firstMessage === undefined && line.includes('"type":"message"')) {
|
||||||
|
const entry = parseJsonLine(line);
|
||||||
|
const message = recordField(entry, "message");
|
||||||
|
if (entry?.type === "message" && message?.role === "user") {
|
||||||
|
const messageText = userMessageText(message.content);
|
||||||
|
if (messageText !== "") firstMessage = messageText;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
...(name === undefined ? {} : { name }),
|
||||||
|
...(firstMessage === undefined ? {} : { firstMessage }),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseJsonLine(line: string): Record<string, unknown> | undefined {
|
||||||
|
try {
|
||||||
|
const parsed: unknown = JSON.parse(line);
|
||||||
|
return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)
|
||||||
|
? (parsed as Record<string, unknown>)
|
||||||
|
: undefined;
|
||||||
|
} catch {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function recordField(value: Record<string, unknown> | undefined, key: string): Record<string, unknown> | undefined {
|
||||||
|
const field = value?.[key];
|
||||||
|
return field !== null && typeof field === "object" && !Array.isArray(field)
|
||||||
|
? (field as Record<string, unknown>)
|
||||||
|
: undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** First text part of a pi user message, flattened and cut for a row label. */
|
||||||
|
function userMessageText(content: unknown): string {
|
||||||
|
let text = "";
|
||||||
|
if (typeof content === "string") {
|
||||||
|
text = content;
|
||||||
|
} else if (Array.isArray(content)) {
|
||||||
|
for (const part of content) {
|
||||||
|
if (part !== null && typeof part === "object" && (part as { type?: unknown }).type === "text") {
|
||||||
|
const value = (part as { text?: unknown }).text;
|
||||||
|
if (typeof value === "string") {
|
||||||
|
text = value;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return text.replace(/\s+/g, " ").trim().slice(0, PREVIEW_MESSAGE_CHARS);
|
||||||
|
}
|
||||||
|
|
||||||
/** `<YYYY-MM-DDTHH-MM-SS-mmmZ>_<id>.jsonl` → `{ id, timestamp }`. */
|
/** `<YYYY-MM-DDTHH-MM-SS-mmmZ>_<id>.jsonl` → `{ id, timestamp }`. */
|
||||||
export function parseSessionFileName(file: string): { id: string; timestamp: number } {
|
export function parseSessionFileName(file: string): { id: string; timestamp: number } {
|
||||||
const name = basename(file).replace(/\.jsonl$/, "");
|
const name = basename(file).replace(/\.jsonl$/, "");
|
||||||
|
|||||||
+10
-1
@@ -266,6 +266,7 @@ class WorkspaceStore implements WorkspaceStoreHandle {
|
|||||||
* stays bounded even on a workspace with a long history. Rows are deduped by
|
* stays bounded even on a workspace with a long history. Rows are deduped by
|
||||||
* session id (two encoded directories can resolve to the same cwd) and sorted
|
* session id (two encoded directories can resolve to the same cwd) and sorted
|
||||||
* by file mtime, then header timestamp, then id for a deterministic order.
|
* by file mtime, then header timestamp, then id for a deterministic order.
|
||||||
|
* Only the returned rows get a bounded display-title preview.
|
||||||
*/
|
*/
|
||||||
recentSessions(limit = 20): RecentSessionInfo[] {
|
recentSessions(limit = 20): RecentSessionInfo[] {
|
||||||
const capped = clampLimit(limit);
|
const capped = clampLimit(limit);
|
||||||
@@ -293,7 +294,15 @@ class WorkspaceStore implements WorkspaceStoreHandle {
|
|||||||
b.timestamp - a.timestamp ||
|
b.timestamp - a.timestamp ||
|
||||||
a.sessionId.localeCompare(b.sessionId),
|
a.sessionId.localeCompare(b.sessionId),
|
||||||
);
|
);
|
||||||
return rows.slice(0, capped);
|
const selected = rows.slice(0, capped);
|
||||||
|
// Enrich only the rows the caller will render: previews are bounded but
|
||||||
|
// per-file reads, so never pay for candidates that are sliced away.
|
||||||
|
for (const row of selected) {
|
||||||
|
const preview = this.discovery.previewSession(row.sessionFile, row.modified);
|
||||||
|
if (preview?.name !== undefined) row.name = preview.name;
|
||||||
|
if (preview?.firstMessage !== undefined) row.firstMessage = preview.firstMessage;
|
||||||
|
}
|
||||||
|
return selected;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ------------------------------------------------------------------
|
// ------------------------------------------------------------------
|
||||||
|
|||||||
@@ -267,4 +267,83 @@ describe("workspace disk discovery", () => {
|
|||||||
discovery.invalidate();
|
discovery.invalidate();
|
||||||
expect(discovery.discover()).toEqual([]);
|
expect(discovery.discover()).toEqual([]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("display-title preview", () => {
|
||||||
|
function titleFile(body: string): { dir: string; file: string } {
|
||||||
|
const dir = writeSessionDir(root, encodedDirName(sandbox), [
|
||||||
|
{ name: "2026-10-10T06-40-33-032Z_title.jsonl", cwd: sandbox, id: "title", body },
|
||||||
|
]);
|
||||||
|
return { dir, file: join(dir, "2026-10-10T06-40-33-032Z_title.jsonl") };
|
||||||
|
}
|
||||||
|
|
||||||
|
it("prefers the latest session_info name and falls back to the first user message", () => {
|
||||||
|
const { file } = titleFile(
|
||||||
|
[
|
||||||
|
JSON.stringify({ type: "session_info", name: "First name" }),
|
||||||
|
JSON.stringify({
|
||||||
|
type: "message",
|
||||||
|
message: { role: "user", content: [{ type: "text", text: "hello\n world from me" }] },
|
||||||
|
}),
|
||||||
|
JSON.stringify({ type: "session_info", name: "Renamed session" }),
|
||||||
|
].join("\n") + "\n",
|
||||||
|
);
|
||||||
|
|
||||||
|
const discovery = createDiscovery({ root });
|
||||||
|
// Listing stays header-only: no preview work on the hot path.
|
||||||
|
expect(discovery.listSessions(sandbox)[0]?.firstMessage).toBeUndefined();
|
||||||
|
expect(discovery.previewSession(file)).toEqual({
|
||||||
|
name: "Renamed session",
|
||||||
|
firstMessage: "hello world from me",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("supports a plain-string user message and ignores assistant turns", () => {
|
||||||
|
const { file } = titleFile(
|
||||||
|
[
|
||||||
|
JSON.stringify({ type: "message", message: { role: "assistant", content: "not me" } }),
|
||||||
|
JSON.stringify({ type: "message", message: { role: "user", content: "plain string prompt" } }),
|
||||||
|
].join("\n") + "\n",
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(createDiscovery({ root }).previewSession(file)).toEqual({ firstMessage: "plain string prompt" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("finds a name written past the head window in the tail window", () => {
|
||||||
|
const filler = `{"type":"note","data":"${"x".repeat(200 * 1024)}"}`;
|
||||||
|
const { file } = titleFile(
|
||||||
|
[
|
||||||
|
JSON.stringify({ type: "message", message: { role: "user", content: "start here" } }),
|
||||||
|
filler,
|
||||||
|
JSON.stringify({ type: "session_info", name: "Late name" }),
|
||||||
|
].join("\n") + "\n",
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(createDiscovery({ root }).previewSession(file)).toEqual({
|
||||||
|
name: "Late name",
|
||||||
|
firstMessage: "start here",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("caches by (mtime, size) and refreshes on invalidate()", () => {
|
||||||
|
const header = `${sessionHeader(sandbox, "title")}\n`;
|
||||||
|
const { file } = titleFile(`${JSON.stringify({ type: "session_info", name: "Cached" })}\n`);
|
||||||
|
const modified = statSync(file).mtimeMs;
|
||||||
|
const discovery = createDiscovery({ root });
|
||||||
|
expect(discovery.previewSession(file, modified)).toEqual({ name: "Cached" });
|
||||||
|
|
||||||
|
// Same size, deliberately reused recorded mtime: a cache hit.
|
||||||
|
writeFileSync(file, `${header}${JSON.stringify({ type: "session_info", name: "Edited" })}\n`);
|
||||||
|
expect(discovery.previewSession(file, modified)).toEqual({ name: "Cached" });
|
||||||
|
|
||||||
|
discovery.invalidate();
|
||||||
|
expect(discovery.previewSession(file, modified)).toEqual({ name: "Edited" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns undefined for a file with no readable title", () => {
|
||||||
|
const { file } = titleFile("garbage that is not json\n");
|
||||||
|
const discovery = createDiscovery({ root });
|
||||||
|
expect(discovery.previewSession(file)).toBeUndefined();
|
||||||
|
expect(discovery.previewSession(join(sandbox, "missing.jsonl"))).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -156,6 +156,9 @@ describe("workspace store", () => {
|
|||||||
timestamp: Date.parse("2026-10-13T06:40:33.032Z"),
|
timestamp: Date.parse("2026-10-13T06:40:33.032Z"),
|
||||||
modified: Date.parse("2026-10-13T06:40:33.032Z"),
|
modified: Date.parse("2026-10-13T06:40:33.032Z"),
|
||||||
sessionFile: expect.stringContaining("g1"),
|
sessionFile: expect.stringContaining("g1"),
|
||||||
|
// The helper writes a user message "hi": the disk preview labels
|
||||||
|
// the row that has no live instance.
|
||||||
|
firstMessage: "hi",
|
||||||
});
|
});
|
||||||
// The default (no limit) still returns every discovered session, and an
|
// The default (no limit) still returns every discovered session, and an
|
||||||
// out-of-range limit is clamped instead of exploding the header scan.
|
// out-of-range limit is clamped instead of exploding the header scan.
|
||||||
|
|||||||
@@ -55,11 +55,17 @@ type Phrases = { unnamed: string; subagentUnnamed: string };
|
|||||||
|
|
||||||
function ActivityRow({ session, phrases }: { session: RecentSessionRow; phrases: Phrases }) {
|
function ActivityRow({ session, phrases }: { session: RecentSessionRow; phrases: Phrases }) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
// A disk-only row has no live state; the session title contract then falls
|
// A live row carries the authoritative name/first message. A disk-only row
|
||||||
// back to `(unnamed)` (never an id), and the dot is the hollow "exited".
|
// gets the daemon's bounded preview (latest `session_info` name → first user
|
||||||
const title = session.state
|
// message); only a session with neither falls back to `(unnamed)`. Merge the
|
||||||
? sessionTitle(session.state, phrases)
|
// two so a sparse live row still keeps the disk title.
|
||||||
: { text: phrases.unnamed, provisional: true, spinner: false };
|
const title = sessionTitle(
|
||||||
|
{
|
||||||
|
name: session.state?.name || session.name,
|
||||||
|
firstMessage: session.state?.firstMessage || session.firstMessage,
|
||||||
|
},
|
||||||
|
phrases,
|
||||||
|
);
|
||||||
const dot = session.state ? sessionDot(session.state) : { status: "exited" as const };
|
const dot = session.state ? sessionDot(session.state) : { status: "exited" as const };
|
||||||
const label = session.state ? t(`state.${sessionStatusKey(session.state)}`) : t("state.exited");
|
const label = session.state ? t(`state.${sessionStatusKey(session.state)}`) : t("state.exited");
|
||||||
|
|
||||||
|
|||||||
@@ -20,6 +20,10 @@ export interface RecentSessionRow {
|
|||||||
ts: number;
|
ts: number;
|
||||||
/** Full state when a live instance answered for the workspace; null for disk-only rows. */
|
/** Full state when a live instance answered for the workspace; null for disk-only rows. */
|
||||||
state: SessionState | null;
|
state: SessionState | null;
|
||||||
|
/** Disk title: latest `session_info` name in the file, when the daemon saw one. */
|
||||||
|
name?: string;
|
||||||
|
/** Disk title fallback: the first user message (≤80 chars). */
|
||||||
|
firstMessage?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
function rec(value: unknown): Record<string, unknown> | undefined {
|
function rec(value: unknown): Record<string, unknown> | undefined {
|
||||||
@@ -47,6 +51,8 @@ export function normalizeRecentSessions(payload: unknown): RecentSessionInfo[] {
|
|||||||
const sessionId = str(row?.sessionId);
|
const sessionId = str(row?.sessionId);
|
||||||
const workspaceId = str(row?.workspaceId);
|
const workspaceId = str(row?.workspaceId);
|
||||||
if (!row || !sessionId || !workspaceId) continue;
|
if (!row || !sessionId || !workspaceId) continue;
|
||||||
|
const name = str(row.name);
|
||||||
|
const firstMessage = str(row.firstMessage);
|
||||||
rows.push({
|
rows.push({
|
||||||
sessionId,
|
sessionId,
|
||||||
workspaceId,
|
workspaceId,
|
||||||
@@ -55,6 +61,8 @@ export function normalizeRecentSessions(payload: unknown): RecentSessionInfo[] {
|
|||||||
sessionFile: str(row.sessionFile) ?? "",
|
sessionFile: str(row.sessionFile) ?? "",
|
||||||
timestamp: num(row.timestamp) ?? 0,
|
timestamp: num(row.timestamp) ?? 0,
|
||||||
modified: num(row.modified) ?? 0,
|
modified: num(row.modified) ?? 0,
|
||||||
|
...(name === undefined ? {} : { name }),
|
||||||
|
...(firstMessage === undefined ? {} : { firstMessage }),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
return rows;
|
return rows;
|
||||||
@@ -65,7 +73,9 @@ export function normalizeRecentSessions(payload: unknown): RecentSessionInfo[] {
|
|||||||
*
|
*
|
||||||
* Disk rows are the base (they exist after a daemon restart, before any
|
* Disk rows are the base (they exist after a daemon restart, before any
|
||||||
* workspace is spawned). A live row with the same id replaces the metadata:
|
* workspace is spawned). A live row with the same id replaces the metadata:
|
||||||
* it carries the authoritative name/first message/status. Sub-sessions are
|
* it carries the authoritative name/first message/status. Disk rows keep the
|
||||||
|
* daemon's bounded display preview (`name`/`firstMessage`) so a history row in
|
||||||
|
* a workspace with no running instance still renders a title. Sub-sessions are
|
||||||
* dropped — the design's activity column is a list of workspace roots.
|
* dropped — the design's activity column is a list of workspace roots.
|
||||||
*/
|
*/
|
||||||
export function mergeRecentSessions(
|
export function mergeRecentSessions(
|
||||||
@@ -105,6 +115,8 @@ export function mergeRecentSessions(
|
|||||||
workspaceName: nameById.get(workspaceId) ?? entry.disk?.workspaceName ?? "",
|
workspaceName: nameById.get(workspaceId) ?? entry.disk?.workspaceName ?? "",
|
||||||
ts,
|
ts,
|
||||||
state: entry.live ?? null,
|
state: entry.live ?? null,
|
||||||
|
...(entry.disk?.name === undefined ? {} : { name: entry.disk.name }),
|
||||||
|
...(entry.disk?.firstMessage === undefined ? {} : { firstMessage: entry.disk.firstMessage }),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
rows.sort((a, b) => b.ts - a.ts || a.sessionId.localeCompare(b.sessionId));
|
rows.sort((a, b) => b.ts - a.ts || a.sessionId.localeCompare(b.sessionId));
|
||||||
|
|||||||
@@ -275,6 +275,45 @@ describe("WorkspacesPage", () => {
|
|||||||
expect(row?.querySelector(".dot")).toHaveClass("dot--busy");
|
expect(row?.querySelector(".dot")).toHaveClass("dot--busy");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("titles disk-only rows from the daemon's bounded display preview", async () => {
|
||||||
|
const items = [
|
||||||
|
workspace({ workspaceId: "ws-a", cwd: "/work/a", name: "Alpha" }),
|
||||||
|
workspace({ workspaceId: "ws-b", cwd: "/work/b", name: "Bravo" }),
|
||||||
|
];
|
||||||
|
mockApi([
|
||||||
|
{ path: "/api/v1/info", handler: () => ({ body: infoBody }) },
|
||||||
|
{ path: "/api/v1/workspaces", handler: () => ({ body: items }) },
|
||||||
|
recentRoute([
|
||||||
|
diskSession({
|
||||||
|
sessionId: "s-name",
|
||||||
|
workspaceId: "ws-a",
|
||||||
|
workspaceName: "Alpha",
|
||||||
|
modified: 2_000,
|
||||||
|
name: "Renamed session",
|
||||||
|
}),
|
||||||
|
diskSession({
|
||||||
|
sessionId: "s-msg",
|
||||||
|
workspaceId: "ws-b",
|
||||||
|
workspaceName: "Bravo",
|
||||||
|
modified: 1_000,
|
||||||
|
firstMessage: "Please fix the recent list",
|
||||||
|
}),
|
||||||
|
]),
|
||||||
|
]);
|
||||||
|
|
||||||
|
await renderPage(routes(), "/workspaces", { paired: true });
|
||||||
|
await waitForCards(2);
|
||||||
|
|
||||||
|
const activity = screen.getByTestId("workspaces-activity");
|
||||||
|
expect(await within(activity).findByText("Renamed session")).toBeInTheDocument();
|
||||||
|
expect(within(activity).getByText("Please fix the recent list")).toBeInTheDocument();
|
||||||
|
// Neither row has a live instance; the title is data, not `(unnamed)`.
|
||||||
|
const rows = within(activity).getAllByTestId("workspace-activity-row");
|
||||||
|
expect(rows[0]?.querySelector(".ws-activity__name")).toHaveTextContent("Renamed session");
|
||||||
|
expect(rows[1]?.querySelector(".ws-activity__name")).toHaveTextContent("Please fix the recent list");
|
||||||
|
expect(within(activity).queryByText("(unnamed)")).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
it("opens the new-workspace dialog from the empty state", async () => {
|
it("opens the new-workspace dialog from the empty state", async () => {
|
||||||
const fetchMock = mockApi([
|
const fetchMock = mockApi([
|
||||||
{ path: "/api/v1/info", handler: () => ({ body: infoBody }) },
|
{ path: "/api/v1/info", handler: () => ({ body: infoBody }) },
|
||||||
|
|||||||
Reference in new issue
Block a user