feat: session-scoped entries query, session title tree and message stream updates
This commit is contained in:
1 parent
bef8a35632
commit
e910e75849
37 files changed
+1409
-75
No files matched your search
@@ -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]);
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
}}
|
||||
>
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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() : "";
|
||||
}
|
||||
@@ -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}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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}`}
|
||||
|
||||
@@ -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";
|
||||
|
||||
Reference in new issue
Block a user