feat: session-scoped entries query, session title tree and message stream updates

This commit is contained in:
yuez committed 2026-10-27 17:30:28 +08:00
1 parent bef8a35632
commit e910e75849
37 files changed
+1409 -75

No files matched your search

+5
View File
@@ -114,6 +114,11 @@ pnpm dev # daemon on 127.0.0.1:7676 (tsx watch)
pnpm --dir web dev # vite dev server on :5173, proxying /api and /ws to the daemon pnpm --dir web dev # vite dev server on :5173, proxying /api and /ws to the daemon
``` ```
The dev proxy presents the daemon's own `Origin`, so the :5173 server needs no `PI2_ORIGINS`
(the daemon's allowlist is derived from its port). Sign in to :5173 once by opening
`http://localhost:5173/#t=<token>` with the fragment from `pnpm exec tsx src/cli/pi2.ts open --print`;
`localStorage` is per origin, so the :7676 session does not carry over.
`pnpm build` → `dist/`, `pnpm build:web` → `web/dist/`. The published tarball ships both, so `pnpm build` → `dist/`, `pnpm build:web` → `web/dist/`. The published tarball ships both, so
`pi2 daemon` serves the web console from its own package with no extra step. `pi2 daemon` serves the web console from its own package with no extra step.
+25 -2
View File
@@ -63,6 +63,8 @@ The plugin dials the daemon (`<runtime>/d.sock`), sends `hello` first.
{"v":1,"type":"sub.unsubscribe","sessionId":"s1"} {"v":1,"type":"sub.unsubscribe","sessionId":"s1"}
{"v":1,"type":"instance.shutdown","payload":{"mode":"drain"}} {"v":1,"type":"instance.shutdown","payload":{"mode":"drain"}}
{"v":1,"type":"workspace.query","id":"req-2","payload":{"kind":"sessions"}} {"v":1,"type":"workspace.query","id":"req-2","payload":{"kind":"sessions"}}
// a session-scoped read keeps the sid on the envelope (see §3.1 entries)
{"v":1,"type":"workspace.query","id":"req-3","sessionId":"s1","payload":{"kind":"entries","limit":50}}
``` ```
Plugin obligations: Plugin obligations:
@@ -83,7 +85,7 @@ Plugin obligations:
| `GET /api/v1/health` | `{ok, items:[{name, ok, detail}]}` | | `GET /api/v1/health` | `{ok, items:[{name, ok, detail}]}` |
| `GET /api/v1/workspaces` | `WorkspaceInfo[]` (registry + disk index + instance state) | | `GET /api/v1/workspaces` | `WorkspaceInfo[]` (registry + disk index + instance state) |
| `GET /api/v1/workspaces/:id/sessions` | relayed `workspace.query{kind:"sessions"}` (row fields below) | | `GET /api/v1/workspaces/:id/sessions` | relayed `workspace.query{kind:"sessions"}` (row fields below) |
| `GET /api/v1/sessions/:sid/entries?before=&limit=` | relayed; plugin paginates | | `GET /api/v1/sessions/:sid/entries?before=&limit=&workspaceId=&sessionFile=` | relayed `workspace.query{kind:"entries"}`; plugin paginates |
| `GET /api/v1/attention?workspaceId=` | pending attention for one workspace | | `GET /api/v1/attention?workspaceId=` | pending attention for one workspace |
| `GET /api/v1/devices` | paired devices (daemon-owned; `{id, name, kind, createdAt, lastSeenAt, revokedAt}`) | | `GET /api/v1/devices` | paired devices (daemon-owned; `{id, name, kind, createdAt, lastSeenAt, revokedAt}`) |
| `POST /api/v1/pair` | **authenticated**; mints `{code, url, expiresAt, nonce, qr, bases}` | | `POST /api/v1/pair` | **authenticated**; mints `{code, url, expiresAt, nonce, qr, bases}` |
@@ -93,6 +95,14 @@ Plugin obligations:
| `GET /api/v1/resources` | instances, sessions, RSS totals for the soft-limit notice | | `GET /api/v1/resources` | instances, sessions, RSS totals for the soft-limit notice |
| `GET /api/v1/diagnostics` | connections, event rates, slow queries, instance table | | `GET /api/v1/diagnostics` | connections, event rates, slow queries, instance table |
The entries read is the only query that is *about a session*. `workspaceId` from the
caller routes it (a disk-only row has no live owner); the `sid` always travels on the
record envelope, so the plugin resolves the session — and its file — from its own
registry. `sessionFile` is an optional fallback for a session the receiving instance
does not know. A session that exists but has no JSONL yet (`pi` creates the file with
the first entry) answers an **empty page** (`{entries:[], cursor:{hasMore:false}}`),
never an error: a new session has no history to fail on.
Workspace row (`GET /api/v1/workspaces`) — registry entry ∪ disk discovery ∪ live instance state. Every known workspace is returned; rows are never filtered, so `/workspace/<workspaceId>` deep links always resolve: Workspace row (`GET /api/v1/workspaces`) — registry entry ∪ disk discovery ∪ live instance state. Every known workspace is returned; rows are never filtered, so `/workspace/<workspaceId>` deep links always resolve:
| Field | Notes | | Field | Notes |
@@ -125,7 +135,8 @@ Session row (`GET /api/v1/workspaces/:id/sessions`) — a subset of `SessionStat
| Field | Notes | | Field | Notes |
|---|---| |---|---|
| `sessionId`, `sessionFile?`, `name?`, `cwd?`, `timestamp?`, `modified?`, `firstMessage?` | identity + disk projection | | `sessionId`, `sessionFile?`, `name?`, `cwd?`, `timestamp?`, `modified?`, `firstMessage?` | identity + disk projection |
| `tab?`, `live?` | live projection | | `tab?` | live projection of `Session.attached_tab`; present ⇒ this row is an nvim tab |
| `live?` | live projection: the session's `pi --mode rpc` process runs (a detached sub-session is live without a `tab`) |
| `status?` | live status when `live` (`busy`, `compacting`, `idle`, `exited`); otherwise the child's manifest status (`dormant`, `done`, `error`, `interrupted`, `exited`). Absent on a non-live root. | | `status?` | live status when `live` (`busy`, `compacting`, `idle`, `exited`); otherwise the child's manifest status (`dormant`, `done`, `error`, `interrupted`, `exited`). Absent on a non-live root. |
| `model?`, `thinking?` | per-session model pin; the child's manifest thinking level | | `model?`, `thinking?` | per-session model pin; the child's manifest thinking level |
| `visible: boolean` | always present; the plugin's `:PiSessions` visibility decision | | `visible: boolean` | always present; the plugin's `:PiSessions` visibility decision |
@@ -133,6 +144,17 @@ Session row (`GET /api/v1/workspaces/:id/sessions`) — a subset of `SessionStat
| `task?`, `agentSpawned?`, `reported?` | sub-session rows only, carried through from the spawn request | | `task?`, `agentSpawned?`, `reported?` | sub-session rows only, carried through from the spawn request |
| `createdAt?`, `lastActiveAt?` | epoch ms; ordering/aging hints, never required | | `createdAt?`, `lastActiveAt?` | epoch ms; ordering/aging hints, never required |
The list is a union of every session JSONL the workspace has on disk and its live
sessions, so a client must not assume every row is an nvim tab. A row carrying
`tab` is a tab; a tab-less root row is *history* — it has no live owner, and a
command routed to it answers `E_SESSION_NOT_FOUND`. A client that mirrors the
nvim session list renders the tab-backed component: the rows with a `tab` plus
every row linked to them through `parentId` in either direction (their
sub-sessions, and the parent row when a tab is in a child view). That is exactly
`:PiSessions` (`Sessions.list()` plus children); pi2 web applies this filter in
`web/src/features/chat/session-state.ts` (`tabSessionRows`). A history row is a
`session.resume` target, never a prompt target.
Sub-session rows sit in the same flat list as their parent: build the tree from `parentId` Sub-session rows sit in the same flat list as their parent: build the tree from `parentId`
(an unknown `parentId`, or one whose row was pruned, promotes the row to a root so a row is (an unknown `parentId`, or one whose row was pruned, promotes the row to a root so a row is
never lost). `status` of a non-live child is one of `dormant|done|error|interrupted|exited`; never lost). `status` of a non-live child is one of `dormant|done|error|interrupted|exited`;
@@ -204,6 +226,7 @@ interface SessionState {
parentId?: string | null; // null = root (client-side only; the plugin omits the field) parentId?: string | null; // null = root (client-side only; the plugin omits the field)
visible?: boolean; // plugin `:PiSessions` visibility decision visible?: boolean; // plugin `:PiSessions` visibility decision
task?: string; // subagent task description from the spawn request task?: string; // subagent task description from the spawn request
firstMessage?: string | null; // first user message of the session file (provisional title)
} }
type Block = type Block =
+8 -7
View File
@@ -287,15 +287,16 @@ export function createApp(deps: AppDeps): Hono<Env> {
if (before !== undefined) params.before = before; if (before !== undefined) params.before = before;
const limit = Number(c.req.query("limit")); const limit = Number(c.req.query("limit"));
if (Number.isFinite(limit) && limit > 0) params.limit = Math.min(500, Math.floor(limit)); if (Number.isFinite(limit) && limit > 0) params.limit = Math.min(500, Math.floor(limit));
const workspaceId = c.req.query("workspaceId");
const sessionFile = c.req.query("sessionFile"); const sessionFile = c.req.query("sessionFile");
if (sessionFile) params.sessionFile = sessionFile; if (sessionFile) params.sessionFile = sessionFile;
const ack = workspaceId // `workspaceId` only routes the read (a disk-only row has no live owner);
? await router.relayWorkspaceQuery(workspaceId, "entries", params) // the sid still rides along so the plugin can answer from its registry.
: await router.relaySessionQuery(c.req.param("sid"), "workspace.query", { const ack = await router.relaySessionQuery(
...params, c.req.param("sid"),
kind: "entries", "workspace.query",
}); { ...params, kind: "entries" },
c.req.query("workspaceId"),
);
return json(200, ack); return json(200, ack);
}); });
+16 -2
View File
@@ -124,13 +124,27 @@ export class CommandRouter {
return this.relay(workspaceId, undefined, "workspace.query", { ...params, kind }); return this.relay(workspaceId, undefined, "workspace.query", { ...params, kind });
} }
/** Relayed read used by `GET /sessions/:sid/entries`. */ /**
* Relayed read used by `GET /sessions/:sid/entries`.
*
* The sid travels on the envelope even when `workspaceIdHint` routes the read
* to an instance that does not own the session (a disk-only row): the plugin
* resolves the file from its registry, so `params.sessionFile` is a fallback,
* never a requirement. Dropping the sid here forced every workspace-scoped
* read to carry a session file, which a session does not have before its
* first entry is persisted.
*/
async relaySessionQuery( async relaySessionQuery(
sessionId: string, sessionId: string,
method: string, method: string,
params: Record<string, unknown> = {}, params: Record<string, unknown> = {},
workspaceIdHint?: string,
): Promise<Record<string, unknown>> { ): Promise<Record<string, unknown>> {
const workspaceId = this.resolveWorkspace(sessionId, params); const hint =
typeof workspaceIdHint === "string" && workspaceIdHint !== ""
? { workspaceId: workspaceIdHint }
: {};
const workspaceId = this.resolveWorkspace(sessionId, { ...params, ...hint });
return this.relay(workspaceId, sessionId, method, params); return this.relay(workspaceId, sessionId, method, params);
} }
+7
View File
@@ -199,6 +199,13 @@ export interface SessionState {
visible?: boolean; visible?: boolean;
/** List metadata only: the subagent task description carried by the list row. Never emitted by the reducer. */ /** List metadata only: the subagent task description carried by the list row. Never emitted by the reducer. */
task?: string; task?: string;
/**
* List metadata only: the first user message of the session file, carried by
* the list row's disk projection. The web client shows it as the provisional
* display name while the session has no name of its own (pi2.nvim's
* `first_message` fallback). Never emitted by the reducer.
*/
firstMessage?: string | null;
} }
/* ------------------------------------------------------------------ */ /* ------------------------------------------------------------------ */
+24
View File
@@ -266,6 +266,9 @@ describe("HTTP API", () => {
(call) => call.method === "workspace.query" && call.params?.kind === "entries", (call) => call.method === "workspace.query" && call.params?.kind === "entries",
); );
expect(entryCall?.params).toEqual({ before: "e9", limit: 25, kind: "entries" }); expect(entryCall?.params).toEqual({ before: "e9", limit: 25, kind: "entries" });
// The routed sid rides on the envelope so the plugin can resolve the
// session file itself (no `sessionFile` guarantee on the wire).
expect(entryCall?.sessionId).toBe("s1");
expect((await entries.json()) as { entries: unknown[] }).toHaveProperty("entries"); expect((await entries.json()) as { entries: unknown[] }).toHaveProperty("entries");
const attention = await fetch(`${h.url}/api/v1/attention?workspaceId=ws-1`, authed()); const attention = await fetch(`${h.url}/api/v1/attention?workspaceId=ws-1`, authed());
@@ -277,6 +280,27 @@ describe("HTTP API", () => {
); );
}); });
it("routes a disk-only session's entries through workspaceId but keeps the sid", async () => {
// A row from disk discovery is not owned by the live instance, so the
// workspace hint is what routes it -- and the sid must survive that.
h.instances.sessionOwners.delete("s1");
conn.commandHandler = async () =>
({ seq: 1, disposition: "started", entries: [] }) as never;
const res = await fetch(
`${h.url}/api/v1/sessions/disk-1/entries?limit=5&workspaceId=ws-1&sessionFile=${encodeURIComponent(
"/tmp/disk-1.jsonl",
)}`,
authed(),
);
expect(res.status).toBe(200);
const call = conn.commands.find(
(entry) => entry.method === "workspace.query" && entry.params?.kind === "entries",
);
expect(call?.sessionId).toBe("disk-1");
expect(call?.params).toEqual({ limit: 5, sessionFile: "/tmp/disk-1.jsonl", kind: "entries" });
});
it("returns resources and diagnostics", async () => { it("returns resources and diagnostics", async () => {
h.instances.resourcesValue = { h.instances.resourcesValue = {
instances: [ instances: [
+16
View File
@@ -8,6 +8,8 @@ import { PagePill } from "@/components/shared/page-pill";
import { PrefsMenu } from "@/components/shared/prefs-menu"; import { PrefsMenu } from "@/components/shared/prefs-menu";
import { ServerChip } from "@/components/shared/server-chip"; import { ServerChip } from "@/components/shared/server-chip";
import { clearPairMeta } from "@/features/connect/pairing"; import { clearPairMeta } from "@/features/connect/pairing";
import { useHealthQuery } from "@/features/status/queries";
import { resolveServerStatus } from "@/features/status/server";
import { api, getDeviceToken, onUnauthorized } from "@/lib/api"; import { api, getDeviceToken, onUnauthorized } from "@/lib/api";
import { CONNECT_PATH, safeNext } from "@/lib/routing"; import { CONNECT_PATH, safeNext } from "@/lib/routing";
import { defaultWsUrl, PiWsClient, type WsConnectionState } from "@/lib/ws"; import { defaultWsUrl, PiWsClient, type WsConnectionState } from "@/lib/ws";
@@ -99,6 +101,7 @@ export function AppShell() {
const href = useRouterState({ select: (state) => state.location.href }); const href = useRouterState({ select: (state) => state.location.href });
const paired = useConnectionStore((state) => state.paired); const paired = useConnectionStore((state) => state.paired);
const setServer = useConnectionStore((state) => state.setServer); const setServer = useConnectionStore((state) => state.setServer);
const setServerStatus = useConnectionStore((state) => state.setServerStatus);
const wsState = useConnectionStore((state) => state.wsState); const wsState = useConnectionStore((state) => state.wsState);
const setWsState = useConnectionStore((state) => state.setWsState); const setWsState = useConnectionStore((state) => state.setWsState);
const disconnect = useConnectionStore((state) => state.disconnect); const disconnect = useConnectionStore((state) => state.disconnect);
@@ -116,11 +119,24 @@ export function AppShell() {
staleTime: 30_000, staleTime: 30_000,
retry: 1, retry: 1,
}); });
const health = useHealthQuery(paired && !isConnect);
const healthOk = health.data?.ok ?? (health.data ? health.data.items.every((item) => item.ok) : undefined);
useEffect(() => { useEffect(() => {
if (info.data) setServer(info.data); if (info.data) setServer(info.data);
}, [info.data, setServer]); }, [info.data, setServer]);
useEffect(() => {
setServerStatus(
resolveServerStatus({
paired,
info: info.data,
infoError: info.isError,
healthOk,
}),
);
}, [healthOk, info.data, info.isError, paired, setServerStatus]);
useEffect(() => { useEffect(() => {
document.body.dataset.page = page; document.body.dataset.page = page;
}, [page]); }, [page]);
@@ -5,6 +5,7 @@ import { useTranslation } from "react-i18next";
import { Icon, type IconName } from "@/components/icons"; import { Icon, type IconName } from "@/components/icons";
import { NAV } from "@/components/shared/nav-list"; import { NAV } from "@/components/shared/nav-list";
import { sessionTitle } from "@/features/chat/session-title";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { useSessionsStore } from "@/stores/sessions"; import { useSessionsStore } from "@/stores/sessions";
import { useWorkspacesStore } from "@/stores/workspaces"; import { useWorkspacesStore } from "@/stores/workspaces";
@@ -76,7 +77,10 @@ export function CommandPalette({ open, onOpenChange }: CommandPaletteProps) {
id: `session-${session.sessionId}`, id: `session-${session.sessionId}`,
group: groupSessions, group: groupSessions,
icon: "chat", icon: "chat",
label: session.name ?? session.sessionId, label: sessionTitle(session, {
unnamed: t("chat.sessionUnnamed"),
subagentUnnamed: t("chat.subagentUnnamed"),
}).text,
hint: t(`state.${session.status}`), hint: t(`state.${session.status}`),
keywords: `${session.sessionId} ${session.model?.id ?? ""} ${session.cwd}`, keywords: `${session.sessionId} ${session.model?.id ?? ""} ${session.cwd}`,
href: `/chat/${encodeURIComponent(session.sessionId)}`, href: `/chat/${encodeURIComponent(session.sessionId)}`,
+2 -2
View File
@@ -57,10 +57,10 @@ export interface NavListProps {
export function NavList({ variant, page }: NavListProps) { export function NavList({ variant, page }: NavListProps) {
const { t } = useTranslation(); const { t } = useTranslation();
const server = useConnectionStore((state) => state.server); const server = useConnectionStore((state) => state.server);
const status = useConnectionStore((state) => state.serverStatus);
const status = server?.status ?? "offline";
const name = server?.name ?? "pi2.nvim"; const name = server?.name ?? "pi2.nvim";
const version = server?.pluginVersion ?? server?.version ?? ""; const version = server?.pluginVersion || server?.version || "";
const serverTip = t("shell.railServerTip", { name, status: t(`state.${status}`), version }); const serverTip = t("shell.railServerTip", { name, status: t(`state.${status}`), version });
const connectTip = t("shell.connection"); const connectTip = t("shell.connection");
+1 -1
View File
@@ -18,12 +18,12 @@ export interface ServerChipProps {
export function ServerChip({ server: override, className }: ServerChipProps) { export function ServerChip({ server: override, className }: ServerChipProps) {
const { t } = useTranslation(); const { t } = useTranslation();
const stored = useConnectionStore((state) => state.server); const stored = useConnectionStore((state) => state.server);
const status = useConnectionStore((state) => state.serverStatus);
const server = override ?? stored; const server = override ?? stored;
const name = server?.name ?? "pi2.nvim"; const name = server?.name ?? "pi2.nvim";
const hostname = const hostname =
server?.hostname ?? (typeof window !== "undefined" ? window.location.hostname || "localhost" : "localhost"); server?.hostname ?? (typeof window !== "undefined" ? window.location.hostname || "localhost" : "localhost");
const status = server?.status ?? "offline";
const dot = serverDotClass(status); const dot = serverDotClass(status);
const dotStatus = dot.replace("dot--", "") as "ok" | "attention" | "exited" | "idle"; const dotStatus = dot.replace("dot--", "") as "ok" | "attention" | "exited" | "idle";
+17 -10
View File
@@ -14,6 +14,7 @@ import {
normalizeSessionSummary, normalizeSessionSummary,
normalizeSessionsPayload, normalizeSessionsPayload,
normalizeSnapshotState, normalizeSnapshotState,
tabSessionRows,
} from "./session-state"; } from "./session-state";
import { setSessionMeta } from "./history"; import { setSessionMeta } from "./history";
import { migrateSessionId } from "./migration"; import { migrateSessionId } from "./migration";
@@ -148,7 +149,13 @@ export interface ChatSessions {
refetch: () => void; refetch: () => void;
} }
/** Sessions of one workspace, merged into the shared store (live state wins). */ /**
* Sessions of one workspace, merged into the shared store (live state wins).
*
* "Sessions" here means the nvim tab set — `tab`-backed rows plus the sessions
* linked to them through `parentId` (see `tabSessionRows`). The plugin's list
* also carries every JSONL on disk, which is history, not a tab.
*/
export function useChatSessions(workspaceId: string | undefined, enabled: boolean): ChatSessions { export function useChatSessions(workspaceId: string | undefined, enabled: boolean): ChatSessions {
const query = useQuery({ const query = useQuery({
queryKey: ["chat-sessions", workspaceId], queryKey: ["chat-sessions", workspaceId],
@@ -162,18 +169,18 @@ export function useChatSessions(workspaceId: string | undefined, enabled: boolea
useEffect(() => { useEffect(() => {
if (!workspaceId || !query.data) return; if (!workspaceId || !query.data) return;
const raw = query.data as { sessions?: Array<{ sessionId?: unknown; sessionFile?: unknown }> } | undefined; // The payload is the union of the workspace's JSONL history and its live
for (const row of raw?.sessions ?? []) { // sessions; the console renders the nvim tab set only, so a historical
if (typeof row?.sessionId === "string") { // row can never look like a tab (and never receives a prompt).
setSessionMeta(row.sessionId, { const rows = tabSessionRows(query.data);
workspaceId, for (const row of rows) {
sessionFile: typeof row.sessionFile === "string" ? row.sessionFile : undefined, const sessionId = str(row.sessionId) ?? str(row.session_id) ?? str(row.id);
}); if (!sessionId) continue;
} setSessionMeta(sessionId, { workspaceId, sessionFile: str(row.sessionFile) });
} }
const current = useSessionsStore.getState(); const current = useSessionsStore.getState();
const existing = current.byWorkspace[workspaceId] ?? []; const existing = current.byWorkspace[workspaceId] ?? [];
const next = normalizeSessionsPayload(query.data, workspaceId, existing); const next = normalizeSessionsPayload(rows, workspaceId, existing);
current.setSessions(workspaceId, next); current.setSessions(workspaceId, next);
}, [workspaceId, query.data]); }, [workspaceId, query.data]);
+22 -9
View File
@@ -34,17 +34,25 @@ export function remapSessionMeta(from: string, to: string): void {
if (meta) sessionMeta.set(to, { ...sessionMeta.get(to), ...meta }); if (meta) sessionMeta.set(to, { ...sessionMeta.get(to), ...meta });
} }
/** `GET /api/v1/sessions/:sid/entries?before=&limit=&workspaceId=&sessionFile=` → raw pi entries + cursor. */ /**
* `GET /api/v1/sessions/:sid/entries?before=&limit=&workspaceId=&sessionFile=` → raw pi entries + cursor.
*
* `workspaceId` is the caller's routing hint (the page knows the workspace it is
* showing): the daemon needs it to reach the right instance for a row that is
* not live, and it must not depend on the list effect having filled
* `sessionMeta` first. `sessionFile` stays metadata-driven — it is a fallback
* for the plugin, which resolves the file from the session id itself.
*/
export async function fetchEntriesPage( export async function fetchEntriesPage(
sessionId: string, sessionId: string,
before?: string, options: { before?: string; limit?: number; signal?: AbortSignal; workspaceId?: string } = {},
limit = HISTORY_PAGE_SIZE,
signal?: AbortSignal,
): Promise<FetchedPage> { ): Promise<FetchedPage> {
const { before, limit = HISTORY_PAGE_SIZE, signal, workspaceId } = options;
const query = new URLSearchParams({ limit: String(limit) }); const query = new URLSearchParams({ limit: String(limit) });
if (before) query.set("before", before); if (before) query.set("before", before);
const meta = sessionMeta.get(sessionId); const meta = sessionMeta.get(sessionId);
if (meta?.workspaceId) query.set("workspaceId", meta.workspaceId); const routedWorkspace = workspaceId ?? meta?.workspaceId;
if (routedWorkspace) query.set("workspaceId", routedWorkspace);
if (meta?.sessionFile) query.set("sessionFile", meta.sessionFile); if (meta?.sessionFile) query.set("sessionFile", meta.sessionFile);
const raw = await apiRequest<unknown>( const raw = await apiRequest<unknown>(
`/api/v1/sessions/${encodeURIComponent(sessionId)}/entries?${query.toString()}`, `/api/v1/sessions/${encodeURIComponent(sessionId)}/entries?${query.toString()}`,
@@ -82,11 +90,16 @@ export interface SessionHistory {
/** /**
* Historical pages merged with the live snapshot entries (live wins by id). * Historical pages merged with the live snapshot entries (live wins by id).
* Paging is backwards (`before` cursor) and dedupes by entry id. * Paging is backwards (`before` cursor) and dedupes by entry id.
*
* `workspaceId` is the routing hint for the entries relay (see
* `fetchEntriesPage`); it is nullable because `/chat` can render before a
* workspace is resolved.
*/ */
export function useSessionHistory( export function useSessionHistory(
sessionId: string | null | undefined, sessionId: string | null | undefined,
liveEntries: Entry[], liveEntries: Entry[],
enabled = true, enabled = true,
workspaceId?: string | null,
): SessionHistory { ): SessionHistory {
const history = useChatStore((state) => const history = useChatStore((state) =>
sessionId ? (state.history[sessionId] ?? EMPTY_HISTORY) : EMPTY_HISTORY, sessionId ? (state.history[sessionId] ?? EMPTY_HISTORY) : EMPTY_HISTORY,
@@ -100,7 +113,7 @@ export function useSessionHistory(
const seq = nextRequest(sessionId); const seq = nextRequest(sessionId);
useChatStore.getState().beginInitial(sessionId); useChatStore.getState().beginInitial(sessionId);
void fetchEntriesPage(sessionId) void fetchEntriesPage(sessionId, { workspaceId: workspaceId ?? undefined })
.then((page) => { .then((page) => {
if (!isCurrent(sessionId, seq)) return; if (!isCurrent(sessionId, seq)) return;
useChatStore.getState().receiveInitial(sessionId, page.entries, page.cursor); useChatStore.getState().receiveInitial(sessionId, page.entries, page.cursor);
@@ -111,7 +124,7 @@ export function useSessionHistory(
useChatStore.getState().historyError(sessionId, message); useChatStore.getState().historyError(sessionId, message);
}); });
// `token` is the resync generation; `sessionId`/`enabled` gate loading. // `token` is the resync generation; `sessionId`/`enabled` gate loading.
}, [sessionId, enabled, token]); }, [sessionId, enabled, token, workspaceId]);
const loadOlder = useCallback(() => { const loadOlder = useCallback(() => {
if (!sessionId) return; if (!sessionId) return;
@@ -122,7 +135,7 @@ export function useSessionHistory(
const seq = nextRequest(sessionId); const seq = nextRequest(sessionId);
useChatStore.getState().beginOlder(sessionId); useChatStore.getState().beginOlder(sessionId);
void fetchEntriesPage(sessionId, before) void fetchEntriesPage(sessionId, { before, workspaceId: workspaceId ?? undefined })
.then((page) => { .then((page) => {
if (!isCurrent(sessionId, seq)) return; if (!isCurrent(sessionId, seq)) return;
useChatStore.getState().receiveOlder(sessionId, page.entries, page.cursor); useChatStore.getState().receiveOlder(sessionId, page.entries, page.cursor);
@@ -132,7 +145,7 @@ export function useSessionHistory(
const message = error instanceof ApiError ? error.code : error instanceof Error ? error.message : String(error); const message = error instanceof ApiError ? error.code : error instanceof Error ? error.message : String(error);
useChatStore.getState().historyError(sessionId, message); useChatStore.getState().historyError(sessionId, message);
}); });
}, [sessionId]); }, [sessionId, workspaceId]);
const retry = useCallback(() => { const retry = useCallback(() => {
if (!sessionId) return; if (!sessionId) return;
+65 -6
View File
@@ -1,6 +1,6 @@
import type { Batch, Entry, QueueItem, SessionState, Subagent, TodoItem } from "@protocol/types"; import type { Batch, Entry, QueueItem, SessionState, Subagent, TodoItem } from "@protocol/types";
import { useVirtualizer } from "@tanstack/react-virtual"; import { useVirtualizer } from "@tanstack/react-virtual";
import { useCallback, useLayoutEffect, useRef, useState } from "react"; import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { Icon } from "@/components/icons"; import { Icon } from "@/components/icons";
@@ -121,18 +121,50 @@ export function MessageStream({
const queued = allItems.filter((item) => item.kind === "queued"); const queued = allItems.filter((item) => item.kind === "queued");
const steerAll = steerAllOf(session.queue); const steerAll = steerAllOf(session.queue);
const scrollRef = useRef<HTMLDivElement | null>(null); const scrollRef = useRef<HTMLDivElement | null>(null);
const listRef = useRef<HTMLDivElement | null>(null);
const [following, setFollowing] = useState(true); const [following, setFollowing] = useState(true);
const followingRef = useRef(true); const followingRef = useRef(true);
const pendingPrepend = useRef<number | null>(null); const pendingPrepend = useRef<number | null>(null);
const loadRequested = useRef(false); const loadRequested = useRef(false);
const rafRef = useRef<number | null>(null); const rafRef = useRef<number | null>(null);
/** Last observed `scrollTop`, so only an *upward* move counts as "stop following". */
const lastTopRef = useRef<number | null>(null);
/** Explicit scroll input (wheel / touch / keys / pointer drag) is the only way to stop following. */
const userInputRef = useRef(false);
const inputTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
/** A smooth FAB scroll is in flight; instant pins would fight it. */
const smoothUntilRef = useRef(0);
const setFollow = useCallback((value: boolean) => { const setFollow = useCallback((value: boolean) => {
followingRef.current = value; followingRef.current = value;
setFollowing(value); setFollowing(value);
}, []); }, []);
/**
* Mark an explicit user scroll. `following` must never be cleared by content
* growth: the virtualizer measures real item heights after its estimated
* pass, so `scrollHeight` jumps while the view sits still — treating that
* as a user scroll froze the stream one or more screens above the newest
* entry (the stream then looked stuck at an old message).
*/
const markScrollInput = useCallback(() => {
userInputRef.current = true;
if (inputTimerRef.current) clearTimeout(inputTimerRef.current);
inputTimerRef.current = setTimeout(() => {
inputTimerRef.current = null;
userInputRef.current = false;
}, 500);
}, []);
useEffect(
() => () => {
if (inputTimerRef.current) clearTimeout(inputTimerRef.current);
},
[],
);
const virtualize = items.length >= VIRTUALIZE_THRESHOLD; const virtualize = items.length >= VIRTUALIZE_THRESHOLD;
const hasItems = items.length > 0;
const virtualizer = useVirtualizer({ const virtualizer = useVirtualizer({
count: items.length, count: items.length,
getScrollElement: () => scrollRef.current, getScrollElement: () => scrollRef.current,
@@ -153,7 +185,7 @@ export function MessageStream({
// Streaming keeps the DOM height changing; stay pinned while following. // Streaming keeps the DOM height changing; stay pinned while following.
useLayoutEffect(() => { useLayoutEffect(() => {
if (!followingRef.current) return; if (!followingRef.current || Date.now() < smoothUntilRef.current) return;
if (rafRef.current != null) cancelAnimationFrame(rafRef.current); if (rafRef.current != null) cancelAnimationFrame(rafRef.current);
rafRef.current = requestAnimationFrame(() => { rafRef.current = requestAnimationFrame(() => {
rafRef.current = requestAnimationFrame(() => { rafRef.current = requestAnimationFrame(() => {
@@ -163,6 +195,20 @@ export function MessageStream({
}); });
}); });
// A one-shot rAF after render lands short of the end: the virtualizer reports
// real heights only after its estimated pass, and images/tool output load
// later still. Observe the list so every real height change re-pins while
// the user is following.
useEffect(() => {
const list = listRef.current;
if (!list || typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(() => {
if (followingRef.current && Date.now() >= smoothUntilRef.current) scrollToBottom(false);
});
observer.observe(list);
return () => observer.disconnect();
}, [scrollToBottom, virtualize, hasItems]);
useLayoutEffect(() => { useLayoutEffect(() => {
const element = scrollRef.current; const element = scrollRef.current;
const previous = pendingPrepend.current; const previous = pendingPrepend.current;
@@ -176,9 +222,16 @@ export function MessageStream({
const handleScroll = useCallback(() => { const handleScroll = useCallback(() => {
const element = scrollRef.current; const element = scrollRef.current;
if (!element) return; if (!element) return;
const distance = element.scrollHeight - element.scrollTop - element.clientHeight; const top = element.scrollTop;
setFollow(distance < 80); const previous = lastTopRef.current;
if (element.scrollTop < 120 && hasMore && !loadingOlder && !loadRequested.current) { lastTopRef.current = top;
const distance = element.scrollHeight - top - element.clientHeight;
// Re-arm at the bottom. Only explicit input that actually moved the view
// *up* may stop following — growth-driven scroll positions (virtualizer
// measurements, streamed text, late images) must never freeze the pin.
if (distance < 80) setFollow(true);
else if (userInputRef.current && (previous === null || top < previous - 2)) setFollow(false);
if (top < 120 && hasMore && !loadingOlder && !loadRequested.current) {
loadRequested.current = true; loadRequested.current = true;
pendingPrepend.current = element.scrollHeight; pendingPrepend.current = element.scrollHeight;
onLoadOlder(); onLoadOlder();
@@ -268,6 +321,7 @@ export function MessageStream({
{items.length ? ( {items.length ? (
virtualize ? ( virtualize ? (
<div <div
ref={listRef}
className="stream-list stream-inner stream-list--virtual" className="stream-list stream-inner stream-list--virtual"
style={{ height: `${virtualizer.getTotalSize()}px` }} style={{ height: `${virtualizer.getTotalSize()}px` }}
> >
@@ -290,7 +344,7 @@ export function MessageStream({
})} })}
</div> </div>
) : ( ) : (
<div className="stream-list stream-inner"> <div ref={listRef} className="stream-list stream-inner">
{items.map((item) => ( {items.map((item) => (
<div className={itemClassName(item)} key={item.key}> <div className={itemClassName(item)} key={item.key}>
{renderItem(item)} {renderItem(item)}
@@ -329,6 +383,10 @@ export function MessageStream({
aria-live="polite" aria-live="polite"
aria-label={t("chat.streamAria")} aria-label={t("chat.streamAria")}
onScroll={handleScroll} onScroll={handleScroll}
onWheel={markScrollInput}
onTouchMove={markScrollInput}
onKeyDown={markScrollInput}
onPointerDown={markScrollInput}
> >
{status} {status}
{body} {body}
@@ -342,6 +400,7 @@ export function MessageStream({
title={t("chat.backToLatest")} title={t("chat.backToLatest")}
onClick={() => { onClick={() => {
setFollow(true); setFollow(true);
smoothUntilRef.current = Date.now() + 700;
scrollToBottom(true); scrollToBottom(true);
}} }}
> >
+79
View File
@@ -321,6 +321,10 @@ export function normalizeSessionSummary(raw: unknown, workspaceId: string, exist
const thinkingValue = str(record.thinking); const thinkingValue = str(record.thinking);
const hasQueue = Array.isArray(record.queue); const hasQueue = Array.isArray(record.queue);
const task = str(record.task) ?? base.task; const task = str(record.task) ?? base.task;
// Provisional display name: the list row's disk projection of the session's
// first user message (pi2.nvim's `first_message` fallback). Absent means
// "not carried", `null` means "there is none".
const firstMessage = record.firstMessage === null ? null : str(record.firstMessage);
return { return {
...base, ...base,
sessionId, sessionId,
@@ -346,9 +350,84 @@ export function normalizeSessionSummary(raw: unknown, workspaceId: string, exist
parentId: summaryParentId(record, base), parentId: summaryParentId(record, base),
visible: typeof record.visible === "boolean" ? record.visible : base.visible, visible: typeof record.visible === "boolean" ? record.visible : base.visible,
...(task !== undefined ? { task } : {}), ...(task !== undefined ? { task } : {}),
...(firstMessage !== undefined ? { firstMessage } : {}),
}; };
} }
/** `sessionId` of a raw list row (`sessionId` is the wire field; aliases are tolerated). */
function rawSessionId(row: Record<string, unknown>): string {
return str(row.sessionId) ?? str(row.session_id) ?? str(row.id) ?? "";
}
/** `parentId` of a raw list row; `null` means a root. */
function rawParentId(row: Record<string, unknown>): string | null {
return str(row.parentId) ?? str(row.parent_id) ?? null;
}
/** A row is a tab when the plugin's live projection carries `attached_tab`. */
function hasTab(row: Record<string, unknown>): boolean {
return typeof row.tab === "number" && Number.isFinite(row.tab) && row.tab > 0;
}
/**
* Restrict a `workspace.query{kind:"sessions"}` payload to the sessions nvim's
* list renders.
*
* The plugin answers with the union of the workspace's session JSONL files on
* disk (`History.list()`) and its live sessions, so a tab-less root row is
* *history*, not a tab: it has no live owner and a command routed to it answers
* `E_SESSION_NOT_FOUND`. nvim's `:PiSessions` is `Sessions.list()` — the
* sessions attached to a tabpage — plus their children, and `tab` is the live
* projection of `Session.attached_tab`.
*
* So keep the connected component (through `parentId`, in both directions) of
* every row that carries a `tab`: the tabs themselves, the sub-sessions below
* them, and the parent row when a tab is in a child view. Everything else is
* disk history and stays out of the console (it is a `session.resume` target,
* never a prompt target).
*/
export function tabSessionRows(raw: unknown): Record<string, unknown>[] {
const record = rec(raw);
const list = Array.isArray(raw) ? raw : arr(record?.sessions ?? record?.items);
const rows: Record<string, unknown>[] = [];
for (const entry of list) {
const row = rec(entry);
if (row) rows.push(row);
}
// Parent links both ways; a duplicate id (a list race) keeps its first row.
const parentOf = new Map<string, string>();
const childrenOf = new Map<string, string[]>();
for (const row of rows) {
const id = rawSessionId(row);
if (id === "" || parentOf.has(id)) continue;
const parentId = rawParentId(row);
parentOf.set(id, parentId ?? "");
if (parentId !== null && parentId !== "") {
const siblings = childrenOf.get(parentId);
if (siblings) siblings.push(id);
else childrenOf.set(parentId, [id]);
}
}
const keep = new Set<string>();
const stack: string[] = [];
for (const row of rows) {
const id = rawSessionId(row);
if (id !== "" && hasTab(row)) stack.push(id);
}
while (stack.length > 0) {
const id = stack.pop();
if (id === undefined || keep.has(id)) continue;
keep.add(id);
const parentId = parentOf.get(id);
if (parentId) stack.push(parentId);
for (const childId of childrenOf.get(id) ?? []) stack.push(childId);
}
return rows.filter((row) => keep.has(rawSessionId(row)));
}
/** Parse `{sessions:[...]}` (also bare arrays) into render states. */ /** Parse `{sessions:[...]}` (also bare arrays) into render states. */
export function normalizeSessionsPayload( export function normalizeSessionsPayload(
raw: unknown, raw: unknown,
@@ -0,0 +1,37 @@
import { useEffect, useState } from "react";
/**
* pi2.nvim's auto-title spinner (`lua/pi/ui/sessions.lua`): 10 braille frames
* ticked every 120 ms and rendered as a *prefix* before the name — never in
* place of it. It only runs while the backend generates a title; the row's own
* text stays static (pi2.nvim animates nothing else in `:PiSessions`).
*
* `prefers-reduced-motion: reduce` freezes it on the first frame: the state is
* still visible, only the motion stops.
*/
const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
const SPINNER_INTERVAL_MS = 120;
export interface SessionTitleSpinnerProps {
/** Hidden from assistive tech: the row's name already carries the state. */
className?: string;
}
export function SessionTitleSpinner({ className = "t-spinner" }: SessionTitleSpinnerProps) {
const [frame, setFrame] = useState(0);
useEffect(() => {
if (typeof window === "undefined") return;
if (window.matchMedia?.("(prefers-reduced-motion: reduce)").matches) return;
const timer = window.setInterval(() => {
setFrame((current) => (current + 1) % SPINNER_FRAMES.length);
}, SPINNER_INTERVAL_MS);
return () => window.clearInterval(timer);
}, []);
return (
<span className={className} aria-hidden="true">
{SPINNER_FRAMES[frame]}
</span>
);
}
+91
View File
@@ -0,0 +1,91 @@
/**
* Session / sub-session display titles — the web port of pi2.nvim's
* `:PiSessions` name resolution (`lua/pi/ui/sessions.lua`, `resolve_name`).
*
* Rules (in this order, each guarded by a trim + non-empty check):
*
* 1. the session's own name (`session.name`, set by the user or the backend's
* auto-title extension);
* 2. while the backend is *generating* a title, the provisional placeholder —
* never the first message: pi2.nvim keeps the label on `(unnamed)` so the
* row makes one visible change (placeholder → title), not two;
* 3. the first user message (`session.firstMessage`, the list row's disk
* projection) as the provisional label;
* 4. the `(unnamed)` placeholder.
*
* Sub-sessions resolve `name` → the task prompt (first 40 characters, the same
* cut as `pi/subsessions/manifest.lua FALLBACK_NAME_CHARS`) → `sub-session`.
*
* **Never returns an id.** A session id is an identity (`data-session-id`,
* hrefs, RPC targets), not a label — pi2.nvim shows `(unnamed)` instead.
*
* Pure and React-free so the state machine is unit-testable without a DOM.
*/
export interface SessionTitleInput {
name?: string | null;
firstMessage?: string | null;
/**
* Reserved: the plugin's `pi-title` extension status (the auto-title
* extension's `setStatus` while it generates a name) is not relayed to the
* browser yet — `docs/protocol.md` has no field for it. When it lands, the
* row's spinner switches on with no change here.
*/
titleGenerating?: boolean;
}
export interface SessionTitlePhrases {
/** `t("chat.sessionUnnamed")` — the pi2.nvim `(unnamed)` literal. */
unnamed: string;
/** `t("chat.subagentUnnamed")` — the pi2.nvim `sub-session` fallback. */
subagentUnnamed: string;
}
export type SessionTitleKind = "name" | "first-message" | "task" | "generating" | "unnamed";
export interface SessionTitle {
/** What the row renders. Never an id. */
text: string;
kind: SessionTitleKind;
/** Placeholder text (`(unnamed)` / `sub-session`) rather than data. */
provisional: boolean;
/** Render the braille spinner prefix (pi2.nvim: prefix, never a replacement). */
spinner: boolean;
}
/** Task characters kept when deriving a sub-session name (`Manifest.fallback_name`). */
export const FALLBACK_NAME_CHARS = 40;
export function sessionTitle(input: SessionTitleInput, phrases: SessionTitlePhrases): SessionTitle {
const name = trim(input?.name);
if (name) return { text: name, kind: "name", provisional: false, spinner: false };
if (input?.titleGenerating === true) {
// pi2.nvim suppresses the first-message fallback while titling.
return { text: phrases.unnamed, kind: "generating", provisional: true, spinner: true };
}
const firstMessage = trim(input?.firstMessage);
if (firstMessage) return { text: firstMessage, kind: "first-message", provisional: false, spinner: false };
return { text: phrases.unnamed, kind: "unnamed", provisional: true, spinner: false };
}
export function subagentTitle(
input: Pick<SessionTitleInput, "name"> & { task?: string | null },
phrases: SessionTitlePhrases,
): SessionTitle {
const name = trim(input?.name);
if (name) return { text: name, kind: "name", provisional: false, spinner: false };
const task = trim(input?.task);
if (task) {
return { text: task.slice(0, FALLBACK_NAME_CHARS), kind: "task", provisional: true, spinner: false };
}
return { text: phrases.subagentUnnamed, kind: "unnamed", provisional: true, spinner: false };
}
function trim(value: string | null | undefined): string {
return typeof value === "string" ? value.trim() : "";
}
+12 -4
View File
@@ -11,6 +11,7 @@ import { cn } from "@/lib/utils";
import { TodoList } from "./blocks"; import { TodoList } from "./blocks";
import { formatDuration } from "./format"; import { formatDuration } from "./format";
import { subagentTitle } from "./session-title";
import type { TrayTab } from "./store"; import type { TrayTab } from "./store";
import "@/styles/pages/chat-tray.css"; import "@/styles/pages/chat-tray.css";
@@ -71,9 +72,16 @@ export function SessionTray({
const tabsRef = useRef<HTMLDivElement | null>(null); const tabsRef = useRef<HTMLDivElement | null>(null);
const [entered, setEntered] = useState(false); const [entered, setEntered] = useState(false);
const title = subagent // The tray names the subagent it is scoped to; a nameless subagent is
? t("chat.subview.trayTitle", { name: subagent.name ?? subagent.id }) // labelled by its task prompt, never by its id (pi2.nvim parity).
: t("chat.trayTitle"); const subagentName = subagent
? subagentTitle(subagent, {
unnamed: t("chat.sessionUnnamed"),
subagentUnnamed: t("chat.subagentUnnamed"),
}).text
: "";
const title = subagent ? t("chat.subview.trayTitle", { name: subagentName }) : t("chat.trayTitle");
// Enter animation: flip `is-open` on the frame after the node is painted. // Enter animation: flip `is-open` on the frame after the node is painted.
useEffect(() => { useEffect(() => {
@@ -185,7 +193,7 @@ export function SessionTray({
<p className="tray-scope" data-testid="tray-scope"> <p className="tray-scope" data-testid="tray-scope">
<span className="tray-scope__label"> <span className="tray-scope__label">
{subagent {subagent
? t("chat.trayScopeSubagent", { name: subagent.name ?? subagent.id }) ? t("chat.trayScopeSubagent", { name: subagentName })
: t("chat.trayScopeSession")} : t("chat.trayScopeSession")}
</span> </span>
{subagent ? <span className="tray-scope__note">{t("chat.trayScopeNote")}</span> : null} {subagent ? <span className="tray-scope__note">{t("chat.trayScopeNote")}</span> : null}
+21 -4
View File
@@ -1,5 +1,7 @@
import type { SessionState, Subagent } from "@protocol/types"; import type { SessionState, Subagent } from "@protocol/types";
import { sessionTitle, subagentTitle } from "./session-title";
/** /**
* The session tree the sidebar renders: workspace sessions nest under their * The session tree the sidebar renders: workspace sessions nest under their
* `parentId` (sub-sessions are separate rows of the same REST list), and a * `parentId` (sub-sessions are separate rows of the same REST list), and a
@@ -145,12 +147,19 @@ function containsNode(node: TreeNode, id: string): boolean {
return node.children.some((child) => containsNode(child, id)); return node.children.some((child) => containsNode(child, id));
} }
/**
* English search phrases: the model is React-free, so it must not depend on
* i18n. Searching matches the rendered label *and* the raw id, which keeps a
* session findable even though an id is never displayed as its title.
*/
const SEARCH_PHRASES = { unnamed: "(unnamed)", subagentUnnamed: "sub-session" };
function sessionLabel(session: SessionState): string { function sessionLabel(session: SessionState): string {
return session.name?.trim() || session.sessionId; return sessionTitle(session, SEARCH_PHRASES).text;
} }
function subagentLabel(subagent: Subagent): string { function subagentLabel(subagent: Subagent): string {
return subagent.name?.trim() || subagent.id; return subagentTitle(subagent, SEARCH_PHRASES).text;
} }
/** Search matches the session/subagent name or its model id (prototype behaviour). */ /** Search matches the session/subagent name or its model id (prototype behaviour). */
@@ -225,7 +234,13 @@ export function buildSessionTreeView(
* active lens > plugin policy > "an kept descendant needs the ancestor". * active lens > plugin policy > "an kept descendant needs the ancestor".
*/ */
function keepSession(session: SessionState, childCount: number): boolean { function keepSession(session: SessionState, childCount: number): boolean {
if (needle !== "") return matches(sessionLabel(session), session.model?.id, needle) || childCount > 0; if (needle !== "") {
return (
matches(sessionLabel(session), session.model?.id, needle) ||
session.sessionId.toLowerCase().includes(needle) ||
childCount > 0
);
}
if (selectedId !== null && session.sessionId === selectedId) return true; if (selectedId !== null && session.sessionId === selectedId) return true;
if (activeOnly && !isSessionActive(session)) return childCount > 0; if (activeOnly && !isSessionActive(session)) return childCount > 0;
if (session.visible === false) return showHidden || childCount > 0; if (session.visible === false) return showHidden || childCount > 0;
@@ -298,7 +313,9 @@ export function buildSessionTreeView(
showHidden || showHidden ||
selectedId === subagent.id || selectedId === subagent.id ||
children.length > 0 || children.length > 0 ||
(needle !== "" && matches(subagentLabel(subagent), subagent.model, needle)); (needle !== "" &&
(matches(subagentLabel(subagent), subagent.model, needle) ||
subagent.id.toLowerCase().includes(needle)));
if (!keep) { if (!keep) {
if (needle === "") hiddenByPolicy += 1; if (needle === "") hiddenByPolicy += 1;
return null; return null;
+33 -6
View File
@@ -8,6 +8,8 @@ import { StatusDot, subagentDotClass } from "@/components/ui/status-dot";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { SessionRowMenu } from "./session-row-menu"; import { SessionRowMenu } from "./session-row-menu";
import { flattenSubagents, sessionDot } from "./session-state"; import { flattenSubagents, sessionDot } from "./session-state";
import { sessionTitle, subagentTitle } from "./session-title";
import { SessionTitleSpinner } from "./session-title-spinner";
import { import {
buildSessionTreeView, buildSessionTreeView,
treeNodeId, treeNodeId,
@@ -104,6 +106,11 @@ export function SessionTree({
const [wsMenuOpen, setWsMenuOpen] = useState(false); const [wsMenuOpen, setWsMenuOpen] = useState(false);
const [rowMenu, setRowMenu] = useState<{ session: SessionState; anchor: HTMLElement } | null>(null); const [rowMenu, setRowMenu] = useState<{ session: SessionState; anchor: HTMLElement } | null>(null);
const anchorRef = useRef<HTMLElement | null>(null); const anchorRef = useRef<HTMLElement | null>(null);
// pi2.nvim's `(unnamed)` / `sub-session` placeholders, in the active locale.
const titlePhrases = useMemo(
() => ({ unnamed: t("chat.sessionUnnamed"), subagentUnnamed: t("chat.subagentUnnamed") }),
[t],
);
const view = useMemo( const view = useMemo(
() => () =>
@@ -172,7 +179,8 @@ export function SessionTree({
const session = node.session; const session = node.session;
const selected = session.sessionId === selectedId; const selected = session.sessionId === selectedId;
const menuOpen = rowMenu?.session.sessionId === session.sessionId; const menuOpen = rowMenu?.session.sessionId === session.sessionId;
const name = session.name?.trim() || session.sessionId; // A row is never labelled with its id (pi2.nvim shows `(unnamed)`).
const title = sessionTitle(session, titlePhrases);
const attention = session.attention.length; const attention = session.attention.length;
return ( return (
<div <div
@@ -197,12 +205,21 @@ export function SessionTree({
<button <button
type="button" type="button"
className="tree-row__main" className="tree-row__main"
title={rowTitle([name, session.model?.id, session.thinking])} title={rowTitle([title.text, session.model?.id, session.thinking])}
aria-current={selected ? "true" : undefined} aria-current={selected ? "true" : undefined}
onClick={() => onSelectSession(session.sessionId)} onClick={() => onSelectSession(session.sessionId)}
> >
<StatusDot status={sessionDot(session)} /> <StatusDot status={sessionDot(session)} />
<span className="t-name truncate">{name}</span> {title.spinner ? <SessionTitleSpinner /> : null}
<span
className={cn(
"t-name truncate",
title.kind === "unnamed" && "is-unnamed",
title.kind === "generating" && "is-generating",
)}
>
{title.text}
</span>
{attention > 0 ? <span className="t-attn">{`!${attention}`}</span> : null} {attention > 0 ? <span className="t-attn">{`!${attention}`}</span> : null}
</button> </button>
<button <button
@@ -227,9 +244,11 @@ export function SessionTree({
function renderSubagentRow(node: SubagentTreeNode) { function renderSubagentRow(node: SubagentTreeNode) {
const { session, subagent } = node; const { session, subagent } = node;
const viewing = subagent.id === activeSubagentId; const viewing = subagent.id === activeSubagentId;
const name = subagent.name?.trim() || subagent.id; // Sub-session rows resolve name → task prompt (40 chars) → `sub-session`;
// the id stays an identity, never a label.
const title = subagentTitle(subagent, titlePhrases);
// Status is carried by the dot only; text goes to title/aria-label. // Status is carried by the dot only; text goes to title/aria-label.
const label = rowTitle([name, subagent.model, subagent.thinking, t(`state.${subagent.status}`)]); const label = rowTitle([title.text, subagent.model, subagent.thinking, t(`state.${subagent.status}`)]);
return ( return (
<div <div
className={cn( className={cn(
@@ -257,7 +276,15 @@ export function SessionTree({
onClick={() => onSelectSubagent(session.sessionId, subagent.id)} onClick={() => onSelectSubagent(session.sessionId, subagent.id)}
> >
<span className={cn("dot", subagentDotClass(subagent.status))} aria-hidden="true" /> <span className={cn("dot", subagentDotClass(subagent.status))} aria-hidden="true" />
<span className="t-name truncate">{name}</span> <span
className={cn(
"t-name truncate",
title.kind === "unnamed" && "is-unnamed",
title.kind === "generating" && "is-generating",
)}
>
{title.text}
</span>
{node.hiddenCount > 0 ? ( {node.hiddenCount > 0 ? (
<span className="t-hidden tabular" title={t("chat.hiddenSubs", { n: node.hiddenCount })}> <span className="t-hidden tabular" title={t("chat.hiddenSubs", { n: node.hiddenCount })}>
{`+${node.hiddenCount}`} {`+${node.hiddenCount}`}
+5 -1
View File
@@ -12,6 +12,7 @@ import { EntryBlock } from "./blocks";
import { Composer } from "./composer"; import { Composer } from "./composer";
import type { ModelGroup } from "./data"; import type { ModelGroup } from "./data";
import { HeadChips } from "./head-chips"; import { HeadChips } from "./head-chips";
import { subagentTitle } from "./session-title";
import type { TrayTab } from "./store"; import type { TrayTab } from "./store";
import "@/styles/pages/chat-telemetry.css"; import "@/styles/pages/chat-telemetry.css";
@@ -185,7 +186,10 @@ export function SubagentView({
className, className,
}: SubagentViewProps) { }: SubagentViewProps) {
const { t } = useTranslation(); const { t } = useTranslation();
const name = subagent.name?.trim() || subagent.id; const name = subagentTitle(subagent, {
unnamed: t("chat.sessionUnnamed"),
subagentUnnamed: t("chat.subagentUnnamed"),
}).text;
const task = subagent.task?.trim() || ""; const task = subagent.task?.trim() || "";
// `live` is authoritative when present; the status is the fallback. // `live` is authoritative when present; the status is the fallback.
const isLive = subagent.live === true || subagent.status === "active"; const isLive = subagent.live === true || subagent.status === "active";
+2 -1
View File
@@ -122,10 +122,11 @@ export function useInfoQuery(enabled = true) {
}); });
} }
export function useHealthQuery() { export function useHealthQuery(enabled = true) {
return useQuery<HealthResponse>({ return useQuery<HealthResponse>({
queryKey: ["health"], queryKey: ["health"],
queryFn: ({ signal }) => api.health(signal), queryFn: ({ signal }) => api.health(signal),
enabled,
staleTime: 10_000, staleTime: 10_000,
}); });
} }
+37 -2
View File
@@ -1,6 +1,41 @@
import type { InfoResponse } from "@/lib/api"; import type { InfoResponse } from "@/lib/api";
import type { WsConnectionState } from "@/lib/ws"; import type { WsConnectionState } from "@/lib/ws";
export type ServerStatusValue = "online" | "degraded" | "offline" | "unknown";
export interface ServerStatusInput {
/** The browser holds a paired device (localStorage `pi2-connection`). */
paired: boolean;
/** Cached `GET /api/v1/info` payload, or `null`/`undefined` before the first success. */
info?: InfoResponse | null;
/** The /info query failed (network error or non-2xx). */
infoError?: boolean;
/** `GET /api/v1/health` → `ok`, `null`/`undefined` while unknown. */
healthOk?: boolean | null;
}
/** Resolve the server status the UI may trust; never the wire's absent `status` field. */
export function resolveServerStatus(input: ServerStatusInput): ServerStatusValue {
// 1. Unpaired clients cannot reach a server session.
if (!input.paired) {
return "offline";
}
// 2. The /info probe failed (network error or non-2xx) — daemon is unreachable.
if (input.infoError) {
return "offline";
}
// 3. /health reported a degraded subsystem while the daemon itself responds.
if (input.healthOk === false) {
return "degraded";
}
// 4. Cached or freshly fetched /info payload is present and healthy.
if (input.info != null) {
return "online";
}
// 5. First probe is still in flight — do not flash offline.
return "unknown";
}
/** /**
* Optional identity fields the daemon may expose beyond the minimal /info * Optional identity fields the daemon may expose beyond the minimal /info
* contract (`{v,daemonId,machineId,platform,hostname,os,version,uptimeMs, * contract (`{v,daemonId,machineId,platform,hostname,os,version,uptimeMs,
@@ -36,7 +71,7 @@ export interface ServerIdentity {
uptimeSec: number | null; uptimeSec: number | null;
uptimeMs: number | null; uptimeMs: number | null;
pid: number | null; pid: number | null;
status: "online" | "degraded" | "offline"; status: ServerStatusValue;
wsConnected: boolean; wsConnected: boolean;
wsProto: string; wsProto: string;
lastHeartbeatAt: number | null; lastHeartbeatAt: number | null;
@@ -85,7 +120,7 @@ export interface DeriveServerInput {
wsState?: WsConnectionState; wsState?: WsConnectionState;
fetchedAt?: number | null; fetchedAt?: number | null;
nameFallback?: string | null; nameFallback?: string | null;
status?: "online" | "degraded" | "offline" | null; status?: ServerStatusValue | null;
} }
/** Resolve the single server's identity from /info + the locally stored endpoint. */ /** Resolve the single server's identity from /info + the locally stored endpoint. */
+1
View File
@@ -257,6 +257,7 @@ export interface InfoResponse {
/** Additive identity fields (daemon ≥ 0.2): OS label and process uptime. */ /** Additive identity fields (daemon ≥ 0.2): OS label and process uptime. */
os?: string; os?: string;
uptimeMs?: number; uptimeMs?: number;
/** Daemon does not send status today; resolveServerStatus() is the authority (a newer daemon may still send it as an override). */
status?: "online" | "degraded" | "offline"; status?: "online" | "degraded" | "offline";
} }
+2
View File
@@ -209,6 +209,7 @@
"chat.sendFailed": "Send failed: {error}", "chat.sendFailed": "Send failed: {error}",
"chat.sendTitle": "Send (Enter)", "chat.sendTitle": "Send (Enter)",
"chat.sending": "Sending…", "chat.sending": "Sending…",
"chat.sessionUnnamed": "(unnamed)",
"chat.sessions": "Sessions", "chat.sessions": "Sessions",
"chat.shell.command": "Command", "chat.shell.command": "Command",
"chat.shell.copyCommand": "Copy command", "chat.shell.copyCommand": "Copy command",
@@ -256,6 +257,7 @@
"chat.subagentCount": "{n} subagents", "chat.subagentCount": "{n} subagents",
"chat.subagentFilter": "Subagent filter", "chat.subagentFilter": "Subagent filter",
"chat.subagentName": "Subagent name", "chat.subagentName": "Subagent name",
"chat.subagentUnnamed": "sub-session",
"chat.subagentNamePlaceholder": "e.g. ui-research", "chat.subagentNamePlaceholder": "e.g. ui-research",
"chat.subview.back": "Parent", "chat.subview.back": "Parent",
"chat.subview.backTo": "Back to {name}", "chat.subview.backTo": "Back to {name}",
+2
View File
@@ -209,6 +209,7 @@
"chat.sendFailed": "发送失败:{error}", "chat.sendFailed": "发送失败:{error}",
"chat.sendTitle": "发送(Enter)", "chat.sendTitle": "发送(Enter)",
"chat.sending": "发送中…", "chat.sending": "发送中…",
"chat.sessionUnnamed": "(未命名)",
"chat.sessions": "会话", "chat.sessions": "会话",
"chat.shell.command": "命令", "chat.shell.command": "命令",
"chat.shell.copyCommand": "复制命令", "chat.shell.copyCommand": "复制命令",
@@ -256,6 +257,7 @@
"chat.subagentCount": "{n} 个子代理", "chat.subagentCount": "{n} 个子代理",
"chat.subagentFilter": "子代理筛选", "chat.subagentFilter": "子代理筛选",
"chat.subagentName": "子代理名称", "chat.subagentName": "子代理名称",
"chat.subagentUnnamed": "子会话",
"chat.subagentNamePlaceholder": "例如 ui-research", "chat.subagentNamePlaceholder": "例如 ui-research",
"chat.subview.back": "父级", "chat.subview.back": "父级",
"chat.subview.backTo": "返回 {name}", "chat.subview.backTo": "返回 {name}",
+28 -8
View File
@@ -39,6 +39,7 @@ import { MessageStream } from "@/features/chat/message-stream";
import { onSessionMigration, replaceChatUrl } from "@/features/chat/migration"; import { onSessionMigration, replaceChatUrl } from "@/features/chat/migration";
import { DispatchModal, RenameDialog, TaskOutputModal, type DispatchInput } from "@/features/chat/modals"; import { DispatchModal, RenameDialog, TaskOutputModal, type DispatchInput } from "@/features/chat/modals";
import { SessionTray } from "@/features/chat/session-tray"; import { SessionTray } from "@/features/chat/session-tray";
import { sessionTitle } from "@/features/chat/session-title";
import { import {
findSubagent, findSubagent,
flattenSubagents, flattenSubagents,
@@ -115,9 +116,26 @@ function ChatExperience({ sessionId }: { sessionId?: string }) {
sessions, sessions,
sessionsQuery.loaded, sessionsQuery.loaded,
); );
const history = useSessionHistory(active?.sessionId, active?.entries ?? NO_ENTRIES, paired); const history = useSessionHistory(
active?.sessionId,
active?.entries ?? NO_ENTRIES,
paired,
active?.workspaceId ?? workspaceId,
);
const models = useChatModels(workspaceId, paired); const models = useChatModels(workspaceId, paired);
const workspace = workspaces.find((item) => item.workspaceId === workspaceId); const workspace = workspaces.find((item) => item.workspaceId === workspaceId);
// pi2.nvim's placeholder vocabulary, and the display title of the routed
// session: name → first message → `(unnamed)`. Never the session id.
const titlePhrases = useMemo(
() => ({ unnamed: t("chat.sessionUnnamed"), subagentUnnamed: t("chat.subagentUnnamed") }),
[t],
);
// Patch the window title from the routed session's display title: name →
// first message → nothing (an unnamed session keeps the page title).
const activeTitle = useMemo(
() => (active ? sessionTitle(active, titlePhrases) : null),
[active, titlePhrases],
);
const filter = useChatStore((state) => state.filter); const filter = useChatStore((state) => state.filter);
const setFilter = useChatStore((state) => state.setFilter); const setFilter = useChatStore((state) => state.setFilter);
@@ -218,9 +236,11 @@ function ChatExperience({ sessionId }: { sessionId?: string }) {
}, [activeSubagentId, closeDrawers, rowMenuId, setRowMenuId, setWsMenuOpen, treeOpen, trayOpen]); }, [activeSubagentId, closeDrawers, rowMenuId, setRowMenuId, setWsMenuOpen, treeOpen, trayOpen]);
useEffect(() => { useEffect(() => {
const title = active?.name?.trim() || (sessionMissing ? t("errors.sessionNotFound") : t("nav.chat")); // A placeholder title is not a title for the window chrome.
const fallback = sessionMissing ? t("errors.sessionNotFound") : t("nav.chat");
const title = activeTitle && !activeTitle.provisional ? activeTitle.text : fallback;
document.title = `${title} — pi2.nvim`; document.title = `${title} — pi2.nvim`;
}, [active?.name, sessionMissing, t]); }, [activeTitle, sessionMissing, t]);
// The optimistic "sending" chip disappears when the authoritative user // The optimistic "sending" chip disappears when the authoritative user
// entry arrives (via entry_appended) or after a safety timeout. // entry arrives (via entry_appended) or after a safety timeout.
@@ -446,7 +466,7 @@ function ChatExperience({ sessionId }: { sessionId?: string }) {
async function closeSession(session: SessionState) { async function closeSession(session: SessionState) {
await exec(chatCommands.closeSession(session.sessionId), "chat.closedProcess", { await exec(chatCommands.closeSession(session.sessionId), "chat.closedProcess", {
name: session.name ?? session.sessionId, name: sessionTitle(session, titlePhrases).text,
}); });
setClosing(null); setClosing(null);
} }
@@ -518,7 +538,7 @@ function ChatExperience({ sessionId }: { sessionId?: string }) {
<StatusDot status={sessionDot(active)} title={t(`state.${sessionStatusKey(active)}`)} /> <StatusDot status={sessionDot(active)} title={t(`state.${sessionStatusKey(active)}`)} />
) : null} ) : null}
<h2 className="stream-name truncate" tabIndex={-1} ref={streamNameRef}> <h2 className="stream-name truncate" tabIndex={-1} ref={streamNameRef}>
{active?.name?.trim() || (active ? active.sessionId : (workspace?.name ?? t("nav.chat")))} {active ? activeTitle?.text : (workspace?.name ?? t("nav.chat"))}
</h2> </h2>
{active?.flags.attention && active.attention.length ? ( {active?.flags.attention && active.attention.length ? (
<Badge tone="warn">{t("chat.pending", { n: active.attention.length })}</Badge> <Badge tone="warn">{t("chat.pending", { n: active.attention.length })}</Badge>
@@ -753,8 +773,8 @@ function ChatExperience({ sessionId }: { sessionId?: string }) {
title={renaming?.kind === "session" ? t("chat.renameSession") : t("chat.renameSubagentAria")} title={renaming?.kind === "session" ? t("chat.renameSession") : t("chat.renameSubagentAria")}
initial={ initial={
renaming?.kind === "session" renaming?.kind === "session"
? (renaming.session.name ?? renaming.session.sessionId) ? (renaming.session.name ?? "")
: (renaming?.subagent.name ?? renaming?.subagent.id ?? "") : (renaming?.subagent.name ?? "")
} }
hint={ hint={
renaming?.kind === "session" ? t("chat.renameSessionHint") : t("chat.renameSubagentHint") renaming?.kind === "session" ? t("chat.renameSessionHint") : t("chat.renameSubagentHint")
@@ -770,7 +790,7 @@ function ChatExperience({ sessionId }: { sessionId?: string }) {
}} }}
title={t("chat.closeProcess")} title={t("chat.closeProcess")}
description={ description={
closing ? t("chat.closeSessionText", { name: closing.name ?? closing.sessionId }) : undefined closing ? t("chat.closeSessionText", { name: sessionTitle(closing, titlePhrases).text }) : undefined
} }
confirmLabel={t("chat.closeProcess")} confirmLabel={t("chat.closeProcess")}
danger danger
+2 -2
View File
@@ -31,7 +31,7 @@ import { mergeTasks,
type DevicesResponse, type DevicesResponse,
type StatusTask, type StatusTask,
} from "@/features/status/queries"; } from "@/features/status/queries";
import { deriveServerIdentity, type InfoExtras } from "@/features/status/server"; import { deriveServerIdentity, resolveServerStatus, type InfoExtras } from "@/features/status/server";
import { ServerInfoCard } from "@/features/status/server-info-card"; import { ServerInfoCard } from "@/features/status/server-info-card";
import { TasksCard } from "@/features/status/tasks-card"; import { TasksCard } from "@/features/status/tasks-card";
import { partitionWorkspaces } from "@/features/workspaces/visibility"; import { partitionWorkspaces } from "@/features/workspaces/visibility";
@@ -91,7 +91,7 @@ export function StatusPage() {
wsState, wsState,
fetchedAt: info.dataUpdatedAt || null, fetchedAt: info.dataUpdatedAt || null,
nameFallback: storedServer?.name || meta?.server?.name, nameFallback: storedServer?.name || meta?.server?.name,
status: info.isError ? "offline" : healthOk === false ? "degraded" : undefined, status: resolveServerStatus({ paired, info: info.data, infoError: info.isError, healthOk }),
}); });
// Background tasks: the live store covers open sessions, the REST session // Background tasks: the live store covers open sessions, the REST session
+6
View File
@@ -1,5 +1,6 @@
import { create } from "zustand"; import { create } from "zustand";
import type { ServerStatusValue } from "@/features/status/server";
import type { InfoResponse } from "@/lib/api"; import type { InfoResponse } from "@/lib/api";
import { getDeviceToken, setDeviceToken } from "@/lib/api"; import { getDeviceToken, setDeviceToken } from "@/lib/api";
import type { WsConnectionState } from "@/lib/ws"; import type { WsConnectionState } from "@/lib/ws";
@@ -43,6 +44,7 @@ export interface ConnectionStore {
connectedAt: number; connectedAt: number;
token: string | null; token: string | null;
server: InfoResponse | null; server: InfoResponse | null;
serverStatus: ServerStatusValue;
wsState: WsConnectionState; wsState: WsConnectionState;
isPaired: () => boolean; isPaired: () => boolean;
@@ -50,6 +52,7 @@ export interface ConnectionStore {
connect: (options?: { endpoint?: string; deviceName?: string; token?: string | null }) => void; connect: (options?: { endpoint?: string; deviceName?: string; token?: string | null }) => void;
disconnect: () => void; disconnect: () => void;
setServer: (server: InfoResponse | null) => void; setServer: (server: InfoResponse | null) => void;
setServerStatus: (status: ServerStatusValue) => void;
setWsState: (state: WsConnectionState) => void; setWsState: (state: WsConnectionState) => void;
setToken: (token: string | null) => void; setToken: (token: string | null) => void;
} }
@@ -62,6 +65,7 @@ function initialState() {
connectedAt: Number(read(CONNECTED_AT_KEY)) || 0, connectedAt: Number(read(CONNECTED_AT_KEY)) || 0,
token: getDeviceToken(), token: getDeviceToken(),
server: null as InfoResponse | null, server: null as InfoResponse | null,
serverStatus: "unknown" as ServerStatusValue,
wsState: "idle" as WsConnectionState, wsState: "idle" as WsConnectionState,
}; };
} }
@@ -102,11 +106,13 @@ export const useConnectionStore = create<ConnectionStore>((set, get) => ({
connectedAt: 0, connectedAt: 0,
token: null, token: null,
server: null, server: null,
serverStatus: "unknown",
wsState: "idle", wsState: "idle",
}); });
}, },
setServer: (server) => set({ server }), setServer: (server) => set({ server }),
setServerStatus: (serverStatus) => set({ serverStatus }),
setWsState: (wsState) => set({ wsState }), setWsState: (wsState) => set({ wsState }),
setToken: (token) => { setToken: (token) => {
setDeviceToken(token); setDeviceToken(token);
+51 -4
View File
@@ -311,7 +311,8 @@
height: 11px; height: 11px;
} }
/* 行:单行 = 折叠箭头 + 主按钮(点 + 名称 + !N)+ 行操作「…」 */ /* 行:单行 = 折叠箭头 + 主按钮(点 + 名称 + !N)+ 行操作「…」
pi2.nvim 的 :PiSessions 不做淡入淡出:hover / 选中态瞬时切换。 */
.tree-row { .tree-row {
display: flex; display: flex;
align-items: center; align-items: center;
@@ -319,7 +320,6 @@
min-height: 32px; min-height: 32px;
padding: 0; padding: 0;
border-radius: var(--radius-sm); border-radius: var(--radius-sm);
transition: background var(--dur-fast) var(--ease-out);
} }
.tree-row:hover { .tree-row:hover {
background: var(--surface-1); background: var(--surface-1);
@@ -355,6 +355,21 @@
flex: 1 1 auto; flex: 1 1 auto;
min-width: 0; min-width: 0;
} }
/* 没有名字的会话:pi2.nvim 的占位样式(comment 色 + 斜体),静止不动。 */
.tree-row .t-name.is-unnamed,
.tree-row .t-name.is-generating {
color: var(--faint);
font-style: italic;
}
/* 自动命名中的 120ms 盲文 spinner:前缀占位,由 JS 驱动帧,CSS 不参与动画。 */
.tree-row .t-spinner {
flex: none;
width: 1ch;
color: var(--faint);
font-family: var(--font-mono);
font-size: var(--fs-sm);
line-height: 1;
}
.tree-row .t-attn { .tree-row .t-attn {
flex: none; flex: none;
font-size: var(--fs-2xs); font-size: var(--fs-2xs);
@@ -389,7 +404,6 @@
} }
.tree-toggle.open svg { .tree-toggle.open svg {
transform: rotate(90deg); transform: rotate(90deg);
transition: transform var(--dur-fast) var(--ease-out);
} }
.tree-toggle.leaf { .tree-toggle.leaf {
visibility: hidden; visibility: hidden;
@@ -400,7 +414,6 @@
width: 22px; width: 22px;
height: 22px; height: 22px;
opacity: 0; opacity: 0;
transition: opacity var(--dur-fast) var(--ease-out);
} }
.tree-row:hover .t-more, .tree-row:hover .t-more,
.tree-row:focus-within .t-more, .tree-row:focus-within .t-more,
@@ -432,6 +445,40 @@
background: color-mix(in oklch, var(--destructive) 12%, transparent); background: color-mix(in oklch, var(--destructive) 12%, transparent);
} }
/* 状态圆点:pi2.nvim 是离散二值闪烁(busy/error 500ms、compacting 1000ms),
不是 app.css 里那种平滑 ease 的 pulse;attention / idle / ok / exited 常亮。
只作用于会话树,其他页面的圆点保持不变。 */
@keyframes tree-dot-blink {
0%,
49% {
opacity: 1;
}
50%,
100% {
opacity: 0.35;
}
}
.tree-row .dot--busy,
.tree-row .dot--err {
animation: tree-dot-blink 1s steps(1, end) infinite;
}
.tree-row .dot--compacting {
animation: tree-dot-blink 2s steps(1, end) infinite;
}
.tree-row .dot--attention,
.tree-row .dot--idle,
.tree-row .dot--ok,
.tree-row .dot--exited {
animation: none;
}
@media (prefers-reduced-motion: reduce) {
.tree-row .dot--busy,
.tree-row .dot--err,
.tree-row .dot--compacting {
animation: none;
}
}
/* 子会话 / 子代理行:更矮、更小、灰一档;状态只由圆点表达。 */ /* 子会话 / 子代理行:更矮、更小、灰一档;状态只由圆点表达。 */
.tree-row--sub .tree-row__main { .tree-row--sub .tree-row__main {
height: 30px; height: 30px;
+77
View File
@@ -0,0 +1,77 @@
import { afterEach, describe, expect, it } from "vitest";
import { fetchEntriesPage, HISTORY_PAGE_SIZE, setSessionMeta } from "@/features/chat/history";
import { mockApi } from "./helpers/api-mock";
const ENTRIES_PATH = /^\/api\/v1\/sessions\/[^/]+\/entries$/;
function page(entries: unknown[] = [], cursor: Record<string, unknown> = { hasMore: false }) {
return { status: 200, body: { entries, cursor } };
}
afterEach(() => {
// `sessionMeta` is module state; keep each case's rows isolated.
for (const id of ["s-hint", "s-meta", "s-cursor", "s-response"]) {
setSessionMeta(id, { workspaceId: undefined, sessionFile: undefined });
}
});
describe("history page request", () => {
it("routes with the caller's workspace hint and the row's session file", async () => {
setSessionMeta("s-hint", { workspaceId: "ws-meta", sessionFile: "/tmp/s-hint.jsonl" });
const fetchMock = mockApi([{ path: ENTRIES_PATH, handler: () => page() }]);
await fetchEntriesPage("s-hint", { workspaceId: "ws-page" });
const url = new URL(String(fetchMock.mock.calls[0]?.[0]), "http://localhost");
expect(url.pathname).toBe("/api/v1/sessions/s-hint/entries");
// The page's workspace wins: it is known before the list effect lands.
expect(url.searchParams.get("workspaceId")).toBe("ws-page");
expect(url.searchParams.get("sessionFile")).toBe("/tmp/s-hint.jsonl");
expect(url.searchParams.get("limit")).toBe(String(HISTORY_PAGE_SIZE));
expect(url.searchParams.has("before")).toBe(false);
});
it("falls back to the row's workspace when the caller has none", async () => {
setSessionMeta("s-meta", { workspaceId: "ws-meta" });
const fetchMock = mockApi([{ path: ENTRIES_PATH, handler: () => page() }]);
await fetchEntriesPage("s-meta", {});
const url = new URL(String(fetchMock.mock.calls[0]?.[0]), "http://localhost");
expect(url.searchParams.get("workspaceId")).toBe("ws-meta");
expect(url.searchParams.has("sessionFile")).toBe(false);
});
it("forwards the before cursor for older pages", async () => {
const fetchMock = mockApi([{ path: ENTRIES_PATH, handler: () => page() }]);
await fetchEntriesPage("s-cursor", { before: "e9", limit: 25, workspaceId: "ws-page" });
const url = new URL(String(fetchMock.mock.calls[0]?.[0]), "http://localhost");
expect(url.searchParams.get("before")).toBe("e9");
expect(url.searchParams.get("limit")).toBe("25");
});
it("projects raw entries and keeps the plugin's cursor", async () => {
mockApi([
{
path: ENTRIES_PATH,
handler: () =>
page(
[
{
type: "message",
id: "u1",
message: { role: "user", content: "hi", timestamp: 1_733_234_400_000 },
},
],
{ before: "u1", hasMore: true },
),
},
]);
const result = await fetchEntriesPage("s-response", { workspaceId: "ws-page" });
expect(result.entries.map((entry) => entry.id)).toEqual(["u1"]);
expect(result.entries[0]?.role).toBe("user");
expect(result.cursor).toEqual({ before: "u1", hasMore: true });
});
});
+108
View File
@@ -338,3 +338,111 @@ describe("chat message stream — layout contract", () => {
expect(css).toMatch(/@media \(prefers-reduced-motion: reduce\)/); expect(css).toMatch(/@media \(prefers-reduced-motion: reduce\)/);
}); });
}); });
/* ------------------------------------------------------------------ */
/* Auto-follow: content growth must never look like a user scroll. */
/* ------------------------------------------------------------------ */
describe("chat message stream — auto-follow", () => {
/**
* jsdom has no layout: give the scroll container a fake viewport so the
* distance heuristic can be exercised (2000px of content, 600px visible).
*/
function renderWithViewport(props: Partial<MessageStreamProps> = {}) {
const utils = renderStream(props);
const scroll = utils.container.querySelector<HTMLElement>(".stream-scroll");
if (!scroll) throw new Error("the chat layout did not render a stream scroll");
const box = { top: 0, height: 2000, client: 600 };
Object.defineProperty(scroll, "scrollHeight", { configurable: true, get: () => box.height });
Object.defineProperty(scroll, "clientHeight", { configurable: true, get: () => box.client });
Object.defineProperty(scroll, "scrollTop", {
configurable: true,
get: () => box.top,
set: (value: number) => {
box.top = value;
},
});
const scrollTo = vi.fn((options?: ScrollToOptions) => {
box.top = Number(options?.top ?? box.height);
});
(scroll as unknown as { scrollTo: typeof scrollTo }).scrollTo = scrollTo;
const latest = () => utils.container.querySelector(".fab--latest.is-visible");
return { ...utils, scroll, box, scrollTo, latest };
}
it("keeps following when the stream grew under the viewport (no user input)", () => {
const { scroll, box, latest } = renderWithViewport();
// The virtualizer measured taller items after the pin: the scroll
// position is now far from the bottom, but nobody scrolled.
box.top = 900;
fireEvent.scroll(scroll);
expect(latest()).toBeNull();
// An explicit wheel up that moves the view up does stop following.
fireEvent.wheel(scroll, { deltaY: -120 });
box.top = 800;
fireEvent.scroll(scroll);
expect(latest()).not.toBeNull();
// Returning to the bottom (by wheel) re-arms it.
fireEvent.wheel(scroll, { deltaY: 4000 });
box.top = box.height - box.client;
fireEvent.scroll(scroll);
expect(latest()).toBeNull();
});
it("re-pins to the newest item on every content resize while following", () => {
const observed: (() => void)[] = [];
const original = globalThis.ResizeObserver;
class RecordingObserver {
constructor(callback: () => void) {
observed.push(callback);
}
observe(): void {}
unobserve(): void {}
disconnect(): void {}
}
globalThis.ResizeObserver = RecordingObserver as unknown as typeof ResizeObserver;
try {
const { box, scrollTo } = renderWithViewport();
expect(observed.length).toBeGreaterThan(0);
box.height = 3200;
for (const callback of observed) callback();
expect(scrollTo).toHaveBeenCalled();
expect(box.top).toBe(3200);
} finally {
globalThis.ResizeObserver = original;
}
});
it("stops re-pinning once the user scrolled away", () => {
const observed: (() => void)[] = [];
const original = globalThis.ResizeObserver;
class RecordingObserver {
constructor(callback: () => void) {
observed.push(callback);
}
observe(): void {}
unobserve(): void {}
disconnect(): void {}
}
globalThis.ResizeObserver = RecordingObserver as unknown as typeof ResizeObserver;
try {
const { scroll, box, scrollTo, latest } = renderWithViewport();
fireEvent.wheel(scroll, { deltaY: -200 });
box.top = 400;
fireEvent.scroll(scroll);
expect(latest()).not.toBeNull();
scrollTo.mockClear();
box.height = 3600;
for (const callback of observed) callback();
expect(scrollTo).not.toHaveBeenCalled();
} finally {
globalThis.ResizeObserver = original;
}
});
});
+79 -3
View File
@@ -510,10 +510,12 @@ function workspaceBody() {
} }
function sessionsBody() { function sessionsBody() {
// Two live tabs. `tab` is the plugin's live projection of `attached_tab`;
// without it a row is disk history, not a tab.
return { return {
sessions: [ sessions: [
{ sessionId: "s1", name: "Alpha", workspaceId: "W1", cwd: "/work/w1", status: "idle" }, { sessionId: "s1", name: "Alpha", workspaceId: "W1", cwd: "/work/w1", status: "idle", tab: 1, live: true },
{ sessionId: "s2", name: "Beta", workspaceId: "W1", cwd: "/work/w1", status: "busy" }, { sessionId: "s2", name: "Beta", workspaceId: "W1", cwd: "/work/w1", status: "busy", tab: 2, live: true },
], ],
}; };
} }
@@ -531,7 +533,16 @@ function subSessionBody() {
parentId: "s1", parentId: "s1",
visible: false, visible: false,
}, },
{ sessionId: "s1", name: "Alpha", workspaceId: "W1", cwd: "/work/w1", status: "idle", visible: true }, {
sessionId: "s1",
name: "Alpha",
workspaceId: "W1",
cwd: "/work/w1",
status: "idle",
visible: true,
tab: 1,
live: true,
},
], ],
}; };
} }
@@ -724,3 +735,68 @@ describe("chat session deep link", () => {
expect(await screen.findByTestId("session-not-found")).toBeInTheDocument(); expect(await screen.findByTestId("session-not-found")).toBeInTheDocument();
}); });
}); });
/* ------------------------------------------------------------------ */
/* The list is the nvim tab set, not the workspace's JSONL history. */
/* ------------------------------------------------------------------ */
/** What `workspace.query{kind:"sessions"}` answers: live tabs ∪ every JSONL on disk. */
function mixedBody() {
return {
sessions: [
{ sessionId: "hist", name: "Yesterday", workspaceId: "W1", cwd: "/work/w1", status: "done", modified: 2 },
{
sessionId: "s1",
name: "Alpha",
workspaceId: "W1",
cwd: "/work/w1",
status: "idle",
tab: 1,
live: true,
},
],
};
}
describe("chat session list mirrors the nvim tabs", () => {
beforeEach(() => {
useSessionsStore.getState().reset();
useChatStore.setState({ history: {}, sending: null });
silentSocket();
});
afterEach(() => {
vi.unstubAllGlobals();
});
it("renders the tab-backed session and never a disk-only historical row", async () => {
mockApi([
{ path: "/api/v1/workspaces", handler: () => ({ body: workspaceBody() }) },
{ path: "/api/v1/workspaces/W1/sessions", handler: () => ({ body: mixedBody() }) },
{ path: "/api/v1/models", handler: () => ({ body: [] }) },
{ path: /^\/api\/v1\/sessions\/s1\/entries/, handler: () => ({ body: entriesBody("Alpha first message") }) },
]);
await renderPage(chatRoutes(), "/chat?workspace=W1");
expect(await screen.findByText("Alpha first message")).toBeInTheDocument();
await waitFor(() => expect(document.querySelector('[data-session-id="s1"]')).not.toBeNull());
expect(document.querySelector('[data-session-id="hist"]')).toBeNull();
expect(screen.queryByText("Yesterday")).toBeNull();
});
it("answers a deep link into history with not-found and no composer", async () => {
const fetchMock = mockApi([
{ path: "/api/v1/workspaces", handler: () => ({ body: workspaceBody() }) },
{ path: "/api/v1/workspaces/W1/sessions", handler: () => ({ body: mixedBody() }) },
{ path: "/api/v1/models", handler: () => ({ body: [] }) },
]);
await renderPage(chatRoutes(), "/chat/hist?workspace=W1");
expect(await screen.findByTestId("session-not-found")).toBeInTheDocument();
// A historical row has no live owner: replying must not be offered.
expect(within(streamPane()).queryByLabelText("Message input")).toBeNull();
expect(requestedUrls(fetchMock).some((url) => url.includes("/sessions/hist/entries"))).toBe(false);
});
});
+114
View File
@@ -0,0 +1,114 @@
import { act } from "@testing-library/react";
import { beforeEach, describe, expect, it } from "vitest";
import { renderPage, type TestRoute } from "./helpers/render-page";
import { ServerChip } from "@/components/shared/server-chip";
import type { InfoResponse } from "@/lib/api";
import { setLanguage } from "@/lib/i18n";
import { useConnectionStore } from "@/stores/connection";
/** Realistic daemon /info response payload without `status` field. */
const realisticInfo: InfoResponse = {
v: 1,
daemonId: "daemon-test-1",
machineId: "machine-test-1",
platform: "linux",
hostname: "devbook-eos",
os: "Linux 6.12.0",
version: "0.1.3",
uptimeMs: 123456,
port: 7676,
capabilities: ["read", "steer"],
limits: { maxInstances: 5 },
};
const routes = (): TestRoute[] => [
{
path: "/",
component: () => <ServerChip />,
},
{
path: "/status",
component: () => <div>Status Page</div>,
},
];
describe("ServerChip", () => {
beforeEach(() => {
setLanguage("en");
useConnectionStore.getState().disconnect();
useConnectionStore.getState().connect({ endpoint: "http://127.0.0.1:7676" });
});
it("renders dot--ok and Online in English / 在线 in Chinese when serverStatus is online with status-less info payload", async () => {
// Explicitly assert that realisticInfo does not contain a wire `status` field.
expect("status" in realisticInfo).toBe(false);
const { container } = await renderPage(routes(), "/", { paired: true });
act(() => {
const store = useConnectionStore.getState();
store.setServer(realisticInfo);
store.setServerStatus("online");
});
const dot = container.querySelector(".server-chip .dot");
expect(dot).not.toBeNull();
expect(dot).toHaveClass("dot--ok");
expect(dot).not.toHaveClass("dot--exited");
expect(dot?.getAttribute("title")).toBe("Online");
expect(dot?.getAttribute("aria-label")).toBe("Online");
// Verify Chinese localization
act(() => {
setLanguage("zh");
});
expect(dot?.getAttribute("title")).toBe("在线");
expect(dot?.getAttribute("aria-label")).toBe("在线");
});
it("renders dot--idle and Unknown / 未知 when serverStatus is unknown", async () => {
const { container } = await renderPage(routes(), "/", { paired: true });
act(() => {
const store = useConnectionStore.getState();
store.setServer(realisticInfo);
store.setServerStatus("unknown");
});
const dot = container.querySelector(".server-chip .dot");
expect(dot).not.toBeNull();
expect(dot).toHaveClass("dot--idle");
expect(dot?.getAttribute("title")).toBe("Unknown");
expect(dot?.getAttribute("aria-label")).toBe("Unknown");
act(() => {
setLanguage("zh");
});
expect(dot?.getAttribute("title")).toBe("未知");
expect(dot?.getAttribute("aria-label")).toBe("未知");
});
it("renders dot--exited and Offline / 离线 when serverStatus is offline", async () => {
const { container } = await renderPage(routes(), "/", { paired: true });
act(() => {
const store = useConnectionStore.getState();
store.setServer(realisticInfo);
store.setServerStatus("offline");
});
const dot = container.querySelector(".server-chip .dot");
expect(dot).not.toBeNull();
expect(dot).toHaveClass("dot--exited");
expect(dot?.getAttribute("title")).toBe("Offline");
expect(dot?.getAttribute("aria-label")).toBe("Offline");
act(() => {
setLanguage("zh");
});
expect(dot?.getAttribute("title")).toBe("离线");
expect(dot?.getAttribute("aria-label")).toBe("离线");
});
});
+97
View File
@@ -0,0 +1,97 @@
import { describe, expect, it } from "vitest";
import { resolveServerStatus, type ServerStatusInput } from "@/features/status/server";
import type { InfoResponse } from "@/lib/api";
/** Exact real payload shape from the daemon: no `status` field present. */
const realisticInfo: InfoResponse = {
v: 1,
daemonId: "daemon-test-1",
machineId: "machine-test-1",
platform: "linux",
hostname: "devbook-eos",
os: "Linux 6.12.0",
version: "0.1.3",
uptimeMs: 123456,
port: 7676,
capabilities: ["read", "steer"],
limits: { maxInstances: 5 },
};
describe("resolveServerStatus", () => {
it("resolves unpaired client to offline", () => {
const input: ServerStatusInput = {
paired: false,
info: realisticInfo,
healthOk: true,
};
expect(resolveServerStatus(input)).toBe("offline");
expect(resolveServerStatus({ paired: false })).toBe("offline");
});
it("resolves infoError to offline", () => {
const input: ServerStatusInput = {
paired: true,
infoError: true,
healthOk: true,
};
expect(resolveServerStatus(input)).toBe("offline");
});
it("resolves info present + healthOk === false to degraded", () => {
const input: ServerStatusInput = {
paired: true,
info: realisticInfo,
healthOk: false,
};
expect(resolveServerStatus(input)).toBe("degraded");
});
it("resolves info present in exact real payload shape (no status field) to online", () => {
// Assert property absence so the regression contract is explicitly guarded.
expect("status" in realisticInfo).toBe(false);
expect(
resolveServerStatus({
paired: true,
info: realisticInfo,
}),
).toBe("online");
expect(
resolveServerStatus({
paired: true,
info: realisticInfo,
healthOk: true,
}),
).toBe("online");
});
it("resolves nothing yet to unknown", () => {
expect(
resolveServerStatus({
paired: true,
}),
).toBe("unknown");
});
it("resolves paired with info: null, healthOk: true to unknown", () => {
expect(
resolveServerStatus({
paired: true,
info: null,
healthOk: true,
}),
).toBe("unknown");
});
it("resolves paired with info: null, healthOk: null to unknown", () => {
expect(
resolveServerStatus({
paired: true,
info: null,
healthOk: null,
}),
).toBe("unknown");
});
});
+98
View File
@@ -0,0 +1,98 @@
import { describe, expect, it } from "vitest";
import { normalizeSessionsPayload, tabSessionRows } from "@/features/chat/session-state";
/**
* `workspace.query{kind:"sessions"}` rows come from the plugin as a union of the
* workspace's JSONL history and its live sessions. Only the tab-backed component
* is the nvim session list; everything else is history.
*/
function ids(rows: Record<string, unknown>[]): string[] {
return rows.map((row) => String(row.sessionId ?? row.session_id ?? row.id));
}
describe("tabSessionRows", () => {
it("drops disk-only history and keeps the tab-backed row", () => {
const raw = {
sessions: [
{ sessionId: "old-1", name: "history one", status: "done" },
{ sessionId: "tab-1", name: "the only tab", tab: 1, live: true, status: "idle" },
{ sessionId: "old-2", name: "history two" },
],
};
expect(ids(tabSessionRows(raw))).toEqual(["tab-1"]);
});
it("drops a live session that owns no tab", () => {
// A detached background session is not an nvim tab: `:PiSessions` renders
// it as a child row, never as a root.
const raw = {
sessions: [
{ sessionId: "tab-1", tab: 1, live: true },
{ sessionId: "detached", live: true, status: "busy" },
],
};
expect(ids(tabSessionRows(raw))).toEqual(["tab-1"]);
});
it("keeps the sub-sessions linked to a tab, at any depth", () => {
const raw = {
sessions: [
{ sessionId: "child", parentId: "tab-1", status: "interrupted" },
{ sessionId: "grandchild", parentId: "child", status: "done" },
{ sessionId: "tab-1", tab: 1, live: true },
{ sessionId: "orphan-history", parentId: "gone", status: "done" },
],
};
expect(ids(tabSessionRows(raw))).toEqual(["child", "grandchild", "tab-1"]);
});
it("keeps the parent row when the tab is in a child view", () => {
// `view_parent_id`: the tab is attached to the child session, the parent
// row anchors the tree and its other children stay in the list.
const raw = {
sessions: [
{ sessionId: "root", live: true, status: "idle" },
{ sessionId: "viewed-child", parentId: "root", tab: 2, live: true },
{ sessionId: "sibling", parentId: "root", status: "completed" },
],
};
expect(ids(tabSessionRows(raw))).toEqual(["root", "viewed-child", "sibling"]);
});
it("accepts a bare array payload and the snake_case aliases", () => {
const raw = [
{ session_id: "old" },
{ session_id: "child", parent_id: "tab-1" },
{ session_id: "tab-1", tab: 3 },
];
expect(ids(tabSessionRows(raw))).toEqual(["child", "tab-1"]);
});
it("returns no rows when nothing is attached to a tab", () => {
expect(tabSessionRows({ sessions: [{ sessionId: "old-1" }, { sessionId: "old-2" }] })).toEqual([]);
expect(tabSessionRows({ sessions: [] })).toEqual([]);
expect(tabSessionRows(undefined)).toEqual([]);
});
it("feeds the render states so a historical row never reaches the tree", () => {
const states = normalizeSessionsPayload(
tabSessionRows({
sessions: [
{ sessionId: "old-1", name: "history", status: "done" },
{ sessionId: "tab-1", name: "the only tab", tab: 1, live: true, status: "idle" },
],
}),
"w1",
);
expect(states.map((state) => state.sessionId)).toEqual(["tab-1"]);
expect(states[0]?.name).toBe("the only tab");
});
});
+74
View File
@@ -0,0 +1,74 @@
import { describe, expect, it } from "vitest";
import { FALLBACK_NAME_CHARS, sessionTitle, subagentTitle } from "@/features/chat/session-title";
const phrases = { unnamed: "(unnamed)", subagentUnnamed: "sub-session" };
describe("sessionTitle", () => {
it("prefers the session's own name", () => {
expect(sessionTitle({ name: "Fix login", firstMessage: "hello" }, phrases)).toEqual({
text: "Fix login",
kind: "name",
provisional: false,
spinner: false,
});
});
it("trims the name and falls through when it is blank", () => {
expect(sessionTitle({ name: " Fix login " }, phrases).text).toBe("Fix login");
expect(sessionTitle({ name: " ", firstMessage: "hello" }, phrases).text).toBe("hello");
expect(sessionTitle({ name: "", firstMessage: "" }, phrases).text).toBe("(unnamed)");
});
it("falls back to the first user message (pi2.nvim's first_message)", () => {
expect(sessionTitle({ name: null, firstMessage: " Fix the auth bug " }, phrases)).toEqual({
text: "Fix the auth bug",
kind: "first-message",
provisional: false,
spinner: false,
});
});
it("shows (unnamed) when nothing is known — never an id", () => {
const title = sessionTitle({ name: null, firstMessage: null }, phrases);
expect(title).toEqual({ text: "(unnamed)", kind: "unnamed", provisional: true, spinner: false });
});
it("suppresses the first message and spins while the backend generates a title", () => {
expect(sessionTitle({ name: null, firstMessage: "Fix the auth bug", titleGenerating: true }, phrases)).toEqual({
text: "(unnamed)",
kind: "generating",
provisional: true,
spinner: true,
});
});
it("drops the spinner the moment a real name arrives", () => {
const title = sessionTitle({ name: "Fix login", titleGenerating: true }, phrases);
expect(title.kind).toBe("name");
expect(title.spinner).toBe(false);
});
});
describe("subagentTitle", () => {
it("prefers the sub-session name", () => {
expect(subagentTitle({ name: "researcher", task: "Research the auth flow" }, phrases).text).toBe("researcher");
});
it("derives the name from the task prompt, capped like Manifest.fallback_name", () => {
const task = "x".repeat(FALLBACK_NAME_CHARS + 25);
const title = subagentTitle({ name: null, task }, phrases);
expect(title.text).toBe("x".repeat(FALLBACK_NAME_CHARS));
expect(title.kind).toBe("task");
expect(FALLBACK_NAME_CHARS).toBe(40);
});
it("falls back to sub-session — never the subagent id", () => {
expect(subagentTitle({ name: " ", task: "" }, phrases)).toEqual({
text: "sub-session",
kind: "unnamed",
provisional: true,
spinner: false,
});
});
});
+140
View File
@@ -0,0 +1,140 @@
import { render, screen } from "@testing-library/react";
import type { ComponentProps } from "react";
import { beforeAll, describe, expect, it, vi } from "vitest";
import { SessionTree } from "@/features/chat/session-tree";
import { setLanguage } from "@/lib/i18n";
import type { SessionState } from "@/lib/protocol";
import { sessionFixture, subagentFixture } from "./chat-fixtures";
beforeAll(async () => {
await setLanguage("en");
});
/** The title of the row for `sessionId` (`null` when the row is absent). */
function rowTitleText(container: HTMLElement, sessionId: string): string | null {
const row = container.querySelector<HTMLElement>(`[data-session-id="${sessionId}"]`);
return row?.querySelector<HTMLElement>(".t-name")?.textContent?.trim() ?? null;
}
function renderTree(overrides: Partial<ComponentProps<typeof SessionTree>> = {}) {
const sessions = overrides.sessions ?? [];
return render(
<SessionTree
sessions={sessions}
workspaces={[
{
workspaceId: "W1",
cwd: "/work/w1",
name: "W1",
trusted: true,
exists: true,
sessionCount: sessions.length,
liveCount: 0,
lastActiveAt: 0,
instance: null,
},
]}
activeWorkspaceId="W1"
selectedId={null}
activeSubagentId={null}
filter=""
collapsed={{}}
activeOnly={false}
showHidden={false}
connected
creating={false}
onFilter={vi.fn()}
onToggleCollapse={vi.fn()}
onToggleAll={vi.fn()}
onToggleActiveOnly={vi.fn()}
onToggleShowHidden={vi.fn()}
onSelectSession={vi.fn()}
onSelectWorkspace={vi.fn()}
onSelectSubagent={vi.fn()}
onNewSession={vi.fn()}
onRenameSession={vi.fn()}
onCloseSession={vi.fn()}
onDispatchSubagent={vi.fn()}
onRenameSubagent={vi.fn()}
{...overrides}
/>,
);
}
describe("session list titles (pi2.nvim parity)", () => {
it("renders (unnamed) for a session without a name and never the session id", () => {
const sessionId = "9f8c1d2e-0000-4000-8000-aaaaaaaaaaaa";
const { container } = renderTree({
sessions: [sessionFixture({ sessionId, name: null, firstMessage: null })],
});
expect(rowTitleText(container, sessionId)).toBe("(unnamed)");
expect(container.textContent ?? "").not.toContain(sessionId);
// Identity still rides on the DOM attribute (routing/select handlers).
expect(container.querySelector(`[data-session-id="${sessionId}"]`)).not.toBeNull();
});
it("marks the placeholder so it renders as the muted, non-animated state", () => {
const sessionId = "s-unnamed";
const { container } = renderTree({
sessions: [sessionFixture({ sessionId, name: null, firstMessage: null })],
});
const name = container.querySelector<HTMLElement>(`[data-session-id="${sessionId}"] .t-name`);
expect(name?.classList.contains("is-unnamed")).toBe(true);
expect(name?.classList.contains("is-generating")).toBe(false);
});
it("prefers the first user message over the placeholder", () => {
const sessionId = "s-first";
const { container } = renderTree({
sessions: [sessionFixture({ sessionId, name: null, firstMessage: "Fix the auth bug" })],
});
expect(rowTitleText(container, sessionId)).toBe("Fix the auth bug");
});
it("keeps (unnamed) and prefixes the braille spinner while a title is generated", () => {
const sessionId = "s-generating";
// The plugin's `pi-title` status is not on the wire yet, so the flag is
// injected here: the row must already react the way pi2.nvim does.
const session = {
...sessionFixture({ sessionId, name: null, firstMessage: "Fix the auth bug" }),
titleGenerating: true,
} as SessionState;
const { container } = renderTree({ sessions: [session] });
const row = container.querySelector<HTMLElement>(`[data-session-id="${sessionId}"]`);
// Spinner is a prefix, the name stays the placeholder (no first message).
expect(row?.querySelector(".t-spinner")).not.toBeNull();
expect(rowTitleText(container, sessionId)).toBe("(unnamed)");
expect(row?.querySelector(".t-name")?.classList.contains("is-generating")).toBe(true);
});
it("keeps the real name when there is one", () => {
const { container } = renderTree({
sessions: [sessionFixture({ sessionId: "s-named", name: "Alpha", subagents: [] })],
});
expect(rowTitleText(container, "s-named")).toBe("Alpha");
});
it("labels a nameless sub-session by its task prompt, not its id", () => {
const subagent = subagentFixture({ id: "sub-uuid-1234", name: undefined, task: "Survey the plugin bridge" });
const { container } = renderTree({
sessions: [sessionFixture({ sessionId: "s-parent", name: "Alpha", subagents: [subagent] })],
});
const sub = container.querySelector<HTMLElement>('[data-subagent-id="sub-uuid-1234"] .t-name');
expect(sub?.textContent?.trim()).toBe("Survey the plugin bridge");
expect(container.textContent ?? "").not.toContain("sub-uuid-1234");
});
it("falls back to sub-session when the manifest carries no name or task", () => {
const subagent = subagentFixture({ id: "sub-empty", name: undefined, task: undefined });
const { container } = renderTree({
sessions: [sessionFixture({ sessionId: "s-parent", name: "Alpha", subagents: [subagent] })],
});
expect(screen.getByText("sub-session")).toBeTruthy();
expect(container.textContent ?? "").not.toContain("sub-empty");
});
});