mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-11-20 06:51:59 +00:00
🛤️ feat: Session Rail for Subagents and Background Tasks (#18504)
* 🛤️ 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.
This commit is contained in:
parent
4376b29740
commit
012cc1c200
42 changed files with 2438 additions and 127 deletions
|
|
@ -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<HTMLElement>('[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<HTMLElement>(
|
||||
'[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]) => (
|
||||
|
|
|
|||
|
|
@ -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<TaskRowStatus, TranslationKeys> = {
|
||||
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<Record<TaskRowStatus, string>> = {
|
||||
error: 'text-status-error',
|
||||
cancelled: 'text-status-warning',
|
||||
};
|
||||
|
||||
const DELIVERY_KEYS: Record<TaskRowDelivery, TranslationKeys> = {
|
||||
pending: 'com_ui_background_tasks_result_pending',
|
||||
failed: 'com_ui_background_tasks_result_undelivered',
|
||||
};
|
||||
|
||||
const DELIVERY_CLASSES: Partial<Record<TaskRowDelivery, string>> = {
|
||||
failed: 'text-status-warning',
|
||||
};
|
||||
|
||||
function TaskCard({
|
||||
row,
|
||||
now,
|
||||
|
|
|
|||
|
|
@ -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',
|
||||
)}
|
||||
>
|
||||
<span>{label}</span>
|
||||
<span className="tabular-nums">{count}</span>
|
||||
|
|
@ -42,7 +50,7 @@ export default function Section({
|
|||
{action}
|
||||
</div>
|
||||
<Collapse open={open}>
|
||||
<ul id={listId} className="space-y-2 pt-2">
|
||||
<ul id={listId} className={dense ? undefined : 'space-y-2 pt-2'}>
|
||||
{children}
|
||||
</ul>
|
||||
</Collapse>
|
||||
|
|
|
|||
|
|
@ -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<typeof buildTaskRows>[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', () => {
|
||||
|
|
|
|||
13
client/src/components/Chat/BackgroundTasks/clock.ts
Normal file
13
client/src/components/Chat/BackgroundTasks/clock.ts
Normal file
|
|
@ -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]);
|
||||
}
|
||||
56
client/src/components/Chat/BackgroundTasks/jump.ts
Normal file
56
client/src/components/Chat/BackgroundTasks/jump.ts
Normal file
|
|
@ -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<HTMLElement>('[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<HTMLElement>(
|
||||
'[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',
|
||||
});
|
||||
}
|
||||
24
client/src/components/Chat/BackgroundTasks/labels.ts
Normal file
24
client/src/components/Chat/BackgroundTasks/labels.ts
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
import type { TaskRowDelivery, TaskRowStatus } from './rows';
|
||||
import type { TranslationKeys } from '~/hooks/useLocalize';
|
||||
|
||||
export const STATUS_KEYS: Record<TaskRowStatus, TranslationKeys> = {
|
||||
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<Record<TaskRowStatus, string>> = {
|
||||
error: 'text-status-error',
|
||||
cancelled: 'text-status-warning',
|
||||
};
|
||||
|
||||
export const DELIVERY_KEYS: Record<TaskRowDelivery, TranslationKeys> = {
|
||||
pending: 'com_ui_background_tasks_result_pending',
|
||||
failed: 'com_ui_background_tasks_result_undelivered',
|
||||
};
|
||||
|
||||
export const DELIVERY_CLASSES: Partial<Record<TaskRowDelivery, string>> = {
|
||||
failed: 'text-status-warning',
|
||||
};
|
||||
|
|
@ -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<string>();
|
||||
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<string>
|
|||
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;
|
||||
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@ import {
|
|||
|
||||
const noThreads: ReadonlyMap<string, ParentSubagentSummary> = new Map();
|
||||
const noRefresh = async () => undefined;
|
||||
const noArgs: Record<string, ToolCallArgs> = {};
|
||||
|
||||
export type BackgroundTasksView = {
|
||||
rows: TaskRow[];
|
||||
|
|
@ -56,15 +57,19 @@ const describeToolCall = (args: ToolCallArgs): Pick<TaskRow, 'title' | 'detail'>
|
|||
/**
|
||||
* 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<TMessage[], unknown, Record<string, ToolCallArgs>>({
|
||||
queryKey: [QueryKeys.messages, conversationId],
|
||||
|
|
|
|||
|
|
@ -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({
|
|||
<div className={cn('flex shrink-0 items-center gap-2', hiddenBehindNav)}>
|
||||
{showTemporaryChat && <TemporaryChatIndicator />}
|
||||
{!isNewChat && <NewChat className={isSmallScreen ? undefined : 'hidden'} />}
|
||||
{!isNewChat && parentConversationId == null && (
|
||||
{sessionRail && parentConversationId == null && (
|
||||
<Session
|
||||
key={routeConversationId ?? Constants.NEW_CONVO}
|
||||
conversationId={routeConversationId ?? Constants.NEW_CONVO}
|
||||
agentId={conversation?.agent_id}
|
||||
isSubmitting={isSubmitting}
|
||||
/>
|
||||
)}
|
||||
{startupConfig != null && !sessionRail && !isNewChat && parentConversationId == null && (
|
||||
<BackgroundTasksButton
|
||||
key={routeConversationId}
|
||||
conversationId={routeConversationId}
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
import React, { memo, useMemo, useState, useCallback } from 'react';
|
||||
import * as Ariakit from '@ariakit/react';
|
||||
import { useElementSize } from '@librechat/chat/react';
|
||||
import { ComposerChip as Chip } from '@librechat/chat/components';
|
||||
import { Mic, Plus, Check, Square, ChevronDown } from 'lucide-react';
|
||||
import { IconButton, TooltipAnchor, SendIcon } from '@librechat/client';
|
||||
import { useElementSize, useElementSizeSelect } from '@librechat/chat/react';
|
||||
import type { TConversation, EModelEndpoint, EndpointFileConfig } from 'librechat-data-provider';
|
||||
import type { PaletteEntry, PaletteMode } from '~/hooks/Input/usePaletteEntries';
|
||||
import type { Dictation } from '~/hooks/Input/useDictation';
|
||||
|
|
@ -276,17 +276,21 @@ function Bar({
|
|||
that row; packing widest-first fills the rows instead. */
|
||||
const { ordered: packedEntries, rootRef, widths } = useChipPacking(barEntries);
|
||||
|
||||
const { ref: rowRef, width: rowWidth } = useElementSize<HTMLDivElement>();
|
||||
const { ref: plusRef, width: plusWidth } = useElementSize<HTMLSpanElement>();
|
||||
const { ref: controlsRef, width: controlsWidth } = useElementSize<HTMLDivElement>();
|
||||
|
||||
/* 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<HTMLDivElement, boolean>(
|
||||
chipsFitRow,
|
||||
);
|
||||
const dictating = dictation.active || dictation.transcribing;
|
||||
|
||||
|
|
|
|||
|
|
@ -129,7 +129,7 @@ jest.mock('~/components/Chat/Input/Files/DragDropWrapper', () => ({
|
|||
|
||||
jest.mock('~/components/SidePanel', () => ({
|
||||
SidePanelGroup: ({ panel, children }: { panel: React.ReactNode; children: React.ReactNode }) => (
|
||||
<div>
|
||||
<div data-testid="side-panel-group">
|
||||
{children}
|
||||
{panel}
|
||||
</div>
|
||||
|
|
@ -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(
|
||||
<ChatSurfaceHarness>
|
||||
<RecoilRoot>
|
||||
<Presentation>
|
||||
<div />
|
||||
</Presentation>
|
||||
</RecoilRoot>
|
||||
</ChatSurfaceHarness>,
|
||||
);
|
||||
|
||||
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(
|
||||
<ChatSurfaceHarness>
|
||||
|
|
|
|||
|
|
@ -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({
|
|||
</MessageSurfaceContext.Provider>
|
||||
</main>
|
||||
</SidePanelGroup>
|
||||
{/* 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. */}
|
||||
<SessionRailSlot />
|
||||
</ParentSubagentsProvider>
|
||||
{isUndocked && artifactsElement != null && (
|
||||
<UndockedArtifacts hidden={routePending}>{artifactsElement}</UndockedArtifacts>
|
||||
|
|
|
|||
58
client/src/components/Chat/Session/Elapsed.tsx
Normal file
58
client/src/components/Chat/Session/Elapsed.tsx
Normal file
|
|
@ -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<typeof setInterval> | 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 (
|
||||
<span
|
||||
className="tabular-nums"
|
||||
aria-label={localize(duration.announcedKey, duration.announcedValues)}
|
||||
>
|
||||
{localize(duration.key, duration.values)}
|
||||
</span>
|
||||
);
|
||||
});
|
||||
|
||||
/** The time since `startedAt`, counted as it passes. */
|
||||
function Elapsed({ startedAt }: { startedAt: number }) {
|
||||
const now = useSyncExternalStore(subscribe, read, read);
|
||||
return <Duration ms={now - startedAt} />;
|
||||
}
|
||||
|
||||
export default memo(Elapsed);
|
||||
62
client/src/components/Chat/Session/Now.tsx
Normal file
62
client/src/components/Chat/Session/Now.tsx
Normal file
|
|
@ -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 (
|
||||
<p
|
||||
data-testid="session-row-now"
|
||||
className="text-text-secondary mt-1 truncate text-xs opacity-70"
|
||||
>
|
||||
{line}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
export default memo(SessionNow);
|
||||
290
client/src/components/Chat/Session/Rail.tsx
Normal file
290
client/src/components/Chat/Session/Rail.tsx
Normal file
|
|
@ -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<HTMLElement | null>(null);
|
||||
const setRoot = useCallback((element: HTMLElement | null) => {
|
||||
rootRef.current = element;
|
||||
}, []);
|
||||
const closeRef = useRef<HTMLButtonElement>(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 (
|
||||
<span className="text-text-secondary pe-1 text-xs tabular-nums">
|
||||
{localize(
|
||||
active === 1
|
||||
? 'com_ui_subagent_count_running_one'
|
||||
: 'com_ui_subagent_count_running_other',
|
||||
{ 0: String(active) },
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
if (failed === 0) return undefined;
|
||||
return (
|
||||
<span className="text-status-error pe-1 text-xs tabular-nums">
|
||||
{localize(
|
||||
failed === 1 ? 'com_ui_subagent_count_failed_one' : 'com_ui_subagent_count_failed_other',
|
||||
{ 0: String(failed) },
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
};
|
||||
|
||||
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 (
|
||||
<SessionRow
|
||||
key={row.id}
|
||||
row={row}
|
||||
title={readableSubagentTitle(row.name, row.agentId, row.subagentKind) ?? source}
|
||||
source={source}
|
||||
agent={agent}
|
||||
selected={row.threadId != null && row.threadId === selectedThreadId}
|
||||
canStop={canStop(row)}
|
||||
isStopping={isStopping}
|
||||
onStop={stopRow}
|
||||
onOpen={openRow}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
const toolRow = (row: TaskRow) => {
|
||||
const source = getToolDisplayLabel(row.name, localize);
|
||||
return (
|
||||
<SessionRow
|
||||
key={row.id}
|
||||
row={row}
|
||||
title={row.title ?? source}
|
||||
source={source}
|
||||
canStop={canStop(row)}
|
||||
isStopping={isStopping}
|
||||
onStop={stopRow}
|
||||
onOpen={openRow}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
const Root = sheet ? 'div' : 'aside';
|
||||
|
||||
return (
|
||||
<Root
|
||||
id={SESSION_RAIL_ID}
|
||||
ref={setRoot}
|
||||
role={sheet ? 'dialog' : undefined}
|
||||
aria-modal={sheet || undefined}
|
||||
aria-labelledby={titleId}
|
||||
data-testid="session-rail"
|
||||
className={cn(
|
||||
'bg-surface-sidebar text-text-primary flex h-full shrink-0 flex-col',
|
||||
sheet ? 'fixed inset-0 z-[100]' : 'border-border-light w-80 border-s',
|
||||
)}
|
||||
>
|
||||
<div className="flex h-[3.25rem] shrink-0 items-center gap-1 ps-4 pe-2">
|
||||
<h2 id={titleId} className="min-w-0 flex-1 truncate text-sm font-semibold">
|
||||
{localize('com_ui_session')}
|
||||
</h2>
|
||||
{running.length > 0 && (
|
||||
<TooltipAnchor
|
||||
description={stopAllLabel}
|
||||
render={
|
||||
<span
|
||||
role={!anyStoppable ? 'group' : undefined}
|
||||
aria-label={!anyStoppable ? stopAllLabel : undefined}
|
||||
tabIndex={!anyStoppable ? 0 : undefined}
|
||||
className="inline-flex"
|
||||
>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="xs"
|
||||
aria-label={stopAllLabel}
|
||||
disabled={!anyStoppable || isStopping}
|
||||
onClick={() => void view.stopAll()}
|
||||
data-testid="session-stop-all"
|
||||
>
|
||||
<Square className="me-1.5 size-2.5 fill-current" aria-hidden="true" />
|
||||
{localize('com_ui_session_stop_all')}
|
||||
</Button>
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
<IconButton
|
||||
ref={closeRef}
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
label={localize('com_ui_session_close')}
|
||||
onClick={() => onClose()}
|
||||
>
|
||||
<X className="size-[1.0625rem]" aria-hidden="true" />
|
||||
</IconButton>
|
||||
</div>
|
||||
<div className="min-h-0 flex-1 space-y-4 overflow-y-auto px-2 pb-3">
|
||||
{view.incomplete && (
|
||||
<p role="status" className="text-status-warning px-2 text-sm">
|
||||
{localize('com_ui_background_tasks_incomplete')}
|
||||
</p>
|
||||
)}
|
||||
{view.loadFailed && (
|
||||
<div role="alert" className="text-status-error px-2 text-sm">
|
||||
<p>{localize('com_ui_background_tasks_load_failed')}</p>
|
||||
<button
|
||||
type="button"
|
||||
className="text-text-primary focus-visible:ring-focus-control mt-1 rounded underline focus-visible:ring-2 focus-visible:outline-none"
|
||||
onClick={() => void view.retry()}
|
||||
>
|
||||
{localize('com_ui_retry')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{view.stopFailed && (
|
||||
<p role="alert" className="text-status-error px-2 text-sm">
|
||||
{localize('com_ui_background_tasks_stop_failed')}
|
||||
</p>
|
||||
)}
|
||||
{subagents.length > 0 && (
|
||||
<Section
|
||||
dense
|
||||
label={localize('com_ui_agent_subagents')}
|
||||
count={subagents.length}
|
||||
action={summary(subagents)}
|
||||
>
|
||||
{subagents.map(subagentRow)}
|
||||
</Section>
|
||||
)}
|
||||
{tools.length > 0 && (
|
||||
<Section
|
||||
dense
|
||||
label={localize('com_ui_background_tasks')}
|
||||
count={tools.length}
|
||||
action={summary(tools)}
|
||||
>
|
||||
{tools.map(toolRow)}
|
||||
</Section>
|
||||
)}
|
||||
{rows.length === 0 && !view.loadFailed && !view.incomplete && (
|
||||
<p className="text-text-secondary px-2 pt-1 text-sm">
|
||||
{localize('com_ui_session_empty')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</Root>
|
||||
);
|
||||
}
|
||||
243
client/src/components/Chat/Session/Row.tsx
Normal file
243
client/src/components/Chat/Session/Row.tsx
Normal file
|
|
@ -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<Agent, 'name' | 'avatar'>;
|
||||
/** 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 = <p className="text-text-primary line-clamp-2 text-sm break-words">{title}</p>;
|
||||
if (isSubagent) {
|
||||
lead = (
|
||||
<button
|
||||
type="button"
|
||||
aria-current={selected || undefined}
|
||||
aria-label={`${localize('com_ui_background_tasks_open_subagent')}: ${title}`}
|
||||
onClick={visit}
|
||||
className="text-text-primary focus-visible:after:ring-focus-control block max-w-full text-start text-sm after:absolute after:inset-0 after:rounded-lg focus-visible:outline-none focus-visible:after:ring-2"
|
||||
>
|
||||
<span className="line-clamp-2 break-words">{title}</span>
|
||||
</button>
|
||||
);
|
||||
} else if (expandable) {
|
||||
lead = (
|
||||
<button
|
||||
type="button"
|
||||
aria-expanded={open}
|
||||
aria-controls={detailId}
|
||||
onClick={() => {
|
||||
setVisited(true);
|
||||
setOpen((value) => !value);
|
||||
}}
|
||||
className="text-text-primary focus-visible:ring-focus-control flex max-w-full items-start gap-1 rounded text-start text-sm focus-visible:ring-2 focus-visible:outline-none"
|
||||
>
|
||||
<span className="line-clamp-2 break-words">{title}</span>
|
||||
<ChevronDown
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
'text-text-secondary mt-1 size-3.5 shrink-0 transition-transform motion-reduce:transition-none',
|
||||
open && 'rotate-180',
|
||||
)}
|
||||
/>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<li
|
||||
data-testid="session-row"
|
||||
data-kind={row.kind}
|
||||
className={cn(
|
||||
'relative flex flex-wrap items-start gap-x-2.5 rounded-lg px-2 py-2',
|
||||
isSubagent && 'hover:bg-surface-nav-hover',
|
||||
selected && 'bg-surface-nav-selected hover:bg-surface-nav-selected',
|
||||
)}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
'bg-surface-tertiary relative mt-0.5 flex size-6 shrink-0 items-center justify-center',
|
||||
isSubagent ? 'rounded-full' : 'rounded-md',
|
||||
)}
|
||||
>
|
||||
{isSubagent ? (
|
||||
<span className="flex size-6 items-center justify-center overflow-hidden rounded-full">
|
||||
<MessageIcon message={agentMessage} agent={agent} />
|
||||
</span>
|
||||
) : (
|
||||
<ToolIcon type={getToolIconType(row.name)} className="size-3.5" />
|
||||
)}
|
||||
{active && (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
data-testid="session-row-live"
|
||||
className="bg-status-info ring-surface-sidebar absolute -end-0.5 -bottom-0.5 size-2 animate-pulse rounded-full ring-2 motion-reduce:animate-none"
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
{lead}
|
||||
<p className="text-text-secondary mt-0.5 flex flex-wrap items-center gap-x-2 text-xs">
|
||||
{title !== source && <span className="font-medium">{source}</span>}
|
||||
{!active && (
|
||||
<span className={STATUS_CLASSES[row.status]}>{localize(STATUS_KEYS[row.status])}</span>
|
||||
)}
|
||||
{row.status === 'stopping' && <span>{localize(STATUS_KEYS.stopping)}</span>}
|
||||
{active && row.startedAt != null && <Elapsed startedAt={row.startedAt} />}
|
||||
{!active && row.startedAt != null && row.settledAt != null && (
|
||||
<Duration ms={row.settledAt - row.startedAt} />
|
||||
)}
|
||||
</p>
|
||||
{isSubagent && row.status === 'running' && row.threadId != null && (
|
||||
<SessionNow threadId={row.threadId} />
|
||||
)}
|
||||
{row.delivery != null && (
|
||||
<p
|
||||
data-testid="background-task-delivery"
|
||||
className={cn('text-text-secondary mt-1 text-xs', DELIVERY_CLASSES[row.delivery])}
|
||||
>
|
||||
{localize(DELIVERY_KEYS[row.delivery])}
|
||||
</p>
|
||||
)}
|
||||
{unavailable && (
|
||||
<p role="status" className="text-text-secondary mt-1 text-xs">
|
||||
{localize(
|
||||
isSubagent
|
||||
? 'com_ui_background_tasks_subagent_unavailable'
|
||||
: 'com_ui_background_tasks_tool_unavailable',
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
{!isSubagent && (
|
||||
<TooltipAnchor
|
||||
description={jumpLabel}
|
||||
render={
|
||||
<IconButton
|
||||
variant="ghost"
|
||||
size="xs"
|
||||
shape="inset"
|
||||
label={`${jumpLabel}: ${title}`}
|
||||
onClick={visit}
|
||||
>
|
||||
<ArrowUpRight className="text-text-secondary size-3.5" aria-hidden="true" />
|
||||
</IconButton>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{row.status === 'running' && canStop && (
|
||||
<TooltipAnchor
|
||||
description={stopLabel}
|
||||
render={
|
||||
<IconButton
|
||||
variant="ghost"
|
||||
size="xs"
|
||||
shape="inset"
|
||||
label={`${stopLabel}: ${title}`}
|
||||
disabled={isStopping}
|
||||
onClick={() => onStop(row)}
|
||||
className="relative"
|
||||
>
|
||||
<Square className="text-text-secondary size-3 fill-current" aria-hidden="true" />
|
||||
</IconButton>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{row.status === 'stopping' && <Spinner className="mt-1 size-4 shrink-0" />}
|
||||
{expandable && (
|
||||
<div className="ms-[2.125rem] min-w-0 basis-full">
|
||||
<Collapse open={open}>
|
||||
{visited && (
|
||||
<pre
|
||||
id={detailId}
|
||||
className="bg-surface-primary text-text-primary mt-2 max-h-48 overflow-auto rounded-md p-2 font-mono text-xs break-words whitespace-pre-wrap"
|
||||
>
|
||||
{row.detail}
|
||||
</pre>
|
||||
)}
|
||||
</Collapse>
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<keyof typeof now>;
|
||||
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<keyof typeof next>;
|
||||
return sameRow(was, now) && keys.every((key) => rest[key] === next[key]);
|
||||
});
|
||||
112
client/src/components/Chat/Session/Session.tsx
Normal file
112
client/src/components/Chat/Session/Session.tsx
Normal file
|
|
@ -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 (
|
||||
<>
|
||||
<TooltipAnchor
|
||||
description={label}
|
||||
render={
|
||||
<button
|
||||
type="button"
|
||||
id={SESSION_TOGGLE_ID}
|
||||
aria-label={label}
|
||||
aria-expanded={open}
|
||||
aria-controls={open ? SESSION_RAIL_ID : undefined}
|
||||
data-testid="header-background-tasks-button"
|
||||
onClick={() => 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"
|
||||
>
|
||||
<ListTodo className="icon-md" aria-hidden="true" />
|
||||
{(activeCount > 0 || awaitingCount > 0 || failedCount > 0 || incomplete) && (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
data-testid="background-tasks-indicator"
|
||||
className={cn(
|
||||
'ring-presentation absolute -top-0.5 -right-0.5 size-2 rounded-full ring-2',
|
||||
failedCount > 0 || incomplete ? 'bg-status-warning' : 'bg-status-info',
|
||||
activeCount > 0 && 'animate-pulse motion-reduce:animate-none',
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
{open &&
|
||||
slot != null &&
|
||||
createPortal(
|
||||
<SessionRail
|
||||
view={view}
|
||||
conversationId={conversationId}
|
||||
agentId={agentId}
|
||||
sheet={sheet}
|
||||
onClose={close}
|
||||
/>,
|
||||
slot,
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default memo(Session);
|
||||
14
client/src/components/Chat/Session/Slot.tsx
Normal file
14
client/src/components/Chat/Session/Slot.tsx
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
import { memo } from 'react';
|
||||
import { useSetAtom } from 'jotai';
|
||||
import { sessionRailSlot } from './state';
|
||||
|
||||
/**
|
||||
* The session rail's column in the chat layout. It takes no room until a rail is drawn in it,
|
||||
* and it is memoized because the layout around it renders for every frame of a streaming reply.
|
||||
*/
|
||||
function SessionRailSlot() {
|
||||
const setSlot = useSetAtom(sessionRailSlot);
|
||||
return <div ref={setSlot} className="contents" data-testid="session-rail-slot" />;
|
||||
}
|
||||
|
||||
export default memo(SessionRailSlot);
|
||||
|
|
@ -0,0 +1,62 @@
|
|||
import React, { Profiler } from 'react';
|
||||
import { act, render, screen } from '@testing-library/react';
|
||||
import Elapsed from '../Elapsed';
|
||||
|
||||
jest.mock('~/hooks', () => ({
|
||||
useLocalize: () => (key: string, values?: Record<string, unknown>) =>
|
||||
`${key}:${Object.values(values ?? {}).join(',')}`,
|
||||
}));
|
||||
|
||||
describe('Elapsed', () => {
|
||||
beforeEach(() => jest.useFakeTimers());
|
||||
afterEach(() => jest.useRealTimers());
|
||||
|
||||
it('counts the seconds as they pass, redrawing only itself', () => {
|
||||
const start = Date.now() - 5_000;
|
||||
let siblingRenders = 0;
|
||||
const Sibling = () => {
|
||||
siblingRenders += 1;
|
||||
return <p data-testid="sibling" />;
|
||||
};
|
||||
let commits = 0;
|
||||
render(
|
||||
<Profiler id="row" onRender={() => (commits += 1)}>
|
||||
<Sibling />
|
||||
<Elapsed startedAt={start} />
|
||||
<Elapsed startedAt={start - 60_000} />
|
||||
</Profiler>,
|
||||
);
|
||||
const texts = () => screen.getAllByLabelText(/./).map((node) => node.textContent);
|
||||
expect(texts()).toEqual(['com_ui_duration_seconds:5', 'com_ui_duration_minutes:1,5']);
|
||||
const settled = commits;
|
||||
|
||||
for (let second = 0; second < 3; second += 1) {
|
||||
act(() => {
|
||||
jest.advanceTimersByTime(1_000);
|
||||
});
|
||||
}
|
||||
expect(texts()).toEqual(['com_ui_duration_seconds:8', 'com_ui_duration_minutes:1,8']);
|
||||
/** One commit a second for every reader together, and nothing beside them renders. */
|
||||
expect(commits - settled).toBe(3);
|
||||
expect(siblingRenders).toBe(1);
|
||||
});
|
||||
|
||||
it('keeps one timer for every reader and none once the last is gone', () => {
|
||||
const first = render(<Elapsed startedAt={Date.now()} />);
|
||||
const second = render(<Elapsed startedAt={Date.now()} />);
|
||||
expect(jest.getTimerCount()).toBe(1);
|
||||
first.unmount();
|
||||
expect(jest.getTimerCount()).toBe(1);
|
||||
second.unmount();
|
||||
expect(jest.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('starts a later reader from the present, not from when the clock last ran', () => {
|
||||
render(<Elapsed startedAt={Date.now()} />).unmount();
|
||||
act(() => {
|
||||
jest.advanceTimersByTime(90_000);
|
||||
});
|
||||
render(<Elapsed startedAt={Date.now() - 2_000} />);
|
||||
expect(screen.getByLabelText(/./)).toHaveTextContent('com_ui_duration_seconds:2');
|
||||
});
|
||||
});
|
||||
64
client/src/components/Chat/Session/__tests__/Now.test.ts
Normal file
64
client/src/components/Chat/Session/__tests__/Now.test.ts
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
import { ContentTypes } from 'librechat-data-provider';
|
||||
import type { TMessageContentParts } from 'librechat-data-provider';
|
||||
import type { LocalizeFunction } from '~/common';
|
||||
import { describeTailPart } from '../Now';
|
||||
|
||||
const localize = ((key: string) => key) as LocalizeFunction;
|
||||
const part = (value: Record<string, unknown>) => value as TMessageContentParts;
|
||||
const call = (name: string, args: string) =>
|
||||
part({ type: ContentTypes.TOOL_CALL, [ContentTypes.TOOL_CALL]: { id: 'call', name, args } });
|
||||
|
||||
describe('describeTailPart', () => {
|
||||
it('reads a tool call by what it says it is for', () => {
|
||||
expect(
|
||||
describeTailPart(
|
||||
call('bash_tool', '{"intent":"Run the focused specs","command":"jest"}'),
|
||||
localize,
|
||||
),
|
||||
).toBe('Run the focused specs');
|
||||
});
|
||||
|
||||
it('falls back to the tool when the call states no intent', () => {
|
||||
const line = describeTailPart(call('web_search', '{"query":"jotai"}'), localize);
|
||||
expect(typeof line).toBe('string');
|
||||
expect(line).not.toBe('');
|
||||
expect(line).not.toContain('jotai');
|
||||
});
|
||||
|
||||
it('reads text by the line being written', () => {
|
||||
expect(
|
||||
describeTailPart(
|
||||
part({
|
||||
type: ContentTypes.TEXT,
|
||||
text: 'Eleven paths are fine.\n\nChecking the bulk updates \n',
|
||||
}),
|
||||
localize,
|
||||
),
|
||||
).toBe('Checking the bulk updates');
|
||||
});
|
||||
|
||||
it('reads a long line from its end, at a word, so the newest words are the ones shown', () => {
|
||||
const line = describeTailPart(
|
||||
part({
|
||||
type: ContentTypes.TEXT,
|
||||
text: 'Fourteen write paths so far, and eleven of them invalidate the cache before they return',
|
||||
}),
|
||||
localize,
|
||||
);
|
||||
expect(line).toBe('…of them invalidate the cache before they return');
|
||||
});
|
||||
|
||||
it('says a reasoning part is thinking without quoting it', () => {
|
||||
expect(
|
||||
describeTailPart(
|
||||
part({ type: ContentTypes.THINK, think: 'private chain of thought' }),
|
||||
localize,
|
||||
),
|
||||
).toBe('com_ui_subagent_progress_thinking');
|
||||
});
|
||||
|
||||
it('has nothing to say for empty text or a part with no short telling', () => {
|
||||
expect(describeTailPart(part({ type: ContentTypes.TEXT, text: ' \n' }), localize)).toBeNull();
|
||||
expect(describeTailPart(part({ type: ContentTypes.IMAGE_FILE }), localize)).toBeNull();
|
||||
});
|
||||
});
|
||||
546
client/src/components/Chat/Session/__tests__/Session.test.tsx
Normal file
546
client/src/components/Chat/Session/__tests__/Session.test.tsx
Normal file
|
|
@ -0,0 +1,546 @@
|
|||
import React from 'react';
|
||||
import { RecoilRoot } from 'recoil';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { render, screen, waitFor, within } from '@testing-library/react';
|
||||
import { ContentTypes, QueryKeys, dataService } from 'librechat-data-provider';
|
||||
import { activeSubagentPanel, ParentSubagentsProvider } from '@librechat/chat/react';
|
||||
import type { ParentSubagentSummary, BackgroundTaskIndex, TMessage } from 'librechat-data-provider';
|
||||
import type { JotaiStore } from 'test/harness';
|
||||
import { AgentsMapContext } from '~/Providers/AgentsMapContext';
|
||||
import { SubagentIndexHostProvider } from 'test/streamHost';
|
||||
import { ChatSurfaceHarness } from 'test/harness';
|
||||
import { sessionRailOpen } from '../state';
|
||||
import SessionRailSlot from '../Slot';
|
||||
import Session from '../Session';
|
||||
|
||||
const mockSheet = { current: false };
|
||||
|
||||
jest.mock('librechat-data-provider', () => {
|
||||
const actual =
|
||||
jest.requireActual<typeof import('librechat-data-provider')>('librechat-data-provider');
|
||||
return { ...actual, dataService: { ...actual.dataService } };
|
||||
});
|
||||
|
||||
const mockTailPart = jest.fn<unknown, [string, boolean]>(() => null);
|
||||
jest.mock('@librechat/chat/react', () => ({
|
||||
...jest.requireActual('@librechat/chat/react'),
|
||||
/** The thread followers need the stream host; what they read is the chat package's to test. */
|
||||
useThreadTailPart: (threadId: string, live: boolean) => mockTailPart(threadId, live),
|
||||
}));
|
||||
|
||||
jest.mock('~/hooks', () => ({
|
||||
useLocalize: () => (key: string) => key,
|
||||
}));
|
||||
jest.mock('~/hooks/useScaledMaxWidth', () => () => mockSheet.current);
|
||||
jest.mock('~/components/Share/MessageIcon', () => ({
|
||||
__esModule: true,
|
||||
default: ({ agent }: { agent?: { name?: string } }) => (
|
||||
<span data-testid="agent-face">{agent?.name ?? ''}</span>
|
||||
),
|
||||
}));
|
||||
|
||||
const conversationId = 'convo-1';
|
||||
const startedAt = new Date(Date.now() - 30_000).toISOString();
|
||||
|
||||
const index = (overrides: Partial<BackgroundTaskIndex> = {}): BackgroundTaskIndex => ({
|
||||
conversationId,
|
||||
cancellable: true,
|
||||
tasks: [
|
||||
{
|
||||
taskId: 'task-running',
|
||||
toolName: 'bash_tool',
|
||||
toolCallId: 'call-running',
|
||||
messageId: 'message-1',
|
||||
status: 'running',
|
||||
cancellationRequested: false,
|
||||
startedAt,
|
||||
},
|
||||
{
|
||||
taskId: 'task-done',
|
||||
toolName: 'bash_tool',
|
||||
toolCallId: 'call-done',
|
||||
status: 'completed',
|
||||
cancellationRequested: false,
|
||||
startedAt,
|
||||
settledAt: new Date().toISOString(),
|
||||
delivery: 'pending',
|
||||
},
|
||||
],
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const runningChild: ParentSubagentSummary = {
|
||||
threadId: 'thread-1',
|
||||
parentMessageId: 'parent-message',
|
||||
parentToolCallId: 'call-subagent',
|
||||
subagentType: 'researcher',
|
||||
subagentKind: 'agent',
|
||||
agentId: 'agent-1',
|
||||
title: 'Research the API',
|
||||
origin: 'tool',
|
||||
status: 'running',
|
||||
latestTaskId: 'sub-task-1',
|
||||
tasks: [{ taskId: 'sub-task-1', status: 'running', createdAt: startedAt }],
|
||||
tasksTruncated: false,
|
||||
};
|
||||
|
||||
const failedChild: ParentSubagentSummary = {
|
||||
...runningChild,
|
||||
threadId: 'thread-2',
|
||||
agentId: undefined,
|
||||
title: 'Draft the changelog',
|
||||
status: 'failed',
|
||||
updatedAt: new Date().toISOString(),
|
||||
latestTaskId: 'sub-task-2',
|
||||
tasks: [{ taskId: 'sub-task-2', status: 'failed', createdAt: startedAt }],
|
||||
};
|
||||
|
||||
const messages: TMessage[] = [
|
||||
{
|
||||
messageId: 'message-1',
|
||||
conversationId,
|
||||
parentMessageId: null,
|
||||
isCreatedByUser: false,
|
||||
text: '',
|
||||
content: [
|
||||
{
|
||||
type: ContentTypes.TOOL_CALL,
|
||||
[ContentTypes.TOOL_CALL]: {
|
||||
id: 'call-running',
|
||||
name: 'bash_tool',
|
||||
args: '{"intent":"Rerun the focused specs","command":"npx jest tasks.spec.ts"}',
|
||||
},
|
||||
},
|
||||
],
|
||||
} as TMessage,
|
||||
];
|
||||
|
||||
const agentsMap = { 'agent-1': { id: 'agent-1', name: 'Code Reviewer' } };
|
||||
|
||||
const renderSession = ({
|
||||
children = [],
|
||||
remembered,
|
||||
id = conversationId,
|
||||
}: {
|
||||
children?: ParentSubagentSummary[];
|
||||
/** The reader's stored choice for the docked rail. */
|
||||
remembered?: boolean;
|
||||
id?: string;
|
||||
} = {}) => {
|
||||
jest.spyOn(dataService, 'getSubagentThread').mockImplementation(() => new Promise(() => {}));
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
queryClient.setQueryData([QueryKeys.messages, conversationId], messages);
|
||||
jest.spyOn(dataService, 'getParentSubagents').mockResolvedValue({
|
||||
parentConversationId: conversationId,
|
||||
children,
|
||||
childrenTruncated: false,
|
||||
});
|
||||
let atoms!: JotaiStore;
|
||||
const rendered = render(
|
||||
<ChatSurfaceHarness
|
||||
seed={(store) => {
|
||||
atoms = store;
|
||||
if (remembered != null) store.set(sessionRailOpen, remembered);
|
||||
}}
|
||||
>
|
||||
<RecoilRoot>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<AgentsMapContext.Provider value={agentsMap as never}>
|
||||
<SubagentIndexHostProvider>
|
||||
<ParentSubagentsProvider conversationId={id} enabled>
|
||||
<header>
|
||||
<Session conversationId={id} isSubmitting={false} />
|
||||
</header>
|
||||
<SessionRailSlot />
|
||||
</ParentSubagentsProvider>
|
||||
</SubagentIndexHostProvider>
|
||||
</AgentsMapContext.Provider>
|
||||
</QueryClientProvider>
|
||||
</RecoilRoot>
|
||||
</ChatSurfaceHarness>,
|
||||
);
|
||||
return {
|
||||
...rendered,
|
||||
queryClient,
|
||||
getSelection: () => atoms.get(activeSubagentPanel),
|
||||
isRemembered: () => atoms.get(sessionRailOpen),
|
||||
};
|
||||
};
|
||||
|
||||
const toggle = () => screen.getByTestId('header-background-tasks-button');
|
||||
const openRail = async () => {
|
||||
await userEvent.click(toggle());
|
||||
return screen.findByTestId('session-rail');
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
mockSheet.current = false;
|
||||
mockTailPart.mockReset();
|
||||
mockTailPart.mockReturnValue(null);
|
||||
localStorage.clear();
|
||||
});
|
||||
afterEach(() => jest.restoreAllMocks());
|
||||
|
||||
describe('Session', () => {
|
||||
it('is offered for a conversation with nothing running, and says so when opened', async () => {
|
||||
const getTasks = jest
|
||||
.spyOn(dataService, 'getBackgroundTasks')
|
||||
.mockResolvedValue(index({ tasks: [] }));
|
||||
renderSession();
|
||||
await waitFor(() => expect(getTasks).toHaveBeenCalledWith(conversationId));
|
||||
expect(toggle()).toHaveAccessibleName('com_ui_session');
|
||||
expect(toggle()).toHaveAttribute('aria-expanded', 'false');
|
||||
expect(screen.queryByTestId('background-tasks-indicator')).toBeNull();
|
||||
expect(screen.queryByTestId('session-rail')).toBeNull();
|
||||
|
||||
const rail = await openRail();
|
||||
expect(toggle()).toHaveAttribute('aria-expanded', 'true');
|
||||
expect(toggle()).toHaveAttribute('aria-controls', rail.id);
|
||||
expect(rail).toHaveAccessibleName('com_ui_session');
|
||||
expect(rail).toHaveTextContent('com_ui_session_empty');
|
||||
expect(within(rail).queryByTestId('session-stop-all')).toBeNull();
|
||||
});
|
||||
|
||||
it('is offered on a chat that has not been saved, without asking the server for its tasks', async () => {
|
||||
const getTasks = jest.spyOn(dataService, 'getBackgroundTasks').mockResolvedValue(index());
|
||||
renderSession({ id: 'new' });
|
||||
const rail = await openRail();
|
||||
expect(rail).toHaveTextContent('com_ui_session_empty');
|
||||
expect(getTasks).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('draws the rail in the layout column, not in the header', async () => {
|
||||
jest.spyOn(dataService, 'getBackgroundTasks').mockResolvedValue(index());
|
||||
renderSession();
|
||||
const rail = await openRail();
|
||||
expect(screen.getByTestId('session-rail-slot')).toContainElement(rail);
|
||||
expect(screen.getByRole('banner')).not.toContainElement(rail);
|
||||
expect(rail.tagName).toBe('ASIDE');
|
||||
});
|
||||
|
||||
it('counts running work on the control whether the rail is open or not', async () => {
|
||||
jest.spyOn(dataService, 'getBackgroundTasks').mockResolvedValue(index());
|
||||
renderSession({ children: [runningChild] });
|
||||
await waitFor(() =>
|
||||
expect(toggle()).toHaveAccessibleName(
|
||||
'com_ui_session_label_running; com_ui_session_label_pending',
|
||||
),
|
||||
);
|
||||
expect(screen.getByTestId('background-tasks-indicator')).toHaveClass(
|
||||
'bg-status-info',
|
||||
'animate-pulse',
|
||||
);
|
||||
expect(screen.queryByTestId('session-rail')).toBeNull();
|
||||
});
|
||||
|
||||
it('lists subagents and background tools as separate sections', async () => {
|
||||
jest.spyOn(dataService, 'getBackgroundTasks').mockResolvedValue(index());
|
||||
renderSession({ children: [runningChild, failedChild] });
|
||||
const rail = await openRail();
|
||||
await waitFor(() => expect(within(rail).getAllByTestId('session-row')).toHaveLength(4));
|
||||
|
||||
const subagents = within(rail)
|
||||
.getByRole('button', { name: /^com_ui_agent_subagents\s*\d/ })
|
||||
.closest('section') as HTMLElement;
|
||||
const tools = within(rail)
|
||||
.getByRole('button', { name: /^com_ui_background_tasks\s*\d/ })
|
||||
.closest('section') as HTMLElement;
|
||||
const subagentRows = within(subagents).getAllByTestId('session-row');
|
||||
const toolRows = within(tools).getAllByTestId('session-row');
|
||||
expect(subagentRows.map((row) => row.dataset.kind)).toEqual(['subagent', 'subagent']);
|
||||
expect(toolRows.map((row) => row.dataset.kind)).toEqual(['tool', 'tool']);
|
||||
|
||||
/** Running work leads each section and carries the live mark; a named agent is named. */
|
||||
expect(subagentRows[0]).toHaveTextContent('Research the API');
|
||||
expect(subagentRows[0]).toHaveTextContent('Code Reviewer');
|
||||
expect(within(subagentRows[0]).getByTestId('agent-face')).toHaveTextContent('Code Reviewer');
|
||||
expect(within(subagentRows[0]).getByTestId('session-row-live')).toBeInTheDocument();
|
||||
expect(subagentRows[1]).toHaveTextContent('Draft the changelog');
|
||||
expect(subagentRows[1]).toHaveTextContent('researcher');
|
||||
expect(subagentRows[1]).toHaveTextContent('com_ui_failed');
|
||||
expect(within(subagentRows[1]).queryByTestId('session-row-live')).toBeNull();
|
||||
expect(subagents).toHaveTextContent('com_ui_subagent_count_running_one');
|
||||
|
||||
expect(toolRows[0]).toHaveTextContent('Rerun the focused specs');
|
||||
expect(toolRows[1]).toHaveTextContent('com_ui_background_tasks_completed');
|
||||
expect(within(toolRows[1]).getByTestId('background-task-delivery')).toHaveTextContent(
|
||||
'com_ui_background_tasks_result_pending',
|
||||
);
|
||||
});
|
||||
|
||||
it('says what a running subagent is doing now, and nothing for one that has finished', async () => {
|
||||
jest.spyOn(dataService, 'getBackgroundTasks').mockResolvedValue(index({ tasks: [] }));
|
||||
mockTailPart.mockReturnValue({
|
||||
type: ContentTypes.TOOL_CALL,
|
||||
[ContentTypes.TOOL_CALL]: {
|
||||
id: 'call-read',
|
||||
name: 'bash_tool',
|
||||
args: '{"intent":"Read the auth service","command":"cat AuthService.js"}',
|
||||
},
|
||||
});
|
||||
renderSession({ children: [runningChild, failedChild] });
|
||||
const rail = await openRail();
|
||||
await waitFor(() => expect(within(rail).getAllByTestId('session-row')).toHaveLength(2));
|
||||
const [running, failed] = within(rail).getAllByTestId('session-row');
|
||||
expect(within(running).getByTestId('session-row-now')).toHaveTextContent(
|
||||
'Read the auth service',
|
||||
);
|
||||
expect(mockTailPart).toHaveBeenCalledWith('thread-1', true);
|
||||
expect(within(failed).queryByTestId('session-row-now')).toBeNull();
|
||||
expect(mockTailPart).not.toHaveBeenCalledWith('thread-2', expect.anything());
|
||||
});
|
||||
|
||||
it('draws no line for a running subagent the page is not following', async () => {
|
||||
jest.spyOn(dataService, 'getBackgroundTasks').mockResolvedValue(index({ tasks: [] }));
|
||||
renderSession({ children: [runningChild] });
|
||||
const rail = await openRail();
|
||||
await within(rail).findByTestId('session-row');
|
||||
expect(within(rail).queryByTestId('session-row-now')).toBeNull();
|
||||
});
|
||||
|
||||
it('opens a subagent from its row and marks the row while its thread is open', async () => {
|
||||
jest.spyOn(dataService, 'getBackgroundTasks').mockResolvedValue(index({ tasks: [] }));
|
||||
const { getSelection } = renderSession({ children: [runningChild] });
|
||||
const rail = await openRail();
|
||||
const open = await within(rail).findByRole('button', {
|
||||
name: 'com_ui_background_tasks_open_subagent: Research the API',
|
||||
});
|
||||
expect(open).not.toHaveAttribute('aria-current');
|
||||
await userEvent.click(open);
|
||||
expect(getSelection()).toMatchObject({
|
||||
durable: { threadId: 'thread-1', taskId: 'sub-task-1' },
|
||||
});
|
||||
await waitFor(() => expect(open).toHaveAttribute('aria-current', 'true'));
|
||||
/** Docked, the rail stays beside the thread it opened. */
|
||||
expect(screen.getByTestId('session-rail')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('unfolds what a tool ran and goes to its call in the conversation', async () => {
|
||||
jest.spyOn(dataService, 'getBackgroundTasks').mockResolvedValue(index());
|
||||
renderSession();
|
||||
const target = document.createElement('button');
|
||||
target.id = 'message-1';
|
||||
target.dataset.toolCallId = 'call-running';
|
||||
target.scrollIntoView = jest.fn();
|
||||
document.body.append(target);
|
||||
try {
|
||||
const rail = await openRail();
|
||||
const row = (await within(rail).findAllByTestId('session-row'))[0];
|
||||
expect(row).not.toHaveTextContent('npx jest tasks.spec.ts');
|
||||
await userEvent.click(
|
||||
await within(row).findByRole('button', { name: /^Rerun the focused specs/ }),
|
||||
);
|
||||
expect(row).toHaveTextContent('npx jest tasks.spec.ts');
|
||||
await userEvent.click(
|
||||
within(row).getByRole('button', { name: /^com_ui_background_tasks_go_to_tool:/ }),
|
||||
);
|
||||
expect(target.scrollIntoView).toHaveBeenCalledWith({ block: 'center', behavior: 'smooth' });
|
||||
expect(target).toHaveFocus();
|
||||
expect(screen.getByTestId('session-rail')).toBeInTheDocument();
|
||||
} finally {
|
||||
target.remove();
|
||||
}
|
||||
});
|
||||
|
||||
it('says when a tool call is not in the loaded messages', async () => {
|
||||
jest.spyOn(dataService, 'getBackgroundTasks').mockResolvedValue(index());
|
||||
renderSession();
|
||||
const rail = await openRail();
|
||||
const row = (await within(rail).findAllByTestId('session-row'))[0];
|
||||
await userEvent.click(
|
||||
within(row).getByRole('button', { name: /^com_ui_background_tasks_go_to_tool:/ }),
|
||||
);
|
||||
expect(within(row).getByRole('status')).toHaveTextContent(
|
||||
'com_ui_background_tasks_tool_unavailable',
|
||||
);
|
||||
});
|
||||
|
||||
it('stops one task from its row and every running task from the header', async () => {
|
||||
jest.spyOn(dataService, 'getBackgroundTasks').mockResolvedValue(index());
|
||||
const cancelTools = jest
|
||||
.spyOn(dataService, 'cancelBackgroundTasks')
|
||||
.mockResolvedValue({ results: [{ taskId: 'task-running', status: 'requested' }] });
|
||||
const cancelSubagent = jest.spyOn(dataService, 'controlSubagentTask').mockResolvedValue({
|
||||
receipt: {
|
||||
invocationId: 'invocation',
|
||||
action: 'cancel',
|
||||
status: 'accepted',
|
||||
createdAt: startedAt,
|
||||
updatedAt: startedAt,
|
||||
},
|
||||
});
|
||||
renderSession({ children: [runningChild] });
|
||||
const rail = await openRail();
|
||||
await waitFor(() => expect(within(rail).getAllByTestId('session-row')).toHaveLength(3));
|
||||
|
||||
await userEvent.click(
|
||||
within(rail).getByRole('button', {
|
||||
name: 'com_ui_background_tasks_stop: Rerun the focused specs',
|
||||
}),
|
||||
);
|
||||
await waitFor(() =>
|
||||
expect(cancelTools).toHaveBeenCalledWith(conversationId, { taskIds: ['task-running'] }),
|
||||
);
|
||||
expect(cancelSubagent).not.toHaveBeenCalled();
|
||||
|
||||
await waitFor(() => expect(within(rail).getByTestId('session-stop-all')).toBeEnabled());
|
||||
await userEvent.click(within(rail).getByTestId('session-stop-all'));
|
||||
await waitFor(() =>
|
||||
expect(cancelSubagent).toHaveBeenCalledWith(
|
||||
conversationId,
|
||||
'thread-1',
|
||||
expect.objectContaining({ taskId: 'sub-task-1', action: 'cancel' }),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps stop-all disabled and explained when the server does not let tools be stopped', async () => {
|
||||
jest.spyOn(dataService, 'getBackgroundTasks').mockResolvedValue(index({ cancellable: false }));
|
||||
renderSession();
|
||||
const rail = await openRail();
|
||||
const stopAll = await within(rail).findByTestId('session-stop-all');
|
||||
expect(stopAll).toBeDisabled();
|
||||
expect(stopAll).toHaveAccessibleName('com_ui_background_tasks_cancel_disabled');
|
||||
expect(
|
||||
within(rail).queryByRole('button', { name: /^com_ui_background_tasks_stop:/ }),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it('shows a load failure in the rail and lets the reader retry', async () => {
|
||||
const getTasks = jest
|
||||
.spyOn(dataService, 'getBackgroundTasks')
|
||||
.mockRejectedValueOnce(new Error('network unavailable'))
|
||||
.mockResolvedValue(index());
|
||||
renderSession();
|
||||
const rail = await openRail();
|
||||
const alert = await within(rail).findByRole('alert');
|
||||
expect(alert).toHaveTextContent('com_ui_background_tasks_load_failed');
|
||||
expect(rail).not.toHaveTextContent('com_ui_session_empty');
|
||||
await userEvent.click(within(alert).getByRole('button', { name: 'com_ui_retry' }));
|
||||
await waitFor(() => expect(within(rail).getAllByTestId('session-row')).toHaveLength(2));
|
||||
expect(within(rail).queryByRole('alert')).toBeNull();
|
||||
expect(getTasks).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('warns that results may be missing while the task store is incomplete', async () => {
|
||||
jest
|
||||
.spyOn(dataService, 'getBackgroundTasks')
|
||||
.mockResolvedValue(index({ tasks: [], complete: false }));
|
||||
renderSession();
|
||||
await waitFor(() =>
|
||||
expect(toggle()).toHaveAccessibleName('com_ui_background_tasks_incomplete'),
|
||||
);
|
||||
expect(screen.getByTestId('background-tasks-indicator')).toHaveClass('bg-status-warning');
|
||||
const rail = await openRail();
|
||||
expect(within(rail).getByRole('status')).toHaveTextContent(
|
||||
'com_ui_background_tasks_incomplete',
|
||||
);
|
||||
expect(rail).not.toHaveTextContent('com_ui_session_empty');
|
||||
});
|
||||
|
||||
it('closes from its own button, hands focus back, and remembers the choice', async () => {
|
||||
jest.spyOn(dataService, 'getBackgroundTasks').mockResolvedValue(index({ tasks: [] }));
|
||||
const { isRemembered } = renderSession();
|
||||
const rail = await openRail();
|
||||
expect(isRemembered()).toBe(true);
|
||||
await userEvent.click(within(rail).getByRole('button', { name: 'com_ui_session_close' }));
|
||||
expect(screen.queryByTestId('session-rail')).toBeNull();
|
||||
expect(toggle()).toHaveFocus();
|
||||
expect(toggle()).toHaveAttribute('aria-expanded', 'false');
|
||||
expect(isRemembered()).toBe(false);
|
||||
});
|
||||
|
||||
it('reopens docked from the remembered choice', async () => {
|
||||
jest.spyOn(dataService, 'getBackgroundTasks').mockResolvedValue(index());
|
||||
renderSession({ remembered: true });
|
||||
const rail = await screen.findByTestId('session-rail');
|
||||
await waitFor(() => expect(within(rail).getAllByTestId('session-row')).toHaveLength(2));
|
||||
expect(toggle()).toHaveAttribute('aria-expanded', 'true');
|
||||
});
|
||||
|
||||
it('leaves the docked rail out of the tab trap', async () => {
|
||||
jest.spyOn(dataService, 'getBackgroundTasks').mockResolvedValue(index({ tasks: [] }));
|
||||
renderSession();
|
||||
const rail = await openRail();
|
||||
expect(rail).not.toHaveAttribute('aria-modal');
|
||||
expect(toggle()).toHaveFocus();
|
||||
await userEvent.tab();
|
||||
expect(within(rail).getByRole('button', { name: 'com_ui_session_close' })).toHaveFocus();
|
||||
await userEvent.tab();
|
||||
expect(rail).not.toContainElement(document.activeElement as HTMLElement);
|
||||
});
|
||||
|
||||
describe('on a small screen', () => {
|
||||
beforeEach(() => {
|
||||
mockSheet.current = true;
|
||||
});
|
||||
|
||||
it('does not cover the conversation from a remembered choice', async () => {
|
||||
jest.spyOn(dataService, 'getBackgroundTasks').mockResolvedValue(index());
|
||||
const { isRemembered } = renderSession({ remembered: true });
|
||||
await waitFor(() => expect(toggle()).not.toHaveAccessibleName('com_ui_session'));
|
||||
expect(screen.queryByTestId('session-rail')).toBeNull();
|
||||
expect(toggle()).toHaveAttribute('aria-expanded', 'false');
|
||||
expect(isRemembered()).toBe(true);
|
||||
});
|
||||
|
||||
it('opens as a sheet that takes focus and closes on Escape', async () => {
|
||||
jest.spyOn(dataService, 'getBackgroundTasks').mockResolvedValue(index());
|
||||
const { isRemembered } = renderSession();
|
||||
await userEvent.click(toggle());
|
||||
const sheet = await screen.findByRole('dialog', { name: 'com_ui_session' });
|
||||
expect(sheet).toHaveClass('fixed', 'inset-0');
|
||||
expect(within(sheet).getByRole('button', { name: 'com_ui_session_close' })).toHaveFocus();
|
||||
/** A sheet is a visit, not a layout choice: it is not what the docked rail remembers. */
|
||||
expect(isRemembered()).toBe(false);
|
||||
await userEvent.keyboard('{Escape}');
|
||||
expect(screen.queryByRole('dialog')).toBeNull();
|
||||
expect(toggle()).toHaveFocus();
|
||||
});
|
||||
|
||||
it('keeps keyboard focus inside the sheet, which covers everything else', async () => {
|
||||
jest.spyOn(dataService, 'getBackgroundTasks').mockResolvedValue(index({ tasks: [] }));
|
||||
renderSession();
|
||||
await userEvent.click(toggle());
|
||||
const sheet = await screen.findByRole('dialog', { name: 'com_ui_session' });
|
||||
expect(sheet).toHaveAttribute('aria-modal', 'true');
|
||||
const close = within(sheet).getByRole('button', { name: 'com_ui_session_close' });
|
||||
expect(close).toHaveFocus();
|
||||
|
||||
/** The control behind the sheet is the next tab stop in the page, and is not reached. */
|
||||
await userEvent.tab();
|
||||
expect(sheet).toContainElement(document.activeElement as HTMLElement);
|
||||
await userEvent.tab({ shift: true });
|
||||
expect(sheet).toContainElement(document.activeElement as HTMLElement);
|
||||
|
||||
await userEvent.keyboard('{Escape}');
|
||||
expect(screen.queryByRole('dialog')).toBeNull();
|
||||
expect(toggle()).toHaveFocus();
|
||||
});
|
||||
|
||||
it('starts on the close button, not on the control that stops everything', async () => {
|
||||
jest.spyOn(dataService, 'getBackgroundTasks').mockResolvedValue(index());
|
||||
renderSession();
|
||||
await waitFor(() => expect(toggle()).not.toHaveAccessibleName('com_ui_session'));
|
||||
await userEvent.click(toggle());
|
||||
const sheet = await screen.findByRole('dialog', { name: 'com_ui_session' });
|
||||
expect(within(sheet).getByTestId('session-stop-all')).toBeInTheDocument();
|
||||
expect(within(sheet).getByRole('button', { name: 'com_ui_session_close' })).toHaveFocus();
|
||||
});
|
||||
|
||||
it('gets out of the way of the thread it opens', async () => {
|
||||
jest.spyOn(dataService, 'getBackgroundTasks').mockResolvedValue(index({ tasks: [] }));
|
||||
const { getSelection } = renderSession({ children: [runningChild] });
|
||||
await userEvent.click(toggle());
|
||||
const sheet = await screen.findByRole('dialog', { name: 'com_ui_session' });
|
||||
await userEvent.click(
|
||||
await within(sheet).findByRole('button', {
|
||||
name: 'com_ui_background_tasks_open_subagent: Research the API',
|
||||
}),
|
||||
);
|
||||
expect(getSelection()).toMatchObject({ durable: { threadId: 'thread-1' } });
|
||||
expect(screen.queryByRole('dialog', { name: 'com_ui_session' })).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
2
client/src/components/Chat/Session/index.ts
Normal file
2
client/src/components/Chat/Session/index.ts
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
export { default as Session } from './Session';
|
||||
export { default as SessionRailSlot } from './Slot';
|
||||
14
client/src/components/Chat/Session/state.ts
Normal file
14
client/src/components/Chat/Session/state.ts
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
import { atom } from 'jotai';
|
||||
import { createStorageAtom } from '~/store/jotai-utils';
|
||||
|
||||
/** Whether the session rail is showing: the reader's choice, kept across chats and reloads. */
|
||||
export const sessionRailOpen = createStorageAtom<boolean>('sessionRailOpen', false);
|
||||
|
||||
/**
|
||||
* Where the rail is drawn. The chat layout owns the column and the header owns the rail, so
|
||||
* the header's control is the one reader of the session's tasks whether the rail shows or not.
|
||||
*/
|
||||
export const sessionRailSlot = atom<HTMLElement | null>(null);
|
||||
|
||||
export const SESSION_RAIL_ID = 'session-rail';
|
||||
export const SESSION_TOGGLE_ID = 'session-rail-toggle';
|
||||
|
|
@ -5,6 +5,10 @@ import Header from '../Header';
|
|||
|
||||
const mockEndpoint = { current: 'agents' };
|
||||
const mockSmallScreen = { current: false };
|
||||
const mockRoute: { current: string | undefined } = { current: 'convo-1' };
|
||||
const mockStartupConfig: { current: { interface: Record<string, unknown> } | undefined } = {
|
||||
current: { interface: {} },
|
||||
};
|
||||
const codeConversation = {
|
||||
conversationId: 'convo-1',
|
||||
codeEnvironmentMode: 'attached',
|
||||
|
|
@ -15,7 +19,7 @@ const mockConversation: { current: Record<string, unknown> | null } = {
|
|||
};
|
||||
|
||||
jest.mock('react-router-dom', () => ({
|
||||
useParams: () => ({ conversationId: 'convo-1' }),
|
||||
useParams: () => ({ conversationId: mockRoute.current }),
|
||||
}));
|
||||
jest.mock('recoil', () => ({
|
||||
useRecoilValue: (selector: string) =>
|
||||
|
|
@ -30,7 +34,9 @@ jest.mock('librechat-data-provider', () => ({
|
|||
isForcedTemporaryRetention:
|
||||
jest.requireActual('librechat-data-provider').isForcedTemporaryRetention,
|
||||
}));
|
||||
jest.mock('~/data-provider', () => ({ useGetStartupConfig: () => ({ data: undefined }) }));
|
||||
jest.mock('~/data-provider', () => ({
|
||||
useGetStartupConfig: () => ({ data: mockStartupConfig.current }),
|
||||
}));
|
||||
jest.mock('~/hooks', () => ({ useHasAccess: () => false }));
|
||||
jest.mock('~/Providers', () => ({
|
||||
useChatContext: () => ({ conversation: mockConversation.current }),
|
||||
|
|
@ -58,7 +64,10 @@ jest.mock('../TemporaryChat', () => ({
|
|||
}));
|
||||
jest.mock('../Trace', () => ({ useTraceControl: () => ({ show: false }) }));
|
||||
jest.mock('../BackgroundTasks', () => ({
|
||||
BackgroundTasksButton: jest.fn(() => <div data-testid="conversation-tasks" />),
|
||||
BackgroundTasksButton: jest.fn(() => <div data-testid="conversation-tasks-popover" />),
|
||||
}));
|
||||
jest.mock('../Session', () => ({
|
||||
Session: jest.fn(() => <div data-testid="conversation-tasks" />),
|
||||
}));
|
||||
jest.mock('../PullRequest', () => ({
|
||||
PullRequestChip: jest.fn(() => <div data-testid="conversation-pull-request" />),
|
||||
|
|
@ -71,12 +80,16 @@ jest.mock('../AddMultiConvo', () => () => null);
|
|||
|
||||
describe('Header stacking', () => {
|
||||
const backgroundTasks = jest.requireMock('../BackgroundTasks').BackgroundTasksButton as jest.Mock;
|
||||
const session = jest.requireMock('../Session').Session as jest.Mock;
|
||||
const pullRequestChip = jest.requireMock('../PullRequest').PullRequestChip as jest.Mock;
|
||||
|
||||
const headerMenu = jest.requireMock('../Menus').HeaderMenu as jest.Mock;
|
||||
|
||||
beforeEach(() => {
|
||||
backgroundTasks.mockClear();
|
||||
session.mockClear();
|
||||
mockRoute.current = 'convo-1';
|
||||
mockStartupConfig.current = { interface: {} };
|
||||
pullRequestChip.mockClear();
|
||||
headerMenu.mockClear();
|
||||
headerMenu.mockImplementation(() => null);
|
||||
|
|
@ -113,7 +126,44 @@ describe('Header stacking', () => {
|
|||
const { container } = render(<Header />);
|
||||
|
||||
expect(container.firstElementChild).toHaveClass('absolute', 'top-0', 'z-20');
|
||||
expect(backgroundTasks).toHaveBeenCalled();
|
||||
expect(session).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('hands the session control the routed conversation and its agent', () => {
|
||||
mockConversation.current = { ...codeConversation, agent_id: 'agent-1' };
|
||||
render(<Header />);
|
||||
expect(session.mock.calls[0][0]).toMatchObject({
|
||||
conversationId: 'convo-1',
|
||||
agentId: 'agent-1',
|
||||
});
|
||||
expect(backgroundTasks).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('offers the session control on a chat that has not been saved yet', () => {
|
||||
mockRoute.current = undefined;
|
||||
render(<Header />);
|
||||
expect(session.mock.calls[0][0]).toMatchObject({ conversationId: 'new' });
|
||||
});
|
||||
|
||||
test('keeps the popover when the deployment turns the session rail off', () => {
|
||||
mockStartupConfig.current = { interface: { sessionRail: false } };
|
||||
render(<Header />);
|
||||
expect(session).not.toHaveBeenCalled();
|
||||
expect(backgroundTasks.mock.calls[0][0]).toMatchObject({ conversationId: 'convo-1' });
|
||||
});
|
||||
|
||||
test('offers the popover no new chat to list', () => {
|
||||
mockStartupConfig.current = { interface: { sessionRail: false } };
|
||||
mockRoute.current = 'new';
|
||||
render(<Header />);
|
||||
expect(backgroundTasks).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('draws neither task control until the config has answered', () => {
|
||||
mockStartupConfig.current = undefined;
|
||||
render(<Header />);
|
||||
expect(session).not.toHaveBeenCalled();
|
||||
expect(backgroundTasks).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('keeps conversation task controls mounted across endpoint switches', () => {
|
||||
|
|
@ -125,6 +175,7 @@ describe('Header stacking', () => {
|
|||
|
||||
test('does not mount parent task controls on child threads', () => {
|
||||
render(<Header parentConversationId="parent" />);
|
||||
expect(session).not.toHaveBeenCalled();
|
||||
expect(backgroundTasks).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -2751,6 +2751,13 @@
|
|||
"com_ui_permissions_updated_success": "Permissions updated successfully",
|
||||
"com_ui_schedules_filter": "Filter schedules...",
|
||||
"com_ui_sharing": "Sharing",
|
||||
"com_ui_session": "Session",
|
||||
"com_ui_session_close": "Close session",
|
||||
"com_ui_session_empty": "Subagents and background tasks from this chat will show up here.",
|
||||
"com_ui_session_label_failed": "Session, {{0}} results not delivered",
|
||||
"com_ui_session_label_pending": "Session, {{0}} results pending",
|
||||
"com_ui_session_label_running": "Session, {{0}} running",
|
||||
"com_ui_session_stop_all": "Stop all",
|
||||
"com_ui_side_chat_load_error": "This conversation couldn't be loaded.",
|
||||
"com_ui_side_chat_open_beside": "Open beside chat",
|
||||
"com_ui_side_chat_open_main": "Open as the main chat",
|
||||
|
|
|
|||
|
|
@ -29,6 +29,16 @@ transcript, from a Chromium trace of the built client:
|
|||
the slide; each direction is traced on its own. `ms/frame` and the longest task say whether
|
||||
the slide can hold a frame rate. `FADE_PERF_PROFILE=1` adds the script's self time and
|
||||
`FADE_PERF_WHY=1` the components that render for each toggle.
|
||||
- **`rail.perf.spec.ts`**: the cost of opening and closing the session rail beside the thread,
|
||||
with the sidebar's toggle traced in the same run as the yardstick. The rail does not slide, so
|
||||
the thread changes width once. `FADE_PERF_WHY=1` counts what renders for each toggle, beside an
|
||||
idle second and the sidebar's: no message row should, at any thread length.
|
||||
A second test grows the last reply for three seconds with the rail closed and then open and
|
||||
listing running work, and prints the page's compositor layer count beside each: a row that
|
||||
animates is a layer, and every frame of the thread pays for the layers on the page. For the
|
||||
cost per kind of stream event, run the replay with `FADE_PERF_RAIL=closed` and then `open`:
|
||||
the conversation becomes an agent's with running tools, finished tools and subagents staged
|
||||
for the rail (`rail.ts`), and the two runs differ only in whether the rail is showing.
|
||||
- **`scroll.perf.spec.ts`**: the cost of reading back through the thread, a page at a time
|
||||
from the latest turn towards the first and back. Rows far from the viewport are skipped by
|
||||
the browser and laid out again as a scroll brings them near, so this is where that work
|
||||
|
|
@ -74,6 +84,7 @@ by side.
|
|||
| `FADE_PERF_GAP_MS` | Pause after each replayed frame; 150 by default. |
|
||||
| `FADE_PERF_ANIMATIONS` | `1` lists what is animating during the replay, and which properties. |
|
||||
| `FADE_PERF_WHY` | `1` counts component renders across the replay, with their causes. |
|
||||
| `FADE_PERF_RAIL` | `closed` or `open`: stages background work for the session rail. |
|
||||
| `FADE_PERF_WHY_LIMIT` | How many components that count lists; 80 by default. |
|
||||
|
||||
## Reading the output
|
||||
|
|
|
|||
154
e2e/benchmarks-fade/rail.perf.spec.ts
Normal file
154
e2e/benchmarks-fade/rail.perf.spec.ts
Normal file
|
|
@ -0,0 +1,154 @@
|
|||
import { test } from '@playwright/test';
|
||||
import { CONVOS, chatName, openChat, removeChats, seedChat } from './chats';
|
||||
import { formatFrameCost, traceFrames } from './trace';
|
||||
import { setRail, stageBackgroundWork } from './rail';
|
||||
import { installRenderProbe } from './why';
|
||||
|
||||
/**
|
||||
* What opening and closing the session rail costs a long thread.
|
||||
*
|
||||
* The rail takes a column beside the chat, so opening it narrows the thread and closing it
|
||||
* widens it again. Unlike the sidebar it does not slide: the width changes once, so the thread
|
||||
* should be laid out once, and nothing in the thread should render, because no state a message
|
||||
* row reads changes. Each direction is traced on its own, with the sidebar's toggle traced in
|
||||
* the same run as the yardstick, and `FADE_PERF_WHY=1` counts what React rendered.
|
||||
*/
|
||||
|
||||
test.use({ trace: 'off', video: 'off' });
|
||||
|
||||
const SETTLE_MS = 1_000;
|
||||
const CPU_RATE = Number(process.env.FADE_PERF_CPU) || 1;
|
||||
const WHY = process.env.FADE_PERF_WHY === '1';
|
||||
const RAIL_TOGGLE = 'header-background-tasks-button';
|
||||
|
||||
test.describe('session rail toggle beside a long thread', () => {
|
||||
test.skip(CONVOS.length === 0, 'FADE_PERF_CHATS names no exported conversation');
|
||||
test.afterAll(removeChats);
|
||||
|
||||
for (const convo of CONVOS) {
|
||||
test(`toggle the session rail beside ${chatName(convo)}`, async ({ page, browser }) => {
|
||||
await seedChat(convo);
|
||||
const probe = WHY ? await installRenderProbe(page) : null;
|
||||
const size = await openChat(page, convo);
|
||||
console.log(`\n${chatName(convo)}: ${size.rows} rows, ${size.nodes} elements`);
|
||||
|
||||
const click = (testId: string) => async () => {
|
||||
await page.evaluate((id) => {
|
||||
document.querySelector<HTMLElement>(`[data-testid="${id}"]`)?.click();
|
||||
}, testId);
|
||||
await page.waitForTimeout(SETTLE_MS);
|
||||
};
|
||||
const railOpen = () =>
|
||||
page.evaluate(() => document.querySelector('[data-testid="session-rail"]') != null);
|
||||
const sidebarExpanded = await page.evaluate(
|
||||
() => document.querySelector('[data-testid="close-sidebar-button"]') != null,
|
||||
);
|
||||
const sidebar = sidebarExpanded
|
||||
? (['close-sidebar-button', 'open-sidebar-button'] as const)
|
||||
: (['open-sidebar-button', 'close-sidebar-button'] as const);
|
||||
|
||||
const session = await page.context().newCDPSession(page);
|
||||
if (CPU_RATE > 1) {
|
||||
await session.send('Emulation.setCPUThrottlingRate', { rate: CPU_RATE });
|
||||
}
|
||||
|
||||
for (let round = 1; round <= 3; round += 1) {
|
||||
for (const direction of ['open', 'close'] as const) {
|
||||
const cost = await traceFrames(browser, page, click(RAIL_TOGGLE));
|
||||
console.log(formatFrameCost(`rail ${direction} (round ${round}) cpu x${CPU_RATE}`, cost));
|
||||
}
|
||||
for (const testId of sidebar) {
|
||||
const cost = await traceFrames(browser, page, click(testId));
|
||||
const name = testId.startsWith('close') ? 'collapse' : 'expand';
|
||||
console.log(formatFrameCost(`sidebar ${name} (round ${round}) cpu x${CPU_RATE}`, cost));
|
||||
}
|
||||
}
|
||||
|
||||
if (probe) {
|
||||
const SHOWN = Number(process.env.FADE_PERF_WHY_LIMIT) || 14;
|
||||
const count = async (name: string, act: () => Promise<void>) => {
|
||||
await probe.start();
|
||||
await act();
|
||||
const { commits, lines } = await probe.finish(400);
|
||||
const renders = lines.reduce((sum, line) => sum + Number(line.trim().split(/\s+/)[0]), 0);
|
||||
console.log(
|
||||
`${name}: ${commits} commits, ${lines.length} components rendered ${renders} times ` +
|
||||
`in all; thread has ${size.rows} rows\n${lines.slice(0, SHOWN).join('\n')}`,
|
||||
);
|
||||
};
|
||||
/** A second with nothing done, for what the page renders by itself. */
|
||||
await count('idle', () => page.waitForTimeout(SETTLE_MS));
|
||||
await count(`rail open`, click(RAIL_TOGGLE));
|
||||
await count(`rail close (rail open before: ${await railOpen()})`, click(RAIL_TOGGLE));
|
||||
for (const testId of sidebar) {
|
||||
await count(
|
||||
`sidebar ${testId.startsWith('close') ? 'collapse' : 'expand'}`,
|
||||
click(testId),
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* What an open rail adds to each frame of a thread that is streaming.
|
||||
*
|
||||
* The rail's rows do nothing while the thread streams, but anything in them that animates is a
|
||||
* compositor layer, and a frame's style, layerize and commit steps grow with the layers on the
|
||||
* page. The last reply is grown by a few words every 50 ms for three seconds, with the rail
|
||||
* closed and then open and listing running work; the layer count says where a difference is from.
|
||||
*/
|
||||
test.describe('session rail beside a streaming thread', () => {
|
||||
test.skip(CONVOS.length === 0, 'FADE_PERF_CHATS names no exported conversation');
|
||||
test.afterAll(removeChats);
|
||||
|
||||
for (const convo of CONVOS) {
|
||||
test(`grow the last reply of ${chatName(convo)} beside the rail`, async ({ page, browser }) => {
|
||||
const messages = await seedChat(convo);
|
||||
await stageBackgroundWork(page, convo, messages);
|
||||
const size = await openChat(page, convo);
|
||||
console.log(`\n${chatName(convo)}: ${size.rows} rows, ${size.nodes} elements`);
|
||||
const session = await page.context().newCDPSession(page);
|
||||
await session.send('LayerTree.enable');
|
||||
let layers = 0;
|
||||
session.on('LayerTree.layerTreeDidChange', (event) => {
|
||||
layers = event.layers?.length ?? layers;
|
||||
});
|
||||
|
||||
const grow = () =>
|
||||
page.evaluate(
|
||||
() =>
|
||||
new Promise<void>((resolve) => {
|
||||
const rows = document.querySelectorAll('.message-render');
|
||||
const target = rows[rows.length - 1].querySelector('p');
|
||||
const node = document.createTextNode('');
|
||||
target?.appendChild(node);
|
||||
let count = 0;
|
||||
const timer = setInterval(() => {
|
||||
node.data += ' streaming words here';
|
||||
count += 1;
|
||||
if (count === 60) {
|
||||
clearInterval(timer);
|
||||
node.remove();
|
||||
resolve();
|
||||
}
|
||||
}, 50);
|
||||
}),
|
||||
);
|
||||
|
||||
for (let round = 1; round <= 3; round += 1) {
|
||||
for (const open of [false, true]) {
|
||||
const listed = await setRail(page, open);
|
||||
const cost = await traceFrames(browser, page, grow);
|
||||
console.log(
|
||||
formatFrameCost(
|
||||
`rail ${open ? `open, ${listed} rows` : 'closed'} (round ${round}), ${layers} layers`,
|
||||
cost,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
143
e2e/benchmarks-fade/rail.ts
Normal file
143
e2e/benchmarks-fade/rail.ts
Normal file
|
|
@ -0,0 +1,143 @@
|
|||
import type { Page } from '@playwright/test';
|
||||
import type { BenchChat, ExportedMessage } from './chats';
|
||||
import { MOCK_ENDPOINTS, getAccessToken, requestJson } from '../specs/mock/helpers';
|
||||
import { withMongo } from '../specs/mock/db';
|
||||
|
||||
/**
|
||||
* Background work for the session rail to list, without running any: the seeded conversation
|
||||
* becomes an agent's, and its task and subagent indexes are answered from here. The running
|
||||
* tools are tool calls the thread already holds, so the rail titles them from the loaded
|
||||
* messages, which is the pass it makes on every update of a streaming thread.
|
||||
*/
|
||||
|
||||
const RUNNING_TOOLS = 6;
|
||||
const FINISHED_TOOLS = 4;
|
||||
const RAIL_TOGGLE = 'header-background-tasks-button';
|
||||
|
||||
type Call = { messageId: string; id: string; name: string };
|
||||
|
||||
function toolCalls(messages: ExportedMessage[]): Call[] {
|
||||
const calls: Call[] = [];
|
||||
for (const message of messages) {
|
||||
for (const part of message.content ?? []) {
|
||||
const call = part.tool_call as { id?: string; name?: string } | undefined;
|
||||
if (part.type === 'tool_call' && call?.id != null) {
|
||||
calls.push({ messageId: message.messageId, id: call.id, name: call.name ?? 'tool' });
|
||||
}
|
||||
}
|
||||
}
|
||||
return calls;
|
||||
}
|
||||
|
||||
/** Returns the conversation fields a run's final frame must keep, so the rail keeps its rows. */
|
||||
export async function stageBackgroundWork(
|
||||
page: Page,
|
||||
chat: BenchChat,
|
||||
messages: ExportedMessage[],
|
||||
): Promise<Record<string, unknown>> {
|
||||
await page.goto('/c/new');
|
||||
const token = await getAccessToken(page);
|
||||
const agent = await requestJson<{ id: string }>(page, {
|
||||
path: '/api/agents',
|
||||
token,
|
||||
method: 'POST',
|
||||
body: {
|
||||
name: `Rail bench ${chat.id.slice(0, 8)}`,
|
||||
description: 'Session rail benchmark.',
|
||||
instructions: 'Follow the request.',
|
||||
provider: MOCK_ENDPOINTS[0].label,
|
||||
model: MOCK_ENDPOINTS[0].model,
|
||||
},
|
||||
});
|
||||
await withMongo((db) =>
|
||||
db
|
||||
.collection('conversations')
|
||||
.updateOne(
|
||||
{ conversationId: chat.id },
|
||||
{ $set: { endpoint: 'agents', agent_id: agent.id }, $unset: { endpointType: '' } },
|
||||
),
|
||||
);
|
||||
|
||||
const now = Date.now();
|
||||
const calls = toolCalls(messages).slice(-(RUNNING_TOOLS + FINISHED_TOOLS));
|
||||
const tasks = calls.map((call, index) => {
|
||||
const running = index >= calls.length - RUNNING_TOOLS;
|
||||
return {
|
||||
taskId: `task-${index}`,
|
||||
toolName: call.name,
|
||||
toolCallId: call.id,
|
||||
messageId: call.messageId,
|
||||
status: running ? 'running' : 'completed',
|
||||
cancellationRequested: false,
|
||||
startedAt: new Date(now - 90_000 - index * 1_000).toISOString(),
|
||||
...(running ? {} : { settledAt: new Date(now - 30_000).toISOString() }),
|
||||
};
|
||||
});
|
||||
const children = [
|
||||
'Audit the cache paths',
|
||||
'Draft the changelog',
|
||||
'Find the open pull requests',
|
||||
].map((title, index) => ({
|
||||
threadId: `thread-${index}`,
|
||||
parentMessageId: messages[messages.length - 1].messageId,
|
||||
parentToolCallId: `call-child-${index}`,
|
||||
subagentType: 'researcher',
|
||||
subagentKind: 'agent',
|
||||
title,
|
||||
origin: 'tool',
|
||||
status: 'completed',
|
||||
updatedAt: new Date(now - 20_000).toISOString(),
|
||||
latestTaskId: `child-task-${index}`,
|
||||
tasks: [
|
||||
{
|
||||
taskId: `child-task-${index}`,
|
||||
status: 'completed',
|
||||
createdAt: new Date(now - 200_000).toISOString(),
|
||||
},
|
||||
],
|
||||
tasksTruncated: false,
|
||||
}));
|
||||
const id = encodeURIComponent(chat.id);
|
||||
await page.route(
|
||||
(url) => url.pathname.endsWith(`/api/convos/${id}/background-tasks`),
|
||||
(route) =>
|
||||
route.fulfill({
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ conversationId: chat.id, cancellable: true, complete: true, tasks }),
|
||||
}),
|
||||
);
|
||||
await page.route(
|
||||
(url) => url.pathname.endsWith(`/api/convos/${id}/subagents`),
|
||||
(route) =>
|
||||
route.fulfill({
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({
|
||||
parentConversationId: chat.id,
|
||||
children,
|
||||
childrenTruncated: false,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
return { endpoint: 'agents', agent_id: agent.id };
|
||||
}
|
||||
|
||||
/** Waits until the header's control has counted the staged work, then leaves the rail as asked. */
|
||||
export async function setRail(page: Page, open: boolean): Promise<number> {
|
||||
await page.waitForFunction(
|
||||
(testId) =>
|
||||
/running/.test(
|
||||
document.querySelector(`[data-testid="${testId}"]`)?.getAttribute('aria-label') ?? '',
|
||||
),
|
||||
RAIL_TOGGLE,
|
||||
{ timeout: 30_000 },
|
||||
);
|
||||
const isOpen = () =>
|
||||
page.evaluate(() => document.querySelector('[data-testid="session-rail"]') != null);
|
||||
if ((await isOpen()) !== open) {
|
||||
await page.evaluate((testId) => {
|
||||
document.querySelector<HTMLElement>(`[data-testid="${testId}"]`)?.click();
|
||||
}, RAIL_TOGGLE);
|
||||
}
|
||||
await page.waitForTimeout(1_500);
|
||||
return page.evaluate(() => document.querySelectorAll('[data-testid="session-row"]').length);
|
||||
}
|
||||
|
|
@ -16,6 +16,7 @@ import {
|
|||
seedChat,
|
||||
} from './chats';
|
||||
import { buildFrames, startReplayServer } from './replay';
|
||||
import { setRail, stageBackgroundWork } from './rail';
|
||||
import { installRenderProbe } from './why';
|
||||
import { formatFrameCost, traceFrames, traceWindows } from './trace';
|
||||
|
||||
|
|
@ -52,6 +53,11 @@ const LIST_ANIMATIONS = process.env.FADE_PERF_ANIMATIONS === '1';
|
|||
const WITH_WHY = process.env.FADE_PERF_WHY === '1';
|
||||
/** How many components the render count lists, most rendered first. */
|
||||
const WHY_LIMIT = Number(process.env.FADE_PERF_WHY_LIMIT) || 80;
|
||||
/**
|
||||
* `closed` or `open`: gives the conversation background work for the session rail to list and
|
||||
* leaves the rail closed or open for the run, so the two runs differ only in the rail.
|
||||
*/
|
||||
const RAIL = process.env.FADE_PERF_RAIL;
|
||||
const MARK = 'fade:';
|
||||
|
||||
function variety(message: ExportedMessage): number {
|
||||
|
|
@ -161,7 +167,12 @@ test.describe('stream event cost', () => {
|
|||
const runId = randomUUID();
|
||||
const frames = buildFrames(content, runId);
|
||||
const why = WITH_WHY ? await installRenderProbe(page) : null;
|
||||
const staged = RAIL ? await stageBackgroundWork(page, convo, messages) : null;
|
||||
const size = await openChat(page, convo);
|
||||
if (RAIL) {
|
||||
const rows = await setRail(page, RAIL === 'open');
|
||||
console.log(`\nsession rail ${RAIL}, listing ${rows} rows`);
|
||||
}
|
||||
console.log(
|
||||
`\n##### ${chatName(convo)}: ${size.rows} rows, ${size.nodes} elements; ` +
|
||||
`replaying ${content.length} parts as ${frames.length} frames, ${GAP_MS}ms apart, cpu x${CPU_RATE}`,
|
||||
|
|
@ -327,6 +338,8 @@ test.describe('stream event cost', () => {
|
|||
endpoint: ENDPOINT.label,
|
||||
endpointType: 'custom',
|
||||
model: ENDPOINT.model,
|
||||
...staged,
|
||||
...(staged ? { endpointType: undefined } : {}),
|
||||
},
|
||||
title: convo.title,
|
||||
requestMessage,
|
||||
|
|
|
|||
|
|
@ -242,6 +242,97 @@ test.describe('detached subagent activity', () => {
|
|||
}
|
||||
}
|
||||
});
|
||||
test('lists detached children in the session rail and opens one beside it @scenario:session-rail-lists-and-opens-children', async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(120_000);
|
||||
const label = `rail-${Date.now().toString(36)}`;
|
||||
const childNames = [uniqueAgentName('E2E Rail Child A'), uniqueAgentName('E2E Rail Child B')];
|
||||
const parentName = uniqueAgentName('E2E Rail Parent');
|
||||
const createdAgentIds: string[] = [];
|
||||
|
||||
try {
|
||||
await page.goto('/c/new');
|
||||
/** The control is offered before the chat has anything to list, and says so. */
|
||||
const toggle = page.getByTestId('header-background-tasks-button');
|
||||
const rail = page.getByRole('complementary', { name: 'Session' });
|
||||
await expect(toggle).toHaveAccessibleName('Session');
|
||||
await toggle.click();
|
||||
await expect(rail).toContainText('will show up here');
|
||||
await rail.getByRole('button', { name: 'Close session' }).click();
|
||||
await expect(rail).toHaveCount(0);
|
||||
await expect(toggle).toBeFocused();
|
||||
|
||||
const token = await getAccessToken(page);
|
||||
const children: AgentDetail[] = [];
|
||||
for (const childName of childNames) {
|
||||
const child = await createAgent(page, token, childName);
|
||||
children.push(child);
|
||||
createdAgentIds.push(child.id);
|
||||
}
|
||||
const parent = await createAgent(page, token, parentName, {
|
||||
enabled: true,
|
||||
allowSelf: false,
|
||||
agent_ids: children.map((child) => child.id),
|
||||
});
|
||||
createdAgentIds.push(parent.id);
|
||||
|
||||
await selectAgent(page, parentName);
|
||||
const response = await sendMessageAndWaitForCompletion(
|
||||
page,
|
||||
`${DETACHED_ACTIVITY_MARKER}${children.map((child) => child.id).join(',')}:${label}`,
|
||||
);
|
||||
expect(response.ok()).toBeTruthy();
|
||||
|
||||
/** The children outlive the parent's turn, and the control counts them from the header. */
|
||||
await expect(toggle).toHaveAccessibleName(/^Session, 2 running/, { timeout: 30_000 });
|
||||
await toggle.click();
|
||||
const rows = rail.getByTestId('session-row');
|
||||
await expect(rows).toHaveCount(2);
|
||||
for (const childName of childNames) {
|
||||
await expect(rail).toContainText(childName);
|
||||
}
|
||||
await expect(rail.getByRole('button', { name: /^Stop task/ })).toHaveCount(2);
|
||||
/** Each running child's row says what it is on now, from the thread the page follows. */
|
||||
await expect(rail.getByTestId('session-row-now')).toHaveCount(2, { timeout: 30_000 });
|
||||
await expect(rail.getByTestId('session-row-now').first()).toContainText(/child-\d-phase-\d+/);
|
||||
|
||||
/** A child opens in the side panel, and the rail keeps its own column beside it. */
|
||||
const open = rows.first().getByRole('button', { name: /^Open subagent/ });
|
||||
await open.click();
|
||||
const panel = childActivityPanel(page);
|
||||
await expect(panel).toBeVisible();
|
||||
await expect(rail).toBeVisible();
|
||||
await expect(open).toHaveAttribute('aria-current', 'true');
|
||||
const [panelBox, railBox] = [await panel.boundingBox(), await rail.boundingBox()];
|
||||
expect(panelBox).not.toBeNull();
|
||||
expect(railBox).not.toBeNull();
|
||||
expect((panelBox?.x ?? 0) + (panelBox?.width ?? 0)).toBeLessThanOrEqual(
|
||||
(railBox?.x ?? 0) + 1,
|
||||
);
|
||||
expect((railBox?.x ?? 0) + (railBox?.width ?? 0)).toBeCloseTo(
|
||||
page.viewportSize()?.width ?? 0,
|
||||
0,
|
||||
);
|
||||
|
||||
await expect(rows.filter({ hasText: 'Completed' })).toHaveCount(2, { timeout: 30_000 });
|
||||
await expect(toggle).toHaveAccessibleName('Session');
|
||||
await expect(rail.getByRole('button', { name: /^Stop/ })).toHaveCount(0);
|
||||
await expect(rail.getByTestId('session-row-now')).toHaveCount(0);
|
||||
|
||||
/** The docked rail is a layout choice: it is still there after a reload. */
|
||||
await panel.getByRole('button', { name: 'Close' }).click();
|
||||
await page.reload();
|
||||
await expect(rail).toBeVisible();
|
||||
await expect(rows).toHaveCount(2);
|
||||
await rail.getByRole('button', { name: 'Close session' }).click();
|
||||
} finally {
|
||||
for (const agentId of createdAgentIds.reverse()) {
|
||||
await cleanupAgent(page, agentId);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('reads a long child thread a page at a time, and the rest on request @scenario:subagent-panel-pages-child-history', async ({
|
||||
page,
|
||||
}) => {
|
||||
|
|
|
|||
|
|
@ -327,6 +327,9 @@ interface:
|
|||
# Continue a subagent's thread as a chat in the side panel, beside the conversation,
|
||||
# instead of navigating to the new chat. Default: true.
|
||||
sideChat: true
|
||||
# List a conversation's subagents and background tasks in a rail beside the chat, opened
|
||||
# from the chat header. Set false to list them in a header popover instead. Default: true.
|
||||
sessionRail: true
|
||||
# Ask each viewer before loading Google Tag Manager (ANALYTICS_GTM_ID).
|
||||
# Set false when the deployment settles consent itself, e.g. internal use. Default: true.
|
||||
# analyticsConsent: true
|
||||
|
|
|
|||
|
|
@ -3,12 +3,7 @@ import { useSetAtom } from 'jotai';
|
|||
import { Button, cn } from '@librechat/client';
|
||||
import { ChevronRight, Users } from 'lucide-react';
|
||||
import { ContentTypes } from 'librechat-data-provider';
|
||||
import type {
|
||||
TMessage,
|
||||
PartMetadata,
|
||||
TAttachment,
|
||||
TMessageContentParts,
|
||||
} from 'librechat-data-provider';
|
||||
import type { PartMetadata, TAttachment, TMessageContentParts } from 'librechat-data-provider';
|
||||
import type { Dispatch, ReactNode, SetStateAction } from 'react';
|
||||
import type { Agent } from 'librechat-data-provider';
|
||||
import type { MessagePartMessage, MessagePartsHost, ToolCallChrome } from '../../react/host';
|
||||
|
|
@ -21,6 +16,7 @@ import {
|
|||
import { isLiveSubagentStatus, subagentStatusLabelKey } from '../../react/subagents/status';
|
||||
import { MessagePartsHostProvider, useMessagePartsHost } from '../../react/host';
|
||||
import { isSelfSpawn as isSelfSpawnType } from '../../react/subagents/author';
|
||||
import { pickTailIndex, pickTailPart } from '../../react/subagents/tail';
|
||||
import { parseSubagentBackgroundHandle } from '../../core/parts/handle';
|
||||
import { lastVisibleContentIdx } from '../../core/parts/activityLabels';
|
||||
import { resolveSubagentAgentId } from '../../react/subagents/identity';
|
||||
|
|
@ -555,21 +551,6 @@ function useDetachedStatus(threadId: string, taskId: string) {
|
|||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a reply's newest row is: its last part that draws something. A batch of tool calls ends
|
||||
* with an empty label reservation, which draws nothing until its label arrives.
|
||||
*/
|
||||
const pickTailIndex = (tail: TMessage | null): number | null => {
|
||||
if (tail == null || tail.isCreatedByUser) return null;
|
||||
const index = lastVisibleContentIdx(tail.content);
|
||||
return index < 0 ? null : index;
|
||||
};
|
||||
|
||||
const pickTailPart = (tail: TMessage | null): TMessageContentParts | null => {
|
||||
const index = pickTailIndex(tail);
|
||||
return index == null ? null : (tail?.content?.[index] ?? null);
|
||||
};
|
||||
|
||||
/**
|
||||
* A detached child's row, read from its thread's messages wherever something is following that
|
||||
* thread. Its own leaf, so a streamed token re-renders this row alone and never the card.
|
||||
|
|
|
|||
|
|
@ -301,7 +301,7 @@ export type {
|
|||
AttachmentDownloadTarget,
|
||||
} from './react/files';
|
||||
export { default as useReducedMotion } from './react/motion';
|
||||
export { default as useElementSize } from './react/size';
|
||||
export { default as useElementSize, useElementSizeSelect } from './react/size';
|
||||
export { default as useAudioLevels, frameLevel } from './react/levels';
|
||||
export { default as useInitPopoverInput } from './react/popover';
|
||||
export { useComposerHost, ComposerHostProvider } from './react/input';
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
* @jest-environment jsdom
|
||||
*/
|
||||
import { renderHook, act } from '@testing-library/react';
|
||||
import useElementSize from '../size';
|
||||
import useElementSize, { useElementSizeSelect } from '../size';
|
||||
|
||||
class MockResizeObserver {
|
||||
static instances: MockResizeObserver[] = [];
|
||||
|
|
@ -116,3 +116,73 @@ describe('useElementSize', () => {
|
|||
expect(result.current.width).toBe(320);
|
||||
});
|
||||
});
|
||||
|
||||
describe('useElementSizeSelect', () => {
|
||||
const originalResizeObserver = window.ResizeObserver;
|
||||
|
||||
beforeEach(() => {
|
||||
MockResizeObserver.instances = [];
|
||||
window.ResizeObserver = MockResizeObserver as unknown as typeof ResizeObserver;
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
window.ResizeObserver = originalResizeObserver;
|
||||
});
|
||||
|
||||
const attach = (node: HTMLElement, initialProps = { needed: 300 }) => {
|
||||
let renders = 0;
|
||||
const hook = renderHook(
|
||||
({ needed }: { needed: number }) => {
|
||||
renders += 1;
|
||||
return useElementSizeSelect<HTMLDivElement, boolean>(({ width }) => width >= needed);
|
||||
},
|
||||
{ initialProps },
|
||||
);
|
||||
act(() => hook.result.current.ref(node as HTMLDivElement));
|
||||
const observer = MockResizeObserver.instances[MockResizeObserver.instances.length - 1];
|
||||
return { ...hook, observer, renders: () => renders };
|
||||
};
|
||||
|
||||
it('answers from an unmeasured element as from one with no size', () => {
|
||||
const { result } = renderHook(() =>
|
||||
useElementSizeSelect<HTMLDivElement, boolean>(({ width }) => width >= 300),
|
||||
);
|
||||
expect(result.current.value).toBe(false);
|
||||
});
|
||||
|
||||
it('does not render for a size that leaves the answer as it was', () => {
|
||||
const { result, observer, renders } = attach(document.createElement('div'));
|
||||
act(() => observer.trigger({ width: 640, height: 40 }));
|
||||
expect(result.current.value).toBe(true);
|
||||
const settled = renders();
|
||||
|
||||
/** A panel sliding in beside the element: a new width on every frame, the same answer. */
|
||||
for (let width = 630; width >= 320; width -= 10) {
|
||||
act(() => observer.trigger({ width, height: 40 }));
|
||||
}
|
||||
expect(renders()).toBe(settled);
|
||||
expect(result.current.value).toBe(true);
|
||||
|
||||
act(() => observer.trigger({ width: 299, height: 40 }));
|
||||
expect(renders()).toBe(settled + 1);
|
||||
expect(result.current.value).toBe(false);
|
||||
});
|
||||
|
||||
it('asks a new question against the size last measured, including one that never rendered', () => {
|
||||
const { result, observer, rerender } = attach(document.createElement('div'));
|
||||
act(() => observer.trigger({ width: 640, height: 40 }));
|
||||
act(() => observer.trigger({ width: 420, height: 40 }));
|
||||
expect(result.current.value).toBe(true);
|
||||
|
||||
rerender({ needed: 500 });
|
||||
expect(result.current.value).toBe(false);
|
||||
rerender({ needed: 400 });
|
||||
expect(result.current.value).toBe(true);
|
||||
});
|
||||
|
||||
it('stops observing an element that is gone', () => {
|
||||
const { result, observer } = attach(document.createElement('div'));
|
||||
act(() => result.current.ref(null));
|
||||
expect(observer.disconnected).toBe(true);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { useCallback, useLayoutEffect, useState } from 'react';
|
||||
import { useCallback, useLayoutEffect, useReducer, useRef, useState } from 'react';
|
||||
|
||||
interface ElementSize {
|
||||
width: number;
|
||||
|
|
@ -49,3 +49,62 @@ export default function useElementSize<T extends HTMLElement>(): UseElementSizeR
|
|||
|
||||
return { ref, width: size.width, height: size.height };
|
||||
}
|
||||
|
||||
const UNMEASURED: ElementSize = { width: 0, height: 0 };
|
||||
|
||||
/**
|
||||
* A fact about an element's size, for a reader that needs the fact and not the size: whether
|
||||
* something fits, which of two layouts applies. The size changes on every frame while a panel
|
||||
* beside it opens or the window is dragged; the fact rarely does, and only a change in the fact
|
||||
* renders. `select` may close over other state: a new `select` is asked again, in the render
|
||||
* that brings it, against the size last measured.
|
||||
*/
|
||||
export function useElementSizeSelect<T extends HTMLElement, S>(
|
||||
select: (size: ElementSize) => S,
|
||||
): { ref: (node: T | null) => void; value: S } {
|
||||
const [node, setNode] = useState<T | null>(null);
|
||||
const sizeRef = useRef<ElementSize>(UNMEASURED);
|
||||
const selectRef = useRef(select);
|
||||
selectRef.current = select;
|
||||
/** The answer on screen, which a measurement is compared with before anything is scheduled:
|
||||
* a state update that leaves state as it was can still cost a render. */
|
||||
const value = select(sizeRef.current);
|
||||
const shownRef = useRef(value);
|
||||
shownRef.current = value;
|
||||
const [, render] = useReducer((count: number) => count + 1, 0);
|
||||
|
||||
const ref = useCallback((element: T | null) => setNode(element), []);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!node) {
|
||||
return;
|
||||
}
|
||||
const apply = (width: number, height: number) => {
|
||||
const size = sizeRef.current;
|
||||
if (size.width !== width || size.height !== height) {
|
||||
sizeRef.current = { width, height };
|
||||
}
|
||||
if (!Object.is(shownRef.current, selectRef.current(sizeRef.current))) {
|
||||
render();
|
||||
}
|
||||
};
|
||||
const measure = () => apply(node.offsetWidth, node.offsetHeight);
|
||||
|
||||
measure();
|
||||
if (typeof ResizeObserver === 'undefined') {
|
||||
window.addEventListener('resize', measure);
|
||||
return () => window.removeEventListener('resize', measure);
|
||||
}
|
||||
const observer = new ResizeObserver((entries) => {
|
||||
const entry = entries[entries.length - 1];
|
||||
if (!entry) {
|
||||
return;
|
||||
}
|
||||
apply(Math.floor(entry.contentRect.width), Math.floor(entry.contentRect.height));
|
||||
});
|
||||
observer.observe(node);
|
||||
return () => observer.disconnect();
|
||||
}, [node]);
|
||||
|
||||
return { ref, value };
|
||||
}
|
||||
|
|
|
|||
45
packages/chat/src/react/subagents/__tests__/tail.spec.ts
Normal file
45
packages/chat/src/react/subagents/__tests__/tail.spec.ts
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
import { ContentTypes } from 'librechat-data-provider';
|
||||
import type { TMessage, TMessageContentParts } from 'librechat-data-provider';
|
||||
import { pickTailIndex, pickTailPart } from '../tail';
|
||||
|
||||
const text = (value: string): TMessageContentParts =>
|
||||
({ type: ContentTypes.TEXT, text: value }) as TMessageContentParts;
|
||||
const call = (id: string): TMessageContentParts =>
|
||||
({
|
||||
type: ContentTypes.TOOL_CALL,
|
||||
[ContentTypes.TOOL_CALL]: { id, name: 'bash_tool', args: '{}' },
|
||||
}) as TMessageContentParts;
|
||||
const reply = (content: TMessageContentParts[], overrides: Partial<TMessage> = {}): TMessage =>
|
||||
({
|
||||
messageId: 'reply',
|
||||
conversationId: 'thread',
|
||||
parentMessageId: 'brief',
|
||||
isCreatedByUser: false,
|
||||
text: '',
|
||||
content,
|
||||
...overrides,
|
||||
}) as TMessage;
|
||||
|
||||
describe('pickTailPart', () => {
|
||||
it('is the newest part of the reply the branch ends on', () => {
|
||||
const tail = reply([text('Starting.'), call('call-1')]);
|
||||
expect(pickTailIndex(tail)).toBe(1);
|
||||
expect(pickTailPart(tail)).toBe(tail.content?.[1]);
|
||||
});
|
||||
|
||||
it('answers nothing before the child has replied', () => {
|
||||
expect(pickTailPart(null)).toBeNull();
|
||||
expect(pickTailPart(reply([text('The brief.')], { isCreatedByUser: true }))).toBeNull();
|
||||
expect(pickTailIndex(reply([]))).toBeNull();
|
||||
});
|
||||
|
||||
it('skips a label still waiting for its text, so the row is what a reader would see', () => {
|
||||
const reserved = {
|
||||
type: ContentTypes.ACTIVITY_LABEL,
|
||||
[ContentTypes.ACTIVITY_LABEL]: '',
|
||||
} as TMessageContentParts;
|
||||
const tail = reply([call('call-1'), reserved]);
|
||||
expect(pickTailIndex(tail)).toBe(0);
|
||||
expect(pickTailPart(tail)).toBe(tail.content?.[0]);
|
||||
});
|
||||
});
|
||||
|
|
@ -17,3 +17,4 @@ export * from './task';
|
|||
export * from './scope';
|
||||
export * from './host';
|
||||
export * from './thread';
|
||||
export { useThreadTailPart } from './tail';
|
||||
|
|
|
|||
31
packages/chat/src/react/subagents/tail.ts
Normal file
31
packages/chat/src/react/subagents/tail.ts
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
import type { TMessage, TMessageContentParts } from 'librechat-data-provider';
|
||||
import { lastVisibleContentIdx } from '../../core/parts/activityLabels';
|
||||
import { useBranchTailSelect } from '../latest';
|
||||
import { useThreadInterest } from './follows';
|
||||
|
||||
/**
|
||||
* Where a reply's newest row is: its last part that draws something. A batch of tool calls ends
|
||||
* with an empty label reservation, which draws nothing until its label arrives.
|
||||
*/
|
||||
export const pickTailIndex = (tail: TMessage | null): number | null => {
|
||||
if (tail == null || tail.isCreatedByUser) return null;
|
||||
const index = lastVisibleContentIdx(tail.content);
|
||||
return index < 0 ? null : index;
|
||||
};
|
||||
|
||||
export const pickTailPart = (tail: TMessage | null): TMessageContentParts | null => {
|
||||
const index = pickTailIndex(tail);
|
||||
return index == null ? null : (tail?.content?.[index] ?? null);
|
||||
};
|
||||
|
||||
/**
|
||||
* The part a running child is on right now, for a reader that names it outside the child's own
|
||||
* card. It registers the interest a card's preview does, so the page follows the thread once for
|
||||
* every reader, and it answers nothing for a thread the page has no room to follow: what was
|
||||
* last read for that thread is not what it is doing now.
|
||||
*/
|
||||
export function useThreadTailPart(threadId: string, live: boolean): TMessageContentParts | null {
|
||||
const followed = useThreadInterest(threadId, { live: true, enabled: live, passive: true });
|
||||
const part = useBranchTailSelect(threadId, threadId, pickTailPart);
|
||||
return live && followed ? part : null;
|
||||
}
|
||||
|
|
@ -3563,6 +3563,10 @@ export const interfaceSchema = z
|
|||
* subagent's thread opens the new chat in the side panel instead of leaving
|
||||
* the conversation. Enabled by default; false restores the navigation. */
|
||||
sideChat: z.boolean().optional(),
|
||||
/** The session rail: a column beside the conversation listing its subagents and
|
||||
* background tasks, opened from the chat header. Enabled by default; false restores
|
||||
* the header button that lists them in a popover and appears only once there are any. */
|
||||
sessionRail: z.boolean().optional(),
|
||||
/** Asks each viewer for consent before Google Tag Manager (`ANALYTICS_GTM_ID`)
|
||||
* loads. A deployment that settles consent itself, such as an internal one
|
||||
* covered by its own policy, can set false to load the container without the
|
||||
|
|
@ -3807,6 +3811,7 @@ export const interfaceSchema = z
|
|||
contextCost: false,
|
||||
artifactUndocking: true,
|
||||
sideChat: true,
|
||||
sessionRail: true,
|
||||
feedback: true,
|
||||
peoplePicker: {
|
||||
users: true,
|
||||
|
|
|
|||
|
|
@ -254,6 +254,24 @@ describe('loadDefaultInterface', () => {
|
|||
expect(interfaceConfig?.sideChat).toBe(true);
|
||||
});
|
||||
|
||||
it('carries a disabled session rail flag to the clients', async () => {
|
||||
const interfaceConfig = await loadDefaultInterface({
|
||||
config: { interface: { sessionRail: false } },
|
||||
configDefaults: getConfigDefaults(),
|
||||
});
|
||||
|
||||
expect(interfaceConfig?.sessionRail).toBe(false);
|
||||
});
|
||||
|
||||
it('uses the schema default for the session rail when not configured', async () => {
|
||||
const interfaceConfig = await loadDefaultInterface({
|
||||
config: {},
|
||||
configDefaults: getConfigDefaults(),
|
||||
});
|
||||
|
||||
expect(interfaceConfig?.sessionRail).toBe(true);
|
||||
});
|
||||
|
||||
it('carries a disabled analytics consent prompt to the clients', async () => {
|
||||
const interfaceConfig = await loadDefaultInterface({
|
||||
config: { interface: { analyticsConsent: false } },
|
||||
|
|
|
|||
|
|
@ -102,6 +102,7 @@ export async function loadDefaultInterface({
|
|||
contextUsage: interfaceConfig?.contextUsage ?? defaults.contextUsage,
|
||||
artifactUndocking: interfaceConfig?.artifactUndocking ?? defaults.artifactUndocking,
|
||||
sideChat: interfaceConfig?.sideChat ?? defaults.sideChat,
|
||||
sessionRail: interfaceConfig?.sessionRail ?? defaults.sessionRail,
|
||||
analyticsConsent: interfaceConfig?.analyticsConsent,
|
||||
contextCost: interfaceConfig?.contextCost ?? defaults.contextCost,
|
||||
feedback: interfaceConfig?.feedback ?? defaults.feedback,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue