From 012cc1c200888afd2bdc5dd54899f30aeede144c Mon Sep 17 00:00:00 2001 From: Danny Avila Date: Thu, 19 Nov 2026 12:59:14 -0500 Subject: [PATCH] =?UTF-8?q?=F0=9F=9B=A4=EF=B8=8F=20feat:=20Session=20Rail?= =?UTF-8?q?=20for=20Subagents=20and=20Background=20Tasks=20(#18504)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 🛤️ feat: Session Rail for Subagents and Background Tasks A column beside the conversation, opened from the chat header, that lists what the conversation has running: its subagents, then its background tools. It replaces the header popover, whose control only appeared once there was something to list. The control is now always offered, and the rail keeps its own column past the side panel, so a subagent opened from it stays in view of the list. A running subagent's row says what the child is on now, read from the thread the page already follows for the card. interface.sessionRail (default true) turns it off and restores the popover. * 🪤 fix: Hold Focus in the Session Rail's Small-Screen Sheet The sheet covers the conversation, so it now traps Tab and answers Escape through the shared focus trap the other sheets use, and says it is modal. Focus still starts on the close button rather than on Stop all. * 🪶 perf: Render Nothing but the Rail When the Session Rail Toggles Opening or closing the rail changes the chat column's width once. The composer bar kept its row's measured width in state, so it and everything under it rendered for every frame of the composer's width change: 6 times on open and 18 on close, and the same on a sidebar toggle. It now reads only whether its chips fit, through useElementSizeSelect, and renders when that answer changes. The scan that titles background tool rows from the loaded messages, which runs on each update of a streaming thread while the rail is open, now passes over every tool call no task names before building its keys. Adds rail.perf.spec.ts beside the sidebar's benchmark. * 🪶 perf: Keep an Open Session Rail Still While the Thread Streams Measured by replaying a recorded reply into long agent chats with the rail closed and then open and listing running work. A once-a-second clock held by the header control rebuilt every row object, so every row rendered each second while anything ran. The clock now belongs to the duration text: one shared timer, read only by the running rows' elapsed times, and a row renders when what it shows changes. A running row's title no longer sweeps. Each sweep is three compositor layers, and every frame of the streaming thread paid for them in style, layerize and commit: six running rows took the page from 9 layers to 33. The row keeps its pulsing dot and its counting duration. The rail's layout slot is memoized: its parent renders for every stream frame. The replay benchmark gains FADE_PERF_RAIL, and rail.perf.spec.ts a test that grows the last reply beside the rail and prints the layer count. --- .../Chat/BackgroundTasks/Button.tsx | 67 +-- .../components/Chat/BackgroundTasks/Card.tsx | 26 +- .../Chat/BackgroundTasks/Section.tsx | 14 +- .../BackgroundTasks/__tests__/rows.test.ts | 67 +++ .../components/Chat/BackgroundTasks/clock.ts | 13 + .../components/Chat/BackgroundTasks/jump.ts | 56 ++ .../components/Chat/BackgroundTasks/labels.ts | 24 + .../components/Chat/BackgroundTasks/rows.ts | 22 +- .../Chat/BackgroundTasks/useTasks.ts | 10 +- client/src/components/Chat/Header.tsx | 15 +- .../components/Chat/Input/Composer/Bar.tsx | 18 +- .../src/components/Chat/Presentation.test.tsx | 22 +- client/src/components/Chat/Presentation.tsx | 4 + .../src/components/Chat/Session/Elapsed.tsx | 58 ++ client/src/components/Chat/Session/Now.tsx | 62 ++ client/src/components/Chat/Session/Rail.tsx | 290 ++++++++++ client/src/components/Chat/Session/Row.tsx | 243 ++++++++ .../src/components/Chat/Session/Session.tsx | 112 ++++ client/src/components/Chat/Session/Slot.tsx | 14 + .../Chat/Session/__tests__/Elapsed.test.tsx | 62 ++ .../Chat/Session/__tests__/Now.test.ts | 64 ++ .../Chat/Session/__tests__/Session.test.tsx | 546 ++++++++++++++++++ client/src/components/Chat/Session/index.ts | 2 + client/src/components/Chat/Session/state.ts | 14 + .../Chat/__tests__/Header.stacking.spec.tsx | 59 +- client/src/locales/en/translation.json | 7 + e2e/benchmarks-fade/README.md | 11 + e2e/benchmarks-fade/rail.perf.spec.ts | 154 +++++ e2e/benchmarks-fade/rail.ts | 143 +++++ e2e/benchmarks-fade/replay.perf.spec.ts | 13 + e2e/specs/mock/subagent-activity.spec.ts | 91 +++ librechat.example.yaml | 3 + .../src/components/parts/SubagentCall.tsx | 23 +- packages/chat/src/react.ts | 2 +- .../chat/src/react/__tests__/size.spec.tsx | 72 ++- packages/chat/src/react/size.ts | 61 +- .../react/subagents/__tests__/tail.spec.ts | 45 ++ packages/chat/src/react/subagents/index.ts | 1 + packages/chat/src/react/subagents/tail.ts | 31 + packages/data-provider/src/config.ts | 5 + .../data-schemas/src/app/interface.spec.ts | 18 + packages/data-schemas/src/app/interface.ts | 1 + 42 files changed, 2438 insertions(+), 127 deletions(-) create mode 100644 client/src/components/Chat/BackgroundTasks/clock.ts create mode 100644 client/src/components/Chat/BackgroundTasks/jump.ts create mode 100644 client/src/components/Chat/BackgroundTasks/labels.ts create mode 100644 client/src/components/Chat/Session/Elapsed.tsx create mode 100644 client/src/components/Chat/Session/Now.tsx create mode 100644 client/src/components/Chat/Session/Rail.tsx create mode 100644 client/src/components/Chat/Session/Row.tsx create mode 100644 client/src/components/Chat/Session/Session.tsx create mode 100644 client/src/components/Chat/Session/Slot.tsx create mode 100644 client/src/components/Chat/Session/__tests__/Elapsed.test.tsx create mode 100644 client/src/components/Chat/Session/__tests__/Now.test.ts create mode 100644 client/src/components/Chat/Session/__tests__/Session.test.tsx create mode 100644 client/src/components/Chat/Session/index.ts create mode 100644 client/src/components/Chat/Session/state.ts create mode 100644 e2e/benchmarks-fade/rail.perf.spec.ts create mode 100644 e2e/benchmarks-fade/rail.ts create mode 100644 packages/chat/src/react/subagents/__tests__/tail.spec.ts create mode 100644 packages/chat/src/react/subagents/tail.ts diff --git a/client/src/components/Chat/BackgroundTasks/Button.tsx b/client/src/components/Chat/BackgroundTasks/Button.tsx index fb800ac702..e30adb322f 100644 --- a/client/src/components/Chat/BackgroundTasks/Button.tsx +++ b/client/src/components/Chat/BackgroundTasks/Button.tsx @@ -8,8 +8,9 @@ import { useParentSubagents, } from '@librechat/chat/react'; import type { TaskRow } from './rows'; -import { RECENT_SUBAGENT_WINDOW_MS } from './rows'; +import { findTaskTarget, focusTaskTarget, scrollToTaskTarget } from './jump'; import useBackgroundTasks from './useTasks'; +import { useTaskExpiry } from './clock'; import { useLocalize } from '~/hooks'; import Section from './Section'; import TaskCard from './Card'; @@ -49,21 +50,7 @@ function BackgroundTasksButton({ return () => clearInterval(timer); }, [open, activeCount]); - const nextExpiry = rows.reduce( - (next, row) => - row.settledAt != null && - row.delivery == null && - row.status !== 'running' && - row.status !== 'stopping' - ? Math.min(next, row.settledAt + RECENT_SUBAGENT_WINDOW_MS + 1) - : next, - Infinity, - ); - useEffect(() => { - if (!Number.isFinite(nextExpiry)) return; - const timer = setTimeout(() => setNow(Date.now()), Math.max(0, nextExpiry - Date.now())); - return () => clearTimeout(timer); - }, [nextExpiry]); + useTaskExpiry(rows, setNow); if (rows.length === 0 && !view.loadFailed && !incomplete) { return null; @@ -111,52 +98,12 @@ function BackgroundTasksButton({ openSubagentPanel({ ...selection, isSubmitting: false }); return true; } - if (row.messageId == null) return false; - const message = document.getElementById(row.messageId); - if (message == null) return false; - const scope = message; - const destinations = Array.from( - scope.querySelectorAll('[data-task-tool-call]'), - ).filter( - (element) => - element.dataset.taskToolCall === row.toolCallId && - (row.stepId == null || element.dataset.taskStep === row.stepId), - ); - const targets = Array.from( - scope.querySelectorAll( - '[data-tool-call-id], [data-subagent-tool-call], [data-subagent-thread]', - ), - ).filter( - (element) => - (row.threadId != null && element.dataset.subagentThread === row.threadId) || - (row.toolCallId != null && - (element.dataset.toolCallId === row.toolCallId || - element.dataset.subagentToolCall === row.toolCallId)), - ); - // Legacy call ids are only usable when they identify one rendered call. - const threads = - row.threadId == null - ? [] - : targets.filter((element) => element.dataset.subagentThread === row.threadId); - let target = message; - if (threads.length === 1) target = threads[0]; - else if (destinations.length === 1) target = destinations[0]; - else if (destinations.length === 0 && targets.length === 1) target = targets[0]; - if (target == null || target.closest('[inert], [hidden], [aria-hidden="true"]') != null) - return false; - if (!target.hasAttribute('tabindex') && !target.matches('button')) { - target.tabIndex = -1; - target.addEventListener('blur', () => target.removeAttribute('tabindex'), { once: true }); - } + const target = findTaskTarget(row); + if (target == null) return false; finalFocusRef.current = null; - target.focus({ preventScroll: true }); + focusTaskTarget(target); popover.hide(); - target.scrollIntoView?.({ - block: 'center', - behavior: window.matchMedia?.('(prefers-reduced-motion: reduce)').matches - ? 'instant' - : 'smooth', - }); + scrollToTaskTarget(target); return true; }; const card = (row: (typeof rows)[number]) => ( diff --git a/client/src/components/Chat/BackgroundTasks/Card.tsx b/client/src/components/Chat/BackgroundTasks/Card.tsx index 3253445867..a7bc8a3934 100644 --- a/client/src/components/Chat/BackgroundTasks/Card.tsx +++ b/client/src/components/Chat/BackgroundTasks/Card.tsx @@ -3,34 +3,12 @@ import { useTranslation } from 'react-i18next'; import { getToolDisplayLabel } from '@librechat/chat'; import { ArrowUpRight, ChevronDown, Square } from 'lucide-react'; import { Shimmer, Spinner, IconButton, TooltipAnchor } from '@librechat/client'; -import type { TaskRow, TaskRowDelivery, TaskRowStatus } from './rows'; -import type { TranslationKeys } from '~/hooks/useLocalize'; +import type { TaskRow } from './rows'; +import { DELIVERY_CLASSES, DELIVERY_KEYS, STATUS_CLASSES, STATUS_KEYS } from './labels'; import { getRunStepDurationLabels, cn } from '~/utils'; import { Collapse } from '~/components/ui'; import { useLocalize } from '~/hooks'; -const STATUS_KEYS: Record = { - running: 'com_ui_background_tasks_running', - stopping: 'com_ui_background_tasks_stopping', - completed: 'com_ui_background_tasks_completed', - error: 'com_ui_failed', - cancelled: 'com_ui_cancelled', -}; - -const STATUS_CLASSES: Partial> = { - error: 'text-status-error', - cancelled: 'text-status-warning', -}; - -const DELIVERY_KEYS: Record = { - pending: 'com_ui_background_tasks_result_pending', - failed: 'com_ui_background_tasks_result_undelivered', -}; - -const DELIVERY_CLASSES: Partial> = { - failed: 'text-status-warning', -}; - function TaskCard({ row, now, diff --git a/client/src/components/Chat/BackgroundTasks/Section.tsx b/client/src/components/Chat/BackgroundTasks/Section.tsx index 893dba443c..39b0ba650a 100644 --- a/client/src/components/Chat/BackgroundTasks/Section.tsx +++ b/client/src/components/Chat/BackgroundTasks/Section.tsx @@ -3,18 +3,23 @@ import { ChevronDown } from 'lucide-react'; import { Collapse } from '~/components/ui'; import { cn } from '~/utils'; -/** A labelled, collapsible group; `action` stays reachable while collapsed. */ +/** + * A labelled, collapsible group; `action` stays reachable while collapsed. `dense` is the + * sidebar's scale: a small label over rows that carry their own spacing. + */ export default function Section({ label, count, action, defaultOpen = true, + dense = false, children, }: { label: string; count: number; action?: React.ReactNode; defaultOpen?: boolean; + dense?: boolean; children: React.ReactNode; }) { const listId = useId(); @@ -27,7 +32,10 @@ export default function Section({ aria-expanded={open} aria-controls={listId} onClick={() => setOpen((value) => !value)} - className="text-text-secondary hover:text-text-primary focus-visible:ring-focus-control flex min-w-0 flex-1 items-center gap-1 rounded text-sm focus-visible:ring-2 focus-visible:outline-none" + className={cn( + 'text-text-secondary hover:text-text-primary focus-visible:ring-focus-control flex min-w-0 flex-1 items-center gap-1 rounded focus-visible:ring-2 focus-visible:outline-none', + dense ? 'h-8 ps-2 text-xs font-medium' : 'text-sm', + )} > {label} {count} @@ -42,7 +50,7 @@ export default function Section({ {action} -
    +
      {children}
    diff --git a/client/src/components/Chat/BackgroundTasks/__tests__/rows.test.ts b/client/src/components/Chat/BackgroundTasks/__tests__/rows.test.ts index b1535b2ea7..9156835211 100644 --- a/client/src/components/Chat/BackgroundTasks/__tests__/rows.test.ts +++ b/client/src/components/Chat/BackgroundTasks/__tests__/rows.test.ts @@ -5,6 +5,7 @@ import { countAwaitingDelivery, countFailedDelivery, buildTaskRows, + nextTaskExpiry, findToolCallArgs, subagentTaskKey, } from '../rows'; @@ -118,6 +119,72 @@ describe('buildTaskRows', () => { expect(rows[3].subagent).toBeUndefined(); expect(rows[3].taskId).toBe('task'); }); + + it('carries who a subagent runs as, for a surface that names the agent', () => { + const [row] = buildTaskRows({ + now, + args: new Map(), + describe: () => ({}), + stoppingThreads: new Set(), + tools: [], + subagents: [child({ agentId: 'agent-1', subagentType: 'agent-1', subagentKind: 'agent' })], + }); + + expect(row).toMatchObject({ + agentId: 'agent-1', + subagentType: 'agent-1', + subagentKind: 'agent', + }); + }); +}); + +describe('nextTaskExpiry', () => { + const rows = (settled: Parameters[0]['tools']) => + buildTaskRows({ + now, + args: new Map(), + describe: () => ({}), + stoppingThreads: new Set(), + tools: settled, + subagents: [], + }); + const tool = { toolName: 'bash_tool', toolCallId: 'call', cancellationRequested: false }; + + it('is the moment the earliest delivered, settled row leaves the list', () => { + const settledAt = iso(10_000); + expect( + nextTaskExpiry( + rows([ + { + ...tool, + taskId: 'later', + status: 'completed', + startedAt: iso(9_000), + settledAt: iso(5_000), + }, + { ...tool, taskId: 'earlier', status: 'completed', startedAt: iso(20_000), settledAt }, + ]), + ), + ).toBe(Date.parse(settledAt) + RECENT_SUBAGENT_WINDOW_MS + 1); + }); + + it('never schedules for running work or for a result still owed to the agent', () => { + expect( + nextTaskExpiry( + rows([ + { ...tool, taskId: 'running', status: 'running', startedAt: iso(9_000) }, + { + ...tool, + taskId: 'owed', + status: 'completed', + startedAt: iso(9_000), + settledAt: iso(5_000), + delivery: 'pending', + }, + ]), + ), + ).toBe(Infinity); + }); }); describe('findToolCallArgs', () => { diff --git a/client/src/components/Chat/BackgroundTasks/clock.ts b/client/src/components/Chat/BackgroundTasks/clock.ts new file mode 100644 index 0000000000..c7cef32bf5 --- /dev/null +++ b/client/src/components/Chat/BackgroundTasks/clock.ts @@ -0,0 +1,13 @@ +import { useEffect } from 'react'; +import type { TaskRow } from './rows'; +import { nextTaskExpiry } from './rows'; + +/** Advances the clock once, at the moment the next settled row ages out of the list. */ +export function useTaskExpiry(rows: readonly TaskRow[], setNow: (now: number) => void): void { + const nextExpiry = nextTaskExpiry(rows); + useEffect(() => { + if (!Number.isFinite(nextExpiry)) return; + const timer = setTimeout(() => setNow(Date.now()), Math.max(0, nextExpiry - Date.now())); + return () => clearTimeout(timer); + }, [nextExpiry, setNow]); +} diff --git a/client/src/components/Chat/BackgroundTasks/jump.ts b/client/src/components/Chat/BackgroundTasks/jump.ts new file mode 100644 index 0000000000..cf28e49fff --- /dev/null +++ b/client/src/components/Chat/BackgroundTasks/jump.ts @@ -0,0 +1,56 @@ +import type { TaskRow } from './rows'; + +/** + * The rendered call a tool row points at, when the loaded messages hold it and it can be + * reached. Legacy call ids are only usable when they identify one rendered call. + */ +export function findTaskTarget(row: TaskRow): HTMLElement | null { + if (row.messageId == null) return null; + const message = document.getElementById(row.messageId); + if (message == null) return null; + const destinations = Array.from( + message.querySelectorAll('[data-task-tool-call]'), + ).filter( + (element) => + element.dataset.taskToolCall === row.toolCallId && + (row.stepId == null || element.dataset.taskStep === row.stepId), + ); + const targets = Array.from( + message.querySelectorAll( + '[data-tool-call-id], [data-subagent-tool-call], [data-subagent-thread]', + ), + ).filter( + (element) => + (row.threadId != null && element.dataset.subagentThread === row.threadId) || + (row.toolCallId != null && + (element.dataset.toolCallId === row.toolCallId || + element.dataset.subagentToolCall === row.toolCallId)), + ); + const threads = + row.threadId == null + ? [] + : targets.filter((element) => element.dataset.subagentThread === row.threadId); + let target = message; + if (threads.length === 1) target = threads[0]; + else if (destinations.length === 1) target = destinations[0]; + else if (destinations.length === 0 && targets.length === 1) target = targets[0]; + return target.closest('[inert], [hidden], [aria-hidden="true"]') == null ? target : null; +} + +/** Moves focus to the call; an element that takes none by itself is focusable until it loses it. */ +export function focusTaskTarget(target: HTMLElement): void { + if (!target.hasAttribute('tabindex') && !target.matches('button')) { + target.tabIndex = -1; + target.addEventListener('blur', () => target.removeAttribute('tabindex'), { once: true }); + } + target.focus({ preventScroll: true }); +} + +export function scrollToTaskTarget(target: HTMLElement): void { + target.scrollIntoView?.({ + block: 'center', + behavior: window.matchMedia?.('(prefers-reduced-motion: reduce)').matches + ? 'instant' + : 'smooth', + }); +} diff --git a/client/src/components/Chat/BackgroundTasks/labels.ts b/client/src/components/Chat/BackgroundTasks/labels.ts new file mode 100644 index 0000000000..c778d073ae --- /dev/null +++ b/client/src/components/Chat/BackgroundTasks/labels.ts @@ -0,0 +1,24 @@ +import type { TaskRowDelivery, TaskRowStatus } from './rows'; +import type { TranslationKeys } from '~/hooks/useLocalize'; + +export const STATUS_KEYS: Record = { + running: 'com_ui_background_tasks_running', + stopping: 'com_ui_background_tasks_stopping', + completed: 'com_ui_background_tasks_completed', + error: 'com_ui_failed', + cancelled: 'com_ui_cancelled', +}; + +export const STATUS_CLASSES: Partial> = { + error: 'text-status-error', + cancelled: 'text-status-warning', +}; + +export const DELIVERY_KEYS: Record = { + pending: 'com_ui_background_tasks_result_pending', + failed: 'com_ui_background_tasks_result_undelivered', +}; + +export const DELIVERY_CLASSES: Partial> = { + failed: 'text-status-warning', +}; diff --git a/client/src/components/Chat/BackgroundTasks/rows.ts b/client/src/components/Chat/BackgroundTasks/rows.ts index 0ef17c7cc5..a05629c673 100644 --- a/client/src/components/Chat/BackgroundTasks/rows.ts +++ b/client/src/components/Chat/BackgroundTasks/rows.ts @@ -28,6 +28,10 @@ export type TaskRow = { stepId?: string; threadId?: string; eventOrigin?: boolean; + /** Who a subagent row runs as, for a surface that names and draws the agent. */ + agentId?: string; + subagentType?: string; + subagentKind?: ParentSubagentSummary['subagentKind']; status: TaskRowStatus; startedAt?: number; settledAt?: number; @@ -69,6 +73,9 @@ export function findToolCallArgs( const wanted = new Set( tasks.map((task) => toolCallKey(task.messageId, task.toolCallId, task.stepId)), ); + /** A call can only answer a task that names its id. Every other call is passed over before + * its keys are built: this pass runs on each update of a streaming thread. */ + const wantedIds = new Set(tasks.map((task) => task.toolCallId)); const ambiguous = new Set(); for (let i = messages.length - 1; i >= 0; i--) { const message = messages[i]; @@ -77,7 +84,7 @@ export function findToolCallArgs( const call = part[ContentTypes.TOOL_CALL] as | { id?: string; stepId?: string; args?: ToolCallArgs } | undefined; - if (call?.id == null) continue; + if (call?.id == null || !wantedIds.has(call.id)) continue; const keys = new Set([ toolCallKey(message.messageId, call.id, call.stepId), toolCallKey(message.messageId, call.id), @@ -136,6 +143,9 @@ const subagentRow = (child: ParentSubagentSummary, stopping: ReadonlySet toolCallId: child.parentToolCallId, threadId: child.threadId, eventOrigin: child.origin === 'event', + agentId: child.agentId, + subagentType: child.subagentType, + subagentKind: child.subagentKind, status: running && stopping.has(subagentTaskKey(child.threadId, taskId)) ? 'stopping' : status, startedAt: time(child.tasks.find((task) => task.taskId === taskId)?.createdAt), settledAt: running ? undefined : time(child.updatedAt), @@ -200,6 +210,16 @@ export function buildTaskRows({ export const countActive = (rows: readonly TaskRow[]) => rows.filter(isActive).length; +/** When the next settled row ages out of the list, or `Infinity` when none will. */ +export const nextTaskExpiry = (rows: readonly TaskRow[]): number => + rows.reduce( + (next, row) => + row.settledAt != null && row.delivery == null && !isActive(row) + ? Math.min(next, row.settledAt + RECENT_SUBAGENT_WINDOW_MS + 1) + : next, + Infinity, + ); + export const countAwaitingDelivery = (rows: readonly TaskRow[]) => rows.filter(isAwaitingDelivery).length; diff --git a/client/src/components/Chat/BackgroundTasks/useTasks.ts b/client/src/components/Chat/BackgroundTasks/useTasks.ts index b79183af2f..578913e18a 100644 --- a/client/src/components/Chat/BackgroundTasks/useTasks.ts +++ b/client/src/components/Chat/BackgroundTasks/useTasks.ts @@ -22,6 +22,7 @@ import { const noThreads: ReadonlyMap = new Map(); const noRefresh = async () => undefined; +const noArgs: Record = {}; export type BackgroundTasksView = { rows: TaskRow[]; @@ -56,15 +57,19 @@ const describeToolCall = (args: ToolCallArgs): Pick /** * Joins ordinary background tools (process registry) with detached subagents * (durable index) for one conversation, and stops one or every running task. + * A reader that only counts passes `details: false` and skips the scan of the + * loaded messages that titles each tool row. */ export default function useBackgroundTasks({ conversationId, isSubmitting, now, + details = true, }: { conversationId: string; isSubmitting: boolean; now: number; + details?: boolean; }): BackgroundTasksView { const parent = useParentSubagents(); // The URL can advance before the host conversation context during navigation. @@ -150,8 +155,9 @@ export default function useBackgroundTasks({ /** Observe existing message data without fetching. Structural sharing of the * selected record ignores unrelated streaming text but includes late restoration. */ const selectArgs = useCallback( - (messages: TMessage[]) => Object.fromEntries(findToolCallArgs(messages, data?.tasks ?? [])), - [data?.tasks], + (messages: TMessage[]) => + details ? Object.fromEntries(findToolCallArgs(messages, data?.tasks ?? [])) : noArgs, + [details, data?.tasks], ); const { data: selectedArgs } = useQuery>({ queryKey: [QueryKeys.messages, conversationId], diff --git a/client/src/components/Chat/Header.tsx b/client/src/components/Chat/Header.tsx index 69484fdd39..41458d3dad 100644 --- a/client/src/components/Chat/Header.tsx +++ b/client/src/components/Chat/Header.tsx @@ -24,6 +24,7 @@ import BookmarkMenu from './Menus/BookmarkMenu'; import { useChatContext } from '~/Providers'; import AddMultiConvo from './AddMultiConvo'; import { useHasAccess } from '~/hooks'; +import { Session } from './Session'; import { cn } from '~/utils'; import store from '~/store'; @@ -93,6 +94,10 @@ function Header({ enabled: parentConversationId == null, }); + /** The session rail replaces the popover unless the deployment turned it off. Until the + * config answers, neither is drawn, so a deployment without the rail never shows its control. */ + const sessionRail = startupConfig != null && interfaceConfig.sessionRail !== false; + /** The drawer covers the header on mobile; keep its controls out of the tab order. */ const hiddenBehindNav = navVisible === true && isSmallScreen && 'hidden'; @@ -138,7 +143,15 @@ function Header({
    {showTemporaryChat && } {!isNewChat && } - {!isNewChat && parentConversationId == null && ( + {sessionRail && parentConversationId == null && ( + + )} + {startupConfig != null && !sessionRail && !isNewChat && parentConversationId == null && ( (); const { ref: plusRef, width: plusWidth } = useElementSize(); const { ref: controlsRef, width: controlsWidth } = useElementSize(); /* A row of their own once they need one, and it runs the full width of the composer (the `+` corner included), since the buttons are on the row below - it rather than in the flow. */ - const inlineChips = useMemo( - () => - chipsFitInline(packedEntries, widths, rowWidth - plusWidth - controlsWidth - CHIP_GAP * 2), - [packedEntries, widths, rowWidth, plusWidth, controlsWidth], + it rather than in the flow. Only whether they fit is read from the row's + width: the composer changes width on every frame while a panel beside the + chat opens or closes, and the bar must not render for each of them. */ + const chipsFitRow = useCallback( + ({ width }: { width: number }) => + chipsFitInline(packedEntries, widths, width - plusWidth - controlsWidth - CHIP_GAP * 2), + [packedEntries, widths, plusWidth, controlsWidth], + ); + const { ref: rowRef, value: inlineChips } = useElementSizeSelect( + chipsFitRow, ); const dictating = dictation.active || dictation.transcribing; diff --git a/client/src/components/Chat/Presentation.test.tsx b/client/src/components/Chat/Presentation.test.tsx index a26c6852e5..f067db5677 100644 --- a/client/src/components/Chat/Presentation.test.tsx +++ b/client/src/components/Chat/Presentation.test.tsx @@ -129,7 +129,7 @@ jest.mock('~/components/Chat/Input/Files/DragDropWrapper', () => ({ jest.mock('~/components/SidePanel', () => ({ SidePanelGroup: ({ panel, children }: { panel: React.ReactNode; children: React.ReactNode }) => ( -
    +
    {children} {panel}
    @@ -289,6 +289,26 @@ describe('Presentation Artifact loading', () => { expect(mockUseParentSubagentsQuery).toHaveBeenCalledWith('', { enabled: false }, false); }); + it('gives the session rail a column of its own, past the side panel', () => { + renderPresentation( + + + +
    + + + , + ); + + const slot = screen.getByTestId('session-rail-slot'); + const group = screen.getByTestId('side-panel-group'); + expect(group.nextElementSibling).toBe(slot); + expect(group).not.toContainElement(slot); + /** Empty, the column takes no room: it is not a box until a rail is drawn in it. */ + expect(slot).toHaveClass('contents'); + expect(slot).toBeEmptyDOMElement(); + }); + it('loads the parent child index only for Agent conversations', () => { renderPresentation( diff --git a/client/src/components/Chat/Presentation.tsx b/client/src/components/Chat/Presentation.tsx index f22271261b..b92b445e69 100644 --- a/client/src/components/Chat/Presentation.tsx +++ b/client/src/components/Chat/Presentation.tsx @@ -21,6 +21,7 @@ import UndockedArtifacts from '~/components/Artifacts/UndockedArtifacts'; import { appSideChatHost } from '~/Providers/SideChatHostContext'; import { artifactsUndocked } from '~/components/Artifacts/state'; import { EditorProvider, ArtifactsProvider } from '~/Providers'; +import { SessionRailSlot } from '~/components/Chat/Session'; import { SidePanelGroup } from '~/components/SidePanel'; import AppChatSurface from '~/components/Chat/Surface'; import { useGetStartupConfig } from '~/data-provider'; @@ -269,6 +270,9 @@ export default function Presentation({ + {/* The session rail's own column, past the side panel: the header's control draws + the rail here, so the list of what is running stays put while a panel opens. */} + {isUndocked && artifactsElement != null && ( diff --git a/client/src/components/Chat/Session/Elapsed.tsx b/client/src/components/Chat/Session/Elapsed.tsx new file mode 100644 index 0000000000..dd596658b5 --- /dev/null +++ b/client/src/components/Chat/Session/Elapsed.tsx @@ -0,0 +1,58 @@ +import { memo, useSyncExternalStore } from 'react'; +import { useTranslation } from 'react-i18next'; +import { getRunStepDurationLabels } from '~/utils'; +import { useLocalize } from '~/hooks'; + +const TICK_MS = 1_000; + +/** + * One clock for every running row. It ticks only while something reads it, and what reads it is + * the text that shows a duration: a second passing redraws those few words and nothing around + * them, where a clock held by the rail would redraw every row each second. + */ +const listeners = new Set<() => void>(); +let timer: ReturnType | undefined; +let current = Date.now(); + +function subscribe(listener: () => void): () => void { + listeners.add(listener); + if (timer == null) { + current = Date.now(); + timer = setInterval(() => { + current = Date.now(); + for (const notify of listeners) notify(); + }, TICK_MS); + } + return () => { + listeners.delete(listener); + if (listeners.size === 0) { + clearInterval(timer); + timer = undefined; + } + }; +} + +const read = (): number => current; + +/** How long something took, or has taken so far. */ +export const Duration = memo(function Duration({ ms }: { ms: number }) { + const localize = useLocalize(); + const { i18n } = useTranslation(); + const duration = getRunStepDurationLabels(Math.max(0, ms), i18n.language); + return ( + + {localize(duration.key, duration.values)} + + ); +}); + +/** The time since `startedAt`, counted as it passes. */ +function Elapsed({ startedAt }: { startedAt: number }) { + const now = useSyncExternalStore(subscribe, read, read); + return ; +} + +export default memo(Elapsed); diff --git a/client/src/components/Chat/Session/Now.tsx b/client/src/components/Chat/Session/Now.tsx new file mode 100644 index 0000000000..7ef3164fc0 --- /dev/null +++ b/client/src/components/Chat/Session/Now.tsx @@ -0,0 +1,62 @@ +import { memo } from 'react'; +import { getToolDisplayLabel } from '@librechat/chat'; +import { ContentTypes } from 'librechat-data-provider'; +import { getToolCallIntent, useThreadTailPart } from '@librechat/chat/react'; +import type { TMessageContentParts } from 'librechat-data-provider'; +import type { LocalizeFunction } from '~/common'; +import { useLocalize } from '~/hooks'; + +/** About what one line of the rail holds. */ +const TAIL_CHARS = 48; + +/** + * One line for the part a subagent is on: what a tool call says it is for, or the tool's name; + * the line being written; or that it is thinking. Anything else has no short telling. + */ +export function describeTailPart( + part: TMessageContentParts, + localize: LocalizeFunction, +): string | null { + if (part.type === ContentTypes.TOOL_CALL) { + const call = part[ContentTypes.TOOL_CALL]; + if (call == null) return null; + /** Only an agent's call carries arguments and a name; the assistants' call kinds do not. */ + const intent = 'args' in call ? getToolCallIntent(call.args) : undefined; + if (intent != null && intent !== '') return intent; + const name = 'name' in call ? call.name : undefined; + return name ? getToolDisplayLabel(name, localize) : null; + } + if (part.type === ContentTypes.THINK) { + return localize('com_ui_subagent_progress_thinking'); + } + if (part.type === ContentTypes.TEXT) { + const text = typeof part.text === 'string' ? part.text : (part.text?.value ?? ''); + const line = text.trimEnd().split('\n').pop()?.trim() ?? ''; + if (line.length <= TAIL_CHARS) return line === '' ? null : line; + /** The row has one line and the newest words are the news, so a long line is read from its end. */ + const tail = line.slice(-TAIL_CHARS); + return `…${tail.slice(tail.indexOf(' ') + 1)}`; + } + return null; +} + +/** + * What a running subagent is doing now. Its own leaf, so a streamed token redraws this line and + * not the row; it draws nothing for a thread the page is not following. + */ +function SessionNow({ threadId }: { threadId: string }) { + const localize = useLocalize(); + const part = useThreadTailPart(threadId, true); + const line = part == null ? null : describeTailPart(part, localize); + if (line == null) return null; + return ( +

    + {line} +

    + ); +} + +export default memo(SessionNow); diff --git a/client/src/components/Chat/Session/Rail.tsx b/client/src/components/Chat/Session/Rail.tsx new file mode 100644 index 0000000000..c079f44241 --- /dev/null +++ b/client/src/components/Chat/Session/Rail.tsx @@ -0,0 +1,290 @@ +import { useCallback, useEffect, useId, useRef } from 'react'; +import { useAtomValue } from 'jotai'; +import { Square, X } from 'lucide-react'; +import { getToolDisplayLabel } from '@librechat/chat'; +import { Button, IconButton, TooltipAnchor, useFocusTrap } from '@librechat/client'; +import { + resolveChildAgent, + activeSubagentPanel, + useParentSubagents, + readableSubagentType, + useOpenSubagentPanel, + readableSubagentTitle, + durableSubagentSelection, +} from '@librechat/chat/react'; +import type { BackgroundTasksView } from '../BackgroundTasks/useTasks'; +import type { TaskRow } from '../BackgroundTasks/rows'; +import { findTaskTarget, focusTaskTarget, scrollToTaskTarget } from '../BackgroundTasks/jump'; +import { useAgentsMapContext } from '~/Providers/AgentsMapContext'; +import Section from '../BackgroundTasks/Section'; +import { SESSION_RAIL_ID } from './state'; +import { useLocalize } from '~/hooks'; +import SessionRow from './Row'; +import { cn } from '~/utils'; + +const isActive = (row: TaskRow) => row.status === 'running' || row.status === 'stopping'; + +/** + * What a conversation has going on beside its messages, grouped by kind: the subagents it + * dispatched, then the tools it left running in the background. `sheet` is the small-screen + * form, which covers the conversation instead of sitting next to it. + */ +export default function SessionRail({ + view, + conversationId, + agentId, + sheet, + onClose, +}: { + view: BackgroundTasksView; + conversationId: string; + /** The conversation's own agent, which a self-spawned subagent runs as. */ + agentId?: string | null; + sheet: boolean; + /** `restoreFocus` is false when the reader is leaving for something the rail pointed at. */ + onClose: (restoreFocus?: boolean) => void; +}) { + const localize = useLocalize(); + const titleId = useId(); + const rootRef = useRef(null); + const setRoot = useCallback((element: HTMLElement | null) => { + rootRef.current = element; + }, []); + const closeRef = useRef(null); + const agentsMap = useAgentsMapContext(); + const parent = useParentSubagents(); + const openSubagentPanel = useOpenSubagentPanel(); + const selectedThreadId = useAtomValue(activeSubagentPanel)?.durable?.threadId; + const { rows, canStop, stop, isStopping } = view; + const subagents = rows.filter((row) => row.kind === 'subagent'); + const tools = rows.filter((row) => row.kind === 'tool'); + const running = rows.filter(isActive); + const anyStoppable = running.some(canStop); + const partiallyStoppable = running.some((row) => row.status === 'running' && !canStop(row)); + let stopAllLabel = localize('com_ui_background_tasks_stop_all'); + if (!anyStoppable) { + stopAllLabel = localize('com_ui_background_tasks_cancel_disabled'); + } else if (partiallyStoppable) { + stopAllLabel = localize('com_ui_background_tasks_stop_available'); + } + + /** + * The sheet covers the page, so it holds focus and answers Escape the way the other sheets + * do; the docked rail sits beside the page and leaves focus where it is. The trap starts on + * the first control, which while something runs is the one that stops everything, so focus is + * then moved to the close button. + */ + useFocusTrap(rootRef, sheet, onClose); + useEffect(() => { + if (sheet) closeRef.current?.focus({ preventScroll: true }); + }, [sheet]); + + const openRow = useCallback( + (row: TaskRow): boolean => { + if (row.kind === 'tool') { + const target = findTaskTarget(row); + if (target == null) return false; + if (sheet) onClose(false); + focusTaskTarget(target); + scrollToTaskTarget(target); + return true; + } + if ( + openSubagentPanel == null || + parent.conversationId !== conversationId || + row.threadId == null || + row.taskId == null + ) { + return false; + } + const child = parent.byThreadId.get(row.threadId); + if (child == null) return false; + const selection = durableSubagentSelection(conversationId, child, row.taskId); + if (selection == null) return false; + /** On a small screen the thread opens as a sheet of its own, where this one stands. */ + if (sheet) onClose(false); + openSubagentPanel({ ...selection, isSubmitting: false }); + return true; + }, + [conversationId, onClose, openSubagentPanel, parent.byThreadId, parent.conversationId, sheet], + ); + + const stopRow = useCallback((row: TaskRow) => void stop(row), [stop]); + + const summary = (group: TaskRow[]) => { + const active = group.filter(isActive).length; + const failed = group.filter((row) => row.status === 'error').length; + if (active > 0) { + return ( + + {localize( + active === 1 + ? 'com_ui_subagent_count_running_one' + : 'com_ui_subagent_count_running_other', + { 0: String(active) }, + )} + + ); + } + if (failed === 0) return undefined; + return ( + + {localize( + failed === 1 ? 'com_ui_subagent_count_failed_one' : 'com_ui_subagent_count_failed_other', + { 0: String(failed) }, + )} + + ); + }; + + const subagentRow = (row: TaskRow) => { + const agent = resolveChildAgent( + row.agentId, + row.subagentType, + agentId == null ? undefined : agentsMap?.[agentId], + agentsMap, + row.subagentKind, + ); + const source = + agent?.name || + readableSubagentType(row.subagentType, row.agentId, row.subagentKind) || + localize('com_ui_background_tasks_subagent'); + return ( + + ); + }; + + const toolRow = (row: TaskRow) => { + const source = getToolDisplayLabel(row.name, localize); + return ( + + ); + }; + + const Root = sheet ? 'div' : 'aside'; + + return ( + +
    +

    + {localize('com_ui_session')} +

    + {running.length > 0 && ( + + + + } + /> + )} + onClose()} + > + +
    +
    + {view.incomplete && ( +

    + {localize('com_ui_background_tasks_incomplete')} +

    + )} + {view.loadFailed && ( +
    +

    {localize('com_ui_background_tasks_load_failed')}

    + +
    + )} + {view.stopFailed && ( +

    + {localize('com_ui_background_tasks_stop_failed')} +

    + )} + {subagents.length > 0 && ( +
    + {subagents.map(subagentRow)} +
    + )} + {tools.length > 0 && ( +
    + {tools.map(toolRow)} +
    + )} + {rows.length === 0 && !view.loadFailed && !view.incomplete && ( +

    + {localize('com_ui_session_empty')} +

    + )} +
    +
    + ); +} diff --git a/client/src/components/Chat/Session/Row.tsx b/client/src/components/Chat/Session/Row.tsx new file mode 100644 index 0000000000..b0d4947c6a --- /dev/null +++ b/client/src/components/Chat/Session/Row.tsx @@ -0,0 +1,243 @@ +import { memo, useId, useState } from 'react'; +import { EModelEndpoint } from 'librechat-data-provider'; +import { ArrowUpRight, ChevronDown, Square } from 'lucide-react'; +import { Spinner, IconButton, TooltipAnchor } from '@librechat/client'; +import type { Agent, TMessage } from 'librechat-data-provider'; +import type { TaskRow } from '../BackgroundTasks/rows'; +import { + STATUS_KEYS, + DELIVERY_KEYS, + STATUS_CLASSES, + DELIVERY_CLASSES, +} from '../BackgroundTasks/labels'; +import ToolIcon, { getToolIconType } from '~/components/Chat/Messages/Content/ToolOutput/ToolIcon'; +import MessageIcon from '~/components/Share/MessageIcon'; +import Elapsed, { Duration } from './Elapsed'; +import { Collapse } from '~/components/ui'; +import { useLocalize } from '~/hooks'; +import SessionNow from './Now'; +import { cn } from '~/utils'; + +const agentMessage = { endpoint: EModelEndpoint.agents, isCreatedByUser: false } as TMessage; + +/** + * One subagent or background tool in the session rail. A running row is marked by its dot and + * its counting duration alone: the rail stays open beside a streaming thread, and a sweeping + * title is three compositor layers a row that every frame of the thread then pays for. + * A subagent's row opens its thread; a + * tool's row unfolds what it ran and has its own way back to the call in the conversation. + */ +function SessionRow({ + row, + title, + source, + agent, + selected = false, + canStop, + isStopping, + onStop, + onOpen, +}: { + row: TaskRow; + title: string; + /** Who or what ran it: the agent's name, or the tool's label. */ + source: string; + agent?: Pick; + /** The row's thread is the one open beside the conversation. */ + selected?: boolean; + canStop: boolean; + isStopping: boolean; + onStop: (row: TaskRow) => void; + /** Opens the subagent's thread or goes to the tool's call; false when it cannot be reached. */ + onOpen: (row: TaskRow) => boolean; +}) { + const localize = useLocalize(); + const detailId = useId(); + const [open, setOpen] = useState(false); + const [visited, setVisited] = useState(false); + const [unavailable, setUnavailable] = useState(false); + const isSubagent = row.kind === 'subagent'; + const active = row.status === 'running' || row.status === 'stopping'; + const expandable = !isSubagent && row.detail != null; + const stopLabel = localize('com_ui_background_tasks_stop'); + const jumpLabel = localize('com_ui_background_tasks_go_to_tool'); + const visit = () => setUnavailable(!onOpen(row)); + + let lead =

    {title}

    ; + if (isSubagent) { + lead = ( + + ); + } else if (expandable) { + lead = ( + + ); + } + + return ( +
  • + + {isSubagent ? ( + + + + ) : ( + + )} + {active && ( + +
    + {lead} +

    + {title !== source && {source}} + {!active && ( + {localize(STATUS_KEYS[row.status])} + )} + {row.status === 'stopping' && {localize(STATUS_KEYS.stopping)}} + {active && row.startedAt != null && } + {!active && row.startedAt != null && row.settledAt != null && ( + + )} +

    + {isSubagent && row.status === 'running' && row.threadId != null && ( + + )} + {row.delivery != null && ( +

    + {localize(DELIVERY_KEYS[row.delivery])} +

    + )} + {unavailable && ( +

    + {localize( + isSubagent + ? 'com_ui_background_tasks_subagent_unavailable' + : 'com_ui_background_tasks_tool_unavailable', + )} +

    + )} +
    + {!isSubagent && ( + +
  • + ); +} + +/** + * A task's row object is rebuilt whenever the list is, which a poll or another task settling + * causes; a row renders only when what it shows has changed. + */ +const sameRow = (a: TaskRow, b: TaskRow): boolean => { + if (a === b) return true; + const { subagent: before, ...was } = a; + const { subagent: after, ...now } = b; + const keys = Object.keys(now) as Array; + return ( + before?.threadId === after?.threadId && + before?.taskId === after?.taskId && + keys.length === Object.keys(was).length && + keys.every((key) => was[key] === now[key]) + ); +}; + +export default memo(SessionRow, (before, after) => { + const { row: was, ...rest } = before; + const { row: now, ...next } = after; + const keys = Object.keys(next) as Array; + return sameRow(was, now) && keys.every((key) => rest[key] === next[key]); +}); diff --git a/client/src/components/Chat/Session/Session.tsx b/client/src/components/Chat/Session/Session.tsx new file mode 100644 index 0000000000..f89e842f5e --- /dev/null +++ b/client/src/components/Chat/Session/Session.tsx @@ -0,0 +1,112 @@ +import { memo, useCallback, useState } from 'react'; +import { ListTodo } from 'lucide-react'; +import { createPortal } from 'react-dom'; +import { useAtom, useAtomValue } from 'jotai'; +import { TooltipAnchor } from '@librechat/client'; +import { SESSION_RAIL_ID, SESSION_TOGGLE_ID, sessionRailOpen, sessionRailSlot } from './state'; +import { ARTIFACTS_SHEET_MAX_WIDTH } from '~/utils/breakpoints'; +import useBackgroundTasks from '../BackgroundTasks/useTasks'; +import useScaledMaxWidth from '~/hooks/useScaledMaxWidth'; +import { useTaskExpiry } from '../BackgroundTasks/clock'; +import { useLocalize } from '~/hooks'; +import SessionRail from './Rail'; +import { cn } from '~/utils'; + +/** + * The chat header's session control and the rail it opens. It is always offered, so a reader + * learns one place to look, and it is the single reader of the conversation's tasks: the dot on + * the control and the rows in the rail cannot disagree. + */ +function Session({ + conversationId, + agentId, + isSubmitting, +}: { + conversationId: string; + agentId?: string | null; + isSubmitting: boolean; +}) { + const localize = useLocalize(); + const slot = useAtomValue(sessionRailSlot); + const sheet = useScaledMaxWidth(ARTIFACTS_SHEET_MAX_WIDTH); + const [docked, setDocked] = useAtom(sessionRailOpen); + /** A sheet covers the conversation, so it never reopens itself from a remembered choice. */ + const [sheetOpen, setSheetOpen] = useState(false); + const open = sheet ? sheetOpen : docked; + const [now, setNow] = useState(() => Date.now()); + const view = useBackgroundTasks({ conversationId, isSubmitting, now, details: open }); + const { activeCount, awaitingCount, failedCount, incomplete } = view; + useTaskExpiry(view.rows, setNow); + + const setOpen = useCallback( + (next: boolean) => (sheet ? setSheetOpen(next) : setDocked(next)), + [sheet, setDocked], + ); + const close = useCallback( + (restoreFocus = true) => { + setOpen(false); + if (restoreFocus) { + document.getElementById(SESSION_TOGGLE_ID)?.focus({ preventScroll: true }); + } + }, + [setOpen], + ); + + const title = localize('com_ui_session'); + const label = + [ + ...(activeCount > 0 ? [localize('com_ui_session_label_running', { 0: activeCount })] : []), + ...(awaitingCount > 0 + ? [localize('com_ui_session_label_pending', { 0: awaitingCount })] + : []), + ...(failedCount > 0 ? [localize('com_ui_session_label_failed', { 0: failedCount })] : []), + ...(incomplete ? [localize('com_ui_background_tasks_incomplete')] : []), + ].join('; ') || title; + + return ( + <> + setOpen(!open)} + className="border-border-light bg-presentation text-text-primary hover:bg-surface-active-alt aria-expanded:bg-surface-active-alt rounded-theme-control relative inline-flex size-9 flex-shrink-0 items-center justify-center border transition-all ease-in-out" + > +