Skip to content

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

📇 feat: Surface Event Child Activity Through a Bounded Parent Index (#15142)

Danny Avilafc2b8584c402
diff --git a/api/server/controllers/agents/__tests__/callbacks.spec.js b/api/server/controllers/agents/__tests__/callbacks.spec.js
index 9b1f3b6eb7..4eeff29642 100644
--- a/api/server/controllers/agents/__tests__/callbacks.spec.js
+++ b/api/server/controllers/agents/__tests__/callbacks.spec.js
@@ -124,6 +124,76 @@ describe('resumable event generation fencing', () => {
);
});
+ it('publishes root event-child progress through the child activity transport', async () => {
+ const { nanoid } = require('nanoid');
+ nanoid.mockReturnValueOnce('invocation-1').mockReturnValueOnce('invocation-2');
+ const { GraphEvents } = jest.requireActual('@librechat/agents');
+ const { getDefaultHandlers } = require('../callbacks');
+ const publish = jest.fn().mockResolvedValue(undefined);
+ const data = {
+ id: 'step-1',
+ index: 0,
+ stepDetails: { type: 'message_creation' },
+ };
+ const handlers = getDefaultHandlers({
+ res: { write: jest.fn() },
+ aggregateContent: jest.fn(),
+ toolEndCallback: jest.fn(),
+ collectedUsage: [],
+ streamId: 'event-thread',
+ jobCreatedAt: 1234,
+ eventChildActivity: {
+ runId: 'event-thread',
+ parentRunId: 'parent-conversation',
+ subagentRunId: 'delivery-1',
+ subagentType: 'agent-1',
+ subagentAgentId: 'agent-1',
+ parentAgentId: 'director',
+ publish,
+ },
+ });
+
+ await handlers[GraphEvents.ON_RUN_STEP].handle(GraphEvents.ON_RUN_STEP, data);
+ await Promise.resolve();
+ await Promise.resolve();
+
+ const firstUpdate = publish.mock.calls[0][0];
+ expect(firstUpdate).toEqual(
+ expect.objectContaining({
+ runId: 'event-thread',
+ parentRunId: 'parent-conversation',
+ subagentRunId: 'delivery-1',
+ phase: 'run_step',
+ activityEventId: expect.stringMatching(/^delivery-1:.+:0$/),
+ data,
+ }),
+ );
+ expect(firstUpdate).not.toHaveProperty('activitySequence');
+
+ const resumedPublish = jest.fn().mockResolvedValue(undefined);
+ const resumedHandlers = getDefaultHandlers({
+ res: { write: jest.fn() },
+ aggregateContent: jest.fn(),
+ toolEndCallback: jest.fn(),
+ collectedUsage: [],
+ streamId: 'event-thread',
+ jobCreatedAt: 1234,
+ eventChildActivity: {
+ runId: 'event-thread',
+ parentRunId: 'parent-conversation',
+ subagentRunId: 'delivery-1',
+ subagentType: 'agent-1',
+ subagentAgentId: 'agent-1',
+ parentAgentId: 'director',
+ publish: resumedPublish,
+ },
+ });
+ await resumedHandlers[GraphEvents.ON_RUN_STEP].handle(GraphEvents.ON_RUN_STEP, data);
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(resumedPublish.mock.calls[0][0].activityEventId).not.toBe(firstUpdate.activityEventId);
+ });
+
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/__tests__/request.resumeMetadata.spec.js b/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js
index f223f2fd91..a5c747364f 100644
--- a/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js
+++ b/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js
@@ -3649,7 +3649,14 @@ describe('ResumableAgentController resume metadata', () => {
);
expect(mockGenerationJobManager.createJob).toHaveBeenCalledTimes(1);
expect(mockAcquireEventChildGenerationLease).toHaveBeenCalledWith(
- expect.objectContaining({ retentionExpiresAt: expiredAt }),
+ expect.objectContaining({ taskId: 'req-event', retentionExpiresAt: expiredAt }),
+ );
+ const eventJobOptions = mockGenerationJobManager.createJob.mock.calls[0][3];
+ expect(eventJobOptions.initialMetadata).toEqual(
+ expect.objectContaining({
+ responseMessageId: 'req-event:assistant',
+ userMessage: expect.objectContaining({ messageId: 'req-event:user' }),
+ }),
);
});
diff --git a/api/server/controllers/agents/__tests__/resume.spec.js b/api/server/controllers/agents/__tests__/resume.spec.js
index be562830ad..a1f5df1c89 100644
--- a/api/server/controllers/agents/__tests__/resume.spec.js
+++ b/api/server/controllers/agents/__tests__/resume.spec.js
@@ -466,7 +466,12 @@ describe('ResumeAgentController (POST /agents/chat/resume)', () => {
it('owns the lease before consuming approval and preserves the inherited deadline', async () => {
const expiredAt = configureEventActorResume();
mockGenerationJobManager.getJob.mockResolvedValue(
- makeToolApprovalJob({ metadata: { isTemporary: true } }),
+ makeToolApprovalJob({
+ metadata: {
+ isTemporary: true,
+ idempotencyClientRequestId: 'trigger_event_delivery',
+ },
+ }),
);
const res = await post(approveBody());
@@ -481,7 +486,10 @@ describe('ResumeAgentController (POST /agents/chat/resume)', () => {
mockGenerationJobManager.approvals.resolve.mock.invocationCallOrder[0],
);
expect(mockAcquireEventChildGenerationLease).toHaveBeenCalledWith(
- expect.objectContaining({ retentionExpiresAt: expiredAt }),
+ expect.objectContaining({
+ taskId: 'trigger_event_delivery',
+ retentionExpiresAt: expiredAt,
+ }),
);
expect(mockSaveMessage).toHaveBeenCalledWith(
expect.objectContaining({ isTemporary: true, expiredAt }),
diff --git a/api/server/controllers/agents/callbacks.js b/api/server/controllers/agents/callbacks.js
index 0b1d597202..6dbe27f1bb 100644
--- a/api/server/controllers/agents/callbacks.js
+++ b/api/server/controllers/agents/callbacks.js
@@ -15,6 +15,7 @@ const {
GraphNodeKeys,
ToolEndHandler,
createContentAggregator,
+ summarizeEvent,
} = require('@librechat/agents');
const {
sendEvent,
@@ -381,13 +382,73 @@ function getDefaultHandlers({
usageCost = null,
contextUsageSink = null,
usageEmitSink = null,
+ eventChildActivity = null,
}) {
if (!res || !aggregateContent) {
throw new Error(
`[getDefaultHandlers] Missing required options: res: ${!res}, aggregateContent: ${!aggregateContent}`,
);
}
- const emitForJob = (eventData) => emitEvent(res, streamId, eventData, jobCreatedAt);
+ const eventActivityPhases = {
+ [GraphEvents.ON_RUN_STEP]: 'run_step',
+ [GraphEvents.ON_RUN_STEP_DELTA]: 'run_step_delta',
+ [GraphEvents.ON_RUN_STEP_COMPLETED]: 'run_step_completed',
+ [GraphEvents.ON_RUN_STEP_CLOSED]: 'run_step_closed',
+ [GraphEvents.ON_MESSAGE_DELTA]: 'message_delta',
+ [GraphEvents.ON_REASONING_DELTA]: 'reasoning_delta',
+ };
+ /** Event tasks retain one logical task id across HITL resume, while each
+ * handler instance is a new generation invocation. Keep replay identity
+ * unique per invocation; the existing stream transport preserves order.
+ * Reusing a zero-based activitySequence here would make the client discard
+ * resumed frames as duplicates of the pre-pause generation. */
+ const eventActivityInvocationId = eventChildActivity == null ? null : nanoid();
+ let eventActivitySequence = 0;
+ let eventActivityPending = 0;
+ let eventActivityCircuitOpen = false;
+ let eventActivityTail = Promise.resolve();
+ const publishEventChildActivity = (eventData) => {
+ const phase = eventActivityPhases[eventData?.event];
+ if (
+ eventChildActivity == null ||
+ phase == null ||
+ eventActivityCircuitOpen ||
+ eventActivityPending >= 128
+ ) {
+ return;
+ }
+ const sequence = eventActivitySequence++;
+ eventActivityPending += 1;
+ const update = {
+ runId: eventChildActivity.runId,
+ parentRunId: eventChildActivity.parentRunId,
+ subagentRunId: eventChildActivity.subagentRunId,
+ subagentType: eventChildActivity.subagentType,
+ subagentKind: 'agent',
+ subagentAgentId: eventChildActivity.subagentAgentId,
+ parentAgentId: eventChildActivity.parentAgentId,
+ depth: 1,
+ ancestry: [],
+ phase,
+ data: eventData.data,
+ label: summarizeEvent(eventData.event, eventData.data),
+ timestamp: new Date().toISOString(),
+ activityEventId: `${eventChildActivity.subagentRunId}:${eventActivityInvocationId}:${sequence}`,
+ };
+ eventActivityTail = eventActivityTail
+ .then(() => eventChildActivity.publish(update))
+ .catch((error) => {
+ eventActivityCircuitOpen = true;
+ logger.warn('[getDefaultHandlers] Failed to publish event child activity', error);
+ })
+ .finally(() => {
+ eventActivityPending = Math.max(0, eventActivityPending - 1);
+ });
+ };
+ const emitForJob = (eventData) => {
+ publishEventChildActivity(eventData);
+ return emitEvent(res, streamId, eventData, jobCreatedAt);
+ };
/**
* Emit a token-usage event, attaching the authoritative per-event USD cost
* when cost display is enabled. The backend is the single source of truth
diff --git a/api/server/controllers/agents/request.js b/api/server/controllers/agents/request.js
index 905723225d..0ab98fdb0c 100644
--- a/api/server/controllers/agents/request.js
+++ b/api/server/controllers/agents/request.js
@@ -1009,13 +1009,28 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit
const overrideUserMessageId = rawOverrideUserMessageId
? rawOverrideUserMessageId.split(Constants.COMMON_DIVIDER)[0]
: undefined;
+ /** Event deliveries already carry a stable, retry-safe idempotency key. Reuse
+ * it as the public child-task identity so the lease, persisted turn, and
+ * parent activity index continue to agree after the live lease is released. */
+ const eventTaskId =
+ req._agentEventBindingParentConversationId != null
+ ? (clientRequestId ?? crypto.randomUUID())
+ : undefined;
+ if (eventTaskId != null) {
+ req._agentEventTaskId = eventTaskId;
+ }
const preallocatedUserMessageId =
- overrideUserMessageId ?? overrideParentMessageId ?? crypto.randomUUID();
+ eventTaskId == null
+ ? (overrideUserMessageId ?? overrideParentMessageId ?? crypto.randomUUID())
+ : `${eventTaskId}:user`;
const overrideConversationId = rawOverrideConversationId
? rawOverrideConversationId.split(Constants.COMMON_DIVIDER)[0]
: undefined;
const effectiveConversationId = overrideConversationId ?? conversationId;
- let preallocatedResponseMessageId = editedResponseMessageId ?? crypto.randomUUID();
+ let preallocatedResponseMessageId =
+ eventTaskId == null
+ ? (editedResponseMessageId ?? crypto.randomUUID())
+ : `${eventTaskId}:assistant`;
if (
(editedContent != null && !isContinued) ||
(isRegenerate && preallocatedResponseMessageId.endsWith('_'))
@@ -1140,6 +1155,7 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit
tenantId: req._agentEventBindingTenantId,
conversationId,
streamId,
+ taskId: eventTaskId,
jobCreatedAt,
retentionExpiresAt: req._agentEventBindingRetention?.expiredAt,
});
diff --git a/api/server/controllers/agents/resume.js b/api/server/controllers/agents/resume.js
index 572f3d1644..30e3c8c73c 100644
--- a/api/server/controllers/agents/resume.js
+++ b/api/server/controllers/agents/resume.js
@@ -1107,12 +1107,14 @@ const ResumeAgentController = async (req, res, next, initializeClient, addTitle)
const providerExecutionId = randomUUID();
try {
if (req._agentEventBindingParentConversationId != null) {
+ req._agentEventTaskId = job.metadata.idempotencyClientRequestId;
try {
releaseEventChildLease = await acquireEventChildGenerationLease({
userId,
tenantId: req._agentEventBindingTenantId,
conversationId,
streamId,
+ taskId: job.metadata.idempotencyClientRequestId,
jobCreatedAt: job.createdAt,
retentionExpiresAt: req._agentEventBindingRetention?.expiredAt,
});
diff --git a/api/server/routes/convos.js b/api/server/routes/convos.js
index a549f07a2b..0750e4044a 100644
--- a/api/server/routes/convos.js
+++ b/api/server/routes/convos.js
@@ -6,6 +6,7 @@ const {
deleteAgentCheckpoints,
createArchiveAllHandler,
createSubagentActivityStreamHandler,
+ createParentSubagentIndexHandler,
createSubagentThreadViewHandler,
resolveImportMaxFileSize,
restoreTenantContextFromReq,
@@ -47,6 +48,11 @@ const subagentThreadViewHandler = createSubagentThreadViewHandler({
getSubagentThreadForParent: db.getSubagentThreadForParent,
getMessagesForSubagentThreadView: db.getMessagesForSubagentThreadView,
});
+const parentSubagentIndexHandler = createParentSubagentIndexHandler({
+ getConvoOwnership: db.getConvoOwnership,
+ listSubagentThreadsForParent: db.listSubagentThreadsForParent,
+ listSubagentTasksForThreads: db.listSubagentTasksForThreads,
+});
const filterConversationTitle = createContentFilter({
getFilters: (req) => req.config?.filters,
extract: (req) => extractConversationTitleContent(req.body),
@@ -111,6 +117,7 @@ router.get(
'/:parentConversationId/subagents/:threadId/tasks/:taskId/activity',
subagentActivityStreamHandler,
);
+router.get('/:parentConversationId/subagents', parentSubagentIndexHandler);
router.get('/:parentConversationId/subagents/:threadId', subagentThreadViewHandler);
router.get('/:conversationId', async (req, res) => {
diff --git a/api/server/services/Endpoints/agents/initialize.js b/api/server/services/Endpoints/agents/initialize.js
index 4a3a5aef6e..d1426fdd26 100644
--- a/api/server/services/Endpoints/agents/initialize.js
+++ b/api/server/services/Endpoints/agents/initialize.js
@@ -1372,6 +1372,25 @@ const initializeClient = async ({
fallback: usageCost.endpointTokenConfig,
});
+ const eventTaskId = req._agentEventTaskId;
+ const eventChildActivity =
+ req._agentEventBindingParentConversationId != null &&
+ typeof conversationId === 'string' &&
+ conversationId !== '' &&
+ typeof eventTaskId === 'string' &&
+ eventTaskId !== ''
+ ? {
+ runId: streamId ?? eventTaskId,
+ parentRunId: req._agentEventBindingParentConversationId,
+ subagentRunId: eventTaskId,
+ subagentType: primaryConfig.id,
+ subagentAgentId: primaryConfig.id,
+ parentAgentId: req._agentEventBindingParentAgentId,
+ publish: (event) =>
+ subagentThreadTaskStore.publishTaskActivity(conversationId, eventTaskId, event),
+ }
+ : null;
+
const eventHandlers = getDefaultHandlers({
res,
contentParts,
@@ -1389,6 +1408,7 @@ const initializeClient = async ({
usageCost,
contextUsageSink,
usageEmitSink,
+ eventChildActivity,
});
const client = new AgentClient({
diff --git a/api/server/services/Endpoints/agents/initialize.spec.js b/api/server/services/Endpoints/agents/initialize.spec.js
index 66335332ef..391c138421 100644
--- a/api/server/services/Endpoints/agents/initialize.spec.js
+++ b/api/server/services/Endpoints/agents/initialize.spec.js
@@ -257,6 +257,46 @@ describe('initializeClient — processAgent ACL gate', () => {
);
});
+ it('publishes event-root activity through the owning child task stream', async () => {
+ const subagentThreadTaskStore = require('./subagentThreadStore');
+ const publishTaskActivity = jest
+ .spyOn(subagentThreadTaskStore, 'publishTaskActivity')
+ .mockResolvedValueOnce(undefined);
+ mockInitializeAgent.mockResolvedValue(makePrimaryConfig([]));
+ const req = makeReq();
+ req._resumableStreamId = 'child-conversation';
+ req.body.conversationId = 'child-conversation';
+ req._agentEventTaskId = 'event-task';
+ req._agentEventBindingParentConversationId = 'parent-conversation';
+ req._agentEventBindingParentAgentId = 'parent-agent';
+
+ await initializeClient({
+ req,
+ res: {},
+ signal: new AbortController().signal,
+ endpointOption: makeEndpointOption(),
+ });
+
+ expect(capturedDefaultHandlerOptions.eventChildActivity).toEqual(
+ expect.objectContaining({
+ runId: 'child-conversation',
+ parentRunId: 'parent-conversation',
+ subagentRunId: 'event-task',
+ subagentType: PRIMARY_ID,
+ subagentAgentId: PRIMARY_ID,
+ parentAgentId: 'parent-agent',
+ }),
+ );
+ await capturedDefaultHandlerOptions.eventChildActivity.publish({
+ phase: 'writing',
+ label: 'Drafting response',
+ });
+ expect(publishTaskActivity).toHaveBeenCalledWith('child-conversation', 'event-task', {
+ phase: 'writing',
+ label: 'Drafting response',
+ });
+ });
+
it('propagates an expected-MCP-tools failure from the runtime tool loader', async () => {
const toolError = Object.assign(new Error('Expected MCP tools are unavailable'), {
code: 'AGENT_EXPECTED_MCP_TOOLS_UNAVAILABLE',
diff --git a/client/src/components/Chat/Messages/Content/ContentParts.tsx b/client/src/components/Chat/Messages/Content/ContentParts.tsx
index a09a9ff5bd..6c4a45b533 100644
--- a/client/src/components/Chat/Messages/Content/ContentParts.tsx
+++ b/client/src/components/Chat/Messages/Content/ContentParts.tsx
@@ -182,7 +182,7 @@ type ContentPartsProps = {
* For 90% of messages (single-agent, no parallel execution), this renders sequentially.
* For multi-agent parallel execution, it uses ParallelContentRenderer to show columns.
*/
-const ContentParts = memo(function ContentParts({
+const ContentPartsBody = memo(function ContentPartsBody({
edit,
isLast,
content,
@@ -507,7 +507,7 @@ const ContentParts = memo(function ContentParts({
key: string,
) => {
return (
- <ContentParts
+ <ContentPartsBody
key={key}
content={segmentContent}
messageId={messageId}
@@ -684,4 +684,8 @@ const ContentParts = memo(function ContentParts({
return <ApprovalProvider>{sequentialContent}</ApprovalProvider>;
});
+const ContentParts = memo(function ContentParts(props: ContentPartsProps) {
+ return <ContentPartsBody {...props} />;
+});
+
export default ContentParts;
diff --git a/client/src/components/Chat/Messages/MultiMessage.tsx b/client/src/components/Chat/Messages/MultiMessage.tsx
index 5b8a658e58..20525561e1 100644
--- a/client/src/components/Chat/Messages/MultiMessage.tsx
+++ b/client/src/components/Chat/Messages/MultiMessage.tsx
@@ -4,6 +4,7 @@ import { isAssistantsEndpoint } from 'librechat-data-provider';
import type { TMessage } from 'librechat-data-provider';
import type { ReactElement } from 'react';
import type { TMessageProps } from '~/common';
+import EventSubagentActivityGroup from '~/components/Chat/Subagents/EventSubagentActivityGroup';
import MessageContent from '~/components/Messages/MessageContent';
import { useRowMountWindow } from '~/hooks/Messages';
import MessageParts from './MessageParts';
@@ -195,6 +196,16 @@ function MultiMessage({
return (
<>
{row}
+ {rowMounted && currentEditId !== message.messageId ? (
+ <div className="w-full border-0 bg-transparent">
+ <div className="m-auto justify-center px-4 sm:px-0">
+ <EventSubagentActivityGroup
+ conversationId={message.conversationId ?? ''}
+ parentMessageId={message.messageId}
+ />
+ </div>
+ </div>
+ ) : null}
<MemoizedMultiMessage
messageId={message.messageId}
messagesTree={message.children ?? []}
diff --git a/client/src/components/Chat/Messages/__tests__/MultiMessage.spec.tsx b/client/src/components/Chat/Messages/__tests__/MultiMessage.spec.tsx
index 586c1f2231..7a2146e1c9 100644
--- a/client/src/components/Chat/Messages/__tests__/MultiMessage.spec.tsx
+++ b/client/src/components/Chat/Messages/__tests__/MultiMessage.spec.tsx
@@ -32,6 +32,12 @@ jest.mock('~/components/Messages/MessageContent', () => ({
}));
jest.mock('../MessageParts', () => ({ __esModule: true, default: createRowStub() }));
jest.mock('../Message', () => ({ __esModule: true, default: createRowStub() }));
+jest.mock('~/components/Chat/Subagents/EventSubagentActivityGroup', () => ({
+ __esModule: true,
+ default: ({ parentMessageId }: { parentMessageId: string }) => (
+ <div data-testid="event-subagent-activity" data-parent-message-id={parentMessageId} />
+ ),
+}));
const msg = (messageId: string): TMessage =>
({
@@ -60,6 +66,41 @@ const treeElement = (ids: string[]) => (
const displayed = () => screen.getAllByTestId('row')[0].textContent;
describe('MultiMessage sibling selection', () => {
+ it('hosts event activity for structured and legacy message rows', () => {
+ const structured = msg('structured');
+ const legacy = { ...msg('legacy'), content: undefined } as TMessage;
+ const view = render(
+ <RecoilRoot>
+ <MultiMessage
+ messageId="parent-1"
+ messagesTree={[structured]}
+ currentEditId={null}
+ setCurrentEditId={jest.fn()}
+ />
+ </RecoilRoot>,
+ );
+
+ expect(screen.getByTestId('event-subagent-activity')).toHaveAttribute(
+ 'data-parent-message-id',
+ 'structured',
+ );
+
+ view.rerender(
+ <RecoilRoot>
+ <MultiMessage
+ messageId="parent-1"
+ messagesTree={[legacy]}
+ currentEditId={null}
+ setCurrentEditId={jest.fn()}
+ />
+ </RecoilRoot>,
+ );
+ expect(screen.getByTestId('event-subagent-activity')).toHaveAttribute(
+ 'data-parent-message-id',
+ 'legacy',
+ );
+ });
+
it('shows the newest sibling by default and follows a newly appended one', () => {
const view = render(treeElement(['a', 'b']));
expect(displayed()).toBe('b');
diff --git a/client/src/components/Chat/Presentation.test.tsx b/client/src/components/Chat/Presentation.test.tsx
index 6f38dc09da..013a01e319 100644
--- a/client/src/components/Chat/Presentation.test.tsx
+++ b/client/src/components/Chat/Presentation.test.tsx
@@ -11,6 +11,11 @@ const mockArtifactPanelLabel = 'Artifact panel loaded';
const mockOpenArtifactLabel = 'Open Artifact';
const mockChildPanelLabel = 'Child activity panel loaded';
const mockOpenChildLabel = 'Open Child Activity';
+const mockSelectAgentConversationLabel = 'Select Agent Conversation';
+const mockUseParentSubagentsQuery = jest.fn((_conversationId?: string, _config?: unknown) => ({
+ data: undefined,
+ refetch: jest.fn(),
+}));
jest.mock('~/components/Artifacts/Artifacts', () => {
const artifactPanelLabel = 'Artifact panel loaded';
@@ -56,6 +61,8 @@ jest.mock('~/hooks/Artifacts/useResetArtifactsOnConversationChange', () => ({
jest.mock('~/data-provider', () => ({
useDeleteFilesMutation: () => ({ mutateAsync: jest.fn() }),
+ useParentSubagentsQuery: (conversationId: string, config?: unknown) =>
+ mockUseParentSubagentsQuery(conversationId, config),
}));
jest.mock('~/hooks', () => ({
@@ -114,6 +121,24 @@ const OpenSubagentPanel = () => {
);
};
+const SelectAgentConversation = () => {
+ const setConversation = useSetRecoilState(store.conversationByIndex(0));
+ return (
+ <button
+ type="button"
+ onClick={() =>
+ setConversation({
+ conversationId: 'agent-conversation',
+ endpoint: 'agents',
+ agent_id: 'agent-1',
+ } as TConversation)
+ }
+ >
+ {mockSelectAgentConversationLabel}
+ </button>
+ );
+};
+
describe('Presentation Artifact loading', () => {
it('loads the Artifact panel bundle only when the panel is opened', async () => {
const testGlobal = globalThis as typeof globalThis & {
@@ -134,6 +159,23 @@ describe('Presentation Artifact loading', () => {
expect(await screen.findByText(mockArtifactPanelLabel)).toBeInTheDocument();
expect(testGlobal.presentationArtifactModuleEvaluations).toBe(1);
+ expect(mockUseParentSubagentsQuery).toHaveBeenCalledWith('', { enabled: false });
+ });
+
+ it('loads the parent child index only for Agent conversations', () => {
+ render(
+ <RecoilRoot>
+ <Presentation>
+ <SelectAgentConversation />
+ </Presentation>
+ </RecoilRoot>,
+ );
+
+ expect(mockUseParentSubagentsQuery).toHaveBeenLastCalledWith('', { enabled: false });
+ fireEvent.click(screen.getByRole('button', { name: mockSelectAgentConversationLabel }));
+ expect(mockUseParentSubagentsQuery).toHaveBeenLastCalledWith('agent-conversation', {
+ enabled: true,
+ });
});
it('uses one panel slot and lets an opened artifact replace child activity', async () => {
diff --git a/client/src/components/Chat/Presentation.tsx b/client/src/components/Chat/Presentation.tsx
index cdb4fce37a..3a09112463 100644
--- a/client/src/components/Chat/Presentation.tsx
+++ b/client/src/components/Chat/Presentation.tsx
@@ -1,8 +1,9 @@
import { lazy, Suspense, useEffect, useMemo, useRef } from 'react';
import { useRecoilValue, useResetRecoilState } from 'recoil';
-import { FileSources, LocalStorageKeys } from 'librechat-data-provider';
+import { EModelEndpoint, FileSources, LocalStorageKeys } from 'librechat-data-provider';
import type { ExtendedFile } from '~/common';
import useResetArtifactsOnConversationChange from '~/hooks/Artifacts/useResetArtifactsOnConversationChange';
+import { ParentSubagentsProvider } from '~/components/Chat/Subagents/ParentSubagentsProvider';
import DragDropWrapper from '~/components/Chat/Input/Files/DragDropWrapper';
import { EditorProvider, ArtifactsProvider } from '~/Providers';
import { useDeleteFilesMutation } from '~/data-provider';
@@ -26,6 +27,8 @@ export default function Presentation({ children }: { children: React.ReactNode }
// (gated on `isSubmitting`), restoring the legacy streaming UX.
const currentArtifactId = useRecoilValue(store.currentArtifactId);
const conversationId = useRecoilValue(store.conversationIdByIndex(0));
+ const conversationEndpoint = useRecoilValue(store.effectiveEndpointByIndex(0));
+ const conversationAgentId = useRecoilValue(store.conversationAgentIdByIndex(0));
const selectedSubagent = useRecoilValue(activeSubagentPanel);
const resetSelectedSubagent = useResetRecoilState(activeSubagentPanel);
const previousConversationIdRef = useRef<string | null>(null);
@@ -114,11 +117,16 @@ export default function Presentation({ children }: { children: React.ReactNode }
return (
<DragDropWrapper className="relative flex w-full grow overflow-hidden bg-presentation">
- <SidePanelGroup panel={panelElement}>
- <main className="flex h-full flex-col overflow-y-auto" role="main">
- {children}
- </main>
- </SidePanelGroup>
+ <ParentSubagentsProvider
+ conversationId={conversationId ?? ''}
+ enabled={conversationEndpoint === EModelEndpoint.agents && conversationAgentId != null}
+ >
+ <SidePanelGroup panel={panelElement}>
+ <main className="flex h-full flex-col overflow-y-auto" role="main">
+ {children}
+ </main>
+ </SidePanelGroup>
+ </ParentSubagentsProvider>
</DragDropWrapper>
);
}
diff --git a/client/src/components/Chat/Subagents/EventSubagentActivityGroup.test.tsx b/client/src/components/Chat/Subagents/EventSubagentActivityGroup.test.tsx
new file mode 100644
index 0000000000..00282caac7
--- /dev/null
+++ b/client/src/components/Chat/Subagents/EventSubagentActivityGroup.test.tsx
@@ -0,0 +1,144 @@
+import React from 'react';
+import { RecoilRoot, useRecoilValue, useSetRecoilState } from 'recoil';
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import type { ParentSubagentSummary } from 'librechat-data-provider';
+import type { ActiveSubagentPanel } from '~/store/subagents';
+import EventSubagentActivityGroup from './EventSubagentActivityGroup';
+import { activeSubagentPanel } from '~/store/subagents';
+
+const mockRefresh = jest.fn().mockResolvedValue(undefined);
+const mockChild: ParentSubagentSummary = {
+ threadId: 'event-thread',
+ parentMessageId: 'parent-message',
+ subagentType: 'agent-1',
+ subagentKind: 'agent',
+ agentId: 'agent-1',
+ title: 'Actor child',
+ origin: 'event',
+ actorId: 'actor-a',
+ status: 'running',
+ latestTaskId: 'task-1',
+ tasks: [{ taskId: 'task-1', status: 'running' }],
+ tasksTruncated: false,
+};
+
+jest.mock('./ParentSubagentsProvider', () => ({
+ useParentSubagents: () => ({
+ byMessageId: new Map([['parent-message', [mockChild]]]),
+ byThreadId: new Map([['event-thread', mockChild]]),
+ refresh: mockRefresh,
+ }),
+}));
+
+jest.mock('~/Providers', () => ({
+ useAgentsMapContext: () => ({ 'agent-1': { id: 'agent-1', name: 'Visible Agent' } }),
+}));
+
+jest.mock('~/hooks', () => ({ useLocalize: () => (key: string) => key }));
+jest.mock('~/utils', () => ({
+ ...jest.requireActual('~/utils'),
+ renderAgentAvatar: () => <span data-testid="agent-avatar" />,
+}));
+jest.mock('@librechat/client', () => ({
+ cn: (...values: Array<string | false | undefined>) => values.filter(Boolean).join(' '),
+}));
+jest.mock('lucide-react', () => ({
+ AlertCircle: () => null,
+ Bot: () => null,
+ Check: () => null,
+ CheckCircle2: () => null,
+ CircleAlert: () => null,
+ Clock3: () => null,
+ LoaderCircle: () => null,
+ X: () => null,
+ XCircle: () => null,
+}));
+
+describe('EventSubagentActivityGroup', () => {
+ beforeEach(() => {
+ mockRefresh.mockReset().mockResolvedValue(undefined);
+ });
+
+ it('opens the durable event child under its owning parent message', () => {
+ let selection: ActiveSubagentPanel | null = null;
+ const Observer = () => {
+ selection = useRecoilValue(activeSubagentPanel);
+ return null;
+ };
+ render(
+ <RecoilRoot>
+ <Observer />
+ <EventSubagentActivityGroup
+ conversationId="parent-conversation"
+ parentMessageId="parent-message"
+ />
+ </RecoilRoot>,
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: /Visible Agent/ }));
+
+ expect(mockRefresh).toHaveBeenCalledTimes(1);
+ expect(selection).toEqual(
+ expect.objectContaining({
+ host: 'conversation',
+ parentConversationId: 'parent-conversation',
+ parentMessageId: 'parent-message',
+ toolCallId: 'event-thread:event-thread',
+ durable: { threadId: 'event-thread', taskId: 'task-1' },
+ event: {
+ actorId: 'actor-a',
+ progressKey: 'event-task:event-thread:task-1',
+ },
+ }),
+ );
+ });
+
+ it('does not reopen a child after the user closes it while refresh is pending', async () => {
+ let selection: ActiveSubagentPanel | null = null;
+ let resolveRefresh!: (value: unknown) => void;
+ mockRefresh.mockReturnValueOnce(
+ new Promise((resolve) => {
+ resolveRefresh = resolve;
+ }),
+ );
+ const Observer = () => {
+ selection = useRecoilValue(activeSubagentPanel);
+ return null;
+ };
+ const ClosePanel = () => {
+ const setSelection = useSetRecoilState(activeSubagentPanel);
+ return <button type="button" data-testid="close-panel" onClick={() => setSelection(null)} />;
+ };
+ render(
+ <RecoilRoot>
+ <Observer />
+ <ClosePanel />
+ <EventSubagentActivityGroup
+ conversationId="parent-conversation"
+ parentMessageId="parent-message"
+ />
+ </RecoilRoot>,
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: /Visible Agent/ }));
+ expect(selection).toEqual(
+ expect.objectContaining({ durable: expect.objectContaining({ taskId: 'task-1' }) }),
+ );
+ fireEvent.click(screen.getByTestId('close-panel'));
+ expect(selection).toBeNull();
+
+ await act(async () => {
+ resolveRefresh({
+ children: [
+ {
+ ...mockChild,
+ latestTaskId: 'task-2',
+ tasks: [{ taskId: 'task-2', status: 'completed' }],
+ },
+ ],
+ });
+ });
+
+ await waitFor(() => expect(selection).toBeNull());
+ });
+});
diff --git a/client/src/components/Chat/Subagents/EventSubagentActivityGroup.tsx b/client/src/components/Chat/Subagents/EventSubagentActivityGroup.tsx
new file mode 100644
index 0000000000..40b1ded56e
--- /dev/null
+++ b/client/src/components/Chat/Subagents/EventSubagentActivityGroup.tsx
@@ -0,0 +1,133 @@
+import { useCallback } from 'react';
+import { Bot } from 'lucide-react';
+import { cn } from '@librechat/client';
+import { useResetRecoilState, useSetRecoilState } from 'recoil';
+import type { ParentSubagentSummary } from 'librechat-data-provider';
+import { subagentStatusIcon, subagentStatusLabelKey } from './status';
+import { useParentSubagents } from './ParentSubagentsProvider';
+import { eventSubagentSelection } from './eventSelection';
+import { activeSubagentPanel } from '~/store/subagents';
+import { useAgentsMapContext } from '~/Providers';
+import { renderAgentAvatar } from '~/utils';
+import { useLocalize } from '~/hooks';
+import store from '~/store';
+
+export default function EventSubagentActivityGroup({
+ conversationId,
+ parentMessageId,
+}: {
+ conversationId: string;
+ parentMessageId: string;
+}) {
+ const { byMessageId } = useParentSubagents();
+ const children = byMessageId.get(parentMessageId) ?? [];
+ if (children.length === 0) return null;
+ return (
+ <EventSubagentRows
+ conversationId={conversationId}
+ parentMessageId={parentMessageId}
+ eventChildren={children}
+ />
+ );
+}
+
+function EventSubagentRows({
+ conversationId,
+ parentMessageId,
+ eventChildren,
+}: {
+ conversationId: string;
+ parentMessageId: string;
+ eventChildren: ParentSubagentSummary[];
+}) {
+ const localize = useLocalize();
+ const agentsMap = useAgentsMapContext();
+ const { refresh } = useParentSubagents();
+ const setSelected = useSetRecoilState(activeSubagentPanel);
+ const setArtifactsVisible = useSetRecoilState(store.artifactsVisibility);
+ const resetCurrentArtifactId = useResetRecoilState(store.currentArtifactId);
+ const openChild = useCallback(
+ (child: ParentSubagentSummary) => {
+ const selection = eventSubagentSelection(conversationId, child);
+ if (selection == null) return;
+ resetCurrentArtifactId();
+ setArtifactsVisible(false);
+ setSelected(selection);
+ void refresh().then((index) => {
+ const fresh = index?.children.find((candidate) => candidate.threadId === child.threadId);
+ if (fresh == null || fresh.latestTaskId === child.latestTaskId) return;
+ const freshSelection = eventSubagentSelection(conversationId, fresh);
+ if (freshSelection != null) {
+ setSelected((current) => {
+ if (
+ current?.durable?.threadId !== selection.durable?.threadId ||
+ current?.durable?.taskId !== selection.durable?.taskId
+ ) {
+ return current;
+ }
+ return freshSelection;
+ });
+ }
+ });
+ },
+ [conversationId, refresh, resetCurrentArtifactId, setArtifactsVisible, setSelected],
+ );
+ return (
+ <section
+ aria-label={localize('com_ui_subagent_activity')}
+ className="my-2 overflow-hidden rounded-lg border border-border-light bg-surface-secondary"
+ data-event-subagent-group={parentMessageId}
+ >
+ <div className="border-b border-border-light px-3 py-2 text-xs font-medium text-text-secondary">
+ {localize('com_ui_subagent_activity')}
+ </div>
+ <div className="divide-y divide-border-light">
+ {eventChildren.map((child) => {
+ const StatusIcon = subagentStatusIcon(child.status);
+ const agent = child.agentId == null ? undefined : agentsMap?.[child.agentId];
+ const label = agent?.name || child.actorId || child.title;
+ const canOpen = child.latestTaskId != null;
+ return (
+ <button
+ key={child.threadId}
+ type="button"
+ disabled={!canOpen}
+ onClick={() => openChild(child)}
+ data-subagent-tool-call={`event-thread:${child.threadId}`}
+ data-subagent-parent-message={parentMessageId}
+ data-subagent-part-index="0"
+ className={cn(
+ 'flex w-full items-center gap-2 px-3 py-2 text-left text-sm',
+ canOpen ? 'hover:bg-surface-tertiary' : 'cursor-default opacity-70',
+ )}
+ >
+ <span className="flex h-5 w-5 shrink-0 items-center justify-center overflow-hidden rounded-full">
+ {agent ? (
+ renderAgentAvatar(agent, { size: 'icon', showBorder: false })
+ ) : (
+ <Bot size={14} />
+ )}
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="block truncate">{label}</span>
+ {child.actorId && child.actorId !== label ? (
+ <span className="block truncate text-xs text-text-secondary">
+ {child.actorId}
+ </span>
+ ) : null}
+ </span>
+ <span className="flex items-center gap-1 text-xs text-text-secondary">
+ <StatusIcon
+ size={14}
+ className={child.status === 'running' ? 'animate-spin' : undefined}
+ aria-hidden="true"
+ />
+ {localize(subagentStatusLabelKey(child.status))}
+ </span>
+ </button>
+ );
+ })}
+ </div>
+ </section>
+ );
+}
diff --git a/client/src/components/Chat/Subagents/ParentSubagentsProvider.test.tsx b/client/src/components/Chat/Subagents/ParentSubagentsProvider.test.tsx
new file mode 100644
index 0000000000..59eade9bda
--- /dev/null
+++ b/client/src/components/Chat/Subagents/ParentSubagentsProvider.test.tsx
@@ -0,0 +1,73 @@
+import React from 'react';
+import { act, render } from '@testing-library/react';
+import type { ParentSubagentIndex, ParentSubagentSummary } from 'librechat-data-provider';
+import { ParentSubagentsProvider, useParentSubagents } from './ParentSubagentsProvider';
+
+const mockUseParentSubagentsQuery = jest.fn();
+
+jest.mock('~/data-provider', () => ({
+ useParentSubagentsQuery: (...args: unknown[]) => mockUseParentSubagentsQuery(...args),
+}));
+
+const eventChild: ParentSubagentSummary = {
+ threadId: 'event-thread',
+ parentMessageId: 'parent-message',
+ subagentType: 'agent-1',
+ subagentKind: 'agent',
+ title: 'Event child',
+ origin: 'event',
+ actorId: 'actor-a',
+ status: 'completed',
+ latestTaskId: 'task-1',
+ tasks: [{ taskId: 'task-1', status: 'completed' }],
+ tasksTruncated: false,
+};
+const toolChild: ParentSubagentSummary = {
+ ...eventChild,
+ threadId: 'tool-thread',
+ parentToolCallId: 'tool-call',
+ origin: 'tool',
+ actorId: undefined,
+};
+
+describe('ParentSubagentsProvider', () => {
+ it('reconstructs event groups from one durable conversation query and refreshes that index', async () => {
+ const refreshed: ParentSubagentIndex = {
+ parentConversationId: 'parent-conversation',
+ children: [{ ...eventChild, latestTaskId: 'task-2' }],
+ childrenTruncated: false,
+ };
+ const refetch = jest.fn().mockResolvedValue({ data: refreshed });
+ mockUseParentSubagentsQuery.mockReturnValue({
+ data: {
+ parentConversationId: 'parent-conversation',
+ children: [eventChild, toolChild],
+ childrenTruncated: false,
+ },
+ refetch,
+ });
+ let context: ReturnType<typeof useParentSubagents> | undefined;
+ const Probe = () => {
+ context = useParentSubagents();
+ return null;
+ };
+
+ render(
+ <ParentSubagentsProvider conversationId="parent-conversation" enabled>
+ <Probe />
+ </ParentSubagentsProvider>,
+ );
+
+ expect(mockUseParentSubagentsQuery).toHaveBeenCalledWith('parent-conversation', {
+ enabled: true,
+ });
+ expect(context?.byMessageId.get('parent-message')).toEqual([eventChild]);
+ expect(context?.byThreadId.get('tool-thread')).toEqual(toolChild);
+ let result: ParentSubagentIndex | undefined;
+ await act(async () => {
+ result = await context?.refresh();
+ });
+ expect(refetch).toHaveBeenCalledTimes(1);
+ expect(result).toEqual(refreshed);
+ });
+});
diff --git a/client/src/components/Chat/Subagents/ParentSubagentsProvider.tsx b/client/src/components/Chat/Subagents/ParentSubagentsProvider.tsx
new file mode 100644
index 0000000000..82ec322f94
--- /dev/null
+++ b/client/src/components/Chat/Subagents/ParentSubagentsProvider.tsx
@@ -0,0 +1,59 @@
+import { createContext, useCallback, useContext, useMemo } from 'react';
+import type { ParentSubagentIndex, ParentSubagentSummary } from 'librechat-data-provider';
+import { useParentSubagentsQuery } from '~/data-provider';
+
+type ParentSubagentsContextValue = {
+ byMessageId: ReadonlyMap<string, ParentSubagentSummary[]>;
+ byThreadId: ReadonlyMap<string, ParentSubagentSummary>;
+ refresh: () => Promise<ParentSubagentIndex | undefined>;
+};
+
+const emptyMap = new Map<string, ParentSubagentSummary[]>();
+const emptyThreadMap = new Map<string, ParentSubagentSummary>();
+const defaultValue: ParentSubagentsContextValue = {
+ byMessageId: emptyMap,
+ byThreadId: emptyThreadMap,
+ refresh: async () => undefined,
+};
+
+const ParentSubagentsContext = createContext<ParentSubagentsContextValue>(defaultValue);
+
+export function ParentSubagentsProvider({
+ conversationId,
+ enabled,
+ children,
+}: {
+ conversationId: string;
+ enabled: boolean;
+ children: React.ReactNode;
+}) {
+ const { data, refetch } = useParentSubagentsQuery(conversationId, { enabled });
+ const refresh = useCallback(async () => {
+ const result = await refetch();
+ return result.data;
+ }, [refetch]);
+ const value = useMemo<ParentSubagentsContextValue>(() => {
+ const byMessageId = new Map<string, ParentSubagentSummary[]>();
+ const byThreadId = new Map<string, ParentSubagentSummary>();
+ for (const child of data?.children ?? []) {
+ byThreadId.set(child.threadId, child);
+ if (child.origin !== 'event') continue;
+ const siblings = byMessageId.get(child.parentMessageId) ?? [];
+ siblings.push(child);
+ byMessageId.set(child.parentMessageId, siblings);
+ }
+ for (const siblings of byMessageId.values()) {
+ siblings.sort((left, right) => {
+ const updated = (right.updatedAt ?? '').localeCompare(left.updatedAt ?? '');
+ return updated === 0 ? left.threadId.localeCompare(right.threadId) : updated;
+ });
+ }
+ return { byMessageId, byThreadId, refresh };
+ }, [data, refresh]);
+
+ return (
+ <ParentSubagentsContext.Provider value={value}>{children}</ParentSubagentsContext.Provider>
+ );
+}
+
+export const useParentSubagents = () => useContext(ParentSubagentsContext);
diff --git a/client/src/components/Chat/Subagents/SubagentActivity.tsx b/client/src/components/Chat/Subagents/SubagentActivity.tsx
index 672c968f79..4bb6ccb1b2 100644
--- a/client/src/components/Chat/Subagents/SubagentActivity.tsx
+++ b/client/src/components/Chat/Subagents/SubagentActivity.tsx
@@ -1,19 +1,12 @@
import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';
import { Button } from '@librechat/client';
import { ContentTypes } from 'librechat-data-provider';
-import {
- AlertCircle,
- ArrowDown,
- CheckCircle2,
- Clock3,
- Maximize2,
- Minimize2,
- XCircle,
-} from 'lucide-react';
+import { ArrowDown, Maximize2, Minimize2 } from 'lucide-react';
import type { TMessageContentParts } from 'librechat-data-provider';
import type { ChildActivity, ChildActivityItem } from './adapters';
import MarkdownLite from '~/components/Chat/Messages/Content/MarkdownLite';
import ContentParts from '~/components/Chat/Messages/Content/ContentParts';
+import { subagentStatusIcon, subagentStatusLabelKey } from './status';
import Container from '~/components/Chat/Messages/Content/Container';
import { EmptyText } from '~/components/Chat/Messages/Content/Parts';
import { useLocalize } from '~/hooks';
@@ -21,22 +14,6 @@ import { cn } from '~/utils';
const AT_BOTTOM_THRESHOLD_PX = 120;
-const statusIcon = (status: ChildActivity['status']) => {
- if (status === 'completed') return CheckCircle2;
- if (status === 'failed' || status === 'interrupted') return AlertCircle;
- if (status === 'cancelled') return XCircle;
- return Clock3;
-};
-
-const statusLabels = {
- dispatched: 'com_ui_subagent_thread_status_dispatched',
- running: 'com_ui_subagent_thread_status_running',
- completed: 'com_ui_subagent_thread_status_completed',
- failed: 'com_ui_subagent_thread_status_failed',
- interrupted: 'com_ui_subagent_thread_status_interrupted',
- cancelled: 'com_ui_subagent_thread_status_cancelled',
-} as const;
-
const toContentPart = (
item: ChildActivityItem,
reasoningMarkerLabel: string,
@@ -155,7 +132,7 @@ export default function SubagentActivity({
const contentRef = useRef<HTMLDivElement>(null);
const [isAtBottom, setIsAtBottom] = useState(true);
const isSubmitting = activity.status === 'running' || activity.status === 'dispatched';
- const StatusIcon = statusIcon(activity.status);
+ const StatusIcon = subagentStatusIcon(activity.status);
const reasoningMarkerLabel = localize('com_ui_subagent_ticker_reasoning');
const parts = useMemo(
() => activity.items.map((item) => toContentPart(item, reasoningMarkerLabel)),
@@ -237,7 +214,7 @@ export default function SubagentActivity({
aria-live="polite"
>
<StatusIcon size={13} aria-hidden />
- <span>{localize(statusLabels[activity.status])}</span>
+ <span>{localize(subagentStatusLabelKey(activity.status))}</span>
</div>
</div>
<div
diff --git a/client/src/components/Chat/Subagents/SubagentThreadPanel.test.tsx b/client/src/components/Chat/Subagents/SubagentThreadPanel.test.tsx
index d45e0fe22a..63e96f6ec9 100644
--- a/client/src/components/Chat/Subagents/SubagentThreadPanel.test.tsx
+++ b/client/src/components/Chat/Subagents/SubagentThreadPanel.test.tsx
@@ -2,7 +2,11 @@ import React from 'react';
import { RecoilRoot, useRecoilValue } from 'recoil';
import { ContentTypes, ForkOptions } from 'librechat-data-provider';
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
-import type { SubagentThreadView, TMessageContentParts } from 'librechat-data-provider';
+import type {
+ ParentSubagentSummary,
+ SubagentThreadView,
+ TMessageContentParts,
+} from 'librechat-data-provider';
import type { ActiveSubagentPanel } from '~/store/subagents';
import {
activeSubagentPanel,
@@ -20,8 +24,12 @@ const mockShowToast = jest.fn();
const mockApprovalProviderMounted = jest.fn();
const mockApprovalProviderUnmounted = jest.fn();
let mockIsMobile = false;
+let mockParentChildrenByMessage = new Map<string, ParentSubagentSummary[]>();
+let mockParentChildrenByThread = new Map<string, ParentSubagentSummary>();
+const mockRefreshParentChildren = jest.fn().mockResolvedValue(undefined);
jest.mock('~/data-provider', () => ({
+ ACTIVE_THREAD_REFRESH_MS: 2000,
useSubagentThreadQuery: (...args: unknown[]) => mockUseSubagentThreadQuery(...args),
subagentThreadHasTaskEvidence: (view: SubagentThreadView | undefined, taskId: string): boolean =>
view?.messages.some(
@@ -48,6 +56,21 @@ jest.mock('~/hooks', () => ({
useNavigateToConvo: () => ({ navigateToConvo: mockNavigateToConvo }),
}));
+jest.mock('~/Providers', () => ({
+ useAgentsMapContext: () => ({
+ 'agent-1': { id: 'agent-1', name: 'Analyst One' },
+ 'agent-2': { id: 'agent-2', name: 'Analyst Two' },
+ }),
+}));
+
+jest.mock('./ParentSubagentsProvider', () => ({
+ useParentSubagents: () => ({
+ byMessageId: mockParentChildrenByMessage,
+ byThreadId: mockParentChildrenByThread,
+ refresh: mockRefreshParentChildren,
+ }),
+}));
+
jest.mock('~/components/Chat/Messages/Content/ApprovalContext', () => ({
__esModule: true,
default: ({ children }: { children: React.ReactNode }) => {
@@ -83,13 +106,45 @@ jest.mock('./SubagentActivity', () => ({
),
}));
-jest.mock('@librechat/client', () => ({
- Button: ({ children, ...props }: React.ComponentProps<'button'>) => (
- <button {...props}>{children}</button>
- ),
- useMediaQuery: () => mockIsMobile,
- useToastContext: () => ({ showToast: mockShowToast }),
-}));
+jest.mock('@librechat/client', () => {
+ const mockReact = jest.requireActual<typeof import('react')>('react');
+ const MockSelectContext = mockReact.createContext((_value: string): void => {});
+ return {
+ Button: ({ children, ...props }: React.ComponentProps<'button'>) => (
+ <button {...props}>{children}</button>
+ ),
+ Select: ({
+ children,
+ onValueChange,
+ }: {
+ children: React.ReactNode;
+ onValueChange: (value: string) => void;
+ }) => <MockSelectContext.Provider value={onValueChange}>{children}</MockSelectContext.Provider>,
+ SelectTrigger: ({ children, ...props }: React.ComponentProps<'button'>) => (
+ <button role="combobox" aria-controls="mock-select-options" aria-expanded="true" {...props}>
+ {children}
+ </button>
+ ),
+ SelectValue: () => null,
+ SelectContent: ({ children }: { children: React.ReactNode }) => (
+ <div id="mock-select-options">{children}</div>
+ ),
+ SelectItem: ({
+ value,
+ children,
+ ...props
+ }: React.ComponentProps<'button'> & { value: string }) => {
+ const onValueChange = mockReact.useContext(MockSelectContext);
+ return (
+ <button role="option" aria-selected="false" onClick={() => onValueChange(value)} {...props}>
+ {children}
+ </button>
+ );
+ },
+ useMediaQuery: () => mockIsMobile,
+ useToastContext: () => ({ showToast: mockShowToast }),
+ };
+});
jest.mock('lucide-react', () => ({
AlertCircle: () => null,
@@ -151,6 +206,9 @@ describe('SubagentThreadPanel', () => {
mockForkMutate.mockClear();
mockNavigateToConvo.mockClear();
mockShowToast.mockClear();
+ mockRefreshParentChildren.mockClear();
+ mockParentChildrenByMessage = new Map();
+ mockParentChildrenByThread = new Map();
});
it('renders a bounded read-only activity timeline and closes its selection', async () => {
@@ -183,6 +241,7 @@ describe('SubagentThreadPanel', () => {
'parent-conversation',
'child-thread',
'task',
+ undefined,
);
expect(mockUseSubagentActivityStream).toHaveBeenCalledWith(selection, false);
expect(screen.getByText('Research child')).toBeInTheDocument();
@@ -446,6 +505,54 @@ describe('SubagentThreadPanel', () => {
expect(mockUseSubagentActivityStream).toHaveBeenLastCalledWith(selection, true);
});
+ it('revalidates a cached terminal event task when its lease resumes', async () => {
+ const refetch = jest.fn().mockResolvedValue({ data: { ...completedView, status: 'running' } });
+ const eventSelection: ActiveSubagentPanel = {
+ ...selection,
+ event: { actorId: 'actor-1', progressKey: 'event-task:child-thread:task' },
+ };
+ mockParentChildrenByThread = new Map([
+ [
+ 'child-thread',
+ {
+ threadId: 'child-thread',
+ parentMessageId: 'parent-message',
+ subagentType: 'agent-1',
+ subagentKind: 'agent',
+ title: 'Event child',
+ origin: 'event',
+ actorId: 'actor-1',
+ status: 'running',
+ latestTaskId: 'task',
+ tasks: [{ taskId: 'task', status: 'running' }],
+ tasksTruncated: false,
+ },
+ ],
+ ]);
+ mockUseSubagentThreadQuery.mockReturnValue({
+ data: completedView,
+ isLoading: false,
+ isError: false,
+ isReadinessPending: false,
+ refetch,
+ });
+
+ render(
+ <RecoilRoot>
+ <SubagentThreadPanel selection={eventSelection} />
+ </RecoilRoot>,
+ );
+
+ expect(mockUseSubagentThreadQuery).toHaveBeenCalledWith(
+ 'parent-conversation',
+ 'child-thread',
+ 'task',
+ { refetchInterval: 2000 },
+ );
+ expect(mockUseSubagentActivityStream).toHaveBeenLastCalledWith(eventSelection, true);
+ await waitFor(() => expect(refetch).toHaveBeenCalled());
+ });
+
it('surfaces a durable read failure after the readiness window', () => {
mockUseSubagentThreadQuery.mockReturnValue({
data: undefined,
@@ -519,4 +626,79 @@ describe('SubagentThreadPanel', () => {
expect(screen.getByRole('dialog')).toHaveAttribute('aria-modal', 'true');
});
+
+ it('navigates event actors and exact durable turns through the same panel', () => {
+ const first: ParentSubagentSummary = {
+ threadId: 'child-thread',
+ parentMessageId: 'parent-message',
+ subagentType: 'agent-1',
+ subagentKind: 'agent',
+ agentId: 'agent-1',
+ title: 'First actor',
+ origin: 'event',
+ actorId: 'actor-1',
+ status: 'completed',
+ latestTaskId: 'task',
+ tasks: [
+ { taskId: 'task', status: 'completed' },
+ { taskId: 'task-earlier', status: 'completed' },
+ ],
+ tasksTruncated: false,
+ };
+ const second: ParentSubagentSummary = {
+ ...first,
+ threadId: 'child-thread-2',
+ subagentType: 'agent-2',
+ agentId: 'agent-2',
+ title: 'Second actor',
+ actorId: 'actor-2',
+ latestTaskId: 'task-2',
+ tasks: [{ taskId: 'task-2', status: 'running' }],
+ status: 'running',
+ };
+ mockParentChildrenByMessage = new Map([['parent-message', [first, second]]]);
+ mockParentChildrenByThread = new Map([
+ [first.threadId, first],
+ [second.threadId, second],
+ ]);
+ mockUseSubagentThreadQuery.mockReturnValue({
+ data: completedView,
+ isLoading: false,
+ isError: false,
+ isReadinessPending: false,
+ });
+ const eventSelection: ActiveSubagentPanel = {
+ ...selection,
+ event: { actorId: 'actor-1', progressKey: 'event-task:child-thread:task' },
+ };
+ let active: ActiveSubagentPanel | null = eventSelection;
+ const Observer = () => {
+ active = useRecoilValue(activeSubagentPanel);
+ return null;
+ };
+
+ render(
+ <RecoilRoot initializeState={({ set }) => set(activeSubagentPanel, eventSelection)}>
+ <Observer />
+ <SubagentThreadPanel selection={eventSelection} />
+ </RecoilRoot>,
+ );
+
+ fireEvent.click(screen.getByRole('option', { name: 'com_ui_subagent_earlier_turn' }));
+ expect(active?.durable).toEqual({ threadId: 'child-thread', taskId: 'task-earlier' });
+ expect(active?.event?.progressKey).toBe('event-task:child-thread:task-earlier');
+
+ fireEvent.click(screen.getByRole('option', { name: /Analyst Two/ }));
+ expect(active).toEqual(
+ expect.objectContaining({
+ subagentType: 'agent-2',
+ event: {
+ actorId: 'actor-2',
+ progressKey: 'event-task:child-thread-2:task-2',
+ },
+ durable: { threadId: 'child-thread-2', taskId: 'task-2' },
+ }),
+ );
+ expect(mockRefreshParentChildren).toHaveBeenCalled();
+ });
});
diff --git a/client/src/components/Chat/Subagents/SubagentThreadPanel.tsx b/client/src/components/Chat/Subagents/SubagentThreadPanel.tsx
index 73b9fdd9fc..90d01d1331 100644
--- a/client/src/components/Chat/Subagents/SubagentThreadPanel.tsx
+++ b/client/src/components/Chat/Subagents/SubagentThreadPanel.tsx
@@ -1,10 +1,20 @@
import { useCallback, useEffect, useMemo, useRef } from 'react';
import { Bot, MessagesSquare, X } from 'lucide-react';
import { ForkOptions } from 'librechat-data-provider';
-import { useRecoilValue, useResetRecoilState } from 'recoil';
-import { Button, useMediaQuery, useToastContext } from '@librechat/client';
+import { useRecoilValue, useResetRecoilState, useSetRecoilState } from 'recoil';
+import {
+ Button,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+ useMediaQuery,
+ useToastContext,
+} from '@librechat/client';
import type { ActiveSubagentPanel } from '~/store/subagents';
import {
+ ACTIVE_THREAD_REFRESH_MS,
subagentThreadHasTaskEvidence,
useForkConvoMutation,
useSubagentThreadQuery,
@@ -17,8 +27,11 @@ import {
import useSubagentActivityStream from '~/data-provider/Subagents/useSubagentActivityStream';
import { adaptDurableThreadActivity, adaptLivePersistedActivity } from './adapters';
import ApprovalProvider from '~/components/Chat/Messages/Content/ApprovalContext';
+import { eventSubagentSelection, eventTaskProgressKey } from './eventSelection';
import { useFocusTrap, useLocalize, useNavigateToConvo } from '~/hooks';
+import { useParentSubagents } from './ParentSubagentsProvider';
import SubagentActivity from './SubagentActivity';
+import { useAgentsMapContext } from '~/Providers';
export default function SubagentThreadPanel({ selection }: { selection: ActiveSubagentPanel }) {
const localize = useLocalize();
@@ -27,9 +40,16 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
const panelRef = useRef<HTMLDivElement>(null);
const isMobile = useMediaQuery('(max-width: 767px)');
const resetSelection = useResetRecoilState(activeSubagentPanel);
+ const setSelection = useSetRecoilState(activeSubagentPanel);
+ const agentsMap = useAgentsMapContext();
+ const { byMessageId, byThreadId, refresh } = useParentSubagents();
const progress = useRecoilValue(
subagentProgressByToolCallId(
- subagentProgressKey(selection.parentMessageId, selection.toolCallId, selection.partIndex),
+ subagentProgressKey(
+ selection.parentMessageId,
+ selection.event?.progressKey ?? selection.toolCallId,
+ selection.partIndex,
+ ),
),
);
const foregroundTitle =
@@ -38,10 +58,18 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
: localize('com_ui_subagent_dialog_title', { 0: selection.subagentType });
const threadId = selection.durable?.threadId ?? '';
const taskId = selection.durable?.taskId ?? '';
- const { data, isLoading, isError, isReadinessPending } = useSubagentThreadQuery(
+ const eventSummary = selection.event == null ? undefined : byThreadId.get(threadId);
+ const eventTaskRunning =
+ eventSummary?.tasks.find((task) => task.taskId === taskId)?.status === 'running';
+ const eventSiblings = useMemo(
+ () => (selection.event == null ? [] : (byMessageId.get(selection.parentMessageId) ?? [])),
+ [byMessageId, selection.event, selection.parentMessageId],
+ );
+ const { data, isLoading, isError, isReadinessPending, refetch } = useSubagentThreadQuery(
selection.parentConversationId,
threadId,
taskId,
+ eventTaskRunning ? { refetchInterval: ACTIVE_THREAD_REFRESH_MS } : undefined,
);
const durableTerminal =
subagentThreadHasTaskEvidence(data, taskId) &&
@@ -49,7 +77,28 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
data?.status === 'failed' ||
data?.status === 'interrupted' ||
data?.status === 'cancelled');
- useSubagentActivityStream(selection, !durableTerminal);
+ const priorTerminalRef = useRef(false);
+ useSubagentActivityStream(selection, !durableTerminal || eventTaskRunning);
+
+ useEffect(() => {
+ if (selection.event == null) return;
+ void refresh();
+ }, [refresh, selection.event, threadId]);
+
+ useEffect(() => {
+ priorTerminalRef.current = false;
+ }, [taskId, threadId]);
+
+ useEffect(() => {
+ if (selection.event == null) return;
+ if (durableTerminal && !priorTerminalRef.current) void refresh();
+ priorTerminalRef.current = durableTerminal;
+ }, [durableTerminal, refresh, selection.event]);
+
+ useEffect(() => {
+ if (selection.event == null || !eventTaskRunning || !durableTerminal) return;
+ void refetch();
+ }, [durableTerminal, eventTaskRunning, refetch, selection.event]);
const detachedLiveSubmitting =
selection.durable != null &&
progress != null &&
@@ -148,6 +197,32 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
option: ForkOptions.DIRECT_PATH,
});
}, [canContinueAsChat, continueChat, selection.durable]);
+ const selectActor = useCallback(
+ (nextThreadId: string) => {
+ const next = eventSiblings.find((child) => child.threadId === nextThreadId);
+ if (next == null) return;
+ const nextSelection = eventSubagentSelection(selection.parentConversationId, next);
+ if (nextSelection != null) setSelection(nextSelection);
+ },
+ [eventSiblings, selection.parentConversationId, setSelection],
+ );
+ const selectTask = useCallback(
+ (nextTaskId: string) => {
+ if (selection.durable == null || selection.event == null) return;
+ const nextTask = eventSummary?.tasks.find((task) => task.taskId === nextTaskId);
+ setSelection({
+ ...selection,
+ durable: { ...selection.durable, taskId: nextTaskId },
+ event: {
+ ...selection.event,
+ progressKey: eventTaskProgressKey(selection.durable.threadId, nextTaskId),
+ },
+ initialProgress: nextTask?.status === 'completed' ? 1 : 0,
+ isSubmitting: nextTask?.status === 'running',
+ });
+ },
+ [eventSummary?.tasks, selection, setSelection],
+ );
let panelState: 'ready' | 'loading' | 'error' = 'ready';
if (
selection.durable != null &&
@@ -202,6 +277,50 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
</Button>
</header>
+ {selection.event != null && (
+ <div className="flex shrink-0 items-center gap-2 border-b border-border-light px-4 py-2">
+ <div className="min-w-0 flex-1">
+ <Select value={threadId} onValueChange={selectActor}>
+ <SelectTrigger className="h-8" aria-label={localize('com_ui_subagent_actor')}>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {eventSiblings.map((child) => (
+ <SelectItem
+ key={child.threadId}
+ value={child.threadId}
+ disabled={!child.latestTaskId}
+ >
+ {child.agentId != null && agentsMap?.[child.agentId]?.name
+ ? agentsMap[child.agentId]?.name
+ : child.actorId || child.title}
+ {child.actorId != null && agentsMap?.[child.agentId ?? '']?.name
+ ? ` · ${child.actorId}`
+ : ''}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ <div className="w-32">
+ <Select value={taskId} onValueChange={selectTask}>
+ <SelectTrigger className="h-8" aria-label={localize('com_ui_subagent_turn')}>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {(eventSummary?.tasks ?? []).map((task, index) => (
+ <SelectItem key={task.taskId} value={task.taskId}>
+ {index === 0
+ ? localize('com_ui_subagent_latest_turn')
+ : localize('com_ui_subagent_earlier_turn', { 0: String(index) })}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ </div>
+ )}
+
{/* Keep the foreground panel's existing nested-tool approval controls
coordinated within this invocation. Detached activity projections
never include approval payloads. */}
diff --git a/client/src/components/Chat/Subagents/eventSelection.ts b/client/src/components/Chat/Subagents/eventSelection.ts
new file mode 100644
index 0000000000..ed37258886
--- /dev/null
+++ b/client/src/components/Chat/Subagents/eventSelection.ts
@@ -0,0 +1,25 @@
+import type { ParentSubagentSummary } from 'librechat-data-provider';
+import type { ActiveSubagentPanel } from '~/store/subagents';
+
+export const eventTaskProgressKey = (threadId: string, taskId: string) =>
+ `event-task:${threadId}:${taskId}`;
+
+export const eventSubagentSelection = (
+ parentConversationId: string,
+ child: ParentSubagentSummary,
+): ActiveSubagentPanel | null => {
+ const taskId = child.latestTaskId;
+ if (child.origin !== 'event' || child.actorId == null || taskId == null) return null;
+ return {
+ host: 'conversation',
+ parentConversationId,
+ parentMessageId: child.parentMessageId,
+ toolCallId: `event-thread:${child.threadId}`,
+ partIndex: 0,
+ subagentType: child.subagentType,
+ initialProgress: child.status === 'completed' ? 1 : 0,
+ isSubmitting: child.status === 'running',
+ durable: { threadId: child.threadId, taskId },
+ event: { actorId: child.actorId, progressKey: eventTaskProgressKey(child.threadId, taskId) },
+ };
+};
diff --git a/client/src/components/Chat/Subagents/status.ts b/client/src/components/Chat/Subagents/status.ts
new file mode 100644
index 0000000000..828a35204d
--- /dev/null
+++ b/client/src/components/Chat/Subagents/status.ts
@@ -0,0 +1,21 @@
+import { AlertCircle, CheckCircle2, Clock3, XCircle } from 'lucide-react';
+import type { SubagentThreadStatus } from 'librechat-data-provider';
+
+export const subagentStatusIcon = (status: SubagentThreadStatus) => {
+ if (status === 'completed') return CheckCircle2;
+ if (status === 'failed' || status === 'interrupted') return AlertCircle;
+ if (status === 'cancelled') return XCircle;
+ return Clock3;
+};
+
+export const subagentStatusLabelKey = (status: SubagentThreadStatus) =>
+ (
+ ({
+ dispatched: 'com_ui_subagent_thread_status_dispatched',
+ running: 'com_ui_subagent_thread_status_running',
+ completed: 'com_ui_subagent_thread_status_completed',
+ failed: 'com_ui_subagent_thread_status_failed',
+ interrupted: 'com_ui_subagent_thread_status_interrupted',
+ cancelled: 'com_ui_subagent_thread_status_cancelled',
+ }) as const
+ )[status];
diff --git a/client/src/data-provider/Subagents/queries.test.ts b/client/src/data-provider/Subagents/queries.test.ts
index 0c464f04be..d1683d7c5a 100644
--- a/client/src/data-provider/Subagents/queries.test.ts
+++ b/client/src/data-provider/Subagents/queries.test.ts
@@ -1,9 +1,11 @@
import { renderHook } from '@testing-library/react';
-import type { SubagentThreadView } from 'librechat-data-provider';
+import type { ParentSubagentIndex, SubagentThreadView } from 'librechat-data-provider';
import {
isSubagentReadinessPending,
+ parentSubagentsRefetchInterval,
subagentThreadHasTaskEvidence,
subagentThreadRefetchInterval,
+ useParentSubagentsQuery,
useSubagentThreadQuery,
} from './queries';
@@ -99,4 +101,37 @@ describe('subagent thread refresh policy', () => {
]);
expect(refetch).not.toHaveBeenCalled();
});
+
+ it('refreshes active parent children quickly and discovers idle actors at a bounded cadence', () => {
+ expect(
+ parentSubagentsRefetchInterval({
+ parentConversationId: 'parent-conversation',
+ childrenTruncated: false,
+ children: [{ status: 'running' }],
+ } as ParentSubagentIndex),
+ ).toBe(2_000);
+ expect(
+ parentSubagentsRefetchInterval({
+ parentConversationId: 'parent-conversation',
+ childrenTruncated: false,
+ children: [{ status: 'dispatched' }],
+ } as ParentSubagentIndex),
+ ).toBe(10_000);
+ expect(parentSubagentsRefetchInterval(undefined)).toBe(10_000);
+
+ mockUseQuery.mockReturnValue({ data: undefined, error: null, refetch: jest.fn() });
+
+ renderHook(() => useParentSubagentsQuery('parent-conversation'));
+
+ expect(mockUseQuery.mock.calls.at(-1)?.[0]).toEqual(['parentSubagents', 'parent-conversation']);
+ expect(mockUseQuery.mock.calls.at(-1)?.[2]).toEqual(
+ expect.objectContaining({
+ enabled: true,
+ refetchOnWindowFocus: true,
+ refetchInterval: parentSubagentsRefetchInterval,
+ refetchIntervalInBackground: false,
+ staleTime: 5_000,
+ }),
+ );
+ });
});
diff --git a/client/src/data-provider/Subagents/queries.ts b/client/src/data-provider/Subagents/queries.ts
index bb626cb345..bac18486d4 100644
--- a/client/src/data-provider/Subagents/queries.ts
+++ b/client/src/data-provider/Subagents/queries.ts
@@ -1,12 +1,38 @@
import { useMemo } from 'react';
import { useQuery } from '@tanstack/react-query';
-import { QueryKeys, dataService } from 'librechat-data-provider';
+import { Constants, QueryKeys, dataService } from 'librechat-data-provider';
+import type { ParentSubagentIndex, SubagentThreadView } from 'librechat-data-provider';
import type { UseQueryOptions, QueryObserverResult } from '@tanstack/react-query';
-import type { SubagentThreadView } from 'librechat-data-provider';
-const ACTIVE_THREAD_REFRESH_MS = 2_000;
+export const ACTIVE_THREAD_REFRESH_MS = 2_000;
+const IDLE_PARENT_REFRESH_MS = 10_000;
const CHILD_READY_POLL_WINDOW_MS = 60_000;
+export const parentSubagentsRefetchInterval = (index: ParentSubagentIndex | undefined): number =>
+ index?.children.some((child) => child.status === 'running') === true
+ ? ACTIVE_THREAD_REFRESH_MS
+ : IDLE_PARENT_REFRESH_MS;
+
+export const useParentSubagentsQuery = (
+ parentConversationId: string,
+ config?: UseQueryOptions<ParentSubagentIndex>,
+) =>
+ useQuery<ParentSubagentIndex>(
+ [QueryKeys.parentSubagents, parentConversationId],
+ () => dataService.getParentSubagents(parentConversationId),
+ {
+ enabled:
+ parentConversationId !== '' &&
+ parentConversationId !== Constants.NEW_CONVO &&
+ parentConversationId !== Constants.PENDING_CONVO,
+ staleTime: 5_000,
+ refetchOnWindowFocus: true,
+ refetchInterval: parentSubagentsRefetchInterval,
+ refetchIntervalInBackground: false,
+ ...config,
+ },
+ );
+
const isTerminal = (status: SubagentThreadView['status']): boolean =>
status === 'completed' ||
status === 'failed' ||
diff --git a/client/src/data-provider/Subagents/useSubagentActivityStream.ts b/client/src/data-provider/Subagents/useSubagentActivityStream.ts
index 1bce9741ee..89f36eaf54 100644
--- a/client/src/data-provider/Subagents/useSubagentActivityStream.ts
+++ b/client/src/data-provider/Subagents/useSubagentActivityStream.ts
@@ -48,7 +48,7 @@ export default function useSubagentActivityStream(
const queryClient = useQueryClient();
const key = subagentProgressKey(
selection.parentMessageId,
- selection.toolCallId,
+ selection.event?.progressKey ?? selection.toolCallId,
selection.partIndex,
);
const setProgress = useSetRecoilState(subagentProgressByToolCallId(key));
@@ -125,7 +125,11 @@ export default function useSubagentActivityStream(
if (envelope.event !== StepEvents.ON_SUBAGENT_UPDATE || !isSubagentUpdate(event)) {
return;
}
- if (event.parentToolCallId != null && event.parentToolCallId !== selection.toolCallId) {
+ if (
+ selection.event == null &&
+ event.parentToolCallId != null &&
+ event.parentToolCallId !== selection.toolCallId
+ ) {
return;
}
retryAttempt = 0;
@@ -155,6 +159,7 @@ export default function useSubagentActivityStream(
key,
queryClient,
selection.host,
+ selection.event,
selection.parentConversationId,
selection.parentMessageId,
selection.partIndex,
diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json
index 13bb8b01c9..03c6c50c97 100644
--- a/client/src/locales/en/translation.json
+++ b/client/src/locales/en/translation.json
@@ -2178,12 +2178,15 @@
"com_ui_storage_filter_sort": "Filter and Sort by Storage",
"com_ui_subagent_back_to_parent": "Back to parent chat",
"com_ui_subagent_activity": "Agent activity",
+ "com_ui_subagent_actor": "Agent",
"com_ui_subagent_cancelled": "Cancelled agent",
"com_ui_subagent_complete": "Ran agent",
"com_ui_subagent_dialog_title": "\"{{0}}\" agent",
"com_ui_subagent_dialog_title_self": "Agent",
+ "com_ui_subagent_earlier_turn": "Earlier turn {{0}}",
"com_ui_subagent_empty_result": "No text returned.",
"com_ui_subagent_errored": "Agent errored",
+ "com_ui_subagent_latest_turn": "Latest turn",
"com_ui_subagent_no_result_yet": "Still running — no final result yet.",
"com_ui_subagent_thread_history_truncated": "Earlier activity is not shown.",
"com_ui_subagent_thread_load_error": "The agent activity could not be loaded.",
@@ -2195,6 +2198,7 @@
"com_ui_subagent_thread_status_failed": "Failed",
"com_ui_subagent_thread_status_interrupted": "Interrupted",
"com_ui_subagent_thread_status_running": "Running",
+ "com_ui_subagent_turn": "Turn",
"com_ui_subagent_running": "Running agent",
"com_ui_subagent_scroll_to_bottom": "Scroll to latest",
"com_ui_subagent_ticker_error": "Error",
diff --git a/client/src/store/subagents.ts b/client/src/store/subagents.ts
index 4940a39bc2..d41bd15d27 100644
--- a/client/src/store/subagents.ts
+++ b/client/src/store/subagents.ts
@@ -267,6 +267,11 @@ export type ActiveSubagentPanel = {
threadId: string;
taskId: string;
};
+ event?: {
+ actorId: string;
+ /** Task-specific live activity identity; the actor thread is reused across turns. */
+ progressKey: string;
+ };
};
export const activeSubagentPanel = atom<ActiveSubagentPanel | null>({
diff --git a/packages/api/src/agents/subagentActivity.spec.ts b/packages/api/src/agents/subagentActivity.spec.ts
index 6ad331e69e..e25c9fb141 100644
--- a/packages/api/src/agents/subagentActivity.spec.ts
+++ b/packages/api/src/agents/subagentActivity.spec.ts
@@ -465,6 +465,96 @@ describe('subagent activity stream authorization', () => {
res.emit('close');
});
+ it('redacts private event-binding identity from live child activity', async () => {
+ const transport = new TestTransport();
+ const stream = new SubagentActivityStream(transport);
+ const handler = createSubagentActivityStreamHandler(
+ {
+ getConvoOwnership: jest.fn().mockResolvedValue(parent),
+ getSubagentThreadForParent: jest.fn().mockResolvedValue({
+ ...child,
+ actorId: 'actor-a',
+ subagentThread: {
+ ...child.subagentThread,
+ parentToolCallId: 'event-binding:private-binding-id',
+ },
+ }),
+ getMessages: jest.fn().mockResolvedValue([]),
+ },
+ stream,
+ );
+ const res = response();
+
+ await handler(request(), res);
+ await stream.publish(
+ threadId,
+ taskId,
+ update({
+ parentToolCallId: 'event-binding:private-binding-id',
+ ancestry: [
+ {
+ subagentRunId: 'parent-run',
+ subagentType: 'parent',
+ subagentKind: 'agent',
+ subagentAgentId: 'parent-agent',
+ parentRunId: 'root-run',
+ parentToolCallId: 'event-binding:private-ancestor-id',
+ },
+ ],
+ }),
+ );
+
+ const output = res.chunks.join('');
+ expect(output).toContain('event-thread:child-thread');
+ expect(output).not.toContain('private-binding-id');
+ expect(output).not.toContain('private-ancestor-id');
+ res.emit('close');
+ });
+
+ it('recognizes an ordinary persisted event assistant row as terminal', async () => {
+ const transport = new TestTransport();
+ const stream = new SubagentActivityStream(transport);
+ const handler = createSubagentActivityStreamHandler(
+ {
+ getConvoOwnership: jest.fn().mockResolvedValue(parent),
+ getSubagentThreadForParent: jest.fn().mockResolvedValue(child),
+ getMessages: jest
+ .fn()
+ .mockResolvedValue([{ messageId: `${taskId}:assistant`, error: false }]),
+ },
+ stream,
+ );
+ const res = response();
+
+ await handler(request(), res);
+
+ expect(res.chunks.join('')).toContain('"status":"completed"');
+ expect(transport.handlers.size).toBe(0);
+ });
+
+ it('keeps streaming through an unfinished snapshot while the exact lease is active', async () => {
+ const transport = new TestTransport();
+ const stream = new SubagentActivityStream(transport);
+ const handler = createSubagentActivityStreamHandler(
+ {
+ getConvoOwnership: jest.fn().mockResolvedValue(parent),
+ getSubagentThreadForParent: jest.fn().mockResolvedValue(child),
+ getMessages: jest
+ .fn()
+ .mockResolvedValue([{ messageId: `${taskId}:assistant`, unfinished: true }]),
+ },
+ stream,
+ );
+ const res = response();
+
+ await handler(request(), res);
+
+ expect(res.chunks.join('')).toContain('"ready":true');
+ expect(res.chunks.join('')).not.toContain('"final":true');
+ expect(transport.handlers.size).toBe(1);
+ res.emit('close');
+ });
+
it('returns the same 404 for a mismatched task without subscribing', async () => {
const transport = new TestTransport();
const stream = new SubagentActivityStream(transport);
diff --git a/packages/api/src/agents/subagentActivity.ts b/packages/api/src/agents/subagentActivity.ts
index f91ec2e700..5e6471f461 100644
--- a/packages/api/src/agents/subagentActivity.ts
+++ b/packages/api/src/agents/subagentActivity.ts
@@ -358,10 +358,21 @@ const terminalTaskStatus = async (
messageId: `${taskId}:assistant`,
...(tenantId == null ? { tenantId: { $exists: false } } : { tenantId }),
},
- 'messageId +subagentTask',
+ 'messageId error unfinished +subagentTask',
{ limit: 1 },
);
- return terminalStatus(messages[0]?.subagentTask?.status);
+ const message = messages[0];
+ let status = message?.subagentTask?.status;
+ if (status == null && message != null) {
+ if (message.error === true) {
+ status = 'error';
+ } else if (message.unfinished === true) {
+ return undefined;
+ } else {
+ status = 'completed';
+ }
+ }
+ return terminalStatus(status);
};
const notFound = (res: Response): void => {
@@ -371,6 +382,30 @@ const notFound = (res: Response): void => {
const writeSse = (res: Response, value: unknown): boolean =>
!res.writableEnded && res.write(`data: ${JSON.stringify(value)}\n\n`);
+/** Event-bound children use a private binding id as their internal tool-call
+ * identity. Keep that delivery identity behind the parent-authorized API
+ * boundary while preserving a stable public identity for the activity UI. */
+const publicActivityEnvelope = (
+ event: SubagentActivityEnvelope,
+ threadId: string,
+ eventBound: boolean,
+): SubagentActivityEnvelope => {
+ if (!eventBound) return event;
+ const ancestry = (event.data.ancestry ?? []).map((entry) => {
+ if (!entry.parentToolCallId?.startsWith('event-binding:')) return entry;
+ const { parentToolCallId: _privateDeliveryId, ...publicEntry } = entry;
+ return publicEntry;
+ });
+ return {
+ ...event,
+ data: {
+ ...event.data,
+ parentToolCallId: `event-thread:${boundedString(threadId, MAX_ID_BYTES - 13) ?? ''}`,
+ ancestry,
+ },
+ };
+};
+
/** Streams one active child task after the same parent/tenant authorization as its durable view. */
export function createSubagentActivityStreamHandler(
deps: SubagentActivityStreamDependencies,
@@ -448,7 +483,16 @@ export function createSubagentActivityStreamHandler(
try {
subscription = stream.subscribe(threadId, taskId, {
onEvent: (event) => {
- if (!writeSse(res, event)) {
+ if (
+ !writeSse(
+ res,
+ publicActivityEnvelope(
+ event,
+ threadId,
+ lineage?.parentToolCallId?.startsWith('event-binding:') === true,
+ ),
+ )
+ ) {
close();
res.end();
}
diff --git a/packages/api/src/agents/subagentThreads.ts b/packages/api/src/agents/subagentThreads.ts
index b90b859be4..e32854f459 100644
--- a/packages/api/src/agents/subagentThreads.ts
+++ b/packages/api/src/agents/subagentThreads.ts
@@ -563,6 +563,14 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
return this.activityStream.subscribe(threadId, taskId, subscriber);
}
+ /** Publishes activity produced by a host-owned event child. Event children
+ * use the same bounded, demand-aware transport as detached tool children,
+ * but their generation lease is owned by the trigger controller instead of
+ * this task store. */
+ publishTaskActivity(threadId: string, taskId: string, event: SubagentUpdateEvent): Promise<void> {
+ return this.activityStream.publish(threadId, taskId, boundSubagentActivityUpdate(event));
+ }
+
private publishActivity(
lease: TaskThreadLease,
threadId: string,
diff --git a/packages/api/src/agents/triggers/lease.spec.ts b/packages/api/src/agents/triggers/lease.spec.ts
index a40125a493..f795748e01 100644
--- a/packages/api/src/agents/triggers/lease.spec.ts
+++ b/packages/api/src/agents/triggers/lease.spec.ts
@@ -171,12 +171,13 @@ describe('event child generation lease', () => {
tenantId: 'tenant-1',
conversationId: 'child-1',
streamId: 'child-1',
+ taskId: 'delivery-1',
jobCreatedAt: 123,
retentionExpiresAt,
});
expect(acquireSubagentThreadLease).toHaveBeenCalledWith(
- expect.objectContaining({ expiresAt: retentionExpiresAt }),
+ expect.objectContaining({ taskId: 'delivery-1', expiresAt: retentionExpiresAt }),
);
await jest.advanceTimersByTimeAsync(4_999);
expect(abortGeneration).not.toHaveBeenCalled();
diff --git a/packages/api/src/agents/triggers/lease.ts b/packages/api/src/agents/triggers/lease.ts
index ebd5df076d..1a26a9a71e 100644
--- a/packages/api/src/agents/triggers/lease.ts
+++ b/packages/api/src/agents/triggers/lease.ts
@@ -29,6 +29,8 @@ export interface EventChildGenerationLeaseInput {
tenantId?: string;
conversationId: string;
streamId: string;
+ /** Stable logical delivery identity exposed through the parent activity view. */
+ taskId?: string;
jobCreatedAt: number;
retentionExpiresAt?: Date | string | number;
}
@@ -45,6 +47,7 @@ export function createEventChildGenerationLeaseAcquirer({
tenantId,
conversationId,
streamId,
+ taskId,
jobCreatedAt,
retentionExpiresAt,
}: EventChildGenerationLeaseInput): Promise<ReleaseEventChildGenerationLease | null> {
@@ -75,7 +78,7 @@ export function createEventChildGenerationLeaseAcquirer({
};
const acquired = await methods.acquireSubagentThreadLease({
...leaseIdentity,
- taskId: streamId,
+ taskId: taskId ?? streamId,
now: new Date(initialTime),
expiresAt: new Date(initialLeaseDeadline),
});
diff --git a/packages/api/src/agents/view.spec.ts b/packages/api/src/agents/view.spec.ts
index 9849af90e4..8bee7350d9 100644
--- a/packages/api/src/agents/view.spec.ts
+++ b/packages/api/src/agents/view.spec.ts
@@ -1,7 +1,12 @@
import type { IConversation, IMessage } from '@librechat/data-schemas';
import type { Response } from 'express';
import type { ServerRequest } from '~/types';
-import { createSubagentThreadViewHandler, SUBAGENT_THREAD_VIEW_LIMITS } from './view';
+import {
+ createParentSubagentIndexHandler,
+ createSubagentThreadViewHandler,
+ PARENT_SUBAGENT_INDEX_LIMITS,
+ SUBAGENT_THREAD_VIEW_LIMITS,
+} from './view';
jest.mock('@librechat/data-schemas', () => ({
CLIENT_MESSAGE_SELECT: '-_id -user',
@@ -553,3 +558,320 @@ describe('subagent thread parent-scoped view', () => {
expect(json.mock.calls[0][0]).toEqual(expect.objectContaining({ status: 'interrupted' }));
});
});
+
+describe('parent child-thread index', () => {
+ const eventChild = {
+ ...child,
+ conversationId: 'event-thread',
+ title: 'Agent actor: analyst-a',
+ actorId: 'analyst-a',
+ subagentThread: {
+ ...child.subagentThread!,
+ parentToolCallId: 'event-binding:private-binding-id',
+ },
+ };
+
+ it('returns one bounded actor projection and batches task discovery', async () => {
+ const listSubagentThreadsForParent = jest.fn().mockResolvedValue([eventChild]);
+ const listSubagentTasksForThreads = jest.fn().mockResolvedValue([
+ {
+ conversationId: 'event-thread',
+ tasks: [
+ {
+ messageId: 'task-1:assistant',
+ status: 'completed',
+ createdAt: new Date('2026-08-21T11:01:00.000Z'),
+ },
+ ],
+ },
+ ]);
+ const handler = createParentSubagentIndexHandler({
+ getConvoOwnership: jest.fn().mockResolvedValue(parent),
+ listSubagentThreadsForParent,
+ listSubagentTasksForThreads,
+ });
+ const { response, json } = createResponse();
+
+ await handler(createRequest(), response);
+
+ expect(listSubagentThreadsForParent).toHaveBeenCalledWith({
+ user: 'user-1',
+ parentConversationId,
+ tenantId: 'tenant-1',
+ limit: PARENT_SUBAGENT_INDEX_LIMITS.children + 1,
+ });
+ expect(listSubagentTasksForThreads).toHaveBeenCalledTimes(1);
+ expect(listSubagentTasksForThreads).toHaveBeenCalledWith({
+ user: 'user-1',
+ conversationIds: ['event-thread'],
+ tenantId: 'tenant-1',
+ limitPerThread: PARENT_SUBAGENT_INDEX_LIMITS.tasksPerChild + 1,
+ });
+ expect(json).toHaveBeenCalledWith({
+ parentConversationId,
+ childrenTruncated: false,
+ children: [
+ expect.objectContaining({
+ threadId: 'event-thread',
+ origin: 'event',
+ actorId: 'analyst-a',
+ status: 'completed',
+ latestTaskId: 'task-1',
+ tasks: [expect.objectContaining({ taskId: 'task-1', status: 'completed' })],
+ }),
+ ],
+ });
+ const publicJson = JSON.stringify(json.mock.calls[0][0]);
+ expect(publicJson).not.toContain('private-binding-id');
+ expect(publicJson).not.toContain('subagentThreadLease');
+ expect(publicJson).not.toContain('sourceKeyId');
+ });
+
+ it('propagates a filled shared task window as truncated child history', async () => {
+ const handler = createParentSubagentIndexHandler({
+ getConvoOwnership: jest.fn().mockResolvedValue(parent),
+ listSubagentThreadsForParent: jest.fn().mockResolvedValue([eventChild]),
+ listSubagentTasksForThreads: jest.fn().mockResolvedValue([
+ {
+ conversationId: 'event-thread',
+ sourceTruncated: true,
+ tasks: [
+ {
+ messageId: 'task-1:assistant',
+ status: 'completed',
+ createdAt: new Date('2026-08-21T11:01:00.000Z'),
+ },
+ ],
+ },
+ ]),
+ });
+ const { response, json } = createResponse();
+
+ await handler(createRequest(), response);
+
+ expect(json.mock.calls[0][0].children[0]).toEqual(
+ expect.objectContaining({ tasksTruncated: true }),
+ );
+ });
+
+ it('keeps a derived partial event snapshot running while its exact lease is active', async () => {
+ const handler = createParentSubagentIndexHandler({
+ getConvoOwnership: jest.fn().mockResolvedValue(parent),
+ listSubagentThreadsForParent: jest.fn().mockResolvedValue([
+ {
+ ...eventChild,
+ subagentThreadLease: {
+ token: 'lease-token',
+ taskId: 'delivery-active',
+ expiresAt: new Date('2099-08-21T12:00:00.000Z'),
+ },
+ },
+ ]),
+ listSubagentTasksForThreads: jest.fn().mockResolvedValue([
+ {
+ conversationId: 'event-thread',
+ tasks: [
+ {
+ messageId: 'delivery-active:assistant',
+ status: 'cancelled',
+ statusDerived: true,
+ createdAt: new Date('2026-08-21T11:01:00.000Z'),
+ },
+ ],
+ },
+ ]),
+ });
+ const { response, json } = createResponse();
+
+ await handler(createRequest(), response);
+
+ expect(json.mock.calls[0][0].children[0]).toEqual(
+ expect.objectContaining({ status: 'running', latestTaskId: 'delivery-active' }),
+ );
+ });
+
+ it('promotes a resumed leased task ahead of a newer completed turn', async () => {
+ const handler = createParentSubagentIndexHandler({
+ getConvoOwnership: jest.fn().mockResolvedValue(parent),
+ listSubagentThreadsForParent: jest.fn().mockResolvedValue([
+ {
+ ...eventChild,
+ subagentThreadLease: {
+ token: 'lease-token',
+ taskId: 'delivery-resumed',
+ expiresAt: new Date('2099-08-21T12:00:00.000Z'),
+ },
+ },
+ ]),
+ listSubagentTasksForThreads: jest.fn().mockResolvedValue([
+ {
+ conversationId: 'event-thread',
+ tasks: [
+ {
+ messageId: 'delivery-newer:assistant',
+ status: 'completed',
+ createdAt: new Date('2026-08-21T11:02:00.000Z'),
+ },
+ {
+ messageId: 'delivery-resumed:assistant',
+ status: 'cancelled',
+ statusDerived: true,
+ createdAt: new Date('2026-08-21T11:01:00.000Z'),
+ },
+ ],
+ },
+ ]),
+ });
+ const { response, json } = createResponse();
+
+ await handler(createRequest(), response);
+
+ expect(json.mock.calls[0][0].children[0]).toEqual(
+ expect.objectContaining({ status: 'running', latestTaskId: 'delivery-resumed' }),
+ );
+ });
+
+ it('redacts event delivery identity from the detailed child view', async () => {
+ const handler = createSubagentThreadViewHandler({
+ getConvoOwnership: jest.fn().mockResolvedValue(parent),
+ getSubagentThreadForParent: jest.fn().mockResolvedValue(eventChild),
+ getMessagesForSubagentThreadView: jest.fn().mockResolvedValue([]),
+ });
+ const { response, json } = createResponse();
+
+ await handler(createRequest({ threadId: 'event-thread' }), response);
+
+ expect(json.mock.calls[0][0].parentToolCallId).toBe('event-thread:event-thread');
+ expect(JSON.stringify(json.mock.calls[0][0])).not.toContain('private-binding-id');
+ });
+
+ it('derives a completed event task from its ordinary persisted assistant row', async () => {
+ const getMessagesForSubagentThreadView = jest.fn().mockResolvedValue([
+ {
+ messageId: 'delivery-1:assistant',
+ isCreatedByUser: false,
+ text: 'Event result',
+ createdAt: new Date('2026-08-21T11:01:00.000Z'),
+ },
+ ]);
+ const handler = createSubagentThreadViewHandler({
+ getConvoOwnership: jest.fn().mockResolvedValue(parent),
+ getSubagentThreadForParent: jest.fn().mockResolvedValue(eventChild),
+ getMessagesForSubagentThreadView,
+ });
+ const { response, json } = createResponse();
+
+ await handler(createRequest({ threadId: 'event-thread' }, { taskId: 'delivery-1' }), response);
+
+ expect(json.mock.calls[0][0]).toEqual(expect.objectContaining({ status: 'completed' }));
+ expect(getMessagesForSubagentThreadView).toHaveBeenCalledWith(
+ expect.objectContaining({ taskId: 'delivery-1' }),
+ );
+ });
+
+ it('projects ordinary and event children together without exposing event delivery identity', async () => {
+ const handler = createParentSubagentIndexHandler({
+ getConvoOwnership: jest.fn().mockResolvedValue(parent),
+ listSubagentThreadsForParent: jest.fn().mockResolvedValue([eventChild, child]),
+ listSubagentTasksForThreads: jest.fn().mockResolvedValue([]),
+ });
+ const { response, json } = createResponse();
+
+ await handler(createRequest(), response);
+
+ expect(json.mock.calls[0][0].children).toEqual([
+ expect.objectContaining({ threadId: 'event-thread', origin: 'event', actorId: 'analyst-a' }),
+ expect.objectContaining({
+ threadId,
+ origin: 'tool',
+ parentToolCallId: 'parent-tool-call',
+ }),
+ ]);
+ expect(JSON.stringify(json.mock.calls[0][0])).not.toContain('private-binding-id');
+ });
+
+ it('bounds child and per-child task discovery while retaining newest tasks', async () => {
+ const children = Array.from(
+ { length: PARENT_SUBAGENT_INDEX_LIMITS.children + 1 },
+ (_, index) => ({
+ ...eventChild,
+ conversationId: `event-thread-${String(index).padStart(2, '0')}`,
+ actorId: `actor-${String(index).padStart(2, '0')}`,
+ subagentThreadLease: undefined,
+ }),
+ );
+ const tasks = Array.from(
+ { length: PARENT_SUBAGENT_INDEX_LIMITS.tasksPerChild + 1 },
+ (_, index) => ({
+ messageId: `task-${String(index).padStart(2, '0')}:assistant`,
+ status: 'completed' as const,
+ createdAt: new Date(Date.UTC(2026, 7, 21, 12, index)),
+ }),
+ ).reverse();
+ const listSubagentTasksForThreads = jest
+ .fn()
+ .mockResolvedValue([{ conversationId: children[0].conversationId, tasks }]);
+ const handler = createParentSubagentIndexHandler({
+ getConvoOwnership: jest.fn().mockResolvedValue(parent),
+ listSubagentThreadsForParent: jest.fn().mockResolvedValue(children),
+ listSubagentTasksForThreads,
+ });
+ const { response, json } = createResponse();
+
+ await handler(createRequest(), response);
+
+ const projection = json.mock.calls[0][0];
+ expect(projection.children).toHaveLength(PARENT_SUBAGENT_INDEX_LIMITS.children);
+ expect(projection.childrenTruncated).toBe(true);
+ expect(projection.children[0].tasks).toHaveLength(PARENT_SUBAGENT_INDEX_LIMITS.tasksPerChild);
+ expect(projection.children[0].tasksTruncated).toBe(true);
+ expect(projection.children[0].latestTaskId).toBe('task-20');
+ expect(listSubagentTasksForThreads.mock.calls[0][0].conversationIds).toHaveLength(
+ PARENT_SUBAGENT_INDEX_LIMITS.children,
+ );
+ });
+
+ it('fails closed for a child parent and does not read task history', async () => {
+ const listSubagentTasksForThreads = jest.fn();
+ const handler = createParentSubagentIndexHandler({
+ getConvoOwnership: jest.fn().mockResolvedValue({
+ ...parent,
+ subagentThread: child.subagentThread,
+ }),
+ listSubagentThreadsForParent: jest.fn().mockResolvedValue([]),
+ listSubagentTasksForThreads,
+ });
+ const { response, status, json } = createResponse();
+
+ await handler(createRequest(), response);
+
+ expect(status).toHaveBeenCalledWith(404);
+ expect(json).toHaveBeenCalledWith({ error: 'Conversation not found' });
+ expect(listSubagentTasksForThreads).not.toHaveBeenCalled();
+ });
+
+ it('drops a mismatched child lineage before the batched task read', async () => {
+ const listSubagentTasksForThreads = jest.fn().mockResolvedValue([]);
+ const handler = createParentSubagentIndexHandler({
+ getConvoOwnership: jest.fn().mockResolvedValue(parent),
+ listSubagentThreadsForParent: jest.fn().mockResolvedValue([
+ {
+ ...eventChild,
+ subagentThread: {
+ ...eventChild.subagentThread,
+ parentConversationId: 'different-parent',
+ },
+ },
+ ]),
+ listSubagentTasksForThreads,
+ });
+ const { response, json } = createResponse();
+
+ await handler(createRequest(), response);
+
+ expect(listSubagentTasksForThreads).toHaveBeenCalledWith(
+ expect.objectContaining({ conversationIds: [] }),
+ );
+ expect(json.mock.calls[0][0].children).toEqual([]);
+ });
+});
diff --git a/packages/api/src/agents/view.ts b/packages/api/src/agents/view.ts
index 92503a3240..ad9393c3a0 100644
--- a/packages/api/src/agents/view.ts
+++ b/packages/api/src/agents/view.ts
@@ -1,14 +1,19 @@
import { logger, SUBAGENT_TRANSCRIPT_SOURCE_BYTE_LIMIT } from '@librechat/data-schemas';
import type {
- ConversationMethods,
- MessageMethods,
- SubagentThreadViewMessageRecord,
-} from '@librechat/data-schemas';
-import type {
+ ParentSubagentIndex,
+ ParentSubagentSummary,
+ ParentSubagentTaskSummary,
SubagentThreadMessage,
SubagentThreadStatus,
SubagentThreadView,
} from 'librechat-data-provider';
+import type {
+ ConversationMethods,
+ MessageMethods,
+ ParentSubagentTaskRecord,
+ ParentSubagentThreadRecord,
+ SubagentThreadViewMessageRecord,
+} from '@librechat/data-schemas';
import type { Response } from 'express';
import type { ServerRequest } from '~/types';
import { projectSubagentActivity, SUBAGENT_ACTIVITY_LIMITS } from './activity';
@@ -22,12 +27,21 @@ const MAX_RESPONSE_TEXT_BYTES = 128 * 1024;
const MAX_RESPONSE_BYTES = 160 * 1024;
const MAX_PUBLIC_ID_BYTES = 512;
const MAX_TITLE_BYTES = 1024;
+const MAX_PARENT_CHILDREN = 64;
+const MAX_PARENT_TASKS_PER_CHILD = 20;
+const MAX_PARENT_INDEX_BYTES = 96 * 1024;
type SubagentThreadViewDependencies = Pick<
ConversationMethods,
'getConvoOwnership' | 'getSubagentThreadForParent'
> &
Pick<MessageMethods, 'getMessagesForSubagentThreadView'>;
+type ParentSubagentIndexDependencies = Pick<
+ ConversationMethods,
+ 'getConvoOwnership' | 'listSubagentThreadsForParent'
+> &
+ Pick<MessageMethods, 'listSubagentTasksForThreads'>;
+
type SubagentThreadViewParams = {
parentConversationId?: string;
threadId?: string;
@@ -125,11 +139,21 @@ const publicStatus = (
return publicStatus([activeTaskMessage], undefined);
}
const message = messages.find(
- (candidate) =>
- candidate.subagentTask != null &&
- (requestedTaskId == null || candidate.messageId.startsWith(`${requestedTaskId}:`)),
+ (candidate) => requestedTaskId == null || candidate.messageId.startsWith(`${requestedTaskId}:`),
);
- switch (message?.subagentTask?.status) {
+ let persistedStatus = message?.subagentTask?.status;
+ if (persistedStatus == null && message != null) {
+ if (message.isCreatedByUser) {
+ persistedStatus = 'running';
+ } else if (message.error === true) {
+ persistedStatus = 'error';
+ } else if (message.unfinished === true) {
+ persistedStatus = 'cancelled';
+ } else {
+ persistedStatus = 'completed';
+ }
+ }
+ switch (persistedStatus) {
case 'running':
return 'interrupted';
case 'completed':
@@ -147,6 +171,188 @@ const notFound = (res: Response): void => {
res.status(404).json({ error: 'Conversation not found' });
};
+const taskIdFromMessageId = (messageId: string): string | undefined => {
+ const suffix = messageId.endsWith(':assistant') ? ':assistant' : ':user';
+ if (!messageId.endsWith(suffix)) return undefined;
+ const taskId = messageId.slice(0, -suffix.length);
+ return validTaskId(taskId) ? taskId : undefined;
+};
+
+const publicTaskStatus = (
+ status: NonNullable<ParentSubagentTaskRecord['tasks'][number]['status']>,
+ active: boolean,
+ statusDerived = false,
+): SubagentThreadStatus => {
+ if (active && (status === 'running' || statusDerived)) return 'running';
+ switch (status) {
+ case 'running':
+ return 'interrupted';
+ case 'completed':
+ return 'completed';
+ case 'error':
+ return 'failed';
+ case 'cancelled':
+ return 'cancelled';
+ }
+ return 'interrupted';
+};
+
+const publicTaskSummaries = (
+ child: ParentSubagentThreadRecord,
+ record: ParentSubagentTaskRecord | undefined,
+ now: Date,
+): { tasks: ParentSubagentTaskSummary[]; truncated: boolean } => {
+ const leaseTaskId =
+ child.subagentThreadLease != null && child.subagentThreadLease.expiresAt > now
+ ? child.subagentThreadLease.taskId
+ : undefined;
+ const activeTaskId = validTaskId(leaseTaskId) ? leaseTaskId : undefined;
+ const source = record?.tasks ?? [];
+ const tasks: ParentSubagentTaskSummary[] = [];
+ for (const task of source.slice(0, MAX_PARENT_TASKS_PER_CHILD + 1)) {
+ const taskId = taskIdFromMessageId(task.messageId);
+ if (taskId == null) continue;
+ tasks.push({
+ taskId: truncateUtf8(taskId, MAX_PUBLIC_ID_BYTES).text,
+ status: publicTaskStatus(task.status, taskId === activeTaskId, task.statusDerived),
+ ...(isoDate(task.createdAt) == null ? {} : { createdAt: isoDate(task.createdAt) }),
+ });
+ }
+ if (activeTaskId != null) {
+ const activeIndex = tasks.findIndex((task) => task.taskId === activeTaskId);
+ if (activeIndex >= 0) {
+ const [activeTask] = tasks.splice(activeIndex, 1);
+ if (activeTask != null) tasks.unshift(activeTask);
+ } else {
+ tasks.unshift({
+ taskId: truncateUtf8(activeTaskId, MAX_PUBLIC_ID_BYTES).text,
+ status: 'running',
+ });
+ }
+ }
+ return {
+ tasks: tasks.slice(0, MAX_PARENT_TASKS_PER_CHILD),
+ truncated:
+ record?.sourceTruncated === true ||
+ source.length > MAX_PARENT_TASKS_PER_CHILD ||
+ (activeTaskId != null &&
+ !source.some((task) => taskIdFromMessageId(task.messageId) === activeTaskId) &&
+ source.length >= MAX_PARENT_TASKS_PER_CHILD),
+ };
+};
+
+/**
+ * Discovers bounded child activity through a human parent. It performs one
+ * child read and one batched task read; detailed activity stays on the lazy
+ * thread Interface.
+ */
+export function createParentSubagentIndexHandler(deps: ParentSubagentIndexDependencies) {
+ return async (req: ServerRequest, res: Response): Promise<void> => {
+ const userId = req.user?.id;
+ const tenantId = req.user?.tenantId || undefined;
+ const { parentConversationId } = req.params as { parentConversationId?: string };
+ if (!userId || !validConversationId(parentConversationId)) {
+ notFound(res);
+ return;
+ }
+
+ try {
+ const [parent, discovered] = await Promise.all([
+ deps.getConvoOwnership(userId, parentConversationId, tenantId ?? null),
+ deps.listSubagentThreadsForParent({
+ user: userId,
+ parentConversationId,
+ ...(tenantId == null ? {} : { tenantId }),
+ limit: MAX_PARENT_CHILDREN + 1,
+ }),
+ ]);
+ if (
+ parent == null ||
+ parent.subagentThread != null ||
+ !tenantMatches(parent.tenantId, tenantId)
+ ) {
+ notFound(res);
+ return;
+ }
+
+ const childrenTruncated = discovered.length > MAX_PARENT_CHILDREN;
+ const children = discovered.slice(0, MAX_PARENT_CHILDREN).filter((child) => {
+ const lineage = child.subagentThread;
+ return (
+ lineage != null &&
+ lineage.parentConversationId === parentConversationId &&
+ tenantMatches(child.tenantId, tenantId)
+ );
+ });
+ const taskRecords = await deps.listSubagentTasksForThreads({
+ user: userId,
+ conversationIds: children.map((child) => child.conversationId),
+ ...(tenantId == null ? {} : { tenantId }),
+ limitPerThread: MAX_PARENT_TASKS_PER_CHILD + 1,
+ });
+ const taskRecordsByThread = new Map(
+ taskRecords.map((record) => [record.conversationId, record]),
+ );
+ const now = new Date();
+ const summaries: ParentSubagentSummary[] = children.flatMap((child) => {
+ const lineage = child.subagentThread;
+ if (lineage == null) return [];
+ const projectedTasks = publicTaskSummaries(
+ child,
+ taskRecordsByThread.get(child.conversationId),
+ now,
+ );
+ const latest = projectedTasks.tasks[0];
+ const origin = lineage.parentToolCallId.startsWith('event-binding:') ? 'event' : 'tool';
+ return [
+ {
+ threadId: truncateUtf8(child.conversationId, MAX_PUBLIC_ID_BYTES).text,
+ parentMessageId: truncateUtf8(lineage.parentMessageId, MAX_PUBLIC_ID_BYTES).text,
+ ...(origin === 'tool'
+ ? {
+ parentToolCallId: truncateUtf8(lineage.parentToolCallId, MAX_PUBLIC_ID_BYTES)
+ .text,
+ }
+ : {}),
+ subagentType: truncateUtf8(lineage.subagentType, MAX_PUBLIC_ID_BYTES).text,
+ subagentKind: lineage.subagentKind,
+ ...(child.agent_id == null
+ ? {}
+ : { agentId: truncateUtf8(child.agent_id, MAX_PUBLIC_ID_BYTES).text }),
+ title: truncateUtf8(child.title ?? `Subagent: ${lineage.subagentType}`, MAX_TITLE_BYTES)
+ .text,
+ origin,
+ ...(child.actorId == null
+ ? {}
+ : { actorId: truncateUtf8(child.actorId, MAX_PUBLIC_ID_BYTES).text }),
+ status: latest?.status ?? 'dispatched',
+ ...(isoDate(child.updatedAt) == null ? {} : { updatedAt: isoDate(child.updatedAt) }),
+ ...(latest == null ? {} : { latestTaskId: latest.taskId }),
+ tasks: projectedTasks.tasks,
+ tasksTruncated: projectedTasks.truncated,
+ },
+ ];
+ });
+ const view: ParentSubagentIndex = {
+ parentConversationId,
+ children: summaries,
+ childrenTruncated,
+ };
+ while (Buffer.byteLength(JSON.stringify(view), 'utf8') > MAX_PARENT_INDEX_BYTES) {
+ if (view.children.length === 0) {
+ throw new Error('Parent child-thread projection exceeded its response limit');
+ }
+ view.children.pop();
+ view.childrenTruncated = true;
+ }
+ res.status(200).json(view);
+ } catch (error) {
+ logger.error('[subagentThreads] Failed to list child threads through parent', error);
+ res.status(500).json({ error: 'Failed to load child activity' });
+ }
+ };
+}
+
/** Reads one durable child through its parent without reopening ordinary conversation reads. */
export function createSubagentThreadViewHandler(deps: SubagentThreadViewDependencies) {
return async (req: ServerRequest, res: Response): Promise<void> => {
@@ -242,7 +448,9 @@ export function createSubagentThreadViewHandler(deps: SubagentThreadViewDependen
threadId,
parentConversationId,
parentMessageId: truncateUtf8(lineage.parentMessageId, MAX_PUBLIC_ID_BYTES).text,
- parentToolCallId: truncateUtf8(lineage.parentToolCallId, MAX_PUBLIC_ID_BYTES).text,
+ parentToolCallId: !lineage.parentToolCallId.startsWith('event-binding:')
+ ? truncateUtf8(lineage.parentToolCallId, MAX_PUBLIC_ID_BYTES).text
+ : `event-thread:${truncateUtf8(threadId, MAX_PUBLIC_ID_BYTES - 13).text}`,
subagentType: truncateUtf8(lineage.subagentType, MAX_PUBLIC_ID_BYTES).text,
subagentKind: lineage.subagentKind,
...(child.agent_id == null
@@ -289,3 +497,13 @@ export const SUBAGENT_THREAD_VIEW_LIMITS: Readonly<{
activityBytes: SUBAGENT_ACTIVITY_LIMITS.bytes,
activitySourceBytes: SUBAGENT_TRANSCRIPT_SOURCE_BYTE_LIMIT,
};
+
+export const PARENT_SUBAGENT_INDEX_LIMITS: Readonly<{
+ children: number;
+ tasksPerChild: number;
+ responseBytes: number;
+}> = Object.freeze({
+ children: MAX_PARENT_CHILDREN,
+ tasksPerChild: MAX_PARENT_TASKS_PER_CHILD,
+ responseBytes: MAX_PARENT_INDEX_BYTES,
+});
diff --git a/packages/data-provider/src/api-endpoints.ts b/packages/data-provider/src/api-endpoints.ts
index 5a75f03e4a..cb652d473f 100644
--- a/packages/data-provider/src/api-endpoints.ts
+++ b/packages/data-provider/src/api-endpoints.ts
@@ -116,6 +116,9 @@ export const conversations = (params: q.ConversationListParams) => {
export const conversationById = (id: string) => `${conversationsRoot}/${id}`;
+export const parentSubagents = (parentConversationId: string) =>
+ `${conversationsRoot}/${encodeURIComponent(parentConversationId)}/subagents`;
+
export const subagentThread = (parentConversationId: string, threadId: string, taskId?: string) => {
const endpoint = `${conversationsRoot}/${encodeURIComponent(parentConversationId)}/subagents/${encodeURIComponent(threadId)}`;
return taskId == null ? endpoint : `${endpoint}?taskId=${encodeURIComponent(taskId)}`;
diff --git a/packages/data-provider/src/data-service.ts b/packages/data-provider/src/data-service.ts
index 50126759fd..bffed4c235 100644
--- a/packages/data-provider/src/data-service.ts
+++ b/packages/data-provider/src/data-service.ts
@@ -1002,6 +1002,10 @@ export function getMessagesByConvoId(conversationId: string): Promise<s.TMessage
return request.get(endpoints.messages({ conversationId }));
}
+export function getParentSubagents(parentConversationId: string): Promise<t.ParentSubagentIndex> {
+ return request.get(endpoints.parentSubagents(parentConversationId));
+}
+
export function getSubagentThread(
parentConversationId: string,
threadId: string,
diff --git a/packages/data-provider/src/keys.ts b/packages/data-provider/src/keys.ts
index 67f4a3a81f..d19d7bf918 100644
--- a/packages/data-provider/src/keys.ts
+++ b/packages/data-provider/src/keys.ts
@@ -93,6 +93,7 @@ export enum QueryKeys {
/* Scheduled chats */
schedules = 'schedules',
schedule = 'schedule',
+ parentSubagents = 'parentSubagents',
subagentThread = 'subagentThread',
}
diff --git a/packages/data-provider/src/types/subagents.ts b/packages/data-provider/src/types/subagents.ts
index cd05af19f1..c5b7695f63 100644
--- a/packages/data-provider/src/types/subagents.ts
+++ b/packages/data-provider/src/types/subagents.ts
@@ -6,6 +6,41 @@ export type SubagentThreadStatus =
| 'interrupted'
| 'cancelled';
+export type ParentSubagentTaskSummary = {
+ taskId: string;
+ status: SubagentThreadStatus;
+ createdAt?: string;
+};
+
+/**
+ * Bounded discovery projection for one child owned by a parent conversation.
+ * Event-delivery identities stay private; `actorId` is the only event-binding
+ * field intentionally exposed to the parent's UI.
+ */
+export type ParentSubagentSummary = {
+ threadId: string;
+ parentMessageId: string;
+ /** Present only for ordinary tool-spawned children. */
+ parentToolCallId?: string;
+ subagentType: string;
+ subagentKind: 'agent' | 'graph';
+ agentId?: string;
+ title: string;
+ origin: 'tool' | 'event';
+ actorId?: string;
+ status: SubagentThreadStatus;
+ updatedAt?: string;
+ latestTaskId?: string;
+ tasks: ParentSubagentTaskSummary[];
+ tasksTruncated: boolean;
+};
+
+export type ParentSubagentIndex = {
+ parentConversationId: string;
+ children: ParentSubagentSummary[];
+ childrenTruncated: boolean;
+};
+
/**
* A bounded, presentation-safe description of child work. This deliberately
* models user-visible activity instead of the LangChain messages, SSE events,
diff --git a/packages/data-schemas/src/methods/conversation.spec.ts b/packages/data-schemas/src/methods/conversation.spec.ts
index 6b05d1a1f8..e7d07acfaf 100644
--- a/packages/data-schemas/src/methods/conversation.spec.ts
+++ b/packages/data-schemas/src/methods/conversation.spec.ts
@@ -1613,6 +1613,17 @@ describe('Conversation Operations', () => {
expect(await methods.getConvoOwnership('user123', 'non-existent-id')).toBeNull();
});
+ it('hides retention-expired conversations before TTL cleanup', async () => {
+ await Conversation.create({
+ conversationId: 'expired-owner',
+ user: 'user123',
+ endpoint: EModelEndpoint.agents,
+ expiredAt: new Date(Date.now() - 60_000),
+ });
+
+ await expect(methods.getConvoOwnership('user123', 'expired-owner')).resolves.toBeNull();
+ });
+
it('includes child-thread identity without materializing conversation content', async () => {
await Conversation.create({
conversationId: 'child-conversation',
@@ -3668,6 +3679,189 @@ describe('Conversation Operations', () => {
);
});
+ it('lists bounded child metadata while collapsing private event bindings to actor identity', async () => {
+ const parentConversationId = uuidv4();
+ const eventThreadId = uuidv4();
+ const toolThreadId = uuidv4();
+ const lineage = (parentToolCallId: string) => ({
+ rootConversationId: parentConversationId,
+ parentConversationId,
+ parentMessageId: 'parent-message',
+ parentToolCallId,
+ subagentType: 'researcher',
+ subagentKind: 'agent' as const,
+ depth: 1,
+ });
+ await Conversation.create([
+ {
+ conversationId: eventThreadId,
+ user: 'index-user',
+ tenantId: 'tenant-a',
+ endpoint: EModelEndpoint.agents,
+ agent_id: 'agent-event',
+ subagentThread: lineage('event-binding:private'),
+ subagentThreadLease: {
+ token: 'private-token',
+ taskId: 'task-live',
+ expiresAt: new Date('2099-08-21T12:00:00.000Z'),
+ },
+ agentEventBinding: {
+ bindingId: `evtbind_${'b'.repeat(48)}`,
+ sourceKeyId: 'private-key',
+ actorId: 'actor-a',
+ },
+ },
+ {
+ conversationId: toolThreadId,
+ user: 'index-user',
+ tenantId: 'tenant-a',
+ endpoint: EModelEndpoint.agents,
+ subagentThread: lineage('tool-call-a'),
+ },
+ {
+ conversationId: uuidv4(),
+ user: 'index-user',
+ tenantId: 'tenant-b',
+ endpoint: EModelEndpoint.agents,
+ subagentThread: lineage('wrong-tenant'),
+ },
+ {
+ conversationId: uuidv4(),
+ user: 'different-user',
+ tenantId: 'tenant-a',
+ endpoint: EModelEndpoint.agents,
+ subagentThread: lineage('wrong-user'),
+ },
+ {
+ conversationId: uuidv4(),
+ user: 'index-user',
+ tenantId: 'tenant-a',
+ endpoint: EModelEndpoint.agents,
+ subagentThread: {
+ ...lineage('wrong-parent'),
+ parentConversationId: uuidv4(),
+ },
+ },
+ ]);
+
+ const records = await methods.listSubagentThreadsForParent({
+ user: 'index-user',
+ tenantId: 'tenant-a',
+ parentConversationId,
+ limit: 10,
+ });
+
+ expect(records.map((record) => record.conversationId).sort()).toEqual(
+ [eventThreadId, toolThreadId].sort(),
+ );
+ expect(records.find((record) => record.conversationId === eventThreadId)).toEqual(
+ expect.objectContaining({
+ actorId: 'actor-a',
+ subagentThreadLease: expect.objectContaining({ taskId: 'task-live' }),
+ }),
+ );
+ expect(records).not.toEqual(
+ expect.arrayContaining([expect.objectContaining({ agentEventBinding: expect.anything() })]),
+ );
+ expect(JSON.stringify(records)).not.toContain('private-key');
+ expect(JSON.stringify(records)).not.toContain(`evtbind_${'b'.repeat(48)}`);
+ });
+
+ it('hides retention-expired children before TTL cleanup', async () => {
+ const parentConversationId = uuidv4();
+ const expiredThreadId = uuidv4();
+ await Conversation.create({
+ conversationId: expiredThreadId,
+ user: 'expired-child-user',
+ endpoint: EModelEndpoint.agents,
+ expiredAt: new Date(Date.now() - 60_000),
+ subagentThread: {
+ rootConversationId: parentConversationId,
+ parentConversationId,
+ parentMessageId: 'parent-message',
+ parentToolCallId: 'parent-tool',
+ subagentType: 'researcher',
+ subagentKind: 'agent',
+ depth: 1,
+ },
+ });
+
+ await expect(
+ methods.getSubagentThreadForParent({
+ user: 'expired-child-user',
+ parentConversationId,
+ conversationId: expiredThreadId,
+ }),
+ ).resolves.toBeNull();
+ await expect(
+ methods.listSubagentThreadsForParent({
+ user: 'expired-child-user',
+ parentConversationId,
+ limit: 10,
+ }),
+ ).resolves.toEqual([]);
+ });
+
+ it('keeps an older child with a live lease inside the bounded parent index', async () => {
+ const parentConversationId = uuidv4();
+ const activeThreadId = uuidv4();
+ const recentThreadId = uuidv4();
+ const lineage = (parentToolCallId: string) => ({
+ rootConversationId: parentConversationId,
+ parentConversationId,
+ parentMessageId: 'parent-message',
+ parentToolCallId,
+ subagentType: 'researcher',
+ subagentKind: 'agent' as const,
+ depth: 1,
+ });
+ await Conversation.create([
+ {
+ conversationId: activeThreadId,
+ user: 'active-index-user',
+ endpoint: EModelEndpoint.agents,
+ subagentThread: lineage('active-tool'),
+ },
+ {
+ conversationId: recentThreadId,
+ user: 'active-index-user',
+ endpoint: EModelEndpoint.agents,
+ subagentThread: lineage('recent-tool'),
+ },
+ ]);
+ await Conversation.updateOne(
+ { conversationId: activeThreadId },
+ { $set: { updatedAt: new Date('2026-08-20T10:00:00.000Z') } },
+ { timestamps: false },
+ );
+ await Conversation.updateOne(
+ { conversationId: recentThreadId },
+ { $set: { updatedAt: new Date('2026-08-21T10:00:00.000Z') } },
+ { timestamps: false },
+ );
+ await methods.acquireSubagentThreadLease({
+ user: 'active-index-user',
+ conversationId: activeThreadId,
+ token: 'private-token',
+ taskId: 'active-task',
+ now: new Date('2026-08-22T10:00:00.000Z'),
+ expiresAt: new Date('2026-08-22T10:00:30.000Z'),
+ });
+
+ const records = await methods.listSubagentThreadsForParent({
+ user: 'active-index-user',
+ parentConversationId,
+ limit: 1,
+ });
+
+ expect(records).toEqual([
+ expect.objectContaining({
+ conversationId: activeThreadId,
+ subagentThreadLease: expect.objectContaining({ taskId: 'active-task' }),
+ }),
+ ]);
+ });
+
it('resolves an event binding only through its owner, tenant, and API key', async () => {
const conversationId = uuidv4();
const bindingId = `evtbind_${'a'.repeat(48)}`;
diff --git a/packages/data-schemas/src/methods/conversation.ts b/packages/data-schemas/src/methods/conversation.ts
index f81e0737fc..168e634b8b 100644
--- a/packages/data-schemas/src/methods/conversation.ts
+++ b/packages/data-schemas/src/methods/conversation.ts
@@ -48,13 +48,32 @@ export type SubagentThreadReadRecord = Pick<
| 'updatedAt'
| 'subagentThread'
| 'subagentThreadLease'
->;
+> & {
+ actorId?: string;
+};
+
+export type ParentSubagentThreadRecord = SubagentThreadReadRecord;
const ARCHIVE_CONVERSATION_BATCH_SIZE = 500;
const PROJECT_STATS_REFRESH_CONCURRENCY = 10;
const PROJECT_STATS_REFRESH_MAX_PASSES = 2;
const PROJECT_DISCOVERY_MAX_ATTEMPTS = 3;
+const subagentThreadReadRecord = (conversation: IConversation): SubagentThreadReadRecord => ({
+ conversationId: conversation.conversationId,
+ ...(conversation.tenantId == null ? {} : { tenantId: conversation.tenantId }),
+ ...(conversation.title == null ? {} : { title: conversation.title }),
+ ...(conversation.agent_id == null ? {} : { agent_id: conversation.agent_id }),
+ ...(conversation.updatedAt == null ? {} : { updatedAt: conversation.updatedAt }),
+ ...(conversation.subagentThread == null ? {} : { subagentThread: conversation.subagentThread }),
+ ...(conversation.subagentThreadLease == null
+ ? {}
+ : { subagentThreadLease: conversation.subagentThreadLease }),
+ ...(conversation.agentEventBinding?.actorId == null
+ ? {}
+ : { actorId: conversation.agentEventBinding.actorId }),
+});
+
async function discoverProjectIds(
Conversation: Model<IConversation>,
filter: FilterQuery<IConversation>,
@@ -180,6 +199,12 @@ export interface ConversationMethods {
conversationId: string;
tenantId?: string;
}): Promise<SubagentThreadReadRecord | null>;
+ listSubagentThreadsForParent(input: {
+ user: string;
+ parentConversationId: string;
+ tenantId?: string;
+ limit: number;
+ }): Promise<ParentSubagentThreadRecord[]>;
getAgentEventBinding(input: {
user: string;
bindingId: string;
@@ -302,22 +327,56 @@ export function createConversationMethods(
}): Promise<SubagentThreadReadRecord | null> {
try {
const Conversation = mongoose.models.Conversation as Model<IConversation>;
- return await Conversation.findOne({
+ const conversation = await Conversation.findOne({
user: input.user,
conversationId: input.conversationId,
'subagentThread.parentConversationId': input.parentConversationId,
...subagentLeaseTenantFilter(input.tenantId),
+ ...activeExpirationFilter<IConversation>(),
})
.select(
- 'conversationId tenantId title agent_id updatedAt subagentThread +subagentThreadLease',
+ 'conversationId tenantId title agent_id updatedAt subagentThread +subagentThreadLease +agentEventBinding',
)
- .lean<SubagentThreadReadRecord>();
+ .lean<IConversation>();
+ if (conversation == null) return null;
+ return subagentThreadReadRecord(conversation);
} catch (error) {
logger.error('[getSubagentThreadForParent] Error getting child conversation', error);
throw new Error('Error getting child conversation');
}
}
+ /**
+ * Lists bounded child metadata through immutable parent lineage. Private
+ * event-delivery records are collapsed to actor identity inside this Module.
+ */
+ async function listSubagentThreadsForParent(input: {
+ user: string;
+ parentConversationId: string;
+ tenantId?: string;
+ limit: number;
+ }): Promise<ParentSubagentThreadRecord[]> {
+ try {
+ const Conversation = mongoose.models.Conversation as Model<IConversation>;
+ const conversations = await Conversation.find({
+ user: input.user,
+ 'subagentThread.parentConversationId': input.parentConversationId,
+ ...subagentLeaseTenantFilter(input.tenantId),
+ ...activeExpirationFilter<IConversation>(),
+ })
+ .select(
+ 'conversationId tenantId title agent_id updatedAt subagentThread +subagentThreadLease +agentEventBinding',
+ )
+ .sort({ updatedAt: -1, conversationId: 1, _id: 1 })
+ .limit(input.limit)
+ .lean<IConversation[]>();
+ return conversations.map(subagentThreadReadRecord);
+ } catch (error) {
+ logger.error('[listSubagentThreadsForParent] Error listing child conversations', error);
+ throw new Error('Error listing child conversations');
+ }
+ }
+
/** Resolves an event target only when the API key, owner, and tenant all match. */
async function getAgentEventBinding(input: {
user: string;
@@ -437,6 +496,10 @@ export function createConversationMethods(
taskId: input.taskId,
expiresAt: input.expiresAt,
},
+ /** Child threads are hidden from normal recents. Stamp the task start
+ * explicitly so bounded parent discovery promotes real new activity;
+ * automatic timestamps stay disabled for lease heartbeats/releases. */
+ updatedAt: input.now,
},
},
{ timestamps: false },
@@ -549,6 +612,7 @@ export function createConversationMethods(
user,
conversationId,
...tenantFilter,
+ ...activeExpirationFilter<IConversation>(),
},
'user tenantId subagentThread',
).lean<Pick<IConversation, 'user' | 'tenantId' | 'subagentThread'>>();
@@ -1720,6 +1784,7 @@ export function createConversationMethods(
getConvosQueried,
getConvo,
getSubagentThreadForParent,
+ listSubagentThreadsForParent,
getAgentEventBinding,
reserveSubagentThread,
acquireSubagentThreadLease,
diff --git a/packages/data-schemas/src/methods/index.ts b/packages/data-schemas/src/methods/index.ts
index de61ec3e64..d1bbfa3db1 100644
--- a/packages/data-schemas/src/methods/index.ts
+++ b/packages/data-schemas/src/methods/index.ts
@@ -49,10 +49,15 @@ import {
CLIENT_MESSAGE_SELECT,
SUBAGENT_TRANSCRIPT_SOURCE_BYTE_LIMIT,
type MessageMethods,
+ type ParentSubagentTaskRecord,
type SubagentThreadViewMessageRecord,
type SubagentTaskResultClaim,
} from './message';
-import { createConversationMethods, type ConversationMethods } from './conversation';
+import {
+ createConversationMethods,
+ type ConversationMethods,
+ type ParentSubagentThreadRecord,
+} from './conversation';
import { createChatProjectMethods, type ChatProjectMethods } from './chatProject';
export type {
AssignConversationToProjectResult,
@@ -378,6 +383,8 @@ export type {
PresetMethods,
ConversationTagMethods,
MessageMethods,
+ ParentSubagentTaskRecord,
+ ParentSubagentThreadRecord,
SubagentThreadViewMessageRecord,
SubagentTaskResultClaim,
ConversationMethods,
diff --git a/packages/data-schemas/src/methods/message.spec.ts b/packages/data-schemas/src/methods/message.spec.ts
index 2541ef1ce7..1444ef5125 100644
--- a/packages/data-schemas/src/methods/message.spec.ts
+++ b/packages/data-schemas/src/methods/message.spec.ts
@@ -28,6 +28,9 @@ let getMessages: ReturnType<typeof createMessageMethods>['getMessages'];
let getMessagesForSubagentThreadView: ReturnType<
typeof createMessageMethods
>['getMessagesForSubagentThreadView'];
+let listSubagentTasksForThreads: ReturnType<
+ typeof createMessageMethods
+>['listSubagentTasksForThreads'];
let updateMessage: ReturnType<typeof createMessageMethods>['updateMessage'];
let updateToolCallResult: ReturnType<typeof createMessageMethods>['updateToolCallResult'];
let deleteMessages: ReturnType<typeof createMessageMethods>['deleteMessages'];
@@ -52,6 +55,7 @@ beforeAll(async () => {
saveMessage = methods.saveMessage;
getMessages = methods.getMessages;
getMessagesForSubagentThreadView = methods.getMessagesForSubagentThreadView;
+ listSubagentTasksForThreads = methods.listSubagentTasksForThreads;
updateMessage = methods.updateMessage;
updateToolCallResult = methods.updateToolCallResult;
deleteMessages = methods.deleteMessages;
@@ -1145,6 +1149,262 @@ describe('Message Operations', () => {
});
});
+ describe('listSubagentTasksForThreads', () => {
+ it('derives event task status from ordinary durable turn rows', async () => {
+ const conversationId = uuidv4();
+ await Message.create([
+ {
+ user: 'user123',
+ messageId: 'delivery-running:user',
+ conversationId,
+ isCreatedByUser: true,
+ createdAt: new Date('2026-08-21T10:00:00.000Z'),
+ },
+ {
+ user: 'user123',
+ messageId: 'delivery-complete:assistant',
+ conversationId,
+ isCreatedByUser: false,
+ createdAt: new Date('2026-08-21T10:01:00.000Z'),
+ },
+ {
+ user: 'user123',
+ messageId: 'delivery-error:assistant',
+ conversationId,
+ isCreatedByUser: false,
+ error: true,
+ createdAt: new Date('2026-08-21T10:02:00.000Z'),
+ },
+ ]);
+
+ const [record] = await listSubagentTasksForThreads({
+ user: 'user123',
+ conversationIds: [conversationId],
+ limitPerThread: 3,
+ });
+
+ expect(record.tasks).toEqual([
+ expect.objectContaining({
+ messageId: 'delivery-error:assistant',
+ status: 'error',
+ statusDerived: true,
+ }),
+ expect.objectContaining({
+ messageId: 'delivery-complete:assistant',
+ status: 'completed',
+ statusDerived: true,
+ }),
+ expect.objectContaining({
+ messageId: 'delivery-running:user',
+ status: 'running',
+ statusDerived: true,
+ }),
+ ]);
+ });
+
+ it('batches threads, deduplicates task rows, and bounds each newest task list', async () => {
+ const firstThread = uuidv4();
+ const secondThread = uuidv4();
+ await saveMessage(mockCtx, {
+ messageId: 'task-old:user',
+ conversationId: firstThread,
+ text: 'Start old task',
+ isCreatedByUser: true,
+ subagentTask: { attemptKey: 'old', status: 'running' },
+ });
+ await waitForTimestampTick();
+ await saveMessage(mockCtx, {
+ messageId: 'task-old:assistant',
+ conversationId: firstThread,
+ text: 'Finish old task',
+ isCreatedByUser: false,
+ subagentTask: { attemptKey: 'old', status: 'completed' },
+ });
+ await waitForTimestampTick();
+ await saveMessage(mockCtx, {
+ messageId: 'task-new:user',
+ conversationId: firstThread,
+ text: 'Start new task',
+ isCreatedByUser: true,
+ subagentTask: { attemptKey: 'new', status: 'running' },
+ });
+ await saveMessage(mockCtx, {
+ messageId: 'task-other:assistant',
+ conversationId: secondThread,
+ text: 'Other result',
+ isCreatedByUser: false,
+ subagentTask: { attemptKey: 'other', status: 'cancelled' },
+ });
+
+ const records = await listSubagentTasksForThreads({
+ user: 'user123',
+ conversationIds: [firstThread, secondThread],
+ limitPerThread: 2,
+ });
+
+ const first = records.find((record) => record.conversationId === firstThread);
+ expect(first?.tasks).toHaveLength(2);
+ expect(first?.tasks[0]).toEqual(
+ expect.objectContaining({ messageId: 'task-new:user', status: 'running' }),
+ );
+ expect(first?.tasks[1]).toEqual(
+ expect.objectContaining({ messageId: 'task-old:assistant', status: 'completed' }),
+ );
+ expect(records.find((record) => record.conversationId === secondThread)?.tasks).toEqual([
+ expect.objectContaining({ messageId: 'task-other:assistant', status: 'cancelled' }),
+ ]);
+ expect(records.every((record) => record.sourceTruncated !== true)).toBe(true);
+ });
+
+ it('marks every selected child truncated when one busy child fills the shared source window', async () => {
+ const quietThread = uuidv4();
+ const busyThread = uuidv4();
+ await Message.create([
+ ...['quiet-old', 'quiet-new'].map((taskId, index) => ({
+ user: 'user123',
+ messageId: `${taskId}:assistant`,
+ conversationId: quietThread,
+ isCreatedByUser: false,
+ createdAt: new Date(`2026-08-20T10:0${index}:00.000Z`),
+ updatedAt: new Date(`2026-08-20T10:0${index}:00.000Z`),
+ subagentTask: { attemptKey: taskId, status: 'completed' },
+ })),
+ ...Array.from({ length: 9 }, (_, index) => ({
+ user: 'user123',
+ messageId: `busy-${index}:assistant`,
+ conversationId: busyThread,
+ isCreatedByUser: false,
+ createdAt: new Date(`2026-08-21T10:${String(index).padStart(2, '0')}:00.000Z`),
+ updatedAt: new Date(`2026-08-21T10:${String(index).padStart(2, '0')}:00.000Z`),
+ subagentTask: { attemptKey: `busy-${index}`, status: 'completed' },
+ })),
+ ]);
+
+ const records = await listSubagentTasksForThreads({
+ user: 'user123',
+ conversationIds: [quietThread, busyThread],
+ limitPerThread: 2,
+ });
+
+ expect(records.find((record) => record.conversationId === quietThread)).toEqual(
+ expect.objectContaining({
+ sourceTruncated: true,
+ tasks: [expect.objectContaining({ messageId: 'quiet-new:assistant' })],
+ }),
+ );
+ expect(records.find((record) => record.conversationId === busyThread)?.sourceTruncated).toBe(
+ true,
+ );
+ });
+
+ it('preserves a newer recent task when the latest-per-thread snapshot is stale', async () => {
+ const conversationId = uuidv4();
+ const aggregate = jest.spyOn(Message, 'aggregate') as unknown as jest.Mock;
+ aggregate
+ .mockReturnValueOnce(
+ Promise.resolve([
+ {
+ conversationId,
+ tasks: [
+ {
+ messageId: 'task-old:assistant',
+ createdAt: new Date('2026-08-21T10:00:00.000Z'),
+ status: 'completed',
+ },
+ ],
+ },
+ ]),
+ )
+ .mockReturnValueOnce(
+ Promise.resolve([
+ {
+ conversationId,
+ sourceRows: 1,
+ tasks: [
+ {
+ messageId: 'task-new:user',
+ createdAt: new Date('2026-08-21T11:00:00.000Z'),
+ status: 'running',
+ },
+ ],
+ },
+ ]),
+ );
+
+ try {
+ await expect(
+ listSubagentTasksForThreads({
+ user: 'user123',
+ conversationIds: [conversationId],
+ limitPerThread: 2,
+ }),
+ ).resolves.toEqual([
+ {
+ conversationId,
+ tasks: [
+ expect.objectContaining({ messageId: 'task-new:user' }),
+ expect.objectContaining({ messageId: 'task-old:assistant' }),
+ ],
+ },
+ ]);
+ } finally {
+ aggregate.mockRestore();
+ }
+ });
+
+ it('preserves Mongo occurrence ordering when task timestamps tie', async () => {
+ const conversationId = uuidv4();
+ const aggregate = jest.spyOn(Message, 'aggregate') as unknown as jest.Mock;
+ aggregate
+ .mockReturnValueOnce(
+ Promise.resolve([
+ {
+ conversationId,
+ tasks: [
+ {
+ messageId: 'task-b:user',
+ createdAt: new Date('2026-08-21T10:00:00.000Z'),
+ occurrenceId: new mongoose.Types.ObjectId('000000000000000000000002'),
+ status: 'running',
+ },
+ ],
+ },
+ ]),
+ )
+ .mockReturnValueOnce(
+ Promise.resolve([
+ {
+ conversationId,
+ sourceRows: 1,
+ tasks: [
+ {
+ messageId: 'task-a:assistant',
+ createdAt: new Date('2026-08-21T10:00:00.000Z'),
+ occurrenceId: new mongoose.Types.ObjectId('000000000000000000000001'),
+ status: 'completed',
+ },
+ ],
+ },
+ ]),
+ );
+
+ try {
+ const [record] = await listSubagentTasksForThreads({
+ user: 'user123',
+ conversationIds: [conversationId],
+ limitPerThread: 2,
+ });
+
+ expect(record.tasks.map((task) => task.messageId)).toEqual([
+ 'task-b:user',
+ 'task-a:assistant',
+ ]);
+ } finally {
+ aggregate.mockRestore();
+ }
+ });
+ });
+
describe('deleteMessages', () => {
it('should delete messages with the correct filter', async () => {
// Save some messages for different users
diff --git a/packages/data-schemas/src/methods/message.ts b/packages/data-schemas/src/methods/message.ts
index 7752d86492..798f9a9343 100644
--- a/packages/data-schemas/src/methods/message.ts
+++ b/packages/data-schemas/src/methods/message.ts
@@ -1,6 +1,6 @@
import { HITL_MESSAGE_FILTER_FIELDS, RetentionMode } from 'librechat-data-provider';
import type { UserSubmittedMessageFieldPath } from 'librechat-data-provider';
-import type { DeleteResult, FilterQuery, Model } from 'mongoose';
+import type { DeleteResult, FilterQuery, Model, Types } from 'mongoose';
import type { AppConfig, IMessage } from '~/types';
import { createTempChatExpirationDate } from '~/utils/tempChatRetention';
import { createFallbackRetentionDate } from '~/utils/retention';
@@ -249,6 +249,7 @@ export type SubagentThreadViewMessageRecord = Pick<
| 'text'
| 'createdAt'
| 'error'
+ | 'unfinished'
| 'subagentTranscript'
| 'subagentTask'
> & {
@@ -256,6 +257,21 @@ export type SubagentThreadViewMessageRecord = Pick<
subagentTranscriptProjectionTruncated?: boolean;
};
+export type ParentSubagentTaskRecord = {
+ conversationId: string;
+ /** The shared bounded source window filled, so this child's history may be incomplete. */
+ sourceTruncated?: boolean;
+ tasks: Array<
+ Pick<IMessage, 'messageId' | 'createdAt'> & {
+ status: NonNullable<IMessage['subagentTask']>['status'];
+ /** True when status was inferred from an ordinary event-turn row. */
+ statusDerived?: boolean;
+ /** Private ordering token used only while merging bounded storage reads. */
+ occurrenceId?: Types.ObjectId;
+ }
+ >;
+};
+
export interface MessageMethods {
saveMessage(
ctx: {
@@ -326,6 +342,12 @@ export interface MessageMethods {
textCodePointLimit: number;
taskId?: string;
}): Promise<SubagentThreadViewMessageRecord[]>;
+ listSubagentTasksForThreads(input: {
+ user: string;
+ conversationIds: string[];
+ tenantId?: string;
+ limitPerThread: number;
+ }): Promise<ParentSubagentTaskRecord[]>;
getMessage(params: { user: string; messageId: string }): Promise<IMessage | null>;
getMessagesByCursor(
filter: FilterQuery<IMessage>,
@@ -1076,7 +1098,7 @@ export function createMessageMethods(mongoose: typeof import('mongoose')): Messa
? []
: [
{
- $set: {
+ $addFields: {
_subagentTranscriptSourceBytes: transcriptJsonBytes,
_subagentTranscriptSourceIsString: transcriptIsString,
},
@@ -1096,6 +1118,7 @@ export function createMessageMethods(mongoose: typeof import('mongoose')): Messa
},
createdAt: 1,
error: 1,
+ unfinished: 1,
...(input.taskId == null
? {}
: {
@@ -1157,6 +1180,211 @@ export function createMessageMethods(mongoose: typeof import('mongoose')): Messa
}
}
+ /** Returns newest bounded task outcomes for every selected child in two
+ * constant-size batch reads. The first read guarantees one latest task per
+ * child; the second caps recent source rows before any grouping accumulator.
+ * This avoids both N+1 reads and newer top-N accumulators that DocumentDB 5
+ * does not support. */
+ async function listSubagentTasksForThreads(input: {
+ user: string;
+ conversationIds: string[];
+ tenantId?: string;
+ limitPerThread: number;
+ }): Promise<ParentSubagentTaskRecord[]> {
+ if (input.conversationIds.length === 0) {
+ return [];
+ }
+ const Message = mongoose.models.Message as Model<IMessage>;
+ const match = {
+ user: input.user,
+ conversationId: { $in: input.conversationIds },
+ ...(input.tenantId == null ? { tenantId: { $exists: false } } : { tenantId: input.tenantId }),
+ messageId: { $regex: /:(user|assistant)$/ },
+ };
+ const taskProjection = {
+ messageId: '$messageId',
+ createdAt: '$createdAt',
+ occurrenceId: '$_id',
+ statusDerived: {
+ $eq: [{ $ifNull: ['$subagentTask.status', null] }, null],
+ },
+ status: {
+ $ifNull: [
+ '$subagentTask.status',
+ {
+ $cond: [
+ { $regexMatch: { input: '$messageId', regex: /:assistant$/ } },
+ {
+ $cond: [
+ { $eq: ['$error', true] },
+ 'error',
+ { $cond: [{ $eq: ['$unfinished', true] }, 'cancelled', 'completed'] },
+ ],
+ },
+ 'running',
+ ],
+ },
+ ],
+ },
+ };
+ const sourceLimit = Math.min(
+ 4096,
+ Math.max(
+ input.conversationIds.length,
+ input.conversationIds.length * input.limitPerThread * 2,
+ ),
+ );
+ type AggregateRecord = ParentSubagentTaskRecord & { sourceRows?: number };
+ const compareOccurrenceIds = (left?: Types.ObjectId, right?: Types.ObjectId): number => {
+ const leftValue = left?.toHexString() ?? '';
+ const rightValue = right?.toHexString() ?? '';
+ if (leftValue === rightValue) return 0;
+ return leftValue > rightValue ? 1 : -1;
+ };
+ const taskTimestamp = (value: Date | undefined): number =>
+ value == null ? Number.NEGATIVE_INFINITY : value.getTime();
+ const [latestRecords, recentRecords] = await Promise.all([
+ Message.aggregate<ParentSubagentTaskRecord>([
+ { $match: match },
+ { $sort: { conversationId: 1, createdAt: -1, _id: -1 } },
+ { $group: { _id: '$conversationId', task: { $first: taskProjection } } },
+ { $project: { _id: 0, conversationId: '$_id', tasks: ['$task'] } },
+ { $sort: { conversationId: 1 } },
+ ]),
+ Message.aggregate<AggregateRecord>([
+ { $match: match },
+ { $sort: { createdAt: -1, _id: -1 } },
+ { $limit: sourceLimit + 1 },
+ {
+ $addFields: {
+ _subagentIsAssistant: { $regexMatch: { input: '$messageId', regex: /:assistant$/ } },
+ _subagentTaskId: {
+ $substrBytes: [
+ '$messageId',
+ 0,
+ {
+ $subtract: [
+ { $strLenBytes: '$messageId' },
+ {
+ $cond: [
+ { $regexMatch: { input: '$messageId', regex: /:assistant$/ } },
+ 10,
+ 5,
+ ],
+ },
+ ],
+ },
+ ],
+ },
+ },
+ },
+ {
+ $sort: {
+ conversationId: 1,
+ _subagentTaskId: 1,
+ _subagentIsAssistant: -1,
+ createdAt: -1,
+ _id: -1,
+ },
+ },
+ {
+ $group: {
+ _id: { conversationId: '$conversationId', taskId: '$_subagentTaskId' },
+ task: { $first: taskProjection },
+ sourceRows: { $sum: 1 },
+ },
+ },
+ {
+ $sort: {
+ '_id.conversationId': 1,
+ 'task.createdAt': -1,
+ 'task.occurrenceId': -1,
+ '_id.taskId': 1,
+ },
+ },
+ {
+ $group: {
+ _id: '$_id.conversationId',
+ tasks: { $push: '$task' },
+ sourceRows: { $sum: '$sourceRows' },
+ },
+ },
+ {
+ $project: {
+ _id: 0,
+ conversationId: '$_id',
+ tasks: { $slice: ['$tasks', input.limitPerThread] },
+ sourceRows: 1,
+ },
+ },
+ { $sort: { conversationId: 1 } },
+ ]),
+ ]);
+ const sourceTruncated =
+ recentRecords.reduce((total, record) => total + (record.sourceRows ?? 0), 0) > sourceLimit;
+ const records = new Map<string, ParentSubagentTaskRecord>(
+ recentRecords.map((record) => [
+ record.conversationId,
+ {
+ conversationId: record.conversationId,
+ tasks: record.tasks,
+ ...(sourceTruncated ? { sourceTruncated: true } : {}),
+ },
+ ]),
+ );
+ for (const latest of latestRecords) {
+ const current = records.get(latest.conversationId);
+ if (current == null) {
+ records.set(latest.conversationId, {
+ ...latest,
+ ...(sourceTruncated ? { sourceTruncated: true } : {}),
+ });
+ continue;
+ }
+ const candidates = [...current.tasks, ...latest.tasks];
+ const tasksById = new Map<string, (typeof candidates)[number]>();
+ for (const candidate of candidates) {
+ const taskId = candidate.messageId.replace(/:(user|assistant)$/, '');
+ const existing = tasksById.get(taskId);
+ const candidateTime = taskTimestamp(candidate.createdAt);
+ const existingTime = taskTimestamp(existing?.createdAt);
+ const candidateIsAssistant = candidate.messageId.endsWith(':assistant');
+ const existingIsAssistant = existing?.messageId.endsWith(':assistant') === true;
+ const occurrenceDifference = compareOccurrenceIds(
+ candidate.occurrenceId,
+ existing?.occurrenceId,
+ );
+ if (
+ existing == null ||
+ candidateTime > existingTime ||
+ (candidateTime === existingTime && occurrenceDifference > 0) ||
+ (candidateTime === existingTime &&
+ occurrenceDifference === 0 &&
+ candidateIsAssistant &&
+ !existingIsAssistant)
+ ) {
+ tasksById.set(taskId, candidate);
+ }
+ }
+ current.tasks = [...tasksById.values()]
+ .sort((left, right) => {
+ const timeDifference = taskTimestamp(right.createdAt) - taskTimestamp(left.createdAt);
+ if (timeDifference !== 0) return timeDifference;
+ const occurrenceDifference = compareOccurrenceIds(right.occurrenceId, left.occurrenceId);
+ if (occurrenceDifference !== 0) return occurrenceDifference;
+ const assistantDifference =
+ Number(right.messageId.endsWith(':assistant')) -
+ Number(left.messageId.endsWith(':assistant'));
+ if (assistantDifference !== 0) return assistantDifference;
+ return left.messageId.localeCompare(right.messageId);
+ })
+ .slice(0, input.limitPerThread);
+ }
+ return [...records.values()].sort((left, right) =>
+ left.conversationId.localeCompare(right.conversationId),
+ );
+ }
+
/**
* Retrieves a single message from the database.
*/
@@ -1247,6 +1475,7 @@ export function createMessageMethods(mongoose: typeof import('mongoose')): Messa
deleteMessagesSince,
getMessages,
getMessagesForSubagentThreadView,
+ listSubagentTasksForThreads,
getMessage,
getMessagesByCursor,
searchMessages,
diff --git a/packages/data-schemas/src/schema/message.ts b/packages/data-schemas/src/schema/message.ts
index 354cd13913..08dfeafaea 100644
--- a/packages/data-schemas/src/schema/message.ts
+++ b/packages/data-schemas/src/schema/message.ts
@@ -274,6 +274,16 @@ messageSchema.index({
*/
messageSchema.index({ conversationId: 1, user: 1, createdAt: 1, _id: 1 });
+/**
+ * Serves the batched newest-task read for child threads. `user` is an equality
+ * prefix and `conversationId` is the partition key, so Mongo/DocumentDB can
+ * stream each partition newest-first without materializing an unbounded sort.
+ */
+messageSchema.index(
+ { user: 1, conversationId: 1, createdAt: -1, _id: -1 },
+ { name: 'subagent_thread_latest_message' },
+);
+
/** Bounds parent-run completion snapshots without scanning a user's message history. */
messageSchema.index(
{ user: 1, 'subagentTask.parentRunId': 1, 'subagentTask.status': 1, updatedAt: -1, _id: -1 },
diff --git a/packages/data-schemas/src/schema/subagent.spec.ts b/packages/data-schemas/src/schema/subagent.spec.ts
index 801c7e608a..5ab17722da 100644
--- a/packages/data-schemas/src/schema/subagent.spec.ts
+++ b/packages/data-schemas/src/schema/subagent.spec.ts
@@ -2,6 +2,14 @@ import type { IndexDefinition, IndexOptions } from 'mongoose';
import messageSchema from './message';
describe('Subagent task indexes', () => {
+ it('streams newest child-task candidates in index order', () => {
+ const indexes = messageSchema.indexes() as Array<[IndexDefinition, IndexOptions]>;
+ expect(indexes).toContainEqual([
+ { user: 1, conversationId: 1, createdAt: -1, _id: -1 },
+ expect.objectContaining({ name: 'subagent_thread_latest_message' }),
+ ]);
+ });
+
it('indexes bounded terminal lookups by parent run and recency', () => {
const indexes = messageSchema.indexes() as Array<[IndexDefinition, IndexOptions]>;
expect(indexes).toContainEqual([