From e910e75849c100bd2a097b100295f835aae10927 Mon Sep 17 00:00:00 2001 From: yuez Date: Tue, 27 Oct 2026 17:30:28 +0800 Subject: [PATCH] feat: session-scoped entries query, session title tree and message stream updates --- README.md | 5 + docs/protocol.md | 27 +++- src/daemon/http.ts | 15 +- src/daemon/router.ts | 18 ++- src/protocol/types.ts | 7 + test/daemon/http.test.ts | 24 +++ web/src/components/app-shell.tsx | 16 ++ web/src/components/shared/command-palette.tsx | 6 +- web/src/components/shared/nav-list.tsx | 4 +- web/src/components/shared/server-chip.tsx | 2 +- web/src/features/chat/data.ts | 27 ++-- web/src/features/chat/history.ts | 31 ++-- web/src/features/chat/message-stream.tsx | 71 ++++++++- web/src/features/chat/session-state.ts | 79 ++++++++++ .../features/chat/session-title-spinner.tsx | 37 +++++ web/src/features/chat/session-title.ts | 91 ++++++++++++ web/src/features/chat/session-tray.tsx | 16 +- web/src/features/chat/session-tree-model.ts | 25 +++- web/src/features/chat/session-tree.tsx | 39 ++++- web/src/features/chat/subagent-view.tsx | 6 +- web/src/features/status/queries.ts | 3 +- web/src/features/status/server.ts | 39 ++++- web/src/lib/api.ts | 1 + web/src/locales/en.json | 2 + web/src/locales/zh.json | 2 + web/src/pages/chat.tsx | 36 ++++- web/src/pages/status.tsx | 4 +- web/src/stores/connection.ts | 6 + web/src/styles/pages/chat.css | 55 ++++++- web/tests/chat.history-request.test.ts | 77 ++++++++++ web/tests/chat.stream.test.tsx | 108 ++++++++++++++ web/tests/chat.tree.test.tsx | 82 +++++++++- web/tests/server-chip.test.tsx | 114 ++++++++++++++ web/tests/server-status.test.ts | 97 ++++++++++++ web/tests/session-tab-rows.test.ts | 98 ++++++++++++ web/tests/session-title.test.ts | 74 +++++++++ web/tests/session-title.tree.test.tsx | 140 ++++++++++++++++++ 37 files changed, 1409 insertions(+), 75 deletions(-) create mode 100644 web/src/features/chat/session-title-spinner.tsx create mode 100644 web/src/features/chat/session-title.ts create mode 100644 web/tests/chat.history-request.test.ts create mode 100644 web/tests/server-chip.test.tsx create mode 100644 web/tests/server-status.test.ts create mode 100644 web/tests/session-tab-rows.test.ts create mode 100644 web/tests/session-title.test.ts create mode 100644 web/tests/session-title.tree.test.tsx diff --git a/README.md b/README.md index 07db10a..aa2619a 100644 --- a/README.md +++ b/README.md @@ -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 ``` +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=` 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 `pi2 daemon` serves the web console from its own package with no extra step. diff --git a/docs/protocol.md b/docs/protocol.md index 1f84e1b..8bf6b66 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -63,6 +63,8 @@ The plugin dials the daemon (`/d.sock`), sends `hello` first. {"v":1,"type":"sub.unsubscribe","sessionId":"s1"} {"v":1,"type":"instance.shutdown","payload":{"mode":"drain"}} {"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: @@ -83,7 +85,7 @@ Plugin obligations: | `GET /api/v1/health` | `{ok, items:[{name, ok, detail}]}` | | `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/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/devices` | paired devices (daemon-owned; `{id, name, kind, createdAt, lastSeenAt, revokedAt}`) | | `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/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/` deep links always resolve: | Field | Notes | @@ -125,7 +135,8 @@ Session row (`GET /api/v1/workspaces/:id/sessions`) — a subset of `SessionStat | Field | Notes | |---|---| | `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. | | `model?`, `thinking?` | per-session model pin; the child's manifest thinking level | | `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 | | `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` (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`; @@ -204,6 +226,7 @@ interface SessionState { parentId?: string | null; // null = root (client-side only; the plugin omits the field) visible?: boolean; // plugin `:PiSessions` visibility decision task?: string; // subagent task description from the spawn request + firstMessage?: string | null; // first user message of the session file (provisional title) } type Block = diff --git a/src/daemon/http.ts b/src/daemon/http.ts index 876685b..9993e3b 100644 --- a/src/daemon/http.ts +++ b/src/daemon/http.ts @@ -287,15 +287,16 @@ export function createApp(deps: AppDeps): Hono { if (before !== undefined) params.before = before; const limit = Number(c.req.query("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"); if (sessionFile) params.sessionFile = sessionFile; - const ack = workspaceId - ? await router.relayWorkspaceQuery(workspaceId, "entries", params) - : await router.relaySessionQuery(c.req.param("sid"), "workspace.query", { - ...params, - kind: "entries", - }); + // `workspaceId` only routes the read (a disk-only row has no live owner); + // the sid still rides along so the plugin can answer from its registry. + const ack = await router.relaySessionQuery( + c.req.param("sid"), + "workspace.query", + { ...params, kind: "entries" }, + c.req.query("workspaceId"), + ); return json(200, ack); }); diff --git a/src/daemon/router.ts b/src/daemon/router.ts index 5444ec8..ddbb158 100644 --- a/src/daemon/router.ts +++ b/src/daemon/router.ts @@ -124,13 +124,27 @@ export class CommandRouter { 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( sessionId: string, method: string, params: Record = {}, + workspaceIdHint?: string, ): Promise> { - 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); } diff --git a/src/protocol/types.ts b/src/protocol/types.ts index a454b16..1708110 100644 --- a/src/protocol/types.ts +++ b/src/protocol/types.ts @@ -199,6 +199,13 @@ export interface SessionState { visible?: boolean; /** List metadata only: the subagent task description carried by the list row. Never emitted by the reducer. */ 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; } /* ------------------------------------------------------------------ */ diff --git a/test/daemon/http.test.ts b/test/daemon/http.test.ts index 4ee9204..95e4dc2 100644 --- a/test/daemon/http.test.ts +++ b/test/daemon/http.test.ts @@ -266,6 +266,9 @@ describe("HTTP API", () => { (call) => call.method === "workspace.query" && call.params?.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"); 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 () => { h.instances.resourcesValue = { instances: [ diff --git a/web/src/components/app-shell.tsx b/web/src/components/app-shell.tsx index ead9007..11d469c 100644 --- a/web/src/components/app-shell.tsx +++ b/web/src/components/app-shell.tsx @@ -8,6 +8,8 @@ import { PagePill } from "@/components/shared/page-pill"; import { PrefsMenu } from "@/components/shared/prefs-menu"; import { ServerChip } from "@/components/shared/server-chip"; 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 { CONNECT_PATH, safeNext } from "@/lib/routing"; import { defaultWsUrl, PiWsClient, type WsConnectionState } from "@/lib/ws"; @@ -99,6 +101,7 @@ export function AppShell() { const href = useRouterState({ select: (state) => state.location.href }); const paired = useConnectionStore((state) => state.paired); const setServer = useConnectionStore((state) => state.setServer); + const setServerStatus = useConnectionStore((state) => state.setServerStatus); const wsState = useConnectionStore((state) => state.wsState); const setWsState = useConnectionStore((state) => state.setWsState); const disconnect = useConnectionStore((state) => state.disconnect); @@ -116,11 +119,24 @@ export function AppShell() { staleTime: 30_000, retry: 1, }); + const health = useHealthQuery(paired && !isConnect); + const healthOk = health.data?.ok ?? (health.data ? health.data.items.every((item) => item.ok) : undefined); useEffect(() => { if (info.data) setServer(info.data); }, [info.data, setServer]); + useEffect(() => { + setServerStatus( + resolveServerStatus({ + paired, + info: info.data, + infoError: info.isError, + healthOk, + }), + ); + }, [healthOk, info.data, info.isError, paired, setServerStatus]); + useEffect(() => { document.body.dataset.page = page; }, [page]); diff --git a/web/src/components/shared/command-palette.tsx b/web/src/components/shared/command-palette.tsx index ae6908d..250a583 100644 --- a/web/src/components/shared/command-palette.tsx +++ b/web/src/components/shared/command-palette.tsx @@ -5,6 +5,7 @@ import { useTranslation } from "react-i18next"; import { Icon, type IconName } from "@/components/icons"; import { NAV } from "@/components/shared/nav-list"; +import { sessionTitle } from "@/features/chat/session-title"; import { cn } from "@/lib/utils"; import { useSessionsStore } from "@/stores/sessions"; import { useWorkspacesStore } from "@/stores/workspaces"; @@ -76,7 +77,10 @@ export function CommandPalette({ open, onOpenChange }: CommandPaletteProps) { id: `session-${session.sessionId}`, group: groupSessions, icon: "chat", - label: session.name ?? session.sessionId, + label: sessionTitle(session, { + unnamed: t("chat.sessionUnnamed"), + subagentUnnamed: t("chat.subagentUnnamed"), + }).text, hint: t(`state.${session.status}`), keywords: `${session.sessionId} ${session.model?.id ?? ""} ${session.cwd}`, href: `/chat/${encodeURIComponent(session.sessionId)}`, diff --git a/web/src/components/shared/nav-list.tsx b/web/src/components/shared/nav-list.tsx index 1f26fb3..160a49a 100644 --- a/web/src/components/shared/nav-list.tsx +++ b/web/src/components/shared/nav-list.tsx @@ -57,10 +57,10 @@ export interface NavListProps { export function NavList({ variant, page }: NavListProps) { const { t } = useTranslation(); const server = useConnectionStore((state) => state.server); + const status = useConnectionStore((state) => state.serverStatus); - const status = server?.status ?? "offline"; 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 connectTip = t("shell.connection"); diff --git a/web/src/components/shared/server-chip.tsx b/web/src/components/shared/server-chip.tsx index 23ea6f4..5472e3a 100644 --- a/web/src/components/shared/server-chip.tsx +++ b/web/src/components/shared/server-chip.tsx @@ -18,12 +18,12 @@ export interface ServerChipProps { export function ServerChip({ server: override, className }: ServerChipProps) { const { t } = useTranslation(); const stored = useConnectionStore((state) => state.server); + const status = useConnectionStore((state) => state.serverStatus); const server = override ?? stored; const name = server?.name ?? "pi2.nvim"; const hostname = server?.hostname ?? (typeof window !== "undefined" ? window.location.hostname || "localhost" : "localhost"); - const status = server?.status ?? "offline"; const dot = serverDotClass(status); const dotStatus = dot.replace("dot--", "") as "ok" | "attention" | "exited" | "idle"; diff --git a/web/src/features/chat/data.ts b/web/src/features/chat/data.ts index 20055d4..c3141cd 100644 --- a/web/src/features/chat/data.ts +++ b/web/src/features/chat/data.ts @@ -14,6 +14,7 @@ import { normalizeSessionSummary, normalizeSessionsPayload, normalizeSnapshotState, + tabSessionRows, } from "./session-state"; import { setSessionMeta } from "./history"; import { migrateSessionId } from "./migration"; @@ -148,7 +149,13 @@ export interface ChatSessions { 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 { const query = useQuery({ queryKey: ["chat-sessions", workspaceId], @@ -162,18 +169,18 @@ export function useChatSessions(workspaceId: string | undefined, enabled: boolea useEffect(() => { if (!workspaceId || !query.data) return; - const raw = query.data as { sessions?: Array<{ sessionId?: unknown; sessionFile?: unknown }> } | undefined; - for (const row of raw?.sessions ?? []) { - if (typeof row?.sessionId === "string") { - setSessionMeta(row.sessionId, { - workspaceId, - sessionFile: typeof row.sessionFile === "string" ? row.sessionFile : undefined, - }); - } + // The payload is the union of the workspace's JSONL history and its live + // sessions; the console renders the nvim tab set only, so a historical + // row can never look like a tab (and never receives a prompt). + const rows = tabSessionRows(query.data); + for (const row of rows) { + 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 existing = current.byWorkspace[workspaceId] ?? []; - const next = normalizeSessionsPayload(query.data, workspaceId, existing); + const next = normalizeSessionsPayload(rows, workspaceId, existing); current.setSessions(workspaceId, next); }, [workspaceId, query.data]); diff --git a/web/src/features/chat/history.ts b/web/src/features/chat/history.ts index eda0b01..db77354 100644 --- a/web/src/features/chat/history.ts +++ b/web/src/features/chat/history.ts @@ -34,17 +34,25 @@ export function remapSessionMeta(from: string, to: string): void { 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( sessionId: string, - before?: string, - limit = HISTORY_PAGE_SIZE, - signal?: AbortSignal, + options: { before?: string; limit?: number; signal?: AbortSignal; workspaceId?: string } = {}, ): Promise { + const { before, limit = HISTORY_PAGE_SIZE, signal, workspaceId } = options; const query = new URLSearchParams({ limit: String(limit) }); if (before) query.set("before", before); 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); const raw = await apiRequest( `/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). * 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( sessionId: string | null | undefined, liveEntries: Entry[], enabled = true, + workspaceId?: string | null, ): SessionHistory { const history = useChatStore((state) => sessionId ? (state.history[sessionId] ?? EMPTY_HISTORY) : EMPTY_HISTORY, @@ -100,7 +113,7 @@ export function useSessionHistory( const seq = nextRequest(sessionId); useChatStore.getState().beginInitial(sessionId); - void fetchEntriesPage(sessionId) + void fetchEntriesPage(sessionId, { workspaceId: workspaceId ?? undefined }) .then((page) => { if (!isCurrent(sessionId, seq)) return; useChatStore.getState().receiveInitial(sessionId, page.entries, page.cursor); @@ -111,7 +124,7 @@ export function useSessionHistory( useChatStore.getState().historyError(sessionId, message); }); // `token` is the resync generation; `sessionId`/`enabled` gate loading. - }, [sessionId, enabled, token]); + }, [sessionId, enabled, token, workspaceId]); const loadOlder = useCallback(() => { if (!sessionId) return; @@ -122,7 +135,7 @@ export function useSessionHistory( const seq = nextRequest(sessionId); useChatStore.getState().beginOlder(sessionId); - void fetchEntriesPage(sessionId, before) + void fetchEntriesPage(sessionId, { before, workspaceId: workspaceId ?? undefined }) .then((page) => { if (!isCurrent(sessionId, seq)) return; 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); useChatStore.getState().historyError(sessionId, message); }); - }, [sessionId]); + }, [sessionId, workspaceId]); const retry = useCallback(() => { if (!sessionId) return; diff --git a/web/src/features/chat/message-stream.tsx b/web/src/features/chat/message-stream.tsx index a8c26d4..31af6e2 100644 --- a/web/src/features/chat/message-stream.tsx +++ b/web/src/features/chat/message-stream.tsx @@ -1,6 +1,6 @@ import type { Batch, Entry, QueueItem, SessionState, Subagent, TodoItem } from "@protocol/types"; 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 { Icon } from "@/components/icons"; @@ -121,18 +121,50 @@ export function MessageStream({ const queued = allItems.filter((item) => item.kind === "queued"); const steerAll = steerAllOf(session.queue); const scrollRef = useRef(null); + const listRef = useRef(null); const [following, setFollowing] = useState(true); const followingRef = useRef(true); const pendingPrepend = useRef(null); const loadRequested = useRef(false); const rafRef = useRef(null); + /** Last observed `scrollTop`, so only an *upward* move counts as "stop following". */ + const lastTopRef = useRef(null); + /** Explicit scroll input (wheel / touch / keys / pointer drag) is the only way to stop following. */ + const userInputRef = useRef(false); + const inputTimerRef = useRef | null>(null); + /** A smooth FAB scroll is in flight; instant pins would fight it. */ + const smoothUntilRef = useRef(0); const setFollow = useCallback((value: boolean) => { followingRef.current = 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 hasItems = items.length > 0; const virtualizer = useVirtualizer({ count: items.length, getScrollElement: () => scrollRef.current, @@ -153,7 +185,7 @@ export function MessageStream({ // Streaming keeps the DOM height changing; stay pinned while following. useLayoutEffect(() => { - if (!followingRef.current) return; + if (!followingRef.current || Date.now() < smoothUntilRef.current) return; if (rafRef.current != null) cancelAnimationFrame(rafRef.current); 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(() => { const element = scrollRef.current; const previous = pendingPrepend.current; @@ -176,9 +222,16 @@ export function MessageStream({ const handleScroll = useCallback(() => { const element = scrollRef.current; if (!element) return; - const distance = element.scrollHeight - element.scrollTop - element.clientHeight; - setFollow(distance < 80); - if (element.scrollTop < 120 && hasMore && !loadingOlder && !loadRequested.current) { + const top = element.scrollTop; + const previous = lastTopRef.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; pendingPrepend.current = element.scrollHeight; onLoadOlder(); @@ -268,6 +321,7 @@ export function MessageStream({ {items.length ? ( virtualize ? (
@@ -290,7 +344,7 @@ export function MessageStream({ })}
) : ( -
+
{items.map((item) => (
{renderItem(item)} @@ -329,6 +383,10 @@ export function MessageStream({ aria-live="polite" aria-label={t("chat.streamAria")} onScroll={handleScroll} + onWheel={markScrollInput} + onTouchMove={markScrollInput} + onKeyDown={markScrollInput} + onPointerDown={markScrollInput} > {status} {body} @@ -342,6 +400,7 @@ export function MessageStream({ title={t("chat.backToLatest")} onClick={() => { setFollow(true); + smoothUntilRef.current = Date.now() + 700; scrollToBottom(true); }} > diff --git a/web/src/features/chat/session-state.ts b/web/src/features/chat/session-state.ts index 85d2ba3..ca0d45a 100644 --- a/web/src/features/chat/session-state.ts +++ b/web/src/features/chat/session-state.ts @@ -321,6 +321,10 @@ export function normalizeSessionSummary(raw: unknown, workspaceId: string, exist const thinkingValue = str(record.thinking); const hasQueue = Array.isArray(record.queue); 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 { ...base, sessionId, @@ -346,9 +350,84 @@ export function normalizeSessionSummary(raw: unknown, workspaceId: string, exist parentId: summaryParentId(record, base), visible: typeof record.visible === "boolean" ? record.visible : base.visible, ...(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 { + 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 | 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): 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[] { + const record = rec(raw); + const list = Array.isArray(raw) ? raw : arr(record?.sessions ?? record?.items); + const rows: Record[] = []; + 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(); + const childrenOf = new Map(); + 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(); + 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. */ export function normalizeSessionsPayload( raw: unknown, diff --git a/web/src/features/chat/session-title-spinner.tsx b/web/src/features/chat/session-title-spinner.tsx new file mode 100644 index 0000000..16a7f27 --- /dev/null +++ b/web/src/features/chat/session-title-spinner.tsx @@ -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 ( + + ); +} diff --git a/web/src/features/chat/session-title.ts b/web/src/features/chat/session-title.ts new file mode 100644 index 0000000..07c92b1 --- /dev/null +++ b/web/src/features/chat/session-title.ts @@ -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 & { 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() : ""; +} diff --git a/web/src/features/chat/session-tray.tsx b/web/src/features/chat/session-tray.tsx index f8221b0..722471d 100644 --- a/web/src/features/chat/session-tray.tsx +++ b/web/src/features/chat/session-tray.tsx @@ -11,6 +11,7 @@ import { cn } from "@/lib/utils"; import { TodoList } from "./blocks"; import { formatDuration } from "./format"; +import { subagentTitle } from "./session-title"; import type { TrayTab } from "./store"; import "@/styles/pages/chat-tray.css"; @@ -71,9 +72,16 @@ export function SessionTray({ const tabsRef = useRef(null); const [entered, setEntered] = useState(false); - const title = subagent - ? t("chat.subview.trayTitle", { name: subagent.name ?? subagent.id }) - : t("chat.trayTitle"); + // The tray names the subagent it is scoped to; a nameless subagent is + // labelled by its task prompt, never by its id (pi2.nvim parity). + 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. useEffect(() => { @@ -185,7 +193,7 @@ export function SessionTray({

{subagent - ? t("chat.trayScopeSubagent", { name: subagent.name ?? subagent.id }) + ? t("chat.trayScopeSubagent", { name: subagentName }) : t("chat.trayScopeSession")} {subagent ? {t("chat.trayScopeNote")} : null} diff --git a/web/src/features/chat/session-tree-model.ts b/web/src/features/chat/session-tree-model.ts index 8b94a7d..eddc0de 100644 --- a/web/src/features/chat/session-tree-model.ts +++ b/web/src/features/chat/session-tree-model.ts @@ -1,5 +1,7 @@ import type { SessionState, Subagent } from "@protocol/types"; +import { sessionTitle, subagentTitle } from "./session-title"; + /** * The session tree the sidebar renders: workspace sessions nest under their * `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)); } +/** + * 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 { - return session.name?.trim() || session.sessionId; + return sessionTitle(session, SEARCH_PHRASES).text; } 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). */ @@ -225,7 +234,13 @@ export function buildSessionTreeView( * active lens > plugin policy > "an kept descendant needs the ancestor". */ 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 (activeOnly && !isSessionActive(session)) return childCount > 0; if (session.visible === false) return showHidden || childCount > 0; @@ -298,7 +313,9 @@ export function buildSessionTreeView( showHidden || selectedId === subagent.id || 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 (needle === "") hiddenByPolicy += 1; return null; diff --git a/web/src/features/chat/session-tree.tsx b/web/src/features/chat/session-tree.tsx index f6a2a7b..2ba0f8c 100644 --- a/web/src/features/chat/session-tree.tsx +++ b/web/src/features/chat/session-tree.tsx @@ -8,6 +8,8 @@ import { StatusDot, subagentDotClass } from "@/components/ui/status-dot"; import { cn } from "@/lib/utils"; import { SessionRowMenu } from "./session-row-menu"; import { flattenSubagents, sessionDot } from "./session-state"; +import { sessionTitle, subagentTitle } from "./session-title"; +import { SessionTitleSpinner } from "./session-title-spinner"; import { buildSessionTreeView, treeNodeId, @@ -104,6 +106,11 @@ export function SessionTree({ const [wsMenuOpen, setWsMenuOpen] = useState(false); const [rowMenu, setRowMenu] = useState<{ session: SessionState; anchor: HTMLElement } | null>(null); const anchorRef = useRef(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( () => @@ -172,7 +179,8 @@ export function SessionTree({ const session = node.session; const selected = session.sessionId === selectedId; 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; return (

onSelectSession(session.sessionId)} > - {name} + {title.spinner ? : null} + + {title.text} + {attention > 0 ? {`!${attention}`} : null}