Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🌲 feat: Expose Navigable Subagent Progress Trees (#16748)

Danny Avila3a2241c04821
diff --git a/client/src/components/Chat/Messages/Content/BackgroundTaskCard.tsx b/client/src/components/Chat/Messages/Content/BackgroundTaskCard.tsx
index 2e3372f6ab..d1b94917e0 100644
--- a/client/src/components/Chat/Messages/Content/BackgroundTaskCard.tsx
+++ b/client/src/components/Chat/Messages/Content/BackgroundTaskCard.tsx
@@ -1,10 +1,15 @@
+import { useMemo } from 'react';
+import { Button } from '@librechat/client';
import type { BackgroundTaskStatus, BackgroundTaskView } from './Parts/background';
import type { TranslationKeys } from '~/hooks';
import { backgroundTaskMessageKey, backgroundTaskNoteKey } from './Parts/guidance';
import { ToolIcon, getToolIconType, OutputRenderer } from './ToolOutput';
+import { useSubagentTaskPanel } from '~/components/Chat/Subagents/task';
import { formatBackgroundCodeOutput } from './Parts/background';
import { parseToolName } from '~/utils/toolLabels';
import { getToolDisplayLabel, cn } from '~/utils';
+import SubagentProgress from './SubagentProgress';
+import { useMessageContext } from '~/Providers';
import { useLocalize } from '~/hooks';
const STATUS: Record<BackgroundTaskStatus, { label: TranslationKeys; dot: string }> = {
@@ -35,7 +40,21 @@ export default function BackgroundTaskCard({
mcpServerNames?: readonly string[];
}) {
const localize = useLocalize();
+ const { conversationId } = useMessageContext();
const isSubagent = task.toolName === 'subagent';
+ const durableTask = useMemo(
+ () =>
+ isSubagent && task.threadId != null
+ ? {
+ threadId: task.threadId,
+ taskId: task.taskId,
+ subagentType: task.subagentType,
+ settled: task.status !== 'running',
+ }
+ : null,
+ [isSubagent, task.status, task.subagentType, task.taskId, task.threadId],
+ );
+ const { selection, open: openActivity } = useSubagentTaskPanel(durableTask, conversationId);
const parsedName = parseToolName(task.toolName, mcpServerNames);
const serverName = parsedName.mcpServer;
let title = getToolDisplayLabel(task.toolName, localize, mcpServerNames);
@@ -97,6 +116,24 @@ export default function BackgroundTaskCard({
{localize(state.label)}
</span>
</div>
+ {task.activity != null && (
+ <SubagentProgress digest={task.activity} serverNames={mcpServerNames} />
+ )}
+ {selection != null && openActivity != null && (
+ <div className="mt-2 flex justify-end">
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={openActivity}
+ data-subagent-tool-call={selection.toolCallId}
+ data-subagent-parent-message={selection.parentMessageId}
+ data-subagent-part-index={selection.partIndex}
+ >
+ {localize('com_ui_wakeup_view_activity')}
+ </Button>
+ </div>
+ )}
{result && (
<div className="border-border-light mt-3 border-t pt-2.5">
<div
diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/BackgroundTaskCall.test.tsx b/client/src/components/Chat/Messages/Content/Parts/__tests__/BackgroundTaskCall.test.tsx
index dd613c8782..1b707af48a 100644
--- a/client/src/components/Chat/Messages/Content/Parts/__tests__/BackgroundTaskCall.test.tsx
+++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/BackgroundTaskCall.test.tsx
@@ -1,6 +1,9 @@
import React from 'react';
import { RecoilRoot } from 'recoil';
import { fireEvent, render, screen, within } from '@testing-library/react';
+import type { ChatSurface } from '~/components/Chat/Subagents/surface';
+import { ChatSurfaceProvider } from '~/components/Chat/Subagents/surface';
+import { MessageContext } from '~/Providers/MessageContext';
import BackgroundTaskCall from '../BackgroundTaskCall';
jest.mock('~/hooks', () => ({
@@ -19,6 +22,7 @@ jest.mock('~/utils', () => ({
cn: (...classes: Array<string | false | null | undefined>) => classes.filter(Boolean).join(' '),
getToolDisplayLabel: (name: string) =>
(({ bash_tool: 'Code', web_search: 'Web Search' }) as Record<string, string>)[name] ?? name,
+ getRunStepDurationLabels: jest.requireActual('~/utils/runStepDuration').getRunStepDurationLabels,
}));
jest.mock('../../ProgressText', () => ({
@@ -457,4 +461,102 @@ describe('BackgroundTaskCall', () => {
);
expect(screen.getByTestId('task-output')).toHaveTextContent('checked at=2026-09-27');
});
+
+ const runningReviewer = {
+ background_task_id: 'task-reviewer',
+ subagent_thread_id: 'thread-reviewer',
+ tool: 'subagent',
+ subagent_type: 'pr-reviewer',
+ status: 'running',
+ progress: 0,
+ next_check_s: 30,
+ message:
+ 'This subagent resumes you automatically when it finishes, so there is no need to check again. If you do, wait next_check_s and pass since: activity.cursor.',
+ activity: {
+ turns: 9,
+ tools: 9,
+ errors: 1,
+ active: '9.1',
+ cursor: '8.1',
+ nodes: [
+ {
+ path: '1-3',
+ kind: 'range',
+ status: 'error',
+ ms: 9_000,
+ summary: 'bash_tool ×2, read_file',
+ errors: 1,
+ folded: true,
+ },
+ { path: '8', kind: 'turn', status: 'ok', ms: 400, summary: 'read_file', folded: true },
+ { path: '9', kind: 'turn', status: 'running', ms: 42_000 },
+ {
+ path: '9.1',
+ kind: 'tool',
+ status: 'running',
+ name: 'bash_tool',
+ label: 'Running the jest suite',
+ ms: 42_000,
+ },
+ ],
+ },
+ };
+
+ it('renders a running subagent as a folded progress tree with its active branch open', () => {
+ renderCall(JSON.stringify(runningReviewer));
+ fireEvent.click(screen.getByTestId('task-header'));
+ const progress = screen.getByTestId('subagent-progress');
+ expect(within(progress).getByText('com_ui_subagent_progress_counts')).toBeInTheDocument();
+ expect(within(progress).getByText('Code ×2, read_file')).toBeInTheDocument();
+ const active = within(progress).getByText('Running the jest suite');
+ expect(active.closest('details')).toHaveAttribute('open');
+ expect(within(progress).getByText('read_file').closest('details')).toBeNull();
+ expect(
+ within(progress).getAllByRole('img', { name: 'com_ui_background_tasks_running' }),
+ ).toHaveLength(2);
+ expect(
+ within(screen.getByTestId('background-task-card')).getByText(
+ 'com_ui_background_tasks_subagent_wakeup_guidance',
+ ),
+ ).toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'com_ui_wakeup_view_activity' })).toBeNull();
+ });
+
+ it('drops a malformed progress digest without losing the task card', () => {
+ renderCall(
+ JSON.stringify({
+ ...runningReviewer,
+ activity: { turns: 1, tools: 1, errors: 0, nodes: [{ path: '../../x', kind: 'tool' }] },
+ }),
+ );
+ fireEvent.click(screen.getByTestId('task-header'));
+ expect(screen.getByTestId('background-task-card')).toBeInTheDocument();
+ expect(screen.queryByTestId('subagent-progress')).toBeNull();
+ });
+
+ it('opens the subagent activity panel for the polled child thread', () => {
+ const claimForeground = jest.fn();
+ const surface = { claimForeground } as unknown as ChatSurface;
+ render(
+ <RecoilRoot>
+ <ChatSurfaceProvider value={surface}>
+ <MessageContext.Provider
+ value={{ messageId: 'parent-message', conversationId: 'convo-1', isExpanded: true }}
+ >
+ <BackgroundTaskCall
+ args={'{"background_task_id":"task-reviewer"}'}
+ output={JSON.stringify(runningReviewer)}
+ isSubmitting={false}
+ initialProgress={1}
+ />
+ </MessageContext.Provider>
+ </ChatSurfaceProvider>
+ </RecoilRoot>,
+ );
+ fireEvent.click(screen.getByTestId('task-header'));
+ const open = screen.getByRole('button', { name: 'com_ui_wakeup_view_activity' });
+ expect(open).toHaveAttribute('data-subagent-tool-call', 'wakeup:thread-reviewer');
+ fireEvent.click(open);
+ expect(claimForeground).toHaveBeenCalledTimes(1);
+ });
});
diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/background.test.ts b/client/src/components/Chat/Messages/Content/Parts/__tests__/background.test.ts
index 6726754532..aff4385d57 100644
--- a/client/src/components/Chat/Messages/Content/Parts/__tests__/background.test.ts
+++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/background.test.ts
@@ -229,10 +229,59 @@ describe('parseBackgroundTaskOutput', () => {
toolName: 'subagent',
subagentType: 'researcher',
status: 'accepted',
+ threadId: 'thread-1',
},
});
});
+ it('parses a subagent progress digest and drops only a malformed one', () => {
+ const task = {
+ background_task_id: 'subagent-1',
+ tool: 'subagent',
+ subagent_type: 'reviewer',
+ status: 'running',
+ };
+ const activity = {
+ turns: 2,
+ tools: 3,
+ errors: 0,
+ active: '2.1',
+ cursor: '1.2',
+ phase: 'thinking',
+ nodes: [
+ { path: '1', kind: 'turn', status: 'ok', summary: 'read_file ×2', folded: true, ms: 10 },
+ { path: '2.1', kind: 'tool', status: 'running', name: 'bash_tool', label: 'Run', ms: 5 },
+ { path: '1-14', kind: 'range', evicted: true, errors: 0 },
+ ],
+ };
+ expect(parseBackgroundTaskOutput(JSON.stringify({ ...task, activity }))).toMatchObject({
+ kind: 'task',
+ task: {
+ activity: {
+ turns: 2,
+ tools: 3,
+ errors: 0,
+ active: '2.1',
+ phase: 'thinking',
+ nodes: [
+ { path: '1', kind: 'turn', status: 'ok', summary: 'read_file ×2', folded: true },
+ { path: '2.1', name: 'bash_tool', label: 'Run' },
+ { path: '1-14', kind: 'range', evicted: true },
+ ],
+ },
+ },
+ });
+ for (const malformed of [
+ { ...activity, turns: -1 },
+ { ...activity, nodes: [{ path: '2.1', kind: 'script' }] },
+ { ...activity, nodes: 'none' },
+ ]) {
+ const parsed = parseBackgroundTaskOutput(JSON.stringify({ ...task, activity: malformed }));
+ expect(parsed).toMatchObject({ kind: 'task', task: { status: 'running' } });
+ expect(parsed?.kind === 'task' ? parsed.task.activity : 'missing').toBeUndefined();
+ }
+ });
+
it.each(['claimed', 'not_running', 'control_not_found'])(
'renders a subagent %s receipt as a task instead of raw JSON',
(status) => {
diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/guidance.test.ts b/client/src/components/Chat/Messages/Content/Parts/__tests__/guidance.test.ts
index 348f86cb79..0ad8a6860d 100644
--- a/client/src/components/Chat/Messages/Content/Parts/__tests__/guidance.test.ts
+++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/guidance.test.ts
@@ -65,6 +65,16 @@ describe('background task host guidance', () => {
'Automatic completion delivery is enabled for this subagent task. Continue independent work if available; otherwise end this turn and the host will resume you when the task finishes. Do not repeatedly poll an unchanged running task. Use check_background_task only for explicit status or control, or as a fallback if automatic delivery is unavailable.',
),
).toBe('com_ui_background_tasks_subagent_wakeup_guidance');
+ expect(
+ backgroundTaskMessageKey(
+ 'This subagent resumes you automatically when it finishes, so there is no need to check again. If you do, wait next_check_s and pass since: activity.cursor.',
+ ),
+ ).toBe('com_ui_background_tasks_subagent_wakeup_guidance');
+ expect(
+ backgroundTaskMessageKey(
+ 'Results are not pushed for this subagent. Check again after next_check_s, passing since: activity.cursor to get only new activity.',
+ ),
+ ).toBe('com_ui_background_tasks_subagent_poll_guidance');
});
it.each([
diff --git a/client/src/components/Chat/Messages/Content/Parts/background.ts b/client/src/components/Chat/Messages/Content/Parts/background.ts
index db5589de06..a0bc79c10f 100644
--- a/client/src/components/Chat/Messages/Content/Parts/background.ts
+++ b/client/src/components/Chat/Messages/Content/Parts/background.ts
@@ -1,4 +1,8 @@
-import type { BackgroundTaskDelivery } from 'librechat-data-provider';
+import type {
+ SubagentDigest,
+ SubagentDigestNode,
+ BackgroundTaskDelivery,
+} from 'librechat-data-provider';
import type { WakeupTaskStatus } from './wakeup';
export function formatBackgroundCodeOutput(output: string): string {
@@ -60,6 +64,10 @@ export type BackgroundTaskView = {
resultAvailable?: boolean;
resultClaimed?: boolean;
delivery?: BackgroundTaskDelivery;
+ /** Durable child thread of a subagent task, for opening its activity panel. */
+ threadId?: string;
+ /** Folded progress tree of a subagent task. */
+ activity?: SubagentDigest;
};
export type BackgroundTaskDisplay =
@@ -135,6 +143,77 @@ const taskStatus = (value: unknown): BackgroundTaskStatus | null => {
const deliveryStatus = (value: unknown): value is BackgroundTaskDelivery | undefined =>
value === undefined || value === 'pending' || value === 'failed' || value === 'delivered';
+const DIGEST_KINDS = new Set(['turn', 'range', 'tool', 'text']);
+const DIGEST_STATUSES = new Set(['running', 'ok', 'error', 'cancelled']);
+const DIGEST_PATH = /^\d+(?:\.\d+)*(?:-\d+)?$/;
+const MAX_DIGEST_NODES = 200;
+
+const count = (value: unknown): value is number =>
+ typeof value === 'number' && Number.isFinite(value) && value >= 0;
+
+const boundedText = (value: unknown, maxChars: number): string | undefined =>
+ typeof value === 'string' && value !== '' ? value.slice(0, maxChars) : undefined;
+
+function parseDigestNode(value: unknown): SubagentDigestNode | null {
+ if (
+ !isRecord(value) ||
+ typeof value.path !== 'string' ||
+ value.path.length > 64 ||
+ !DIGEST_PATH.test(value.path) ||
+ typeof value.kind !== 'string' ||
+ !DIGEST_KINDS.has(value.kind)
+ ) {
+ return null;
+ }
+ const name = boundedText(value.name, 128);
+ const label = boundedText(value.label, 256);
+ const summary = boundedText(value.summary, 512);
+ return {
+ path: value.path,
+ kind: value.kind as SubagentDigestNode['kind'],
+ ...(typeof value.status === 'string' && DIGEST_STATUSES.has(value.status)
+ ? { status: value.status as SubagentDigestNode['status'] }
+ : {}),
+ ...(name == null ? {} : { name }),
+ ...(label == null ? {} : { label }),
+ ...(summary == null ? {} : { summary }),
+ ...(count(value.ms) ? { ms: value.ms } : {}),
+ ...(count(value.chars) ? { chars: value.chars } : {}),
+ ...(count(value.errors) && value.errors > 0 ? { errors: value.errors } : {}),
+ ...(value.folded === true ? { folded: true as const } : {}),
+ ...(value.evicted === true ? { evicted: true as const } : {}),
+ };
+}
+
+/** Progress is optional decoration: a malformed digest is dropped, never the card. */
+function parseDigest(value: unknown): SubagentDigest | undefined {
+ if (
+ !isRecord(value) ||
+ !count(value.turns) ||
+ !count(value.tools) ||
+ !count(value.errors) ||
+ !Array.isArray(value.nodes) ||
+ value.nodes.length > MAX_DIGEST_NODES
+ ) {
+ return undefined;
+ }
+ const nodes = value.nodes.map(parseDigestNode);
+ if (nodes.some((node) => node == null)) {
+ return undefined;
+ }
+ const active = boundedText(value.active, 64);
+ return {
+ turns: value.turns,
+ tools: value.tools,
+ errors: value.errors,
+ nodes: nodes as SubagentDigestNode[],
+ ...(active != null && DIGEST_PATH.test(active) ? { active } : {}),
+ ...(value.phase === 'thinking' ? { phase: 'thinking' as const } : {}),
+ ...(count(value.idle_ms) ? { idle_ms: value.idle_ms } : {}),
+ ...(value.truncated === true ? { truncated: true as const } : {}),
+ };
+}
+
function parseTask(value: unknown): BackgroundTaskView | null {
if (!isRecord(value)) {
return null;
@@ -169,9 +248,18 @@ function parseTask(value: unknown): BackgroundTaskView | null {
...(value.result_available === true ? { resultAvailable: true } : {}),
...(value.result_claimed === true ? { resultClaimed: true } : {}),
...(value.delivery != null ? { delivery: value.delivery } : {}),
+ ...(typeof value.subagent_thread_id === 'string' && value.subagent_thread_id !== ''
+ ? { threadId: value.subagent_thread_id }
+ : {}),
+ ...withDigest(value.activity),
};
}
+function withDigest(value: unknown): Pick<BackgroundTaskView, 'activity'> {
+ const activity = value == null ? undefined : parseDigest(value);
+ return activity == null ? {} : { activity };
+}
+
/** Only host-shaped results become cards. Unknown or partial output stays visible as raw tool output. */
export function parseBackgroundTaskOutput(output?: string | null): BackgroundTaskDisplay | null {
if (!output || output.length > 2_000_000) {
diff --git a/client/src/components/Chat/Messages/Content/Parts/guidance.ts b/client/src/components/Chat/Messages/Content/Parts/guidance.ts
index 09e3821f58..729b043db8 100644
--- a/client/src/components/Chat/Messages/Content/Parts/guidance.ts
+++ b/client/src/components/Chat/Messages/Content/Parts/guidance.ts
@@ -24,6 +24,10 @@ const MESSAGE_KEYS: Record<string, TranslationKeys> = {
'com_ui_background_tasks_cancellation_requested',
'Automatic completion delivery is enabled for this subagent task. Continue independent work if available; otherwise end this turn and the host will resume you when the task finishes. Do not repeatedly poll an unchanged running task. Use check_background_task only for explicit status or control, or as a fallback if automatic delivery is unavailable.':
'com_ui_background_tasks_subagent_wakeup_guidance',
+ 'This subagent resumes you automatically when it finishes, so there is no need to check again. If you do, wait next_check_s and pass since: activity.cursor.':
+ 'com_ui_background_tasks_subagent_wakeup_guidance',
+ 'Results are not pushed for this subagent. Check again after next_check_s, passing since: activity.cursor to get only new activity.':
+ 'com_ui_background_tasks_subagent_poll_guidance',
};
const NOTICE_KEYS: Record<string, TranslationKeys> = {
diff --git a/client/src/components/Chat/Messages/Content/SubagentProgress.tsx b/client/src/components/Chat/Messages/Content/SubagentProgress.tsx
new file mode 100644
index 0000000000..f7b261e729
--- /dev/null
+++ b/client/src/components/Chat/Messages/Content/SubagentProgress.tsx
@@ -0,0 +1,236 @@
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+import type {
+ SubagentDigest,
+ SubagentDigestNode,
+ SubagentDigestStatus,
+} from 'librechat-data-provider';
+import type { TranslationKeys } from '~/hooks';
+import { cn, getToolDisplayLabel, getRunStepDurationLabels } from '~/utils';
+import { ToolIcon, getToolIconType } from './ToolOutput';
+import { useLocalize } from '~/hooks';
+
+export type DigestTreeNode = { node: SubagentDigestNode; children: DigestTreeNode[] };
+
+type Localize = ReturnType<typeof useLocalize>;
+
+const STATUS: Record<SubagentDigestStatus, { label: TranslationKeys; dot: string }> = {
+ running: { label: 'com_ui_background_tasks_running', dot: 'bg-status-info' },
+ ok: { label: 'com_ui_background_tasks_completed', dot: 'bg-status-success' },
+ error: { label: 'com_ui_failed', dot: 'bg-status-error' },
+ cancelled: { label: 'com_ui_cancelled', dot: 'bg-status-warning' },
+};
+
+/** `3.2` belongs to `3`, `3.1-20` to `3`, and `1-14` to the run itself. */
+function parentPath(path: string): string {
+ const dash = path.indexOf('-');
+ const base = dash === -1 ? path : path.slice(0, dash);
+ const dot = base.lastIndexOf('.');
+ return dot === -1 ? '' : base.slice(0, dot);
+}
+
+/** Rebuilds the tree the digest flattened into path-addressed nodes. */
+export function buildDigestTree(nodes: readonly SubagentDigestNode[]): DigestTreeNode[] {
+ const roots: DigestTreeNode[] = [];
+ const byPath = new Map<string, DigestTreeNode>();
+ for (const node of nodes) {
+ const entry: DigestTreeNode = { node, children: [] };
+ byPath.set(node.path, entry);
+ const parent = byPath.get(parentPath(node.path));
+ (parent == null ? roots : parent.children).push(entry);
+ }
+ return roots;
+}
+
+const NESTED_SUMMARY = /^(\d+) turns?, (\d+) tools?$/;
+const COUNTED_ENTRY = /^(.+) ×(\d+)$/;
+const MORE_SUFFIX = / \+(\d+) more$/;
+
+/**
+ * The server folds children into a model-facing English tally ("bash_tool ×3,
+ * text +2 more", "1 turn, 2 tools"). Tool names stay as display labels and every
+ * other fragment is localized here, so the card never shows the raw prose.
+ */
+export function localizeDigestSummary(
+ summary: string,
+ localize: Localize,
+ serverNames?: readonly string[],
+): string {
+ const nested = NESTED_SUMMARY.exec(summary);
+ if (nested != null) {
+ return localize('com_ui_subagent_progress_nested', { 0: nested[1], 1: nested[2] });
+ }
+ const more = MORE_SUFFIX.exec(summary);
+ const entries = (more == null ? summary : summary.slice(0, more.index)).split(', ');
+ const parts = entries.map((entry) => {
+ const counted = COUNTED_ENTRY.exec(entry);
+ const name = counted == null ? entry : counted[1];
+ const label =
+ name === 'text'
+ ? localize('com_ui_subagent_progress_reply')
+ : getToolDisplayLabel(name, localize, serverNames);
+ return counted == null ? label : `${label} ×${counted[2]}`;
+ });
+ if (more != null) {
+ parts.push(localize('com_ui_subagent_progress_more', { 0: more[1] }));
+ }
+ return parts.join(', ');
+}
+
+const isOnPath = (path: string, active?: string): boolean =>
+ active != null && (active === path || active.startsWith(`${path}.`));
+
+function NodeRow({
+ node,
+ serverNames,
+}: {
+ node: SubagentDigestNode;
+ serverNames?: readonly string[];
+}) {
+ const localize = useLocalize();
+ const { i18n } = useTranslation();
+ const status = node.status == null ? undefined : STATUS[node.status];
+ let title: string;
+ if (node.kind === 'tool') {
+ title = node.label ?? getToolDisplayLabel(node.name ?? '', localize, serverNames);
+ } else if (node.kind === 'text') {
+ title = localize('com_ui_subagent_progress_reply');
+ } else if (node.kind === 'range') {
+ title = localize('com_ui_subagent_progress_turns', { 0: node.path });
+ } else {
+ title = localize('com_ui_subagent_progress_turn', { 0: node.path });
+ }
+ const duration = node.ms == null ? undefined : getRunStepDurationLabels(node.ms, i18n.language);
+ return (
+ <span className="flex min-w-0 flex-1 items-center gap-1.5 text-xs">
+ {node.kind === 'tool' && (
+ <span className="flex size-4 shrink-0 items-center justify-center" aria-hidden="true">
+ <ToolIcon type={getToolIconType(node.name ?? '')} />
+ </span>
+ )}
+ <span
+ className={cn(
+ 'min-w-0 truncate',
+ node.kind === 'tool' || node.kind === 'text'
+ ? 'text-text-primary'
+ : 'text-text-secondary',
+ )}
+ title={node.evicted === true ? localize('com_ui_subagent_progress_evicted') : title}
+ >
+ {title}
+ </span>
+ {node.summary != null && (
+ <span className="text-text-tertiary min-w-0 truncate">
+ {localizeDigestSummary(node.summary, localize, serverNames)}
+ </span>
+ )}
+ <span className="ms-auto flex shrink-0 items-center gap-1.5">
+ {duration != null && (
+ <span className="text-text-tertiary tabular-nums">
+ {localize(duration.key, duration.values)}
+ </span>
+ )}
+ {status != null && (
+ <span
+ className={cn('size-1.5 rounded-full', status.dot)}
+ role="img"
+ aria-label={localize(status.label)}
+ />
+ )}
+ </span>
+ </span>
+ );
+}
+
+function DigestBranch({
+ entry,
+ active,
+ serverNames,
+}: {
+ entry: DigestTreeNode;
+ active?: string;
+ serverNames?: readonly string[];
+}) {
+ if (entry.children.length === 0) {
+ return (
+ <li className="flex min-w-0 items-center py-0.5">
+ <NodeRow node={entry.node} serverNames={serverNames} />
+ </li>
+ );
+ }
+ return (
+ <li className="min-w-0">
+ <details open={isOnPath(entry.node.path, active)} className="group">
+ <summary className="focus-visible:ring-border-heavy flex min-w-0 cursor-pointer items-center rounded py-0.5 focus-visible:ring-2 focus-visible:outline-none">
+ <NodeRow node={entry.node} serverNames={serverNames} />
+ </summary>
+ <ul className="border-border-light ms-1.5 border-s ps-2">
+ {entry.children.map((child) => (
+ <DigestBranch
+ key={child.node.path}
+ entry={child}
+ active={active}
+ serverNames={serverNames}
+ />
+ ))}
+ </ul>
+ </details>
+ </li>
+ );
+}
+
+/**
+ * A background subagent's folded progress tree: turns and ranges fold, and the
+ * branch holding the child's current step opens by default. The full, live
+ * transcript stays in the subagent activity panel this card links to.
+ */
+const SubagentProgress = memo(function SubagentProgress({
+ digest,
+ serverNames,
+}: {
+ digest: SubagentDigest;
+ /** Configured MCP server names, so `tool_mcp_server` names label correctly. */
+ serverNames?: readonly string[];
+}) {
+ const localize = useLocalize();
+ const tree = useMemo(() => buildDigestTree(digest.nodes), [digest.nodes]);
+ const active = digest.active ?? digest.nodes[digest.nodes.length - 1]?.path;
+ return (
+ <div className="border-border-light mt-3 border-t pt-2.5" data-testid="subagent-progress">
+ <div className="text-text-secondary mb-1.5 flex items-center gap-2 text-xs font-medium">
+ <span>{localize('com_ui_subagent_progress')}</span>
+ <span className="text-text-tertiary font-normal tabular-nums">
+ {localize('com_ui_subagent_progress_counts', {
+ 0: digest.turns,
+ 1: digest.tools,
+ 2: digest.errors,
+ })}
+ </span>
+ {digest.phase === 'thinking' && (
+ <span className="text-text-tertiary font-normal">
+ {localize('com_ui_subagent_progress_thinking')}
+ </span>
+ )}
+ </div>
+ {tree.length > 0 && (
+ <ul aria-label={localize('com_ui_subagent_progress')} className="min-w-0">
+ {tree.map((entry) => (
+ <DigestBranch
+ key={entry.node.path}
+ entry={entry}
+ active={active}
+ serverNames={serverNames}
+ />
+ ))}
+ </ul>
+ )}
+ {digest.truncated === true && (
+ <p className="text-text-tertiary mt-1 text-xs">
+ {localize('com_ui_subagent_progress_truncated')}
+ </p>
+ )}
+ </div>
+ );
+});
+
+export default SubagentProgress;
diff --git a/client/src/components/Chat/Messages/Content/Wakeup.tsx b/client/src/components/Chat/Messages/Content/Wakeup.tsx
index 59343eb184..b6345cd244 100644
--- a/client/src/components/Chat/Messages/Content/Wakeup.tsx
+++ b/client/src/components/Chat/Messages/Content/Wakeup.tsx
@@ -2,7 +2,6 @@ import { memo, useCallback, useMemo, useState } from 'react';
import { Users } from 'lucide-react';
import { useRecoilValue } from 'recoil';
import { Button } from '@librechat/client';
-import type { ActiveSubagentPanel } from '~/components/Chat/Subagents/state';
import type { WakeupDisplay, WakeupTask } from './Parts/wakeup';
import type { TranslationKeys } from '~/hooks';
import SystemEventHeader, {
@@ -10,15 +9,11 @@ import SystemEventHeader, {
systemEventHeaderClasses,
} from '~/components/Chat/Messages/ui/SystemEvent';
import { subagentStatusIcon, subagentStatusLabelKey } from '~/components/Chat/Subagents/status';
-import { useParentSubagents } from '~/components/Chat/Subagents/ParentSubagentsProvider';
-import { durableSubagentSelection } from '~/components/Chat/Subagents/eventSelection';
import { useLocalize, useExpandCollapse, useLazyCollapseBody } from '~/hooks';
-import { useOpenSubagentPanel } from '~/components/Chat/Subagents/surface';
+import { useSubagentTaskPanel } from '~/components/Chat/Subagents/task';
import { useMCPIconMap, useMCPServerNames } from '~/hooks/MCP';
-import { useShareContext } from '~/Providers/ShareContext';
import BackgroundTaskCard from './BackgroundTaskCard';
import { cn, getToolDisplayLabel } from '~/utils';
-import { useMessageContext } from '~/Providers';
import { StackedToolIcons } from './ToolOutput';
import MarkdownLite from './MarkdownLite';
import store from '~/store';
@@ -40,50 +35,21 @@ function WakeupTaskCard({
conversationId?: string | null;
}) {
const localize = useLocalize();
- const { isSharedConvo } = useShareContext();
- const { messageId } = useMessageContext();
- const { byThreadId } = useParentSubagents();
- const openPanel = useOpenSubagentPanel();
- const child = task.threadId == null ? undefined : byThreadId.get(task.threadId);
- const selection = useMemo<ActiveSubagentPanel | null>(() => {
- /** Share pages have no authenticated durable-thread panel; a conversation
- * selection there would be written and silently ignored. */
- if (
- isSharedConvo === true ||
- task.threadId == null ||
- conversationId == null ||
- conversationId === ''
- ) {
- return null;
- }
- if (child != null) {
- return durableSubagentSelection(conversationId, child, task.taskId);
- }
- /** The bounded discovery index can omit older children; the wake-up payload
- * already carries the exact durable identities, so link to the authorized
- * thread query directly instead of requiring index membership. */
- return {
- host: 'conversation',
- parentConversationId: conversationId,
- parentMessageId: messageId,
- toolCallId: `wakeup:${task.threadId}`,
- partIndex: 0,
- subagentType: task.subagentType ?? '',
- initialProgress: task.status === 'completed' ? 1 : 0,
- isSubmitting: false,
- durable: { threadId: task.threadId, taskId: task.taskId },
- };
- }, [child, conversationId, isSharedConvo, messageId, task]);
+ const durableTask = useMemo(
+ () => ({
+ threadId: task.threadId,
+ taskId: task.taskId,
+ subagentType: task.subagentType,
+ settled: task.status === 'completed',
+ }),
+ [task.status, task.subagentType, task.taskId, task.threadId],
+ );
+ const { selection, open: openActivity } = useSubagentTaskPanel(durableTask, conversationId);
const status = threadStatus(task.status);
const StatusIcon = subagentStatusIcon(status);
const title = task.subagentType ?? '';
const hasResult = task.result.trim() !== '';
- const openActivity = useCallback(() => {
- if (selection == null || openPanel == null) return;
- openPanel(selection);
- }, [openPanel, selection]);
-
return (
<div className="border-border-light bg-surface-secondary/40 my-1.5 rounded-lg border p-3">
<div className="text-text-secondary flex min-h-6 items-center gap-1.5 text-xs">
@@ -94,7 +60,7 @@ function WakeupTaskCard({
/>
{title !== '' && <span className="min-w-0 truncate font-medium">{title}</span>}
<span className="shrink-0">{localize(subagentStatusLabelKey(status))}</span>
- {selection != null && openPanel != null && (
+ {selection != null && openActivity != null && (
/** The trigger identity attributes let the panel's close handler
* return keyboard focus to this button. */
<Button
diff --git a/client/src/components/Chat/Messages/Content/__tests__/SubagentProgress.test.ts b/client/src/components/Chat/Messages/Content/__tests__/SubagentProgress.test.ts
new file mode 100644
index 0000000000..da30a93340
--- /dev/null
+++ b/client/src/components/Chat/Messages/Content/__tests__/SubagentProgress.test.ts
@@ -0,0 +1,46 @@
+import { buildDigestTree, localizeDigestSummary } from '../SubagentProgress';
+
+jest.mock('~/utils', () => ({
+ cn: (...classes: string[]) => classes.filter(Boolean).join(' '),
+ getToolDisplayLabel: (name: string, _localize: unknown, serverNames?: readonly string[]) =>
+ name === 'bash_tool' ? 'Code' : (serverNames?.find((server) => name.endsWith(server)) ?? name),
+ getRunStepDurationLabels: jest.fn(),
+}));
+
+const localize = ((key: string, values?: Record<string, string | number>) =>
+ values == null ? key : `${key}(${Object.values(values).join(',')})`) as Parameters<
+ typeof localizeDigestSummary
+>[1];
+
+describe('localizeDigestSummary', () => {
+ it('localizes every fragment of a server tally except tool display names', () => {
+ expect(localizeDigestSummary('bash_tool ×3, read_file, text ×2 +4 more', localize)).toBe(
+ 'Code ×3, read_file, com_ui_subagent_progress_reply ×2, com_ui_subagent_progress_more(4)',
+ );
+ expect(
+ localizeDigestSummary('search_mcp_Google_mcp_Workspace ×2', localize, [
+ 'Google_mcp_Workspace',
+ ]),
+ ).toBe('Google_mcp_Workspace ×2');
+ expect(localizeDigestSummary('1 turn, 2 tools', localize)).toBe(
+ 'com_ui_subagent_progress_nested(1,2)',
+ );
+ });
+});
+
+describe('buildDigestTree', () => {
+ it('nests nodes under their parent path and keeps ranges and orphans at their level', () => {
+ const tree = buildDigestTree([
+ { path: '1-5', kind: 'range' },
+ { path: '6', kind: 'turn' },
+ { path: '6.1-3', kind: 'range' },
+ { path: '6.4', kind: 'tool' },
+ { path: '6.4.1', kind: 'turn' },
+ { path: '6.4.1.1', kind: 'tool' },
+ { path: '7.2', kind: 'tool' },
+ ]);
+ expect(tree.map((entry) => entry.node.path)).toEqual(['1-5', '6', '7.2']);
+ expect(tree[1].children.map((entry) => entry.node.path)).toEqual(['6.1-3', '6.4']);
+ expect(tree[1].children[1].children[0].children[0].node.path).toBe('6.4.1.1');
+ });
+});
diff --git a/client/src/components/Chat/Subagents/task.ts b/client/src/components/Chat/Subagents/task.ts
new file mode 100644
index 0000000000..a055503197
--- /dev/null
+++ b/client/src/components/Chat/Subagents/task.ts
@@ -0,0 +1,66 @@
+import { useCallback, useMemo } from 'react';
+import type { ActiveSubagentPanel } from './state';
+import { useParentSubagents } from './ParentSubagentsProvider';
+import { durableSubagentSelection } from './eventSelection';
+import { useShareContext } from '~/Providers/ShareContext';
+import { useOpenSubagentPanel } from './surface';
+import { useMessageContext } from '~/Providers';
+
+/** One durable child task, as a wake-up or a background-task check names it. */
+export interface DurableSubagentTask {
+ threadId?: string;
+ taskId: string;
+ subagentType?: string;
+ settled: boolean;
+}
+
+/**
+ * Opens the unified activity panel on one durable child task. Share pages have
+ * no authenticated thread panel, so they get no selection; a selection there
+ * would be written and silently ignored.
+ */
+export function useSubagentTaskPanel(
+ task: DurableSubagentTask | null,
+ conversationId?: string | null,
+): { selection: ActiveSubagentPanel | null; open: (() => void) | null } {
+ const { isSharedConvo } = useShareContext();
+ const { messageId } = useMessageContext();
+ const { byThreadId } = useParentSubagents();
+ const openPanel = useOpenSubagentPanel();
+ const threadId = task?.threadId;
+ const child = threadId == null ? undefined : byThreadId.get(threadId);
+ const selection = useMemo<ActiveSubagentPanel | null>(() => {
+ if (
+ task == null ||
+ threadId == null ||
+ isSharedConvo === true ||
+ conversationId == null ||
+ conversationId === ''
+ ) {
+ return null;
+ }
+ if (child != null) {
+ return durableSubagentSelection(conversationId, child, task.taskId);
+ }
+ /** The bounded discovery index can omit older children; the task already
+ * carries the exact durable identities, so link to the authorized thread
+ * query directly instead of requiring index membership. */
+ return {
+ host: 'conversation',
+ parentConversationId: conversationId,
+ parentMessageId: messageId,
+ toolCallId: `wakeup:${threadId}`,
+ partIndex: 0,
+ subagentType: task.subagentType ?? '',
+ initialProgress: task.settled ? 1 : 0,
+ isSubmitting: false,
+ durable: { threadId, taskId: task.taskId },
+ };
+ }, [child, conversationId, isSharedConvo, messageId, task, threadId]);
+ const open = useCallback(() => {
+ if (selection != null) {
+ openPanel?.(selection);
+ }
+ }, [openPanel, selection]);
+ return { selection, open: selection == null || openPanel == null ? null : open };
+}
diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json
index ec9ffafbef..897fcbb686 100644
--- a/client/src/locales/en/translation.json
+++ b/client/src/locales/en/translation.json
@@ -58,6 +58,7 @@
"com_ui_background_tasks_running_elsewhere": "Still running outside this turn. Its result may arrive as a new turn.",
"com_ui_background_tasks_subagent_pending_guidance": "Finished subagent results are pending delivery. Poll to collect now or wait for the agent to resume.",
"com_ui_background_tasks_subagent_wakeup_guidance": "This subagent will automatically resume the agent when it finishes; there is no need to poll it repeatedly.",
+ "com_ui_background_tasks_subagent_poll_guidance": "This subagent's result is not delivered automatically; the agent checks on it again later.",
"com_ui_repository_instructions": "Repository instructions",
"com_ui_repository_instructions_prefer": "Prefer repository conventions",
"com_ui_repository_instructions_defer": "Prefer agent conventions",
@@ -2844,6 +2845,16 @@
"com_ui_storage_filter_sort": "Filter and Sort by Storage",
"com_ui_subagent_back_to_parent": "Back to parent chat",
"com_ui_subagent_activity": "Agent activity",
+ "com_ui_subagent_progress": "Progress",
+ "com_ui_subagent_progress_counts": "Turns {{0}} · Tool calls {{1}} · Failed {{2}}",
+ "com_ui_subagent_progress_more": "+{{0}} more",
+ "com_ui_subagent_progress_nested": "Turns {{0}} · Tool calls {{1}}",
+ "com_ui_subagent_progress_evicted": "Summary only; the detail of these turns is no longer kept",
+ "com_ui_subagent_progress_reply": "Reply",
+ "com_ui_subagent_progress_thinking": "Thinking",
+ "com_ui_subagent_progress_truncated": "Some steps are folded to keep this summary short.",
+ "com_ui_subagent_progress_turn": "Turn {{0}}",
+ "com_ui_subagent_progress_turns": "Turns {{0}}",
"com_ui_subagent_agent_count": "{{0}} agent",
"com_ui_subagent_agents_count": "{{0}} agents",
"com_ui_subagent_count_dispatched_one": "{{0}} dispatched",
diff --git a/packages/api/src/agents/background.spec.ts b/packages/api/src/agents/background.spec.ts
index ead7e37788..401653d580 100644
--- a/packages/api/src/agents/background.spec.ts
+++ b/packages/api/src/agents/background.spec.ts
@@ -3,10 +3,14 @@ import { InMemorySubagentTaskStore } from '@librechat/agents';
import type {
LCTool,
LCToolRegistry,
+ SubagentTaskClaim,
SubagentTaskConfig,
SubagentTaskRuntime,
+ SubagentUpdateEvent,
+ SubagentTaskSnapshot,
} from '@librechat/agents';
import type { HostSubagentTaskConfig } from './subagentDelivery';
+import type { ActivitySnapshot } from './digest';
import {
isBackgroundEligibleToolName,
isBackgroundRequested,
@@ -26,11 +30,18 @@ import {
CHECK_BACKGROUND_TASK_NAME,
RUN_IN_BACKGROUND_ARG,
} from './background';
+import {
+ SUBAGENT_POLL_GUIDANCE,
+ SUBAGENT_WAKEUP_GUIDANCE,
+ SUBAGENT_COMPLETION_DELIVERY,
+ SUBAGENT_POLL_WAKEUP_GUIDANCE,
+} from './subagentDelivery';
+import { parseBackgroundTaskOutput } from '../../../../client/src/components/Chat/Messages/Content/Parts/background';
import { parseBackgroundHandle } from '../../../../client/src/components/Chat/Messages/Content/Parts/handle';
-import { SUBAGENT_COMPLETION_DELIVERY, SUBAGENT_WAKEUP_GUIDANCE } from './subagentDelivery';
import { SubagentTaskOwnerUnavailableError } from './subagentTaskRouting';
import { TOOL_SELECTION_WILDCARD } from './selection';
import { toolOptionsSchema } from './validation';
+import { ActivityRecorder } from './digest';
const mcpDef = (name: string): LCTool =>
({
@@ -475,6 +486,12 @@ describe('registerBackgroundTaskTool', () => {
expect(automatic.toolDefinitions[0].description).toContain(
'Polling or cancelling a finished task retires its pending delivery',
);
+ for (const description of [manualDescription, automatic.toolDefinitions[0].description ?? '']) {
+ expect(description).toContain('Pass since: activity.cursor');
+ expect(description).toContain('expand:');
+ /** OpenAI-compatible validators reject longer tool descriptions. */
+ expect(description.length).toBeLessThan(1024);
+ }
});
});
@@ -3248,7 +3265,8 @@ describe('runCheckBackgroundTask (singleton)', () => {
);
expect(polled).toMatchObject({
status: 'running',
- message: SUBAGENT_WAKEUP_GUIDANCE,
+ message: SUBAGENT_POLL_WAKEUP_GUIDANCE,
+ next_check_s: 30,
});
const listed = JSON.parse(
@@ -3273,7 +3291,7 @@ describe('runCheckBackgroundTask (singleton)', () => {
}),
);
expect(ephemeralPoll.status).toBe('running');
- expect(ephemeralPoll.message).toBeUndefined();
+ expect(ephemeralPoll.message).toBe(SUBAGENT_POLL_GUIDANCE);
store.control(subagentTasks.scopeId, started.task.taskId, { action: 'cancel' });
});
@@ -3309,8 +3327,12 @@ describe('runCheckBackgroundTask (singleton)', () => {
subagentTasks,
}),
);
- expect(polled).toMatchObject({ status: 'running' });
- expect(polled.message).toBeUndefined();
+ expect(polled).toMatchObject({
+ status: 'running',
+ message: SUBAGENT_POLL_GUIDANCE,
+ next_check_s: 30,
+ });
+ expect(polled.message).not.toContain('resumes you automatically');
store.control(subagentTasks.scopeId, started.task.taskId, { action: 'cancel' });
});
@@ -4018,3 +4040,248 @@ describe('runCheckBackgroundTask delivery semantics', () => {
expect(cancelled).toEqual(expect.objectContaining({ status: 'not_found' }));
});
});
+
+describe('runCheckBackgroundTask subagent activity', () => {
+ /** The host task store decorates claims and lists with the owner's progress tree;
+ * this store does the same over the SDK store so the poll path runs end to end. */
+ class ActivityTaskStore extends InMemorySubagentTaskStore {
+ readonly recorders = new Map<string, ActivityRecorder>();
+
+ override claim(scopeId: string, taskId: string): SubagentTaskClaim {
+ const claim = super.claim(scopeId, taskId);
+ const recorder = this.recorders.get(taskId);
+ if (claim.status === 'not_found' || recorder == null) {
+ return claim;
+ }
+ const task: ActivitySnapshot = { ...claim.task, activity: recorder.snapshot() };
+ return { ...claim, task };
+ }
+
+ override list(scopeId: string): SubagentTaskSnapshot[] {
+ return super.list(scopeId).map((task): ActivitySnapshot => {
+ const recorder = this.recorders.get(task.taskId);
+ return recorder == null ? task : { ...task, activitySummary: recorder.summary() };
+ });
+ }
+ }
+
+ const update = (phase: SubagentUpdateEvent['phase'], data: unknown): SubagentUpdateEvent => ({
+ runId: 'root-run',
+ subagentRunId: 'child-run',
+ subagentType: 'pr-reviewer',
+ subagentAgentId: 'agent-reviewer',
+ phase,
+ data,
+ timestamp: new Date().toISOString(),
+ });
+
+ const toolCall = (id: string, name: string, intent: string) =>
+ update('run_step', {
+ id: `step-${id}`,
+ stepDetails: {
+ type: 'tool_calls',
+ tool_calls: [{ id, name, args: { intent, secret: 'sk-1' } }],
+ },
+ });
+
+ const toolResult = (id: string, name: string, output: string) =>
+ update('run_step_completed', {
+ result: { type: 'tool_call', tool_call: { id, name, output } },
+ });
+
+ let reviewers = 0;
+
+ function startReviewer(release?: Promise<{ content: string }>) {
+ const store = new ActivityTaskStore();
+ const subagentTasks: HostSubagentTaskConfig = {
+ store,
+ scopeId: 'owner:digest-parent',
+ completionDelivery: SUBAGENT_COMPLETION_DELIVERY,
+ };
+ const recorder = new ActivityRecorder();
+ reviewers += 1;
+ const started = store.start({
+ scopeId: subagentTasks.scopeId,
+ idempotencyKey: `parent-run:parent-agent:reviewer-${reviewers}`,
+ parentRunId: 'parent-run',
+ parentAgentId: 'parent-agent',
+ parentToolCallId: 'call-reviewer',
+ input: 'Review the PR.',
+ subagentKind: 'agent',
+ subagentType: 'pr-reviewer',
+ run: (runtime: SubagentTaskRuntime) =>
+ release ??
+ new Promise((_, reject) => {
+ runtime.signal.addEventListener('abort', () => reject(runtime.signal.reason), {
+ once: true,
+ });
+ }),
+ });
+ if (!started.accepted) {
+ throw new Error('Expected subagent task to start.');
+ }
+ store.recorders.set(started.task.taskId, recorder);
+ for (let index = 1; index <= 8; index++) {
+ const name = index % 2 === 1 ? 'bash_tool' : 'read_file';
+ recorder.record(toolCall(`call-${index}`, name, `Step ${index}`));
+ recorder.record(
+ toolResult(
+ `call-${index}`,
+ name,
+ index === 3 ? 'Error: tool call failed: exit 1' : 'API_KEY=leak',
+ ),
+ );
+ }
+ recorder.record(toolCall('call-9', 'bash_tool', 'Running the jest suite'));
+ const poll = async (args: Record<string, unknown> = {}) =>
+ JSON.parse(
+ await runCheckBackgroundTask({
+ userId: 'owner',
+ conversationId: 'digest-parent',
+ agentId: 'agent_parent',
+ args: { background_task_id: started.task.taskId, ...args },
+ subagentTasks,
+ }),
+ );
+ return { store, subagentTasks, recorder, taskId: started.task.taskId, poll };
+ }
+
+ const paths = (digest: { nodes: Array<{ path: string }> }): string[] =>
+ digest.nodes.map((node) => node.path);
+
+ it('returns a folded, navigable digest for a running subagent', async () => {
+ const { store, subagentTasks, taskId, poll, recorder } = startReviewer();
+ const polled = await poll();
+ expect(polled).toMatchObject({
+ status: 'running',
+ message: SUBAGENT_POLL_WAKEUP_GUIDANCE,
+ next_check_s: 30,
+ activity: { turns: 9, tools: 9, errors: 1, active: '9.1', cursor: '8.1' },
+ });
+ expect(polled.progress_detail).toBeUndefined();
+ expect(paths(polled.activity)).toEqual(['1-3', '4', '5', '6', '7', '8', '9', '9.1']);
+ expect(JSON.stringify(polled)).not.toContain('leak');
+ expect(JSON.stringify(polled)).not.toContain('sk-1');
+
+ const unchanged = await poll({ since: polled.activity.cursor });
+ expect(paths(unchanged.activity)).toEqual(['9', '9.1']);
+ recorder.record(toolResult('call-9', 'bash_tool', 'PASS'));
+ recorder.record(toolCall('call-10', 'read_file', 'Reading the diff'));
+ const advanced = await poll({ since: unchanged.activity.cursor });
+ expect(advanced.activity).toMatchObject({ since: '8.1', cursor: '9.1', active: '10.1' });
+ expect(paths(advanced.activity)).toEqual(['9', '9.1', '10', '10.1']);
+
+ const expanded = await poll({ expand: '1-3' });
+ expect(expanded.activity.expanded).toBe('1-3');
+ expect(expanded.activity.nodes).toEqual([
+ expect.objectContaining({ path: '1', summary: 'bash_tool' }),
+ expect.objectContaining({ path: '2', summary: 'read_file' }),
+ expect.objectContaining({ path: '3', status: 'error', errors: 1 }),
+ ]);
+
+ const display = parseBackgroundTaskOutput(JSON.stringify(polled));
+ expect(display?.kind === 'task' ? display.task.activity?.nodes : undefined).toHaveLength(8);
+
+ store.control(subagentTasks.scopeId, taskId, { action: 'cancel' });
+ });
+
+ it('rejects malformed navigation without touching the task', async () => {
+ const { store, subagentTasks, taskId, poll } = startReviewer();
+ expect(await poll({ expand: 'turn three' })).toEqual({
+ status: 'invalid',
+ background_task_id: taskId,
+ message: expect.stringContaining('expand must be a node path'),
+ });
+ expect(await poll({ since: '1', expand: '2' })).toMatchObject({ status: 'invalid' });
+ expect(store.get(subagentTasks.scopeId, taskId)?.status).toBe('running');
+ store.control(subagentTasks.scopeId, taskId, { action: 'cancel' });
+ });
+
+ it('lists running subagents with counts and only the node in flight', async () => {
+ const { store, subagentTasks, taskId } = startReviewer();
+ const listed = JSON.parse(
+ await runCheckBackgroundTask({
+ userId: 'owner',
+ conversationId: 'digest-parent',
+ agentId: 'agent_parent',
+ args: {},
+ subagentTasks,
+ }),
+ );
+ expect(listed.tasks[0].activity).toEqual({
+ turns: 9,
+ tools: 9,
+ errors: 1,
+ active: '9.1',
+ nodes: [
+ expect.objectContaining({
+ path: '9.1',
+ name: 'bash_tool',
+ label: 'Running the jest suite',
+ status: 'running',
+ }),
+ ],
+ });
+ expect(listed.message).toBe(SUBAGENT_WAKEUP_GUIDANCE);
+ store.control(subagentTasks.scopeId, taskId, { action: 'cancel' });
+ });
+
+ it('returns the result with its activity when a finished, undelivered task is polled', async () => {
+ let finish = (_value: { content: string }): void => undefined;
+ const release = new Promise<{ content: string }>((resolve) => (finish = resolve));
+ const { store, subagentTasks, taskId, poll, recorder } = startReviewer(release);
+ recorder.record(toolResult('call-9', 'bash_tool', 'PASS'));
+ recorder.settle('completed');
+ finish({ content: 'Two findings.' });
+ await waitForSubagentTaskToSettle(store, subagentTasks.scopeId, taskId);
+
+ const collected = await poll();
+ expect(collected).toMatchObject({
+ status: 'completed',
+ result: 'Two findings.',
+ activity: { turns: 9, tools: 9, errors: 1, cursor: '9.1' },
+ });
+ expect(collected.activity.active).toBeUndefined();
+ expect(collected.activity.idle_ms).toBeUndefined();
+ expect(collected.next_check_s).toBeUndefined();
+ expect(collected.message).toBeUndefined();
+ });
+
+ it('keeps the legacy progress label when the owner sends no activity', async () => {
+ const store = new InMemorySubagentTaskStore();
+ const subagentTasks: SubagentTaskConfig = { store, scopeId: 'owner:legacy-parent' };
+ const started = store.start({
+ scopeId: subagentTasks.scopeId,
+ idempotencyKey: 'parent-run:parent-agent:legacy',
+ parentRunId: 'parent-run',
+ parentAgentId: 'parent-agent',
+ parentToolCallId: 'call-legacy',
+ input: 'Research this.',
+ subagentKind: 'agent',
+ subagentType: 'researcher',
+ run: (runtime: SubagentTaskRuntime) => {
+ runtime.reportProgress(update('message_delta', { delta: { content: [] } }));
+ return new Promise((_, reject) => {
+ runtime.signal.addEventListener('abort', () => reject(runtime.signal.reason), {
+ once: true,
+ });
+ });
+ },
+ });
+ if (!started.accepted) {
+ throw new Error('Expected subagent task to start.');
+ }
+ await Promise.resolve();
+ const polled = JSON.parse(
+ await runCheckBackgroundTask({
+ userId: 'owner',
+ conversationId: 'legacy-parent',
+ args: { background_task_id: started.task.taskId, since: '3' },
+ subagentTasks,
+ }),
+ );
+ expect(polled.activity).toBeUndefined();
+ expect(polled.progress_detail).toMatchObject({ phase: 'message_delta' });
+ store.control(subagentTasks.scopeId, started.task.taskId, { action: 'cancel' });
+ });
+});
diff --git a/packages/api/src/agents/background.ts b/packages/api/src/agents/background.ts
index 43cfb15893..7bd90c0e52 100644
--- a/packages/api/src/agents/background.ts
+++ b/packages/api/src/agents/background.ts
@@ -53,13 +53,18 @@ import type {
SubagentTaskControlResult,
SubagentTaskStore,
} from '@librechat/agents';
+import type {
+ SubagentDigest,
+ AgentToolOptions,
+ BackgroundTaskDelivery,
+} from 'librechat-data-provider';
import type {
BackgroundToolResultClaim,
BackgroundToolResultRecord,
} from '@librechat/data-schemas';
-import type { AgentToolOptions, BackgroundTaskDelivery } from 'librechat-data-provider';
import type { BackgroundToolResultState } from './harvest';
import type { CapabilityToolNames } from './selection';
+import type { DigestRequest } from './digest';
import {
BACKGROUND_TASK_TIMEOUT_MS,
BACKGROUND_TASK_SHUTDOWN_MESSAGE,
@@ -70,6 +75,20 @@ import {
type BackgroundToolWakeupAdmission,
type PendingBackgroundCompletionControls,
} from './backgroundCompletion';
+import {
+ SUBAGENT_POLL_GUIDANCE,
+ SUBAGENT_WAKEUP_GUIDANCE,
+ SUBAGENT_POLL_WAKEUP_GUIDANCE,
+ agentUsesSubagentCompletionWakeups,
+} from './subagentDelivery';
+import {
+ renderDigest,
+ DIGEST_LIMITS,
+ snapshotActivity,
+ parseDigestRequest,
+ renderSummaryDigest,
+ snapshotActivitySummary,
+} from './digest';
import {
CREATE_FILE_TOOL_NAME,
EDIT_FILE_TOOL_NAME,
@@ -82,7 +101,6 @@ import {
warnUnmatchedSelectionNames,
synthesizeSelectionToolOptions,
} from './selection';
-import { SUBAGENT_WAKEUP_GUIDANCE, agentUsesSubagentCompletionWakeups } from './subagentDelivery';
import { registerShutdownTask, getRemainingShutdownMs } from '~/app/shutdown';
import { SubagentTaskOwnerUnavailableError } from './subagentTaskRouting';
import { SET_MEMORY_TOOL_NAME, DELETE_MEMORY_TOOL_NAME } from './memory';
@@ -363,13 +381,18 @@ export function stripBackgroundFromToolRegistry(
return next;
}
-const CHECK_BACKGROUND_TASK_DESCRIPTION = `Check, control, and retrieve tool or subagent tasks previously dispatched in the background (with run_in_background: true).
+/** Shared by both descriptions; each stays under the 1,024-character ceiling that
+ * OpenAI-compatible validators enforce. */
+const SUBAGENT_ACTIVITY_DESCRIPTION =
+ 'A subagent returns activity: its turns and tool calls folded to one line each, addressed by stable paths (3 is turn 3, 3.2 its second call). Pass since: activity.cursor for only newer nodes, or expand: a path or range ("3.2", "1-14") to unfold one node.';
+
+const CHECK_BACKGROUND_TASK_DESCRIPTION = `Check, control, and retrieve tasks dispatched with run_in_background: true.
-Provide a background_task_id to poll one task; omit it to list every background task in this thread. A task is only finished when its status is "completed", "error", or "cancelled" — never assume completion without polling. Results are not pushed to you; you must call this tool to collect them. The cancel action applies to subagents and to ordinary tools when enabled by the deployment; steer, queue, interrupt, and cancel_message apply only to subagents. Live controls route to process-local executors and do not survive an owning-process restart. A completed subagent thread may be continued later through the subagent tool's durable thread id.`;
+Give a background_task_id to poll one task; omit it to list every task in this thread. A task is finished only when its status is "completed", "error", or "cancelled". Results are not pushed to you; call this tool to collect them. ${SUBAGENT_ACTIVITY_DESCRIPTION} Cancel applies to subagents, and to ordinary tools when the deployment allows; steer, queue, interrupt, and cancel_message apply only to subagents. Live controls do not survive a restart of the owning process. A completed subagent thread may be continued through the subagent tool's thread id.`;
-const CHECK_BACKGROUND_TASK_WAKEUP_DESCRIPTION = `Check, control, and retrieve tool or subagent tasks previously dispatched in the background (with run_in_background: true).
+const CHECK_BACKGROUND_TASK_WAKEUP_DESCRIPTION = `Check, control, and retrieve tasks dispatched with run_in_background: true.
-Provide a background_task_id to inspect one task; omit it to list every background task in this thread. Background tools and detached subagents use automatic completion delivery: continue independent work or end the turn instead of repeatedly polling an unchanged running task, and the host will resume you when one finishes. Use this tool for explicit status, steer, queue, interrupt, cancel, or cancel_message actions, or as a fallback if automatic delivery is unavailable. A task is outstanding until its result is delivered, not merely until it stops running: a finished task whose delivery is "pending" will still arrive as a new turn, so never report it as done or cancelled on the strength of its status alone. Polling or cancelling a finished task retires its pending delivery so it never arrives as a new turn: a poll returns the result now, and cancelling a result this turn can no longer poll discards it. Ordinary tool execution remains process-local and does not survive restart; once its result is persisted, completion delivery may continue on another replica. Live subagent controls route across API replicas but do not survive a restart of the process that owns the executor. A completed subagent thread may be continued later through the subagent tool's durable thread id.`;
+Give a background_task_id to inspect one task; omit it to list every task in this thread. Background tools and detached subagents use automatic completion delivery: the host resumes you when one finishes, so continue other work or end the turn instead of polling. ${SUBAGENT_ACTIVITY_DESCRIPTION} A task is outstanding until its result is delivered: a finished task with delivery "pending" still arrives as a new turn, so never report it as done on status alone. Polling or cancelling a finished task retires its pending delivery: a poll returns the result now. Controls steer, queue, interrupt, cancel, and cancel_message apply to subagents. Ordinary tool execution remains process-local.`;
function checkBackgroundTaskDescription(subagentCompletionWakeups: boolean): string {
return subagentCompletionWakeups
@@ -395,6 +418,8 @@ interface CheckBackgroundTaskParameters {
action: { type: 'string'; enum: string[]; description: string };
message: BoundedStringSchema;
control_id: BoundedStringSchema;
+ since: BoundedStringSchema;
+ expand: BoundedStringSchema;
};
required: string[];
}
@@ -424,6 +449,18 @@ const CHECK_BACKGROUND_TASK_PARAMETERS = Object.freeze<CheckBackgroundTaskParame
maxLength: MAX_BACKGROUND_CONTROL_ID_CHARS,
description: 'Required for cancel_message; use the id returned by a prior control action.',
},
+ since: {
+ type: 'string',
+ maxLength: DIGEST_LIMITS.argChars,
+ description:
+ 'Subagent poll: activity.cursor from an earlier check; returns only newer nodes.',
+ },
+ expand: {
+ type: 'string',
+ maxLength: DIGEST_LIMITS.argChars,
+ description:
+ 'Subagent poll: a path or range from activity.nodes ("3", "3.2", "1-14"); returns that node with its children.',
+ },
},
required: [],
});
@@ -2303,6 +2340,33 @@ interface SerializedSubagentTask {
message?: string;
/** A finished subagent whose result will still resume the parent turn. */
delivery?: 'pending';
+ /** Navigable progress tree, folded to fit the output budget. */
+ activity?: SubagentDigest;
+ /** Seconds a caller should let pass before checking a running task again. */
+ next_check_s?: number;
+}
+
+/** Bounds of the suggested wait between checks of one running subagent. */
+const NEXT_CHECK_MIN_S = 30;
+const NEXT_CHECK_MAX_S = 300;
+
+/** Advisory only: half the task's age, so a long task is checked less often. */
+function suggestedNextCheck(task: SubagentTaskSnapshot): number {
+ const elapsedS = Math.max(0, Date.now() - task.createdAt) / 1000;
+ return Math.min(NEXT_CHECK_MAX_S, Math.max(NEXT_CHECK_MIN_S, Math.round(elapsedS / 2)));
+}
+
+function subagentActivity(
+ task: SubagentTaskSnapshot,
+ digest: DigestRequest | undefined,
+): SubagentDigest | undefined {
+ const running = task.status === 'running';
+ const tree = snapshotActivity(task);
+ if (tree != null) {
+ return renderDigest(tree, { now: Date.now(), running, request: digest });
+ }
+ const summary = snapshotActivitySummary(task);
+ return summary == null ? undefined : renderSummaryDigest(summary, { now: Date.now(), running });
}
function serializeSubagentSnapshot(
@@ -2312,8 +2376,19 @@ function serializeSubagentSnapshot(
status?: string;
controlId?: string;
completionWakeups?: boolean;
+ /** Set for a single-task poll, which carries the navigation request and guidance. */
+ poll?: { digest?: DigestRequest };
} = {},
): SerializedSubagentTask {
+ const activity = subagentActivity(task, options.poll?.digest);
+ const runningPoll = options.poll != null && task.status === 'running';
+ let message: string | undefined;
+ if (runningPoll) {
+ message =
+ options.completionWakeups === true ? SUBAGENT_POLL_WAKEUP_GUIDANCE : SUBAGENT_POLL_GUIDANCE;
+ } else if (options.completionWakeups === true && task.status === 'running') {
+ message = SUBAGENT_WAKEUP_GUIDANCE;
+ }
return {
background_task_id: task.taskId,
...(task.threadId == null ? {} : { subagent_thread_id: task.threadId }),
@@ -2321,7 +2396,8 @@ function serializeSubagentSnapshot(
subagent_type: task.subagentType,
status: options.status ?? task.status,
progress: task.status === 'running' ? 0 : 1,
- ...(task.progress == null ? {} : { progress_detail: task.progress }),
+ /** The digest supersedes the single latest-event label. */
+ ...(task.progress == null || activity != null ? {} : { progress_detail: task.progress }),
/** Timings follow the task's own lifecycle, never a control receipt's status. */
...taskTimings(task),
...(options.includeResult == null ? {} : { result: options.includeResult }),
@@ -2330,29 +2406,31 @@ function serializeSubagentSnapshot(
...(task.pendingControls > 0 ? { pending_controls: task.pendingControls } : {}),
...(task.error == null ? {} : { error: task.error }),
...(options.controlId == null ? {} : { control_id: options.controlId }),
- ...(options.completionWakeups === true && task.status === 'running'
- ? { message: SUBAGENT_WAKEUP_GUIDANCE }
- : {}),
+ ...(activity == null ? {} : { activity }),
+ ...(runningPoll ? { next_check_s: suggestedNextCheck(task) } : {}),
+ ...(message == null ? {} : { message }),
};
}
function serializeSubagentClaim(
claim: SubagentTaskClaim,
completionWakeups: boolean,
+ digest?: DigestRequest,
): SerializedSubagentTask | undefined {
if (claim.status === 'not_found') {
return undefined;
}
+ const poll = { digest };
if (claim.status === 'completed') {
- return serializeSubagentSnapshot(claim.task, { includeResult: claim.result });
+ return serializeSubagentSnapshot(claim.task, { includeResult: claim.result, poll });
}
if (claim.status === 'error' || claim.status === 'cancelled') {
return {
- ...serializeSubagentSnapshot(claim.task, { status: claim.status }),
+ ...serializeSubagentSnapshot(claim.task, { status: claim.status, poll }),
error: claim.error,
};
}
- return serializeSubagentSnapshot(claim.task, { status: claim.status, completionWakeups });
+ return serializeSubagentSnapshot(claim.task, { status: claim.status, completionWakeups, poll });
}
function serializeSubagentControl(
@@ -2478,6 +2556,15 @@ export async function runCheckBackgroundTask(params: {
const taskId = typeof rawId === 'string' && rawId.trim() !== '' ? rawId.trim() : undefined;
const action = typeof args.action === 'string' && args.action !== '' ? args.action : 'poll';
const invocationId = controlInvocationId(params);
+ const navigation = parseDigestRequest(args);
+ if ('error' in navigation) {
+ return JSON.stringify({
+ status: 'invalid',
+ ...(taskId == null ? {} : { background_task_id: taskId }),
+ message: navigation.error,
+ });
+ }
+ const digest = navigation.request;
if (taskId) {
const task = backgroundTaskRegistry.get(userId, conversationId, taskId);
@@ -2827,6 +2914,7 @@ export async function runCheckBackgroundTask(params: {
const claimed = serializeSubagentClaim(
claim,
agentUsesSubagentCompletionWakeups(subagentTasks, params.agentId),
+ digest,
);
if (claimed != null) {
return JSON.stringify(claimed);
@@ -2947,6 +3035,7 @@ export async function runCheckBackgroundTask(params: {
const claimed = serializeSubagentClaim(
claim,
agentUsesSubagentCompletionWakeups(subagentTasks, params.agentId),
+ digest,
);
if (claimed != null) {
return JSON.stringify(claimed);
diff --git a/packages/api/src/agents/digest/index.ts b/packages/api/src/agents/digest/index.ts
new file mode 100644
index 0000000000..8132ef5550
--- /dev/null
+++ b/packages/api/src/agents/digest/index.ts
@@ -0,0 +1,3 @@
+export * from './tree';
+export * from './view';
+export { ActivityRecorder } from './recorder';
diff --git a/packages/api/src/agents/digest/recorder.spec.ts b/packages/api/src/agents/digest/recorder.spec.ts
new file mode 100644
index 0000000000..1bbaa4a164
--- /dev/null
+++ b/packages/api/src/agents/digest/recorder.spec.ts
@@ -0,0 +1,387 @@
+import type { SubagentUpdateEvent } from '@librechat/agents';
+import { ACTIVITY_TREE_LIMITS, countLeaves, findActiveLeaf } from './tree';
+import { ActivityRecorder } from './recorder';
+
+type Phase = SubagentUpdateEvent['phase'];
+
+function event(
+ phase: Phase,
+ data: unknown,
+ overrides: Partial<SubagentUpdateEvent> = {},
+): SubagentUpdateEvent {
+ return {
+ runId: 'root-run',
+ parentRunId: 'parent-run',
+ subagentRunId: 'child-run',
+ parentToolCallId: 'parent-call',
+ subagentType: 'reviewer',
+ subagentKind: 'agent',
+ subagentAgentId: 'agent-reviewer',
+ phase,
+ data,
+ timestamp: '2026-10-04T12:00:00.000Z',
+ ...overrides,
+ };
+}
+
+const toolStep = (stepId: string, calls: Array<{ id: string; name: string; args?: unknown }>) =>
+ event('run_step', { id: stepId, stepDetails: { type: 'tool_calls', tool_calls: calls } });
+
+const completed = (id: string, name: string, output: string, extra: Record<string, unknown> = {}) =>
+ event('run_step_completed', {
+ result: { type: 'tool_call', tool_call: { id, name, output, ...extra } },
+ });
+
+const text = (stepId: string, value: string) =>
+ event('message_delta', { id: stepId, delta: { content: [{ type: 'text', text: value }] } });
+
+describe('ActivityRecorder', () => {
+ it('folds turns from step events and keeps only names, labels, statuses, and sizes', () => {
+ const recorder = new ActivityRecorder(1_000);
+ recorder.record(event('start', undefined), 1_000);
+ recorder.record(text('msg-1', 'SECRET reply text that must stay private.'), 1_100);
+ recorder.record(
+ toolStep('step-1', [
+ {
+ id: 'call-1',
+ name: 'bash_tool',
+ args: { intent: 'Running the jest suite', command: 'TOKEN=sk-live-123 npm test' },
+ },
+ { id: 'call-2', name: 'read_file', args: JSON.stringify({ path: '/etc/secret.env' }) },
+ ]),
+ 1_200,
+ );
+ recorder.record(completed('call-1', 'bash_tool', 'PASS 12 tests'), 1_700);
+ recorder.record(
+ completed('call-2', 'read_file', 'Error: tool call failed: ENOENT /etc/secret.env'),
+ 1_800,
+ );
+ recorder.record(toolStep('step-2', [{ id: 'call-3', name: 'search_workspace' }]), 2_000);
+
+ const tree = recorder.snapshot();
+ expect(tree.root.turns).toHaveLength(2);
+ expect(tree.root.turns[0].children).toEqual([
+ expect.objectContaining({ kind: 'text', status: 'ok', chars: 41 }),
+ expect.objectContaining({
+ kind: 'tool',
+ name: 'bash_tool',
+ label: 'Running the jest suite',
+ status: 'ok',
+ startedAt: 1_200,
+ endedAt: 1_700,
+ chars: 13,
+ }),
+ expect.objectContaining({ kind: 'tool', name: 'read_file', status: 'error' }),
+ ]);
+ expect(tree.root.turns[1].children).toEqual([
+ expect.objectContaining({ name: 'search_workspace', status: 'running' }),
+ ]);
+ expect(findActiveLeaf(tree.root)?.path).toBe('2.1');
+ const serialized = JSON.stringify(tree);
+ expect(serialized).not.toContain('SECRET');
+ expect(serialized).not.toContain('sk-live');
+ expect(serialized).not.toContain('secret.env');
+ expect(serialized).not.toContain('PASS 12');
+ });
+
+ it('keeps tool calls streamed as separate steps of one response in one turn', () => {
+ const recorder = new ActivityRecorder(0);
+ recorder.record(toolStep('step-a', [{ id: 'a', name: 'read_file' }]), 10);
+ recorder.record(toolStep('step-b', [{ id: 'b', name: 'read_file' }]), 11);
+ recorder.record(
+ event('tool_calls_dispatched', {
+ dispatched_at: 12,
+ toolCalls: [
+ { id: 'a', name: 'read_file' },
+ { id: 'b', name: 'read_file' },
+ ],
+ }),
+ 12,
+ );
+ recorder.record(completed('a', 'read_file', 'one'), 20);
+ recorder.record(completed('b', 'read_file', 'two'), 21);
+ recorder.record(text('msg-2', 'Done.'), 30);
+
+ const tree = recorder.snapshot();
+ expect(tree.root.turns.map((turn) => turn.children.length)).toEqual([2, 1]);
+ });
+
+ it('prefers the tool-authored outcome and reads complete args from execution requests', () => {
+ const recorder = new ActivityRecorder(0);
+ recorder.record(toolStep('step-1', [{ id: 'call', name: 'edit_file', args: '' }]), 1);
+ recorder.record(
+ event('run_step', {
+ toolCalls: [{ id: 'call', name: 'edit_file', args: { intent: 'Editing background.ts' } }],
+ }),
+ 2,
+ );
+ expect(recorder.snapshot().root.turns[0].children[0].label).toBe('Editing background.ts');
+ recorder.record(
+ completed('call', 'edit_file', 'Updated 1 file', { outcome: 'Edited background.ts' }),
+ 3,
+ );
+ expect(recorder.snapshot().root.turns[0].children[0]).toMatchObject({
+ label: 'Edited background.ts',
+ status: 'ok',
+ });
+ });
+
+ it('sanitizes labels to one bounded line without rendering markers', () => {
+ const recorder = new ActivityRecorder(0);
+ recorder.record(
+ toolStep('step', [
+ {
+ id: 'call',
+ name: 'bash\u0000_tool',
+ args: { intent: `Line one\nline two \\ui{abc} \u202e${'x'.repeat(400)}` },
+ },
+ ]),
+ 1,
+ );
+ const leaf = recorder.snapshot().root.turns[0].children[0];
+ expect(leaf.name).toBe('bash _tool');
+ expect(leaf.label?.startsWith('Line one line two ')).toBe(true);
+ expect(leaf.label).not.toContain('\\ui{');
+ expect(leaf.label).not.toContain('\u202e');
+ expect(leaf.label?.length).toBe(ACTIVITY_TREE_LIMITS.labelChars);
+ expect(leaf.label?.endsWith('…')).toBe(true);
+ });
+
+ it('reads intent only as the injected first-property label, never a business field', () => {
+ const recorder = new ActivityRecorder(0);
+ recorder.record(
+ toolStep('step', [
+ { id: 'a', name: 'dialogflow_detect', args: { query: 'refund', intent: 'billing.refund' } },
+ { id: 'b', name: 'web_search', args: '{"intent":"Searching the changelog","q":"x"}' },
+ ]),
+ 1,
+ );
+ const [business, labeled] = recorder.snapshot().root.turns[0].children;
+ expect(business.label).toBeUndefined();
+ expect(labeled.label).toBe('Searching the changelog');
+ });
+
+ it('marks calls of a failed or cancelled step and settles open nodes with the task', () => {
+ const recorder = new ActivityRecorder(0);
+ recorder.record(toolStep('step-1', [{ id: 'a', name: 'bash_tool' }]), 1);
+ recorder.record(event('run_step_closed', { id: 'step-1', status: 'failed' }), 2);
+ expect(recorder.snapshot().root.turns[0].children[0].status).toBe('error');
+
+ recorder.record(toolStep('step-2', [{ id: 'b', name: 'bash_tool' }]), 3);
+ recorder.record(text('msg', 'partial'), 4);
+ recorder.settle('cancelled', 5);
+ const tree = recorder.snapshot();
+ expect(tree.root.turns[1].children.map((leaf) => leaf.status)).toEqual([
+ 'cancelled',
+ 'cancelled',
+ ]);
+ expect(findActiveLeaf(tree.root)).toBeUndefined();
+ });
+
+ it('measures single-part message deltas as well as part arrays', () => {
+ const recorder = new ActivityRecorder(0);
+ recorder.record(
+ event('message_delta', { id: 'msg', delta: { content: { type: 'text', text: 'Hello' } } }),
+ 1,
+ );
+ recorder.record(text('msg', ' there'), 2);
+ expect(recorder.snapshot().root.turns[0].children).toEqual([
+ expect.objectContaining({ kind: 'text', status: 'running', chars: 11 }),
+ ]);
+ });
+
+ it('records a failed reply step and a schema-rejected call as errors', () => {
+ const recorder = new ActivityRecorder(0);
+ recorder.record(text('msg-1', 'partial answer'), 1);
+ recorder.record(event('run_step_closed', { id: 'msg-1', status: 'failed' }), 2);
+ recorder.record(toolStep('step', [{ id: 'call', name: 'edit_file' }]), 3);
+ recorder.record(
+ event('run_step_completed', {
+ result: {
+ type: 'tool_call',
+ tool_call: { id: 'call', name: 'edit_file', inputValidationError: true },
+ },
+ }),
+ 4,
+ );
+ const tree = recorder.snapshot();
+ expect(tree.root.turns.flatMap((turn) => turn.children.map((leaf) => leaf.status))).toEqual([
+ 'error',
+ 'error',
+ ]);
+ });
+
+ it('counts an overflowed call once across all of its events', () => {
+ const recorder = new ActivityRecorder(0);
+ const calls = Array.from({ length: ACTIVITY_TREE_LIMITS.turnChildren + 8 }, (_, index) => ({
+ id: `call-${index}`,
+ name: 'read_file',
+ args: { intent: `Read ${index}` },
+ }));
+ recorder.record(toolStep('step', calls), 1);
+ recorder.record(event('run_step', { toolCalls: calls }), 2);
+ recorder.record(event('tool_calls_dispatched', { dispatched_at: 3, toolCalls: calls }), 3);
+ for (const call of calls) {
+ recorder.record(completed(call.id, call.name, 'ok'), 4);
+ }
+ const [turn] = recorder.snapshot().root.turns;
+ expect(turn.children).toHaveLength(ACTIVITY_TREE_LIMITS.turnChildren);
+ expect(turn.overflow).toBe(8);
+ expect(turn.children.every((leaf) => leaf.status === 'ok')).toBe(true);
+ });
+
+ it('nests a subagent the child starts under its calling tool, within the depth bound', () => {
+ const recorder = new ActivityRecorder(0);
+ recorder.record(toolStep('step', [{ id: 'spawn', name: 'subagent' }]), 1);
+ const nested = { subagentRunId: 'grandchild-run', parentToolCallId: 'spawn', depth: 2 };
+ recorder.record(
+ event(
+ 'run_step',
+ {
+ id: 'g-step',
+ stepDetails: { type: 'tool_calls', tool_calls: [{ id: 'g-call', name: 'web_search' }] },
+ },
+ nested,
+ ),
+ 2,
+ );
+ const deeper = { subagentRunId: 'great-run', parentToolCallId: 'g-call', depth: 3 };
+ recorder.record(
+ event(
+ 'run_step',
+ {
+ id: 'gg-step',
+ stepDetails: { type: 'tool_calls', tool_calls: [{ id: 'gg-call', name: 'bash_tool' }] },
+ },
+ deeper,
+ ),
+ 3,
+ );
+ const tooDeep = { subagentRunId: 'too-deep', parentToolCallId: 'gg-call', depth: 4 };
+ recorder.record(
+ event(
+ 'message_delta',
+ { id: 'x', delta: { content: [{ type: 'text', text: 'hi' }] } },
+ tooDeep,
+ ),
+ 4,
+ );
+
+ const tree = recorder.snapshot();
+ const spawn = tree.root.turns[0].children[0];
+ expect(spawn.run?.turns[0].children[0]).toMatchObject({
+ name: 'web_search',
+ status: 'running',
+ });
+ const grand = spawn.run?.turns[0].children[0];
+ expect(grand?.run?.turns[0].children[0]).toMatchObject({ name: 'bash_tool' });
+ expect(grand?.run?.turns[0].children[0].run).toBeUndefined();
+ expect(tree.root.turns).toHaveLength(1);
+ expect(findActiveLeaf(tree.root)?.path).toBe('1.1.1.1.1.1');
+
+ recorder.record(completed('spawn', 'subagent', 'Nested result'), 5);
+ expect(findActiveLeaf(recorder.snapshot().root)).toBeUndefined();
+ });
+
+ it('attaches a nested run to the call of its own parent run when call ids repeat', () => {
+ const recorder = new ActivityRecorder(0);
+ recorder.record(toolStep('root-step', [{ id: 'call_2', name: 'subagent' }]), 1);
+ const grandchild = {
+ subagentRunId: 'grandchild-run',
+ parentRunId: 'child-run',
+ parentToolCallId: 'call_2',
+ };
+ recorder.record(
+ event(
+ 'run_step',
+ {
+ id: 'g-step',
+ stepDetails: { type: 'tool_calls', tool_calls: [{ id: 'call_2', name: 'subagent' }] },
+ },
+ grandchild,
+ ),
+ 2,
+ );
+ const greatGrandchild = {
+ subagentRunId: 'great-run',
+ parentRunId: 'grandchild-run',
+ parentToolCallId: 'call_2',
+ };
+ recorder.record(
+ event(
+ 'message_delta',
+ { id: 'x', delta: { content: [{ type: 'text', text: 'hi' }] } },
+ greatGrandchild,
+ ),
+ 3,
+ );
+ const spawn = recorder.snapshot().root.turns[0].children[0];
+ expect(spawn.run?.turns[0].children).toHaveLength(1);
+ const nestedSpawn = spawn.run?.turns[0].children[0];
+ expect(nestedSpawn?.run?.turns[0].children).toEqual([
+ expect.objectContaining({ kind: 'text', chars: 2 }),
+ ]);
+ });
+
+ it('never double-counts overflow however many calls one turn announces', () => {
+ const recorder = new ActivityRecorder(0);
+ const calls = Array.from({ length: 700 }, (_, index) => ({
+ id: `c${index}`,
+ name: 'read_file',
+ }));
+ recorder.record(toolStep('step', calls), 1);
+ for (const call of calls) {
+ recorder.record(event('run_step', { toolCalls: [call] }), 2);
+ recorder.record(completed(call.id, call.name, 'ok'), 3);
+ }
+ const [turn] = recorder.snapshot().root.turns;
+ expect(turn.children.length + (turn.overflow ?? 0)).toBe(700);
+ });
+
+ it('folds evicted turns into counts and keeps the tree within its bounds', () => {
+ const recorder = new ActivityRecorder(0);
+ const turns = ACTIVITY_TREE_LIMITS.rootTurns + 10;
+ for (let index = 0; index < turns; index++) {
+ const name = index % 3 === 0 ? 'read_file' : 'bash_tool';
+ recorder.record(toolStep(`step-${index}`, [{ id: `call-${index}`, name }]), index * 10);
+ recorder.record(
+ completed(`call-${index}`, name, index === 0 ? 'Error processing tool: boom' : 'ok'),
+ index * 10 + 5,
+ );
+ }
+ const tree = recorder.snapshot();
+ expect(tree.root.turns).toHaveLength(ACTIVITY_TREE_LIMITS.rootTurns);
+ expect(tree.root.evicted).toMatchObject({ turns: 10, errors: 1, startedAt: 0, endedAt: 95 });
+ expect(Object.fromEntries(tree.root.evicted?.tools ?? [])).toEqual({
+ read_file: 4,
+ bash_tool: 6,
+ });
+ });
+
+ it('caps the retained leaves across the whole tree', () => {
+ const recorder = new ActivityRecorder(0);
+ for (let turn = 0; turn < 40; turn++) {
+ const calls = Array.from({ length: ACTIVITY_TREE_LIMITS.turnChildren + 4 }, (_, index) => ({
+ id: `t${turn}-c${index}`,
+ name: 'read_file',
+ }));
+ recorder.record(toolStep(`step-${turn}`, calls), turn);
+ for (const call of calls) {
+ recorder.record(completed(call.id, 'read_file', 'ok'), turn);
+ }
+ }
+ const tree = recorder.snapshot();
+ expect(countLeaves(tree.root)).toBeLessThanOrEqual(ACTIVITY_TREE_LIMITS.leaves);
+ expect(tree.root.turns[tree.root.turns.length - 1]?.overflow).toBe(4);
+ expect(tree.root.evicted?.turns).toBeGreaterThan(0);
+ });
+
+ it('ignores events without a run identity and never throws on malformed data', () => {
+ const recorder = new ActivityRecorder(0);
+ recorder.record(event('run_step', 'not-an-object'), 1);
+ recorder.record(event('run_step_completed', { result: { tool_call: { name: 'x' } } }), 2);
+ recorder.record(event('message_delta', { delta: { content: 'nope' } }), 3);
+ recorder.record(event('run_step', {}, { subagentRunId: '' }), 4);
+ expect(recorder.snapshot().root.turns).toEqual([]);
+ });
+});
diff --git a/packages/api/src/agents/digest/recorder.ts b/packages/api/src/agents/digest/recorder.ts
new file mode 100644
index 0000000000..2067e23e68
--- /dev/null
+++ b/packages/api/src/agents/digest/recorder.ts
@@ -0,0 +1,505 @@
+import { isFailedToolOutput } from 'librechat-data-provider';
+import type { SubagentDigestStatus } from 'librechat-data-provider';
+import type { SubagentUpdateEvent } from '@librechat/agents';
+import type {
+ ActivityRun,
+ ActivityLeaf,
+ ActivityTree,
+ ActivityTurn,
+ ActivitySummary,
+} from './tree';
+import {
+ foldTurns,
+ emptyFold,
+ countLeaves,
+ readActivityIntent,
+ sanitizeActivityText,
+ ACTIVITY_TREE_LIMITS,
+ summarizeActivityTree,
+} from './tree';
+
+interface RunState {
+ runId: string;
+ run: ActivityRun;
+ depth: number;
+ /** The reply step whose leaf overflowed; its later deltas are not counted again. */
+ overflowTextStep?: string;
+ /** Set once a step announced a call; later sightings then never create leaves. */
+ announced: boolean;
+ maxTurns: number;
+ toolByCallId: Map<string, ActivityLeaf>;
+ textByStepId: Map<string, ActivityLeaf>;
+ callIdsByStepId: Map<string, string[]>;
+}
+
+interface ToolCallShape {
+ id?: unknown;
+ name?: unknown;
+ args?: unknown;
+ function?: { name?: unknown; arguments?: unknown };
+}
+
+const ownerKey = (runId: string, callId: string): string => `${runId.length}:${runId}:${callId}`;
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ value != null && typeof value === 'object' && !Array.isArray(value);
+
+const toolCalls = (value: unknown): ToolCallShape[] =>
+ Array.isArray(value) ? value.filter((call): call is ToolCallShape => isRecord(call)) : [];
+
+const nonEmpty = (value: unknown): string | undefined =>
+ typeof value === 'string' && value !== '' ? value : undefined;
+
+const textPartChars = (part: unknown): number =>
+ isRecord(part) && part.type === 'text' && typeof part.text === 'string' ? part.text.length : 0;
+
+/**
+ * Text characters in one message delta; content is measured, never retained.
+ * Providers send either a part array or a single part object.
+ */
+function deltaChars(data: Record<string, unknown>): number {
+ const content = isRecord(data.delta) ? data.delta.content : undefined;
+ if (!Array.isArray(content)) {
+ return textPartChars(content);
+ }
+ return content.reduce((total: number, part: unknown) => total + textPartChars(part), 0);
+}
+
+function closedStatus(status: unknown): SubagentDigestStatus {
+ if (status === 'cancelled') return 'cancelled';
+ if (status === 'failed' || status === 'error') return 'error';
+ return 'ok';
+}
+
+function settleLeaves(run: ActivityRun, status: SubagentDigestStatus, at: number): void {
+ for (const turn of run.turns) {
+ for (const leaf of turn.children) {
+ if (leaf.run != null) {
+ settleLeaves(leaf.run, status, at);
+ }
+ if (leaf.status === 'running') {
+ leaf.status = status;
+ leaf.endedAt = at;
+ }
+ }
+ }
+}
+
+function collectLeaves(turns: readonly ActivityTurn[], into: Set<ActivityLeaf>): void {
+ for (const turn of turns) {
+ for (const leaf of turn.children) {
+ into.add(leaf);
+ if (leaf.run != null) {
+ collectLeaves(leaf.run.turns, into);
+ }
+ }
+ }
+}
+
+/**
+ * Folds one detached child's update stream into its bounded progress tree on the
+ * process that owns the child. It reads only identities, tool names, the
+ * model-authored `intent` label, the tool-authored `outcome` label, and sizes:
+ * tool arguments, outputs, and reply text never enter the tree.
+ *
+ * A turn is one model response: it opens with the first reply or tool call after
+ * every tool call of the previous turn has settled, so tool calls streamed as
+ * separate steps of one response stay together. Events from a subagent the child
+ * starts (a different `subagentRunId` whose `parentToolCallId` is a recorded call)
+ * nest under that call, up to {@link ACTIVITY_TREE_LIMITS.depth} runs deep.
+ */
+export class ActivityRecorder {
+ private readonly tree: ActivityTree;
+ private readonly runs = new Map<string, RunState>();
+ /** Keyed by owning run and call id: provider call ids repeat across runs. */
+ private readonly callOwners = new Map<
+ string,
+ { leaf: ActivityLeaf; depth: number; callId: string }
+ >();
+
+ private rootRunId?: string;
+ private leaves = 0;
+
+ constructor(now: number = Date.now()) {
+ this.tree = { version: 1, root: { turns: [] }, updatedAt: now };
+ }
+
+ record(event: SubagentUpdateEvent, now: number = Date.now()): void {
+ const state = this.runFor(event);
+ if (state == null) {
+ return;
+ }
+ this.tree.updatedAt = now;
+ if (state.depth === 0) {
+ this.tree.thinking = event.phase === 'reasoning_delta' ? true : undefined;
+ }
+ const data = isRecord(event.data) ? event.data : undefined;
+ if (data == null) {
+ if (event.phase === 'stop' || event.phase === 'error') {
+ this.finishNested(state, event.phase === 'stop' ? 'ok' : 'error', now);
+ }
+ return;
+ }
+ switch (event.phase) {
+ case 'run_step':
+ this.recordStep(state, data, now);
+ return;
+ case 'tool_calls_dispatched':
+ for (const call of toolCalls(data.toolCalls)) {
+ const id = nonEmpty(call.id);
+ if (id != null) {
+ this.ensureTool(state, id, call.name, now, false);
+ }
+ }
+ return;
+ case 'run_step_completed':
+ this.recordCompletion(state, data, now);
+ return;
+ case 'run_step_closed':
+ this.recordClose(state, data, now);
+ return;
+ case 'message_delta':
+ this.recordText(state, data, now);
+ return;
+ case 'stop':
+ case 'error':
+ this.finishNested(state, event.phase === 'stop' ? 'ok' : 'error', now);
+ return;
+ default:
+ return;
+ }
+ }
+
+ /** Closes every node still in flight when the task itself settles. */
+ settle(status: 'completed' | 'error' | 'cancelled', now: number = Date.now()): void {
+ let leafStatus: SubagentDigestStatus = 'error';
+ if (status === 'completed') {
+ leafStatus = 'ok';
+ } else if (status === 'cancelled') {
+ leafStatus = 'cancelled';
+ }
+ settleLeaves(this.tree.root, leafStatus, now);
+ this.tree.thinking = undefined;
+ this.tree.updatedAt = Math.max(this.tree.updatedAt, now);
+ }
+
+ /** An independent copy: callers serialize it while the child keeps recording. */
+ snapshot(): ActivityTree {
+ return structuredClone(this.tree);
+ }
+
+ summary(): ActivitySummary {
+ return summarizeActivityTree(this.tree);
+ }
+
+ private runFor(event: SubagentUpdateEvent): RunState | undefined {
+ const runId = nonEmpty(event.subagentRunId);
+ if (runId == null) {
+ return undefined;
+ }
+ const existing = this.runs.get(runId);
+ if (existing != null) {
+ return existing;
+ }
+ if (this.rootRunId == null) {
+ this.rootRunId = runId;
+ return this.addRun(runId, this.tree.root, 0);
+ }
+ const owner = this.ownerOf(event);
+ if (owner == null || owner.depth + 1 >= ACTIVITY_TREE_LIMITS.depth) {
+ return undefined;
+ }
+ owner.leaf.run ??= { turns: [] };
+ return this.addRun(runId, owner.leaf.run, owner.depth + 1);
+ }
+
+ /**
+ * The recorded call that started a nested run: matched on the spawning run and
+ * call id, or on the call id alone only when exactly one run recorded it.
+ */
+ private ownerOf(event: SubagentUpdateEvent): { leaf: ActivityLeaf; depth: number } | undefined {
+ const callId = nonEmpty(event.parentToolCallId);
+ if (callId == null) {
+ return undefined;
+ }
+ const parentRunId = nonEmpty(event.parentRunId);
+ const exact =
+ parentRunId == null ? undefined : this.callOwners.get(ownerKey(parentRunId, callId));
+ if (exact != null) {
+ return exact;
+ }
+ let match: { leaf: ActivityLeaf; depth: number } | undefined;
+ for (const owner of this.callOwners.values()) {
+ if (owner.callId !== callId) continue;
+ if (match != null) return undefined;
+ match = owner;
+ }
+ return match;
+ }
+
+ private addRun(runId: string, run: ActivityRun, depth: number): RunState {
+ const state: RunState = {
+ runId,
+ announced: false,
+ run,
+ depth,
+ maxTurns: depth === 0 ? ACTIVITY_TREE_LIMITS.rootTurns : ACTIVITY_TREE_LIMITS.nestedTurns,
+ toolByCallId: new Map(),
+ textByStepId: new Map(),
+ callIdsByStepId: new Map(),
+ };
+ this.runs.set(runId, state);
+ return state;
+ }
+
+ private recordStep(state: RunState, data: Record<string, unknown>, now: number): void {
+ /** The SDK forwards tool execution requests on this phase with complete args. */
+ for (const call of toolCalls(data.toolCalls)) {
+ const id = nonEmpty(call.id);
+ if (id != null) {
+ this.labelTool(this.ensureTool(state, id, call.name, now, false), call.args);
+ }
+ }
+ const details = isRecord(data.stepDetails) ? data.stepDetails : undefined;
+ if (details?.type !== 'tool_calls') {
+ return;
+ }
+ const ids: string[] = [];
+ for (const call of toolCalls(details.tool_calls)) {
+ const id = nonEmpty(call.id);
+ if (id == null) {
+ continue;
+ }
+ ids.push(id);
+ const leaf = this.ensureTool(state, id, call.name ?? call.function?.name, now, true);
+ this.labelTool(leaf, call.args ?? call.function?.arguments);
+ }
+ const stepId = nonEmpty(data.id);
+ if (stepId != null && ids.length > 0) {
+ state.callIdsByStepId.set(stepId, ids);
+ }
+ }
+
+ private labelTool(leaf: ActivityLeaf, args: unknown): void {
+ if (leaf.label == null) {
+ const intent = readActivityIntent(args);
+ if (intent != null) {
+ leaf.label = intent;
+ }
+ }
+ }
+
+ private recordCompletion(state: RunState, data: Record<string, unknown>, now: number): void {
+ const result = isRecord(data.result) ? data.result : undefined;
+ const call = isRecord(result?.tool_call) ? result.tool_call : undefined;
+ const id = nonEmpty(call?.id);
+ if (call == null || id == null) {
+ return;
+ }
+ const leaf = this.ensureTool(state, id, call.name, now, false);
+ const output = typeof call.output === 'string' ? call.output : undefined;
+ const failed =
+ call.inputValidationError === true || (output != null && isFailedToolOutput(output));
+ leaf.status = failed ? 'error' : 'ok';
+ leaf.endedAt = now;
+ if (output != null) {
+ leaf.chars = output.length;
+ }
+ const outcome = sanitizeActivityText(call.outcome, ACTIVITY_TREE_LIMITS.labelChars);
+ if (outcome != null) {
+ leaf.label = outcome;
+ } else {
+ this.labelTool(leaf, call.args);
+ }
+ if (leaf.run != null) {
+ settleLeaves(leaf.run, leaf.status, now);
+ }
+ }
+
+ private recordClose(state: RunState, data: Record<string, unknown>, now: number): void {
+ const stepId = nonEmpty(data.id);
+ if (stepId == null) {
+ return;
+ }
+ const status = data.status;
+ const text = state.textByStepId.get(stepId);
+ if (text?.status === 'running') {
+ text.status = closedStatus(status);
+ text.endedAt = now;
+ }
+ if (status !== 'failed' && status !== 'error' && status !== 'cancelled') {
+ return;
+ }
+ for (const callId of state.callIdsByStepId.get(stepId) ?? []) {
+ const leaf = state.toolByCallId.get(callId);
+ if (leaf?.status === 'running') {
+ leaf.status = status === 'cancelled' ? 'cancelled' : 'error';
+ leaf.endedAt = now;
+ }
+ }
+ }
+
+ private recordText(state: RunState, data: Record<string, unknown>, now: number): void {
+ const chars = deltaChars(data);
+ if (chars === 0) {
+ return;
+ }
+ const stepId = nonEmpty(data.id) ?? '';
+ if (state.overflowTextStep === stepId) {
+ return;
+ }
+ let leaf = state.textByStepId.get(stepId);
+ if (leaf == null || leaf.status !== 'running') {
+ leaf = { kind: 'text', status: 'running', startedAt: now, chars: 0 };
+ if (!this.append(state, leaf, now, true)) {
+ state.overflowTextStep = stepId;
+ return;
+ }
+ state.textByStepId.set(stepId, leaf);
+ }
+ leaf.chars = (leaf.chars ?? 0) + chars;
+ }
+
+ /**
+ * Finds or records a tool call. Only the step that announces a call may count it
+ * as overflow; its execution request, dispatch, and result are later sightings of
+ * the same call, so an unretained call is counted exactly once with no lookup
+ * state kept for it.
+ */
+ private ensureTool(
+ state: RunState,
+ id: string,
+ name: unknown,
+ now: number,
+ announces: boolean,
+ ): ActivityLeaf {
+ const existing = state.toolByCallId.get(id);
+ if (existing != null) {
+ existing.name ??= sanitizeActivityText(name, ACTIVITY_TREE_LIMITS.nameChars);
+ return existing;
+ }
+ state.announced ||= announces;
+ const leaf: ActivityLeaf = {
+ kind: 'tool',
+ name: sanitizeActivityText(name, ACTIVITY_TREE_LIMITS.nameChars) ?? 'tool',
+ status: 'running',
+ startedAt: now,
+ };
+ /** Once steps announce calls, an unknown id in a later sighting was overflowed
+ * or evicted; recording it again would count it twice or reopen old history. */
+ if ((state.announced && !announces) || !this.append(state, leaf, now, announces)) {
+ return leaf;
+ }
+ state.toolByCallId.set(id, leaf);
+ this.callOwners.set(ownerKey(state.runId, id), { leaf, depth: state.depth, callId: id });
+ return leaf;
+ }
+
+ /** Returns whether the leaf was retained; a detached nested run retains nothing. */
+ private append(
+ state: RunState,
+ leaf: ActivityLeaf,
+ now: number,
+ countOverflow: boolean,
+ ): boolean {
+ const turn = this.turnFor(state, leaf.kind, now);
+ while (this.leaves >= ACTIVITY_TREE_LIMITS.leaves && this.tree.root.turns.length > 1) {
+ this.evictOldest(this.tree.root);
+ }
+ if (state.depth > 0 && !this.isAttached(state.run)) {
+ return false;
+ }
+ if (
+ turn.children.length >= ACTIVITY_TREE_LIMITS.turnChildren ||
+ this.leaves >= ACTIVITY_TREE_LIMITS.leaves
+ ) {
+ if (countOverflow) {
+ turn.overflow = (turn.overflow ?? 0) + 1;
+ }
+ return false;
+ }
+ turn.children.push(leaf);
+ this.leaves += 1;
+ return true;
+ }
+
+ private turnFor(state: RunState, kind: ActivityLeaf['kind'], now: number): ActivityTurn {
+ const current = state.run.turns[state.run.turns.length - 1];
+ if (current != null && !this.opensTurn(current, kind)) {
+ return current;
+ }
+ for (const leaf of current?.children ?? []) {
+ if (leaf.kind === 'text' && leaf.status === 'running') {
+ leaf.status = 'ok';
+ leaf.endedAt = now;
+ }
+ }
+ const turn: ActivityTurn = { startedAt: now, children: [] };
+ state.run.turns.push(turn);
+ while (state.run.turns.length > state.maxTurns) {
+ this.evictOldest(state.run);
+ }
+ return turn;
+ }
+
+ private opensTurn(turn: ActivityTurn, kind: ActivityLeaf['kind']): boolean {
+ let tools = 0;
+ let settledTools = 0;
+ let openText = false;
+ for (const leaf of turn.children) {
+ if (leaf.kind === 'tool') {
+ tools += 1;
+ settledTools += leaf.status === 'running' ? 0 : 1;
+ } else {
+ openText ||= leaf.status === 'running';
+ }
+ }
+ if (tools > 0) {
+ return settledTools === tools;
+ }
+ return kind === 'text' && turn.children.length > 0 && !openText;
+ }
+
+ private evictOldest(run: ActivityRun): void {
+ const turn = run.turns.shift();
+ if (turn == null) {
+ return;
+ }
+ run.evicted = foldTurns([turn], run.evicted ?? emptyFold(turn.startedAt));
+ const evicted = new Set<ActivityLeaf>();
+ collectLeaves([turn], evicted);
+ this.leaves -= countLeaves({ turns: [turn] });
+ for (const state of this.runs.values()) {
+ for (const [key, leaf] of state.toolByCallId) {
+ if (evicted.has(leaf)) state.toolByCallId.delete(key);
+ }
+ for (const [key, leaf] of state.textByStepId) {
+ if (evicted.has(leaf)) state.textByStepId.delete(key);
+ }
+ for (const [key, callIds] of state.callIdsByStepId) {
+ if (!callIds.some((callId) => state.toolByCallId.has(callId))) {
+ state.callIdsByStepId.delete(key);
+ }
+ }
+ }
+ for (const [key, owner] of this.callOwners) {
+ if (evicted.has(owner.leaf)) this.callOwners.delete(key);
+ }
+ for (const [runId, state] of this.runs) {
+ if (state.depth > 0 && !this.isAttached(state.run)) this.runs.delete(runId);
+ }
+ }
+
+ private isAttached(run: ActivityRun): boolean {
+ for (const owner of this.callOwners.values()) {
+ if (owner.leaf.run === run) return true;
+ }
+ return false;
+ }
+
+ private finishNested(state: RunState, status: SubagentDigestStatus, now: number): void {
+ if (state.depth > 0) {
+ settleLeaves(state.run, status, now);
+ }
+ }
+}
diff --git a/packages/api/src/agents/digest/tree.spec.ts b/packages/api/src/agents/digest/tree.spec.ts
new file mode 100644
index 0000000000..fa5cf3d5d3
--- /dev/null
+++ b/packages/api/src/agents/digest/tree.spec.ts
@@ -0,0 +1,248 @@
+import type { SubagentActivityItem } from 'librechat-data-provider';
+import type { SubagentTaskSnapshot } from '@librechat/agents';
+import type { ActivitySnapshot, ActivityTree } from './tree';
+import {
+ ACTIVITY_TREE_LIMITS,
+ boundActivityTree,
+ snapshotActivity,
+ boundActivitySummary,
+ summarizeActivityTree,
+ activityTreeFromProjection,
+} from './tree';
+import { boundedClaim } from '../subagentTaskRouting';
+import { ActivityRecorder } from './recorder';
+import { renderDigest } from './view';
+
+function recordedTree(): ActivityTree {
+ const recorder = new ActivityRecorder(0);
+ recorder.record(
+ {
+ runId: 'root',
+ subagentRunId: 'child',
+ subagentType: 'reviewer',
+ subagentAgentId: 'agent',
+ phase: 'run_step',
+ data: {
+ id: 'step',
+ stepDetails: {
+ type: 'tool_calls',
+ tool_calls: [{ id: 'call', name: 'bash_tool', args: { intent: 'Run the tests' } }],
+ },
+ },
+ timestamp: '2026-10-04T12:00:00.000Z',
+ },
+ 10,
+ );
+ return recorder.snapshot();
+}
+
+const snapshot = (extra: Partial<ActivitySnapshot> = {}): ActivitySnapshot => ({
+ taskId: 'task-1',
+ threadId: 'thread-1',
+ subagentType: 'reviewer',
+ status: 'running',
+ createdAt: 0,
+ updatedAt: 10,
+ resultAvailable: false,
+ resultClaimed: false,
+ pendingControls: 0,
+ ...extra,
+});
+
+describe('boundActivityTree', () => {
+ it('accepts a recorded tree unchanged after a JSON round trip', () => {
+ const tree = recordedTree();
+ expect(boundActivityTree(JSON.parse(JSON.stringify(tree)))).toEqual(tree);
+ });
+
+ it('re-sanitizes peer-supplied names and labels', () => {
+ const tree = recordedTree();
+ const leaf = tree.root.turns[0].children[0];
+ leaf.name = `evil\u0007${'n'.repeat(200)}`;
+ leaf.label = 'Label \\ui{x}\u2066 tail';
+ const bounded = boundActivityTree(tree);
+ const boundedLeaf = bounded?.root.turns[0].children[0];
+ expect(boundedLeaf?.name?.length).toBe(ACTIVITY_TREE_LIMITS.nameChars);
+ expect(boundedLeaf?.name?.startsWith('evil n')).toBe(true);
+ expect(boundedLeaf?.label).toBe('Label tail');
+ });
+
+ it('refuses malformed, oversized, or over-deep trees instead of renumbering them', () => {
+ const tree = recordedTree();
+ expect(boundActivityTree({ ...tree, version: 2 })).toBeUndefined();
+ expect(
+ boundActivityTree({
+ ...tree,
+ root: {
+ turns: [{ startedAt: 0, children: [{ kind: 'tool', status: 'weird', startedAt: 0 }] }],
+ },
+ }),
+ ).toBeUndefined();
+ const tooMany = {
+ ...tree,
+ root: {
+ turns: Array.from({ length: ACTIVITY_TREE_LIMITS.rootTurns + 1 }, () => ({
+ startedAt: 0,
+ children: [],
+ })),
+ },
+ };
+ expect(boundActivityTree(tooMany)).toBeUndefined();
+ const crowded = {
+ ...tree,
+ root: {
+ turns: Array.from({ length: 12 }, () => ({
+ startedAt: 0,
+ children: Array.from({ length: 30 }, () => ({
+ kind: 'tool',
+ status: 'ok',
+ startedAt: 0,
+ })),
+ })),
+ },
+ };
+ expect(boundActivityTree(crowded)).toBeUndefined();
+
+ let deepLeaf: Record<string, unknown> = { kind: 'tool', status: 'ok', startedAt: 0 };
+ for (let depth = 0; depth < 5; depth++) {
+ deepLeaf = {
+ kind: 'tool',
+ status: 'ok',
+ startedAt: 0,
+ run: { turns: [{ startedAt: 0, children: [deepLeaf] }] },
+ };
+ }
+ const deep = boundActivityTree({
+ version: 1,
+ updatedAt: 0,
+ root: { turns: [{ startedAt: 0, children: [deepLeaf] }] },
+ });
+ const level2 = deep?.root.turns[0].children[0].run?.turns[0].children[0];
+ expect(level2?.run?.turns[0].children[0].run).toBeUndefined();
+ });
+
+ it('travels through the routed claim bounds and drops undecodable decorations', () => {
+ const tree = recordedTree();
+ const routed = JSON.parse(
+ JSON.stringify(boundedClaim({ status: 'running', task: snapshot({ activity: tree }) })),
+ ) as { task: SubagentTaskSnapshot };
+ expect(snapshotActivity(routed.task)).toEqual(tree);
+
+ const tampered = boundedClaim({
+ status: 'running',
+ task: snapshot({ activity: { version: 1 } as unknown as ActivityTree }),
+ });
+ expect('task' in tampered && 'activity' in tampered.task).toBe(false);
+ });
+
+ it('bounds list summaries to counts and one in-flight leaf', () => {
+ const summary = summarizeActivityTree(recordedTree());
+ expect(summary).toEqual({
+ turns: 1,
+ tools: 1,
+ errors: 0,
+ updatedAt: 10,
+ active: {
+ path: '1.1',
+ leaf: expect.objectContaining({ name: 'bash_tool', label: 'Run the tests' }),
+ },
+ });
+ expect(boundActivitySummary(JSON.parse(JSON.stringify(summary)))).toEqual({
+ ...summary,
+ active: {
+ path: '1.1',
+ leaf: {
+ kind: 'tool',
+ name: 'bash_tool',
+ label: 'Run the tests',
+ status: 'running',
+ startedAt: 10,
+ },
+ },
+ });
+ expect(
+ boundActivitySummary({ ...summary, active: { path: '../x', leaf: summary.active?.leaf } }),
+ ).not.toHaveProperty('active');
+ });
+});
+
+describe('activityTreeFromProjection', () => {
+ it('splits turns at replies after tool results and keeps only intents and sizes', () => {
+ const items: SubagentActivityItem[] = [
+ { type: 'reasoning', text: 'private chain of thought' },
+ { type: 'writing', text: 'I will inspect the routing code.' },
+ {
+ type: 'tool',
+ toolCallId: 'a',
+ name: 'read_file',
+ input: JSON.stringify({ intent: 'Reading routing', path: '/srv/.env' }),
+ output: 'API_KEY=secret',
+ status: 'completed',
+ },
+ {
+ type: 'tool',
+ toolCallId: 'b',
+ name: 'bash_tool',
+ input: '{"command":"ls"}',
+ status: 'failed',
+ },
+ { type: 'writing', text: 'Final answer with private details.' },
+ ];
+ const tree = activityTreeFromProjection(items, { startedAt: 100, settledAt: 900 });
+ expect(tree?.root.turns.map((turn) => turn.children.map((leaf) => leaf.kind))).toEqual([
+ ['text', 'tool', 'tool'],
+ ['text'],
+ ]);
+ expect(tree?.root.turns[0].children[1]).toEqual({
+ kind: 'tool',
+ name: 'read_file',
+ label: 'Reading routing',
+ status: 'ok',
+ startedAt: 100,
+ endedAt: 900,
+ chars: 14,
+ });
+ expect(tree?.root.turns[0].children[2].status).toBe('error');
+ const serialized = JSON.stringify(tree);
+ for (const secret of ['secret', 'private', '.env', 'inspect', 'command']) {
+ expect(serialized).not.toContain(secret);
+ }
+ });
+
+ it('re-checks completed calls for failures and marks the tree as rebuilt', () => {
+ const items: SubagentActivityItem[] = [
+ {
+ type: 'tool',
+ toolCallId: 'a',
+ name: 'bash_tool',
+ output: 'Error: tool call failed: exit 2',
+ status: 'completed',
+ },
+ {
+ type: 'tool',
+ toolCallId: 'b',
+ name: 'edit_file',
+ status: 'completed',
+ inputValidationError: true,
+ },
+ { type: 'tool', toolCallId: 'c', name: 'read_file', output: 'fine', status: 'completed' },
+ ];
+ const tree = activityTreeFromProjection(items, { startedAt: 0, settledAt: 1, truncated: true });
+ expect(tree?.root.turns[0].children.map((leaf) => leaf.status)).toEqual([
+ 'error',
+ 'error',
+ 'ok',
+ ]);
+ expect(tree?.rebuilt).toEqual({ partial: true });
+ const digest = renderDigest(tree!, { now: 2, running: false });
+ expect(digest).toMatchObject({ errors: 2, truncated: true });
+ expect(digest.note).toContain('Rebuilt from the saved activity summary');
+ expect(digest.note).toContain('kept only the newest activity');
+ });
+
+ it('returns nothing for a projection without steps', () => {
+ expect(
+ activityTreeFromProjection([{ type: 'reasoning' }], { startedAt: 0, settledAt: 1 }),
+ ).toBeUndefined();
+ });
+});
diff --git a/packages/api/src/agents/digest/tree.ts b/packages/api/src/agents/digest/tree.ts
new file mode 100644
index 0000000000..0eee1253f7
--- /dev/null
+++ b/packages/api/src/agents/digest/tree.ts
@@ -0,0 +1,541 @@
+import { isFailedToolOutput } from 'librechat-data-provider';
+import type { SubagentDigestStatus, SubagentActivityItem } from 'librechat-data-provider';
+import type { SubagentTaskSnapshot } from '@librechat/agents';
+
+/**
+ * Retention bounds for one task's progress tree. The tree travels inside routed
+ * claim responses between replicas, so every bound here caps a wire payload too.
+ */
+export const ACTIVITY_TREE_LIMITS: Readonly<{
+ rootTurns: number;
+ nestedTurns: number;
+ turnChildren: number;
+ leaves: number;
+ depth: number;
+ nameChars: number;
+ labelChars: number;
+ foldTools: number;
+}> = Object.freeze({
+ rootTurns: 48,
+ nestedTurns: 12,
+ turnChildren: 32,
+ leaves: 300,
+ /** The task's own run plus two levels of subagents it starts. */
+ depth: 3,
+ nameChars: 64,
+ labelChars: 120,
+ foldTools: 16,
+});
+
+/** One tool call or text reply inside a turn; a subagent call may hold a nested run. */
+export interface ActivityLeaf {
+ kind: 'tool' | 'text';
+ name?: string;
+ label?: string;
+ status: SubagentDigestStatus;
+ startedAt: number;
+ endedAt?: number;
+ chars?: number;
+ run?: ActivityRun;
+}
+
+/** One model response and the tool calls it made. */
+export interface ActivityTurn {
+ startedAt: number;
+ children: ActivityLeaf[];
+ /** Children past the per-turn cap: counted, never retained or addressed. */
+ overflow?: number;
+}
+
+/** Aggregate of turns no longer retained, so their range still reads truthfully. */
+export interface ActivityFold {
+ turns: number;
+ tools: Array<[string, number]>;
+ otherTools: number;
+ texts: number;
+ errors: number;
+ startedAt: number;
+ endedAt: number;
+}
+
+export interface ActivityRun {
+ /** Turns `1..evicted.turns`; retained turns are numbered after them. */
+ evicted?: ActivityFold;
+ turns: ActivityTurn[];
+}
+
+/** A task's bounded progress tree. Paths into it are positional and append-only. */
+export interface ActivityTree {
+ version: 1;
+ root: ActivityRun;
+ /** Epoch milliseconds of the child's most recent activity. */
+ updatedAt: number;
+ /** The child is reasoning with no tool call or reply in flight. */
+ thinking?: boolean;
+ /**
+ * Rebuilt from the settlement-time public projection after the owner was gone.
+ * Its turn split and paths are a reconstruction and may differ from the live
+ * tree's; `partial` means the projection itself kept only the newest activity.
+ */
+ rebuilt?: { partial: boolean };
+}
+
+/** The list-path view: counts plus the node in flight, never the whole tree. */
+export interface ActivitySummary {
+ turns: number;
+ tools: number;
+ errors: number;
+ updatedAt: number;
+ thinking?: boolean;
+ active?: { path: string; leaf: ActivityLeaf };
+}
+
+/** A task snapshot as the host decorates it for the poll tool. */
+export type ActivitySnapshot = SubagentTaskSnapshot & {
+ activity?: ActivityTree;
+ activitySummary?: ActivitySummary;
+};
+
+const STATUSES: ReadonlySet<string> = new Set(['running', 'ok', 'error', 'cancelled']);
+const UI_RESOURCE_MARKER = /\\ui\{[\w]+(?:,[\w]+)*\}/g;
+/** C0/C1 controls, bidi overrides and isolates, and citation private-use markers. */
+const isUnsafeCode = (code: number): boolean =>
+ code <= 0x1f ||
+ (code >= 0x7f && code <= 0x9f) ||
+ (code >= 0x202a && code <= 0x202e) ||
+ (code >= 0x2066 && code <= 0x2069) ||
+ (code >= 0xe200 && code <= 0xe206);
+
+function replaceUnsafe(value: string): string {
+ let line = '';
+ for (const char of value) {
+ line += isUnsafeCode(char.codePointAt(0) ?? 0) ? ' ' : char;
+ }
+ return line;
+}
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ value != null && typeof value === 'object' && !Array.isArray(value);
+
+const timestamp = (value: unknown): number | undefined =>
+ typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined;
+
+const count = (value: unknown): number | undefined =>
+ Number.isSafeInteger(value) && (value as number) >= 0 ? (value as number) : undefined;
+
+/**
+ * Normalizes a model- or tool-authored display string to one bounded line. Labels
+ * are the child's own one-line intents, so this only strips rendering markers and
+ * control characters; it never reads beyond the string it is given.
+ */
+export function sanitizeActivityText(value: unknown, maxChars: number): string | undefined {
+ if (typeof value !== 'string' || maxChars <= 0) {
+ return undefined;
+ }
+ const line = replaceUnsafe(value.replace(UI_RESOURCE_MARKER, '')).replace(/\s+/g, ' ').trim();
+ if (line === '') {
+ return undefined;
+ }
+ return line.length <= maxChars ? line : `${line.slice(0, Math.max(1, maxChars - 1))}…`;
+}
+
+const coerceArgs = (args: unknown): Record<string, unknown> | undefined => {
+ if (isRecord(args)) {
+ return args;
+ }
+ if (typeof args !== 'string' || !args.trimStart().startsWith('{')) {
+ return undefined;
+ }
+ try {
+ const parsed: unknown = JSON.parse(args);
+ return isRecord(parsed) ? parsed : undefined;
+ } catch {
+ return undefined;
+ }
+};
+
+/**
+ * Reads only the model-authored `intent` label from tool-call arguments. The host
+ * injects that label as the first property, and the chat UI only treats a first
+ * `intent` key as a label, so a tool's own `intent` business field stays unread.
+ */
+export function readActivityIntent(args: unknown): string | undefined {
+ const parsed = coerceArgs(args);
+ if (parsed == null || Object.keys(parsed)[0] !== 'intent') {
+ return undefined;
+ }
+ return sanitizeActivityText(parsed.intent, ACTIVITY_TREE_LIMITS.labelChars);
+}
+
+export function emptyFold(at: number): ActivityFold {
+ return { turns: 0, tools: [], otherTools: 0, texts: 0, errors: 0, startedAt: at, endedAt: at };
+}
+
+const leafEnd = (leaf: ActivityLeaf): number => leaf.endedAt ?? leaf.startedAt;
+
+/** Adds turns to a fold, keeping the most frequent tool names within the bound. */
+export function foldTurns(turns: readonly ActivityTurn[], into?: ActivityFold): ActivityFold {
+ const fold = into ?? emptyFold(turns[0]?.startedAt ?? 0);
+ const tools = new Map<string, number>(fold.tools);
+ let otherTools = fold.otherTools;
+ for (const turn of turns) {
+ fold.turns += 1;
+ fold.startedAt = Math.min(fold.startedAt, turn.startedAt);
+ otherTools += turn.overflow ?? 0;
+ for (const leaf of turn.children) {
+ fold.endedAt = Math.max(fold.endedAt, leafEnd(leaf));
+ if (leaf.status === 'error') {
+ fold.errors += 1;
+ }
+ if (leaf.kind === 'text') {
+ fold.texts += 1;
+ continue;
+ }
+ const name = leaf.name ?? 'tool';
+ tools.set(name, (tools.get(name) ?? 0) + 1);
+ }
+ }
+ const ranked = [...tools.entries()].sort((left, right) => right[1] - left[1]);
+ fold.tools = ranked.slice(0, ACTIVITY_TREE_LIMITS.foldTools);
+ fold.otherTools =
+ otherTools +
+ ranked.slice(ACTIVITY_TREE_LIMITS.foldTools).reduce((total, [, value]) => total + value, 0);
+ return fold;
+}
+
+export function countLeaves(run: ActivityRun): number {
+ let total = 0;
+ for (const turn of run.turns) {
+ for (const leaf of turn.children) {
+ total += 1 + (leaf.run == null ? 0 : countLeaves(leaf.run));
+ }
+ }
+ return total;
+}
+
+/** Walks the root run to the most recent leaf still in flight, through nested runs. */
+export function findActiveLeaf(
+ run: ActivityRun,
+ prefix = '',
+): { path: string; leaf: ActivityLeaf } | undefined {
+ const base = run.evicted?.turns ?? 0;
+ for (let turnIndex = run.turns.length - 1; turnIndex >= 0; turnIndex--) {
+ const children = run.turns[turnIndex].children;
+ for (let childIndex = children.length - 1; childIndex >= 0; childIndex--) {
+ const leaf = children[childIndex];
+ if (leaf.status !== 'running') {
+ continue;
+ }
+ const path = `${prefix}${base + turnIndex + 1}.${childIndex + 1}`;
+ const nested = leaf.run == null ? undefined : findActiveLeaf(leaf.run, `${path}.`);
+ return nested ?? { path, leaf };
+ }
+ }
+ return undefined;
+}
+
+/** Root-level counters shared by the full digest and the list summary. */
+export function countActivity(run: ActivityRun): { turns: number; tools: number; errors: number } {
+ let tools = 0;
+ let errors = run.evicted?.errors ?? 0;
+ for (const [, value] of run.evicted?.tools ?? []) {
+ tools += value;
+ }
+ tools += run.evicted?.otherTools ?? 0;
+ for (const turn of run.turns) {
+ tools += turn.overflow ?? 0;
+ for (const leaf of turn.children) {
+ if (leaf.kind === 'tool') {
+ tools += 1;
+ }
+ if (leaf.status === 'error') {
+ errors += 1;
+ }
+ }
+ }
+ return { turns: (run.evicted?.turns ?? 0) + run.turns.length, tools, errors };
+}
+
+export function summarizeActivityTree(tree: ActivityTree): ActivitySummary {
+ const active = findActiveLeaf(tree.root);
+ return {
+ ...countActivity(tree.root),
+ updatedAt: tree.updatedAt,
+ ...(tree.thinking === true ? { thinking: true } : {}),
+ ...(active == null
+ ? {}
+ : { active: { path: active.path, leaf: { ...active.leaf, run: undefined } } }),
+ };
+}
+
+function boundFold(value: unknown): ActivityFold | undefined {
+ if (!isRecord(value)) {
+ return undefined;
+ }
+ const turns = count(value.turns);
+ const startedAt = timestamp(value.startedAt);
+ const endedAt = timestamp(value.endedAt);
+ if (turns == null || turns === 0 || startedAt == null || endedAt == null) {
+ return undefined;
+ }
+ const tools = Array.isArray(value.tools)
+ ? value.tools.flatMap((entry): Array<[string, number]> => {
+ if (!Array.isArray(entry) || entry.length !== 2) {
+ return [];
+ }
+ const name = sanitizeActivityText(entry[0], ACTIVITY_TREE_LIMITS.nameChars);
+ const total = count(entry[1]);
+ return name == null || total == null ? [] : [[name, total]];
+ })
+ : [];
+ return {
+ turns,
+ tools: tools.slice(0, ACTIVITY_TREE_LIMITS.foldTools),
+ otherTools: count(value.otherTools) ?? 0,
+ texts: count(value.texts) ?? 0,
+ errors: count(value.errors) ?? 0,
+ startedAt,
+ endedAt,
+ };
+}
+
+interface BoundBudget {
+ leaves: number;
+}
+
+function boundLeaf(value: unknown, depth: number, budget: BoundBudget): ActivityLeaf | undefined {
+ if (!isRecord(value) || budget.leaves <= 0) {
+ return undefined;
+ }
+ const kind = value.kind === 'tool' || value.kind === 'text' ? value.kind : undefined;
+ const status =
+ typeof value.status === 'string' && STATUSES.has(value.status)
+ ? (value.status as SubagentDigestStatus)
+ : undefined;
+ const startedAt = timestamp(value.startedAt);
+ if (kind == null || status == null || startedAt == null) {
+ return undefined;
+ }
+ budget.leaves -= 1;
+ const name = sanitizeActivityText(value.name, ACTIVITY_TREE_LIMITS.nameChars);
+ const label = sanitizeActivityText(value.label, ACTIVITY_TREE_LIMITS.labelChars);
+ const endedAt = timestamp(value.endedAt);
+ const chars = count(value.chars);
+ const run =
+ kind === 'tool' && depth + 1 < ACTIVITY_TREE_LIMITS.depth
+ ? boundRun(value.run, depth + 1, budget)
+ : undefined;
+ return {
+ kind,
+ status,
+ startedAt,
+ ...(name == null ? {} : { name }),
+ ...(label == null ? {} : { label }),
+ ...(endedAt == null ? {} : { endedAt }),
+ ...(chars == null ? {} : { chars }),
+ ...(run == null ? {} : { run }),
+ };
+}
+
+function boundRun(value: unknown, depth: number, budget: BoundBudget): ActivityRun | undefined {
+ if (!isRecord(value) || !Array.isArray(value.turns)) {
+ return undefined;
+ }
+ const maxTurns = depth === 0 ? ACTIVITY_TREE_LIMITS.rootTurns : ACTIVITY_TREE_LIMITS.nestedTurns;
+ /** Owners fold old turns before sending. Re-folding here would renumber nothing
+ * but would trust a peer that ignored the bound, so an oversized run is refused. */
+ if (value.turns.length > maxTurns) {
+ return undefined;
+ }
+ const evicted = boundFold(value.evicted);
+ const turns: ActivityTurn[] = [];
+ for (const candidate of value.turns) {
+ if (!isRecord(candidate) || !Array.isArray(candidate.children)) {
+ return undefined;
+ }
+ const startedAt = timestamp(candidate.startedAt);
+ if (startedAt == null) {
+ return undefined;
+ }
+ const children = candidate.children
+ .slice(0, ACTIVITY_TREE_LIMITS.turnChildren)
+ .map((child) => boundLeaf(child, depth, budget));
+ if (children.some((child) => child == null)) {
+ return undefined;
+ }
+ const overflow =
+ (count(candidate.overflow) ?? 0) +
+ Math.max(0, candidate.children.length - ACTIVITY_TREE_LIMITS.turnChildren);
+ turns.push({
+ startedAt,
+ children: children as ActivityLeaf[],
+ ...(overflow > 0 ? { overflow } : {}),
+ });
+ }
+ return { ...(evicted == null ? {} : { evicted }), turns };
+}
+
+/**
+ * Validates a tree from another replica or a decorated snapshot and re-applies
+ * every bound. A malformed tree is dropped whole rather than renumbered, because a
+ * partial tree would hand the model paths that address different nodes.
+ */
+export function boundActivityTree(value: unknown): ActivityTree | undefined {
+ if (!isRecord(value) || value.version !== 1) {
+ return undefined;
+ }
+ const updatedAt = timestamp(value.updatedAt);
+ const root = boundRun(value.root, 0, { leaves: ACTIVITY_TREE_LIMITS.leaves });
+ if (updatedAt == null || root == null) {
+ return undefined;
+ }
+ const rebuilt = isRecord(value.rebuilt) ? { partial: value.rebuilt.partial === true } : undefined;
+ return {
+ version: 1,
+ root,
+ updatedAt,
+ ...(value.thinking === true ? { thinking: true } : {}),
+ ...(rebuilt == null ? {} : { rebuilt }),
+ };
+}
+
+const PATH_PATTERN = /^\d{1,6}(?:\.\d{1,6})*$/;
+
+export function boundActivitySummary(value: unknown): ActivitySummary | undefined {
+ if (!isRecord(value)) {
+ return undefined;
+ }
+ const turns = count(value.turns);
+ const tools = count(value.tools);
+ const errors = count(value.errors);
+ const updatedAt = timestamp(value.updatedAt);
+ if (turns == null || tools == null || errors == null || updatedAt == null) {
+ return undefined;
+ }
+ let active: ActivitySummary['active'];
+ if (isRecord(value.active) && typeof value.active.path === 'string') {
+ const leaf = boundLeaf(value.active.leaf, ACTIVITY_TREE_LIMITS.depth, { leaves: 1 });
+ if (leaf != null && value.active.path.length <= 64 && PATH_PATTERN.test(value.active.path)) {
+ active = { path: value.active.path, leaf };
+ }
+ }
+ return {
+ turns,
+ tools,
+ errors,
+ updatedAt,
+ ...(value.thinking === true ? { thinking: true } : {}),
+ ...(active == null ? {} : { active }),
+ };
+}
+
+/** Reads the host decoration from a snapshot without trusting its shape. */
+export function snapshotActivity(task: SubagentTaskSnapshot): ActivityTree | undefined {
+ const decorated = task as ActivitySnapshot;
+ return decorated.activity == null ? undefined : boundActivityTree(decorated.activity);
+}
+
+export function snapshotActivitySummary(task: SubagentTaskSnapshot): ActivitySummary | undefined {
+ const decorated = task as ActivitySnapshot;
+ return decorated.activitySummary == null
+ ? undefined
+ : boundActivitySummary(decorated.activitySummary);
+}
+
+/** Copies a snapshot's bounded decorations onto a rebuilt snapshot. */
+export function carryActivity(
+ from: SubagentTaskSnapshot,
+ to: SubagentTaskSnapshot,
+): ActivitySnapshot {
+ const activity = snapshotActivity(from);
+ const activitySummary = snapshotActivitySummary(from);
+ return {
+ ...to,
+ ...(activity == null ? {} : { activity }),
+ ...(activitySummary == null ? {} : { activitySummary }),
+ };
+}
+
+/** Current SDK results can persist a failure as a completed message, so a
+ * completed status is re-checked against the same verdict the live recorder uses. */
+const projectionStatus = (
+ item: Extract<SubagentActivityItem, { type: 'tool' }>,
+): SubagentDigestStatus => {
+ if (item.status === 'failed') return 'error';
+ if (item.status !== 'completed') return item.status;
+ const failed =
+ item.inputValidationError === true || (item.output != null && isFailedToolOutput(item.output));
+ return failed ? 'error' : 'ok';
+};
+
+/**
+ * Rebuilds a coarse tree from the durable public activity projection a completed
+ * child persisted at settlement. It carries no timings, so every node shares the
+ * task's own window; it exists so a finished result can still be navigated after
+ * the owning process has gone. Tool results arrive in result order, and a reply
+ * after a tool result starts the next turn, so the tree is marked `rebuilt`.
+ */
+export function activityTreeFromProjection(
+ items: readonly SubagentActivityItem[],
+ window: { startedAt: number; settledAt: number; truncated?: boolean },
+): ActivityTree | undefined {
+ const root: ActivityRun = { turns: [] };
+ let turn: ActivityTurn | undefined;
+ let sawTool = false;
+ let leaves = 0;
+ const open = (): ActivityTurn => {
+ const next: ActivityTurn = { startedAt: window.startedAt, children: [] };
+ root.turns.push(next);
+ sawTool = false;
+ return next;
+ };
+ for (const item of items) {
+ if (item.type !== 'tool' && item.type !== 'writing') {
+ continue;
+ }
+ if (turn == null || (item.type === 'writing' && sawTool)) {
+ turn = open();
+ }
+ if (turn.children.length >= ACTIVITY_TREE_LIMITS.turnChildren) {
+ turn.overflow = (turn.overflow ?? 0) + 1;
+ continue;
+ }
+ leaves += 1;
+ if (item.type === 'writing') {
+ turn.children.push({
+ kind: 'text',
+ status: 'ok',
+ startedAt: window.startedAt,
+ endedAt: window.settledAt,
+ chars: item.text.length,
+ });
+ continue;
+ }
+ sawTool = true;
+ const label = readActivityIntent(item.input);
+ turn.children.push({
+ kind: 'tool',
+ name: sanitizeActivityText(item.name, ACTIVITY_TREE_LIMITS.nameChars) ?? 'tool',
+ status: projectionStatus(item),
+ startedAt: window.startedAt,
+ endedAt: window.settledAt,
+ ...(label == null ? {} : { label }),
+ ...(item.output == null ? {} : { chars: item.output.length }),
+ });
+ }
+ if (leaves === 0) {
+ return undefined;
+ }
+ const evictedTurns = root.turns.splice(
+ 0,
+ Math.max(0, root.turns.length - ACTIVITY_TREE_LIMITS.rootTurns),
+ );
+ const run: ActivityRun =
+ evictedTurns.length === 0 ? root : { evicted: foldTurns(evictedTurns), turns: root.turns };
+ return boundActivityTree({
+ version: 1,
+ root: run,
+ updatedAt: window.settledAt,
+ rebuilt: { partial: window.truncated === true },
+ });
+}
diff --git a/packages/api/src/agents/digest/view.spec.ts b/packages/api/src/agents/digest/view.spec.ts
new file mode 100644
index 0000000000..2948f3debb
--- /dev/null
+++ b/packages/api/src/agents/digest/view.spec.ts
@@ -0,0 +1,309 @@
+import type { ActivityLeaf, ActivityTree, ActivityTurn } from './tree';
+import { DIGEST_LIMITS, parseDigestRequest, renderDigest, renderSummaryDigest } from './view';
+import { summarizeActivityTree } from './tree';
+
+const tool = (
+ name: string,
+ status: ActivityLeaf['status'] = 'ok',
+ extra: Partial<ActivityLeaf> = {},
+): ActivityLeaf => ({
+ kind: 'tool',
+ name,
+ status,
+ startedAt: 1_000,
+ ...(status === 'running' ? {} : { endedAt: 1_400 }),
+ ...extra,
+});
+
+const turn = (...children: ActivityLeaf[]): ActivityTurn => ({ startedAt: 1_000, children });
+
+function tree(turns: ActivityTurn[], extra: Partial<ActivityTree> = {}): ActivityTree {
+ return { version: 1, root: { turns }, updatedAt: 1_500, ...extra };
+}
+
+function request(args: Record<string, unknown>) {
+ const parsed = parseDigestRequest(args);
+ if ('error' in parsed) {
+ throw new Error(parsed.error);
+ }
+ return parsed.request;
+}
+
+/** A long-running child: 20 settled turns, then one turn with a call in flight. */
+function longRun(): ActivityTree {
+ const turns = Array.from({ length: 20 }, (_, index) =>
+ turn(
+ tool(index % 2 === 0 ? 'bash_tool' : 'read_file', index === 4 ? 'error' : 'ok', {
+ label: `Step ${index + 1} intent`,
+ }),
+ ),
+ );
+ turns.push(
+ turn(
+ { kind: 'text', status: 'ok', startedAt: 1_000, endedAt: 1_100, chars: 240 },
+ tool('bash_tool', 'running', { label: 'Running jest for background.spec' }),
+ ),
+ );
+ return tree(turns);
+}
+
+describe('renderDigest', () => {
+ it('folds history into aligned ranges and opens the active turn', () => {
+ const digest = renderDigest(longRun(), { now: 43_000, running: true });
+ expect(digest).toMatchObject({
+ turns: 21,
+ tools: 21,
+ errors: 1,
+ active: '21.2',
+ cursor: '21.1',
+ });
+ expect(digest.nodes.map((node) => node.path)).toEqual([
+ '1-5',
+ '6-10',
+ '11-15',
+ '16',
+ '17',
+ '18',
+ '19',
+ '20',
+ '21',
+ '21.1',
+ '21.2',
+ ]);
+ expect(digest.nodes[0]).toMatchObject({
+ kind: 'range',
+ status: 'error',
+ summary: 'bash_tool ×3, read_file ×2',
+ errors: 1,
+ folded: true,
+ });
+ expect(digest.nodes[3]).toMatchObject({ kind: 'turn', summary: 'read_file', folded: true });
+ expect(digest.truncated).toBeUndefined();
+ expect(digest.nodes[digest.nodes.length - 1]).toMatchObject({
+ kind: 'tool',
+ name: 'bash_tool',
+ status: 'running',
+ label: 'Running jest for background.spec',
+ ms: 42_000,
+ });
+ expect(digest.idle_ms).toBeUndefined();
+ });
+
+ it('returns only nodes after a cursor, and says so when nothing is new', () => {
+ const digest = renderDigest(longRun(), {
+ now: 2_000,
+ running: true,
+ request: request({ since: '21.1' }),
+ });
+ expect(digest.since).toBe('21.1');
+ expect(digest.nodes.map((node) => node.path)).toEqual(['21', '21.2']);
+
+ const settled = tree([turn(tool('read_file'), tool('bash_tool'))]);
+ const none = renderDigest(settled, {
+ now: 2_000,
+ running: true,
+ request: request({ since: '1.2' }),
+ });
+ expect(none.nodes).toEqual([]);
+ expect(none.note).toBe('No new activity since 1.2.');
+ expect(none).toMatchObject({ cursor: '1.2', idle_ms: 500 });
+ expect(none.phase).toBeUndefined();
+
+ const fromTurn = renderDigest(longRun(), {
+ now: 2_000,
+ running: true,
+ request: request({ since: '19' }),
+ });
+ expect(fromTurn.nodes.map((node) => node.path)).toEqual(['20', '20.1', '21', '21.1', '21.2']);
+ });
+
+ it('expands one turn, one leaf with its nested run, and ranges of either', () => {
+ const nested = tool('subagent', 'running', {
+ run: { turns: [turn(tool('web_search')), turn(tool('bash_tool', 'running'))] },
+ });
+ const source = tree([turn(tool('read_file'), nested, tool('bash_tool', 'error'))]);
+
+ const turnView = renderDigest(source, {
+ now: 2_000,
+ running: true,
+ request: request({ expand: '1' }),
+ });
+ expect(turnView.expanded).toBe('1');
+ expect(turnView.nodes.map((node) => [node.path, node.kind])).toEqual([
+ ['1', 'turn'],
+ ['1.1', 'tool'],
+ ['1.2', 'tool'],
+ ['1.3', 'tool'],
+ ]);
+ expect(turnView.nodes[2]).toMatchObject({ summary: '2 turns, 2 tools', folded: true });
+ expect(turnView.active).toBe('1.2.2.1');
+
+ const leafView = renderDigest(source, {
+ now: 2_000,
+ running: true,
+ request: request({ expand: '1.2' }),
+ });
+ expect(leafView.nodes.map((node) => node.path)).toEqual(['1.2', '1.2.1', '1.2.2']);
+ expect(leafView.nodes[0].folded).toBeUndefined();
+
+ const nestedTurn = renderDigest(source, {
+ now: 2_000,
+ running: true,
+ request: request({ expand: '1.2.2' }),
+ });
+ expect(nestedTurn.nodes.map((node) => node.path)).toEqual(['1.2.2', '1.2.2.1']);
+
+ const childRange = renderDigest(source, {
+ now: 2_000,
+ running: true,
+ request: request({ expand: '1.2-3' }),
+ });
+ expect(childRange.nodes.map((node) => node.path)).toEqual(['1.2', '1.3']);
+
+ const turnRange = renderDigest(longRun(), {
+ now: 2_000,
+ running: true,
+ request: request({ expand: '3-5' }),
+ });
+ expect(turnRange.nodes.map((node) => [node.path, node.folded])).toEqual([
+ ['3', true],
+ ['4', true],
+ ['5', true],
+ ]);
+ expect(turnRange.nodes[2].errors).toBe(1);
+ });
+
+ it('explains an address that is evicted or absent', () => {
+ const source = tree([turn(tool('read_file'))]);
+ source.root.evicted = {
+ turns: 30,
+ tools: [['bash_tool', 30]],
+ otherTools: 0,
+ texts: 0,
+ errors: 0,
+ startedAt: 0,
+ endedAt: 900,
+ };
+ const evicted = renderDigest(source, {
+ now: 2_000,
+ running: false,
+ request: request({ expand: '12' }),
+ });
+ expect(evicted.nodes).toEqual([
+ expect.objectContaining({
+ path: '1-30',
+ kind: 'range',
+ evicted: true,
+ summary: 'bash_tool ×30',
+ }),
+ ]);
+ expect(evicted.note).toContain('no longer retained');
+
+ const current = renderDigest(source, {
+ now: 2_000,
+ running: false,
+ request: request({ expand: '31' }),
+ });
+ expect(current.nodes.map((node) => node.path)).toEqual(['31', '31.1']);
+
+ const missing = renderDigest(source, {
+ now: 2_000,
+ running: false,
+ request: request({ expand: '31.4' }),
+ });
+ expect(missing).toMatchObject({ nodes: [], note: 'No node at 31.4.' });
+ });
+
+ it('stays within the output budget for the largest tree the owner retains', () => {
+ const label = 'Inspecting the subagent routing transport for cross-replica claims '.repeat(3);
+ const turns = Array.from({ length: 48 }, (_, index) =>
+ turn(
+ ...Array.from({ length: 6 }, (__, child) =>
+ tool(
+ `mcp_server_tool_${child}_${'x'.repeat(40)}`,
+ index === 47 && child === 5 ? 'running' : 'ok',
+ {
+ label,
+ },
+ ),
+ ),
+ ),
+ );
+ for (const args of [{}, { since: '1.1' }, { expand: '1-48' }, { expand: '48' }]) {
+ const digest = renderDigest(tree(turns), {
+ now: 9_000,
+ running: true,
+ request: request(args),
+ });
+ expect(JSON.stringify(digest).length).toBeLessThanOrEqual(DIGEST_LIMITS.chars);
+ expect(digest.nodes.length).toBeGreaterThan(0);
+ }
+ const defaultView = renderDigest(tree(turns), { now: 9_000, running: true });
+ expect(defaultView.nodes[defaultView.nodes.length - 1]?.path).toBe('48.6');
+ const sinceView = renderDigest(tree(turns), {
+ now: 9_000,
+ running: true,
+ request: request({ since: '1.1' }),
+ });
+ expect(sinceView.nodes[0]).toMatchObject({ kind: 'range', folded: true });
+ });
+
+ it('reports a thinking child with nothing in flight', () => {
+ const digest = renderDigest(tree([turn(tool('read_file'))], { thinking: true }), {
+ now: 4_500,
+ running: true,
+ });
+ expect(digest).toMatchObject({ phase: 'thinking', idle_ms: 3_000 });
+ expect(digest.active).toBeUndefined();
+ });
+});
+
+describe('renderSummaryDigest', () => {
+ it('carries counts and only the node in flight', () => {
+ const summary = summarizeActivityTree(longRun());
+ const digest = renderSummaryDigest(summary, { now: 2_000, running: true });
+ expect(digest).toEqual({
+ turns: 21,
+ tools: 21,
+ errors: 1,
+ active: '21.2',
+ nodes: [
+ {
+ path: '21.2',
+ kind: 'tool',
+ status: 'running',
+ name: 'bash_tool',
+ label: 'Running jest for background.spec',
+ ms: 1_000,
+ },
+ ],
+ });
+ });
+});
+
+describe('parseDigestRequest', () => {
+ it('accepts paths, ranges, and cursors, and treats empty strings as unset', () => {
+ expect(request({ expand: ' 3.2 ' })).toEqual({ expand: { text: '3.2', segments: [3, 2] } });
+ expect(request({ expand: '1-14' })).toEqual({
+ expand: { text: '1-14', segments: [1], rangeEnd: 14 },
+ });
+ expect(request({ since: '7.3' })).toEqual({ since: { text: '7.3', turn: 7, child: 3 } });
+ expect(request({ since: '', expand: '' })).toEqual({});
+ });
+
+ it('rejects malformed or conflicting navigation', () => {
+ for (const args of [
+ { expand: '0' },
+ { expand: '3-1' },
+ { expand: 'abc' },
+ { expand: 4 },
+ { since: '1.2.3' },
+ { since: '0' },
+ { since: '7.0' },
+ { since: '7', expand: '3' },
+ { expand: `${'1.'.repeat(40)}1` },
+ ]) {
+ expect(parseDigestRequest(args)).toEqual({ error: expect.any(String) });
+ }
+ });
+});
diff --git a/packages/api/src/agents/digest/view.ts b/packages/api/src/agents/digest/view.ts
new file mode 100644
index 0000000000..9f939726a2
--- /dev/null
+++ b/packages/api/src/agents/digest/view.ts
@@ -0,0 +1,745 @@
+import type {
+ SubagentDigest,
+ SubagentDigestNode,
+ SubagentDigestStatus,
+} from 'librechat-data-provider';
+import type {
+ ActivityFold,
+ ActivityLeaf,
+ ActivityRun,
+ ActivityTree,
+ ActivityTurn,
+ ActivitySummary,
+} from './tree';
+import { countActivity, findActiveLeaf, foldTurns } from './tree';
+
+/**
+ * Output bounds for one digest. 4,000 characters is about a thousand tokens: enough
+ * for a folded history plus the open turn, small against the 100,000-character
+ * bound on a collected background result.
+ */
+export const DIGEST_LIMITS: Readonly<{
+ chars: number;
+ expandNodes: number;
+ argChars: number;
+}> = Object.freeze({ chars: 4_000, expandNodes: 40, argChars: 64 });
+
+/** A positional address: alternating turn and child numbers, optionally ending in a range. */
+export interface DigestPath {
+ text: string;
+ segments: number[];
+ rangeEnd?: number;
+}
+
+export interface DigestCursor {
+ text: string;
+ turn: number;
+ child?: number;
+}
+
+export interface DigestRequest {
+ expand?: DigestPath;
+ since?: DigestCursor;
+}
+
+interface RenderContext {
+ now: number;
+ labelChars: number;
+}
+
+interface Shape {
+ /** Turns before the open one that keep their own folded line. */
+ individual: number;
+ /** Aligned range lines for the turns before those. */
+ ranges: number;
+ /** Children of the open turn listed individually. */
+ window: number;
+ labelChars: number;
+ /** Nested runs opened along the active path. */
+ depth: number;
+}
+
+const DEFAULT_SHAPES: readonly Shape[] = [
+ { individual: 5, ranges: 3, window: 12, labelChars: 72, depth: 2 },
+ { individual: 3, ranges: 2, window: 8, labelChars: 48, depth: 2 },
+ { individual: 1, ranges: 2, window: 5, labelChars: 32, depth: 1 },
+ { individual: 0, ranges: 1, window: 3, labelChars: 0, depth: 0 },
+];
+
+const EXPAND_LABEL_CHARS: readonly number[] = [120, 48, 0];
+const CHUNK_SIZES: readonly number[] = [5, 10, 25, 50, 100, 250, 500, 1_000, 10_000];
+const PATH_PATTERN = /^(\d{1,6}(?:\.\d{1,6}){0,7})(?:-(\d{1,6}))?$/;
+const CURSOR_PATTERN = /^(\d{1,6})(?:\.(\d{1,6}))?$/;
+
+const positive = (value: number): boolean => Number.isSafeInteger(value) && value > 0;
+
+/** Form writers and some providers send `""` for an unset optional argument. */
+function presentArg(value: unknown): unknown {
+ if (value == null) {
+ return undefined;
+ }
+ if (typeof value !== 'string') {
+ return value;
+ }
+ const trimmed = value.trim();
+ return trimmed === '' ? undefined : trimmed;
+}
+
+/**
+ * Reads the optional navigation arguments. Both are positional addresses taken from
+ * an earlier digest, so a malformed one is reported rather than guessed at.
+ */
+export function parseDigestRequest(
+ args: Record<string, unknown>,
+): { request: DigestRequest } | { error: string } {
+ const expand = presentArg(args.expand);
+ const since = presentArg(args.since);
+ if (expand != null && since != null) {
+ return { error: 'Pass either expand or since, not both.' };
+ }
+ if (expand != null) {
+ const match = typeof expand === 'string' ? PATH_PATTERN.exec(expand) : null;
+ const segments = match?.[1].split('.').map(Number) ?? [];
+ const rangeEnd = match?.[2] == null ? undefined : Number(match[2]);
+ if (
+ typeof expand !== 'string' ||
+ match == null ||
+ !segments.every(positive) ||
+ (rangeEnd != null && rangeEnd < segments[segments.length - 1])
+ ) {
+ return {
+ error: 'expand must be a node path from activity.nodes, such as "3", "3.2", or "1-14".',
+ };
+ }
+ return { request: { expand: { text: expand, segments, rangeEnd } } };
+ }
+ if (since != null) {
+ const match = typeof since === 'string' ? CURSOR_PATTERN.exec(since) : null;
+ const zero =
+ match != null && (Number(match[1]) === 0 || (match[2] != null && Number(match[2]) === 0));
+ if (typeof since !== 'string' || match == null || zero) {
+ return { error: 'since must be an activity.cursor value, such as "7" or "7.3".' };
+ }
+ return {
+ request: {
+ since: {
+ text: since,
+ turn: Number(match[1]),
+ ...(match[2] == null ? {} : { child: Number(match[2]) }),
+ },
+ },
+ };
+ }
+ return { request: {} };
+}
+
+const leafEnd = (leaf: ActivityLeaf, now: number): number =>
+ leaf.endedAt ?? (leaf.status === 'running' ? now : leaf.startedAt);
+
+const span = (start: number, end: number): number => Math.max(0, Math.round(end - start));
+
+function clipLabel(label: string | undefined, maxChars: number): string | undefined {
+ if (label == null || maxChars <= 0) {
+ return undefined;
+ }
+ return label.length <= maxChars ? label : `${label.slice(0, maxChars - 1)}…`;
+}
+
+const plural = (total: number, noun: string): string => `${total} ${noun}${total === 1 ? '' : 's'}`;
+
+function formatCounts(entries: ReadonlyArray<[string, number]>, other: number): string {
+ const shown = entries
+ .slice(0, 4)
+ .map(([name, total]) => (total > 1 ? `${name} ×${total}` : name));
+ const hidden = other + entries.slice(4).reduce((total, [, value]) => total + value, 0);
+ return hidden > 0 ? `${shown.join(', ')} +${hidden} more` : shown.join(', ');
+}
+
+function leafCounts(leaves: readonly ActivityLeaf[]): Array<[string, number]> {
+ const counts = new Map<string, number>();
+ for (const leaf of leaves) {
+ const name = leaf.kind === 'text' ? 'text' : (leaf.name ?? 'tool');
+ counts.set(name, (counts.get(name) ?? 0) + 1);
+ }
+ return [...counts.entries()].sort((left, right) => right[1] - left[1]);
+}
+
+function foldSummary(fold: ActivityFold): string {
+ const entries: Array<[string, number]> = [...fold.tools];
+ if (fold.texts > 0) {
+ entries.push(['text', fold.texts]);
+ }
+ entries.sort((left, right) => right[1] - left[1]);
+ return formatCounts(entries, fold.otherTools);
+}
+
+function aggregateStatus(leaves: readonly ActivityLeaf[]): SubagentDigestStatus {
+ let status: SubagentDigestStatus = 'ok';
+ for (const leaf of leaves) {
+ if (leaf.status === 'running') {
+ return 'running';
+ }
+ if (leaf.status === 'error') {
+ status = 'error';
+ } else if (leaf.status === 'cancelled' && status === 'ok') {
+ status = 'cancelled';
+ }
+ }
+ return status;
+}
+
+const errorCount = (leaves: readonly ActivityLeaf[]): number =>
+ leaves.reduce((total, leaf) => total + (leaf.status === 'error' ? 1 : 0), 0);
+
+function leafNode(
+ leaf: ActivityLeaf,
+ path: string,
+ context: RenderContext,
+ folded: boolean,
+): SubagentDigestNode {
+ const label = clipLabel(leaf.label, context.labelChars);
+ const nested = leaf.run == null ? undefined : countActivity(leaf.run);
+ return {
+ path,
+ kind: leaf.kind,
+ status: leaf.status,
+ ...(leaf.kind === 'tool' && leaf.name != null ? { name: leaf.name } : {}),
+ ...(label == null ? {} : { label }),
+ ms: span(leaf.startedAt, leafEnd(leaf, context.now)),
+ ...(leaf.chars == null || leaf.chars === 0 ? {} : { chars: leaf.chars }),
+ ...(nested == null
+ ? {}
+ : {
+ summary: `${plural(nested.turns, 'turn')}, ${plural(nested.tools, 'tool')}`,
+ ...(nested.errors > 0 ? { errors: nested.errors } : {}),
+ ...(folded ? { folded: true as const } : {}),
+ }),
+ };
+}
+
+function turnNode(
+ turn: ActivityTurn,
+ path: string,
+ context: RenderContext,
+ folded: boolean,
+): SubagentDigestNode {
+ const end = turn.children.reduce(
+ (latest, leaf) => Math.max(latest, leafEnd(leaf, context.now)),
+ turn.startedAt,
+ );
+ const errors = errorCount(turn.children);
+ return {
+ path,
+ kind: 'turn',
+ status: aggregateStatus(turn.children),
+ ms: span(turn.startedAt, end),
+ ...(folded
+ ? { summary: formatCounts(leafCounts(turn.children), turn.overflow ?? 0), folded: true }
+ : {}),
+ ...(errors > 0 ? { errors } : {}),
+ };
+}
+
+function foldNode(fold: ActivityFold, path: string, evicted: boolean): SubagentDigestNode {
+ return {
+ path,
+ kind: 'range',
+ status: fold.errors > 0 ? 'error' : 'ok',
+ ms: span(fold.startedAt, fold.endedAt),
+ summary: foldSummary(fold),
+ ...(fold.errors > 0 ? { errors: fold.errors } : {}),
+ folded: true,
+ ...(evicted ? { evicted: true as const } : {}),
+ };
+}
+
+function turnRangeNode(
+ turns: readonly ActivityTurn[],
+ path: string,
+ context: RenderContext,
+): SubagentDigestNode {
+ const leaves = turns.flatMap((turn) => turn.children);
+ const status = aggregateStatus(leaves);
+ const fold = foldTurns(turns);
+ return {
+ ...foldNode(fold, path, false),
+ status,
+ ms: span(
+ fold.startedAt,
+ leaves.reduce((latest, leaf) => Math.max(latest, leafEnd(leaf, context.now)), fold.endedAt),
+ ),
+ };
+}
+
+function childRangeNode(
+ leaves: readonly ActivityLeaf[],
+ path: string,
+ context: RenderContext,
+): SubagentDigestNode {
+ const start = leaves.reduce((first, leaf) => Math.min(first, leaf.startedAt), Infinity);
+ const end = leaves.reduce((last, leaf) => Math.max(last, leafEnd(leaf, context.now)), 0);
+ const errors = errorCount(leaves);
+ return {
+ path,
+ kind: 'range',
+ status: aggregateStatus(leaves),
+ ms: Number.isFinite(start) ? span(start, end) : 0,
+ summary: formatCounts(leafCounts(leaves), 0),
+ ...(errors > 0 ? { errors } : {}),
+ folded: true,
+ };
+}
+
+/** Splits turn numbers into ranges aligned to round sizes, so they read stably across polls. */
+function alignedChunks(first: number, last: number, maxChunks: number): Array<[number, number]> {
+ if (last < first) {
+ return [];
+ }
+ for (const size of CHUNK_SIZES) {
+ const chunks: Array<[number, number]> = [];
+ let start = first;
+ while (start <= last) {
+ const end = Math.min(last, (Math.floor((start - 1) / size) + 1) * size);
+ chunks.push([start, end]);
+ start = end + 1;
+ }
+ if (chunks.length <= Math.max(1, maxChunks)) {
+ return chunks;
+ }
+ }
+ return [[first, last]];
+}
+
+function rangeNodes(
+ run: ActivityRun,
+ fromIndex: number,
+ toIndex: number,
+ prefix: string,
+ context: RenderContext,
+ maxChunks: number,
+): SubagentDigestNode[] {
+ const base = run.evicted?.turns ?? 0;
+ return alignedChunks(base + fromIndex + 1, base + toIndex, maxChunks).map(([start, end]) => {
+ const turns = run.turns.slice(start - base - 1, end - base);
+ if (start === end) {
+ return turnNode(turns[0], `${prefix}${start}`, context, true);
+ }
+ return turnRangeNode(turns, `${prefix}${start}-${end}`, context);
+ });
+}
+
+function openTurnNodes(
+ turn: ActivityTurn,
+ path: string,
+ context: RenderContext,
+ shape: Shape,
+ firstChild = 0,
+): SubagentDigestNode[] {
+ const nodes = [turnNode(turn, path, context, false)];
+ const children = turn.children;
+ const start = Math.max(firstChild, children.length - shape.window);
+ if (start > firstChild) {
+ nodes.push(
+ childRangeNode(
+ children.slice(firstChild, start),
+ `${path}.${firstChild + 1}-${start}`,
+ context,
+ ),
+ );
+ }
+ for (let index = start; index < children.length; index++) {
+ const leaf = children[index];
+ const childPath = `${path}.${index + 1}`;
+ const onPath =
+ leaf.run != null &&
+ shape.depth > 0 &&
+ (leaf.status === 'running' || index === children.length - 1);
+ nodes.push(leafNode(leaf, childPath, context, leaf.run != null && !onPath));
+ if (onPath && leaf.run != null) {
+ nodes.push(
+ ...runNodes(leaf.run, `${childPath}.`, context, {
+ ...shape,
+ individual: Math.min(shape.individual, 2),
+ ranges: 1,
+ window: Math.min(shape.window, 6),
+ depth: shape.depth - 1,
+ }),
+ );
+ }
+ }
+ return nodes;
+}
+
+/** Folded history plus the newest turn opened, recursing along the active path. */
+function runNodes(
+ run: ActivityRun,
+ prefix: string,
+ context: RenderContext,
+ shape: Shape,
+): SubagentDigestNode[] {
+ const base = run.evicted?.turns ?? 0;
+ const nodes: SubagentDigestNode[] = [];
+ if (run.evicted != null) {
+ nodes.push(foldNode(run.evicted, `${prefix}1-${base}`, true));
+ }
+ const last = run.turns.length - 1;
+ if (last < 0) {
+ return nodes;
+ }
+ const firstIndividual = Math.max(0, last - shape.individual);
+ nodes.push(...rangeNodes(run, 0, firstIndividual, prefix, context, shape.ranges));
+ for (let index = firstIndividual; index < last; index++) {
+ nodes.push(turnNode(run.turns[index], `${prefix}${base + index + 1}`, context, true));
+ }
+ nodes.push(...openTurnNodes(run.turns[last], `${prefix}${base + last + 1}`, context, shape));
+ return nodes;
+}
+
+function sinceNodes(
+ run: ActivityRun,
+ since: DigestCursor,
+ context: RenderContext,
+ shape: Shape,
+): SubagentDigestNode[] {
+ const base = run.evicted?.turns ?? 0;
+ const nodes: SubagentDigestNode[] = [];
+ if (run.evicted != null && since.turn < base) {
+ nodes.push(foldNode(run.evicted, `1-${base}`, true));
+ }
+ const groups: Array<{ index: number; firstChild: number }> = [];
+ for (let index = 0; index < run.turns.length; index++) {
+ const number = base + index + 1;
+ if (number < since.turn || (number === since.turn && since.child == null)) {
+ continue;
+ }
+ const firstChild = number === since.turn ? (since.child ?? 0) : 0;
+ if (firstChild < run.turns[index].children.length) {
+ groups.push({ index, firstChild });
+ }
+ }
+ const detailed = groups.slice(-(shape.individual + 1));
+ const folded = groups.slice(0, groups.length - detailed.length);
+ if (folded.length > 0) {
+ /** New turns are consecutive, so older ones fold into aligned ranges. */
+ nodes.push(
+ ...rangeNodes(
+ run,
+ folded[0].index,
+ folded[folded.length - 1].index + 1,
+ '',
+ context,
+ shape.ranges,
+ ),
+ );
+ }
+ for (const group of detailed) {
+ nodes.push(
+ ...openTurnNodes(
+ run.turns[group.index],
+ `${base + group.index + 1}`,
+ context,
+ shape,
+ group.firstChild,
+ ),
+ );
+ }
+ return nodes;
+}
+
+function runHeaderNodes(
+ run: ActivityRun,
+ prefix: string,
+ context: RenderContext,
+): SubagentDigestNode[] {
+ const base = run.evicted?.turns ?? 0;
+ const nodes: SubagentDigestNode[] =
+ run.evicted == null ? [] : [foldNode(run.evicted, `${prefix}1-${base}`, true)];
+ if (run.turns.length <= DIGEST_LIMITS.expandNodes) {
+ run.turns.forEach((turn, index) => {
+ nodes.push(turnNode(turn, `${prefix}${base + index + 1}`, context, true));
+ });
+ return nodes;
+ }
+ return [...nodes, ...rangeNodes(run, 0, run.turns.length, prefix, context, 20)];
+}
+
+function turnRange(
+ run: ActivityRun,
+ prefix: string,
+ first: number,
+ last: number,
+ context: RenderContext,
+): SubagentDigestNode[] {
+ const base = run.evicted?.turns ?? 0;
+ const nodes: SubagentDigestNode[] = [];
+ if (run.evicted != null && first <= base) {
+ nodes.push(foldNode(run.evicted, `${prefix}1-${base}`, true));
+ }
+ const fromIndex = Math.max(first, base + 1) - base - 1;
+ const toIndex = Math.min(last - base, run.turns.length);
+ if (toIndex <= fromIndex) {
+ return nodes;
+ }
+ if (toIndex - fromIndex <= DIGEST_LIMITS.expandNodes) {
+ for (let index = fromIndex; index < toIndex; index++) {
+ nodes.push(turnNode(run.turns[index], `${prefix}${base + index + 1}`, context, true));
+ }
+ return nodes;
+ }
+ return [...nodes, ...rangeNodes(run, fromIndex, toIndex, prefix, context, 20)];
+}
+
+function childNodes(
+ turn: ActivityTurn,
+ path: string,
+ first: number,
+ last: number,
+ context: RenderContext,
+): SubagentDigestNode[] {
+ const leaves = turn.children.slice(first - 1, last);
+ if (leaves.length > DIGEST_LIMITS.expandNodes) {
+ const shown = leaves.slice(-DIGEST_LIMITS.expandNodes);
+ const hiddenEnd = first - 1 + leaves.length - shown.length;
+ return [
+ childRangeNode(
+ leaves.slice(0, leaves.length - shown.length),
+ `${path}.${first}-${hiddenEnd}`,
+ context,
+ ),
+ ...shown.map((leaf, index) =>
+ leafNode(leaf, `${path}.${hiddenEnd + index + 1}`, context, leaf.run != null),
+ ),
+ ];
+ }
+ return leaves.map((leaf, index) =>
+ leafNode(leaf, `${path}.${first + index}`, context, leaf.run != null),
+ );
+}
+
+/**
+ * Resolves one address and returns that node with its direct children folded.
+ * Turn numbers sit at even positions and child numbers at odd ones, so `3.2.1` is
+ * the first turn of the run started by turn 3's second child.
+ */
+function expandNodes(
+ tree: ActivityTree,
+ target: DigestPath,
+ context: RenderContext,
+): { nodes: SubagentDigestNode[]; note?: string } {
+ let run = tree.root;
+ let prefix = '';
+ let turn: ActivityTurn | undefined;
+ let turnPath = '';
+ const notFound = { nodes: [], note: `No node at ${target.text}.` };
+ for (let position = 0; position < target.segments.length; position++) {
+ const value = target.segments[position];
+ const last = position === target.segments.length - 1;
+ if (position % 2 === 0) {
+ const base = run.evicted?.turns ?? 0;
+ if (last && target.rangeEnd != null) {
+ const nodes = turnRange(run, prefix, value, target.rangeEnd, context);
+ return nodes.length === 0 ? notFound : { nodes };
+ }
+ if (value <= base && run.evicted != null) {
+ return {
+ nodes: [foldNode(run.evicted, `${prefix}1-${base}`, true)],
+ note: `Turn ${prefix}${value} is summarized only; its detail is no longer retained.`,
+ };
+ }
+ turn = run.turns[value - base - 1];
+ if (turn == null) {
+ return notFound;
+ }
+ turnPath = `${prefix}${value}`;
+ if (last) {
+ return {
+ nodes: [
+ turnNode(turn, turnPath, context, false),
+ ...childNodes(turn, turnPath, 1, turn.children.length, context),
+ ],
+ };
+ }
+ continue;
+ }
+ if (turn == null) {
+ return notFound;
+ }
+ if (last && target.rangeEnd != null) {
+ const nodes = childNodes(turn, turnPath, value, target.rangeEnd, context);
+ return nodes.length === 0 ? notFound : { nodes };
+ }
+ const leaf = turn.children[value - 1];
+ if (leaf == null) {
+ return notFound;
+ }
+ const leafPath = `${turnPath}.${value}`;
+ if (last) {
+ return {
+ nodes: [
+ leafNode(leaf, leafPath, context, false),
+ ...(leaf.run == null ? [] : runHeaderNodes(leaf.run, `${leafPath}.`, context)),
+ ],
+ };
+ }
+ if (leaf.run == null) {
+ return notFound;
+ }
+ run = leaf.run;
+ prefix = `${leafPath}.`;
+ }
+ return notFound;
+}
+
+/** The last root-level node such that it and every node before it have settled. */
+function settledCursor(run: ActivityRun): string | undefined {
+ const base = run.evicted?.turns ?? 0;
+ let cursor: string | undefined = base > 0 ? `${base}` : undefined;
+ for (let index = 0; index < run.turns.length; index++) {
+ const children = run.turns[index].children;
+ for (let child = 0; child < children.length; child++) {
+ if (children[child].status === 'running') {
+ return cursor;
+ }
+ cursor = `${base + index + 1}.${child + 1}`;
+ }
+ }
+ return cursor;
+}
+
+function headline(
+ run: ActivityRun,
+ state: { updatedAt: number; thinking?: boolean; activePath?: string },
+ context: RenderContext,
+ running: boolean,
+): Omit<SubagentDigest, 'nodes'> {
+ const totals = countActivity(run);
+ const idle = running && state.activePath == null;
+ return {
+ ...totals,
+ ...(state.activePath == null ? {} : { active: state.activePath }),
+ ...(idle && state.thinking === true ? { phase: 'thinking' as const } : {}),
+ ...(idle ? { idle_ms: span(state.updatedAt, context.now) } : {}),
+ };
+}
+
+const fits = (digest: SubagentDigest): boolean =>
+ JSON.stringify(digest).length <= DIGEST_LIMITS.chars;
+
+/** Drops the oldest nodes until the digest fits; the newest carry the active path. */
+function clamp(digest: SubagentDigest): SubagentDigest {
+ const nodes = [...digest.nodes];
+ let clamped: SubagentDigest = { ...digest, nodes, truncated: true };
+ while (nodes.length > 0 && !fits(clamped)) {
+ nodes.shift();
+ clamped = { ...digest, nodes: [...nodes], truncated: true };
+ }
+ return clamped;
+}
+
+function rebuiltDescription(rebuilt: { partial: boolean }): string {
+ const base =
+ 'Rebuilt from the saved activity summary after the process that ran this subagent ended; paths from earlier checks may not match.';
+ return rebuilt.partial ? `${base} The summary kept only the newest activity.` : base;
+}
+
+function joinNotes(...notes: Array<string | undefined>): string | undefined {
+ const present = notes.filter((note): note is string => note != null);
+ return present.length === 0 ? undefined : present.join(' ');
+}
+
+/**
+ * Renders a navigable digest of one task's progress tree. With no request it
+ * returns the folded history and the open turn along the active path; `since`
+ * returns only nodes after a cursor; `expand` returns one node and its direct
+ * children. Every form is bounded by {@link DIGEST_LIMITS.chars}.
+ */
+export function renderDigest(
+ tree: ActivityTree,
+ options: { now: number; running: boolean; request?: DigestRequest },
+): SubagentDigest {
+ const { now, running, request } = options;
+ const active = findActiveLeaf(tree.root);
+ const cursor = settledCursor(tree.root);
+ const head = headline(
+ tree.root,
+ { updatedAt: tree.updatedAt, thinking: tree.thinking, activePath: active?.path },
+ { now, labelChars: 0 },
+ running,
+ );
+ const withCursor = {
+ ...head,
+ ...(cursor == null ? {} : { cursor }),
+ ...(tree.rebuilt?.partial === true ? { truncated: true as const } : {}),
+ };
+ const rebuiltNote = tree.rebuilt == null ? undefined : rebuiltDescription(tree.rebuilt);
+
+ if (request?.expand != null) {
+ const expand = request.expand;
+ let digest: SubagentDigest = { ...withCursor, nodes: [], expanded: expand.text };
+ for (const labelChars of EXPAND_LABEL_CHARS) {
+ const { nodes, note } = expandNodes(tree, expand, { now, labelChars });
+ const combined = joinNotes(rebuiltNote, note);
+ digest = {
+ ...withCursor,
+ expanded: expand.text,
+ nodes,
+ ...(combined == null ? {} : { note: combined }),
+ };
+ if (fits(digest)) {
+ return digest;
+ }
+ }
+ return clamp(digest);
+ }
+
+ const since = request?.since;
+ let digest: SubagentDigest = { ...withCursor, nodes: [] };
+ for (const [index, shape] of DEFAULT_SHAPES.entries()) {
+ const context = { now, labelChars: shape.labelChars };
+ const nodes =
+ since == null
+ ? runNodes(tree.root, '', context, shape)
+ : sinceNodes(tree.root, since, context, shape);
+ digest = {
+ ...withCursor,
+ ...(since == null ? {} : { since: since.text }),
+ nodes,
+ ...(index > 0 ? { truncated: true as const } : {}),
+ };
+ const note = joinNotes(
+ rebuiltNote,
+ since != null && nodes.length === 0 ? `No new activity since ${since.text}.` : undefined,
+ );
+ if (note != null) {
+ digest.note = note;
+ }
+ if (fits(digest)) {
+ return digest;
+ }
+ }
+ return clamp(digest);
+}
+
+/** The list-path digest: counts plus the node in flight, never history. */
+export function renderSummaryDigest(
+ summary: ActivitySummary,
+ options: { now: number; running: boolean },
+): SubagentDigest {
+ const context = { now: options.now, labelChars: 72 };
+ return {
+ turns: summary.turns,
+ tools: summary.tools,
+ errors: summary.errors,
+ ...(summary.active == null ? {} : { active: summary.active.path }),
+ ...(options.running && summary.active == null && summary.thinking === true
+ ? { phase: 'thinking' as const }
+ : {}),
+ ...(options.running && summary.active == null
+ ? { idle_ms: span(summary.updatedAt, options.now) }
+ : {}),
+ nodes:
+ summary.active == null
+ ? []
+ : [leafNode(summary.active.leaf, summary.active.path, context, false)],
+ };
+}
diff --git a/packages/api/src/agents/subagentCrossReplica.integration.spec.ts b/packages/api/src/agents/subagentCrossReplica.integration.spec.ts
index fda20c2d99..d05578ef64 100644
--- a/packages/api/src/agents/subagentCrossReplica.integration.spec.ts
+++ b/packages/api/src/agents/subagentCrossReplica.integration.spec.ts
@@ -22,6 +22,7 @@ import {
SubagentTaskOwnerUnavailableError,
} from './subagentTaskRouting';
import { buildSubagentThreadTaskConfig, SubagentThreadTaskStore } from './subagentThreads';
+import { snapshotActivity, snapshotActivitySummary } from './digest';
import { __resetShutdownStateForTests } from '../app/shutdown';
import { createAgentTriggerService } from './triggers/service';
import { SubagentActivityStream } from './subagentActivity';
@@ -434,4 +435,88 @@ describeWithRedis('subagent cross-replica orchestration', () => {
await requesterStore.destroyTaskControlTransport();
});
+
+ it('serves a running child progress tree to a poll on another replica over Redis', async () => {
+ const userId = new mongoose.Types.ObjectId().toString();
+ const tenantId = 'tenant-progress';
+ const parentConversationId = randomUUID();
+ await saveParent(userId, tenantId, parentConversationId);
+ const ownerStore = new SubagentThreadTaskStore(methods);
+ const requesterStore = new SubagentThreadTaskStore(methods);
+ taskStores.push(ownerStore, requesterStore);
+ const namespace = `subagent-progress-${randomUUID()}`;
+ await ownerStore.configureTaskControlTransport(
+ await createRoutingTransport('progress-owner', namespace),
+ );
+ await requesterStore.configureTaskControlTransport(
+ await createRoutingTransport('progress-requester', namespace),
+ );
+ const config = buildSubagentThreadTaskConfig(ownerStore, {
+ userId,
+ tenantId,
+ parentConversationId,
+ });
+ let finish = (_value: { content: string }): void => undefined;
+ let reported = false;
+ const started = accepted(
+ config.store.start(
+ taskRequest(config.scopeId, 'review the change', 'reviewer', async (runtime) => {
+ const base = {
+ runId: 'root-run',
+ subagentRunId: runtime.taskId,
+ subagentType: 'reviewer',
+ subagentAgentId: 'agent-reviewer',
+ timestamp: new Date().toISOString(),
+ };
+ runtime.reportProgress({
+ ...base,
+ phase: 'run_step',
+ data: {
+ id: 'step-1',
+ stepDetails: {
+ type: 'tool_calls',
+ tool_calls: [
+ {
+ id: 'call-1',
+ name: 'bash_tool',
+ args: { intent: 'Running the suite', env: 'KEY=1' },
+ },
+ ],
+ },
+ },
+ });
+ reported = true;
+ return new Promise<{ content: string }>((resolve) => (finish = resolve));
+ }),
+ ),
+ );
+ await waitUntil(() => (reported ? true : undefined));
+
+ const routed = await waitUntil(async () => {
+ const claim = await requesterStore.claimTask(config.scopeId, started.task.taskId);
+ return claim.status === 'running' && snapshotActivity(claim.task) != null ? claim : undefined;
+ });
+ const tree = routed.status === 'running' ? snapshotActivity(routed.task) : undefined;
+ expect(tree?.root.turns[0].children[0]).toMatchObject({
+ kind: 'tool',
+ name: 'bash_tool',
+ label: 'Running the suite',
+ status: 'running',
+ });
+ expect(JSON.stringify(tree)).not.toContain('KEY=1');
+ const [listed] = await requesterStore.listTasks(config.scopeId);
+ expect(snapshotActivitySummary(listed)).toMatchObject({ turns: 1, tools: 1 });
+
+ const otherTenant = buildSubagentThreadTaskConfig(requesterStore, {
+ userId,
+ tenantId: 'tenant-other',
+ parentConversationId,
+ });
+ await expect(
+ requesterStore.claimTask(otherTenant.scopeId, started.task.taskId),
+ ).resolves.toEqual({ status: 'not_found' });
+
+ finish({ content: 'Review complete.' });
+ await requesterStore.destroyTaskControlTransport();
+ });
});
diff --git a/packages/api/src/agents/subagentDelivery.ts b/packages/api/src/agents/subagentDelivery.ts
index 568a360d6a..7dae16f9f4 100644
--- a/packages/api/src/agents/subagentDelivery.ts
+++ b/packages/api/src/agents/subagentDelivery.ts
@@ -13,6 +13,13 @@ export interface HostSubagentTaskConfig extends SubagentTaskConfig {
export const SUBAGENT_WAKEUP_GUIDANCE =
'Automatic completion delivery is enabled for this subagent task. Continue independent work if available; otherwise end this turn and the host will resume you when the task finishes. Do not repeatedly poll an unchanged running task. Use check_background_task only for explicit status or control, or as a fallback if automatic delivery is unavailable.';
+/** Single-task poll guidance, secondary to the activity digest it accompanies. */
+export const SUBAGENT_POLL_WAKEUP_GUIDANCE =
+ 'This subagent resumes you automatically when it finishes, so there is no need to check again. If you do, wait next_check_s and pass since: activity.cursor.';
+
+export const SUBAGENT_POLL_GUIDANCE =
+ 'Results are not pushed for this subagent. Check again after next_check_s, passing since: activity.cursor to get only new activity.';
+
/** Automatic conversational completion is default-on and has one administrator opt-out. */
export function backgroundCompletionWakeupsEnabled(config: TAgentsEndpoint | undefined): boolean {
return config?.backgroundTasks?.completionWakeups !== false;
diff --git a/packages/api/src/agents/subagentTaskRouting.ts b/packages/api/src/agents/subagentTaskRouting.ts
index e1147db53a..3078eeaa98 100644
--- a/packages/api/src/agents/subagentTaskRouting.ts
+++ b/packages/api/src/agents/subagentTaskRouting.ts
@@ -7,6 +7,8 @@ import type {
SubagentTaskSnapshot,
} from '@librechat/agents';
import type { Cluster, Redis } from 'ioredis';
+import type { ActivitySnapshot } from './digest';
+import { snapshotActivity, snapshotActivitySummary } from './digest';
import { createConcurrencyLimiter } from '~/utils/promise';
const PROTOCOL_VERSION = 1;
@@ -258,8 +260,13 @@ function truncateMiddle(value: string, maxChars: number): string {
return `${value.slice(0, head)}${marker}${value.slice(value.length - (available - head))}`;
}
-function boundedSnapshot(snapshot: SubagentTaskSnapshot): SubagentTaskSnapshot {
+/** Progress decorations are re-validated on every hop, so a peer cannot widen them. */
+function boundedSnapshot(snapshot: SubagentTaskSnapshot): ActivitySnapshot {
+ const activity = snapshotActivity(snapshot);
+ const activitySummary = snapshotActivitySummary(snapshot);
return {
+ ...(activity == null ? {} : { activity }),
+ ...(activitySummary == null ? {} : { activitySummary }),
taskId: truncateMiddle(snapshot.taskId, MAX_TASK_ID_CHARS),
...(snapshot.threadId == null
? {}
diff --git a/packages/api/src/agents/subagentThreads.spec.ts b/packages/api/src/agents/subagentThreads.spec.ts
index df315f415f..114ef2aa61 100644
--- a/packages/api/src/agents/subagentThreads.spec.ts
+++ b/packages/api/src/agents/subagentThreads.spec.ts
@@ -2,7 +2,7 @@ import mongoose from 'mongoose';
import { randomUUID } from 'node:crypto';
import { MongoMemoryServer } from 'mongodb-memory-server';
import { Constants, EModelEndpoint } from 'librechat-data-provider';
-import { AIMessage, HumanMessage } from '@librechat/agents/langchain/messages';
+import { AIMessage, HumanMessage, ToolMessage } from '@librechat/agents/langchain/messages';
import {
createMethods,
createModels,
@@ -37,9 +37,11 @@ import {
SubagentThreadTaskStore,
} from './subagentThreads';
import { controlFingerprint, SubagentTaskOwnerUnavailableError } from './subagentTaskRouting';
+import { snapshotActivity, snapshotActivitySummary } from './digest';
import { SUBAGENT_COMPLETION_DELIVERY } from './subagentDelivery';
import { createSubagentAttemptKey } from './subagentThreadIds';
import { SubagentActivityStream } from './subagentActivity';
+import { runCheckBackgroundTask } from './background';
import { InMemoryEventTransport } from '~/stream';
import { createSubagentUsageSink } from './usage';
@@ -4916,3 +4918,189 @@ describe('SubagentThreadTaskStore', () => {
expect(await methods.getConvo(userId, requireThreadId(started))).toBeNull();
});
});
+
+describe('subagent progress trees', () => {
+ const progress = (phase: SubagentUpdateEvent['phase'], data: unknown): SubagentUpdateEvent => ({
+ runId: 'root-run',
+ parentRunId: 'parent-run',
+ subagentRunId: 'child-run',
+ subagentType: 'researcher-agent',
+ subagentKind: 'agent',
+ subagentAgentId: 'agent-1',
+ parentToolCallId: 'tool-call',
+ phase,
+ data,
+ timestamp: new Date().toISOString(),
+ });
+
+ const reportSteps = (runtime: SubagentTaskRuntime): void => {
+ runtime.reportProgress(
+ progress('run_step', {
+ id: 'step-1',
+ stepDetails: {
+ type: 'tool_calls',
+ tool_calls: [
+ {
+ id: 'call-1',
+ name: 'read_file',
+ args: { intent: 'Reading the notes', path: '/srv/.env' },
+ },
+ ],
+ },
+ }),
+ );
+ runtime.reportProgress(
+ progress('run_step_completed', {
+ result: {
+ type: 'tool_call',
+ tool_call: { id: 'call-1', name: 'read_file', output: 'SECRET=1' },
+ },
+ }),
+ );
+ runtime.reportProgress(
+ progress('run_step', {
+ id: 'step-2',
+ stepDetails: {
+ type: 'tool_calls',
+ tool_calls: [{ id: 'call-2', name: 'bash_tool', args: { intent: 'Running the tests' } }],
+ },
+ }),
+ );
+ };
+
+ it('serves a running child progress to local and routed polls, scoped to its parent', async () => {
+ const userId = 'progress-user';
+ const parentConversationId = randomUUID();
+ await saveParent(userId, parentConversationId);
+ const hub = new TestTaskRoutingHub();
+ const ownerStore = new SubagentThreadTaskStore(methods);
+ const requesterStore = new SubagentThreadTaskStore(methods);
+ await ownerStore.configureTaskControlTransport(new TestTaskControlTransport(hub));
+ await requesterStore.configureTaskControlTransport(new TestTaskControlTransport(hub));
+ const config = buildSubagentThreadTaskConfig(ownerStore, { userId, parentConversationId });
+ let finish = (_value: { content: string }): void => undefined;
+ const result = new Promise<{ content: string }>((resolve) => (finish = resolve));
+ let reported = false;
+ const started = ownerStore.start(
+ taskRequest(config.scopeId, {
+ run: async (runtime) => {
+ reportSteps(runtime);
+ reported = true;
+ return result;
+ },
+ }),
+ );
+ const taskId = requireAccepted(started).task.taskId;
+ await waitUntil(() => reported, 'the child to report progress');
+
+ const local = await ownerStore.claimTask(config.scopeId, taskId);
+ const localTree = local.status === 'running' ? snapshotActivity(local.task) : undefined;
+ expect(localTree?.root.turns.map((turn) => turn.children.map((leaf) => leaf.name))).toEqual([
+ ['read_file'],
+ ['bash_tool'],
+ ]);
+ expect(JSON.stringify(localTree)).not.toContain('SECRET');
+ expect(JSON.stringify(localTree)).not.toContain('.env');
+
+ const routed = await requesterStore.claimTask(config.scopeId, taskId);
+ expect(routed.status === 'running' ? snapshotActivity(routed.task) : undefined).toEqual(
+ localTree,
+ );
+ const [listed] = await requesterStore.listTasks(config.scopeId);
+ expect(snapshotActivitySummary(listed)).toMatchObject({
+ turns: 2,
+ tools: 2,
+ active: { path: '2.1', leaf: { name: 'bash_tool', label: 'Running the tests' } },
+ });
+
+ const polled = JSON.parse(
+ await runCheckBackgroundTask({
+ userId,
+ conversationId: parentConversationId,
+ agentId: 'agent_parent',
+ args: { background_task_id: taskId },
+ subagentTasks: buildSubagentThreadTaskConfig(requesterStore, {
+ userId,
+ parentConversationId,
+ }),
+ }),
+ );
+ expect(polled.activity).toMatchObject({ turns: 2, tools: 2, active: '2.1', cursor: '1.1' });
+
+ const otherParent = randomUUID();
+ await saveParent(userId, otherParent);
+ for (const scope of [
+ buildSubagentThreadTaskConfig(requesterStore, { userId: 'intruder', parentConversationId }),
+ buildSubagentThreadTaskConfig(requesterStore, { userId, parentConversationId: otherParent }),
+ ]) {
+ await expect(requesterStore.claimTask(scope.scopeId, taskId)).resolves.toEqual({
+ status: 'not_found',
+ });
+ await expect(requesterStore.listTasks(scope.scopeId)).resolves.toEqual([]);
+ }
+
+ finish({ content: 'Finished research.' });
+ await waitForSettled(ownerStore, config.scopeId, started);
+ const collected = await requesterStore.claimTask(config.scopeId, taskId, 'poll-1');
+ expect(collected).toMatchObject({ status: 'completed', result: 'Finished research.' });
+ const settledTree =
+ collected.status === 'completed' ? snapshotActivity(collected.task) : undefined;
+ expect(settledTree?.root.turns[1].children[0].status).toBe('ok');
+ await Promise.all([
+ ownerStore.destroyTaskControlTransport(),
+ requesterStore.destroyTaskControlTransport(),
+ ]);
+ });
+
+ it('rebuilds a finished child progress from its durable projection once the owner is gone', async () => {
+ const userId = 'durable-progress-user';
+ const parentConversationId = randomUUID();
+ await saveParent(userId, parentConversationId);
+ const ownerStore = new SubagentThreadTaskStore(methods);
+ const config = buildSubagentThreadTaskConfig(ownerStore, { userId, parentConversationId });
+ const input = 'Investigate the outage.';
+ const started = ownerStore.start(
+ taskRequest(config.scopeId, {
+ input,
+ run: async (_runtime, initialMessages = []) => ({
+ content: 'Root cause found.',
+ messages: [
+ ...initialMessages,
+ new HumanMessage(input),
+ new AIMessage({
+ content: '',
+ tool_calls: [
+ {
+ id: 'call-1',
+ name: 'read_file',
+ args: { intent: 'Reading the incident log', path: '/var/log/private' },
+ },
+ ],
+ }),
+ new ToolMessage({ tool_call_id: 'call-1', name: 'read_file', content: 'token=abc' }),
+ new AIMessage('Root cause found.'),
+ ],
+ }),
+ }),
+ );
+ const taskId = requireAccepted(started).task.taskId;
+ await waitForSettled(ownerStore, config.scopeId, started);
+
+ const restartedStore = new SubagentThreadTaskStore(methods);
+ const recovered = await restartedStore.claimTask(config.scopeId, taskId, 'poll-1');
+ expect(recovered).toMatchObject({ status: 'completed', result: 'Root cause found.' });
+ const tree = recovered.status === 'completed' ? snapshotActivity(recovered.task) : undefined;
+ expect(tree?.root.turns.map((turn) => turn.children.map((leaf) => leaf.kind))).toEqual([
+ ['tool'],
+ ['text'],
+ ]);
+ expect(tree?.root.turns[0].children[0]).toMatchObject({
+ name: 'read_file',
+ label: 'Reading the incident log',
+ status: 'ok',
+ chars: 9,
+ });
+ expect(JSON.stringify(tree)).not.toContain('token');
+ expect(JSON.stringify(tree)).not.toContain('private');
+ });
+});
diff --git a/packages/api/src/agents/subagentThreads.ts b/packages/api/src/agents/subagentThreads.ts
index c2d5fb81d2..5b49f2ecc4 100644
--- a/packages/api/src/agents/subagentThreads.ts
+++ b/packages/api/src/agents/subagentThreads.ts
@@ -40,15 +40,21 @@ import type {
import type { SubagentTaskControlTransport } from './subagentTaskRouting';
import type { UsageMetadata } from '~/stream/interfaces/IJobStore';
import type { HostSubagentTaskConfig } from './subagentDelivery';
+import type { ActivitySnapshot, ActivityTree } from './digest';
import {
boundedClaim,
boundedTaskList,
controlFingerprint,
SubagentTaskOwnerUnavailableError,
} from './subagentTaskRouting';
+import {
+ SUBAGENT_ACTIVITY_LIMITS,
+ projectSubagentActivity,
+ projectPersistedMessageActivityJson,
+} from './activity';
import { boundSubagentActivityUpdate, SubagentActivityStream } from './subagentActivity';
import { createSubagentAttemptKey, createSubagentThreadId } from './subagentThreadIds';
-import { SUBAGENT_ACTIVITY_LIMITS, projectSubagentActivity } from './activity';
+import { ActivityRecorder, activityTreeFromProjection } from './digest';
import { runWithDetachedSubagentUsage } from './subagentTaskContext';
import { SUBAGENT_COMPLETION_DELIVERY } from './subagentDelivery';
import { createConcurrencyLimiter } from '~/utils/promise';
@@ -79,6 +85,10 @@ const SHUTDOWN_CONTROL_RECEIPT_FLUSH_ATTEMPTS = 4;
const DEFAULT_SHUTDOWN_CONTROL_RECEIPT_BACKOFF_MS = 1_000;
/** Bounds retained live-only updates while an event transport is unavailable. */
const MAX_PENDING_ACTIVITY_EVENTS = SUBAGENT_ACTIVITY_LIMITS.items;
+/** Matches the SDK's default retention of a settled task's result. */
+const ACTIVITY_TREE_RETENTION_MS = 60 * 60_000;
+/** Each tree is capped at a few dozen kilobytes; this caps the process total. */
+const MAX_ACTIVITY_TREES = 512;
/** A cancellation target set resolved before the conversations are removed. */
export interface SubagentCancellationPlan {
@@ -95,7 +105,7 @@ const MAX_TRANSCRIPT_BYTES = 12 * 1024 * 1024;
const TRANSCRIPT_SELECT =
'messageId parentMessageId text createdAt +subagentTranscript +subagentTask';
const DURABLE_RESULT_SELECT =
- 'messageId conversationId sender text createdAt updatedAt +subagentTask';
+ 'messageId conversationId sender text createdAt updatedAt +subagentTask +subagentActivityProjection';
class SubagentThreadPublicError extends Error {}
class SubagentThreadDeletedError extends SubagentThreadPublicError {}
@@ -568,6 +578,37 @@ function boundedControlCommand(command: SubagentTaskControlCommand): SubagentTas
};
}
+/**
+ * The settlement-time public projection is the only progress that outlives the
+ * owning process. It is scoped to the task it was written for, and is read only
+ * after the caller has re-established the child's parent lineage.
+ */
+function durableActivity(
+ message: IMessage,
+ taskId: string,
+ startedAt: number,
+ settledAt: number,
+): ActivityTree | undefined {
+ const projection = message.subagentActivityProjection;
+ if (projection == null || projection.taskId !== taskId) {
+ return undefined;
+ }
+ const { activity, truncated } = projectPersistedMessageActivityJson(
+ projection.activityJson,
+ projection.truncated,
+ );
+ return activityTreeFromProjection(activity, { startedAt, settledAt, truncated });
+}
+
+/** Progress is observational: a recording failure must never fail the child. */
+function recordActivity(recorder: ActivityRecorder, event: SubagentUpdateEvent): void {
+ try {
+ recorder.record(event);
+ } catch (error) {
+ logger.warn('[subagentThreads] Failed to record child progress', error);
+ }
+}
+
function safeErrorMessage(error: unknown): string {
return `Subagent task failed: ${publicFailureDetail(error).slice(0, 2_000)}`;
}
@@ -641,6 +682,10 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
private taskControlTransport?: SubagentTaskControlTransport;
private activityOptions: TSubagentActivityConfig = subagentActivityConfigSchema.parse({});
private activityStream = new SubagentActivityStream(new InMemoryEventTransport());
+ private readonly activityTrees = new Map<
+ string,
+ { recorder: ActivityRecorder; settledAt?: number }
+ >();
constructor(
private readonly methods: SubagentThreadMethods,
@@ -1070,10 +1115,10 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
throw new Error('Subagent task control transport is already configured.');
}
await transport.bind({
- claim: (scopeId, taskId) => super.claim(scopeId, taskId),
+ claim: (scopeId, taskId) => this.withActivity(scopeId, super.claim(scopeId, taskId)),
control: (scopeId, taskId, command, invocationId) =>
this.controlInvocationAndPersist(scopeId, taskId, command, invocationId),
- list: (scopeId) => super.list(scopeId),
+ list: (scopeId) => this.withActivitySummaries(scopeId, super.list(scopeId)),
cancelScope: (scopeId, threadIds, removedConversationIds = []) => {
const cancelled = this.cancelForScope(scopeId, threadIds);
if (removedConversationIds.length > 0) {
@@ -1221,6 +1266,62 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
return this.activityStream.publish(threadId, taskId, boundSubagentActivityUpdate(event));
}
+ /**
+ * Starts the bounded progress tree for one locally executing child. Trees outlive
+ * settlement so a finished, undelivered result can still be navigated, and are
+ * released by age and count rather than by the SDK's own result retention.
+ */
+ private trackActivity(scopeId: string, taskId: string): ActivityRecorder {
+ const now = Date.now();
+ for (const [key, entry] of this.activityTrees) {
+ if (entry.settledAt != null && now - entry.settledAt > ACTIVITY_TREE_RETENTION_MS) {
+ this.activityTrees.delete(key);
+ }
+ }
+ if (this.activityTrees.size >= MAX_ACTIVITY_TREES) {
+ const oldest =
+ [...this.activityTrees].find(([, entry]) => entry.settledAt != null) ??
+ this.activityTrees.entries().next().value;
+ if (oldest != null) {
+ this.activityTrees.delete(oldest[0]);
+ }
+ }
+ const recorder = new ActivityRecorder(now);
+ this.activityTrees.set(controlTaskKey(scopeId, taskId), { recorder });
+ return recorder;
+ }
+
+ private settleActivity(
+ scopeId: string,
+ taskId: string,
+ terminal: SubagentActivityTerminalStatus,
+ ): void {
+ const entry = this.activityTrees.get(controlTaskKey(scopeId, taskId));
+ if (entry == null) return;
+ entry.recorder.settle(terminal === 'failed' ? 'error' : terminal);
+ entry.settledAt = Date.now();
+ }
+
+ /** Attaches this process's progress tree to a claim the poll tool will render. */
+ private withActivity(scopeId: string, claim: SubagentTaskClaim): SubagentTaskClaim {
+ if (claim.status === 'not_found') return claim;
+ const entry = this.activityTrees.get(controlTaskKey(scopeId, claim.task.taskId));
+ if (entry == null) return claim;
+ const task: ActivitySnapshot = { ...claim.task, activity: entry.recorder.snapshot() };
+ return { ...claim, task };
+ }
+
+ /** Lists carry only counts and the node in flight, never whole trees. */
+ private withActivitySummaries(
+ scopeId: string,
+ snapshots: SubagentTaskSnapshot[],
+ ): SubagentTaskSnapshot[] {
+ return snapshots.map((snapshot): ActivitySnapshot => {
+ const entry = this.activityTrees.get(controlTaskKey(scopeId, snapshot.taskId));
+ return entry == null ? snapshot : { ...snapshot, activitySummary: entry.recorder.summary() };
+ });
+ }
+
private publishActivity(
lease: TaskThreadLease,
threadId: string,
@@ -1465,6 +1566,7 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
);
}
const preparedThread = prepared;
+ const recorder = this.trackActivity(request.scopeId, runtime.taskId);
let activitySequence = 0;
const activityRuntime: SubagentTaskRuntime = {
...runtime,
@@ -1476,6 +1578,7 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
activitySequence: sequence,
};
runtime.reportProgress(activityEvent);
+ recordActivity(recorder, activityEvent);
this.publishActivity(
lease,
preparedThread.conversation.conversationId,
@@ -1559,6 +1662,7 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
this.wakeupTaskIds.delete(prepared.replay?.taskId ?? runtime.taskId);
}
if (prepared != null && prepared.replay == null) {
+ this.settleActivity(request.scopeId, runtime.taskId, activityTerminal);
this.completeActivity(
lease,
prepared.conversation.conversationId,
@@ -1623,7 +1727,7 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
taskId: string,
invocationId?: string,
): Promise<SubagentTaskClaim> {
- const local = super.claim(scopeId, taskId);
+ const local = this.withActivity(scopeId, super.claim(scopeId, taskId));
const claim =
local.status !== 'not_found'
? local
@@ -1725,7 +1829,8 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
if (createdAt == null || updatedAt == null) {
return { status: 'not_found' };
}
- const task: SubagentTaskSnapshot = {
+ const activity = durableActivity(message, taskId, createdAt, updatedAt);
+ const task: ActivitySnapshot = {
taskId,
threadId,
subagentType: lineage.subagentType,
@@ -1736,6 +1841,7 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
resultClaimed: true,
pendingControls: 0,
...(status === 'completed' ? {} : { error: message.text ?? '' }),
+ ...(activity == null ? {} : { activity }),
};
const collected = await this.assignResultClaim(scope.userId, threadId, taskId, invocationId);
if (collected.status === 'not_found') {
@@ -2224,7 +2330,7 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
/** Returns this process's tasks plus tasks reported by registered remote owners. */
async listTasks(scopeId: string): Promise<SubagentTaskSnapshot[]> {
- const local = super.list(scopeId);
+ const local = this.withActivitySummaries(scopeId, super.list(scopeId));
const remote = (await this.taskControlTransport?.list(scopeId)) ?? [];
const byId = new Map(local.map((task) => [task.taskId, task]));
for (const task of remote) {
diff --git a/packages/api/src/stream/GenerationJobManager.ts b/packages/api/src/stream/GenerationJobManager.ts
index 4bbc4a1b47..1be0ffdbe6 100644
--- a/packages/api/src/stream/GenerationJobManager.ts
+++ b/packages/api/src/stream/GenerationJobManager.ts
@@ -9,7 +9,7 @@ import {
ApprovalEvents,
SteerEvents,
parseTextParts,
- hasToolCallErrorPrefix,
+ isFailedToolOutput,
reconcileContextUsageFromEvent,
} from 'librechat-data-provider';
import type {
@@ -129,13 +129,7 @@ function completedToolExecutionStatus(call: Agents.ToolCall): ToolExecutionStatu
if (call.inputValidationError === true) {
return 'error';
}
- const output = call.output;
- return typeof output === 'string' &&
- (hasToolCallErrorPrefix(output) ||
- /^Error processing tool(?::|$)/i.test(output) ||
- /^Error:[\s\S]*\n Please fix your mistakes\.$/i.test(output))
- ? 'error'
- : 'success';
+ return typeof call.output === 'string' && isFailedToolOutput(call.output) ? 'error' : 'success';
}
/** Bounded completed-request replay horizon. It exceeds the default 24-hour
diff --git a/packages/data-provider/src/errors.spec.ts b/packages/data-provider/src/errors.spec.ts
index f512309e48..21f89a45cf 100644
--- a/packages/data-provider/src/errors.spec.ts
+++ b/packages/data-provider/src/errors.spec.ts
@@ -1,4 +1,4 @@
-import { hasToolCallErrorPrefix, stripToolCallErrorPrefix } from './errors';
+import { isFailedToolOutput, hasToolCallErrorPrefix, stripToolCallErrorPrefix } from './errors';
describe('tool call errors', () => {
test.each([
@@ -28,3 +28,21 @@ describe('tool call errors', () => {
);
});
});
+
+describe('isFailedToolOutput', () => {
+ test.each([
+ 'Error: tool call failed: unavailable',
+ 'Error processing tool',
+ 'Error processing tool: boom',
+ 'Error: Received tool input did not match expected schema\n Please fix your mistakes.',
+ ])('treats %j as a failed call', (output) => {
+ expect(isFailedToolOutput(output)).toBe(true);
+ });
+
+ test.each(['PASS 12 tests', 'Error processing tools completed', 'Error: something\nPlease fix'])(
+ 'treats %j as a completed call',
+ (output) => {
+ expect(isFailedToolOutput(output)).toBe(false);
+ },
+ );
+});
diff --git a/packages/data-provider/src/errors.ts b/packages/data-provider/src/errors.ts
index ed9da1909e..bc18cef5b0 100644
--- a/packages/data-provider/src/errors.ts
+++ b/packages/data-provider/src/errors.ts
@@ -9,6 +9,21 @@ export function isToolErrorOutput(text: string): boolean {
return hasToolCallErrorPrefix(text) || text.startsWith('Error processing tool');
}
+const VALIDATION_FEEDBACK = /^Error:[\s\S]*\n Please fix your mistakes\.$/i;
+
+/**
+ * Whether a completed tool call failed. Agents SDK releases serialize tool failures
+ * into these host-authored prefixes, and schema-validation feedback into a plain
+ * `Error:` block, without carrying `ToolMessage.status` on the wire.
+ */
+export function isFailedToolOutput(text: string): boolean {
+ return (
+ hasToolCallErrorPrefix(text) ||
+ /^Error processing tool(?::|$)/i.test(text) ||
+ VALIDATION_FEEDBACK.test(text)
+ );
+}
+
export function stripToolCallErrorPrefix(text: string): string {
return text.replace(TOOL_CALL_ERROR_PREFIX, '');
}
diff --git a/packages/data-provider/src/types/subagents.ts b/packages/data-provider/src/types/subagents.ts
index 86fa532640..8019fdfba5 100644
--- a/packages/data-provider/src/types/subagents.ts
+++ b/packages/data-provider/src/types/subagents.ts
@@ -187,3 +187,57 @@ export type SubagentThreadView = {
nextCursor?: string;
updatedAt?: string;
};
+
+export type SubagentDigestStatus = 'running' | 'ok' | 'error' | 'cancelled';
+
+/**
+ * One node of a background subagent's progress tree, as `check_background_task`
+ * returns it. A run holds numbered turns; a turn holds numbered tool calls and
+ * text replies; a nested subagent call holds its own run. `path` addresses the
+ * node positionally (`3` is turn 3, `3.2` its second child, `3.2.1` the first
+ * turn of a subagent that child started) and never shifts as the run grows. A
+ * `range` folds consecutive turns (`1-14`). Labels are the child's own one-line
+ * tool intents; tool arguments, outputs, and reply text are never included.
+ */
+export type SubagentDigestNode = {
+ path: string;
+ kind: 'turn' | 'range' | 'tool' | 'text';
+ status?: SubagentDigestStatus;
+ /** Tool name for `tool` nodes. */
+ name?: string;
+ label?: string;
+ /** Duration, or elapsed time while running. */
+ ms?: number;
+ /** Size of a tool output or text reply, never its content. */
+ chars?: number;
+ /** Folded children, by kind and count. */
+ summary?: string;
+ errors?: number;
+ /** The node has children this view did not include; expand its path to see them. */
+ folded?: true;
+ /** Folded turns whose detail is no longer retained and cannot be expanded. */
+ evicted?: true;
+};
+
+/** Compact, navigable progress for a running or not-yet-delivered subagent task. */
+export type SubagentDigest = {
+ turns: number;
+ tools: number;
+ errors: number;
+ /** Path of the node the child is working on now. */
+ active?: string;
+ /** Set while the child is reasoning with no tool or reply in flight. */
+ phase?: 'thinking';
+ /** Time since the child's last activity, when nothing is in flight. */
+ idle_ms?: number;
+ nodes: SubagentDigestNode[];
+ /** Pass back as `since` to receive only newer nodes. */
+ cursor?: string;
+ /** Echo of the requested `expand` or `since`. */
+ expanded?: string;
+ since?: string;
+ /** Some nodes were folded or dropped to stay within the output budget. */
+ truncated?: true;
+ /** Why an `expand` returned less than the node it named. */
+ note?: string;
+};