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

📼 fix: Replay Running Subagent Activity (#16541)

lia-by-librechat[bot]bb0543fd1519
diff --git a/api/server/experimental.js b/api/server/experimental.js
index 52870f2e4c..18983dafb8 100644
--- a/api/server/experimental.js
+++ b/api/server/experimental.js
@@ -439,7 +439,6 @@ if (cluster.isMaster) {
logger.info(`Worker ${process.pid} initializing...`);
await waitForKeyvRedisClient();
- await configureSubagentTaskRouting();
if (typeof Bun !== 'undefined') {
axios.defaults.headers.common['Accept-Encoding'] = 'gzip';
@@ -501,6 +500,7 @@ if (cluster.isMaster) {
// principal) still merges DB `__base__` overrides, which must not drive which hook
// modules load in every worker (matches api/server/index.js's baseOnly usage).
const baseAppConfig = await getAppConfig({ baseOnly: true });
+ await configureSubagentTaskRouting(baseAppConfig?.endpoints?.agents?.subagentActivity);
registerBackgroundTaskShutdown({
interruptGraceMs: baseAppConfig?.endpoints?.agents?.backgroundTasks?.shutdownInterruptGraceMs,
getBudgetMs: clusterShutdownBudgetMs,
diff --git a/api/server/experimental.spec.js b/api/server/experimental.spec.js
index 30d2878a09..9ed24e3d7a 100644
--- a/api/server/experimental.spec.js
+++ b/api/server/experimental.spec.js
@@ -85,7 +85,9 @@ describe('Experimental server configuration', () => {
it('configures routed subagent controls before a worker accepts requests', () => {
const redisReadyIndex = source.indexOf('await waitForKeyvRedisClient();');
- const routingIndex = source.indexOf('await configureSubagentTaskRouting();');
+ const routingIndex = source.indexOf(
+ 'await configureSubagentTaskRouting(baseAppConfig?.endpoints?.agents?.subagentActivity);',
+ );
const listenIndex = source.indexOf('const server = app.listen');
expect(redisReadyIndex).toBeGreaterThan(-1);
diff --git a/api/server/index.js b/api/server/index.js
index 134cc5b7a3..eec43ca22e 100644
--- a/api/server/index.js
+++ b/api/server/index.js
@@ -170,7 +170,6 @@ const SHUTDOWN_TEARDOWN_RESERVE_MS = 10_000;
const startServer = async () => {
await waitForKeyvRedisClient();
- await configureSubagentTaskRouting();
const { metricsMiddleware, metricsRouter } = createMetrics({
collectAgentEventActorStorageMetrics: () =>
runAsSystem(async () => {
@@ -231,6 +230,7 @@ const startServer = async () => {
logger.error('[sweepOrphanedPreviews] Background sweep failed:', err);
});
const appConfig = await getAppConfig({ baseOnly: true });
+ await configureSubagentTaskRouting(appConfig?.endpoints?.agents?.subagentActivity);
registerBackgroundTaskShutdown({
interruptGraceMs: appConfig?.endpoints?.agents?.backgroundTasks?.shutdownInterruptGraceMs,
});
diff --git a/api/server/index.spec.js b/api/server/index.spec.js
index 5f5a54c475..6b8f76543e 100644
--- a/api/server/index.spec.js
+++ b/api/server/index.spec.js
@@ -171,7 +171,9 @@ describe('Startup readiness wiring', () => {
});
it('configures subagent task routing before the server accepts requests', () => {
- const routingIndex = source.indexOf('await configureSubagentTaskRouting();');
+ const routingIndex = source.indexOf(
+ 'await configureSubagentTaskRouting(appConfig?.endpoints?.agents?.subagentActivity);',
+ );
const listenIndex = source.indexOf('const server = app.listen');
expect(routingIndex).toBeGreaterThan(-1);
diff --git a/api/server/services/Endpoints/agents/subagentThreadStore.js b/api/server/services/Endpoints/agents/subagentThreadStore.js
index d98f0f275f..0c7fc885b2 100644
--- a/api/server/services/Endpoints/agents/subagentThreadStore.js
+++ b/api/server/services/Endpoints/agents/subagentThreadStore.js
@@ -61,6 +61,7 @@ const subagentThreadTaskStore = createSubagentThreadTaskStore(
deleteConvos: db.deleteConvos,
deleteMessages: db.deleteMessages,
getConvo: db.getConvo,
+ getAgentName: db.getAgentName,
getSubagentTaskControlReplay: db.getSubagentTaskControlReplay,
getMessages: db.getMessages,
listActiveSubagentThreadLeases: db.listActiveSubagentThreadLeases,
@@ -106,7 +107,8 @@ registerShutdownTask(
);
/** Starts the optional Redis owner directory before HTTP admission opens. */
-async function configureSubagentTaskRouting() {
+async function configureSubagentTaskRouting(config) {
+ const activityOptions = subagentThreadTaskStore.configureActivity(config);
if (taskRoutingConfigured || !cacheConfig.USE_REDIS) {
return;
}
@@ -126,14 +128,21 @@ async function configureSubagentTaskRouting() {
ioredisClient,
'[SubagentTaskRouting] activity subscriber',
);
- const activityPublisher = duplicateIoRedisClient(ioredisClient, { enableOfflineQueue: false });
+ const activityPublisher = duplicateIoRedisClient(ioredisClient, {
+ enableOfflineQueue: false,
+ maxRetriesPerRequest: 1,
+ commandTimeout: activityOptions.publicationTimeoutMs,
+ });
const transport = new RedisSubagentTaskControlTransport(publisher, subscriber, {
namespace: cacheConfig.REDIS_KEY_PREFIX,
});
try {
await subagentThreadTaskStore.configureTaskControlTransport(transport);
subagentThreadTaskStore.configureActivityStream(
- new SubagentActivityStream(new RedisEventTransport(activityPublisher, activitySubscriber)),
+ new SubagentActivityStream(
+ new RedisEventTransport(activityPublisher, activitySubscriber),
+ activityOptions,
+ ),
);
} catch (error) {
subscriber.disconnect();
diff --git a/api/server/services/Endpoints/agents/subagentThreadStore.spec.js b/api/server/services/Endpoints/agents/subagentThreadStore.spec.js
index a7d2609468..b42198f590 100644
--- a/api/server/services/Endpoints/agents/subagentThreadStore.spec.js
+++ b/api/server/services/Endpoints/agents/subagentThreadStore.spec.js
@@ -1,4 +1,5 @@
const mockTaskStore = {
+ configureActivity: jest.fn((config) => ({ publicationTimeoutMs: 1000, ...config })),
configureTaskControlTransport: jest.fn().mockResolvedValue(undefined),
configureActivityStream: jest.fn(),
prepareActivityForShutdown: jest.fn(),
@@ -111,7 +112,16 @@ describe('subagent thread Redis lifecycle', () => {
.mockReturnValueOnce(taskPublisher)
.mockReturnValueOnce(activityPublisher);
- await configureSubagentTaskRouting();
+ await configureSubagentTaskRouting({ publicationTimeoutMs: 4321, replayTtlMs: 600000 });
+ expect(mockTaskStore.configureActivity).toHaveBeenCalledWith({
+ publicationTimeoutMs: 4321,
+ replayTtlMs: 600000,
+ });
+ expect(duplicateIoRedisClient).toHaveBeenCalledWith(ioredisClient, {
+ enableOfflineQueue: false,
+ maxRetriesPerRequest: 1,
+ commandTimeout: 4321,
+ });
expect(createIoRedisSubscriber.mock.calls).toEqual([
[ioredisClient, '[SubagentTaskRouting] task subscriber'],
diff --git a/client/src/components/Chat/Subagents/SubagentActivity.test.tsx b/client/src/components/Chat/Subagents/SubagentActivity.test.tsx
index c62c42f1a2..287dcd5ba3 100644
--- a/client/src/components/Chat/Subagents/SubagentActivity.test.tsx
+++ b/client/src/components/Chat/Subagents/SubagentActivity.test.tsx
@@ -216,6 +216,19 @@ const base: ChildActivity = {
],
};
+it('keeps a host notice inside the floating-header clearance', () => {
+ const activity: ChildActivity = { title: 'Review', status: 'running', items: [] };
+ const { container } = render(
+ <SubagentActivity
+ activity={activity}
+ headerInset
+ notice={<div role="status">{String(19)}</div>}
+ />,
+ );
+ const inset = container.querySelector('[class*="pt-[52px]"]');
+ expect(inset).toContainElement(screen.getByRole('status'));
+});
+
describe('SubagentActivity', () => {
it.each(['failed', 'cancelled'] as const)(
'renders the %s lifecycle through the shared view',
diff --git a/client/src/components/Chat/Subagents/SubagentActivity.tsx b/client/src/components/Chat/Subagents/SubagentActivity.tsx
index 58c08de893..9382559d75 100644
--- a/client/src/components/Chat/Subagents/SubagentActivity.tsx
+++ b/client/src/components/Chat/Subagents/SubagentActivity.tsx
@@ -420,6 +420,7 @@ export default function SubagentActivity({
showPrompt = true,
headerInset = false,
onCancelControl,
+ notice,
}: {
activity: ChildActivity;
activityId?: string;
@@ -427,6 +428,7 @@ export default function SubagentActivity({
embedded?: boolean;
showPrompt?: boolean;
headerInset?: boolean;
+ notice?: React.ReactNode;
onCancelControl?: (controlId: string) => void;
}) {
const statusHeader = isAbnormalTerminalStatus(activity.status) ? (
@@ -435,13 +437,16 @@ export default function SubagentActivity({
</div>
) : null;
const content = (
- <SubagentActivityContent
- activity={activity}
- activityId={activityId}
- state={state}
- showPrompt={showPrompt}
- onCancelControl={onCancelControl}
- />
+ <>
+ {notice}
+ <SubagentActivityContent
+ activity={activity}
+ activityId={activityId}
+ state={state}
+ showPrompt={showPrompt}
+ onCancelControl={onCancelControl}
+ />
+ </>
);
if (embedded) {
diff --git a/client/src/components/Chat/Subagents/SubagentThreadPanel.test.tsx b/client/src/components/Chat/Subagents/SubagentThreadPanel.test.tsx
index c835da419a..9a895f17fc 100644
--- a/client/src/components/Chat/Subagents/SubagentThreadPanel.test.tsx
+++ b/client/src/components/Chat/Subagents/SubagentThreadPanel.test.tsx
@@ -554,7 +554,7 @@ describe('SubagentThreadPanel', () => {
{ keepPreviousData: true },
);
expect(mockUseSubagentActivityStream).toHaveBeenCalledWith(selection, false);
- expect(screen.getByText('Research child')).toBeInTheDocument();
+ expect(screen.getByText('Analyst One')).toBeInTheDocument();
expect(screen.queryByText('com_ui_subagent_depth')).not.toBeInTheDocument();
expect(screen.getByText('Investigate the release.')).toBeInTheDocument();
expect(screen.getByText('The release is ready.')).toBeInTheDocument();
diff --git a/client/src/components/Chat/Subagents/SubagentThreadPanel.tsx b/client/src/components/Chat/Subagents/SubagentThreadPanel.tsx
index 250d914cc1..6858babb96 100644
--- a/client/src/components/Chat/Subagents/SubagentThreadPanel.tsx
+++ b/client/src/components/Chat/Subagents/SubagentThreadPanel.tsx
@@ -824,7 +824,9 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
}
return { ...merged, controls: [...(merged.controls ?? []), transientControl] };
}, [liveActivity, progress, selection.durable, taskView, transientControl]);
- const panelTitle = selection.event == null ? activity.title : selectedEventActorName;
+ const panelAgent = threadView?.agentId == null ? undefined : agentsMap?.[threadView.agentId];
+ const panelTitle =
+ selection.event == null ? panelAgent?.name || activity.title : selectedEventActorName;
const actorOptions = useMemo<OptionWithIcon[]>(() => {
if (selection.event == null) return [];
return (
@@ -1128,7 +1130,7 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
key: 'steer',
label: localize('com_ui_steer'),
kbd: steerKbd,
- icon: <Zap className="h-4 w-4 text-status-warning" aria-hidden="true" />,
+ icon: <Zap className="text-status-warning h-4 w-4" aria-hidden="true" />,
disabled: blocked,
onClick: () => submitControl('steer'),
},
@@ -1136,7 +1138,7 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
key: 'queue',
label: localize('com_ui_queue'),
kbd: modEnter === 'other' ? modSymbol : undefined,
- icon: <Clock className="h-4 w-4 text-status-info" aria-hidden="true" />,
+ icon: <Clock className="text-status-info h-4 w-4" aria-hidden="true" />,
disabled: blocked,
onClick: () => submitControl('queue'),
},
@@ -1144,7 +1146,7 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
key: 'interrupt',
label: localize('com_ui_subagent_interrupt'),
kbd: altEnter === 'interrupt' ? altSymbol : undefined,
- icon: <OctagonPause className="h-4 w-4 text-status-error" aria-hidden="true" />,
+ icon: <OctagonPause className="text-status-error h-4 w-4" aria-hidden="true" />,
disabled: blocked,
onClick: () => submitControl('interrupt'),
},
@@ -1273,7 +1275,7 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
let timelinePrefix: ReactNode = null;
if (hasEarlierRetainedTasks) {
timelinePrefix = (
- <div className="flex justify-center border-b border-border-light px-4 py-2">
+ <div className="border-border-light flex justify-center border-b px-4 py-2">
<Button type="button" variant="ghost" size="sm" onClick={loadEarlierEventTasks}>
{localize('com_ui_load_more')}
</Button>
@@ -1284,7 +1286,7 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
<div
role="status"
aria-label={localize('com_ui_subagent_thread_history_truncated')}
- className="flex h-7 items-center justify-center border-b border-border-light text-text-tertiary"
+ className="border-border-light text-text-tertiary flex h-7 items-center justify-center border-b"
>
<span aria-hidden>•••</span>
</div>
@@ -1295,21 +1297,33 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
[conversationTurns, panelState, taskId],
);
+ const droppedNotice =
+ (progress?.droppedCount ?? 0) > 0 ? (
+ <div role="status" className="text-text-secondary px-4 py-2 text-sm">
+ {localize(
+ progress!.droppedCount === 1
+ ? 'com_ui_subagent_activity_dropped_one'
+ : 'com_ui_subagent_activity_dropped',
+ { count: progress!.droppedCount! },
+ )}
+ </div>
+ ) : null;
let activityPanel: ReactNode;
if (hasConversationProjection) {
activityPanel = (
<SubagentActivityScrollSurface padded={false} headerInset>
+ {droppedNotice}
{showUnavailableHistoryBoundary && (
<div
role="status"
aria-label={localize('com_ui_subagent_thread_history_truncated')}
- className="flex h-7 items-center justify-center border-b border-border-light text-text-tertiary"
+ className="border-border-light text-text-tertiary flex h-7 items-center justify-center border-b"
>
<span aria-hidden>•••</span>
</div>
)}
{effectiveHistoryCursor != null && historyState !== 'error' && (
- <div className="flex justify-center border-b border-border-light px-4 py-2">
+ <div className="border-border-light flex justify-center border-b px-4 py-2">
<Button
type="button"
variant="ghost"
@@ -1324,7 +1338,7 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
</div>
)}
{historyState === 'error' && (
- <div className="flex justify-center border-b border-border-light px-4 py-2">
+ <div className="border-border-light flex justify-center border-b px-4 py-2">
<Button
type="button"
variant="ghost"
@@ -1357,6 +1371,7 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
) {
activityPanel = (
<SubagentActivityScrollSurface padded={false} headerInset>
+ {droppedNotice}
<div data-subagent-thread-timeline>
{timelinePrefix}
{visibleEventTasks.map(renderEventTask)}
@@ -1372,6 +1387,7 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
state={panelState}
showPrompt={false}
headerInset
+ notice={droppedNotice}
onCancelControl={
controlAvailable && !controlPending
? (controlId) => submitControl('cancel_message', controlId)
@@ -1388,13 +1404,13 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
aria-modal={isMobile || undefined}
aria-label={localize('com_ui_subagent_thread_panel')}
onKeyDown={handlePanelKeyDown}
- className="relative flex h-full w-full flex-col overflow-hidden bg-surface-primary-alt text-text-primary"
+ className="bg-surface-primary-alt text-text-primary relative flex h-full w-full flex-col overflow-hidden"
>
{/* The main chat header's own shape: a 52px bar that floats over the
thread and fades into it, so the conversation scrolls under it and
more of it is on screen. Gradient stops track THIS surface rather
than the chat's, since the panel sits on its own background. */}
- <header className="absolute top-0 z-10 flex h-[52px] w-full items-center gap-2 bg-gradient-to-b from-surface-primary-alt via-surface-primary-alt/70 to-transparent p-2 font-semibold text-text-primary">
+ <header className="from-surface-primary-alt via-surface-primary-alt/70 text-text-primary absolute top-0 z-10 flex h-[52px] w-full items-center gap-2 bg-gradient-to-b to-transparent p-2 font-semibold">
{actorOptions.length > 1 ? (
/* The agent builder's picker, so switching actors here reads as the
same control as every other agent selection in the app — avatar,
@@ -1427,7 +1443,7 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
portal={false}
onOpenChange={setActorPickerOpen}
containerClassName="min-w-0 flex-1 px-0"
- className="h-9 w-full border-transparent bg-transparent font-semibold hover:bg-surface-hover"
+ className="hover:bg-surface-hover h-9 w-full border-transparent bg-transparent font-semibold"
showCarat
/>
</div>
@@ -1526,7 +1542,7 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
aria-label={action.label}
disabled={action.disabled}
onClick={action.onClick}
- className="size-9 rounded-full text-text-secondary hover:text-text-primary"
+ className="text-text-secondary hover:text-text-primary size-9 rounded-full"
>
{action.icon}
</Button>
diff --git a/client/src/components/Chat/Subagents/state.spec.ts b/client/src/components/Chat/Subagents/state.spec.ts
index 6d4d9042f1..4a54563c8e 100644
--- a/client/src/components/Chat/Subagents/state.spec.ts
+++ b/client/src/components/Chat/Subagents/state.spec.ts
@@ -6,6 +6,7 @@ import type { SubagentUpdateEvent } from 'librechat-data-provider';
import {
closeParentSubagentProgress,
reduceSubagentProgress,
+ reduceSubagentReplay,
registerSubagentProgressKey,
removeSubagentProgressAtoms,
subagentParentStreamOpenByToolCallId,
@@ -498,3 +499,842 @@ describe('useSubagentProgress', () => {
expect(store.get(held)).not.toBeNull();
});
});
+
+it('counts an expired rejected interval without discarding later retained pending frames', () => {
+ const event = (sequence: number) =>
+ update({
+ activityEventId: `overflow:${sequence}`,
+ activitySequence: sequence,
+ phase: 'message_delta',
+ data: { delta: { content: [{ type: 'text', text: `${sequence},` }] } },
+ });
+ let progress = reduceSubagentProgress(
+ null,
+ Array.from({ length: 100 }, (_, i) => event(i + 2)),
+ 'detached',
+ true,
+ );
+ progress = reduceSubagentProgress(progress, [event(102), event(103)], 'detached', true);
+ progress = reduceSubagentProgress(progress, [event(0), event(1)], 'parent', true);
+ progress = reduceSubagentProgress(progress, [event(104), event(105)], 'detached', true);
+ expect(progress?.activityReplayFrom).toBe(102);
+ expect(progress?.pendingSequencedEvents).toHaveLength(2);
+ progress = reduceSubagentReplay(closeParentSubagentProgress(progress), [], false);
+ expect(progress?.lastActivitySequence).toBe(105);
+ expect(progress?.droppedCount).toBe(2);
+ expect(progress?.activityReplayFrom).toBeUndefined();
+ expect(progress?.contentParts).toEqual([
+ {
+ type: 'text',
+ text: Array.from({ length: 106 }, (_, i) => i)
+ .filter((i) => i !== 102 && i !== 103)
+ .map((i) => `${i},`)
+ .join(''),
+ },
+ ]);
+});
+
+describe('replay prefix projection reconciliation', () => {
+ const event = (sequence: number, phase: SubagentUpdateEvent['phase'] = 'message_delta') =>
+ update({
+ activityEventId: `backfill:${sequence}`,
+ activitySequence: sequence,
+ phase,
+ data:
+ phase === 'reasoning_delta'
+ ? { delta: { content: [{ type: 'think', think: `${sequence},` }] } }
+ : { delta: { content: [{ type: 'text', text: `${sequence},` }] } },
+ });
+ it.each([0, 2, 4])(
+ 'preserves a displayed suffix when replay stops at sequence %s',
+ (snapshotEnd) => {
+ let progress = reduceSubagentProgress(
+ null,
+ [event(2), event(3), event(4)],
+ 'detached',
+ false,
+ );
+ const replay = Array.from({ length: snapshotEnd + 1 }, (_, i) => event(i));
+ progress = reduceSubagentReplay(progress, replay, false);
+ expect(progress?.contentParts).toEqual([
+ { type: 'text', text: `${snapshotEnd === 0 ? '0,' : '0,1,'}2,3,4,` },
+ ]);
+ expect(progress?.lastActivitySequence).toBe(4);
+ progress = reduceSubagentReplay(progress, replay, false);
+ expect(progress?.contentParts).toEqual([
+ { type: 'text', text: `${snapshotEnd === 0 ? '0,' : '0,1,'}2,3,4,` },
+ ]);
+ progress = reduceSubagentProgress(
+ progress,
+ [{ ...event(4), data: undefined, activityDroppedCount: 4 }],
+ 'detached',
+ false,
+ );
+ expect(progress?.droppedCount).toBe(0);
+ progress = reduceSubagentProgress(progress, [event(5)], 'detached', false);
+ expect(progress?.contentParts).toEqual([
+ { type: 'text', text: `${snapshotEnd === 0 ? '0,' : '0,1,'}2,3,4,5,` },
+ ]);
+ },
+ );
+ it('preserves reasoning and tool output while merging a prefix tool start', () => {
+ const toolResult = {
+ ...event(3),
+ phase: 'run_step_completed' as const,
+ data: {
+ result: {
+ id: 'step',
+ tool_call: {
+ id: 'tool',
+ name: 'execute_code',
+ args: { code: '1' },
+ output: 'success',
+ progress: 1,
+ },
+ },
+ },
+ };
+ let progress = reduceSubagentProgress(
+ null,
+ [event(2, 'reasoning_delta'), toolResult, event(4)],
+ 'detached',
+ false,
+ );
+ const toolStart = {
+ ...event(0),
+ phase: 'run_step' as const,
+ data: {
+ id: 'step',
+ stepDetails: {
+ type: 'tool_calls',
+ tool_calls: [{ id: 'tool', name: 'execute_code', args: { code: '1' } }],
+ },
+ },
+ };
+ progress = reduceSubagentReplay(progress, [toolStart, event(1)], false);
+ expect(progress?.contentParts.map((part) => part.type)).toEqual([
+ 'tool_call',
+ 'text',
+ 'think',
+ 'text',
+ ]);
+ expect(progress?.contentParts[0]).toMatchObject({
+ tool_call: { id: 'tool', output: 'success', progress: 1 },
+ });
+ expect(progress?.contentParts[2]).toEqual({ type: 'think', think: '2,' });
+ expect(progress?.contentParts[3]).toEqual({ type: 'text', text: '4,' });
+ progress = reduceSubagentProgress(progress, [event(5)], 'detached', false);
+ expect(progress?.contentParts[3]).toEqual({ type: 'text', text: '4,5,' });
+ expect(progress?.tickerState.lines.some((line) => line.kind === 'tool_complete')).toBe(true);
+ });
+ it('keeps item and byte limits while prepending a missing prefix', () => {
+ const tool = (sequence: number) => ({
+ ...event(sequence),
+ phase: 'run_step' as const,
+ data: {
+ id: `step-${sequence}`,
+ stepDetails: {
+ type: 'tool_calls',
+ tool_calls: [
+ { id: `tool-${sequence}`, name: 'execute_code', args: { code: 'x'.repeat(2000) } },
+ ],
+ },
+ },
+ });
+ const previous = reduceSubagentProgress(
+ null,
+ Array.from({ length: 80 }, (_, i) => tool(i + 20)),
+ 'detached',
+ false,
+ );
+ const progress = reduceSubagentReplay(
+ previous,
+ Array.from({ length: 20 }, (_, i) => tool(i)),
+ false,
+ );
+ expect(progress?.contentParts.length).toBeLessThanOrEqual(100);
+ expect(
+ new TextEncoder().encode(JSON.stringify(progress?.contentParts)).byteLength,
+ ).toBeLessThanOrEqual(65_536);
+ expect(progress?.contentParts.at(-1)).toMatchObject({ tool_call: { id: 'tool-99' } });
+ });
+});
+
+describe('disjoint replay coverage', () => {
+ const event = (sequence: number) =>
+ update({
+ activityEventId: `coverage:${sequence}`,
+ activitySequence: sequence,
+ data: { delta: { content: [{ type: 'text', text: `${sequence},` }] } },
+ });
+ it.each(['live', 'replay'])(
+ 'keeps an uncovered prefix boundary recoverable through %s',
+ (source) => {
+ const suffix = reduceSubagentProgress(
+ null,
+ [event(2), event(3), event(4)],
+ 'detached',
+ false,
+ );
+ let progress = reduceSubagentReplay(suffix, [event(0)], false);
+ expect(progress?.contentParts).toEqual([{ type: 'text', text: '0,2,3,4,' }]);
+ expect(progress?.coverage).toBe('suffix');
+ expect(progress?.replaySegments?.map((segment) => [segment.from, segment.through])).toEqual([
+ [0, 0],
+ [2, 4],
+ ]);
+ const before = JSON.stringify(progress);
+ const next =
+ source === 'live'
+ ? reduceSubagentProgress(progress, [event(1)], 'detached', false)
+ : reduceSubagentReplay(
+ progress,
+ [event(0), event(1), event(2), event(3), event(4)],
+ false,
+ );
+ expect(JSON.stringify(progress)).toBe(before);
+ progress = next;
+ expect(progress?.contentParts).toEqual([{ type: 'text', text: '0,1,2,3,4,' }]);
+ expect(progress?.coverage).toBe('complete');
+ expect(progress?.replaySegments).toBeUndefined();
+ progress = reduceSubagentProgress(progress, [event(5)], 'detached', false);
+ expect(progress?.contentParts).toEqual([{ type: 'text', text: '0,1,2,3,4,5,' }]);
+ },
+ );
+ it('tracks multiple disjoint prefix ranges rather than inferring coverage from endpoints', () => {
+ let progress = reduceSubagentProgress(null, [event(6), event(7)], 'detached', false);
+ progress = reduceSubagentReplay(progress, [event(0), event(2), event(4)], false);
+ expect(progress?.coverage).toBe('suffix');
+ progress = reduceSubagentReplay(
+ progress,
+ Array.from({ length: 8 }, (_, i) => event(i)),
+ false,
+ );
+ expect(progress?.contentParts).toEqual([{ type: 'text', text: '0,1,2,3,4,5,6,7,' }]);
+ expect(progress?.coverage).toBe('complete');
+ expect(progress?.replaySegments).toBeUndefined();
+ });
+ it('clears an overflow fence once live frames fill the rejected interval', () => {
+ let progress = reduceSubagentProgress(
+ null,
+ Array.from({ length: 100 }, (_, i) => event(i + 2)),
+ 'detached',
+ true,
+ );
+ progress = reduceSubagentProgress(progress, [event(102), event(103)], 'detached', true);
+ progress = reduceSubagentProgress(progress, [event(0), event(1)], 'parent', true);
+ progress = reduceSubagentReplay(progress, [event(100), event(101)], false);
+ expect(progress?.activityReplayFrom).toBe(102);
+ progress = reduceSubagentProgress(progress, [event(102)], 'detached', true);
+ expect(progress?.activityReplayFrom).toBe(102);
+ progress = reduceSubagentProgress(progress, [event(103)], 'detached', true);
+ expect(progress?.activityReplayFrom).toBeUndefined();
+ progress = reduceSubagentProgress(progress, [event(104), event(105)], 'detached', false);
+ progress = reduceSubagentProgress(
+ progress,
+ [{ ...event(108), data: undefined, activityDroppedCount: 3 }],
+ 'detached',
+ progress?.activityReplayFrom != null,
+ );
+ expect(progress?.lastActivitySequence).toBe(108);
+ expect(progress?.droppedCount).toBe(3);
+ expect(progress?.pendingSequencedEvents).toBeUndefined();
+ });
+});
+
+describe('legacy event-child invocation coverage', () => {
+ const event = (sequence: number, invocation = 'generation-a') =>
+ update({
+ subagentRunId: 'event-task',
+ activityEventId: `event-task:${invocation}:${sequence}`,
+ activitySequence: undefined,
+ data: { delta: { content: [{ type: 'text', text: `${invocation}:${sequence},` }] } },
+ });
+ it.each([0, 3])('backfills an unsequenced rollout suffix when replay ends at %s', (end) => {
+ let progress = reduceSubagentProgress(null, [event(2), event(3)], 'detached', false);
+ progress = reduceSubagentReplay(
+ progress,
+ Array.from({ length: end + 1 }, (_, i) => event(i)),
+ false,
+ );
+ expect(progress?.contentParts).toEqual([
+ {
+ type: 'text',
+ text: `generation-a:0,${end === 0 ? '' : 'generation-a:1,'}generation-a:2,generation-a:3,`,
+ },
+ ]);
+ progress = reduceSubagentReplay(progress, [event(0), event(1), event(2), event(3)], false);
+ expect(progress?.contentParts).toEqual([
+ { type: 'text', text: 'generation-a:0,generation-a:1,generation-a:2,generation-a:3,' },
+ ]);
+ progress = reduceSubagentProgress(progress, [event(4)], 'detached', false);
+ expect(progress?.contentParts).toEqual([
+ {
+ type: 'text',
+ text: 'generation-a:0,generation-a:1,generation-a:2,generation-a:3,generation-a:4,',
+ },
+ ]);
+ expect(progress?.lastActivitySequence).toBeUndefined();
+ });
+ it('keeps prior and resumed invocations separate while restoring earlier frames within each', () => {
+ let progress = reduceSubagentProgress(
+ null,
+ [event(0), event(1), event(2, 'generation-b'), event(3, 'generation-b')],
+ 'detached',
+ false,
+ );
+ progress = reduceSubagentReplay(
+ progress,
+ [event(0, 'generation-b'), event(1, 'generation-b')],
+ false,
+ );
+ progress = reduceSubagentProgress(progress, [event(0, 'generation-c')], 'detached', false);
+ expect(progress?.contentParts).toEqual([
+ {
+ type: 'text',
+ text: 'generation-a:0,generation-a:1,generation-b:0,generation-b:1,generation-b:2,generation-b:3,generation-c:0,',
+ },
+ ]);
+ progress = reduceSubagentReplay(
+ progress,
+ [event(0), event(1), event(0, 'generation-c')],
+ false,
+ );
+ expect(progress?.contentParts).toEqual([
+ {
+ type: 'text',
+ text: 'generation-a:0,generation-a:1,generation-b:0,generation-b:1,generation-b:2,generation-b:3,generation-c:0,',
+ },
+ ]);
+ });
+});
+
+it('preserves compatibility updates while a numeric coverage gap is open', () => {
+ const event = (sequence: number) =>
+ update({
+ activityEventId: `mixed:${sequence}`,
+ activitySequence: sequence,
+ data: { delta: { content: [{ type: 'text', text: `${sequence},` }] } },
+ });
+ let progress = reduceSubagentProgress(null, [event(2), event(3)], 'detached', false);
+ progress = reduceSubagentReplay(progress, [event(0)], false);
+ progress = reduceSubagentProgress(
+ progress,
+ [
+ update({
+ activityEventId: 'older-provider',
+ activitySequence: undefined,
+ data: { delta: { content: [{ type: 'text', text: 'compat,' }] } },
+ }),
+ ],
+ 'detached',
+ false,
+ );
+ progress = reduceSubagentProgress(progress, [event(1)], 'detached', false);
+ expect(progress?.contentParts).toEqual([{ type: 'text', text: '0,1,2,3,compat,' }]);
+});
+
+describe('tool prefix metadata reconciliation', () => {
+ const start = (args: unknown) =>
+ update({
+ activityEventId: 'tool-fields:0',
+ activitySequence: 0,
+ phase: 'run_step',
+ data: {
+ id: 'step',
+ stepDetails: { type: 'tool_calls', tool_calls: [{ id: 'tool', name: 'search', args }] },
+ },
+ });
+ const complete = (fields: { args?: unknown; name?: string }) =>
+ update({
+ activityEventId: 'tool-fields:1',
+ activitySequence: 1,
+ phase: 'run_step_completed',
+ data: {
+ result: { id: 'step', tool_call: { id: 'tool', output: 'found', progress: 1, ...fields } },
+ },
+ });
+ it('preserves recovered inputs and names when completion synthesis omitted both', () => {
+ const end = complete({});
+ const suffix = reduceSubagentProgress(null, [end], 'detached', false);
+ expect(suffix?.contentParts[0]).toMatchObject({
+ tool_call: { argsUnavailable: true, nameUnavailable: true },
+ });
+ const progress = reduceSubagentReplay(suffix, [start({ query: 'release notes' }), end], false);
+ expect(progress?.contentParts[0]).toMatchObject({
+ tool_call: {
+ name: 'search',
+ args: '{"query":"release notes"}',
+ output: 'found',
+ progress: 1,
+ },
+ });
+ expect(progress?.contentParts[0]).toEqual(
+ reduceSubagentProgress(null, [start({ query: 'release notes' }), end], 'detached', false)
+ ?.contentParts[0],
+ );
+ });
+ it('keeps explicitly supplied empty args and a newer name instead of treating them as defaults', () => {
+ const end = complete({ args: {}, name: 'search_v2' });
+ const progress = reduceSubagentReplay(
+ reduceSubagentProgress(null, [end], 'detached', false),
+ [start({ query: 'release notes' }), end],
+ false,
+ );
+ expect(progress?.contentParts[0]).toMatchObject({
+ tool_call: { name: 'search_v2', args: '{}', output: 'found' },
+ });
+ });
+});
+
+describe('cumulative omission receipts independent of projection eviction', () => {
+ const marker = (sequence: number, invocation?: string) =>
+ update({
+ subagentRunId: 'event-task',
+ activityEventId:
+ invocation == null ? `omissions:${sequence}` : `event-task:${invocation}:${sequence}`,
+ activitySequence: invocation == null ? sequence : undefined,
+ activityDroppedCount: 3,
+ phase: 'message_delta',
+ data: undefined,
+ });
+ const text = (sequence: number, invocation?: string) => ({
+ ...marker(sequence, invocation),
+ activityDroppedCount: undefined,
+ data: { delta: { content: [{ type: 'text', text: 'x'.repeat(60_000) }] } },
+ });
+ it.each(['task', 'invocation'])(
+ 'retains nine omissions after large %s projections evict earlier markers',
+ (mode) => {
+ let progress = null as ReturnType<typeof reduceSubagentProgress>;
+ for (let index = 0; index < 3; index++) {
+ const invocation = mode === 'invocation' ? `generation-${index}` : undefined;
+ progress = reduceSubagentProgress(
+ progress,
+ [
+ marker(mode === 'task' ? index * 5 : 0, invocation),
+ text(mode === 'task' ? index * 5 + 1 : 1, invocation),
+ ],
+ 'detached',
+ false,
+ );
+ expect(progress?.droppedCount).toBe((index + 1) * 3);
+ }
+ const replay = [
+ marker(0, mode === 'invocation' ? 'generation-0' : undefined),
+ text(1, mode === 'invocation' ? 'generation-0' : undefined),
+ ];
+ progress = reduceSubagentReplay(progress, replay, false);
+ expect(progress?.droppedCount).toBe(9);
+ progress = reduceSubagentReplay(progress, replay, false);
+ expect(progress?.droppedCount).toBe(9);
+ expect(progress?.omissionEventKeys).toHaveLength(3);
+ expect(progress?.contentParts.length).toBeLessThanOrEqual(100);
+ expect(
+ new TextEncoder().encode(JSON.stringify(progress?.contentParts)).byteLength,
+ ).toBeLessThanOrEqual(65_536);
+ },
+ );
+});
+
+describe('measured tool timing replay provenance', () => {
+ const events = (identity: 'task' | 'invocation', completedAt = 8_000, completedStep = 'step') => {
+ const event = (
+ sequence: number,
+ phase: SubagentUpdateEvent['phase'],
+ data: SubagentUpdateEvent['data'],
+ ) =>
+ update({
+ subagentRunId: 'event-task',
+ activityEventId:
+ identity === 'task' ? `timing:${sequence}` : `event-task:timing-invocation:${sequence}`,
+ activitySequence: identity === 'task' ? sequence : undefined,
+ phase,
+ data,
+ });
+ return [
+ event(0, 'run_step', {
+ id: 'step',
+ stepDetails: {
+ type: 'tool_calls',
+ tool_calls: [{ id: 'tool', name: 'search', args: { query: 'release notes' } }],
+ },
+ }),
+ event(1, 'tool_preparation', { id: 'step', toolCallId: 'tool', observed_at: 1_000 }),
+ event(2, 'tool_calls_dispatched', {
+ dispatched_at: 3_000,
+ toolCalls: [{ id: 'tool', stepId: 'step' }],
+ }),
+ event(3, 'run_step_completed', {
+ result: {
+ id: completedStep,
+ completed_at: completedAt,
+ tool_call: { id: 'tool', output: 'found', progress: 1 },
+ },
+ }),
+ ];
+ };
+ it.each(['task', 'invocation'] as const)(
+ 'restores preparation and execution intervals from %s prefix replay',
+ (identity) => {
+ const lifecycle = events(identity);
+ const chronological = reduceSubagentProgress(null, lifecycle, 'detached', false);
+ let progress = reduceSubagentProgress(null, [lifecycle[3]], 'detached', false);
+ expect(progress?.contentParts[0]).toMatchObject({
+ tool_call: { stepId: 'step', toolCompletedAt: 8_000 },
+ });
+ expect(progress?.contentParts[0]).not.toHaveProperty('tool_call.toolPreparationDurationMs');
+ expect(progress?.contentParts[0]).not.toHaveProperty('tool_call.toolExecutionDurationMs');
+ const before = JSON.stringify(progress);
+ progress = reduceSubagentReplay(progress, lifecycle, false);
+ expect(progress?.contentParts).toEqual(chronological?.contentParts);
+ expect(progress?.contentParts[0]).toMatchObject({
+ tool_call: { toolPreparationDurationMs: 2_000, toolExecutionDurationMs: 5_000 },
+ });
+ expect(before).toContain('"toolCompletedAt":8000');
+ progress = reduceSubagentReplay(progress, lifecycle, false);
+ expect(progress?.contentParts).toEqual(chronological?.contentParts);
+ },
+ );
+ it.each(['task', 'invocation'] as const)(
+ 'keeps %s timing context through partial backfill and interior gap recovery',
+ (identity) => {
+ const lifecycle = events(identity);
+ let progress = reduceSubagentProgress(null, [lifecycle[3]], 'detached', false);
+ progress = reduceSubagentReplay(progress, lifecycle.slice(0, 2), false);
+ expect(progress?.contentParts[0]).not.toHaveProperty('tool_call.toolExecutionDurationMs');
+ progress = reduceSubagentReplay(progress, lifecycle, false);
+ expect(progress?.contentParts[0]).toMatchObject({
+ tool_call: { toolPreparationDurationMs: 2_000, toolExecutionDurationMs: 5_000 },
+ });
+ expect(progress?.contentParts).toEqual(
+ reduceSubagentProgress(null, lifecycle, 'detached', false)?.contentParts,
+ );
+ },
+ );
+ it.each(['task', 'invocation'] as const)(
+ 'does not present another step completion as measured %s intervals',
+ (identity) => {
+ const lifecycle = events(identity, 8_000, 'other-step');
+ const progress = reduceSubagentReplay(
+ reduceSubagentProgress(null, [lifecycle[3]], 'detached', false),
+ lifecycle,
+ false,
+ );
+ expect(progress?.contentParts[0]).not.toHaveProperty('tool_call.toolPreparationDurationMs');
+ expect(progress?.contentParts[0]).not.toHaveProperty('tool_call.toolExecutionDurationMs');
+ },
+ );
+ it.each([NaN, Infinity, -1, 2_000])(
+ 'rejects invalid or clock-skewed completion %s instead of inventing elapsed time',
+ (at) => {
+ const lifecycle = events('task', at);
+ const progress = reduceSubagentReplay(
+ reduceSubagentProgress(null, [lifecycle[3]], 'detached', false),
+ lifecycle,
+ false,
+ );
+ expect(progress?.contentParts[0]).toMatchObject({
+ tool_call: { toolPreparationDurationMs: 2_000 },
+ });
+ expect(progress?.contentParts[0]).not.toHaveProperty('tool_call.toolExecutionDurationMs');
+ },
+ );
+});
+
+describe('covered timing metadata reconciliation', () => {
+ const lifecycle = (identity: 'task' | 'invocation', invocation = 'generation-a') => {
+ const event = (
+ sequence: number,
+ phase: SubagentUpdateEvent['phase'],
+ data: SubagentUpdateEvent['data'],
+ ) =>
+ update({
+ subagentRunId: 'event-task',
+ activityEventId:
+ identity === 'task'
+ ? `covered-timing:${sequence}`
+ : `event-task:${invocation}:${sequence}`,
+ activitySequence: identity === 'task' ? sequence : undefined,
+ phase,
+ data,
+ });
+ return [
+ event(0, 'run_step', {
+ id: 'step',
+ stepDetails: {
+ type: 'tool_calls',
+ tool_calls: [{ id: 'tool', name: 'search', args: { query: 'release notes' } }],
+ },
+ }),
+ event(1, 'tool_preparation', { id: 'step', toolCallId: 'tool', observed_at: 1_000 }),
+ event(2, 'tool_calls_dispatched', {
+ dispatched_at: 3_000,
+ toolCalls: [{ id: 'tool', stepId: 'step' }],
+ }),
+ event(3, 'run_step_completed', {
+ result: {
+ id: 'step',
+ completed_at: 8_000,
+ tool_call: { id: 'tool', output: 'found', progress: 1 },
+ },
+ }),
+ ];
+ };
+ it.each(['task', 'invocation'] as const)(
+ 'restores discarded %s timing from every partial suffix',
+ (identity) => {
+ const full = lifecycle(identity);
+ const expected = reduceSubagentProgress(null, full, 'detached', false);
+ for (const start of [1, 2, 3]) {
+ let progress = reduceSubagentProgress(null, full.slice(start), 'detached', false);
+ expect(progress?.contentParts[0]).not.toHaveProperty('tool_call.toolExecutionDurationMs');
+ const original = JSON.stringify(progress);
+ const repaired = reduceSubagentReplay(progress, full, false);
+ expect(JSON.stringify(progress)).toBe(original);
+ progress = repaired;
+ expect(progress?.contentParts).toEqual(expected?.contentParts);
+ expect(progress?.contentParts[0]).toMatchObject({
+ tool_call: { toolPreparationDurationMs: 2_000, toolExecutionDurationMs: 5_000 },
+ });
+ progress = reduceSubagentReplay(progress, full, false);
+ expect(progress?.contentParts).toEqual(expected?.contentParts);
+ const next = {
+ ...full[3],
+ activityEventId: identity === 'task' ? 'covered-timing:4' : `event-task:generation-a:4`,
+ activitySequence: identity === 'task' ? 4 : undefined,
+ phase: 'message_delta' as const,
+ data: { delta: { content: [{ type: 'text', text: 'after' }] } },
+ };
+ progress = reduceSubagentProgress(progress, [next], 'detached', false);
+ expect(progress?.contentParts[0]).toEqual(expected?.contentParts[0]);
+ expect(progress?.contentParts[1]).toEqual({ type: 'text', text: 'after' });
+ }
+ },
+ );
+ it('does not borrow stamps from another event-child resume with reused tool and step IDs', () => {
+ const a = lifecycle('invocation', 'generation-a');
+ const b = lifecycle('invocation', 'generation-b');
+ b[2] = { ...b[2], data: { dispatched_at: 5_000, toolCalls: [{ id: 'tool', stepId: 'step' }] } };
+ let progress = reduceSubagentProgress(null, [...a.slice(2), ...b.slice(2)], 'detached', false);
+ progress = reduceSubagentReplay(progress, a, false);
+ const invocations = progress?.legacyReplayInvocations ?? [];
+ expect(invocations[0].progress.contentParts[0]).toMatchObject({
+ tool_call: { toolExecutionDurationMs: 5_000 },
+ });
+ expect(invocations[1].progress.contentParts[0]).not.toHaveProperty(
+ 'tool_call.toolExecutionDurationMs',
+ );
+ progress = reduceSubagentReplay(progress, b, false);
+ expect(progress?.legacyReplayInvocations?.[1].progress.contentParts[0]).toMatchObject({
+ tool_call: { toolExecutionDurationMs: 3_000 },
+ });
+ });
+ it('does not repair timing from another step or a post-completion handoff', () => {
+ const full = lifecycle('task');
+ const mismatched = {
+ ...full[2],
+ data: { dispatched_at: 3_000, toolCalls: [{ id: 'tool', stepId: 'wrong-step' }] },
+ };
+ const late = { ...full[2], activitySequence: 4, activityEventId: 'covered-timing:4' };
+ const original = reduceSubagentProgress(null, [full[3], late], 'detached', false);
+ const progress = reduceSubagentReplay(
+ original,
+ [full[0], full[1], mismatched, full[3], late],
+ false,
+ );
+ expect(progress?.contentParts[0]).not.toHaveProperty('tool_call.toolExecutionDurationMs');
+ });
+});
+
+describe('message-step phase replay provenance', () => {
+ const identity = (
+ sequence: number,
+ mode: 'task' | 'invocation',
+ invocation = 'generation-a',
+ ) => ({
+ subagentRunId: 'event-task',
+ activityEventId:
+ mode === 'task' ? `message-phase:${sequence}` : `event-task:${invocation}:${sequence}`,
+ activitySequence: mode === 'task' ? sequence : undefined,
+ });
+ const declaration = (
+ phase: 'commentary' | 'final_answer',
+ mode: 'task' | 'invocation',
+ step = 'message',
+ invocation = 'generation-a',
+ ) =>
+ update({
+ ...identity(0, mode, invocation),
+ phase: 'run_step',
+ data: { id: step, stepDetails: { type: 'message_creation', message_creation: { phase } } },
+ });
+ const text = (
+ sequence: number,
+ value: string,
+ mode: 'task' | 'invocation',
+ step = 'message',
+ invocation = 'generation-a',
+ ) =>
+ update({
+ ...identity(sequence, mode, invocation),
+ phase: 'message_delta',
+ data: { id: step, delta: { content: [{ type: 'text', text: value }] } },
+ });
+ it.each(['task', 'invocation'] as const)(
+ 'recovers %s phase before continuing a Markdown span',
+ (mode) => {
+ for (const phase of ['commentary', 'final_answer'] as const) {
+ const start = declaration(phase, mode);
+ const first = text(1, '**release', mode);
+ const last = text(2, ' notes**', mode);
+ let progress = reduceSubagentProgress(null, [first], 'detached', false);
+ expect(progress?.contentParts[0]).toEqual({
+ type: 'text',
+ text: '**release',
+ stepId: 'message',
+ });
+ const original = JSON.stringify(progress);
+ const repaired = reduceSubagentReplay(progress, [start, first], false);
+ expect(JSON.stringify(progress)).toBe(original);
+ progress = repaired;
+ expect(progress?.contentParts).toEqual([
+ { type: 'text', text: '**release', stepId: 'message', phase },
+ ]);
+ progress = reduceSubagentReplay(progress, [start, first], false);
+ progress = reduceSubagentProgress(progress, [last], 'detached', false);
+ expect(progress?.contentParts).toEqual([
+ { type: 'text', text: '**release notes**', stepId: 'message', phase },
+ ]);
+ expect(progress?.contentParts).toEqual(
+ reduceSubagentProgress(null, [start, first, last], 'detached', false)?.contentParts,
+ );
+ }
+ },
+ );
+ it('repairs a phase split already displayed before reconnect and rebases a following tool', () => {
+ const start = declaration('commentary', 'task');
+ const first = text(1, '**release', 'task');
+ const last = {
+ ...text(2, ' notes**', 'task'),
+ data: {
+ id: 'message',
+ delta: { content: [{ type: 'text', text: ' notes**', phase: 'commentary' }] },
+ },
+ };
+ const tool = update({
+ ...identity(3, 'task'),
+ phase: 'run_step',
+ data: {
+ id: 'tool-step',
+ stepDetails: { type: 'tool_calls', tool_calls: [{ id: 'tool', name: 'search', args: {} }] },
+ },
+ });
+ let progress = reduceSubagentProgress(null, [first, last, tool], 'detached', false);
+ expect(progress?.contentParts).toHaveLength(3);
+ progress = reduceSubagentReplay(progress, [start, first, last, tool], false);
+ expect(progress?.contentParts).toHaveLength(2);
+ expect(progress?.contentParts[0]).toEqual({
+ type: 'text',
+ text: '**release notes**',
+ phase: 'commentary',
+ stepId: 'message',
+ });
+ expect(progress?.aggregatorState.toolCallIndexById.tool).toBe(1);
+ progress = reduceSubagentProgress(
+ progress,
+ [
+ update({
+ ...identity(4, 'task'),
+ phase: 'run_step_completed',
+ data: {
+ result: { id: 'tool-step', tool_call: { id: 'tool', output: 'done', progress: 1 } },
+ },
+ }),
+ ],
+ 'detached',
+ false,
+ );
+ expect(progress?.contentParts[1]).toMatchObject({ tool_call: { output: 'done', progress: 1 } });
+ });
+ it('keeps independent message steps and explicit phases separate', () => {
+ const a = text(1, 'A', 'task', 'a');
+ const b = text(2, 'B', 'task', 'b');
+ let progress = reduceSubagentProgress(null, [a, b], 'detached', false);
+ expect(progress?.contentParts).toHaveLength(2);
+ progress = reduceSubagentReplay(
+ progress,
+ [declaration('commentary', 'task', 'a'), a, b],
+ false,
+ );
+ expect(progress?.contentParts).toEqual([
+ { type: 'text', text: 'A', stepId: 'a', phase: 'commentary' },
+ { type: 'text', text: 'B', stepId: 'b' },
+ ]);
+ const explicit = {
+ ...a,
+ data: { id: 'a', delta: { content: [{ type: 'text', text: 'A', phase: 'final_answer' }] } },
+ };
+ const explicitProgress = reduceSubagentReplay(
+ reduceSubagentProgress(null, [explicit], 'detached', false),
+ [declaration('commentary', 'task', 'a'), explicit],
+ false,
+ );
+ expect(explicitProgress?.contentParts[0]).toMatchObject({ phase: 'final_answer' });
+ });
+ it('recovers historical phase without reviving a closed message-step map', () => {
+ const start = declaration('commentary', 'task');
+ const first = text(1, 'first', 'task');
+ const close = update({
+ ...identity(2, 'task'),
+ phase: 'run_step_closed',
+ data: { id: 'message' },
+ });
+ const progress = reduceSubagentReplay(
+ reduceSubagentProgress(null, [first, close], 'detached', false),
+ [start, first, close],
+ false,
+ );
+ expect(progress?.contentParts[0]).toMatchObject({ phase: 'commentary', stepId: 'message' });
+ expect(progress?.aggregatorState.messagePhaseByStepId).not.toHaveProperty('message');
+ });
+ it('scopes recovered phase to its event-child invocation when step IDs are reused', () => {
+ const a = text(1, 'A', 'invocation', 'message', 'generation-a');
+ const b = text(1, 'B', 'invocation', 'message', 'generation-b');
+ let progress = reduceSubagentProgress(null, [a, b], 'detached', false);
+ progress = reduceSubagentReplay(
+ progress,
+ [declaration('commentary', 'invocation', 'message', 'generation-a'), a],
+ false,
+ );
+ expect(progress?.legacyReplayInvocations?.[0].progress.contentParts[0]).toMatchObject({
+ phase: 'commentary',
+ });
+ expect(progress?.legacyReplayInvocations?.[1].progress.contentParts[0]).not.toHaveProperty(
+ 'phase',
+ );
+ expect(progress?.contentParts).toEqual([
+ { type: 'text', text: 'A', stepId: 'message', phase: 'commentary' },
+ { type: 'text', text: 'B', stepId: 'message' },
+ ]);
+ progress = reduceSubagentReplay(
+ progress,
+ [declaration('final_answer', 'invocation', 'message', 'generation-b'), b],
+ false,
+ );
+ expect(progress?.legacyReplayInvocations?.[1].progress.contentParts[0]).toMatchObject({
+ phase: 'final_answer',
+ });
+ });
+ it('includes text provenance in the existing retention budgets', () => {
+ const parts = Array.from({ length: 110 }, (_, i) =>
+ text(i + 1, 'x'.repeat(1_000), 'task', `message-${i}`),
+ );
+ const progress = reduceSubagentProgress(null, parts, 'detached', false);
+ expect(progress?.contentParts.length).toBeLessThanOrEqual(100);
+ expect(
+ new TextEncoder().encode(JSON.stringify(progress?.contentParts)).byteLength,
+ ).toBeLessThanOrEqual(65_536);
+ expect(progress?.contentParts.at(-1)).toMatchObject({ stepId: 'message-109' });
+ });
+});
diff --git a/client/src/components/Chat/Subagents/state.ts b/client/src/components/Chat/Subagents/state.ts
index 8d0ffcd802..8373c3d6a3 100644
--- a/client/src/components/Chat/Subagents/state.ts
+++ b/client/src/components/Chat/Subagents/state.ts
@@ -1,7 +1,7 @@
import { useEffect } from 'react';
import { atomFamily } from 'jotai/utils';
import { atom, useAtomValue, useStore } from 'jotai';
-import { ContentTypes } from 'librechat-data-provider';
+import { ContentTypes, getToolTimingDurations } from 'librechat-data-provider';
import type {
PartMetadata,
SubagentControlReceipt,
@@ -18,6 +18,8 @@ import type {
SubagentTickerState,
} from '~/utils/subagentContent';
import {
+ reconcileSubagentMessagePhases,
+ reconcileSubagentToolTimings,
foldSubagentEvent,
foldSubagentEventIntoTicker,
initSubagentAggregatorState,
@@ -49,6 +51,10 @@ export interface SubagentProgress {
* runs + reasoning runs + tool calls), not by delta volume.
*/
contentParts: SubagentContentPart[];
+ /** Activity omitted by the bounded producer buffer during transport pressure. */
+ droppedCount?: number;
+ /** Marker receipts outlive content eviction, bounded like the delivery identity window. */
+ omissionEventKeys?: string[];
/** Cursor carried across `foldSubagentEvent` calls. */
aggregatorState: SubagentAggregatorState;
/** Ticker lines + live-cursor state, built incrementally. */
@@ -61,13 +67,34 @@ export interface SubagentProgress {
recentEventKeys?: string[];
/** Highest host sequence folded for this child run. Older overlap frames are ignored. */
lastActivitySequence?: number;
+ /** Earliest folded host sequence, used to distinguish backfill from a newer capped snapshot. */
+ firstActivitySequence?: number;
+ firstActivityEventId?: string;
+ /** Disjoint folded ranges, never raw history. Adjacent ranges collapse into one. */
+ replaySegments?: SubagentReplaySegment[];
+ legacyReplayInvocations?: Array<{
+ invocation: string;
+ progress: Omit<SubagentProgress, 'legacyReplayInvocations'>;
+ }>;
/** Bounded future frames waiting for an earlier sequence at the parent/detached handoff. */
pendingSequencedEvents?: SubagentUpdateEvent[];
+ /** Earliest rejected host sequence. A detached reader requests replay after parent close. */
+ activityReplayFrom?: number;
+ activityReplayThrough?: number;
/** Whether the folded events cover the run from its beginning or only the
* forward-only suffix observed after opening a detached task stream. */
coverage?: 'complete' | 'suffix';
}
+type SubagentReplaySegment = {
+ from: number;
+ through: number;
+ progress: Omit<
+ SubagentProgress,
+ 'replaySegments' | 'legacyReplayInvocations' | 'pendingSequencedEvents'
+ >;
+};
+
const MAX_RECENT_EVENT_KEYS = 256;
const MAX_PENDING_SEQUENCE_EVENTS = 100;
const MAX_PENDING_SEQUENCE_BYTES = 128 * 1024;
@@ -528,11 +555,43 @@ export function useSubagentProgress(invocationKey: string): SubagentProgress | n
const validActivitySequence = (value: number | undefined): value is number =>
Number.isSafeInteger(value) && value != null && value >= 0;
+function acceptedOmissions(
+ previous: SubagentProgress | null,
+ events: SubagentUpdateEvent[],
+): Pick<SubagentProgress, 'droppedCount' | 'omissionEventKeys'> {
+ let droppedCount = previous?.droppedCount ?? 0;
+ let keys = previous?.omissionEventKeys;
+ let seen: Set<string> | undefined;
+ for (const event of events) {
+ const count = event.activityDroppedCount;
+ if (!Number.isSafeInteger(count) || (count ?? 0) <= 0) continue;
+ const key = eventKey(event);
+ if (key != null) {
+ seen ??= new Set(keys);
+ if (seen.has(key)) continue;
+ }
+ droppedCount += count!;
+ if (key != null) {
+ seen!.add(key);
+ if (keys == null || keys === previous?.omissionEventKeys) keys = [...(keys ?? [])];
+ keys.push(key);
+ }
+ }
+ return {
+ droppedCount,
+ omissionEventKeys:
+ keys != null && keys.length > MAX_RECENT_EVENT_KEYS
+ ? keys.slice(-MAX_RECENT_EVENT_KEYS)
+ : keys,
+ };
+}
+
const foldAcceptedSubagentEvents = (
previous: SubagentProgress | null,
events: SubagentUpdateEvent[],
source: 'parent' | 'detached',
pendingSequencedEvents: SubagentUpdateEvent[],
+ projectingLegacy = false,
): SubagentProgress | null => {
if (events.length === 0) {
if (previous == null) {
@@ -566,6 +625,26 @@ const foldAcceptedSubagentEvents = (
...(pendingSequencedEvents.length === 0 ? {} : { pendingSequencedEvents }),
};
}
+ if (
+ !projectingLegacy &&
+ events.every((event) => event.activitySequence == null && eventLegacyOrdinal(event) != null)
+ )
+ return foldLegacyInvocations(previous, events, pendingSequencedEvents);
+ const firstSequence = events[0].activitySequence;
+ const priorSequence = previous?.lastActivitySequence;
+ const hasGap =
+ validActivitySequence(firstSequence) &&
+ validActivitySequence(priorSequence) &&
+ firstSequence > priorSequence + 1;
+ const batchGap = events.some(
+ (event, index) =>
+ index > 0 &&
+ validActivitySequence(event.activitySequence) &&
+ validActivitySequence(events[index - 1].activitySequence) &&
+ event.activitySequence !== events[index - 1].activitySequence! + 1,
+ );
+ if (previous?.replaySegments != null || hasGap || batchGap)
+ return foldReplaySegments(previous, events, pendingSequencedEvents);
const recentEventKeys = [...(previous?.recentEventKeys ?? [])];
for (const event of events) {
const key = eventKey(event);
@@ -576,6 +655,7 @@ const foldAcceptedSubagentEvents = (
let aggregatorState = previous?.aggregatorState ?? initSubagentAggregatorState();
let tickerState = previous?.tickerState ?? initSubagentTickerState();
let subagentKind = previous?.subagentKind;
+ const omissions = acceptedOmissions(previous, events);
for (const event of events) {
subagentKind = event.subagentKind ?? subagentKind;
const foldEvent =
@@ -618,7 +698,17 @@ const foldAcceptedSubagentEvents = (
contentParts,
aggregatorState,
tickerState,
+ activityReplayFrom: previous?.activityReplayFrom,
+ activityReplayThrough: previous?.activityReplayThrough,
+ legacyReplayInvocations: previous?.legacyReplayInvocations,
+ firstActivityEventId: previous?.firstActivityEventId ?? events[0].activityEventId,
+ firstActivitySequence:
+ previous?.subagentRunId === last.subagentRunId
+ ? (previous.firstActivitySequence ??
+ events.find((event) => validActivitySequence(event.activitySequence))?.activitySequence)
+ : events.find((event) => validActivitySequence(event.activitySequence))?.activitySequence,
status: last.phase,
+ ...omissions,
latestLabel: last.label ?? previous?.latestLabel,
recentEventKeys: boundedEventKeys,
...(effectiveActivitySequence == null
@@ -635,6 +725,9 @@ const foldAcceptedSubagentEvents = (
export function closeParentSubagentProgress(
previous: SubagentProgress | null,
): SubagentProgress | null {
+ if (previous?.activityReplayFrom != null) {
+ return previous;
+ }
if (previous?.pendingSequencedEvents == null || previous.pendingSequencedEvents.length === 0) {
return previous;
}
@@ -657,6 +750,26 @@ export function reduceSubagentProgress(
waitForEarlierSequences = source === 'parent',
): SubagentProgress | null {
if (events.length === 0) return previous;
+ const repair =
+ previous?.replaySegments != null
+ ? events.filter(
+ (event) =>
+ validActivitySequence(event.activitySequence) &&
+ event.activitySequence <= (previous.lastActivitySequence ?? -1) &&
+ !previous.replaySegments!.some(
+ (segment) =>
+ event.activitySequence! >= segment.from &&
+ event.activitySequence! <= segment.through,
+ ),
+ )
+ : [];
+ if (repair.length > 0) {
+ const repaired = foldReplaySegments(previous, repair, previous!.pendingSequencedEvents ?? []);
+ const remaining = events.filter((event) => !repair.includes(event));
+ return remaining.length === 0
+ ? releaseRecoveredActivity(repaired)
+ : reduceSubagentProgress(repaired, remaining, source, waitForEarlierSequences);
+ }
const recentEventKeys = [...(previous?.recentEventKeys ?? [])];
const seen = new Set(recentEventKeys);
const sequenced = events.every(
@@ -676,6 +789,8 @@ export function reduceSubagentProgress(
pending.map((event) => event.activitySequence).filter(validActivitySequence),
);
const directEvents: SubagentUpdateEvent[] = [];
+ let replayFrom = sameRun ? previous?.activityReplayFrom : undefined;
+ let replayThrough = sameRun ? previous?.activityReplayThrough : undefined;
let expected = lastActivitySequence == null ? 0 : lastActivitySequence + 1;
if (!waitForEarlierSequences && lastActivitySequence == null) {
const firstSequence = [...pending, ...orderedEvents]
@@ -702,7 +817,15 @@ export function reduceSubagentProgress(
const key = eventKey(event);
if (key != null && seen.has(key)) continue;
if (validActivitySequence(sequence)) {
- if (sequence < expected || pendingSequences.has(sequence)) continue;
+ if (sequence < expected) continue;
+ if (pendingSequences.has(sequence)) {
+ if ((event.activityDroppedCount ?? 0) > 0) {
+ const index = pending.findIndex((entry) => entry.activitySequence === sequence);
+ if (index >= 0 && (pending[index].activityDroppedCount ?? 0) === 0)
+ pending[index] = event;
+ }
+ continue;
+ }
if (sequence === expected) {
directEvents.push(event);
expected += 1;
@@ -713,6 +836,9 @@ export function reduceSubagentProgress(
) {
pending.push(event);
pendingSequences.add(sequence);
+ } else {
+ replayFrom = Math.min(replayFrom ?? sequence, sequence);
+ replayThrough = Math.max(replayThrough ?? sequence, sequence);
}
} else {
if (key != null) seen.add(key);
@@ -720,13 +846,524 @@ export function reduceSubagentProgress(
}
}
drainPending();
- if (
- !waitForEarlierSequences &&
- pending[0]?.activitySequence != null &&
- pending[0].activitySequence > expected
- ) {
+ while (!waitForEarlierSequences && pending[0]?.activitySequence != null) {
expected = pending[0].activitySequence;
drainPending();
}
- return foldAcceptedSubagentEvents(previous, directEvents, source, pending);
+ const progress = foldAcceptedSubagentEvents(previous, directEvents, source, pending);
+ if (progress == null) return progress;
+ if (
+ progress.activityReplayFrom === replayFrom &&
+ progress.activityReplayThrough === replayThrough
+ )
+ return releaseRecoveredActivity(progress);
+ return releaseRecoveredActivity({
+ ...progress,
+ activityReplayFrom: replayFrom,
+ activityReplayThrough: replayThrough,
+ });
+}
+
+/** Prefix events are new coverage, not a replacement for newer foreground parts.
+ * Reconcile bounded projections instead of retaining another raw event history. */
+function prependSubagentReplay(
+ previous: SubagentProgress,
+ prefix: SubagentProgress,
+ inheritMessagePhases = true,
+): SubagentProgress {
+ let parts = prefix.contentParts;
+ let state = inheritMessagePhases
+ ? prefix.aggregatorState
+ : { ...prefix.aggregatorState, messagePhaseByStepId: {}, idlessTextPhase: undefined };
+ const indices = new Map<number, number>();
+ for (let index = 0; index < previous.contentParts.length; index++) {
+ const part = previous.contentParts[index];
+ const event: SubagentUpdateEvent = {
+ runId: '',
+ subagentRunId: previous.subagentRunId,
+ subagentType: previous.subagentType,
+ subagentAgentId: previous.subagentAgentId ?? '',
+ phase: 'message_delta',
+ timestamp: '',
+ };
+ if (part.type === ContentTypes.TEXT) {
+ event.phase = 'message_delta';
+ event.data = {
+ ...(part.stepId == null ? {} : { id: part.stepId }),
+ delta: { content: [part] },
+ };
+ } else if (part.type === ContentTypes.THINK) {
+ event.phase = 'reasoning_delta';
+ event.data = { delta: { content: [part] } };
+ } else {
+ event.phase = 'run_step';
+ event.data = {
+ id: part.tool_call.stepId,
+ stepDetails: { type: 'tool_calls', tool_calls: [part.tool_call] },
+ };
+ }
+ ({ parts, state } = foldSubagentEvent(parts, state, event));
+ let target: number;
+ if (part.type === ContentTypes.TOOL_CALL) {
+ target = state.toolCallIndexById[part.tool_call.id];
+ const prefixTool = parts[target];
+ parts = parts.slice();
+ const sameStep =
+ prefixTool.type === ContentTypes.TOOL_CALL &&
+ prefixTool.tool_call.stepId != null &&
+ prefixTool.tool_call.stepId === part.tool_call.stepId;
+ const tool = {
+ ...(prefixTool.type === ContentTypes.TOOL_CALL ? prefixTool.tool_call : {}),
+ ...part.tool_call,
+ ...(part.tool_call.argsUnavailable &&
+ prefixTool.type === ContentTypes.TOOL_CALL &&
+ !prefixTool.tool_call.argsUnavailable
+ ? { args: prefixTool.tool_call.args, argsUnavailable: undefined }
+ : {}),
+ ...(part.tool_call.nameUnavailable &&
+ prefixTool.type === ContentTypes.TOOL_CALL &&
+ !prefixTool.tool_call.nameUnavailable
+ ? { name: prefixTool.tool_call.name, nameUnavailable: undefined }
+ : {}),
+ };
+ /** Inputs can backfill by tool identity; measured times require the exact step. */
+ if (!sameStep) {
+ for (const key of [
+ 'toolPreparationStartedAt',
+ 'toolDispatchedAt',
+ 'toolCompletedAt',
+ 'toolPreparationDurationMs',
+ 'toolExecutionDurationMs',
+ ] as const) {
+ const stamp = part.tool_call[key];
+ if (stamp == null) delete tool[key];
+ else tool[key] = stamp;
+ }
+ }
+ parts[target] = {
+ ...part,
+ tool_call: {
+ ...tool,
+ ...getToolTimingDurations({
+ observedAt: tool.toolPreparationStartedAt,
+ dispatchedAt: tool.toolDispatchedAt,
+ completedAt: tool.toolCompletedAt,
+ }),
+ },
+ };
+ } else target = part.type === ContentTypes.TEXT ? state.openTextIdx! : state.openThinkIdx!;
+ indices.set(index, target);
+ }
+ const bounded = boundContentParts(parts, {
+ ...previous.aggregatorState,
+ messagePhaseByStepId: inheritMessagePhases
+ ? {
+ ...prefix.aggregatorState.messagePhaseByStepId,
+ ...previous.aggregatorState.messagePhaseByStepId,
+ }
+ : previous.aggregatorState.messagePhaseByStepId,
+ openTextIdx:
+ previous.aggregatorState.openTextIdx == null
+ ? null
+ : (indices.get(previous.aggregatorState.openTextIdx) ?? null),
+ openThinkIdx:
+ previous.aggregatorState.openThinkIdx == null
+ ? null
+ : (indices.get(previous.aggregatorState.openThinkIdx) ?? null),
+ });
+ const offset = prefix.tickerState.lines.length;
+ return {
+ ...previous,
+ contentParts: bounded.parts,
+ aggregatorState: bounded.state,
+ tickerState: boundTickerState({
+ ...previous.tickerState,
+ lines: [...prefix.tickerState.lines, ...previous.tickerState.lines],
+ textLineIdx:
+ previous.tickerState.textLineIdx == null ? null : previous.tickerState.textLineIdx + offset,
+ thinkLineIdx:
+ previous.tickerState.thinkLineIdx == null
+ ? null
+ : previous.tickerState.thinkLineIdx + offset,
+ }),
+ firstActivitySequence: prefix.firstActivitySequence,
+ firstActivityEventId: prefix.firstActivityEventId,
+ recentEventKeys: [...(prefix.recentEventKeys ?? []), ...(previous.recentEventKeys ?? [])].slice(
+ -MAX_RECENT_EVENT_KEYS,
+ ),
+ droppedCount: (prefix.droppedCount ?? 0) + (previous.droppedCount ?? 0),
+ coverage: previous.coverage,
+ };
+}
+
+function releaseRecoveredActivity(progress: SubagentProgress): SubagentProgress {
+ const from = progress.activityReplayFrom;
+ const through = progress.activityReplayThrough;
+ if (from == null || through == null) return progress;
+ const ranges = progress.replaySegments ?? [
+ { from: progress.firstActivitySequence ?? 0, through: progress.lastActivitySequence ?? -1 },
+ ];
+ if (!ranges.some((range) => range.from <= from && range.through >= through)) return progress;
+ return { ...progress, activityReplayFrom: undefined, activityReplayThrough: undefined };
+}
+
+function foldReplaySegments(
+ previous: SubagentProgress | null,
+ events: SubagentUpdateEvent[],
+ pending: SubagentUpdateEvent[],
+): SubagentProgress {
+ const segments = (previous?.replaySegments ?? []).map((segment) => ({ ...segment }));
+ if (
+ segments.length === 0 &&
+ previous != null &&
+ previous.firstActivitySequence != null &&
+ previous.lastActivitySequence != null
+ ) {
+ const {
+ replaySegments: _segments,
+ legacyReplayInvocations: _legacy,
+ pendingSequencedEvents: _pending,
+ ...progress
+ } = previous;
+ segments.push({
+ from: previous.firstActivitySequence,
+ through: previous.lastActivitySequence,
+ progress,
+ });
+ }
+ const accepted: SubagentUpdateEvent[] = [];
+ const ordered = [...events].sort(
+ (left, right) => (left.activitySequence ?? 0) - (right.activitySequence ?? 0),
+ );
+ for (const event of ordered) {
+ const sequence = event.activitySequence;
+ if (!validActivitySequence(sequence)) {
+ const latest = segments[segments.length - 1];
+ if (latest != null) {
+ const key = eventKey(event);
+ if (key != null && latest.progress.recentEventKeys?.includes(key)) continue;
+ accepted.push(event);
+ latest.progress = foldAcceptedSubagentEvents(latest.progress, [event], 'detached', [])!;
+ }
+ continue;
+ }
+ if (segments.some((segment) => sequence >= segment.from && sequence <= segment.through))
+ continue;
+ accepted.push(event);
+ const preceding = segments.find((segment) => segment.through === sequence - 1);
+ if (preceding != null) {
+ preceding.progress = foldAcceptedSubagentEvents(preceding.progress, [event], 'detached', [])!;
+ preceding.through = sequence;
+ } else {
+ const progress = foldAcceptedSubagentEvents(null, [event], 'detached', [])!;
+ segments.push({ from: sequence, through: sequence, progress });
+ }
+ segments.sort((left, right) => left.from - right.from);
+ for (let index = 1; index < segments.length; ) {
+ const left = segments[index - 1];
+ const right = segments[index];
+ if (left.through + 1 !== right.from) {
+ index++;
+ continue;
+ }
+ left.progress = prependSubagentReplay(right.progress, left.progress);
+ left.through = right.through;
+ segments.splice(index, 1);
+ }
+ }
+ /** Sum projection budgets before retaining ranges. Trimming old ranges cannot erase
+ * newer displayed content; dropped coverage is not treated as a continuous prefix. */
+ let items = 0;
+ let bytes = 0;
+ let keepFrom = segments.length;
+ for (let index = segments.length - 1; index >= 0; index--) {
+ const progress = segments[index].progress;
+ const addedBytes = encodedBytes(progress.contentParts) + encodedBytes(progress.tickerState);
+ if (
+ items + progress.contentParts.length > MAX_LIVE_ACTIVITY_ITEMS ||
+ bytes + addedBytes > 2 * MAX_LIVE_ACTIVITY_BYTES
+ )
+ break;
+ items += progress.contentParts.length;
+ bytes += addedBytes;
+ keepFrom = index;
+ }
+ if (keepFrom > 0) segments.splice(0, Math.min(keepFrom, segments.length - 1));
+ while (segments.length > MAX_LIVE_ACTIVITY_ITEMS) segments.shift();
+ const latest = segments[segments.length - 1];
+ let projection: SubagentProgress = latest.progress;
+ for (let index = segments.length - 2; index >= 0; index--)
+ projection = prependSubagentReplay(projection, segments[index].progress);
+ return {
+ ...projection,
+ ...acceptedOmissions(previous, accepted),
+ pendingSequencedEvents: pending.length === 0 ? undefined : pending,
+ activityReplayFrom: previous?.activityReplayFrom,
+ activityReplayThrough: previous?.activityReplayThrough,
+ coverage: segments.length === 1 && segments[0].from === 0 ? 'complete' : 'suffix',
+ replaySegments: segments.length === 1 ? undefined : segments,
+ };
+}
+
+/** Event-child IDs include a generation invocation and ordinal, deliberately without
+ * a task-wide sequence. Use observed identity anchors, not a synthetic resume counter. */
+function legacyOrdinal(
+ id: string | undefined,
+): { invocation: string; ordinal: number } | undefined {
+ if (id == null) return undefined;
+ const split = id.lastIndexOf(':');
+ const ordinal = Number(id.slice(split + 1));
+ if (split < 0 || !/^\d+$/.test(id.slice(split + 1)) || !Number.isSafeInteger(ordinal))
+ return undefined;
+ return { invocation: id.slice(0, split), ordinal };
+}
+
+function eventLegacyOrdinal(
+ event: SubagentUpdateEvent,
+): { invocation: string; ordinal: number } | undefined {
+ const order = legacyOrdinal(event.activityEventId);
+ return order != null && order.invocation.startsWith(`${event.subagentRunId}:`)
+ ? order
+ : undefined;
+}
+
+function foldLegacyInvocations(
+ previous: SubagentProgress | null,
+ events: SubagentUpdateEvent[],
+ pending: SubagentUpdateEvent[],
+ replay = false,
+): SubagentProgress {
+ const invocations = (previous?.legacyReplayInvocations ?? []).map((entry) => ({ ...entry }));
+ const accepted: SubagentUpdateEvent[] = [];
+ const order = Array.from(new Set(events.map((event) => eventLegacyOrdinal(event)!.invocation)));
+ for (const event of events) {
+ const cursor = eventLegacyOrdinal(event)!;
+ let entry = invocations.find((item) => item.invocation === cursor.invocation);
+ const normalized = { ...event, activitySequence: cursor.ordinal };
+ if (entry == null) {
+ accepted.push(event);
+ const progress = foldAcceptedSubagentEvents(null, [normalized], 'detached', [], true)!;
+ entry = { invocation: cursor.invocation, progress };
+ invocations.push(entry);
+ } else {
+ const ranges = entry.progress.replaySegments ?? [
+ {
+ from: entry.progress.firstActivitySequence ?? 0,
+ through: entry.progress.lastActivitySequence ?? -1,
+ },
+ ];
+ if (ranges.some((range) => cursor.ordinal >= range.from && cursor.ordinal <= range.through))
+ continue;
+ accepted.push(event);
+ if (cursor.ordinal <= (entry.progress.lastActivitySequence ?? -1))
+ entry.progress = foldReplaySegments(entry.progress, [normalized], []);
+ else
+ entry.progress = foldAcceptedSubagentEvents(
+ entry.progress,
+ [normalized],
+ 'detached',
+ [],
+ true,
+ )!;
+ }
+ }
+ if (replay) {
+ const byInvocation = new Map<string, SubagentUpdateEvent[]>();
+ for (const event of events) {
+ const invocation = eventLegacyOrdinal(event)!.invocation;
+ const group = byInvocation.get(invocation);
+ if (group == null) byInvocation.set(invocation, [event]);
+ else group.push(event);
+ }
+ for (const entry of invocations) {
+ const lifecycle = byInvocation.get(entry.invocation);
+ if (lifecycle != null)
+ entry.progress = reconcileReplayTiming(
+ entry.progress,
+ lifecycle.filter(
+ (event) =>
+ eventLegacyOrdinal(event)!.ordinal <= (entry.progress.lastActivitySequence ?? -1),
+ ),
+ );
+ }
+ const anchored = (previous?.legacyReplayInvocations ?? []).map((entry) => entry.invocation);
+ for (let index = 0; index < order.length; index++) {
+ const invocation = order[index];
+ if (anchored.includes(invocation)) continue;
+ const nextKnown = order.slice(index + 1).find((next) => anchored.includes(next));
+ const position = nextKnown == null ? anchored.length : anchored.indexOf(nextKnown);
+ anchored.splice(position, 0, invocation);
+ }
+ invocations.sort(
+ (left, right) => anchored.indexOf(left.invocation) - anchored.indexOf(right.invocation),
+ );
+ }
+ let items = 0;
+ let bytes = 0;
+ let keepFrom = invocations.length;
+ for (let index = invocations.length - 1; index >= 0; index--) {
+ const progress = invocations[index].progress;
+ const added = encodedBytes(progress.contentParts) + encodedBytes(progress.tickerState);
+ if (
+ items + progress.contentParts.length > MAX_LIVE_ACTIVITY_ITEMS ||
+ bytes + added > 2 * MAX_LIVE_ACTIVITY_BYTES
+ )
+ break;
+ items += progress.contentParts.length;
+ bytes += added;
+ keepFrom = index;
+ }
+ if (keepFrom > 0) invocations.splice(0, Math.min(keepFrom, invocations.length - 1));
+ while (invocations.length > MAX_LIVE_ACTIVITY_ITEMS) invocations.shift();
+ let projection: SubagentProgress = invocations[invocations.length - 1].progress;
+ for (let index = invocations.length - 2; index >= 0; index--)
+ projection = prependSubagentReplay(projection, invocations[index].progress, false);
+ return {
+ ...projection,
+ ...acceptedOmissions(previous, accepted),
+ firstActivitySequence: undefined,
+ lastActivitySequence: undefined,
+ replaySegments: undefined,
+ pendingSequencedEvents: pending.length === 0 ? undefined : pending,
+ legacyReplayInvocations: invocations,
+ coverage: invocations.every((entry) => entry.progress.coverage === 'complete')
+ ? 'complete'
+ : 'suffix',
+ };
+}
+
+function reconcileReplayTiming(
+ progress: SubagentProgress,
+ events: SubagentUpdateEvent[],
+): SubagentProgress {
+ const observed = events.filter(
+ (event) =>
+ event.subagentRunId === progress.subagentRunId &&
+ (event.activitySequence == null ||
+ event.activitySequence <= (progress.lastActivitySequence ?? -1)),
+ );
+ const phased = reconcileSubagentMessagePhases(
+ progress.contentParts,
+ progress.aggregatorState,
+ observed,
+ );
+ const parts = reconcileSubagentToolTimings(phased.parts, observed);
+ const segments = progress.replaySegments?.map((segment) => {
+ const updated = reconcileReplayTiming(segment.progress, events);
+ return updated === segment.progress ? segment : { ...segment, progress: updated };
+ });
+ const segmentsChanged =
+ segments?.some((segment, index) => segment !== progress.replaySegments?.[index]) ?? false;
+ if (
+ parts === progress.contentParts &&
+ phased.state === progress.aggregatorState &&
+ !segmentsChanged
+ )
+ return progress;
+ if (segmentsChanged)
+ return foldReplaySegments(
+ { ...progress, replaySegments: segments },
+ [],
+ progress.pendingSequencedEvents ?? [],
+ );
+ const bounded =
+ parts === progress.contentParts
+ ? { parts, state: phased.state }
+ : boundContentParts(parts, phased.state);
+ return {
+ ...progress,
+ contentParts: bounded.parts,
+ aggregatorState: bounded.state,
+ };
+}
+
+/** Reconcile snapshot coverage and bounded client overflow without advancing past an open parent. */
+export function reduceSubagentReplay(
+ previous: SubagentProgress | null,
+ events: SubagentUpdateEvent[],
+ parentOpen: boolean,
+): SubagentProgress | null {
+ if (events.length === 0) {
+ const from = previous?.activityReplayFrom;
+ const through = previous?.activityReplayThrough;
+ if (parentOpen || previous == null || from == null || through == null) return previous;
+ const start = Math.max(from, (previous.lastActivitySequence ?? -1) + 1);
+ const retainedPending = (previous.pendingSequencedEvents ?? []).filter(
+ (event) =>
+ event.activitySequence != null &&
+ event.activitySequence >= start &&
+ event.activitySequence <= through,
+ ).length;
+ const omitted = Math.max(0, through - start + 1 - retainedPending);
+ const acknowledged = closeParentSubagentProgress({
+ ...previous,
+ activityReplayFrom: undefined,
+ activityReplayThrough: undefined,
+ });
+ if (acknowledged == null || omitted === 0) return acknowledged;
+ if ((acknowledged.lastActivitySequence ?? -1) >= through)
+ return { ...acknowledged, droppedCount: (acknowledged.droppedCount ?? 0) + omitted };
+ /** The retained window expired. Count the rejected range and resume later live frames. */
+ return reduceSubagentProgress(
+ acknowledged,
+ [
+ {
+ runId: '',
+ subagentRunId: previous.subagentRunId,
+ subagentType: previous.subagentType,
+ subagentAgentId: previous.subagentAgentId ?? '',
+ activityEventId: `client-overflow:${through}`,
+ activitySequence: through,
+ activityDroppedCount: omitted,
+ phase: 'message_delta',
+ timestamp: new Date().toISOString(),
+ },
+ ],
+ 'detached',
+ false,
+ );
+ }
+ const firstSequence = events[0].activitySequence;
+ const sameRun = previous?.subagentRunId === events[0].subagentRunId;
+ let base: SubagentProgress | null = sameRun ? previous : null;
+ if (base != null) {
+ if (events.every((event) => validActivitySequence(event.activitySequence))) {
+ const backfill = events.filter(
+ (event) =>
+ event.activitySequence! <= (base!.lastActivitySequence ?? -1) &&
+ !(
+ base!.replaySegments ?? [
+ { from: base!.firstActivitySequence ?? 0, through: base!.lastActivitySequence ?? -1 },
+ ]
+ ).some(
+ (range) =>
+ event.activitySequence! >= range.from && event.activitySequence! <= range.through,
+ ),
+ );
+ if (backfill.length > 0)
+ base = foldReplaySegments(base, backfill, base.pendingSequencedEvents ?? []);
+ } else if (events.every((event) => eventLegacyOrdinal(event) != null))
+ return foldLegacyInvocations(base, events, base.pendingSequencedEvents ?? [], true);
+ }
+ const folded = reduceSubagentProgress(base, events, 'detached', parentOpen);
+ if (folded == null) return previous;
+ const progress = reconcileReplayTiming(folded, events);
+ const missing = sameRun ? previous?.activityReplayFrom : undefined;
+ if (parentOpen || missing == null || (progress.lastActivitySequence ?? -1) < missing)
+ return progress;
+ const start = Math.max(missing, (base?.lastActivitySequence ?? -1) + 1);
+ const retainedPending = (base?.pendingSequencedEvents ?? []).filter(
+ (event) =>
+ event.activitySequence != null &&
+ event.activitySequence >= start &&
+ event.activitySequence < (firstSequence ?? start),
+ ).length;
+ return {
+ ...progress,
+ activityReplayFrom: undefined,
+ activityReplayThrough: undefined,
+ droppedCount:
+ (progress.droppedCount ?? 0) +
+ Math.max(0, (firstSequence ?? start) - start - retainedPending),
+ };
}
diff --git a/client/src/data-provider/Subagents/useSubagentActivityStream.test.tsx b/client/src/data-provider/Subagents/useSubagentActivityStream.test.tsx
index b67fd32080..b411c088ec 100644
--- a/client/src/data-provider/Subagents/useSubagentActivityStream.test.tsx
+++ b/client/src/data-provider/Subagents/useSubagentActivityStream.test.tsx
@@ -4,6 +4,8 @@ import { act, renderHook } from '@testing-library/react';
import { ContentTypes, QueryKeys, StepEvents } from 'librechat-data-provider';
import type { ActiveSubagentPanel } from '~/components/Chat/Subagents/state';
import {
+ reduceSubagentProgress,
+ closeParentSubagentProgress,
subagentParentStreamOpenByToolCallId,
subagentProgressByToolCallId,
subagentProgressKey,
@@ -76,6 +78,49 @@ describe('useSubagentActivityStream', () => {
takeRegisteredSubagentProgressKeys();
});
+ it('backfills a late foreground bucket even when its coverage was marked complete', () => {
+ const { result } = renderHook(
+ () => {
+ const progressAtom = subagentProgressByToolCallId(
+ subagentProgressKey(selection.parentMessageId, selection.toolCallId, selection.partIndex),
+ );
+ const setProgress = useSetAtom(progressAtom);
+ useSubagentActivityStream(selection);
+ return { progress: useAtomValue(progressAtom), setProgress };
+ },
+ { wrapper },
+ );
+ const event = (sequence: number) => ({
+ event: StepEvents.ON_SUBAGENT_UPDATE,
+ data: {
+ runId: 'parent',
+ subagentRunId: 'child',
+ subagentType: 'researcher',
+ subagentAgentId: 'agent-1',
+ parentToolCallId: selection.toolCallId,
+ activityEventId: `task:${sequence}`,
+ activitySequence: sequence,
+ phase: 'message_delta' as const,
+ timestamp: '2026-09-29T00:00:00.000Z',
+ data: { delta: { content: [{ type: 'text', text: `${sequence}` }] } },
+ },
+ });
+ act(() =>
+ result.current.setProgress(
+ closeParentSubagentProgress(reduceSubagentProgress(null, [event(2).data], 'parent', true)),
+ ),
+ );
+ expect(result.current.progress?.coverage).toBe('complete');
+ expect(result.current.progress?.firstActivitySequence).toBe(2);
+ act(() =>
+ streams[0].emit('message', {
+ event: 'subagent_activity_replay',
+ data: [event(0), event(1), event(2)],
+ }),
+ );
+ expect(result.current.progress?.contentParts).toEqual([{ type: 'text', text: '012' }]);
+ });
+
it('opens one authorized task stream and closes after terminal delivery', () => {
const { result, unmount } = renderHook(
() => {
@@ -142,6 +187,192 @@ describe('useSubagentActivityStream', () => {
expect(streams[0]?.close).toHaveBeenCalledTimes(1);
});
+ it('folds a replay batch before live activity and deduplicates a reconnect snapshot', () => {
+ const { result } = renderHook(
+ () => {
+ useSubagentActivityStream(selection);
+ return useAtomValue(
+ subagentProgressByToolCallId(
+ subagentProgressKey(
+ selection.parentMessageId,
+ selection.toolCallId,
+ selection.partIndex,
+ ),
+ ),
+ );
+ },
+ { wrapper },
+ );
+ const event = (sequence: number, phase = 'message_delta') => ({
+ event: StepEvents.ON_SUBAGENT_UPDATE,
+ data: {
+ runId: 'parent',
+ subagentRunId: 'child',
+ subagentType: 'researcher',
+ subagentAgentId: 'agent-1',
+ parentToolCallId: selection.toolCallId,
+ activityEventId: `task:${sequence}`,
+ activitySequence: sequence,
+ phase,
+ timestamp: '2026-09-29T00:00:00.000Z',
+ data: (() => {
+ if (phase === 'reasoning_delta')
+ return { delta: { content: [{ type: 'think', think: 'Reasoning' }] } };
+ if (phase === 'run_step')
+ return {
+ id: 'step',
+ stepDetails: {
+ type: 'tool_calls',
+ tool_calls: [{ id: 'call', name: 'execute_code', args: { code: '1' } }],
+ },
+ };
+ return { delta: { content: [{ type: 'text', text: `text-${sequence}` }] } };
+ })(),
+ },
+ });
+ const backlog = [event(0, 'reasoning_delta'), event(1, 'run_step'), event(2)];
+ act(() => {
+ streams[0].emit('message', { event: 'subagent_activity_replay', data: backlog });
+ });
+ expect(result.current?.contentParts.map((part) => part.type)).toEqual([
+ 'think',
+ 'tool_call',
+ 'text',
+ ]);
+ act(() => {
+ streams[0].emit('message', event(3));
+ });
+ expect(result.current?.contentParts[2]).toEqual({ type: 'text', text: 'text-2text-3' });
+ act(() => {
+ streams[0].emit('message', {
+ event: 'subagent_activity_replay',
+ data: [...backlog, event(3)],
+ });
+ });
+ expect(result.current?.contentParts[2]).toEqual({ type: 'text', text: 'text-2text-3' });
+ expect(result.current?.lastActivitySequence).toBe(3);
+ act(() => {
+ streams[0].emit('message', { ...event(6), droppedCount: 2 });
+ });
+ expect(result.current?.droppedCount).toBe(2);
+ expect(result.current?.lastActivitySequence).toBe(6);
+ });
+
+ it('preserves a displayed tool and text when a capped reconnect snapshot starts later', () => {
+ const { result } = renderHook(
+ () => {
+ useSubagentActivityStream(selection);
+ return useAtomValue(
+ subagentProgressByToolCallId(
+ subagentProgressKey(
+ selection.parentMessageId,
+ selection.toolCallId,
+ selection.partIndex,
+ ),
+ ),
+ );
+ },
+ { wrapper },
+ );
+ const event = (sequence: number) => ({
+ event: StepEvents.ON_SUBAGENT_UPDATE,
+ data: {
+ runId: 'parent',
+ subagentRunId: 'child',
+ subagentType: 'researcher',
+ subagentAgentId: 'agent-1',
+ parentToolCallId: selection.toolCallId,
+ activityEventId: `task:${sequence}`,
+ activitySequence: sequence,
+ phase: sequence === 10 ? 'run_step' : 'message_delta',
+ timestamp: '2026-09-29T00:00:00.000Z',
+ data:
+ sequence === 10
+ ? {
+ id: 'step',
+ stepDetails: {
+ type: 'tool_calls',
+ tool_calls: [{ id: 'old-tool', name: 'execute_code', args: {} }],
+ },
+ }
+ : { delta: { content: [{ type: 'text', text: `${sequence},` }] } },
+ },
+ });
+ act(() => {
+ streams[0].emit('message', {
+ event: 'subagent_activity_replay',
+ data: Array.from({ length: 100 }, (_, i) => event(i + 10)),
+ });
+ });
+ for (let sequence = 110; sequence < 120; sequence++)
+ act(() => {
+ streams[0].emit('message', event(sequence));
+ });
+ const before = result.current?.contentParts;
+ expect(result.current?.firstActivitySequence).toBe(10);
+ act(() => {
+ streams[0].emit('message', {
+ event: 'subagent_activity_replay',
+ data: Array.from({ length: 100 }, (_, i) => event(i + 20)),
+ });
+ });
+ expect(result.current?.contentParts).toEqual(before);
+ expect(result.current?.contentParts[0]).toMatchObject({
+ type: 'tool_call',
+ tool_call: { id: 'old-tool' },
+ });
+ expect(result.current?.firstActivitySequence).toBe(10);
+ act(() => {
+ streams[0].emit('message', event(120));
+ });
+ expect(result.current?.lastActivitySequence).toBe(120);
+ });
+
+ it('replaces an incomplete suffix with the retained snapshot on reconnect', () => {
+ const { result } = renderHook(
+ () => {
+ useSubagentActivityStream(selection);
+ return useAtomValue(
+ subagentProgressByToolCallId(
+ subagentProgressKey(
+ selection.parentMessageId,
+ selection.toolCallId,
+ selection.partIndex,
+ ),
+ ),
+ );
+ },
+ { wrapper },
+ );
+ const event = (sequence: number) => ({
+ event: StepEvents.ON_SUBAGENT_UPDATE,
+ data: {
+ runId: 'parent',
+ subagentRunId: 'child',
+ subagentType: 'researcher',
+ subagentAgentId: 'agent-1',
+ parentToolCallId: selection.toolCallId,
+ activityEventId: `task:${sequence}`,
+ activitySequence: sequence,
+ phase: 'message_delta',
+ timestamp: '2026-09-29T00:00:00.000Z',
+ data: { delta: { content: [{ type: 'text', text: `${sequence}` }] } },
+ },
+ });
+ act(() => {
+ streams[0].emit('message', event(2));
+ });
+ expect(result.current?.coverage).toBe('suffix');
+ act(() => {
+ streams[0].emit('message', {
+ event: 'subagent_activity_replay',
+ data: [event(0), event(1), event(2)],
+ });
+ });
+ expect(result.current?.contentParts).toEqual([{ type: 'text', text: '012' }]);
+ expect(result.current?.coverage).toBe('complete');
+ });
+
it('accepts an exact task-stream update when older providers omit the optional tool-call id', () => {
const { result } = renderHook(
() => {
@@ -180,6 +411,107 @@ describe('useSubagentActivityStream', () => {
expect(result.current?.contentParts).toEqual([{ type: 'text', text: 'Compatible update' }]);
});
+ it('keeps a capped replay pending until delayed parent activity backfills it', () => {
+ const active = { ...selection, isSubmitting: true };
+ const { result } = renderHook(
+ () => {
+ const progressAtom = subagentProgressByToolCallId(
+ subagentProgressKey(active.parentMessageId, active.toolCallId, active.partIndex),
+ );
+ useSubagentActivityStream(active);
+ return {
+ progress: useAtomValue(progressAtom),
+ setProgress: useSetAtom(progressAtom),
+ closeParent: useSetAtom(
+ subagentParentStreamOpenByToolCallId(
+ subagentProgressKey(active.parentMessageId, active.toolCallId, active.partIndex),
+ ),
+ ),
+ };
+ },
+ { wrapper },
+ );
+ const event = (sequence: number) => ({
+ event: StepEvents.ON_SUBAGENT_UPDATE,
+ data: {
+ runId: 'parent',
+ subagentRunId: 'child',
+ subagentType: 'researcher',
+ subagentAgentId: 'agent-1',
+ parentToolCallId: active.toolCallId,
+ activityEventId: `task:${sequence}`,
+ activitySequence: sequence,
+ phase: 'message_delta' as const,
+ timestamp: '2026-09-29T00:00:00.000Z',
+ data: { delta: { content: [{ type: 'text', text: `${sequence}` }] } },
+ },
+ });
+ act(() =>
+ streams[0].emit('message', { event: 'subagent_activity_replay', data: [event(2), event(3)] }),
+ );
+ expect(result.current.progress?.contentParts).toEqual([]);
+ expect(result.current.progress?.pendingSequencedEvents).toHaveLength(2);
+ act(() =>
+ result.current.setProgress((previous) =>
+ reduceSubagentProgress(previous, [event(0).data, event(1).data], 'parent', true),
+ ),
+ );
+ expect(result.current.progress?.contentParts).toEqual([{ type: 'text', text: '0123' }]);
+ expect(result.current.progress?.pendingSequencedEvents).toBeUndefined();
+ act(() => streams[0].emit('message', event(4)));
+ expect(result.current.progress?.contentParts).toEqual([{ type: 'text', text: '01234' }]);
+ act(() => result.current.closeParent(false));
+ act(() => streams[0].emit('message', event(6)));
+ expect(result.current.progress?.lastActivitySequence).toBe(6);
+ });
+
+ it('counts omission markers only once when accepted, including pending replay overlap', () => {
+ const active = { ...selection, isSubmitting: true };
+ const { result } = renderHook(
+ () => {
+ const key = subagentProgressKey(
+ active.parentMessageId,
+ active.toolCallId,
+ active.partIndex,
+ );
+ useSubagentActivityStream(active);
+ return {
+ progress: useAtomValue(subagentProgressByToolCallId(key)),
+ closeParent: useSetAtom(subagentParentStreamOpenByToolCallId(key)),
+ };
+ },
+ { wrapper },
+ );
+ const marker = {
+ event: StepEvents.ON_SUBAGENT_UPDATE,
+ droppedCount: 2,
+ data: {
+ runId: 'parent',
+ subagentRunId: 'child',
+ subagentType: 'researcher',
+ subagentAgentId: 'agent-1',
+ parentToolCallId: active.toolCallId,
+ activityEventId: 'task:3',
+ activitySequence: 3,
+ phase: 'message_delta' as const,
+ timestamp: '2026-09-29T00:00:00.000Z',
+ },
+ };
+ act(() => streams[0].emit('message', marker));
+ act(() =>
+ streams[0].emit('message', { event: 'subagent_activity_replay', data: [marker, marker] }),
+ );
+ expect(result.current.progress?.droppedCount ?? 0).toBe(0);
+ expect(result.current.progress?.pendingSequencedEvents).toHaveLength(1);
+ act(() => result.current.closeParent(false));
+ expect(result.current.progress?.droppedCount).toBe(2);
+ act(() =>
+ streams[0].emit('message', { event: 'subagent_activity_replay', data: [marker, marker] }),
+ );
+ act(() => streams[0].emit('message', marker));
+ expect(result.current.progress?.droppedCount).toBe(2);
+ });
+
it('buffers the first detached suffix while the parent stream is still open', () => {
const activeSelection = { ...selection, isSubmitting: true };
const key = subagentProgressKey(
@@ -200,6 +532,7 @@ describe('useSubagentActivityStream', () => {
);
act(() => {
+ streams[0]?.emit('message', { event: 'subagent_activity_replay', data: [] });
streams[0]?.emit('message', {
event: StepEvents.ON_SUBAGENT_UPDATE,
data: {
@@ -234,6 +567,165 @@ describe('useSubagentActivityStream', () => {
expect(result.current.progress?.pendingSequencedEvents).toBeUndefined();
});
+ it.each([6, 104, 106])(
+ 'recovers a full pending buffer with retained replay starting at %s',
+ (snapshotStart) => {
+ jest.useFakeTimers();
+ const active = { ...selection, isSubmitting: true };
+ const { result, unmount } = renderHook(
+ () => {
+ const key = subagentProgressKey(
+ active.parentMessageId,
+ active.toolCallId,
+ active.partIndex,
+ );
+ useSubagentActivityStream(active);
+ return {
+ progress: useAtomValue(subagentProgressByToolCallId(key)),
+ setProgress: useSetAtom(subagentProgressByToolCallId(key)),
+ closeParent: useSetAtom(subagentParentStreamOpenByToolCallId(key)),
+ };
+ },
+ { wrapper },
+ );
+ const event = (sequence: number) => ({
+ event: StepEvents.ON_SUBAGENT_UPDATE,
+ data: {
+ runId: 'parent',
+ subagentRunId: 'child',
+ subagentType: 'researcher',
+ subagentAgentId: 'agent-1',
+ parentToolCallId: active.toolCallId,
+ activityEventId: `task:${sequence}`,
+ activitySequence: sequence,
+ phase: 'message_delta' as const,
+ timestamp: '2026-09-29T00:00:00.000Z',
+ data: { delta: { content: [{ type: 'text', text: `${sequence},` }] } },
+ },
+ });
+ act(() =>
+ streams[0].emit('message', {
+ event: 'subagent_activity_replay',
+ data: Array.from({ length: 100 }, (_, i) => event(i + 2)),
+ }),
+ );
+ for (let seq = 102; seq <= 105; seq++) act(() => streams[0].emit('message', event(seq)));
+ expect(result.current.progress?.pendingSequencedEvents).toHaveLength(100);
+ expect(result.current.progress?.activityReplayFrom).toBe(102);
+ act(() =>
+ result.current.setProgress((previous) =>
+ reduceSubagentProgress(previous, [event(0).data, event(1).data], 'parent', true),
+ ),
+ );
+ expect(result.current.progress?.lastActivitySequence).toBe(101);
+ act(() => result.current.closeParent(false));
+ expect(streams[0].close).toHaveBeenCalledTimes(1);
+ act(() => jest.advanceTimersByTime(500));
+ expect(streams).toHaveLength(2);
+ act(() =>
+ streams[1].emit('message', {
+ event: 'subagent_activity_replay',
+ data: Array.from({ length: 106 - snapshotStart }, (_, i) => event(i + snapshotStart)),
+ }),
+ );
+ expect(result.current.progress?.lastActivitySequence).toBe(105);
+ expect(result.current.progress?.activityReplayFrom).toBeUndefined();
+ expect(result.current.progress?.droppedCount).toBe(Math.max(0, snapshotStart - 102));
+ expect(result.current.progress?.contentParts).toEqual([
+ {
+ type: 'text',
+ text: Array.from({ length: 106 }, (_, i) => i)
+ .filter((i) => i < 102 || i >= snapshotStart)
+ .map((i) => `${i},`)
+ .join(''),
+ },
+ ]);
+ act(() => streams[1].emit('message', event(106)));
+ expect(result.current.progress?.lastActivitySequence).toBe(106);
+ expect(result.current.progress?.activityReplayFrom).toBeUndefined();
+ unmount();
+ jest.useRealTimers();
+ },
+ );
+
+ it('releases strict recovery ordering when healthy live frames fill the rejected interval', () => {
+ jest.useFakeTimers();
+ const active = { ...selection, isSubmitting: true };
+ const { result, unmount } = renderHook(
+ () => {
+ const key = subagentProgressKey(
+ active.parentMessageId,
+ active.toolCallId,
+ active.partIndex,
+ );
+ useSubagentActivityStream(active);
+ return {
+ progress: useAtomValue(subagentProgressByToolCallId(key)),
+ setProgress: useSetAtom(subagentProgressByToolCallId(key)),
+ closeParent: useSetAtom(subagentParentStreamOpenByToolCallId(key)),
+ };
+ },
+ { wrapper },
+ );
+ const event = (sequence: number) => ({
+ event: StepEvents.ON_SUBAGENT_UPDATE,
+ data: {
+ runId: 'parent',
+ subagentRunId: 'child',
+ subagentType: 'researcher',
+ subagentAgentId: 'agent-1',
+ parentToolCallId: active.toolCallId,
+ activityEventId: `recover-live:${sequence}`,
+ activitySequence: sequence,
+ phase: 'message_delta' as const,
+ timestamp: '2026-09-29T00:00:00.000Z',
+ data: { delta: { content: [{ type: 'text', text: `${sequence},` }] } },
+ },
+ });
+ act(() =>
+ streams[0].emit('message', {
+ event: 'subagent_activity_replay',
+ data: Array.from({ length: 100 }, (_, i) => event(i + 2)),
+ }),
+ );
+ act(() => {
+ streams[0].emit('message', event(102));
+ streams[0].emit('message', event(103));
+ });
+ act(() =>
+ result.current.setProgress((previous) =>
+ reduceSubagentProgress(previous, [event(0).data, event(1).data], 'parent', true),
+ ),
+ );
+ act(() => result.current.closeParent(false));
+ act(() => jest.advanceTimersByTime(500));
+ act(() =>
+ streams[1].emit('message', {
+ event: 'subagent_activity_replay',
+ data: [event(100), event(101)],
+ }),
+ );
+ expect(result.current.progress?.activityReplayFrom).toBe(102);
+ act(() => {
+ for (let sequence = 102; sequence <= 105; sequence++)
+ streams[1].emit('message', event(sequence));
+ });
+ expect(result.current.progress?.activityReplayFrom).toBeUndefined();
+ act(() =>
+ streams[1].emit('message', {
+ ...event(108),
+ droppedCount: 3,
+ data: { ...event(108).data, data: undefined },
+ }),
+ );
+ expect(result.current.progress?.lastActivitySequence).toBe(108);
+ expect(result.current.progress?.droppedCount).toBe(3);
+ expect(result.current.progress?.pendingSequencedEvents).toBeUndefined();
+ expect(streams).toHaveLength(2);
+ unmount();
+ jest.useRealTimers();
+ });
+
it('reconnects with bounded backoff after a transient stream error', () => {
jest.useFakeTimers();
const { unmount } = renderHook(() => useSubagentActivityStream(selection), { wrapper });
diff --git a/client/src/data-provider/Subagents/useSubagentActivityStream.ts b/client/src/data-provider/Subagents/useSubagentActivityStream.ts
index dbe503bf27..ba86fb2c74 100644
--- a/client/src/data-provider/Subagents/useSubagentActivityStream.ts
+++ b/client/src/data-provider/Subagents/useSubagentActivityStream.ts
@@ -1,5 +1,6 @@
-import { useEffect, useRef } from 'react';
+import { useEffect, useMemo, useRef } from 'react';
import { SSE } from 'sse.js';
+import { selectAtom } from 'jotai/utils';
import { useAtomValue, useSetAtom } from 'jotai';
import { useQueryClient } from '@tanstack/react-query';
import { QueryKeys, StepEvents, apiBaseUrl } from 'librechat-data-provider';
@@ -8,6 +9,7 @@ import type { ActiveSubagentPanel } from '~/components/Chat/Subagents/state';
import {
closeParentSubagentProgress,
reduceSubagentProgress,
+ reduceSubagentReplay,
registerSubagentProgressKey,
subagentParentStreamOpenByToolCallId,
subagentProgressByToolCallId,
@@ -20,6 +22,7 @@ type ActivityEnvelope = {
data?: unknown;
final?: unknown;
subagentActivity?: unknown;
+ droppedCount?: unknown;
};
const INITIAL_RECONNECT_MS = 500;
@@ -39,7 +42,7 @@ const isSubagentUpdate = (value: unknown): value is SubagentUpdateEvent => {
);
};
-/** Live-only enhancement for the selected durable child; the durable query remains canonical. */
+/** Replay-then-live enhancement for the selected durable child; the durable query remains canonical. */
export default function useSubagentActivityStream(
selection: ActiveSubagentPanel,
enabled = true,
@@ -51,6 +54,14 @@ export default function useSubagentActivityStream(
selection.event?.progressKey ?? selection.toolCallId,
selection.partIndex,
);
+ const replayFrom = useAtomValue(
+ useMemo(
+ () =>
+ selectAtom(subagentProgressByToolCallId(key), (progress) => progress?.activityReplayFrom),
+ [key],
+ ),
+ );
+ const reconnectRef = useRef<(() => void) | undefined>();
const setProgress = useSetAtom(subagentProgressByToolCallId(key));
const parentStreamOpen = useAtomValue(subagentParentStreamOpenByToolCallId(key));
const setParentStreamOpen = useSetAtom(subagentParentStreamOpenByToolCallId(key));
@@ -66,6 +77,10 @@ export default function useSubagentActivityStream(
}
}, [parentStreamOpen, setProgress]);
+ useEffect(() => {
+ if (replayFrom != null && !parentStreamOpen) reconnectRef.current?.();
+ }, [replayFrom, parentStreamOpen]);
+
useEffect(() => {
if (!selection.isSubmitting) return;
registerSubagentProgressKey(key);
@@ -121,6 +136,28 @@ export default function useSubagentActivityStream(
void queryClient.invalidateQueries(queryKey);
return;
}
+ if (envelope.event === 'subagent_activity_replay' && Array.isArray(envelope.data)) {
+ const replay = envelope.data as ActivityEnvelope[];
+ const events = replay.flatMap((entry) =>
+ entry.event === StepEvents.ON_SUBAGENT_UPDATE && isSubagentUpdate(entry.data)
+ ? [
+ {
+ ...entry.data,
+ activityDroppedCount:
+ Number.isSafeInteger(entry.droppedCount) && (entry.droppedCount as number) > 0
+ ? (entry.droppedCount as number)
+ : undefined,
+ },
+ ]
+ : [],
+ );
+ registerSubagentProgressKey(key);
+ setProgress((previous) =>
+ reduceSubagentReplay(previous, events, parentStreamOpenRef.current),
+ );
+ retryAttempt = 0;
+ return;
+ }
const event = envelope.data;
if (envelope.event !== StepEvents.ON_SUBAGENT_UPDATE || !isSubagentUpdate(event)) {
return;
@@ -135,20 +172,39 @@ export default function useSubagentActivityStream(
retryAttempt = 0;
registerSubagentProgressKey(key);
setProgress((previous) =>
- reduceSubagentProgress(previous, [event], 'detached', parentStreamOpenRef.current),
+ reduceSubagentProgress(
+ previous,
+ [
+ {
+ ...event,
+ activityDroppedCount:
+ Number.isSafeInteger(envelope.droppedCount) &&
+ (envelope.droppedCount as number) > 0
+ ? (envelope.droppedCount as number)
+ : undefined,
+ },
+ ],
+ 'detached',
+ parentStreamOpenRef.current || previous?.activityReplayFrom != null,
+ ),
);
});
next.addEventListener('error', () => {
- if (stream !== next || disposed || terminal || retryTimer != null) return;
- closeCurrent();
- const delay = Math.min(INITIAL_RECONNECT_MS * 2 ** retryAttempt, MAX_RECONNECT_MS);
- retryAttempt += 1;
- retryTimer = setTimeout(connect, delay);
+ if (stream === next) reconnect();
});
};
+ const reconnect = () => {
+ if (disposed || terminal || retryTimer != null) return;
+ closeCurrent();
+ const delay = Math.min(INITIAL_RECONNECT_MS * 2 ** retryAttempt, MAX_RECONNECT_MS);
+ retryAttempt += 1;
+ retryTimer = setTimeout(connect, delay);
+ };
+ reconnectRef.current = reconnect;
connect();
return () => {
+ if (reconnectRef.current === reconnect) reconnectRef.current = undefined;
disposed = true;
if (retryTimer != null) clearTimeout(retryTimer);
closeCurrent();
diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json
index 21df8f11e4..187698f420 100644
--- a/client/src/locales/en/translation.json
+++ b/client/src/locales/en/translation.json
@@ -2851,6 +2851,8 @@
"com_ui_subagent_control_cancel_message": "Withdraw message",
"com_ui_subagent_control_history": "Control history",
"com_ui_subagent_control_history_truncated": "Earlier control activity is not shown.",
+ "com_ui_subagent_activity_dropped_one": "One activity update was omitted while the live stream was unavailable. The completed transcript remains available.",
+ "com_ui_subagent_activity_dropped": "{{count}} activity updates were omitted while the live stream was unavailable. The completed transcript remains available.",
"com_ui_subagent_activity_details_unavailable": "Additional activity details are unavailable.",
"com_ui_subagent_show_full_activity": "Show full activity",
"com_ui_subagent_load_earlier_activity": "Load earlier activity",
diff --git a/client/src/utils/__tests__/subagentContent.test.ts b/client/src/utils/__tests__/subagentContent.test.ts
index e861303b0f..cea6c98b8f 100644
--- a/client/src/utils/__tests__/subagentContent.test.ts
+++ b/client/src/utils/__tests__/subagentContent.test.ts
@@ -75,8 +75,18 @@ describe('aggregateSubagentContent', () => {
]);
expect(parts).toEqual([
- { type: ContentTypes.TEXT, text: 'Commentary.', phase: 'commentary' },
- { type: ContentTypes.TEXT, text: 'Final answer.', phase: 'final_answer' },
+ {
+ type: ContentTypes.TEXT,
+ text: 'Commentary.',
+ phase: 'commentary',
+ stepId: 'commentary-step',
+ },
+ {
+ type: ContentTypes.TEXT,
+ text: 'Final answer.',
+ phase: 'final_answer',
+ stepId: 'final-step',
+ },
]);
});
@@ -117,7 +127,12 @@ describe('aggregateSubagentContent', () => {
];
expect(aggregateSubagentContent(events)).toEqual([
- { type: ContentTypes.TEXT, text: 'Still commentary.', phase: 'commentary' },
+ {
+ type: ContentTypes.TEXT,
+ text: 'Still commentary.',
+ phase: 'commentary',
+ stepId: 'long-lived-step',
+ },
]);
});
diff --git a/client/src/utils/subagentContent.ts b/client/src/utils/subagentContent.ts
index ccab985ddd..fa3a595108 100644
--- a/client/src/utils/subagentContent.ts
+++ b/client/src/utils/subagentContent.ts
@@ -1,5 +1,5 @@
import { ContentTypes, ToolCallTypes, getToolTimingDurations } from 'librechat-data-provider';
-import type { SubagentUpdateEvent } from 'librechat-data-provider';
+import type { SubagentUpdateEvent, ToolTimingStamps } from 'librechat-data-provider';
/**
* Client-side helpers for rendering the live `SubagentCall` UI while
@@ -82,7 +82,12 @@ type ReasoningDeltaData = {
type ErrorData = { message?: string };
type AssistantTextPhase = 'commentary' | 'final_answer';
-type TextPart = { type: ContentTypes.TEXT; text: string; phase?: AssistantTextPhase };
+type TextPart = {
+ type: ContentTypes.TEXT;
+ text: string;
+ phase?: AssistantTextPhase;
+ stepId?: string;
+};
type ThinkPart = { type: ContentTypes.THINK; think: string };
type ToolCallPart = {
type: ContentTypes.TOOL_CALL;
@@ -90,6 +95,9 @@ type ToolCallPart = {
id: string;
name: string;
args: string;
+ /** Synthesis defaults are not observed tool fields. */
+ argsUnavailable?: true;
+ nameUnavailable?: true;
output?: string;
progress: number;
inputValidationError?: true;
@@ -97,6 +105,7 @@ type ToolCallPart = {
stepId?: string;
toolPreparationStartedAt?: number;
toolDispatchedAt?: number;
+ toolCompletedAt?: number;
toolPreparationDurationMs?: number;
toolExecutionDurationMs?: number;
};
@@ -219,7 +228,10 @@ export function foldSubagentEvent(
if (afterThinkClose.openTextIdx != null) {
const idx = afterThinkClose.openTextIdx;
const existing = parts[idx] as TextPart;
- if ((existing.phase ?? null) === (phase ?? null)) {
+ if (
+ (existing.phase ?? null) === (phase ?? null) &&
+ (existing.stepId ?? null) === (stepId || null)
+ ) {
const next = parts.slice();
next[idx] = { ...existing, text: existing.text + chunk };
return { parts: next, state: afterThinkClose };
@@ -231,6 +243,7 @@ export function foldSubagentEvent(
type: ContentTypes.TEXT,
text: chunk,
...(phase == null ? {} : { phase }),
+ ...(typeof stepId === 'string' && stepId !== '' ? { stepId } : {}),
});
return { parts: next, state: { ...afterThinkClose, openTextIdx: newIdx } };
}
@@ -368,6 +381,15 @@ export function foldSubagentEvent(
const existingIdx = state.toolCallIndexById[tc.id];
if (existingIdx != null) {
const existing = parts[existingIdx] as ToolCallPart;
+ const completedAt = data?.result?.completed_at;
+ const completion =
+ existing.tool_call.stepId != null &&
+ data?.result?.id === existing.tool_call.stepId &&
+ typeof completedAt === 'number' &&
+ Number.isFinite(completedAt) &&
+ completedAt >= 0
+ ? { toolCompletedAt: completedAt }
+ : {};
const timings =
data?.result?.id === existing.tool_call.stepId
? getToolTimingDurations({
@@ -380,9 +402,20 @@ export function foldSubagentEvent(
type: ContentTypes.TOOL_CALL,
tool_call: {
...existing.tool_call,
+ ...completion,
...timings,
- ...(tc.name ? { name: tc.name } : {}),
- ...(tc.args != null ? { args: stringifyArgs(tc.args) } : {}),
+ ...(tc.name
+ ? {
+ name: tc.name,
+ ...(existing.tool_call.nameUnavailable ? { nameUnavailable: undefined } : {}),
+ }
+ : {}),
+ ...(tc.args != null
+ ? {
+ args: stringifyArgs(tc.args),
+ ...(existing.tool_call.argsUnavailable ? { argsUnavailable: undefined } : {}),
+ }
+ : {}),
...(tc.output != null ? { output: tc.output } : {}),
...(tc.inputValidationError === true ? { inputValidationError: true } : {}),
progress: tc.progress ?? 1,
@@ -400,8 +433,20 @@ export function foldSubagentEvent(
type: ContentTypes.TOOL_CALL,
tool_call: {
id: tc.id,
+ ...(typeof data?.result?.id === 'string' && data.result.id !== ''
+ ? {
+ stepId: data.result.id,
+ ...(typeof data.result.completed_at === 'number' &&
+ Number.isFinite(data.result.completed_at) &&
+ data.result.completed_at >= 0
+ ? { toolCompletedAt: data.result.completed_at }
+ : {}),
+ }
+ : {}),
name: tc.name ?? '',
args: stringifyArgs(tc.args),
+ ...(tc.args == null ? { argsUnavailable: true } : {}),
+ ...(!tc.name ? { nameUnavailable: true } : {}),
output: tc.output,
...(tc.inputValidationError === true ? { inputValidationError: true } : {}),
progress: tc.progress ?? 1,
@@ -435,6 +480,190 @@ export function foldSubagentEvent(
return { parts, state };
}
+/** Recover phase metadata by the retained message step, then repair adjacent Markdown
+ * runs split by late phase discovery. The declaration is historical; closed steps stay retired. */
+export function reconcileSubagentMessagePhases(
+ parts: SubagentContentPart[],
+ state: SubagentAggregatorState,
+ events: SubagentUpdateEvent[],
+): { parts: SubagentContentPart[]; state: SubagentAggregatorState } {
+ const phases = new Map<string, AssistantTextPhase>();
+ const closed = new Set<string>();
+ for (const event of events) {
+ if (event.phase === 'run_step') {
+ const data = event.data as RunStepData | undefined;
+ const phase = data?.stepDetails?.message_creation?.phase;
+ if (
+ data?.id &&
+ data.stepDetails?.type === 'message_creation' &&
+ (phase === 'commentary' || phase === 'final_answer')
+ )
+ phases.set(data.id, phase);
+ } else if (event.phase === 'run_step_closed') {
+ const id = (event.data as RunStepClosedData | undefined)?.id;
+ if (id) closed.add(id);
+ }
+ }
+ if (phases.size === 0 && closed.size === 0) return { parts, state };
+ let next = parts;
+ for (let index = 0; index < parts.length; index++) {
+ const part = parts[index];
+ if (part.type !== ContentTypes.TEXT || part.phase != null || !part.stepId) continue;
+ const phase = phases.get(part.stepId);
+ if (phase == null) continue;
+ if (next === parts) next = parts.slice();
+ next[index] = { ...part, phase };
+ }
+ let messagePhaseByStepId = state.messagePhaseByStepId;
+ for (const [id, phase] of phases) {
+ if (closed.has(id) || messagePhaseByStepId[id] === phase) continue;
+ if (messagePhaseByStepId === state.messagePhaseByStepId)
+ messagePhaseByStepId = { ...messagePhaseByStepId };
+ messagePhaseByStepId[id] = phase;
+ }
+ for (const id of closed) {
+ if (!(id in messagePhaseByStepId)) continue;
+ if (messagePhaseByStepId === state.messagePhaseByStepId)
+ messagePhaseByStepId = { ...messagePhaseByStepId };
+ delete messagePhaseByStepId[id];
+ }
+ /** Never combine different message steps or cross a tool/reasoning boundary. */
+ const joins = next.some((part, index) => {
+ const previous = next[index - 1];
+ return (
+ part.type === ContentTypes.TEXT &&
+ part.stepId != null &&
+ previous?.type === ContentTypes.TEXT &&
+ previous.stepId === part.stepId &&
+ previous.phase === part.phase
+ );
+ });
+ if (!joins)
+ return {
+ parts: next,
+ state:
+ messagePhaseByStepId === state.messagePhaseByStepId
+ ? state
+ : { ...state, messagePhaseByStepId },
+ };
+ const merged: SubagentContentPart[] = [];
+ const indices: number[] = [];
+ for (const part of next) {
+ const previous = merged[merged.length - 1];
+ if (
+ part.type === ContentTypes.TEXT &&
+ part.stepId != null &&
+ previous?.type === ContentTypes.TEXT &&
+ previous.stepId === part.stepId &&
+ previous.phase === part.phase
+ )
+ merged[merged.length - 1] = { ...previous, text: previous.text + part.text };
+ else merged.push(part);
+ indices.push(merged.length - 1);
+ }
+ return {
+ parts: merged,
+ state: {
+ ...state,
+ messagePhaseByStepId,
+ openTextIdx: state.openTextIdx == null ? null : (indices[state.openTextIdx] ?? null),
+ openThinkIdx: state.openThinkIdx == null ? null : (indices[state.openThinkIdx] ?? null),
+ toolCallIndexById: Object.fromEntries(
+ merged.flatMap((part, index) =>
+ part.type === ContentTypes.TOOL_CALL ? [[part.tool_call.id, index]] : [],
+ ),
+ ),
+ },
+ };
+}
+
+/** Replay metadata is idempotent even when the associated event was observed before
+ * its tool part existed. Recover only stamps, never append content or reopen tools. */
+export function reconcileSubagentToolTimings(
+ parts: SubagentContentPart[],
+ events: SubagentUpdateEvent[],
+): SubagentContentPart[] {
+ const stamps = new Map<string, ToolTimingStamps & { completed?: true }>();
+ const valid = (at: number | undefined): at is number =>
+ typeof at === 'number' && Number.isFinite(at) && at >= 0;
+ const key = (id: string, step: string) => JSON.stringify([id, step]);
+ const record = (
+ id: string | undefined,
+ step: string | undefined,
+ field: keyof ToolTimingStamps,
+ at: number | undefined,
+ ) => {
+ if (!id || !step || !valid(at)) return;
+ const identity = key(id, step);
+ const current = stamps.get(identity) ?? {};
+ /** A later handoff is not part of the measured invocation after its completion. */
+ if (current.completed) return;
+ const old = current[field];
+ current[field] = old == null ? at : Math.min(old, at);
+ stamps.set(identity, current);
+ };
+ for (const event of events) {
+ if (event.phase === 'tool_preparation') {
+ const data = event.data as ToolPreparationData | undefined;
+ record(data?.toolCallId, data?.id, 'observedAt', data?.observed_at);
+ } else if (event.phase === 'tool_calls_dispatched') {
+ const data = event.data as ToolDispatchData | undefined;
+ for (const call of data?.toolCalls ?? [])
+ record(call.id, call.stepId, 'dispatchedAt', data?.dispatched_at);
+ } else if (event.phase === 'run_step_completed') {
+ const result = (event.data as RunStepCompletedData | undefined)?.result;
+ const id = result?.tool_call?.id;
+ const step = result?.id;
+ record(id, step, 'completedAt', result?.completed_at);
+ if (id && step) {
+ const identity = key(id, step);
+ const current = stamps.get(identity) ?? {};
+ current.completed = true;
+ stamps.set(identity, current);
+ }
+ }
+ }
+ if (stamps.size === 0) return parts;
+ let next = parts;
+ for (let index = 0; index < parts.length; index++) {
+ const part = parts[index];
+ if (part.type !== ContentTypes.TOOL_CALL || !part.tool_call.stepId) continue;
+ const recovered = stamps.get(key(part.tool_call.id, part.tool_call.stepId));
+ if (recovered == null) continue;
+ const existing = part.tool_call;
+ const earliest = (old: number | undefined, at: number | undefined) => {
+ if (old == null) return at;
+ return at == null ? old : Math.min(old, at);
+ };
+ const observedAt = earliest(existing.toolPreparationStartedAt, recovered.observedAt);
+ const dispatchedAt = earliest(existing.toolDispatchedAt, recovered.dispatchedAt);
+ const completedAt = existing.toolCompletedAt ?? recovered.completedAt;
+ const durations = getToolTimingDurations({ observedAt, dispatchedAt, completedAt });
+ if (
+ observedAt === existing.toolPreparationStartedAt &&
+ dispatchedAt === existing.toolDispatchedAt &&
+ completedAt === existing.toolCompletedAt &&
+ (durations.toolPreparationDurationMs == null ||
+ durations.toolPreparationDurationMs === existing.toolPreparationDurationMs) &&
+ (durations.toolExecutionDurationMs == null ||
+ durations.toolExecutionDurationMs === existing.toolExecutionDurationMs)
+ )
+ continue;
+ if (next === parts) next = parts.slice();
+ next[index] = {
+ ...part,
+ tool_call: {
+ ...existing,
+ ...(observedAt == null ? {} : { toolPreparationStartedAt: observedAt }),
+ ...(dispatchedAt == null ? {} : { toolDispatchedAt: dispatchedAt }),
+ ...(completedAt == null ? {} : { toolCompletedAt: completedAt }),
+ ...durations,
+ },
+ };
+ }
+ return next;
+}
+
/**
* Batch wrapper around {@link foldSubagentEvent}: folds an entire event
* stream in one go and returns just the parts. Kept for tests and for
diff --git a/librechat.example.yaml b/librechat.example.yaml
index 978046c90e..280886cc3a 100644
--- a/librechat.example.yaml
+++ b/librechat.example.yaml
@@ -751,6 +751,15 @@ endpoints:
# # (optional) Shared files during an active agent run. Each delegating agent must
# # also opt in with subagents.shareFiles. Inputs are read-only; outputs stay
# # private until explicitly published. Published files remain downloadable.
+ # # Live child activity, independent of the completed transcript.
+ # subagentActivity:
+ # replayTtlMs: 300000 # Increase for long silent tool calls.
+ # publicationTimeoutMs: 1000
+ # retryAttempts: 3
+ # retryBaseDelayMs: 100
+ # recoveryDelayMs: 1000
+ # memoryMaxStreams: 1000 # Non-Redis replay cache.
+ # memoryMaxBytes: 16777216
# fileSharing:
# enabled: false
# allowSiblingSharing: false # permit explicitly named sibling/descendant recipients
diff --git a/packages/api/src/agents/subagentActivity.spec.ts b/packages/api/src/agents/subagentActivity.spec.ts
index 647ef092c6..ecd0daf68f 100644
--- a/packages/api/src/agents/subagentActivity.spec.ts
+++ b/packages/api/src/agents/subagentActivity.spec.ts
@@ -1,6 +1,8 @@
import { EventEmitter } from 'node:events';
+import { createServer, get } from 'node:http';
import type { IConversation, IMessage } from '@librechat/data-schemas';
import type { SubagentUpdateEvent } from '@librechat/agents';
+import type { AddressInfo } from 'node:net';
import type { Response } from 'express';
import type { SubagentActivityEnvelope, SubagentActivityUpdateEvent } from './subagentActivity';
import type { IEventTransport } from '~/stream/interfaces/IJobStore';
@@ -666,7 +668,7 @@ describe('subagent activity stream authorization', () => {
expect(transport.handlers.size).toBe(0);
});
- it('closes a slow SSE consumer instead of buffering later activity', async () => {
+ it('waits for drain before sending buffered activity and the terminal event', async () => {
const transport = new TestTransport();
const stream = new SubagentActivityStream(transport);
const handler = createSubagentActivityStreamHandler(
@@ -688,7 +690,225 @@ describe('subagent activity stream authorization', () => {
await handler(request(), res);
await stream.publish(threadId, taskId, update());
+ await stream.publish(threadId, taskId, update({ label: 'buffered' }));
+ await stream.complete(threadId, taskId, 'completed');
+ expect(res.end).not.toHaveBeenCalled();
+ expect(res.chunks.join('')).not.toContain('buffered');
+ (res.write as jest.Mock).mockImplementation((chunk: string) => {
+ res.chunks.push(chunk);
+ return true;
+ });
+ res.emit('drain');
+ expect(res.chunks.join('')).toContain('buffered');
+ expect(res.chunks.join('')).toContain('"status":"completed"');
+ expect(res.end).toHaveBeenCalledTimes(1);
+ expect(res.listenerCount('drain')).toBe(0);
+ expect(transport.handlers.size).toBe(0);
+ });
+
+ it('closes an over-budget blocked reader so it can recover through replay', async () => {
+ const transport = new TestTransport();
+ const stream = new SubagentActivityStream(transport);
+ const handler = createSubagentActivityStreamHandler(
+ {
+ getConvoOwnership: jest.fn().mockResolvedValue(parent),
+ getSubagentThreadForParent: jest.fn().mockResolvedValue(child),
+ getMessages: jest.fn().mockResolvedValue([]),
+ },
+ stream,
+ );
+ const res = response();
+ (res.write as jest.Mock).mockImplementation((chunk: string) => {
+ res.chunks.push(chunk);
+ return false;
+ });
+ await handler(request(), res);
+ for (let index = 0; index < 110; index++) await stream.publish(threadId, taskId, update());
expect(res.end).toHaveBeenCalledTimes(1);
+ expect(res.listenerCount('drain')).toBe(0);
expect(transport.handlers.size).toBe(0);
});
+
+ it('writes a bounded live event whose public identity exceeds the waiting-queue budget', async () => {
+ const eventThreadId = `${'\u0001'.repeat(498)}x`;
+ const req = request();
+ req.params = { parentConversationId, threadId: eventThreadId, taskId };
+ const transport = new TestTransport();
+ const stream = new SubagentActivityStream(transport);
+ const handler = createSubagentActivityStreamHandler(
+ {
+ getConvoOwnership: jest.fn().mockResolvedValue(parent),
+ getSubagentThreadForParent: jest.fn().mockResolvedValue({
+ ...child,
+ subagentThread: { ...child.subagentThread, parentToolCallId: 'event-binding:private' },
+ }),
+ getMessages: jest.fn().mockResolvedValue([]),
+ },
+ stream,
+ );
+ const res = response();
+ await handler(req, res);
+ await stream.publish(
+ eventThreadId,
+ taskId,
+ update({ parentToolCallId: undefined, ancestry: [], data: { text: 'x'.repeat(64_000) } }),
+ );
+ const publicFrame = res.chunks.find((chunk) => chunk.includes('on_subagent_update'))!;
+ expect(Buffer.byteLength(publicFrame)).toBeGreaterThan(65_536);
+ expect(res.end).not.toHaveBeenCalled();
+ expect(transport.getSubscriberCount(subagentActivityStreamId(eventThreadId, taskId))).toBe(1);
+ res.emit('close');
+ stream.destroy();
+ });
+
+ it.each([false, true])(
+ 'delivers an expanded event-thread snapshot without closing (blocked: %s)',
+ async (blocked) => {
+ const transport = new TestTransport();
+ const stream = new SubagentActivityStream(transport);
+ const eventThreadId = 'x'.repeat(499);
+ const req = request();
+ req.params = { parentConversationId, threadId: eventThreadId, taskId };
+ const entries: SubagentActivityEnvelope[] = Array.from({ length: 100 }, (_, sequence) => ({
+ event: 'on_subagent_update',
+ data: update({
+ parentToolCallId: undefined,
+ ancestry: [],
+ activitySequence: sequence,
+ data: { text: 'a'.repeat(250) },
+ }),
+ }));
+ const retainedBytes = entries.reduce(
+ (total, data, seq) =>
+ total + Buffer.byteLength(JSON.stringify({ type: 'chunk', seq, data })),
+ 0,
+ );
+ expect(retainedBytes).toBeLessThanOrEqual(65_536);
+ const unsubscribe = jest.fn();
+ const handler = createSubagentActivityStreamHandler(
+ {
+ getConvoOwnership: jest.fn().mockResolvedValue(parent),
+ getSubagentThreadForParent: jest.fn().mockResolvedValue({
+ ...child,
+ subagentThread: {
+ ...child.subagentThread,
+ parentToolCallId: 'event-binding:private',
+ },
+ }),
+ getMessages: jest.fn().mockResolvedValue([]),
+ },
+ {
+ subscribe: (_thread, _task, subscriber) => ({
+ unsubscribe,
+ ready: Promise.resolve().then(() => {
+ if (blocked)
+ subscriber.onEvent({
+ event: 'on_subagent_update',
+ data: update({ label: 'before-snapshot' }),
+ });
+ subscriber.onEvent({ event: 'subagent_activity_replay', data: entries });
+ subscriber.onEvent({
+ event: 'on_subagent_update',
+ data: update({ activitySequence: 100, label: 'live-tail' }),
+ });
+ }),
+ }),
+ },
+ );
+ const res = response();
+ if (blocked)
+ (res.write as jest.Mock).mockImplementationOnce((frame: string) => {
+ res.chunks.push(frame);
+ return false;
+ });
+ await handler(req, res);
+ expect(res.end).not.toHaveBeenCalled();
+ if (blocked) {
+ expect(res.chunks.join('')).not.toContain('subagent_activity_replay');
+ res.emit('drain');
+ }
+ const frames = res.chunks
+ .filter((chunk) => chunk.startsWith('data: '))
+ .map((chunk) => JSON.parse(chunk.slice(6)));
+ const replay = frames.find((frame) => frame.event === 'subagent_activity_replay');
+ expect(Buffer.byteLength(JSON.stringify(replay))).toBeGreaterThan(65_536);
+ expect(replay.data).toHaveLength(100);
+ expect(
+ replay.data.map((entry: SubagentActivityEnvelope) => entry.data.activitySequence),
+ ).toEqual(Array.from({ length: 100 }, (_, index) => index));
+ expect(replay.data[0].data.parentToolCallId).toBe(`event-thread:${eventThreadId}`);
+ expect(res.chunks.join('')).not.toContain('event-binding:');
+ expect(res.chunks.join('')).toContain('live-tail');
+ res.emit('close');
+ expect(unsubscribe).toHaveBeenCalled();
+ expect(res.listenerCount('drain')).toBe(0);
+ stream.destroy();
+ },
+ );
+
+ it('streams a full snapshot and concurrent buffered frames through actual HTTP backpressure', async () => {
+ const unsubscribe = jest.fn();
+ const activity = (sequence: number, text: string): SubagentActivityEnvelope => ({
+ event: 'on_subagent_update',
+ data: update({ activitySequence: sequence, data: { text } }),
+ });
+ const handler = createSubagentActivityStreamHandler(
+ {
+ getConvoOwnership: jest.fn().mockResolvedValue(parent),
+ getSubagentThreadForParent: jest.fn().mockResolvedValue(child),
+ getMessages: jest.fn().mockResolvedValue([]),
+ },
+ {
+ subscribe: (_thread, _task, subscriber) => ({
+ unsubscribe,
+ ready: Promise.resolve().then(() => {
+ subscriber.onEvent({
+ event: 'subagent_activity_replay',
+ data: [activity(0, 'x'.repeat(52_000))],
+ });
+ for (let sequence = 1; sequence <= 4; sequence++)
+ subscriber.onEvent(activity(sequence, 'y'.repeat(10_000)));
+ subscriber.onDone?.({ final: true, subagentActivity: true, status: 'completed' });
+ }),
+ }),
+ },
+ );
+ let backpressure = 0;
+ const server = createServer((req, res) => {
+ const write = res.write.bind(res);
+ jest.spyOn(res, 'write').mockImplementation((...args: Parameters<typeof res.write>) => {
+ const accepted = write(...args);
+ if (!accepted) backpressure++;
+ return accepted;
+ });
+ Object.assign(req, { params: request().params, user: request().user });
+ void handler(req as ServerRequest, res as Response).catch(() => res.destroy());
+ });
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const chunks: string[] = [];
+ try {
+ await new Promise<void>((resolve, reject) => {
+ const client = get(`http://127.0.0.1:${(server.address() as AddressInfo).port}`, (res) => {
+ res.setEncoding('utf8');
+ res.on('data', (chunk: string) => chunks.push(chunk));
+ res.on('end', resolve);
+ res.on('error', reject);
+ });
+ client.on('error', reject);
+ });
+ expect(backpressure).toBeGreaterThan(0);
+ const frames = chunks
+ .join('')
+ .split('\n\n')
+ .filter((frame) => frame.startsWith('data: '))
+ .map((frame) => JSON.parse(frame.slice(6)));
+ expect(frames[0].data[0].data.activitySequence).toBe(0);
+ expect(frames.slice(1, 5).map((frame) => frame.data.activitySequence)).toEqual([1, 2, 3, 4]);
+ expect(frames[5]).toMatchObject({ final: true, status: 'completed' });
+ expect(unsubscribe).toHaveBeenCalled();
+ } finally {
+ server.closeAllConnections();
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ }
+ });
});
diff --git a/packages/api/src/agents/subagentActivity.ts b/packages/api/src/agents/subagentActivity.ts
index 7e13c8d553..4b6cfeac75 100644
--- a/packages/api/src/agents/subagentActivity.ts
+++ b/packages/api/src/agents/subagentActivity.ts
@@ -1,17 +1,22 @@
-import { createHash } from 'node:crypto';
import { logger } from '@librechat/data-schemas';
+import { createHash, randomUUID } from 'node:crypto';
+import { subagentActivityConfigSchema } from 'librechat-data-provider';
import type { ConversationMethods, MessageMethods } from '@librechat/data-schemas';
+import type { TSubagentActivityConfig } from 'librechat-data-provider';
import type { SubagentUpdateEvent } from '@librechat/agents';
import type { Response } from 'express';
import type { IEventTransport } from '~/stream/interfaces/IJobStore';
import type { ServerRequest } from '~/types';
import { emitObservedChunk } from '~/stream/internal/chunkPublication';
+import { SUBAGENT_ACTIVITY_LIMITS } from './activity';
const STREAM_PREFIX = 'subagent-activity:';
const MAX_ID_BYTES = 512;
const MAX_LABEL_BYTES = 512;
const MAX_ANCESTRY_ENTRIES = 16;
-const MAX_EVENT_BYTES = 64 * 1024;
+/** Includes Redis type/data/seq wrappers and the largest safe omission count. */
+const REPLAY_WIRE_RESERVE_BYTES = 128;
+const MAX_EVENT_BYTES = SUBAGENT_ACTIVITY_LIMITS.bytes - REPLAY_WIRE_RESERVE_BYTES;
const HEARTBEAT_MS = 15_000;
const DEMAND_TTL_MS = 30_000;
const DEMAND_HEARTBEAT_MS = 10_000;
@@ -30,6 +35,12 @@ export type SubagentActivityUpdateEvent = SubagentUpdateEvent & {
export type SubagentActivityEnvelope = {
event: 'on_subagent_update';
data: SubagentActivityUpdateEvent;
+ droppedCount?: number;
+};
+
+export type SubagentActivityReplayEnvelope = {
+ event: 'subagent_activity_replay';
+ data: SubagentActivityEnvelope[];
};
export type SubagentActivitySubscription = {
@@ -38,7 +49,7 @@ export type SubagentActivitySubscription = {
};
export type SubagentActivitySubscriber = {
- onEvent: (event: SubagentActivityEnvelope) => void;
+ onEvent: (event: SubagentActivityEnvelope | SubagentActivityReplayEnvelope) => void;
onDone?: (event: {
final: true;
subagentActivity: true;
@@ -182,7 +193,19 @@ export const subagentActivityStreamId = (threadId: string, taskId: string): stri
export class SubagentActivityStream {
private readonly demandCache = new Map<string, { demanded: boolean; expiresAt: number }>();
- constructor(private readonly transport: IEventTransport) {}
+ private readonly replayLimits: { items: number; bytes: number; ttlMs: number };
+
+ constructor(
+ private readonly transport: IEventTransport,
+ options: Partial<TSubagentActivityConfig> = {},
+ ) {
+ const config = subagentActivityConfigSchema.parse(options);
+ this.replayLimits = {
+ items: SUBAGENT_ACTIVITY_LIMITS.items,
+ bytes: SUBAGENT_ACTIVITY_LIMITS.bytes,
+ ttlMs: config.replayTtlMs,
+ };
+ }
private async isDemanded(streamId: string): Promise<boolean> {
if (this.transport.hasDemand == null) return true;
@@ -213,13 +236,22 @@ export class SubagentActivityStream {
threadId: string,
taskId: string,
event: SubagentActivityUpdateEvent,
+ droppedCount = 0,
): Promise<void> {
const streamId = subagentActivityStreamId(threadId, taskId);
- if (!(await this.isDemanded(streamId))) return;
+ if (this.transport.emitReplayableChunk == null && !(await this.isDemanded(streamId))) return;
const envelope: SubagentActivityEnvelope = {
event: 'on_subagent_update',
data: boundSubagentActivityUpdate(event),
+ ...(droppedCount > 0 ? { droppedCount } : {}),
};
+ if (this.transport.emitReplayableChunk != null) {
+ await this.transport.emitReplayableChunk(streamId, envelope, this.replayLimits, {
+ id: `${droppedCount > 0 ? 'gap' : 'event'}:${envelope.data.activityEventId ?? envelope.data.activitySequence?.toString() ?? randomUUID()}`,
+ sequence: envelope.data.activitySequence,
+ });
+ return;
+ }
await emitObservedChunk(this.transport, streamId, envelope);
}
@@ -239,10 +271,17 @@ export class SubagentActivityStream {
};
/** subscribe() registers synchronously. Sampling zero before it distinguishes a fresh
* local attachment without moving an already-active shared reorder frontier. */
- const synchronizeAttachment = this.transport.getSubscriberCount(streamId) === 0;
+ const replayable = this.transport.emitReplayableChunk != null;
+ const synchronizeAttachment = !replayable && this.transport.getSubscriberCount(streamId) === 0;
const subscription = this.transport.subscribe(
streamId,
{
+ onReplay: (events) => {
+ subscriber.onEvent({
+ event: 'subagent_activity_replay',
+ data: events.filter(isActivityEnvelope),
+ });
+ },
onChunk: (event) => {
if (isActivityEnvelope(event)) subscriber.onEvent(event);
},
@@ -263,6 +302,7 @@ export class SubagentActivityStream {
},
},
{
+ ...(replayable ? { replay: this.replayLimits } : {}),
deferSequenceDelivery: synchronizeAttachment,
captureSequenceFrontier: synchronizeAttachment,
},
@@ -304,12 +344,15 @@ export class SubagentActivityStream {
const streamId = subagentActivityStreamId(threadId, taskId);
this.demandCache.delete(streamId);
try {
+ const terminal = { final: true, subagentActivity: true, status };
+ if (this.transport.emitReplayableDone != null) {
+ await this.transport.emitReplayableDone(streamId, terminal, this.replayLimits, {
+ id: 'done',
+ });
+ return;
+ }
if (!(await this.isDemanded(streamId))) return;
- await this.transport.emitDone(streamId, {
- final: true,
- subagentActivity: true,
- status,
- });
+ await this.transport.emitDone(streamId, terminal);
} finally {
this.demandCache.delete(streamId);
}
@@ -377,17 +420,120 @@ const notFound = (res: Response): void => {
res.status(404).json({ error: 'Conversation not found' });
};
-const writeSse = (res: Response, value: unknown): boolean =>
- !res.writableEnded && res.write(`data: ${JSON.stringify(value)}\n\n`);
+/** Snapshot plus attachment buffer can each hold one retention window. Public IDs
+ * may JSON-escape to six bytes per input byte; budget that expansion without trimming. */
+const MAX_PUBLIC_REPLAY_BYTES =
+ 2 * (SUBAGENT_ACTIVITY_LIMITS.bytes + SUBAGENT_ACTIVITY_LIMITS.items * (6 * MAX_ID_BYTES + 32)) +
+ 128;
+
+/** Node accepts a write that returns false. Hold later frames until drain instead of
+ * closing a healthy socket. One public snapshot has its own derived budget; later
+ * queued live activity retains the standard byte/item budget. */
+function createActivityWriter(res: Response, onClose: () => void) {
+ const pending: Array<{ frame: string; bytes: number }> = [];
+ let replaySent = false;
+ let pendingBytes = 0;
+ let blocked = false;
+ let ending = false;
+ let stopped = false;
+ let terminal: string | undefined;
+ const dispose = () => {
+ stopped = true;
+ pending.length = 0;
+ pendingBytes = 0;
+ terminal = undefined;
+ res.off('drain', flush);
+ };
+ const finish = () => {
+ dispose();
+ onClose();
+ if (!res.writableEnded && !res.destroyed) res.end();
+ };
+ const write = (frame: string) => {
+ if (res.writableEnded || res.destroyed) {
+ dispose();
+ onClose();
+ return;
+ }
+ blocked = !res.write(frame);
+ };
+ function flush(): void {
+ if (stopped) return;
+ blocked = false;
+ while (pending.length > 0 && !blocked && !stopped) {
+ const next = pending.shift()!;
+ pendingBytes -= next.bytes;
+ write(next.frame);
+ }
+ if (blocked || stopped || pending.length > 0) return;
+ if (terminal != null) {
+ const frame = terminal;
+ terminal = undefined;
+ write(frame);
+ }
+ if (ending && !blocked && !stopped) finish();
+ }
+ res.on('drain', flush);
+ return {
+ dispose,
+ isEnding: () => ending,
+ send: (value: unknown, final = false, replay = false): void => {
+ if (stopped || ending) return;
+ const frame = `data: ${JSON.stringify(value)}\n\n`;
+ if (final) {
+ ending = true;
+ terminal = frame;
+ } else {
+ const frameBytes = Buffer.byteLength(frame, 'utf8');
+ /** Reserve one bounded snapshot separately so public identity expansion cannot
+ * consume the live queue or cause a reconnect loop on an otherwise valid replay. */
+ const bytes = replay ? 0 : frameBytes;
+ if (replay && (replaySent || frameBytes > MAX_PUBLIC_REPLAY_BYTES)) {
+ finish();
+ return;
+ }
+ if (replay) replaySent = true;
+ if (!blocked && pending.length === 0) {
+ /** The socket accepts this already-bounded public frame. Queue limits govern
+ * waiting frames, not identity expansion of an immediately writable update. */
+ write(frame);
+ return;
+ }
+ if (
+ pending.length >= SUBAGENT_ACTIVITY_LIMITS.items ||
+ pendingBytes + bytes > SUBAGENT_ACTIVITY_LIMITS.bytes
+ ) {
+ /** A stalled reader cannot allocate unbounded memory; reconnect replays Redis. */
+ finish();
+ return;
+ }
+ pending.push({ frame, bytes });
+ pendingBytes += bytes;
+ }
+ if (!blocked) flush();
+ },
+ heartbeat: (): void => {
+ if (!stopped && !ending && !blocked) write(': keep-alive\n\n');
+ },
+ };
+}
/** Event-bound children use a private binding id as their internal tool-call
* identity. Keep that delivery identity behind the parent-authorized API
* boundary while preserving a stable public identity for the activity UI. */
const publicActivityEnvelope = (
- event: SubagentActivityEnvelope,
+ event: SubagentActivityEnvelope | SubagentActivityReplayEnvelope,
threadId: string,
eventBound: boolean,
-): SubagentActivityEnvelope => {
+): SubagentActivityEnvelope | SubagentActivityReplayEnvelope => {
+ if (event.event === 'subagent_activity_replay') {
+ return {
+ ...event,
+ data: event.data.map(
+ (entry) => publicActivityEnvelope(entry, threadId, eventBound) as SubagentActivityEnvelope,
+ ),
+ };
+ }
if (!eventBound) return event;
const ancestry = (event.data.ancestry ?? []).map((entry) => {
if (!entry.parentToolCallId?.startsWith('event-binding:')) return entry;
@@ -427,6 +573,7 @@ export function createSubagentActivityStreamHandler(
let closed = req.destroyed || res.destroyed;
let heartbeat: ReturnType<typeof setInterval> | undefined;
let subscription: SubagentActivitySubscription | undefined;
+ let writer: ReturnType<typeof createActivityWriter> | undefined;
const dispose = () => {
if (heartbeat != null) clearInterval(heartbeat);
subscription?.unsubscribe();
@@ -434,6 +581,7 @@ export function createSubagentActivityStreamHandler(
const close = () => {
closed = true;
dispose();
+ writer?.dispose();
};
req.once('aborted', close);
res.once('close', close);
@@ -471,39 +619,29 @@ export function createSubagentActivityStreamHandler(
res.setHeader('X-Accel-Buffering', 'no');
res.flushHeaders?.();
- heartbeat = setInterval(() => {
- if (!res.writableEnded && !res.write(': keep-alive\n\n')) {
- close();
- res.end();
- }
- }, HEARTBEAT_MS);
+ writer = createActivityWriter(res, close);
+ heartbeat = setInterval(() => writer?.heartbeat(), HEARTBEAT_MS);
heartbeat.unref?.();
try {
subscription = stream.subscribe(threadId, taskId, {
onEvent: (event) => {
- if (
- !writeSse(
- res,
- publicActivityEnvelope(
- event,
- threadId,
- lineage?.parentToolCallId?.startsWith('event-binding:') === true,
- ),
- )
- ) {
- close();
- res.end();
- }
+ writer?.send(
+ publicActivityEnvelope(
+ event,
+ threadId,
+ lineage?.parentToolCallId?.startsWith('event-binding:') === true,
+ ),
+ false,
+ event.event === 'subagent_activity_replay',
+ );
},
onDone: (event) => {
- close();
- writeSse(res, event);
- res.end();
+ dispose();
+ writer?.send(event, true);
},
onError: () => {
- close();
- writeSse(res, { error: 'Subagent activity stream unavailable' });
- res.end();
+ dispose();
+ writer?.send({ error: 'Subagent activity stream unavailable' }, true);
},
});
await subscription.ready;
@@ -513,23 +651,25 @@ export function createSubagentActivityStreamHandler(
dispose();
throw error;
}
- if (closed || res.destroyed) return;
+ if (closed || res.destroyed || writer.isEnding()) {
+ dispose();
+ return;
+ }
const durableTerminal = await terminalTaskStatus(deps, userId, threadId, taskId, tenantId);
- if (closed || res.destroyed) return;
+ if (closed || res.destroyed || writer.isEnding()) return;
if (durableTerminal != null) {
- close();
- writeSse(res, {
- final: true,
- subagentActivity: true,
- status: durableTerminal,
- });
- res.end();
+ dispose();
+ writer.send(
+ {
+ final: true,
+ subagentActivity: true,
+ status: durableTerminal,
+ },
+ true,
+ );
return;
}
- if (!writeSse(res, { ready: true })) {
- close();
- res.end();
- }
+ writer.send({ ready: true });
} catch (error) {
if (closed || res.destroyed) return;
logger.error('[subagentActivity] Failed to open child activity stream', error);
@@ -537,8 +677,8 @@ export function createSubagentActivityStreamHandler(
res.status(500).json({ error: 'Failed to open subagent activity stream' });
return;
}
- writeSse(res, { error: 'Subagent activity stream unavailable' });
- res.end();
+ dispose();
+ writer?.send({ error: 'Subagent activity stream unavailable' }, true);
}
};
}
diff --git a/packages/api/src/agents/subagentCrossReplica.integration.spec.ts b/packages/api/src/agents/subagentCrossReplica.integration.spec.ts
index fc946ddfab..fda20c2d99 100644
--- a/packages/api/src/agents/subagentCrossReplica.integration.spec.ts
+++ b/packages/api/src/agents/subagentCrossReplica.integration.spec.ts
@@ -342,7 +342,10 @@ describeWithRedis('subagent cross-replica orchestration', () => {
accepted(first).task.threadId!,
firstTaskId,
{
- onEvent: (event) => remoteActivity.push(event),
+ onEvent: (event) =>
+ remoteActivity.push(
+ ...(event.event === 'subagent_activity_replay' ? event.data : [event]),
+ ),
onDone: (event) => resolveRemoteDone(event.status),
},
);
diff --git a/packages/api/src/agents/subagentThreads.spec.ts b/packages/api/src/agents/subagentThreads.spec.ts
index 410261e711..003a8aaa17 100644
--- a/packages/api/src/agents/subagentThreads.spec.ts
+++ b/packages/api/src/agents/subagentThreads.spec.ts
@@ -29,6 +29,7 @@ import type {
} from './subagentTaskRouting';
import type { SubagentTaskWakeupRegistration } from './subagentThreads';
import type { IEventTransport } from '~/stream/interfaces/IJobStore';
+import type { SubagentActivityEnvelope } from './subagentActivity';
import type { UsageMetadata } from '~/stream/interfaces/IJobStore';
import {
buildSubagentThreadTaskConfig,
@@ -39,6 +40,7 @@ import { controlFingerprint, SubagentTaskOwnerUnavailableError } from './subagen
import { SUBAGENT_COMPLETION_DELIVERY } from './subagentDelivery';
import { createSubagentAttemptKey } from './subagentThreadIds';
import { SubagentActivityStream } from './subagentActivity';
+import { InMemoryEventTransport } from '~/stream';
import { createSubagentUsageSink } from './usage';
let mongod: MongoMemoryServer;
@@ -215,8 +217,9 @@ async function waitForSettled(
async function waitUntil(
condition: () => boolean | Promise<boolean>,
description: string,
+ timeoutMs = 4_000,
): Promise<void> {
- for (let attempt = 0; attempt < 400; attempt += 1) {
+ for (let attempt = 0; attempt < Math.ceil(timeoutMs / 10); attempt += 1) {
if (await condition()) {
return;
}
@@ -305,6 +308,97 @@ describe('SubagentThreadTaskStore', () => {
await expect(automaticStore.listTasks(automatic.scopeId)).resolves.toEqual([]);
});
+ it('scopes the plain agent-name lookup to the execution tenant', async () => {
+ const userId = new mongoose.Types.ObjectId().toString();
+ const id = 'tenant-name-agent';
+ await tenantStorage.run({ tenantId: 'name-tenant-a', userId }, async () => {
+ await methods.createAgent({
+ id,
+ name: 'Scoped Reviewer',
+ author: userId,
+ provider: 'openAI',
+ model: 'test-model',
+ });
+ expect(await methods.getAgentName(id, 'name-tenant-a')).toBe('Scoped Reviewer');
+ expect(await methods.getAgentName(id, 'name-tenant-b')).toBeUndefined();
+ expect(await methods.getAgentName(id)).toBeUndefined();
+ });
+ });
+
+ it('keeps child execution independent of display-name lookup failure', async () => {
+ const userId = 'name-fallback-user';
+ const parentConversationId = randomUUID();
+ await saveParent(userId, parentConversationId);
+ jest
+ .spyOn(methods, 'getAgentName')
+ .mockRejectedValueOnce(new Error('display-name lookup unavailable'));
+ const store = new SubagentThreadTaskStore(methods);
+ const config = buildSubagentThreadTaskConfig(store, { userId, parentConversationId });
+ const started = store.start(taskRequest(config.scopeId));
+ await waitForSettled(store, config.scopeId, started);
+ expect(store.get(config.scopeId, requireAccepted(started).task.taskId)?.status).toBe(
+ 'completed',
+ );
+ expect((await methods.getConvo(userId, requireThreadId(started)))?.title).toBe(
+ 'researcher-agent',
+ );
+ store.destroyActivityStream();
+ });
+
+ it('resolves legacy null-tenant names without crossing tenant boundaries', async () => {
+ const userId = new mongoose.Types.ObjectId().toString();
+ await methods.createAgent({
+ id: 'null-tenant-agent',
+ name: 'Legacy Reviewer',
+ author: userId,
+ provider: 'openAI',
+ model: 'test-model',
+ });
+ await mongoose.connection
+ .collection('agents')
+ .updateOne({ id: 'null-tenant-agent' }, { $set: { tenantId: null } });
+ expect(await methods.getAgentName('null-tenant-agent')).toBe('Legacy Reviewer');
+ expect(await methods.getAgentName('null-tenant-agent', 'other-tenant')).toBeUndefined();
+ const parentConversationId = randomUUID();
+ await saveParent(userId, parentConversationId);
+ const store = new SubagentThreadTaskStore(methods);
+ const config = buildSubagentThreadTaskConfig(store, { userId, parentConversationId });
+ const started = store.start(taskRequest(config.scopeId, { subagentType: 'null-tenant-agent' }));
+ await waitForSettled(store, config.scopeId, started);
+ expect((await methods.getConvo(userId, requireThreadId(started)))?.title).toBe(
+ 'Legacy Reviewer',
+ );
+ store.destroyActivityStream();
+ });
+
+ it('persists the child agent name and falls back to its id', async () => {
+ const userId = new mongoose.Types.ObjectId().toString();
+ const parentConversationId = randomUUID();
+ await saveParent(userId, parentConversationId);
+ await methods.createAgent({
+ id: 'researcher-agent',
+ name: 'PR Reviewer',
+ author: userId,
+ provider: 'openAI',
+ model: 'test-model',
+ });
+ const store = new SubagentThreadTaskStore(methods);
+ const config = buildSubagentThreadTaskConfig(store, { userId, parentConversationId });
+ const named = store.start(taskRequest(config.scopeId));
+ await waitForSettled(store, config.scopeId, named);
+ expect((await methods.getConvo(userId, requireThreadId(named)))?.title).toBe('PR Reviewer');
+ const unnamed = store.start(
+ taskRequest(config.scopeId, {
+ subagentType: 'missing-agent',
+ idempotencyKey: randomUUID(),
+ parentToolCallId: 'second-call',
+ }),
+ );
+ await waitForSettled(store, config.scopeId, unnamed);
+ expect((await methods.getConvo(userId, requireThreadId(unnamed)))?.title).toBe('missing-agent');
+ store.destroyActivityStream();
+ });
+
it('maps one logical SDK thread to a durable, view-only LibreChat conversation', async () => {
const userId = 'user-1';
const parentConversationId = randomUUID();
@@ -563,6 +657,7 @@ describe('SubagentThreadTaskStore', () => {
await expect(terminal).resolves.toBe('completed');
expect(events).toEqual([
+ { event: 'subagent_activity_replay', data: [] },
{
event: 'on_subagent_update',
data: expect.objectContaining({
@@ -648,6 +743,153 @@ describe('SubagentThreadTaskStore', () => {
expect(publicationOrder).toEqual(['first', 'second', 'done']);
});
+ it('retries a transient publication and shows overflow counts without blocking persistence', async () => {
+ const userId = 'activity-recovery-user';
+ const parentConversationId = randomUUID();
+ await saveParent(userId, parentConversationId);
+ const store = new SubagentThreadTaskStore(methods, {
+ activity: {
+ publicationTimeoutMs: 200,
+ retryAttempts: 3,
+ retryBaseDelayMs: 10,
+ recoveryDelayMs: 100,
+ },
+ });
+ const stream = new SubagentActivityStream(new InMemoryEventTransport());
+ store.configureActivityStream(stream);
+ const originalPublish = stream.publish.bind(stream);
+ let release!: () => void;
+ const blocked = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const publish = jest
+ .spyOn(stream, 'publish')
+ .mockRejectedValueOnce(new Error('transient Redis failure'));
+ publish.mockImplementationOnce(async (...args) => {
+ await blocked;
+ return originalPublish(...args);
+ });
+ const config = buildSubagentThreadTaskConfig(store, { userId, parentConversationId });
+ const defaultRun = taskRequest(config.scopeId).run;
+ const run = async (...args: Parameters<typeof defaultRun>) => {
+ for (let i = 0; i < 120; i++)
+ args[0].reportProgress({
+ runId: 'parent',
+ parentRunId: 'parent',
+ subagentRunId: 'child',
+ subagentType: 'researcher-agent',
+ subagentKind: 'agent',
+ subagentAgentId: 'agent-1',
+ depth: 1,
+ ancestry: [],
+ phase: 'message_delta',
+ data: { delta: { content: [{ type: 'text', text: `${i},` }] } },
+ timestamp: '2026-09-29T00:00:00.000Z',
+ });
+ return defaultRun(...args);
+ };
+ const started = store.start(taskRequest(config.scopeId, { run }));
+ const events: SubagentActivityEnvelope[] = [];
+ const onDone = jest.fn();
+ const subscription = store.subscribeActivity(
+ requireThreadId(started),
+ requireAccepted(started).task.taskId,
+ {
+ onEvent: (event) => {
+ if (event.event === 'on_subagent_update') events.push(event);
+ },
+ onDone,
+ },
+ );
+ await subscription.ready;
+ await waitForSettled(store, config.scopeId, started);
+ await waitUntil(() => publish.mock.calls.length === 2, 'retry after transient failure');
+ release();
+ await waitUntil(() => onDone.mock.calls.length === 1, 'recovered activity terminal');
+ expect(events[0].data.activitySequence).toBe(0);
+ expect(events[events.length - 1].data.activitySequence).toBe(119);
+ expect(events.reduce((count, event) => count + (event.droppedCount ?? 0), 0)).toBe(19);
+ expect(events).toHaveLength(102);
+ const durable = await methods.getMessages({
+ user: userId,
+ conversationId: requireThreadId(started),
+ messageId: `${requireAccepted(started).task.taskId}:assistant`,
+ });
+ expect(durable).toHaveLength(1);
+ subscription.unsubscribe();
+ store.destroyActivityStream();
+ });
+
+ it.each([true, false])(
+ 'drains activity admitted during worker release before DONE (hold run: %s)',
+ async (holdRun) => {
+ const userId = `activity-handoff-${holdRun}`;
+ const parentConversationId = randomUUID();
+ await saveParent(userId, parentConversationId);
+ const store = new SubagentThreadTaskStore(methods);
+ const config = buildSubagentThreadTaskConfig(store, { userId, parentConversationId });
+ const defaultRun = taskRequest(config.scopeId).run;
+ let activityRuntime!: SubagentTaskRuntime;
+ let release!: () => void;
+ const finish = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const progress: SubagentUpdateEvent = {
+ runId: 'parent',
+ parentRunId: 'parent',
+ subagentRunId: 'child',
+ subagentType: 'researcher-agent',
+ subagentKind: 'agent',
+ subagentAgentId: 'agent-1',
+ depth: 1,
+ ancestry: [],
+ phase: 'message_delta',
+ data: { delta: { content: [{ type: 'text', text: 'first' }] } },
+ timestamp: '2026-09-29T00:00:00.000Z',
+ };
+ const drainStore = store as object as { drainActivity: (typeof store)['drainActivity'] };
+ const originalDrain = drainStore.drainActivity.bind(store);
+ jest.spyOn(drainStore, 'drainActivity').mockImplementationOnce(async (...args) => {
+ await originalDrain(...args);
+ activityRuntime.reportProgress({
+ ...progress,
+ data: { delta: { content: [{ type: 'text', text: 'last' }] } },
+ });
+ });
+ const run = async (...args: Parameters<typeof defaultRun>) => {
+ activityRuntime = args[0];
+ activityRuntime.reportProgress(progress);
+ if (holdRun) await finish;
+ return defaultRun(...args);
+ };
+ const started = store.start(taskRequest(config.scopeId, { run }));
+ const received: Array<number | 'done'> = [];
+ const subscription = store.subscribeActivity(
+ requireThreadId(started),
+ requireAccepted(started).task.taskId,
+ {
+ onEvent: (envelope) => {
+ const events =
+ envelope.event === 'subagent_activity_replay' ? envelope.data : [envelope];
+ for (const event of events)
+ if (event.data.activitySequence != null) received.push(event.data.activitySequence);
+ },
+ onDone: () => {
+ received.push('done');
+ },
+ },
+ );
+ await subscription.ready;
+ await waitUntil(() => received.includes(1), 'activity admitted at the idle handoff');
+ release();
+ await waitUntil(() => received.includes('done'), 'terminal after all admitted activity');
+ expect(received).toEqual([0, 1, 'done']);
+ await waitForSettled(store, config.scopeId, started);
+ subscription.unsubscribe();
+ store.destroyActivityStream();
+ },
+ );
+
it('keeps activity delivery observational when its transport is unavailable', async () => {
const userId = 'activity-stream-failure-user';
const parentConversationId = randomUUID();
@@ -709,7 +951,10 @@ describe('SubagentThreadTaskStore', () => {
expect(store.get(config.scopeId, requireAccepted(started).task.taskId)?.status).toBe(
'completed',
);
- expect(emitChunk).toHaveBeenCalledTimes(1);
+ await waitUntil(
+ () => emitChunk.mock.calls.length === 6,
+ 'bounded activity and gap-marker retries',
+ );
});
it('bounds stalled activity and still attempts terminal delivery', async () => {
@@ -774,8 +1019,8 @@ describe('SubagentThreadTaskStore', () => {
expect(store.get(config.scopeId, requireAccepted(started).task.taskId)?.status).toBe(
'completed',
);
- await waitUntil(() => emitDone.mock.calls.length === 1, 'terminal activity delivery');
- expect(emitChunk).toHaveBeenCalledTimes(1);
+ await waitUntil(() => emitDone.mock.calls.length === 1, 'terminal activity delivery', 10_000);
+ expect(emitChunk).toHaveBeenCalledTimes(6);
});
it('fails before provider work and keeps the durable failure collectable when registration fails', async () => {
diff --git a/packages/api/src/agents/subagentThreads.ts b/packages/api/src/agents/subagentThreads.ts
index f3bae71a20..10171e48ae 100644
--- a/packages/api/src/agents/subagentThreads.ts
+++ b/packages/api/src/agents/subagentThreads.ts
@@ -1,7 +1,7 @@
import { randomUUID } from 'node:crypto';
import { InMemorySubagentTaskStore } from '@librechat/agents';
import { logger, tenantStorage } from '@librechat/data-schemas';
-import { EModelEndpoint, Constants } from 'librechat-data-provider';
+import { EModelEndpoint, Constants, subagentActivityConfigSchema } from 'librechat-data-provider';
import {
mapChatMessagesToStoredMessages,
mapStoredMessagesToChatMessages,
@@ -29,6 +29,7 @@ import type {
SubagentTaskResultClaim,
} from '@librechat/data-schemas';
import type { BaseMessage, StoredMessage } from '@librechat/agents/langchain/messages';
+import type { TSubagentActivityConfig } from 'librechat-data-provider';
import type {
SubagentActivityUpdateEvent,
SubagentActivitySubscriber,
@@ -46,10 +47,10 @@ import {
} from './subagentTaskRouting';
import { boundSubagentActivityUpdate, SubagentActivityStream } from './subagentActivity';
import { createSubagentAttemptKey, createSubagentThreadId } from './subagentThreadIds';
+import { SUBAGENT_ACTIVITY_LIMITS, projectSubagentActivity } from './activity';
import { runWithDetachedSubagentUsage } from './subagentTaskContext';
import { SUBAGENT_COMPLETION_DELIVERY } from './subagentDelivery';
import { createConcurrencyLimiter } from '~/utils/promise';
-import { projectSubagentActivity } from './activity';
import { InMemoryEventTransport } from '~/stream';
import { aggregateEmittedUsage } from './usage';
@@ -76,9 +77,7 @@ const DEFAULT_CONTROL_RECEIPT_RETRY_MS = 5_000;
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 = 32;
-/** Live activity must never delay terminal notification indefinitely. */
-const ACTIVITY_PUBLICATION_TIMEOUT_MS = 1_000;
+const MAX_PENDING_ACTIVITY_EVENTS = SUBAGENT_ACTIVITY_LIMITS.items;
/** A cancellation target set resolved before the conversations are removed. */
export interface SubagentCancellationPlan {
@@ -118,7 +117,8 @@ type SubagentThreadMethods = Pick<
| 'renewSubagentThreadLease'
| 'saveConvo'
| 'saveMessage'
->;
+> &
+ Partial<Pick<AllMethods, 'getAgentName'>>;
interface SubagentThreadScope {
version: typeof SCOPE_VERSION;
@@ -201,11 +201,16 @@ interface TaskThreadLease {
execution?: Promise<void>;
/** Ordered observational tail; canonical child settlement never awaits it. */
activityTail?: Promise<void>;
- activityPending?: number;
+ activityWorkerActive?: boolean;
+ activityQueue?: Array<{
+ event: SubagentActivityUpdateEvent;
+ bytes: number;
+ droppedCount?: number;
+ }>;
+ activityQueuedBytes?: number;
+ activityDropped?: { event: SubagentActivityUpdateEvent; count: number };
/** Terminal settlement stops new admission but must not discard admitted events. */
activityAdmissionClosed?: boolean;
- /** A failed observational publication suppresses the remainder of this task's queue. */
- activityCircuitOpen?: boolean;
shared?: {
token: string;
lost: boolean;
@@ -223,7 +228,7 @@ class SubagentActivityPublicationTimeoutError extends Error {
}
}
-async function settleActivityWithin(operation: Promise<void>): Promise<void> {
+async function settleActivityWithin(operation: Promise<void>, timeoutMs: number): Promise<void> {
let timeout: ReturnType<typeof setTimeout> | undefined;
try {
await Promise.race([
@@ -231,7 +236,7 @@ async function settleActivityWithin(operation: Promise<void>): Promise<void> {
new Promise<void>((_, reject) => {
timeout = setTimeout(
() => reject(new SubagentActivityPublicationTimeoutError()),
- ACTIVITY_PUBLICATION_TIMEOUT_MS,
+ timeoutMs,
);
timeout.unref?.();
}),
@@ -242,6 +247,7 @@ async function settleActivityWithin(operation: Promise<void>): Promise<void> {
}
export interface SubagentThreadTaskStoreOptions extends InMemorySubagentTaskStoreOptions {
+ activity?: Partial<TSubagentActivityConfig>;
maxThreadDepth?: number;
leaseTtlMs?: number;
leaseHeartbeatMs?: number;
@@ -629,6 +635,7 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
/** Tasks whose completion wake-up was registered; only they announce settlement. */
private readonly wakeupTaskIds = new Set<string>();
private taskControlTransport?: SubagentTaskControlTransport;
+ private activityOptions: TSubagentActivityConfig = subagentActivityConfigSchema.parse({});
private activityStream = new SubagentActivityStream(new InMemoryEventTransport());
constructor(
@@ -636,6 +643,7 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
options: SubagentThreadTaskStoreOptions = {},
) {
super(options);
+ this.configureActivity(options.activity);
this.maxThreadDepth =
Number.isSafeInteger(options.maxThreadDepth) && (options.maxThreadDepth ?? 0) > 0
? (options.maxThreadDepth as number)
@@ -1163,6 +1171,21 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
}
}
+ /** Host injects the base configuration before task admission. */
+ configureActivity(options: Partial<TSubagentActivityConfig> = {}): TSubagentActivityConfig {
+ this.activityOptions = subagentActivityConfigSchema.parse(options);
+ this.configureActivityStream(
+ new SubagentActivityStream(
+ new InMemoryEventTransport({
+ maxStreams: this.activityOptions.memoryMaxStreams,
+ maxBytes: this.activityOptions.memoryMaxBytes,
+ }),
+ this.activityOptions,
+ ),
+ );
+ return this.activityOptions;
+ }
+
/** Replaces the process-local activity bus after the host's Redis service is ready. */
configureActivityStream(stream: SubagentActivityStream): void {
const previous = this.activityStream;
@@ -1200,30 +1223,110 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
taskId: string,
event: SubagentUpdateEvent,
): void {
+ if (lease.activityAdmissionClosed === true) return;
+ const boundedEvent = boundSubagentActivityUpdate(event);
+ const bytes = Buffer.byteLength(JSON.stringify(boundedEvent), 'utf8');
+ const queue = (lease.activityQueue ??= []);
if (
- lease.activityAdmissionClosed === true ||
- lease.activityCircuitOpen === true ||
- (lease.activityPending ?? 0) >= MAX_PENDING_ACTIVITY_EVENTS
+ queue.length >= MAX_PENDING_ACTIVITY_EVENTS ||
+ (lease.activityQueuedBytes ?? 0) + bytes > SUBAGENT_ACTIVITY_LIMITS.bytes
) {
+ lease.activityDropped = {
+ event: boundedEvent,
+ count: (lease.activityDropped?.count ?? 0) + 1,
+ };
return;
}
- lease.activityPending = (lease.activityPending ?? 0) + 1;
- const boundedEvent = boundSubagentActivityUpdate(event);
- const publication = (lease.activityTail ?? Promise.resolve())
- .then(() => {
- if (lease.activityCircuitOpen === true) return;
- return settleActivityWithin(this.activityStream.publish(threadId, taskId, boundedEvent));
- })
- .catch((error) => {
- /** Any failed observational command opens the per-task circuit. Retrying every
- * token during an outage only creates command/log pressure; durable state remains. */
- lease.activityCircuitOpen = true;
- logger.warn('[subagentThreads] Failed to publish child activity', error);
- })
- .finally(() => {
- lease.activityPending = Math.max(0, (lease.activityPending ?? 1) - 1);
- });
- lease.activityTail = publication;
+ if (lease.activityDropped != null) {
+ /** Preserve ordering: an overflow suffix stays a gap until the worker has drained it. */
+ lease.activityDropped = { event: boundedEvent, count: lease.activityDropped.count + 1 };
+ return;
+ }
+ queue.push({ event: boundedEvent, bytes });
+ lease.activityQueuedBytes = (lease.activityQueuedBytes ?? 0) + bytes;
+ this.startActivityWorker(lease, threadId, taskId);
+ }
+
+ private hasPendingActivity(lease: TaskThreadLease): boolean {
+ return (lease.activityQueue?.length ?? 0) > 0 || lease.activityDropped != null;
+ }
+
+ private startActivityWorker(lease: TaskThreadLease, threadId: string, taskId: string): void {
+ if (
+ lease.activityWorkerActive === true ||
+ lease.activityAdmissionClosed === true ||
+ !this.hasPendingActivity(lease)
+ )
+ return;
+ lease.activityWorkerActive = true;
+ const worker = this.drainActivity(lease, threadId, taskId).finally(() => {
+ lease.activityWorkerActive = false;
+ if (lease.activityTail === worker) lease.activityTail = undefined;
+ if (this.hasPendingActivity(lease)) this.startActivityWorker(lease, threadId, taskId);
+ });
+ lease.activityTail = worker;
+ }
+
+ private async retryActivity(operation: () => Promise<void>): Promise<boolean> {
+ for (let attempt = 0; attempt < this.activityOptions.retryAttempts; attempt++) {
+ try {
+ await settleActivityWithin(operation(), this.activityOptions.publicationTimeoutMs);
+ return true;
+ } catch (error) {
+ if (attempt + 1 === this.activityOptions.retryAttempts) {
+ logger.warn(
+ '[subagentThreads] Failed to publish child activity after bounded retries',
+ error,
+ );
+ return false;
+ }
+ await new Promise<void>((resolve) =>
+ setTimeout(
+ resolve,
+ Math.min(
+ this.activityOptions.recoveryDelayMs,
+ this.activityOptions.retryBaseDelayMs * 2 ** attempt,
+ ),
+ ),
+ );
+ }
+ }
+ return false;
+ }
+
+ private async drainActivity(
+ lease: TaskThreadLease,
+ threadId: string,
+ taskId: string,
+ ): Promise<void> {
+ const queue = lease.activityQueue!;
+ while (queue.length > 0 || lease.activityDropped != null) {
+ const next = queue.shift();
+ if (next != null) lease.activityQueuedBytes = (lease.activityQueuedBytes ?? 0) - next.bytes;
+ const dropped = next == null ? lease.activityDropped : undefined;
+ if (dropped != null) lease.activityDropped = undefined;
+ const event =
+ next?.event ?? (dropped == null ? undefined : { ...dropped.event, data: undefined });
+ if (event == null) continue;
+ const droppedCount = next?.droppedCount ?? dropped?.count ?? 0;
+ const published = await this.retryActivity(() =>
+ this.activityStream.publish(threadId, taskId, event, droppedCount),
+ );
+ if (!published) {
+ /** Keep the failed suffix visible on recovery without retrying an unbounded number of events. */
+ const pending = queue.splice(0);
+ const last = lease.activityDropped?.event ?? pending[pending.length - 1]?.event ?? event;
+ lease.activityDropped = {
+ event: last,
+ count: (lease.activityDropped?.count ?? 0) + pending.length + Math.max(1, droppedCount),
+ };
+ lease.activityQueuedBytes = 0;
+ if (lease.activityAdmissionClosed === true) break;
+ await new Promise<void>((resolve) =>
+ setTimeout(resolve, this.activityOptions.recoveryDelayMs),
+ );
+ }
+ }
}
private completeActivity(
@@ -1234,7 +1337,10 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
): void {
lease.activityAdmissionClosed = true;
const terminal = (lease.activityTail ?? Promise.resolve())
- .then(() => settleActivityWithin(this.activityStream.complete(threadId, taskId, status)))
+ .then(async () => {
+ if (this.hasPendingActivity(lease)) await this.drainActivity(lease, threadId, taskId);
+ await this.retryActivity(() => this.activityStream.complete(threadId, taskId, status));
+ })
.catch((error) => {
logger.warn('[subagentThreads] Failed to close child activity stream', error);
});
@@ -2775,9 +2881,16 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
if (!(await this.isOwnerActive(scope.userId))) {
throw new SubagentThreadPublicError('The thread owner is unavailable.');
}
- const [parent, existing] = await Promise.all([
+ const agentId = childAgentId(request);
+ const [parent, existing, agentName] = await Promise.all([
this.methods.getConvo(scope.userId, scope.parentConversationId),
this.methods.getConvo(scope.userId, threadId),
+ isContinuation || agentId == null
+ ? undefined
+ : this.methods.getAgentName?.(agentId, scope.tenantId).catch((error) => {
+ logger.warn('[subagentThreads] Failed to resolve child display name', error);
+ return undefined;
+ }),
]);
if (parent == null || !matchesTenant(parent.tenantId, scope.tenantId)) {
throw new SubagentThreadPublicError('Parent thread is unavailable.');
@@ -2800,7 +2913,6 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
);
}
const depth = parentDepth + 1;
- const agentId = childAgentId(request);
const reserved = await this.methods.reserveSubagentThread({
user: scope.userId,
conversationId: threadId,
@@ -2808,7 +2920,7 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
conversation: {
conversationId: threadId,
endpoint: EModelEndpoint.agents,
- title: `Subagent: ${request.subagentType}`.slice(0, 120),
+ title: (agentName || agentId || request.subagentType).slice(0, 120),
...(agentId == null ? {} : { agent_id: agentId }),
...retentionFields(parent),
subagentThread: {
@@ -3476,7 +3588,8 @@ export function createSubagentThreadTaskStore(
| 'getMessages'
| 'recordSubagentTaskControlReceipt'
| 'saveMessage'
- >,
+ > &
+ Partial<Pick<AllMethods, 'getAgentName'>>,
options?: SubagentThreadTaskStoreOptions,
): SubagentThreadTaskStore {
/** The host wires this from JavaScript, where the parameter type checks nothing. A
diff --git a/packages/api/src/stream/__tests__/replay.spec.ts b/packages/api/src/stream/__tests__/replay.spec.ts
new file mode 100644
index 0000000000..61f9cd730d
--- /dev/null
+++ b/packages/api/src/stream/__tests__/replay.spec.ts
@@ -0,0 +1,93 @@
+import { InMemoryEventTransport } from '../implementations/InMemoryEventTransport';
+
+const limits = { items: 100, bytes: 65_536, ttlMs: 1_000 };
+
+async function replay(transport: InMemoryEventTransport, streamId: string) {
+ const events: unknown[] = [];
+ const subscription = transport.subscribe(
+ streamId,
+ { onChunk: (event) => events.push(event) },
+ { replay: limits },
+ );
+ await subscription.ready;
+ subscription.unsubscribe();
+ return events;
+}
+
+describe('bounded local replay', () => {
+ afterEach(() => {
+ jest.useRealTimers();
+ });
+
+ it('caps total entries and timer count while retaining recent streams', async () => {
+ jest.useFakeTimers();
+ const transport = new InMemoryEventTransport({ maxStreams: 2, maxBytes: 65_536 });
+ for (let index = 0; index < 20; index++)
+ await transport.emitReplayableChunk(`task-${index}`, { text: `${index}` }, limits);
+ expect(jest.getTimerCount()).toBe(2);
+ expect(await replay(transport, 'task-0')).toEqual([]);
+ expect(await replay(transport, 'task-18')).toEqual([{ text: '18' }]);
+ expect(await replay(transport, 'task-19')).toEqual([{ text: '19' }]);
+ transport.destroy();
+ jest.runAllTicks();
+ expect(jest.getTimerCount()).toBe(0);
+ });
+
+ it('caps aggregate encoded bytes separately from per-stream budgets', async () => {
+ const transport = new InMemoryEventTransport({ maxStreams: 10, maxBytes: 65_536 });
+ await transport.emitReplayableChunk('old', { text: 'x'.repeat(40_000) }, limits);
+ await transport.emitReplayableChunk('new', { text: 'y'.repeat(40_000) }, limits);
+ expect(await replay(transport, 'old')).toEqual([]);
+ expect(await replay(transport, 'new')).toHaveLength(1);
+ transport.destroy();
+ });
+
+ it('accounts for expiry and refresh without evicting a later replacement', async () => {
+ jest.useFakeTimers();
+ const transport = new InMemoryEventTransport({ maxStreams: 2, maxBytes: 65_536 });
+ await transport.emitReplayableChunk('task', { text: 'first' }, limits);
+ jest.advanceTimersByTime(500);
+ await transport.emitReplayableChunk('task', { text: 'second' }, limits);
+ jest.advanceTimersByTime(501);
+ expect(await replay(transport, 'task')).toHaveLength(2);
+ jest.advanceTimersByTime(500);
+ expect(await replay(transport, 'task')).toEqual([]);
+ jest.runAllTicks();
+ expect(jest.getTimerCount()).toBe(0);
+ transport.destroy();
+ });
+
+ it('deduplicates chunk and terminal retries with bounded publication state', async () => {
+ const transport = new InMemoryEventTransport();
+ const received: unknown[] = [];
+ const onDone = jest.fn();
+ const subscription = transport.subscribe(
+ 'task',
+ { onChunk: (event) => received.push(event), onDone },
+ { replay: limits },
+ );
+ await subscription.ready;
+ await transport.emitReplayableChunk('task', { text: 'first' }, limits, {
+ id: '0',
+ sequence: 0,
+ });
+ await transport.emitReplayableChunk('task', { text: 'first' }, limits, {
+ id: '0',
+ sequence: 0,
+ });
+ await transport.emitReplayableChunk('task', { text: 'second' }, limits, {
+ id: '1',
+ sequence: 1,
+ });
+ await transport.emitReplayableChunk('task', { text: 'first' }, limits, {
+ id: '0',
+ sequence: 0,
+ });
+ await transport.emitReplayableDone('task', { final: true }, limits, { id: 'done' });
+ await transport.emitReplayableDone('task', { final: true }, limits, { id: 'done' });
+ expect(received).toEqual([{ text: 'first' }, { text: 'second' }]);
+ expect(onDone).toHaveBeenCalledTimes(1);
+ subscription.unsubscribe();
+ transport.destroy();
+ });
+});
diff --git a/packages/api/src/stream/__tests__/subagentReplay.stream_integration.spec.ts b/packages/api/src/stream/__tests__/subagentReplay.stream_integration.spec.ts
new file mode 100644
index 0000000000..051037509f
--- /dev/null
+++ b/packages/api/src/stream/__tests__/subagentReplay.stream_integration.spec.ts
@@ -0,0 +1,386 @@
+import { randomUUID } from 'node:crypto';
+import IoRedis, { Cluster } from 'ioredis';
+import type { Redis } from 'ioredis';
+import type { SubagentActivityEnvelope } from '~/agents/subagentActivity';
+import {
+ SubagentActivityStream,
+ subagentActivityStreamId,
+ boundSubagentActivityUpdate,
+} from '~/agents/subagentActivity';
+import { RedisEventTransport } from '../implementations/RedisEventTransport';
+import { SUBAGENT_ACTIVITY_LIMITS } from '~/agents/activity';
+import { READ_REPLAY_LUA } from '../internal/replay';
+
+const clients: Array<Redis | Cluster> = [];
+const transports: RedisEventTransport[] = [];
+const subscriptions: Array<{ unsubscribe: () => void }> = [];
+const prefix = `activity-replay-${randomUUID()}:`;
+
+async function client(): Promise<Redis | Cluster> {
+ const urls = (process.env.REDIS_URI ?? 'redis://127.0.0.1:6379').split(',');
+ const options = { keyPrefix: prefix, maxRetriesPerRequest: 1, enableOfflineQueue: false };
+ const connection =
+ process.env.USE_REDIS_CLUSTER === 'true'
+ ? new Cluster(
+ urls.map((uri) => {
+ const url = new URL(uri);
+ return { host: url.hostname, port: Number(url.port) };
+ }),
+ { redisOptions: options, lazyConnect: true },
+ )
+ : new IoRedis(urls[0], { ...options, lazyConnect: true });
+ clients.push(connection);
+ await connection.connect();
+ return connection;
+}
+
+async function replica() {
+ const [publisher, subscriber] = await Promise.all([client(), client()]);
+ const transport = new RedisEventTransport(publisher, subscriber);
+ transports.push(transport);
+ return { publisher, transport, stream: new SubagentActivityStream(transport) };
+}
+
+async function waitUntil(predicate: () => boolean) {
+ const deadline = Date.now() + 5_000;
+ while (!predicate()) {
+ if (Date.now() > deadline) throw new Error('Timed out waiting for activity');
+ await new Promise<void>((resolve) => setTimeout(resolve, 5));
+ }
+}
+
+const update = (
+ sequence: number,
+ phase: 'message_delta' | 'reasoning_delta' | 'run_step' = 'message_delta',
+) => ({
+ runId: 'parent',
+ parentRunId: 'parent',
+ subagentRunId: 'child',
+ subagentType: 'reviewer',
+ subagentKind: 'agent' as const,
+ subagentAgentId: 'agent-1',
+ depth: 1,
+ ancestry: [],
+ activityEventId: `task:${sequence}`,
+ activitySequence: sequence,
+ phase,
+ timestamp: '2026-09-29T00:00:00.000Z',
+ data:
+ phase === 'run_step'
+ ? {
+ id: `step-${sequence}`,
+ stepDetails: {
+ type: 'tool_calls',
+ tool_calls: [
+ { id: `call-${sequence}`, name: 'execute_code', args: { code: 'print(1)' } },
+ ],
+ },
+ }
+ : {
+ delta: {
+ content: [
+ {
+ type: phase === 'message_delta' ? 'text' : 'think',
+ ...(phase === 'message_delta'
+ ? { text: `text-${sequence}` }
+ : { think: `reason-${sequence}` }),
+ },
+ ],
+ },
+ },
+});
+
+function collect(stream: SubagentActivityStream, thread: string, task: string) {
+ const events: SubagentActivityEnvelope[] = [];
+ const onDone = jest.fn();
+ const subscription = stream.subscribe(thread, task, {
+ onEvent: (envelope) => {
+ if (envelope.event === 'subagent_activity_replay') events.push(...envelope.data);
+ else events.push(envelope);
+ },
+ onDone,
+ });
+ subscriptions.push(subscription);
+ return { events, onDone, subscription };
+}
+
+afterEach(async () => {
+ for (const subscription of subscriptions.splice(0)) subscription.unsubscribe();
+ for (const transport of transports.splice(0)) transport.destroy();
+ await Promise.all(
+ clients.splice(0).map(async (connection) => {
+ connection.disconnect();
+ }),
+ );
+});
+
+describe('bounded cross-replica subagent replay (real Redis)', () => {
+ it('replays tool calls, reasoning and text produced without demand, then streams and reconnects', async () => {
+ const owner = await replica();
+ const viewer = await replica();
+ const thread = randomUUID();
+ const task = randomUUID();
+ for (let index = 0; index < 18; index++)
+ await owner.stream.publish(thread, task, update(index, 'run_step'));
+ await owner.stream.publish(thread, task, update(18, 'reasoning_delta'));
+ await owner.stream.publish(thread, task, update(19));
+ const first = collect(viewer.stream, thread, task);
+ await first.subscription.ready;
+ expect(first.events.map((event) => event.data.activitySequence)).toEqual(
+ Array.from({ length: 20 }, (_, i) => i),
+ );
+ expect(first.events[0].data.data).toEqual(update(0, 'run_step').data);
+ await owner.stream.publish(thread, task, update(20));
+ await waitUntil(() => first.events.length === 21);
+ first.subscription.unsubscribe();
+ const replacement = collect((await replica()).stream, thread, task);
+ await replacement.subscription.ready;
+ expect(replacement.events.map((event) => event.data.activitySequence)).toEqual(
+ Array.from({ length: 21 }, (_, i) => i),
+ );
+ await owner.stream.complete(thread, task, 'completed');
+ await waitUntil(() => replacement.onDone.mock.calls.length === 1);
+ expect(replacement.events).toHaveLength(21);
+ });
+
+ it('buffers snapshot-time live events without gaps or duplicates and does not rewind another viewer', async () => {
+ const owner = await replica();
+ const viewer = await replica();
+ const thread = randomUUID();
+ const task = randomUUID();
+ await owner.stream.publish(thread, task, update(0));
+ const first = collect(viewer.stream, thread, task);
+ await first.subscription.ready;
+ let release!: () => void;
+ let captured!: () => void;
+ const held = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const snapshotCaptured = new Promise<void>((resolve) => {
+ captured = resolve;
+ });
+ const evalOriginal = viewer.publisher.eval.bind(viewer.publisher);
+ jest
+ .spyOn(viewer.publisher, 'eval')
+ .mockImplementation(async (...args: Parameters<Redis['eval']>) => {
+ const result = await evalOriginal(...args);
+ if (args[0] === READ_REPLAY_LUA) {
+ captured();
+ await held;
+ }
+ return result;
+ });
+ const second = collect(viewer.stream, thread, task);
+ await snapshotCaptured;
+ await owner.stream.publish(thread, task, update(1));
+ await waitUntil(() => first.events.length === 2);
+ expect(second.events).toHaveLength(0);
+ release();
+ await second.subscription.ready;
+ await waitUntil(() => second.events.length === 2);
+ expect(first.events.map((event) => event.data.activitySequence)).toEqual([0, 1]);
+ expect(second.events.map((event) => event.data.activitySequence)).toEqual([0, 1]);
+ });
+
+ it('recovers from a failed Redis publish without losing later activity', async () => {
+ const owner = await replica();
+ const viewer = await replica();
+ const thread = randomUUID();
+ const task = randomUUID();
+ await owner.stream.publish(thread, task, update(0));
+ jest
+ .spyOn(owner.publisher, 'eval')
+ .mockRejectedValueOnce(new Error('simulated transient Redis failure'));
+ await expect(owner.stream.publish(thread, task, update(1))).rejects.toThrow('transient');
+ await owner.stream.publish(thread, task, update(1));
+ const attached = collect(viewer.stream, thread, task);
+ await attached.subscription.ready;
+ await owner.stream.publish(thread, task, update(2));
+ await waitUntil(() => attached.events.length === 3);
+ expect(attached.events.map((event) => event.data.activitySequence)).toEqual([0, 1, 2]);
+ });
+
+ it('deduplicates commit-before-response-loss retries without retaining duplicate chunks or DONE', async () => {
+ const owner = await replica();
+ const viewer = await replica();
+ const thread = randomUUID();
+ const task = randomUUID();
+ const streamId = subagentActivityStreamId(thread, task);
+ const attached = collect(viewer.stream, thread, task);
+ await attached.subscription.ready;
+ const originalEval = owner.publisher.eval.bind(owner.publisher);
+ jest
+ .spyOn(owner.publisher, 'eval')
+ .mockImplementationOnce(async (...args: Parameters<Redis['eval']>) => {
+ await originalEval(...args);
+ throw new Error('response lost after commit');
+ });
+ await expect(owner.stream.publish(thread, task, update(0))).rejects.toThrow('response lost');
+ await owner.stream.publish(thread, task, update(0));
+ await owner.stream.publish(thread, task, update(1));
+ await owner.stream.publish(thread, task, update(0));
+ expect(await owner.publisher.get(`stream:{${streamId}}:seq`)).toBe('2');
+ expect(await owner.publisher.llen(`stream:{${streamId}}:activity-backlog`)).toBe(2);
+ jest
+ .spyOn(owner.publisher, 'eval')
+ .mockImplementationOnce(async (...args: Parameters<Redis['eval']>) => {
+ await originalEval(...args);
+ throw new Error('terminal response lost after commit');
+ });
+ await expect(owner.stream.complete(thread, task, 'completed')).rejects.toThrow('response lost');
+ await owner.stream.complete(thread, task, 'completed');
+ await owner.stream.publish(thread, task, update(2));
+ await waitUntil(() => attached.onDone.mock.calls.length === 1);
+ expect(attached.events.map((event) => event.data.activitySequence)).toEqual([0, 1]);
+ expect(await owner.publisher.get(`stream:{${streamId}}:seq`)).toBe('3');
+ expect(await owner.publisher.llen(`stream:{${streamId}}:activity-backlog`)).toBe(3);
+ });
+
+ it('retains the largest permitted payload including wire and omission-marker overhead', async () => {
+ const owner = await replica();
+ const thread = randomUUID();
+ const task = randomUUID();
+ let low = 0;
+ let high = 65_536;
+ const candidate = (length: number) => ({ ...update(0), data: { text: 'x'.repeat(length) } });
+ while (low < high) {
+ const middle = Math.ceil((low + high) / 2);
+ if (boundSubagentActivityUpdate(candidate(middle)).data != null) low = middle;
+ else high = middle - 1;
+ }
+ const event = candidate(low);
+ expect(low).toBeGreaterThan(63 * 1024);
+ await owner.stream.publish(thread, task, event, Number.MAX_SAFE_INTEGER);
+ const retained = await owner.publisher.lrange(
+ `stream:{${subagentActivityStreamId(thread, task)}}:activity-backlog`,
+ 0,
+ -1,
+ );
+ expect(retained).toHaveLength(1);
+ expect(Buffer.byteLength(retained[0])).toBeLessThanOrEqual(SUBAGENT_ACTIVITY_LIMITS.bytes);
+ expect(JSON.parse(retained[0]).data.data.data).toEqual(event.data);
+ });
+
+ it('injects retention long enough to cover a silent tool interval', async () => {
+ const owner = await replica();
+ const thread = randomUUID();
+ const task = randomUUID();
+ const stream = new SubagentActivityStream(owner.transport, { replayTtlMs: 3_600_000 });
+ await stream.publish(thread, task, update(0));
+ const ttl = await owner.publisher.pttl(
+ `stream:{${subagentActivityStreamId(thread, task)}}:activity-backlog`,
+ );
+ expect(ttl).toBeGreaterThan(3_590_000);
+ expect(ttl).toBeLessThanOrEqual(3_600_000);
+ });
+
+ it('renews demand for an older publisher during a rolling deployment', async () => {
+ const owner = await replica();
+ const viewer = await replica();
+ const thread = randomUUID();
+ const task = randomUUID();
+ const attached = collect(viewer.stream, thread, task);
+ await attached.subscription.ready;
+ const streamId = subagentActivityStreamId(thread, task);
+ const publishLegacy = async (sequence: number) => {
+ if (!(await owner.transport.hasDemand(streamId))) return;
+ await owner.transport.emitChunk(streamId, {
+ event: 'on_subagent_update',
+ data: update(sequence),
+ });
+ };
+ expect(await owner.transport.hasDemand(streamId)).toBe(true);
+ await publishLegacy(0);
+ await waitUntil(() => attached.events.length === 1);
+ expect(await owner.publisher.pttl(`stream:{${streamId}}:demand`)).toBeGreaterThan(0);
+ if (await owner.transport.hasDemand(streamId)) {
+ await owner.transport.emitDone(streamId, {
+ final: true,
+ subagentActivity: true,
+ status: 'completed',
+ });
+ }
+ await waitUntil(() => attached.onDone.mock.calls.length === 1);
+ expect(attached.events[0].data.activitySequence).toBe(0);
+ });
+
+ it('preserves an older owner frame published between SUBSCRIBE and snapshot capture', async () => {
+ const owner = await replica();
+ const viewer = await replica();
+ const thread = randomUUID();
+ const task = randomUUID();
+ const streamId = subagentActivityStreamId(thread, task);
+ const originalEval = viewer.publisher.eval.bind(viewer.publisher);
+ jest
+ .spyOn(viewer.publisher, 'eval')
+ .mockImplementationOnce(async (...args: Parameters<Redis['eval']>) => {
+ expect(args[0]).toBe(READ_REPLAY_LUA);
+ await owner.transport.emitChunk(streamId, { event: 'on_subagent_update', data: update(0) });
+ return originalEval(...args);
+ });
+ const attached = collect(viewer.stream, thread, task);
+ await attached.subscription.ready;
+ expect(attached.events.map((event) => event.data.activitySequence)).toEqual([0]);
+ await owner.transport.emitChunk(streamId, { event: 'on_subagent_update', data: update(1) });
+ await waitUntil(() => attached.events.length === 2);
+ expect(attached.events.map((event) => event.data.activitySequence)).toEqual([0, 1]);
+ });
+
+ it('caps retained items and encoded bytes, expires them, and preserves the shared sequence', async () => {
+ const owner = await replica();
+ const streamId = subagentActivityStreamId(randomUUID(), randomUUID());
+ const limits = { items: 3, bytes: 250, ttlMs: 100 };
+ for (let index = 0; index < 8; index++)
+ await owner.transport.emitReplayableChunk(streamId, { text: `payload-${index}` }, limits);
+ const key = `stream:{${streamId}}:activity-backlog`;
+ const backlog = await owner.publisher.lrange(key, 0, -1);
+ expect(backlog.length).toBeLessThanOrEqual(3);
+ expect(
+ backlog.reduce((bytes, event) => bytes + Buffer.byteLength(event), 0),
+ ).toBeLessThanOrEqual(250);
+ const pttl = await owner.publisher.pttl(key);
+ expect(pttl).toBeGreaterThan(0);
+ expect(pttl).toBeLessThanOrEqual(100);
+ await new Promise<void>((resolve) => setTimeout(resolve, 150));
+ expect(await owner.publisher.exists(key)).toBe(0);
+ expect(await owner.publisher.get(`stream:{${streamId}}:seq`)).toBe('8');
+ expect(SUBAGENT_ACTIVITY_LIMITS).toMatchObject({ items: 100, bytes: 65536 });
+ });
+
+ it('retains terminal frames and rejects a stalled attachment with bounded live buffering', async () => {
+ const owner = await replica();
+ const viewer = await replica();
+ const streamId = subagentActivityStreamId(randomUUID(), randomUUID());
+ const limits = { items: 3, bytes: 4096, ttlMs: 1000 };
+ await owner.transport.emitReplayableChunk(streamId, { text: 'before' }, limits);
+ await owner.transport.emitReplayableDone(streamId, { final: true }, limits);
+ const onReplay = jest.fn();
+ const onDone = jest.fn();
+ const subscription = viewer.transport.subscribe(
+ streamId,
+ { onChunk: jest.fn(), onReplay, onDone },
+ { replay: limits },
+ );
+ subscriptions.push(subscription);
+ await subscription.ready;
+ expect(onReplay).toHaveBeenCalledWith([{ text: 'before' }]);
+ expect(onDone).toHaveBeenCalledWith({ final: true });
+ const stalledStreamId = subagentActivityStreamId(randomUUID(), randomUUID());
+ const held = new Promise<never>(() => undefined);
+ jest.spyOn(viewer.publisher, 'eval').mockImplementationOnce(() => held);
+ const onError = jest.fn();
+ const stalled = viewer.transport.subscribe(
+ stalledStreamId,
+ { onChunk: jest.fn(), onError },
+ { replay: limits },
+ );
+ subscriptions.push(stalled);
+ const readyFailure = stalled.ready?.catch((error: Error) => error.message);
+ await new Promise<void>((resolve) => setTimeout(resolve, 10));
+ for (let i = 0; i < 4; i++)
+ await owner.transport.emitReplayableChunk(stalledStreamId, { text: i }, limits);
+ await waitUntil(() => onError.mock.calls.length === 1);
+ expect(onError.mock.calls[0][0]).toContain('overflow');
+ expect(await readyFailure).toContain('Timed out synchronizing');
+ });
+});
diff --git a/packages/api/src/stream/implementations/InMemoryEventTransport.ts b/packages/api/src/stream/implementations/InMemoryEventTransport.ts
index 5e106f2f8e..6180362729 100644
--- a/packages/api/src/stream/implementations/InMemoryEventTransport.ts
+++ b/packages/api/src/stream/implementations/InMemoryEventTransport.ts
@@ -1,5 +1,7 @@
import { EventEmitter } from 'events';
import { logger } from '@librechat/data-schemas';
+import { subagentActivityConfigSchema } from 'librechat-data-provider';
+import type { ReplayLimits, ReplayPublication } from '../internal/replay';
import type { IEventTransport } from '../interfaces/IJobStore';
interface StreamState {
@@ -7,11 +9,34 @@ interface StreamState {
allSubscribersLeftCallback?: () => void;
}
+interface ReplayBuffer {
+ events: Array<{ type: 'chunk' | 'done'; data: unknown; bytes: number }>;
+ bytes: number;
+ expiresAt: number;
+ timer?: ReturnType<typeof setTimeout>;
+ publication?: ReplayPublication;
+ done: boolean;
+}
+
/**
* In-memory event transport using Node.js EventEmitter.
* For horizontal scaling, replace with RedisEventTransport.
*/
export class InMemoryEventTransport implements IEventTransport {
+ private replay = new Map<string, ReplayBuffer>();
+ private replayBytes = 0;
+ private readonly replayMaxStreams: number;
+ private readonly replayMaxBytes: number;
+
+ constructor(options: { maxStreams?: number; maxBytes?: number } = {}) {
+ const config = subagentActivityConfigSchema.parse({
+ memoryMaxStreams: options.maxStreams,
+ memoryMaxBytes: options.maxBytes,
+ });
+ this.replayMaxStreams = config.memoryMaxStreams;
+ this.replayMaxBytes = config.memoryMaxBytes;
+ }
+
private streams = new Map<string, StreamState>();
private providerDrainProofs = new Map<string, number>();
private providerDrainWrites = 0;
@@ -41,10 +66,60 @@ export class InMemoryEventTransport implements IEventTransport {
streamId: string,
handlers: {
onChunk: (event: unknown, generationId?: number) => void;
+ onReplay?: (events: unknown[]) => void;
onDone?: (event: unknown, generationId?: number) => void;
onError?: (error: string, generationId?: number) => void;
},
+ options?: { replay?: ReplayLimits },
): { unsubscribe: () => void; ready?: Promise<void> } {
+ if (options?.replay != null) {
+ const cached = this.replay.get(streamId);
+ if (cached != null && cached.expiresAt <= Date.now()) this.dropReplay(streamId);
+ const snapshot = this.replay.get(streamId)?.events.slice() ?? [];
+ let attached = false;
+ let closed = false;
+ let pendingBytes = 0;
+ const pending: Array<{ type: 'chunk' | 'done'; data: unknown }> = [];
+ const deliver = (type: 'chunk' | 'done', data: unknown) => {
+ if (closed) return;
+ if (attached) {
+ if (type === 'chunk') handlers.onChunk(data);
+ else handlers.onDone?.(data);
+ return;
+ }
+ pendingBytes += Buffer.byteLength(JSON.stringify(data), 'utf8');
+ if (pending.length >= options.replay!.items || pendingBytes > options.replay!.bytes) {
+ closed = true;
+ subscription.unsubscribe();
+ handlers.onError?.('Activity replay buffer overflow; reconnect to replay.');
+ return;
+ }
+ pending.push({ type, data });
+ };
+ const subscription = this.subscribe(streamId, {
+ onChunk: (data) => deliver('chunk', data),
+ onDone: (data) => deliver('done', data),
+ onError: handlers.onError,
+ });
+ return {
+ unsubscribe: () => {
+ closed = true;
+ subscription.unsubscribe();
+ },
+ ready: Promise.resolve().then(() => {
+ if (closed) return;
+ const chunks = snapshot
+ .filter((event) => event.type === 'chunk')
+ .map((event) => event.data);
+ if (handlers.onReplay != null) handlers.onReplay(chunks);
+ else chunks.forEach((data) => handlers.onChunk(data));
+ attached = true;
+ for (const event of snapshot) if (event.type === 'done') deliver('done', event.data);
+ for (const event of pending) deliver(event.type, event.data);
+ pending.length = 0;
+ }),
+ };
+ }
const state = this.getOrCreateStream(streamId);
const chunkHandler = (event: unknown, generationId?: number) => {
@@ -103,6 +178,80 @@ export class InMemoryEventTransport implements IEventTransport {
};
}
+ private dropReplay(streamId: string): void {
+ const buffer = this.replay.get(streamId);
+ if (buffer == null) return;
+ if (buffer.timer != null) clearTimeout(buffer.timer);
+ this.replayBytes -= buffer.bytes;
+ this.replay.delete(streamId);
+ }
+
+ private retainReplay(
+ streamId: string,
+ type: 'chunk' | 'done',
+ data: unknown,
+ limits: ReplayLimits,
+ publication?: ReplayPublication,
+ ): boolean {
+ const cached = this.replay.get(streamId);
+ if (cached != null && cached.expiresAt <= Date.now()) this.dropReplay(streamId);
+ const existing = this.replay.get(streamId);
+ if (
+ existing?.done === true ||
+ (publication != null &&
+ existing?.publication != null &&
+ (existing.publication.id === publication.id ||
+ (publication.sequence != null &&
+ existing.publication.sequence != null &&
+ publication.sequence <= existing.publication.sequence)))
+ )
+ return false;
+ const buffer: ReplayBuffer = existing ?? { events: [], bytes: 0, expiresAt: 0, done: false };
+ const priorBytes = buffer.bytes;
+ const bytes = Buffer.byteLength(JSON.stringify({ type, data }), 'utf8');
+ buffer.events.push({ type, data, bytes });
+ buffer.bytes += bytes;
+ while (buffer.events.length > limits.items || buffer.bytes > limits.bytes) {
+ buffer.bytes -= buffer.events.shift()!.bytes;
+ }
+ buffer.publication = publication;
+ buffer.done = type === 'done';
+ buffer.expiresAt = Date.now() + limits.ttlMs;
+ if (buffer.timer != null) clearTimeout(buffer.timer);
+ buffer.timer = setTimeout(() => this.dropReplay(streamId), limits.ttlMs);
+ buffer.timer.unref?.();
+ /** Map insertion order is a write-recency eviction queue, independent of stream cleanup. */
+ this.replay.delete(streamId);
+ this.replay.set(streamId, buffer);
+ this.replayBytes += buffer.bytes - priorBytes;
+ while (this.replay.size > this.replayMaxStreams || this.replayBytes > this.replayMaxBytes) {
+ const oldest = this.replay.keys().next().value;
+ if (oldest == null) break;
+ this.dropReplay(oldest);
+ }
+ return true;
+ }
+
+ async emitReplayableChunk(
+ streamId: string,
+ event: unknown,
+ limits: ReplayLimits,
+ publication?: ReplayPublication,
+ ): Promise<void> {
+ if (this.retainReplay(streamId, 'chunk', event, limits, publication))
+ this.emitChunk(streamId, event);
+ }
+
+ async emitReplayableDone(
+ streamId: string,
+ event: unknown,
+ limits: ReplayLimits,
+ publication?: ReplayPublication,
+ ): Promise<void> {
+ if (this.retainReplay(streamId, 'done', event, limits, publication))
+ this.emitDone(streamId, event);
+ }
+
emitChunk(streamId: string, event: unknown, generationId?: number): void {
const state = this.streams.get(streamId);
state?.emitter.emit('chunk', event, generationId);
@@ -240,6 +389,9 @@ export class InMemoryEventTransport implements IEventTransport {
}
destroy(): void {
+ for (const buffer of this.replay.values()) if (buffer.timer != null) clearTimeout(buffer.timer);
+ this.replay.clear();
+ this.replayBytes = 0;
for (const state of this.streams.values()) {
state.emitter.removeAllListeners();
}
diff --git a/packages/api/src/stream/implementations/RedisEventTransport.ts b/packages/api/src/stream/implementations/RedisEventTransport.ts
index 5854447576..05ea6fa894 100644
--- a/packages/api/src/stream/implementations/RedisEventTransport.ts
+++ b/packages/api/src/stream/implementations/RedisEventTransport.ts
@@ -3,6 +3,7 @@ import { logger } from '@librechat/data-schemas';
import type { Redis, Cluster } from 'ioredis';
import type { IEventTransport, PreemptMessage } from '~/stream/interfaces/IJobStore';
import type { ChunkPublicationOptions } from '~/stream/internal/chunkPublication';
+import type { ReplayLimits, ReplayPublication } from '../internal/replay';
import {
MAX_COALESCED_BYTES,
MAX_COALESCED_EVENTS,
@@ -15,6 +16,7 @@ import {
import { registerChunkPublicationCapability } from '~/stream/internal/chunkPublication';
import { GenerationPublicationFencedError } from '~/stream/interfaces/IJobStore';
import { instrumentIORedisClient, RedisUseCases } from '~/cache/redisTelemetry';
+import { PUBLISH_REPLAY_LUA, READ_REPLAY_LUA } from '../internal/replay';
/**
* Redis key prefixes for pub/sub channels
@@ -30,6 +32,9 @@ const CHANNELS = {
const KEYS = {
/** Atomic sequence counter: shared across all replicas for a given stream */
sequence: (streamId: string) => `stream:{${streamId}}:seq`,
+ backlog: (streamId: string) => `stream:{${streamId}}:activity-backlog`,
+ publication: (streamId: string) => `stream:{${streamId}}:activity-publication`,
+ backlogBytes: (streamId: string) => `stream:{${streamId}}:activity-bytes`,
/** Job metadata, used to keep the sequence counter alive for the full job lifetime */
job: (streamId: string) => `stream:{${streamId}}:job`,
/** Latest generation epoch, retained briefly beyond the live job hash. */
@@ -232,6 +237,11 @@ const ABORT_ACK_TTL_SECONDS = 86400;
const PROVIDER_DRAIN_TTL_SECONDS = 86400;
const SUBSCRIPTION_ATTACHMENT_TIMEOUT_MS = 3_000;
+interface ReplaySnapshot {
+ frontier: number;
+ events: string[];
+}
+
interface SubscriptionFrontierWaiter {
streamId: string;
resolve: () => void;
@@ -255,6 +265,7 @@ interface StreamSubscribers {
string,
{
onChunk: (event: unknown, generationId?: number) => void;
+ onReplayMessage?: (message: PubSubMessage) => void;
onDone?: (event: unknown, generationId?: number) => void;
onError?: (error: string, generationId?: number) => void;
}
@@ -336,7 +347,12 @@ export class RedisEventTransport implements IEventTransport {
return state;
}
- private async captureSubscriptionFrontier(streamId: string): Promise<number> {
+ private captureSubscriptionFrontier(streamId: string): Promise<number>;
+ private captureSubscriptionFrontier(streamId: string, replay: true): Promise<ReplaySnapshot>;
+ private async captureSubscriptionFrontier(
+ streamId: string,
+ replay = false,
+ ): Promise<number | ReplaySnapshot> {
const subscriptionFrontierId = randomUUID();
let operationTimeout: ReturnType<typeof setTimeout> | undefined;
const observed = new Promise<void>((resolve, reject) => {
@@ -360,9 +376,10 @@ export class RedisEventTransport implements IEventTransport {
* admission instead of leaving every surviving local subscriber deferred forever. */
const operation = Promise.all([
this.publisher.eval(
- CAPTURE_SUBSCRIPTION_FRONTIER_LUA,
- 1,
+ replay ? READ_REPLAY_LUA : CAPTURE_SUBSCRIPTION_FRONTIER_LUA,
+ replay ? 2 : 1,
KEYS.sequence(streamId),
+ ...(replay ? [KEYS.backlog(streamId)] : []),
CHANNELS.events(streamId),
JSON.stringify({
type: EventTypes.SUBSCRIPTION_FRONTIER,
@@ -379,8 +396,10 @@ export class RedisEventTransport implements IEventTransport {
operationTimeout.unref?.();
});
const [raw] = await Promise.race([operation, operationDeadline]);
- const parsed = raw != null ? parseInt(String(raw), 10) : 0;
- return Number.isNaN(parsed) ? 0 : parsed;
+ const counter = replay ? (raw as [string, string[]])[0] : raw;
+ const parsed = counter != null ? parseInt(String(counter), 10) : 0;
+ const frontier = Number.isNaN(parsed) ? 0 : parsed;
+ return replay ? { frontier, events: (raw as [string, string[]])[1] } : frontier;
} catch (error) {
const waiter = this.subscriptionFrontierWaiters.get(subscriptionFrontierId);
if (waiter != null) {
@@ -899,6 +918,12 @@ export class RedisEventTransport implements IEventTransport {
}
return;
}
+ let replayOnly = streamState.handlers.size > 0;
+ for (const handlers of streamState.handlers.values()) {
+ if (handlers.onReplayMessage == null) replayOnly = false;
+ else handlers.onReplayMessage(parsed);
+ }
+ if (replayOnly) return;
/** Aborts, preempts, and abort acknowledgements are consumed by
* transport-internal waiters (e.g. pending-ack resolution), not SSE
* subscribers, so they must flow even with zero local subscribers. */
@@ -1095,6 +1120,7 @@ export class RedisEventTransport implements IEventTransport {
message: PubSubMessage,
): void {
for (const [, handlers] of streamState.handlers) {
+ if (handlers.onReplayMessage != null) continue;
switch (message.type) {
case EventTypes.CHUNK:
if (message.generationId == null) {
@@ -1208,6 +1234,130 @@ export class RedisEventTransport implements IEventTransport {
this.channelSubscriptions.delete(channel);
}
+ private async publishReplayable(
+ streamId: string,
+ type: 'chunk' | 'done',
+ event: unknown,
+ limits: ReplayLimits,
+ publication?: ReplayPublication,
+ ): Promise<void> {
+ const [prefix, suffix] = RedisEventTransport.buildPayloadParts({ type, data: event });
+ await this.publisher.eval(
+ PUBLISH_REPLAY_LUA,
+ 4,
+ KEYS.sequence(streamId),
+ KEYS.backlog(streamId),
+ KEYS.backlogBytes(streamId),
+ KEYS.publication(streamId),
+ CHANNELS.events(streamId),
+ prefix,
+ suffix,
+ limits.items,
+ limits.bytes,
+ limits.ttlMs,
+ RedisEventTransport.SEQUENCE_TTL_SECONDS,
+ publication?.id ?? '',
+ publication?.sequence ?? '',
+ type === 'done' ? '1' : '0',
+ );
+ }
+
+ emitReplayableChunk(
+ streamId: string,
+ event: unknown,
+ limits: ReplayLimits,
+ publication?: ReplayPublication,
+ ): Promise<void> {
+ return this.publishReplayable(streamId, 'chunk', event, limits, publication);
+ }
+
+ emitReplayableDone(
+ streamId: string,
+ event: unknown,
+ limits: ReplayLimits,
+ publication?: ReplayPublication,
+ ): Promise<void> {
+ return this.publishReplayable(streamId, 'done', event, limits, publication);
+ }
+
+ private subscribeReplayable(
+ streamId: string,
+ handlers: Parameters<IEventTransport['subscribe']>[1],
+ limits: ReplayLimits,
+ ): ReturnType<IEventTransport['subscribe']> {
+ const state = this.getOrCreateStreamState(streamId);
+ const id = `sub_${++this.subscriberIdCounter}`;
+ let closed = false;
+ let frontier: number | undefined;
+ let pendingBytes = 0;
+ const pending: PubSubMessage[] = [];
+ const unsubscribe = () => {
+ if (closed) return;
+ closed = true;
+ pending.length = 0;
+ if (this.streams.get(streamId) !== state || !state.handlers.delete(id)) return;
+ state.count--;
+ if (state.count === 0) this.detachStreamSubscribers(streamId, state);
+ };
+ const deliver = (message: PubSubMessage) => {
+ if (closed || this.streams.get(streamId) !== state) return;
+ if (message.seq != null) {
+ if (frontier != null && message.seq < frontier) return;
+ frontier = message.seq + 1;
+ }
+ if (message.type === EventTypes.CHUNK) handlers.onChunk(message.data);
+ else if (message.type === EventTypes.DONE) handlers.onDone?.(message.data);
+ else if (message.type === EventTypes.ERROR)
+ handlers.onError?.(message.error ?? 'Unknown error');
+ };
+ state.count++;
+ state.handlers.set(id, {
+ ...handlers,
+ onReplayMessage: (message) => {
+ if (closed) return;
+ if (frontier != null) return deliver(message);
+ pendingBytes += Buffer.byteLength(JSON.stringify(message), 'utf8');
+ if (pending.length >= limits.items || pendingBytes > limits.bytes) {
+ unsubscribe();
+ handlers.onError?.('Activity replay buffer overflow; reconnect to replay.');
+ return;
+ }
+ pending.push(message);
+ },
+ });
+ const ready = this.ensureChannelSubscription(streamId)
+ .then(async () => {
+ const snapshot = await this.captureSubscriptionFrontier(streamId, true);
+ if (closed || this.streams.get(streamId) !== state) return;
+ const messages = snapshot.events.map((raw) => JSON.parse(raw) as PubSubMessage);
+ const retained = new Set(messages.map((message) => message.seq));
+ /** The observed marker fences all receivable pre-snapshot frames. Older owners
+ * publish without retaining, so their buffered frames are not replay duplicates. */
+ for (const message of pending) {
+ if (message.seq != null && message.seq < snapshot.frontier && !retained.has(message.seq))
+ messages.push(message);
+ }
+ messages.sort((left, right) => (left.seq ?? 0) - (right.seq ?? 0));
+ const chunks = messages.filter((message) => message.type === EventTypes.CHUNK);
+ if (handlers.onReplay != null) handlers.onReplay(chunks.map((message) => message.data));
+ else for (const message of chunks) handlers.onChunk(message.data);
+ frontier = snapshot.frontier;
+ for (const message of messages) {
+ if (message.type === EventTypes.DONE) handlers.onDone?.(message.data);
+ else if (message.type === EventTypes.ERROR)
+ handlers.onError?.(message.error ?? 'Unknown error');
+ }
+ pending.sort((left, right) => (left.seq ?? 0) - (right.seq ?? 0));
+ for (const message of pending) deliver(message);
+ pending.length = 0;
+ })
+ .catch((error) => {
+ unsubscribe();
+ throw error;
+ });
+ return { unsubscribe, ready };
+ }
+
/**
* Subscribe to events for a stream.
*
@@ -1217,11 +1367,13 @@ export class RedisEventTransport implements IEventTransport {
streamId: string,
handlers: {
onChunk: (event: unknown, generationId?: number) => void;
+ onReplay?: (events: unknown[]) => void;
onDone?: (event: unknown, generationId?: number) => void;
onError?: (error: string, generationId?: number) => void;
},
options?: {
deferSequenceDelivery?: boolean;
+ replay?: ReplayLimits;
captureSequenceFrontier?: boolean;
/** @deprecated Use deferSequenceDelivery. */
deferDeliveryUntilSynchronized?: boolean;
@@ -1231,6 +1383,8 @@ export class RedisEventTransport implements IEventTransport {
ready?: Promise<void>;
syncReorderBuffer?: () => void | Promise<void>;
} {
+ if (options?.replay != null)
+ return this.subscribeReplayable(streamId, handlers, options.replay);
const subscriberId = `sub_${++this.subscriberIdCounter}`;
// Initialize stream state if needed
diff --git a/packages/api/src/stream/interfaces/IJobStore.ts b/packages/api/src/stream/interfaces/IJobStore.ts
index 5f1681979c..5c705d70bb 100644
--- a/packages/api/src/stream/interfaces/IJobStore.ts
+++ b/packages/api/src/stream/interfaces/IJobStore.ts
@@ -12,6 +12,7 @@ import type { RunStep, StandardGraph } from '@librechat/agents';
import type { AgentEventDetachedTerminalEvidence } from '~/agents/triggers/types';
import type { EarlyBufferOverflowState } from '../../types/earlyBufferRecovery';
import type { ActivityPhaseSnapshot } from '~/agents/activityPhases/runtime';
+import type { ReplayLimits, ReplayPublication } from '../internal/replay';
import type { ResolvedAskUserQuestion } from '~/agents/hitl/resume';
import type { RecoveredSteerPayload } from '../SteerRecovery';
import type { MCPRuntimeRequestBody } from '~/mcp/types';
@@ -1660,6 +1661,8 @@ export interface IEventTransport {
handlers: {
/** `generationId` identifies the immutable generation that emitted the chunk. */
onChunk: (event: unknown, generationId?: number) => void;
+ /** One ordered snapshot before live delivery, only for replay subscriptions. */
+ onReplay?: (events: unknown[]) => void;
/** `generationId` identifies the immutable generation that emitted the done event. */
onDone?: (event: unknown, generationId?: number) => void;
/** `generationId` identifies the immutable generation that emitted the error. */
@@ -1668,6 +1671,8 @@ export interface IEventTransport {
options?: {
/** Hold sequenced events until syncReorderBuffer establishes the replay frontier. */
deferSequenceDelivery?: boolean;
+ /** Per-viewer bounded replay; does not rewind other subscribers. */
+ replay?: ReplayLimits;
/** After opening a fresh Pub/Sub channel, atomically capture its sequence frontier
* and fence delivery so synchronization cannot lose an attachment-time frame. */
captureSequenceFrontier?: boolean;
@@ -1686,6 +1691,20 @@ export interface IEventTransport {
*/
emitChunk(streamId: string, event: unknown, generationId?: number): void | Promise<void | number>;
+ /** Retain an observational chunk even with no viewers, then publish it atomically. */
+ emitReplayableChunk?(
+ streamId: string,
+ event: unknown,
+ limits: ReplayLimits,
+ publication?: ReplayPublication,
+ ): Promise<void>;
+ emitReplayableDone?(
+ streamId: string,
+ event: unknown,
+ limits: ReplayLimits,
+ publication?: ReplayPublication,
+ ): Promise<void>;
+
/**
* Publish a done event - returns Promise in Redis mode for ordered delivery.
* `generationId` is optional for compatibility with legacy, untagged publishers.
diff --git a/packages/api/src/stream/internal/replay.ts b/packages/api/src/stream/internal/replay.ts
new file mode 100644
index 0000000000..d582dadcb1
--- /dev/null
+++ b/packages/api/src/stream/internal/replay.ts
@@ -0,0 +1,49 @@
+/** Resource protection for ephemeral replay, independent of durable job persistence. */
+export interface ReplayLimits {
+ items: number;
+ bytes: number;
+ ttlMs: number;
+}
+
+/** Stable retry identity; sequenced producers fence delayed retries with their high-water mark. */
+export interface ReplayPublication {
+ id: string;
+ sequence?: number;
+}
+
+/** Sequence allocation, retention and publication share a cluster slot and one round trip.
+ * Payloads are spliced without cjson so empty arrays and numeric precision survive. */
+export const PUBLISH_REPLAY_LUA = `
+local previous = redis.call('HMGET', KEYS[4], 'id', 'seq', 'ordinal', 'done')
+if previous[4] == '1' or (ARGV[8] ~= '' and previous[1] == ARGV[8]) or
+ (ARGV[9] ~= '' and previous[3] and tonumber(ARGV[9]) <= tonumber(previous[3])) then
+ return tonumber(previous[2])
+end
+local seq = redis.call('INCR', KEYS[1]) - 1
+local payload = ARGV[2] .. string.format('%d', seq) .. ARGV[3]
+local bytes = tonumber(redis.call('GET', KEYS[3]) or '0') + #payload
+redis.call('RPUSH', KEYS[2], payload)
+local count = redis.call('LLEN', KEYS[2])
+while count > tonumber(ARGV[4]) or bytes > tonumber(ARGV[5]) do
+ local removed = redis.call('LPOP', KEYS[2])
+ if not removed then break end
+ bytes = bytes - #removed
+ count = count - 1
+end
+redis.call('SET', KEYS[3], bytes, 'PX', ARGV[6])
+redis.call('PEXPIRE', KEYS[2], ARGV[6])
+redis.call('EXPIRE', KEYS[1], ARGV[7])
+redis.call('HSET', KEYS[4], 'id', ARGV[8], 'seq', seq, 'done', ARGV[10])
+if ARGV[9] ~= '' then redis.call('HSET', KEYS[4], 'ordinal', ARGV[9]) end
+redis.call('EXPIRE', KEYS[4], ARGV[7])
+redis.call('PUBLISH', ARGV[1], payload)
+return seq
+`;
+
+/** SUBSCRIBE must be acknowledged first. Every later frame is either in this atomic
+ * snapshot or in the viewer's live buffer; the returned :seq frontier removes overlap. */
+export const READ_REPLAY_LUA = `
+local snapshot = {redis.call('GET', KEYS[1]) or '0', redis.call('LRANGE', KEYS[2], 0, -1)}
+redis.call('PUBLISH', ARGV[1], ARGV[2])
+return snapshot
+`;
diff --git a/packages/data-provider/src/config.spec.ts b/packages/data-provider/src/config.spec.ts
index d18d2b4f1e..672e5a4549 100644
--- a/packages/data-provider/src/config.spec.ts
+++ b/packages/data-provider/src/config.spec.ts
@@ -2424,3 +2424,45 @@ describe('built-in endpoint model lists', () => {
},
);
});
+
+describe('subagent activity policy', () => {
+ it('defaults operational controls through the config schema', () => {
+ const parsed = configSchema.parse({
+ version: '1.3.17',
+ endpoints: { agents: { subagentActivity: {} } },
+ });
+ expect(parsed.endpoints?.agents?.subagentActivity).toEqual({
+ replayTtlMs: 300_000,
+ publicationTimeoutMs: 1_000,
+ retryAttempts: 3,
+ retryBaseDelayMs: 100,
+ recoveryDelayMs: 1_000,
+ memoryMaxStreams: 1_000,
+ memoryMaxBytes: 16_777_216,
+ });
+ });
+ it('retains operator overrides and rejects unsafe budgets', () => {
+ const config = {
+ version: '1.3.17',
+ endpoints: {
+ agents: {
+ subagentActivity: {
+ replayTtlMs: 3_600_000,
+ publicationTimeoutMs: 5_000,
+ retryAttempts: 2,
+ memoryMaxBytes: 65_536,
+ },
+ },
+ },
+ };
+ expect(configSchema.parse(config).endpoints?.agents?.subagentActivity).toMatchObject(
+ config.endpoints.agents.subagentActivity,
+ );
+ expect(
+ configSchema.safeParse({
+ ...config,
+ endpoints: { agents: { subagentActivity: { retryAttempts: 0 } } },
+ }).success,
+ ).toBe(false);
+ });
+});
diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.ts
index 8139be6282..23e1977960 100644
--- a/packages/data-provider/src/config.ts
+++ b/packages/data-provider/src/config.ts
@@ -1392,6 +1392,19 @@ export const DEFAULT_MAX_PROVIDER_ERROR_CHARS = 2000;
export const DEFAULT_AGENT_MODEL_RESPONSE_BODY_TIMEOUT_MS = 900_000;
export const DEFAULT_AGENT_MODEL_RESPONSE_HEADERS_TIMEOUT_MS = 300_000;
+/** Server-side resource and recovery policy for ephemeral child activity. */
+export const subagentActivityConfigSchema = z.object({
+ replayTtlMs: z.number().int().min(1_000).max(86_400_000).default(300_000),
+ publicationTimeoutMs: z.number().int().min(100).max(60_000).default(1_000),
+ retryAttempts: z.number().int().min(1).max(10).default(3),
+ retryBaseDelayMs: z.number().int().min(1).max(10_000).default(100),
+ recoveryDelayMs: z.number().int().min(100).max(60_000).default(1_000),
+ memoryMaxStreams: z.number().int().min(1).max(100_000).default(1_000),
+ memoryMaxBytes: z.number().int().min(65_536).max(1_073_741_824).default(16_777_216),
+});
+
+export type TSubagentActivityConfig = z.infer<typeof subagentActivityConfigSchema>;
+
export const agentsEndpointSchema = baseEndpointSchema
.omit({ baseURL: true })
.merge(
@@ -1461,6 +1474,8 @@ export const agentsEndpointSchema = baseEndpointSchema
.max(MAX_SUBAGENTS_CEILING)
.optional()
.default(MAX_SUBAGENTS),
+ /** Live replay retention, publication recovery and process-local cache budgets. */
+ subagentActivity: subagentActivityConfigSchema.optional(),
/** Run-scoped file access for explicitly opted-in subagent delegations. */
fileSharing: z
.object({
diff --git a/packages/data-provider/src/types/runs.ts b/packages/data-provider/src/types/runs.ts
index 8cebf418bc..10bf09519d 100644
--- a/packages/data-provider/src/types/runs.ts
+++ b/packages/data-provider/src/types/runs.ts
@@ -575,6 +575,8 @@ export interface SubagentUpdateEvent {
activityEventId?: string;
/** Host-assigned monotonic sequence within one detached child run. */
activitySequence?: number;
+ /** Host omission marker, counted only when its event is folded. */
+ activityDroppedCount?: number;
/** Parent-side `tool_call_id` for the `subagent` tool invocation that
* triggered this run. Surfaces from the SDK (`3.1.67-dev.2`+) so hosts
* can correlate child progress to the parent tool call deterministically. */
diff --git a/packages/data-schemas/src/methods/agent.ts b/packages/data-schemas/src/methods/agent.ts
index 2c844d8537..b59a3f69d0 100644
--- a/packages/data-schemas/src/methods/agent.ts
+++ b/packages/data-schemas/src/methods/agent.ts
@@ -1050,6 +1050,7 @@ export function createAgentMethods(
deps: AgentDeps,
): {
getAgent: GetAgent;
+ getAgentName: (id: string, tenantId?: string) => Promise<string | undefined>;
getAgentVersions: (searchParameter: FilterQuery<IAgent>) => Promise<IAgent['versions'] | null>;
getAgentWithVersionCount: (
searchParameter: FilterQuery<IAgent>,
@@ -1272,6 +1273,16 @@ export function createAgentMethods(
return await Agent.findOne(searchParameter, projection).lean<IAgent>();
};
+ /** Storage-neutral display-name lookup for a known execution subject. */
+ async function getAgentName(id: string, tenantId?: string): Promise<string | undefined> {
+ const agent = await getAgent(
+ { id, tenantId: tenantId ?? null },
+ { name: 1, tenantId: 1, _id: 0 },
+ );
+ if ((agent?.tenantId ?? undefined) !== tenantId) return undefined;
+ return agent?.name || undefined;
+ }
+
/**
* Get an agent's version history only, without the rest of the document.
* Returns an empty array when the agent exists but has no versions, or `null`
@@ -2722,6 +2733,7 @@ export function createAgentMethods(
return {
getAgent,
+ getAgentName,
getAgentVersions,
getAgentWithVersionCount,
getAgents,