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: Keep Subagent Guidance in Main Chat Order (#17394)

lia-by-librechat[bot]5cf87548cd55
diff --git a/api/server/controllers/agents/__tests__/callbacks.spec.js b/api/server/controllers/agents/__tests__/callbacks.spec.js
index 19f4be4c42..b1334c2e6c 100644
--- a/api/server/controllers/agents/__tests__/callbacks.spec.js
+++ b/api/server/controllers/agents/__tests__/callbacks.spec.js
@@ -34,6 +34,7 @@ jest.mock('@librechat/api', () => ({
isCodeSessionToolName: jest.requireActual('@librechat/api').isCodeSessionToolName,
collectToolCallIds: jest.requireActual('@librechat/api').collectToolCallIds,
captureSubagentIdentity: jest.requireActual('@librechat/api').captureSubagentIdentity,
+ feedSubagentAggregator: jest.requireActual('@librechat/api').feedSubagentAggregator,
createToolTimingAdapter: jest.requireActual('@librechat/api').createToolTimingAdapter,
stampCommandExecutor: jest.requireActual('@librechat/api').stampCommandExecutor,
}));
@@ -507,6 +508,101 @@ describe('resumable event generation fencing', () => {
});
});
+ it('retains a duplicate steering boundary between parallel child tools and shifted text', async () => {
+ const { GraphEvents } = jest.requireActual('@librechat/agents');
+ const { getDefaultHandlers } = require('../callbacks');
+ const aggregators = new Map();
+ const handlers = getDefaultHandlers({
+ res: { write: jest.fn() },
+ aggregateContent: jest.fn(),
+ toolEndCallback: jest.fn(),
+ collectedUsage: [],
+ subagentAggregatorsByToolCallId: aggregators,
+ });
+ const base = {
+ parentToolCallId: 'nested-parent-call',
+ parentRunId: 'child-run',
+ subagentRunId: 'nested-run',
+ subagentType: 'researcher',
+ subagentAgentId: 'nested-agent',
+ runId: 'parent-run',
+ depth: 2,
+ };
+ const part = {
+ type: 'steer',
+ steer: 'Use the revised sources',
+ steerId: 'steer-1',
+ clientSteerId: 'client-steer-1',
+ createdAt: 1234,
+ };
+ const boundary = {
+ phase: 'steer_applied',
+ data: { index: 2, steerId: part.steerId, clientSteerId: part.clientSteerId, part },
+ };
+ for (const update of [
+ {
+ phase: 'run_step',
+ data: {
+ id: 'parallel-tools',
+ index: 0,
+ stepDetails: {
+ type: 'tool_calls',
+ tool_calls: [
+ { id: 'query-1', name: 'query', args: '{}', mcpServerName: 'search' },
+ { id: 'query-2', name: 'query', args: '{}' },
+ ],
+ },
+ },
+ },
+ boundary,
+ {
+ phase: 'run_step',
+ data: { id: 'after-step', index: 3, stepDetails: { type: 'message_creation' } },
+ },
+ {
+ phase: 'message_delta',
+ data: { id: 'after-step', delta: { content: [{ type: 'text', text: 'after' }] } },
+ },
+ boundary,
+ ]) {
+ await handlers[GraphEvents.ON_SUBAGENT_UPDATE].handle(GraphEvents.ON_SUBAGENT_UPDATE, {
+ ...base,
+ ...update,
+ });
+ }
+ const aggregator = aggregators.get(base.parentToolCallId);
+ expect(aggregator.contentParts).toHaveLength(4);
+ expect(aggregator.contentParts[0].tool_call).toMatchObject({
+ id: 'query-1',
+ mcpServerName: 'search',
+ });
+ expect(aggregator.contentParts[1].tool_call.id).toBe('query-2');
+ expect(aggregator.contentParts[2]).toEqual(part);
+ expect(aggregator.contentParts[3]).toMatchObject({ type: 'text', text: 'after' });
+ expect(aggregator.stepMap.get('after-step').index).toBe(3);
+ expect(aggregator.contentParts.filter((content) => content?.type === 'steer')).toHaveLength(1);
+ expect(jest.requireMock('@librechat/data-schemas').logger.warn).not.toHaveBeenCalled();
+ });
+
+ it.each([-1, 1.5, NaN, Infinity])('ignores invalid steering index %s', async (index) => {
+ const { GraphEvents } = jest.requireActual('@librechat/agents');
+ const { getDefaultHandlers } = require('../callbacks');
+ const aggregators = new Map();
+ const handlers = getDefaultHandlers({
+ res: { write: jest.fn() },
+ aggregateContent: jest.fn(),
+ toolEndCallback: jest.fn(),
+ collectedUsage: [],
+ subagentAggregatorsByToolCallId: aggregators,
+ });
+ await handlers[GraphEvents.ON_SUBAGENT_UPDATE].handle(GraphEvents.ON_SUBAGENT_UPDATE, {
+ parentToolCallId: 'parent-call',
+ phase: 'steer_applied',
+ data: { index, part: { type: 'steer', steer: 'guidance' } },
+ });
+ expect(aggregators.get('parent-call').contentParts).toEqual([]);
+ });
+
it('forwards the originating job epoch with deferred attachments', () => {
const { GenerationJobManager } = require('@librechat/api');
const { createAttachmentEmitter } = require('../callbacks');
diff --git a/api/server/controllers/agents/callbacks.js b/api/server/controllers/agents/callbacks.js
index 37ac16d90a..85502523d8 100644
--- a/api/server/controllers/agents/callbacks.js
+++ b/api/server/controllers/agents/callbacks.js
@@ -34,6 +34,7 @@ const {
shouldSignalSandboxStart,
getToolInputValidationDetails,
captureSubagentIdentity,
+ feedSubagentAggregator,
getAttachmentOwnership,
collectToolCallIds,
createToolTimingAdapter,
@@ -305,66 +306,6 @@ async function maybeEmitSandboxStarting(emitForJob, data, metadata) {
}
}
-/**
- * Maps a {@link SubagentUpdateEvent} phase to the corresponding
- * {@link GraphEvents} name that the SDK's `createContentAggregator`
- * knows how to consume. Phases that don't carry content (`start`, `stop`,
- * `error`) or whose payload doesn't match a handled event (`run_step`
- * with an `ON_TOOL_EXECUTE`-shaped batch request rather than a RunStep)
- * return `null` so the caller skips them.
- * @param {SubagentUpdateEvent} event
- * @returns {string | null}
- */
-function subagentPhaseToGraphEvent(event) {
- switch (event?.phase) {
- case 'run_step':
- /** `ON_RUN_STEP` and `ON_TOOL_EXECUTE` both forward with phase
- * `run_step`; only the former matches the aggregator's RunStep
- * schema. Detect by presence of `stepDetails`. */
- return event.data?.stepDetails ? GraphEvents.ON_RUN_STEP : null;
- case 'run_step_delta':
- return GraphEvents.ON_RUN_STEP_DELTA;
- case 'run_step_completed':
- return GraphEvents.ON_RUN_STEP_COMPLETED;
- case 'message_delta':
- return GraphEvents.ON_MESSAGE_DELTA;
- case 'reasoning_delta':
- return GraphEvents.ON_REASONING_DELTA;
- default:
- return null;
- }
-}
-
-/**
- * Folds a single {@link SubagentUpdateEvent} into the given content
- * aggregator. Silent no-op for phases outside the aggregator's domain.
- * @param {{ aggregateContent: Function, contentParts?: Array, stepMap?: Map }} aggregator
- * @param {SubagentUpdateEvent} event
- */
-function feedSubagentAggregator(aggregator, event, applyChildTiming) {
- const graphEvent = subagentPhaseToGraphEvent(event);
- if (graphEvent) aggregator.aggregateContent({ event: graphEvent, data: event.data });
- applyChildTiming(aggregator, event);
- if (!graphEvent) return;
-
- /** The SDK aggregator intentionally projects run-step tool calls onto its
- * public content shape, so host-only routing metadata is not copied. Restore
- * the server-owned identity by call id after that projection; otherwise the
- * persistence fallback has to parse an ambiguous delimiter-bearing name. */
- const toolCalls = event.data?.stepDetails?.tool_calls ?? [];
- const stepIndex = aggregator.stepMap?.get(event.data?.id)?.index;
- if (!Number.isInteger(stepIndex) || !Array.isArray(aggregator.contentParts)) {
- return;
- }
- for (let index = 0; index < toolCalls.length; index++) {
- const source = toolCalls[index];
- const target = aggregator.contentParts[stepIndex + index]?.tool_call;
- if (target?.id === source?.id && typeof source?.mcpServerName === 'string') {
- target.mcpServerName = source.mcpServerName;
- }
- }
-}
-
/**
* @typedef {Object} ToolExecuteOptions
* @property {(toolNames: string[]) => Promise<{loadedTools: StructuredTool[]}>} loadTools - Function to load tools by name
diff --git a/api/server/controllers/agents/client.test.js b/api/server/controllers/agents/client.test.js
index 34d9ae1d64..2cd42d8c84 100644
--- a/api/server/controllers/agents/client.test.js
+++ b/api/server/controllers/agents/client.test.js
@@ -9664,6 +9664,61 @@ describe('AgentClient - finalizeSubagentContent', () => {
expect(buffer.size).toBe(0);
});
+ it('persists before/steer/after without a private child journal or duplicate offset', async () => {
+ const part = {
+ type: 'steer',
+ steer: 'Use the revised sources',
+ steerId: 'steer-1',
+ clientSteerId: 'client-steer-1',
+ createdAt: 1234,
+ quotes: ['quoted guidance'],
+ files: [{ file_id: 'public-file' }],
+ };
+ const applied = event('steer_applied', {
+ index: 1,
+ steerId: part.steerId,
+ clientSteerId: part.clientSteerId,
+ part,
+ });
+ const buffer = await runSubagentEvents([
+ event('run_step', {
+ id: 'before-step',
+ index: 0,
+ stepDetails: { type: 'message_creation' },
+ }),
+ event('message_delta', {
+ id: 'before-step',
+ delta: { content: [{ type: 'text', text: 'before' }] },
+ }),
+ applied,
+ event('run_step', {
+ id: 'after-step',
+ index: 2,
+ stepDetails: { type: 'message_creation' },
+ }),
+ event('message_delta', {
+ id: 'after-step',
+ delta: { content: [{ type: 'text', text: 'after' }] },
+ }),
+ applied,
+ ]);
+ const client = makeClient(buffer);
+ client.options.req.config.subagentActivity = { enabled: false };
+ client.contentParts = [
+ { type: 'tool_call', tool_call: { id: 'call_sub', name: Constants.SUBAGENT } },
+ ];
+ client.finalizeSubagentContent();
+ const attached = client.contentParts[0].tool_call.subagent_content;
+ expect(attached).toEqual([
+ { type: 'text', text: 'before' },
+ part,
+ { type: 'text', text: 'after' },
+ ]);
+ expect(buffer.size).toBe(0);
+ client.finalizeSubagentContent();
+ expect(client.contentParts[0].tool_call.subagent_content).toEqual(attached);
+ });
+
it('stamps durable MCP server identity onto nested persisted tool calls', () => {
const client = makeClient(new Map());
client.options.agent.accessibleMcpServerNames = ['bar', 'foo_mcp_bar'];
diff --git a/api/server/routes/__test-utils__/convos-route-mocks.js b/api/server/routes/__test-utils__/convos-route-mocks.js
index 87e4935702..0f76f9c056 100644
--- a/api/server/routes/__test-utils__/convos-route-mocks.js
+++ b/api/server/routes/__test-utils__/convos-route-mocks.js
@@ -144,6 +144,7 @@ module.exports = {
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({})),
+ createSubagentControlReceiptHandler: () => jest.fn(),
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 50e26c4b31..27d7bc4f40 100644
--- a/api/server/routes/convos.js
+++ b/api/server/routes/convos.js
@@ -14,6 +14,7 @@ const {
createSubagentActivityStreamHandler,
createSubagentTaskContentHandler,
createSubagentControlHandler,
+ createSubagentControlReceiptHandler,
isValidSubagentControlRequest,
exemptAgentTriggerFromIpLimiter,
createParentSubagentIndexHandler,
@@ -169,6 +170,11 @@ const subagentTaskContentHandler = createSubagentTaskContentHandler(
() => subagentThreadTaskStore.contentPageBytes,
() => subagentThreadTaskStore.contentRecoveryGraceMs,
);
+const subagentControlReceiptHandler = createSubagentControlReceiptHandler({
+ getConvoOwnership: db.getConvoOwnership,
+ getSubagentThreadForParent: db.getSubagentThreadForParent,
+ getSubagentTaskControlReceipt: db.getSubagentTaskControlReceipt,
+});
const subagentControlHandler = createSubagentControlHandler({
getConvoOwnership: db.getConvoOwnership,
getSubagentThreadForParent: db.getSubagentThreadForParent,
@@ -278,6 +284,10 @@ router.get(
'/:parentConversationId/subagents/:threadId/tasks/:taskId/activity',
subagentActivityStreamHandler,
);
+router.get(
+ '/:parentConversationId/subagents/:threadId/tasks/:taskId/controls/:invocationId',
+ subagentControlReceiptHandler,
+);
router.post(
'/:parentConversationId/subagents/:threadId/control',
configMiddleware,
diff --git a/client/src/components/Chat/Messages/Content/Parts/PendingSteers.tsx b/client/src/components/Chat/Messages/Content/Parts/PendingSteers.tsx
index 81e7f9bc41..60cc385f01 100644
--- a/client/src/components/Chat/Messages/Content/Parts/PendingSteers.tsx
+++ b/client/src/components/Chat/Messages/Content/Parts/PendingSteers.tsx
@@ -162,7 +162,7 @@ function PendingSteers({ conversationId, index = 0, fullWidth = false }: Pending
files={steer.files}
steerId={steer.steerId}
createdAt={steer.createdAt}
- receiptState={receiptState}
+ receiptState={steer.status === 'failed' ? null : receiptState}
/>
{steer.status === 'failed' ? (
<div className="-mt-2 mb-2 flex flex-wrap items-center justify-end gap-3 text-xs">
diff --git a/client/src/components/Chat/Messages/Content/Parts/SteerPart.tsx b/client/src/components/Chat/Messages/Content/Parts/SteerPart.tsx
index 07b963d104..6d9e4c4917 100644
--- a/client/src/components/Chat/Messages/Content/Parts/SteerPart.tsx
+++ b/client/src/components/Chat/Messages/Content/Parts/SteerPart.tsx
@@ -30,8 +30,12 @@ const SteerPart = memo(function SteerPart({
createdAt,
isSubmitting = false,
receiptState = 'applied',
+ hasMore = false,
+ onExpand,
}: {
steer: string;
+ hasMore?: boolean;
+ onExpand?: () => void;
files?: TMessage['files'];
/** Quoted excerpts steered with the message; rendered as the same reference
* blocks a user bubble shows for `message.quotes`. */
@@ -44,7 +48,7 @@ const SteerPart = memo(function SteerPart({
* to timestamp gray (always settled on reload, share, and search). */
isSubmitting?: boolean;
/** Pending renderer state must never claim server application early. */
- receiptState?: SteerReceiptState;
+ receiptState?: SteerReceiptState | null;
}) {
const localize = useLocalize();
const { useUser, useFileMap, useUserTextPreferences, useLiveAppliedSteer } =
@@ -76,6 +80,9 @@ const SteerPart = memo(function SteerPart({
() => hydratedFiles?.filter((file) => !usesImagePreview(file)) ?? [],
[hydratedFiles],
);
+ useEffect(() => {
+ if (hasMore && !collapseLongUserMessages) onExpand?.();
+ }, [hasMore, collapseLongUserMessages, onExpand]);
const [selectedFile, setSelectedFile] = useState<Partial<TFile> | null>(null);
const handlePreviewClose = useCallback((open: boolean) => {
if (!open) {
@@ -148,7 +155,11 @@ const SteerPart = memo(function SteerPart({
)}
</div>
)}
- <CollapsibleText enabled={collapseLongUserMessages}>
+ <CollapsibleText
+ enabled={collapseLongUserMessages || hasMore}
+ hasMore={hasMore}
+ onExpand={onExpand}
+ >
<div
className={cn(
'markdown prose message-content light w-full break-words',
@@ -166,7 +177,9 @@ const SteerPart = memo(function SteerPart({
* width changes as the relative string ticks. */}
<div className="text-text-secondary mt-1 flex min-h-8 items-center justify-end gap-2">
<MessageTimestamp value={timestamp} className="ms-0" />
- <SteerReceipt state={receiptState} live={isSubmitting} animateIn={animateIn} />
+ {receiptState != null && (
+ <SteerReceipt state={receiptState} live={isSubmitting} animateIn={animateIn} />
+ )}
</div>
</div>
{otherFiles.length > 0 && (
diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/SteerPart.test.tsx b/client/src/components/Chat/Messages/Content/Parts/__tests__/SteerPart.test.tsx
index 8fc514f11d..b311c9f480 100644
--- a/client/src/components/Chat/Messages/Content/Parts/__tests__/SteerPart.test.tsx
+++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/SteerPart.test.tsx
@@ -335,3 +335,24 @@ describe('SteerPart receipt settling', () => {
expect(checks()).not.toHaveClass(STEER_ICON);
});
});
+
+it('keeps an unsuccessful guidance body and timestamp without a waiting or applied receipt', () => {
+ const queryClient = new QueryClient();
+ queryClient.setQueryData([QueryKeys.endpoints], {});
+ render(
+ <QueryClientProvider client={queryClient}>
+ <RecoilRoot>
+ <SteerPart
+ steer="unsuccessful guidance"
+ steerId="failed"
+ createdAt={1}
+ receiptState={null}
+ />
+ </RecoilRoot>
+ </QueryClientProvider>,
+ );
+ expect(screen.getByText('unsuccessful guidance')).toBeVisible();
+ expect(screen.getByTestId('steer-timestamp')).toBeInTheDocument();
+ expect(screen.queryByTestId('steer-receipt')).not.toBeInTheDocument();
+ queryClient.clear();
+});
diff --git a/client/src/components/Chat/Subagents/SubagentActivity.test.tsx b/client/src/components/Chat/Subagents/SubagentActivity.test.tsx
index b2164870fb..40d57b415b 100644
--- a/client/src/components/Chat/Subagents/SubagentActivity.test.tsx
+++ b/client/src/components/Chat/Subagents/SubagentActivity.test.tsx
@@ -1,9 +1,11 @@
import React from 'react';
import { ContentTypes } from 'librechat-data-provider';
-import { act, fireEvent, render as rtlRender, screen } from '@testing-library/react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { act, fireEvent, render as rtlRender, screen, waitFor } from '@testing-library/react';
import type { TMessageContentParts, Agents } from 'librechat-data-provider';
import type { ChildActivity } from './adapters';
import SubagentActivity, { SubagentActivityScrollSurface } from './SubagentActivity';
+import { TaskContentScopeContext } from '~/data-provider/Subagents/content';
import { ChatSurfaceHarness } from 'test/harness';
const Wrapper = ({ children }: { children: React.ReactNode }) => (
@@ -11,6 +13,18 @@ const Wrapper = ({ children }: { children: React.ReactNode }) => (
);
const render = (ui: React.ReactElement) => rtlRender(ui, { wrapper: Wrapper });
+const mockShowMore = 'com_ui_show_more';
+const mockReadControl = jest.fn();
+jest.mock('librechat-data-provider', () => {
+ const actual = jest.requireActual('librechat-data-provider');
+ return {
+ ...actual,
+ dataService: {
+ ...actual.dataService,
+ getSubagentControlReceipt: (...args: unknown[]) => mockReadControl(...args),
+ },
+ };
+});
const mockContentParts = jest.fn();
let mockAutoExpandTools = false;
@@ -25,6 +39,32 @@ jest.mock('~/hooks', () => ({
useLocalize: () => (key: string) => key,
}));
+jest.mock('~/components/Chat/Messages/Content/Parts/SteerPart', () => ({
+ __esModule: true,
+ default: ({
+ steer,
+ steerId,
+ receiptState,
+ hasMore,
+ onExpand,
+ }: {
+ steer: string;
+ steerId?: string;
+ receiptState?: string | null;
+ hasMore?: boolean;
+ onExpand?: () => void;
+ }) => (
+ <div data-testid="shared-steer-part" data-receipt={receiptState} data-steer-id={steerId}>
+ {steer}
+ {hasMore && (
+ <button type="button" onClick={onExpand}>
+ {mockShowMore}
+ </button>
+ )}
+ </div>
+ ),
+}));
+
jest.mock('~/components/Chat/Messages/Content/Parts', () => ({
EmptyText: () => <div data-testid="thinking-cursor" />,
}));
@@ -493,7 +533,12 @@ describe('SubagentActivity', () => {
expect(screen.getByText('com_ui_subagent_control_status_accepted')).toBeInTheDocument();
expect(screen.getByText('com_ui_subagent_control_status_applied')).toBeInTheDocument();
expect(screen.getByText('com_ui_subagent_control_status_rejected')).toBeInTheDocument();
- expect(screen.getByText('com_ui_subagent_control_message_truncated')).toBeInTheDocument();
+ expect(screen.queryByText('com_ui_subagent_control_message_truncated')).not.toBeInTheDocument();
+ expect(
+ screen
+ .getAllByTestId('shared-steer-part')
+ .some((part) => part.textContent === 'Add a citation.'),
+ ).toBe(true);
expect(screen.getByText('com_ui_subagent_control_reason_task_completed')).toBeInTheDocument();
const accepted = screen.getByText('com_ui_subagent_control_status_accepted');
@@ -708,7 +753,7 @@ it('does not claim delivery or application before the server confirms it', () =>
}}
/>,
);
- expect(screen.getByTestId('steer-receipt')).toHaveAttribute('data-receipt-state', 'sending');
+ expect(screen.getByTestId('shared-steer-part')).toHaveAttribute('data-receipt', 'sending');
});
it('preserves empty recovered slots when rendering applied control receipts', () => {
@@ -741,3 +786,293 @@ it('preserves empty recovered slots when rendering applied control receipts', ()
expect(mockContentParts.mock.calls[0][0].content[0]).toBeNull();
expect(mockContentParts.mock.calls[0][0].content[1].tool_call.id).toBe('retained');
});
+
+it('renders applied controls inline once instead of repeating them below all current activity', () => {
+ const part = {
+ type: ContentTypes.STEER as const,
+ steer: 'Apply now.',
+ steerId: 'control',
+ createdAt: 100,
+ };
+ render(
+ <SubagentActivity
+ activity={{
+ ...base,
+ content: [part, { type: ContentTypes.TEXT, text: 'Work after guidance.' }],
+ controls: [
+ {
+ invocationId: 'invocation',
+ controlId: 'control',
+ action: 'steer',
+ status: 'applied',
+ message: 'Apply now.',
+ createdAt: '2026-08-24T12:00:00.000Z',
+ updatedAt: '2026-08-24T12:00:01.000Z',
+ },
+ ],
+ }}
+ />,
+ );
+ expect(screen.queryByTestId('shared-steer-part')).not.toBeInTheDocument();
+ expect(mockContentParts.mock.calls.at(-1)?.[0].content).toEqual([
+ part,
+ { type: ContentTypes.TEXT, text: 'Work after guidance.' },
+ ]);
+});
+
+it('keeps retained applied guidance that a partial legacy transcript does not contain', () => {
+ render(
+ <SubagentActivity
+ activity={{
+ ...base,
+ activityTruncated: true,
+ content: [
+ { type: ContentTypes.STEER, steer: 'Guidance present in the transcript.' },
+ { type: ContentTypes.TEXT, text: 'Continued work.' },
+ ],
+ controls: [
+ {
+ invocationId: 'retained',
+ controlId: 'retained-control',
+ action: 'steer',
+ status: 'applied',
+ message: 'Different retained guidance outside this transcript prefix.',
+ createdAt: '2026-10-23T00:00:00Z',
+ updatedAt: '2026-10-23T00:00:01Z',
+ },
+ ],
+ }}
+ />,
+ );
+ expect(screen.getByTestId('shared-steer-part')).toHaveTextContent(
+ 'Different retained guidance outside this transcript prefix.',
+ );
+});
+
+it('suppresses only the corresponding number of legacy guidance bodies and does not invent identities', () => {
+ const receipt = {
+ action: 'steer' as const,
+ status: 'applied' as const,
+ message: 'Repeated guidance.',
+ createdAt: '2026-10-23T00:00:00Z',
+ updatedAt: '2026-10-23T00:00:01Z',
+ };
+ render(
+ <SubagentActivity
+ activity={{
+ ...base,
+ activityTruncated: true,
+ content: [{ type: ContentTypes.STEER, steer: 'Repeated guidance.' }],
+ controls: [
+ { ...receipt, invocationId: 'one', controlId: 'one' },
+ { ...receipt, invocationId: 'two', controlId: 'two' },
+ ],
+ }}
+ />,
+ );
+ expect(screen.getAllByTestId('shared-steer-part')).toHaveLength(1);
+ expect(screen.getByTestId('shared-steer-part')).toHaveTextContent('Repeated guidance.');
+ expect(screen.getByTestId('shared-steer-part')).toHaveAttribute('data-steer-id', 'one');
+ expect(mockContentParts.mock.calls.at(-1)?.[0].content).toEqual([
+ { type: ContentTypes.STEER, steer: 'Repeated guidance.' },
+ ]);
+});
+
+it('loads a budgeted retained body only after expansion while keeping Withdraw actionable', async () => {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ const full = 'Full retained guidance. '.repeat(80);
+ const control = {
+ invocationId: 'budgeted',
+ controlId: 'pending-control',
+ action: 'queue' as const,
+ status: 'accepted' as const,
+ createdAt: '2026-10-23T00:00:00Z',
+ updatedAt: '2026-10-23T00:00:01Z',
+ message: 'Budgeted prefix',
+ messageTruncated: true,
+ };
+ mockReadControl.mockResolvedValueOnce({
+ receipt: { ...control, message: full, messageTruncated: false },
+ });
+ const withdraw = jest.fn();
+ const { unmount } = render(
+ <QueryClientProvider client={client}>
+ <TaskContentScopeContext.Provider
+ value={{ parentConversationId: 'parent', threadId: 'child', taskId: 'task' }}
+ >
+ <SubagentActivity activity={{ ...base, controls: [control] }} onCancelControl={withdraw} />
+ </TaskContentScopeContext.Provider>
+ </QueryClientProvider>,
+ );
+ expect(mockReadControl).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole('button', { name: mockShowMore }));
+ await waitFor(() =>
+ expect(screen.getByTestId('shared-steer-part')).toHaveTextContent(full.trim()),
+ );
+ expect(mockReadControl).toHaveBeenCalledTimes(1);
+ expect(mockReadControl).toHaveBeenCalledWith('parent', 'child', 'task', 'budgeted');
+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_subagent_control_withdraw' }));
+ expect(withdraw).toHaveBeenCalledWith('pending-control');
+ expect(screen.queryByText('Message shortened for display.')).not.toBeInTheDocument();
+ unmount();
+ client.clear();
+});
+
+it.each(['submitted', 'accepted', 'failed'] as const)(
+ 'retires an already-applied %s receipt by its client identity without waiting for the ledger',
+ (status) => {
+ const applied = {
+ type: ContentTypes.STEER as const,
+ steer: 'Applied guidance.',
+ steerId: 'server-control',
+ clientSteerId: 'client-invocation',
+ };
+ render(
+ <SubagentActivity
+ activity={{
+ ...base,
+ content: [applied, { type: ContentTypes.TEXT, text: 'Later activity.' }],
+ controls: [
+ {
+ invocationId: 'client-invocation',
+ action: 'steer',
+ status,
+ message: 'Applied guidance.',
+ createdAt: '2026-10-23T00:00:00Z',
+ updatedAt: '2026-10-23T00:00:01Z',
+ },
+ ],
+ }}
+ />,
+ );
+ expect(screen.queryByTestId('shared-steer-part')).not.toBeInTheDocument();
+ expect(mockContentParts.mock.calls.at(-1)?.[0].content).toContainEqual(applied);
+ },
+);
+
+it('does not hide a failed withdrawal just because its target was already applied', () => {
+ render(
+ <SubagentActivity
+ activity={{
+ ...base,
+ content: [
+ { type: ContentTypes.STEER, steer: 'Applied guidance.', steerId: 'server-control' },
+ ],
+ controls: [
+ {
+ invocationId: 'withdrawal',
+ controlId: 'server-control',
+ action: 'cancel_message',
+ status: 'rejected',
+ reason: 'control_not_found',
+ createdAt: '2026-10-23T00:00:00Z',
+ updatedAt: '2026-10-23T00:00:01Z',
+ },
+ ],
+ }}
+ />,
+ );
+ expect(screen.getByText('com_ui_subagent_control_reason_control_not_found')).toBeInTheDocument();
+});
+
+it.each(['failed', 'rejected'] as const)(
+ 'keeps the %s guidance body readable without asserting enqueue or application',
+ (status) => {
+ render(
+ <SubagentActivity
+ activity={{
+ ...base,
+ controls: [
+ {
+ invocationId: 'terminal',
+ action: 'steer',
+ status,
+ message: 'Retained terminal guidance.',
+ reason: status === 'rejected' ? 'withdrawn' : 'owner_unavailable',
+ createdAt: '2026-10-23T00:00:00Z',
+ updatedAt: '2026-10-23T00:00:01Z',
+ },
+ ],
+ }}
+ />,
+ );
+ expect(screen.getByTestId('shared-steer-part')).toHaveTextContent(
+ 'Retained terminal guidance.',
+ );
+ expect(screen.getByTestId('shared-steer-part')).not.toHaveAttribute('data-receipt');
+ expect(screen.getByText(`com_ui_subagent_control_status_${status}`)).toBeVisible();
+ },
+);
+
+it.each(['submitted', 'failed'] as const)(
+ 'retains the durable client identity to retire an already-applied %s receipt',
+ (status) => {
+ render(
+ <SubagentActivity
+ activity={{
+ ...base,
+ items: [
+ {
+ type: 'steer',
+ steer: 'Durably applied guidance.',
+ steerId: 'server-control',
+ clientSteerId: 'client-invocation',
+ createdAt: 100,
+ },
+ { type: 'writing', text: 'Later durable work.' },
+ ],
+ controls: [
+ {
+ invocationId: 'client-invocation',
+ action: 'steer',
+ status,
+ message: 'Durably applied guidance.',
+ createdAt: '2026-10-23T00:00:00Z',
+ updatedAt: '2026-10-23T00:00:01Z',
+ },
+ ],
+ }}
+ />,
+ );
+ expect(screen.queryByTestId('shared-steer-part')).not.toBeInTheDocument();
+ expect(mockContentParts.mock.calls.at(-1)?.[0].content).toEqual([
+ {
+ type: ContentTypes.STEER,
+ steer: 'Durably applied guidance.',
+ steerId: 'server-control',
+ clientSteerId: 'client-invocation',
+ createdAt: 100,
+ },
+ { type: ContentTypes.TEXT, text: 'Later durable work.' },
+ ]);
+ },
+);
+
+it('reserves identified inline controls before matching the newest legacy occurrences', () => {
+ const receipt = {
+ action: 'steer' as const,
+ status: 'applied' as const,
+ message: 'Same guidance.',
+ createdAt: '2026-10-23T00:00:00Z',
+ updatedAt: '2026-10-23T00:00:01Z',
+ };
+ render(
+ <SubagentActivity
+ activity={{
+ ...base,
+ activityTruncated: true,
+ content: [
+ { type: ContentTypes.STEER, steer: 'Same guidance.' },
+ { type: ContentTypes.STEER, steer: 'Same guidance.', steerId: 'identified' },
+ ],
+ controls: [
+ { ...receipt, invocationId: 'oldest', controlId: 'oldest' },
+ { ...receipt, invocationId: 'legacy', controlId: 'legacy' },
+ { ...receipt, invocationId: 'identified', controlId: 'identified' },
+ ],
+ }}
+ />,
+ );
+ expect(screen.getAllByTestId('shared-steer-part')).toHaveLength(1);
+ expect(screen.getByTestId('shared-steer-part')).toHaveAttribute('data-steer-id', 'oldest');
+});
diff --git a/client/src/components/Chat/Subagents/SubagentActivity.tsx b/client/src/components/Chat/Subagents/SubagentActivity.tsx
index a260bd908d..54d7cd6edd 100644
--- a/client/src/components/Chat/Subagents/SubagentActivity.tsx
+++ b/client/src/components/Chat/Subagents/SubagentActivity.tsx
@@ -1,11 +1,13 @@
-import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';
+import { useCallback, useEffect, useId, useMemo, useContext, useRef, useState } from 'react';
+import { useQuery } from '@tanstack/react-query';
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 { ContentTypes, QueryKeys, dataService } 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 { TaskContentScope } from '~/data-provider/Subagents/content';
import type { ChildActivity, ChildActivityItem } from './adapters';
import type { TranslationKeys } from '~/hooks';
import {
@@ -16,13 +18,14 @@ import {
} from './status';
import { ToolContentQueryContext } from '~/components/Chat/Messages/Content/disclosure';
import MessageTimestamp from '~/components/Chat/Messages/ui/MessageTimestamp';
+import { TaskContentScopeContext } from '~/data-provider/Subagents/content';
import MarkdownLite from '~/components/Chat/Messages/Content/MarkdownLite';
import ContentParts from '~/components/Chat/Messages/Content/ContentParts';
+import SteerPart from '~/components/Chat/Messages/Content/Parts/SteerPart';
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 SteerReceipt from '~/components/Chat/Steering/Receipt';
import { useChatSurface } from './surface';
import { useLocalize } from '~/hooks';
import { cn } from '~/utils';
@@ -54,6 +57,81 @@ const CONTROL_REASON_LABELS: Record<string, TranslationKeys> = {
withdrawn: 'com_ui_subagent_control_reason_withdrawn',
};
+type ControlMessageProps = {
+ control: NonNullable<ChildActivity['controls']>[number];
+ receiptState: SteerReceiptState | null;
+ pending: boolean;
+};
+
+function RetainedControlMessage({
+ control,
+ receiptState,
+ pending,
+ scope,
+}: ControlMessageProps & { scope: TaskContentScope }) {
+ const localize = useLocalize();
+ const [expanded, setExpanded] = useState(false);
+ const reveal = useCallback(() => setExpanded(true), []);
+ const query = useQuery(
+ [
+ QueryKeys.subagentControlReceipt,
+ scope.parentConversationId,
+ scope.threadId,
+ scope.taskId,
+ control.invocationId,
+ ],
+ async () => {
+ const response = await dataService.getSubagentControlReceipt(
+ scope.parentConversationId,
+ scope.threadId,
+ scope.taskId,
+ control.invocationId,
+ );
+ if (response.receipt.invocationId !== control.invocationId)
+ throw new Error('subagent_control_identity_mismatch');
+ return response;
+ },
+ { enabled: expanded, retry: 1, staleTime: Infinity, refetchOnWindowFocus: false },
+ );
+ return (
+ <>
+ <SteerPart
+ steer={query.data?.receipt.message ?? control.message ?? ''}
+ steerId={control.controlId ?? control.invocationId}
+ createdAt={Date.parse(control.createdAt)}
+ receiptState={receiptState}
+ isSubmitting={pending}
+ hasMore={query.data == null}
+ onExpand={reveal}
+ />
+ {query.isFetching && <span role="status">{localize('com_ui_loading')}</span>}
+ {query.isError && (
+ <Alert variant="error">
+ <span>{localize('com_ui_conversation_load_error')}</span>
+ <Button variant="ghost" size="sm" onClick={() => void query.refetch()}>
+ {localize('com_ui_retry')}
+ </Button>
+ </Alert>
+ )}
+ </>
+ );
+}
+
+function ControlMessage(props: ControlMessageProps) {
+ const scope = useContext(TaskContentScopeContext);
+ if (props.control.messageTruncated === true && scope != null)
+ return <RetainedControlMessage {...props} scope={scope} />;
+ return (
+ <SteerPart
+ steer={props.control.message ?? ''}
+ steerId={props.control.controlId ?? props.control.invocationId}
+ createdAt={Date.parse(props.control.createdAt)}
+ receiptState={props.receiptState}
+ isSubmitting={props.pending}
+ />
+ );
+}
+
function SubagentControlHistory({
controls,
onCancelControl,
@@ -74,57 +152,76 @@ function SubagentControlHistory({
left.control.createdAt.localeCompare(right.control.createdAt) || left.index - right.index,
)
.map(({ control }) => control);
+ const legacyGuidance = new Map<string, number>();
+ const appliedIds = new Set<string>();
+ for (const part of content) {
+ if (part?.type !== ContentTypes.STEER) continue;
+ if (part.steerId != null) appliedIds.add(part.steerId);
+ if (part.clientSteerId != null) appliedIds.add(part.clientSteerId);
+ if (part.steerId == null) {
+ legacyGuidance.set(part.steer, (legacyGuidance.get(part.steer) ?? 0) + 1);
+ }
+ }
+ const representedControls = new Set<string>();
+ for (let index = chronologicalControls.length - 1; index >= 0; index--) {
+ const control = chronologicalControls[index];
+ if (control.action !== 'steer' && control.action !== 'queue' && control.action !== 'interrupt')
+ continue;
+ if (
+ appliedIds.has(control.invocationId) ||
+ (control.controlId != null && appliedIds.has(control.controlId))
+ ) {
+ representedControls.add(control.invocationId);
+ continue;
+ }
+ if (control.status !== 'applied' || control.message == null) continue;
+ const remaining = legacyGuidance.get(control.message) ?? 0;
+ if (remaining > 0) {
+ representedControls.add(control.invocationId);
+ legacyGuidance.set(control.message, remaining - 1);
+ }
+ }
return (
<section aria-label={localize('com_ui_subagent_control_history')} className="mb-3 space-y-2">
{chronologicalControls.map((control) => {
+ const represented = representedControls.has(control.invocationId);
if (
- control.status === 'applied' &&
- content.some(
- (part) =>
- part?.type === ContentTypes.STEER &&
- part.steerId != null &&
- (part.steerId === control.controlId || part.steerId === control.invocationId),
- )
- ) {
+ represented &&
+ (appliedIds.has(control.invocationId) ||
+ (control.controlId != null && appliedIds.has(control.controlId)))
+ )
return null;
- }
+ const legacyInlineGuidance = represented;
const pending = control.status === 'submitted' || control.status === 'accepted';
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 === 'accepted')
+ receiptState = control.action === 'interrupt' ? 'interrupting' : 'delivered';
else if (control.status === 'applied') receiptState = 'applied';
}
return (
- <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
+ key={control.invocationId}
+ className={cn('group flex flex-col items-end text-sm', pending && 'opacity-60')}
+ >
+ {!legacyInlineGuidance && control.message != null && control.message !== '' && (
+ <ControlMessage
+ control={control}
+ receiptState={receiptState ?? null}
+ pending={pending}
+ />
)}
- <div className="text-text-secondary mt-1 flex min-h-8 flex-wrap items-center justify-end gap-2 text-xs">
+ <div className="text-text-secondary flex flex-wrap items-center justify-end gap-2 text-xs">
<span className={control.message ? 'sr-only' : undefined}>
{localize(CONTROL_ACTION_LABELS[control.action])}
</span>
- <MessageTimestamp value={control.createdAt} className="ms-0" />
+ {(legacyInlineGuidance || !control.message) && (
+ <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 && (
@@ -232,6 +329,15 @@ export function SubagentActivityScrollSurface({
}
const toContentPart = (item: ChildActivityItem): TMessageContentParts => {
+ if (item.type === 'steer') {
+ return {
+ type: ContentTypes.STEER,
+ steer: item.steer,
+ steerId: item.steerId,
+ clientSteerId: item.clientSteerId,
+ createdAt: item.createdAt,
+ };
+ }
if (item.type === 'writing') {
return {
type: ContentTypes.TEXT,
diff --git a/client/src/components/Chat/Subagents/SubagentConversation.test.tsx b/client/src/components/Chat/Subagents/SubagentConversation.test.tsx
index dd831b61bc..7e1f7571c4 100644
--- a/client/src/components/Chat/Subagents/SubagentConversation.test.tsx
+++ b/client/src/components/Chat/Subagents/SubagentConversation.test.tsx
@@ -938,3 +938,55 @@ it.each(['partial', 'complete'] as const)(
expect(content).toHaveLength(1);
},
);
+
+it.each(['completed', 'failed', 'cancelled', 'interrupted'] as const)(
+ 'keeps the %s outcome after ordered guidance with recovery disabled',
+ (status) => {
+ mockRecoveredQuery.mockReturnValue({ data: undefined });
+ const content: TMessageContentParts[] = [
+ { type: ContentTypes.TEXT, text: 'Before guidance.' },
+ {
+ type: ContentTypes.STEER,
+ steer: 'Parent guidance.',
+ steerId: 'control',
+ clientSteerId: 'invocation',
+ },
+ { type: ContentTypes.TEXT, text: 'After guidance.' },
+ ];
+ const outcome = {
+ messageId: 'task-1:assistant',
+ parentMessageId: 'task-1:user',
+ role: 'assistant' as const,
+ text: `Durable ${status} result.`,
+ ...(status === 'failed' ? { error: true } : {}),
+ };
+ render(
+ <ChatSurfaceHarness>
+ <SubagentConversation
+ author={author}
+ parentAuthor={parentAuthor}
+ recovery={{
+ parentConversationId: 'parent',
+ threadId: 'child',
+ selectedTaskId: 'task-1',
+ ready: true,
+ }}
+ turns={[
+ {
+ ...turns[0],
+ contentRecoveryAvailable: false,
+ outcome,
+ activity: { ...turns[0].activity, status, content },
+ },
+ ]}
+ />
+ </ChatSurfaceHarness>,
+ );
+ expect(screen.getAllByText(outcome.text)).toHaveLength(1);
+ expect(mockCopyMessage.mock.calls.at(-1)?.[0].content).toEqual([
+ ...content,
+ { type: ContentTypes.TEXT, text: outcome.text, phase: 'final_answer' },
+ ]);
+ expect(content).toHaveLength(3);
+ },
+);
diff --git a/client/src/components/Chat/Subagents/SubagentConversation.tsx b/client/src/components/Chat/Subagents/SubagentConversation.tsx
index 9b94e27f87..a492476ca8 100644
--- a/client/src/components/Chat/Subagents/SubagentConversation.tsx
+++ b/client/src/components/Chat/Subagents/SubagentConversation.tsx
@@ -228,10 +228,8 @@ function ChildMessage({
onLoadDetails,
toolContentQuery,
notice,
- outcomeContent,
}: {
notice?: ReactNode;
- outcomeContent?: TMessageContentParts[];
toolContentQuery?: ToolContentQuery;
turn: ChildConversationTurn;
state: 'ready' | 'loading' | 'error';
@@ -245,6 +243,16 @@ function ChildMessage({
const localize = useLocalize();
const activity = turn.activity;
const content = useMemo(() => getActivityContent(activity), [activity]);
+ const outcomeContent = useMemo<TMessageContentParts[] | undefined>(() => {
+ const outcome = turn.outcome;
+ if (
+ isLiveSubagentStatus(activity.status) ||
+ !outcome?.text ||
+ hasTerminalOutcome(content, outcome, activity.status)
+ )
+ return undefined;
+ return [{ type: ContentTypes.TEXT, text: outcome.text, phase: 'final_answer' }];
+ }, [content, turn.outcome, activity.status]);
const message = useMemo<TMessage>(
() => ({
messageId: activity.messageId ?? `${turn.taskId}:assistant`,
@@ -394,19 +402,6 @@ function RecoveredChildMessage({
},
};
}, [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 &&
@@ -431,7 +426,6 @@ function RecoveredChildMessage({
: 'ready'
}
toolContentQuery={useSubagentToolContentQuery}
- outcomeContent={outcomeContent}
notice={notice}
/>
</TaskContentScopeContext.Provider>
diff --git a/client/src/components/Chat/Subagents/SubagentThreadPanel.test.tsx b/client/src/components/Chat/Subagents/SubagentThreadPanel.test.tsx
index e7d9e8af4e..b4b139faa4 100644
--- a/client/src/components/Chat/Subagents/SubagentThreadPanel.test.tsx
+++ b/client/src/components/Chat/Subagents/SubagentThreadPanel.test.tsx
@@ -196,7 +196,7 @@ jest.mock('./SubagentActivity', () => ({
SubagentActivityScrollSurface: ({ children }: { children: React.ReactNode }) => (
<div data-testid="shared-scroll-surface">{children}</div>
),
- default: ({
+ default: function MockActivity({
activity,
activityId,
state,
@@ -211,35 +211,43 @@ jest.mock('./SubagentActivity', () => ({
activityId?: string;
state: string;
onCancelControl?: (controlId: string) => void;
- }) => (
- <div
- data-testid="shared-activity"
- data-activity-id={activityId}
- data-state={state}
- data-status={activity.status}
- data-can-withdraw={onCancelControl != null ? 'true' : 'false'}
- >
- {activity.prompt}
- {activity.items.map((item, index) => (
- <span key={index}>{item.text ?? item.type}</span>
- ))}
- {activity.controls?.map((control) => (
- <span key={control.invocationId}>{control.status}</span>
- ))}
- {onCancelControl != null && (
- <button
- type="button"
- data-testid="withdraw-control"
- onClick={() => onCancelControl('control-1')}
- />
- )}
- </div>
- ),
+ }) {
+ const { useContext } = jest.requireActual<typeof import('react')>('react');
+ const { TaskContentScopeContext } = jest.requireActual<
+ typeof import('~/data-provider/Subagents/content')
+ >('~/data-provider/Subagents/content');
+ const scope = useContext(TaskContentScopeContext);
+ return (
+ <div
+ data-testid="shared-activity"
+ data-receipt-scope={JSON.stringify(scope)}
+ data-activity-id={activityId}
+ data-state={state}
+ data-status={activity.status}
+ data-can-withdraw={onCancelControl != null ? 'true' : 'false'}
+ >
+ {activity.prompt}
+ {activity.items.map((item, index) => (
+ <span key={index}>{item.text ?? item.type}</span>
+ ))}
+ {activity.controls?.map((control) => (
+ <span key={control.invocationId}>{control.status}</span>
+ ))}
+ {onCancelControl != null && (
+ <button
+ type="button"
+ data-testid="withdraw-control"
+ onClick={() => onCancelControl('control-1')}
+ />
+ )}
+ </div>
+ );
+ },
}));
jest.mock('./SubagentConversation', () => ({
__esModule: true,
- default: ({
+ default: function MockConversation({
turns,
author,
parentAuthor,
@@ -258,30 +266,38 @@ jest.mock('./SubagentConversation', () => ({
stateByTask?: ReadonlyMap<string, string>;
detailStateByTask?: ReadonlyMap<string, string>;
onLoadTurnDetails?: (taskId: string) => void;
- }) => (
- <div
- data-testid="subagent-conversation"
- data-state={turns[0] == null ? undefined : stateByTask?.get(turns[0].taskId)}
- data-author={author.name}
- data-parent-author={parentAuthor.name}
- >
- {author.icon}
- {turns.map((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>
- ))}
- {turn.activity.activityTruncated === true && onLoadTurnDetails != null && (
- <button type="button" onClick={() => onLoadTurnDetails(turn.taskId)}>
- {`load-${turn.taskId}`}
- </button>
- )}
- {detailStateByTask?.get(turn.taskId)}
- </div>
- ))}
- </div>
- ),
+ }) {
+ const { useContext } = jest.requireActual<typeof import('react')>('react');
+ const { TaskContentScopeContext } = jest.requireActual<
+ typeof import('~/data-provider/Subagents/content')
+ >('~/data-provider/Subagents/content');
+ const scope = useContext(TaskContentScopeContext);
+ return (
+ <div
+ data-testid="subagent-conversation"
+ data-receipt-scope={JSON.stringify(scope)}
+ data-state={turns[0] == null ? undefined : stateByTask?.get(turns[0].taskId)}
+ data-author={author.name}
+ data-parent-author={parentAuthor.name}
+ >
+ {author.icon}
+ {turns.map((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>
+ ))}
+ {turn.activity.activityTruncated === true && onLoadTurnDetails != null && (
+ <button type="button" onClick={() => onLoadTurnDetails(turn.taskId)}>
+ {`load-${turn.taskId}`}
+ </button>
+ )}
+ {detailStateByTask?.get(turn.taskId)}
+ </div>
+ ))}
+ </div>
+ );
+ },
}));
/** The shared composer's own Enter contract, for the mock to fall back on when
@@ -546,6 +562,94 @@ describe('SubagentThreadPanel', () => {
jest.restoreAllMocks();
});
+ it.each([false, true])(
+ 'provides the exact durable receipt scope with conversation projection=%s',
+ (projected) => {
+ mockUseSubagentThreadQuery.mockReturnValue({
+ data: {
+ ...completedView,
+ messages: projected ? completedView.messages : [],
+ turns: projected ? completedTurns : undefined,
+ },
+ isLoading: false,
+ isError: false,
+ isReadinessPending: false,
+ });
+ render(
+ <Root>
+ <SubagentThreadPanel selection={selection} />
+ </Root>,
+ );
+ const surface =
+ screen.queryByTestId('shared-activity') ?? screen.getByTestId('subagent-conversation');
+ expect(surface).toHaveAttribute(
+ 'data-receipt-scope',
+ JSON.stringify({
+ parentConversationId: selection.parentConversationId,
+ threadId: 'child-thread',
+ taskId: 'task',
+ }),
+ );
+ },
+ );
+
+ it('isolates historical event receipt scopes from the selected task', () => {
+ const child: ParentSubagentSummary = {
+ threadId: 'child-thread',
+ parentMessageId: 'parent-message',
+ subagentType: 'researcher',
+ subagentKind: 'agent',
+ title: 'Worker',
+ origin: 'event',
+ actorId: 'actor',
+ status: 'completed',
+ latestTaskId: 'task',
+ tasks: [
+ { taskId: 'task', status: 'completed' },
+ { taskId: 'earlier', status: 'completed' },
+ ],
+ tasksTruncated: false,
+ };
+ mockParentChildrenByThread = new Map([[child.threadId, child]]);
+ mockParentChildrenByMessage = new Map([['parent-message', [child]]]);
+ mockUseSubagentThreadQuery.mockReturnValue({
+ data: { ...completedView, turns: undefined },
+ isLoading: false,
+ isError: false,
+ isReadinessPending: false,
+ });
+ render(
+ <Root>
+ <SubagentThreadPanel
+ selection={{
+ ...selection,
+ event: { actorId: 'actor', progressKey: 'event-task:child-thread:task' },
+ }}
+ />
+ </Root>,
+ );
+ expect(
+ screen
+ .getAllByTestId('shared-activity')
+ .map((surface) => JSON.parse(surface.getAttribute('data-receipt-scope')!)),
+ ).toEqual([
+ { parentConversationId: 'parent-conversation', threadId: 'child-thread', taskId: 'earlier' },
+ { parentConversationId: 'parent-conversation', threadId: 'child-thread', taskId: 'task' },
+ ]);
+ });
+
+ it('does not provide private receipt scope for a foreground activity without a durable task', () => {
+ mockUseSubagentThreadQuery.mockReturnValue({ isLoading: false, isError: false });
+ render(
+ <Root>
+ <SubagentThreadPanel selection={{ ...selection, durable: undefined }} />
+ </Root>,
+ );
+ expect(screen.getByTestId('subagent-conversation')).toHaveAttribute(
+ 'data-receipt-scope',
+ 'null',
+ );
+ });
it.each(['agent-1', 'missing-agent', 'self'])(
'resolves the saved foreground identity %s in the panel',
(subagentType) => {
diff --git a/client/src/components/Chat/Subagents/SubagentThreadPanel.tsx b/client/src/components/Chat/Subagents/SubagentThreadPanel.tsx
index f8f7152b51..95f7690133 100644
--- a/client/src/components/Chat/Subagents/SubagentThreadPanel.tsx
+++ b/client/src/components/Chat/Subagents/SubagentThreadPanel.tsx
@@ -57,6 +57,7 @@ import {
import useSubagentActivityStream from '~/data-provider/Subagents/useSubagentActivityStream';
import SubagentActivity, { SubagentActivityScrollSurface } from './SubagentActivity';
import ApprovalProvider from '~/components/Chat/Messages/Content/ApprovalContext';
+import { TaskContentScopeContext } from '~/data-provider/Subagents/content';
import { isMacPlatform, resolveComposerKeyDown } from '~/utils/shortcuts';
import { useFocusTrap, useLocalize, useNavigateToConvo } from '~/hooks';
import { ARTIFACTS_SHEET_MAX_WIDTH } from '~/utils/breakpoints';
@@ -176,6 +177,13 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
);
const threadId = selection.durable?.threadId ?? '';
const taskId = selection.durable?.taskId ?? '';
+ const receiptScope = useMemo(
+ () =>
+ selection.host === 'conversation' && threadId !== '' && taskId !== ''
+ ? { parentConversationId: selection.parentConversationId, threadId, taskId }
+ : null,
+ [selection.host, selection.parentConversationId, threadId, taskId],
+ );
const controlIdentity = subagentControlStateKey(selection.parentConversationId, threadId, taskId);
const [controlState, setControlState] = useAtom(subagentControlStateByTask(controlIdentity));
const setControlStateForIdentity = useCallback(
@@ -1680,7 +1688,9 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
<ApprovalProvider
key={`${selection.parentMessageId}\u0000${selection.toolCallId}\u0000${selection.partIndex}`}
>
- {activityPanel}
+ <TaskContentScopeContext.Provider value={receiptScope}>
+ {activityPanel}
+ </TaskContentScopeContext.Provider>
</ApprovalProvider>
{(showControlFooter || composerMode != null) && (
/* The main chat form's own bottom rhythm, read from the same answer it
@@ -1770,6 +1780,13 @@ function HistoricalEventTaskActivity({
title: string;
}) {
const threadId = selection.durable?.threadId ?? '';
+ const receiptScope = useMemo(
+ () =>
+ selection.host === 'conversation' && threadId !== ''
+ ? { parentConversationId: selection.parentConversationId, threadId, taskId: task.taskId }
+ : null,
+ [selection.host, selection.parentConversationId, threadId, task.taskId],
+ );
const { data, isLoading, isError, isReadinessPending } = useSubagentThreadQuery(
selection.parentConversationId,
threadId,
@@ -1790,12 +1807,14 @@ function HistoricalEventTaskActivity({
}
return (
- <SubagentActivity
- activityId={`${selection.parentMessageId}\u0000${selection.toolCallId}\u0000${task.taskId}`}
- activity={activity}
- state={state}
- showPrompt={false}
- embedded
- />
+ <TaskContentScopeContext.Provider value={receiptScope}>
+ <SubagentActivity
+ activityId={`${selection.parentMessageId}\u0000${selection.toolCallId}\u0000${task.taskId}`}
+ activity={activity}
+ state={state}
+ showPrompt={false}
+ embedded
+ />
+ </TaskContentScopeContext.Provider>
);
}
diff --git a/client/src/components/Chat/Subagents/adapters.ts b/client/src/components/Chat/Subagents/adapters.ts
index 9c6353cf06..cf68117055 100644
--- a/client/src/components/Chat/Subagents/adapters.ts
+++ b/client/src/components/Chat/Subagents/adapters.ts
@@ -16,6 +16,7 @@ import type { SubagentProgress } from './state';
import { REDACTED_REASONING_MARKER } from './state';
export type ChildActivityItem =
+ | Extract<SubagentActivityItem, { type: 'steer' }>
| {
type: 'writing';
text: string;
@@ -105,6 +106,17 @@ const contentPartsToActivity = (
): ChildActivityItem[] =>
parts.flatMap((part, index): ChildActivityItem[] => {
if (part == null) return [];
+ if (part.type === ContentTypes.STEER) {
+ return [
+ {
+ type: 'steer',
+ steer: part.steer,
+ steerId: part.steerId,
+ clientSteerId: part.clientSteerId,
+ createdAt: part.createdAt,
+ },
+ ];
+ }
if (part.type === ContentTypes.TEXT) {
const textPart = part as {
text: string;
@@ -246,7 +258,7 @@ const mergePersistedAndLiveActivity = (
merged.push(item);
continue;
}
- if (item.type === 'activity_label') {
+ if (item.type === 'activity_label' || item.type === 'steer') {
merged.push(item);
continue;
}
diff --git a/client/src/components/Chat/Subagents/recovery.test.ts b/client/src/components/Chat/Subagents/recovery.test.ts
index c19716c6b2..769bb435a7 100644
--- a/client/src/components/Chat/Subagents/recovery.test.ts
+++ b/client/src/components/Chat/Subagents/recovery.test.ts
@@ -1,4 +1,4 @@
-import { ContentTypes, StepEvents, StepTypes } from 'librechat-data-provider';
+import { ContentTypes, StepEvents, StepTypes, SteerEvents } from 'librechat-data-provider';
import type {
SubagentTaskContentSnapshot,
SubagentTaskContentSuffix,
@@ -467,3 +467,67 @@ it('rejects parent identity changes as well as child identity changes', () => {
).toBeNull();
expect(reduceRecoveredContent(before, suffix([], { parentMessageId: 'other-user' }))).toBeNull();
});
+
+it('replays applied steering at its reserved slot before subsequent run steps without mutating the snapshot', () => {
+ const before = reduceRecoveredContent(null, snapshot())!;
+ const part = {
+ type: ContentTypes.STEER as const,
+ steer: 'Continue with citation',
+ steerId: 'control',
+ createdAt: 100,
+ };
+ const next = reduceRecoveredContent(
+ before,
+ suffix(
+ [
+ {
+ sequence: 1,
+ frame: {
+ event: SteerEvents.ON_STEER_APPLIED,
+ data: {
+ index: 1,
+ part,
+ steerId: 'control',
+ responseMessageId: 'task:assistant',
+ conversationId: 'thread',
+ },
+ },
+ },
+ {
+ sequence: 2,
+ frame: {
+ event: StepEvents.ON_RUN_STEP,
+ data: {
+ id: 'after',
+ runId: 'provider-run',
+ index: 2,
+ type: StepTypes.MESSAGE_CREATION,
+ stepDetails: {
+ type: StepTypes.MESSAGE_CREATION,
+ message_creation: { message_id: 'answer' },
+ },
+ usage: null,
+ },
+ },
+ },
+ {
+ sequence: 3,
+ frame: {
+ event: StepEvents.ON_MESSAGE_DELTA,
+ data: {
+ id: 'after',
+ delta: { content: [{ type: ContentTypes.TEXT, text: 'After control.' }] },
+ },
+ },
+ },
+ ],
+ { throughSequence: 3, targetThroughSequence: 3 },
+ ),
+ )!;
+ expect(next.snapshot.content).toMatchObject([
+ { text: 'Opening. ' },
+ part,
+ { text: 'After control.' },
+ ]);
+ expect(before.snapshot.content).toHaveLength(1);
+});
diff --git a/client/src/components/Chat/Subagents/recovery.ts b/client/src/components/Chat/Subagents/recovery.ts
index 46c4b049b1..6dad96238b 100644
--- a/client/src/components/Chat/Subagents/recovery.ts
+++ b/client/src/components/Chat/Subagents/recovery.ts
@@ -1,5 +1,11 @@
-import { createStreamState, reduceStep } from '@librechat/chat';
-import { ContentTypes, EModelEndpoint, StepEvents, StepTypes } from 'librechat-data-provider';
+import { createStreamState, reduceStep, applySteerPart } from '@librechat/chat';
+import {
+ ContentTypes,
+ EModelEndpoint,
+ StepEvents,
+ StepTypes,
+ SteerEvents,
+} from 'librechat-data-provider';
import type {
EventSubmission,
SubagentTaskContentResponse,
@@ -172,7 +178,13 @@ function applyRecoveredContent(
if (sequence <= response.afterSequence) continue;
if (sequence <= through || sequence > response.throughSequence) return null;
through = sequence;
- if (frame.event === StepEvents.ON_RUN_STEP) {
+ if (frame.event === SteerEvents.ON_STEER_APPLIED) {
+ const message = stream.messages.get(response.messageId);
+ if (message == null) return null;
+ const next = applySteerPart(message, frame.data);
+ stream.messages.set(response.messageId, next);
+ messages = messages.map((value) => (value.messageId === response.messageId ? next : value));
+ } else 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) {
diff --git a/client/src/components/Chat/Subagents/state.ts b/client/src/components/Chat/Subagents/state.ts
index 768c4ee8ba..4477e9592e 100644
--- a/client/src/components/Chat/Subagents/state.ts
+++ b/client/src/components/Chat/Subagents/state.ts
@@ -171,6 +171,13 @@ const boundSingletonPart = (part: SubagentContentPart): SubagentContentPart => {
);
}
+ if (part.type === ContentTypes.STEER) {
+ return fitStringField(
+ truncateUtf8(part.steer, MAX_SINGLE_ACTIVITY_TEXT_BYTES),
+ (steer) => ({ ...part, steer }),
+ MAX_SINGLE_ACTIVITY_ENCODED_BYTES,
+ );
+ }
let bounded: SubagentContentPart = {
...part,
tool_call: {
@@ -1046,6 +1053,9 @@ function prependSubagentReplay(
} else if (part.type === ContentTypes.THINK) {
event.phase = 'reasoning_delta';
event.data = { delta: { content: [part] } };
+ } else if (part.type === ContentTypes.STEER) {
+ event.phase = 'steer_applied';
+ event.data = { index: parts.length, part };
} else {
event.phase = 'run_step';
event.data = {
diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json
index df36d52e6e..a4b44ef8ab 100644
--- a/client/src/locales/en/translation.json
+++ b/client/src/locales/en/translation.json
@@ -3192,7 +3192,6 @@
"com_ui_subagent_event_expected_action": "Expected action",
"com_ui_subagent_continue_new_chat": "Continue in a new chat",
"com_ui_subagent_control_interrupt": "Interrupt",
- "com_ui_subagent_control_message_truncated": "Message shortened for display.",
"com_ui_subagent_control_queue": "Queued guidance",
"com_ui_subagent_control_reason_control_not_found": "That queued message is no longer available.",
"com_ui_subagent_control_reason_invalid_command": "The command was not accepted.",
diff --git a/client/src/utils/__tests__/subagentContent.test.ts b/client/src/utils/__tests__/subagentContent.test.ts
index a3d579ab1f..7a9af1379f 100644
--- a/client/src/utils/__tests__/subagentContent.test.ts
+++ b/client/src/utils/__tests__/subagentContent.test.ts
@@ -752,3 +752,39 @@ describe('tail ellipsis direction', () => {
expect(textDirection('\u0661\u0662 \u0645\u0631\u062D\u0628\u0627')).toBe('rtl');
});
});
+
+it('places applied guidance before subsequent live activity and closes the current text buffer', () => {
+ const applied = makeEvent({
+ phase: 'steer_applied',
+ data: {
+ index: 1,
+ steerId: 'control-1',
+ responseMessageId: 'task:assistant',
+ conversationId: 'thread',
+ part: {
+ type: ContentTypes.STEER,
+ steer: 'Continue with a citation.',
+ steerId: 'control-1',
+ clientSteerId: 'invocation-1',
+ createdAt: 100,
+ },
+ },
+ });
+ const parts = aggregateSubagentContent([
+ makeEvent({
+ phase: 'message_delta',
+ data: { id: 'before', delta: { content: [{ type: 'text', text: 'Earlier work.' }] } },
+ }),
+ applied,
+ applied,
+ makeEvent({
+ phase: 'message_delta',
+ data: { id: 'after', delta: { content: [{ type: 'text', text: 'Later work.' }] } },
+ }),
+ ]);
+ expect(parts).toMatchObject([
+ { type: ContentTypes.TEXT, text: 'Earlier work.' },
+ { type: ContentTypes.STEER, steer: 'Continue with a citation.', steerId: 'control-1' },
+ { type: ContentTypes.TEXT, text: 'Later work.' },
+ ]);
+});
diff --git a/client/src/utils/subagentContent.ts b/client/src/utils/subagentContent.ts
index da5e9856b8..a4599cfc8e 100644
--- a/client/src/utils/subagentContent.ts
+++ b/client/src/utils/subagentContent.ts
@@ -1,5 +1,9 @@
import { ContentTypes, ToolCallTypes, getToolTimingDurations } from 'librechat-data-provider';
-import type { SubagentUpdateEvent, ToolTimingStamps } from 'librechat-data-provider';
+import type {
+ SubagentUpdateEvent,
+ ToolTimingStamps,
+ TSteerAppliedEvent,
+} from 'librechat-data-provider';
import { strongDirection } from './direction';
/**
@@ -114,7 +118,7 @@ type ToolCallPart = {
/** Single content-part-shaped entry produced by the aggregator. The union
* matches the subset of `TMessageContentParts` a subagent run emits. */
-export type SubagentContentPart = TextPart | ThinkPart | ToolCallPart;
+export type SubagentContentPart = TextPart | ThinkPart | ToolCallPart | TSteerAppliedEvent['part'];
const extractTextChunk = (
data: MessageDeltaData | undefined,
@@ -217,6 +221,25 @@ export function foldSubagentEvent(
state: SubagentAggregatorState,
event: SubagentUpdateEvent,
): { parts: SubagentContentPart[]; state: SubagentAggregatorState } {
+ if (event.phase === 'steer_applied') {
+ const data = event.data as TSteerAppliedEvent | undefined;
+ if (
+ data?.part?.type !== ContentTypes.STEER ||
+ typeof data.part.steer !== 'string' ||
+ !Number.isSafeInteger(data.index) ||
+ data.index < 0
+ )
+ return { parts, state };
+ if (
+ parts.some((part) => part?.type === ContentTypes.STEER && part.steerId === data.part.steerId)
+ )
+ return { parts, state };
+ const next = [...parts, data.part];
+ return {
+ parts: next,
+ state: { ...state, openTextIdx: null, openThinkIdx: null, idlessTextPhase: undefined },
+ };
+ }
if (event.phase === 'message_delta') {
const data = event.data as MessageDeltaData | undefined;
const extracted = extractTextChunk(data);
diff --git a/e2e/fixtures/subagent-history.cjs b/e2e/fixtures/subagent-history.cjs
index 5fcbaf907f..e26a913c4a 100644
--- a/e2e/fixtures/subagent-history.cjs
+++ b/e2e/fixtures/subagent-history.cjs
@@ -67,7 +67,7 @@ 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 }) {
+function responsesForText(text, { messageType, getContentText }) {
const match = text.match(/E2E_SUBAGENT_HISTORY:([\w-]+):([a-z0-9-]{1,96})(?:\s|$)/);
if (!match) return null;
const [, childId, label] = match;
@@ -92,7 +92,12 @@ function responsesForText(text, { getLatestUserText, messageType, getContentText
.filter((message) => messageType(message) === 'tool')
.map((message) => [message.tool_call_id, getContentText(message.content)]),
);
- if (childId !== 'main' && !getLatestUserText(messages).includes(childPrompt)) {
+ const isChild = (messages ?? []).some(
+ (message) =>
+ ['human', 'user'].includes(messageType(message)) &&
+ getContentText(message.content).includes(childPrompt),
+ );
+ if (childId !== 'main' && !isChild) {
if (results.has(dispatchId(label))) {
return { response: `E2E history child dispatched ${label}` };
}
diff --git a/e2e/fixtures/subagent-history.test.cjs b/e2e/fixtures/subagent-history.test.cjs
index b4ca9e77f2..d286c9afa3 100644
--- a/e2e/fixtures/subagent-history.test.cjs
+++ b/e2e/fixtures/subagent-history.test.cjs
@@ -224,3 +224,15 @@ test('does not demand old full model context after a tool batch was already veri
assert.equal(third.toolCalls[0].id, history.callId(label, 2 * history.BATCH_SIZE));
assert.equal(await gates.has('ready'), false);
});
+
+test('keeps a steered child on its original fixture branch instead of dispatching another child', async (t) => {
+ const { label, script } = scenario(t, 'self');
+ const messages = [
+ human(`E2E_SUBAGENT_HISTORY_CHILD:${label}`),
+ human('Additional parent guidance.'),
+ ];
+ const invocation = await script.resolveInvocation(messages);
+ assert.equal(invocation.toolCalls.length, history.BATCH_SIZE);
+ assert.equal(invocation.toolCalls[0].name, history.TOOL_NAME);
+ assert.equal(invocation.toolCalls[0].id, history.callId(label, 0));
+});
diff --git a/e2e/specs/mock/subagent-activity.spec.ts b/e2e/specs/mock/subagent-activity.spec.ts
index db3f2fdd1d..1a778f3008 100644
--- a/e2e/specs/mock/subagent-activity.spec.ts
+++ b/e2e/specs/mock/subagent-activity.spec.ts
@@ -269,6 +269,7 @@ test.describe('subagent chat retained-history parity', () => {
let coldContext: BrowserContext | undefined;
let activePage = page;
let activityRequests = 0;
+ let primaryError: unknown;
page.on('request', (request) => {
if (ACTIVITY_PATH.test(new URL(request.url()).pathname)) activityRequests++;
});
@@ -356,6 +357,26 @@ test.describe('subagent chat retained-history parity', () => {
0,
);
+ const guidance = `Additional parent design checks:\n${'Keep parent guidance in transcript order and preserve complete text.\n'.repeat(18)}END_OF_PARENT_GUIDANCE_${label}`;
+ if (threadPath) {
+ const [threadEndpoint, query] = threadPath.split('?');
+ const controlledTaskId = new URLSearchParams(query).get('taskId');
+ const controlled = await requestJson<{ receipt: { status: string } }>(activePage, {
+ path: `${threadEndpoint}/control`,
+ token: viewerToken,
+ method: 'POST',
+ body: {
+ taskId: controlledTaskId,
+ invocationId: `history-guidance-${label}`,
+ action: 'steer',
+ message: guidance,
+ },
+ });
+ expect(controlled.receipt.status).toBe('accepted');
+ await expect(
+ surface.getByText('Message shortened for display.', { exact: true }),
+ ).toHaveCount(0);
+ }
await gates.signal('advance');
await gates.wait('live', { timeoutMs: 15_000 });
await assertHistoryCalls(surface, label, history.CALL_COUNT + 1);
@@ -400,6 +421,63 @@ test.describe('subagent chat retained-history parity', () => {
);
await assertHistoryCalls(surface, label, history.CALL_COUNT + 1);
await assertFullToolDetails(surface, label, 0);
+ if (threadPath) {
+ const steer = surface
+ .locator('[data-steer-render]')
+ .filter({ hasText: `END_OF_PARENT_GUIDANCE_${label}` });
+ await expect(steer).toHaveCount(1);
+ const expand = steer.getByRole('button', { name: 'Show more', exact: true });
+ if (await expand.isVisible()) await expand.click();
+ await expect(steer).toContainText(`END_OF_PARENT_GUIDANCE_${label}`);
+ await expect(
+ surface.getByText('Message shortened for display.', { exact: true }),
+ ).toHaveCount(0);
+ const precedingText = history.liveText(label);
+ expect(
+ await steer.evaluate((node, text) => {
+ const root = node.closest('[data-subagent-conversation]')!;
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT);
+ let current: Node | null;
+ while ((current = walker.nextNode())) {
+ if (
+ current.textContent === text &&
+ current instanceof HTMLElement &&
+ current.children.length === 0
+ ) {
+ return Boolean(
+ current.compareDocumentPosition(node) & Node.DOCUMENT_POSITION_FOLLOWING,
+ );
+ }
+ }
+ return false;
+ }, precedingText),
+ ).toBe(true);
+ const completion = surface.getByText(history.completionText(label), { exact: true });
+ expect(
+ await steer.evaluate(
+ (node, completedText) => {
+ const walker = document.createTreeWalker(
+ node.closest('[data-subagent-conversation]')!,
+ NodeFilter.SHOW_ELEMENT,
+ );
+ let current: Node | null;
+ while ((current = walker.nextNode())) {
+ if (
+ current.textContent === completedText &&
+ current instanceof HTMLElement &&
+ current.children.length === 0
+ ) {
+ return Boolean(
+ node.compareDocumentPosition(current) & Node.DOCUMENT_POSITION_FOLLOWING,
+ );
+ }
+ }
+ return false;
+ },
+ await completion.textContent(),
+ ),
+ ).toBe(true);
+ }
if (mode !== 'normal chat') {
await surface.getByRole('button', { name: 'Close', exact: true }).click();
@@ -411,6 +489,16 @@ test.describe('subagent chat retained-history parity', () => {
: await openHistoryChild(activePage, label);
await assertHistoryCalls(restored, label, history.CALL_COUNT + 1);
await assertFullToolDetails(restored, label, 0);
+ if (threadPath) {
+ await expect(
+ restored
+ .locator('[data-steer-render]')
+ .filter({ hasText: `END_OF_PARENT_GUIDANCE_${label}` }),
+ ).toHaveCount(1);
+ await expect(
+ restored.getByText('Message shortened for display.', { exact: true }),
+ ).toHaveCount(0);
+ }
await expect(
restored.getByText(history.completionText(label), { exact: true }),
).toHaveCount(1);
@@ -418,13 +506,16 @@ test.describe('subagent chat retained-history parity', () => {
contentType: 'application/json',
body: JSON.stringify({ mode, hydrateMs, detailsMs, historicalCalls: history.CALL_COUNT }),
});
+ } catch (error) {
+ primaryError = error;
+ throw error;
} finally {
try {
await gates.release();
- if (await gates.has('ready')) {
+ if (primaryError == null && (await gates.has('ready'))) {
await gates.wait('done', { timeoutMs: 10_000 });
- await rm(gates.directory, { recursive: true, force: true });
}
+ if (await gates.has('done')) await rm(gates.directory, { recursive: true, force: true });
} finally {
try {
for (const agentId of createdAgentIds.reverse()) {
diff --git a/packages/api/src/agents/activity.spec.ts b/packages/api/src/agents/activity.spec.ts
index 6b2938bb06..7579a32d87 100644
--- a/packages/api/src/agents/activity.spec.ts
+++ b/packages/api/src/agents/activity.spec.ts
@@ -1,4 +1,7 @@
+import { createContentAggregator, GraphEvents } from '@librechat/agents';
+import type { SubagentUpdateEvent } from '@librechat/agents';
import {
+ SubagentPublicRecorder,
projectPersistedMessageActivity,
projectPersistedMessageActivityJson,
projectSubagentActivity,
@@ -397,3 +400,493 @@ describe('durable subagent activity projection', () => {
]);
});
});
+
+describe('applied child guidance projection', () => {
+ const stored = (type: string, content: string, additional_kwargs = {}) => ({
+ type,
+ data: { content, additional_kwargs },
+ });
+
+ it('keeps trusted SDK-injected steer humans between assistant content after reload', () => {
+ const messages = [
+ stored('human', 'Old task'),
+ stored('ai', 'Old answer'),
+ stored('human', 'Current task'),
+ stored('ai', 'Before'),
+ stored('human', 'Apply guidance', { injected: true, source: 'steer', role: 'user' }),
+ stored('ai', 'After'),
+ ];
+ const projection = projectSubagentActivity(JSON.stringify(messages), 'replace', 'Current task');
+ expect(projection).toEqual({
+ activity: [
+ { type: 'writing', text: 'Before' },
+ { type: 'steer', steer: 'Apply guidance' },
+ { type: 'writing', text: 'After' },
+ ],
+ truncated: false,
+ });
+ expect(projectPersistedMessageActivityJson(JSON.stringify(projection.activity))).toEqual(
+ projection,
+ );
+ });
+
+ it('does not expose raw prompts or untrusted injected humans as applied guidance', () => {
+ const messages = [
+ stored('human', 'Prompt'),
+ stored('human', 'Unmarked', { source: 'steer' }),
+ stored('human', 'Synthetic', { injected: true, source: 'tool' }),
+ stored('human', 'Generic', { injected: true }),
+ stored('ai', 'Answer'),
+ ];
+ expect(projectSubagentActivity(JSON.stringify(messages)).activity).toEqual([
+ { type: 'writing', text: 'Answer' },
+ ]);
+ });
+
+ it('bounds escaped and multibyte guidance without weakening the projection budget', () => {
+ const result = projectSubagentActivity(
+ JSON.stringify([
+ stored('human', '\u0001😀'.repeat(40000), { injected: true, source: 'steer' }),
+ ]),
+ );
+ expect(result.activity[0]).toMatchObject({ type: 'steer', textTruncated: true });
+ expect(Buffer.byteLength(JSON.stringify(result.activity))).toBeLessThanOrEqual(
+ SUBAGENT_ACTIVITY_LIMITS.bytes,
+ );
+ });
+});
+
+it('stamps trusted injected guidance only when authoritative apply order is complete', () => {
+ const messages = JSON.stringify([
+ { type: 'ai', data: { content: 'Before' } },
+ {
+ type: 'human',
+ data: { content: 'Same text', additional_kwargs: { injected: true, source: 'steer' } },
+ },
+ {
+ type: 'human',
+ data: { content: 'Same text', additional_kwargs: { injected: true, source: 'steer' } },
+ },
+ { type: 'ai', data: { content: 'After' } },
+ ]);
+ const controls = [
+ { steerId: 'control-1', clientSteerId: 'invocation-1', createdAt: 10 },
+ { steerId: 'control-2', clientSteerId: 'invocation-2', createdAt: 10 },
+ ];
+ expect(projectSubagentActivity(messages, 'append', undefined, controls).activity).toEqual([
+ { type: 'writing', text: 'Before' },
+ { type: 'steer', steer: 'Same text', ...controls[0] },
+ { type: 'steer', steer: 'Same text', ...controls[1] },
+ { type: 'writing', text: 'After' },
+ ]);
+ expect(
+ projectSubagentActivity(messages, 'append', undefined, controls.slice(1)).activity[1],
+ ).toEqual({ type: 'steer', steer: 'Same text' });
+});
+
+describe('bounded public observations', () => {
+ const progress = (phase: SubagentUpdateEvent['phase'], data: unknown): SubagentUpdateEvent => ({
+ phase,
+ data,
+ runId: 'root',
+ parentRunId: 'parent',
+ subagentRunId: 'child',
+ subagentType: 'worker',
+ subagentAgentId: 'agent',
+ timestamp: '2026-10-23T00:00:00.000Z',
+ });
+
+ it.each([
+ { type: 'think', think: 'Public reasoning.' },
+ { type: 'reasoning', reasoning: 'Public reasoning.' },
+ { type: 'thinking', thinking: 'Public reasoning.' },
+ { type: 'text', text: 'Public reasoning.' },
+ ])('retains visible reasoning from the $type wire shape', (block) => {
+ const recorder = new SubagentPublicRecorder();
+ recorder.record(
+ progress('run_step', {
+ id: 'reasoning',
+ stepDetails: { type: 'message_creation', message_creation: { message_id: 'reasoning' } },
+ }),
+ );
+ recorder.record(progress('reasoning_delta', { id: 'reasoning', delta: { content: [block] } }));
+ expect(recorder.snapshot()).toEqual({
+ activity: [{ type: 'reasoning', text: 'Public reasoning.' }],
+ truncated: false,
+ });
+ });
+
+ it.each([
+ { label: 'empty object placeholder', args: {}, fragments: ['{"query":', '"x"}'] },
+ {
+ label: 'nonempty object announcement',
+ args: { initial: true },
+ fragments: ['{"query":', '"x"}'],
+ },
+ { label: 'empty initial string', args: '', fragments: ['{"query":', '"x"}'] },
+ { label: 'initial string prefix', args: '{"query":', fragments: ['"x"}'] },
+ { label: 'literal object-shaped string', args: '{}', fragments: ['{"query":"x"}'] },
+ { label: 'empty first fragment', args: {}, fragments: ['', '{"query":"x"}'] },
+ { label: 'object without fragments', args: { query: 'x' }, fragments: [] },
+ { label: 'object delta replacing text', args: '{"query":', fragments: [{ query: 'x' }] },
+ { label: 'name-only first delta', args: {}, fragments: [undefined, '{"query":"x"}'] },
+ ])('matches the locked SDK arguments through $label', ({ args, fragments }) => {
+ const recorder = new SubagentPublicRecorder();
+ const sdk = createContentAggregator();
+ const data = {
+ id: 'tool-step',
+ index: 0,
+ stepDetails: {
+ type: 'tool_calls',
+ tool_calls: [{ id: 'call', name: 'lookup', args, type: 'tool_call' }],
+ },
+ };
+ recorder.record(progress('run_step', data));
+ sdk.aggregateContent({
+ event: GraphEvents.ON_RUN_STEP,
+ data: data as Parameters<typeof sdk.aggregateContent>[0]['data'],
+ });
+ const compare = () => {
+ const part = sdk.contentParts[0];
+ const expected = part != null && 'tool_call' in part ? part.tool_call?.args : undefined;
+ const input = typeof expected === 'string' ? expected : JSON.stringify(expected);
+ const snapshot = recorder.snapshot();
+ expect(snapshot).toMatchObject({
+ activity: [{ type: 'tool', ...(input ? { input } : {}) }],
+ truncated: false,
+ });
+ const tool = snapshot.activity[0];
+ expect(tool.type === 'tool' ? (tool.input ?? '') : undefined).toBe(input ?? '');
+ const stored = projectPersistedMessageActivity(snapshot.activity);
+ const restoredTool = stored.activity[0];
+ expect(restoredTool.type === 'tool' ? (restoredTool.input ?? '') : undefined).toBe(
+ input ?? '',
+ );
+ expect(stored.truncated).toBe(false);
+ };
+ compare();
+ for (const args of fragments) {
+ const data = {
+ id: 'tool-step',
+ delta: { type: 'tool_calls', tool_calls: [{ id: 'call', index: 0, name: 'lookup', args }] },
+ };
+ recorder.record(progress('run_step_delta', data));
+ sdk.aggregateContent({
+ event: GraphEvents.ON_RUN_STEP_DELTA,
+ data: data as Parameters<typeof sdk.aggregateContent>[0]['data'],
+ });
+ compare();
+ }
+ const dataCompleted = {
+ result: {
+ id: 'tool-step',
+ index: 0,
+ tool_call: { id: 'call', name: 'lookup', args: { query: 'final' }, output: 'Done' },
+ },
+ };
+ recorder.record(progress('run_step_completed', dataCompleted));
+ sdk.aggregateContent({
+ event: GraphEvents.ON_RUN_STEP_COMPLETED,
+ data: dataCompleted as Parameters<typeof sdk.aggregateContent>[0]['data'],
+ });
+ compare();
+ expect(recorder.snapshot().activity[0]).toMatchObject({
+ input: '{"query":"final"}',
+ output: 'Done',
+ status: 'completed',
+ });
+ const settled = recorder.snapshot();
+ recorder.record(
+ progress('run_step_delta', {
+ id: 'tool-step',
+ delta: {
+ type: 'tool_calls',
+ tool_calls: [{ id: 'call', index: 0, name: 'lookup', args: 'late fragment' }],
+ },
+ }),
+ );
+ expect(recorder.snapshot()).toEqual(settled);
+ });
+
+ it.each([
+ { initial: [] },
+ { initial: [{ id: 'first', name: 'first_tool', args: {}, type: 'tool_call' }] },
+ ])('retains a parallel call first introduced by a delta after $initial', ({ initial }) => {
+ const recorder = new SubagentPublicRecorder();
+ const sdk = createContentAggregator();
+ const announce = {
+ id: 'step',
+ index: 0,
+ stepDetails: { type: 'tool_calls', tool_calls: initial },
+ };
+ recorder.record(progress('run_step', announce));
+ sdk.aggregateContent({
+ event: GraphEvents.ON_RUN_STEP,
+ data: announce as Parameters<typeof sdk.aggregateContent>[0]['data'],
+ });
+ const index = initial.length;
+ const delta = (call: object) => {
+ const data = { id: 'step', delta: { type: 'tool_calls', tool_calls: [call] } };
+ recorder.record(progress('run_step_delta', data));
+ sdk.aggregateContent({
+ event: GraphEvents.ON_RUN_STEP_DELTA,
+ data: data as Parameters<typeof sdk.aggregateContent>[0]['data'],
+ });
+ };
+ delta({ id: 'late', index, name: 'late_tool', args: '{"query":' });
+ delta({ index, name: 'late_tool', args: '"x"}' });
+ const snapshot = recorder.snapshot();
+ const expected = sdk.contentParts
+ .filter((part) => part != null && part.type === 'tool_call' && 'tool_call' in part)
+ .map((part) => {
+ if (part == null || !('tool_call' in part)) throw new Error('Expected tool content');
+ const call = part.tool_call!;
+ return {
+ type: 'tool',
+ toolCallId: call.id,
+ name: call.name,
+ input: typeof call.args === 'string' ? call.args : JSON.stringify(call.args),
+ status: 'running',
+ };
+ });
+ expect(snapshot).toEqual({ activity: expected, truncated: false });
+ expect(projectPersistedMessageActivity(snapshot.activity).activity).toEqual(snapshot.activity);
+ });
+
+ it('binds a delta-first provider ID to its unbound slot without duplicating its prefix', () => {
+ const recorder = new SubagentPublicRecorder();
+ recorder.record(
+ progress('run_step', {
+ id: 'step',
+ index: 0,
+ stepDetails: { type: 'tool_calls', tool_calls: [] },
+ }),
+ );
+ recorder.record(
+ progress('run_step_delta', {
+ id: 'step',
+ delta: { tool_calls: [{ index: 0, name: 'lookup', args: '{"query":' }] },
+ }),
+ );
+ recorder.record(
+ progress('run_step_delta', {
+ id: 'step',
+ delta: { tool_calls: [{ id: 'provider', index: 0, name: 'lookup', args: '"x"}' }] },
+ }),
+ );
+ recorder.record(
+ progress('run_step_completed', {
+ result: { id: 'step', tool_call: { id: 'provider', name: 'lookup', output: 'Done' } },
+ }),
+ );
+ expect(recorder.snapshot()).toEqual({
+ activity: [
+ {
+ type: 'tool',
+ toolCallId: 'provider',
+ name: 'lookup',
+ input: '{"query":"x"}',
+ output: 'Done',
+ status: 'completed',
+ },
+ ],
+ truncated: false,
+ });
+ });
+
+ it('does not reassign an earlier chunk slot when an additional delta call has only an ID', () => {
+ const recorder = new SubagentPublicRecorder();
+ recorder.record(
+ progress('run_step', {
+ id: 'step',
+ index: 0,
+ stepDetails: {
+ type: 'tool_calls',
+ tool_calls: [{ id: 'first', name: 'first_tool', args: {} }],
+ },
+ }),
+ );
+ recorder.record(
+ progress('run_step_delta', {
+ id: 'step',
+ delta: { tool_calls: [{ id: 'late', name: 'late_tool', args: 'late-input' }] },
+ }),
+ );
+ recorder.record(
+ progress('run_step_delta', {
+ id: 'step',
+ delta: { tool_calls: [{ index: 0, name: 'first_tool', args: 'first-input' }] },
+ }),
+ );
+ expect(recorder.snapshot()).toEqual({
+ activity: [
+ {
+ type: 'tool',
+ toolCallId: 'first',
+ name: 'first_tool',
+ input: 'first-input',
+ status: 'running',
+ },
+ {
+ type: 'tool',
+ toolCallId: 'late',
+ name: 'late_tool',
+ input: 'late-input',
+ status: 'running',
+ },
+ ],
+ truncated: false,
+ });
+ });
+
+ it('routes an idless fragment to the sole delta-first call in its own step', () => {
+ const recorder = new SubagentPublicRecorder();
+ recorder.record(
+ progress('run_step', {
+ id: 'step',
+ index: 0,
+ stepDetails: { type: 'tool_calls', tool_calls: [] },
+ }),
+ );
+ recorder.record(
+ progress('run_step_delta', {
+ id: 'step',
+ delta: { tool_calls: [{ id: 'only', name: 'lookup', args: '{"query":' }] },
+ }),
+ );
+ recorder.record(
+ progress('run_step_delta', {
+ id: 'step',
+ delta: { tool_calls: [{ name: 'lookup', args: '"x"}' }] },
+ }),
+ );
+ expect(recorder.snapshot()).toEqual({
+ activity: [
+ {
+ type: 'tool',
+ toolCallId: 'only',
+ name: 'lookup',
+ input: '{"query":"x"}',
+ status: 'running',
+ },
+ ],
+ truncated: false,
+ });
+ });
+
+ it('retains late parallel calls within the existing public item and byte bounds', () => {
+ const recorder = new SubagentPublicRecorder();
+ recorder.record(
+ progress('run_step', {
+ id: 'step',
+ index: 0,
+ stepDetails: { type: 'tool_calls', tool_calls: [] },
+ }),
+ );
+ for (let index = 0; index < 150; index++)
+ recorder.record(
+ progress('run_step_delta', {
+ id: 'step',
+ delta: {
+ type: 'tool_calls',
+ tool_calls: [{ id: `late-${index}`, index, name: 'lookup', args: 'x'.repeat(400) }],
+ },
+ }),
+ );
+ const snapshot = recorder.snapshot();
+ expect(snapshot.activity.length).toBeLessThanOrEqual(SUBAGENT_ACTIVITY_LIMITS.items);
+ expect(Buffer.byteLength(JSON.stringify(snapshot.activity))).toBeLessThanOrEqual(
+ SUBAGENT_ACTIVITY_LIMITS.bytes,
+ );
+ expect(snapshot.truncated).toBe(true);
+ expect(snapshot.activity[snapshot.activity.length - 1]).toMatchObject({
+ toolCallId: 'late-149',
+ input: 'x'.repeat(400),
+ });
+ });
+
+ it('isolates repeated provider call IDs by step and ignores duplicate announcements', () => {
+ const recorder = new SubagentPublicRecorder();
+ const step = (id: string) =>
+ progress('run_step', {
+ id,
+ stepDetails: {
+ type: 'tool_calls',
+ tool_calls: [{ id: 'same', name: 'lookup', args: '', type: 'tool_call' }],
+ },
+ });
+ recorder.record(step('first'));
+ recorder.record(step('second'));
+ recorder.record(step('first'));
+ recorder.record(
+ progress('run_step_delta', {
+ id: 'second',
+ delta: { tool_calls: [{ index: 0, args: 'second input' }] },
+ }),
+ );
+ recorder.record(
+ progress('run_step', {
+ id: 'text',
+ stepDetails: {
+ type: 'message_creation',
+ message_creation: { message_id: 'text', phase: 'commentary' },
+ },
+ }),
+ );
+ recorder.record(progress('run_step_closed', { id: 'text', status: 'completed' }));
+ expect(recorder.snapshot().truncated).toBe(false);
+ expect(recorder.snapshot().activity).toEqual([
+ { type: 'tool', toolCallId: 'same', name: 'lookup', status: 'running' },
+ {
+ type: 'tool',
+ toolCallId: 'same#2',
+ name: 'lookup',
+ input: 'second input',
+ status: 'running',
+ },
+ ]);
+ recorder.record(
+ progress('run_step_completed', {
+ result: { id: 'first', tool_call: { id: 'same', output: 'first output' } },
+ }),
+ );
+ recorder.record(progress('run_step_closed', { id: 'second', status: 'cancelled' }));
+ recorder.record(
+ progress('message_delta', {
+ id: 'text',
+ delta: { content: [{ type: 'text', text: 'Commentary' }] },
+ }),
+ );
+ const snapshot = recorder.snapshot();
+ expect(snapshot.truncated).toBe(false);
+ expect(snapshot.activity).toEqual([
+ {
+ type: 'tool',
+ toolCallId: 'same',
+ name: 'lookup',
+ output: 'first output',
+ status: 'completed',
+ },
+ {
+ type: 'tool',
+ toolCallId: 'same#2',
+ name: 'lookup',
+ input: 'second input',
+ status: 'cancelled',
+ },
+ { type: 'writing', text: 'Commentary', phase: 'commentary' },
+ ]);
+ expect(projectPersistedMessageActivity(snapshot.activity).activity).toEqual(snapshot.activity);
+ });
+
+ it('contains observation errors and marks the retained history incomplete', () => {
+ const recorder = new SubagentPublicRecorder();
+ const data = {
+ get id(): string {
+ throw new Error('observer failure');
+ },
+ };
+ expect(() => recorder.record(progress('run_step', data))).not.toThrow();
+ expect(recorder.snapshot()).toEqual({ activity: [], truncated: true });
+ });
+});
diff --git a/packages/api/src/agents/activity.ts b/packages/api/src/agents/activity.ts
index 0f2df76684..d9d384fb9f 100644
--- a/packages/api/src/agents/activity.ts
+++ b/packages/api/src/agents/activity.ts
@@ -1,4 +1,5 @@
-import type { SubagentActivityItem } from 'librechat-data-provider';
+import type { SubagentActivityItem, TSteerAppliedEvent } from 'librechat-data-provider';
+import type { SubagentUpdateEvent } from '@librechat/agents';
const MAX_ACTIVITY_ITEMS = 100;
const MAX_ACTIVITY_BYTES = 64 * 1024;
@@ -13,6 +14,12 @@ type Projection = {
truncated: boolean;
};
+export type AppliedSubagentSteer = {
+ steerId: string;
+ clientSteerId: string;
+ createdAt: number;
+};
+
type MutableToolActivity = Extract<SubagentActivityItem, { type: 'tool' }>;
type ProjectedActivityEntry = { item: SubagentActivityItem; active: boolean };
type MutableToolProjection = {
@@ -96,6 +103,9 @@ const fitNewestItemToSerializedBudget = (item: SubagentActivityItem): SubagentAc
if (item.type === 'writing' || item.type === 'reasoning') {
return shrinkStringField(item, 'text', 'textTruncated');
}
+ if (item.type === 'steer') {
+ return shrinkStringField(item, 'steer', 'textTruncated');
+ }
if (item.type === 'activity_label') {
const withoutAssociations = { ...item, toolCallIds: undefined, agentIds: undefined };
return shrinkStringField(withoutAssociations, 'label', 'labelTruncated');
@@ -166,6 +176,29 @@ export function projectPersistedMessageActivity(
truncated = true;
return [];
}
+ if (candidate.type === 'steer') {
+ if (typeof candidate.steer !== 'string') {
+ truncated = true;
+ return [];
+ }
+ const text = truncateUtf8(candidate.steer, MAX_ACTIVITY_TEXT_BYTES);
+ return [
+ {
+ type: 'steer',
+ steer: text.value,
+ ...(typeof candidate.steerId === 'string'
+ ? { steerId: truncateUtf8(candidate.steerId, MAX_TOOL_CALL_ID_BYTES).value }
+ : {}),
+ ...(typeof candidate.clientSteerId === 'string'
+ ? { clientSteerId: truncateUtf8(candidate.clientSteerId, MAX_TOOL_CALL_ID_BYTES).value }
+ : {}),
+ ...(nonNegativeTiming(candidate.createdAt) == null
+ ? {}
+ : { createdAt: nonNegativeTiming(candidate.createdAt) }),
+ ...(text.truncated || candidate.textTruncated === true ? { textTruncated: true } : {}),
+ },
+ ];
+ }
if (candidate.type === 'writing') {
if (typeof candidate.text !== 'string') {
truncated = true;
@@ -175,6 +208,9 @@ export function projectPersistedMessageActivity(
{
type: 'writing',
text: candidate.text,
+ ...(candidate.phase === 'commentary' || candidate.phase === 'final_answer'
+ ? { phase: candidate.phase }
+ : {}),
...(candidate.textTruncated === true ? { textTruncated: true } : {}),
},
];
@@ -231,13 +267,14 @@ export function projectPersistedMessageActivity(
const completed =
finiteNumber(candidate.progress) != null && finiteNumber(candidate.progress)! >= 1;
const output = typeof candidate.output === 'string' ? candidate.output : undefined;
- const runStepStatus = visibleStatus(candidate.runStepStatus);
+ const storedStatus = candidate.runStepStatus ?? candidate.status;
+ const runStepStatus = visibleStatus(storedStatus);
const toolPreparationStartedAt = nonNegativeTiming(candidate.toolPreparationStartedAt);
const toolDispatchedAt = nonNegativeTiming(candidate.toolDispatchedAt);
const toolPreparationDurationMs = nonNegativeTiming(candidate.toolPreparationDurationMs);
const toolExecutionDurationMs = nonNegativeTiming(candidate.toolExecutionDurationMs);
let status: MutableToolActivity['status'] = runStepStatus;
- if (candidate.runStepStatus == null) {
+ if (storedStatus == null) {
status = completed || output != null ? 'completed' : 'running';
}
return [
@@ -276,6 +313,7 @@ export function projectPersistedMessageActivityJson(
}
const reasoningBlockText = (block: Record<string, unknown>): string => {
+ if (typeof block.think === 'string') return block.think;
if (typeof block.reasoning === 'string') return block.reasoning;
if (typeof block.thinking === 'string') return block.thinking;
if (typeof block.text === 'string') return block.text;
@@ -294,7 +332,7 @@ const visibleContent = (
if (!isRecord(block) || typeof block.type !== 'string') continue;
if ((block.type === 'text' || block.type === 'text-plain') && typeof block.text === 'string') {
text.push(block.text);
- } else if (block.type === 'reasoning' || block.type === 'thinking') {
+ } else if (block.type === 'think' || block.type === 'reasoning' || block.type === 'thinking') {
/** The same user reads this exact reasoning in the main chat view, so the
* bounded projection keeps its text rather than only a lifecycle marker. */
hasReasoning = true;
@@ -314,7 +352,7 @@ const readToolCalls = (data: Record<string, unknown>): unknown[] => {
const normalizeToolCall = (
value: unknown,
index: number,
-): { rawId: string; item: MutableToolActivity } | undefined => {
+): { rawId: string; item: MutableToolActivity; inputIsObject: boolean } | undefined => {
if (!isRecord(value)) return undefined;
const fn = isRecord(value.function) ? value.function : undefined;
const rawName = typeof value.name === 'string' ? value.name : fn?.name;
@@ -324,6 +362,7 @@ const normalizeToolCall = (
const input = truncateUtf8(safeJson(rawInput), MAX_TOOL_INPUT_BYTES);
return {
rawId,
+ inputIsObject: typeof rawInput === 'object',
item: {
type: 'tool',
toolCallId: truncateUtf8(rawId, MAX_TOOL_CALL_ID_BYTES).value,
@@ -352,6 +391,11 @@ const uniqueToolActivityId = (
return candidate;
};
+const isInjectedSteer = (data: Record<string, unknown>): boolean =>
+ isRecord(data.additional_kwargs) &&
+ data.additional_kwargs.injected === true &&
+ data.additional_kwargs.source === 'steer';
+
/**
* Converts one server-private LangChain transcript into a bounded public
* activity projection. Visible text, bounded reasoning text, and declared
@@ -362,6 +406,7 @@ export function projectSubagentActivity(
messagesJson: string | undefined,
mode: 'append' | 'replace' = 'append',
expectedTaskInput?: string,
+ appliedSteers?: readonly AppliedSubagentSteer[],
): Projection {
if (messagesJson == null) return { activity: [], truncated: false };
let parsed: unknown;
@@ -377,7 +422,12 @@ export function projectSubagentActivity(
let latestInputIndex = -1;
for (let index = parsed.length - 1; index >= 0; index -= 1) {
const stored = parsed[index];
- if (isRecord(stored) && (stored.type === 'human' || stored.type === 'user')) {
+ if (
+ isRecord(stored) &&
+ isRecord(stored.data) &&
+ (stored.type === 'human' || stored.type === 'user') &&
+ !isInjectedSteer(stored.data)
+ ) {
latestInputIndex = index;
break;
}
@@ -397,6 +447,7 @@ export function projectSubagentActivity(
}
const activity: ProjectedActivityEntry[] = [];
+ const steerItems: Array<Extract<SubagentActivityItem, { type: 'steer' }>> = [];
const toolsByRawId = new Map<string, MutableToolQueue>();
const usedToolActivityIds = new Set<string>();
// A global cursor makes collision probing amortized linear even when many
@@ -415,6 +466,29 @@ export function projectSubagentActivity(
continue;
}
const { data } = stored;
+ if ((stored.type === 'human' || stored.type === 'user') && isInjectedSteer(data)) {
+ const metadata = isRecord(data.additional_kwargs) ? data.additional_kwargs : {};
+ const text = truncateUtf8(visibleContent(data.content).text, MAX_ACTIVITY_TEXT_BYTES);
+ if (text.value !== '') {
+ const item: Extract<SubagentActivityItem, { type: 'steer' }> = {
+ type: 'steer',
+ steer: text.value,
+ ...(typeof metadata.steerId === 'string'
+ ? { steerId: truncateUtf8(metadata.steerId, MAX_TOOL_CALL_ID_BYTES).value }
+ : {}),
+ ...(typeof metadata.clientSteerId === 'string'
+ ? { clientSteerId: truncateUtf8(metadata.clientSteerId, MAX_TOOL_CALL_ID_BYTES).value }
+ : {}),
+ ...(nonNegativeTiming(metadata.createdAt) == null
+ ? {}
+ : { createdAt: nonNegativeTiming(metadata.createdAt) }),
+ ...(text.truncated ? { textTruncated: true } : {}),
+ };
+ steerItems.push(item);
+ append(item);
+ }
+ continue;
+ }
if (stored.type === 'ai' || stored.type === 'assistant') {
const content = visibleContent(data.content);
if (content.hasReasoning) {
@@ -479,10 +553,355 @@ export function projectSubagentActivity(
append(orphan);
}
+ // SDK conversion strips control IDs. Only a complete apply-order correspondence is safe.
+ if (appliedSteers != null && steerItems.length === appliedSteers.length) {
+ steerItems.forEach((item, index) => Object.assign(item, appliedSteers[index]));
+ }
const boundedActivity = activity.filter((entry) => entry.active).map((entry) => entry.item);
return boundActivity(boundedActivity, truncated);
}
+type ObservationField = { chunks: string[]; bytes: number; limit: number };
+type Observation = {
+ key: string;
+ item: SubagentActivityItem;
+ fields: Map<string, ObservationField>;
+ bytes: number;
+ stepId?: string;
+ slot?: string;
+ phase?: 'commentary' | 'final_answer';
+ inputIsObject?: boolean;
+ completed?: boolean;
+ providerId?: string;
+};
+
+/** Public observations only. Payloads and correlation state share the projection's bounds. */
+export class SubagentPublicRecorder {
+ private readonly entries: Observation[] = [];
+ private readonly tools = new Map<string, Observation>();
+ private readonly steps = new Map<string, 'commentary' | 'final_answer' | undefined>();
+ private readonly toolSlots = new Map<string, Observation>();
+ private readonly toolIds = new Set<string>();
+ private readonly nextToolOccurrence = { value: 2 };
+ private bytes = 0;
+ private truncated = false;
+
+ private append(key: string, item: SubagentActivityItem): Observation {
+ const entry = {
+ key,
+ item,
+ fields: new Map<string, ObservationField>(),
+ bytes: serializedBytes(item) + 128,
+ };
+ this.entries.push(entry);
+ this.bytes += entry.bytes;
+ this.bound();
+ return entry;
+ }
+
+ private bound(): void {
+ while (this.entries.length > MAX_ACTIVITY_ITEMS || this.bytes > MAX_ACTIVITY_BYTES) {
+ const removed = this.entries.shift();
+ if (removed == null) break;
+ this.bytes -= removed.bytes;
+ if (this.tools.get(removed.key) === removed) this.tools.delete(removed.key);
+ if (removed.item.type === 'tool') this.toolIds.delete(removed.item.toolCallId);
+ if (removed.slot != null && this.toolSlots.get(removed.slot) === removed)
+ this.toolSlots.delete(removed.slot);
+ this.truncated = true;
+ }
+ }
+
+ private declareTool(
+ stepId: string,
+ call: Record<string, unknown>,
+ index?: number,
+ ): Observation | undefined {
+ const normalized = normalizeToolCall(call, index ?? 0);
+ if (normalized == null || normalized.rawId.length > MAX_TOOL_CALL_ID_BYTES) {
+ this.truncated = true;
+ return undefined;
+ }
+ const key = `${stepId.length}:${stepId}:${normalized.rawId}`;
+ const existing = this.tools.get(key);
+ if (existing != null) return existing;
+ const { input, ...item } = normalized.item;
+ item.toolCallId = uniqueToolActivityId(item.toolCallId, this.toolIds, this.nextToolOccurrence);
+ const entry = this.append(key, item);
+ this.tools.set(key, entry);
+ entry.stepId = stepId;
+ entry.inputIsObject = normalized.inputIsObject;
+ entry.providerId = typeof call.id === 'string' && call.id !== '' ? call.id : undefined;
+ if (index != null) {
+ entry.slot = `${stepId}:${index}`;
+ this.toolSlots.set(entry.slot, entry);
+ }
+ if (input != null) this.field(entry, 'input', input, MAX_TOOL_INPUT_BYTES);
+ if (normalized.item.inputTruncated) this.truncated = true;
+ return entry;
+ }
+
+ private field(
+ entry: Observation,
+ name: string,
+ value: string,
+ limit: number,
+ replace = false,
+ ): void {
+ let field = entry.fields.get(name);
+ if (field == null || replace) {
+ if (field != null) {
+ this.bytes -= field.bytes;
+ entry.bytes -= field.bytes;
+ }
+ field = { chunks: [], bytes: 0, limit };
+ entry.fields.set(name, field);
+ }
+ if (value === '') return;
+ const remaining = Math.max(0, field.limit - field.bytes);
+ const text = truncateUtf8(value, remaining);
+ // Count JSON escaping as well as UTF-8 so retained memory and stored payload stay bounded.
+ const bytes = serializedBytes(text.value) - 2;
+ if (text.truncated || bytes > remaining) {
+ this.truncated = true;
+ Object.assign(entry.item, {
+ [name === 'steer' || name === 'text' ? 'textTruncated' : `${name}Truncated`]: true,
+ });
+ }
+ const bounded =
+ bytes > remaining ? truncateUtf8(text.value, Math.floor(remaining / 6)).value : text.value;
+ if (bounded !== '') {
+ const added = serializedBytes(bounded) - 2;
+ field.chunks.push(bounded);
+ field.bytes += added;
+ entry.bytes += added;
+ this.bytes += added;
+ }
+ this.bound();
+ }
+
+ steer(data: TSteerAppliedEvent): void {
+ try {
+ this.recordSteer(data);
+ } catch {
+ this.truncated = true;
+ }
+ }
+
+ private recordSteer(data: TSteerAppliedEvent): void {
+ const item = projectPersistedMessageActivity([data.part]).activity[0];
+ if (item == null || item.type !== 'steer') {
+ this.truncated = true;
+ return;
+ }
+ if (item.textTruncated) this.truncated = true;
+ const entry = this.append('', { ...item, steer: '' });
+ this.field(entry, 'steer', item.steer, MAX_ACTIVITY_TEXT_BYTES);
+ }
+
+ record(event: SubagentUpdateEvent): void {
+ try {
+ this.recordEvent(event);
+ } catch {
+ this.truncated = true;
+ }
+ }
+
+ private recordEvent(event: SubagentUpdateEvent): void {
+ const data = isRecord(event.data) ? event.data : undefined;
+ if (data == null) return;
+ const id = typeof data.id === 'string' ? data.id : '';
+ if (id.length > MAX_TOOL_CALL_ID_BYTES) {
+ this.truncated = true;
+ return;
+ }
+ if (event.phase === 'run_step') {
+ const details = isRecord(data.stepDetails) ? data.stepDetails : undefined;
+ const creation = isRecord(details?.message_creation) ? details.message_creation : undefined;
+ const phase =
+ creation?.phase === 'commentary' || creation?.phase === 'final_answer'
+ ? creation.phase
+ : undefined;
+ this.steps.set(id, phase);
+ if (this.steps.size > MAX_ACTIVITY_ITEMS) {
+ this.steps.delete(this.steps.keys().next().value!);
+ this.truncated = true;
+ }
+ if (details?.type !== 'tool_calls' || !Array.isArray(details.tool_calls)) return;
+ for (const [index, call] of details.tool_calls.entries()) {
+ if (isRecord(call)) this.declareTool(id, call, index);
+ else this.truncated = true;
+ }
+ return;
+ }
+ if (event.phase === 'message_delta' || event.phase === 'reasoning_delta') {
+ if (!this.steps.has(id)) this.truncated = true;
+ const delta = isRecord(data.delta) ? data.delta : undefined;
+ const content = delta?.content;
+ for (const block of Array.isArray(content) ? content : [content]) {
+ if (!isRecord(block)) continue;
+ const reasoning =
+ event.phase === 'reasoning_delta' ||
+ block.type === 'think' ||
+ block.type === 'reasoning' ||
+ block.type === 'thinking';
+ if (!reasoning && block.type !== 'text' && block.type !== 'text-plain') continue;
+ let text = '';
+ if (reasoning) text = reasoningBlockText(block);
+ else if (typeof block.text === 'string') text = block.text;
+ if (text === '') continue;
+ const type = reasoning ? 'reasoning' : 'writing';
+ const key = `${id}:${type}`;
+ const last = this.entries[this.entries.length - 1];
+ const entry = last?.key === key ? last : this.append(key, { type, text: '' });
+ if (type === 'writing') entry.phase = this.steps.get(id);
+ this.field(entry, 'text', text, MAX_ACTIVITY_TEXT_BYTES);
+ }
+ return;
+ }
+ if (event.phase === 'run_step_delta') {
+ const delta = isRecord(data.delta) ? data.delta : undefined;
+ if (!Array.isArray(delta?.tool_calls)) return;
+ for (const call of delta.tool_calls) {
+ if (!isRecord(call)) continue;
+ const providerId = typeof call.id === 'string' && call.id !== '' ? call.id : undefined;
+ const index =
+ typeof call.index === 'number' && Number.isSafeInteger(call.index) && call.index >= 0
+ ? call.index
+ : undefined;
+ if (
+ (providerId != null && providerId.length > MAX_TOOL_CALL_ID_BYTES) ||
+ !this.steps.has(id)
+ ) {
+ this.truncated = true;
+ continue;
+ }
+ const key = providerId == null ? undefined : `${id.length}:${id}:${providerId}`;
+ let entry = key == null ? undefined : this.tools.get(key);
+ const slot = index == null ? undefined : this.toolSlots.get(`${id}:${index}`);
+ if (
+ entry == null &&
+ slot != null &&
+ (providerId == null || slot.providerId == null || slot.providerId === providerId)
+ )
+ entry = slot;
+ if (entry == null && providerId == null && index == null) {
+ for (const candidate of this.tools.values()) {
+ if (candidate.stepId !== id) continue;
+ if (entry != null) {
+ entry = undefined;
+ break;
+ }
+ entry = candidate;
+ }
+ }
+ if (entry == null) {
+ if (providerId == null && index == null) {
+ this.truncated = true;
+ continue;
+ }
+ entry = this.declareTool(id, { ...call, args: '' }, index);
+ if (entry == null) continue;
+ } else if (
+ providerId != null &&
+ key != null &&
+ entry.providerId == null &&
+ entry.item.type === 'tool'
+ ) {
+ const before = serializedBytes(entry.item);
+ this.tools.delete(entry.key);
+ this.toolIds.delete(entry.item.toolCallId);
+ entry.key = key;
+ entry.providerId = providerId;
+ entry.item.toolCallId = uniqueToolActivityId(
+ providerId,
+ this.toolIds,
+ this.nextToolOccurrence,
+ );
+ this.tools.set(key, entry);
+ const added = serializedBytes(entry.item) - before;
+ entry.bytes += added;
+ this.bytes += added;
+ this.bound();
+ }
+ if (index != null && entry.slot !== `${id}:${index}`) {
+ if (entry.slot != null && this.toolSlots.get(entry.slot) === entry)
+ this.toolSlots.delete(entry.slot);
+ entry.slot = `${id}:${index}`;
+ this.toolSlots.set(entry.slot, entry);
+ }
+ if (entry.completed) continue;
+ const args = call.args ?? '';
+ const inputIsObject = typeof args === 'object';
+ this.field(
+ entry,
+ 'input',
+ safeJson(args),
+ MAX_TOOL_INPUT_BYTES,
+ entry.inputIsObject === true || inputIsObject,
+ );
+ entry.inputIsObject = inputIsObject;
+ }
+ return;
+ }
+ if (event.phase === 'run_step_completed') {
+ const result = isRecord(data.result) ? data.result : undefined;
+ const call = isRecord(result?.tool_call) ? result.tool_call : undefined;
+ if (call == null) return;
+ const stepId = typeof result?.id === 'string' ? result.id : '';
+ let entry =
+ typeof call.id === 'string'
+ ? this.tools.get(`${stepId.length}:${stepId}:${call.id}`)
+ : undefined;
+ if (entry == null) {
+ this.truncated = true;
+ const normalized = normalizeToolCall(call, 0);
+ if (
+ normalized == null ||
+ normalized.rawId.length > MAX_TOOL_CALL_ID_BYTES ||
+ stepId.length > MAX_TOOL_CALL_ID_BYTES
+ )
+ return;
+ const key = `${stepId.length}:${stepId}:${normalized.rawId}`;
+ normalized.item.toolCallId = uniqueToolActivityId(
+ normalized.item.toolCallId,
+ this.toolIds,
+ this.nextToolOccurrence,
+ );
+ entry = this.append(key, { ...normalized.item, input: undefined });
+ entry.stepId = stepId;
+ this.tools.set(key, entry);
+ }
+ if (entry.item.type !== 'tool') return;
+ entry.completed = true;
+ entry.item.status = toolResultStatus(call.runStepStatus ?? result?.status);
+ if (call.args != null)
+ this.field(entry, 'input', safeJson(call.args), MAX_TOOL_INPUT_BYTES, true);
+ if (call.output != null)
+ this.field(entry, 'output', safeJson(call.output), MAX_TOOL_OUTPUT_BYTES, true);
+ return;
+ }
+ if (event.phase === 'run_step_closed') {
+ for (const entry of this.entries) {
+ if (entry.item.type !== 'tool' || entry.stepId !== id) continue;
+ if (entry.item.status === 'running') entry.item.status = toolResultStatus(data.status);
+ }
+ }
+ }
+
+ snapshot(): Projection {
+ return boundActivity(
+ this.entries.map((entry) => {
+ const item = { ...entry.item, ...(entry.phase == null ? {} : { phase: entry.phase }) };
+ for (const [name, field] of entry.fields)
+ Object.assign(item, { [name]: field.chunks.join('') });
+ return item;
+ }),
+ this.truncated || this.steps.size === 0,
+ );
+ }
+}
+
export const SUBAGENT_ACTIVITY_LIMITS = {
items: MAX_ACTIVITY_ITEMS,
bytes: MAX_ACTIVITY_BYTES,
diff --git a/packages/api/src/agents/aggregation.ts b/packages/api/src/agents/aggregation.ts
new file mode 100644
index 0000000000..d85a8c1c25
--- /dev/null
+++ b/packages/api/src/agents/aggregation.ts
@@ -0,0 +1,74 @@
+import { GraphEvents } from '@librechat/agents';
+import { ContentTypes } from 'librechat-data-provider';
+import type { Agents, TSteerAppliedEvent } from 'librechat-data-provider';
+import type { createContentAggregator } from '@librechat/agents';
+import type { SubagentActivityUpdateEvent } from './subagentActivity';
+import type { ToolTimingAdapter } from './toolTiming';
+
+type SubagentAggregator = ReturnType<typeof createContentAggregator>;
+type AggregateInput = Parameters<SubagentAggregator['aggregateContent']>[0];
+
+function subagentPhaseToGraphEvent(event: SubagentActivityUpdateEvent): GraphEvents | null {
+ switch (event?.phase) {
+ case 'run_step':
+ // Tool-execute batch requests share this phase but are not run steps.
+ return (event.data as Agents.RunStep | undefined)?.stepDetails
+ ? GraphEvents.ON_RUN_STEP
+ : null;
+ case 'run_step_delta':
+ return GraphEvents.ON_RUN_STEP_DELTA;
+ case 'run_step_completed':
+ return GraphEvents.ON_RUN_STEP_COMPLETED;
+ case 'message_delta':
+ return GraphEvents.ON_MESSAGE_DELTA;
+ case 'reasoning_delta':
+ return GraphEvents.ON_REASONING_DELTA;
+ default:
+ return null;
+ }
+}
+
+/** Consume already-public child updates; host indices already include steering offsets. */
+export function feedSubagentAggregator(
+ aggregator: SubagentAggregator,
+ event: SubagentActivityUpdateEvent,
+ applyChildTiming: ToolTimingAdapter['child'],
+): void {
+ if (event.phase === 'steer_applied') {
+ const data = event.data as TSteerAppliedEvent | undefined;
+ if (
+ data != null &&
+ Number.isSafeInteger(data.index) &&
+ data.index >= 0 &&
+ data.part?.type === ContentTypes.STEER
+ ) {
+ // Seed, do not splice: the SDK observes this slot on its next allocation.
+ aggregator.contentParts[data.index] = data.part;
+ }
+ }
+ const graphEvent = subagentPhaseToGraphEvent(event);
+ if (graphEvent) {
+ aggregator.aggregateContent({ event: graphEvent, data: event.data as AggregateInput['data'] });
+ }
+ applyChildTiming(aggregator, event);
+ if (!graphEvent) return;
+
+ // Restore host routing metadata omitted by the SDK's public tool projection.
+ const data = event.data as Agents.RunStep | undefined;
+ const toolCalls =
+ data?.stepDetails?.type === 'tool_calls' ? (data.stepDetails.tool_calls ?? []) : [];
+ const stepIndex = aggregator.stepMap.get(data?.id ?? '')?.index;
+ if (stepIndex == null || !Number.isInteger(stepIndex)) return;
+ for (let index = 0; index < toolCalls.length; index++) {
+ const source = toolCalls[index];
+ const part = aggregator.contentParts[stepIndex + index];
+ const target = part && 'tool_call' in part ? part.tool_call : undefined;
+ if (
+ target?.id === source?.id &&
+ 'mcpServerName' in source &&
+ typeof source.mcpServerName === 'string'
+ ) {
+ target.mcpServerName = source.mcpServerName;
+ }
+ }
+}
diff --git a/packages/api/src/agents/control.spec.ts b/packages/api/src/agents/control.spec.ts
index c9e4ec626b..1258951360 100644
--- a/packages/api/src/agents/control.spec.ts
+++ b/packages/api/src/agents/control.spec.ts
@@ -1,8 +1,12 @@
import type { IConversation } from '@librechat/data-schemas';
import type { Response } from 'express';
import type { ServerRequest } from '~/types';
+import {
+ createSubagentControlHandler,
+ createSubagentControlReceiptHandler,
+ isValidSubagentControlRequest,
+} from './control';
import { controlFingerprint, SubagentTaskOwnerUnavailableError } from './subagentTaskRouting';
-import { createSubagentControlHandler, isValidSubagentControlRequest } from './control';
const parentConversationId = 'parent-conversation';
const threadId = 'child-thread';
@@ -575,3 +579,66 @@ describe('subagent control handler', () => {
expect(res.status).toHaveBeenCalledWith(400);
});
});
+
+describe('parent-authorized retained control body', () => {
+ const readRequest = () =>
+ ({
+ ...request({}),
+ params: { parentConversationId, threadId, taskId, invocationId: 'invocation-1' },
+ }) as ServerRequest;
+ it('returns the retained body without private replay fields or invoking control', async () => {
+ const deps = dependencies();
+ deps.getSubagentTaskControlReceipt.mockResolvedValue({
+ invocationId: 'invocation-1',
+ fingerprint: 'private',
+ action: 'queue',
+ status: 'accepted',
+ message: '界'.repeat(4096),
+ createdAt: new Date(0),
+ updatedAt: new Date(1),
+ });
+ const res = response();
+ await createSubagentControlReceiptHandler(deps)(readRequest(), res.value);
+ expect(res.status).toHaveBeenCalledWith(200);
+ expect(res.json.mock.calls[0][0].receipt.message).toBe('界'.repeat(4096));
+ expect(res.json.mock.calls[0][0].receipt).not.toHaveProperty('fingerprint');
+ expect(deps.store.controlTask).not.toHaveBeenCalled();
+ });
+ it.each(['parent', 'child', 'tenant'] as const)(
+ 'does not read a body without its authorized %s',
+ async (missing) => {
+ const deps = dependencies();
+ if (missing === 'parent') deps.getConvoOwnership.mockResolvedValue(null);
+ if (missing === 'child') deps.getSubagentThreadForParent.mockResolvedValue(null);
+ if (missing === 'tenant')
+ deps.getSubagentThreadForParent.mockResolvedValue({ ...child, tenantId: 'other' });
+ const res = response();
+ await createSubagentControlReceiptHandler(deps)(readRequest(), res.value);
+ expect(res.status).toHaveBeenCalledWith(404);
+ expect(deps.getSubagentTaskControlReceipt).not.toHaveBeenCalled();
+ },
+ );
+ it('requires an active source receipt from the storage boundary', async () => {
+ const deps = dependencies();
+ const res = response();
+ await createSubagentControlReceiptHandler(deps)(readRequest(), res.value);
+ expect(res.status).toHaveBeenCalledWith(404);
+ expect(deps.getSubagentTaskControlReceipt).toHaveBeenCalledWith({
+ userId: 'user-1',
+ conversationId: threadId,
+ taskId,
+ invocationId: 'invocation-1',
+ tenantId: 'tenant-1',
+ activeOnly: true,
+ });
+ expect(deps.getMessages).not.toHaveBeenCalled();
+ });
+ it('sanitizes unexpected body storage failures', async () => {
+ const deps = dependencies();
+ deps.getSubagentTaskControlReceipt.mockRejectedValue(new Error('private storage content'));
+ const res = response();
+ await createSubagentControlReceiptHandler(deps)(readRequest(), res.value);
+ expect(res.status).toHaveBeenCalledWith(503);
+ expect(JSON.stringify(res.json.mock.calls)).not.toContain('private');
+ });
+});
diff --git a/packages/api/src/agents/control.ts b/packages/api/src/agents/control.ts
index f69efb3a14..bef84fd9be 100644
--- a/packages/api/src/agents/control.ts
+++ b/packages/api/src/agents/control.ts
@@ -37,6 +37,8 @@ type Dependencies = Pick<ConversationMethods, 'getConvoOwnership' | 'getSubagent
type Params = {
parentConversationId?: string;
threadId?: string;
+ taskId?: string;
+ invocationId?: string;
};
const validId = (value: unknown, byteLimit = MAX_THREAD_ID_BYTES): value is string =>
@@ -277,3 +279,65 @@ export function createSubagentControlHandler(deps: Dependencies) {
}
};
}
+
+/** Reads one retained body through its parent without mutating or replaying the control. */
+export function createSubagentControlReceiptHandler(
+ deps: Pick<
+ Dependencies,
+ 'getConvoOwnership' | 'getSubagentThreadForParent' | 'getSubagentTaskControlReceipt'
+ >,
+) {
+ return async (req: ServerRequest, res: Response): Promise<void> => {
+ const userId = req.user?.id;
+ const tenantId = req.user?.tenantId || undefined;
+ const { parentConversationId, threadId, taskId, invocationId } = req.params as Params;
+ if (
+ !userId ||
+ !validId(parentConversationId) ||
+ !validId(threadId) ||
+ parentConversationId === threadId ||
+ !validId(taskId, MAX_TASK_ID_BYTES) ||
+ !validId(invocationId, MAX_INVOCATION_ID_BYTES)
+ ) {
+ res.status(400).json({ error: 'Invalid subagent control request' });
+ return;
+ }
+ try {
+ const [parent, child] = await Promise.all([
+ deps.getConvoOwnership(userId, parentConversationId, tenantId ?? null),
+ deps.getSubagentThreadForParent({
+ user: userId,
+ parentConversationId,
+ conversationId: threadId,
+ tenantId,
+ }),
+ ]);
+ if (
+ parent == null ||
+ child?.subagentThread?.parentConversationId !== parentConversationId ||
+ parent.tenantId !== tenantId ||
+ child.tenantId !== tenantId
+ ) {
+ res.status(404).json({ error: 'Conversation not found' });
+ return;
+ }
+ const receipt = await deps.getSubagentTaskControlReceipt({
+ userId,
+ conversationId: threadId,
+ taskId,
+ invocationId,
+ tenantId,
+ activeOnly: true,
+ });
+ if (receipt == null || receipt.status === 'reserved') {
+ res.status(404).json({ error: 'Control not found' });
+ return;
+ }
+ res
+ .status(200)
+ .json({ receipt: publicStoredReceipt(receipt) } satisfies SubagentControlResponse);
+ } catch {
+ res.status(503).json({ error: 'Subagent content unavailable' });
+ }
+ };
+}
diff --git a/packages/api/src/agents/index.ts b/packages/api/src/agents/index.ts
index 5b85cc6d1c..fb0b2653cd 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 './aggregation';
export * from './subagentContent';
export * from './subagentIdentity';
export * from './subagentCompletionWakeup';
diff --git a/packages/api/src/agents/subagentActivity.spec.ts b/packages/api/src/agents/subagentActivity.spec.ts
index a545c5f186..f90c11ce9f 100644
--- a/packages/api/src/agents/subagentActivity.spec.ts
+++ b/packages/api/src/agents/subagentActivity.spec.ts
@@ -8,6 +8,7 @@ import type { SubagentActivityEnvelope, SubagentActivityUpdateEvent } from './su
import type { IEventTransport } from '~/stream/interfaces/IJobStore';
import type { ServerRequest } from '~/types';
import {
+ boundSubagentActivityUpdate,
SubagentActivityStream,
createSubagentActivityStreamHandler,
subagentActivityStreamId,
@@ -935,3 +936,33 @@ describe('subagent activity stream authorization', () => {
}
});
});
+
+it('bounds applied-steer activity while retaining identity, source timestamp and replay sequence', () => {
+ const event: SubagentActivityUpdateEvent = {
+ runId: 'root',
+ subagentRunId: 'task',
+ subagentType: 'worker',
+ subagentAgentId: 'agent',
+ phase: 'steer_applied',
+ activityEventId: 'task:4',
+ activitySequence: 4,
+ timestamp: '2026-10-23T00:00:00.000Z',
+ data: {
+ index: 2,
+ steerId: 'control',
+ part: { type: 'steer', steer: 'Guidance', steerId: 'control' },
+ },
+ };
+ expect(boundSubagentActivityUpdate(event)).toMatchObject(event);
+ const oversized = boundSubagentActivityUpdate({
+ ...event,
+ data: { body: 'x'.repeat(256 * 1024) },
+ });
+ expect(oversized.data).toBeUndefined();
+ expect(oversized).toMatchObject({
+ phase: 'steer_applied',
+ activityEventId: 'task:4',
+ activitySequence: 4,
+ timestamp: event.timestamp,
+ });
+});
diff --git a/packages/api/src/agents/subagentActivity.ts b/packages/api/src/agents/subagentActivity.ts
index 9cb8b7fcdf..b74a23b578 100644
--- a/packages/api/src/agents/subagentActivity.ts
+++ b/packages/api/src/agents/subagentActivity.ts
@@ -29,7 +29,8 @@ const SHUTDOWN_SUBSCRIBER_ERROR = 'Server is shutting down';
export type SubagentActivityTerminalStatus = 'completed' | 'failed' | 'cancelled';
-export type SubagentActivityUpdateEvent = SubagentUpdateEvent & {
+export type SubagentActivityUpdateEvent = Omit<SubagentUpdateEvent, 'phase'> & {
+ phase: SubagentUpdateEvent['phase'] | 'steer_applied';
/** Host-assigned identity shared by parent and detached delivery paths. */
activityEventId?: string;
/** Host-assigned monotonic sequence shared by parent and detached delivery paths. */
diff --git a/packages/api/src/agents/subagentContent.integration.spec.ts b/packages/api/src/agents/subagentContent.integration.spec.ts
index 0f47aa2531..7ce465b404 100644
--- a/packages/api/src/agents/subagentContent.integration.spec.ts
+++ b/packages/api/src/agents/subagentContent.integration.spec.ts
@@ -13,6 +13,7 @@ import {
readSubagentContent,
} from './subagentContent';
import { buildSubagentThreadTaskConfig, SubagentThreadTaskStore } from './subagentThreads';
+import { createSubagentThreadViewHandler } from './view';
let mongo: MongoMemoryServer;
let methods: AllMethods;
@@ -1293,3 +1294,96 @@ describe('selective task content deletion', () => {
}
});
});
+
+it.each(['long input', 'mismatched input', 'safe boundary', 'append'] as const)(
+ 'preserves usable legacy history through the real parent-authorized view with %s',
+ async (condition) => {
+ const { scope } = await runningTask(async () => ({ content: 'Final result.' }));
+ await until(
+ async () =>
+ (await methods.getMessages({ user: scope.user, messageId: `${scope.taskId}:assistant` }))
+ .length === 1,
+ );
+ const prompt = condition === 'long input' ? 'Long current task. '.repeat(575) : 'Current task.';
+ const activity = [
+ { type: 'reasoning', text: 'Saved current reasoning.' },
+ { type: 'writing', text: 'Saved current activity.' },
+ ];
+ const current = [
+ {
+ type: 'human',
+ data: { content: condition === 'mismatched input' ? 'Unrelated prompt.' : prompt },
+ },
+ { type: 'ai', data: { content: 'Before current guidance.' } },
+ {
+ type: 'human',
+ data: {
+ content: 'Current guidance.',
+ additional_kwargs: { injected: true, source: 'steer' },
+ },
+ },
+ { type: 'ai', data: { content: 'After current guidance.' } },
+ ];
+ const previous = [
+ { type: 'human', data: { content: 'Private previous task.' } },
+ {
+ type: 'human',
+ data: {
+ content: 'Private previous guidance.',
+ additional_kwargs: { injected: true, source: 'steer' },
+ },
+ },
+ { type: 'ai', data: { content: 'Private previous activity.' } },
+ ];
+ await mongoose.models.Message.updateOne(
+ { user: scope.user, messageId: `${scope.taskId}:user` },
+ { $set: { text: prompt } },
+ );
+ await mongoose.models.Message.updateOne(
+ { user: scope.user, messageId: `${scope.taskId}:assistant` },
+ {
+ $set: {
+ subagentActivityProjection: {
+ taskId: scope.taskId,
+ version: 1,
+ activityJson: JSON.stringify(activity),
+ truncated: false,
+ },
+ subagentTranscript: {
+ taskId: scope.taskId,
+ mode: condition === 'append' ? 'append' : 'replace',
+ messagesJson: JSON.stringify(
+ condition === 'append' ? current.slice(1) : [...previous, ...current],
+ ),
+ },
+ },
+ },
+ );
+ const app = express();
+ app.use((req, _res, next) => {
+ (req as ServerRequest).user = { id: scope.user } as ServerRequest['user'];
+ next();
+ });
+ const handler = createSubagentThreadViewHandler(methods);
+ app.get('/api/convos/:parentConversationId/subagents/:threadId', (req, res) =>
+ handler(req as ServerRequest, res),
+ );
+ const response = await request(app)
+ .get(
+ `/api/convos/${scope.parentConversationId}/subagents/${scope.conversationId}?taskId=${scope.taskId}`,
+ )
+ .expect(200);
+ expect(response.body.activity).toEqual(
+ condition === 'safe boundary' || condition === 'append'
+ ? [
+ { type: 'writing', text: 'Before current guidance.' },
+ { type: 'steer', steer: 'Current guidance.' },
+ { type: 'writing', text: 'After current guidance.' },
+ ]
+ : activity,
+ );
+ expect(response.body.activityTruncated).toBe(false);
+ expect(JSON.stringify(response.body)).not.toContain('Private previous');
+ expect(response.body).not.toHaveProperty('subagentTranscript');
+ },
+);
diff --git a/packages/api/src/agents/subagentContent.spec.ts b/packages/api/src/agents/subagentContent.spec.ts
index 8626bfd649..04780b6f64 100644
--- a/packages/api/src/agents/subagentContent.spec.ts
+++ b/packages/api/src/agents/subagentContent.spec.ts
@@ -1,3 +1,4 @@
+import { ContentTypes, SteerEvents } from 'librechat-data-provider';
import type {
SubagentContentAppendResult,
SubagentContentMethods,
@@ -780,3 +781,57 @@ it('does not open a payload cursor when the caller already has the committed hea
});
expect(stream).not.toHaveBeenCalled();
});
+
+it('journals applied steering in its reserved slot before later normalized SDK steps', async () => {
+ const { methods } = memoryStorage();
+ const journal = journalFor(methods);
+ const step = (id: string, index: number) =>
+ update('run_step', {
+ id,
+ index,
+ stepDetails: { type: 'message_creation', message_creation: { message_id: id } },
+ });
+ journal.record(step('before', 0), 0);
+ journal.record(
+ update('message_delta', {
+ id: 'before',
+ delta: { content: [{ type: 'text', text: 'Before' }] },
+ }),
+ 1,
+ );
+ const applied = {
+ steerId: 'control',
+ clientSteerId: 'invocation',
+ index: 1,
+ part: {
+ type: ContentTypes.STEER,
+ steer: 'Actual guidance',
+ steerId: 'control',
+ clientSteerId: 'invocation',
+ createdAt: 42,
+ },
+ responseMessageId: 'task:assistant',
+ conversationId: 'child',
+ };
+ journal.record({ phase: 'steer_applied', data: applied }, 2);
+ journal.record(step('after', 2), 3);
+ journal.record(
+ update('message_delta', { id: 'after', delta: { content: [{ type: 'text', text: 'After' }] } }),
+ 4,
+ );
+ await journal.close();
+ const snapshot = await readSubagentContent(methods, scope);
+ expect(snapshot.ok).toBe(true);
+ if (!snapshot.ok) return;
+ expect(snapshot.value.content).toEqual([
+ expect.objectContaining({ type: 'text', text: 'Before' }),
+ applied.part,
+ expect.objectContaining({ type: 'text', text: 'After' }),
+ ]);
+ expect(snapshot.value.runSteps.map(({ index }) => index)).toEqual([0, 2]);
+ const suffix = await readSubagentContent(methods, scope, 1);
+ expect(suffix.ok && suffix.value.events[0]).toEqual({
+ sequence: 2,
+ frame: { event: SteerEvents.ON_STEER_APPLIED, data: applied },
+ });
+});
diff --git a/packages/api/src/agents/subagentContent.ts b/packages/api/src/agents/subagentContent.ts
index abf0bd2548..bef87338b8 100644
--- a/packages/api/src/agents/subagentContent.ts
+++ b/packages/api/src/agents/subagentContent.ts
@@ -3,12 +3,14 @@ import { createContentAggregator, GraphEvents } from '@librechat/agents';
import {
subagentActivityConfigSchema,
StepEvents,
+ SteerEvents,
ContentTypes,
getRunStepCloseMetadata,
getRunStepDurationMs,
} from 'librechat-data-provider';
import type {
TSubagentActivityConfig,
+ TSteerAppliedEvent,
SubagentContentEvent,
SubagentContentFrame,
SubagentContentWatermark,
@@ -40,12 +42,14 @@ const CONTENT_GRAPH_EVENTS = {
};
type SubagentContentUpdate = Pick<SubagentUpdateEvent, 'data'> & {
- phase: SubagentUpdateEvent['phase'] | 'tool_preparation';
+ phase: SubagentUpdateEvent['phase'] | 'tool_preparation' | 'steer_applied';
};
/** This boundary accepts only events already intended for the public main-chat stream. */
export function subagentContentFrame(update: SubagentContentUpdate): SubagentContentFrame | null {
switch (update.phase) {
+ case 'steer_applied':
+ return { event: SteerEvents.ON_STEER_APPLIED, data: update.data as TSteerAppliedEvent };
case 'run_step': {
const data = update.data as Agents.RunStep | undefined;
return data?.stepDetails == null ? null : { event: StepEvents.ON_RUN_STEP, data };
@@ -481,6 +485,10 @@ export async function readSubagentContent(
continue;
}
const frame = entry.frame;
+ if (frame.event === SteerEvents.ON_STEER_APPLIED) {
+ aggregator.contentParts[frame.data.index] = frame.data.part;
+ continue;
+ }
if (frame.event === StepEvents.ON_RUN_STEP_CLOSED) {
const step = aggregator.stepMap.get(frame.data.id);
if (step != null) step.status = frame.data.status;
diff --git a/packages/api/src/agents/subagentThreads.spec.ts b/packages/api/src/agents/subagentThreads.spec.ts
index 9c2eebbc0c..ac9a96c972 100644
--- a/packages/api/src/agents/subagentThreads.spec.ts
+++ b/packages/api/src/agents/subagentThreads.spec.ts
@@ -1,8 +1,8 @@
import mongoose from 'mongoose';
import { randomUUID } from 'node:crypto';
import { MongoMemoryServer } from 'mongodb-memory-server';
-import { SubagentResolutionError } from '@librechat/agents';
-import { Constants, EModelEndpoint } from 'librechat-data-provider';
+import { Constants, EModelEndpoint, ContentTypes } from 'librechat-data-provider';
+import { InMemorySubagentTaskStore, SubagentResolutionError } from '@librechat/agents';
import { AIMessage, HumanMessage, ToolMessage } from '@librechat/agents/langchain/messages';
import {
createMethods,
@@ -28,9 +28,9 @@ import type {
SubagentTaskControlHandler,
SubagentTaskControlTransport,
} from './subagentTaskRouting';
+import type { SubagentActivityEnvelope, SubagentActivityUpdateEvent } from './subagentActivity';
import type { SubagentTaskWakeupRegistration } from './subagentThreads';
import type { IEventTransport } from '~/stream/interfaces/IJobStore';
-import type { SubagentActivityEnvelope } from './subagentActivity';
import type { UsageMetadata } from '~/stream/interfaces/IJobStore';
import {
buildSubagentThreadTaskConfig,
@@ -49,6 +49,7 @@ import { SUBAGENT_COMPLETION_DELIVERY } from './subagentDelivery';
import { createSubagentAttemptKey } from './subagentThreadIds';
import { SubagentActivityStream } from './subagentActivity';
import { runCheckBackgroundTask } from './background';
+import { SUBAGENT_ACTIVITY_LIMITS } from './activity';
import { InMemoryEventTransport } from '~/stream';
import { createSubagentUsageSink } from './usage';
@@ -297,6 +298,761 @@ beforeEach(async () => {
});
describe('SubagentThreadTaskStore', () => {
+ it('forwards the same immutable activity identity to the parent and detached stream', async () => {
+ const userId = 'shared-progress-identity';
+ const parentConversationId = randomUUID();
+ await saveParent(userId, parentConversationId);
+ const forwarded: SubagentActivityUpdateEvent[] = [];
+ const originalStart = InMemorySubagentTaskStore.prototype.start;
+ jest.spyOn(InMemorySubagentTaskStore.prototype, 'start').mockImplementation(function (
+ this: InMemorySubagentTaskStore,
+ request,
+ ) {
+ return originalStart.call(this, {
+ ...request,
+ run: async (runtime) => {
+ const forward = runtime.reportProgress;
+ return request.run({
+ ...runtime,
+ reportProgress: (event) => {
+ forwarded.push(event);
+ forward(event);
+ },
+ });
+ },
+ });
+ });
+ const store = new SubagentThreadTaskStore(methods);
+ const config = buildSubagentThreadTaskConfig(store, { userId, parentConversationId });
+ let runtime!: SubagentTaskRuntime;
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const started = store.start(
+ taskRequest(config.scopeId, {
+ run: async (child) => {
+ runtime = child;
+ await gate;
+ return { content: 'Hello' };
+ },
+ }),
+ );
+ const taskId = requireAccepted(started).task.taskId;
+ const events: SubagentActivityEnvelope[] = [];
+ const subscription = store.subscribeActivity(requireThreadId(started), taskId, {
+ onEvent: (event) => {
+ if (event.event === 'on_subagent_update') events.push(event);
+ },
+ });
+ await subscription.ready;
+ await waitUntil(() => runtime != null, 'the shared-identity runtime');
+ const metadata = {
+ runId: 'parent',
+ subagentRunId: 'child',
+ subagentType: 'worker',
+ subagentAgentId: 'worker',
+ timestamp: '2026-10-24T00:00:00Z',
+ };
+ const step: SubagentUpdateEvent = {
+ ...metadata,
+ phase: 'run_step',
+ data: {
+ id: 'text',
+ index: 0,
+ stepDetails: { type: 'message_creation', message_creation: { message_id: 'text' } },
+ },
+ };
+ const delta: SubagentUpdateEvent = {
+ ...metadata,
+ phase: 'message_delta',
+ data: { id: 'text', delta: { content: [{ type: 'text', text: 'Hello' }] } },
+ };
+ try {
+ runtime.reportProgress(step);
+ runtime.reportProgress(delta);
+ await store.controlTask(
+ config.scopeId,
+ taskId,
+ { action: 'steer', message: 'Continue' },
+ 'control',
+ );
+ runtime.drain('tool');
+ runtime.reportProgress({
+ ...step,
+ data: {
+ id: 'after',
+ index: 1,
+ stepDetails: { type: 'message_creation', message_creation: { message_id: 'after' } },
+ },
+ });
+ runtime.reportProgress({
+ ...delta,
+ data: { id: 'after', delta: { content: [{ type: 'text', text: 'Later work.' }] } },
+ });
+ await waitUntil(() => events.length === 5, 'both delivery paths');
+ expect(forwarded.map((event) => event.phase)).toEqual([
+ 'run_step',
+ 'message_delta',
+ 'steer_applied',
+ 'run_step',
+ 'message_delta',
+ ]);
+ expect(
+ forwarded.map(({ activityEventId, activitySequence }) => ({
+ activityEventId,
+ activitySequence,
+ })),
+ ).toEqual(
+ [0, 1, 2, 3, 4].map((sequence) => ({
+ activityEventId: `${taskId}:${sequence}`,
+ activitySequence: sequence,
+ })),
+ );
+ for (const event of forwarded) {
+ expect(
+ events.find(({ data }) => data.activityEventId === event.activityEventId)?.data,
+ ).toMatchObject(event);
+ }
+ expect(step).not.toHaveProperty('activityEventId');
+ expect(delta).not.toHaveProperty('activitySequence');
+ } finally {
+ release();
+ await waitForSettled(store, config.scopeId, started);
+ subscription.unsubscribe();
+ store.destroyActivityStream();
+ }
+ });
+
+ it.each(['success', 'error', 'cancel'] as const)(
+ 'persists public injection order without private messages on %s',
+ async (outcome) => {
+ const userId = `public-${outcome}`;
+ const parentConversationId = randomUUID();
+ await saveParent(userId, parentConversationId);
+ const store = new SubagentThreadTaskStore(methods);
+ const config = buildSubagentThreadTaskConfig(store, { userId, parentConversationId });
+ let runtime!: SubagentTaskRuntime;
+ let finish!: () => void;
+ const gate = new Promise<void>((resolve) => {
+ finish = resolve;
+ });
+ const started = store.start(
+ taskRequest(config.scopeId, {
+ run: async (childRuntime) => {
+ runtime = childRuntime;
+ await gate;
+ if (outcome === 'error') throw new Error('private upstream diagnostic');
+ return { content: 'After' };
+ },
+ }),
+ );
+ const taskId = requireAccepted(started).task.taskId;
+ const threadId = requireThreadId(started);
+ await waitUntil(() => runtime != null, 'the public runtime');
+ const write = (id: string, index: number, text: string) => {
+ const metadata = {
+ runId: 'root',
+ parentRunId: 'parent',
+ subagentRunId: taskId,
+ subagentType: 'worker',
+ subagentAgentId: 'agent',
+ timestamp: '2026-10-23T00:00:00.000Z',
+ };
+ runtime.reportProgress({
+ ...metadata,
+ phase: 'run_step',
+ data: {
+ id,
+ index,
+ stepDetails: { type: 'message_creation', message_creation: { message_id: id } },
+ },
+ });
+ runtime.reportProgress({
+ ...metadata,
+ phase: 'message_delta',
+ data: {
+ id,
+ delta: { content: [{ type: 'text', text }] },
+ },
+ });
+ };
+ write('before', 0, 'Before');
+ runtime.reportProgress({
+ runId: 'root',
+ subagentRunId: taskId,
+ subagentType: 'worker',
+ subagentAgentId: 'agent',
+ timestamp: '2026-10-24T00:00:00Z',
+ phase: 'reasoning_delta',
+ data: {
+ id: 'before',
+ delta: { content: [{ type: 'think', think: 'Visible reasoning.' }] },
+ },
+ });
+ const accepted = await store.controlTask(
+ config.scopeId,
+ taskId,
+ { action: 'steer', message: 'Guidance' },
+ 'public-guidance',
+ );
+ const queued = await store.controlTask(
+ config.scopeId,
+ taskId,
+ { action: 'queue', message: 'Withdrawn' },
+ 'public-withdrawn',
+ );
+ if (queued.status !== 'accepted' || queued.controlId == null)
+ throw new Error('Expected queue');
+ await store.controlTask(
+ config.scopeId,
+ taskId,
+ { action: 'cancel_message', controlId: queued.controlId },
+ 'public-withdraw',
+ );
+ expect(runtime.drain('tool').map(({ content }) => content)).toEqual(['Guidance']);
+ expect(runtime.drain('tool')).toEqual([]);
+ write('after', 1, 'After');
+ if (outcome === 'cancel') {
+ await store.controlTask(config.scopeId, taskId, { action: 'cancel' }, 'public-cancel');
+ }
+ finish();
+ await waitUntil(
+ async () =>
+ (
+ await methods.getMessages({
+ user: userId,
+ conversationId: threadId,
+ messageId: `${taskId}:assistant`,
+ })
+ ).length === 1,
+ 'the terminal public write',
+ );
+ await waitForSettled(store, config.scopeId, started);
+ const [saved] = await methods.getMessages(
+ { user: userId, conversationId: threadId, messageId: `${taskId}:assistant` },
+ '+subagentActivityProjection +subagentTranscript',
+ );
+ expect(saved.subagentTranscript).toBeUndefined();
+ expect(saved.subagentContent).toBeUndefined();
+ expect(saved.subagentActivityProjection).toMatchObject({
+ taskId,
+ version: 2,
+ truncated: false,
+ });
+ const activity = JSON.parse(saved.subagentActivityProjection!.activityJson);
+ expect(activity).toEqual([
+ { type: 'writing', text: 'Before' },
+ { type: 'reasoning', text: 'Visible reasoning.' },
+ {
+ type: 'steer',
+ steer: 'Guidance',
+ steerId: accepted.status === 'accepted' ? accepted.controlId : '',
+ clientSteerId: 'public-guidance',
+ createdAt: expect.any(Number),
+ },
+ { type: 'writing', text: 'After' },
+ ]);
+ if (outcome === 'error') expect(saved.text).not.toContain('private upstream');
+ const adjacent = store.start(
+ taskRequest(config.scopeId, { run: async () => ({ content: 'Adjacent' }) }),
+ );
+ await waitForSettled(store, config.scopeId, adjacent);
+ const [other] = await methods.getMessages(
+ {
+ user: userId,
+ conversationId: requireThreadId(adjacent),
+ messageId: `${requireAccepted(adjacent).task.taskId}:assistant`,
+ },
+ '+subagentActivityProjection',
+ );
+ expect(JSON.parse(other.subagentActivityProjection!.activityJson)).toEqual([]);
+ expect(other.subagentActivityProjection!.truncated).toBe(true);
+ store.destroyActivityStream();
+ },
+ );
+
+ it.each(['error', 'cancel'] as const)(
+ 'persists streamed arguments without an object placeholder on %s',
+ async (outcome) => {
+ const userId = `streamed-args-${outcome}`;
+ const parentConversationId = randomUUID();
+ await saveParent(userId, parentConversationId);
+ const store = new SubagentThreadTaskStore(methods);
+ const config = buildSubagentThreadTaskConfig(store, { userId, parentConversationId });
+ let runtime!: SubagentTaskRuntime;
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const started = store.start(
+ taskRequest(config.scopeId, {
+ run: async (child) => {
+ runtime = child;
+ await gate;
+ if (outcome === 'error') throw new Error('Executor failed');
+ return { content: 'Interrupted' };
+ },
+ }),
+ );
+ const taskId = requireAccepted(started).task.taskId;
+ await waitUntil(() => runtime != null, 'streamed tool arguments');
+ const base = {
+ runId: 'parent',
+ subagentRunId: taskId,
+ subagentType: 'worker',
+ subagentAgentId: 'worker',
+ timestamp: '2026-10-24T00:00:00Z',
+ };
+ try {
+ runtime.reportProgress({
+ ...base,
+ phase: 'run_step',
+ data: {
+ id: 'tool',
+ index: 0,
+ stepDetails: {
+ type: 'tool_calls',
+ tool_calls: [{ id: 'call', name: 'lookup', args: {}, type: 'tool_call' }],
+ },
+ },
+ });
+ for (const args of ['{"query":', '"x"}'])
+ runtime.reportProgress({
+ ...base,
+ phase: 'run_step_delta',
+ data: {
+ id: 'tool',
+ delta: {
+ type: 'tool_calls',
+ tool_calls: [{ id: 'call', index: 0, name: 'lookup', args }],
+ },
+ },
+ });
+ runtime.reportProgress({
+ ...base,
+ phase: 'run_step_delta',
+ data: {
+ id: 'tool',
+ delta: {
+ type: 'tool_calls',
+ tool_calls: [{ id: 'late-call', index: 1, name: 'late_lookup', args: '{"other":' }],
+ },
+ },
+ });
+ runtime.reportProgress({
+ ...base,
+ phase: 'run_step_delta',
+ data: {
+ id: 'tool',
+ delta: {
+ type: 'tool_calls',
+ tool_calls: [{ index: 1, name: 'late_lookup', args: 'true}' }],
+ },
+ },
+ });
+ if (outcome === 'cancel')
+ await store.controlTask(
+ config.scopeId,
+ taskId,
+ { action: 'cancel' },
+ 'cancel-streamed-input',
+ );
+ } finally {
+ release();
+ }
+ await waitUntil(
+ async () =>
+ (await methods.getMessages({ user: userId, messageId: `${taskId}:assistant` })).length ===
+ 1,
+ 'terminal streamed-input projection',
+ );
+ await waitForSettled(store, config.scopeId, started);
+ const [saved] = await methods.getMessages(
+ { user: userId, messageId: `${taskId}:assistant` },
+ '+subagentActivityProjection',
+ );
+ expect(saved.subagentActivityProjection).toMatchObject({
+ taskId,
+ version: 2,
+ truncated: false,
+ });
+ expect(JSON.parse(saved.subagentActivityProjection!.activityJson)).toEqual([
+ {
+ type: 'tool',
+ toolCallId: 'call',
+ name: 'lookup',
+ input: '{"query":"x"}',
+ status: 'running',
+ },
+ {
+ type: 'tool',
+ toolCallId: 'late-call',
+ name: 'late_lookup',
+ input: '{"other":true}',
+ status: 'running',
+ },
+ ]);
+ store.destroyActivityStream();
+ },
+ );
+
+ it('prefers bounded canonical history with a recent applied steer over a sparse observer', async () => {
+ const userId = 'canonical-public';
+ const parentConversationId = randomUUID();
+ await saveParent(userId, parentConversationId);
+ const store = new SubagentThreadTaskStore(methods);
+ const config = buildSubagentThreadTaskConfig(store, { userId, parentConversationId });
+ let runtime!: SubagentTaskRuntime;
+ let finish!: (value: { content: string; messages: BaseMessage[] }) => void;
+ const result = new Promise<{ content: string; messages: BaseMessage[] }>((resolve) => {
+ finish = resolve;
+ });
+ const started = store.start(
+ taskRequest(config.scopeId, {
+ run: async (child) => {
+ runtime = child;
+ return result;
+ },
+ }),
+ );
+ const taskId = requireAccepted(started).task.taskId;
+ await waitUntil(() => runtime != null, 'the canonical runtime');
+ const control = await store.controlTask(
+ config.scopeId,
+ taskId,
+ { action: 'steer', message: 'Recent guidance' },
+ 'canonical-steer',
+ );
+ runtime.drain('tool');
+ finish({
+ content: 'After',
+ messages: [
+ ...Array.from({ length: 120 }, (_, index) => new AIMessage(`Before-${index}`)),
+ new HumanMessage({
+ content: 'Recent guidance',
+ additional_kwargs: { injected: true, source: 'steer' },
+ }),
+ new AIMessage('After'),
+ ],
+ });
+ await waitForSettled(store, config.scopeId, started);
+ const [saved] = await methods.getMessages(
+ { user: userId, conversationId: requireThreadId(started), messageId: `${taskId}:assistant` },
+ '+subagentActivityProjection',
+ );
+ const projection = saved.subagentActivityProjection!;
+ const activity = JSON.parse(projection.activityJson);
+ expect(projection.truncated).toBe(true);
+ expect(activity).toHaveLength(SUBAGENT_ACTIVITY_LIMITS.items);
+ expect(activity.slice(-2)).toEqual([
+ {
+ type: 'steer',
+ steer: 'Recent guidance',
+ clientSteerId: 'canonical-steer',
+ steerId: control.status === 'accepted' ? control.controlId : '',
+ createdAt: expect.any(Number),
+ },
+ { type: 'writing', text: 'After' },
+ ]);
+ store.destroyActivityStream();
+ });
+
+ it('bounds retained public history and large tool payloads without a transcript', async () => {
+ const userId = 'bounded-public';
+ const parentConversationId = randomUUID();
+ await saveParent(userId, parentConversationId);
+ const store = new SubagentThreadTaskStore(methods);
+ const config = buildSubagentThreadTaskConfig(store, { userId, parentConversationId });
+ const started = store.start(
+ taskRequest(config.scopeId, {
+ run: async (runtime) => {
+ const progress = (phase: SubagentUpdateEvent['phase'], data: unknown) =>
+ runtime.reportProgress({
+ runId: 'root',
+ parentRunId: 'parent',
+ subagentRunId: 'child',
+ subagentType: 'worker',
+ subagentAgentId: 'agent',
+ timestamp: '2026-10-23T00:00:00.000Z',
+ phase,
+ data,
+ });
+ for (let index = 0; index < SUBAGENT_ACTIVITY_LIMITS.items + 20; index++) {
+ progress('run_step', {
+ id: `step-${index}`,
+ index,
+ stepDetails: {
+ type: 'message_creation',
+ message_creation: { message_id: `message-${index}` },
+ },
+ });
+ progress('message_delta', {
+ id: `step-${index}`,
+ delta: { content: [{ type: 'text', text: `text-${index}` }] },
+ });
+ }
+ const args = { query: 'x'.repeat(100_000) };
+ progress('run_step', {
+ id: 'tool',
+ index: 120,
+ stepDetails: {
+ type: 'tool_calls',
+ tool_calls: [{ id: 'call', type: 'tool_call', name: 'lookup', args }],
+ },
+ });
+ progress('run_step_completed', {
+ result: {
+ id: 'tool',
+ type: 'tool_call',
+ tool_call: {
+ id: 'call',
+ name: 'lookup',
+ args,
+ output: '\u0000'.repeat(100_000),
+ progress: 1,
+ },
+ },
+ });
+ return { content: 'Done' };
+ },
+ }),
+ );
+ await waitForSettled(store, config.scopeId, started);
+ const [saved] = await methods.getMessages(
+ {
+ user: userId,
+ conversationId: requireThreadId(started),
+ messageId: `${requireAccepted(started).task.taskId}:assistant`,
+ },
+ '+subagentActivityProjection',
+ );
+ const projection = saved.subagentActivityProjection!;
+ const activity = JSON.parse(projection.activityJson);
+ expect(projection.truncated).toBe(true);
+ expect(activity.length).toBeLessThanOrEqual(SUBAGENT_ACTIVITY_LIMITS.items);
+ expect(Buffer.byteLength(projection.activityJson)).toBeLessThanOrEqual(
+ SUBAGENT_ACTIVITY_LIMITS.bytes,
+ );
+ expect(activity[0]).not.toMatchObject({ text: 'text-0' });
+ const tool = activity.at(-1);
+ expect(tool).toMatchObject({
+ type: 'tool',
+ toolCallId: 'call',
+ status: 'completed',
+ inputTruncated: true,
+ outputTruncated: true,
+ });
+ expect(Buffer.byteLength(tool.input)).toBeLessThanOrEqual(
+ SUBAGENT_ACTIVITY_LIMITS.toolInputBytes,
+ );
+ expect(Buffer.byteLength(tool.output)).toBeLessThanOrEqual(
+ SUBAGENT_ACTIVITY_LIMITS.toolOutputBytes,
+ );
+ store.destroyActivityStream();
+ });
+
+ it.each([1, 2])(
+ 'publishes applied guidance at SDK drain boundaries once and shifts only new steps (width %s)',
+ async (width) => {
+ const userId = 'steer-order-user';
+ const parentConversationId = randomUUID();
+ await saveParent(userId, parentConversationId);
+ const store = new SubagentThreadTaskStore(methods);
+ const config = buildSubagentThreadTaskConfig(store, { userId, parentConversationId });
+ let runtime!: SubagentTaskRuntime;
+ let finish!: (result: { content: string; messages: BaseMessage[] }) => void;
+ const result = new Promise<{ content: string; messages: BaseMessage[] }>((resolve) => {
+ finish = resolve;
+ });
+ const started = store.start(
+ taskRequest(config.scopeId, {
+ run: async (childRuntime) => {
+ runtime = childRuntime;
+ return result;
+ },
+ }),
+ );
+ const taskId = requireAccepted(started).task.taskId;
+ const threadId = requireThreadId(started);
+ const events: SubagentActivityEnvelope[] = [];
+ const subscription = store.subscribeActivity(threadId, taskId, {
+ onEvent: (event) => {
+ if (event.event === 'on_subagent_update') events.push(event);
+ },
+ });
+ await subscription.ready;
+ await waitUntil(() => runtime != null, 'the controlled runtime');
+ const progress = (id: string, index: number): SubagentUpdateEvent => ({
+ runId: 'root',
+ parentRunId: 'parent',
+ subagentRunId: 'child-run',
+ subagentType: 'worker',
+ subagentAgentId: 'agent',
+ phase: 'run_step',
+ timestamp: '2026-10-23T00:00:00.000Z',
+ data: {
+ id,
+ index,
+ stepDetails: { type: 'message_creation', message_creation: { message_id: id } },
+ },
+ });
+ const before = progress('before', 0);
+ if (width === 2)
+ before.data = {
+ id: 'before',
+ index: 0,
+ stepDetails: {
+ type: 'tool_calls',
+ tool_calls: [
+ { id: 'parallel-1', name: 'first', args: {}, type: 'tool_call' },
+ { id: 'parallel-2', name: 'second', args: {}, type: 'tool_call' },
+ ],
+ },
+ };
+ runtime.reportProgress(before);
+ const queued = await store.controlTask(
+ config.scopeId,
+ taskId,
+ { action: 'queue', message: 'Queued' },
+ 'queue-id',
+ );
+ const steered = await store.controlTask(
+ config.scopeId,
+ taskId,
+ { action: 'steer', message: 'Steered' },
+ 'steer-id',
+ );
+ const interrupted = await store.controlTask(
+ config.scopeId,
+ taskId,
+ { action: 'interrupt', message: 'Interrupted' },
+ 'interrupt-id',
+ );
+ const withdrawn = await store.controlTask(
+ config.scopeId,
+ taskId,
+ { action: 'queue', message: 'Withdrawn' },
+ 'withdrawn-id',
+ );
+ if (withdrawn.status !== 'accepted' || withdrawn.controlId == null)
+ throw new Error('Expected pending control');
+ await store.controlTask(
+ config.scopeId,
+ taskId,
+ { action: 'cancel_message', controlId: withdrawn.controlId },
+ 'withdraw-id',
+ );
+ await expect(
+ store.controlTask(
+ config.scopeId,
+ 'wrong-task',
+ { action: 'steer', message: 'Wrong' },
+ 'wrong-id',
+ ),
+ ).resolves.toMatchObject({ status: 'not_found' });
+ const preempt = runtime.drain('preempt');
+ expect(preempt.map(({ content }) => content)).toEqual(['Interrupted']);
+ runtime.reportProgress(progress('middle', 1));
+ const tool = runtime.drain('tool');
+ expect(tool.map(({ content }) => content)).toEqual(['Steered']);
+ const turn = runtime.drain('turn');
+ expect(turn.map(({ content }) => content)).toEqual(['Queued']);
+ expect(runtime.drain('turn')).toEqual([]);
+ runtime.reportProgress(before);
+ runtime.reportProgress(progress('after', 2));
+ await store.controlTask(
+ config.scopeId,
+ taskId,
+ { action: 'queue', message: 'Not applied' },
+ 'failed-id',
+ );
+ finish({
+ content: 'Done',
+ messages: [
+ new AIMessage('Before'),
+ ...[...preempt, ...tool, ...turn].map((injected) => {
+ if (typeof injected.content !== 'string') throw new Error('Expected string guidance');
+ return new HumanMessage({
+ content: injected.content,
+ additional_kwargs: { injected: true, source: injected.source, role: injected.role },
+ });
+ }),
+ new AIMessage('After'),
+ ],
+ });
+ await waitForSettled(store, config.scopeId, started);
+ await waitUntil(() => events.length === 7, 'the ordered activity tail');
+ expect(events.map(({ data }) => data.phase)).toEqual([
+ 'run_step',
+ 'steer_applied',
+ 'run_step',
+ 'steer_applied',
+ 'steer_applied',
+ 'run_step',
+ 'run_step',
+ ]);
+ expect(events.map(({ data }) => (data.data as { index: number }).index)).toEqual([
+ 0,
+ width,
+ width + 1,
+ width + 2,
+ width + 3,
+ 0,
+ width + 4,
+ ]);
+ expect(events.map(({ data }) => data.activitySequence)).toEqual([0, 1, 2, 3, 4, 5, 6]);
+ expect(events[1].data).toMatchObject({
+ subagentRunId: 'child-run',
+ activityEventId: `${taskId}:1`,
+ data: {
+ index: width,
+ steerId: interrupted.status === 'accepted' ? interrupted.controlId : '',
+ clientSteerId: 'interrupt-id',
+ responseMessageId: `${taskId}:assistant`,
+ conversationId: threadId,
+ part: {
+ type: ContentTypes.STEER,
+ steer: 'Interrupted',
+ clientSteerId: 'interrupt-id',
+ createdAt: expect.any(Number),
+ },
+ },
+ });
+ expect(
+ events
+ .filter(({ data }) => data.phase === 'steer_applied')
+ .map(({ data }) => (data.data as { part: { steer: string } }).part.steer),
+ ).toEqual(['Interrupted', 'Steered', 'Queued']);
+ expect(queued.status).toBe('accepted');
+ expect(steered.status).toBe('accepted');
+ expect(before.data).toMatchObject({ index: 0 });
+ const [saved] = await methods.getMessages(
+ { user: userId, conversationId: threadId, messageId: `${taskId}:assistant` },
+ '+subagentActivityProjection +subagentTranscript',
+ );
+ expect(saved.subagentActivityProjection?.version).toBe(2);
+ expect(
+ JSON.parse(saved.subagentTranscript!.messagesJson)
+ .filter((message: { type: string }) => message.type === 'human')
+ .map(
+ (message: { data: { additional_kwargs: { clientSteerId: string } } }) =>
+ message.data.additional_kwargs.clientSteerId,
+ ),
+ ).toEqual(['interrupt-id', 'steer-id', 'queue-id']);
+ expect(JSON.parse(saved.subagentActivityProjection!.activityJson)).toEqual([
+ { type: 'writing', text: 'Before' },
+ ...events
+ .filter(({ data }) => data.phase === 'steer_applied')
+ .map(({ data }) => (data.data as { part: object }).part),
+ { type: 'writing', text: 'After' },
+ ]);
+ expect(saved.subagentContent).toBeUndefined();
+ subscription.unsubscribe();
+ store.destroyActivityStream();
+ },
+ );
+
it('records the automatic delivery contract without hiding routed store operations', async () => {
const store = new SubagentThreadTaskStore(methods);
const scope = { userId: 'delivery-user', parentConversationId: randomUUID() };
@@ -530,7 +1286,7 @@ describe('SubagentThreadTaskStore', () => {
});
expect(messages[1].subagentActivityProjection).toEqual({
taskId: requireAccepted(started).task.taskId,
- version: 1,
+ version: 2,
activityJson: JSON.stringify([{ type: 'writing', text: 'Completed the investigation.' }]),
truncated: false,
});
diff --git a/packages/api/src/agents/subagentThreads.ts b/packages/api/src/agents/subagentThreads.ts
index 4bca8fefb2..71532e472b 100644
--- a/packages/api/src/agents/subagentThreads.ts
+++ b/packages/api/src/agents/subagentThreads.ts
@@ -1,11 +1,21 @@
import { randomUUID } from 'node:crypto';
import { logger, tenantStorage } from '@librechat/data-schemas';
-import { InMemorySubagentTaskStore, SubagentResolutionError } from '@librechat/agents';
-import { EModelEndpoint, Constants, subagentActivityConfigSchema } from 'librechat-data-provider';
+import {
+ EModelEndpoint,
+ Constants,
+ ContentTypes,
+ subagentActivityConfigSchema,
+} from 'librechat-data-provider';
import {
mapChatMessagesToStoredMessages,
mapStoredMessagesToChatMessages,
} from '@librechat/agents/langchain/messages';
+import {
+ createContentAggregator,
+ GraphEvents,
+ InMemorySubagentTaskStore,
+ SubagentResolutionError,
+} from '@librechat/agents';
import type {
InMemorySubagentTaskStoreOptions,
SubagentTaskClaim,
@@ -28,8 +38,8 @@ import type {
ConversationMethods,
SubagentTaskResultClaim,
} from '@librechat/data-schemas';
+import type { TSubagentActivityConfig, TSteerAppliedEvent, Agents } from 'librechat-data-provider';
import type { BaseMessage, StoredMessage } from '@librechat/agents/langchain/messages';
-import type { TSubagentActivityConfig } from 'librechat-data-provider';
import type { ScheduledMCPIdentity } from 'librechat-data-provider';
import type {
SubagentActivityUpdateEvent,
@@ -42,17 +52,19 @@ import type { RequestScopedMCPConnectionStore } from '~/mcp/types';
import type { UsageMetadata } from '~/stream/interfaces/IJobStore';
import type { HostSubagentTaskConfig } from './subagentDelivery';
import type { ActivitySnapshot, ActivityTree } from './digest';
+import type { AppliedSubagentSteer } from './activity';
+import {
+ SubagentPublicRecorder,
+ SUBAGENT_ACTIVITY_LIMITS,
+ projectSubagentActivity,
+ projectPersistedMessageActivityJson,
+} from './activity';
import {
boundedClaim,
boundedTaskList,
controlFingerprint,
SubagentTaskOwnerUnavailableError,
} from './subagentTaskRouting';
-import {
- SUBAGENT_ACTIVITY_LIMITS,
- projectSubagentActivity,
- projectPersistedMessageActivityJson,
-} from './activity';
import { boundSubagentActivityUpdate, SubagentActivityStream } from './subagentActivity';
import { createSubagentAttemptKey, createSubagentThreadId } from './subagentThreadIds';
import { describeErrorCauses, describeStackFrames } from './failures/subagent';
@@ -195,6 +207,8 @@ type ControlInvocationRecord = {
fingerprint: string;
command: SubagentTaskControlCommand;
commandMessageTruncated: boolean;
+ /** Original SDK-accepted body, released at the authoritative terminal transition. */
+ pendingMessage?: string;
result: SubagentTaskControlResult;
createdAt: number;
/** Last authoritative SDK transition, retained for idempotent retries even
@@ -220,6 +234,7 @@ interface TaskThreadLease {
/** Resolves only after child persistence and lease cleanup finish. */
execution?: Promise<void>;
content?: SubagentContentJournal;
+ publishAppliedSteer?: (data: Omit<TSteerAppliedEvent, 'index'>, timestamp: string) => void;
/** Ordered observational tail; canonical child settlement never awaits it. */
activityTail?: Promise<void>;
activityWorkerActive?: boolean;
@@ -465,6 +480,9 @@ function serializeTranscript(
taskId: string,
initialMessages: StoredMessage[],
resultMessages: BaseMessage[] | undefined,
+ appliedSteers?: readonly AppliedSubagentSteer[],
+ expectedTaskInput?: string,
+ observation?: { steersMatched: boolean },
): IMessage['subagentTranscript'] {
if (resultMessages == null) {
return undefined;
@@ -481,7 +499,55 @@ function serializeTranscript(
if (messages.length === 0) {
return undefined;
}
- const messagesJson = append ? JSON.stringify(messages) : storedResultJson;
+ let start = 0;
+ if (!append) {
+ start = -1;
+ for (let index = messages.length - 1; index >= 0; index--) {
+ const message = messages[index];
+ if (
+ (message.type === 'human' || message.type === 'user') &&
+ message.data.additional_kwargs?.injected !== true
+ ) {
+ if (message.data.content === expectedTaskInput) start = index + 1;
+ break;
+ }
+ }
+ }
+ if (appliedSteers != null && start >= 0) {
+ const injectedIndices: number[] = [];
+ for (let index = start; index < messages.length; index++) {
+ const message = messages[index];
+ const metadata = message.data.additional_kwargs;
+ if (
+ (message.type === 'human' || message.type === 'user') &&
+ metadata?.injected === true &&
+ metadata.source === 'steer'
+ )
+ injectedIndices.push(index);
+ }
+ if (injectedIndices.length === appliedSteers.length) {
+ if (observation != null) observation.steersMatched = true;
+ injectedIndices.forEach((messageIndex, controlIndex) => {
+ const message = messages[messageIndex];
+ messages[messageIndex] = {
+ ...message,
+ data: {
+ ...message.data,
+ additional_kwargs: {
+ ...message.data.additional_kwargs,
+ ...appliedSteers[controlIndex],
+ },
+ },
+ };
+ });
+ }
+ }
+ const messagesJson = JSON.stringify(messages);
+ if (Buffer.byteLength(messagesJson, 'utf8') > MAX_TRANSCRIPT_BYTES) {
+ throw new SubagentThreadPublicError(
+ 'Subagent thread transcript is too large to persist safely.',
+ );
+ }
return {
taskId,
mode: append ? 'append' : 'replace',
@@ -765,8 +831,10 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
durable,
this.get(scopeId, taskId)?.pendingControls,
);
+ const message = receipt.status === 'accepted' ? undefined : invocation.pendingMessage;
if (receipt.status !== 'accepted') {
this.controlInvocationByReceipt.delete(controlReceiptKey(scopeId, taskId, receipt.controlId));
+ invocation.pendingMessage = undefined;
}
invocation.receiptPersisted = false;
const persistence = this.queueControlReceipt(scopeId, taskId, threadId, durable).then(() => {
@@ -776,6 +844,34 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
if (invocation.receiptPersistence === tracked) invocation.receiptPersistence = undefined;
});
invocation.receiptPersistence = tracked;
+ try {
+ if (receipt.status === 'applied' && message != null) {
+ const lease = this.activeThreads.get(`${scopeId}\u0000${threadId}`);
+ if (lease?.taskId === taskId) {
+ lease.publishAppliedSteer?.(
+ {
+ steerId: receipt.controlId,
+ clientSteerId: invocation.invocationId,
+ part: {
+ type: ContentTypes.STEER,
+ steer: message,
+ steerId: receipt.controlId,
+ clientSteerId: invocation.invocationId,
+ createdAt: receipt.createdAt,
+ },
+ responseMessageId: `${taskId}:assistant`,
+ conversationId: threadId,
+ },
+ new Date(receipt.updatedAt).toISOString(),
+ );
+ }
+ }
+ } catch (error) {
+ logger.warn(
+ '[subagentThreads] Failed to publish applied child guidance',
+ getSafeErrorMetadata(error),
+ );
+ }
return tracked;
}
@@ -1344,7 +1440,7 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
lease: TaskThreadLease,
threadId: string,
taskId: string,
- event: SubagentUpdateEvent,
+ event: SubagentActivityUpdateEvent,
): void {
if (lease.activityAdmissionClosed === true) return;
const boundedEvent = boundSubagentActivityUpdate(event);
@@ -1541,6 +1637,8 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
lease.running = true;
const detachedUsage: UsageMetadata[] = [];
let prepared: PreparedThread | undefined;
+ let appliedSteers: AppliedSubagentSteer[] | undefined = [];
+ const publicRecorder = new SubagentPublicRecorder();
let activityTerminal: SubagentActivityTerminalStatus = 'failed';
try {
if (runtime.signal.aborted) {
@@ -1629,24 +1727,154 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
),
});
}
+ let maxContentIndex = -1;
+ let contentOffset = 0;
+ const stepIndices = new Map<string, number>();
+ const slots = createContentAggregator();
+ let identity: Omit<
+ SubagentActivityUpdateEvent,
+ 'phase' | 'data' | 'label' | 'timestamp'
+ > = {
+ runId: request.parentRunId,
+ parentRunId: request.parentRunId,
+ subagentRunId: runtime.taskId,
+ parentToolCallId: request.parentToolCallId,
+ parentAgentId: request.parentAgentId,
+ subagentType: request.subagentType,
+ subagentKind: request.subagentKind,
+ subagentAgentId: request.subagentType,
+ };
+ const stamp = <T extends SubagentActivityUpdateEvent>(
+ event: T,
+ ): T & { activitySequence: number } => {
+ const sequence = activitySequence++;
+ return {
+ ...event,
+ activityEventId: `${runtime.taskId}:${sequence}`,
+ activitySequence: sequence,
+ };
+ };
+ // The SDK observes the envelope; host steering extends its phase union.
+ const forwardProgress = runtime.reportProgress as (
+ event: SubagentActivityUpdateEvent,
+ ) => void;
+ const publish = (
+ activityEvent: SubagentActivityUpdateEvent & { activitySequence: number },
+ ): void => {
+ forwardProgress(activityEvent);
+ const sequence = activityEvent.activitySequence;
+ lease.content?.record(activityEvent, sequence);
+ if (activityEvent.phase === 'steer_applied') {
+ publicRecorder.steer(activityEvent.data as TSteerAppliedEvent);
+ } else {
+ publicRecorder.record(activityEvent as SubagentUpdateEvent);
+ }
+ this.publishActivity(
+ lease,
+ preparedThread.conversation.conversationId,
+ runtime.taskId,
+ activityEvent,
+ );
+ };
+ lease.publishAppliedSteer = (data, timestamp) => {
+ if (appliedSteers != null) {
+ if (appliedSteers.length >= MAX_CONTROL_INVOCATIONS) {
+ appliedSteers = undefined;
+ } else {
+ appliedSteers.push({
+ steerId: data.steerId,
+ clientSteerId: data.clientSteerId!,
+ createdAt: data.part.createdAt!,
+ });
+ }
+ }
+ const index = ++maxContentIndex;
+ slots.contentParts[index] = { type: ContentTypes.STEER, steer: '' };
+ contentOffset++;
+ publish(
+ stamp({
+ ...identity,
+ phase: 'steer_applied',
+ data: { ...data, index },
+ timestamp,
+ }),
+ );
+ };
const activityRuntime: SubagentTaskRuntime = {
...runtime,
reportProgress: (event) => {
- const sequence = activitySequence++;
- const activityEvent: SubagentActivityUpdateEvent = {
- ...event,
- activityEventId: `${runtime.taskId}:${sequence}`,
- activitySequence: sequence,
- };
- lease.content?.record(activityEvent, sequence);
- runtime.reportProgress(activityEvent);
+ const {
+ phase: _phase,
+ data: _data,
+ label: _label,
+ timestamp: _timestamp,
+ ...metadata
+ } = event;
+ identity = metadata;
+ let normalized = event;
+ if (event.phase === 'run_step') {
+ const step = event.data as Agents.RunStep | undefined;
+ if (step != null && Number.isSafeInteger(step.index) && step.index >= 0) {
+ let index = stepIndices.get(step.id);
+ if (index == null) {
+ index = Math.max(step.index + contentOffset, maxContentIndex + 1);
+ stepIndices.set(step.id, index);
+ const width =
+ step.stepDetails.type === 'tool_calls'
+ ? Math.max(1, step.stepDetails.tool_calls?.length ?? 0)
+ : 1;
+ maxContentIndex = Math.max(maxContentIndex, index + width - 1);
+ }
+ normalized = { ...event, data: { ...step, index } };
+ // Reuse SDK slot allocation without retaining arguments, deltas or output.
+ slots.aggregateContent({
+ event: GraphEvents.ON_RUN_STEP,
+ data: {
+ id: step.id,
+ index,
+ stepDetails:
+ step.stepDetails.type === 'tool_calls'
+ ? {
+ type: 'tool_calls',
+ tool_calls: step.stepDetails.tool_calls?.map(({ id }) => ({
+ id,
+ name: 'tool',
+ args: {},
+ type: 'tool_call',
+ })),
+ }
+ : {
+ type: 'message_creation',
+ message_creation: { message_id: step.id },
+ },
+ } as Parameters<typeof slots.aggregateContent>[0]['data'],
+ });
+ }
+ }
+ if (event.phase === 'run_step_delta') {
+ const delta = event.data as Agents.RunStepDeltaEvent | undefined;
+ if (delta != null && slots.stepMap.has(delta.id)) {
+ slots.aggregateContent({
+ event: GraphEvents.ON_RUN_STEP_DELTA,
+ data: {
+ id: delta.id,
+ delta: {
+ type: 'tool_calls',
+ tool_calls: delta.delta.tool_calls?.map(({ id, index }) => ({
+ id,
+ index,
+ name: 'tool',
+ args: '',
+ })),
+ },
+ } as Parameters<typeof slots.aggregateContent>[0]['data'],
+ });
+ }
+ }
+ maxContentIndex = Math.max(maxContentIndex, slots.contentParts.length - 1);
+ const activityEvent = stamp(normalized);
recordActivity(recorder, activityEvent);
- this.publishActivity(
- lease,
- preparedThread.conversation.conversationId,
- runtime.taskId,
- activityEvent,
- );
+ publish(activityEvent);
},
};
const result = await runWithDetachedSubagentUsage(detachedUsage, () =>
@@ -1670,6 +1898,8 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
result,
detachedUsage,
lease.content?.throughSequence,
+ appliedSteers,
+ publicRecorder.snapshot(),
);
activityTerminal = 'completed';
return result;
@@ -1693,6 +1923,7 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
runtime.taskId,
detachedUsage,
lease.content?.throughSequence,
+ publicRecorder.snapshot(),
).catch((persistError) => {
logger.error(
'[subagentThreads] Failed to persist child-thread cancellation',
@@ -1721,6 +1952,7 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
error,
detachedUsage,
lease.content?.throughSequence,
+ publicRecorder.snapshot(),
).catch((persistError) => {
logger.error(
'[subagentThreads] Failed to persist child-thread failure',
@@ -1742,6 +1974,7 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
activityTerminal,
);
}
+ lease.publishAppliedSteer = undefined;
await this.stopAndReleaseSharedLease(scope, threadId, lease);
if (this.activeThreads.get(lockKey) === lease) {
this.activeThreads.delete(lockKey);
@@ -2211,6 +2444,7 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
invocationId,
fingerprint,
command: boundedControlCommand(command),
+ ...('message' in command ? { pendingMessage: command.message } : {}),
commandMessageTruncated:
'message' in command && command.message.length > MAX_DURABLE_CONTROL_MESSAGE_CHARS,
result,
@@ -3431,32 +3665,50 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
result: { content: string; messages?: BaseMessage[] },
detachedUsage: UsageMetadata[],
contentThroughSequence?: number,
+ appliedSteers?: readonly AppliedSubagentSteer[],
+ observedActivity?: ReturnType<SubagentPublicRecorder['snapshot']>,
): Promise<void> {
if (prepared.userMessageId == null) {
throw new Error('The child-thread input was not prepared.');
}
await this.flushControlReceiptsForSettlement(request.scopeId, taskId);
+ const transcriptObservation = { steersMatched: false };
const subagentTranscript = serializeTranscript(
taskId,
prepared.initialStoredMessages,
result.messages,
+ appliedSteers,
+ request.input,
+ transcriptObservation,
);
- const activityProjection =
+ const sourceProjection =
subagentTranscript == null
? undefined
: projectSubagentActivity(
subagentTranscript.messagesJson,
subagentTranscript.mode,
request.input,
+ appliedSteers,
);
+ // A complete transcript is richer than a bounded observation window. Missing
+ // applied controls make it incomplete even when its JSON is otherwise valid.
+ const sourceTrusted =
+ sourceProjection != null &&
+ transcriptObservation.steersMatched &&
+ (sourceProjection.activity.length > 0 || !sourceProjection.truncated);
+ const activityProjection = sourceTrusted
+ ? sourceProjection
+ : (observedActivity ?? sourceProjection);
const subagentActivityProjection =
activityProjection == null
? undefined
: {
taskId,
- version: 1 as const,
+ version: 2 as const,
activityJson: JSON.stringify(activityProjection.activity),
- truncated: activityProjection.truncated,
+ truncated:
+ activityProjection.truncated ||
+ (!sourceTrusted && activityProjection.activity.length === 0),
};
const conversation = await this.requireCurrentConversation(
scope,
@@ -3509,6 +3761,7 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
error: unknown,
detachedUsage: UsageMetadata[],
contentThroughSequence?: number,
+ observedActivity?: ReturnType<SubagentPublicRecorder['snapshot']>,
): Promise<void> {
await this.flushControlReceiptsForSettlement(request.scopeId, taskId);
const conversation = await this.currentConversation(scope, request, threadId);
@@ -3533,6 +3786,15 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
subagentContent: { version: 1 as const, throughSequence: contentThroughSequence },
}),
error: true,
+ subagentActivityProjection: {
+ taskId,
+ version: 2 as const,
+ activityJson: JSON.stringify(observedActivity?.activity ?? []),
+ truncated:
+ observedActivity == null ||
+ observedActivity.truncated ||
+ observedActivity.activity.length === 0,
+ },
subagentTask: {
attemptKey: createSubagentAttemptKey(request.scopeId, request.idempotencyKey),
parentRunId: request.parentRunId,
@@ -3588,6 +3850,7 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
taskId: string,
detachedUsage: UsageMetadata[],
contentThroughSequence?: number,
+ observedActivity?: ReturnType<SubagentPublicRecorder['snapshot']>,
): Promise<void> {
await this.flushControlReceiptsForSettlement(request.scopeId, taskId);
const conversation = await this.currentConversation(scope, request, threadId);
@@ -3611,6 +3874,15 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
: {
subagentContent: { version: 1 as const, throughSequence: contentThroughSequence },
}),
+ subagentActivityProjection: {
+ taskId,
+ version: 2 as const,
+ activityJson: JSON.stringify(observedActivity?.activity ?? []),
+ truncated:
+ observedActivity == null ||
+ observedActivity.truncated ||
+ observedActivity.activity.length === 0,
+ },
subagentTask: {
attemptKey: createSubagentAttemptKey(request.scopeId, request.idempotencyKey),
parentRunId: request.parentRunId,
diff --git a/packages/api/src/agents/view.spec.ts b/packages/api/src/agents/view.spec.ts
index cbcb43c04a..b32f3ee4be 100644
--- a/packages/api/src/agents/view.spec.ts
+++ b/packages/api/src/agents/view.spec.ts
@@ -87,6 +87,75 @@ const createRequest = (
}) as ServerRequest;
describe('subagent thread parent-scoped view', () => {
+ it('preserves every accepted identity and withdrawal target while budgeting Unicode message bodies', async () => {
+ const input = message('task-1:user', 'running', true);
+ input.subagentTask!.controlReceipts = Array.from({ length: 8 }, (_, index) => ({
+ invocationId: `pending-${index}`,
+ fingerprint: 'private',
+ controlId: `withdraw-${index}`,
+ action: 'queue',
+ status: 'accepted',
+ createdAt: new Date('2026-10-23T00:00:00Z'),
+ updatedAt: new Date('2026-10-23T00:00:01Z'),
+ message: '界'.repeat(4096),
+ }));
+ const handler = createSubagentThreadViewHandler({
+ getConvoOwnership: jest.fn().mockResolvedValue(parent),
+ getSubagentThreadForParent: jest.fn().mockResolvedValue(child),
+ getMessagesForSubagentThreadView: jest.fn().mockResolvedValue([input]),
+ });
+ const { response, json } = createResponse();
+ await handler(createRequest({}, { taskId: 'task-1' }), response);
+ const body = json.mock.calls[0][0];
+ expect(body.controlReceipts.map((receipt: { controlId: string }) => receipt.controlId)).toEqual(
+ Array.from({ length: 8 }, (_, index) => `withdraw-${index}`),
+ );
+ expect(
+ body.controlReceipts.some(
+ (receipt: { messageTruncated?: boolean }) => receipt.messageTruncated,
+ ),
+ ).toBe(true);
+ expect(body.controlReceiptsTruncated).not.toBe(true);
+ expect(Buffer.byteLength(JSON.stringify(body), 'utf8')).toBeLessThanOrEqual(
+ SUBAGENT_THREAD_VIEW_LIMITS.responseBytes,
+ );
+ });
+
+ it('keeps complete stored Unicode control messages and omits whole old receipts to fit the budget', async () => {
+ const input = message('task-1:user', 'running', true);
+ input.subagentTask!.controlReceipts = Array.from({ length: 32 }, (_, index) => ({
+ invocationId: `full-${index}`,
+ fingerprint: 'private',
+ controlId: `control-${index}`,
+ action: 'steer',
+ status: 'applied',
+ createdAt: new Date('2026-10-23T00:00:00Z'),
+ updatedAt: new Date('2026-10-23T00:00:01Z'),
+ message: '🧭'.repeat(2048),
+ }));
+ const handler = createSubagentThreadViewHandler({
+ getConvoOwnership: jest.fn().mockResolvedValue(parent),
+ getSubagentThreadForParent: jest.fn().mockResolvedValue(child),
+ getMessagesForSubagentThreadView: jest
+ .fn()
+ .mockResolvedValue([message('task-1:assistant', 'completed'), input]),
+ });
+ const { response, json } = createResponse();
+ await handler(createRequest({}, { taskId: 'task-1' }), response);
+ const body = json.mock.calls[0][0];
+ expect(body.controlReceipts.length).toBeGreaterThan(0);
+ expect(body.controlReceipts.length).toBeLessThan(32);
+ expect(body.controlReceiptsTruncated).toBe(true);
+ expect(body.controlReceipts.at(-1).invocationId).toBe('full-31');
+ for (const receipt of body.controlReceipts) {
+ expect(receipt.message).toBe('🧭'.repeat(2048));
+ expect(receipt.messageTruncated).not.toBe(true);
+ }
+ expect(Buffer.byteLength(JSON.stringify(body), 'utf8')).toBeLessThanOrEqual(
+ SUBAGENT_THREAD_VIEW_LIMITS.responseBytes,
+ );
+ });
+
it.each([
[false, true, false],
[true, false, true],
@@ -482,7 +551,6 @@ describe('subagent thread parent-scoped view', () => {
action: 'steer',
status: 'applied',
boundary: 'tool',
- messageTruncated: true,
}),
]),
);
@@ -490,13 +558,119 @@ describe('subagent thread parent-scoped view', () => {
(receipt: { invocationId: string }) => receipt.invocationId === 'invocation-1',
);
expect(projected).toBeDefined();
- expect(Buffer.byteLength(projected?.message ?? '', 'utf8')).toBeLessThanOrEqual(512);
+ expect(projected?.message).toBe('x'.repeat(1_000));
+ expect(projected?.messageTruncated).not.toBe(true);
expect(view.controlReceipts).toHaveLength(32);
expect(view.controlReceiptsTruncated).toBe(true);
expect(JSON.stringify(view)).not.toContain('private-reservation');
expect(JSON.stringify(view)).not.toContain('private-fingerprint');
});
+ it.each([
+ 'truncated input',
+ 'missing input',
+ 'mismatched boundary',
+ 'malformed source',
+ 'other task',
+ 'earlier steer only',
+ ] as const)(
+ 'preserves usable legacy activity with %s instead of an unsafe reconstruction',
+ async (condition) => {
+ const input = message('task-1:user', 'running', true);
+ if (condition === 'truncated input')
+ Object.assign(input, {
+ text: 'Long current task. '.repeat(575).slice(0, 8192),
+ textProjectionTruncated: true,
+ });
+ const activity = [
+ { type: 'reasoning', text: 'Retained current reasoning.' },
+ { type: 'writing', text: 'Retained current activity.' },
+ ];
+ const transcript = [
+ { type: 'human', data: { content: 'Previous task.' } },
+ {
+ type: 'human',
+ data: {
+ content: 'Previous guidance.',
+ additional_kwargs: { injected: true, source: 'steer' },
+ },
+ },
+ { type: 'ai', data: { content: 'Private previous activity.' } },
+ {
+ type: 'human',
+ data: { content: condition === 'mismatched boundary' ? 'Other prompt.' : input.text },
+ },
+ { type: 'ai', data: { content: 'Current reconstructed activity.' } },
+ ];
+ const selected = {
+ ...message('task-1:assistant', 'completed'),
+ subagentActivityProjectionJson: JSON.stringify(activity),
+ subagentTranscript: {
+ taskId: condition === 'other task' ? 'task-other' : 'task-1',
+ mode: 'replace' as const,
+ messagesJson: condition === 'malformed source' ? 'not-json' : JSON.stringify(transcript),
+ },
+ };
+ const handler = createSubagentThreadViewHandler({
+ getConvoOwnership: jest.fn().mockResolvedValue(parent),
+ getSubagentThreadForParent: jest
+ .fn()
+ .mockResolvedValue({ ...child, subagentThreadLease: undefined }),
+ getMessagesForSubagentThreadView: jest
+ .fn()
+ .mockResolvedValue(condition === 'missing input' ? [selected] : [selected, input]),
+ });
+ const { response, json } = createResponse();
+ await handler(createRequest({}, { taskId: 'task-1' }), response);
+ expect(json.mock.calls[0][0]).toMatchObject({ activity, activityTruncated: false });
+ expect(JSON.stringify(json.mock.calls[0][0])).not.toContain('Private previous activity.');
+ },
+ );
+
+ it('reprojects legacy activity only when current-task guidance has a safe transcript boundary', async () => {
+ const selected = {
+ ...message('task-1:assistant', 'completed'),
+ subagentActivityProjectionJson: JSON.stringify([
+ { type: 'writing', text: 'Old projection without guidance.' },
+ ]),
+ subagentTranscript: {
+ taskId: 'task-1',
+ mode: 'replace' as const,
+ messagesJson: JSON.stringify([
+ { type: 'human', data: { content: 'Previous task.' } },
+ { type: 'ai', data: { content: 'Private previous activity.' } },
+ { type: 'human', data: { content: 'Investigate this.' } },
+ { type: 'ai', data: { content: 'Before guidance.' } },
+ {
+ type: 'human',
+ data: {
+ content: 'Current guidance.',
+ additional_kwargs: { injected: true, source: 'steer' },
+ },
+ },
+ { type: 'ai', data: { content: 'After guidance.' } },
+ ]),
+ },
+ };
+ const handler = createSubagentThreadViewHandler({
+ getConvoOwnership: jest.fn().mockResolvedValue(parent),
+ getSubagentThreadForParent: jest
+ .fn()
+ .mockResolvedValue({ ...child, subagentThreadLease: undefined }),
+ getMessagesForSubagentThreadView: jest
+ .fn()
+ .mockResolvedValue([selected, message('task-1:user', 'running', true)]),
+ });
+ const { response, json } = createResponse();
+ await handler(createRequest({}, { taskId: 'task-1' }), response);
+ expect(json.mock.calls[0][0].activity).toEqual([
+ { type: 'writing', text: 'Before guidance.' },
+ { type: 'steer', steer: 'Current guidance.' },
+ { type: 'writing', text: 'After guidance.' },
+ ]);
+ expect(JSON.stringify(json.mock.calls[0][0])).not.toContain('Private previous activity.');
+ });
+
it('fences replacement activity to the exact selected task input', async () => {
const selected = {
...message('task-1:assistant', 'completed'),
diff --git a/packages/api/src/agents/view.ts b/packages/api/src/agents/view.ts
index dc6449523a..5ee6b9e37d 100644
--- a/packages/api/src/agents/view.ts
+++ b/packages/api/src/agents/view.ts
@@ -38,7 +38,7 @@ const MAX_PARENT_CHILDREN = 64;
const MAX_PARENT_TASKS_PER_CHILD = 20;
const MAX_PARENT_INDEX_BYTES = 96 * 1024;
const MAX_PUBLIC_CONTROL_RECEIPTS = 32;
-const MAX_PUBLIC_CONTROL_MESSAGE_BYTES = 512;
+const MAX_PUBLIC_CONTROL_BYTES = MAX_RESPONSE_BYTES / 4;
type SubagentThreadViewDependencies = Pick<
ConversationMethods,
'getConvoOwnership' | 'getSubagentThreadForParent'
@@ -154,10 +154,6 @@ const publicControlReceipts = (
const retained = [...accepted, ...(terminalLimit === 0 ? [] : terminal.slice(-terminalLimit))]
.slice(0, MAX_PUBLIC_CONTROL_RECEIPTS)
.map((receipt) => {
- const message =
- receipt.message == null
- ? undefined
- : truncateUtf8(receipt.message, MAX_PUBLIC_CONTROL_MESSAGE_BYTES);
return {
invocationId: truncateUtf8(receipt.invocationId, MAX_PUBLIC_ID_BYTES).text,
...(receipt.controlId == null
@@ -171,12 +167,32 @@ const publicControlReceipts = (
...(receipt.reason == null
? {}
: { reason: truncateUtf8(receipt.reason, MAX_PUBLIC_ID_BYTES).text }),
- ...(message == null ? {} : { message: message.text }),
- ...(receipt.messageTruncated === true || message?.truncated === true
- ? { messageTruncated: true }
- : {}),
+ ...(receipt.message == null ? {} : { message: receipt.message }),
+ ...(receipt.messageTruncated === true ? { messageTruncated: true } : {}),
};
});
+ // Keep pending identities actionable. Budgeted pending bodies hydrate on expansion.
+ let bytes = Buffer.byteLength(JSON.stringify(retained), 'utf8');
+ while (bytes > MAX_PUBLIC_CONTROL_BYTES && retained.length > 0) {
+ let index = retained.findIndex((receipt) => receipt.status !== 'accepted');
+ if (index >= 0) {
+ const removed = retained.splice(index, 1)[0];
+ bytes -= Buffer.byteLength(JSON.stringify(removed), 'utf8') + 1;
+ continue;
+ }
+ index = retained.findIndex(
+ (receipt) => receipt.message != null && Buffer.byteLength(receipt.message, 'utf8') > 512,
+ );
+ if (index < 0) break;
+ const receipt = retained[index];
+ const before = Buffer.byteLength(JSON.stringify(receipt), 'utf8');
+ retained[index] = {
+ ...receipt,
+ message: truncateUtf8(receipt.message!, 512).text,
+ messageTruncated: true,
+ };
+ bytes += Buffer.byteLength(JSON.stringify(retained[index]), 'utf8') - before;
+ }
return {
receipts: retained,
truncated:
@@ -268,6 +284,18 @@ const projectedTaskActivity = (
taskId: string,
): ReturnType<typeof projectSubagentActivity> => {
if (assistant?.subagentActivityProjectionJson != null) {
+ const transcript = assistant.subagentTranscript;
+ if (
+ transcript?.taskId === taskId &&
+ (transcript.mode === 'append' || (input != null && input.textProjectionTruncated !== true))
+ ) {
+ const restored = projectSubagentActivity(
+ transcript.messagesJson,
+ transcript.mode,
+ input?.textProjectionTruncated === true ? undefined : input?.text,
+ );
+ if (restored.activity.some((item) => item.type === 'steer')) return restored;
+ }
return projectPersistedMessageActivityJson(
assistant.subagentActivityProjectionJson,
assistant.subagentActivityProjectionTruncated === true,
diff --git a/packages/chat/src/components/CollapsibleText.tsx b/packages/chat/src/components/CollapsibleText.tsx
index 827697a5ee..7f45cae570 100644
--- a/packages/chat/src/components/CollapsibleText.tsx
+++ b/packages/chat/src/components/CollapsibleText.tsx
@@ -5,6 +5,8 @@ import type { ReactNode, NamedExoticComponent } from 'react';
type CollapsibleTextProps = {
enabled: boolean;
+ hasMore?: boolean;
+ onExpand?: () => void;
children: ReactNode;
};
@@ -26,6 +28,8 @@ const OVERFLOW_TOLERANCE = 8;
*/
const CollapsibleText: NamedExoticComponent<CollapsibleTextProps> = memo(function CollapsibleText({
enabled,
+ hasMore = false,
+ onExpand,
children,
}: CollapsibleTextProps) {
const localize = useLocalize();
@@ -88,6 +92,7 @@ const CollapsibleText: NamedExoticComponent<CollapsibleTextProps> = memo(functio
const boundary = event.currentTarget.getBoundingClientRect().top + collapsedMaxHeight;
if (target.getBoundingClientRect().bottom > boundary) {
setExpanded(true);
+ onExpand?.();
}
};
@@ -109,12 +114,15 @@ const CollapsibleText: NamedExoticComponent<CollapsibleTextProps> = memo(functio
/>
)}
</div>
- {overflowing && (
+ {(overflowing || hasMore) && (
<Button
type="button"
variant="link"
size="bare"
- onClick={() => setExpanded((prev) => !prev)}
+ onClick={() => {
+ if (!expanded) onExpand?.();
+ setExpanded((prev) => !prev);
+ }}
aria-expanded={expanded}
aria-controls={contentId}
className="mt-1 gap-1 text-xs"
diff --git a/packages/chat/src/components/__tests__/CollapsibleText.spec.tsx b/packages/chat/src/components/__tests__/CollapsibleText.spec.tsx
index 6b9732677f..2fccab3838 100644
--- a/packages/chat/src/components/__tests__/CollapsibleText.spec.tsx
+++ b/packages/chat/src/components/__tests__/CollapsibleText.spec.tsx
@@ -308,3 +308,27 @@ describe('CollapsibleText', () => {
}
});
});
+
+it('uses the same expansion control for a server-budgeted body and requests it only on reveal', () => {
+ const reveal = jest.fn();
+ const scroll = stubScrollHeight(100);
+ try {
+ const { rerender } = render(
+ <CollapsibleText enabled hasMore onExpand={reveal}>
+ <p>Retained prefix</p>
+ </CollapsibleText>,
+ );
+ expect(reveal).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_show_more' }));
+ expect(reveal).toHaveBeenCalledTimes(1);
+ rerender(
+ <CollapsibleText enabled onExpand={reveal}>
+ <p>Complete retained body</p>
+ </CollapsibleText>,
+ );
+ expect(screen.getByText('Complete retained body')).toBeInTheDocument();
+ expect(screen.queryByRole('button')).toBeNull();
+ } finally {
+ scroll.mockRestore();
+ }
+});
diff --git a/packages/data-provider/src/api-endpoints.ts b/packages/data-provider/src/api-endpoints.ts
index 8aa7b0b4d7..68fa7891fd 100644
--- a/packages/data-provider/src/api-endpoints.ts
+++ b/packages/data-provider/src/api-endpoints.ts
@@ -186,6 +186,14 @@ export const subagentTaskContent = (
export const subagentControl = (parentConversationId: string, threadId: string) =>
`${conversationsRoot}/${encodeURIComponent(parentConversationId)}/subagents/${encodeURIComponent(threadId)}/control`;
+export const subagentControlReceipt = (
+ parentConversationId: string,
+ threadId: string,
+ taskId: string,
+ invocationId: string,
+) =>
+ `${parentSubagents(parentConversationId)}/${encodeURIComponent(threadId)}/tasks/${encodeURIComponent(taskId)}/controls/${encodeURIComponent(invocationId)}`;
+
export const backgroundTasks = (conversationId: string) =>
`${conversationsRoot}/${encodeURIComponent(conversationId)}/background-tasks`;
diff --git a/packages/data-provider/src/data-service.ts b/packages/data-provider/src/data-service.ts
index 30d11388a0..a6e18531d2 100644
--- a/packages/data-provider/src/data-service.ts
+++ b/packages/data-provider/src/data-service.ts
@@ -1244,6 +1244,17 @@ export function getSubagentTaskContent(
);
}
+export function getSubagentControlReceipt(
+ parentConversationId: string,
+ threadId: string,
+ taskId: string,
+ invocationId: string,
+): Promise<t.SubagentControlResponse> {
+ return request.get(
+ endpoints.subagentControlReceipt(parentConversationId, threadId, taskId, invocationId),
+ );
+}
+
export function controlSubagentTask(
parentConversationId: string,
threadId: string,
diff --git a/packages/data-provider/src/keys.ts b/packages/data-provider/src/keys.ts
index b76b0c3951..c960b0772c 100644
--- a/packages/data-provider/src/keys.ts
+++ b/packages/data-provider/src/keys.ts
@@ -110,6 +110,7 @@ export enum QueryKeys {
parentSubagents = 'parentSubagents',
subagentThread = 'subagentThread',
subagentTaskContent = 'subagentTaskContent',
+ subagentControlReceipt = 'subagentControlReceipt',
backgroundTasks = 'backgroundTasks',
conversationPullRequest = 'conversationPullRequest',
pullRequestConnection = 'pullRequestConnection',
diff --git a/packages/data-provider/src/types/runs.ts b/packages/data-provider/src/types/runs.ts
index f5358d4654..8ee3a83c8f 100644
--- a/packages/data-provider/src/types/runs.ts
+++ b/packages/data-provider/src/types/runs.ts
@@ -540,7 +540,7 @@ export const reconcileContextUsageFromEvent = (
cacheWrite: finiteNonNegativeInteger(event.input_token_details?.cache_creation) ?? 0,
});
-/** Lifecycle phase carried on subagent-progress envelopes (mirrors SDK SubagentUpdatePhase). */
+/** SDK lifecycle phases plus host-authored applied-guidance boundaries. */
export type SubagentUpdatePhase =
| 'start'
| 'run_step'
@@ -552,7 +552,8 @@ export type SubagentUpdatePhase =
| 'message_delta'
| 'reasoning_delta'
| 'stop'
- | 'error';
+ | 'error'
+ | 'steer_applied';
/** Structured root-to-leaf identity for one nested subagent execution. */
export interface SubagentAncestryEntry {
diff --git a/packages/data-provider/src/types/subagents.ts b/packages/data-provider/src/types/subagents.ts
index d32a8f8c48..ed5dee0d50 100644
--- a/packages/data-provider/src/types/subagents.ts
+++ b/packages/data-provider/src/types/subagents.ts
@@ -1,6 +1,6 @@
+import type { StepEvents, SteerEvents, TSteerAppliedEvent } from './runs';
import type { TMessageContentParts } from './content';
import type { ChatStepFrame } from './transport';
-import type { StepEvents } from './runs';
import type { Agents } from './agents';
export type SubagentThreadStatus =
@@ -52,6 +52,14 @@ export type ParentSubagentIndex = {
* or durable records that produced it.
*/
export type SubagentActivityItem =
+ | {
+ type: 'steer';
+ steer: string;
+ steerId?: string;
+ clientSteerId?: string;
+ createdAt?: number;
+ textTruncated?: boolean;
+ }
| {
type: 'writing';
text: string;
@@ -251,6 +259,7 @@ export type SubagentDigest = {
/** Public graph events only. Never a private model transcript or tool execution request. */
export type SubagentContentFrame =
+ | { event: SteerEvents.ON_STEER_APPLIED; data: TSteerAppliedEvent }
| Extract<
ChatStepFrame,
{
diff --git a/packages/data-schemas/src/methods/message.spec.ts b/packages/data-schemas/src/methods/message.spec.ts
index 54ffb4beff..bf9133e625 100644
--- a/packages/data-schemas/src/methods/message.spec.ts
+++ b/packages/data-schemas/src/methods/message.spec.ts
@@ -3643,8 +3643,8 @@ describe('Message Operations', () => {
),
);
for (const receipt of message.subagentTask?.controlReceipts ?? []) {
- expect(Buffer.byteLength(receipt.message ?? '', 'utf8')).toBeLessThanOrEqual(512);
- expect(receipt.messageTruncated).toBe(true);
+ expect(receipt.message).toHaveLength(4_096);
+ expect(receipt.messageTruncated).not.toBe(true);
expect(receipt).not.toHaveProperty('fingerprint');
}
expect(message.subagentTask).not.toHaveProperty('attemptKey');
@@ -3761,6 +3761,113 @@ describe('Message Operations', () => {
expect(messages[0].subagentTranscriptProjectionTruncated).toBe(true);
});
+ it.each([1, 2] as const)(
+ 'uses projection version %s with steering-aware legacy catch-up',
+ async (version) => {
+ const conversationId = uuidv4();
+ const transcript = JSON.stringify([
+ { type: 'human', data: { content: 'Initial task' } },
+ { type: 'ai', data: { content: 'Before guidance' } },
+ {
+ type: 'human',
+ data: { content: 'Guidance', additional_kwargs: { injected: true, source: 'steer' } },
+ },
+ { type: 'ai', data: { content: 'After guidance' } },
+ ]);
+ const projection = JSON.stringify([
+ { type: 'writing', text: 'Earlier incomplete projection' },
+ ]);
+ await saveMessage(mockCtx, {
+ messageId: 'task-steering:assistant',
+ conversationId,
+ user: 'user123',
+ text: 'Final',
+ subagentTranscript: {
+ taskId: 'task-steering',
+ mode: 'replace',
+ messagesJson: transcript,
+ },
+ subagentActivityProjection: {
+ taskId: 'task-steering',
+ version,
+ activityJson: projection,
+ truncated: false,
+ },
+ });
+ const [message] = await getMessagesForSubagentThreadView({
+ user: 'user123',
+ conversationId,
+ selectedTaskId: 'task-steering',
+ limit: 1,
+ textCodePointLimit: 8192,
+ });
+ if (version === 1) {
+ expect(message.subagentTranscript?.messagesJson).toBe(transcript);
+ expect(message.subagentActivityProjectionJson).toBe(projection);
+ } else {
+ expect(message.subagentActivityProjectionJson).toBe(projection);
+ expect(message.subagentTranscript).toBeUndefined();
+ }
+ },
+ );
+
+ it.each([undefined, 'task-long'] as const)(
+ 'retains the legacy fallback beside bounded steering history with selected task %s',
+ async (selectedTaskId) => {
+ const conversationId = uuidv4();
+ const prompt = 'Long current task. '.repeat(575);
+ const projection = JSON.stringify([
+ { type: 'reasoning', text: 'Retained current reasoning.' },
+ { type: 'writing', text: 'Retained current activity.' },
+ ]);
+ const transcript = JSON.stringify([
+ { type: 'human', data: { content: 'Previous task.' } },
+ {
+ type: 'human',
+ data: {
+ content: 'Previous guidance.',
+ additional_kwargs: { injected: true, source: 'steer' },
+ },
+ },
+ { type: 'human', data: { content: prompt } },
+ { type: 'ai', data: { content: 'Current activity.' } },
+ ]);
+ await saveMessage(mockCtx, {
+ messageId: 'task-long:user',
+ conversationId,
+ user: 'user123',
+ text: prompt,
+ isCreatedByUser: true,
+ });
+ await saveMessage(mockCtx, {
+ messageId: 'task-long:assistant',
+ parentMessageId: 'task-long:user',
+ conversationId,
+ user: 'user123',
+ text: 'Result',
+ subagentTranscript: { taskId: 'task-long', mode: 'replace', messagesJson: transcript },
+ subagentActivityProjection: {
+ taskId: 'task-long',
+ version: 1,
+ activityJson: projection,
+ truncated: false,
+ },
+ });
+ const records = await getMessagesForSubagentThreadView({
+ user: 'user123',
+ conversationId,
+ selectedTaskId,
+ limit: 3,
+ textCodePointLimit: 8192,
+ });
+ const input = records.find((message) => message.messageId === 'task-long:user');
+ const assistant = records.find((message) => message.messageId === 'task-long:assistant');
+ expect(input?.textProjectionTruncated).toBe(true);
+ expect(assistant?.subagentActivityProjectionJson).toBe(projection);
+ expect(assistant?.subagentTranscript?.messagesJson).toBe(transcript);
+ },
+ );
+
it('prefers the bounded settlement projection without materializing its private transcript', async () => {
const conversationId = uuidv4();
await saveMessage(mockCtx, {
@@ -5079,6 +5186,39 @@ describe('Message Operations', () => {
});
};
+ it('keeps expired receipt replay private while denying public body reads', async () => {
+ const conversationId = uuidv4();
+ await createTaskInput(conversationId);
+ await recordSubagentTaskControlReceipt({
+ userId: 'user123',
+ conversationId,
+ taskId: 'task-1',
+ receipt: {
+ invocationId: 'expired-read',
+ fingerprint: 'private',
+ controlId: 'control',
+ action: 'steer',
+ status: 'accepted',
+ message: 'retained body',
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ },
+ });
+ const identity = {
+ userId: 'user123',
+ conversationId,
+ taskId: 'task-1',
+ invocationId: 'expired-read',
+ };
+ expect(await getSubagentTaskControlReceipt({ ...identity, activeOnly: true })).not.toBeNull();
+ await Message.updateOne(
+ { user: 'user123', conversationId, messageId: 'task-1:user' },
+ { $set: { expiredAt: new Date(Date.now() - 1000) } },
+ );
+ expect(await getSubagentTaskControlReceipt({ ...identity, activeOnly: true })).toBeNull();
+ expect(await getSubagentTaskControlReceipt(identity)).not.toBeNull();
+ });
+
it('advances one invocation monotonically and enforces ownership', async () => {
const conversationId = uuidv4();
await createTaskInput(conversationId);
diff --git a/packages/data-schemas/src/methods/message.ts b/packages/data-schemas/src/methods/message.ts
index beac043578..dcc062e3c2 100644
--- a/packages/data-schemas/src/methods/message.ts
+++ b/packages/data-schemas/src/methods/message.ts
@@ -809,6 +809,7 @@ export interface MessageMethods {
taskId: string;
invocationId: string;
tenantId?: string;
+ activeOnly?: boolean;
}): Promise<NonNullable<NonNullable<IMessage['subagentTask']>['controlReceipts']>[number] | null>;
getSubagentTaskControlReplay(input: {
userId: string;
@@ -2662,12 +2663,14 @@ export function createMessageMethods(
taskId,
invocationId,
tenantId,
+ activeOnly = false,
}: {
userId: string;
conversationId: string;
taskId: string;
invocationId: string;
tenantId?: string;
+ activeOnly?: boolean;
}): Promise<StoredSubagentControlReceipt | null> {
if (
userId.length === 0 ||
@@ -2682,6 +2685,7 @@ export function createMessageMethods(
}
const Message = mongoose.models.Message as Model<IMessage>;
const input = await Message.findOne({
+ ...(activeOnly ? activeExpirationFilter<IMessage>() : {}),
user: userId,
conversationId,
...(tenantId == null ? { tenantId: { $exists: false } } : { tenantId }),
@@ -3017,7 +3021,10 @@ export function createMessageMethods(
};
const activityProjectionAvailable = {
$and: [
- { $eq: ['$subagentActivityProjection.version', 1] },
+ { $in: ['$subagentActivityProjection.version', [1, 2]] },
+ {
+ $eq: ['$messageId', { $concat: ['$subagentActivityProjection.taskId', ':assistant'] }],
+ },
'$_subagentActivityProjectionSourceIsString',
{
$lte: [
@@ -3030,11 +3037,31 @@ export function createMessageMethods(
const transcriptAvailable = {
$and: [
'$_subagentTranscriptSourceIsString',
+ { $eq: ['$messageId', { $concat: ['$subagentTranscript.taskId', ':assistant'] }] },
{
$lte: ['$_subagentTranscriptSourceBytes', SUBAGENT_TRANSCRIPT_SOURCE_BYTE_LIMIT],
},
],
};
+ // Legacy reprojection is optional: retain the usable projection until the
+ // API validates the current input boundary against the bounded transcript.
+ const legacySteeringTranscriptAvailable = {
+ $and: [
+ { $eq: ['$subagentActivityProjection.version', 1] },
+ {
+ $cond: [
+ transcriptAvailable,
+ {
+ $gte: [
+ { $indexOfBytes: ['$subagentTranscript.messagesJson', '"source":"steer"'] },
+ 0,
+ ],
+ },
+ false,
+ ],
+ },
+ ],
+ };
const boundedString = (path: string, codePointLimit: number) => ({
$substrCP: [
{
@@ -3093,17 +3120,14 @@ export function createMessageMethods(
message: {
$cond: [
{ $eq: [{ $type: '$$receipt.message' }, 'string'] },
- boundedString('$$receipt.message', SUBAGENT_VIEW_CONTROL_STRING_CODE_POINT_LIMIT),
+ boundedString('$$receipt.message', MAX_SUBAGENT_CONTROL_MESSAGE_LENGTH),
null,
],
},
messageTruncated: {
$or: [
{ $eq: ['$$receipt.messageTruncated', true] },
- stringProjectionTruncated(
- '$$receipt.message',
- SUBAGENT_VIEW_CONTROL_STRING_CODE_POINT_LIMIT,
- ),
+ stringProjectionTruncated('$$receipt.message', MAX_SUBAGENT_CONTROL_MESSAGE_LENGTH),
],
},
};
@@ -3566,13 +3590,23 @@ export function createMessageMethods(
},
subagentTranscript: {
$cond: [
- activityProjectionAvailable,
- null,
+ {
+ $and: [
+ transcriptAvailable,
+ {
+ $or: [
+ { $eq: [activityProjectionAvailable, false] },
+ legacySteeringTranscriptAvailable,
+ ],
+ },
+ ],
+ },
{
taskId: '$subagentTranscript.taskId',
mode: '$subagentTranscript.mode',
messagesJson: '$subagentTranscript.messagesJson',
},
+ null,
],
},
};
@@ -3777,6 +3811,9 @@ export function createMessageMethods(
return {
...projected,
subagentActivityProjectionJson: source.subagentActivityProjectionJson,
+ ...(source.subagentTranscript == null
+ ? {}
+ : { subagentTranscript: source.subagentTranscript }),
...(source.subagentActivityProjectionTruncated === true
? { subagentActivityProjectionTruncated: true }
: {}),
diff --git a/packages/data-schemas/src/schema/message.ts b/packages/data-schemas/src/schema/message.ts
index 4a00eab9d8..45484f270e 100644
--- a/packages/data-schemas/src/schema/message.ts
+++ b/packages/data-schemas/src/schema/message.ts
@@ -175,7 +175,7 @@ const messageSchema: Schema<IMessage> = new Schema(
subagentActivityProjection: {
type: {
taskId: { type: String, required: true },
- version: { type: Number, enum: [1], required: true },
+ version: { type: Number, enum: [1, 2], required: true },
activityJson: { type: String, required: true },
truncated: { type: Boolean, required: true },
},
diff --git a/packages/data-schemas/src/types/message.ts b/packages/data-schemas/src/types/message.ts
index 84e9eea0b2..bbb9238d3e 100644
--- a/packages/data-schemas/src/types/message.ts
+++ b/packages/data-schemas/src/types/message.ts
@@ -108,7 +108,7 @@ export interface IMessage extends Document {
/** Server-private bounded rendering projection derived once at child settlement. */
subagentActivityProjection?: {
taskId: string;
- version: 1;
+ version: 1 | 2;
activityJson: string;
truncated: boolean;
};