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: Recover Subagent Content With Shared Chat Rendering (#17290)

lia-by-librechat[bot]ff962fcaa2e0
diff --git a/api/server/routes/__test-utils__/convos-route-mocks.js b/api/server/routes/__test-utils__/convos-route-mocks.js
index 231e6db8a7..87e4935702 100644
--- a/api/server/routes/__test-utils__/convos-route-mocks.js
+++ b/api/server/routes/__test-utils__/convos-route-mocks.js
@@ -142,6 +142,7 @@ module.exports = {
return archiveAllHandler;
}),
createSubagentThreadViewHandler: jest.fn(() => (_req, res) => res.status(200).json({})),
+ createSubagentTaskContentHandler: jest.fn(() => (_req, res) => res.status(200).json({})),
createSubagentControlHandler: jest.fn(() => (_req, res) => res.status(200).json({})),
createBackgroundTaskIndexHandler: jest.fn(
() => (_req, res) => res.status(200).json({ tasks: [] }),
diff --git a/api/server/routes/convos.js b/api/server/routes/convos.js
index 25d71a3757..50e26c4b31 100644
--- a/api/server/routes/convos.js
+++ b/api/server/routes/convos.js
@@ -12,6 +12,7 @@ const {
waitForGenerationPersistence,
createArchiveAllHandler,
createSubagentActivityStreamHandler,
+ createSubagentTaskContentHandler,
createSubagentControlHandler,
isValidSubagentControlRequest,
exemptAgentTriggerFromIpLimiter,
@@ -157,6 +158,17 @@ const subagentActivityStreamHandler = createSubagentActivityStreamHandler(
subscribe: subagentThreadTaskStore.subscribeActivity.bind(subagentThreadTaskStore),
},
);
+const subagentTaskContentHandler = createSubagentTaskContentHandler(
+ {
+ getConvoOwnership: db.getConvoOwnership,
+ getSubagentThreadForParent: db.getSubagentThreadForParent,
+ getMessages: db.getMessages,
+ getSubagentContentHead: db.getSubagentContentHead,
+ streamSubagentContentBatches: db.streamSubagentContentBatches,
+ },
+ () => subagentThreadTaskStore.contentPageBytes,
+ () => subagentThreadTaskStore.contentRecoveryGraceMs,
+);
const subagentControlHandler = createSubagentControlHandler({
getConvoOwnership: db.getConvoOwnership,
getSubagentThreadForParent: db.getSubagentThreadForParent,
@@ -258,6 +270,10 @@ router.get('/', async (req, res) => {
}
});
+router.get(
+ '/:parentConversationId/subagents/:threadId/tasks/:taskId/content',
+ subagentTaskContentHandler,
+);
router.get(
'/:parentConversationId/subagents/:threadId/tasks/:taskId/activity',
subagentActivityStreamHandler,
diff --git a/api/server/services/Endpoints/agents/initialize.js b/api/server/services/Endpoints/agents/initialize.js
index 976f6224b5..f7be7411f1 100644
--- a/api/server/services/Endpoints/agents/initialize.js
+++ b/api/server/services/Endpoints/agents/initialize.js
@@ -1839,6 +1839,7 @@ const initializeClientWithProvider = async ({
},
{
completionWakeups: completionWakeupsEnabled,
+ requestScopedConnections: getMCPRequestContext(req, res),
scheduleMCPIdentity: getScheduleMCPExecution(getMCPRequestContext(req, res))?.identity,
},
)
diff --git a/api/server/services/Endpoints/agents/initialize.spec.js b/api/server/services/Endpoints/agents/initialize.spec.js
index 9922136450..336b0ccab6 100644
--- a/api/server/services/Endpoints/agents/initialize.spec.js
+++ b/api/server/services/Endpoints/agents/initialize.spec.js
@@ -1367,22 +1367,30 @@ describe('initializeClient — subagent loading', () => {
endpointOption: makeEndpointOption(),
});
const existingConfig = agentClientArgs.subagentTasks;
- const hasTasksSpy = jest.spyOn(existingConfig.store, 'hasTasks').mockResolvedValueOnce(true);
+ const subagentThreadTaskStore = require('./subagentThreadStore');
+ const hasTasksSpy = jest.spyOn(subagentThreadTaskStore, 'hasTasks').mockResolvedValueOnce(true);
mockInitializeAgent.mockResolvedValue(makePrimaryConfig({}));
const changedReq = makeSubagentReq();
changedReq.config.endpoints.agents.capabilities.push('run_in_background');
- await initializeClient({
- req: changedReq,
- res: {},
- signal: new AbortController().signal,
- endpointOption: makeEndpointOption(),
- });
+ try {
+ await initializeClient({
+ req: changedReq,
+ res: {},
+ signal: new AbortController().signal,
+ endpointOption: makeEndpointOption(),
+ });
- expect(agentClientArgs.subagentTasks).toEqual(existingConfig);
- expect(capturedToolExecuteOptions.subagentTasks).toEqual(existingConfig);
- expect(agentClientArgs.agent.subagents).toBeUndefined();
- hasTasksSpy.mockRestore();
+ const currentConfig = agentClientArgs.subagentTasks;
+ expect(hasTasksSpy).toHaveBeenCalledWith(existingConfig.scopeId);
+ expect(currentConfig.scopeId).toBe(existingConfig.scopeId);
+ expect(currentConfig.completionDelivery).toBe(existingConfig.completionDelivery);
+ expect(currentConfig.store).not.toBe(existingConfig.store);
+ expect(capturedToolExecuteOptions.subagentTasks).toBe(currentConfig);
+ expect(agentClientArgs.agent.subagents).toBeUndefined();
+ } finally {
+ hasTasksSpy.mockRestore();
+ }
});
it('disables every nested subagent path at the durable child-thread depth limit', async () => {
diff --git a/api/server/services/Endpoints/agents/subagentThreadStore.js b/api/server/services/Endpoints/agents/subagentThreadStore.js
index 0c7fc885b2..1631f97f10 100644
--- a/api/server/services/Endpoints/agents/subagentThreadStore.js
+++ b/api/server/services/Endpoints/agents/subagentThreadStore.js
@@ -55,6 +55,8 @@ async function cancelUnroutedGeneration({ userId, tenantId, taskId }) {
const subagentThreadTaskStore = createSubagentThreadTaskStore(
{
acquireSubagentThreadLease: db.acquireSubagentThreadLease,
+ appendSubagentContentBatch: db.appendSubagentContentBatch,
+ reconcileSubagentContent: db.reconcileSubagentContent,
claimSubagentTaskResult: db.claimSubagentTaskResult,
releaseSubagentTaskResultClaim: db.releaseSubagentTaskResultClaim,
countActiveSubagentThreadLeases: db.countActiveSubagentThreadLeases,
diff --git a/client/src/components/Chat/Messages/Content/Parts/SubagentCall.tsx b/client/src/components/Chat/Messages/Content/Parts/SubagentCall.tsx
index 606df0255e..66543c39e8 100644
--- a/client/src/components/Chat/Messages/Content/Parts/SubagentCall.tsx
+++ b/client/src/components/Chat/Messages/Content/Parts/SubagentCall.tsx
@@ -1,7 +1,7 @@
import { useCallback, useContext, useEffect, useMemo, useReducer, useRef } from 'react';
import { useSetAtom } from 'jotai';
import { ChevronRight, Users } from 'lucide-react';
-import { EModelEndpoint } from 'librechat-data-provider';
+import { ContentTypes, EModelEndpoint } from 'librechat-data-provider';
import type {
PartMetadata,
TAttachment,
@@ -17,7 +17,6 @@ import {
} from '~/components/Chat/Subagents/state';
import { useParentSubagents } from '~/components/Chat/Subagents/ParentSubagentsProvider';
import { isSelfSpawn as isSelfSpawnType } from '~/components/Chat/Subagents/author';
-import { adaptLivePersistedActivity } from '~/components/Chat/Subagents/adapters';
import { resolveSubagentAgentId } from '~/components/Chat/Subagents/identity';
import { subagentStatusLabelKey } from '~/components/Chat/Subagents/status';
import { useOpenSubagentPanel } from '~/components/Chat/Subagents/surface';
@@ -302,41 +301,29 @@ export default function SubagentCall({
const cardLabel = subagentNameLabel ? `${subagentNameLabel}: ${headerText}` : headerText;
const canOpenDetails = useMemo(() => {
- const fallbackActivity = adaptLivePersistedActivity({
- title: '',
- progress: null,
- persistedContent,
- legacyOutput: backgroundHandle == null ? output : undefined,
- initialProgress,
- isSubmitting: false,
- runStepStatus,
- approvalVisibility: 'hidden',
- });
- const hasRenderableFallback = fallbackActivity.items.some(
- (item) =>
- (item.type !== 'writing' || item.text.length > 0) &&
- (item.type !== 'activity_label' || item.label.length > 0),
- );
const hasParentContext = parentConversationId !== '' && parentMessageId !== '';
- const canOpenLiveForeground =
- isSharedConvo !== true && backgroundHandle == null && hasParentContext;
+ if (openPanel == null || !hasParentContext) return false;
+ if (canOpenDurablePanel || (isSharedConvo !== true && backgroundHandle == null)) return true;
return (
- /** No host, no panel to open — a search result renders this same card. */
- openPanel != null &&
- hasParentContext &&
- (canOpenDurablePanel || canOpenLiveForeground || hasRenderableFallback)
+ persistedContent?.some((part) => {
+ if (part == null) return false;
+ if (part.type === ContentTypes.ACTIVITY_LABEL) return Boolean(part.activity_label?.trim());
+ if (part.type === ContentTypes.TEXT) {
+ return typeof part.text === 'string' ? part.text.length > 0 : Boolean(part.text?.value);
+ }
+ return true;
+ }) === true ||
+ (backgroundHandle == null && output != null && output !== '')
);
}, [
backgroundHandle,
openPanel,
canOpenDurablePanel,
- initialProgress,
isSharedConvo,
output,
parentConversationId,
parentMessageId,
persistedContent,
- runStepStatus,
]);
const panelSelection = useMemo(
@@ -352,6 +339,7 @@ export default function SubagentCall({
...(prompt == null ? {} : { prompt }),
...(backgroundHandle == null ? { legacyOutput: output } : {}),
...(persistedContent == null ? {} : { persistedContent }),
+ ...(attachments == null ? {} : { attachments }),
...(contentPreview == null ? {} : { contentPreview }),
initialProgress,
isSubmitting,
@@ -366,6 +354,7 @@ export default function SubagentCall({
: {}),
}),
[
+ attachments,
backgroundHandle,
canOpenDurablePanel,
contentPreview,
diff --git a/client/src/components/Chat/Messages/Content/__tests__/hydration.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/hydration.test.tsx
index 931f11e94e..39ca7c7e76 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/hydration.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/hydration.test.tsx
@@ -4,9 +4,10 @@ import { ContentTypes, dataService } from 'librechat-data-provider';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
import type { TMessageContentParts, ToolCallPartResponse } from 'librechat-data-provider';
-import type { ToolDisclosures } from '../disclosure';
+import type { ToolContentQuery, ToolDisclosures } from '../disclosure';
import {
SoleToolContext,
+ ToolContentQueryContext,
useToolExpansion,
useToolContentPending,
ToolDisclosureContext,
@@ -84,7 +85,12 @@ function Card({ part }: { part: TMessageContentParts }) {
function renderPart(
part: TMessageContentParts,
- options: { sole?: boolean; partIndex?: number; queryClient?: QueryClient } = {},
+ options: {
+ sole?: boolean;
+ partIndex?: number;
+ queryClient?: QueryClient;
+ contentQuery?: ToolContentQuery | null;
+ } = {},
) {
const queryClient =
options.queryClient ?? new QueryClient({ defaultOptions: { queries: { retry: false } } });
@@ -99,13 +105,15 @@ function renderPart(
<ToolDisclosureContext.Provider value={disclosures}>
<ToolDisclosureKeyContext.Provider value="call_1">
<SoleToolContext.Provider value={options.sole}>
- {isPreviewedToolCallPart(part) ? (
- <PreviewedToolCallPart part={part}>
- {(rendered) => <Card part={rendered} />}
- </PreviewedToolCallPart>
- ) : (
- <Card part={part} />
- )}
+ <ToolContentQueryContext.Provider value={options.contentQuery}>
+ {isPreviewedToolCallPart(part) ? (
+ <PreviewedToolCallPart part={part}>
+ {(rendered) => <Card part={rendered} />}
+ </PreviewedToolCallPart>
+ ) : (
+ <Card part={part} />
+ )}
+ </ToolContentQueryContext.Provider>
</SoleToolContext.Provider>
</ToolDisclosureKeyContext.Provider>
</ToolDisclosureContext.Provider>
@@ -284,3 +292,34 @@ describe('withFullToolCall', () => {
});
});
});
+
+describe('task-authorized tool preview loading', () => {
+ const getToolCallPart = dataService.getToolCallPart as jest.Mock;
+
+ beforeEach(() => getToolCallPart.mockReset());
+
+ it('keeps a view-only nested preview from requesting private child messages', async () => {
+ renderPart(previewPart(), { sole: true, contentQuery: null });
+ expect(await screen.findByRole('alert')).toHaveTextContent('com_ui_tool_content_error');
+ expect(screen.queryByText('com_ui_retry')).not.toBeInTheDocument();
+ expect(screen.queryByRole('status')).not.toBeInTheDocument();
+ expect(getToolCallPart).not.toHaveBeenCalled();
+ });
+
+ it('uses the authorized task query without changing standard preview hydration', async () => {
+ const useAuthorizedQuery = jest.fn().mockReturnValue({
+ data: stored(),
+ isError: false,
+ refetch: jest.fn(),
+ });
+ renderPart(previewPart(), { sole: true, contentQuery: useAuthorizedQuery });
+ expect(screen.getByTestId('output').textContent).toBe(fullOutput);
+ expect(screen.getByTestId('markers')).toHaveTextContent('false');
+ expect(getToolCallPart).not.toHaveBeenCalled();
+ expect(useAuthorizedQuery).toHaveBeenCalledWith(
+ expect.objectContaining({ messageId: 'msg-1', partIndex: 2, toolCallId: 'call_1' }),
+ expect.objectContaining({ enabled: false }),
+ expect.any(String),
+ );
+ });
+});
diff --git a/client/src/components/Chat/Messages/Content/disclosure.ts b/client/src/components/Chat/Messages/Content/disclosure.ts
index 34df97cd15..36899cf4bd 100644
--- a/client/src/components/Chat/Messages/Content/disclosure.ts
+++ b/client/src/components/Chat/Messages/Content/disclosure.ts
@@ -1,6 +1,7 @@
import { createContext, useContext, useEffect, useMemo } from 'react';
import { atom, useAtom } from 'jotai';
import type { PrimitiveAtom } from 'jotai';
+import type { useToolCallPartQuery } from '~/data-provider/Messages/queries';
import { useMessagePartsHost } from '~/Providers/MessagePartsHostContext';
export type ReasoningDisclosures = Map<number, PrimitiveAtom<boolean | undefined>>;
@@ -108,3 +109,10 @@ export function useToolExpansion(canExpand: boolean) {
useToolContentRequest(expanded);
return [expanded, setOverride] as const;
}
+
+export type ToolContentQuery = typeof useToolCallPartQuery;
+
+/** Undefined uses normal message access; null keeps a nested transcript view-only. */
+export const ToolContentQueryContext = createContext<ToolContentQuery | null | undefined>(
+ undefined,
+);
diff --git a/client/src/components/Chat/Messages/Content/hydration.tsx b/client/src/components/Chat/Messages/Content/hydration.tsx
index 10f9dc78c5..37a22db0d4 100644
--- a/client/src/components/Chat/Messages/Content/hydration.tsx
+++ b/client/src/components/Chat/Messages/Content/hydration.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useMemo, useState } from 'react';
+import { useCallback, useContext, useMemo, useState } from 'react';
import { Spinner } from '@librechat/client';
import {
ContentTypes,
@@ -7,7 +7,11 @@ import {
} from 'librechat-data-provider';
import type { FullToolCall, TMessageContentParts } from 'librechat-data-provider';
import type { ReactNode } from 'react';
-import { ToolContentRequestContext, ToolContentPendingContext } from './disclosure';
+import {
+ ToolContentRequestContext,
+ ToolContentPendingContext,
+ ToolContentQueryContext,
+} from './disclosure';
import { useMessagePartsHost } from '~/Providers/MessagePartsHostContext';
import { useToolCallPartQuery } from '~/data-provider';
import { useLocalize } from '~/hooks';
@@ -71,8 +75,11 @@ export function PreviewedToolCallPart({
const request = useCallback(() => setRequested(true), []);
const toolCall = part.tool_call as FullToolCall;
const revision = useMemo(() => getToolCallPreviewRevision(toolCall), [toolCall]);
- const canFetch = !!conversationId && !!messageId && partIndex != null;
- const query = useToolCallPartQuery(
+ const configuredQuery = useContext(ToolContentQueryContext);
+ const queryHook = configuredQuery === undefined ? useToolCallPartQuery : configuredQuery;
+ const usePartQuery = queryHook ?? useToolCallPartQuery;
+ const canFetch = queryHook != null && !!conversationId && !!messageId && partIndex != null;
+ const query = usePartQuery(
{
conversationId: conversationId ?? '',
messageId: messageId ?? '',
@@ -84,7 +91,7 @@ export function PreviewedToolCallPart({
{ enabled: requested && canFetch },
revision,
);
- const full = query.data?.tool_call;
+ const full = queryHook == null ? undefined : query.data?.tool_call;
const effectivePart = useMemo(
() => (full == null ? part : withFullToolCall(part, full)),
[full, part],
@@ -98,16 +105,18 @@ export function PreviewedToolCallPart({
<ToolContentPendingContext.Provider value={full == null}>
{children(effectivePart)}
</ToolContentPendingContext.Provider>
- {requested && full == null && query.isError && (
+ {requested && full == null && (queryHook == null || query.isError) && (
<div role="alert" className="text-text-warning mb-2 flex items-center gap-2 ps-1 text-xs">
<span>{localize('com_ui_tool_content_error')}</span>
- <button
- type="button"
- onClick={retry}
- className="text-text-primary underline underline-offset-2"
- >
- {localize('com_ui_retry')}
- </button>
+ {queryHook != null && (
+ <button
+ type="button"
+ onClick={retry}
+ className="text-text-primary underline underline-offset-2"
+ >
+ {localize('com_ui_retry')}
+ </button>
+ )}
</div>
)}
{requested && full == null && !query.isError && canFetch && (
diff --git a/client/src/components/Chat/Subagents/SharedSubagentActivityDialog.tsx b/client/src/components/Chat/Subagents/SharedSubagentActivityDialog.tsx
index 64376d029b..071fbc00e3 100644
--- a/client/src/components/Chat/Subagents/SharedSubagentActivityDialog.tsx
+++ b/client/src/components/Chat/Subagents/SharedSubagentActivityDialog.tsx
@@ -82,6 +82,7 @@ export default function SharedSubagentActivityDialog({
prompt: selection?.prompt,
progress: null,
persistedContent: selection?.persistedContent,
+ attachments: selection?.attachments,
legacyOutput: selection?.legacyOutput,
initialProgress: selection?.initialProgress ?? 1,
isSubmitting: false,
diff --git a/client/src/components/Chat/Subagents/SubagentActivity.test.tsx b/client/src/components/Chat/Subagents/SubagentActivity.test.tsx
index 45fcd6d145..b2164870fb 100644
--- a/client/src/components/Chat/Subagents/SubagentActivity.test.tsx
+++ b/client/src/components/Chat/Subagents/SubagentActivity.test.tsx
@@ -1,6 +1,7 @@
import React from 'react';
+import { ContentTypes } from 'librechat-data-provider';
import { act, fireEvent, render as rtlRender, screen } from '@testing-library/react';
-import type { Agents } from 'librechat-data-provider';
+import type { TMessageContentParts, Agents } from 'librechat-data-provider';
import type { ChildActivity } from './adapters';
import SubagentActivity, { SubagentActivityScrollSurface } from './SubagentActivity';
import { ChatSurfaceHarness } from 'test/harness';
@@ -10,6 +11,16 @@ const Wrapper = ({ children }: { children: React.ReactNode }) => (
);
const render = (ui: React.ReactElement) => rtlRender(ui, { wrapper: Wrapper });
+const mockContentParts = jest.fn();
+let mockAutoExpandTools = false;
+
+jest.mock('~/Providers/MessagePartsHostContext', () => ({
+ useMessagePartsHost: () => ({
+ useShowThinking: () => false,
+ useAutoExpandTools: () => mockAutoExpandTools,
+ }),
+}));
+
jest.mock('~/hooks', () => ({
useLocalize: () => (key: string) => key,
}));
@@ -23,6 +34,7 @@ jest.mock('~/components/Chat/Messages/Content/ContentParts', () => ({
default: function MockContentParts({
content,
messageId,
+ ...props
}: {
content: Array<{
type: string;
@@ -42,13 +54,16 @@ jest.mock('~/components/Chat/Messages/Content/ContentParts', () => ({
};
}>;
messageId: string;
+ foldLiveActivity?: boolean;
}) {
+ mockContentParts({ content, messageId, ...props });
const { useState } = jest.requireActual<typeof import('react')>('react');
const [expandedTool, setExpandedTool] = useState<string | null>(null);
- const tools = content.filter((part) => part.type === 'tool_call');
+ const tools = content.filter((part) => part?.type === 'tool_call');
return (
<div data-testid="regular-content-parts" data-message-id={messageId}>
{content.map((part, index) => {
+ if (part == null) return null;
if (part.type === 'text') {
return (
<div key={index} data-phase={part.phase}>
@@ -169,7 +184,15 @@ jest.mock('~/components/Chat/Messages/Content/ToolApproval', () => ({
default: () => <div data-testid="tool-approval">approval</div>,
}));
+jest.mock('~/components/Chat/Steering/Receipt', () => ({
+ __esModule: true,
+ default: ({ state }: { state: string }) => (
+ <span data-testid="steer-receipt" data-receipt-state={state} />
+ ),
+}));
+
jest.mock('@librechat/client', () => ({
+ Alert: ({ children }: { children: React.ReactNode }) => <div role="alert">{children}</div>,
Button: ({ children, ...props }: React.ComponentProps<'button'>) => (
<button {...props}>{children}</button>
),
@@ -225,6 +248,62 @@ it('keeps a host notice inside the floating-header clearance', () => {
});
describe('SubagentActivity', () => {
+ beforeEach(() => {
+ mockContentParts.mockClear();
+ mockAutoExpandTools = false;
+ });
+
+ it('passes standard content unchanged with its stable message identity', () => {
+ const content: TMessageContentParts[] = [
+ {
+ type: ContentTypes.THINK,
+ think: 'Reasoning.',
+ agentId: 'agent-1',
+ reasoning_label: 'Checked constraints',
+ reasoning_label_step_id: 'step-1',
+ reasoning_label_revision: 4,
+ },
+ {
+ type: ContentTypes.TOOL_CALL,
+ agentId: 'agent-1',
+ tool_call: {
+ id: 'call-1',
+ name: 'bash',
+ args: '{}',
+ output: 'result',
+ stepId: 'step-2',
+ progress: 1,
+ outputTruncated: true,
+ previewRevision: 'revision-2',
+ toolPreparationDurationMs: 21,
+ toolExecutionDurationMs: 34,
+ },
+ },
+ { type: ContentTypes.ERROR, error: 'Failure', agentId: 'agent-1' },
+ ] as TMessageContentParts[];
+ render(
+ <SubagentActivity
+ activity={{ ...base, content, messageId: 'stable-response', items: [] }}
+ activityId="synthetic-response"
+ />,
+ );
+ expect(mockContentParts).toHaveBeenLastCalledWith(
+ expect.objectContaining({ content, messageId: 'stable-response' }),
+ );
+ expect(mockContentParts.mock.calls.at(-1)?.[0].content).toBe(content);
+ });
+
+ it.each([false, true])(
+ 'uses the shared default fold policy with card auto-expand=%s',
+ (autoExpand) => {
+ mockAutoExpandTools = autoExpand;
+ render(<SubagentActivity activity={{ ...base, status: 'running' }} />);
+ expect(mockContentParts).toHaveBeenLastCalledWith(
+ expect.objectContaining({ isSubmitting: true }),
+ );
+ expect(mockContentParts.mock.calls.at(-1)?.[0].foldLiveActivity).toBeUndefined();
+ },
+ );
it.each(['failed', 'cancelled'] as const)(
'renders the %s lifecycle through the shared view',
(status) => {
@@ -298,7 +377,7 @@ describe('SubagentActivity', () => {
expect(screen.getByTestId('tool-approval')).toBeInTheDocument();
});
- it('renders bounded tool details without any shortening caption', () => {
+ it('keeps a genuine legacy truncation notice instead of claiming full details', () => {
render(
<SubagentActivity
activity={{
@@ -318,9 +397,7 @@ describe('SubagentActivity', () => {
);
expect(screen.queryByText('bounded input')).not.toBeInTheDocument();
- expect(
- screen.queryByText('com_ui_subagent_activity_details_truncated'),
- ).not.toBeInTheDocument();
+ expect(screen.queryByText('com_ui_subagent_activity_details_unavailable')).toBeInTheDocument();
expect(screen.queryByText('com_ui_subagent_thread_history_truncated')).not.toBeInTheDocument();
});
@@ -571,7 +648,7 @@ describe('SubagentActivity', () => {
it('renders the load error state', () => {
render(<SubagentActivity activity={{ ...base, items: [] }} state="error" />);
- expect(screen.getByText('com_ui_subagent_thread_load_error')).toBeInTheDocument();
+ expect(screen.getByText('com_ui_conversation_load_error')).toBeInTheDocument();
});
it('does not describe a completed tool-only child as missing a result', () => {
@@ -579,3 +656,88 @@ describe('SubagentActivity', () => {
expect(screen.queryByText('com_ui_subagent_empty_result')).not.toBeInTheDocument();
});
});
+
+it('retains standard content when a refresh fails and reports the failure', () => {
+ render(<SubagentActivity activity={base} state="error" />);
+ expect(screen.getByText('Final answer.')).toBeInTheDocument();
+ expect(screen.getByRole('alert')).toHaveTextContent('com_ui_conversation_load_error');
+});
+
+it('does not repeat an applied control already rendered at its standard content position', () => {
+ render(
+ <SubagentActivity
+ activity={{
+ ...base,
+ content: [{ type: ContentTypes.STEER, steer: 'Applied message', steerId: 'control-1' }],
+ controls: [
+ {
+ invocationId: 'invocation-1',
+ controlId: 'control-1',
+ action: 'steer',
+ status: 'applied',
+ message: 'Applied message',
+ createdAt: '2026-10-20T00:00:00Z',
+ updatedAt: '2026-10-20T00:00:01Z',
+ },
+ ],
+ }}
+ />,
+ );
+ expect(screen.queryByText('com_ui_subagent_control_status_applied')).not.toBeInTheDocument();
+ expect(mockContentParts.mock.calls.at(-1)?.[0].content[0]).toMatchObject({
+ type: ContentTypes.STEER,
+ steerId: 'control-1',
+ });
+});
+
+it('does not claim delivery or application before the server confirms it', () => {
+ render(
+ <SubagentActivity
+ activity={{
+ ...base,
+ controls: [
+ {
+ invocationId: 'invocation-1',
+ action: 'steer',
+ status: 'submitted',
+ message: 'Check it',
+ createdAt: '2026-10-20T00:00:00Z',
+ updatedAt: '2026-10-20T00:00:00Z',
+ },
+ ],
+ }}
+ />,
+ );
+ expect(screen.getByTestId('steer-receipt')).toHaveAttribute('data-receipt-state', 'sending');
+});
+
+it('preserves empty recovered slots when rendering applied control receipts', () => {
+ const sparse = new Array<TMessageContentParts>(2);
+ sparse[1] = {
+ type: ContentTypes.TOOL_CALL,
+ tool_call: { id: 'retained', name: 'retained', args: '{}', output: 'Done', progress: 1 },
+ };
+ const content: TMessageContentParts[] = JSON.parse(JSON.stringify(sparse));
+ render(
+ <SubagentActivity
+ activity={{
+ ...base,
+ content,
+ controls: [
+ {
+ invocationId: 'applied-sparse',
+ controlId: 'guidance',
+ action: 'steer',
+ status: 'applied',
+ createdAt: '2026-10-20T00:00:00.000Z',
+ updatedAt: '2026-10-20T00:00:00.000Z',
+ message: 'Continue',
+ },
+ ],
+ }}
+ />,
+ );
+ expect(screen.getAllByTestId('regular-content-parts').length).toBeGreaterThan(0);
+ expect(mockContentParts.mock.calls[0][0].content[0]).toBeNull();
+ expect(mockContentParts.mock.calls[0][0].content[1].tool_call.id).toBe('retained');
+});
diff --git a/client/src/components/Chat/Subagents/SubagentActivity.tsx b/client/src/components/Chat/Subagents/SubagentActivity.tsx
index 2e2dfab50e..a260bd908d 100644
--- a/client/src/components/Chat/Subagents/SubagentActivity.tsx
+++ b/client/src/components/Chat/Subagents/SubagentActivity.tsx
@@ -1,10 +1,11 @@
import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';
-import { useAtomValue } from 'jotai';
-import { Button } from '@librechat/client';
+import { Alert, Button } from '@librechat/client';
+import { Maximize2, Minimize2 } from 'lucide-react';
import { ContentTypes } from 'librechat-data-provider';
import { CSSTransition } from 'react-transition-group';
-import { CheckCircle2, Clock3, Maximize2, Minimize2, XCircle } from 'lucide-react';
-import type { TMessageContentParts } from 'librechat-data-provider';
+import type { SearchResultData, TMessageContentParts } from 'librechat-data-provider';
+import type { ToolContentQuery } from '~/components/Chat/Messages/Content/disclosure';
+import type { SteerReceiptState } from '~/components/Chat/Steering/Receipt';
import type { ChildActivity, ChildActivityItem } from './adapters';
import type { TranslationKeys } from '~/hooks';
import {
@@ -13,12 +14,15 @@ import {
subagentStatusIcon,
subagentStatusLabelKey,
} from './status';
+import { ToolContentQueryContext } from '~/components/Chat/Messages/Content/disclosure';
+import MessageTimestamp from '~/components/Chat/Messages/ui/MessageTimestamp';
import MarkdownLite from '~/components/Chat/Messages/Content/MarkdownLite';
import ContentParts from '~/components/Chat/Messages/Content/ContentParts';
+import { useMessagePartsHost } from '~/Providers/MessagePartsHostContext';
import Container from '~/components/Chat/Messages/Content/Container';
import { EmptyText } from '~/components/Chat/Messages/Content/Parts';
import ScrollToBottom from '~/components/Messages/ScrollToBottom';
-import { showThinkingAtom } from '~/store/showThinking';
+import SteerReceipt from '~/components/Chat/Steering/Receipt';
import { useChatSurface } from './surface';
import { useLocalize } from '~/hooks';
import { cn } from '~/utils';
@@ -53,7 +57,9 @@ const CONTROL_REASON_LABELS: Record<string, TranslationKeys> = {
function SubagentControlHistory({
controls,
onCancelControl,
+ content,
}: {
+ content: TMessageContentParts[];
controls: NonNullable<ChildActivity['controls']>;
onCancelControl?: (controlId: string) => void;
}) {
@@ -71,23 +77,54 @@ function SubagentControlHistory({
return (
<section aria-label={localize('com_ui_subagent_control_history')} className="mb-3 space-y-2">
{chronologicalControls.map((control) => {
+ if (
+ control.status === 'applied' &&
+ content.some(
+ (part) =>
+ part?.type === ContentTypes.STEER &&
+ part.steerId != null &&
+ (part.steerId === control.controlId || part.steerId === control.invocationId),
+ )
+ ) {
+ return null;
+ }
const pending = control.status === 'submitted' || control.status === 'accepted';
- let StatusIcon = XCircle;
- if (pending) StatusIcon = Clock3;
- if (control.status === 'applied') StatusIcon = CheckCircle2;
+ let receiptState: SteerReceiptState | undefined;
+ if (control.action !== 'cancel' && control.action !== 'cancel_message') {
+ if (control.status === 'submitted') receiptState = 'sending';
+ else if (control.status === 'accepted') receiptState = 'delivered';
+ else if (control.status === 'applied') receiptState = 'applied';
+ }
return (
- <div
- key={control.invocationId}
- className="border-border-light bg-surface-secondary rounded-lg border px-3 py-2 text-sm"
- >
- <div className="flex flex-wrap items-center gap-2">
- <StatusIcon size={14} aria-hidden className="text-text-secondary shrink-0" />
- <span className="min-w-0 flex-1 font-medium">
+ <div key={control.invocationId} className="group my-3 flex flex-col items-end text-sm">
+ {control.message != null && control.message !== '' && (
+ <div className="rounded-theme-surface rounded-ee-theme-control bg-surface-user-message px-theme-normal max-w-[90%] py-2.5 sm:max-w-[85%]">
+ <ContentParts
+ content={[{ type: ContentTypes.TEXT, text: control.message }]}
+ messageId={`control:${control.invocationId}`}
+ conversationId={null}
+ isCreatedByUser
+ isLast={false}
+ isSubmitting={false}
+ isLatestMessage={false}
+ showThinking={false}
+ />
+ {control.messageTruncated === true && (
+ <div className="text-text-secondary mt-1 text-xs italic">
+ {localize('com_ui_subagent_control_message_truncated')}
+ </div>
+ )}
+ </div>
+ )}
+ <div className="text-text-secondary mt-1 flex min-h-8 flex-wrap items-center justify-end gap-2 text-xs">
+ <span className={control.message ? 'sr-only' : undefined}>
{localize(CONTROL_ACTION_LABELS[control.action])}
</span>
- <span className="text-text-secondary ms-auto shrink-0 text-xs" aria-live="polite">
+ <MessageTimestamp value={control.createdAt} className="ms-0" />
+ <span className={receiptState == null ? undefined : 'sr-only'} aria-live="polite">
{localize(CONTROL_STATUS_LABELS[control.status])}
</span>
+ {receiptState != null && <SteerReceipt state={receiptState} live={pending} />}
{control.status === 'accepted' &&
control.controlId != null &&
onCancelControl != null && (
@@ -102,16 +139,6 @@ function SubagentControlHistory({
</Button>
)}
</div>
- {control.message != null && control.message !== '' && (
- <div className="text-text-secondary mt-1 break-words">
- {control.message}
- {control.messageTruncated === true && (
- <span className="ms-1 text-xs italic">
- {localize('com_ui_subagent_control_message_truncated')}
- </span>
- )}
- </div>
- )}
{control.reason != null && (
<div className="text-status-error mt-1 text-xs">
{localize(
@@ -266,6 +293,9 @@ const toContentPart = (item: ChildActivityItem): TMessageContentParts => {
} as TMessageContentParts;
};
+export const getActivityContent = (activity: ChildActivity): TMessageContentParts[] =>
+ activity.content ?? activity.items.map(toContentPart);
+
function SubagentPrompt({ prompt }: { prompt: string }) {
const localize = useLocalize();
const [expanded, setExpanded] = useState(false);
@@ -324,7 +354,15 @@ export function SubagentActivityContent({
conversationId = null,
underHeaderIcon = false,
onCancelControl,
+ content,
+ authorHeader,
+ searchResults,
+ toolContentQuery,
}: {
+ toolContentQuery?: ToolContentQuery;
+ authorHeader?: React.ReactNode;
+ searchResults?: Record<string, SearchResultData>;
+ content?: TMessageContentParts[];
activity: ChildActivity;
activityId?: string;
state?: 'ready' | 'loading' | 'error';
@@ -337,24 +375,26 @@ export function SubagentActivityContent({
onCancelControl?: (controlId: string) => void;
}) {
const localize = useLocalize();
- const showThinking = useAtomValue(showThinkingAtom);
+ const host = useMessagePartsHost();
+ const showThinking = host.useShowThinking();
const isSubmitting = isLiveSubagentStatus(activity.status);
- const parts = useMemo(() => activity.items.map(toContentPart), [activity.items]);
+ const parts = useMemo(() => content ?? getActivityContent(activity), [content, activity]);
+ const errorNotice = (
+ <Alert variant="error" role="alert">
+ {localize('com_ui_conversation_load_error')}
+ </Alert>
+ );
let body: React.ReactNode;
- if (state === 'loading') {
+ if (state === 'loading' && parts.length === 0) {
body = (
<Container>
<EmptyText underHeaderIcon={underHeaderIcon} />
</Container>
);
- } else if (state === 'error') {
- body = (
- <div className="border-status-error-border bg-status-error-subtle text-status-error rounded-lg border p-3 text-sm">
- {localize('com_ui_subagent_thread_load_error')}
- </div>
- );
- } else if (activity.items.length === 0) {
+ } else if (state === 'error' && parts.length === 0) {
+ body = errorNotice;
+ } else if (parts.length === 0) {
body = isSubmitting ? (
<Container>
<EmptyText underHeaderIcon={underHeaderIcon} />
@@ -362,25 +402,44 @@ export function SubagentActivityContent({
) : null;
} else {
body = (
- <ContentParts
- content={parts}
- messageId={activityId ?? 'subagent-activity-panel'}
- conversationId={conversationId}
- isCreatedByUser={false}
- isLast
- isSubmitting={isSubmitting}
- showThinking={showThinking}
- isLatestMessage={isSubmitting}
- foldLiveActivity={false}
- />
+ <ToolContentQueryContext.Provider value={toolContentQuery ?? null}>
+ <ContentParts
+ content={parts}
+ messageId={activity.messageId ?? activityId ?? 'subagent-activity-panel'}
+ conversationId={conversationId}
+ attachments={activity.attachments}
+ searchResults={searchResults}
+ authorHeader={authorHeader}
+ isCreatedByUser={false}
+ isLast
+ isSubmitting={isSubmitting}
+ showThinking={showThinking}
+ isLatestMessage={isSubmitting}
+ />
+ </ToolContentQueryContext.Provider>
);
}
return (
<div className="flex max-w-full flex-col gap-0">
{showPrompt && activity.prompt != null && <SubagentPrompt prompt={activity.prompt} />}
+ {state === 'error' && parts.length > 0 && errorNotice}
+ {body}
+ {activity.content == null &&
+ activity.activityTruncated !== true &&
+ activity.items.some((item) => {
+ if (item.type === 'tool')
+ return item.inputTruncated === true || item.outputTruncated === true;
+ if (item.type === 'activity_label') return item.labelTruncated === true;
+ return item.textTruncated === true;
+ }) && (
+ <div role="status" className="text-text-secondary mt-2 text-xs">
+ {localize('com_ui_subagent_activity_details_unavailable')}
+ </div>
+ )}
<SubagentControlHistory
controls={activity.controls ?? []}
+ content={parts}
onCancelControl={onCancelControl}
/>
{activity.controlsTruncated === true && (
@@ -388,7 +447,6 @@ export function SubagentActivityContent({
{localize('com_ui_subagent_control_history_truncated')}
</div>
)}
- {body}
</div>
);
}
diff --git a/client/src/components/Chat/Subagents/SubagentConversation.test.tsx b/client/src/components/Chat/Subagents/SubagentConversation.test.tsx
index 220743914c..dd831b61bc 100644
--- a/client/src/components/Chat/Subagents/SubagentConversation.test.tsx
+++ b/client/src/components/Chat/Subagents/SubagentConversation.test.tsx
@@ -1,10 +1,58 @@
import React from 'react';
+import { ContentTypes } from 'librechat-data-provider';
import { fireEvent, render, screen, within } from '@testing-library/react';
+import type {
+ FullToolCall,
+ PartMetadata,
+ TMessage,
+ TMessageContentParts,
+} from 'librechat-data-provider';
+import type { ChatContract } from '~/hooks/Chat/contract';
import type { ChildConversationTurn } from './adapters';
import type { TurnAuthor } from './author';
import SubagentConversation from './SubagentConversation';
+import { mergeChildConversationTurns } from './adapters';
+import { ChatContext } from '~/Providers/ChatContext';
import { ChatSurfaceHarness } from 'test/harness';
+const mockRecoveredQuery = jest.fn();
+jest.mock('~/data-provider/Subagents/content', () => ({
+ ...jest.requireActual('~/data-provider/Subagents/content'),
+ useSubagentTaskContentQuery: (...args: unknown[]) => mockRecoveredQuery(...args),
+}));
+
+const mockCopyMessage = jest.fn();
+const mockRenderedContent = jest.fn();
+const mockPartScope = jest.fn();
+const mockParentAsk = jest.fn();
+
+jest.mock('~/Providers/MessagePartsHostContext', () => {
+ const React = jest.requireActual<typeof import('react')>('react');
+ const Context = React.createContext({
+ useShowThinking: () => false,
+ useAutoExpandTools: () => false,
+ useMessagesAsk: () => mockParentAsk,
+ });
+ return {
+ MessagePartsHostProvider: ({
+ host,
+ children,
+ }: {
+ host: React.ContextType<typeof Context>;
+ children: React.ReactNode;
+ }) => <Context.Provider value={host}>{children}</Context.Provider>,
+ useMessagePartsHost: () => React.useContext(Context),
+ };
+});
+
+jest.mock('~/components/Chat/Messages/MinimalHoverButtons', () => ({
+ __esModule: true,
+ default: ({ message }: { message: TMessage }) => {
+ mockCopyMessage(message);
+ return <button type="button" aria-label="copy" />;
+ },
+}));
+
jest.mock('~/hooks', () => ({
useLocalize: () => (key: string) => key,
}));
@@ -15,24 +63,31 @@ jest.mock('~/Providers', () => ({
jest.mock('~/components/Chat/Messages/Content/ContentParts', () => ({
__esModule: true,
- default: ({
+ default: function ContentPartsMock({
content,
messageId,
}: {
content: Array<Record<string, unknown>>;
messageId: string;
- }) => (
- <div data-testid="shared-content-parts" data-message-id={messageId}>
- {content.map((part, index) => (
- <span key={index}>
- {(part.text as string | undefined) ??
- (part.think as string | undefined) ??
- (part.tool_call as { name?: string } | undefined)?.name ??
- ''}
- </span>
- ))}
- </div>
- ),
+ }) {
+ const React = jest.requireActual<typeof import('react')>('react');
+ const { ChatContext } = jest.requireActual('~/Providers/ChatContext');
+ const { useMessagePartsHost } = jest.requireMock('~/Providers/MessagePartsHostContext');
+ mockPartScope(React.useContext(ChatContext), useMessagePartsHost().useMessagesAsk());
+ mockRenderedContent(content);
+ return (
+ <div data-testid="shared-content-parts" data-message-id={messageId}>
+ {content.map((part, index) => (
+ <span key={index}>
+ {(part?.text as string | undefined) ??
+ (part?.think as string | undefined) ??
+ (part?.tool_call as { name?: string } | undefined)?.name ??
+ ''}
+ </span>
+ ))}
+ </div>
+ );
+ },
}));
jest.mock('~/components/Chat/Messages/Content/Container', () => ({
@@ -147,9 +202,7 @@ describe('SubagentConversation', () => {
expect(
screen.queryByText('com_ui_subagent_activity_details_truncated'),
).not.toBeInTheDocument();
- expect(
- screen.queryByText('com_ui_subagent_activity_details_unavailable'),
- ).not.toBeInTheDocument();
+ expect(screen.queryByText('com_ui_subagent_activity_details_unavailable')).toBeInTheDocument();
expect(screen.getByTestId('stream-elapsed')).toBeInTheDocument();
fireEvent.click(
@@ -198,7 +251,7 @@ describe('SubagentConversation', () => {
</ChatSurfaceHarness>,
);
- fireEvent.click(screen.getByRole('button', { name: 'com_ui_subagent_show_full_activity' }));
+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_load_more' }));
expect(loadDetails).toHaveBeenCalledWith('task-1');
});
@@ -239,3 +292,649 @@ describe('SubagentConversation', () => {
).toBeInTheDocument();
});
});
+
+describe('standard conversation content', () => {
+ beforeEach(() => {
+ mockCopyMessage.mockClear();
+ mockPartScope.mockClear();
+ mockParentAsk.mockClear();
+ });
+
+ it('copies the standard message source through the normal safe-copy action', () => {
+ const content = [
+ { type: 'text', text: 'Authoritative answer', phase: 'final_answer' },
+ {
+ type: 'tool_call',
+ tool_call: { id: 'tool', name: 'bash', args: 'private input', output: 'private output' },
+ },
+ ] as TMessageContentParts[];
+ render(
+ <ChatSurfaceHarness>
+ <SubagentConversation
+ turns={[
+ {
+ ...turns[0],
+ activity: { ...turns[0].activity, content, messageId: 'stable-response' },
+ },
+ ]}
+ author={author}
+ parentAuthor={parentAuthor}
+ />
+ </ChatSurfaceHarness>,
+ );
+ expect(mockCopyMessage).toHaveBeenCalledWith(
+ expect.objectContaining({
+ messageId: 'stable-response',
+ content,
+ text: '',
+ isCreatedByUser: false,
+ }),
+ );
+ expect(mockCopyMessage.mock.calls.at(-1)?.[0].content).toBe(content);
+ expect(screen.queryByText('The release is ready.')).not.toBeInTheDocument();
+ });
+
+ it.each([false, true])(
+ 'never binds normal send effects, interactive approval scope=%s',
+ (interactive) => {
+ const parent: ChatContract = {
+ index: 0,
+ conversation: {
+ conversationId: 'parent',
+ title: null,
+ endpoint: null,
+ createdAt: '2026-10-20T00:00:00.000Z',
+ updatedAt: '2026-10-20T00:00:00.000Z',
+ },
+ setConversation: () => undefined,
+ newConversation: () => undefined,
+ preset: null,
+ setPreset: () => undefined,
+ optionSettings: {},
+ setOptionSettings: () => undefined,
+ messagesKey: 'parent',
+ getMessages: () => [],
+ setMessages: () => undefined,
+ setSiblingIdx: () => undefined,
+ latestMessageId: undefined,
+ latestMessageDepth: undefined,
+ useLiveAttachments: () => ({}),
+ ask: mockParentAsk,
+ regenerate: () => undefined,
+ isSubmitting: false,
+ setIsSubmitting: () => undefined,
+ handleRegenerate: () => undefined,
+ handleContinue: () => undefined,
+ stopGenerating: async () => undefined,
+ handleStopGenerating: () => undefined,
+ abortScroll: false,
+ setAbortScroll: () => undefined,
+ files: new Map(),
+ setFiles: () => undefined,
+ filesLoading: false,
+ setFilesLoading: () => undefined,
+ feedbackEnabled: false,
+ };
+ render(
+ <ChatSurfaceHarness>
+ <ChatContext.Provider value={parent}>
+ <SubagentConversation
+ turns={[turns[0]]}
+ author={author}
+ parentAuthor={parentAuthor}
+ interactive={interactive}
+ />
+ </ChatContext.Provider>
+ </ChatSurfaceHarness>,
+ );
+ const [context, ask] = mockPartScope.mock.calls.at(-1)!;
+ expect(context).toBe(interactive ? parent : null);
+ ask({ text: 'Do not send this through the parent' });
+ expect(mockParentAsk).not.toHaveBeenCalled();
+ },
+ );
+});
+
+it.each(['failed', 'cancelled', 'interrupted', 'completed'] as const)(
+ 'keeps the durable %s explanation when recovered content is empty',
+ (status) => {
+ mockRecoveredQuery.mockReturnValue({
+ data: {
+ messageId: 'task-1:assistant',
+ status,
+ recovery: 'complete',
+ content: [],
+ throughSequence: -1,
+ targetThroughSequence: -1,
+ },
+ isError: false,
+ isUnavailable: false,
+ });
+ render(
+ <ChatSurfaceHarness>
+ <SubagentConversation
+ author={author}
+ parentAuthor={parentAuthor}
+ recovery={{
+ parentConversationId: 'parent',
+ threadId: 'child',
+ selectedTaskId: 'task-1',
+ ready: true,
+ }}
+ turns={[
+ {
+ ...turns[0],
+ activity: {
+ ...turns[0].activity,
+ status,
+ items: [{ type: 'writing', text: 'Safe durable outcome.' }],
+ },
+ },
+ ]}
+ />
+ </ChatSurfaceHarness>,
+ );
+ expect(screen.getByText('Safe durable outcome.')).toBeInTheDocument();
+ },
+);
+
+it.each(['running', 'completed'] as const)(
+ 'keeps visible activity until the %s recovery snapshot has renderable content',
+ (status) => {
+ mockRecoveredQuery.mockReturnValue({
+ data: {
+ messageId: 'task-1:assistant',
+ status,
+ recovery: 'partial',
+ content: [],
+ throughSequence: -1,
+ targetThroughSequence: -1,
+ },
+ });
+ const props = {
+ author,
+ parentAuthor,
+ recovery: {
+ parentConversationId: 'parent',
+ threadId: 'child',
+ selectedTaskId: 'task-1',
+ ready: true,
+ },
+ turns: [
+ {
+ ...turns[0],
+ activity: {
+ ...turns[0].activity,
+ status,
+ items: [{ type: 'writing' as const, text: 'Visible live activity.' }],
+ },
+ },
+ ],
+ };
+ const { rerender } = render(
+ <ChatSurfaceHarness>
+ <SubagentConversation {...props} />
+ </ChatSurfaceHarness>,
+ );
+ expect(screen.getByText('Visible live activity.')).toBeInTheDocument();
+ mockRecoveredQuery.mockReturnValue({
+ data: {
+ messageId: 'task-1:assistant',
+ status,
+ recovery: 'partial',
+ content: [{ type: 'text', text: 'Committed history.' }],
+ throughSequence: 0,
+ targetThroughSequence: 0,
+ },
+ });
+ rerender(
+ <ChatSurfaceHarness>
+ <SubagentConversation {...props} />
+ </ChatSurfaceHarness>,
+ );
+ expect(screen.getByText('Committed history.')).toBeInTheDocument();
+ expect(screen.queryByText('Visible live activity.')).not.toBeInTheDocument();
+ },
+);
+
+it.each([false, true, undefined])(
+ 'gates historical recovery with loaded task capability %s',
+ (contentRecoveryAvailable) => {
+ mockRecoveredQuery.mockReset();
+ mockRecoveredQuery.mockReturnValue({});
+ render(
+ <ChatSurfaceHarness>
+ <SubagentConversation
+ author={author}
+ parentAuthor={parentAuthor}
+ recovery={{
+ parentConversationId: 'parent',
+ threadId: 'child',
+ selectedTaskId: 'other',
+ ready: true,
+ }}
+ turns={[{ ...turns[0], contentRecoveryAvailable }]}
+ />
+ </ChatSurfaceHarness>,
+ );
+ expect(mockRecoveredQuery).toHaveBeenLastCalledWith(
+ { parentConversationId: 'parent', threadId: 'child', taskId: 'task-1' },
+ { enabled: contentRecoveryAvailable !== false },
+ );
+ },
+);
+
+it('does not render cached recovery after refreshed history revokes the retained task', () => {
+ mockRecoveredQuery.mockReturnValue({
+ data: {
+ messageId: 'task-1:assistant',
+ status: 'completed',
+ recovery: 'complete',
+ content: [{ type: 'text', text: 'Cached recovered content.' }],
+ throughSequence: 0,
+ targetThroughSequence: 0,
+ },
+ });
+ const props = {
+ author,
+ parentAuthor,
+ recovery: {
+ parentConversationId: 'parent',
+ threadId: 'child',
+ selectedTaskId: 'task-1',
+ ready: true,
+ },
+ turns: [
+ {
+ ...turns[0],
+ contentRecoveryAvailable: true,
+ activity: {
+ ...turns[0].activity,
+ items: [{ type: 'writing' as const, text: 'Current durable activity.' }],
+ },
+ },
+ ],
+ };
+ const { rerender } = render(
+ <ChatSurfaceHarness>
+ <SubagentConversation {...props} />
+ </ChatSurfaceHarness>,
+ );
+ expect(screen.getByText('Cached recovered content.')).toBeInTheDocument();
+ rerender(
+ <ChatSurfaceHarness>
+ <SubagentConversation
+ {...props}
+ turns={mergeChildConversationTurns(props.turns, [
+ { ...props.turns[0], contentRecoveryAvailable: false },
+ ])}
+ />
+ </ChatSurfaceHarness>,
+ );
+ expect(screen.queryByText('Cached recovered content.')).not.toBeInTheDocument();
+ expect(screen.getByText('Current durable activity.')).toBeInTheDocument();
+ expect(mockRecoveredQuery).toHaveBeenLastCalledWith(expect.any(Object), { enabled: false });
+});
+
+it.each(
+ (['running', 'completed'] as const).flatMap((status) =>
+ (['snapshot', 'live fallback', 'revoked cache'] as const).map((source) => ({ status, source })),
+ ),
+)(
+ 'strips root and nested approvals from $status $source without changing the cache',
+ ({ status, source }) => {
+ const nested: FullToolCall & PartMetadata = {
+ id: 'nested',
+ name: 'nested_tool',
+ args: '{}',
+ output: '',
+ progress: 0,
+ approval: { actionId: 'nested-approval', allowed_decisions: ['approve'] },
+ };
+ const tool: FullToolCall & PartMetadata = {
+ id: 'root',
+ name: 'protected_tool',
+ args: '{}',
+ output: '',
+ progress: 0,
+ stepId: 'root-step',
+ toolPreparationDurationMs: 12,
+ approval: { actionId: 'root-approval', allowed_decisions: ['approve', 'reject'] },
+ subagent_content: [
+ { type: ContentTypes.TOOL_CALL, agentId: 'nested-worker', tool_call: nested },
+ ],
+ };
+ const content: TMessageContentParts[] = [
+ {
+ type: ContentTypes.TEXT,
+ text: 'Recovered answer.',
+ phase: 'commentary',
+ agentId: 'worker',
+ },
+ { type: ContentTypes.TOOL_CALL, agentId: 'worker', tool_call: tool },
+ ];
+ const cached = JSON.parse(JSON.stringify(content));
+ mockRecoveredQuery.mockReturnValue({
+ data:
+ source === 'live fallback'
+ ? undefined
+ : {
+ messageId: 'task-1:assistant',
+ status,
+ recovery: 'complete',
+ content,
+ throughSequence: 1,
+ targetThroughSequence: 1,
+ },
+ });
+ render(
+ <ChatSurfaceHarness>
+ <SubagentConversation
+ author={author}
+ parentAuthor={parentAuthor}
+ recovery={{
+ parentConversationId: 'parent',
+ threadId: 'child',
+ selectedTaskId: 'task-1',
+ ready: true,
+ }}
+ turns={[
+ {
+ ...turns[0],
+ contentRecoveryAvailable: source !== 'revoked cache',
+ activity: { ...turns[0].activity, status, content },
+ },
+ ]}
+ />
+ </ChatSurfaceHarness>,
+ );
+ const rendered = mockRenderedContent.mock.calls.findLast(([parts]) =>
+ parts.some(
+ (part: TMessageContentParts) => part?.type === 'tool_call' && part.tool_call.id === 'root',
+ ),
+ )?.[0];
+ expect(rendered).toBeDefined();
+ expect(JSON.stringify(rendered)).not.toContain('approval');
+ expect(rendered[0]).toEqual(content[0]);
+ expect(rendered[1]).toMatchObject({
+ agentId: 'worker',
+ tool_call: {
+ id: 'root',
+ stepId: 'root-step',
+ toolPreparationDurationMs: 12,
+ subagent_content: [
+ { agentId: 'nested-worker', tool_call: { id: 'nested', name: 'nested_tool' } },
+ ],
+ },
+ });
+ expect(content).toEqual(cached);
+ expect(mockPartScope.mock.calls.at(-1)?.[0]).toBeNull();
+ if (status === 'completed') {
+ expect(mockCopyMessage.mock.calls.at(-1)?.[0].content).toEqual(rendered);
+ }
+ },
+);
+
+it.each(
+ (['completed', 'failed', 'cancelled', 'interrupted'] as const).flatMap((status) =>
+ (['partial', 'complete'] as const).map((recovery) => ({ status, recovery })),
+ ),
+)(
+ 'retains the durable $status outcome beside nonempty $recovery history without replaying it',
+ ({ status, recovery }) => {
+ const content: TMessageContentParts[] = [
+ { type: ContentTypes.TEXT, text: 'Retained earlier work.' },
+ ];
+ mockRecoveredQuery.mockReturnValue({
+ data: {
+ messageId: 'task-1:assistant',
+ status,
+ recovery,
+ content,
+ throughSequence: 0,
+ targetThroughSequence: 0,
+ retryUntil: 0,
+ },
+ });
+ const props = {
+ author,
+ parentAuthor,
+ recovery: {
+ parentConversationId: 'parent',
+ threadId: 'child',
+ selectedTaskId: 'task-1',
+ ready: true,
+ },
+ turns: [
+ {
+ ...turns[0],
+ outcome: {
+ messageId: 'task-1:assistant',
+ parentMessageId: 'task-1:user',
+ role: 'assistant' as const,
+ text: 'Durable final outcome.',
+ ...(status === 'failed' ? { error: true } : {}),
+ },
+ activity: { ...turns[0].activity, status },
+ },
+ ],
+ };
+ const { rerender } = render(
+ <ChatSurfaceHarness>
+ <SubagentConversation {...props} />
+ </ChatSurfaceHarness>,
+ );
+ expect(screen.getByText('Retained earlier work.')).toBeInTheDocument();
+ expect(screen.getAllByText('Durable final outcome.')).toHaveLength(1);
+ expect(mockCopyMessage.mock.calls.at(-1)?.[0].content).toEqual([
+ ...content,
+ { type: ContentTypes.TEXT, text: 'Durable final outcome.', phase: 'final_answer' },
+ ]);
+ expect(content).toHaveLength(1);
+ mockRecoveredQuery.mockReturnValue({
+ data: {
+ messageId: 'task-1:assistant',
+ status,
+ recovery: 'complete',
+ content: [
+ ...content,
+ { type: ContentTypes.TEXT, text: 'Durable final outcome.', phase: 'final_answer' },
+ ],
+ throughSequence: 1,
+ targetThroughSequence: 1,
+ },
+ });
+ rerender(
+ <ChatSurfaceHarness>
+ <SubagentConversation {...props} />
+ </ChatSurfaceHarness>,
+ );
+ expect(screen.getAllByText('Durable final outcome.')).toHaveLength(1);
+ },
+);
+
+it('shows the durable outcome when partial capture and fallback both lack the final answer', () => {
+ mockRecoveredQuery.mockReturnValue({
+ data: {
+ messageId: 'task-1:assistant',
+ status: 'completed',
+ recovery: 'partial',
+ content: [],
+ throughSequence: -1,
+ targetThroughSequence: -1,
+ },
+ });
+ render(
+ <ChatSurfaceHarness>
+ <SubagentConversation
+ author={author}
+ parentAuthor={parentAuthor}
+ recovery={{
+ parentConversationId: 'parent',
+ threadId: 'child',
+ selectedTaskId: 'task-1',
+ ready: true,
+ }}
+ turns={[
+ {
+ ...turns[0],
+ activity: { ...turns[0].activity, items: [] },
+ outcome: {
+ messageId: 'task-1:assistant',
+ parentMessageId: 'task-1:user',
+ role: 'assistant',
+ text: 'Durable outcome survives.',
+ },
+ },
+ ]}
+ />
+ </ChatSurfaceHarness>,
+ );
+ expect(screen.getAllByText('Durable outcome survives.')).toHaveLength(1);
+});
+
+it.each(['partial', 'complete'] as const)(
+ 'does not append a truncated terminal projection already present in %s journal text',
+ (recovery) => {
+ const content: TMessageContentParts[] = [
+ {
+ type: ContentTypes.TEXT,
+ text: 'Durable final outcome with retained full detail.',
+ phase: 'final_answer',
+ },
+ ];
+ mockRecoveredQuery.mockReturnValue({
+ data: {
+ messageId: 'task-1:assistant',
+ status: 'completed',
+ recovery,
+ content,
+ throughSequence: 1,
+ targetThroughSequence: 1,
+ },
+ });
+ render(
+ <ChatSurfaceHarness>
+ <SubagentConversation
+ author={author}
+ parentAuthor={parentAuthor}
+ recovery={{
+ parentConversationId: 'parent',
+ threadId: 'child',
+ selectedTaskId: 'task-1',
+ ready: true,
+ }}
+ turns={[
+ {
+ ...turns[0],
+ outcome: {
+ messageId: 'task-1:assistant',
+ parentMessageId: 'task-1:user',
+ role: 'assistant',
+ text: 'Durable final outcome',
+ textTruncated: true,
+ },
+ },
+ ]}
+ />
+ </ChatSurfaceHarness>,
+ );
+ expect(screen.getAllByText('Durable final outcome with retained full detail.')).toHaveLength(1);
+ expect(screen.queryByText('Durable final outcome', { exact: true })).not.toBeInTheDocument();
+ expect(mockCopyMessage.mock.calls.at(-1)?.[0].content).toBe(content);
+ expect(content).toHaveLength(1);
+ },
+);
+
+it.each(['partial', 'complete'] as const)(
+ 'does not display a terminal outcome while a %s capture is still running',
+ (recovery) => {
+ mockRecoveredQuery.mockReturnValue({
+ data: {
+ messageId: 'task-1:assistant',
+ status: 'running',
+ recovery,
+ content: [{ type: ContentTypes.TEXT, text: 'Current work.' }],
+ throughSequence: 0,
+ targetThroughSequence: 0,
+ },
+ });
+ render(
+ <ChatSurfaceHarness>
+ <SubagentConversation
+ author={author}
+ parentAuthor={parentAuthor}
+ recovery={{
+ parentConversationId: 'parent',
+ threadId: 'child',
+ selectedTaskId: 'task-1',
+ ready: true,
+ }}
+ turns={[
+ {
+ ...turns[0],
+ outcome: {
+ messageId: 'task-1:assistant',
+ parentMessageId: 'task-1:user',
+ role: 'assistant',
+ text: 'Durable terminal outcome.',
+ },
+ },
+ ]}
+ />
+ </ChatSurfaceHarness>,
+ );
+ expect(screen.getByText('Current work.')).toBeInTheDocument();
+ expect(screen.queryByText('Durable terminal outcome.')).not.toBeInTheDocument();
+ },
+);
+
+it.each(['partial', 'complete'] as const)(
+ 'does not append the locked SDK multi-block result already present in %s recovered content',
+ (recovery) => {
+ const outcome = 'First paragraph.\nAn intrinsic line.\nSecond paragraph.';
+ const content: TMessageContentParts[] = [
+ { type: ContentTypes.TEXT, text: 'First paragraph.\nAn intrinsic line.Second paragraph.' },
+ ];
+ mockRecoveredQuery.mockReturnValue({
+ data: {
+ messageId: 'task-1:assistant',
+ status: 'completed',
+ recovery,
+ content,
+ throughSequence: 1,
+ targetThroughSequence: 1,
+ },
+ });
+ render(
+ <ChatSurfaceHarness>
+ <SubagentConversation
+ author={author}
+ parentAuthor={parentAuthor}
+ recovery={{
+ parentConversationId: 'parent',
+ threadId: 'child',
+ selectedTaskId: 'task-1',
+ ready: true,
+ }}
+ turns={[
+ {
+ ...turns[0],
+ outcome: {
+ messageId: 'task-1:assistant',
+ parentMessageId: 'task-1:user',
+ role: 'assistant',
+ text: outcome,
+ },
+ },
+ ]}
+ />
+ </ChatSurfaceHarness>,
+ );
+ expect(
+ screen.queryByText(outcome, { exact: true, normalizer: (text) => text }),
+ ).not.toBeInTheDocument();
+ expect(mockCopyMessage.mock.calls.at(-1)?.[0].content).toBe(content);
+ expect(content).toHaveLength(1);
+ },
+);
diff --git a/client/src/components/Chat/Subagents/SubagentConversation.tsx b/client/src/components/Chat/Subagents/SubagentConversation.tsx
index 8dd38dd08c..9b94e27f87 100644
--- a/client/src/components/Chat/Subagents/SubagentConversation.tsx
+++ b/client/src/components/Chat/Subagents/SubagentConversation.tsx
@@ -1,28 +1,59 @@
-import { useMemo, useState } from 'react';
-import { useAtomValue } from 'jotai';
+import { useContext, useMemo, useState } from 'react';
import { Radio } from 'lucide-react';
import { ContentTypes } from 'librechat-data-provider';
-import { Button, Collapsible, CollapsibleContent, CollapsibleTrigger } from '@librechat/client';
-import type { TMessageContentParts } from 'librechat-data-provider';
+import {
+ Alert,
+ Button,
+ Collapsible,
+ CollapsibleContent,
+ CollapsibleTrigger,
+} from '@librechat/client';
+import type { TMessage, TMessageContentParts } from 'librechat-data-provider';
import type { ReactNode } from 'react';
+import type { ToolContentQuery } from '~/components/Chat/Messages/Content/disclosure';
+import type { TaskContentScope } from '~/data-provider/Subagents/content';
+import type { MessagePartsHost } from '~/hooks/Chat/contract';
import type { ChildConversationTurn } from './adapters';
import type { TranslationKeys } from '~/hooks';
import type { TurnAuthor } from './author';
+import {
+ TaskContentScopeContext,
+ useSubagentTaskContentQuery,
+ useSubagentToolContentQuery,
+} from '~/data-provider/Subagents/content';
import SystemEventHeader, {
SystemEventIcon,
systemEventHeaderClasses,
} from '~/components/Chat/Messages/ui/SystemEvent';
-import { SubagentActivityContent, SubagentStatus } from './SubagentActivity';
+import { MessagePartsHostProvider, useMessagePartsHost } from '~/Providers/MessagePartsHostContext';
+import { SubagentActivityContent, SubagentStatus, getActivityContent } from './SubagentActivity';
+import ResumeAuthorHeader from '~/components/Chat/Messages/Content/Parts/ResumeAuthorHeader';
+import { useSearchResultsByTurn } from '~/hooks/Messages/useSearchResultsByTurn';
+import { ErrorSourceProvider } from '~/components/Messages/Content/Error/source';
+import MinimalHoverButtons from '~/components/Chat/Messages/MinimalHoverButtons';
import ContentParts from '~/components/Chat/Messages/Content/ContentParts';
import { isAbnormalTerminalStatus, isLiveSubagentStatus } from './status';
import { messageFooterClasses } from '~/components/Chat/Messages/styles';
import MessageRow from '~/components/Chat/Messages/ui/MessageRow';
import { ElapsedTimer } from '~/components/Chat/Messages/Elapsed';
-import { showThinkingAtom } from '~/store/showThinking';
+import { AuthorContext } from '~/Providers/AuthorContext';
+import { ChatContext } from '~/Providers/ChatContext';
+import { isEmptyContentPart } from '~/utils/messages';
+import { hasTerminalOutcome } from './outcome';
+import { standardContent } from './adapters';
import { useChatSurface } from './surface';
import { useLocalize } from '~/hooks';
import { cn } from '~/utils';
+type ConversationRecovery = Omit<TaskContentScope, 'taskId'> & {
+ selectedTaskId: string;
+ ready: boolean;
+};
+
+const RESUME_AUTHOR_HEADER = <ResumeAuthorHeader />;
+const ignoreMessage: ReturnType<MessagePartsHost['useMessagesAsk']> = () => undefined;
+const useNoMessagesAsk: MessagePartsHost['useMessagesAsk'] = () => ignoreMessage;
+
const TRIGGER_LABELS = {
parent_dispatch: 'com_ui_subagent_trigger_parent_dispatch',
parent_continuation: 'com_ui_subagent_trigger_parent_continuation',
@@ -69,7 +100,7 @@ function ExternalEventTrigger({
<span className="sr-only">{details.occurredAt}</span>
</Button>
</CollapsibleTrigger>
- <CollapsibleContent className="text-text-secondary pt-0.5 pb-1 text-xs">
+ <CollapsibleContent>
<dl className="grid grid-cols-[auto_1fr] gap-x-3 gap-y-1">
<dt>{localize('com_ui_subagent_event_type')}</dt>
<dd className="text-text-primary break-words">{details.eventType}</dd>
@@ -121,7 +152,7 @@ function TriggerMessage({
fullWidth: boolean;
parentAuthor: TurnAuthor;
}) {
- const showThinking = useAtomValue(showThinkingAtom);
+ const showThinking = useMessagePartsHost().useShowThinking();
const localize = useLocalize();
const label = localize(TRIGGER_LABELS[turn.trigger.kind]);
const content = useMemo<TMessageContentParts[]>(
@@ -136,6 +167,17 @@ function TriggerMessage({
],
[turn.trigger.summary],
);
+ const message = useMemo<TMessage>(
+ () => ({
+ messageId: `${turn.taskId}:trigger`,
+ parentMessageId: null,
+ conversationId: null,
+ isCreatedByUser: true,
+ text: '',
+ content,
+ }),
+ [content, turn.taskId],
+ );
if (turn.trigger.kind === 'external_event') {
return <ExternalEventTrigger turn={turn} fullWidth={fullWidth} />;
}
@@ -144,7 +186,7 @@ function TriggerMessage({
id={`${turn.taskId}:trigger`}
icon={parentAuthor.icon}
label={parentAuthor.name}
- footer={null}
+ footer={<MinimalHoverButtons message={message} />}
timestamp={turn.trigger.createdAt}
ariaLabel={label}
headerPrefix=""
@@ -184,7 +226,13 @@ function ChildMessage({
onCancelControl,
detailState,
onLoadDetails,
+ toolContentQuery,
+ notice,
+ outcomeContent,
}: {
+ notice?: ReactNode;
+ outcomeContent?: TMessageContentParts[];
+ toolContentQuery?: ToolContentQuery;
turn: ChildConversationTurn;
state: 'ready' | 'loading' | 'error';
author: TurnAuthor;
@@ -195,23 +243,36 @@ function ChildMessage({
onLoadDetails?: () => void;
}) {
const localize = useLocalize();
- const detailsLimited = turn.activity.activityTruncated === true;
+ const activity = turn.activity;
+ const content = useMemo(() => getActivityContent(activity), [activity]);
+ const message = useMemo<TMessage>(
+ () => ({
+ messageId: activity.messageId ?? `${turn.taskId}:assistant`,
+ parentMessageId: `${turn.taskId}:trigger`,
+ conversationId: conversationId ?? null,
+ isCreatedByUser: false,
+ text: '',
+ content: outcomeContent == null ? content : [...content, ...outcomeContent],
+ }),
+ [content, outcomeContent, conversationId, activity.messageId, turn.taskId],
+ );
+ const searchResults = useSearchResultsByTurn(activity.attachments);
+ const messageAuthor = useMemo(() => ({ icon: author.icon, label: author.name }), [author]);
+ const detailsLimited = activity.activityTruncated === true;
let limitedNotice: ReactNode;
if (detailsLimited && onLoadDetails != null && detailState !== 'unavailable') {
limitedNotice = (
<Button type="button" variant="ghost" size="sm" onClick={onLoadDetails}>
- {detailState === 'error'
- ? localize('com_ui_retry')
- : localize('com_ui_subagent_show_full_activity')}
+ {detailState === 'error' ? localize('com_ui_retry') : localize('com_ui_load_more')}
</Button>
);
} else {
limitedNotice = localize('com_ui_subagent_activity_details_unavailable');
}
let footerContent: ReactNode = null;
- if (isAbnormalTerminalStatus(turn.activity.status)) {
- footerContent = <SubagentStatus activity={turn.activity} />;
- } else if (isLiveSubagentStatus(turn.activity.status)) {
+ if (isAbnormalTerminalStatus(activity.status)) {
+ footerContent = <SubagentStatus activity={activity} />;
+ } else if (isLiveSubagentStatus(activity.status)) {
const triggeredAt = turn.trigger.createdAt ?? turn.trigger.externalEvent?.occurredAt;
const startedAt = triggeredAt == null ? NaN : Date.parse(triggeredAt);
footerContent = <ElapsedTimer start={Number.isFinite(startedAt) ? startedAt : undefined} />;
@@ -221,11 +282,16 @@ function ChildMessage({
* upward, and the reading has to be sized by the same `text-xs` its main
* chat counterpart inherits rather than by the panel's body size. */
const footer = (
- <div className={cn('mt-1 flex justify-start gap-3', messageFooterClasses)}>{footerContent}</div>
+ <div className={cn('mt-1 flex justify-start gap-3', messageFooterClasses)}>
+ {footerContent}
+ {!isLiveSubagentStatus(activity.status) && (
+ <MinimalHoverButtons message={message} searchResults={searchResults} />
+ )}
+ </div>
);
return (
<MessageRow
- id={`${turn.taskId}:assistant`}
+ id={message.messageId}
icon={author.icon}
label={author.name}
footer={footer}
@@ -234,15 +300,36 @@ function ChildMessage({
isCreatedByUser={false}
fullWidth={fullWidth}
>
- <SubagentActivityContent
- activity={turn.activity}
- activityId={`${turn.taskId}:assistant`}
- state={state}
- showPrompt={false}
- conversationId={conversationId}
- underHeaderIcon
- onCancelControl={onCancelControl}
- />
+ {notice}
+ <AuthorContext.Provider value={messageAuthor}>
+ <ErrorSourceProvider message={message}>
+ <SubagentActivityContent
+ activity={activity}
+ activityId={message.messageId}
+ content={content}
+ authorHeader={RESUME_AUTHOR_HEADER}
+ searchResults={searchResults}
+ toolContentQuery={toolContentQuery}
+ state={state}
+ showPrompt={false}
+ conversationId={conversationId}
+ underHeaderIcon
+ onCancelControl={onCancelControl}
+ />
+ {outcomeContent != null && (
+ <ContentParts
+ content={outcomeContent}
+ messageId={message.messageId}
+ conversationId={conversationId}
+ isCreatedByUser={false}
+ isSubmitting={false}
+ isLast
+ isLatestMessage={false}
+ showThinking={false}
+ />
+ )}
+ </ErrorSourceProvider>
+ </AuthorContext.Provider>
{detailsLimited && detailState !== 'loading' && (
<div className="text-text-secondary mt-2 text-xs">{limitedNotice}</div>
)}
@@ -255,6 +342,102 @@ function ChildMessage({
);
}
+function RecoveredChildMessage({
+ recovery,
+ ...props
+}: React.ComponentProps<typeof ChildMessage> & { recovery?: ConversationRecovery }) {
+ const localize = useLocalize();
+ const scope = useMemo<TaskContentScope>(
+ () => ({
+ parentConversationId: recovery?.parentConversationId ?? '',
+ threadId: recovery?.threadId ?? '',
+ taskId: props.turn.taskId,
+ }),
+ [recovery?.parentConversationId, recovery?.threadId, props.turn.taskId],
+ );
+ const recovered = useSubagentTaskContentQuery(scope, {
+ enabled:
+ recovery != null &&
+ props.turn.contentRecoveryAvailable !== false &&
+ (props.turn.taskId !== recovery.selectedTaskId ||
+ recovery.ready ||
+ !isLiveSubagentStatus(props.turn.activity.status)),
+ });
+ const turn = useMemo(() => {
+ const snapshot = recovered.data;
+ if (snapshot == null || props.turn.contentRecoveryAvailable === false) {
+ return {
+ ...props.turn,
+ activity: {
+ ...props.turn.activity,
+ content: standardContent(getActivityContent(props.turn.activity), 'hidden'),
+ },
+ };
+ }
+ const preserveActivity = !snapshot.content.some(
+ (part) => part != null && !isEmptyContentPart(part),
+ );
+ return {
+ ...props.turn,
+ activity: {
+ ...props.turn.activity,
+ messageId: snapshot.messageId,
+ content: standardContent(
+ preserveActivity ? getActivityContent(props.turn.activity) : snapshot.content,
+ 'hidden',
+ ),
+ status: snapshot.status,
+ activityTruncated: preserveActivity
+ ? props.turn.activity.activityTruncated
+ : snapshot.throughSequence < snapshot.targetThroughSequence ||
+ (!isLiveSubagentStatus(snapshot.status) && snapshot.recovery === 'partial'),
+ },
+ };
+ }, [recovered.data, props.turn]);
+ const outcomeContent = useMemo<TMessageContentParts[] | undefined>(() => {
+ const snapshot = recovered.data;
+ const outcome = props.turn.outcome;
+ if (
+ snapshot == null ||
+ props.turn.contentRecoveryAvailable === false ||
+ isLiveSubagentStatus(snapshot.status) ||
+ !outcome?.text ||
+ hasTerminalOutcome(getActivityContent(turn.activity), outcome, snapshot.status)
+ )
+ return undefined;
+ return [{ type: ContentTypes.TEXT, text: outcome.text, phase: 'final_answer' }];
+ }, [recovered.data, props.turn.contentRecoveryAvailable, props.turn.outcome, turn.activity]);
+ const notice =
+ props.turn.contentRecoveryAvailable !== false &&
+ recovered.isError &&
+ !recovered.isUnavailable ? (
+ <Alert variant="error" className="mb-2">
+ <div className="flex items-center gap-2">
+ <span>{localize('com_ui_conversation_load_error')}</span>
+ <Button variant="ghost" size="sm" onClick={() => void recovered.refetch()}>
+ {localize('com_ui_retry')}
+ </Button>
+ </div>
+ </Alert>
+ ) : undefined;
+ return (
+ <TaskContentScopeContext.Provider value={scope}>
+ <ChildMessage
+ {...props}
+ turn={turn}
+ state={
+ recovered.data == null || props.turn.contentRecoveryAvailable === false
+ ? props.state
+ : 'ready'
+ }
+ toolContentQuery={useSubagentToolContentQuery}
+ outcomeContent={outcomeContent}
+ notice={notice}
+ />
+ </TaskContentScopeContext.Provider>
+ );
+}
+
export default function SubagentConversation({
turns,
author,
@@ -265,8 +448,16 @@ export default function SubagentConversation({
onCancelControl,
detailStateByTask,
onLoadTurnDetails,
+ interactive = false,
+ toolContentQueries,
+ recovery,
}: {
+ recovery?: ConversationRecovery;
+ /** Task-authorized preview hooks, backed by the recovery API rather than child message reads. */
+ toolContentQueries?: ReadonlyMap<string, ToolContentQuery>;
turns: ChildConversationTurn[];
+ /** Only foreground children share their parent's live approval scope. */
+ interactive?: boolean;
/** The child agent: every assistant turn's header. */
author: TurnAuthor;
/** The agent that briefs the child: every parent-written turn's header. */
@@ -279,39 +470,49 @@ export default function SubagentConversation({
onLoadTurnDetails?: (taskId: string) => void;
}) {
const { maximizeChatSpace: fullWidth } = useChatSurface();
+ const parentChat = useContext(ChatContext);
+ const host = useMessagePartsHost();
+ const contentHost = useMemo(() => ({ ...host, useMessagesAsk: useNoMessagesAsk }), [host]);
+ const Message = recovery == null ? ChildMessage : RecoveredChildMessage;
return (
- <div className="flex flex-col gap-6 py-4" data-subagent-conversation>
- {turns.map((turn) => (
- <section
- key={turn.taskId}
- className="flex flex-col gap-4"
- data-subagent-thread-turn={turn.taskId}
- >
- <div className="px-4">
- <TriggerMessage turn={turn} fullWidth={fullWidth} parentAuthor={parentAuthor} />
- </div>
- <div className="px-4">
- <ChildMessage
- turn={turn}
- author={author}
- conversationId={conversationId}
- fullWidth={fullWidth}
- state={stateByTask?.get(turn.taskId) ?? 'ready'}
- onCancelControl={
- onCancelControl == null || turn.taskId !== controllableTaskId
- ? undefined
- : (controlId) => onCancelControl(turn.taskId, controlId)
- }
- detailState={detailStateByTask?.get(turn.taskId)}
- onLoadDetails={
- turn.activity.activityTruncated !== true || onLoadTurnDetails == null
- ? undefined
- : () => onLoadTurnDetails(turn.taskId)
- }
- />
- </div>
- </section>
- ))}
- </div>
+ <ChatContext.Provider value={interactive ? parentChat : null}>
+ <MessagePartsHostProvider host={contentHost}>
+ <div className="flex flex-col gap-6 py-4" data-subagent-conversation>
+ {turns.map((turn) => (
+ <section
+ key={turn.taskId}
+ className="flex flex-col gap-4"
+ data-subagent-thread-turn={turn.taskId}
+ >
+ <div className="px-4">
+ <TriggerMessage turn={turn} fullWidth={fullWidth} parentAuthor={parentAuthor} />
+ </div>
+ <div className="px-4">
+ <Message
+ turn={turn}
+ recovery={recovery}
+ author={author}
+ conversationId={conversationId}
+ fullWidth={fullWidth}
+ state={stateByTask?.get(turn.taskId) ?? 'ready'}
+ onCancelControl={
+ onCancelControl == null || turn.taskId !== controllableTaskId
+ ? undefined
+ : (controlId) => onCancelControl(turn.taskId, controlId)
+ }
+ toolContentQuery={toolContentQueries?.get(turn.taskId)}
+ detailState={detailStateByTask?.get(turn.taskId)}
+ onLoadDetails={
+ turn.activity.activityTruncated !== true || onLoadTurnDetails == null
+ ? undefined
+ : () => onLoadTurnDetails(turn.taskId)
+ }
+ />
+ </div>
+ </section>
+ ))}
+ </div>
+ </MessagePartsHostProvider>
+ </ChatContext.Provider>
);
}
diff --git a/client/src/components/Chat/Subagents/SubagentThreadPanel.test.tsx b/client/src/components/Chat/Subagents/SubagentThreadPanel.test.tsx
index ac52400615..e7d9e8af4e 100644
--- a/client/src/components/Chat/Subagents/SubagentThreadPanel.test.tsx
+++ b/client/src/components/Chat/Subagents/SubagentThreadPanel.test.tsx
@@ -251,6 +251,7 @@ jest.mock('./SubagentConversation', () => ({
parentAuthor: { name: string };
turns: Array<{
taskId: string;
+ outcome?: { text: string };
trigger: { summary: string };
activity: { items: Array<{ text?: string }>; activityTruncated?: boolean };
}>;
@@ -266,7 +267,7 @@ jest.mock('./SubagentConversation', () => ({
>
{author.icon}
{turns.map((turn) => (
- <div key={turn.taskId} data-testid="conversation-turn">
+ <div key={turn.taskId} data-testid="conversation-turn" data-outcome={turn.outcome?.text}>
{turn.trigger.summary}
{turn.activity.items.map((item, index) => (
<span key={index}>{item.text}</span>
@@ -3465,6 +3466,69 @@ describe('SubagentThreadPanel', () => {
},
);
+ it.each(['latest window', 'empty window', 'selected trigger only'] as const)(
+ 'carries the exact durable answer into a selected task outside the %s',
+ (window) => {
+ const outcome = {
+ messageId: 'task-old:assistant',
+ parentMessageId: 'task-old:user',
+ role: 'assistant' as const,
+ text: 'Durable historical answer.',
+ };
+ const turn = {
+ taskId: window === 'selected trigger only' ? 'task-old' : 'task-new',
+ trigger: { kind: 'parent_continuation' as const, summary: 'Window trigger' },
+ status: 'completed' as const,
+ activity: [],
+ activityTruncated: false,
+ messages: [],
+ };
+ mockUseSubagentThreadQuery.mockReturnValue({
+ data: {
+ ...completedView,
+ messages: [
+ outcome,
+ { ...outcome, messageId: 'another-task:assistant', text: 'Unrelated answer' },
+ ],
+ turns: window === 'empty window' ? [] : [turn],
+ },
+ isLoading: false,
+ isError: false,
+ isReadinessPending: false,
+ });
+ const selected: ActiveSubagentPanel = {
+ ...selection,
+ durable: { threadId: 'child-thread', taskId: 'task-old' },
+ };
+ render(
+ <Root>
+ <SubagentThreadPanel selection={selected} />
+ </Root>,
+ );
+ const outcomes = screen
+ .getAllByTestId('conversation-turn')
+ .map((row) => row.getAttribute('data-outcome'))
+ .filter(Boolean);
+ expect(outcomes).toEqual(['Durable historical answer.']);
+ },
+ );
+
+ it('does not attribute a retained previous-task response to the newly selected task', () => {
+ mockUseSubagentThreadQuery.mockReturnValue({
+ data: { ...completedView, turns: [] },
+ isPreviousData: true,
+ isLoading: false,
+ isError: false,
+ isReadinessPending: false,
+ });
+ render(
+ <Root>
+ <SubagentThreadPanel selection={selection} />
+ </Root>,
+ );
+ expect(screen.getByTestId('conversation-turn')).not.toHaveAttribute('data-outcome');
+ });
+
it('loads an exact older turn projection only after the local disclosure is opened', async () => {
const truncatedView: SubagentThreadView = {
...completedView,
@@ -3607,7 +3671,7 @@ describe('SubagentThreadPanel', () => {
</Root>,
);
- fireEvent.click(screen.getByRole('button', { name: 'com_ui_subagent_load_earlier_activity' }));
+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_load_more' }));
await waitFor(() => expect(screen.getAllByTestId('conversation-turn')).toHaveLength(2));
expect(mockGetSubagentThread).toHaveBeenCalledWith(
'parent-conversation',
@@ -3649,7 +3713,7 @@ describe('SubagentThreadPanel', () => {
<SubagentThreadPanel selection={selection} />
</Root>,
);
- fireEvent.click(screen.getByRole('button', { name: 'com_ui_subagent_load_earlier_activity' }));
+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_load_more' }));
mockUseSubagentThreadQuery.mockReturnValue({
data: {
@@ -3705,9 +3769,7 @@ describe('SubagentThreadPanel', () => {
expect(screen.queryByText('Displaced result')).not.toBeInTheDocument();
await waitFor(() =>
- expect(
- screen.getByRole('button', { name: 'com_ui_subagent_load_earlier_activity' }),
- ).toBeEnabled(),
+ expect(screen.getByRole('button', { name: 'com_ui_load_more' })).toBeEnabled(),
);
});
@@ -3739,11 +3801,9 @@ describe('SubagentThreadPanel', () => {
</Root>,
);
- fireEvent.click(screen.getByRole('button', { name: 'com_ui_subagent_load_earlier_activity' }));
+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_load_more' }));
await waitFor(() => expect(screen.getByRole('button', { name: 'com_ui_retry' })).toBeEnabled());
- expect(
- screen.queryByRole('button', { name: 'com_ui_subagent_load_earlier_activity' }),
- ).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'com_ui_load_more' })).not.toBeInTheDocument();
});
it('shows a compact inaccessible-history boundary when no recovery cursor exists', () => {
@@ -3776,9 +3836,7 @@ describe('SubagentThreadPanel', () => {
expect(
screen.getByRole('status', { name: 'com_ui_subagent_thread_history_truncated' }),
).toHaveTextContent('•••');
- expect(
- screen.queryByRole('button', { name: 'com_ui_subagent_load_earlier_activity' }),
- ).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'com_ui_load_more' })).not.toBeInTheDocument();
});
it('preserves an unrecoverable boundary while loading later cursor pages', async () => {
@@ -3816,7 +3874,7 @@ describe('SubagentThreadPanel', () => {
</Root>,
);
- fireEvent.click(screen.getByRole('button', { name: 'com_ui_subagent_load_earlier_activity' }));
+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_load_more' }));
await waitFor(() =>
expect(mockGetSubagentThread).toHaveBeenLastCalledWith(
'parent-conversation',
@@ -3825,7 +3883,7 @@ describe('SubagentThreadPanel', () => {
'older:assistant',
),
);
- fireEvent.click(screen.getByRole('button', { name: 'com_ui_subagent_load_earlier_activity' }));
+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_load_more' }));
await waitFor(() =>
expect(mockGetSubagentThread).toHaveBeenLastCalledWith(
'parent-conversation',
@@ -4029,7 +4087,7 @@ describe('SubagentThreadPanel', () => {
<SubagentThreadPanel selection={selectionA} />
</Root>,
);
- fireEvent.click(screen.getByRole('button', { name: 'com_ui_subagent_load_earlier_activity' }));
+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_load_more' }));
rerender(
<Root>
<SubagentThreadPanel selection={selectionB} />
@@ -4041,11 +4099,9 @@ describe('SubagentThreadPanel', () => {
</Root>,
);
await waitFor(() =>
- expect(
- screen.getByRole('button', { name: 'com_ui_subagent_load_earlier_activity' }),
- ).toBeEnabled(),
+ expect(screen.getByRole('button', { name: 'com_ui_load_more' })).toBeEnabled(),
);
- fireEvent.click(screen.getByRole('button', { name: 'com_ui_subagent_load_earlier_activity' }));
+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_load_more' }));
await waitFor(() => expect(screen.getByText('Fresh older result')).toBeInTheDocument());
await act(async () => {
@@ -4120,7 +4176,7 @@ describe('SubagentThreadPanel', () => {
<SubagentThreadPanel selection={selection} />
</Root>,
);
- fireEvent.click(screen.getByRole('button', { name: 'com_ui_subagent_load_earlier_activity' }));
+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_load_more' }));
await waitFor(() => expect(screen.getAllByTestId('conversation-turn')).toHaveLength(3));
latestView = {
@@ -4141,7 +4197,7 @@ describe('SubagentThreadPanel', () => {
expect(screen.getByText('New result')).toBeInTheDocument();
expect(screen.getByText('Newest result')).toBeInTheDocument();
- fireEvent.click(screen.getByRole('button', { name: 'com_ui_subagent_load_earlier_activity' }));
+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_load_more' }));
await waitFor(() =>
expect(mockGetSubagentThread).toHaveBeenLastCalledWith(
'parent-conversation',
@@ -4164,7 +4220,7 @@ describe('SubagentThreadPanel', () => {
);
await waitFor(() => expect(screen.getAllByTestId('conversation-turn')).toHaveLength(7));
- fireEvent.click(screen.getByRole('button', { name: 'com_ui_subagent_load_earlier_activity' }));
+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_load_more' }));
await waitFor(() =>
expect(mockGetSubagentThread).toHaveBeenLastCalledWith(
'parent-conversation',
@@ -4212,9 +4268,7 @@ describe('SubagentThreadPanel', () => {
expect.stringContaining('Final live result'),
expect.stringContaining('Ultimate live result'),
]);
- expect(
- screen.queryByRole('button', { name: 'com_ui_subagent_load_earlier_activity' }),
- ).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'com_ui_load_more' })).not.toBeInTheDocument();
});
it('does not accumulate displaced latest-window turns before history is requested', async () => {
diff --git a/client/src/components/Chat/Subagents/SubagentThreadPanel.tsx b/client/src/components/Chat/Subagents/SubagentThreadPanel.tsx
index 414b73aa99..f8f7152b51 100644
--- a/client/src/components/Chat/Subagents/SubagentThreadPanel.tsx
+++ b/client/src/components/Chat/Subagents/SubagentThreadPanel.tsx
@@ -284,7 +284,7 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
taskView?.status === 'interrupted' ||
taskView?.status === 'cancelled');
const priorTerminalRef = useRef(false);
- useSubagentActivityStream(selection, !durableTerminal || eventTaskRunning);
+ const contentStream = useSubagentActivityStream(selection, !durableTerminal || eventTaskRunning);
useEffect(() => {
if (selection.event == null) return;
@@ -874,6 +874,7 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
prompt,
progress,
persistedContent,
+ attachments: selection.attachments,
isDetached: selection.durable != null,
legacyOutput,
// A detached parent tool step closes as soon as dispatch succeeds;
@@ -904,13 +905,15 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
const durable = adaptDurableThreadActivity(taskView, selection.durable.taskId);
const useLiveItems =
(durable.status === 'running' || durable.status === 'dispatched') &&
- liveActivity.items.length > 0;
+ (liveActivity.content?.length ?? liveActivity.items.length) > 0;
const mergedItems =
!useLiveItems && durable.items.length > 0 ? durable.items : liveActivity.items;
const merged = {
...durable,
prompt: durable.prompt ?? liveActivity.prompt,
items: mergedItems,
+ attachments: durable.attachments ?? liveActivity.attachments,
+ content: !useLiveItems && durable.items.length > 0 ? durable.content : liveActivity.content,
};
if (
transientControl == null ||
@@ -1027,6 +1030,13 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
};
}, [historyRebaseActive, latestConversationTurns, latestHistoryGeneration, threadId, threadView]);
const retainedTurnsValid = retainedTurnsGenerationRef.current === selectionGenerationRef.current;
+ const selectedOutcome = useMemo(
+ () =>
+ taskView?.messages.find(
+ (message) => message.messageId === `${taskId}:assistant` && message.role === 'assistant',
+ ),
+ [taskView, taskId],
+ );
const conversationTurns = useMemo(() => {
const durableTurns = retainedTurnsValid
? mergeChildConversationTurns(
@@ -1041,7 +1051,10 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
const selectedTurnIndex = durableTurns.findIndex((turn) => turn.taskId === taskId);
if (selectedTurnIndex >= 0) {
return durableTurns.map((turn, index) => {
- const selected = index === selectedTurnIndex ? { ...turn, activity } : turn;
+ const selected =
+ index === selectedTurnIndex
+ ? { ...turn, activity, outcome: selectedOutcome ?? turn.outcome }
+ : turn;
const override = turnDetailOverrides.get(turn.taskId);
return override == null ? selected : { ...selected, activity: override };
});
@@ -1057,6 +1070,7 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
)?.createdAt;
const synthesizedTurn = {
taskId: taskId || `${selection.parentMessageId}:${selection.toolCallId}`,
+ ...(selectedOutcome == null ? {} : { outcome: selectedOutcome }),
trigger: {
kind:
selection.event == null
@@ -1086,6 +1100,7 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
return [
{
taskId: taskId || `${selection.parentMessageId}:${selection.toolCallId}`,
+ ...(selectedOutcome == null ? {} : { outcome: selectedOutcome }),
trigger: {
kind:
selection.event == null ? ('parent_dispatch' as const) : ('external_event' as const),
@@ -1106,6 +1121,7 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
retainedTurnsValid,
threadId,
selection,
+ selectedOutcome,
taskId,
turnDetailOverrides,
]);
@@ -1375,11 +1391,15 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
panelState = storedPart.isError ? 'error' : 'loading';
} else if (
selection.durable != null &&
- liveActivity.items.length === 0 &&
+ (liveActivity.content?.length ?? liveActivity.items.length) === 0 &&
(isLoading || isReadinessPending)
) {
panelState = 'loading';
- } else if (selection.durable != null && liveActivity.items.length === 0 && isError) {
+ } else if (
+ selection.durable != null &&
+ (liveActivity.content?.length ?? liveActivity.items.length) === 0 &&
+ isError
+ ) {
panelState = 'error';
}
const renderEventTask = (task: ParentSubagentTaskSummary) => {
@@ -1492,7 +1512,7 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
>
{historyState === 'loading'
? localize('com_ui_loading')
- : localize('com_ui_subagent_load_earlier_activity')}
+ : localize('com_ui_load_more')}
</Button>
</div>
)}
@@ -1513,6 +1533,17 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
author={childAuthor}
parentAuthor={isSelfSpawn && selection.event == null ? childAuthor : parentAuthor}
conversationId={threadId || selection.parentConversationId}
+ interactive={selection.host === 'conversation' && selection.durable == null}
+ recovery={
+ selection.durable == null
+ ? undefined
+ : {
+ parentConversationId: selection.parentConversationId,
+ threadId,
+ selectedTaskId: taskId,
+ ready: contentStream?.isReady === true,
+ }
+ }
stateByTask={conversationStateByTask}
controllableTaskId={
controlAvailable && !controlPending ? selection.durable?.taskId : undefined
diff --git a/client/src/components/Chat/Subagents/adapters.test.ts b/client/src/components/Chat/Subagents/adapters.test.ts
index 99478285f7..de8ddf9e9a 100644
--- a/client/src/components/Chat/Subagents/adapters.test.ts
+++ b/client/src/components/Chat/Subagents/adapters.test.ts
@@ -3,10 +3,12 @@ import type {
SubagentThreadView,
SubagentUpdateEvent,
TMessageContentParts,
+ FullToolCall,
} from 'librechat-data-provider';
import type { ChildConversationTurn } from './adapters';
import {
adaptDurableThreadActivity,
+ adaptDurableThreadConversation,
adaptLivePersistedActivity,
MAX_RETAINED_MOVING_WINDOW_TURNS,
mergeChildConversationTurns,
@@ -688,3 +690,220 @@ describe('child activity adapters', () => {
);
});
});
+
+describe('standard content compatibility', () => {
+ const content = [
+ { type: ContentTypes.TEXT, text: 'Answer', phase: 'final_answer', agentId: 'child' },
+ {
+ type: ContentTypes.THINK,
+ think: 'Reasoning',
+ reasoning_label: 'Checked constraints',
+ reasoning_label_revision: 3,
+ },
+ {
+ type: ContentTypes.TOOL_CALL,
+ agentId: 'child',
+ tool_call: {
+ id: 'tool',
+ name: 'bash',
+ args: '{}',
+ output: 'ok',
+ progress: 1,
+ stepId: 'step',
+ outputTruncated: true,
+ previewRevision: 'r2',
+ subagent_content: [{ type: ContentTypes.TEXT, text: 'Nested answer' }],
+ },
+ },
+ { type: ContentTypes.ERROR, error: 'Failure', agentId: 'child' },
+ ] as TMessageContentParts[];
+
+ it('preserves standard parts, including non-projected parts and nested metadata', () => {
+ const result = adaptLivePersistedActivity({
+ title: 'Child',
+ progress: null,
+ persistedContent: content,
+ initialProgress: 1,
+ isSubmitting: false,
+ });
+ expect(result.content).toBe(content);
+ expect(result.items).toHaveLength(3);
+ });
+
+ it('retains old text-only records as a compatibility fallback', () => {
+ const result = adaptLivePersistedActivity({
+ title: 'Child',
+ progress: null,
+ legacyOutput: 'Stored answer',
+ initialProgress: 1,
+ isSubmitting: false,
+ });
+ expect(result.content).toBeUndefined();
+ expect(result.items).toEqual([{ type: 'writing', text: 'Stored answer' }]);
+ });
+
+ it('removes public approval payloads without dropping other standard metadata', () => {
+ const nested: FullToolCall = {
+ id: 'nested',
+ name: 'bash',
+ args: '{}',
+ output: '',
+ approval: { actionId: 'private-nested-action', allowed_decisions: ['approve', 'reject'] },
+ };
+ const tool: FullToolCall = {
+ id: 'tool',
+ name: 'bash',
+ args: '{}',
+ output: '',
+ stepId: 'step',
+ approval: { actionId: 'private-action', allowed_decisions: ['approve', 'reject'] },
+ subagent_content: [{ type: ContentTypes.TOOL_CALL, tool_call: nested }],
+ };
+ const withApproval: TMessageContentParts[] = [
+ {
+ type: ContentTypes.TOOL_CALL,
+ agentId: 'child',
+ tool_call: tool,
+ },
+ ];
+ const result = adaptLivePersistedActivity({
+ title: 'Child',
+ progress: null,
+ persistedContent: withApproval,
+ initialProgress: 1,
+ isSubmitting: false,
+ approvalVisibility: 'hidden',
+ });
+ expect(JSON.stringify(result.content)).not.toContain('private-action');
+ expect(JSON.stringify(result.content)).not.toContain('private-nested-action');
+ expect(result.content?.[0]).toMatchObject({ agentId: 'child', tool_call: { stepId: 'step' } });
+ expect(JSON.stringify(withApproval)).toContain('private-action');
+ });
+});
+
+it('keeps sparse public content positions while removing nested approval data', () => {
+ const sparse = new Array<TMessageContentParts>(2);
+ sparse[1] = { type: ContentTypes.TEXT, text: 'Retained text' };
+ const content: TMessageContentParts[] = JSON.parse(JSON.stringify(sparse));
+ const activity = adaptLivePersistedActivity({
+ title: 'Child',
+ progress: null,
+ persistedContent: content,
+ initialProgress: 1,
+ isSubmitting: false,
+ approvalVisibility: 'hidden',
+ });
+ expect(activity.content).toBe(content);
+ expect(activity.content?.[0]).toBeNull();
+ expect(activity.content?.[1]).toMatchObject({ text: 'Retained text' });
+});
+
+it.each([false, true, undefined])('preserves split-page recovery enrollment %s', (available) => {
+ const base: ChildConversationTurn = {
+ taskId: 'split',
+ trigger: { kind: 'parent_dispatch', summary: '' },
+ activity: { title: 'Child', status: 'running', items: [] },
+ };
+ const enrolled = { ...base, contentRecoveryAvailable: available };
+ for (const pages of [
+ [[enrolled], [base]],
+ [[base], [enrolled]],
+ ]) {
+ expect(mergeChildConversationTurns(...pages)[0].contentRecoveryAvailable).toBe(available);
+ }
+});
+
+it.each([
+ [true, false],
+ [false, true],
+ [true, true],
+ [false, false],
+ [undefined, false],
+ [undefined, true],
+ [true, undefined],
+ [false, undefined],
+ [undefined, undefined],
+])(
+ 'prefers explicit refreshed recovery capability over retained %s -> %s',
+ (retained, refreshed) => {
+ const base: ChildConversationTurn = {
+ taskId: 'task',
+ trigger: { kind: 'parent_dispatch', summary: 'Investigate' },
+ activity: { title: 'Child', status: 'completed', items: [] },
+ };
+ const history = { ...base, contentRecoveryAvailable: retained };
+ const latest = { ...base, contentRecoveryAvailable: refreshed };
+ expect(
+ mergeChildConversationTurns([history], [latest], [base])[0].contentRecoveryAvailable,
+ ).toBe(refreshed ?? retained);
+ expect(history.contentRecoveryAvailable).toBe(retained);
+ expect(latest.contentRecoveryAvailable).toBe(refreshed);
+ },
+);
+
+it('keeps foreground approval payloads and clean content references intact', () => {
+ const content: TMessageContentParts[] = [
+ {
+ type: ContentTypes.TOOL_CALL,
+ tool_call: {
+ id: 'foreground',
+ name: 'protected_tool',
+ args: '{}',
+ output: '',
+ progress: 0,
+ approval: { actionId: 'foreground-approval', allowed_decisions: ['approve', 'reject'] },
+ },
+ },
+ ];
+ const activity = adaptLivePersistedActivity({
+ title: 'Foreground',
+ progress: null,
+ persistedContent: content,
+ initialProgress: 0,
+ isSubmitting: true,
+ approvalVisibility: 'visible',
+ });
+ expect(activity.content).toBe(content);
+ expect(JSON.stringify(activity.content)).toContain('foreground-approval');
+});
+
+it('keeps the durable terminal outcome independently of the activity projection across pages', () => {
+ const outcome = {
+ messageId: 'task:assistant',
+ parentMessageId: 'task:user',
+ role: 'assistant' as const,
+ text: 'Final result',
+ };
+ const base: ChildConversationTurn = {
+ taskId: 'task',
+ trigger: { kind: 'parent_dispatch', summary: '' },
+ activity: { title: 'Worker', status: 'completed', items: [] },
+ };
+ const view: SubagentThreadView = {
+ threadId: 'thread',
+ parentConversationId: 'parent',
+ parentMessageId: 'message',
+ parentToolCallId: 'call',
+ subagentType: 'worker',
+ subagentKind: 'agent',
+ status: 'completed',
+ activity: [],
+ activityTruncated: false,
+ messages: [],
+ historyTruncated: false,
+ title: 'Worker',
+ turns: [
+ {
+ taskId: 'task',
+ trigger: base.trigger,
+ status: 'completed',
+ activity: [],
+ activityTruncated: false,
+ messages: [outcome],
+ },
+ ],
+ };
+ const [turn] = adaptDurableThreadConversation(view);
+ expect(turn.outcome).toBe(outcome);
+ expect(mergeChildConversationTurns([turn], [base])[0].outcome).toBe(outcome);
+});
diff --git a/client/src/components/Chat/Subagents/adapters.ts b/client/src/components/Chat/Subagents/adapters.ts
index b5218373f2..9c6353cf06 100644
--- a/client/src/components/Chat/Subagents/adapters.ts
+++ b/client/src/components/Chat/Subagents/adapters.ts
@@ -7,7 +7,10 @@ import type {
SubagentThreadTurn,
SubagentThreadStatus,
SubagentThreadView,
+ SubagentThreadMessage,
TMessageContentParts,
+ TAttachment,
+ FullToolCall,
} from 'librechat-data-provider';
import type { SubagentProgress } from './state';
import { REDACTED_REASONING_MARKER } from './state';
@@ -60,6 +63,10 @@ export type ChildActivity = {
prompt?: string;
status: SubagentThreadStatus;
items: ChildActivityItem[];
+ /** Standard parts bypass the legacy activity projection. */
+ content?: TMessageContentParts[];
+ messageId?: string;
+ attachments?: TAttachment[];
controls?: Array<
Omit<SubagentControlReceipt, 'status'> & {
status: SubagentControlReceipt['status'] | 'submitted';
@@ -71,6 +78,8 @@ export type ChildActivity = {
export type ChildConversationTurn = {
taskId: string;
+ outcome?: SubagentThreadMessage;
+ contentRecoveryAvailable?: boolean;
trigger: SubagentThreadTurn['trigger'];
activity: ChildActivity;
};
@@ -95,6 +104,7 @@ const contentPartsToActivity = (
approvalVisibility: 'visible' | 'hidden',
): ChildActivityItem[] =>
parts.flatMap((part, index): ChildActivityItem[] => {
+ if (part == null) return [];
if (part.type === ContentTypes.TEXT) {
const textPart = part as {
text: string;
@@ -288,12 +298,68 @@ const liveStatus = ({
return isSubmitting ? 'running' : 'cancelled';
};
+/** Keep standard metadata and sharing; public nested transcripts must not expose approvals. */
+export const standardContent = (
+ content: TMessageContentParts[],
+ approvalVisibility: 'visible' | 'hidden',
+): TMessageContentParts[] => {
+ type Frame = {
+ source: TMessageContentParts[];
+ result: TMessageContentParts[];
+ index: number;
+ };
+ const stack: Frame[] = [{ source: content, result: content, index: 0 }];
+ const replace = (frame: Frame, index: number, part: TMessageContentParts) => {
+ if (frame.result === frame.source) frame.result = frame.source.slice();
+ frame.result[index] = part;
+ };
+ while (stack.length > 0) {
+ const frame = stack[stack.length - 1];
+ if (frame.index === frame.source.length) {
+ stack.pop();
+ const parent = stack[stack.length - 1];
+ if (parent == null) return frame.result;
+ if (frame.result !== frame.source) {
+ const index = parent.index - 1;
+ const part = parent.result[index];
+ if (part.type === ContentTypes.TOOL_CALL) {
+ const toolCall: FullToolCall = {
+ ...(part.tool_call as FullToolCall),
+ subagent_content: frame.result,
+ };
+ replace(parent, index, { ...part, tool_call: toolCall });
+ }
+ }
+ continue;
+ }
+ const index = frame.index++;
+ const part = frame.source[index];
+ if (part == null) continue;
+ if (part.type === ContentTypes.THINK && part.think === REDACTED_REASONING_MARKER) {
+ replace(frame, index, { ...part, think: '', reasoning_unavailable: true });
+ continue;
+ }
+ if (part.type !== ContentTypes.TOOL_CALL || approvalVisibility !== 'hidden') continue;
+ const tool = part.tool_call as FullToolCall;
+ if (tool == null) continue;
+ if (tool.approval != null) {
+ const { approval: _approval, ...visibleTool } = tool;
+ replace(frame, index, { ...part, tool_call: visibleTool } as TMessageContentParts);
+ }
+ if (tool.subagent_content != null) {
+ stack.push({ source: tool.subagent_content, result: tool.subagent_content, index: 0 });
+ }
+ }
+ return content;
+};
+
/** Adapts live SSE state, parent persistence, and legacy output at one seam. */
export function adaptLivePersistedActivity(input: {
title: string;
prompt?: string;
progress: SubagentProgress | null;
persistedContent?: TMessageContentParts[];
+ attachments?: TAttachment[];
legacyOutput?: string | null;
initialProgress: number;
isSubmitting: boolean;
@@ -307,10 +373,14 @@ export function adaptLivePersistedActivity(input: {
const persistedItems = contentPartsToActivity(persisted, approvalVisibility);
const liveItems = contentPartsToActivity(live, approvalVisibility);
let items = persistedItems.length > 0 ? persistedItems : liveItems;
+ let content = persisted.length > 0 ? persisted : live;
if (input.isDetached === true && input.progress?.coverage === 'suffix') {
items = mergePersistedAndLiveActivity(persistedItems, liveItems);
- } else if (input.isDetached === true && liveItems.length > 0) {
+ // A suffix without sequence-aligned standard recovery still needs the legacy bridge.
+ content = [];
+ } else if (input.isDetached === true && live.length > 0) {
items = liveItems;
+ content = live;
}
if (items.length === 0 && input.legacyOutput != null && input.legacyOutput !== '') {
items.push({ type: 'writing', text: input.legacyOutput });
@@ -320,7 +390,12 @@ export function adaptLivePersistedActivity(input: {
...(input.prompt == null ? {} : { prompt: input.prompt }),
status: liveStatus(input),
items,
+ ...(content.length === 0 ? {} : { content: standardContent(content, approvalVisibility) }),
controls: [],
+ ...(input.progress?.coverage === 'suffix' || (input.progress?.droppedCount ?? 0) > 0
+ ? { activityTruncated: true }
+ : {}),
+ ...(input.attachments == null ? {} : { attachments: input.attachments }),
};
}
@@ -369,6 +444,10 @@ const adaptDurableTurn = (turn: SubagentThreadTurn, title: string): ChildConvers
}
return {
taskId: turn.taskId,
+ ...(response == null ? {} : { outcome: response }),
+ ...(turn.contentRecoveryAvailable == null
+ ? {}
+ : { contentRecoveryAvailable: turn.contentRecoveryAvailable }),
trigger: turn.trigger,
activity: {
title,
@@ -420,8 +499,14 @@ export function mergeChildConversationTurns(
const trigger =
triggerDetailScore(turn) > triggerDetailScore(older) ? turn.trigger : older.trigger;
const controls = mergeTurnControls(older.activity.controls, turn.activity.controls);
+ const contentRecoveryAvailable =
+ turn.contentRecoveryAvailable ?? older.contentRecoveryAvailable;
merged[existingIndex] = {
taskId: turn.taskId,
+ ...(turn.outcome == null && older.outcome == null
+ ? {}
+ : { outcome: turn.outcome ?? older.outcome }),
+ ...(contentRecoveryAvailable == null ? {} : { contentRecoveryAvailable }),
trigger,
activity: {
...older.activity,
diff --git a/client/src/components/Chat/Subagents/outcome.test.ts b/client/src/components/Chat/Subagents/outcome.test.ts
new file mode 100644
index 0000000000..572fef6837
--- /dev/null
+++ b/client/src/components/Chat/Subagents/outcome.test.ts
@@ -0,0 +1,138 @@
+import { File } from 'node:buffer';
+import { ContentTypes } from 'librechat-data-provider';
+import { ReadableStream, TransformStream, WritableStream } from 'node:stream/web';
+import type { SubagentThreadMessage, TMessageContentParts } from 'librechat-data-provider';
+import { hasTerminalOutcome } from './outcome';
+
+const outcome = (text: string, textTruncated = false): SubagentThreadMessage => ({
+ messageId: 'task:assistant',
+ parentMessageId: 'task:user',
+ role: 'assistant',
+ text,
+ textTruncated,
+});
+const textPart = (text: string): TMessageContentParts => ({ type: ContentTypes.TEXT, text });
+
+it.each(
+ [
+ [
+ { type: 'text', text: 'Alpha' },
+ { type: 'text', text: 'Beta' },
+ ],
+ [
+ { type: 'text', text: 'Alpha\nInside' },
+ { type: 'text', text: 'Beta' },
+ ],
+ [
+ { type: 'text_delta', index: 0, text: 'Al' },
+ { type: 'text_delta', index: 0, text: 'pha' },
+ { type: 'text_delta', index: 1, text: 'Beta' },
+ ],
+ [
+ { type: 'text', text: '😀 Alpha' },
+ { type: 'text', text: '' },
+ { type: 'text', text: '𐐷 Beta' },
+ ],
+ ].map((blocks) => ({ blocks })),
+)('recognizes the locked SDK aggregate of serialized blocks %j', ({ blocks }) => {
+ Object.assign(globalThis, { File, ReadableStream, TransformStream, WritableStream });
+ const { createContentAggregator, filterSubagentResult, GraphEvents } =
+ jest.requireActual<typeof import('@librechat/agents')>('@librechat/agents');
+ const { AIMessage } = jest.requireActual<typeof import('@librechat/agents/langchain/messages')>(
+ '@librechat/agents/langchain/messages',
+ );
+ const aggregator = createContentAggregator();
+ aggregator.aggregateContent({
+ event: GraphEvents.ON_RUN_STEP,
+ data: {
+ id: 'answer',
+ runId: 'provider',
+ index: 0,
+ type: 'message_creation',
+ usage: null,
+ stepDetails: { type: 'message_creation', message_creation: { message_id: 'answer' } },
+ },
+ });
+ aggregator.aggregateContent({
+ event: GraphEvents.ON_MESSAGE_DELTA,
+ data: { id: 'answer', delta: { content: blocks } },
+ });
+ const result = filterSubagentResult([new AIMessage({ content: blocks })]);
+ const content = aggregator.contentParts as TMessageContentParts[];
+ expect(hasTerminalOutcome(content, outcome(result), 'completed')).toBe(true);
+ expect(hasTerminalOutcome(content, outcome(result.slice(0, 4), true), 'completed')).toBe(true);
+ expect(content).toHaveLength(1);
+});
+
+it.each(['failed', 'cancelled', 'interrupted'] as const)(
+ 'does not normalize a genuinely separate %s explanation',
+ (status) => {
+ expect(hasTerminalOutcome([textPart('AlphaBeta')], outcome('Alpha\nBeta'), status)).toBe(false);
+ expect(hasTerminalOutcome([textPart('AlphaBeta')], outcome('Alpha\nBeta', true), status)).toBe(
+ false,
+ );
+ expect(hasTerminalOutcome([textPart('Alpha\nBeta')], outcome('Alpha\nBeta'), status)).toBe(
+ true,
+ );
+ },
+);
+
+it('keeps an error-marked outcome exact even if status reports completed', () => {
+ expect(
+ hasTerminalOutcome(
+ [textPart('AlphaBeta')],
+ { ...outcome('Alpha\nBeta'), error: true },
+ 'completed',
+ ),
+ ).toBe(false);
+});
+
+it.each([
+ ['Alpha Beta', 'AlphaBeta'],
+ ['Alpha\tBeta', 'AlphaBeta'],
+ ['AlphaBeta', 'Alpha Beta'],
+ ['Alpha\nBeta', 'AlphaBeta'],
+ ['AlphaBeta', 'Alpha\nDifferent'],
+ ['Anything', '\n\n'],
+])('does not equate different output %j with %j', (rendered, durable) => {
+ expect(hasTerminalOutcome([textPart(rendered)], outcome(durable), 'completed')).toBe(false);
+});
+
+it('recognizes adjacent same-author text parts without joining unrelated content', () => {
+ const first = textPart('Alpha');
+ const second = textPart('Beta');
+ const expected = outcome('Alpha\nBeta');
+ expect(hasTerminalOutcome([first, second], expected, 'completed')).toBe(true);
+ expect(hasTerminalOutcome([first, { ...second, agentId: 'other' }], expected, 'completed')).toBe(
+ false,
+ );
+ expect(hasTerminalOutcome([first, { ...second, groupId: 2 }], expected, 'completed')).toBe(false);
+ expect(
+ hasTerminalOutcome(
+ [
+ { type: ContentTypes.TEXT, text: 'Alpha', phase: 'commentary' },
+ { type: ContentTypes.TEXT, text: 'Beta', phase: 'final_answer' },
+ ],
+ expected,
+ 'completed',
+ ),
+ ).toBe(false);
+ expect(
+ hasTerminalOutcome([first, { type: ContentTypes.THINK, think: 'Beta' }], expected, 'completed'),
+ ).toBe(false);
+ expect(
+ hasTerminalOutcome(
+ JSON.parse(JSON.stringify([first, undefined, second])),
+ expected,
+ 'completed',
+ ),
+ ).toBe(false);
+});
+
+it('matches a truncated multi-block prefix but does not mutate recovered content', () => {
+ const content = [textPart('Alpha'), textPart('Beta and full detail')];
+ const before = JSON.stringify(content);
+ expect(hasTerminalOutcome(content, outcome('Alpha\nBeta', true), 'completed')).toBe(true);
+ expect(hasTerminalOutcome(content, outcome('Alpha\nBeta'), 'completed')).toBe(false);
+ expect(JSON.stringify(content)).toBe(before);
+});
diff --git a/client/src/components/Chat/Subagents/outcome.ts b/client/src/components/Chat/Subagents/outcome.ts
new file mode 100644
index 0000000000..94bc915c0f
--- /dev/null
+++ b/client/src/components/Chat/Subagents/outcome.ts
@@ -0,0 +1,58 @@
+import { ContentTypes } from 'librechat-data-provider';
+import type {
+ SubagentThreadMessage,
+ SubagentThreadStatus,
+ TMessageContentParts,
+} from 'librechat-data-provider';
+
+type TextPart = Extract<TMessageContentParts, { type: ContentTypes.TEXT }>;
+
+export function hasTerminalOutcome(
+ content: TMessageContentParts[],
+ outcome: SubagentThreadMessage,
+ status: SubagentThreadStatus,
+): boolean {
+ // The SDK result serializer inserts LF between blocks; its stream aggregator does not.
+ const separators = status === 'completed' && outcome.error !== true;
+ const matches = (parts: string[]): boolean => {
+ let index = 0;
+ let matched = false;
+ for (const part of parts) {
+ for (let offset = 0; offset < part.length; offset++) {
+ const character = part[offset];
+ while (separators && outcome.text[index] === '\n' && character !== '\n') index++;
+ if (index === outcome.text.length) return outcome.textTruncated === true && matched;
+ if (outcome.text[index] !== character) return false;
+ index++;
+ matched = true;
+ }
+ }
+ while (separators && outcome.text[index] === '\n') index++;
+ return matched && index === outcome.text.length;
+ };
+ let group: string[] = [];
+ let previous: TextPart | undefined;
+ for (const part of content) {
+ if (part?.type !== ContentTypes.TEXT) {
+ if (group.length > 1 && matches(group)) return true;
+ group = [];
+ previous = undefined;
+ continue;
+ }
+ const text = typeof part.text === 'string' ? part.text : part.text?.value;
+ if (text == null) continue;
+ if (matches([text])) return true;
+ if (
+ previous != null &&
+ (previous.agentId !== part.agentId ||
+ previous.groupId !== part.groupId ||
+ previous.phase !== part.phase)
+ ) {
+ if (group.length > 1 && matches(group)) return true;
+ group = [];
+ }
+ group.push(text);
+ previous = part;
+ }
+ return group.length > 1 && matches(group);
+}
diff --git a/client/src/components/Chat/Subagents/recovery.test.ts b/client/src/components/Chat/Subagents/recovery.test.ts
new file mode 100644
index 0000000000..c19716c6b2
--- /dev/null
+++ b/client/src/components/Chat/Subagents/recovery.test.ts
@@ -0,0 +1,469 @@
+import { ContentTypes, StepEvents, StepTypes } from 'librechat-data-provider';
+import type {
+ SubagentTaskContentSnapshot,
+ SubagentTaskContentSuffix,
+ SubagentContentEvent,
+} from 'librechat-data-provider';
+import { reduceRecoveredContent, recoverTaskContent, recoveredToolPart } from './recovery';
+
+const snapshot = (
+ overrides: Partial<SubagentTaskContentSnapshot> = {},
+): SubagentTaskContentSnapshot => ({
+ mode: 'snapshot',
+ taskId: 'task',
+ threadId: 'thread',
+ parentConversationId: 'parent',
+ messageId: 'task:assistant',
+ parentMessageId: 'task:user',
+ sender: 'worker',
+ revision: 1,
+ throughSequence: 0,
+ targetThroughSequence: 0,
+ status: 'running',
+ recovery: 'partial',
+ content: [{ type: ContentTypes.TEXT, text: 'Opening. ', phase: 'commentary', agentId: 'child' }],
+ runSteps: [
+ {
+ id: 'text-step',
+ runId: 'provider-run',
+ index: 0,
+ type: StepTypes.MESSAGE_CREATION,
+ stepDetails: {
+ type: StepTypes.MESSAGE_CREATION,
+ message_creation: { message_id: 'provider' },
+ },
+ usage: null,
+ },
+ ],
+ ...overrides,
+});
+const suffix = (
+ events: SubagentContentEvent[],
+ overrides: Partial<SubagentTaskContentSuffix> = {},
+): SubagentTaskContentSuffix => {
+ const { content: _content, runSteps: _steps, ...identity } = snapshot();
+ return {
+ ...identity,
+ mode: 'suffix',
+ afterSequence: 0,
+ revision: 2,
+ throughSequence: 1,
+ targetThroughSequence: 1,
+ events,
+ ...overrides,
+ };
+};
+const text = (sequence: number, value: string): SubagentContentEvent => ({
+ sequence,
+ frame: {
+ event: StepEvents.ON_MESSAGE_DELTA,
+ data: {
+ id: 'text-step',
+ delta: {
+ content: [{ type: ContentTypes.TEXT, text: value }],
+ },
+ },
+ },
+});
+
+it('replays only committed suffix frames through the normal reducer without mutating its snapshot', () => {
+ const first = reduceRecoveredContent(null, snapshot())!;
+ const next = reduceRecoveredContent(first, suffix([text(1, 'Later.')]))!;
+ expect(next.snapshot.content[0]).toMatchObject({
+ text: 'Opening. Later.',
+ agentId: 'child',
+ phase: 'commentary',
+ });
+ expect(first.snapshot.content[0]).toMatchObject({ text: 'Opening. ' });
+ expect(first.stream.messages.get('task:assistant')?.content?.[0]).toMatchObject({
+ text: 'Opening. ',
+ });
+ expect(reduceRecoveredContent(next, suffix([text(1, 'Later.')]))).toBe(next);
+});
+
+it('drains opaque cursor pages at one target, including pages from the same revision', async () => {
+ const load = jest
+ .fn()
+ .mockResolvedValueOnce(snapshot({ nextCursor: 'opaque cursor', targetThroughSequence: 2 }))
+ .mockResolvedValueOnce(
+ suffix([text(1, 'One. ')], { revision: 1, targetThroughSequence: 2, nextCursor: 'second' }),
+ )
+ .mockResolvedValueOnce(
+ suffix([text(2, 'Two.')], {
+ revision: 1,
+ afterSequence: 1,
+ throughSequence: 2,
+ targetThroughSequence: 2,
+ }),
+ );
+ const result = await recoverTaskContent(null, load);
+ expect(load.mock.calls).toEqual([
+ [undefined],
+ [undefined, 'opaque cursor'],
+ [undefined, 'second'],
+ ]);
+ expect(result.snapshot.content[0]).toMatchObject({ text: 'Opening. One. Two.' });
+ expect(result.snapshot.throughSequence).toBe(2);
+});
+
+it('rejects non-advancing pages instead of hiding a missing prefix', async () => {
+ const load = jest
+ .fn()
+ .mockResolvedValueOnce(snapshot({ nextCursor: 'cursor', targetThroughSequence: 2 }))
+ .mockResolvedValueOnce(
+ suffix([], { throughSequence: 0, targetThroughSequence: 2, nextCursor: 'cursor' }),
+ );
+ await expect(recoverTaskContent(null, load)).rejects.toThrow('subagent_content_cursor_mismatch');
+});
+
+it('keeps more than 112 calls and over-24KiB arguments and outputs intact', async () => {
+ const large = 'payload'.repeat(5_000);
+ const content = Array.from({ length: 113 }, (_, index) => ({
+ type: ContentTypes.TOOL_CALL as const,
+ agentId: 'child',
+ streamedIndex: index,
+ tool_call: {
+ id: `call-${index}`,
+ name: 'bash',
+ args: large,
+ output: large,
+ progress: 1,
+ stepId: `step-${index}`,
+ toolExecutionDurationMs: index + 1,
+ },
+ }));
+ const result = await recoverTaskContent(null, jest.fn().mockResolvedValue(snapshot({ content })));
+ expect(result.snapshot.content).toBe(content);
+ expect(result.snapshot.content).toHaveLength(113);
+ expect(
+ recoveredToolPart(result.snapshot, { partIndex: 112, toolCallId: 'call-112' })?.tool_call
+ .output,
+ ).toBe(large);
+});
+
+it('requires a snapshot for a mismatched cursor or task identity', () => {
+ const first = reduceRecoveredContent(null, snapshot())!;
+ expect(
+ reduceRecoveredContent(first, suffix([text(2, 'Wrong.')], { afterSequence: 1 })),
+ ).toBeNull();
+ expect(
+ reduceRecoveredContent(first, suffix([text(1, 'Wrong.')], { taskId: 'other-task' })),
+ ).toBeNull();
+});
+
+it('will not hydrate a repeated provider id from an ambiguous moved occurrence', () => {
+ const part = {
+ type: ContentTypes.TOOL_CALL as const,
+ tool_call: { id: 'reused', name: 'bash', args: '{}' },
+ };
+ const source = snapshot({ content: [part, { ...part }] });
+ expect(recoveredToolPart(source, { partIndex: 9, toolCallId: 'reused' })).toBeNull();
+ expect(recoveredToolPart(source, { partIndex: 1, toolCallId: 'reused' })?.partIndex).toBe(1);
+});
+
+it('catches up beyond a pinned target when completion arrives during pagination', async () => {
+ const load = jest
+ .fn()
+ .mockResolvedValueOnce(snapshot({ targetThroughSequence: 1, nextCursor: 'pinned' }))
+ .mockResolvedValueOnce(
+ suffix([text(1, 'Earlier. ')], {
+ revision: 1,
+ throughSequence: 1,
+ targetThroughSequence: 1,
+ status: 'completed',
+ recovery: 'partial',
+ }),
+ )
+ .mockResolvedValueOnce(
+ suffix([text(2, 'Final.')], {
+ afterSequence: 1,
+ revision: 2,
+ throughSequence: 2,
+ targetThroughSequence: 2,
+ status: 'completed',
+ recovery: 'complete',
+ }),
+ );
+ const recovered = await recoverTaskContent(null, load);
+ expect(load.mock.calls).toEqual([[undefined], [undefined, 'pinned'], [1]]);
+ expect(recovered.snapshot).toMatchObject({
+ throughSequence: 2,
+ status: 'completed',
+ recovery: 'complete',
+ });
+ expect(recovered.snapshot.content[0]).toMatchObject({ text: 'Opening. Earlier. Final.' });
+});
+
+it('keeps a genuinely partial terminal capture honest without an endless catch-up loop', async () => {
+ const load = jest
+ .fn()
+ .mockResolvedValueOnce(snapshot({ status: 'failed', recovery: 'partial' }))
+ .mockResolvedValueOnce(
+ suffix([], {
+ revision: 1,
+ throughSequence: 0,
+ targetThroughSequence: 0,
+ status: 'failed',
+ recovery: 'partial',
+ }),
+ );
+ const recovered = await recoverTaskContent(null, load);
+ expect(load.mock.calls).toEqual([[undefined], [0]]);
+ expect(recovered.snapshot).toMatchObject({ throughSequence: 0, recovery: 'partial' });
+});
+
+it('keeps preparation timing from a snapshot when later arguments and completion arrive', () => {
+ const initial = snapshot({
+ content: [
+ {
+ type: ContentTypes.TOOL_CALL,
+ tool_call: {
+ id: 'call',
+ name: 'lookup',
+ args: '{',
+ stepId: 'tool',
+ toolPreparationStartedAt: 100,
+ },
+ },
+ ],
+ runSteps: [
+ {
+ id: 'tool',
+ index: 0,
+ type: StepTypes.TOOL_CALLS,
+ stepDetails: {
+ type: StepTypes.TOOL_CALLS,
+ tool_calls: [{ id: 'call', name: 'lookup', args: '{' }],
+ },
+ usage: null,
+ },
+ ],
+ });
+ const seeded = reduceRecoveredContent(null, initial)!;
+ const continued = reduceRecoveredContent(
+ seeded,
+ suffix(
+ [
+ {
+ sequence: 1,
+ frame: {
+ event: StepEvents.ON_RUN_STEP_DELTA,
+ data: {
+ id: 'tool',
+ observed_at: 150,
+ delta: {
+ type: StepTypes.TOOL_CALLS,
+ tool_calls: [{ id: 'call', index: 0, name: 'lookup', args: '}' }],
+ },
+ },
+ },
+ },
+ {
+ sequence: 2,
+ frame: {
+ event: StepEvents.ON_TOOL_CALLS_DISPATCHED,
+ data: {
+ dispatched_at: 1000,
+ toolCalls: [{ id: 'call', stepId: 'tool', name: 'lookup' }],
+ },
+ },
+ },
+ {
+ sequence: 3,
+ frame: {
+ event: StepEvents.ON_RUN_STEP_COMPLETED,
+ data: {
+ result: {
+ id: 'tool',
+ index: 0,
+ completed_at: 1340,
+ tool_call: { id: 'call', name: 'lookup', args: '{}', output: 'Done' },
+ },
+ },
+ },
+ },
+ {
+ sequence: 4,
+ frame: {
+ event: StepEvents.ON_RUN_STEP_CLOSED,
+ data: {
+ id: 'tool',
+ index: 0,
+ type: StepTypes.TOOL_CALLS,
+ status: 'completed',
+ created_at: 100,
+ closed_at: 1340,
+ },
+ },
+ },
+ ],
+ { throughSequence: 4, targetThroughSequence: 4 },
+ ),
+ )!;
+ expect(continued.snapshot.content[0]).toMatchObject({
+ tool_call: {
+ toolPreparationStartedAt: 100,
+ toolPreparationDurationMs: 900,
+ toolDispatchedAt: 1000,
+ toolExecutionDurationMs: 340,
+ },
+ });
+ expect(seeded.snapshot.content[0]).toMatchObject({
+ tool_call: { toolPreparationStartedAt: 100 },
+ });
+});
+
+it('carries an idless first fragment forward when its provider call identity arrives', () => {
+ const initial = snapshot({
+ content: [
+ {
+ type: ContentTypes.TOOL_CALL,
+ tool_call: {
+ id: '',
+ name: 'lookup',
+ args: '{',
+ toolPreparationStartedAt: 100,
+ },
+ },
+ ],
+ runSteps: [
+ {
+ id: 'tool',
+ index: 0,
+ type: StepTypes.TOOL_CALLS,
+ stepDetails: { type: StepTypes.TOOL_CALLS, tool_calls: [{ name: 'lookup', args: '{' }] },
+ usage: null,
+ },
+ ],
+ });
+ const seeded = reduceRecoveredContent(null, initial)!;
+ const continued = reduceRecoveredContent(
+ seeded,
+ suffix([
+ {
+ sequence: 1,
+ frame: {
+ event: StepEvents.ON_RUN_STEP_DELTA,
+ data: {
+ id: 'tool',
+ observed_at: 150,
+ delta: {
+ type: StepTypes.TOOL_CALLS,
+ tool_calls: [{ id: 'assigned', index: 0, name: 'lookup', args: '}' }],
+ },
+ },
+ },
+ },
+ ]),
+ )!;
+ expect(continued.snapshot.content[0]).toMatchObject({
+ tool_call: {
+ id: 'assigned',
+ toolPreparationStartedAt: 100,
+ },
+ });
+});
+
+it('seeds an already dispatched timestamp before a later committed argument delta', () => {
+ const initial = snapshot({
+ content: [
+ {
+ type: ContentTypes.TOOL_CALL,
+ tool_call: {
+ id: 'call',
+ name: 'lookup',
+ args: '{',
+ toolPreparationStartedAt: 100,
+ toolDispatchedAt: 1000,
+ },
+ },
+ ],
+ runSteps: [
+ {
+ id: 'tool',
+ index: 0,
+ type: StepTypes.TOOL_CALLS,
+ stepDetails: {
+ type: StepTypes.TOOL_CALLS,
+ tool_calls: [{ id: 'call', name: 'lookup', args: '{' }],
+ },
+ usage: null,
+ },
+ ],
+ });
+ const continued = reduceRecoveredContent(
+ reduceRecoveredContent(null, initial),
+ suffix([
+ {
+ sequence: 1,
+ frame: {
+ event: StepEvents.ON_RUN_STEP_DELTA,
+ data: {
+ id: 'tool',
+ observed_at: 150,
+ delta: {
+ type: StepTypes.TOOL_CALLS,
+ tool_calls: [{ id: 'call', index: 0, name: 'lookup', args: '}' }],
+ },
+ },
+ },
+ },
+ ]),
+ )!;
+ expect(continued.snapshot.content[0]).toMatchObject({
+ tool_call: {
+ toolPreparationStartedAt: 100,
+ toolDispatchedAt: 1000,
+ },
+ });
+});
+
+it('keeps the published stream immutable across many pages and a later page failure', async () => {
+ const before = reduceRecoveredContent(null, snapshot())!;
+ const page = (sequence: number, nextCursor?: string) =>
+ suffix([text(sequence, `${sequence}.`)], {
+ afterSequence: sequence - 1,
+ throughSequence: sequence,
+ targetThroughSequence: 3,
+ nextCursor,
+ });
+ const load = jest
+ .fn()
+ .mockResolvedValueOnce(page(1, 'two'))
+ .mockResolvedValueOnce(page(2, 'three'))
+ .mockResolvedValueOnce(page(3));
+ const result = await recoverTaskContent(before, load);
+ expect(result.snapshot.content[0]).toMatchObject({ text: 'Opening. 1.2.3.' });
+ expect(result.snapshot.runSteps).toEqual(Array.from(result.stream.steps.values()));
+ expect(before.snapshot.content[0]).toMatchObject({ text: 'Opening. ' });
+ expect(before.stream.messages.get('task:assistant')?.content).toBe(before.snapshot.content);
+ expect(result.stream.steps).not.toBe(before.stream.steps);
+ const fail = jest
+ .fn()
+ .mockResolvedValueOnce(page(1, 'two'))
+ .mockRejectedValueOnce(new Error('offline'));
+ await expect(recoverTaskContent(before, fail)).rejects.toThrow('offline');
+ expect(before.snapshot.content[0]).toMatchObject({ text: 'Opening. ' });
+});
+
+it('stops before another cursor page after cancellation without mutating the prior reader', async () => {
+ const controller = new AbortController();
+ const before = reduceRecoveredContent(null, snapshot())!;
+ const load = jest.fn().mockImplementation(async () => {
+ controller.abort();
+ return suffix([text(1, 'Not published.')], { targetThroughSequence: 2, nextCursor: 'two' });
+ });
+ await expect(recoverTaskContent(before, load, controller.signal)).rejects.toThrow(
+ 'subagent_content_cancelled',
+ );
+ expect(load).toHaveBeenCalledTimes(1);
+ expect(before.snapshot.content[0]).toMatchObject({ text: 'Opening. ' });
+});
+
+it('rejects parent identity changes as well as child identity changes', () => {
+ const before = reduceRecoveredContent(null, snapshot())!;
+ expect(
+ reduceRecoveredContent(before, suffix([], { parentConversationId: 'other-parent' })),
+ ).toBeNull();
+ expect(reduceRecoveredContent(before, suffix([], { parentMessageId: 'other-user' }))).toBeNull();
+});
diff --git a/client/src/components/Chat/Subagents/recovery.ts b/client/src/components/Chat/Subagents/recovery.ts
new file mode 100644
index 0000000000..46c4b049b1
--- /dev/null
+++ b/client/src/components/Chat/Subagents/recovery.ts
@@ -0,0 +1,295 @@
+import { createStreamState, reduceStep } from '@librechat/chat';
+import { ContentTypes, EModelEndpoint, StepEvents, StepTypes } from 'librechat-data-provider';
+import type {
+ EventSubmission,
+ SubagentTaskContentResponse,
+ SubagentTaskContentSnapshot,
+ TMessage,
+ FullToolCall,
+ PartMetadata,
+} from 'librechat-data-provider';
+import type { StreamState, StepContext } from '@librechat/chat';
+import { isLiveSubagentStatus } from './status';
+
+export type RecoveredContent = {
+ snapshot: SubagentTaskContentSnapshot;
+ stream: StreamState;
+};
+
+export const recoveredMessage = (snapshot: SubagentTaskContentSnapshot): TMessage => ({
+ messageId: snapshot.messageId,
+ parentMessageId: snapshot.parentMessageId,
+ conversationId: snapshot.threadId,
+ sender: snapshot.sender,
+ isCreatedByUser: false,
+ text: '',
+ content: snapshot.content,
+});
+
+/** Null requests a fresh snapshot. Only committed task frames enter the normal pure reducer. */
+export function reduceRecoveredContent(
+ previous: RecoveredContent | null,
+ response: SubagentTaskContentResponse,
+): RecoveredContent | null {
+ return applyRecoveredContent(previous, response);
+}
+
+function applyRecoveredContent(
+ previous: RecoveredContent | null,
+ response: SubagentTaskContentResponse,
+ owned = false,
+ materializeSteps = true,
+): RecoveredContent | null {
+ if (
+ previous != null &&
+ (previous.snapshot.parentConversationId !== response.parentConversationId ||
+ previous.snapshot.parentMessageId !== response.parentMessageId ||
+ previous.snapshot.taskId !== response.taskId ||
+ previous.snapshot.threadId !== response.threadId ||
+ previous.snapshot.messageId !== response.messageId)
+ ) {
+ return null;
+ }
+ if (
+ previous != null &&
+ (response.revision < previous.snapshot.revision ||
+ response.throughSequence < previous.snapshot.throughSequence)
+ ) {
+ return previous;
+ }
+ if (response.mode === 'snapshot') {
+ const stream = createStreamState();
+ stream.messages.set(response.messageId, recoveredMessage(response));
+ for (const step of response.runSteps) {
+ const part = response.content[step.index];
+ stream.steps.set(step.id, {
+ ...step,
+ runId: response.messageId,
+ agentId: step.agentId ?? part?.agentId,
+ groupId: step.groupId ?? part?.groupId,
+ });
+ if (step.stepDetails.type === StepTypes.TOOL_CALLS) {
+ const tool =
+ part?.type === ContentTypes.TOOL_CALL
+ ? (part.tool_call as FullToolCall & PartMetadata)
+ : undefined;
+ const preparedAt = tool?.toolPreparationStartedAt;
+ if (
+ !tool?.id &&
+ (step.stepDetails.tool_calls?.length ?? 0) <= 1 &&
+ typeof preparedAt === 'number' &&
+ Number.isFinite(preparedAt) &&
+ preparedAt >= 0
+ ) {
+ stream.firstFragmentByStep.set(step.id, preparedAt);
+ }
+ for (const call of step.stepDetails.tool_calls ?? []) {
+ if (!call.id) continue;
+ stream.toolCallIds.set(step.id, call.id);
+ if (part?.type !== ContentTypes.TOOL_CALL || part.tool_call?.id !== call.id) continue;
+ const tool = part.tool_call as FullToolCall & PartMetadata;
+ const timingKey = `${step.id}\u0000${call.id}`;
+ const preparedAt = tool.toolPreparationStartedAt;
+ const dispatchedAt = tool.toolDispatchedAt;
+ if (typeof preparedAt === 'number' && Number.isFinite(preparedAt) && preparedAt >= 0) {
+ stream.firstFragmentByCall.set(timingKey, preparedAt);
+ }
+ if (
+ typeof dispatchedAt === 'number' &&
+ Number.isFinite(dispatchedAt) &&
+ dispatchedAt >= 0
+ ) {
+ stream.dispatchedByCall.set(timingKey, dispatchedAt);
+ }
+ }
+ }
+ }
+ return { snapshot: response, stream };
+ }
+ if (
+ previous != null &&
+ response.throughSequence <= previous.snapshot.throughSequence &&
+ response.revision <= previous.snapshot.revision &&
+ response.status === previous.snapshot.status &&
+ response.recovery === previous.snapshot.recovery &&
+ response.retryUntil === previous.snapshot.retryUntil &&
+ response.targetThroughSequence === previous.snapshot.targetThroughSequence
+ )
+ return previous;
+ if (previous == null || response.afterSequence !== previous.snapshot.throughSequence) return null;
+ if (
+ response.revision === previous.snapshot.revision &&
+ response.throughSequence === previous.snapshot.throughSequence &&
+ response.status === previous.snapshot.status &&
+ response.recovery === previous.snapshot.recovery &&
+ response.retryUntil === previous.snapshot.retryUntil &&
+ response.targetThroughSequence === previous.snapshot.targetThroughSequence
+ ) {
+ return previous;
+ }
+ const source = previous.stream;
+ const stream: StreamState = owned
+ ? source
+ : {
+ ...source,
+ messages: new Map(source.messages),
+ steps: new Map(source.steps),
+ toolCallIds: new Map(source.toolCallIds),
+ firstFragmentByCall: new Map(source.firstFragmentByCall),
+ firstFragmentByStep: new Map(source.firstFragmentByStep),
+ dispatchedByCall: new Map(source.dispatchedByCall),
+ completedByCall: new Map(source.completedByCall),
+ pendingDeltas: new Map(
+ [...source.pendingDeltas].map(([key, events]) => [key, events.slice()]),
+ ),
+ };
+ const initialResponse = recoveredMessage(previous.snapshot);
+ const userMessage: TMessage = {
+ messageId: response.parentMessageId,
+ parentMessageId: null,
+ conversationId: response.threadId,
+ isCreatedByUser: true,
+ text: '',
+ };
+ let messages = [userMessage, initialResponse];
+ const submission: EventSubmission = {
+ userMessage,
+ initialResponse,
+ messages,
+ conversation: { conversationId: response.threadId },
+ endpointOption: { endpoint: EModelEndpoint.agents },
+ isTemporary: false,
+ };
+ const context: StepContext = {
+ submission,
+ getMessages: () => messages,
+ setMessages: (next) => {
+ messages = next;
+ },
+ };
+ let through = response.afterSequence;
+ for (const { sequence, frame } of response.events) {
+ if (sequence <= response.afterSequence) continue;
+ if (sequence <= through || sequence > response.throughSequence) return null;
+ through = sequence;
+ if (frame.event === StepEvents.ON_RUN_STEP) {
+ reduceStep(stream, { ...frame, data: { ...frame.data, runId: response.messageId } }, context);
+ } else if (frame.event === StepEvents.ON_RUN_STEP_COMPLETED) {
+ if (frame.data.result != null) {
+ reduceStep(stream, { event: frame.event, data: { result: frame.data.result } }, context);
+ }
+ } else {
+ reduceStep(stream, frame, context);
+ }
+ }
+ const message = stream.messages.get(response.messageId);
+ if (message == null) return null;
+ const { events: _events, afterSequence: _afterSequence, mode: _mode, ...identity } = response;
+ return {
+ stream,
+ snapshot: {
+ ...identity,
+ mode: 'snapshot',
+ content: message.content ?? [],
+ runSteps: materializeSteps ? Array.from(stream.steps.values()) : previous.snapshot.runSteps,
+ },
+ };
+}
+
+export const recoveredToolPart = (
+ snapshot: SubagentTaskContentSnapshot,
+ params: { partIndex: number; toolCallId?: string; stepId?: string; agentId?: string },
+) => {
+ const matches = (index: number) => {
+ const part = snapshot.content[index];
+ if (part?.type !== ContentTypes.TOOL_CALL) return false;
+ const call = part.tool_call as FullToolCall;
+ return (
+ (params.toolCallId == null || call.id === params.toolCallId) &&
+ (params.stepId == null || call.stepId === params.stepId) &&
+ (params.agentId == null || part.agentId === params.agentId)
+ );
+ };
+ let index = matches(params.partIndex) ? params.partIndex : -1;
+ if (index < 0 && params.toolCallId != null) {
+ for (let candidate = 0; candidate < snapshot.content.length; candidate++) {
+ if (!matches(candidate)) continue;
+ if (index >= 0) return null;
+ index = candidate;
+ }
+ }
+ const part = snapshot.content[index];
+ return part?.type === ContentTypes.TOOL_CALL
+ ? { partIndex: index, tool_call: part.tool_call as FullToolCall }
+ : null;
+};
+
+export type TaskContentLoader = (
+ afterSequence?: number,
+ cursor?: string,
+) => Promise<SubagentTaskContentResponse>;
+
+/** Drain the sampled target before publishing it or asking for a newer suffix. */
+export async function recoverTaskContent(
+ previous: RecoveredContent | null,
+ load: TaskContentLoader,
+ signal?: AbortSignal,
+): Promise<RecoveredContent> {
+ const read: TaskContentLoader = async (afterSequence, cursor) => {
+ if (signal?.aborted) throw new Error('subagent_content_cancelled');
+ const response = cursor == null ? await load(afterSequence) : await load(afterSequence, cursor);
+ if (signal?.aborted) throw new Error('subagent_content_cancelled');
+ return response;
+ };
+ // Only this unpublished catch-up may reuse its mutable maps.
+ const apply = (before: RecoveredContent | null, response: SubagentTaskContentResponse) =>
+ applyRecoveredContent(
+ before,
+ response,
+ before != null && before.stream !== previous?.stream,
+ false,
+ );
+ let response = await read(previous?.snapshot.throughSequence);
+ let next = apply(previous, response);
+ if (next == null) {
+ response = await read();
+ next = apply(null, response);
+ }
+ let caughtUpTerminal = false;
+ const seen = new Set<string>();
+ while (true) {
+ const target = response.targetThroughSequence;
+ while (response.nextCursor != null) {
+ const cursor = response.nextCursor;
+ if (seen.has(cursor)) throw new Error('subagent_content_cursor_repeated');
+ seen.add(cursor);
+ const through = response.throughSequence;
+ response = await read(undefined, cursor);
+ if (response.targetThroughSequence !== target || response.throughSequence <= through) {
+ throw new Error('subagent_content_cursor_mismatch');
+ }
+ next = apply(next, response);
+ if (next == null) throw new Error('subagent_content_snapshot_required');
+ }
+ if (next == null || next.snapshot.throughSequence < target) {
+ throw new Error('subagent_content_snapshot_incomplete');
+ }
+ if (
+ caughtUpTerminal ||
+ isLiveSubagentStatus(next.snapshot.status) ||
+ next.snapshot.recovery === 'complete'
+ ) {
+ if (next === previous) return next;
+ return {
+ ...next,
+ snapshot: { ...next.snapshot, runSteps: Array.from(next.stream.steps.values()) },
+ };
+ }
+ // A pinned page can observe terminal status from a newer committed head.
+ // Refresh once; a genuinely incomplete capture must remain partial.
+ caughtUpTerminal = true;
+ response = await read(next.snapshot.throughSequence);
+ next = apply(next, response);
+ if (next == null) throw new Error('subagent_content_snapshot_required');
+ }
+}
diff --git a/client/src/components/Chat/Subagents/state.ts b/client/src/components/Chat/Subagents/state.ts
index 4f599186e7..768c4ee8ba 100644
--- a/client/src/components/Chat/Subagents/state.ts
+++ b/client/src/components/Chat/Subagents/state.ts
@@ -9,6 +9,7 @@ import type {
SubagentControlRequest,
SubagentUpdatePhase,
TMessageContentParts,
+ TAttachment,
SubagentUpdateEvent,
} from 'librechat-data-provider';
import type { Getter, PrimitiveAtom, WritableAtom } from 'jotai';
@@ -316,6 +317,7 @@ export type ActiveSubagentPanel = {
prompt?: string;
legacyOutput?: string | null;
persistedContent?: TMessageContentParts[];
+ attachments?: TAttachment[];
/** The tool call came from the server as a preview: its transcript, output or arguments are
* shortened or absent, so the panel loads the stored part before rendering activity. Carries
* what identifies the stored part and the preview's revision. */
diff --git a/client/src/data-provider/Subagents/content.test.tsx b/client/src/data-provider/Subagents/content.test.tsx
new file mode 100644
index 0000000000..09248d10b6
--- /dev/null
+++ b/client/src/data-provider/Subagents/content.test.tsx
@@ -0,0 +1,510 @@
+import React from 'react';
+import { Provider, createStore } from 'jotai';
+import { renderHook, waitFor, act } from '@testing-library/react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { ContentTypes, dataService, StepEvents, StepTypes } from 'librechat-data-provider';
+import type {
+ SubagentTaskContentSnapshot,
+ SubagentTaskContentSuffix,
+} from 'librechat-data-provider';
+import {
+ isLegacyContentUnavailable,
+ useSubagentTaskContentQuery,
+ useSubagentToolContentQuery,
+ TaskContentScopeContext,
+ subagentTaskContentKey,
+} from './content';
+
+jest.mock('librechat-data-provider', () => {
+ const actual = jest.requireActual('librechat-data-provider');
+ return { ...actual, dataService: { ...actual.dataService, getSubagentTaskContent: jest.fn() } };
+});
+
+const scope = { parentConversationId: 'parent', threadId: 'thread', taskId: 'task' };
+const initial: SubagentTaskContentSnapshot = {
+ ...scope,
+ mode: 'snapshot',
+ messageId: 'task:assistant',
+ parentMessageId: 'task:user',
+ sender: 'worker',
+ status: 'running',
+ recovery: 'partial',
+ revision: 1,
+ throughSequence: 0,
+ targetThroughSequence: 0,
+ content: [{ type: ContentTypes.TEXT, text: 'Opening. ' }],
+ runSteps: [
+ {
+ id: 'text',
+ runId: 'provider',
+ index: 0,
+ type: StepTypes.MESSAGE_CREATION,
+ stepDetails: {
+ type: StepTypes.MESSAGE_CREATION,
+ message_creation: { message_id: 'provider' },
+ },
+ usage: null,
+ },
+ ],
+};
+const clients: QueryClient[] = [];
+const Wrapper = ({ children }: { children: React.ReactNode }) => {
+ const [client] = React.useState(() => {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ clients.push(client);
+ return client;
+ });
+ return (
+ <QueryClientProvider client={client}>
+ <Provider>{children}</Provider>
+ </QueryClientProvider>
+ );
+};
+const getContent = jest.mocked(dataService.getSubagentTaskContent);
+beforeEach(() => getContent.mockReset());
+afterEach(() => clients.splice(0).forEach((client) => client.clear()));
+
+it('waits for subscription readiness before reading an authorized task snapshot', async () => {
+ getContent.mockResolvedValue(initial);
+ const { result, rerender } = renderHook(
+ ({ ready }) => useSubagentTaskContentQuery(scope, { enabled: ready }),
+ { wrapper: Wrapper, initialProps: { ready: false } },
+ );
+ expect(getContent).not.toHaveBeenCalled();
+ rerender({ ready: true });
+ await waitFor(() => expect(result.current.data?.messageId).toBe('task:assistant'));
+ expect(getContent).toHaveBeenCalledWith('parent', 'thread', 'task', undefined, undefined);
+});
+
+it('requests only the committed suffix on invalidation, not bounded activity deltas', async () => {
+ const { content: _content, runSteps: _steps, ...identity } = initial;
+ const suffix: SubagentTaskContentSuffix = {
+ ...identity,
+ mode: 'suffix',
+ afterSequence: 0,
+ revision: 2,
+ throughSequence: 1,
+ targetThroughSequence: 1,
+ events: [
+ {
+ sequence: 1,
+ frame: {
+ event: StepEvents.ON_MESSAGE_DELTA,
+ data: { id: 'text', delta: { content: [{ type: ContentTypes.TEXT, text: 'Later.' }] } },
+ },
+ },
+ ],
+ };
+ getContent.mockResolvedValueOnce(initial).mockResolvedValueOnce(suffix);
+ const { result } = renderHook(() => useSubagentTaskContentQuery(scope), { wrapper: Wrapper });
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ await act(async () => {
+ await result.current.refetch();
+ });
+ expect(getContent).toHaveBeenLastCalledWith('parent', 'thread', 'task', 0, undefined);
+ await waitFor(() =>
+ expect(result.current.data?.content[0]).toMatchObject({ text: 'Opening. Later.' }),
+ );
+});
+
+it('treats old-record absence as compatibility fallback without retrying it', async () => {
+ const error = { response: { status: 409, data: { code: 'SUBAGENT_CONTENT_UNAVAILABLE' } } };
+ getContent.mockRejectedValue(error);
+ const { result } = renderHook(() => useSubagentTaskContentQuery(scope), { wrapper: Wrapper });
+ await waitFor(() => expect(result.current.isUnavailable).toBe(true));
+ expect(getContent).toHaveBeenCalledTimes(1);
+ expect(isLegacyContentUnavailable(error)).toBe(true);
+ expect(isLegacyContentUnavailable({ response: { status: 503 } })).toBe(false);
+});
+
+it('keeps the prior standard message readable when a recoverable request fails', async () => {
+ getContent.mockResolvedValueOnce(initial).mockRejectedValueOnce(new Error('offline'));
+ const { result } = renderHook(() => useSubagentTaskContentQuery(scope, { retry: false }), {
+ wrapper: Wrapper,
+ });
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ await act(async () => {
+ await result.current.refetch();
+ });
+ await waitFor(() => expect(result.current.isError).toBe(true));
+ expect(result.current.data?.content).toEqual(initial.content);
+ expect(result.current.isUnavailable).toBe(false);
+});
+
+it('retains the committed cursor while another reader still owns the same task', async () => {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ clients.push(client);
+ const store = createStore();
+ const SharedWrapper = ({ children }: { children: React.ReactNode }) => (
+ <QueryClientProvider client={client}>
+ <Provider store={store}>{children}</Provider>
+ </QueryClientProvider>
+ );
+ const { content: _content, runSteps: _steps, ...identity } = initial;
+ getContent.mockImplementation(async (_parent, _thread, _task, afterSequence) =>
+ afterSequence == null
+ ? initial
+ : {
+ ...identity,
+ mode: 'suffix',
+ afterSequence,
+ events: [],
+ },
+ );
+ const options = { staleTime: Infinity, refetchInterval: false } as const;
+ const first = renderHook(() => useSubagentTaskContentQuery(scope, options), {
+ wrapper: SharedWrapper,
+ });
+ const second = renderHook(() => useSubagentTaskContentQuery(scope, options), {
+ wrapper: SharedWrapper,
+ });
+ await waitFor(() => expect(second.result.current.isSuccess).toBe(true));
+ first.unmount();
+ await act(async () => {
+ await Promise.resolve();
+ });
+ const third = renderHook(() => useSubagentTaskContentQuery(scope, options), {
+ wrapper: SharedWrapper,
+ });
+ await act(async () => {
+ await third.result.current.refetch();
+ });
+ expect(getContent).toHaveBeenLastCalledWith('parent', 'thread', 'task', 0, undefined);
+ third.unmount();
+ second.unmount();
+});
+
+it('refreshes a partial terminal prefix during the server-bounded late-commit window', async () => {
+ jest.useFakeTimers();
+ const partial = { ...initial, status: 'completed' as const, retryUntil: Date.now() + 6000 };
+ const { content: _content, runSteps: _steps, ...identity } = partial;
+ const missing = { ...identity, mode: 'suffix' as const, afterSequence: 0, events: [] };
+ const complete = {
+ ...missing,
+ revision: 2,
+ throughSequence: 1,
+ targetThroughSequence: 1,
+ recovery: 'complete' as const,
+ events: [
+ {
+ sequence: 1,
+ frame: {
+ event: StepEvents.ON_MESSAGE_DELTA as const,
+ data: {
+ id: 'text',
+ delta: { content: [{ type: ContentTypes.TEXT as const, text: 'Late result.' }] },
+ },
+ },
+ },
+ ],
+ };
+ let committed = false;
+ getContent.mockImplementation(async (_parent, _thread, _task, afterSequence) => {
+ if (afterSequence == null) return partial;
+ return committed ? complete : missing;
+ });
+ const { result, unmount } = renderHook(() => useSubagentTaskContentQuery(scope), {
+ wrapper: Wrapper,
+ });
+ try {
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ committed = true;
+ await act(async () => {
+ await jest.advanceTimersByTimeAsync(2000);
+ });
+ await waitFor(() => expect(result.current.data?.recovery).toBe('complete'));
+ expect(result.current.data?.content[0]).toMatchObject({ text: 'Opening. Late result.' });
+ const requests = getContent.mock.calls.length;
+ await act(async () => {
+ await jest.advanceTimersByTimeAsync(10_000);
+ });
+ expect(getContent).toHaveBeenCalledTimes(requests);
+ } finally {
+ unmount();
+ jest.useRealTimers();
+ }
+});
+
+it('stops retrying genuinely partial terminal capture when its fixed deadline expires', async () => {
+ jest.useFakeTimers();
+ const partial = { ...initial, status: 'failed' as const, retryUntil: Date.now() + 4000 };
+ const { content: _content, runSteps: _steps, ...identity } = partial;
+ getContent.mockImplementation(async (_parent, _thread, _task, afterSequence) =>
+ afterSequence == null ? partial : { ...identity, mode: 'suffix', afterSequence, events: [] },
+ );
+ const { result, unmount } = renderHook(() => useSubagentTaskContentQuery(scope), {
+ wrapper: Wrapper,
+ });
+ try {
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ const before = getContent.mock.calls.length;
+ await act(async () => {
+ await jest.advanceTimersByTimeAsync(4000);
+ });
+ expect(getContent.mock.calls.length).toBeGreaterThan(before);
+ const settled = getContent.mock.calls.length;
+ await act(async () => {
+ await jest.advanceTimersByTimeAsync(20_000);
+ });
+ expect(getContent).toHaveBeenCalledTimes(settled);
+ expect(result.current.data?.recovery).toBe('partial');
+ } finally {
+ unmount();
+ jest.useRealTimers();
+ }
+});
+
+it('does not probe unsupported retained tasks even after query invalidation', async () => {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ clients.push(client);
+ const DisabledWrapper = ({ children }: { children: React.ReactNode }) => (
+ <QueryClientProvider client={client}>
+ <Provider>{children}</Provider>
+ </QueryClientProvider>
+ );
+ const { result } = renderHook(() => useSubagentTaskContentQuery(scope, { enabled: false }), {
+ wrapper: DisabledWrapper,
+ });
+ await act(async () => {
+ await client.invalidateQueries();
+ });
+ expect(result.current.fetchStatus).toBe('idle');
+ expect(getContent).not.toHaveBeenCalled();
+});
+
+const sharedClient = () => {
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ logger: { log: console.log, warn: console.warn, error: () => {} },
+ });
+ clients.push(client);
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
+ <QueryClientProvider client={client}>
+ <Provider>
+ <TaskContentScopeContext.Provider value={scope}>
+ {children}
+ </TaskContentScopeContext.Provider>
+ </Provider>
+ </QueryClientProvider>
+ );
+ return { client, wrapper };
+};
+const noPolling = { staleTime: Infinity, refetchInterval: false, retry: false } as const;
+const unchanged = (afterSequence: number): SubagentTaskContentSuffix => {
+ const { content: _content, runSteps: _steps, ...identity } = initial;
+ return { ...identity, mode: 'suffix', afterSequence, events: [] };
+};
+const partParams = (index: number) => ({
+ conversationId: 'thread',
+ messageId: initial.messageId,
+ partIndex: index,
+ toolCallId: `call-${index}`,
+ stepId: `step-${index}`,
+});
+const fullParts: SubagentTaskContentSnapshot = {
+ ...initial,
+ content: [0, 1].map((index) => ({
+ type: ContentTypes.TOOL_CALL,
+ tool_call: {
+ id: `call-${index}`,
+ stepId: `step-${index}`,
+ name: 'bash',
+ args: '{}',
+ output: `full-${index}`,
+ },
+ })),
+};
+
+it('retains a closed task until query eviction but never shares it across clients', async () => {
+ const one = sharedClient();
+ getContent.mockImplementation(async (_parent, _thread, _task, afterSequence) =>
+ afterSequence == null ? initial : unchanged(afterSequence),
+ );
+ const first = renderHook(() => useSubagentTaskContentQuery(scope, noPolling), {
+ wrapper: one.wrapper,
+ });
+ await waitFor(() => expect(first.result.current.isSuccess).toBe(true));
+ first.unmount();
+ await act(async () => {
+ await Promise.resolve();
+ });
+ const reopened = renderHook(() => useSubagentTaskContentQuery(scope, noPolling), {
+ wrapper: one.wrapper,
+ });
+ expect(getContent).toHaveBeenCalledTimes(1);
+ await act(async () => {
+ await reopened.result.current.refetch();
+ });
+ expect(getContent).toHaveBeenLastCalledWith('parent', 'thread', 'task', 0, undefined);
+ const two = sharedClient();
+ const isolated = renderHook(() => useSubagentTaskContentQuery(scope, noPolling), {
+ wrapper: two.wrapper,
+ });
+ await waitFor(() => expect(isolated.result.current.isSuccess).toBe(true));
+ expect(getContent).toHaveBeenLastCalledWith('parent', 'thread', 'task', undefined, undefined);
+ reopened.unmount();
+ act(() => one.client.removeQueries(subagentTaskContentKey(scope), { exact: true }));
+ const evicted = renderHook(() => useSubagentTaskContentQuery(scope, noPolling), {
+ wrapper: one.wrapper,
+ });
+ await waitFor(() => expect(evicted.result.current.isSuccess).toBe(true));
+ expect(getContent).toHaveBeenLastCalledWith('parent', 'thread', 'task', undefined, undefined);
+});
+
+it('cancels abandoned pages and does not publish their result over a new mount', async () => {
+ const { wrapper } = sharedClient();
+ let resolveOld!: (value: SubagentTaskContentSnapshot) => void;
+ getContent
+ .mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveOld = resolve;
+ }),
+ )
+ .mockResolvedValue(initial);
+ const abandoned = renderHook(() => useSubagentTaskContentQuery(scope, noPolling), { wrapper });
+ abandoned.unmount();
+ const current = renderHook(() => useSubagentTaskContentQuery(scope, noPolling), { wrapper });
+ await waitFor(() => expect(current.result.current.isSuccess).toBe(true));
+ await act(async () => {
+ resolveOld({ ...initial, revision: 99, targetThroughSequence: 100, nextCursor: 'abandoned' });
+ await Promise.resolve();
+ });
+ expect(getContent).toHaveBeenCalledTimes(2);
+ expect(current.result.current.data?.revision).toBe(1);
+ await act(async () => {
+ getContent.mockResolvedValueOnce(unchanged(0));
+ await current.result.current.refetch();
+ });
+ expect(getContent).toHaveBeenLastCalledWith('parent', 'thread', 'task', 0, undefined);
+});
+
+it('shares simultaneous full-part recovery and seeds later task and part readers', async () => {
+ const { client, wrapper } = sharedClient();
+ let resolve!: (value: SubagentTaskContentSnapshot) => void;
+ getContent.mockImplementationOnce(
+ () =>
+ new Promise((done) => {
+ resolve = done;
+ }),
+ );
+ const parts = renderHook(
+ () => [
+ useSubagentToolContentQuery(partParams(0), noPolling),
+ useSubagentToolContentQuery(partParams(1), noPolling),
+ ],
+ { wrapper },
+ );
+ expect(getContent).toHaveBeenCalledTimes(1);
+ await act(async () => {
+ resolve(fullParts);
+ });
+ await waitFor(() => expect(parts.result.current.every((part) => part.isSuccess)).toBe(true));
+ expect(parts.result.current.map((part) => part.data?.tool_call.output)).toEqual([
+ 'full-0',
+ 'full-1',
+ ]);
+ expect(
+ client.getQueryData<SubagentTaskContentSnapshot>(subagentTaskContentKey(scope))?.content,
+ ).toEqual(fullParts.content);
+ const reader = renderHook(() => useSubagentTaskContentQuery(scope, noPolling), { wrapper });
+ expect(reader.result.current.data?.content).toEqual(fullParts.content);
+ expect(getContent).toHaveBeenCalledTimes(1);
+ getContent.mockResolvedValueOnce(unchanged(0));
+ await act(async () => {
+ await reader.result.current.refetch();
+ });
+ expect(getContent).toHaveBeenLastCalledWith('parent', 'thread', 'task', 0, undefined);
+});
+
+it('fetches a fresh authorized snapshot when a requested earlier full part is missing', async () => {
+ const { client, wrapper } = sharedClient();
+ getContent.mockResolvedValueOnce(initial).mockResolvedValueOnce(fullParts);
+ const reader = renderHook(() => useSubagentTaskContentQuery(scope, noPolling), { wrapper });
+ await waitFor(() => expect(reader.result.current.isSuccess).toBe(true));
+ const part = renderHook(() => useSubagentToolContentQuery(partParams(1), noPolling), { wrapper });
+ await waitFor(() => expect(part.result.current.isSuccess).toBe(true));
+ expect(getContent).toHaveBeenLastCalledWith('parent', 'thread', 'task', undefined, undefined);
+ expect(part.result.current.data?.tool_call.output).toBe('full-1');
+ expect(
+ client.getQueryData<SubagentTaskContentSnapshot>(subagentTaskContentKey(scope))?.content,
+ ).toEqual(fullParts.content);
+});
+
+it('never seeds a mismatched parent snapshot or reuses a part under another message identity', async () => {
+ const { client, wrapper } = sharedClient();
+ getContent.mockResolvedValueOnce({ ...fullParts, parentConversationId: 'other' });
+ const rejected = renderHook(() => useSubagentToolContentQuery(partParams(0), noPolling), {
+ wrapper,
+ });
+ await waitFor(() => expect(rejected.result.current.isError).toBe(true));
+ expect(client.getQueryData(subagentTaskContentKey(scope))).toBeUndefined();
+ getContent.mockResolvedValueOnce(fullParts);
+ const valid = renderHook(() => useSubagentToolContentQuery(partParams(1), noPolling), {
+ wrapper,
+ });
+ await waitFor(() => expect(valid.result.current.isSuccess).toBe(true));
+ const wrong = renderHook(
+ () => useSubagentToolContentQuery({ ...partParams(1), messageId: 'wrong-message' }, noPolling),
+ { wrapper },
+ );
+ await waitFor(() => expect(wrong.result.current.isError).toBe(true));
+ expect(wrong.result.current.data).toBeUndefined();
+});
+
+it('keeps shared full-part demand alive for another reader and cancels its last abandoned reader', async () => {
+ const { client, wrapper } = sharedClient();
+ let resolve!: (value: SubagentTaskContentSnapshot) => void;
+ getContent.mockImplementationOnce(
+ () =>
+ new Promise((done) => {
+ resolve = done;
+ }),
+ );
+ const first = renderHook(() => useSubagentToolContentQuery(partParams(0), noPolling), {
+ wrapper,
+ });
+ const second = renderHook(() => useSubagentToolContentQuery(partParams(1), noPolling), {
+ wrapper,
+ });
+ first.unmount();
+ await act(async () => {
+ resolve(fullParts);
+ });
+ await waitFor(() => expect(second.result.current.isSuccess).toBe(true));
+ expect(getContent).toHaveBeenCalledTimes(1);
+ second.unmount();
+ act(() => client.removeQueries(subagentTaskContentKey(scope), { exact: true }));
+ getContent.mockImplementationOnce(
+ () =>
+ new Promise((done) => {
+ resolve = done;
+ }),
+ );
+ const abandoned = renderHook(() => useSubagentToolContentQuery(partParams(0), noPolling, 'new'), {
+ wrapper,
+ });
+ abandoned.unmount();
+ await act(async () => {
+ resolve({ ...fullParts, nextCursor: 'abandoned-page', targetThroughSequence: 10 });
+ });
+ expect(getContent).toHaveBeenCalledTimes(2);
+ expect(client.getQueryData(subagentTaskContentKey(scope))).toBeUndefined();
+});
+
+it('replaces a cached preview with full authorized content rather than replaying an empty suffix', async () => {
+ const { client, wrapper } = sharedClient();
+ const part = fullParts.content[0];
+ if (part.type !== ContentTypes.TOOL_CALL) throw new Error('tool required');
+ client.setQueryData(subagentTaskContentKey(scope), {
+ ...fullParts,
+ content: [{ ...part, tool_call: { ...part.tool_call, outputTruncated: true } }],
+ });
+ getContent.mockResolvedValueOnce(fullParts);
+ const result = renderHook(() => useSubagentToolContentQuery(partParams(0), noPolling), {
+ wrapper,
+ });
+ await waitFor(() => expect(result.result.current.isSuccess).toBe(true));
+ expect(getContent).toHaveBeenLastCalledWith('parent', 'thread', 'task', undefined, undefined);
+ expect(result.result.current.data?.tool_call.output).toBe('full-0');
+});
diff --git a/client/src/data-provider/Subagents/content.tsx b/client/src/data-provider/Subagents/content.tsx
new file mode 100644
index 0000000000..5c7a084f50
--- /dev/null
+++ b/client/src/data-provider/Subagents/content.tsx
@@ -0,0 +1,209 @@
+import { createContext, useContext } from 'react';
+import { atom, createStore } from 'jotai';
+import { useQuery, useQueryClient } from '@tanstack/react-query';
+import { QueryKeys, dataService, hasToolCallPreview } from 'librechat-data-provider';
+import type { SubagentTaskContentSnapshot, ToolCallPartResponse } from 'librechat-data-provider';
+import type { QueryClient, UseQueryOptions } from '@tanstack/react-query';
+import type { ToolContentQuery } from '~/components/Chat/Messages/Content/disclosure';
+import type { RecoveredContent } from '~/components/Chat/Subagents/recovery';
+import { recoverTaskContent, recoveredToolPart } from '~/components/Chat/Subagents/recovery';
+import { isLiveSubagentStatus } from '~/components/Chat/Subagents/status';
+import { ACTIVE_THREAD_REFRESH_MS } from './queries';
+
+export type TaskContentScope = {
+ parentConversationId: string;
+ threadId: string;
+ taskId: string;
+};
+
+export const TaskContentScopeContext = createContext<TaskContentScope | null>(null);
+export const subagentTaskContentKey = (scope: TaskContentScope) =>
+ [
+ QueryKeys.subagentTaskContent,
+ scope.parentConversationId,
+ scope.threadId,
+ scope.taskId,
+ ] as const;
+
+const streams = new WeakMap<object, ReturnType<typeof createRecoveryState>>();
+const createRecoveryState = () => ({
+ store: createStore(),
+ stream: atom<RecoveredContent | null>(null),
+ partReaders: 0,
+});
+
+function recoveryState(queryClient: QueryClient, scope: TaskContentScope) {
+ const query = queryClient.getQueryCache().build(queryClient, {
+ queryKey: subagentTaskContentKey(scope),
+ });
+ let state = streams.get(query);
+ if (state == null) {
+ state = createRecoveryState();
+ streams.set(query, state);
+ }
+ return state;
+}
+
+async function loadTaskContent(
+ queryClient: QueryClient,
+ scope: TaskContentScope,
+ signal?: AbortSignal,
+ fresh = false,
+): Promise<SubagentTaskContentSnapshot> {
+ const { store, stream } = recoveryState(queryClient, scope);
+ const before = fresh ? null : store.get(stream);
+ const load = async (afterSequence?: number, cursor?: string) => {
+ const response = await dataService.getSubagentTaskContent(
+ scope.parentConversationId,
+ scope.threadId,
+ scope.taskId,
+ afterSequence,
+ cursor,
+ );
+ if (
+ response.taskId !== scope.taskId ||
+ response.threadId !== scope.threadId ||
+ response.parentConversationId !== scope.parentConversationId
+ ) {
+ throw new Error('subagent_content_identity_mismatch');
+ }
+ return response;
+ };
+ let next: RecoveredContent;
+ try {
+ next = await recoverTaskContent(before, load, signal);
+ } catch (error) {
+ const code = responseCode(error);
+ if (code !== 'SUBAGENT_CONTENT_AHEAD' && code !== 'SUBAGENT_CONTENT_GAP') throw error;
+ next = await recoverTaskContent(null, load, signal);
+ }
+ if (signal?.aborted) throw new Error('subagent_content_cancelled');
+ const current = store.get(stream);
+ if (
+ current != null &&
+ (current.snapshot.throughSequence > next.snapshot.throughSequence ||
+ current.snapshot.revision > next.snapshot.revision)
+ )
+ return current.snapshot;
+ store.set(stream, next);
+ return next.snapshot;
+}
+
+async function loadFullTaskContent(
+ queryClient: QueryClient,
+ scope: TaskContentScope,
+ signal?: AbortSignal,
+): Promise<SubagentTaskContentSnapshot> {
+ if (signal?.aborted) throw new Error('subagent_content_cancelled');
+ const state = recoveryState(queryClient, scope);
+ const queryKey = subagentTaskContentKey(scope);
+ const query = queryClient.getQueryCache().find(queryKey, { exact: true });
+ state.partReaders++;
+ let released = false;
+ const release = () => {
+ if (released) return;
+ released = true;
+ state.partReaders--;
+ if (signal?.aborted && state.partReaders === 0 && query?.getObserversCount() === 0) {
+ void query.cancel({ revert: true });
+ }
+ };
+ signal?.addEventListener('abort', release, { once: true });
+ try {
+ return await queryClient.fetchQuery<SubagentTaskContentSnapshot>({
+ queryKey,
+ queryFn: ({ signal: taskSignal }) => loadTaskContent(queryClient, scope, taskSignal, true),
+ staleTime: 0,
+ });
+ } finally {
+ signal?.removeEventListener('abort', release);
+ release();
+ }
+}
+
+type ContentError = { response?: { status?: number; data?: { code?: string } } };
+const responseStatus = (error: unknown): number | undefined =>
+ (error as ContentError | null)?.response?.status;
+const responseCode = (error: unknown): string | undefined =>
+ (error as ContentError | null)?.response?.data?.code;
+export const isLegacyContentUnavailable = (error: unknown): boolean =>
+ responseStatus(error) === 404 ||
+ (responseStatus(error) === 409 && responseCode(error) === 'SUBAGENT_CONTENT_UNAVAILABLE');
+
+export function subagentContentRefetchInterval(
+ snapshot: SubagentTaskContentSnapshot | undefined,
+ error?: unknown,
+): number | false {
+ if (isLegacyContentUnavailable(error)) return false;
+ if (snapshot == null || isLiveSubagentStatus(snapshot.status)) return ACTIVE_THREAD_REFRESH_MS;
+ const remaining = (snapshot.retryUntil ?? 0) - Date.now();
+ if (snapshot.recovery !== 'partial' || !Number.isFinite(remaining) || remaining <= 0)
+ return false;
+ return Math.min(ACTIVE_THREAD_REFRESH_MS, remaining);
+}
+
+export function useSubagentTaskContentQuery(
+ scope: TaskContentScope,
+ options: UseQueryOptions<SubagentTaskContentSnapshot> = {},
+) {
+ const queryClient = useQueryClient();
+ const query = useQuery<SubagentTaskContentSnapshot>(
+ subagentTaskContentKey(scope),
+ ({ signal }) => loadTaskContent(queryClient, scope, signal),
+ {
+ enabled: scope.parentConversationId !== '' && scope.threadId !== '' && scope.taskId !== '',
+ retry: (attempt, error) => !isLegacyContentUnavailable(error) && attempt < 2,
+ refetchOnWindowFocus: true,
+ refetchInterval: (snapshot, query) =>
+ subagentContentRefetchInterval(snapshot, query.state.error),
+ ...options,
+ },
+ );
+ return { ...query, isUnavailable: isLegacyContentUnavailable(query.error) };
+}
+
+/** Uses the parent-authorized task endpoint, never the child's private message route. */
+export const useSubagentToolContentQuery: ToolContentQuery = (params, options, revision = '') => {
+ const scope = useContext(TaskContentScopeContext);
+ const queryClient = useQueryClient();
+ return useQuery<ToolCallPartResponse>(
+ [
+ ...subagentTaskContentKey(scope ?? { parentConversationId: '', threadId: '', taskId: '' }),
+ 'part',
+ params.conversationId,
+ params.messageId,
+ params.toolCallId,
+ params.stepId,
+ params.agentId,
+ params.partIndex,
+ revision,
+ ],
+ async ({ signal }) => {
+ if (scope == null) throw new Error('subagent_content_scope_required');
+ const cached = queryClient.getQueryData<SubagentTaskContentSnapshot>(
+ subagentTaskContentKey(scope),
+ );
+ let part = cached == null ? null : recoveredToolPart(cached, params);
+ if (cached != null && cached.messageId !== params.messageId) {
+ throw new Error('subagent_content_identity_mismatch');
+ }
+ if (part == null || hasToolCallPreview(part.tool_call)) {
+ const full = await loadFullTaskContent(queryClient, scope, signal);
+ if (signal?.aborted) throw new Error('subagent_content_cancelled');
+ if (full.messageId !== params.messageId)
+ throw new Error('subagent_content_identity_mismatch');
+ part = recoveredToolPart(full, params);
+ }
+ if (part == null || hasToolCallPreview(part.tool_call))
+ throw new Error('subagent_content_part_unavailable');
+ return { conversationId: params.conversationId, messageId: params.messageId, ...part };
+ },
+ {
+ staleTime: Infinity,
+ retry: 1,
+ refetchOnWindowFocus: false,
+ ...options,
+ enabled: scope != null && options?.enabled !== false,
+ },
+ );
+};
diff --git a/client/src/data-provider/Subagents/useSubagentActivityStream.test.tsx b/client/src/data-provider/Subagents/useSubagentActivityStream.test.tsx
index b411c088ec..1d758e0a8c 100644
--- a/client/src/data-provider/Subagents/useSubagentActivityStream.test.tsx
+++ b/client/src/data-provider/Subagents/useSubagentActivityStream.test.tsx
@@ -45,7 +45,11 @@ jest.mock('sse.js', () => ({
}));
const mockInvalidateQueries = jest.fn();
-const mockQueryClient = { invalidateQueries: mockInvalidateQueries };
+const mockGetQueryData = jest.fn();
+const mockQueryClient = {
+ invalidateQueries: mockInvalidateQueries,
+ getQueryData: mockGetQueryData,
+};
jest.mock('@tanstack/react-query', () => ({
...jest.requireActual('@tanstack/react-query'),
useQueryClient: () => mockQueryClient,
@@ -75,6 +79,7 @@ describe('useSubagentActivityStream', () => {
beforeEach(() => {
streams.length = 0;
mockInvalidateQueries.mockClear();
+ mockGetQueryData.mockReset();
takeRegisteredSubagentProgressKeys();
});
@@ -794,3 +799,53 @@ describe('useSubagentActivityStream', () => {
expect(streams).toHaveLength(0);
});
});
+
+it('treats content watermarks as invalidation only after the subscribed ready boundary', () => {
+ const { result } = renderHook(() => useSubagentActivityStream(selection), { wrapper });
+ const stream = streams.at(-1)!;
+ expect(result.current.isReady).toBe(false);
+ act(() => stream.emit('message', { ready: true, contentRecovery: true }));
+ expect(result.current.isReady).toBe(true);
+ mockInvalidateQueries.mockClear();
+ act(() =>
+ stream.emit('message', {
+ event: 'subagent_content_available',
+ data: { taskId: 'task?1', revision: 3, throughSequence: 118 },
+ }),
+ );
+ expect(mockInvalidateQueries).toHaveBeenCalledWith(
+ [QueryKeys.subagentTaskContent, 'parent conversation', 'child/thread', 'task?1'],
+ { exact: true },
+ { cancelRefetch: false },
+ );
+ mockInvalidateQueries.mockClear();
+ act(() =>
+ stream.emit('message', {
+ event: 'subagent_content_available',
+ data: { taskId: 'other-task', revision: 9, throughSequence: 119 },
+ }),
+ );
+ expect(mockInvalidateQueries).not.toHaveBeenCalled();
+});
+
+it('skips already committed content notifications but still refreshes a newer revision or sequence', () => {
+ mockGetQueryData.mockReturnValue({ revision: 3, throughSequence: 118 });
+ const { unmount } = renderHook(() => useSubagentActivityStream(selection), { wrapper });
+ const stream = streams.at(-1)!;
+ mockInvalidateQueries.mockClear();
+ const notify = (revision: number, throughSequence: number) =>
+ act(() =>
+ stream.emit('message', {
+ event: 'subagent_content_available',
+ data: { taskId: 'task?1', revision, throughSequence },
+ }),
+ );
+ notify(3, 118);
+ notify(2, 117);
+ expect(mockInvalidateQueries).not.toHaveBeenCalled();
+ notify(4, 118);
+ notify(3, 119);
+ expect(mockInvalidateQueries).toHaveBeenCalledTimes(2);
+ unmount();
+ mockGetQueryData.mockReset();
+});
diff --git a/client/src/data-provider/Subagents/useSubagentActivityStream.ts b/client/src/data-provider/Subagents/useSubagentActivityStream.ts
index ba86fb2c74..5f1acf999b 100644
--- a/client/src/data-provider/Subagents/useSubagentActivityStream.ts
+++ b/client/src/data-provider/Subagents/useSubagentActivityStream.ts
@@ -1,10 +1,10 @@
import { useEffect, useMemo, useRef } from 'react';
import { SSE } from 'sse.js';
-import { selectAtom } from 'jotai/utils';
-import { useAtomValue, useSetAtom } from 'jotai';
+import { atomFamily, selectAtom } from 'jotai/utils';
import { useQueryClient } from '@tanstack/react-query';
+import { atom, useAtom, useAtomValue, useSetAtom } from 'jotai';
import { QueryKeys, StepEvents, apiBaseUrl } from 'librechat-data-provider';
-import type { SubagentUpdateEvent } from 'librechat-data-provider';
+import type { SubagentTaskContentSnapshot, SubagentUpdateEvent } from 'librechat-data-provider';
import type { ActiveSubagentPanel } from '~/components/Chat/Subagents/state';
import {
closeParentSubagentProgress,
@@ -23,8 +23,12 @@ type ActivityEnvelope = {
final?: unknown;
subagentActivity?: unknown;
droppedCount?: unknown;
+ ready?: unknown;
};
+const contentReady = atomFamily((_key: string) => atom(false));
+const readyReaders = new Map<string, number>();
+
const INITIAL_RECONNECT_MS = 500;
const MAX_RECONNECT_MS = 5_000;
@@ -46,7 +50,7 @@ const isSubagentUpdate = (value: unknown): value is SubagentUpdateEvent => {
export default function useSubagentActivityStream(
selection: ActiveSubagentPanel,
enabled = true,
-): void {
+): { isReady: boolean } {
const { token, isAuthenticated } = useAuthContext();
const queryClient = useQueryClient();
const key = subagentProgressKey(
@@ -54,6 +58,28 @@ export default function useSubagentActivityStream(
selection.event?.progressKey ?? selection.toolCallId,
selection.partIndex,
);
+ const readyKey = JSON.stringify([
+ selection.parentConversationId,
+ selection.durable?.threadId,
+ selection.durable?.taskId,
+ ]);
+ const [isReady, setReady] = useAtom(contentReady(readyKey));
+ useEffect(() => {
+ readyReaders.set(readyKey, (readyReaders.get(readyKey) ?? 0) + 1);
+ return () => {
+ const remaining = (readyReaders.get(readyKey) ?? 1) - 1;
+ if (remaining > 0) {
+ readyReaders.set(readyKey, remaining);
+ return;
+ }
+ readyReaders.delete(readyKey);
+ queueMicrotask(() => {
+ if (readyReaders.has(readyKey)) return;
+ setReady(false);
+ contentReady.remove(readyKey);
+ });
+ };
+ }, [readyKey, setReady]);
const replayFrom = useAtomValue(
useMemo(
() =>
@@ -101,6 +127,16 @@ export default function useSubagentActivityStream(
}
const queryKey = [QueryKeys.subagentThread, selection.parentConversationId, threadId, taskId];
+ const contentKey = [
+ QueryKeys.subagentTaskContent,
+ selection.parentConversationId,
+ threadId,
+ taskId,
+ ];
+ const refreshContent = () => {
+ void queryClient.invalidateQueries(contentKey, { exact: true }, { cancelRefetch: false });
+ };
+ if ((readyReaders.get(readyKey) ?? 0) <= 1) setReady(false);
const endpoint = `${apiBaseUrl()}/api/convos/${encodeURIComponent(selection.parentConversationId)}/subagents/${encodeURIComponent(threadId)}/tasks/${encodeURIComponent(taskId)}/activity`;
let stream: SSE | undefined;
let retryTimer: ReturnType<typeof setTimeout> | undefined;
@@ -130,7 +166,37 @@ export default function useSubagentActivityStream(
} catch {
return;
}
+ if (envelope.ready === true) {
+ setReady(true);
+ refreshContent();
+ return;
+ }
+ if (envelope.event === 'subagent_content_available') {
+ const watermark = envelope.data as
+ | {
+ taskId?: string;
+ revision?: number;
+ throughSequence?: number;
+ }
+ | undefined;
+ if (
+ watermark?.taskId === taskId &&
+ Number.isSafeInteger(watermark.revision) &&
+ Number.isSafeInteger(watermark.throughSequence)
+ ) {
+ const cached = queryClient.getQueryData<SubagentTaskContentSnapshot>(contentKey);
+ if (
+ cached == null ||
+ cached.revision < watermark.revision! ||
+ cached.throughSequence < watermark.throughSequence!
+ )
+ refreshContent();
+ }
+ return;
+ }
if (envelope.final === true && envelope.subagentActivity === true) {
+ setReady(true);
+ refreshContent();
terminal = true;
closeCurrent();
void queryClient.invalidateQueries(queryKey);
@@ -190,7 +256,10 @@ export default function useSubagentActivityStream(
);
});
next.addEventListener('error', () => {
- if (stream === next) reconnect();
+ if (stream !== next) return;
+ setReady(true);
+ refreshContent();
+ reconnect();
});
};
@@ -214,6 +283,7 @@ export default function useSubagentActivityStream(
isAuthenticated,
key,
queryClient,
+ readyKey,
selection.host,
selection.event,
selection.parentConversationId,
@@ -221,8 +291,10 @@ export default function useSubagentActivityStream(
selection.partIndex,
selection.toolCallId,
setProgress,
+ setReady,
taskId,
threadId,
token,
]);
+ return { isReady };
}
diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json
index 0ed04866c0..bed8f9dd72 100644
--- a/client/src/locales/en/translation.json
+++ b/client/src/locales/en/translation.json
@@ -3186,8 +3186,6 @@
"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_other": "{{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",
"com_ui_subagent_event_type": "Event",
"com_ui_subagent_event_source": "Source",
"com_ui_subagent_event_received": "Occurred",
@@ -3217,7 +3215,6 @@
"com_ui_subagent_errored": "Agent failed",
"com_ui_subagent_no_result_yet": "Still running — no final result yet.",
"com_ui_subagent_thread_history_truncated": "Some earlier activity is unavailable.",
- "com_ui_subagent_thread_load_error": "The agent activity could not be loaded.",
"com_ui_subagent_thread_panel": "Child agent activity",
"com_ui_subagent_depth": "Level {{0}} child",
"com_ui_subagent_thread_read_only": "This child thread is view-only here. Its parent agent owns this execution and can continue it with the saved thread history.",
diff --git a/e2e/config/librechat.e2e.yaml b/e2e/config/librechat.e2e.yaml
index 9e0904515a..838fda2547 100644
--- a/e2e/config/librechat.e2e.yaml
+++ b/e2e/config/librechat.e2e.yaml
@@ -173,6 +173,8 @@ endpoints:
# Default capabilities plus run_in_background (off by default upstream) so the
# background tool-call e2e can opt an MCP tool into detached dispatch.
agents:
+ subagentActivity:
+ contentRecoveryEnabled: true
fileSharing:
enabled: true
allowSiblingSharing: true
@@ -219,6 +221,16 @@ endpoints:
- module: e2e/setup/tool-approval-hook.js
matcher: ^approval_probe_mcp_e2e-memory$
custom:
+ - name: 'Mock Retained History'
+ apiKey: 'e2e-mock-history'
+ baseURL: 'http://127.0.0.1:8889/v1'
+ models:
+ default:
+ - 'mock-retained-history'
+ fetch: false
+ maxToolResultChars: 131072
+ titleConvo: false
+ modelDisplayLabel: 'Mock Retained History'
# Substituted with a REAL provider endpoint only when the mock config runs
# in model-fixture record mode (E2E_MODEL_FIXTURES=record); a comment
# otherwise, so the credential-free profile never gains a live endpoint.
diff --git a/e2e/fixtures/subagent-history.cjs b/e2e/fixtures/subagent-history.cjs
new file mode 100644
index 0000000000..5fcbaf907f
--- /dev/null
+++ b/e2e/fixtures/subagent-history.cjs
@@ -0,0 +1,167 @@
+const fs = require('node:fs/promises');
+const path = require('node:path');
+const { setTimeout: delay } = require('node:timers/promises');
+
+const MARKER = 'E2E_SUBAGENT_HISTORY:';
+const CHILD_MARKER = 'E2E_SUBAGENT_HISTORY_CHILD:';
+const TOOL_NAME = 'slow_echo_mcp_e2e-memory';
+const CALL_COUNT = 112;
+const BATCH_SIZE = 16;
+const GATE_TIMEOUT_MS = 90_000;
+const STATE_ROOT = path.resolve(__dirname, '../.generated/subagent-history');
+
+function control(label) {
+ if (!/^[a-z0-9-]{1,96}$/.test(label)) {
+ throw new Error('Invalid subagent history fixture label');
+ }
+ const directory = path.join(STATE_ROOT, label);
+ const signalPath = (name) => {
+ if (!['ready', 'advance', 'live', 'complete', 'done'].includes(name)) {
+ throw new Error('Invalid subagent history fixture signal');
+ }
+ return path.join(directory, name);
+ };
+ return {
+ directory,
+ async signal(name) {
+ await fs.mkdir(directory, { recursive: true });
+ await fs.writeFile(signalPath(name), '1');
+ },
+ async has(name) {
+ try {
+ await fs.access(signalPath(name));
+ return true;
+ } catch (error) {
+ if (error.code === 'ENOENT') return false;
+ throw error;
+ }
+ },
+ async wait(name, { signal, timeoutMs = GATE_TIMEOUT_MS } = {}) {
+ const deadline = Date.now() + timeoutMs;
+ while (!(await this.has(name))) {
+ signal?.throwIfAborted();
+ if (Date.now() >= deadline) {
+ throw new Error(`Subagent history fixture timed out waiting for ${name}: ${label}`);
+ }
+ await delay(50, undefined, { signal });
+ }
+ signal?.throwIfAborted();
+ },
+ async release() {
+ await Promise.all([this.signal('advance'), this.signal('complete')]);
+ },
+ };
+}
+
+const callId = (label, index) => `call_e2e_history_${label}_${String(index).padStart(3, '0')}`;
+const dispatchId = (label) => `call_e2e_history_dispatch_${label}`;
+const openingText = (label) => `E2E history opening ${label}`;
+const liveText = (label) => `E2E history live continuation ${label}`;
+const completionText = (label) => `E2E history complete ${label}`;
+const stepText = (label, batch) => `E2E history batch ${label} ${batch}`;
+const payload = (label, index) =>
+ `history-input-${label}-${index}-begin|` +
+ 'x'.repeat(index === 0 ? 24 * 1024 : 1024) +
+ `|history-input-${label}-${index}-end`;
+const output = (label, index) => `E2E slow echo: ${payload(label, index)}`;
+const prompt = (label, childId = 'main') => `${MARKER}${childId}:${label}`;
+
+/** Only the model is scripted. Every output must come back through the real MCP tool node. */
+function responsesForText(text, { getLatestUserText, messageType, getContentText }) {
+ const match = text.match(/E2E_SUBAGENT_HISTORY:([\w-]+):([a-z0-9-]{1,96})(?:\s|$)/);
+ if (!match) return null;
+ const [, childId, label] = match;
+ const gates = control(label);
+ const childPrompt = `${CHILD_MARKER}${label}`;
+ const verifiedBatches = new Set();
+ const toolCall = (index) => ({
+ id: callId(label, index),
+ name: TOOL_NAME,
+ args: { text: payload(label, index), delay_ms: 0 },
+ type: 'tool_call',
+ });
+
+ return {
+ responses: [''],
+ sleep: 1,
+ overrideSubagentModel: childId !== 'main',
+ disableHumanInTheLoop: true,
+ resolveInvocation: async (messages, options) => {
+ const results = new Map(
+ (messages ?? [])
+ .filter((message) => messageType(message) === 'tool')
+ .map((message) => [message.tool_call_id, getContentText(message.content)]),
+ );
+ if (childId !== 'main' && !getLatestUserText(messages).includes(childPrompt)) {
+ if (results.has(dispatchId(label))) {
+ return { response: `E2E history child dispatched ${label}` };
+ }
+ return {
+ response: '',
+ toolCalls: [
+ {
+ id: dispatchId(label),
+ name: 'subagent',
+ args: {
+ description: childPrompt,
+ subagent_type: childId,
+ run_in_background: true,
+ },
+ type: 'tool_call',
+ },
+ ],
+ };
+ }
+
+ for (let start = 0; start < CALL_COUNT; start += BATCH_SIZE) {
+ if (verifiedBatches.has(start)) continue;
+ const indices = Array.from({ length: BATCH_SIZE }, (_, index) => start + index);
+ const returned = indices.filter((index) => results.has(callId(label, index)));
+ if (returned.length === 0) {
+ return {
+ response: start === 0 ? openingText(label) : stepText(label, start / BATCH_SIZE),
+ toolCalls: indices.map(toolCall),
+ };
+ }
+ if (
+ returned.length !== BATCH_SIZE ||
+ indices.some((index) => !results.get(callId(label, index)).includes(output(label, index)))
+ ) {
+ throw new Error(`Subagent history fixture lost MCP results: ${label} batch ${start}`);
+ }
+ // Old provider context can be pruned after the actual tool result was verified.
+ verifiedBatches.add(start);
+ }
+
+ await gates.signal('ready');
+ await gates.wait('advance', { signal: options?.signal });
+ if (!results.has(callId(label, CALL_COUNT))) {
+ return { response: liveText(label), toolCalls: [toolCall(CALL_COUNT)] };
+ }
+ if (!results.get(callId(label, CALL_COUNT)).includes(output(label, CALL_COUNT))) {
+ throw new Error(`Subagent history fixture lost the live MCP result: ${label}`);
+ }
+ await gates.signal('live');
+ await gates.wait('complete', { signal: options?.signal });
+ await gates.signal('done');
+ return { response: completionText(label) };
+ },
+ };
+}
+
+module.exports = {
+ TOOL_NAME,
+ CALL_COUNT,
+ BATCH_SIZE,
+ control,
+ callId,
+ dispatchId,
+ openingText,
+ liveText,
+ completionText,
+ stepText,
+ payload,
+ output,
+ prompt,
+ responsesForText,
+};
diff --git a/e2e/fixtures/subagent-history.test.cjs b/e2e/fixtures/subagent-history.test.cjs
new file mode 100644
index 0000000000..b4ca9e77f2
--- /dev/null
+++ b/e2e/fixtures/subagent-history.test.cjs
@@ -0,0 +1,226 @@
+const assert = require('node:assert/strict');
+const { randomUUID } = require('node:crypto');
+const fs = require('node:fs/promises');
+const test = require('node:test');
+const vm = require('node:vm');
+const path = require('node:path');
+const history = require('./subagent-history.cjs');
+
+const helpers = {
+ getLatestUserText: (messages) => messages.findLast((message) => message.type === 'human').content,
+ messageType: (message) => message.type,
+ getContentText: (content) => content,
+};
+const human = (content) => ({ type: 'human', content });
+const result = (call) => ({
+ type: 'tool',
+ tool_call_id: call.id,
+ content: JSON.stringify([{ type: 'text', text: `E2E slow echo: ${call.args.text}` }]),
+});
+
+function scenario(t, childId) {
+ const label = `node-${randomUUID()}`;
+ const gates = history.control(label);
+ t.after(() => fs.rm(gates.directory, { recursive: true, force: true }));
+ const script = history.responsesForText(history.prompt(label, childId), helpers);
+ return { label, gates, script };
+}
+
+async function drainHistory(script, messages) {
+ const calls = [];
+ for (let batch = 0; batch < history.CALL_COUNT / history.BATCH_SIZE; batch++) {
+ const invocation = await script.resolveInvocation(messages);
+ assert.equal(invocation.toolCalls.length, history.BATCH_SIZE);
+ calls.push(...invocation.toolCalls);
+ messages.push(...invocation.toolCalls.map(result));
+ }
+ return calls;
+}
+
+test('fixture exceeds retention, replay and output-preview limits', async (t) => {
+ const { label, gates, script } = scenario(t);
+ const messages = [human(history.prompt(label))];
+ const calls = await drainHistory(script, messages);
+ assert.equal(new Set(calls.map((call) => call.id)).size, history.CALL_COUNT);
+ assert.ok(calls.length > 100);
+ assert.ok(calls.length * 2 > 100, 'tool starts and ends alone overflow the event ring');
+ assert.ok(Buffer.byteLength(history.output(label, 0)) > 16 * 1024);
+ assert.ok(
+ calls.slice(-100).reduce((bytes, call) => bytes + Buffer.byteLength(result(call).content), 0) >
+ 64 * 1024,
+ 'even the last 100 outputs exceed the replay byte budget',
+ );
+ assert.equal(await gates.has('ready'), false, 'readiness follows actual tool results');
+});
+
+test('normal and child scripts share retained history and gated continuation', async (t) => {
+ for (const childId of ['main', 'agent_e2e_child']) {
+ const { label, gates, script } = scenario(t, childId);
+ const messages = [human(history.prompt(label, childId))];
+ if (childId !== 'main') {
+ const dispatch = await script.resolveInvocation(messages);
+ assert.equal(dispatch.toolCalls[0].name, 'subagent');
+ assert.equal(dispatch.toolCalls[0].args.run_in_background, true);
+ assert.equal(dispatch.toolCalls[0].args.subagent_type, childId);
+ const parent = await script.resolveInvocation([
+ ...messages,
+ { type: 'tool', tool_call_id: history.dispatchId(label), content: '{"status":"running"}' },
+ ]);
+ assert.equal(parent.response, `E2E history child dispatched ${label}`);
+ messages.splice(0, 1, human(dispatch.toolCalls[0].args.description));
+ }
+ const calls = await drainHistory(script, messages);
+ assert.deepEqual(
+ calls.map((call) => call.id),
+ Array.from({ length: history.CALL_COUNT }, (_, index) => history.callId(label, index)),
+ );
+ assert.ok(calls.every((call) => call.args.delay_ms === 0));
+ assert.equal(calls[0].args.text, history.payload(label, 0));
+
+ let advanced = false;
+ const next = script.resolveInvocation(messages).then((value) => {
+ advanced = true;
+ return value;
+ });
+ await gates.wait('ready');
+ assert.equal(advanced, false, 'browser hydration cannot race task completion');
+ assert.equal(await gates.has('done'), false);
+ await gates.signal('advance');
+ const live = await next;
+ assert.equal(live.response, history.liveText(label));
+ assert.equal(live.toolCalls[0].id, history.callId(label, history.CALL_COUNT));
+ messages.push(...live.toolCalls.map(result));
+
+ let completed = false;
+ const final = script.resolveInvocation(messages).then((value) => {
+ completed = true;
+ return value;
+ });
+ await gates.wait('live');
+ assert.equal(completed, false, 'the new tool output is inspectable before completion');
+ await gates.signal('complete');
+ assert.equal((await final).response, history.completionText(label));
+ assert.equal(await gates.has('done'), true);
+ }
+});
+
+test('fixture refuses partial or truncated tool batches rather than reporting ready', async (t) => {
+ const { label, gates, script } = scenario(t);
+ const messages = [human(history.prompt(label))];
+ const first = await script.resolveInvocation(messages);
+ const results = first.toolCalls.map(result);
+ await assert.rejects(script.resolveInvocation([...messages, results[0]]), /lost MCP results/);
+ results[0].content = 'E2E slow echo: truncated';
+ await assert.rejects(script.resolveInvocation([...messages, ...results]), /lost MCP results/);
+ assert.equal(await gates.has('ready'), false);
+});
+
+test('fixture gates have bounded timeouts and honor cancellation', async (t) => {
+ const { gates } = scenario(t);
+ await assert.rejects(gates.wait('advance', { timeoutMs: 0 }), /timed out/);
+ const controller = new AbortController();
+ const waiting = gates.wait('complete', { signal: controller.signal });
+ controller.abort();
+ await assert.rejects(waiting, { name: 'AbortError' });
+ await gates.release();
+ assert.equal(await gates.has('advance'), true);
+ assert.equal(await gates.has('complete'), true);
+});
+
+test('fixture ignores unrelated prompts and rejects unsafe signal paths', () => {
+ assert.equal(history.responsesForText('E2E_SUBAGENT_ACTIVITY:one,two:existing', helpers), null);
+ assert.equal(history.responsesForText('E2E_REPLY:unchanged', helpers), null);
+ assert.throws(() => history.control('../other-lane'), /Invalid.*label/);
+});
+
+test('fake-model hook routes the history marker without changing ordinary replies', async () => {
+ class FakeChatModel {
+ constructor(options) {
+ Object.assign(this, options);
+ }
+ }
+ const dependencies = {
+ '@librechat/agents': { FakeChatModel },
+ '@langchain/core/outputs': { ChatGenerationChunk: class {} },
+ '@langchain/core/messages': { AIMessageChunk: class {} },
+ './model-replay': { tryBindReplay: () => false },
+ './run-files-model': { runFileDeliveryResponses: () => null },
+ './run-files-lifecycle-model': {
+ createRunFileLifecycleResponses: () => ({
+ responsesForText: () => null,
+ resolveInvocation: () => null,
+ isFixtureAgents: () => false,
+ }),
+ },
+ '../fixtures/subagent-history.cjs': history,
+ };
+ const sandbox = {
+ module: { exports: {} },
+ process: { env: {} },
+ require: (name) => {
+ assert.ok(Object.hasOwn(dependencies, name), `Unexpected hook dependency ${name}`);
+ return dependencies[name];
+ },
+ };
+ const source = await fs.readFile(path.resolve(__dirname, '../setup/fake-model.js'), 'utf8');
+ vm.runInNewContext(source, sandbox, { filename: 'fake-model.js' });
+ const hook = sandbox.module.exports;
+ const graph = {
+ overrideTestModel() {},
+ setSubagentModelOverride(model) {
+ this.childModel = model;
+ },
+ humanInTheLoop: {},
+ _subagentExecutors: [{ humanInTheLoop: {} }],
+ };
+ const messages = [human(history.prompt('hook-routing', 'agent_child'))];
+ hook({ Graph: graph }, { messages });
+ assert.equal(graph.childModel, graph.overrideModel);
+ assert.equal(graph.humanInTheLoop, undefined);
+ assert.equal(graph._subagentExecutors[0].humanInTheLoop, undefined);
+ const dispatch = await graph.overrideModel.resolveInvocation(messages);
+ assert.equal(dispatch.toolCalls[0].args.subagent_type, 'agent_child');
+ const child = await graph.childModel.resolveInvocation([
+ human(dispatch.toolCalls[0].args.description),
+ ]);
+ assert.equal(child.toolCalls.length, history.BATCH_SIZE);
+
+ hook({ Graph: graph }, { messages: [human('E2E_REPLY:ordinary')] });
+ assert.equal(graph.overrideModel.responses[0], 'E2E reply ordinary');
+});
+
+test('browser history worker uses an isolated endpoint with enough retained output budget', async () => {
+ const config = await fs.readFile(path.resolve(__dirname, '../config/librechat.e2e.yaml'), 'utf8');
+ const endpoint = config.match(/- name: 'Mock Retained History'\n(?:(?! - name:).|\n)*/)?.[0];
+ assert.ok(endpoint, 'history endpoint must remain available');
+ const retainedChars = Number(endpoint.match(/maxToolResultChars: (\d+)/)?.[1]);
+ assert.ok(retainedChars > history.output('retention-budget', 0).length);
+ assert.match(endpoint, /mock-retained-history/);
+ const browser = await fs.readFile(
+ path.resolve(__dirname, '../specs/mock/subagent-activity.spec.ts'),
+ 'utf8',
+ );
+ assert.match(browser, /provider: tools\?\.length \? 'Mock Retained History'/);
+});
+
+test('does not demand old full model context after a tool batch was already verified', async (t) => {
+ const { label, gates, script } = scenario(t);
+ const messages = [human(history.prompt(label))];
+ const first = await script.resolveInvocation(messages);
+ messages.push(...first.toolCalls.map(result));
+ const second = await script.resolveInvocation(messages);
+ // Simulate provider-only pruning, not deletion of stored/public UI history.
+ messages.splice(
+ 1,
+ messages.length - 1,
+ ...first.toolCalls.map((call) => ({
+ type: 'tool',
+ tool_call_id: call.id,
+ content: 'Earlier context shortened',
+ })),
+ ...second.toolCalls.map(result),
+ );
+ const third = await script.resolveInvocation(messages);
+ assert.equal(third.toolCalls[0].id, history.callId(label, 2 * history.BATCH_SIZE));
+ assert.equal(await gates.has('ready'), false);
+});
diff --git a/e2e/setup/fake-model.js b/e2e/setup/fake-model.js
index e324892d70..13222eca10 100644
--- a/e2e/setup/fake-model.js
+++ b/e2e/setup/fake-model.js
@@ -15,6 +15,7 @@ const { AIMessageChunk } = require('@langchain/core/messages');
const { tryBindReplay } = require('./model-replay');
const { runFileDeliveryResponses } = require('./run-files-model');
const { createRunFileLifecycleResponses } = require('./run-files-lifecycle-model');
+const subagentHistory = require('../fixtures/subagent-history.cjs');
const runFileLifecycle = createRunFileLifecycleResponses({
findLastToolMessage,
@@ -3530,6 +3531,13 @@ function codeExecResponses({ filename, toolCallId, finalText, code }, toolNames)
}
function resolveResponses({ graph, messages, text, toolNames }) {
+ const history = subagentHistory.responsesForText(text, {
+ getLatestUserText,
+ messageType,
+ getContentText,
+ });
+ if (history) return history;
+
const lifecycle = runFileLifecycle.responsesForText(text);
if (lifecycle) return lifecycle;
diff --git a/e2e/specs/mock/subagent-activity.spec.ts b/e2e/specs/mock/subagent-activity.spec.ts
index 479a24fafc..db3f2fdd1d 100644
--- a/e2e/specs/mock/subagent-activity.spec.ts
+++ b/e2e/specs/mock/subagent-activity.spec.ts
@@ -1,13 +1,18 @@
+import { rm } from 'node:fs/promises';
import { expect, test } from '@playwright/test';
-import type { Page } from '@playwright/test';
+import type { ParentSubagentIndex, SubagentThreadView, TMessage } from 'librechat-data-provider';
+import type { BrowserContext, Locator, Page } from '@playwright/test';
import type { AgentDetail } from './agents.helpers';
-import { cleanupAgent, openAgentBuilder, uniqueAgentName } from './agents.helpers';
import {
MOCK_ENDPOINTS,
getAccessToken,
+ messagesView,
requestJson,
+ sendMessage,
sendMessageAndWaitForCompletion,
} from './helpers';
+import { cleanupAgent, openAgentBuilder, uniqueAgentName } from './agents.helpers';
+import history from '../../fixtures/subagent-history.cjs';
const DETACHED_ACTIVITY_MARKER = 'E2E_SUBAGENT_ACTIVITY:';
/** The activity hook's first reconnect is scheduled after 500 ms. */
@@ -19,6 +24,7 @@ async function createAgent(
token: string,
name: string,
subagents?: AgentDetail['subagents'],
+ tools?: string[],
): Promise<AgentDetail> {
return requestJson<AgentDetail>(page, {
path: '/api/agents',
@@ -28,9 +34,11 @@ async function createAgent(
name,
description: 'Playwright verification of detached child activity.',
instructions: 'Follow the deterministic end-to-end request exactly.',
- provider: MOCK_ENDPOINTS[0].label,
- model: MOCK_ENDPOINTS[0].model,
+ provider: tools?.length ? 'Mock Retained History' : MOCK_ENDPOINTS[0].label,
+ model: tools?.length ? 'mock-retained-history' : MOCK_ENDPOINTS[0].model,
subagents,
+ tools,
+ ...(tools?.length ? { model_parameters: { maxContextTokens: 262_144 } } : {}),
},
});
}
@@ -154,3 +162,279 @@ test.describe('detached subagent activity', () => {
}
});
});
+
+const HISTORY_FOLDS =
+ '[data-fold-root] > div > button[aria-expanded="false"]:visible, ' +
+ '[data-testid="activity-phase-card"] > div > div > button[aria-expanded="false"]:visible';
+
+async function expandHistory(surface: Locator): Promise<void> {
+ for (let depth = 0; depth < 32; depth++) {
+ const collapsed = surface.locator(HISTORY_FOLDS);
+ if ((await collapsed.count()) === 0) return;
+ await collapsed.first().click();
+ }
+ await expect(surface.locator(HISTORY_FOLDS), 'history folds must be reachable').toHaveCount(0);
+}
+
+function historyRows(surface: Locator, label: string): Locator {
+ return surface.locator(
+ `[data-testid="tool-call"][data-tool-call-id^="call_e2e_history_${label}_"]`,
+ );
+}
+
+async function assertHistoryCalls(
+ surface: Locator,
+ label: string,
+ count = history.CALL_COUNT,
+): Promise<void> {
+ await expect
+ .poll(
+ async () => {
+ await expandHistory(surface);
+ return historyRows(surface, label).evaluateAll((rows) =>
+ rows.map((row) => row.getAttribute('data-tool-call-id')),
+ );
+ },
+ {
+ timeout: 20_000,
+ intervals: [100, 250, 500],
+ message: 'every retained call must appear once, in transcript order, not only the tail',
+ },
+ )
+ .toEqual(Array.from({ length: count }, (_, index) => history.callId(label, index)));
+}
+
+async function assertFullToolDetails(
+ surface: Locator,
+ label: string,
+ index: number,
+): Promise<void> {
+ const id = history.callId(label, index);
+ const row = surface.locator(`[data-testid="tool-call"][data-tool-call-id="${id}"]`);
+ const disclosure = row.getByRole('button').first();
+ await expect(row).toHaveCount(1);
+ if ((await disclosure.getAttribute('aria-expanded')) !== 'true') {
+ await disclosure.click();
+ }
+ const details = surface.locator(`[data-tool-call-output-id="${id}"]`);
+ await expect(details).toHaveCount(1);
+ await expect(details.locator('pre').first()).toHaveText(history.output(label, index));
+ const parameters = details.getByRole('button', { name: 'Parameters', exact: true });
+ if ((await parameters.getAttribute('aria-expanded')) !== 'true') {
+ await parameters.click();
+ }
+ await expect(details.getByText(history.payload(label, index), { exact: true })).toBeVisible();
+}
+
+async function openHistoryChild(page: Page, label: string): Promise<Locator> {
+ const card = page.locator(`[data-subagent-tool-call="${history.dispatchId(label)}"]`);
+ await expect
+ .poll(async () => {
+ await expandHistory(messagesView(page));
+ return card.isVisible();
+ })
+ .toBe(true);
+ await expect(card).toHaveCount(1);
+ await card.click();
+ const panel = page.getByRole('region', { name: 'Child agent activity' });
+ await expect(panel).toBeVisible();
+ return panel;
+}
+
+async function historyThreadPath(
+ page: Page,
+ token: string,
+ conversationId: string,
+ label: string,
+): Promise<string> {
+ const root = `/api/convos/${encodeURIComponent(conversationId)}/subagents`;
+ const index = await requestJson<ParentSubagentIndex>(page, { path: root, token });
+ const child = index.children.find(
+ (entry) => entry.parentToolCallId === history.dispatchId(label),
+ );
+ if (!child?.latestTaskId) throw new Error('History fixture has no durable child task');
+ const taskId = encodeURIComponent(child.latestTaskId);
+ return `${root}/${encodeURIComponent(child.threadId)}?taskId=${taskId}`;
+}
+
+test.describe('subagent chat retained-history parity', () => {
+ for (const mode of ['normal chat', 'late open', 'cold reload'] as const) {
+ const name = `${mode} restores over-capacity history while running and completes once`;
+ test(name, async ({ page, browser, baseURL }, testInfo) => {
+ test.setTimeout(120_000);
+ const prefix = `history-${mode.replaceAll(' ', '-')}`;
+ const label = `${prefix}-${Date.now().toString(36)}-${testInfo.retry}`;
+ const gates = history.control(label);
+ const createdAgentIds: string[] = [];
+ let coldContext: BrowserContext | undefined;
+ let activePage = page;
+ let activityRequests = 0;
+ page.on('request', (request) => {
+ if (ACTIVITY_PATH.test(new URL(request.url()).pathname)) activityRequests++;
+ });
+
+ try {
+ await page.addInitScript(() => localStorage.setItem('autoExpandTools', 'false'));
+ await page.goto('/c/new');
+ const token = await getAccessToken(page);
+ const worker = await createAgent(
+ page,
+ token,
+ uniqueAgentName('E2E History Worker'),
+ mode === 'normal chat' ? undefined : { enabled: true, allowSelf: true },
+ [history.TOOL_NAME],
+ );
+ createdAgentIds.push(worker.id);
+ await selectAgent(page, worker.name!);
+ const prompt = history.prompt(label, mode === 'normal chat' ? 'main' : 'self');
+ if (mode === 'normal chat') {
+ expect((await sendMessage(page, prompt)).ok()).toBeTruthy();
+ } else {
+ expect((await sendMessageAndWaitForCompletion(page, prompt)).ok()).toBeTruthy();
+ }
+ await expect(page).toHaveURL(/\/c\/(?!new(?:\/|$))[^/]+$/);
+ const conversationUrl = page.url();
+ const conversationId = decodeURIComponent(new URL(conversationUrl).pathname.split('/')[2]);
+ if (mode === 'cold reload') {
+ await openHistoryChild(page, label);
+ }
+ await gates.wait('ready', { timeoutMs: 45_000 });
+ expect(await gates.has('done'), 'task cannot finish before hydration').toBe(false);
+ if (mode === 'late open') {
+ expect(activityRequests, 'no child stream was opened before the ring overflowed').toBe(0);
+ }
+ if (mode === 'cold reload') {
+ await page
+ .getByRole('region', { name: 'Child agent activity' })
+ .getByRole('button', { name: 'Close', exact: true })
+ .click();
+ const storageState = await page.context().storageState();
+ await page.goto('/c/new');
+ // A new context removes query caches and live reducers, not just the mounted panel.
+ coldContext = await browser.newContext({ baseURL, storageState });
+ activePage = await coldContext.newPage();
+ await activePage.goto(conversationUrl);
+ }
+ const viewerToken = await getAccessToken(activePage);
+ const threadPath =
+ mode === 'normal chat'
+ ? undefined
+ : await historyThreadPath(activePage, viewerToken, conversationId, label);
+ if (threadPath) {
+ const running = await requestJson<SubagentThreadView>(activePage, {
+ path: threadPath,
+ token: viewerToken,
+ });
+ expect(running.status).toBe('running');
+ }
+ const startedAt = performance.now();
+ const surface =
+ mode === 'normal chat'
+ ? messagesView(activePage)
+ : await openHistoryChild(activePage, label);
+ await assertHistoryCalls(surface, label);
+ const hydrateMs = performance.now() - startedAt;
+ await expect(
+ surface.getByText(history.openingText(label), { exact: true }).first(),
+ ).toBeVisible();
+ for (let batch = 1; batch < history.CALL_COUNT / history.BATCH_SIZE; batch++) {
+ await expect(
+ surface.getByText(history.stepText(label, batch), { exact: true }).first(),
+ ).toBeVisible();
+ }
+ const detailsStartedAt = performance.now();
+ await assertFullToolDetails(surface, label, 0);
+ await assertFullToolDetails(surface, label, history.CALL_COUNT - 1);
+ const detailsMs = performance.now() - detailsStartedAt;
+ expect(
+ await gates.has('done'),
+ 'earliest full output is available while still running',
+ ).toBe(false);
+ // The same live phase primitive must wrap both surfaces, without a bespoke summary UI.
+ expect(await surface.getByTestId('activity-phase-card').count()).toBeGreaterThan(0);
+ await expect(surface.getByText(history.completionText(label), { exact: true })).toHaveCount(
+ 0,
+ );
+
+ await gates.signal('advance');
+ await gates.wait('live', { timeoutMs: 15_000 });
+ await assertHistoryCalls(surface, label, history.CALL_COUNT + 1);
+ await expect(
+ surface.getByText(history.liveText(label), { exact: true }).first(),
+ ).toBeVisible();
+ await assertFullToolDetails(surface, label, history.CALL_COUNT);
+ expect(
+ await gates.has('done'),
+ 'live continuation must not close the retained transcript',
+ ).toBe(false);
+ await gates.signal('complete');
+ await gates.wait('done', { timeoutMs: 10_000 });
+ await expect
+ .poll(
+ async () => {
+ if (threadPath) {
+ const terminal = await requestJson<SubagentThreadView>(activePage, {
+ path: threadPath,
+ token: viewerToken,
+ });
+ return terminal.status === 'completed';
+ }
+ const messages = await requestJson<TMessage[]>(activePage, {
+ path: `/api/messages/${encodeURIComponent(conversationId)}`,
+ token: viewerToken,
+ });
+ return messages.some(
+ (message) =>
+ message.isCreatedByUser === false &&
+ message.unfinished !== true &&
+ !message.error &&
+ JSON.stringify(message.content).includes(history.completionText(label)),
+ );
+ },
+ { timeout: 20_000, intervals: [100, 250, 500] },
+ )
+ .toBe(true);
+ await expect(surface.getByText(history.completionText(label), { exact: true })).toHaveCount(
+ 1,
+ { timeout: 20_000 },
+ );
+ await assertHistoryCalls(surface, label, history.CALL_COUNT + 1);
+ await assertFullToolDetails(surface, label, 0);
+
+ if (mode !== 'normal chat') {
+ await surface.getByRole('button', { name: 'Close', exact: true }).click();
+ }
+ await activePage.reload();
+ const restored =
+ mode === 'normal chat'
+ ? messagesView(activePage)
+ : await openHistoryChild(activePage, label);
+ await assertHistoryCalls(restored, label, history.CALL_COUNT + 1);
+ await assertFullToolDetails(restored, label, 0);
+ await expect(
+ restored.getByText(history.completionText(label), { exact: true }),
+ ).toHaveCount(1);
+ await testInfo.attach('history-parity-timings', {
+ contentType: 'application/json',
+ body: JSON.stringify({ mode, hydrateMs, detailsMs, historicalCalls: history.CALL_COUNT }),
+ });
+ } finally {
+ try {
+ await gates.release();
+ if (await gates.has('ready')) {
+ await gates.wait('done', { timeoutMs: 10_000 });
+ await rm(gates.directory, { recursive: true, force: true });
+ }
+ } finally {
+ try {
+ for (const agentId of createdAgentIds.reverse()) {
+ await cleanupAgent(page, agentId);
+ }
+ } finally {
+ await coldContext?.close();
+ }
+ }
+ }
+ });
+ }
+});
diff --git a/eslint-suppressions.json b/eslint-suppressions.json
index d0ade1c008..b9c20f336d 100644
--- a/eslint-suppressions.json
+++ b/eslint-suppressions.json
@@ -550,9 +550,6 @@
}
},
"client/src/components/Chat/Subagents/SubagentConversation.tsx": {
- "shadcn/no-restyle": {
- "count": 4
- },
"shadcn/require-static-classes": {
"count": 1
}
diff --git a/packages/api/src/agents/index.ts b/packages/api/src/agents/index.ts
index b3270f56a0..5b85cc6d1c 100644
--- a/packages/api/src/agents/index.ts
+++ b/packages/api/src/agents/index.ts
@@ -61,6 +61,7 @@ export * from './stepBudget';
export * from './startup';
export * from './subagentThreads';
export * from './subagentActivity';
+export * from './subagentContent';
export * from './subagentIdentity';
export * from './subagentCompletionWakeup';
export * from './subagentTaskRouting';
diff --git a/packages/api/src/agents/subagentActivity.spec.ts b/packages/api/src/agents/subagentActivity.spec.ts
index ecd0daf68f..a545c5f186 100644
--- a/packages/api/src/agents/subagentActivity.spec.ts
+++ b/packages/api/src/agents/subagentActivity.spec.ts
@@ -384,6 +384,29 @@ describe('detached subagent activity stream', () => {
});
});
+ it('publishes committed content invalidations in a separate sequence space', async () => {
+ const transport = new TestTransport();
+ const stream = new SubagentActivityStream(transport);
+ const onContent = jest.fn();
+ const subscription = stream.subscribe('child-thread', 'task-1', {
+ onEvent: jest.fn(),
+ onContent,
+ });
+ await subscription.ready;
+ const watermark = { taskId: 'task-1', throughSequence: 150, revision: 3 };
+ await stream.publishContent('child-thread', 'task-1', watermark);
+ expect(onContent).toHaveBeenCalledWith({
+ event: 'subagent_content_available',
+ data: watermark,
+ });
+ expect(transport.emitted[0].streamId).toBe(
+ `${subagentActivityStreamId('child-thread', 'task-1')}:content`,
+ );
+ subscription.unsubscribe();
+ await Promise.resolve();
+ expect(transport.handlers.size).toBe(0);
+ });
+
it('delivers terminal state before the subscriber releases its task stream', async () => {
const transport = new TestTransport();
const stream = new SubagentActivityStream(transport);
@@ -558,7 +581,7 @@ describe('subagent activity stream authorization', () => {
expect(res.chunks.join('')).toContain('"ready":true');
expect(res.chunks.join('')).not.toContain('"final":true');
- expect(transport.handlers.size).toBe(1);
+ expect(transport.handlers.size).toBe(2);
res.emit('close');
});
diff --git a/packages/api/src/agents/subagentActivity.ts b/packages/api/src/agents/subagentActivity.ts
index 3501de1ef0..9cb8b7fcdf 100644
--- a/packages/api/src/agents/subagentActivity.ts
+++ b/packages/api/src/agents/subagentActivity.ts
@@ -1,8 +1,12 @@
import { logger } from '@librechat/data-schemas';
import { createHash, randomUUID } from 'node:crypto';
import { subagentActivityConfigSchema } from 'librechat-data-provider';
+import type {
+ TSubagentActivityConfig,
+ SubagentContentAvailableFrame,
+ SubagentContentWatermark,
+} 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';
@@ -49,6 +53,7 @@ export type SubagentActivitySubscription = {
};
export type SubagentActivitySubscriber = {
+ onContent?: (event: SubagentContentAvailableFrame) => void;
onEvent: (event: SubagentActivityEnvelope | SubagentActivityReplayEnvelope) => void;
onDone?: (event: {
final: true;
@@ -255,6 +260,29 @@ export class SubagentActivityStream {
await emitObservedChunk(this.transport, streamId, envelope);
}
+ /** Tiny invalidations have their own sequence space and never evict activity replay. */
+ async publishContent(
+ threadId: string,
+ taskId: string,
+ watermark: SubagentContentWatermark,
+ ): Promise<void> {
+ const streamId = `${subagentActivityStreamId(threadId, taskId)}:content`;
+ const event: SubagentContentAvailableFrame = {
+ event: 'subagent_content_available',
+ data: watermark,
+ };
+ if (this.transport.emitReplayableChunk != null) {
+ await this.transport.emitReplayableChunk(
+ streamId,
+ event,
+ { ...this.replayLimits, items: 1, bytes: 1024 },
+ { id: `content:${watermark.revision}` },
+ );
+ return;
+ }
+ await emitObservedChunk(this.transport, streamId, event);
+ }
+
subscribe(
threadId: string,
taskId: string,
@@ -307,6 +335,19 @@ export class SubagentActivityStream {
captureSequenceFrontier: synchronizeAttachment,
},
);
+ const contentStreamId = `${streamId}:content`;
+ const onContent = (value: unknown): void => {
+ const frame = value as SubagentContentAvailableFrame | null;
+ if (frame?.event === 'subagent_content_available') subscriber.onContent?.(frame);
+ };
+ const contentSubscription =
+ subscriber.onContent == null
+ ? undefined
+ : this.transport.subscribe(
+ contentStreamId,
+ { onChunk: onContent, onReplay: (events) => events.forEach(onContent) },
+ replayable ? { replay: { ...this.replayLimits, items: 1, bytes: 1024 } } : undefined,
+ );
let closed = false;
let demandHeartbeat: ReturnType<typeof setInterval> | undefined;
unsubscribe = () => {
@@ -314,9 +355,13 @@ export class SubagentActivityStream {
closed = true;
if (demandHeartbeat != null) clearInterval(demandHeartbeat);
subscription.unsubscribe();
+ contentSubscription?.unsubscribe();
+ if (contentSubscription != null && this.transport.getSubscriberCount(contentStreamId) === 0) {
+ this.transport.cleanup(contentStreamId);
+ }
cleanupIfIdle();
};
- const ready = Promise.resolve(subscription.ready).then(async () => {
+ const ready = Promise.all([subscription.ready, contentSubscription?.ready]).then(async () => {
if (synchronizeAttachment) {
/** The attachment that deferred the shared buffer owns synchronization even if
* its panel closes meanwhile; a surviving local subscriber still needs release. */
@@ -624,6 +669,7 @@ export function createSubagentActivityStreamHandler(
heartbeat.unref?.();
try {
subscription = stream.subscribe(threadId, taskId, {
+ onContent: (event) => writer?.send(event),
onEvent: (event) => {
writer?.send(
publicActivityEnvelope(
@@ -669,7 +715,7 @@ export function createSubagentActivityStreamHandler(
);
return;
}
- writer.send({ ready: true });
+ writer.send({ ready: true, contentRecovery: true });
} catch (error) {
if (closed || res.destroyed) return;
logger.error('[subagentActivity] Failed to open child activity stream', error);
diff --git a/packages/api/src/agents/subagentContent.integration.spec.ts b/packages/api/src/agents/subagentContent.integration.spec.ts
new file mode 100644
index 0000000000..0f47aa2531
--- /dev/null
+++ b/packages/api/src/agents/subagentContent.integration.spec.ts
@@ -0,0 +1,1295 @@
+import express from 'express';
+import request from 'supertest';
+import mongoose from 'mongoose';
+import { createHash, randomUUID } from 'node:crypto';
+import { MongoMemoryServer } from 'mongodb-memory-server';
+import { createMethods, createModels } from '@librechat/data-schemas';
+import type { AllMethods, IMessage, SubagentContentScope } from '@librechat/data-schemas';
+import type { SubagentTaskRuntime, SubagentUpdateEvent } from '@librechat/agents';
+import type { ServerRequest } from '~/types';
+import {
+ SubagentContentJournal,
+ createSubagentTaskContentHandler,
+ readSubagentContent,
+} from './subagentContent';
+import { buildSubagentThreadTaskConfig, SubagentThreadTaskStore } from './subagentThreads';
+
+let mongo: MongoMemoryServer;
+let methods: AllMethods;
+const stores: SubagentThreadTaskStore[] = [];
+
+beforeAll(async () => {
+ mongo = await MongoMemoryServer.create({ instance: { args: ['--nounixsocket'] } });
+ createModels(mongoose);
+ await mongoose.connect(mongo.getUri());
+ methods = createMethods(mongoose);
+ await Promise.all(
+ ['Message', 'SubagentContent'].map((name) => mongoose.models[name].createIndexes()),
+ );
+});
+afterEach(async () => {
+ await Promise.all(
+ stores.splice(0).map(async (store) => {
+ await store.destroyTaskControlTransport();
+ store.destroyActivityStream();
+ }),
+ );
+ await Promise.all(
+ ['Conversation', 'Message', 'SubagentContent'].map((name) =>
+ mongoose.models[name].deleteMany({}),
+ ),
+ );
+});
+afterAll(async () => {
+ await mongoose.disconnect();
+ await mongo.stop();
+});
+
+const progress = (phase: SubagentUpdateEvent['phase'], data: unknown): SubagentUpdateEvent => ({
+ runId: 'root',
+ parentRunId: 'parent-run',
+ subagentRunId: 'execution',
+ subagentType: 'researcher',
+ subagentKind: 'agent',
+ subagentAgentId: 'researcher',
+ parentToolCallId: 'dispatch',
+ phase,
+ data,
+ timestamp: new Date().toISOString(),
+});
+
+async function until(predicate: () => Promise<boolean>): Promise<void> {
+ const deadline = Date.now() + 10_000;
+ while (!(await predicate())) {
+ if (Date.now() > deadline) throw new Error('Timed out waiting for content persistence');
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ }
+}
+
+async function runningTask(
+ run: (runtime: SubagentTaskRuntime) => Promise<{ content: string }>,
+ contentSettlementTimeoutMs = 1000,
+) {
+ const user = 'content-owner';
+ const parentConversationId = randomUUID();
+ await methods.saveConvo(
+ { userId: user },
+ { conversationId: parentConversationId, title: 'Parent' },
+ );
+ const store = new SubagentThreadTaskStore(methods, {
+ activity: { contentRecoveryEnabled: true, contentFlushMs: 10, contentSettlementTimeoutMs },
+ });
+ stores.push(store);
+ const config = buildSubagentThreadTaskConfig(store, { userId: user, parentConversationId });
+ const started = store.start({
+ scopeId: config.scopeId,
+ idempotencyKey: randomUUID(),
+ parentRunId: randomUUID(),
+ parentAgentId: 'parent-agent',
+ parentToolCallId: randomUUID(),
+ input: 'Investigate',
+ subagentKind: 'agent',
+ subagentType: 'researcher',
+ run,
+ });
+ if (!started.accepted || started.task.threadId == null) throw new Error('Task rejected');
+ const scope: SubagentContentScope = {
+ user,
+ parentConversationId,
+ conversationId: started.task.threadId,
+ taskId: started.task.taskId,
+ };
+ return { store, scope, scopeId: config.scopeId };
+}
+
+function appFor(
+ scope: SubagentContentScope,
+ user: string | null = scope.user,
+ tenantId?: string,
+ recoveryGraceMs = 30_000,
+) {
+ const app = express();
+ app.use((req, _res, next) => {
+ if (user != null) {
+ (req as ServerRequest).user = { id: user, tenantId } as ServerRequest['user'];
+ }
+ next();
+ });
+ const handler = createSubagentTaskContentHandler(methods, undefined, () => recoveryGraceMs);
+ app.get(
+ '/api/convos/:parentConversationId/subagents/:threadId/tasks/:taskId/content',
+ (req, res) => handler(req as ServerRequest, res),
+ );
+ const url = `/api/convos/${scope.parentConversationId}/subagents/${scope.conversationId}/tasks/${scope.taskId}/content`;
+ return { app, url };
+}
+
+it('cold-opens >100 public events and large arguments/output without running work again, then hands off terminal content', async () => {
+ let finish: (value: { content: string }) => void = () => undefined;
+ const result = new Promise<{ content: string }>((resolve) => {
+ finish = resolve;
+ });
+ let executions = 0;
+ const output = 'whole tool body '.repeat(30_000);
+ const args = { query: 'full arguments '.repeat(10_000) };
+ const { scope, store, scopeId } = await runningTask(async (runtime) => {
+ executions++;
+ runtime.reportProgress(
+ progress('run_step', {
+ id: 'message-step',
+ index: 0,
+ type: 'message_creation',
+ stepDetails: {
+ type: 'message_creation',
+ message_creation: { message_id: 'visible-message' },
+ },
+ }),
+ );
+ for (let index = 0; index < 150; index++) {
+ runtime.reportProgress(
+ progress('message_delta', {
+ id: 'message-step',
+ delta: { content: [{ type: 'text', text: `${index},` }] },
+ }),
+ );
+ }
+ runtime.reportProgress(
+ progress('run_step', {
+ id: 'tool-step',
+ index: 1,
+ type: 'tool_calls',
+ stepDetails: {
+ type: 'tool_calls',
+ tool_calls: [{ id: 'call-1', type: 'tool_call', name: 'lookup', args }],
+ },
+ }),
+ );
+ runtime.reportProgress(
+ progress('run_step_completed', {
+ result: {
+ id: 'tool-step',
+ type: 'tool_call',
+ tool_call: { id: 'call-1', name: 'lookup', args, output, progress: 1 },
+ },
+ }),
+ );
+ return result;
+ });
+ await until(async () => (await methods.getSubagentContentHead(scope))?.throughSequence === 152);
+ const { app, url } = appFor(scope);
+ const opened = await request(app).get(url).expect(200);
+ expect(opened.body).toMatchObject({
+ mode: 'snapshot',
+ status: 'running',
+ recovery: 'partial',
+ targetThroughSequence: 152,
+ messageId: `${scope.taskId}:assistant`,
+ parentMessageId: `${scope.taskId}:user`,
+ });
+ expect(JSON.stringify(opened.body.content)).toContain('0,1,2,');
+ expect(JSON.stringify(opened.body.content)).toContain('148,149,');
+ expect(opened.body.nextCursor).toBeDefined();
+ const suffix = await request(app)
+ .get(`${url}?cursor=${encodeURIComponent(opened.body.nextCursor)}`)
+ .expect(200);
+ expect(suffix.body).toMatchObject({
+ mode: 'suffix',
+ throughSequence: 152,
+ targetThroughSequence: 152,
+ });
+ expect(suffix.body.events.at(-1).frame.data.result.tool_call.output).toBe(output);
+ expect(JSON.stringify(opened.body.content)).toContain(args.query);
+ expect(opened.body.runSteps.map((step: { id: string }) => step.id)).toEqual([
+ 'message-step',
+ 'tool-step',
+ ]);
+ expect(executions).toBe(1);
+ expect(JSON.stringify(opened.body)).not.toContain('subagentTranscript');
+ finish({ content: 'Done' });
+ await until(async () => store.get(scopeId, scope.taskId)?.status === 'completed');
+ const terminal = await request(app).get(url).expect(200);
+ expect(terminal.body).toMatchObject({
+ status: 'completed',
+ recovery: 'complete',
+ targetThroughSequence: 152,
+ });
+ expect(terminal.body.content).toEqual(opened.body.content);
+ expect(await store.claimTask(scopeId, scope.taskId)).toMatchObject({
+ status: 'completed',
+ result: 'Done',
+ });
+ expect(executions).toBe(1);
+});
+
+it('denies owner, parent, tenant and missing-task access before journal reads', async () => {
+ const { scope } = await runningTask(async () => ({ content: 'Done' }));
+ const read = jest.spyOn(methods, 'getSubagentContentHead');
+ const anonymous = appFor(scope, null);
+ await request(anonymous.app).get(anonymous.url).expect(404);
+ const unauthorized = appFor(scope, 'other-owner');
+ await request(unauthorized.app).get(unauthorized.url).expect(404);
+ const foreignTenant = appFor(scope, scope.user, 'other-tenant');
+ await request(foreignTenant.app).get(foreignTenant.url).expect(404);
+ const wrongParent = appFor({ ...scope, parentConversationId: randomUUID() });
+ await request(wrongParent.app).get(wrongParent.url).expect(404);
+ const missingTask = appFor({ ...scope, taskId: 'missing' });
+ await request(missingTask.app).get(missingTask.url).expect(404);
+ expect(read).not.toHaveBeenCalled();
+ read.mockRestore();
+});
+
+it('keeps a snapshot at its sampled revision and returns the racing suffix exactly once', async () => {
+ let release: (value: { content: string }) => void = () => undefined;
+ const running = new Promise<{ content: string }>((resolve) => {
+ release = resolve;
+ });
+ const { scope } = await runningTask(async () => running);
+ await until(
+ async () =>
+ (await methods.getMessages({ user: scope.user, conversationId: scope.conversationId }))
+ .length > 0,
+ );
+ const journal = new SubagentContentJournal({
+ scope,
+ flushMs: 10_000,
+ batchBytes: 1_000_000,
+ append: methods.appendSubagentContentBatch,
+ notify: async () => undefined,
+ onError: () => undefined,
+ });
+ const delta = (text: string) =>
+ progress('message_delta', { id: 's', delta: { content: [{ type: 'text', text }] } });
+ journal.record(delta('first'), 0);
+ await journal.flush();
+ const sampled = await methods.getSubagentContentHead(scope);
+ journal.record(delta('second'), 1);
+ await journal.flush();
+ const snapshot = await readSubagentContent(
+ { ...methods, getSubagentContentHead: async () => sampled },
+ scope,
+ );
+ expect(snapshot).toMatchObject({ ok: true, value: { revision: 1, throughSequence: 0 } });
+ const suffix = await readSubagentContent(methods, scope, 0);
+ expect(suffix).toMatchObject({
+ ok: true,
+ value: { revision: 2, throughSequence: 1, events: [{ sequence: 1 }] },
+ });
+ expect(suffix.ok && suffix.value.events).toHaveLength(1);
+ expect(await readSubagentContent(methods, scope, 1)).toMatchObject({
+ ok: true,
+ value: { events: [] },
+ });
+ expect(await readSubagentContent(methods, scope, 2)).toMatchObject({
+ ok: false,
+ error: { code: 'SUBAGENT_CONTENT_AHEAD' },
+ });
+ await journal.close();
+ release({ content: 'Done' });
+});
+
+it('pins paged suffixes to the original revision without losing or repeating events', async () => {
+ let release: (value: { content: string }) => void = () => undefined;
+ const running = new Promise<{ content: string }>((resolve) => {
+ release = resolve;
+ });
+ const { scope } = await runningTask(async () => running);
+ await until(
+ async () =>
+ (await methods.getMessages({ user: scope.user, conversationId: scope.conversationId }))
+ .length > 0,
+ );
+ const journal = new SubagentContentJournal({
+ scope,
+ flushMs: 10_000,
+ batchBytes: 1024,
+ append: methods.appendSubagentContentBatch,
+ notify: async () => undefined,
+ onError: () => undefined,
+ });
+ for (let sequence = 0; sequence < 40; sequence++) {
+ journal.record(
+ progress('message_delta', {
+ id: 's',
+ delta: { content: [{ type: 'text', text: `${sequence}:${'x'.repeat(200)}` }] },
+ }),
+ sequence,
+ );
+ }
+ await journal.flush();
+ const first = await readSubagentContent(methods, scope, -1, { pageBytes: 1024 });
+ if (!first.ok) throw new Error('Expected first page');
+ const sequences = first.value.events.map((event) => event.sequence);
+ let cursor = first.value.nextCursor;
+ journal.record(
+ progress('message_delta', {
+ id: 's',
+ delta: { content: [{ type: 'text', text: 'racing suffix' }] },
+ }),
+ 40,
+ );
+ await journal.flush();
+ while (cursor != null) {
+ const pin: { afterSequence: number; throughRevision: number } = JSON.parse(
+ Buffer.from(cursor, 'base64url').toString('utf8'),
+ );
+ const page = await readSubagentContent(methods, scope, pin.afterSequence, {
+ pageBytes: 1024,
+ throughRevision: pin.throughRevision,
+ });
+ if (!page.ok) throw new Error('Expected suffix page');
+ sequences.push(...page.value.events.map((event) => event.sequence));
+ cursor = page.value.nextCursor;
+ }
+ expect(sequences).toEqual(Array.from({ length: 40 }, (_, index) => index));
+ expect(await readSubagentContent(methods, scope, 39)).toMatchObject({
+ ok: true,
+ value: { events: [{ sequence: 40 }] },
+ });
+ await journal.close();
+ release({ content: 'Done' });
+});
+
+it('retains failed-batch bytes for retry and reports a missing committed range instead of plausible empty history', async () => {
+ let release: (value: { content: string }) => void = () => undefined;
+ const running = new Promise<{ content: string }>((resolve) => {
+ release = resolve;
+ });
+ const { scope } = await runningTask(async () => running);
+ await until(
+ async () =>
+ (await methods.getMessages({ user: scope.user, conversationId: scope.conversationId }))
+ .length > 0,
+ );
+ const append = jest
+ .fn(methods.appendSubagentContentBatch)
+ .mockRejectedValueOnce(new Error('database unavailable'));
+ const journal = new SubagentContentJournal({
+ scope,
+ flushMs: 10_000,
+ batchBytes: 1_000_000,
+ append,
+ notify: async () => undefined,
+ onError: () => undefined,
+ });
+ journal.record(
+ progress('message_delta', {
+ id: 's',
+ delta: { content: [{ type: 'text', text: 'retained' }] },
+ }),
+ 0,
+ );
+ await expect(journal.flush()).rejects.toThrow('database unavailable');
+ await expect(journal.flush()).resolves.toEqual({ ok: true });
+ expect(append.mock.calls[0][0].eventsJson).toBe(append.mock.calls[1][0].eventsJson);
+ expect(append.mock.calls[1][0].revision).toBe(1);
+ await mongoose.models.SubagentContent.deleteMany({ taskId: scope.taskId, fragment: { $gte: 0 } });
+ await expect(readSubagentContent(methods, scope)).rejects.toThrow('Incomplete committed');
+ await journal.close();
+ release({ content: 'Done' });
+});
+
+it('returns a typed gap when an indexed suffix seek passes a missing committed revision', async () => {
+ const scope: SubagentContentScope = {
+ user: 'gap-owner',
+ parentConversationId: randomUUID(),
+ conversationId: randomUUID(),
+ taskId: randomUUID(),
+ };
+ const records = [0, 1, 2].flatMap((sequence) => {
+ const payload = JSON.stringify([{ sequence, frame: { event: 'on_message_delta', data: {} } }]);
+ const base = {
+ ...scope,
+ revision: sequence + 1,
+ fromSequence: sequence,
+ throughSequence: sequence,
+ fragments: 1,
+ digest: createHash('sha256').update(payload).digest('hex'),
+ };
+ return [
+ { ...base, _id: randomUUID(), fragment: -1 },
+ { ...base, _id: randomUUID(), fragment: 0, payload },
+ ];
+ });
+ await mongoose.models.SubagentContent.create(records);
+ await mongoose.models.SubagentContent.deleteMany({ ...scope, revision: 2 });
+ expect(await readSubagentContent(methods, scope, 0)).toEqual({
+ ok: false,
+ error: { code: 'SUBAGENT_CONTENT_GAP' },
+ });
+});
+
+it('expires and deletes task journals with the owning messages, without resurrecting deleted work', async () => {
+ const { scope, store, scopeId } = await runningTask(async (runtime) => {
+ runtime.reportProgress(
+ progress('message_delta', {
+ id: 's',
+ delta: { content: [{ type: 'text', text: 'visible' }] },
+ }),
+ );
+ return { content: 'Done' };
+ });
+ await until(async () => store.get(scopeId, scope.taskId)?.status === 'completed');
+ expect(await methods.getSubagentContentHead(scope)).not.toBeNull();
+ const { app, url } = appFor(scope);
+ await mongoose.models.Message.updateMany(
+ { conversationId: scope.conversationId },
+ { $set: { expiredAt: new Date(0) } },
+ );
+ await request(app).get(url).expect(404);
+ await methods.deleteMessages({ user: scope.user, conversationId: scope.conversationId });
+ expect(await mongoose.models.SubagentContent.countDocuments({ taskId: scope.taskId })).toBe(0);
+ expect(
+ await methods.appendSubagentContentBatch({
+ ...scope,
+ revision: 2,
+ fromSequence: 1,
+ throughSequence: 1,
+ eventsJson: '[]',
+ }),
+ ).toEqual({ ok: false, error: { code: 'SUBAGENT_CONTENT_GONE' } });
+ await request(app).get(url).expect(404);
+});
+
+it('keeps partial public content on task failure and never discloses a recovery exception', async () => {
+ const { scope, store, scopeId } = await runningTask(async (runtime) => {
+ runtime.reportProgress(
+ progress('run_step', {
+ id: 's',
+ index: 0,
+ type: 'message_creation',
+ stepDetails: { type: 'message_creation', message_creation: { message_id: 'visible' } },
+ }),
+ );
+ runtime.reportProgress(
+ progress('message_delta', {
+ id: 's',
+ delta: { content: [{ type: 'text', text: 'Partial work' }] },
+ }),
+ );
+ throw new Error('provider failure');
+ });
+ await until(async () => store.get(scopeId, scope.taskId)?.status === 'error');
+ const { app, url } = appFor(scope);
+ const partial = await request(app).get(url).expect(200);
+ expect(partial.body).toMatchObject({
+ status: 'failed',
+ throughSequence: 1,
+ recovery: 'complete',
+ });
+ expect(JSON.stringify(partial.body.content)).toContain('Partial work');
+ const read = jest
+ .spyOn(methods, 'getSubagentContentHead')
+ .mockRejectedValueOnce(new Error('private database payload'));
+ const failed = await request(app).get(url).expect(503);
+ expect(failed.body).toEqual({
+ error: 'Subagent content unavailable',
+ code: 'SUBAGENT_CONTENT_UNAVAILABLE',
+ });
+ expect(JSON.stringify(failed.body)).not.toContain('private');
+ read.mockRestore();
+});
+
+it('settles the child result and releases ownership when final content persistence stalls', async () => {
+ let release: () => void = () => undefined;
+ const pending = new Promise<{ ok: false; error: { code: 'SUBAGENT_CONTENT_GONE' } }>(
+ (resolve) => {
+ release = () => resolve({ ok: false, error: { code: 'SUBAGENT_CONTENT_GONE' } });
+ },
+ );
+ const append = jest
+ .spyOn(methods, 'appendSubagentContentBatch')
+ .mockImplementation(() => pending);
+ try {
+ const { scope, store, scopeId } = await runningTask(async (runtime) => {
+ runtime.reportProgress(
+ progress('message_delta', {
+ id: 's',
+ delta: { content: [{ type: 'text', text: 'Partial capture' }] },
+ }),
+ );
+ return { content: 'Durable task result' };
+ }, 100);
+ await until(async () => store.get(scopeId, scope.taskId)?.status === 'completed');
+ expect(store.isThreadActiveForOwner(scope.user, scope.conversationId)).toBe(false);
+ const terminal = (
+ await methods.getMessages(
+ { user: scope.user, conversationId: scope.conversationId },
+ '+subagentContent',
+ )
+ ).find((message) => message.messageId === `${scope.taskId}:assistant`);
+ expect(terminal).toMatchObject({
+ text: 'Durable task result',
+ subagentContent: { version: 1, throughSequence: 0 },
+ });
+ const { app, url } = appFor(scope);
+ const response = await request(app).get(url).expect(200);
+ expect(response.body).toMatchObject({
+ status: 'completed',
+ recovery: 'partial',
+ throughSequence: -1,
+ });
+ const retryUntil = response.body.retryUntil;
+ expect(retryUntil).toBeGreaterThan(Date.now());
+ const repeated = await request(app).get(url).expect(200);
+ expect(repeated.body.retryUntil).toBe(retryUntil);
+ const disabled = appFor(scope, scope.user, undefined, 0);
+ const noGrace = await request(disabled.app).get(disabled.url).expect(200);
+ expect(noGrace.body).not.toHaveProperty('retryUntil');
+ await mongoose.models.Message.updateOne(
+ { user: scope.user, messageId: `${scope.taskId}:assistant` },
+ { $set: { createdAt: new Date(0) } },
+ { overwriteImmutable: true, timestamps: false },
+ );
+ const expired = await request(app).get(url).expect(200);
+ expect(expired.body).not.toHaveProperty('retryUntil');
+ expect(await store.claimTask(scopeId, scope.taskId)).toMatchObject({
+ status: 'completed',
+ result: 'Durable task result',
+ });
+ } finally {
+ release();
+ append.mockRestore();
+ }
+});
+
+it('preserves the committed prefix when the timed-out final database append finishes after lease release', async () => {
+ const appends: Array<ReturnType<typeof methods.appendSubagentContentBatch>> = [];
+ const appendContent = methods.appendSubagentContentBatch;
+ const observeAppend = jest
+ .spyOn(methods, 'appendSubagentContentBatch')
+ .mockImplementation((input) => {
+ const operation = appendContent(input);
+ appends.push(operation);
+ return operation;
+ });
+ let finish: () => void = () => undefined;
+ const finished = new Promise<void>((resolve) => {
+ finish = resolve;
+ });
+ const { scope, store, scopeId } = await runningTask(async (runtime) => {
+ runtime.reportProgress(
+ progress('run_step', {
+ id: 'text',
+ index: 0,
+ stepDetails: {
+ type: 'message_creation',
+ message_creation: { message_id: 'retained' },
+ },
+ }),
+ );
+ runtime.reportProgress(
+ progress('message_delta', {
+ id: 'text',
+ delta: { content: [{ type: 'text', text: 'Retained prefix. ' }] },
+ }),
+ );
+ await finished;
+ runtime.reportProgress(
+ progress('message_delta', {
+ id: 'text',
+ delta: { content: [{ type: 'text', text: 'Late suffix.' }] },
+ }),
+ );
+ return { content: 'Durable result' };
+ }, 100);
+ await until(async () => (await methods.getSubagentContentHead(scope))?.throughSequence === 1);
+ const prefix = await methods.getSubagentContentHead(scope);
+ const collection = mongoose.models.SubagentContent.collection;
+ const bulkWrite = collection.bulkWrite.bind(collection);
+ let release: () => void = () => undefined;
+ const released = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ let completed: () => void = () => undefined;
+ const completion = new Promise<void>((resolve) => {
+ completed = resolve;
+ });
+ const pending = jest.spyOn(collection, 'bulkWrite').mockImplementation(async (...args) => {
+ await released;
+ try {
+ return await bulkWrite(...args);
+ } finally {
+ completed();
+ }
+ });
+ try {
+ finish();
+ await until(async () => store.get(scopeId, scope.taskId)?.status === 'completed');
+ expect(store.isThreadActiveForOwner(scope.user, scope.conversationId)).toBe(false);
+ expect(await methods.getSubagentContentHead(scope)).toEqual(prefix);
+ release();
+ await completion;
+ await Promise.all(appends);
+ expect(await methods.getSubagentContentHead(scope)).toMatchObject({ throughSequence: 2 });
+ const recovered = await readSubagentContent(methods, scope);
+ expect(recovered).toMatchObject({
+ ok: true,
+ value: {
+ throughSequence: 2,
+ content: [{ type: 'text', text: 'Retained prefix. Late suffix.' }],
+ },
+ });
+ expect(await store.claimTask(scopeId, scope.taskId)).toMatchObject({
+ status: 'completed',
+ result: 'Durable result',
+ });
+ } finally {
+ finish();
+ release();
+ pending.mockRestore();
+ observeAppend.mockRestore();
+ }
+});
+
+it.each(['deleted', 'expired'] as const)(
+ 'removes in-flight content when the retained child is %s, not merely settled',
+ async (lifetime) => {
+ let finish: () => void = () => undefined;
+ const finished = new Promise<void>((resolve) => {
+ finish = resolve;
+ });
+ const { scope } = await runningTask(async () => {
+ await finished;
+ return { content: 'Done' };
+ });
+ await until(
+ async () =>
+ (
+ await methods.getMessages({
+ user: scope.user,
+ conversationId: scope.conversationId,
+ })
+ ).length > 0,
+ );
+ const first = await methods.appendSubagentContentBatch({
+ ...scope,
+ revision: 1,
+ fromSequence: 0,
+ throughSequence: 0,
+ eventsJson: '[]',
+ });
+ expect(first).toEqual({ ok: true });
+ const collection = mongoose.models.SubagentContent.collection;
+ const bulkWrite = collection.bulkWrite.bind(collection);
+ let release: () => void = () => undefined;
+ const released = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ let started: () => void = () => undefined;
+ const entering = new Promise<void>((resolve) => {
+ started = resolve;
+ });
+ const pending = jest.spyOn(collection, 'bulkWrite').mockImplementation(async (...args) => {
+ started();
+ await released;
+ return bulkWrite(...args);
+ });
+ const late = methods.appendSubagentContentBatch({
+ ...scope,
+ revision: 2,
+ fromSequence: 1,
+ throughSequence: 1,
+ eventsJson: '[]',
+ });
+ try {
+ await entering;
+ const conversation = mongoose.models.Conversation;
+ const filter = { user: scope.user, conversationId: scope.conversationId };
+ if (lifetime === 'deleted') await conversation.deleteOne(filter);
+ else await conversation.updateOne(filter, { $set: { expiredAt: new Date(0) } });
+ release();
+ expect(await late).toEqual({ ok: false, error: { code: 'SUBAGENT_CONTENT_GONE' } });
+ expect(await mongoose.models.SubagentContent.countDocuments({ taskId: scope.taskId })).toBe(
+ 0,
+ );
+ } finally {
+ release();
+ await late;
+ pending.mockRestore();
+ finish();
+ }
+ },
+);
+
+describe('selective task content deletion', () => {
+ const batch = { revision: 1, fromSequence: 0, throughSequence: 0, eventsJson: '[]' };
+ const nextBatch = { ...batch, revision: 2, fromSequence: 1, throughSequence: 1 };
+ const gone = { ok: false, error: { code: 'SUBAGENT_CONTENT_GONE' } };
+ type Selection = 'user' | 'assistant' | 'both';
+
+ const owner = (scope: SubagentContentScope) => ({
+ user: scope.user,
+ tenantId: scope.tenantId ?? { $exists: false },
+ });
+ const sourceFilter = (scope: SubagentContentScope, selection: Selection) => ({
+ ...owner(scope),
+ conversationId: scope.conversationId,
+ messageId:
+ selection === 'both'
+ ? { $in: [`${scope.taskId}:user`, `${scope.taskId}:assistant`] }
+ : `${scope.taskId}:${selection}`,
+ });
+ const journalFilter = (scope: SubagentContentScope) => ({
+ ...owner(scope),
+ conversationId: scope.conversationId,
+ taskId: scope.taskId,
+ });
+
+ async function seedTask(tenantId?: string): Promise<SubagentContentScope> {
+ const scope: SubagentContentScope = {
+ user: 'deletion-owner',
+ parentConversationId: randomUUID(),
+ conversationId: randomUUID(),
+ taskId: randomUUID(),
+ ...(tenantId == null ? {} : { tenantId }),
+ };
+ await mongoose.models.Conversation.create([
+ {
+ user: scope.user,
+ tenantId,
+ conversationId: scope.parentConversationId,
+ endpoint: 'agents',
+ },
+ {
+ user: scope.user,
+ tenantId,
+ conversationId: scope.conversationId,
+ endpoint: 'agents',
+ subagentThread: {
+ rootConversationId: scope.parentConversationId,
+ parentConversationId: scope.parentConversationId,
+ parentMessageId: 'parent-message',
+ parentToolCallId: 'dispatch',
+ subagentType: 'researcher',
+ subagentKind: 'agent',
+ depth: 1,
+ },
+ subagentThreadLease: {
+ taskId: scope.taskId,
+ token: 'lease',
+ expiresAt: new Date(Date.now() + 60_000),
+ },
+ },
+ ]);
+ await mongoose.models.Message.create(
+ (['user', 'assistant'] as const).map((role) => ({
+ user: scope.user,
+ tenantId,
+ conversationId: scope.conversationId,
+ messageId: `${scope.taskId}:${role}`,
+ isCreatedByUser: role === 'user',
+ subagentContent: { version: 1 },
+ })),
+ );
+ expect(await methods.appendSubagentContentBatch({ ...scope, ...batch })).toEqual({ ok: true });
+ return scope;
+ }
+
+ describe.each(['journal', 'source'] as const)('%s deletion failure', (failure) => {
+ it.each(['user', 'assistant', 'both'] as const)(
+ 'keeps the %s source discoverable and revoked until retry succeeds',
+ async (selection) => {
+ const scope = await seedTask();
+ const filter = sourceFilter(scope, selection);
+ const collection =
+ failure === 'journal'
+ ? mongoose.models.SubagentContent.collection
+ : mongoose.models.Message.collection;
+ const outage = new Error('deletion storage unavailable');
+ const failed = jest.spyOn(collection, 'deleteMany').mockRejectedValueOnce(outage);
+ try {
+ await expect(methods.deleteMessages(filter)).rejects.toThrow(outage);
+ expect(await mongoose.models.Message.countDocuments(filter)).toBe(
+ selection === 'both' ? 2 : 1,
+ );
+ const sources = await mongoose.models.Message.find(sourceFilter(scope, 'both'))
+ .select('+subagentContent')
+ .lean<Array<Pick<IMessage, 'subagentContent'>>>();
+ expect(sources).toHaveLength(2);
+ expect(sources.every((source) => source.subagentContent?.deleted === true)).toBe(true);
+ const read = jest.spyOn(methods, 'getSubagentContentHead');
+ const revoked = appFor(scope);
+ const response = await request(revoked.app).get(revoked.url).expect(409);
+ expect(response.body.code).toBe('SUBAGENT_CONTENT_UNAVAILABLE');
+ expect(read).not.toHaveBeenCalled();
+ read.mockRestore();
+ expect(await mongoose.models.SubagentContent.countDocuments(journalFilter(scope))).toBe(
+ failure === 'journal' ? 2 : 0,
+ );
+ await expect(methods.deleteMessages(filter)).resolves.toMatchObject({
+ acknowledged: true,
+ deletedCount: selection === 'both' ? 2 : 1,
+ });
+ expect(await mongoose.models.Message.countDocuments(filter)).toBe(0);
+ expect(await mongoose.models.SubagentContent.countDocuments(journalFilter(scope))).toBe(
+ 0,
+ );
+ expect(await methods.appendSubagentContentBatch({ ...scope, ...nextBatch })).toEqual(
+ gone,
+ );
+ } finally {
+ failed.mockRestore();
+ }
+ },
+ );
+ });
+
+ it('retries an ambiguously committed source deletion without retaining payloads', async () => {
+ const scope = await seedTask();
+ const collection = mongoose.models.Message.collection;
+ const deleteMany = collection.deleteMany.bind(collection);
+ const failed = jest.spyOn(collection, 'deleteMany').mockImplementationOnce(async (...args) => {
+ await deleteMany(...args);
+ throw new Error('source acknowledgement lost');
+ });
+ try {
+ const filter = sourceFilter(scope, 'both');
+ await expect(methods.deleteMessages(filter)).rejects.toThrow('source acknowledgement lost');
+ expect(await mongoose.models.Message.countDocuments(filter)).toBe(0);
+ expect(await mongoose.models.SubagentContent.countDocuments(journalFilter(scope))).toBe(0);
+ await expect(methods.deleteMessages(filter)).resolves.toMatchObject({ deletedCount: 0 });
+ } finally {
+ failed.mockRestore();
+ }
+ });
+
+ it('does not remove sources or payloads when revocation fails', async () => {
+ const scope = await seedTask();
+ const failed = jest
+ .spyOn(mongoose.models.Message.collection, 'updateMany')
+ .mockRejectedValueOnce(new Error('revocation unavailable'));
+ try {
+ const filter = sourceFilter(scope, 'assistant');
+ await expect(methods.deleteMessages(filter)).rejects.toThrow('revocation unavailable');
+ expect(await mongoose.models.Message.countDocuments(sourceFilter(scope, 'both'))).toBe(2);
+ expect(await mongoose.models.SubagentContent.countDocuments(journalFilter(scope))).toBe(2);
+ await expect(methods.deleteMessages(filter)).resolves.toMatchObject({ deletedCount: 1 });
+ } finally {
+ failed.mockRestore();
+ }
+ });
+
+ it.each([undefined, 'tenant-a'])(
+ 'preserves adjacent task, owner, child and tenant scopes (%s)',
+ async (tenantId) => {
+ const scope = await seedTask(tenantId);
+ const neighbors = [
+ { ...scope, taskId: randomUUID() },
+ { ...scope, conversationId: randomUUID(), taskId: randomUUID() },
+ { ...scope, user: 'another-owner' },
+ { ...scope, tenantId: 'tenant-b' },
+ ];
+ for (const neighbor of neighbors) {
+ await mongoose.models.Message.create({
+ user: neighbor.user,
+ tenantId: neighbor.tenantId,
+ conversationId: neighbor.conversationId,
+ messageId: `${neighbor.taskId}:assistant`,
+ subagentContent: { version: 1 },
+ });
+ await mongoose.models.SubagentContent.create({
+ ...neighbor,
+ ...batch,
+ _id: randomUUID(),
+ fragment: 0,
+ fragments: 1,
+ digest: 'unrelated',
+ payload: 'retained',
+ });
+ }
+ const otherChildJournal = { ...scope, conversationId: randomUUID() };
+ await mongoose.models.SubagentContent.create({
+ ...otherChildJournal,
+ ...batch,
+ _id: randomUUID(),
+ fragment: 0,
+ fragments: 1,
+ digest: 'unrelated',
+ payload: 'retained',
+ });
+ const missing = { ...sourceFilter(scope, 'assistant'), messageId: 'missing:assistant' };
+ await expect(methods.deleteMessages(missing)).resolves.toMatchObject({ deletedCount: 0 });
+ expect(await mongoose.models.SubagentContent.countDocuments(journalFilter(scope))).toBe(2);
+ await methods.deleteMessages(sourceFilter(scope, 'assistant'));
+ expect(await mongoose.models.Message.countDocuments(sourceFilter(scope, 'user'))).toBe(1);
+ expect(await mongoose.models.SubagentContent.countDocuments(journalFilter(scope))).toBe(0);
+ expect(
+ await mongoose.models.SubagentContent.countDocuments(journalFilter(otherChildJournal)),
+ ).toBe(1);
+ for (const neighbor of neighbors) {
+ const source = await mongoose.models.Message.findOne(sourceFilter(neighbor, 'assistant'))
+ .select('+subagentContent')
+ .lean<Pick<IMessage, 'subagentContent'> | null>();
+ expect(source?.subagentContent).toMatchObject({ version: 1 });
+ expect(source?.subagentContent).not.toHaveProperty('deleted');
+ expect(await mongoose.models.SubagentContent.countDocuments(journalFilter(neighbor))).toBe(
+ 1,
+ );
+ }
+ },
+ );
+
+ it.each([undefined, 'tenant-a'])(
+ 'does not report successful conversation deletion before journal cleanup succeeds (%s)',
+ async (tenantId) => {
+ const scope = await seedTask(tenantId);
+ const unrelated = await seedTask(tenantId);
+ const Content = mongoose.models.SubagentContent;
+ const Conversation = mongoose.models.Conversation;
+ const journalDelete = Content.collection.deleteMany.bind(Content.collection);
+ const conversationDelete = Conversation.collection.deleteMany.bind(Conversation.collection);
+ let successfulCleanup = false;
+ const cleanup = jest
+ .spyOn(Content.collection, 'deleteMany')
+ .mockRejectedValueOnce(new Error('journal temporarily unavailable'))
+ .mockImplementation(async (...args) => {
+ const result = await journalDelete(...args);
+ successfulCleanup = true;
+ return result;
+ });
+ const deleting = jest
+ .spyOn(Conversation.collection, 'deleteMany')
+ .mockImplementation(async (...args) => {
+ expect(successfulCleanup).toBe(true);
+ expect(await Content.countDocuments(journalFilter(scope))).toBe(0);
+ return conversationDelete(...args);
+ });
+ try {
+ const result = await methods.deleteConvos(scope.user, {
+ conversationId: scope.conversationId,
+ });
+ expect(result.deletedCount).toBe(1);
+ expect(result.messages.acknowledged).toBe(true);
+ expect(cleanup.mock.calls.length).toBeGreaterThanOrEqual(2);
+ expect(await mongoose.models.Message.countDocuments(sourceFilter(scope, 'both'))).toBe(0);
+ expect(await Content.countDocuments(journalFilter(scope))).toBe(0);
+ expect(await Content.countDocuments(journalFilter(unrelated))).toBe(2);
+ expect(
+ await Conversation.countDocuments({
+ user: unrelated.user,
+ conversationId: unrelated.conversationId,
+ }),
+ ).toBe(1);
+ } finally {
+ cleanup.mockRestore();
+ deleting.mockRestore();
+ }
+ },
+ );
+
+ it.each(['revocation', 'journal', 'conversation'] as const)(
+ 'keeps a failed %s barrier discoverable for a direct conversation retry',
+ async (failure) => {
+ const scope = await seedTask();
+ const Message = mongoose.models.Message;
+ const Conversation = mongoose.models.Conversation;
+ const Content = mongoose.models.SubagentContent;
+ const injectFailure = {
+ revocation: () => jest.spyOn(Message.collection, 'updateMany'),
+ journal: () => jest.spyOn(Content.collection, 'deleteMany'),
+ conversation: () => jest.spyOn(Conversation.collection, 'deleteMany'),
+ };
+ const failed = injectFailure[failure]().mockRejectedValue(new Error('erasure unavailable'));
+ try {
+ await expect(
+ methods.deleteConvos(scope.user, { conversationId: scope.conversationId }),
+ ).rejects.toThrow('erasure unavailable');
+ expect(
+ await Conversation.countDocuments({
+ user: scope.user,
+ conversationId: scope.conversationId,
+ }),
+ ).toBe(1);
+ expect(await Message.countDocuments(sourceFilter(scope, 'both'))).toBe(2);
+ expect(await Content.countDocuments(journalFilter(scope))).toBe(
+ failure === 'conversation' ? 0 : 2,
+ );
+ failed.mockRestore();
+ const result = await methods.deleteConvos(scope.user, {
+ conversationId: scope.conversationId,
+ });
+ expect(result.deletedCount).toBe(1);
+ expect(result.messages.deletedCount).toBe(2);
+ expect(await Content.countDocuments(journalFilter(scope))).toBe(0);
+ expect(await Message.countDocuments(sourceFilter(scope, 'both'))).toBe(0);
+ } finally {
+ failed.mockRestore();
+ }
+ },
+ );
+
+ it('retries a committed journal deletion whose acknowledgement was lost before deleting topology', async () => {
+ const scope = await seedTask();
+ const collection = mongoose.models.SubagentContent.collection;
+ const original = collection.deleteMany.bind(collection);
+ const failed = jest.spyOn(collection, 'deleteMany').mockImplementationOnce(async (...args) => {
+ await original(...args);
+ throw new Error('journal acknowledgement lost');
+ });
+ try {
+ const result = await methods.deleteConvos(scope.user, {
+ conversationId: scope.conversationId,
+ });
+ expect(result.deletedCount).toBe(1);
+ expect(result.messages.deletedCount).toBe(2);
+ expect(await mongoose.models.SubagentContent.countDocuments(journalFilter(scope))).toBe(0);
+ expect(await mongoose.models.Message.countDocuments(sourceFilter(scope, 'both'))).toBe(0);
+ } finally {
+ failed.mockRestore();
+ }
+ });
+
+ it('preserves a failed descendant wave for root retry without losing journal scope', async () => {
+ const scope = await seedTask();
+ const Content = mongoose.models.SubagentContent;
+ const original = Content.collection.deleteMany.bind(Content.collection);
+ const failed = jest
+ .spyOn(Content.collection, 'deleteMany')
+ .mockImplementation(async (...args) => {
+ const query = JSON.stringify(args[0]);
+ if (query.includes(scope.conversationId)) throw new Error('child journal unavailable');
+ return original(...args);
+ });
+ try {
+ await expect(
+ methods.deleteConvos(scope.user, { conversationId: scope.parentConversationId }),
+ ).rejects.toThrow('child journal unavailable');
+ expect(
+ await mongoose.models.Conversation.countDocuments({
+ user: scope.user,
+ conversationId: scope.parentConversationId,
+ }),
+ ).toBe(0);
+ expect(
+ await mongoose.models.Conversation.countDocuments({
+ user: scope.user,
+ conversationId: scope.conversationId,
+ }),
+ ).toBe(1);
+ expect(await mongoose.models.Message.countDocuments(sourceFilter(scope, 'both'))).toBe(2);
+ expect(await Content.countDocuments(journalFilter(scope))).toBe(2);
+ failed.mockRestore();
+ const result = await methods.deleteConvos(scope.user, {
+ conversationId: scope.parentConversationId,
+ });
+ expect(result.conversationIds).toEqual([scope.parentConversationId, scope.conversationId]);
+ expect(await Content.countDocuments(journalFilter(scope))).toBe(0);
+ expect(await mongoose.models.Message.countDocuments(sourceFilter(scope, 'both'))).toBe(0);
+ } finally {
+ failed.mockRestore();
+ }
+ });
+
+ it.each(['owner', 'conversation'] as const)(
+ 'keeps whole-%s sources until journal cleanup succeeds',
+ async (selection) => {
+ const scope = await seedTask();
+ const filter = {
+ ...owner(scope),
+ ...(selection === 'conversation' ? { conversationId: scope.conversationId } : {}),
+ };
+ const failed = jest
+ .spyOn(mongoose.models.SubagentContent.collection, 'deleteMany')
+ .mockRejectedValueOnce(new Error('journal unavailable'));
+ try {
+ await expect(methods.deleteMessages(filter)).rejects.toThrow('journal unavailable');
+ expect(await mongoose.models.Message.countDocuments(sourceFilter(scope, 'both'))).toBe(2);
+ expect(await mongoose.models.SubagentContent.countDocuments(journalFilter(scope))).toBe(2);
+ await expect(methods.deleteMessages(filter)).resolves.toMatchObject({ deletedCount: 2 });
+ expect(await mongoose.models.SubagentContent.countDocuments(journalFilter(scope))).toBe(0);
+ } finally {
+ failed.mockRestore();
+ }
+ },
+ );
+
+ it.each(['user', 'assistant', 'both'] as const)(
+ 'cleans an admitted append after deleting %s sources',
+ async (selection) => {
+ const scope = await seedTask();
+ const collection = mongoose.models.SubagentContent.collection;
+ const bulkWrite = collection.bulkWrite.bind(collection);
+ let release: () => void = () => undefined;
+ const released = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ let started: () => void = () => undefined;
+ const entering = new Promise<void>((resolve) => {
+ started = resolve;
+ });
+ const pending = jest
+ .spyOn(collection, 'bulkWrite')
+ .mockImplementationOnce(async (...args) => {
+ started();
+ await released;
+ return bulkWrite(...args);
+ });
+ const late = methods.appendSubagentContentBatch({ ...scope, ...nextBatch });
+ try {
+ await entering;
+ await methods.deleteMessages(sourceFilter(scope, selection));
+ expect(await mongoose.models.SubagentContent.countDocuments(journalFilter(scope))).toBe(0);
+ if (selection === 'assistant') {
+ const revoked = appFor(scope);
+ const response = await request(revoked.app).get(revoked.url).expect(409);
+ expect(response.body.code).toBe('SUBAGENT_CONTENT_UNAVAILABLE');
+ }
+ release();
+ expect(await late).toEqual(gone);
+ expect(await mongoose.models.SubagentContent.countDocuments(journalFilter(scope))).toBe(0);
+ expect(await methods.appendSubagentContentBatch({ ...scope, ...nextBatch })).toEqual(gone);
+ } finally {
+ release();
+ await late;
+ pending.mockRestore();
+ }
+ },
+ );
+
+ it.each(
+ [undefined, 'tenant-a'].flatMap((tenantId) =>
+ (['postwrite', 'fragment', 'commit'] as const).map((failure) => ({ tenantId, failure })),
+ ),
+ )(
+ 'automatically reconciles an abandoned journal after $failure cleanup failure ($tenantId)',
+ async ({ tenantId, failure }) => {
+ const scope = await seedTask(tenantId);
+ const Model = mongoose.models.SubagentContent;
+ await Model.deleteMany(journalFilter(scope));
+ const neighbors = [
+ { ...scope, taskId: randomUUID() },
+ { ...scope, user: 'other-owner' },
+ { ...scope, tenantId: tenantId == null ? 'tenant-b' : undefined },
+ { ...scope, conversationId: randomUUID() },
+ ];
+ await Model.create(
+ neighbors.map((neighbor) => ({
+ ...neighbor,
+ ...batch,
+ _id: randomUUID(),
+ fragment: 0,
+ fragments: 1,
+ digest: 'neighbor',
+ payload: 'retained',
+ })),
+ );
+ const collection = Model.collection;
+ const bulkWrite = collection.bulkWrite.bind(collection);
+ let release: () => void = () => undefined;
+ const released = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ let started: () => void = () => undefined;
+ const entering = new Promise<void>((resolve) => {
+ started = resolve;
+ });
+ const pending = jest
+ .spyOn(collection, 'bulkWrite')
+ .mockImplementationOnce(async (...args) => {
+ started();
+ await released;
+ const result = await bulkWrite(...args);
+ if (failure === 'fragment') throw new Error('partial fragment acknowledgement lost');
+ return result;
+ });
+ const updateOne = collection.updateOne.bind(collection);
+ const commit = jest.spyOn(collection, 'updateOne').mockImplementationOnce(async (...args) => {
+ const result = await updateOne(...args);
+ if (failure === 'commit') throw new Error('commit acknowledgement lost');
+ return result;
+ });
+ const append = jest.fn(methods.appendSubagentContentBatch);
+ const notify = jest.fn(async () => undefined);
+ const errors = jest.fn();
+ const journal = new SubagentContentJournal({
+ scope,
+ flushMs: 60_000,
+ batchBytes: 1,
+ settlementTimeoutMs: 20,
+ append,
+ reconcile: methods.reconcileSubagentContent,
+ cleanupRetry: { retryAttempts: 3, retryBaseDelayMs: 1, recoveryDelayMs: 100 },
+ notify,
+ onError: errors,
+ });
+ journal.record(
+ progress('message_delta', {
+ id: 's',
+ delta: { content: [{ type: 'text', text: 'late bytes' }] },
+ }),
+ 0,
+ );
+ await entering;
+ journal.record(progress('message_delta', { id: 's', delta: { content: [] } }), 1);
+ await expect(journal.close()).resolves.toMatchObject({
+ ok: false,
+ error: { code: 'SUBAGENT_CONTENT_SETTLEMENT_TIMEOUT' },
+ });
+ await methods.deleteMessages(sourceFilter(scope, 'both'));
+ await mongoose.models.Conversation.deleteMany({
+ ...owner(scope),
+ conversationId: { $in: [scope.parentConversationId, scope.conversationId] },
+ });
+ const failed = jest
+ .spyOn(collection, 'deleteMany')
+ .mockRejectedValueOnce(new Error('late cleanup unavailable'));
+ try {
+ release();
+ await until(async () => failed.mock.calls.length >= 2);
+ await until(async () => (await Model.countDocuments(journalFilter(scope))) === 0);
+ expect(append).toHaveBeenCalledTimes(1);
+ expect(notify).not.toHaveBeenCalled();
+ expect(errors).toHaveBeenCalled();
+ for (const neighbor of neighbors) {
+ expect(await Model.countDocuments(journalFilter(neighbor))).toBe(1);
+ }
+ } finally {
+ release();
+ await Promise.allSettled(append.mock.results.map((result) => result.value));
+ failed.mockRestore();
+ pending.mockRestore();
+ commit.mockRestore();
+ }
+ },
+ );
+
+ it('retries a failed post-write cleanup after selective source erasure', async () => {
+ const scope = await seedTask();
+ const collection = mongoose.models.SubagentContent.collection;
+ const bulkWrite = collection.bulkWrite.bind(collection);
+ let release: () => void = () => undefined;
+ const released = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ let started: () => void = () => undefined;
+ const entering = new Promise<void>((resolve) => {
+ started = resolve;
+ });
+ const pending = jest.spyOn(collection, 'bulkWrite').mockImplementationOnce(async (...args) => {
+ started();
+ await released;
+ return bulkWrite(...args);
+ });
+ const late = methods.appendSubagentContentBatch({ ...scope, ...nextBatch });
+ try {
+ await entering;
+ await methods.deleteMessages(sourceFilter(scope, 'both'));
+ const failed = jest
+ .spyOn(collection, 'deleteMany')
+ .mockRejectedValueOnce(new Error('late cleanup unavailable'));
+ try {
+ release();
+ await expect(late).rejects.toThrow('late cleanup unavailable');
+ expect(await mongoose.models.SubagentContent.countDocuments(journalFilter(scope))).toBe(2);
+ expect(await methods.appendSubagentContentBatch({ ...scope, ...nextBatch })).toEqual(gone);
+ expect(await mongoose.models.SubagentContent.countDocuments(journalFilter(scope))).toBe(0);
+ } finally {
+ failed.mockRestore();
+ }
+ } finally {
+ release();
+ await late.catch(() => undefined);
+ pending.mockRestore();
+ }
+ });
+});
diff --git a/packages/api/src/agents/subagentContent.spec.ts b/packages/api/src/agents/subagentContent.spec.ts
new file mode 100644
index 0000000000..8626bfd649
--- /dev/null
+++ b/packages/api/src/agents/subagentContent.spec.ts
@@ -0,0 +1,782 @@
+import type {
+ SubagentContentAppendResult,
+ SubagentContentMethods,
+ SubagentContentBatch,
+ SubagentContentScope,
+} from '@librechat/data-schemas';
+import type { SubagentUpdateEvent } from '@librechat/agents';
+import { readSubagentContent, SubagentContentJournal } from './subagentContent';
+
+const scope: SubagentContentScope = {
+ user: 'owner',
+ parentConversationId: 'parent',
+ conversationId: 'child',
+ taskId: 'task',
+};
+
+const update = (phase: SubagentUpdateEvent['phase'], data: unknown): SubagentUpdateEvent => ({
+ runId: 'root',
+ subagentRunId: 'execution',
+ subagentType: 'worker',
+ subagentAgentId: 'worker',
+ phase,
+ data,
+ timestamp: '2026-10-20T00:00:00.000Z',
+});
+
+function memoryStorage() {
+ const batches: SubagentContentBatch[] = [];
+ const methods: SubagentContentMethods = {
+ reconcileSubagentContent: async () => ({ ok: true }),
+ appendSubagentContentBatch: async ({ revision, fromSequence, throughSequence, eventsJson }) => {
+ batches.push({ revision, fromSequence, throughSequence, eventsJson });
+ return { ok: true };
+ },
+ getSubagentContentHead: async (_scope, throughRevision) => {
+ let head: SubagentContentBatch | undefined;
+ for (let index = batches.length - 1; index >= 0; index--) {
+ if (throughRevision == null || batches[index].revision <= throughRevision) {
+ head = batches[index];
+ break;
+ }
+ }
+ return head == null
+ ? null
+ : { revision: head.revision, throughSequence: head.throughSequence };
+ },
+ streamSubagentContentBatches: async function* (_scope, throughRevision, afterSequence = -1) {
+ for (const batch of batches) {
+ if (batch.revision <= throughRevision && batch.throughSequence > afterSequence) yield batch;
+ }
+ },
+ };
+ return { methods, batches };
+}
+
+const journalFor = (methods: SubagentContentMethods, batchBytes = 1_000_000) =>
+ new SubagentContentJournal({
+ scope,
+ flushMs: 60_000,
+ batchBytes,
+ append: methods.appendSubagentContentBatch,
+ notify: async () => undefined,
+ onError: () => undefined,
+ });
+
+it('reconstructs earlier text after more than a replay window of public deltas', async () => {
+ const { methods } = memoryStorage();
+ const journal = journalFor(methods);
+ journal.record(
+ update('run_step', {
+ id: 'text',
+ index: 0,
+ stepDetails: {
+ type: 'message_creation',
+ message_creation: { message_id: 'reply', phase: 'commentary' },
+ },
+ }),
+ 0,
+ );
+ for (let index = 1; index <= 150; index++) {
+ journal.record(
+ update('message_delta', {
+ id: 'text',
+ delta: { content: [{ type: 'text', text: `${index},` }] },
+ }),
+ index,
+ );
+ }
+ await journal.close();
+ const result = await readSubagentContent(methods, scope);
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(result.value.content).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ type: 'text',
+ text: Array.from({ length: 150 }, (_, i) => `${i + 1},`).join(''),
+ }),
+ ]),
+ );
+ expect(result.value.content[0]).toMatchObject({ phase: 'commentary' });
+ expect(result.value.throughSequence).toBe(150);
+});
+
+it('keeps full tool content larger than the previous activity projection', async () => {
+ const { methods } = memoryStorage();
+ const journal = journalFor(methods);
+ const output = 'full-output:'.repeat(4000);
+ const args = { query: 'full-arguments:'.repeat(2000) };
+ journal.record(
+ update('run_step', {
+ id: 'tool',
+ index: 0,
+ stepDetails: {
+ type: 'tool_calls',
+ tool_calls: [{ id: 'call', name: 'lookup', args, type: 'tool_call' }],
+ },
+ }),
+ 0,
+ );
+ journal.record(
+ update('run_step_completed', {
+ result: {
+ id: 'tool',
+ type: 'tool_call',
+ tool_call: { id: 'call', name: 'lookup', args, output, progress: 1 },
+ },
+ }),
+ 1,
+ );
+ await journal.close();
+ const result = await readSubagentContent(methods, scope);
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(JSON.stringify(result.value.content)).toContain(output);
+ expect(JSON.stringify(result.value.content)).toContain(args.query);
+});
+
+it('pins paged recovery before a racing later batch without duplicate sequences', async () => {
+ const { methods } = memoryStorage();
+ const journal = journalFor(methods);
+ for (let sequence = 0; sequence < 12; sequence++) {
+ journal.record(
+ update('message_delta', {
+ id: 's',
+ delta: { content: [{ type: 'text', text: 'x'.repeat(250) }] },
+ }),
+ sequence,
+ );
+ }
+ await journal.flush();
+ const first = await readSubagentContent(methods, scope, -1, { pageBytes: 1024 });
+ expect(first.ok).toBe(true);
+ if (!first.ok) return;
+ const sequences = first.value.events.map((event) => event.sequence);
+ journal.record(
+ update('message_delta', { id: 's', delta: { content: [{ type: 'text', text: 'later' }] } }),
+ 12,
+ );
+ await journal.flush();
+ let cursor = first.value.nextCursor;
+ while (cursor != null) {
+ const pin: { afterSequence: number; throughRevision: number } = JSON.parse(
+ Buffer.from(cursor, 'base64url').toString('utf8'),
+ );
+ const page = await readSubagentContent(methods, scope, pin.afterSequence, {
+ pageBytes: 1024,
+ throughRevision: pin.throughRevision,
+ });
+ expect(page.ok).toBe(true);
+ if (!page.ok) break;
+ sequences.push(...page.value.events.map((event) => event.sequence));
+ cursor = page.value.nextCursor;
+ }
+ await journal.close();
+ expect(sequences).toEqual(Array.from({ length: 12 }, (_, i) => i));
+ expect(await readSubagentContent(methods, scope, 11)).toMatchObject({
+ ok: true,
+ value: { events: [{ sequence: 12 }] },
+ });
+});
+
+it('reports a missing committed range instead of treating it as an empty response', async () => {
+ const { methods, batches } = memoryStorage();
+ batches.push({ revision: 2, fromSequence: 5, throughSequence: 7, eventsJson: '[]' });
+ expect(await readSubagentContent(methods, scope)).toEqual({
+ ok: false,
+ error: { code: 'SUBAGENT_CONTENT_GAP' },
+ });
+});
+
+it('bounds a blocked capture backlog without blocking child execution or claiming complete history', async () => {
+ const { methods, batches } = memoryStorage();
+ const errors: unknown[] = [];
+ const journal = new SubagentContentJournal({
+ scope,
+ flushMs: 60_000,
+ batchBytes: 1_000_000,
+ maxPendingBytes: 1024,
+ append: methods.appendSubagentContentBatch,
+ notify: async () => undefined,
+ onError: (error) => errors.push(error),
+ });
+ for (let sequence = 0; sequence < 1000; sequence++) {
+ journal.record(
+ update('message_delta', {
+ id: 's',
+ delta: { content: [{ type: 'text', text: 'x'.repeat(250) }] },
+ }),
+ sequence,
+ );
+ }
+ await journal.close();
+ expect(errors).toHaveLength(1);
+ expect(journal.throughSequence).toBe(999);
+ expect(batches[batches.length - 1]?.throughSequence).toBeLessThan(journal.throughSequence);
+ expect(
+ batches.reduce((size, batch) => size + Buffer.byteLength(batch.eventsJson), 0),
+ ).toBeLessThan(1024);
+});
+
+it('retries the exact frozen batch before admitting later events into a new revision', async () => {
+ const { methods } = memoryStorage();
+ const attempts: Array<{ revision: number; eventsJson: string }> = [];
+ const fragments = new Map<number, string>();
+ let fail = true;
+ const journal = new SubagentContentJournal({
+ scope,
+ flushMs: 60_000,
+ batchBytes: 1_000_000,
+ append: async (input) => {
+ attempts.push({ revision: input.revision, eventsJson: input.eventsJson });
+ const prior = fragments.get(input.revision);
+ if (prior != null && prior !== input.eventsJson) throw new Error('Conflicting revision');
+ fragments.set(input.revision, input.eventsJson);
+ if (fail) {
+ fail = false;
+ throw new Error('Lost append acknowledgment');
+ }
+ return methods.appendSubagentContentBatch(input);
+ },
+ notify: async () => undefined,
+ onError: () => undefined,
+ });
+ journal.record(
+ update('message_delta', { id: 's', delta: { content: [{ type: 'text', text: 'first' }] } }),
+ 0,
+ );
+ await expect(journal.flush()).rejects.toThrow('Lost append acknowledgment');
+ journal.record(
+ update('message_delta', { id: 's', delta: { content: [{ type: 'text', text: 'second' }] } }),
+ 1,
+ );
+ await expect(journal.close()).resolves.toEqual({ ok: true });
+ expect(attempts).toHaveLength(3);
+ expect(attempts[1]).toEqual(attempts[0]);
+ expect(attempts[2].revision).toBe(2);
+});
+
+describe('journal close retries', () => {
+ const timeoutResult = {
+ ok: false,
+ error: { code: 'SUBAGENT_CONTENT_SETTLEMENT_TIMEOUT' },
+ };
+ const unhandled = jest.fn();
+
+ beforeEach(() => {
+ jest.useFakeTimers();
+ unhandled.mockClear();
+ process.on('unhandledRejection', unhandled);
+ });
+
+ afterEach(() => {
+ process.off('unhandledRejection', unhandled);
+ jest.useRealTimers();
+ });
+
+ it.each([
+ { trigger: 'threshold', lostAck: false },
+ { trigger: 'timer', lostAck: false },
+ { trigger: 'threshold', lostAck: true },
+ ])(
+ 'retries an active $trigger flush after close begins (lost ack: $lostAck)',
+ async ({ trigger, lostAck }) => {
+ const { methods, batches } = memoryStorage();
+ let rejectFirst: (error: Error) => void = () => undefined;
+ const blocked = new Promise<SubagentContentAppendResult>((_resolve, reject) => {
+ rejectFirst = reject;
+ });
+ const append = jest.fn(methods.appendSubagentContentBatch).mockImplementationOnce((input) => {
+ if (lostAck) void methods.appendSubagentContentBatch(input);
+ return blocked;
+ });
+ if (lostAck) {
+ append.mockImplementation(async (input) =>
+ batches.some((batch) => batch.revision === input.revision)
+ ? { ok: true }
+ : methods.appendSubagentContentBatch(input),
+ );
+ }
+ const notify = jest.fn(async () => undefined);
+ const journal = new SubagentContentJournal({
+ scope,
+ leaseToken: 'lease',
+ flushMs: 10,
+ batchBytes: trigger === 'threshold' ? 1 : 1_000_000,
+ settlementTimeoutMs: 100,
+ append,
+ notify,
+ onError: () => undefined,
+ });
+ const first = { id: 's', delta: { content: [{ type: 'text', text: 'first' }] } };
+ journal.record(update('message_delta', first), 0);
+ if (trigger === 'timer') await jest.advanceTimersByTimeAsync(10);
+ expect(append).toHaveBeenCalledTimes(1);
+ first.delta.content[0].text = 'mutated first';
+ const suffix = { id: 's', delta: { content: [{ type: 'text', text: 'suffix' }] } };
+ journal.record(update('message_delta', suffix), 1);
+ suffix.delta.content[0].text = 'mutated suffix';
+ const closing = journal.close();
+ void closing.catch(() => undefined);
+ expect(journal.close()).toBe(closing);
+ rejectFirst(new Error('Transient append failure'));
+ await jest.advanceTimersByTimeAsync(10);
+
+ await expect(closing).resolves.toEqual({ ok: true });
+ expect(append).toHaveBeenCalledTimes(3);
+ expect(append.mock.calls[1][0]).toEqual(append.mock.calls[0][0]);
+ expect(append.mock.calls[1][0]).toMatchObject({
+ ...scope,
+ leaseToken: 'lease',
+ revision: 1,
+ fromSequence: 0,
+ throughSequence: 0,
+ });
+ expect(append.mock.calls[2][0]).toMatchObject({
+ revision: 2,
+ fromSequence: 1,
+ throughSequence: 1,
+ });
+ expect(JSON.parse(append.mock.calls[0][0].eventsJson)[0].frame.data).toEqual({
+ id: 's',
+ delta: { content: [{ type: 'text', text: 'first' }] },
+ });
+ expect(JSON.parse(append.mock.calls[2][0].eventsJson)[0].frame.data).toEqual({
+ id: 's',
+ delta: { content: [{ type: 'text', text: 'suffix' }] },
+ });
+ expect(batches).toHaveLength(2);
+ expect(notify.mock.calls).toEqual([
+ [{ taskId: scope.taskId, revision: 1, throughSequence: 0 }],
+ [{ taskId: scope.taskId, revision: 2, throughSequence: 1 }],
+ ]);
+ expect(journal.throughSequence).toBe(1);
+ expect(jest.getTimerCount()).toBe(0);
+ expect(unhandled).not.toHaveBeenCalled();
+ },
+ );
+
+ it('retries a fresh close flush even when the normal flush cadence exceeds its budget', async () => {
+ const { methods } = memoryStorage();
+ const append = jest
+ .fn(methods.appendSubagentContentBatch)
+ .mockRejectedValueOnce(new Error('Transient append failure'));
+ const journal = new SubagentContentJournal({
+ scope,
+ flushMs: 60_000,
+ batchBytes: 1_000_000,
+ settlementTimeoutMs: 100,
+ append,
+ notify: async () => undefined,
+ onError: () => undefined,
+ });
+ journal.record(update('message_delta', { id: 's', delta: { content: [] } }), 0);
+ const closing = journal.close();
+ void closing.catch(() => undefined);
+ await jest.advanceTimersByTimeAsync(99);
+ await expect(closing).resolves.toEqual({ ok: true });
+ expect(append).toHaveBeenCalledTimes(2);
+ expect(append.mock.calls[1][0]).toEqual(append.mock.calls[0][0]);
+ expect(jest.getTimerCount()).toBe(0);
+ expect(unhandled).not.toHaveBeenCalled();
+ });
+
+ it.each(['active', 'fresh'])(
+ 'bounds persistent %s failures by the original close deadline',
+ async (trigger) => {
+ const { methods } = memoryStorage();
+ const startedAt = Date.now();
+ const attempts: number[] = [];
+ const append = jest.fn(async () => {
+ attempts.push(Date.now() - startedAt);
+ throw new Error('Storage unavailable');
+ });
+ const notify = jest.fn(async () => undefined);
+ const journal = new SubagentContentJournal({
+ scope,
+ flushMs: 10,
+ batchBytes: trigger === 'active' ? 1 : 1_000_000,
+ settlementTimeoutMs: 100,
+ append,
+ notify,
+ onError: () => undefined,
+ });
+ journal.record(update('message_delta', { id: 's', delta: { content: [] } }), 0);
+ journal.record(update('message_delta', { id: 's', delta: { content: [] } }), 1);
+ const closing = journal.close();
+ let outcome: SubagentContentAppendResult | typeof timeoutResult | undefined;
+ void closing.then(
+ (result) => {
+ outcome = result;
+ },
+ () => undefined,
+ );
+ await jest.advanceTimersByTimeAsync(99);
+ expect(outcome).toBeUndefined();
+ expect(attempts).toEqual([0, 10, 20, 30, 40, 50, 60, 70, 80, 90]);
+ await jest.advanceTimersByTimeAsync(1);
+ await expect(closing).resolves.toEqual(timeoutResult);
+ expect(journal.close()).toBe(closing);
+ await jest.advanceTimersByTimeAsync(1000);
+ expect(append).toHaveBeenCalledTimes(10);
+ expect(notify).not.toHaveBeenCalled();
+ expect(journal.throughSequence).toBe(1);
+ expect(await methods.getSubagentContentHead(scope)).toBeNull();
+ expect(jest.getTimerCount()).toBe(0);
+ expect(unhandled).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each(['active', 'fresh', 'prior'])(
+ 'keeps a typed %s append denial terminal',
+ async (trigger) => {
+ const { methods } = memoryStorage();
+ const denied = { ok: false, error: { code: 'SUBAGENT_CONTENT_GONE' } } as const;
+ const append = jest.fn(methods.appendSubagentContentBatch).mockResolvedValueOnce(denied);
+ const notify = jest.fn(async () => undefined);
+ const journal = new SubagentContentJournal({
+ scope,
+ flushMs: 10,
+ batchBytes: trigger === 'fresh' ? 1_000_000 : 1,
+ settlementTimeoutMs: 100,
+ append,
+ notify,
+ onError: () => undefined,
+ });
+ journal.record(update('message_delta', { id: 's', delta: { content: [] } }), 0);
+ if (trigger === 'prior') await jest.advanceTimersByTimeAsync(0);
+ const closing = journal.close();
+ await expect(closing).resolves.toEqual(denied);
+ expect(journal.close()).toBe(closing);
+ await expect(journal.flush()).resolves.toEqual(denied);
+ await jest.advanceTimersByTimeAsync(1000);
+ expect(append).toHaveBeenCalledTimes(1);
+ expect(notify).not.toHaveBeenCalled();
+ expect(jest.getTimerCount()).toBe(0);
+ expect(unhandled).not.toHaveBeenCalled();
+ },
+ );
+
+ it('keeps failed staged bytes charged against the capture backlog', async () => {
+ const { methods, batches } = memoryStorage();
+ const append = jest
+ .fn(methods.appendSubagentContentBatch)
+ .mockRejectedValueOnce(new Error('Transient append failure'));
+ const errors: unknown[] = [];
+ const journal = new SubagentContentJournal({
+ scope,
+ flushMs: 10,
+ batchBytes: 1,
+ maxPendingBytes: 1024,
+ settlementTimeoutMs: 100,
+ append,
+ notify: async () => undefined,
+ onError: (error) => errors.push(error),
+ });
+ const frame = update('message_delta', {
+ id: 's',
+ delta: { content: [{ type: 'text', text: 'x'.repeat(600) }] },
+ });
+ journal.record(frame, 0);
+ await jest.advanceTimersByTimeAsync(0);
+ journal.record(frame, 1);
+ journal.record(update('message_delta', { id: 's', delta: { content: [] } }), 2);
+ await expect(journal.close()).resolves.toEqual({ ok: true });
+ expect(append).toHaveBeenCalledTimes(2);
+ expect(append.mock.calls[1][0]).toEqual(append.mock.calls[0][0]);
+ expect(errors).toContainEqual(
+ new Error('Subagent content persistence backlog exceeded its byte limit'),
+ );
+ expect(batches).toHaveLength(1);
+ expect(batches[0].throughSequence).toBe(0);
+ expect(journal.throughSequence).toBe(2);
+ expect(unhandled).not.toHaveBeenCalled();
+ });
+
+ it('continues cleanup-only recovery at the configured cadence after fast retries are exhausted', async () => {
+ const { methods } = memoryStorage();
+ let rejectAppend: (error: Error) => void = () => undefined;
+ const append = jest.fn(methods.appendSubagentContentBatch).mockImplementationOnce(
+ () =>
+ new Promise((_resolve, reject) => {
+ rejectAppend = reject;
+ }),
+ );
+ const reconcile = jest
+ .fn(methods.reconcileSubagentContent)
+ .mockRejectedValueOnce(new Error('cleanup 1'))
+ .mockRejectedValueOnce(new Error('cleanup 2'))
+ .mockRejectedValueOnce(new Error('cleanup 3'))
+ .mockRejectedValueOnce(new Error('cleanup 4'));
+ const notify = jest.fn(async () => undefined);
+ const journal = new SubagentContentJournal({
+ scope,
+ leaseToken: 'lease',
+ flushMs: 10,
+ batchBytes: 1,
+ settlementTimeoutMs: 100,
+ append,
+ reconcile,
+ cleanupRetry: { retryAttempts: 3, retryBaseDelayMs: 10, recoveryDelayMs: 100 },
+ notify,
+ onError: () => undefined,
+ });
+ journal.record(update('message_delta', { id: 's', delta: { content: [] } }), 0);
+ const closing = journal.close();
+ await jest.advanceTimersByTimeAsync(100);
+ await expect(closing).resolves.toEqual(timeoutResult);
+ expect(reconcile).not.toHaveBeenCalled();
+ rejectAppend(new Error('late partial write'));
+ await jest.advanceTimersByTimeAsync(0);
+ expect(reconcile).toHaveBeenCalledTimes(1);
+ await jest.advanceTimersByTimeAsync(30);
+ expect(reconcile).toHaveBeenCalledTimes(3);
+ await jest.advanceTimersByTimeAsync(99);
+ expect(reconcile).toHaveBeenCalledTimes(3);
+ await jest.advanceTimersByTimeAsync(101);
+ expect(reconcile).toHaveBeenCalledTimes(5);
+ expect(
+ reconcile.mock.calls.every(([target]) => JSON.stringify(target) === JSON.stringify(scope)),
+ ).toBe(true);
+ expect(append).toHaveBeenCalledTimes(1);
+ expect(notify).not.toHaveBeenCalled();
+ expect(jest.getTimerCount()).toBe(0);
+ expect(unhandled).not.toHaveBeenCalled();
+ });
+
+ it('reconciles when the deadline expires between failed append attempts', async () => {
+ const { methods } = memoryStorage();
+ const append = jest
+ .fn(methods.appendSubagentContentBatch)
+ .mockRejectedValue(new Error('partial write'));
+ const reconcile = jest.fn(methods.reconcileSubagentContent);
+ const journal = new SubagentContentJournal({
+ scope,
+ flushMs: 1000,
+ batchBytes: 1_000_000,
+ settlementTimeoutMs: 100,
+ append,
+ reconcile,
+ notify: async () => undefined,
+ onError: () => undefined,
+ });
+ journal.record(update('message_delta', { id: 's', delta: { content: [] } }), 0);
+ const closing = journal.close();
+ await jest.advanceTimersByTimeAsync(100);
+ await expect(closing).resolves.toEqual(timeoutResult);
+ expect(reconcile).toHaveBeenCalledTimes(1);
+ const attempts = append.mock.calls.length;
+ await jest.advanceTimersByTimeAsync(1000);
+ expect(append).toHaveBeenCalledTimes(attempts);
+ expect(jest.getTimerCount()).toBe(0);
+ });
+
+ it.each(['resolve', 'reject'])(
+ 'does not retry or notify after a timed-out append later %ss',
+ async (settlement) => {
+ const { methods } = memoryStorage();
+ let release: () => void = () => undefined;
+ const append = jest
+ .fn(methods.appendSubagentContentBatch)
+ .mockImplementationOnce(methods.appendSubagentContentBatch)
+ .mockImplementationOnce(
+ (input) =>
+ new Promise<SubagentContentAppendResult>((resolve, reject) => {
+ release = () => {
+ if (settlement === 'reject') reject(new Error('Late append failure'));
+ else resolve(methods.appendSubagentContentBatch(input));
+ };
+ }),
+ );
+ const notify = jest.fn(async () => undefined);
+ const journal = new SubagentContentJournal({
+ scope,
+ flushMs: 10,
+ batchBytes: 1,
+ settlementTimeoutMs: 100,
+ append,
+ notify,
+ onError: () => undefined,
+ });
+ journal.record(update('message_delta', { id: 's', delta: { content: [] } }), 0);
+ await journal.flush();
+ journal.record(update('message_delta', { id: 's', delta: { content: [] } }), 1);
+ journal.record(update('message_delta', { id: 's', delta: { content: [] } }), 2);
+ const closing = journal.close();
+ await jest.advanceTimersByTimeAsync(100);
+ await expect(closing).resolves.toEqual(timeoutResult);
+ release();
+ await jest.advanceTimersByTimeAsync(1000);
+ await expect(journal.flush()).resolves.toEqual(timeoutResult);
+ expect(append).toHaveBeenCalledTimes(2);
+ expect(notify).toHaveBeenCalledTimes(1);
+ expect(notify).toHaveBeenCalledWith({
+ taskId: scope.taskId,
+ revision: 1,
+ throughSequence: 0,
+ });
+ expect(journal.throughSequence).toBe(2);
+ expect(await methods.getSubagentContentHead(scope)).toEqual({
+ revision: settlement === 'resolve' ? 2 : 1,
+ throughSequence: settlement === 'resolve' ? 1 : 0,
+ });
+ expect(jest.getTimerCount()).toBe(0);
+ expect(unhandled).not.toHaveBeenCalled();
+ },
+ );
+});
+
+it('bounds final settlement and never starts another batch after a timed-out append', async () => {
+ jest.useFakeTimers();
+ const { methods } = memoryStorage();
+ let release: () => void = () => undefined;
+ const blocked = new Promise<{ ok: true }>((resolve) => {
+ release = () => resolve({ ok: true });
+ });
+ const append = jest.fn(methods.appendSubagentContentBatch).mockImplementationOnce(() => blocked);
+ const notify = jest.fn(async () => undefined);
+ const journal = new SubagentContentJournal({
+ scope,
+ flushMs: 60_000,
+ batchBytes: 1024,
+ settlementTimeoutMs: 100,
+ append,
+ notify,
+ onError: () => undefined,
+ });
+ try {
+ journal.record(
+ update('message_delta', {
+ id: 's',
+ delta: { content: [{ type: 'text', text: 'x'.repeat(1500) }] },
+ }),
+ 0,
+ );
+ journal.record(
+ update('message_delta', { id: 's', delta: { content: [{ type: 'text', text: 'later' }] } }),
+ 1,
+ );
+ let outcome: unknown;
+ const closing = journal.close().then((result) => {
+ outcome = result;
+ });
+ await jest.advanceTimersByTimeAsync(100);
+ const atDeadline = outcome;
+ release();
+ await closing;
+ await Promise.resolve();
+ expect(atDeadline).toEqual({
+ ok: false,
+ error: { code: 'SUBAGENT_CONTENT_SETTLEMENT_TIMEOUT' },
+ });
+ expect(journal.throughSequence).toBe(1);
+ expect(append).toHaveBeenCalledTimes(1);
+ expect(notify).not.toHaveBeenCalled();
+ } finally {
+ release();
+ jest.useRealTimers();
+ }
+});
+
+it.each(['marker', 'argument delta'] as const)(
+ 'restores preparation timing from a retained %s',
+ async (source) => {
+ const { methods } = memoryStorage();
+ const journal = journalFor(methods);
+ journal.record(
+ update('run_step', {
+ id: 'tool',
+ index: 0,
+ stepDetails: {
+ type: 'tool_calls',
+ tool_calls: [{ id: 'call', name: 'lookup', args: '{}', type: 'tool_call' }],
+ },
+ }),
+ 0,
+ );
+ if (source === 'marker') {
+ journal.record(
+ {
+ phase: 'tool_preparation',
+ data: { id: 'tool', index: 0, toolCallId: 'call', observed_at: 100 },
+ },
+ 1,
+ );
+ } else {
+ journal.record(
+ update('run_step_delta', {
+ id: 'tool',
+ observed_at: 100,
+ delta: {
+ type: 'tool_calls',
+ tool_calls: [{ id: 'call', index: 0, name: 'lookup', args: '{}' }],
+ },
+ }),
+ 1,
+ );
+ }
+ journal.record(
+ update('tool_calls_dispatched', {
+ dispatched_at: 1000,
+ toolCalls: [{ id: 'call', stepId: 'tool', name: 'lookup' }],
+ }),
+ 2,
+ );
+ journal.record(
+ update('run_step_completed', {
+ result: {
+ id: 'tool',
+ type: 'tool_call',
+ completed_at: 1340,
+ tool_call: { id: 'call', name: 'lookup', args: '{}', output: 'Done', progress: 1 },
+ },
+ }),
+ 3,
+ );
+ await journal.close();
+ const result = await readSubagentContent(methods, scope);
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(result.value.content[0]).toMatchObject({
+ type: 'tool_call',
+ tool_call: {
+ toolPreparationStartedAt: 100,
+ toolPreparationDurationMs: 900,
+ toolDispatchedAt: 1000,
+ toolExecutionDurationMs: 340,
+ },
+ });
+ if (source === 'marker') {
+ const suffix = await readSubagentContent(methods, scope, 0);
+ expect(suffix).toMatchObject({
+ ok: true,
+ value: {
+ events: expect.arrayContaining([
+ expect.objectContaining({
+ sequence: 1,
+ frame: expect.objectContaining({ event: 'on_tool_preparation' }),
+ }),
+ ]),
+ },
+ });
+ }
+ },
+);
+
+it('does not open a payload cursor when the caller already has the committed head', async () => {
+ const stream = jest.fn();
+ const result = await readSubagentContent(
+ {
+ getSubagentContentHead: async () => ({ revision: 5000, throughSequence: 9999 }),
+ streamSubagentContentBatches: stream,
+ },
+ scope,
+ 9999,
+ );
+ expect(result).toMatchObject({
+ ok: true,
+ value: { revision: 5000, throughSequence: 9999, events: [] },
+ });
+ expect(stream).not.toHaveBeenCalled();
+});
diff --git a/packages/api/src/agents/subagentContent.ts b/packages/api/src/agents/subagentContent.ts
new file mode 100644
index 0000000000..abf0bd2548
--- /dev/null
+++ b/packages/api/src/agents/subagentContent.ts
@@ -0,0 +1,729 @@
+import { logger } from '@librechat/data-schemas';
+import { createContentAggregator, GraphEvents } from '@librechat/agents';
+import {
+ subagentActivityConfigSchema,
+ StepEvents,
+ ContentTypes,
+ getRunStepCloseMetadata,
+ getRunStepDurationMs,
+} from 'librechat-data-provider';
+import type {
+ TSubagentActivityConfig,
+ SubagentContentEvent,
+ SubagentContentFrame,
+ SubagentContentWatermark,
+ SubagentTaskContentResponse,
+ SubagentThreadStatus,
+ TMessageContentParts,
+ Agents,
+} from 'librechat-data-provider';
+import type {
+ SubagentContentMethods,
+ SubagentContentAppendResult,
+ SubagentContentScope,
+ ConversationMethods,
+ MessageMethods,
+} from '@librechat/data-schemas';
+import type { SubagentUpdateEvent } from '@librechat/agents';
+import type { Response } from 'express';
+import type { ServerRequest } from '~/types';
+import { toWireRunSteps } from '~/stream/interfaces/IJobStore';
+import { createToolTimingAdapter } from './toolTiming';
+import { getSafeErrorMetadata } from '~/utils/errors';
+
+const CONTENT_GRAPH_EVENTS = {
+ [StepEvents.ON_RUN_STEP]: GraphEvents.ON_RUN_STEP,
+ [StepEvents.ON_MESSAGE_DELTA]: GraphEvents.ON_MESSAGE_DELTA,
+ [StepEvents.ON_REASONING_DELTA]: GraphEvents.ON_REASONING_DELTA,
+ [StepEvents.ON_RUN_STEP_DELTA]: GraphEvents.ON_RUN_STEP_DELTA,
+ [StepEvents.ON_RUN_STEP_COMPLETED]: GraphEvents.ON_RUN_STEP_COMPLETED,
+};
+
+type SubagentContentUpdate = Pick<SubagentUpdateEvent, 'data'> & {
+ phase: SubagentUpdateEvent['phase'] | 'tool_preparation';
+};
+
+/** This boundary accepts only events already intended for the public main-chat stream. */
+export function subagentContentFrame(update: SubagentContentUpdate): SubagentContentFrame | null {
+ switch (update.phase) {
+ case 'run_step': {
+ const data = update.data as Agents.RunStep | undefined;
+ return data?.stepDetails == null ? null : { event: StepEvents.ON_RUN_STEP, data };
+ }
+ case 'message_delta':
+ return { event: StepEvents.ON_MESSAGE_DELTA, data: update.data as Agents.MessageDeltaEvent };
+ case 'reasoning_delta':
+ return {
+ event: StepEvents.ON_REASONING_DELTA,
+ data: update.data as Agents.ReasoningDeltaEvent,
+ };
+ case 'run_step_delta':
+ return { event: StepEvents.ON_RUN_STEP_DELTA, data: update.data as Agents.RunStepDeltaEvent };
+ case 'run_step_completed':
+ return {
+ event: StepEvents.ON_RUN_STEP_COMPLETED,
+ data: update.data as { result?: Agents.ToolEndEvent | null },
+ };
+ case 'tool_preparation':
+ return {
+ event: StepEvents.ON_TOOL_PREPARATION,
+ data: update.data as Agents.ToolPreparationMarker,
+ };
+ case 'tool_calls_dispatched':
+ return {
+ event: StepEvents.ON_TOOL_CALLS_DISPATCHED,
+ data: update.data as Agents.ToolCallsDispatchedEvent,
+ };
+ case 'run_step_closed':
+ return {
+ event: StepEvents.ON_RUN_STEP_CLOSED,
+ data: update.data as Agents.RunStepClosedEvent,
+ };
+ default:
+ return null;
+ }
+}
+
+type CleanupRetry = Pick<
+ TSubagentActivityConfig,
+ 'retryAttempts' | 'retryBaseDelayMs' | 'recoveryDelayMs'
+>;
+
+/** Detached from execution: one small scope and one unref'd timer until storage recovers. */
+async function reconcileAbandonedContent(
+ scope: SubagentContentScope,
+ reconcile: SubagentContentMethods['reconcileSubagentContent'],
+ policy: CleanupRetry,
+ onError: (error: unknown) => void,
+): Promise<void> {
+ let attempt = 0;
+ for (;;) {
+ try {
+ await reconcile(scope);
+ return;
+ } catch (error) {
+ onError(error);
+ attempt = Math.min(attempt + 1, policy.retryAttempts);
+ const delay =
+ attempt < policy.retryAttempts
+ ? Math.min(policy.recoveryDelayMs, policy.retryBaseDelayMs * 2 ** (attempt - 1))
+ : policy.recoveryDelayMs;
+ await new Promise<void>((resolve) => {
+ const timer = setTimeout(resolve, delay);
+ timer.unref?.();
+ });
+ }
+ }
+}
+
+function reconcileAfterWrite(
+ writing: Promise<SubagentContentJournalResult> | undefined,
+ scope: SubagentContentScope,
+ reconcile: SubagentContentMethods['reconcileSubagentContent'],
+ policy: CleanupRetry,
+ onError: (error: unknown) => void,
+): void {
+ void Promise.resolve(writing)
+ .catch(() => undefined)
+ .then(() => reconcileAbandonedContent(scope, reconcile, policy, onError))
+ .catch(onError);
+}
+
+type JournalOptions = {
+ scope: SubagentContentScope;
+ leaseToken?: string;
+ flushMs: number;
+ batchBytes: number;
+ maxPendingBytes?: number;
+ settlementTimeoutMs?: number;
+ append: SubagentContentMethods['appendSubagentContentBatch'];
+ reconcile?: SubagentContentMethods['reconcileSubagentContent'];
+ cleanupRetry?: CleanupRetry;
+ notify: (watermark: SubagentContentWatermark) => Promise<void>;
+ onError: (error: unknown) => void;
+};
+
+type SubagentContentJournalResult =
+ | SubagentContentAppendResult
+ | { ok: false; error: { code: 'SUBAGENT_CONTENT_SETTLEMENT_TIMEOUT' } };
+
+/** Immutable append batches, not per-token replacements of a growing Mongo document. */
+export class SubagentContentJournal {
+ private readonly pending: Array<{ sequence: number; json?: string; bytes: number }> = [];
+ private pendingBytes = 0;
+ private captureStopped = false;
+ private readonly maxPendingBytes: number;
+ private timer?: ReturnType<typeof setTimeout>;
+ private writing?: Promise<SubagentContentJournalResult>;
+ private closing?: Promise<SubagentContentJournalResult>;
+ private terminalResult?: SubagentContentJournalResult;
+ private abandoned = false;
+ private closed = false;
+ private revision = 0;
+ private committedSequence = -1;
+ private observedSequence = -1;
+ private notification?: Promise<void>;
+ private pendingNotification?: SubagentContentWatermark;
+ private staged?: {
+ count: number;
+ bytes: number;
+ revision: number;
+ fromSequence: number;
+ throughSequence: number;
+ eventsJson: string;
+ };
+
+ constructor(private readonly options: JournalOptions) {
+ this.maxPendingBytes =
+ options.maxPendingBytes ?? subagentActivityConfigSchema.parse({}).contentPendingBytes;
+ }
+
+ get throughSequence(): number {
+ return this.observedSequence;
+ }
+
+ record(update: SubagentContentUpdate, sequence: number): void {
+ if (this.closed || sequence <= this.observedSequence) return;
+ if (sequence !== this.observedSequence + 1) throw new Error('Subagent content sequence gap');
+ this.observedSequence = sequence;
+ if (this.captureStopped) return;
+ const frame = subagentContentFrame(update);
+ /** Serialize before returning to the producer, which can mutate its event objects. */
+ let json: string | undefined;
+ try {
+ json = frame == null ? undefined : JSON.stringify({ sequence, frame });
+ } catch (error) {
+ this.captureStopped = true;
+ this.options.onError(error);
+ return;
+ }
+ const bytes = (json == null ? 0 : Buffer.byteLength(json, 'utf8')) + 64;
+ if (this.pendingBytes + bytes > this.maxPendingBytes) {
+ this.captureStopped = true;
+ this.options.onError(
+ new Error('Subagent content persistence backlog exceeded its byte limit'),
+ );
+ return;
+ }
+ this.pending.push({ sequence, json, bytes });
+ this.pendingBytes += bytes;
+ if (this.pendingBytes >= this.options.batchBytes && this.writing == null) {
+ this.startFlush();
+ } else {
+ this.schedule();
+ }
+ }
+
+ private schedule(): void {
+ if (this.closed || this.timer != null || this.pending.length === 0) return;
+ this.timer = setTimeout(() => {
+ this.timer = undefined;
+ this.startFlush();
+ }, this.options.flushMs);
+ this.timer.unref?.();
+ }
+
+ private startFlush(): void {
+ void this.flush()
+ .catch(this.options.onError)
+ .finally(() => this.schedule());
+ }
+
+ flush(): Promise<SubagentContentJournalResult> {
+ if (this.terminalResult != null) return Promise.resolve(this.terminalResult);
+ if (this.writing != null) return this.writing;
+ const operation = this.drain();
+ this.writing = operation;
+ void operation
+ .finally(() => {
+ if (this.writing === operation) this.writing = undefined;
+ })
+ .catch(() => undefined);
+ return operation;
+ }
+
+ private async drain(): Promise<SubagentContentJournalResult> {
+ while (this.pending.length > 0) {
+ if (this.staged == null) {
+ let count = 0;
+ let bytes = 2;
+ for (const entry of this.pending) {
+ if (count > 0 && bytes + entry.bytes + 1 > this.options.batchBytes) break;
+ bytes += entry.bytes + 1;
+ count++;
+ }
+ const batch = this.pending.slice(0, count);
+ this.staged = {
+ count,
+ bytes: batch.reduce((total, entry) => total + entry.bytes, 0),
+ revision: this.revision + 1,
+ fromSequence: this.committedSequence + 1,
+ throughSequence: batch[count - 1].sequence,
+ eventsJson: `[${batch.flatMap((entry) => (entry.json == null ? [] : [entry.json])).join(',')}]`,
+ };
+ }
+ const { count, bytes, ...batch } = this.staged;
+ const result = await this.options.append({
+ ...this.options.scope,
+ leaseToken: this.options.leaseToken,
+ ...batch,
+ });
+ if (this.abandoned) {
+ return { ok: false, error: { code: 'SUBAGENT_CONTENT_SETTLEMENT_TIMEOUT' } };
+ }
+ if (!result.ok) {
+ this.closed = true;
+ this.terminalResult = result;
+ return result;
+ }
+ this.pending.splice(0, count);
+ this.pendingBytes -= bytes;
+ this.revision = batch.revision;
+ this.committedSequence = batch.throughSequence;
+ this.staged = undefined;
+ this.notify({
+ taskId: this.options.scope.taskId,
+ revision: batch.revision,
+ throughSequence: batch.throughSequence,
+ });
+ }
+ return { ok: true };
+ }
+
+ private notify(watermark: SubagentContentWatermark): void {
+ if (this.abandoned) return;
+ this.pendingNotification = watermark;
+ if (this.notification != null) return;
+ const operation = (async () => {
+ while (this.pendingNotification != null) {
+ const next = this.pendingNotification;
+ this.pendingNotification = undefined;
+ await this.options.notify(next).catch(this.options.onError);
+ }
+ })();
+ this.notification = operation;
+ void operation
+ .finally(() => {
+ if (this.notification === operation) this.notification = undefined;
+ if (this.pendingNotification != null) this.notify(this.pendingNotification);
+ })
+ .catch(this.options.onError);
+ }
+
+ close(): Promise<SubagentContentJournalResult> {
+ if (this.closing != null) return this.closing;
+ this.closed = true;
+ if (this.timer != null) clearTimeout(this.timer);
+ this.closing = this.closeWithinBudget();
+ return this.closing;
+ }
+
+ private async closeWithinBudget(): Promise<SubagentContentJournalResult> {
+ let timeout: ReturnType<typeof setTimeout> | undefined;
+ let retry: ReturnType<typeof setTimeout> | undefined;
+ const timeoutMs =
+ this.options.settlementTimeoutMs ??
+ subagentActivityConfigSchema.parse({}).contentSettlementTimeoutMs;
+ const timeoutResult: SubagentContentJournalResult = {
+ ok: false,
+ error: { code: 'SUBAGENT_CONTENT_SETTLEMENT_TIMEOUT' },
+ };
+ const deadline = new Promise<SubagentContentJournalResult>((resolve) => {
+ timeout = setTimeout(() => {
+ this.abandoned = true;
+ this.terminalResult = timeoutResult;
+ this.pending.length = 0;
+ this.pendingBytes = 0;
+ this.staged = undefined;
+ this.pendingNotification = undefined;
+ if (this.options.reconcile != null) {
+ const { user, tenantId, parentConversationId, conversationId, taskId } =
+ this.options.scope;
+ reconcileAfterWrite(
+ this.writing,
+ { user, tenantId, parentConversationId, conversationId, taskId },
+ this.options.reconcile,
+ this.options.cleanupRetry ?? subagentActivityConfigSchema.parse({}),
+ this.options.onError,
+ );
+ }
+ resolve(timeoutResult);
+ }, timeoutMs);
+ });
+ try {
+ while (!this.abandoned) {
+ try {
+ return await Promise.race([this.flush(), deadline]);
+ } catch (error) {
+ this.options.onError(error);
+ /** Yield between attempts without letting a long flush cadence consume the whole budget. */
+ await Promise.race([
+ new Promise<void>((resolve) => {
+ retry = setTimeout(
+ resolve,
+ Math.max(1, Math.min(this.options.flushMs, timeoutMs / 2)),
+ );
+ }),
+ deadline,
+ ]);
+ }
+ }
+ return timeoutResult;
+ } finally {
+ if (timeout != null) clearTimeout(timeout);
+ if (retry != null) clearTimeout(retry);
+ }
+ }
+}
+
+type ContentReadMethods = Pick<
+ SubagentContentMethods,
+ 'getSubagentContentHead' | 'streamSubagentContentBatches'
+>;
+
+export type SubagentContentReadResult =
+ | {
+ ok: true;
+ value: {
+ content: TMessageContentParts[];
+ runSteps: Agents.RunStep[];
+ events: SubagentContentEvent[];
+ throughSequence: number;
+ revision: number;
+ targetThroughSequence: number;
+ nextCursor?: string;
+ };
+ }
+ | { ok: false; error: { code: 'SUBAGENT_CONTENT_AHEAD' | 'SUBAGENT_CONTENT_GAP' } };
+
+/** A sampled commit head fences the snapshot. Later batches are a suffix, never
+ * folded into this snapshot accidentally. Reads stream from one Mongo cursor. */
+export async function readSubagentContent(
+ methods: ContentReadMethods,
+ scope: SubagentContentScope,
+ afterSequence?: number,
+ options: { pageBytes?: number; throughRevision?: number } = {},
+): Promise<SubagentContentReadResult> {
+ const head = (await methods.getSubagentContentHead(scope, options.throughRevision)) ?? {
+ revision: 0,
+ throughSequence: -1,
+ };
+ if (options.throughRevision != null && head.revision !== options.throughRevision) {
+ return { ok: false, error: { code: 'SUBAGENT_CONTENT_GAP' } };
+ }
+ if ((afterSequence ?? -1) > head.throughSequence) {
+ return { ok: false, error: { code: 'SUBAGENT_CONTENT_AHEAD' } };
+ }
+ if (afterSequence != null && afterSequence === head.throughSequence) {
+ return {
+ ok: true,
+ value: {
+ revision: head.revision,
+ throughSequence: afterSequence,
+ targetThroughSequence: head.throughSequence,
+ content: [],
+ runSteps: [],
+ events: [],
+ },
+ };
+ }
+ const aggregator = createContentAggregator();
+ const timing = createToolTimingAdapter({
+ emit: (event) =>
+ timing.child(aggregator, {
+ phase: event.event.slice(3),
+ data: event.data,
+ }),
+ });
+ const events: SubagentContentEvent[] = [];
+ let throughSequence = afterSequence ?? -1;
+ let revision: number | undefined;
+ let pageBytes = 0;
+ let stopped = false;
+ const pageLimit = options.pageBytes ?? subagentActivityConfigSchema.parse({}).contentPageBytes;
+ pages: for await (const batch of methods.streamSubagentContentBatches(
+ scope,
+ head.revision,
+ afterSequence,
+ )) {
+ if (
+ batch.fromSequence > throughSequence + 1 ||
+ batch.throughSequence <= throughSequence ||
+ (revision != null && batch.revision !== revision + 1)
+ ) {
+ return { ok: false, error: { code: 'SUBAGENT_CONTENT_GAP' } };
+ }
+ const entries: SubagentContentEvent[] = JSON.parse(batch.eventsJson);
+ let previous = batch.fromSequence - 1;
+ for (const entry of entries) {
+ if (
+ !Number.isSafeInteger(entry.sequence) ||
+ entry.sequence <= previous ||
+ entry.sequence < batch.fromSequence ||
+ entry.sequence > batch.throughSequence
+ ) {
+ return { ok: false, error: { code: 'SUBAGENT_CONTENT_GAP' } };
+ }
+ previous = entry.sequence;
+ if (entry.sequence <= (afterSequence ?? -1)) continue;
+ const bytes = Buffer.byteLength(JSON.stringify(entry), 'utf8');
+ /** One oversized public event remains whole; a full-part/preview protocol
+ * is required before this can be a hard per-response byte ceiling. */
+ if (pageBytes > 0 && pageBytes + bytes > pageLimit) {
+ stopped = true;
+ break pages;
+ }
+ pageBytes += bytes;
+ throughSequence = entry.sequence;
+ revision = batch.revision;
+ if (afterSequence != null) {
+ events.push(entry);
+ continue;
+ }
+ const frame = entry.frame;
+ if (frame.event === StepEvents.ON_RUN_STEP_CLOSED) {
+ const step = aggregator.stepMap.get(frame.data.id);
+ if (step != null) step.status = frame.data.status;
+ const part = step == null ? undefined : aggregator.contentParts[step.index];
+ if (part?.type === ContentTypes.TOOL_CALL && part.tool_call != null) {
+ part.tool_call.runStepStatus = frame.data.status;
+ Object.assign(part.tool_call, getRunStepCloseMetadata(frame.data));
+ const duration = getRunStepDurationMs(frame.data);
+ if (duration != null) part.tool_call.runStepDurationMs = duration;
+ }
+ continue;
+ }
+ if (frame.event === StepEvents.ON_RUN_STEP_DELTA) await timing.delta(frame.data);
+ /** SDK and wire enums have identical values, as in main-chat Redis recovery. */
+ if (
+ frame.event !== StepEvents.ON_TOOL_PREPARATION &&
+ frame.event !== StepEvents.ON_TOOL_CALLS_DISPATCHED
+ ) {
+ aggregator.aggregateContent({
+ event: CONTENT_GRAPH_EVENTS[frame.event],
+ data: frame.data,
+ } as Parameters<typeof aggregator.aggregateContent>[0]);
+ }
+ if (frame.event === StepEvents.ON_MESSAGE_DELTA) {
+ const step = aggregator.stepMap.get(frame.data.id);
+ const part = step == null ? undefined : aggregator.contentParts[step.index];
+ if (part?.type === ContentTypes.TEXT && step?.stepDetails.type === 'message_creation') {
+ const creation = step.stepDetails.message_creation;
+ const phase = creation != null && 'phase' in creation ? creation.phase : undefined;
+ if (phase === 'commentary' || phase === 'final_answer') part.phase = phase;
+ }
+ }
+ timing.child(aggregator, { phase: frame.event.slice(3), data: frame.data });
+ }
+ throughSequence = batch.throughSequence;
+ revision = batch.revision;
+ }
+ if (
+ !stopped &&
+ (throughSequence !== head.throughSequence || (revision != null && revision !== head.revision))
+ ) {
+ return { ok: false, error: { code: 'SUBAGENT_CONTENT_GAP' } };
+ }
+ return {
+ ok: true,
+ value: {
+ revision: revision ?? head.revision,
+ throughSequence,
+ targetThroughSequence: head.throughSequence,
+ ...(stopped
+ ? {
+ nextCursor: Buffer.from(
+ JSON.stringify({
+ afterSequence: throughSequence,
+ throughRevision: head.revision,
+ }),
+ ).toString('base64url'),
+ }
+ : {}),
+ content: aggregator.contentParts as TMessageContentParts[],
+ runSteps: toWireRunSteps(
+ [...aggregator.stepMap.values()].filter(
+ (step): step is NonNullable<typeof step> => step != null,
+ ),
+ ),
+ events,
+ },
+ };
+}
+
+type ContentHandlerDependencies = ContentReadMethods &
+ Pick<ConversationMethods, 'getConvoOwnership' | 'getSubagentThreadForParent'> &
+ Pick<MessageMethods, 'getMessages'>;
+
+const validId = (value: string | undefined): value is string =>
+ value != null && value.trim() !== '' && Buffer.byteLength(value, 'utf8') <= 512;
+
+export function createSubagentTaskContentHandler(
+ deps: ContentHandlerDependencies,
+ getPageBytes: () => number = () => subagentActivityConfigSchema.parse({}).contentPageBytes,
+ getRecoveryGraceMs: () => number = () =>
+ subagentActivityConfigSchema.parse({}).contentRecoveryGraceMs,
+): (req: ServerRequest, res: Response) => Promise<void> {
+ return async (req: ServerRequest, res: Response): Promise<void> => {
+ const user = req.user?.id;
+ const tenantId = req.user?.tenantId || undefined;
+ const { parentConversationId, threadId, taskId } = req.params as {
+ parentConversationId?: string;
+ threadId?: string;
+ taskId?: string;
+ };
+ if (
+ !user ||
+ !validId(parentConversationId) ||
+ !validId(threadId) ||
+ !validId(taskId) ||
+ parentConversationId === threadId
+ ) {
+ res.status(404).json({ error: 'Conversation not found' });
+ return;
+ }
+ const after = req.query.afterSequence;
+ let afterSequence = after == null ? undefined : Number(after);
+ let throughRevision: number | undefined;
+ const cursor = req.query.cursor;
+ if (cursor != null) {
+ try {
+ if (typeof cursor !== 'string' || cursor.length > 1024 || after != null)
+ throw new Error('Invalid cursor');
+ const parsed: { afterSequence?: number; throughRevision?: number } = JSON.parse(
+ Buffer.from(cursor, 'base64url').toString('utf8'),
+ );
+ if (
+ !Number.isSafeInteger(parsed.afterSequence) ||
+ parsed.afterSequence! < -1 ||
+ !Number.isSafeInteger(parsed.throughRevision) ||
+ parsed.throughRevision! < 0
+ )
+ throw new Error('Invalid cursor');
+ afterSequence = parsed.afterSequence;
+ throughRevision = parsed.throughRevision;
+ } catch {
+ res
+ .status(400)
+ .json({ error: 'Invalid content cursor', code: 'SUBAGENT_CONTENT_INVALID_CURSOR' });
+ return;
+ }
+ }
+ if (
+ after != null &&
+ (typeof after !== 'string' ||
+ !/^-?\d+$/.test(after) ||
+ !Number.isSafeInteger(afterSequence) ||
+ afterSequence! < -1)
+ ) {
+ res
+ .status(400)
+ .json({ error: 'Invalid content cursor', code: 'SUBAGENT_CONTENT_INVALID_CURSOR' });
+ return;
+ }
+ const scope: SubagentContentScope = {
+ user,
+ tenantId,
+ parentConversationId,
+ conversationId: threadId,
+ taskId,
+ };
+ try {
+ const [parent, child, messages] = await Promise.all([
+ deps.getConvoOwnership(user, parentConversationId, tenantId ?? null),
+ deps.getSubagentThreadForParent({
+ user,
+ parentConversationId,
+ conversationId: threadId,
+ tenantId,
+ }),
+ deps.getMessages(
+ {
+ user,
+ conversationId: threadId,
+ messageId: { $in: [`${taskId}:user`, `${taskId}:assistant`] },
+ ...(tenantId == null ? { tenantId: { $exists: false } } : { tenantId }),
+ $or: [{ expiredAt: null }, { expiredAt: { $gt: new Date() } }],
+ },
+ 'messageId unfinished error expiredAt createdAt +subagentTask +subagentContent',
+ { limit: 2 },
+ ),
+ ]);
+ const seed = messages.find((message) => message.messageId === `${taskId}:user`);
+ const assistant = messages.find((message) => message.messageId === `${taskId}:assistant`);
+ if (
+ parent == null ||
+ child == null ||
+ seed == null ||
+ parent.tenantId !== tenantId ||
+ child.tenantId !== tenantId ||
+ child.subagentThread?.parentConversationId !== parentConversationId
+ ) {
+ res.status(404).json({ error: 'Conversation not found' });
+ return;
+ }
+ if (seed.subagentContent?.version !== 1 || seed.subagentContent.deleted === true) {
+ res
+ .status(409)
+ .json({ error: 'Subagent content unavailable', code: 'SUBAGENT_CONTENT_UNAVAILABLE' });
+ return;
+ }
+ const result = await readSubagentContent(deps, scope, afterSequence, {
+ pageBytes: getPageBytes(),
+ throughRevision,
+ });
+ if (!result.ok) {
+ res
+ .status(409)
+ .json({ error: 'Subagent content must be reloaded', code: result.error.code });
+ return;
+ }
+ const { content, runSteps, events, ...watermark } = result.value;
+ const durableStatus = assistant?.subagentTask?.status;
+ const running = durableStatus == null || durableStatus === 'running';
+ const leaseActive =
+ child.subagentThreadLease?.taskId === taskId &&
+ child.subagentThreadLease.expiresAt > new Date();
+ let status: SubagentThreadStatus = 'completed';
+ if (running) status = leaseActive ? 'running' : 'interrupted';
+ else if (durableStatus === 'error') status = 'failed';
+ else if (durableStatus === 'cancelled') status = 'cancelled';
+ /** A live lease proves ownership, not that every producer-observed event
+ * has reached storage. Only terminal expected-watermark equality is complete. */
+ const recovery =
+ !running && assistant?.subagentContent?.throughSequence === watermark.targetThroughSequence
+ ? 'complete'
+ : 'partial';
+ const settledAt =
+ assistant?.createdAt == null ? NaN : new Date(assistant.createdAt).getTime();
+ const retryUntil = settledAt + getRecoveryGraceMs();
+ const identity = {
+ ...watermark,
+ ...(!running &&
+ recovery === 'partial' &&
+ Number.isFinite(retryUntil) &&
+ retryUntil > Date.now()
+ ? { retryUntil }
+ : {}),
+ parentConversationId,
+ threadId,
+ taskId,
+ messageId: `${taskId}:assistant`,
+ parentMessageId: `${taskId}:user`,
+ sender: child.subagentThread.subagentType,
+ status,
+ recovery,
+ } as const;
+ const response: SubagentTaskContentResponse =
+ afterSequence == null
+ ? { ...identity, mode: 'snapshot', content, runSteps }
+ : { ...identity, mode: 'suffix', afterSequence, events };
+ res.json(response);
+ } catch (error) {
+ logger.error('[subagentContent] Content recovery unavailable', getSafeErrorMetadata(error));
+ res
+ .status(503)
+ .json({ error: 'Subagent content unavailable', code: 'SUBAGENT_CONTENT_UNAVAILABLE' });
+ }
+ };
+}
diff --git a/packages/api/src/agents/subagentThreads.spec.ts b/packages/api/src/agents/subagentThreads.spec.ts
index 114ef2aa61..e253b18f99 100644
--- a/packages/api/src/agents/subagentThreads.spec.ts
+++ b/packages/api/src/agents/subagentThreads.spec.ts
@@ -36,8 +36,14 @@ import {
createSubagentThreadTaskStore,
SubagentThreadTaskStore,
} from './subagentThreads';
+import {
+ createMCPRequestContext,
+ cleanupMCPRequestContext,
+ getMCPRequestSignal,
+} from '~/mcp/request';
import { controlFingerprint, SubagentTaskOwnerUnavailableError } from './subagentTaskRouting';
import { snapshotActivity, snapshotActivitySummary } from './digest';
+import { resolveScheduledMCPBearerConfig } from '~/schedules/bearer';
import { SUBAGENT_COMPLETION_DELIVERY } from './subagentDelivery';
import { createSubagentAttemptKey } from './subagentThreadIds';
import { SubagentActivityStream } from './subagentActivity';
@@ -310,6 +316,88 @@ describe('SubagentThreadTaskStore', () => {
await expect(automaticStore.listTasks(automatic.scopeId)).resolves.toEqual([]);
});
+ it.each([false, true])(
+ 'retains MCP ownership after parent settlement (wakeups: %s)',
+ async (completionWakeups) => {
+ const userId = 'retained-mcp-user';
+ const parentConversationId = randomUUID();
+ await saveParent(userId, parentConversationId);
+ const store = new SubagentThreadTaskStore(methods);
+ const context = createMCPRequestContext();
+ const signal = getMCPRequestSignal(context);
+ const disconnect = jest.fn(async () => undefined);
+ context.connections.set('retained', { disconnect });
+ const config = buildSubagentThreadTaskConfig(
+ store,
+ { userId, parentConversationId },
+ { completionWakeups, requestScopedConnections: context },
+ );
+ const request = taskRequest(config.scopeId, {
+ run: async () => {
+ await cleanupMCPRequestContext(context);
+ expect(signal.aborted).toBe(false);
+ expect(disconnect).not.toHaveBeenCalled();
+ await expect(
+ resolveScheduledMCPBearerConfig({
+ context,
+ serverName: 'retained',
+ config: { type: 'stdio', command: 'node', args: [], source: 'yaml' },
+ }),
+ ).resolves.toMatchObject({ command: 'node' });
+ return { content: 'MCP scope remains open for the child.' };
+ },
+ });
+ const started = config.store.start(request);
+ expect(config.store.start(request)).toMatchObject({ accepted: true, isNew: false });
+ await waitForSettled(store, config.scopeId, started);
+ expect(store.get(config.scopeId, requireAccepted(started).task.taskId)?.status).toBe(
+ 'completed',
+ );
+ await waitUntil(() => disconnect.mock.calls.length === 1, 'last child MCP cleanup');
+ expect(signal.aborted).toBe(true);
+ await cleanupMCPRequestContext(context);
+ expect(disconnect).toHaveBeenCalledTimes(1);
+ store.destroyActivityStream();
+ },
+ );
+
+ it('releases retained MCP ownership when preparation fails before provider work', async () => {
+ const store = new SubagentThreadTaskStore(methods);
+ const context = createMCPRequestContext();
+ const config = buildSubagentThreadTaskConfig(
+ store,
+ { userId: 'missing-mcp-parent', parentConversationId: randomUUID() },
+ { requestScopedConnections: context },
+ );
+ const run = jest.fn(taskRequest('').run);
+ const started = config.store.start(taskRequest(config.scopeId, { run }));
+ await cleanupMCPRequestContext(context);
+ expect(context.cleanupStarted).toBe(false);
+ await waitForSettled(store, config.scopeId, started);
+ expect(run).not.toHaveBeenCalled();
+ expect(context.cleanupStarted).toBe(true);
+ store.destroyActivityStream();
+ });
+
+ it('releases retained MCP ownership when cancellation prevents the launch callback', async () => {
+ const store = new SubagentThreadTaskStore(methods);
+ const context = createMCPRequestContext();
+ const config = buildSubagentThreadTaskConfig(
+ store,
+ { userId: 'cancelled-mcp-user', parentConversationId: randomUUID() },
+ { requestScopedConnections: context },
+ );
+ const run = jest.fn(taskRequest('').run);
+ const started = config.store.start(taskRequest(config.scopeId, { run }));
+ config.store.control(config.scopeId, requireAccepted(started).task.taskId, {
+ action: 'cancel',
+ });
+ await cleanupMCPRequestContext(context);
+ await waitUntil(() => context.cleanupStarted, 'cancelled child MCP release');
+ expect(run).not.toHaveBeenCalled();
+ store.destroyActivityStream();
+ });
+
it('scopes the plain agent-name lookup to the execution tenant', async () => {
const userId = new mongoose.Types.ObjectId().toString();
const id = 'tenant-name-agent';
diff --git a/packages/api/src/agents/subagentThreads.ts b/packages/api/src/agents/subagentThreads.ts
index 5b49f2ecc4..c7ea66fbc8 100644
--- a/packages/api/src/agents/subagentThreads.ts
+++ b/packages/api/src/agents/subagentThreads.ts
@@ -38,6 +38,7 @@ import type {
SubagentActivityTerminalStatus,
} from './subagentActivity';
import type { SubagentTaskControlTransport } from './subagentTaskRouting';
+import type { RequestScopedMCPConnectionStore } from '~/mcp/types';
import type { UsageMetadata } from '~/stream/interfaces/IJobStore';
import type { HostSubagentTaskConfig } from './subagentDelivery';
import type { ActivitySnapshot, ActivityTree } from './digest';
@@ -58,6 +59,9 @@ import { ActivityRecorder, activityTreeFromProjection } from './digest';
import { runWithDetachedSubagentUsage } from './subagentTaskContext';
import { SUBAGENT_COMPLETION_DELIVERY } from './subagentDelivery';
import { createConcurrencyLimiter } from '~/utils/promise';
+import { SubagentContentJournal } from './subagentContent';
+import { retainMCPRequestContext } from '~/mcp/request';
+import { getSafeErrorMetadata } from '~/utils/errors';
import { InMemoryEventTransport } from '~/stream';
import { aggregateEmittedUsage } from './usage';
@@ -129,7 +133,9 @@ type SubagentThreadMethods = Pick<
| 'saveConvo'
| 'saveMessage'
> &
- Partial<Pick<AllMethods, 'getAgentName'>>;
+ Partial<
+ Pick<AllMethods, 'getAgentName' | 'appendSubagentContentBatch' | 'reconcileSubagentContent'>
+ >;
interface SubagentThreadScope {
version: typeof SCOPE_VERSION;
@@ -157,6 +163,7 @@ interface PreparedThread {
}
interface HostSubagentTaskStartRequest extends SubagentTaskStartRequest {
+ requestScopedConnections?: RequestScopedMCPConnectionStore;
scheduleMCPIdentity?: ScheduledMCPIdentity | null;
completionDelivery?: typeof SUBAGENT_COMPLETION_DELIVERY;
}
@@ -211,6 +218,7 @@ interface TaskThreadLease {
settling: boolean;
/** Resolves only after child persistence and lease cleanup finish. */
execution?: Promise<void>;
+ content?: SubagentContentJournal;
/** Ordered observational tail; canonical child settlement never awaits it. */
activityTail?: Promise<void>;
activityWorkerActive?: boolean;
@@ -1220,6 +1228,14 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
}
}
+ get contentPageBytes(): number {
+ return this.activityOptions.contentPageBytes;
+ }
+
+ get contentRecoveryGraceMs(): number {
+ return this.activityOptions.contentRecoveryGraceMs;
+ }
+
/** Host injects the base configuration before task admission. */
configureActivity(options: Partial<TSubagentActivityConfig> = {}): TSubagentActivityConfig {
this.activityOptions = subagentActivityConfigSchema.parse(options);
@@ -1505,11 +1521,19 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
}
let started: SubagentTaskStartResult;
+ let executionStarted = false;
+ let releaseContext: (() => void) | undefined;
try {
+ const context = (request as HostSubagentTaskStartRequest).requestScopedConnections;
+ if (context) releaseContext = retainMCPRequestContext(context);
started = super.start({
...request,
threadId,
run: (runtime: SubagentTaskRuntime) => {
+ executionStarted = true;
+ if (releaseContext) {
+ runtime.signal.addEventListener('abort', releaseContext, { once: true });
+ }
const execution = this.runWithOwnerContext(scope, async () => {
lease.taskId = runtime.taskId;
lease.running = true;
@@ -1568,6 +1592,41 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
const preparedThread = prepared;
const recorder = this.trackActivity(request.scopeId, runtime.taskId);
let activitySequence = 0;
+ const append = this.methods.appendSubagentContentBatch;
+ if (append != null && this.activityOptions.contentRecoveryEnabled) {
+ lease.content = new SubagentContentJournal({
+ scope: {
+ user: scope.userId,
+ tenantId: scope.tenantId,
+ parentConversationId: scope.parentConversationId,
+ conversationId: preparedThread.conversation.conversationId,
+ taskId: runtime.taskId,
+ },
+ leaseToken: lease.shared?.token,
+ flushMs: this.activityOptions.contentFlushMs,
+ batchBytes: this.activityOptions.contentBatchBytes,
+ maxPendingBytes: this.activityOptions.contentPendingBytes,
+ settlementTimeoutMs: this.activityOptions.contentSettlementTimeoutMs,
+ append,
+ reconcile: this.methods.reconcileSubagentContent,
+ cleanupRetry: {
+ retryAttempts: this.activityOptions.retryAttempts,
+ retryBaseDelayMs: this.activityOptions.retryBaseDelayMs,
+ recoveryDelayMs: this.activityOptions.recoveryDelayMs,
+ },
+ notify: (watermark) =>
+ this.activityStream.publishContent(
+ preparedThread.conversation.conversationId,
+ runtime.taskId,
+ watermark,
+ ),
+ onError: (error) =>
+ logger.warn(
+ '[subagentThreads] Public child content persistence unavailable',
+ getSafeErrorMetadata(error),
+ ),
+ });
+ }
const activityRuntime: SubagentTaskRuntime = {
...runtime,
reportProgress: (event) => {
@@ -1577,6 +1636,7 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
activityEventId: `${runtime.taskId}:${sequence}`,
activitySequence: sequence,
};
+ lease.content?.record(activityEvent, sequence);
runtime.reportProgress(activityEvent);
recordActivity(recorder, activityEvent);
this.publishActivity(
@@ -1599,6 +1659,7 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
);
}
lease.settling = true;
+ await this.closeContent(lease);
await this.persistResult(
scope,
request,
@@ -1606,6 +1667,7 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
prepared,
result,
detachedUsage,
+ lease.content?.throughSequence,
);
activityTerminal = 'completed';
return result;
@@ -1617,6 +1679,7 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
}
const mayPersist =
lease.shared == null || (await this.renewSharedLease(scope, threadId, lease));
+ await this.closeContent(lease);
const terminalTask = this.get(request.scopeId, runtime.taskId);
if (runtime.signal.aborted && terminalTask?.status === 'cancelled') {
activityTerminal = 'cancelled';
@@ -1627,6 +1690,7 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
request,
runtime.taskId,
detachedUsage,
+ lease.content?.throughSequence,
).catch((persistError) => {
logger.error(
'[subagentThreads] Failed to persist child-thread cancellation',
@@ -1649,6 +1713,7 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
runtime.taskId,
error,
detachedUsage,
+ lease.content?.throughSequence,
).catch((persistError) => {
logger.error(
'[subagentThreads] Failed to persist child-thread failure',
@@ -1681,10 +1746,15 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
() => undefined,
);
lease.execution = settlement;
- return execution;
+ if (!releaseContext) return execution;
+ return execution.finally(() => {
+ if (releaseContext) runtime.signal.removeEventListener('abort', releaseContext);
+ releaseContext?.();
+ });
},
});
} catch (error) {
+ releaseContext?.();
if (ownsLease && this.activeThreads.get(lockKey) === lease) {
this.activeThreads.delete(lockKey);
}
@@ -1693,8 +1763,17 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
if (started.accepted && started.isNew) {
lease.taskId = started.task.taskId;
- } else if (ownsLease && this.activeThreads.get(lockKey) === lease) {
- this.activeThreads.delete(lockKey);
+ if (releaseContext) {
+ // The SDK skips run() if cancellation wins before its launch microtask.
+ queueMicrotask(() => {
+ if (!executionStarted) releaseContext?.();
+ });
+ }
+ } else {
+ releaseContext?.();
+ if (ownsLease && this.activeThreads.get(lockKey) === lease) {
+ this.activeThreads.delete(lockKey);
+ }
}
return started;
}
@@ -3240,6 +3319,12 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
text: request.input,
endpoint: EModelEndpoint.agents,
isCreatedByUser: true,
+ ...(this.methods.appendSubagentContentBatch == null ||
+ !this.activityOptions.contentRecoveryEnabled
+ ? {}
+ : {
+ subagentContent: { version: 1 as const },
+ }),
subagentTask: {
attemptKey,
parentRunId: request.parentRunId,
@@ -3315,6 +3400,22 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
);
}
+ private async closeContent(lease: TaskThreadLease): Promise<void> {
+ const result = await lease.content?.close().catch((error) => {
+ /** The terminal row records the expected watermark, so a failed final
+ * flush exposes a partial prefix instead of pretending history is complete. */
+ logger.warn(
+ '[subagentThreads] Public child content handoff incomplete',
+ getSafeErrorMetadata(error),
+ );
+ });
+ if (result != null && !result.ok) {
+ logger.warn('[subagentThreads] Public child content handoff unavailable', {
+ code: result.error.code,
+ });
+ }
+ }
+
private async persistResult(
scope: SubagentThreadScope,
request: SubagentTaskStartRequest,
@@ -3322,6 +3423,7 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
prepared: PreparedThread,
result: { content: string; messages?: BaseMessage[] },
detachedUsage: UsageMetadata[],
+ contentThroughSequence?: number,
): Promise<void> {
if (prepared.userMessageId == null) {
throw new Error('The child-thread input was not prepared.');
@@ -3366,6 +3468,11 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
endpoint: EModelEndpoint.agents,
isCreatedByUser: false,
unfinished: false,
+ ...(contentThroughSequence == null
+ ? {}
+ : {
+ subagentContent: { version: 1 as const, throughSequence: contentThroughSequence },
+ }),
...(subagentTranscript == null ? {} : { subagentTranscript }),
...(subagentActivityProjection == null ? {} : { subagentActivityProjection }),
subagentTask: {
@@ -3394,6 +3501,7 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
taskId: string,
error: unknown,
detachedUsage: UsageMetadata[],
+ contentThroughSequence?: number,
): Promise<void> {
await this.flushControlReceiptsForSettlement(request.scopeId, taskId);
const conversation = await this.currentConversation(scope, request, threadId);
@@ -3412,6 +3520,11 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
endpoint: EModelEndpoint.agents,
isCreatedByUser: false,
unfinished: false,
+ ...(contentThroughSequence == null
+ ? {}
+ : {
+ subagentContent: { version: 1 as const, throughSequence: contentThroughSequence },
+ }),
error: true,
subagentTask: {
attemptKey: createSubagentAttemptKey(request.scopeId, request.idempotencyKey),
@@ -3467,6 +3580,7 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
request: SubagentTaskStartRequest,
taskId: string,
detachedUsage: UsageMetadata[],
+ contentThroughSequence?: number,
): Promise<void> {
await this.flushControlReceiptsForSettlement(request.scopeId, taskId);
const conversation = await this.currentConversation(scope, request, threadId);
@@ -3485,6 +3599,11 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
endpoint: EModelEndpoint.agents,
isCreatedByUser: false,
unfinished: false,
+ ...(contentThroughSequence == null
+ ? {}
+ : {
+ subagentContent: { version: 1 as const, throughSequence: contentThroughSequence },
+ }),
subagentTask: {
attemptKey: createSubagentAttemptKey(request.scopeId, request.idempotencyKey),
parentRunId: request.parentRunId,
@@ -3723,9 +3842,12 @@ const completionWakeupStores = new WeakMap<SubagentThreadTaskStore, CompletionWa
function completionWakeupStore(
store: SubagentThreadTaskStore,
identity?: ScheduledMCPIdentity,
+ requestScopedConnections?: RequestScopedMCPConnectionStore,
+ completionWakeups = true,
): CompletionWakeupStore {
const captured = identity && Object.freeze(structuredClone(identity));
- const existing = captured ? undefined : completionWakeupStores.get(store);
+ const cacheable = !captured && !requestScopedConnections && completionWakeups;
+ const existing = cacheable ? completionWakeupStores.get(store) : undefined;
if (existing != null) {
return existing;
}
@@ -3734,7 +3856,8 @@ function completionWakeupStore(
start: (request) => {
const hostRequest: HostSubagentTaskStartRequest = {
...request,
- completionDelivery: SUBAGENT_COMPLETION_DELIVERY,
+ completionDelivery: completionWakeups ? SUBAGENT_COMPLETION_DELIVERY : undefined,
+ requestScopedConnections,
scheduleMCPIdentity: captured ?? null,
};
return store.start(hostRequest);
@@ -3749,18 +3872,27 @@ function completionWakeupStore(
hasTasks: (scopeId) => store.hasTasks(scopeId),
listTasks: (scopeId) => store.listTasks(scopeId),
};
- if (!captured) completionWakeupStores.set(store, adapter);
+ if (cacheable) completionWakeupStores.set(store, adapter);
return adapter;
}
export function buildSubagentThreadTaskConfig(
store: SubagentThreadTaskStore,
scope: Omit<SubagentThreadScope, 'version'>,
- options: { completionWakeups?: boolean; scheduleMCPIdentity?: ScheduledMCPIdentity } = {},
+ options: {
+ completionWakeups?: boolean;
+ scheduleMCPIdentity?: ScheduledMCPIdentity;
+ requestScopedConnections?: RequestScopedMCPConnectionStore;
+ } = {},
): HostSubagentTaskConfig {
const taskStore =
- options.completionWakeups === true
- ? completionWakeupStore(store, options.scheduleMCPIdentity)
+ options.completionWakeups === true || options.requestScopedConnections
+ ? completionWakeupStore(
+ store,
+ options.scheduleMCPIdentity,
+ options.requestScopedConnections,
+ options.completionWakeups === true,
+ )
: store;
return {
store: taskStore,
diff --git a/packages/api/src/agents/toolTiming.ts b/packages/api/src/agents/toolTiming.ts
index c35c597e11..bf0a4df693 100644
--- a/packages/api/src/agents/toolTiming.ts
+++ b/packages/api/src/agents/toolTiming.ts
@@ -38,17 +38,20 @@ type ToolCompletion = {
type ChildTimingStamps = { observedAt?: number; dispatchedAt?: number };
type ChildTimingAggregator = {
- stepMap?: Map<string, { index: number }>;
- contentParts?: Array<{
- type?: string;
- tool_call?: {
- id?: string;
- toolPreparationStartedAt?: number;
- toolDispatchedAt?: number;
- toolPreparationDurationMs?: number;
- toolExecutionDurationMs?: number;
- };
- }>;
+ stepMap?: Map<string, { index: number } | undefined>;
+ contentParts?: Array<
+ | {
+ type?: string;
+ tool_call?: {
+ id?: string;
+ toolPreparationStartedAt?: number;
+ toolDispatchedAt?: number;
+ toolPreparationDurationMs?: number;
+ toolExecutionDurationMs?: number;
+ };
+ }
+ | undefined
+ >;
};
export type ToolTimingAdapter = {
diff --git a/packages/api/src/agents/view.spec.ts b/packages/api/src/agents/view.spec.ts
index 28f4ce87cb..cbcb43c04a 100644
--- a/packages/api/src/agents/view.spec.ts
+++ b/packages/api/src/agents/view.spec.ts
@@ -87,6 +87,54 @@ const createRequest = (
}) as ServerRequest;
describe('subagent thread parent-scoped view', () => {
+ it.each([
+ [false, true, false],
+ [true, false, true],
+ [undefined, true, true],
+ [undefined, false, false],
+ ])(
+ 'uses the seed recovery capability %s over assistant capability %s',
+ async (seed, assistant, expected) => {
+ const handler = createSubagentThreadViewHandler({
+ getConvoOwnership: jest.fn().mockResolvedValue(parent),
+ getSubagentThreadForParent: jest.fn().mockResolvedValue(child),
+ getMessagesForSubagentThreadView: jest
+ .fn()
+ .mockResolvedValue([
+ { ...message('task-1:assistant', 'completed'), contentRecoveryAvailable: assistant },
+ ...(seed == null
+ ? []
+ : [{ ...message('task-1:user', 'running', true), contentRecoveryAvailable: seed }]),
+ ]),
+ });
+ const { response, json } = createResponse();
+ await handler(createRequest({}, { taskId: 'task-1' }), response);
+ expect(json.mock.calls[0][0].turns[0].contentRecoveryAvailable).toBe(expected);
+ },
+ );
+
+ it.each([false, true])(
+ 'returns task recovery enrollment %s from its loaded seed',
+ async (available) => {
+ const input = {
+ ...message('task-1:user', 'running', true),
+ contentRecoveryAvailable: available,
+ };
+ const getMessages = jest.fn().mockResolvedValue([input]);
+ const handler = createSubagentThreadViewHandler({
+ getConvoOwnership: jest.fn().mockResolvedValue(parent),
+ getSubagentThreadForParent: jest.fn().mockResolvedValue(child),
+ getMessagesForSubagentThreadView: getMessages,
+ });
+ const { response, json } = createResponse();
+ await handler(createRequest({}, { taskId: 'task-1' }), response);
+ expect(json.mock.calls[0][0].turns).toEqual([
+ expect.objectContaining({ taskId: 'task-1', contentRecoveryAvailable: available }),
+ ]);
+ expect(getMessages).toHaveBeenCalledTimes(1);
+ },
+ );
+
it('returns a bounded public child projection through the owning parent', async () => {
const getConvoOwnership = jest.fn().mockResolvedValue(parent);
const newest = {
@@ -132,6 +180,7 @@ describe('subagent thread parent-scoped view', () => {
turns: [
{
taskId: 'task-1',
+ contentRecoveryAvailable: false,
trigger: {
kind: 'parent_dispatch',
summary: 'Investigate this.',
diff --git a/packages/api/src/agents/view.ts b/packages/api/src/agents/view.ts
index 2037825a02..dc6449523a 100644
--- a/packages/api/src/agents/view.ts
+++ b/packages/api/src/agents/view.ts
@@ -339,6 +339,10 @@ const publicThreadTurns = (
return [
{
taskId,
+ contentRecoveryAvailable:
+ record.input?.contentRecoveryAvailable ??
+ record.assistant?.contentRecoveryAvailable ??
+ false,
trigger: {
kind: triggerKind,
summary: eventThread ? '' : (input?.text ?? ''),
diff --git a/packages/api/src/mcp/__tests__/request.test.ts b/packages/api/src/mcp/__tests__/request.test.ts
index 978cc53bbf..47a5766999 100644
--- a/packages/api/src/mcp/__tests__/request.test.ts
+++ b/packages/api/src/mcp/__tests__/request.test.ts
@@ -1,9 +1,11 @@
import { EventEmitter } from 'events';
+import { logger } from '@librechat/data-schemas';
import {
createMCPRuntimeRequestBody,
createMCPRequestContext,
getMCPRequestSignal,
+ retainMCPRequestContext,
quiesceMCPRequestContext,
cleanupMCPRequestContext,
getMCPRequestContext,
@@ -115,6 +117,254 @@ describe('MCP request context', () => {
});
});
+describe('retained MCP request contexts', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it('returns from parent cleanup without closing either child owner', async () => {
+ const req = {};
+ const res = createResponse();
+ const context = getMCPRequestContext(req, res)!;
+ const signal = getMCPRequestSignal(context);
+ const disconnect = jest.fn().mockResolvedValue(undefined);
+ context.connections.set('server', { disconnect });
+ const releaseFirst = retainMCPRequestContext(context);
+ const releaseSecond = retainMCPRequestContext(context);
+
+ res.writableEnded = true;
+ res.emit('finish');
+ await cleanupMCPRequestContextForReq(req);
+
+ expect(context.cleanupStarted).toBe(false);
+ expect(signal.aborted).toBe(false);
+ expect(getMCPRequestContext(req, res)).toBe(context);
+ expect(disconnect).not.toHaveBeenCalled();
+
+ expect(releaseFirst()).toBeUndefined();
+ releaseFirst();
+ res.emit('close');
+ await cleanupMCPRequestContextForReq(req);
+ expect(context.cleanupStarted).toBe(false);
+ expect(disconnect).not.toHaveBeenCalled();
+
+ expect(releaseSecond()).toBeUndefined();
+ expect(context.cleanupStarted).toBe(true);
+ expect(signal.aborted).toBe(true);
+ await cleanupMCPRequestContext(context);
+ releaseSecond();
+ await cleanupMCPRequestContextForReq(req);
+ expect(disconnect).toHaveBeenCalledTimes(1);
+ expect(context.connections.size).toBe(0);
+ expect(context.pending.size).toBe(0);
+ });
+
+ it('includes a child connection opened lazily after parent cleanup was requested', async () => {
+ const context = createMCPRequestContext();
+ const release = retainMCPRequestContext(context);
+ await cleanupMCPRequestContext(context);
+
+ const connection = { disconnect: jest.fn().mockResolvedValue(undefined) };
+ let resolve!: (value: typeof connection) => void;
+ context.pending.set(
+ 'late-server',
+ new Promise<typeof connection>((settle) => {
+ resolve = settle;
+ }),
+ );
+ release();
+ await nextTick();
+ expect(connection.disconnect).not.toHaveBeenCalled();
+
+ resolve(connection);
+ await cleanupMCPRequestContext(context);
+ expect(connection.disconnect).toHaveBeenCalledTimes(1);
+ expect(context.pending.size).toBe(0);
+ });
+
+ it('returns from parent cleanup without waiting for a pending child connection', async () => {
+ const context = {
+ connections: new Map<string, unknown>(),
+ pending: new Map<string, Promise<unknown>>(),
+ };
+ const connection = { disconnect: jest.fn().mockResolvedValue(undefined) };
+ let resolve!: (value: typeof connection) => void;
+ context.pending.set(
+ 'pending-server',
+ new Promise<typeof connection>((settle) => {
+ resolve = settle;
+ }),
+ );
+ const signal = getMCPRequestSignal(context);
+ const release = retainMCPRequestContext(context);
+
+ await expect(
+ Promise.race([
+ cleanupMCPRequestContext(context).then(() => 'returned'),
+ nextTick().then(() => 'blocked'),
+ ]),
+ ).resolves.toBe('returned');
+ expect(signal.aborted).toBe(false);
+ expect(context.pending.size).toBe(1);
+
+ release();
+ expect(signal.aborted).toBe(true);
+ resolve(connection);
+ await cleanupMCPRequestContext(context);
+ expect(connection.disconnect).toHaveBeenCalledTimes(1);
+ expect(context.pending.size).toBe(0);
+ });
+
+ it('does not close a context released before parent cleanup', async () => {
+ const context = createMCPRequestContext();
+ const signal = getMCPRequestSignal(context);
+ const disconnect = jest.fn().mockResolvedValue(undefined);
+ context.connections.set('server', { disconnect });
+ const release = retainMCPRequestContext(context);
+
+ release();
+ release();
+ await nextTick();
+ expect(context.cleanupStarted).toBe(false);
+ expect(signal.aborted).toBe(false);
+ expect(disconnect).not.toHaveBeenCalled();
+
+ const releaseAgain = retainMCPRequestContext(context);
+ releaseAgain();
+ await cleanupMCPRequestContext(context);
+ expect(disconnect).toHaveBeenCalledTimes(1);
+ });
+
+ it.each([false, true])(
+ 'quiesces immediately with child owners (parent cleanup requested: %s)',
+ async (cleanupRequested) => {
+ const context = createMCPRequestContext();
+ const signal = getMCPRequestSignal(context);
+ const disconnect = jest.fn().mockResolvedValue(undefined);
+ context.connections.set('server', { disconnect });
+ context.pending.set(
+ 'resolver',
+ new Promise<void>((resolve) =>
+ signal.addEventListener('abort', () => resolve(), { once: true }),
+ ),
+ );
+ const releaseFirst = retainMCPRequestContext(context);
+ const releaseSecond = retainMCPRequestContext(context);
+ if (cleanupRequested) await cleanupMCPRequestContext(context);
+
+ const closing = quiesceMCPRequestContext(context);
+ expect(context.cleanupStarted).toBe(true);
+ expect(context.quiesceStarted).toBe(true);
+ expect(signal.aborted).toBe(true);
+ expect(() => retainMCPRequestContext(context)).toThrow('MCP request has settled.');
+ await closing;
+ expect(disconnect).toHaveBeenCalledTimes(1);
+
+ releaseFirst();
+ releaseSecond();
+ await cleanupMCPRequestContext(context);
+ expect(disconnect).toHaveBeenCalledTimes(1);
+ },
+ );
+
+ it('preserves strict admission failure when quiescing a retained context', async () => {
+ const context = createMCPRequestContext();
+ const failure = Object.assign(new Error('generation retired'), { name: 'AbortError' });
+ const dispose = jest.fn().mockRejectedValue(failure);
+ context.connections.set('server', { disconnect: jest.fn(), dispose });
+ const release = retainMCPRequestContext(context);
+ await cleanupMCPRequestContext(context);
+
+ await expect(quiesceMCPRequestContext(context)).rejects.toBe(failure);
+ release();
+ await nextTick();
+ expect(dispose).toHaveBeenCalledTimes(1);
+ await expect(quiesceMCPRequestContext(context)).rejects.toBe(failure);
+ });
+
+ it('allows an active child to retain a nested task after parent cleanup is requested', async () => {
+ const context = createMCPRequestContext();
+ const disconnect = jest.fn().mockResolvedValue(undefined);
+ context.connections.set('server', { disconnect });
+ const releaseChild = retainMCPRequestContext(context);
+ await cleanupMCPRequestContext(context);
+
+ expect(context.cleanupStarted).toBe(false);
+ const releaseNested = retainMCPRequestContext(context);
+ releaseChild();
+ await nextTick();
+ expect(context.cleanupStarted).toBe(false);
+ expect(disconnect).not.toHaveBeenCalled();
+
+ releaseNested();
+ expect(context.cleanupStarted).toBe(true);
+ expect(() => retainMCPRequestContext(context)).toThrow('MCP request has settled.');
+ await cleanupMCPRequestContext(context);
+ expect(disconnect).toHaveBeenCalledTimes(1);
+ });
+
+ it.each(['cleanup', 'quiesce'] as const)('rejects new owners after %s starts', async (mode) => {
+ const context = createMCPRequestContext();
+ const closing =
+ mode === 'cleanup' ? cleanupMCPRequestContext(context) : quiesceMCPRequestContext(context);
+
+ expect(() => retainMCPRequestContext(context)).toThrow('MCP request has settled.');
+ await closing;
+ expect(() => retainMCPRequestContext(context)).toThrow('MCP request has settled.');
+ });
+
+ it.each(['release', 'quiesce'] as const)(
+ 'keeps the original scope for lazy request lookups without reopening it after %s',
+ async (cutoff) => {
+ const req = {};
+ const context = getMCPRequestContext(req)!;
+ const release = retainMCPRequestContext(context);
+
+ await cleanupMCPRequestContextForReq(req);
+ expect(getMCPRequestContext(req)).toBe(context);
+ expect(getMCPRequestContext(req, undefined, { cleanupOnResponse: false })).toBe(context);
+ await cleanupMCPRequestContextForReq(req);
+ expect(getMCPRequestContext(req)).toBe(context);
+
+ if (cutoff === 'quiesce') await quiesceMCPRequestContext(context);
+ else release();
+ expect(getMCPRequestContext(req)).toBeUndefined();
+ await cleanupMCPRequestContextForReq(req);
+ expect(getMCPRequestContext(req)).toBeUndefined();
+ expect(getMCPRequestContext(req, undefined, { cleanupOnResponse: false })).toBeUndefined();
+ release();
+ },
+ );
+
+ it('preserves request reuse for contexts that were never retained', async () => {
+ const req = {};
+ const context = getMCPRequestContext(req)!;
+ await cleanupMCPRequestContextForReq(req);
+
+ const replacement = getMCPRequestContext(req);
+ expect(replacement).toBeDefined();
+ expect(replacement).not.toBe(context);
+ await cleanupMCPRequestContextForReq(req);
+ });
+
+ it('logs asynchronous disposal failure without rejecting the synchronous release', async () => {
+ const context = createMCPRequestContext();
+ const dispose = jest.fn().mockRejectedValue(new Error('disposal failed'));
+ context.connections.set('server', { disconnect: jest.fn(), dispose });
+ const release = retainMCPRequestContext(context);
+ await cleanupMCPRequestContext(context);
+
+ expect(release()).toBeUndefined();
+ await nextTick();
+ expect(logger.warn).toHaveBeenCalledTimes(1);
+ expect(logger.warn).toHaveBeenCalledWith(
+ '[MCP Request Context] Failed to dispose request-scoped connection',
+ );
+ expect(dispose).toHaveBeenCalledTimes(1);
+ expect(context.connections.size).toBe(0);
+ });
+});
+
describe('MCP runtime request body', () => {
it('preserves a supplied parent message id', () => {
expect(
diff --git a/packages/api/src/mcp/request.ts b/packages/api/src/mcp/request.ts
index 1f530baf29..ab700d07bd 100644
--- a/packages/api/src/mcp/request.ts
+++ b/packages/api/src/mcp/request.ts
@@ -58,6 +58,10 @@ interface Disconnectable {
}
const contexts = new WeakMap<object, MCPRequestContext>();
+const contextRetentions = new WeakMap<
+ RequestScopedMCPConnectionStore,
+ { holds: number; cleanupRequested: boolean }
+>();
const cleanupFlights = new WeakMap<RequestScopedMCPConnectionStore, Promise<void>>();
const requestControllers = new WeakMap<RequestScopedMCPConnectionStore, AbortController>();
@@ -95,6 +99,30 @@ export function createMCPRequestContext(): MCPRequestContext {
};
}
+/** Keeps normal cleanup deferred while an admitted child task owns the context. */
+export function retainMCPRequestContext(context: RequestScopedMCPConnectionStore): () => void {
+ let retention = contextRetentions.get(context);
+ if (
+ context.cleanupStarted ||
+ context.quiesceStarted ||
+ (retention?.cleanupRequested && retention.holds === 0)
+ ) {
+ throw new MCPRequestQuiescedError();
+ }
+ if (!retention) {
+ retention = { holds: 0, cleanupRequested: false };
+ contextRetentions.set(context, retention);
+ }
+ retention.holds++;
+ let released = false;
+ return () => {
+ if (released) return;
+ released = true;
+ retention.holds--;
+ if (retention.holds === 0 && retention.cleanupRequested) runCleanup(context);
+ };
+}
+
function isDisconnectable(value: unknown): value is Disconnectable {
return (
value != null &&
@@ -157,8 +185,15 @@ async function disposeContext(
}
}
-export async function cleanupMCPRequestContext(context?: MCPRequestContext): Promise<void> {
+export async function cleanupMCPRequestContext(
+ context?: RequestScopedMCPConnectionStore,
+): Promise<void> {
if (!context) return;
+ const retention = contextRetentions.get(context);
+ if (retention) {
+ retention.cleanupRequested = true;
+ if (retention.holds > 0 && !context.cleanupStarted && !context.quiesceStarted) return;
+ }
let flight = cleanupFlights.get(context);
if (!flight) {
if (context.cleanupStarted) {
@@ -179,7 +214,7 @@ function isResponseFinished(res?: MCPResponseLike): boolean {
return Boolean(res?.writableEnded || res?.finished || res?.destroyed);
}
-function runCleanup(context: MCPRequestContext): void {
+function runCleanup(context: RequestScopedMCPConnectionStore): void {
cleanupMCPRequestContext(context).catch(() => {
logger.warn('[MCP Request Context] Cleanup failed');
});
@@ -252,6 +287,7 @@ export async function cleanupMCPRequestContextForReq(req?: object): Promise<void
try {
await cleanupMCPRequestContext(context);
} finally {
- contexts.delete(req);
+ // Retained request closures must keep their original scope, including its final cutoff.
+ if (!contextRetentions.has(context)) contexts.delete(req);
}
}
diff --git a/packages/data-provider/src/api-endpoints.ts b/packages/data-provider/src/api-endpoints.ts
index 0b653f2150..788ef135b1 100644
--- a/packages/data-provider/src/api-endpoints.ts
+++ b/packages/data-provider/src/api-endpoints.ts
@@ -167,6 +167,18 @@ export const subagentThread = (
return cursor == null ? endpoint : `${endpoint}?cursor=${encodeURIComponent(cursor)}`;
};
+export const subagentTaskContent = (
+ parentConversationId: string,
+ threadId: string,
+ taskId: string,
+ afterSequence?: number,
+ cursor?: string,
+) => {
+ const endpoint = `${parentSubagents(parentConversationId)}/${encodeURIComponent(threadId)}/tasks/${encodeURIComponent(taskId)}/content`;
+ if (cursor != null) return `${endpoint}?cursor=${encodeURIComponent(cursor)}`;
+ return afterSequence == null ? endpoint : `${endpoint}?afterSequence=${afterSequence}`;
+};
+
export const subagentControl = (parentConversationId: string, threadId: string) =>
`${conversationsRoot}/${encodeURIComponent(parentConversationId)}/subagents/${encodeURIComponent(threadId)}/control`;
diff --git a/packages/data-provider/src/config.spec.ts b/packages/data-provider/src/config.spec.ts
index 839b956e65..c586916224 100644
--- a/packages/data-provider/src/config.spec.ts
+++ b/packages/data-provider/src/config.spec.ts
@@ -2800,6 +2800,13 @@ describe('subagent activity policy', () => {
endpoints: { agents: { subagentActivity: {} } },
});
expect(parsed.endpoints?.agents?.subagentActivity).toEqual({
+ contentRecoveryEnabled: false,
+ contentPageBytes: 262_144,
+ contentFlushMs: 250,
+ contentSettlementTimeoutMs: 1000,
+ contentRecoveryGraceMs: 30_000,
+ contentBatchBytes: 65_536,
+ contentPendingBytes: 8_388_608,
replayTtlMs: 300_000,
publicationTimeoutMs: 1_000,
retryAttempts: 3,
@@ -2815,6 +2822,13 @@ describe('subagent activity policy', () => {
endpoints: {
agents: {
subagentActivity: {
+ contentRecoveryEnabled: true,
+ contentPageBytes: 524_288,
+ contentFlushMs: 500,
+ contentSettlementTimeoutMs: 5000,
+ contentRecoveryGraceMs: 60_000,
+ contentBatchBytes: 131_072,
+ contentPendingBytes: 16_777_216,
replayTtlMs: 3_600_000,
publicationTimeoutMs: 5_000,
retryAttempts: 2,
diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.ts
index 642ebb37e9..e2e696aa17 100644
--- a/packages/data-provider/src/config.ts
+++ b/packages/data-provider/src/config.ts
@@ -1542,6 +1542,14 @@ export type HostFileEditLimits = z.infer<typeof hostFileEditLimitsSchema>;
/** Server-side resource and recovery policy for ephemeral child activity. */
export const subagentActivityConfigSchema = z.object({
+ contentRecoveryEnabled: z.boolean().default(false),
+ /** Batch public content writes independently of the lossy live activity projection. */
+ contentPageBytes: z.number().int().min(1024).max(4_194_304).default(262_144),
+ contentFlushMs: z.number().int().min(10).max(10_000).default(250),
+ contentSettlementTimeoutMs: z.number().int().min(100).max(60_000).default(1000),
+ contentRecoveryGraceMs: z.number().int().min(0).max(300_000).default(30_000),
+ contentBatchBytes: z.number().int().min(1024).max(4_194_304).default(65_536),
+ contentPendingBytes: z.number().int().min(65_536).max(1_073_741_824).default(8_388_608),
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),
diff --git a/packages/data-provider/src/data-service.ts b/packages/data-provider/src/data-service.ts
index 73e0eb1291..2844ce803f 100644
--- a/packages/data-provider/src/data-service.ts
+++ b/packages/data-provider/src/data-service.ts
@@ -1198,6 +1198,18 @@ export function getSubagentThread(
return request.get(endpoints.subagentThread(parentConversationId, threadId, taskId, cursor));
}
+export function getSubagentTaskContent(
+ parentConversationId: string,
+ threadId: string,
+ taskId: string,
+ afterSequence?: number,
+ cursor?: string,
+): Promise<t.SubagentTaskContentResponse> {
+ return request.get(
+ endpoints.subagentTaskContent(parentConversationId, threadId, taskId, afterSequence, cursor),
+ );
+}
+
export function controlSubagentTask(
parentConversationId: string,
threadId: string,
diff --git a/packages/data-provider/src/keys.ts b/packages/data-provider/src/keys.ts
index 8c40da74fe..d2b72a7f9d 100644
--- a/packages/data-provider/src/keys.ts
+++ b/packages/data-provider/src/keys.ts
@@ -109,6 +109,7 @@ export enum QueryKeys {
schedule = 'schedule',
parentSubagents = 'parentSubagents',
subagentThread = 'subagentThread',
+ subagentTaskContent = 'subagentTaskContent',
backgroundTasks = 'backgroundTasks',
conversationPullRequest = 'conversationPullRequest',
pullRequestConnection = 'pullRequestConnection',
diff --git a/packages/data-provider/src/types/subagents.ts b/packages/data-provider/src/types/subagents.ts
index 8019fdfba5..d32a8f8c48 100644
--- a/packages/data-provider/src/types/subagents.ts
+++ b/packages/data-provider/src/types/subagents.ts
@@ -1,3 +1,8 @@
+import type { TMessageContentParts } from './content';
+import type { ChatStepFrame } from './transport';
+import type { StepEvents } from './runs';
+import type { Agents } from './agents';
+
export type SubagentThreadStatus =
| 'dispatched'
| 'running'
@@ -143,6 +148,8 @@ export type SubagentExternalEventDetails = {
*/
export type SubagentThreadTurn = {
taskId: string;
+ /** Absent on older servers; false when this task has no captured content. */
+ contentRecoveryAvailable?: boolean;
trigger: {
kind: SubagentThreadTriggerKind;
summary: string;
@@ -241,3 +248,73 @@ export type SubagentDigest = {
/** Why an `expand` returned less than the node it named. */
note?: string;
};
+
+/** Public graph events only. Never a private model transcript or tool execution request. */
+export type SubagentContentFrame =
+ | Extract<
+ ChatStepFrame,
+ {
+ event:
+ | StepEvents.ON_RUN_STEP
+ | StepEvents.ON_MESSAGE_DELTA
+ | StepEvents.ON_REASONING_DELTA
+ | StepEvents.ON_RUN_STEP_DELTA
+ | StepEvents.ON_RUN_STEP_COMPLETED
+ | StepEvents.ON_RUN_STEP_CLOSED;
+ }
+ >
+ | { event: StepEvents.ON_TOOL_PREPARATION; data: Agents.ToolPreparationMarker }
+ | { event: StepEvents.ON_TOOL_CALLS_DISPATCHED; data: Agents.ToolCallsDispatchedEvent };
+
+export type SubagentContentEvent = { sequence: number; frame: SubagentContentFrame };
+
+export type SubagentContentWatermark = {
+ taskId: string;
+ throughSequence: number;
+ /** Monotonic committed journal batch, scoped to this immutable task execution. */
+ revision: number;
+};
+
+export type SubagentContentAvailableFrame = {
+ event: 'subagent_content_available';
+ data: SubagentContentWatermark;
+};
+
+type SubagentTaskContentIdentity = SubagentContentWatermark & {
+ /** Opaque cursor for the next suffix page at the same sampled target. */
+ nextCursor?: string;
+ targetThroughSequence: number;
+ /** Fixed server deadline for refreshing a terminal prefix after a late commit. */
+ retryUntil?: number;
+ parentConversationId: string;
+ threadId: string;
+ /** Stable normal assistant message identity, including before terminal persistence. */
+ messageId: string;
+ parentMessageId: string;
+ sender: string;
+ status: SubagentThreadStatus;
+ /** Running tasks expose committed prefixes (partial). Complete requires a
+ * terminal row whose expected watermark matches the committed target. */
+ recovery: 'complete' | 'partial';
+};
+
+export type SubagentTaskContentSnapshot = SubagentTaskContentIdentity & {
+ mode: 'snapshot';
+ content: TMessageContentParts[];
+ runSteps: Agents.RunStep[];
+};
+
+export type SubagentTaskContentSuffix = SubagentTaskContentIdentity & {
+ mode: 'suffix';
+ afterSequence: number;
+ events: SubagentContentEvent[];
+};
+
+/** Subscribe to activity first, wait for ready or terminal, then GET content. Treat
+ * subagent_content_available as invalidation, never a content delta. Read the
+ * committed suffix with afterSequence; drain nextCursor before fetching a newer
+ * target. Deduplicate by sequence, not revision alone (pages may share a batch).
+ * Never fold bounded activity deltas onto these content snapshots.
+ * Poll while running as a fallback for an unavailable notification transport.
+ * A suffix's throughSequence also covers non-rendering activity events. */
+export type SubagentTaskContentResponse = SubagentTaskContentSnapshot | SubagentTaskContentSuffix;
diff --git a/packages/data-schemas/src/methods/conversation.ts b/packages/data-schemas/src/methods/conversation.ts
index 350178cafe..16bbe61175 100644
--- a/packages/data-schemas/src/methods/conversation.ts
+++ b/packages/data-schemas/src/methods/conversation.ts
@@ -52,6 +52,7 @@ import { createChatExpirationDate, createTempChatExpirationDate } from '~/utils/
import { isAgentFadingTier, isAgentFadingTierEntries } from '~/utils/fading';
import { isCompactionSemanticIndexProjection } from '~/types/compaction';
import { withoutMeiliIndexing } from '~/models/plugins/mongoMeili';
+import { prepareSubagentContentDeletion } from './subagentContent';
import { tenantSafeBulkWrite } from '~/utils/tenantBulkWrite';
import { isValidObjectIdString } from '~/utils/objectId';
import { decrementTagCounts } from './conversationTag';
@@ -4140,6 +4141,12 @@ export function createConversationMethods(
);
await options?.beforeDelete?.(waveIds);
await deps?.prepareAgentTriggerConversationResultErasure?.(user, waveIds);
+ await retryCascadeOperation(() =>
+ prepareSubagentContentDeletion(mongoose, {
+ user,
+ conversationId: { $in: waveIds },
+ }),
+ );
const result = await Conversation.deleteMany({ user, conversationId: { $in: waveIds } });
if (result.deletedCount > 0) {
/** Result erasure is irreversible. Keep receipts intact when a
diff --git a/packages/data-schemas/src/methods/import.ts b/packages/data-schemas/src/methods/import.ts
index 7f2b6c4cad..068704200b 100644
--- a/packages/data-schemas/src/methods/import.ts
+++ b/packages/data-schemas/src/methods/import.ts
@@ -51,6 +51,13 @@ export function createConversationImportMethods(
await runAsSystem(async () => {
for (const conversationIds of chunkConversationIds(scope.conversationIds)) {
await Message.deleteMany(createImportCleanupFilter<IMessage>(scope, conversationIds));
+ await mongoose.models.SubagentContent?.deleteMany({
+ user: scope.user,
+ conversationId: { $in: conversationIds },
+ ...(scope.tenantId == null
+ ? { tenantId: { $exists: false } }
+ : { tenantId: scope.tenantId }),
+ });
}
});
}
@@ -71,6 +78,7 @@ export function createConversationImportMethods(
}
}
await Conversation.deleteMany(filter);
+ await mongoose.models.SubagentContent?.deleteMany(filter);
}
return [...affectedProjectIds];
});
diff --git a/packages/data-schemas/src/methods/index.ts b/packages/data-schemas/src/methods/index.ts
index 0af1e815b2..f624427bcf 100644
--- a/packages/data-schemas/src/methods/index.ts
+++ b/packages/data-schemas/src/methods/index.ts
@@ -1,3 +1,11 @@
+import { createSubagentContentMethods, type SubagentContentMethods } from './subagentContent';
+export type {
+ SubagentContentScope,
+ SubagentContentHead,
+ SubagentContentBatch,
+ SubagentContentMethods,
+ SubagentContentAppendResult,
+} from './subagentContent';
import type { ToolApprovalGrantStorage } from 'librechat-data-provider';
import type { ScheduleMCPConsentStorage } from './scheduleConsent';
import { createToolApprovalGrantMethods } from './toolApprovalGrant';
@@ -259,7 +267,8 @@ export {
AgentQueuedTurnLaneRetiredError,
};
-export type AllMethods = ToolApprovalGrantStorage &
+export type AllMethods = SubagentContentMethods &
+ ToolApprovalGrantStorage &
UserMethods &
SessionMethods &
TokenMethods &
@@ -508,6 +517,7 @@ export function createMethods(
...createRefreshTokenBridgeMethods(mongoose),
...createOpenIDRefreshFlightMethods(mongoose),
...createResourceLockMethods(mongoose),
+ ...createSubagentContentMethods(mongoose),
...createPasskeyMethods(mongoose),
...roleMethods,
...createKeyMethods(mongoose),
diff --git a/packages/data-schemas/src/methods/message.spec.ts b/packages/data-schemas/src/methods/message.spec.ts
index cd24172a76..54ffb4beff 100644
--- a/packages/data-schemas/src/methods/message.spec.ts
+++ b/packages/data-schemas/src/methods/message.spec.ts
@@ -3257,6 +3257,51 @@ describe('Message Operations', () => {
});
describe('getMessagesForSubagentThreadView', () => {
+ it('projects recovery enrollment without exposing private journal metadata', async () => {
+ const conversationId = uuidv4();
+ for (const captured of [false, true, 'deleted'] as const) {
+ await saveMessage(mockCtx, {
+ messageId: `captured-${captured}:user`,
+ conversationId,
+ user: 'user123',
+ text: 'Input',
+ ...(captured
+ ? {
+ subagentContent: {
+ version: 1 as const,
+ throughSequence: 12,
+ ...(captured === 'deleted' ? { deleted: true } : {}),
+ },
+ }
+ : {}),
+ });
+ }
+ const messages = await getMessagesForSubagentThreadView({
+ user: 'user123',
+ conversationId,
+ limit: 3,
+ textCodePointLimit: 100,
+ });
+ expect(messages).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ messageId: 'captured-true:user',
+ contentRecoveryAvailable: true,
+ }),
+ expect.objectContaining({
+ messageId: 'captured-false:user',
+ contentRecoveryAvailable: false,
+ }),
+ expect.objectContaining({
+ messageId: 'captured-deleted:user',
+ contentRecoveryAvailable: false,
+ }),
+ ]),
+ );
+ expect(JSON.stringify(messages)).not.toContain('subagentContent');
+ expect(JSON.stringify(messages)).not.toContain('throughSequence');
+ });
+
it('bounds text in MongoDB before returning the public projection', async () => {
const conversationId = uuidv4();
await saveMessage(mockCtx, {
@@ -4015,6 +4060,28 @@ describe('Message Operations', () => {
});
describe('deleteMessages', () => {
+ it('does not discover journals for an exact ordinary message id', async () => {
+ const messageId = uuidv4();
+ await saveMessage(mockCtx, {
+ messageId,
+ conversationId: uuidv4(),
+ user: 'user123',
+ text: 'Ordinary chat',
+ });
+ const find = jest.spyOn(Message, 'find');
+ const journalDelete = jest.spyOn(mongoose.models.SubagentContent, 'deleteMany');
+ try {
+ await expect(deleteMessages({ user: 'user123', messageId })).resolves.toMatchObject({
+ deletedCount: 1,
+ });
+ expect(find).not.toHaveBeenCalled();
+ expect(journalDelete).not.toHaveBeenCalled();
+ } finally {
+ find.mockRestore();
+ journalDelete.mockRestore();
+ }
+ });
+
it('should delete messages with the correct filter', async () => {
// Save some messages for different users
await saveMessage(mockCtx, mockMessageData);
diff --git a/packages/data-schemas/src/methods/message.ts b/packages/data-schemas/src/methods/message.ts
index a368f1cf2c..beac043578 100644
--- a/packages/data-schemas/src/methods/message.ts
+++ b/packages/data-schemas/src/methods/message.ts
@@ -8,10 +8,12 @@ import type { DeleteResult, FilterQuery, Model, Types, UpdateQuery } from 'mongo
import type { UserSubmittedMessageFieldPath } from 'librechat-data-provider';
import type { SearchParams } from 'meilisearch';
import type { SchemaWithMeiliMethods } from '~/models/plugins/mongoMeili';
+import type { ISubagentContentChunk } from '~/models/subagentContent';
import type { AppConfig, IConversation, IMessage } from '~/types';
import { createChatExpirationDate, createTempChatExpirationDate } from '~/utils/tempChatRetention';
import { activeExpirationFilter, createFallbackRetentionDate } from '~/utils/retention';
import { fitBoundAppSnapshots, hasBoundAppSnapshots } from './appSnapshots';
+import { prepareSubagentContentDeletion } from './subagentContent';
import { tenantSafeBulkWrite } from '~/utils/tenantBulkWrite';
import { tenantStorage } from '~/config/tenantContext';
import logger from '~/config/winston';
@@ -603,6 +605,7 @@ export type SubagentThreadViewMessageRecord = Pick<
| 'subagentTriggerProjection'
> & {
textProjectionTruncated?: boolean;
+ contentRecoveryAvailable?: boolean;
subagentTranscriptProjectionTruncated?: boolean;
/** Storage-bounded visible content; validated into the public activity type by the API. */
subagentActivity?: unknown[];
@@ -3493,6 +3496,12 @@ export function createMessageMethods(
createdAt: 1,
error: 1,
unfinished: 1,
+ contentRecoveryAvailable: {
+ $and: [
+ { $eq: [{ $ifNull: ['$subagentContent.version', 0] }, 1] },
+ { $ne: [{ $ifNull: ['$subagentContent.deleted', false] }, true] },
+ ],
+ },
subagentTranscriptProjectionTruncated: {
$cond: [{ $ne: [{ $type: '$subagentTranscript.messagesJson' }, 'missing'] }, true, null],
},
@@ -4122,6 +4131,62 @@ export function createMessageMethods(
async function deleteMessages(filter: FilterQuery<IMessage>) {
try {
const Message = mongoose.models.Message as Model<IMessage>;
+ if (typeof filter.messageId === 'string' && !/:(user|assistant)$/.test(filter.messageId)) {
+ return await Message.deleteMany(filter);
+ }
+ const wholeScope =
+ typeof filter.user === 'string' &&
+ Object.keys(filter).every((key) => ['user', 'conversationId', 'tenantId'].includes(key));
+ const contentSources = wholeScope
+ ? []
+ : await Message.find({
+ $and: [filter, { subagentContent: { $exists: true } }],
+ })
+ .select('user tenantId conversationId messageId')
+ .lean<IMessage[]>();
+ const SubagentContent = mongoose.models.SubagentContent as
+ | Model<ISubagentContentChunk>
+ | undefined;
+ if (SubagentContent != null) {
+ if (wholeScope) {
+ await prepareSubagentContentDeletion(mongoose, filter);
+ return await Message.deleteMany(filter);
+ }
+ const scopes = new Map<
+ string,
+ {
+ user: string;
+ conversationId: string;
+ taskId: string;
+ tenantId: string | { $exists: false };
+ }
+ >();
+ for (const source of contentSources) {
+ const taskId = source.messageId.replace(/:(user|assistant)$/, '');
+ if (taskId === source.messageId) continue;
+ scopes.set(`${source.tenantId ?? ''}:${source.user}:${source.conversationId}:${taskId}`, {
+ user: source.user,
+ conversationId: source.conversationId,
+ taskId,
+ tenantId: source.tenantId ?? { $exists: false },
+ });
+ }
+ if (scopes.size > 0) {
+ const contentScopes = [...scopes.values()];
+ /** Revoke the task before cleanup, including appends already admitted.
+ * Retain both markers until payload deletion succeeds so retries rediscover them. */
+ await Message.updateMany(
+ {
+ $or: contentScopes.map(({ taskId, ...scope }) => ({
+ ...scope,
+ messageId: { $in: [`${taskId}:user`, `${taskId}:assistant`] },
+ })),
+ },
+ { $set: { 'subagentContent.deleted': true } },
+ );
+ await SubagentContent.deleteMany({ $or: contentScopes });
+ }
+ }
return await Message.deleteMany(filter);
} catch (err) {
logger.error('Error deleting messages:', err);
diff --git a/packages/data-schemas/src/methods/subagentContent.recovery.spec.ts b/packages/data-schemas/src/methods/subagentContent.recovery.spec.ts
new file mode 100644
index 0000000000..51747c3bee
--- /dev/null
+++ b/packages/data-schemas/src/methods/subagentContent.recovery.spec.ts
@@ -0,0 +1,231 @@
+import mongoose from 'mongoose';
+import { createHash, randomUUID } from 'node:crypto';
+import { MongoMemoryServer } from 'mongodb-memory-server';
+import type { CommandStartedEvent, Collection } from 'mongodb';
+import type { Model } from 'mongoose';
+import type { SubagentContentBatch, SubagentContentScope } from './subagentContent';
+import type { ISubagentContentChunk } from '../models/subagentContent';
+import { createSubagentContentModel } from '../models/subagentContent';
+import { createSubagentContentMethods } from './subagentContent';
+
+let mongo: MongoMemoryServer;
+let Content: Model<ISubagentContentChunk>;
+let collection: Collection<ISubagentContentChunk>;
+const scope: SubagentContentScope = {
+ tenantId: 'tenant',
+ user: 'owner',
+ parentConversationId: 'parent',
+ conversationId: 'child',
+ taskId: 'task',
+};
+const methods = createSubagentContentMethods(mongoose);
+const queries: CommandStartedEvent['command'][] = [];
+
+beforeAll(async () => {
+ mongo = await MongoMemoryServer.create({ instance: { args: ['--nounixsocket'] } });
+ Content = createSubagentContentModel(mongoose);
+ await mongoose.connect(mongo.getUri(), { monitorCommands: true });
+ await Content.init();
+ collection = mongoose.connection.db!.collection<ISubagentContentChunk>(Content.collection.name);
+ mongoose.connection.getClient().on('commandStarted', (event: CommandStartedEvent) => {
+ if (event.commandName === 'find' && event.command.find === 'subagentcontents') {
+ queries.push(event.command);
+ }
+ });
+});
+afterAll(async () => {
+ await mongoose.disconnect();
+ await mongo.stop();
+});
+beforeEach(async () => {
+ await Content.deleteMany({});
+ queries.length = 0;
+});
+
+function records(revision: number, target = scope, expiredAt?: Date): ISubagentContentChunk[] {
+ const payload = JSON.stringify([{ sequence: revision * 3 - 3 }, { sequence: revision * 3 - 1 }]);
+ const { tenantId, ...identity } = target;
+ const base = {
+ ...identity,
+ ...(tenantId == null ? {} : { tenantId }),
+ revision,
+ fromSequence: revision * 3 - 3,
+ throughSequence: revision * 3 - 1,
+ fragments: 1,
+ digest: createHash('sha256').update(payload).digest('hex'),
+ ...(expiredAt == null ? {} : { expiredAt }),
+ };
+ return [
+ { ...base, _id: randomUUID(), fragment: -1 },
+ { ...base, _id: randomUUID(), fragment: 0, payload },
+ ];
+}
+
+async function read(throughRevision: number, afterSequence = -1, target = scope) {
+ const batches: SubagentContentBatch[] = [];
+ for await (const batch of methods.streamSubagentContentBatches(
+ target,
+ throughRevision,
+ afterSequence,
+ )) {
+ batches.push(batch);
+ }
+ return batches;
+}
+
+async function stats() {
+ const result = [];
+ for (const command of queries.splice(0)) {
+ const { find, filter, sort, hint, limit, projection } = command;
+ const explain = await mongoose.connection.db!.command({
+ explain: {
+ find,
+ filter,
+ sort,
+ ...(hint ? { hint } : {}),
+ ...(limit ? { limit } : {}),
+ ...(projection ? { projection } : {}),
+ },
+ verbosity: 'executionStats',
+ });
+ result.push(explain.executionStats);
+ if (filter.fragment === -1 && sort.throughSequence === 1) {
+ expect(hint).toBeUndefined();
+ expect(JSON.stringify(explain.queryPlanner.winningPlan)).toContain(
+ 'subagent_content_sequence',
+ );
+ }
+ expect(JSON.stringify(explain.queryPlanner.winningPlan)).not.toContain('COLLSCAN');
+ expect(JSON.stringify(explain.queryPlanner.winningPlan)).not.toContain('"stage":"SORT"');
+ }
+ return {
+ queries: result.length,
+ documents: result.reduce((sum, item) => sum + item.totalDocsExamined, 0),
+ keys: result.reduce((sum, item) => sum + item.totalKeysExamined, 0),
+ };
+}
+
+it.each([100, 1000, 5000])(
+ 'seeks suffixes independently of %i retained revisions',
+ async (count) => {
+ await collection.insertMany(
+ Array.from({ length: count }, (_, index) => records(index + 1)).flat(),
+ );
+ queries.length = 0;
+ expect(await methods.getSubagentContentHead(scope)).toEqual({
+ revision: count,
+ throughSequence: count * 3 - 1,
+ });
+ const head = await stats();
+ expect(head.documents).toBe(1);
+ expect(head.keys).toBeLessThanOrEqual(3);
+ expect(await methods.getSubagentContentHead(scope, Math.floor(count / 2))).toEqual({
+ revision: Math.floor(count / 2),
+ throughSequence: Math.floor(count / 2) * 3 - 1,
+ });
+ const pinnedHead = await stats();
+ expect(pinnedHead.documents).toBe(1);
+ expect(pinnedHead.keys).toBeLessThanOrEqual(3);
+ expect((await read(count, count * 3 - 4)).map((batch) => batch.revision)).toEqual([count]);
+ const suffix = await stats();
+ expect(suffix).toMatchObject({ queries: 2, documents: 3 });
+ expect(suffix.keys).toBeLessThanOrEqual(5);
+
+ expect(await read(count, count * 3 - 1)).toEqual([]);
+ const empty = await stats();
+ expect(empty).toMatchObject({ queries: 1, documents: 0 });
+ expect(empty.keys).toBeLessThanOrEqual(1);
+
+ expect((await read(count)).length).toBe(count);
+ const initial = await stats();
+ expect(initial).toMatchObject({ queries: 1, documents: count * 2, keys: count * 2 });
+
+ const pin = Math.floor(count / 2);
+ // Resume inside the last pinned batch, not just at a batch boundary.
+ expect((await read(pin, pin * 3 - 3)).map((batch) => batch.revision)).toEqual([pin]);
+ const midBatch = await stats();
+ expect(midBatch.documents).toBe(3);
+ expect(midBatch.keys).toBeLessThanOrEqual(5);
+ expect(await read(pin, pin * 3 - 1)).toEqual([]);
+ const pinnedEmpty = await stats();
+ expect(pinnedEmpty).toMatchObject({ queries: 1, documents: 1, keys: 1 });
+ console.log(
+ JSON.stringify({
+ measurement: 'indexed_recovery',
+ revisions: count,
+ head,
+ pinnedHead,
+ suffix,
+ empty,
+ initial,
+ midBatch,
+ pinnedEmpty,
+ }),
+ );
+ },
+);
+
+it('keeps the sampled pin after later commits and isolates every scope field', async () => {
+ const neighbors = [
+ { ...scope, tenantId: 'foreign' },
+ { ...scope, user: 'foreign' },
+ { ...scope, parentConversationId: 'foreign' },
+ { ...scope, conversationId: 'foreign' },
+ { ...scope, taskId: 'foreign' },
+ { ...scope, tenantId: undefined },
+ ];
+ // The unique revision index intentionally rejects reusing a child/task in another parent.
+ await collection.insertMany([
+ ...records(1),
+ ...records(2),
+ ...neighbors
+ .filter((item) => item.parentConversationId === scope.parentConversationId)
+ .flatMap((item) => records(1, item)),
+ ]);
+ const pin = await methods.getSubagentContentHead(scope);
+ await collection.insertMany(records(3));
+ expect((await read(pin!.revision, 3)).map((batch) => batch.revision)).toEqual([2]);
+ expect(await read(pin!.revision, 5)).toEqual([]);
+ for (const neighbor of neighbors) {
+ const batches = await read(3, -1, neighbor);
+ expect(batches.map((batch) => batch.revision)).toEqual(
+ neighbor.parentConversationId === 'foreign' ? [] : [1],
+ );
+ }
+});
+
+it('excludes actively expired commits and fragments without relying on TTL cleanup', async () => {
+ await collection.insertMany([...records(1), ...records(2, scope, new Date(0))]);
+ expect(await methods.getSubagentContentHead(scope)).toEqual({ revision: 1, throughSequence: 2 });
+ expect((await read(2)).map((batch) => batch.revision)).toEqual([1]);
+ expect(await read(2, 2)).toEqual([]);
+});
+
+it.each(['missing', 'digest', 'fragment'] as const)(
+ 'rejects %s payload corruption after an indexed seek',
+ async (failure) => {
+ await collection.insertMany([...records(1), ...records(2)]);
+ const filter = { ...scope, revision: 2, fragment: 0 };
+ if (failure === 'missing') await Content.deleteOne(filter);
+ if (failure === 'digest') await Content.updateOne(filter, { $set: { payload: 'tampered' } });
+ if (failure === 'fragment') await Content.updateOne(filter, { $set: { fragment: 1 } });
+ const errors = {
+ missing: 'Incomplete committed',
+ digest: 'Invalid committed subagent content digest',
+ fragment: 'Invalid committed subagent content fragment',
+ };
+ await expect(read(2, 2)).rejects.toThrow(errors[failure]);
+ },
+);
+
+it('reads safely before the sequence index is built, then restores the test index', async () => {
+ await collection.insertMany([...records(1), ...records(2)]);
+ await collection.dropIndex('subagent_content_sequence');
+ try {
+ expect((await read(2, 2)).map((batch) => batch.revision)).toEqual([2]);
+ expect(await read(2, 5)).toEqual([]);
+ expect(await read(1, 2)).toEqual([]);
+ } finally {
+ await Content.createIndexes();
+ }
+});
diff --git a/packages/data-schemas/src/methods/subagentContent.spec.ts b/packages/data-schemas/src/methods/subagentContent.spec.ts
new file mode 100644
index 0000000000..c46325e6bc
--- /dev/null
+++ b/packages/data-schemas/src/methods/subagentContent.spec.ts
@@ -0,0 +1,15 @@
+import { createHash } from 'node:crypto';
+import { fragmentSubagentContent } from './subagentContent';
+
+it('preserves Unicode scalars across independent BSON UTF-8 fragment encodings', () => {
+ const original = `${'x'.repeat(128 * 1024 - 1)}😀${'y'.repeat(128 * 1024)}𐐷`;
+ const fragments = fragmentSubagentContent(original);
+ const recovered = fragments
+ .map((fragment) => Buffer.from(fragment, 'utf8').toString('utf8'))
+ .join('');
+ expect(recovered).toBe(original);
+ expect(createHash('sha256').update(recovered).digest('hex')).toBe(
+ createHash('sha256').update(original).digest('hex'),
+ );
+ expect(fragments.every((fragment) => fragment.length <= 128 * 1024)).toBe(true);
+});
diff --git a/packages/data-schemas/src/methods/subagentContent.ts b/packages/data-schemas/src/methods/subagentContent.ts
new file mode 100644
index 0000000000..084c6d0650
--- /dev/null
+++ b/packages/data-schemas/src/methods/subagentContent.ts
@@ -0,0 +1,316 @@
+import { createHash } from 'node:crypto';
+import type { FilterQuery, Model } from 'mongoose';
+import type { ISubagentContentChunk } from '~/models/subagentContent';
+import type { IConversation, IMessage } from '~/types';
+import { tenantSafeBulkWrite } from '~/utils/tenantBulkWrite';
+import { activeExpirationFilter } from '~/utils/retention';
+
+export type SubagentContentScope = {
+ user: string;
+ tenantId?: string;
+ parentConversationId: string;
+ conversationId: string;
+ taskId: string;
+};
+
+export type SubagentContentHead = { revision: number; throughSequence: number };
+export type SubagentContentBatch = SubagentContentHead & {
+ fromSequence: number;
+ eventsJson: string;
+};
+
+export type SubagentContentAppendResult =
+ | { ok: true }
+ | { ok: false; error: { code: 'SUBAGENT_CONTENT_GONE' } };
+
+const tenantFilter = (tenantId?: string) =>
+ tenantId == null ? { tenantId: { $exists: false } } : { tenantId };
+const scopeFilter = (scope: SubagentContentScope) => ({
+ ...scope,
+ ...tenantFilter(scope.tenantId),
+});
+
+/** Preserve source/topology records when erasure fails, and fence admitted appends first. */
+export async function prepareSubagentContentDeletion(
+ mongoose: typeof import('mongoose'),
+ filter: Pick<FilterQuery<IMessage>, 'user' | 'tenantId' | 'conversationId'>,
+): Promise<void> {
+ const Content = mongoose.models.SubagentContent as Model<ISubagentContentChunk> | undefined;
+ if (Content == null) return;
+ const Message = mongoose.models.Message as Model<IMessage>;
+ await Message.updateMany(
+ { ...filter, 'subagentContent.version': 1 },
+ { $set: { 'subagentContent.deleted': true } },
+ );
+ await Content.deleteMany(filter);
+}
+
+/** Fragments keep even a single large tool body well below Mongo's BSON ceiling.
+ * This is a storage encoding, not a content-retention limit. */
+const FRAGMENT_CHARS = 128 * 1024;
+
+/** BSON string fragments must not divide a supplementary Unicode character. */
+export function fragmentSubagentContent(payload: string): string[] {
+ const fragments: string[] = [];
+ let start = 0;
+ while (start < payload.length) {
+ let end = Math.min(start + FRAGMENT_CHARS, payload.length);
+ const previous = payload.charCodeAt(end - 1);
+ const next = payload.charCodeAt(end);
+ if (
+ end < payload.length &&
+ previous >= 0xd800 &&
+ previous <= 0xdbff &&
+ next >= 0xdc00 &&
+ next <= 0xdfff
+ )
+ end--;
+ fragments.push(payload.slice(start, end));
+ start = end;
+ }
+ return fragments;
+}
+
+export function createSubagentContentMethods(mongoose: typeof import('mongoose')): {
+ appendSubagentContentBatch: (
+ input: SubagentContentScope & SubagentContentBatch & { leaseToken?: string },
+ ) => Promise<SubagentContentAppendResult>;
+ reconcileSubagentContent: (scope: SubagentContentScope) => Promise<SubagentContentAppendResult>;
+ getSubagentContentHead: (
+ scope: SubagentContentScope,
+ throughRevision?: number,
+ ) => Promise<SubagentContentHead | null>;
+ streamSubagentContentBatches: (
+ scope: SubagentContentScope,
+ throughRevision: number,
+ afterSequence?: number,
+ ) => AsyncIterable<SubagentContentBatch>;
+} {
+ const contentModel = () => mongoose.models.SubagentContent as Model<ISubagentContentChunk>;
+
+ async function appendSubagentContentBatch(
+ input: SubagentContentScope & SubagentContentBatch & { leaseToken?: string },
+ ): Promise<SubagentContentAppendResult> {
+ const { revision, fromSequence, throughSequence, eventsJson, leaseToken, ...scope } = input;
+ if (
+ !Number.isSafeInteger(revision) ||
+ revision < 1 ||
+ !Number.isSafeInteger(fromSequence) ||
+ fromSequence < 0 ||
+ !Number.isSafeInteger(throughSequence) ||
+ throughSequence < fromSequence
+ ) {
+ throw new Error('Invalid subagent content batch');
+ }
+ const Message = mongoose.models.Message as Model<IMessage>;
+ const Conversation = mongoose.models.Conversation as Model<IConversation>;
+ const owner = { user: scope.user, ...tenantFilter(scope.tenantId) };
+ const inputFilter = {
+ ...owner,
+ conversationId: scope.conversationId,
+ messageId: `${scope.taskId}:user`,
+ 'subagentContent.deleted': { $ne: true },
+ ...activeExpirationFilter<IMessage>(),
+ };
+ const [seed, parent, child] = await Promise.all([
+ Message.findOne(inputFilter).select('expiredAt').lean<Pick<IMessage, 'expiredAt'>>(),
+ Conversation.exists({
+ ...owner,
+ conversationId: scope.parentConversationId,
+ ...activeExpirationFilter<IConversation>(),
+ }),
+ Conversation.exists({
+ ...owner,
+ conversationId: scope.conversationId,
+ 'subagentThread.parentConversationId': scope.parentConversationId,
+ 'subagentThreadLease.taskId': scope.taskId,
+ 'subagentThreadLease.expiresAt': { $gt: new Date() },
+ ...(leaseToken == null ? {} : { 'subagentThreadLease.token': leaseToken }),
+ ...activeExpirationFilter<IConversation>(),
+ }),
+ ]);
+ if (seed == null || parent == null || child == null) {
+ await reconcileSubagentContent(scope);
+ return { ok: false, error: { code: 'SUBAGENT_CONTENT_GONE' } };
+ }
+ const Model = contentModel();
+ const digest = createHash('sha256').update(eventsJson).digest('hex');
+ const payloads = fragmentSubagentContent(eventsJson);
+ const fragments = payloads.length;
+ const base = {
+ ...scope,
+ revision,
+ fromSequence,
+ throughSequence,
+ digest,
+ fragments,
+ ...(seed.expiredAt == null ? {} : { expiredAt: seed.expiredAt }),
+ };
+ const recordId = (fragment: number) =>
+ createHash('sha256')
+ .update(
+ JSON.stringify([
+ scope.tenantId ?? null,
+ scope.user,
+ scope.conversationId,
+ scope.taskId,
+ revision,
+ fragment,
+ ]),
+ )
+ .digest('hex');
+ const records = Array.from({ length: fragments }, (_, fragment) => ({
+ updateOne: {
+ filter: { _id: recordId(fragment), ...scopeFilter(scope), revision, fragment, digest },
+ update: {
+ $setOnInsert: {
+ ...base,
+ fragment,
+ payload: payloads[fragment],
+ },
+ },
+ upsert: true,
+ },
+ }));
+ await tenantSafeBulkWrite(Model, records, { ordered: false });
+ /** A retry can only commit identical bytes; conflicting retries hit the unique index. */
+ await Model.updateOne(
+ { _id: recordId(-1), ...scopeFilter(scope), revision, fragment: -1, digest },
+ { $setOnInsert: { ...base, fragment: -1 } },
+ { upsert: true },
+ );
+ return reconcileSubagentContent(scope);
+ }
+
+ /** Cleanup never replays payloads or requires a live execution lease. */
+ async function reconcileSubagentContent(
+ scope: SubagentContentScope,
+ ): Promise<SubagentContentAppendResult> {
+ const Message = mongoose.models.Message as Model<IMessage>;
+ const Conversation = mongoose.models.Conversation as Model<IConversation>;
+ const owner = { user: scope.user, ...tenantFilter(scope.tenantId) };
+ const [seed, parent, child] = await Promise.all([
+ Message.exists({
+ ...owner,
+ conversationId: scope.conversationId,
+ messageId: `${scope.taskId}:user`,
+ 'subagentContent.deleted': { $ne: true },
+ ...activeExpirationFilter<IMessage>(),
+ }),
+ Conversation.exists({
+ ...owner,
+ conversationId: scope.parentConversationId,
+ ...activeExpirationFilter<IConversation>(),
+ }),
+ Conversation.exists({
+ ...owner,
+ conversationId: scope.conversationId,
+ 'subagentThread.parentConversationId': scope.parentConversationId,
+ ...activeExpirationFilter<IConversation>(),
+ }),
+ ]);
+ if (seed == null || parent == null || child == null) {
+ await contentModel().deleteMany(scopeFilter(scope));
+ return { ok: false, error: { code: 'SUBAGENT_CONTENT_GONE' } };
+ }
+ return { ok: true };
+ }
+
+ async function getSubagentContentHead(
+ scope: SubagentContentScope,
+ throughRevision?: number,
+ ): Promise<SubagentContentHead | null> {
+ return contentModel()
+ .findOne({
+ ...scopeFilter(scope),
+ fragment: -1,
+ ...(throughRevision == null ? {} : { revision: { $lte: throughRevision } }),
+ ...activeExpirationFilter(),
+ })
+ .sort({ revision: -1 })
+ .select('revision throughSequence -_id')
+ .lean<SubagentContentHead>();
+ }
+
+ async function* streamSubagentContentBatches(
+ scope: SubagentContentScope,
+ throughRevision: number,
+ afterSequence = -1,
+ ): AsyncGenerator<SubagentContentBatch> {
+ if (throughRevision < 1) return;
+ const Model = contentModel();
+ let fromRevision = 1;
+ if (afterSequence >= 0) {
+ /** Commit sequences increase with revisions. Seek without a revision predicate so
+ * an exhausted pin cannot scan later commits looking for an older revision. */
+ const first = await Model.findOne({
+ ...scopeFilter(scope),
+ fragment: -1,
+ throughSequence: { $gt: afterSequence },
+ ...activeExpirationFilter(),
+ })
+ .sort({ throughSequence: 1 })
+ .select('revision -_id')
+ .lean<Pick<SubagentContentHead, 'revision'>>();
+ if (first == null || first.revision > throughRevision) return;
+ fromRevision = first.revision;
+ }
+ const cursor = Model.find({
+ ...scopeFilter(scope),
+ revision: { $gte: fromRevision, $lte: throughRevision },
+ ...activeExpirationFilter(),
+ })
+ .sort({ revision: 1, fragment: 1 })
+ .lean()
+ .cursor();
+ let commit: ISubagentContentChunk | undefined;
+ let payloads: string[] = [];
+ const decode = (): SubagentContentBatch => {
+ if (commit == null || payloads.length !== commit.fragments) {
+ throw new Error('Incomplete committed subagent content batch');
+ }
+ const eventsJson = payloads.join('');
+ if (createHash('sha256').update(eventsJson).digest('hex') !== commit.digest) {
+ throw new Error('Invalid committed subagent content digest');
+ }
+ return {
+ revision: commit.revision,
+ fromSequence: commit.fromSequence,
+ throughSequence: commit.throughSequence,
+ eventsJson,
+ };
+ };
+ try {
+ for await (const row of cursor) {
+ if (row.fragment === -1) {
+ if (commit != null) yield decode();
+ commit = row;
+ payloads = [];
+ continue;
+ }
+ if (
+ commit == null ||
+ row.revision !== commit.revision ||
+ row.fragment !== payloads.length ||
+ row.digest !== commit.digest ||
+ typeof row.payload !== 'string'
+ ) {
+ throw new Error('Invalid committed subagent content fragment');
+ }
+ payloads.push(row.payload);
+ }
+ if (commit != null) yield decode();
+ } finally {
+ await cursor.close();
+ }
+ }
+
+ return {
+ appendSubagentContentBatch,
+ reconcileSubagentContent,
+ getSubagentContentHead,
+ streamSubagentContentBatches,
+ };
+}
+
+export type SubagentContentMethods = ReturnType<typeof createSubagentContentMethods>;
diff --git a/packages/data-schemas/src/models/index.ts b/packages/data-schemas/src/models/index.ts
index 7cc7b1eb3b..8081a9310a 100644
--- a/packages/data-schemas/src/models/index.ts
+++ b/packages/data-schemas/src/models/index.ts
@@ -9,6 +9,7 @@ import { createRefreshTokenBridgeModel } from './refreshTokenBridge';
import { createAgentTriggerDeliveryModel } from './triggerDelivery';
import { createToolApprovalGrantModel } from './toolApprovalGrant';
import { createSkillUploadIntentModel } from './skillUploadIntent';
+import { createSubagentContentModel } from './subagentContent';
import { createSkillSyncStatusModel } from './skillSyncStatus';
import { createConversationTagModel } from './conversationTag';
import { createCodeEnvironmentModel } from './codeEnvironment';
@@ -65,6 +66,7 @@ export function createModels(mongoose: typeof import('mongoose')): {
ChatProject: ReturnType<typeof createChatProjectModel>;
CodeEnvironment: ReturnType<typeof createCodeEnvironmentModel>;
Message: ReturnType<typeof createMessageModel>;
+ SubagentContent: ReturnType<typeof createSubagentContentModel>;
Agent: ReturnType<typeof createAgentModel>;
AgentApiKey: ReturnType<typeof createAgentApiKeyModel>;
AgentCategory: ReturnType<typeof createAgentCategoryModel>;
@@ -119,6 +121,7 @@ export function createModels(mongoose: typeof import('mongoose')): {
ChatProject: createChatProjectModel(mongoose),
CodeEnvironment: createCodeEnvironmentModel(mongoose),
Message: createMessageModel(mongoose),
+ SubagentContent: createSubagentContentModel(mongoose),
Agent: createAgentModel(mongoose),
AgentApiKey: createAgentApiKeyModel(mongoose),
AgentCategory: createAgentCategoryModel(mongoose),
diff --git a/packages/data-schemas/src/models/subagentContent.ts b/packages/data-schemas/src/models/subagentContent.ts
new file mode 100644
index 0000000000..0aa2395b86
--- /dev/null
+++ b/packages/data-schemas/src/models/subagentContent.ts
@@ -0,0 +1,64 @@
+import { Schema } from 'mongoose';
+import type { Model } from 'mongoose';
+import { applyTenantIsolation } from './plugins/tenantIsolation';
+
+export interface ISubagentContentChunk {
+ _id: string;
+ user: string;
+ tenantId?: string;
+ parentConversationId: string;
+ conversationId: string;
+ taskId: string;
+ revision: number;
+ /** -1 is the commit record, published only after every payload fragment exists. */
+ fragment: number;
+ fragments: number;
+ fromSequence: number;
+ throughSequence: number;
+ digest: string;
+ payload?: string;
+ expiredAt?: Date;
+}
+
+export function createSubagentContentModel(
+ mongoose: typeof import('mongoose'),
+): Model<ISubagentContentChunk> {
+ if (mongoose.models.SubagentContent != null) return mongoose.models.SubagentContent;
+ const schema = new Schema<ISubagentContentChunk>(
+ {
+ _id: { type: String, required: true },
+ user: { type: String, required: true },
+ tenantId: String,
+ parentConversationId: { type: String, required: true },
+ conversationId: { type: String, required: true },
+ taskId: { type: String, required: true },
+ revision: { type: Number, required: true },
+ fragment: { type: Number, required: true },
+ fragments: { type: Number, required: true },
+ fromSequence: { type: Number, required: true },
+ throughSequence: { type: Number, required: true },
+ digest: { type: String, required: true },
+ payload: String,
+ expiredAt: Date,
+ },
+ { versionKey: false },
+ );
+ schema.index(
+ { tenantId: 1, user: 1, conversationId: 1, taskId: 1, revision: 1, fragment: 1 },
+ { unique: true },
+ );
+ schema.index(
+ {
+ tenantId: 1,
+ user: 1,
+ parentConversationId: 1,
+ conversationId: 1,
+ taskId: 1,
+ throughSequence: 1,
+ },
+ { name: 'subagent_content_sequence', partialFilterExpression: { fragment: -1 } },
+ );
+ schema.index({ expiredAt: 1 }, { expireAfterSeconds: 0 });
+ applyTenantIsolation(schema);
+ return mongoose.model<ISubagentContentChunk>('SubagentContent', schema);
+}
diff --git a/packages/data-schemas/src/schema/message.ts b/packages/data-schemas/src/schema/message.ts
index 6f0552fb5a..4a00eab9d8 100644
--- a/packages/data-schemas/src/schema/message.ts
+++ b/packages/data-schemas/src/schema/message.ts
@@ -152,6 +152,16 @@ const messageSchema: Schema<IMessage> = new Schema(
type: String,
},
metadata: { type: mongoose.Schema.Types.Mixed },
+ subagentContent: {
+ type: {
+ version: { type: Number, enum: [1], required: true },
+ throughSequence: Number,
+ deleted: { type: Boolean, default: undefined },
+ },
+ _id: false,
+ select: false,
+ default: undefined,
+ },
subagentTranscript: {
type: {
taskId: { type: String, required: true },
diff --git a/packages/data-schemas/src/types/message.ts b/packages/data-schemas/src/types/message.ts
index f6fcd3f8d3..84e9eea0b2 100644
--- a/packages/data-schemas/src/types/message.ts
+++ b/packages/data-schemas/src/types/message.ts
@@ -46,6 +46,8 @@ export interface ISubagentTaskControlReceipt {
// @ts-ignore
export interface IMessage extends Document {
+ /** Public content capture version and expected terminal watermark; never a transcript. */
+ subagentContent?: { version: 1; throughSequence?: number; deleted?: boolean };
messageId: string;
conversationId: string;
user: string;