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

+16
View File
@@ -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]);
@@ -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)}`,
+2 -2
View File
@@ -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");
+1 -1
View File
@@ -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";
+17 -10
View File
@@ -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]);
+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 });
}
/** `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<FetchedPage> {
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<unknown>(
`/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;
+65 -6
View File
@@ -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<HTMLDivElement | null>(null);
const listRef = useRef<HTMLDivElement | null>(null);
const [following, setFollowing] = useState(true);
const followingRef = useRef(true);
const pendingPrepend = useRef<number | null>(null);
const loadRequested = useRef(false);
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) => {
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 ? (
<div
ref={listRef}
className="stream-list stream-inner stream-list--virtual"
style={{ height: `${virtualizer.getTotalSize()}px` }}
>
@@ -290,7 +344,7 @@ export function MessageStream({
})}
</div>
) : (
<div className="stream-list stream-inner">
<div ref={listRef} className="stream-list stream-inner">
{items.map((item) => (
<div className={itemClassName(item)} key={item.key}>
{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);
}}
>
+79
View File
@@ -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, 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. */
export function normalizeSessionsPayload(
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 { 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<HTMLDivElement | null>(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({
<p className="tray-scope" data-testid="tray-scope">
<span className="tray-scope__label">
{subagent
? t("chat.trayScopeSubagent", { name: subagent.name ?? subagent.id })
? t("chat.trayScopeSubagent", { name: subagentName })
: t("chat.trayScopeSession")}
</span>
{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 { 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;
+33 -6
View File
@@ -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<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(
() =>
@@ -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 (
<div
@@ -197,12 +205,21 @@ export function SessionTree({
<button
type="button"
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}
onClick={() => onSelectSession(session.sessionId)}
>
<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}
</button>
<button
@@ -227,9 +244,11 @@ export function SessionTree({
function renderSubagentRow(node: SubagentTreeNode) {
const { session, subagent } = node;
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.
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 (
<div
className={cn(
@@ -257,7 +276,15 @@ export function SessionTree({
onClick={() => onSelectSubagent(session.sessionId, subagent.id)}
>
<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 ? (
<span className="t-hidden tabular" title={t("chat.hiddenSubs", { n: node.hiddenCount })}>
{`+${node.hiddenCount}`}
+5 -1
View File
@@ -12,6 +12,7 @@ import { EntryBlock } from "./blocks";
import { Composer } from "./composer";
import type { ModelGroup } from "./data";
import { HeadChips } from "./head-chips";
import { subagentTitle } from "./session-title";
import type { TrayTab } from "./store";
import "@/styles/pages/chat-telemetry.css";
@@ -185,7 +186,10 @@ export function SubagentView({
className,
}: SubagentViewProps) {
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() || "";
// `live` is authoritative when present; the status is the fallback.
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>({
queryKey: ["health"],
queryFn: ({ signal }) => api.health(signal),
enabled,
staleTime: 10_000,
});
}
+37 -2
View File
@@ -1,6 +1,41 @@
import type { InfoResponse } from "@/lib/api";
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
* contract (`{v,daemonId,machineId,platform,hostname,os,version,uptimeMs,
@@ -36,7 +71,7 @@ export interface ServerIdentity {
uptimeSec: number | null;
uptimeMs: number | null;
pid: number | null;
status: "online" | "degraded" | "offline";
status: ServerStatusValue;
wsConnected: boolean;
wsProto: string;
lastHeartbeatAt: number | null;
@@ -85,7 +120,7 @@ export interface DeriveServerInput {
wsState?: WsConnectionState;
fetchedAt?: number | null;
nameFallback?: string | null;
status?: "online" | "degraded" | "offline" | null;
status?: ServerStatusValue | null;
}
/** 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. */
os?: string;
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";
}
+2
View File
@@ -209,6 +209,7 @@
"chat.sendFailed": "Send failed: {error}",
"chat.sendTitle": "Send (Enter)",
"chat.sending": "Sending…",
"chat.sessionUnnamed": "(unnamed)",
"chat.sessions": "Sessions",
"chat.shell.command": "Command",
"chat.shell.copyCommand": "Copy command",
@@ -256,6 +257,7 @@
"chat.subagentCount": "{n} subagents",
"chat.subagentFilter": "Subagent filter",
"chat.subagentName": "Subagent name",
"chat.subagentUnnamed": "sub-session",
"chat.subagentNamePlaceholder": "e.g. ui-research",
"chat.subview.back": "Parent",
"chat.subview.backTo": "Back to {name}",
+2
View File
@@ -209,6 +209,7 @@
"chat.sendFailed": "发送失败:{error}",
"chat.sendTitle": "发送(Enter)",
"chat.sending": "发送中…",
"chat.sessionUnnamed": "(未命名)",
"chat.sessions": "会话",
"chat.shell.command": "命令",
"chat.shell.copyCommand": "复制命令",
@@ -256,6 +257,7 @@
"chat.subagentCount": "{n} 个子代理",
"chat.subagentFilter": "子代理筛选",
"chat.subagentName": "子代理名称",
"chat.subagentUnnamed": "子会话",
"chat.subagentNamePlaceholder": "例如 ui-research",
"chat.subview.back": "父级",
"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 { DispatchModal, RenameDialog, TaskOutputModal, type DispatchInput } from "@/features/chat/modals";
import { SessionTray } from "@/features/chat/session-tray";
import { sessionTitle } from "@/features/chat/session-title";
import {
findSubagent,
flattenSubagents,
@@ -115,9 +116,26 @@ function ChatExperience({ sessionId }: { sessionId?: string }) {
sessions,
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 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 setFilter = useChatStore((state) => state.setFilter);
@@ -218,9 +236,11 @@ function ChatExperience({ sessionId }: { sessionId?: string }) {
}, [activeSubagentId, closeDrawers, rowMenuId, setRowMenuId, setWsMenuOpen, treeOpen, trayOpen]);
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`;
}, [active?.name, sessionMissing, t]);
}, [activeTitle, sessionMissing, t]);
// The optimistic "sending" chip disappears when the authoritative user
// entry arrives (via entry_appended) or after a safety timeout.
@@ -446,7 +466,7 @@ function ChatExperience({ sessionId }: { sessionId?: string }) {
async function closeSession(session: SessionState) {
await exec(chatCommands.closeSession(session.sessionId), "chat.closedProcess", {
name: session.name ?? session.sessionId,
name: sessionTitle(session, titlePhrases).text,
});
setClosing(null);
}
@@ -518,7 +538,7 @@ function ChatExperience({ sessionId }: { sessionId?: string }) {
<StatusDot status={sessionDot(active)} title={t(`state.${sessionStatusKey(active)}`)} />
) : null}
<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>
{active?.flags.attention && active.attention.length ? (
<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")}
initial={
renaming?.kind === "session"
? (renaming.session.name ?? renaming.session.sessionId)
: (renaming?.subagent.name ?? renaming?.subagent.id ?? "")
? (renaming.session.name ?? "")
: (renaming?.subagent.name ?? "")
}
hint={
renaming?.kind === "session" ? t("chat.renameSessionHint") : t("chat.renameSubagentHint")
@@ -770,7 +790,7 @@ function ChatExperience({ sessionId }: { sessionId?: string }) {
}}
title={t("chat.closeProcess")}
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")}
danger
+2 -2
View File
@@ -31,7 +31,7 @@ import { mergeTasks,
type DevicesResponse,
type StatusTask,
} 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 { TasksCard } from "@/features/status/tasks-card";
import { partitionWorkspaces } from "@/features/workspaces/visibility";
@@ -91,7 +91,7 @@ export function StatusPage() {
wsState,
fetchedAt: info.dataUpdatedAt || null,
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
+6
View File
@@ -1,5 +1,6 @@
import { create } from "zustand";
import type { ServerStatusValue } from "@/features/status/server";
import type { InfoResponse } from "@/lib/api";
import { getDeviceToken, setDeviceToken } from "@/lib/api";
import type { WsConnectionState } from "@/lib/ws";
@@ -43,6 +44,7 @@ export interface ConnectionStore {
connectedAt: number;
token: string | null;
server: InfoResponse | null;
serverStatus: ServerStatusValue;
wsState: WsConnectionState;
isPaired: () => boolean;
@@ -50,6 +52,7 @@ export interface ConnectionStore {
connect: (options?: { endpoint?: string; deviceName?: string; token?: string | null }) => void;
disconnect: () => void;
setServer: (server: InfoResponse | null) => void;
setServerStatus: (status: ServerStatusValue) => void;
setWsState: (state: WsConnectionState) => void;
setToken: (token: string | null) => void;
}
@@ -62,6 +65,7 @@ function initialState() {
connectedAt: Number(read(CONNECTED_AT_KEY)) || 0,
token: getDeviceToken(),
server: null as InfoResponse | null,
serverStatus: "unknown" as ServerStatusValue,
wsState: "idle" as WsConnectionState,
};
}
@@ -102,11 +106,13 @@ export const useConnectionStore = create<ConnectionStore>((set, get) => ({
connectedAt: 0,
token: null,
server: null,
serverStatus: "unknown",
wsState: "idle",
});
},
setServer: (server) => set({ server }),
setServerStatus: (serverStatus) => set({ serverStatus }),
setWsState: (wsState) => set({ wsState }),
setToken: (token) => {
setDeviceToken(token);
+51 -4
View File
@@ -311,7 +311,8 @@
height: 11px;
}
/* 行:单行 = 折叠箭头 + 主按钮(点 + 名称 + !N)+ 行操作「…」 */
/* 行:单行 = 折叠箭头 + 主按钮(点 + 名称 + !N)+ 行操作「…」
pi2.nvim 的 :PiSessions 不做淡入淡出:hover / 选中态瞬时切换。 */
.tree-row {
display: flex;
align-items: center;
@@ -319,7 +320,6 @@
min-height: 32px;
padding: 0;
border-radius: var(--radius-sm);
transition: background var(--dur-fast) var(--ease-out);
}
.tree-row:hover {
background: var(--surface-1);
@@ -355,6 +355,21 @@
flex: 1 1 auto;
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 {
flex: none;
font-size: var(--fs-2xs);
@@ -389,7 +404,6 @@
}
.tree-toggle.open svg {
transform: rotate(90deg);
transition: transform var(--dur-fast) var(--ease-out);
}
.tree-toggle.leaf {
visibility: hidden;
@@ -400,7 +414,6 @@
width: 22px;
height: 22px;
opacity: 0;
transition: opacity var(--dur-fast) var(--ease-out);
}
.tree-row:hover .t-more,
.tree-row:focus-within .t-more,
@@ -432,6 +445,40 @@
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 {
height: 30px;