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

📡 refactor: Attach the Subagent Activity Feed Through the Chat Transport (#17526)

Marco Beretta528820d81c1d
diff --git a/client/src/Providers/StreamHostContext.tsx b/client/src/Providers/StreamHostContext.tsx
index e08869ef33..4200bab719 100644
--- a/client/src/Providers/StreamHostContext.tsx
+++ b/client/src/Providers/StreamHostContext.tsx
@@ -1,12 +1,26 @@
+import { useMemo } from 'react';
import type { StreamHost } from '@librechat/chat/react';
+import { useChatTransport } from '~/Providers/ChatTransportContext';
import { useResumableServices } from '~/hooks/SSE/resumable';
+import { useAuthContext } from '~/hooks/AuthContext';
import useSSE from '~/hooks/SSE/useSSE';
+function useTransport() {
+ const { token, isAuthenticated } = useAuthContext();
+ const transport = useChatTransport();
+ return useMemo(
+ () => (isAuthenticated && token != null ? transport.stream({ token }) : null),
+ [isAuthenticated, token, transport],
+ );
+}
+
/** The app's services behind the stream bindings: the resumable stream's handlers, cache and
- * transport, and the Assistants stream, which carries its own response. */
+ * transport, the Assistants stream, which carries its own response, and the signed-in transport
+ * other feeds attach through. */
export const appStreamHost: StreamHost = {
useResumableServices,
useLegacyStream: useSSE,
+ useTransport,
};
export { StreamHostProvider, useStreamHost } from '@librechat/chat/react';
diff --git a/client/src/components/Chat/BackgroundTasks/__tests__/Button.test.tsx b/client/src/components/Chat/BackgroundTasks/__tests__/Button.test.tsx
index 260587d593..5e3c219de1 100644
--- a/client/src/components/Chat/BackgroundTasks/__tests__/Button.test.tsx
+++ b/client/src/components/Chat/BackgroundTasks/__tests__/Button.test.tsx
@@ -1,13 +1,13 @@
import React from 'react';
import { RecoilRoot } from 'recoil';
import userEvent from '@testing-library/user-event';
+import { activeSubagentPanel } from '@librechat/chat/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { act, render, screen, waitFor, within } from '@testing-library/react';
import { ContentTypes, QueryKeys, dataService } from 'librechat-data-provider';
import type { ParentSubagentSummary, BackgroundTaskIndex, TMessage } from 'librechat-data-provider';
import type { JotaiStore } from 'test/harness';
import { ParentSubagentsProvider } from '~/components/Chat/Subagents/ParentSubagentsProvider';
-import { activeSubagentPanel } from '~/components/Chat/Subagents/state';
import { ChatSurfaceHarness } from 'test/harness';
import BackgroundTasksButton from '../Button';
diff --git a/client/src/components/Chat/Messages/Content/MarkdownComponents.tsx b/client/src/components/Chat/Messages/Content/MarkdownComponents.tsx
index b63c5997e3..86f3965b53 100644
--- a/client/src/components/Chat/Messages/Content/MarkdownComponents.tsx
+++ b/client/src/components/Chat/Messages/Content/MarkdownComponents.tsx
@@ -1,4 +1,5 @@
import React, { memo, useMemo, useRef, useEffect } from 'react';
+import { strongDirection } from '@librechat/chat';
import { PermissionTypes, Permissions, apiBaseUrl } from 'librechat-data-provider';
import type { Element, ElementContent } from 'hast';
import {
@@ -12,7 +13,6 @@ import { useMessagePartsHost } from '~/Providers/MessagePartsHostContext';
import { useCodeBlockContext, useMediaContext } from '~/Providers';
import CodeBlock from '~/components/Messages/Content/CodeBlock';
import useHasAccess from '~/hooks/Roles/useHasAccess';
-import { strongDirection } from '~/utils/direction';
import { useFileDownload } from '~/data-provider';
import { useLocalize } from '~/hooks';
diff --git a/client/src/components/Chat/Messages/Content/Parts/SubagentCall.tsx b/client/src/components/Chat/Messages/Content/Parts/SubagentCall.tsx
index 20836ffe63..027f887979 100644
--- a/client/src/components/Chat/Messages/Content/Parts/SubagentCall.tsx
+++ b/client/src/components/Chat/Messages/Content/Parts/SubagentCall.tsx
@@ -1,30 +1,29 @@
import { useCallback, useContext, useEffect, useMemo, useReducer, useRef } from 'react';
import { useSetAtom } from 'jotai';
import { ChevronRight, Users } from 'lucide-react';
-import { useToolCallIntent } from '@librechat/chat/react';
import { FOLD_GLYPH_CLASS } from '@librechat/chat/components';
-import { parseSubagentBackgroundHandle } from '@librechat/chat';
import { ContentTypes, EModelEndpoint } from 'librechat-data-provider';
+import { parseSubagentBackgroundHandle, tailOverflowDirection } from '@librechat/chat';
+import {
+ activeSubagentPanel,
+ subagentProgressKey,
+ useSubagentProgress,
+ useToolCallIntent,
+} from '@librechat/chat/react';
import type {
PartMetadata,
TAttachment,
TMessage,
TMessageContentParts,
} from 'librechat-data-provider';
-import type { SubagentContentPreview } from '~/components/Chat/Subagents/state';
-import type { SubagentTickerLine } from '~/utils/subagentContent';
-import {
- activeSubagentPanel,
- subagentProgressKey,
- useSubagentProgress,
-} from '~/components/Chat/Subagents/state';
+import type { SubagentContentPreview } from '@librechat/chat/react';
+import type { SubagentTickerLine } from '@librechat/chat';
import { useParentSubagents } from '~/components/Chat/Subagents/ParentSubagentsProvider';
import { isSelfSpawn as isSelfSpawnType } from '~/components/Chat/Subagents/author';
import { resolveSubagentAgentId } from '~/components/Chat/Subagents/identity';
import { subagentStatusLabelKey } from '~/components/Chat/Subagents/status';
import { useOpenSubagentPanel } from '~/components/Chat/Subagents/surface';
import { getSubagentPrompt } from '~/components/Chat/Subagents/prompt';
-import { tailOverflowDirection } from '~/utils/subagentContent';
import { MessageContext } from '~/Providers/MessageContext';
import { useShareContext } from '~/Providers/ShareContext';
import MessageIcon from '~/components/Share/MessageIcon';
diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/SubagentCall.test.tsx b/client/src/components/Chat/Messages/Content/Parts/__tests__/SubagentCall.test.tsx
index 0c26c4dd79..34fecc66a8 100644
--- a/client/src/components/Chat/Messages/Content/Parts/__tests__/SubagentCall.test.tsx
+++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/SubagentCall.test.tsx
@@ -4,6 +4,17 @@ import { useAtomValue, useStore } from 'jotai';
import { MemoryRouter } from 'react-router-dom';
import { FOLD_GLYPH_SELECTOR } from '@librechat/chat/components';
import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
+import {
+ activeSubagentPanel,
+ subagentProgressByToolCallId,
+ subagentProgressKey,
+} from '@librechat/chat/react';
+import {
+ foldSubagentEvent,
+ foldSubagentEventIntoTicker,
+ initSubagentAggregatorState,
+ initSubagentTickerState,
+} from '@librechat/chat';
import type {
PartMetadata,
TAttachment,
@@ -15,19 +26,8 @@ import type {
SubagentAggregatorState,
SubagentContentPart,
SubagentTickerState,
-} from '~/utils/subagentContent';
-import type { ActiveSubagentPanel, SubagentProgress } from '~/components/Chat/Subagents/state';
-import {
- foldSubagentEvent,
- foldSubagentEventIntoTicker,
- initSubagentAggregatorState,
- initSubagentTickerState,
-} from '~/utils/subagentContent';
-import {
- activeSubagentPanel,
- subagentProgressByToolCallId,
- subagentProgressKey,
-} from '~/components/Chat/Subagents/state';
+} from '@librechat/chat';
+import type { ActiveSubagentPanel, SubagentProgress } from '@librechat/chat/react';
import SubagentCall, { SUBAGENT_TICKER_THROTTLE_MS } from '../SubagentCall';
import { MessageContext } from '~/Providers/MessageContext';
import { FailedRevealContext } from '../../reveal';
diff --git a/client/src/components/Chat/Messages/Content/__tests__/ContentParts.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ContentParts.test.tsx
index 66c70586c0..a33ff6c74f 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/ContentParts.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/ContentParts.test.tsx
@@ -2,17 +2,17 @@ import React from 'react';
import { getDefaultStore } from 'jotai';
import { ContentTypes, Tools } from 'librechat-data-provider';
import { act, fireEvent, render, screen } from '@testing-library/react';
+import {
+ subagentProgressKey,
+ reduceSubagentProgress,
+ subagentProgressByToolCallId,
+} from '@librechat/chat/react';
import type {
TMessageContentParts,
SubagentUpdateEvent,
TAttachment,
} from 'librechat-data-provider';
-import type { SubagentProgress } from '~/components/Chat/Subagents/state';
-import {
- subagentProgressKey,
- reduceSubagentProgress,
- subagentProgressByToolCallId,
-} from '~/components/Chat/Subagents/state';
+import type { SubagentProgress } from '@librechat/chat/react';
import { preserveStreamedContentIdentity } from '~/utils/messages';
import { mapAttachments, groupSequentialToolCalls } from '~/utils';
diff --git a/client/src/components/Chat/Messages/Content/__tests__/Wakeup.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/Wakeup.test.tsx
index d1f9bf8875..28a81ba849 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/Wakeup.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/Wakeup.test.tsx
@@ -1,9 +1,9 @@
import React from 'react';
import { RecoilRoot } from 'recoil';
import { useAtomValue } from 'jotai';
+import { activeSubagentPanel } from '@librechat/chat/react';
import { fireEvent, render, screen, within } from '@testing-library/react';
import type { ParentSubagentSummary } from 'librechat-data-provider';
-import { activeSubagentPanel } from '~/components/Chat/Subagents/state';
import { ChatSurfaceHarness } from 'test/harness';
import Wakeup from '../Wakeup';
diff --git a/client/src/components/Chat/Presentation.test.tsx b/client/src/components/Chat/Presentation.test.tsx
index 536f33e5d0..f9b33f89f4 100644
--- a/client/src/components/Chat/Presentation.test.tsx
+++ b/client/src/components/Chat/Presentation.test.tsx
@@ -1,14 +1,13 @@
import React from 'react';
import { useSetAtom } from 'jotai';
import { RecoilRoot, useSetRecoilState } from 'recoil';
-import { isSubmittingFamily } from '@librechat/chat/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { activeSubagentPanel, isSubmittingFamily } from '@librechat/chat/react';
import type { TConversation } from 'librechat-data-provider';
import type { JotaiStore } from 'test/harness';
import type { Artifact } from '~/common';
import { prepareUndockedDocument } from '~/components/Artifacts/undockedWindow';
-import { activeSubagentPanel } from '~/components/Chat/Subagents/state';
import { undockedArtifacts } from '~/components/Artifacts/state';
import { ChatSurfaceHarness } from 'test/harness';
import Presentation from './Presentation';
diff --git a/client/src/components/Chat/Presentation.tsx b/client/src/components/Chat/Presentation.tsx
index e8c9e14963..a9f60d709e 100644
--- a/client/src/components/Chat/Presentation.tsx
+++ b/client/src/components/Chat/Presentation.tsx
@@ -1,7 +1,7 @@
import { Suspense, useCallback, useEffect, useMemo, useRef } from 'react';
import { useRecoilValue } from 'recoil';
import { useAtomValue, useSetAtom } from 'jotai';
-import { useIsSubmitting } from '@librechat/chat/react';
+import { activeSubagentPanel, useIsSubmitting } from '@librechat/chat/react';
import { EModelEndpoint, FileSources, LocalStorageKeys } from 'librechat-data-provider';
import type { ExtendedFile } from '~/common';
import { ParentSubagentsProvider } from '~/components/Chat/Subagents/ParentSubagentsProvider';
@@ -10,7 +10,6 @@ import { useDeleteFilesMutation, useGetStartupConfig } from '~/data-provider';
import { MessageSurfaceContext } from '~/components/Chat/Messages/ui/surface';
import DragDropWrapper from '~/components/Chat/Input/Files/DragDropWrapper';
import UndockedArtifacts from '~/components/Artifacts/UndockedArtifacts';
-import { activeSubagentPanel } from '~/components/Chat/Subagents/state';
import { artifactsUndocked } from '~/components/Artifacts/state';
import { EditorProvider, ArtifactsProvider } from '~/Providers';
import { SidePanelGroup } from '~/components/SidePanel';
diff --git a/client/src/components/Chat/Subagents/EventSubagentActivityGroup.test.tsx b/client/src/components/Chat/Subagents/EventSubagentActivityGroup.test.tsx
index 40f607c236..5e8bc18b0a 100644
--- a/client/src/components/Chat/Subagents/EventSubagentActivityGroup.test.tsx
+++ b/client/src/components/Chat/Subagents/EventSubagentActivityGroup.test.tsx
@@ -1,12 +1,12 @@
import React from 'react';
import { useAtomValue, useSetAtom } from 'jotai';
+import { activeSubagentPanel } from '@librechat/chat/react';
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
import type { ParentSubagentSummary } from 'librechat-data-provider';
-import type { ActiveSubagentPanel } from './state';
+import type { ActiveSubagentPanel } from '@librechat/chat/react';
import EventSubagentActivityGroup from './EventSubagentActivityGroup';
import { ChatSurfaceHarness, testChatSurface } from 'test/harness';
import { durableSubagentSelection } from './eventSelection';
-import { activeSubagentPanel } from './state';
const mockRefresh = jest.fn().mockResolvedValue(undefined);
const mockChild: ParentSubagentSummary = {
diff --git a/client/src/components/Chat/Subagents/EventSubagentActivityGroup.tsx b/client/src/components/Chat/Subagents/EventSubagentActivityGroup.tsx
index dc14175785..0a9fea1c3a 100644
--- a/client/src/components/Chat/Subagents/EventSubagentActivityGroup.tsx
+++ b/client/src/components/Chat/Subagents/EventSubagentActivityGroup.tsx
@@ -2,6 +2,7 @@ import { useCallback, useId, useMemo, useState } from 'react';
import { useSetAtom } from 'jotai';
import { Button, cn } from '@librechat/client';
import { Bot, ChevronDown } from 'lucide-react';
+import { activeSubagentPanel } from '@librechat/chat/react';
import { getMessageRowWidthClass } from '@librechat/chat/components';
import type { ParentSubagentSummary } from 'librechat-data-provider';
import { isLiveSubagentStatus, subagentStatusDotClass, subagentStatusLabelKey } from './status';
@@ -9,7 +10,6 @@ import { useChatSurface, useOpenSubagentPanel } from './surface';
import { useParentSubagents } from './ParentSubagentsProvider';
import { eventSubagentSelection } from './eventSelection';
import { useAgentsMapContext } from '~/Providers';
-import { activeSubagentPanel } from './state';
import { renderAgentAvatar } from '~/utils';
import { useLocalize } from '~/hooks';
diff --git a/client/src/components/Chat/Subagents/SharedSubagentActivityDialog.tsx b/client/src/components/Chat/Subagents/SharedSubagentActivityDialog.tsx
index 071fbc00e3..ecace48292 100644
--- a/client/src/components/Chat/Subagents/SharedSubagentActivityDialog.tsx
+++ b/client/src/components/Chat/Subagents/SharedSubagentActivityDialog.tsx
@@ -1,5 +1,6 @@
import { useCallback, useEffect, useMemo, useRef } from 'react';
import { useAtom } from 'jotai';
+import { activeSubagentPanel } from '@librechat/chat/react';
import { OGDialog, OGDialogContent, OGDialogHeader, OGDialogTitle } from '@librechat/client';
import type { TMessage } from 'librechat-data-provider';
import {
@@ -15,7 +16,6 @@ import SubagentConversation from './SubagentConversation';
import { adaptLivePersistedActivity } from './adapters';
import { resolveSubagentAgentId } from './identity';
import { useAgentsMapContext } from '~/Providers';
-import { activeSubagentPanel } from './state';
import { useLocalize } from '~/hooks';
/** Public-share fallback for subagent activity already embedded in the shared message payload. */
diff --git a/client/src/components/Chat/Subagents/SubagentThreadPanel.test.tsx b/client/src/components/Chat/Subagents/SubagentThreadPanel.test.tsx
index b4b139faa4..85a803fff9 100644
--- a/client/src/components/Chat/Subagents/SubagentThreadPanel.test.tsx
+++ b/client/src/components/Chat/Subagents/SubagentThreadPanel.test.tsx
@@ -1,18 +1,22 @@
import React from 'react';
import { useAtomValue, useSetAtom } from 'jotai';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { initSubagentAggregatorState, initSubagentTickerState } from '@librechat/chat';
import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { ContentTypes, EModelEndpoint, ForkOptions, QueryKeys } from 'librechat-data-provider';
+import {
+ activeSubagentPanel,
+ subagentProgressByToolCallId,
+ subagentProgressKey,
+} from '@librechat/chat/react';
import type {
TMessage,
SubagentThreadView,
TMessageContentParts,
ParentSubagentSummary,
} from 'librechat-data-provider';
-import type { ActiveSubagentPanel } from './state';
+import type { ActiveSubagentPanel } from '@librechat/chat/react';
import type { JotaiStore } from 'test/harness';
-import { activeSubagentPanel, subagentProgressByToolCallId, subagentProgressKey } from './state';
-import { initSubagentAggregatorState, initSubagentTickerState } from '~/utils/subagentContent';
import { ChatSurfaceHarness, testChatSurface } from 'test/harness';
import SubagentThreadPanel from './SubagentThreadPanel';
import { useOpenSubagentPanel } from './surface';
@@ -124,9 +128,9 @@ jest.mock('~/data-provider', () => ({
}),
}));
-jest.mock('~/data-provider/Subagents/useSubagentActivityStream', () => ({
- __esModule: true,
- default: (...args: unknown[]) => mockUseSubagentActivityStream(...args),
+jest.mock('@librechat/chat/react', () => ({
+ ...jest.requireActual('@librechat/chat/react'),
+ useSubagentActivityStream: (...args: unknown[]) => mockUseSubagentActivityStream(...args),
}));
jest.mock('~/hooks', () => ({
diff --git a/client/src/components/Chat/Subagents/SubagentThreadPanel.tsx b/client/src/components/Chat/Subagents/SubagentThreadPanel.tsx
index 95f7690133..40e70b2a3b 100644
--- a/client/src/components/Chat/Subagents/SubagentThreadPanel.tsx
+++ b/client/src/components/Chat/Subagents/SubagentThreadPanel.tsx
@@ -12,6 +12,15 @@ import {
useMediaQuery,
useToastContext,
} from '@librechat/client';
+import {
+ activeSubagentPanel,
+ subagentPanelFocusRequest,
+ subagentControlStateByTask,
+ subagentControlStateKey,
+ subagentProgressKey,
+ useSubagentProgress,
+ useSubagentActivityStream,
+} from '@librechat/chat/react';
import type {
ParentSubagentTaskSummary,
SubagentControlAction,
@@ -19,8 +28,8 @@ import type {
SubagentControlRequest,
} from 'librechat-data-provider';
import type { ComposerKeyVerdict, ComposerStopProps, SendAction } from '@librechat/client';
+import type { ActiveSubagentPanel, SubagentControlUiState } from '@librechat/chat/react';
import type { KeyboardEvent as ReactKeyboardEvent, ReactNode } from 'react';
-import type { ActiveSubagentPanel, SubagentControlUiState } from './state';
import type { ComposerKeyAction } from '~/utils/shortcuts';
import type { OptionWithIcon } from '~/common';
import {
@@ -38,14 +47,6 @@ import {
mergeChildConversationTurns,
retainBoundedMovingWindowTurns,
} from './adapters';
-import {
- activeSubagentPanel,
- subagentPanelFocusRequest,
- subagentControlStateByTask,
- subagentControlStateKey,
- subagentProgressKey,
- useSubagentProgress,
-} from './state';
import {
agentAuthor,
resolveSubagentAuthor,
@@ -54,7 +55,6 @@ import {
readableSubagentType,
useParentAuthor,
} from './author';
-import useSubagentActivityStream from '~/data-provider/Subagents/useSubagentActivityStream';
import SubagentActivity, { SubagentActivityScrollSurface } from './SubagentActivity';
import ApprovalProvider from '~/components/Chat/Messages/Content/ApprovalContext';
import { TaskContentScopeContext } from '~/data-provider/Subagents/content';
diff --git a/client/src/components/Chat/Subagents/adapters.test.ts b/client/src/components/Chat/Subagents/adapters.test.ts
index de8ddf9e9a..db865bd18b 100644
--- a/client/src/components/Chat/Subagents/adapters.test.ts
+++ b/client/src/components/Chat/Subagents/adapters.test.ts
@@ -1,4 +1,5 @@
import { ContentTypes } from 'librechat-data-provider';
+import { initSubagentAggregatorState, initSubagentTickerState } from '@librechat/chat';
import type {
SubagentThreadView,
SubagentUpdateEvent,
@@ -14,7 +15,6 @@ import {
mergeChildConversationTurns,
retainBoundedMovingWindowTurns,
} from './adapters';
-import { initSubagentAggregatorState, initSubagentTickerState } from '~/utils/subagentContent';
import { aggregateSubagentContent } from 'test/subagents';
describe('child activity adapters', () => {
diff --git a/client/src/components/Chat/Subagents/adapters.ts b/client/src/components/Chat/Subagents/adapters.ts
index cf68117055..887a9c257f 100644
--- a/client/src/components/Chat/Subagents/adapters.ts
+++ b/client/src/components/Chat/Subagents/adapters.ts
@@ -1,4 +1,5 @@
import { ContentTypes } from 'librechat-data-provider';
+import { REDACTED_REASONING_MARKER } from '@librechat/chat/react';
import type {
Agents,
PartMetadata,
@@ -12,8 +13,7 @@ import type {
TAttachment,
FullToolCall,
} from 'librechat-data-provider';
-import type { SubagentProgress } from './state';
-import { REDACTED_REASONING_MARKER } from './state';
+import type { SubagentProgress } from '@librechat/chat/react';
export type ChildActivityItem =
| Extract<SubagentActivityItem, { type: 'steer' }>
diff --git a/client/src/components/Chat/Subagents/attachments.ts b/client/src/components/Chat/Subagents/attachments.ts
index fe9ccdfe00..4ac6789407 100644
--- a/client/src/components/Chat/Subagents/attachments.ts
+++ b/client/src/components/Chat/Subagents/attachments.ts
@@ -1,15 +1,6 @@
import { createContext, useEffect, useMemo, useRef } from 'react';
import { Constants } from 'librechat-data-provider';
import { atom, useStore, useAtomValue } from 'jotai';
-import type {
- Agents,
- TAttachment,
- FullToolCall,
- TMessageContentParts,
- SubagentAttachmentFile,
- SubagentAttachmentCallsResponse,
-} from 'librechat-data-provider';
-import type { SubagentContentPart } from '~/utils/subagentContent';
import {
nestedToolCallOf,
collectNestedCalls,
@@ -18,7 +9,16 @@ import {
rememberSubagentChildCalls,
rememberedSubagentChildCalls,
subagentProgressByToolCallId,
-} from './state';
+} from '@librechat/chat/react';
+import type {
+ Agents,
+ TAttachment,
+ FullToolCall,
+ TMessageContentParts,
+ SubagentAttachmentFile,
+ SubagentAttachmentCallsResponse,
+} from 'librechat-data-provider';
+import type { SubagentContentPart } from '@librechat/chat';
import { useSubagentAttachmentCallsQueries } from '~/data-provider';
export { collectNestedCalls };
diff --git a/client/src/components/Chat/Subagents/eventSelection.ts b/client/src/components/Chat/Subagents/eventSelection.ts
index 1ef2122b01..70e694ef9a 100644
--- a/client/src/components/Chat/Subagents/eventSelection.ts
+++ b/client/src/components/Chat/Subagents/eventSelection.ts
@@ -1,5 +1,5 @@
import type { ParentSubagentSummary } from 'librechat-data-provider';
-import type { ActiveSubagentPanel } from './state';
+import type { ActiveSubagentPanel } from '@librechat/chat/react';
export const eventTaskProgressKey = (threadId: string, taskId: string) =>
`event-task:${threadId}:${taskId}`;
diff --git a/client/src/components/Chat/Subagents/surface.tsx b/client/src/components/Chat/Subagents/surface.tsx
index 4bfddabd54..bcf0c2943b 100644
--- a/client/src/components/Chat/Subagents/surface.tsx
+++ b/client/src/components/Chat/Subagents/surface.tsx
@@ -1,9 +1,9 @@
import { createContext, useContext, useMemo } from 'react';
import { useSetAtom } from 'jotai';
+import { activeSubagentPanel, subagentPanelFocusRequest } from '@librechat/chat/react';
+import type { ActiveSubagentPanel } from '@librechat/chat/react';
import type { ReactNode } from 'react';
import type { ComposerBindings } from '~/hooks/Input/useComposerBindings';
-import type { ActiveSubagentPanel } from './state';
-import { activeSubagentPanel, subagentPanelFocusRequest } from './state';
/**
* Everything this feature needs from the application hosting it, and nothing
diff --git a/client/src/components/Chat/Subagents/task.ts b/client/src/components/Chat/Subagents/task.ts
index a055503197..94a6a851ed 100644
--- a/client/src/components/Chat/Subagents/task.ts
+++ b/client/src/components/Chat/Subagents/task.ts
@@ -1,5 +1,5 @@
import { useCallback, useMemo } from 'react';
-import type { ActiveSubagentPanel } from './state';
+import type { ActiveSubagentPanel } from '@librechat/chat/react';
import { useParentSubagents } from './ParentSubagentsProvider';
import { durableSubagentSelection } from './eventSelection';
import { useShareContext } from '~/Providers/ShareContext';
diff --git a/client/src/hooks/SSE/__tests__/stepEquivalence.spec.ts b/client/src/hooks/SSE/__tests__/stepEquivalence.spec.ts
index b1246267af..451968d3b0 100644
--- a/client/src/hooks/SSE/__tests__/stepEquivalence.spec.ts
+++ b/client/src/hooks/SSE/__tests__/stepEquivalence.spec.ts
@@ -10,6 +10,12 @@ import {
ContentTypes,
ToolCallTypes,
} from 'librechat-data-provider';
+import {
+ subagentProgressKey,
+ subagentProgressByToolCallId,
+ takeRegisteredSubagentProgressKeys,
+ subagentParentStreamOpenByToolCallId,
+} from '@librechat/chat/react';
import type {
Agents,
TMessage,
@@ -19,12 +25,6 @@ import type {
TMessageContentParts,
} from 'librechat-data-provider';
import type { StepEvent } from '@librechat/chat';
-import {
- subagentProgressKey,
- subagentProgressByToolCallId,
- takeRegisteredSubagentProgressKeys,
- subagentParentStreamOpenByToolCallId,
-} from '~/components/Chat/Subagents/state';
import { ptcTraceByToolCallId, ptcTraceKey } from '~/hooks/SSE/ptc';
import { sandboxStartingByToolCallId } from '~/hooks/SSE/sandbox';
import useStepHandler from '~/hooks/SSE/useStepHandler';
diff --git a/client/src/hooks/SSE/__tests__/useStepHandler.spec.ts b/client/src/hooks/SSE/__tests__/useStepHandler.spec.ts
index 7ea3fb729f..89fbe9699a 100644
--- a/client/src/hooks/SSE/__tests__/useStepHandler.spec.ts
+++ b/client/src/hooks/SSE/__tests__/useStepHandler.spec.ts
@@ -9,6 +9,15 @@ import {
ContentTypes,
ToolCallTypes,
} from 'librechat-data-provider';
+import {
+ activeSubagentPanel,
+ listRegisteredSubagentProgressKeys,
+ reduceSubagentProgress,
+ registerSubagentProgressKey,
+ subagentParentStreamOpenByToolCallId,
+ subagentProgressByToolCallId,
+ subagentProgressKey,
+} from '@librechat/chat/react';
import type {
TMessageContentParts,
SummaryContentPart,
@@ -20,17 +29,8 @@ import type {
PtcToolCallEvent,
Agents,
} from 'librechat-data-provider';
-import type { ActiveSubagentPanel } from '~/components/Chat/Subagents/state';
+import type { ActiveSubagentPanel } from '@librechat/chat/react';
import type { PtcTrace, PtcTraceEntry } from '~/common';
-import {
- activeSubagentPanel,
- listRegisteredSubagentProgressKeys,
- reduceSubagentProgress,
- registerSubagentProgressKey,
- subagentParentStreamOpenByToolCallId,
- subagentProgressByToolCallId,
- subagentProgressKey,
-} from '~/components/Chat/Subagents/state';
import { ptcTraceByToolCallId, ptcTraceKey, PTC_TRACE_MAX_ENTRIES } from '~/hooks/SSE/ptc';
import { sandboxStartingByToolCallId } from '~/hooks/SSE/sandbox';
import { resolveAskUserQuestionPart } from '~/utils/approval';
diff --git a/client/src/hooks/SSE/useStepHandler.ts b/client/src/hooks/SSE/useStepHandler.ts
index d3f351daaa..53e9b437a6 100644
--- a/client/src/hooks/SSE/useStepHandler.ts
+++ b/client/src/hooks/SSE/useStepHandler.ts
@@ -9,14 +9,6 @@ import {
createStreamState,
subagentProgressKey,
} from '@librechat/chat';
-import type {
- TMessage,
- EventSubmission,
- SubagentUpdateEvent,
- PtcToolCallEvent,
-} from 'librechat-data-provider';
-import type { StepEvent, StepEffect, StepContext, StreamState } from '@librechat/chat';
-import type { AnnounceOptions } from '~/common';
import {
activeSubagentPanel,
closeParentSubagentProgress,
@@ -27,7 +19,15 @@ import {
subagentParentStreamOpenByToolCallId,
subagentProgressByToolCallId,
takeRegisteredSubagentProgressKeys,
-} from '~/components/Chat/Subagents/state';
+} from '@librechat/chat/react';
+import type {
+ TMessage,
+ EventSubmission,
+ SubagentUpdateEvent,
+ PtcToolCallEvent,
+} from 'librechat-data-provider';
+import type { StepEvent, StepEffect, StepContext, StreamState } from '@librechat/chat';
+import type { AnnounceOptions } from '~/common';
import { ptcTraceByToolCallId, EMPTY_PTC_TRACE, PTC_TRACE_MAX_ENTRIES, ptcTraceKey } from './ptc';
import { sandboxStartingByToolCallId } from './sandbox';
import { MESSAGE_UPDATE_INTERVAL } from '~/common';
diff --git a/client/test/subagents.ts b/client/test/subagents.ts
index ccdb4a1d9f..323535c080 100644
--- a/client/test/subagents.ts
+++ b/client/test/subagents.ts
@@ -1,11 +1,11 @@
import type { SubagentUpdateEvent } from 'librechat-data-provider';
-import type { SubagentContentPart, SubagentTickerLine } from '~/utils/subagentContent';
+import type { SubagentContentPart, SubagentTickerLine } from '@librechat/chat';
import {
foldSubagentEvent,
initSubagentTickerState,
foldSubagentEventIntoTicker,
initSubagentAggregatorState,
-} from '~/utils/subagentContent';
+} from '@librechat/chat';
/** Folds a whole event stream through the incremental aggregator the live UI uses. */
export function aggregateSubagentContent(events: SubagentUpdateEvent[]): SubagentContentPart[] {
diff --git a/e2e/specs/mock/subagent-activity.spec.ts b/e2e/specs/mock/subagent-activity.spec.ts
index 1a778f3008..1b73d8d46b 100644
--- a/e2e/specs/mock/subagent-activity.spec.ts
+++ b/e2e/specs/mock/subagent-activity.spec.ts
@@ -52,7 +52,7 @@ async function selectAgent(page: Page, name: string): Promise<void> {
}
test.describe('detached subagent activity', () => {
- test('streams two child runs into the shared panel and restores terminal activity', async ({
+ test('streams two child runs into the shared panel and restores terminal activity @scenario:subagent-panel-streams-child-activity-once', async ({
page,
}) => {
test.setTimeout(120_000);
@@ -226,6 +226,43 @@ async function assertFullToolDetails(
await expect(details.getByText(history.payload(label, index), { exact: true })).toBeVisible();
}
+/**
+ * Where the steer sits relative to the text before and after it, in document
+ * order within its conversation. Each text is matched by the innermost element
+ * holding exactly that text, so the check reads the same whether the turn is
+ * still streaming (words split into `[data-lc-fade]` spans) or has settled.
+ */
+async function steerPlacement(
+ steer: Locator,
+ before: string,
+ after: string,
+): Promise<{ before: boolean; after: boolean }> {
+ return steer.evaluate(
+ (node, texts) => {
+ const root = node.closest('[data-subagent-conversation]');
+ const find = (text: string): Element | undefined => {
+ if (root == null) return undefined;
+ return [...root.querySelectorAll('*')].find(
+ (element) =>
+ element.textContent === text &&
+ ![...element.children].some((child) => child.textContent === text),
+ );
+ };
+ const preceding = find(texts.before);
+ const following = find(texts.after);
+ return {
+ before:
+ preceding != null &&
+ Boolean(preceding.compareDocumentPosition(node) & Node.DOCUMENT_POSITION_FOLLOWING),
+ after:
+ following != null &&
+ Boolean(node.compareDocumentPosition(following) & Node.DOCUMENT_POSITION_FOLLOWING),
+ };
+ },
+ { before, after },
+ );
+}
+
async function openHistoryChild(page: Page, label: string): Promise<Locator> {
const card = page.locator(`[data-subagent-tool-call="${history.dispatchId(label)}"]`);
await expect
@@ -259,7 +296,9 @@ async function historyThreadPath(
test.describe('subagent chat retained-history parity', () => {
for (const mode of ['normal chat', 'late open', 'cold reload'] as const) {
- const name = `${mode} restores over-capacity history while running and completes once`;
+ const scenario =
+ mode === 'late open' ? ' @scenario:subagent-panel-replays-history-then-goes-live' : '';
+ const name = `${mode} restores over-capacity history while running and completes once${scenario}`;
test(name, async ({ page, browser, baseURL }, testInfo) => {
test.setTimeout(120_000);
const prefix = `history-${mode.replaceAll(' ', '-')}`;
@@ -432,51 +471,12 @@ test.describe('subagent chat retained-history parity', () => {
await expect(
surface.getByText('Message shortened for display.', { exact: true }),
).toHaveCount(0);
- const precedingText = history.liveText(label);
- expect(
- await steer.evaluate((node, text) => {
- const root = node.closest('[data-subagent-conversation]')!;
- const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT);
- let current: Node | null;
- while ((current = walker.nextNode())) {
- if (
- current.textContent === text &&
- current instanceof HTMLElement &&
- current.children.length === 0
- ) {
- return Boolean(
- current.compareDocumentPosition(node) & Node.DOCUMENT_POSITION_FOLLOWING,
- );
- }
- }
- return false;
- }, precedingText),
- ).toBe(true);
- const completion = surface.getByText(history.completionText(label), { exact: true });
- expect(
- await steer.evaluate(
- (node, completedText) => {
- const walker = document.createTreeWalker(
- node.closest('[data-subagent-conversation]')!,
- NodeFilter.SHOW_ELEMENT,
- );
- let current: Node | null;
- while ((current = walker.nextNode())) {
- if (
- current.textContent === completedText &&
- current instanceof HTMLElement &&
- current.children.length === 0
- ) {
- return Boolean(
- node.compareDocumentPosition(current) & Node.DOCUMENT_POSITION_FOLLOWING,
- );
- }
- }
- return false;
- },
- await completion.textContent(),
- ),
- ).toBe(true);
+ const placement = { before: true, after: true };
+ const live = history.liveText(label);
+ const completed = history.completionText(label);
+ expect(await steerPlacement(steer, live, completed)).toEqual(placement);
+ await expect(surface.locator('[data-lc-fade]')).toHaveCount(0, { timeout: 20_000 });
+ expect(await steerPlacement(steer, live, completed)).toEqual(placement);
}
if (mode !== 'normal chat') {
diff --git a/packages/chat/jest.config.js b/packages/chat/jest.config.js
index e3941e18d6..b627d8dfc9 100644
--- a/packages/chat/jest.config.js
+++ b/packages/chat/jest.config.js
@@ -21,5 +21,6 @@ module.exports = {
},
// The core runs without a DOM; a React spec opts into jsdom with a docblock.
testEnvironment: 'node',
+ setupFiles: ['<rootDir>/jest.polyfills.js'],
setupFilesAfterEnv: ['@testing-library/jest-dom/extend-expect'],
};
diff --git a/packages/chat/jest.polyfills.js b/packages/chat/jest.polyfills.js
new file mode 100644
index 0000000000..132109e01f
--- /dev/null
+++ b/packages/chat/jest.polyfills.js
@@ -0,0 +1,6 @@
+/** jsdom has no TextEncoder; the subagent reducers measure payload sizes with it. */
+const { TextEncoder } = require('node:util');
+
+if (typeof globalThis.TextEncoder === 'undefined') {
+ globalThis.TextEncoder = TextEncoder;
+}
diff --git a/packages/chat/src/core/__fixtures__/subagents.ts b/packages/chat/src/core/__fixtures__/subagents.ts
new file mode 100644
index 0000000000..55c16b72a8
--- /dev/null
+++ b/packages/chat/src/core/__fixtures__/subagents.ts
@@ -0,0 +1,27 @@
+import type { SubagentUpdateEvent } from 'librechat-data-provider';
+import type { SubagentContentPart, SubagentTickerLine } from '../subagents/content';
+import {
+ foldSubagentEvent,
+ initSubagentTickerState,
+ foldSubagentEventIntoTicker,
+ initSubagentAggregatorState,
+} from '../subagents/content';
+
+/** Folds a whole event stream through the incremental aggregator the live UI uses. */
+export function aggregateSubagentContent(events: SubagentUpdateEvent[]): SubagentContentPart[] {
+ let parts: SubagentContentPart[] = [];
+ let state = initSubagentAggregatorState();
+ for (const event of events) {
+ ({ parts, state } = foldSubagentEvent(parts, state, event));
+ }
+ return parts;
+}
+
+/** Folds a whole event stream through the incremental ticker the live UI uses. */
+export function buildSubagentTickerLines(events: SubagentUpdateEvent[]): SubagentTickerLine[] {
+ let state = initSubagentTickerState();
+ for (const event of events) {
+ state = foldSubagentEventIntoTicker(state, event);
+ }
+ return state.lines;
+}
diff --git a/client/src/utils/__tests__/direction.test.ts b/packages/chat/src/core/__tests__/direction.spec.ts
similarity index 100%
rename from client/src/utils/__tests__/direction.test.ts
rename to packages/chat/src/core/__tests__/direction.spec.ts
diff --git a/packages/chat/src/core/__tests__/frames.spec.ts b/packages/chat/src/core/__tests__/frames.spec.ts
index 10df6de5dd..867a34b504 100644
--- a/packages/chat/src/core/__tests__/frames.spec.ts
+++ b/packages/chat/src/core/__tests__/frames.spec.ts
@@ -79,6 +79,13 @@ describe('normalizeFrame', () => {
expect(normalizeFrame(text)).toEqual({ type: 'text', data: text });
});
+ it('marks the live boundary of a replaying feed as ready', () => {
+ expect(normalizeFrame(frame({ ready: true, contentRecovery: true }))).toEqual({
+ type: 'ready',
+ });
+ expect(normalizeFrame(frame({ ready: false }))).toBeUndefined();
+ });
+
it('returns undefined for a frame with none of the keys', () => {
expect(normalizeFrame(frame({}))).toBeUndefined();
expect(normalizeFrame(frame({ final: null, created: null }))).toBeUndefined();
diff --git a/client/src/utils/direction.ts b/packages/chat/src/core/direction.ts
similarity index 100%
rename from client/src/utils/direction.ts
rename to packages/chat/src/core/direction.ts
diff --git a/packages/chat/src/core/index.ts b/packages/chat/src/core/index.ts
index 58e7dc8703..d3c29f4d63 100644
--- a/packages/chat/src/core/index.ts
+++ b/packages/chat/src/core/index.ts
@@ -17,3 +17,5 @@ export * from './regenerate';
export * from './content';
export * from './turns';
export * from './parts';
+export * from './subagents';
+export { strongDirection } from './direction';
diff --git a/client/src/utils/__tests__/subagentContent.test.ts b/packages/chat/src/core/subagents/__tests__/content.spec.ts
similarity index 99%
rename from client/src/utils/__tests__/subagentContent.test.ts
rename to packages/chat/src/core/subagents/__tests__/content.spec.ts
index 7a9af1379f..f67d163a5d 100644
--- a/client/src/utils/__tests__/subagentContent.test.ts
+++ b/packages/chat/src/core/subagents/__tests__/content.spec.ts
@@ -1,7 +1,7 @@
import { ContentTypes } from 'librechat-data-provider';
import type { SubagentUpdateEvent } from 'librechat-data-provider';
-import { aggregateSubagentContent, buildSubagentTickerLines } from 'test/subagents';
-import { tailOverflowDirection, textDirection } from '../subagentContent';
+import { aggregateSubagentContent, buildSubagentTickerLines } from '../../__fixtures__/subagents';
+import { tailOverflowDirection, textDirection } from '../content';
const makeEvent = (overrides: Partial<SubagentUpdateEvent>): SubagentUpdateEvent => ({
runId: 'parent-run',
diff --git a/client/src/utils/subagentContent.ts b/packages/chat/src/core/subagents/content.ts
similarity index 99%
rename from client/src/utils/subagentContent.ts
rename to packages/chat/src/core/subagents/content.ts
index a4599cfc8e..8f66d580b1 100644
--- a/client/src/utils/subagentContent.ts
+++ b/packages/chat/src/core/subagents/content.ts
@@ -4,7 +4,7 @@ import type {
ToolTimingStamps,
TSteerAppliedEvent,
} from 'librechat-data-provider';
-import { strongDirection } from './direction';
+import { strongDirection } from '../direction';
/**
* Client-side helpers for rendering the live `SubagentCall` UI while
diff --git a/packages/chat/src/core/subagents/index.ts b/packages/chat/src/core/subagents/index.ts
new file mode 100644
index 0000000000..7b367d1463
--- /dev/null
+++ b/packages/chat/src/core/subagents/index.ts
@@ -0,0 +1 @@
+export * from './content';
diff --git a/packages/chat/src/core/transport/frames.ts b/packages/chat/src/core/transport/frames.ts
index cbf6149482..37f2c51268 100644
--- a/packages/chat/src/core/transport/frames.ts
+++ b/packages/chat/src/core/transport/frames.ts
@@ -24,6 +24,7 @@ type FrameKeys = {
sync?: unknown;
type?: unknown;
message?: unknown;
+ ready?: unknown;
};
function normalizeEventFrame(frame: ChatEventFrame): ChatEvent {
@@ -57,8 +58,8 @@ function normalizeEventFrame(frame: ChatEventFrame): ChatEvent {
* Tags one `message` frame by the keys the server wrote, checked in the order
* the stream hooks have always checked them: a frame carrying both `final`
* and `event` is final. An `event` the client does not name is a step event,
- * so the step handler keeps seeing new graph events as it did before. A frame
- * with none of the keys returns `undefined`.
+ * so the step handler keeps seeing new graph events as it did before. A replay
+ * feed's `{ ready: true }` is `ready`; a frame with none of the keys returns `undefined`.
*/
export function normalizeFrame(frame: ChatFrame): ChatEvent | undefined {
const keys: FrameKeys = frame;
@@ -80,5 +81,8 @@ export function normalizeFrame(frame: ChatFrame): ChatEvent | undefined {
if (keys.message != null) {
return { type: 'text', data: frame as ChatTextFrame };
}
+ if (keys.ready === true) {
+ return { type: 'ready' };
+ }
return undefined;
}
diff --git a/packages/chat/src/react.ts b/packages/chat/src/react.ts
index 1c72201cdc..15a9589664 100644
--- a/packages/chat/src/react.ts
+++ b/packages/chat/src/react.ts
@@ -1,6 +1,7 @@
/** React bindings for the core `Chat`: providers and `useChat`. Populated as the hooks move in. */
export * from './react/chat';
export * from './react/stream';
+export * from './react/subagents';
export { MessageContext, MessagePartIndex, useMessageContext } from './react/message';
export {
useMessagePartsHost,
diff --git a/packages/chat/src/react/stream/__tests__/adaptive.spec.tsx b/packages/chat/src/react/stream/__tests__/adaptive.spec.tsx
index be5c10e9cc..3689c1e286 100644
--- a/packages/chat/src/react/stream/__tests__/adaptive.spec.tsx
+++ b/packages/chat/src/react/stream/__tests__/adaptive.spec.tsx
@@ -18,6 +18,7 @@ const host: StreamHost = {
throw new Error('the resumable binding is replaced in this spec');
},
useLegacyStream,
+ useTransport: () => null,
};
const wrapper = ({ children }: { children: React.ReactNode }) => (
diff --git a/packages/chat/src/react/stream/host.tsx b/packages/chat/src/react/stream/host.tsx
index d753c1a1fd..ab51f44bd1 100644
--- a/packages/chat/src/react/stream/host.tsx
+++ b/packages/chat/src/react/stream/host.tsx
@@ -1,6 +1,6 @@
import { createContext, useContext } from 'react';
+import type { ChatTransport, TSubmission } from 'librechat-data-provider';
import type { Dispatch, ReactNode, SetStateAction } from 'react';
-import type { TSubmission } from 'librechat-data-provider';
import type { ResumableHost, ResumableRun } from '../../core';
import type { ChatContract } from '../chat/contract';
@@ -44,6 +44,11 @@ export interface StreamHost {
isAddedRequest: boolean,
runIndex: number,
): void;
+ /**
+ * The signed-in user's stream transport, or `null` before sign-in, for feeds outside a chat
+ * turn such as a subagent's activity. Changes when the token does.
+ */
+ useTransport(): ChatTransport | null;
}
const StreamHostContext = createContext<StreamHost | null>(null);
diff --git a/client/src/components/Chat/Subagents/state.spec.ts b/packages/chat/src/react/subagents/__tests__/state.spec.ts
similarity index 99%
rename from client/src/components/Chat/Subagents/state.spec.ts
rename to packages/chat/src/react/subagents/__tests__/state.spec.ts
index 91fa6c2442..20fd5526b2 100644
--- a/client/src/components/Chat/Subagents/state.spec.ts
+++ b/packages/chat/src/react/subagents/__tests__/state.spec.ts
@@ -1,9 +1,12 @@
+/**
+ * @jest-environment jsdom
+ */
import React from 'react';
import { ContentTypes } from 'librechat-data-provider';
import { act, renderHook } from '@testing-library/react';
import { createStore, Provider as JotaiProvider } from 'jotai';
import type { SubagentUpdateEvent } from 'librechat-data-provider';
-import type { SubagentProgress } from './state';
+import type { SubagentProgress } from '../state';
import {
closeParentSubagentProgress,
reduceSubagentProgress,
@@ -17,7 +20,7 @@ import {
subagentProgressKey,
takeRegisteredSubagentProgressKeys,
useSubagentProgress,
-} from './state';
+} from '../state';
const update = (overrides: Partial<SubagentUpdateEvent> = {}): SubagentUpdateEvent => ({
runId: 'root-run',
@@ -466,7 +469,7 @@ describe('reduceSubagentProgress', () => {
expect(bounded?.contentParts).toHaveLength(100);
expect(continued?.contentParts).toHaveLength(100);
- expect(continued?.contentParts.at(-1)).toEqual({
+ expect(continued?.contentParts.slice(-1)[0]).toEqual({
type: ContentTypes.TEXT,
text: 'Final answer.',
});
@@ -740,7 +743,7 @@ describe('replay prefix projection reconciliation', () => {
expect(
new TextEncoder().encode(JSON.stringify(progress?.contentParts)).byteLength,
).toBeLessThanOrEqual(65_536);
- expect(progress?.contentParts.at(-1)).toMatchObject({ tool_call: { id: 'tool-99' } });
+ expect(progress?.contentParts.slice(-1)[0]).toMatchObject({ tool_call: { id: 'tool-99' } });
});
});
@@ -1419,6 +1422,6 @@ describe('message-step phase replay provenance', () => {
expect(
new TextEncoder().encode(JSON.stringify(progress?.contentParts)).byteLength,
).toBeLessThanOrEqual(65_536);
- expect(progress?.contentParts.at(-1)).toMatchObject({ stepId: 'message-109' });
+ expect(progress?.contentParts.slice(-1)[0]).toMatchObject({ stepId: 'message-109' });
});
});
diff --git a/client/src/data-provider/Subagents/useSubagentActivityStream.test.tsx b/packages/chat/src/react/subagents/__tests__/stream.spec.tsx
similarity index 75%
rename from client/src/data-provider/Subagents/useSubagentActivityStream.test.tsx
rename to packages/chat/src/react/subagents/__tests__/stream.spec.tsx
index 1d758e0a8c..c1dabb1793 100644
--- a/client/src/data-provider/Subagents/useSubagentActivityStream.test.tsx
+++ b/packages/chat/src/react/subagents/__tests__/stream.spec.tsx
@@ -1,8 +1,12 @@
+/**
+ * @jest-environment jsdom
+ */
import React from 'react';
-import { useAtomValue, useSetAtom } from 'jotai';
import { act, renderHook } from '@testing-library/react';
import { ContentTypes, QueryKeys, StepEvents } from 'librechat-data-provider';
-import type { ActiveSubagentPanel } from '~/components/Chat/Subagents/state';
+import { createStore, useAtomValue, useSetAtom, Provider as JotaiProvider } from 'jotai';
+import type { ActiveSubagentPanel } from '../state';
+import type { StreamHost } from '../../stream/host';
import {
reduceSubagentProgress,
closeParentSubagentProgress,
@@ -10,9 +14,10 @@ import {
subagentProgressByToolCallId,
subagentProgressKey,
takeRegisteredSubagentProgressKeys,
-} from '~/components/Chat/Subagents/state';
-import useSubagentActivityStream from './useSubagentActivityStream';
-import { IsolatedAtomStore } from 'test/harness';
+} from '../state';
+import { createSSETransport } from '../../../core/transport';
+import { StreamHostProvider } from '../../stream/host';
+import { useSubagentActivityStream } from '../stream';
type Listener = (event: MessageEvent) => void;
type MockStream = {
@@ -21,27 +26,38 @@ type MockStream = {
listeners: Record<string, Listener>;
close: jest.Mock;
emit: (type: string, data: unknown) => void;
+ /** The connection failed with an HTTP status (sse.js reports it on `error`). */
+ refuse: (status: number) => void;
+ /** The response body ended; sse.js reports only the closed ready state. */
+ end: () => void;
};
const streams: MockStream[] = [];
jest.mock('sse.js', () => ({
- SSE: jest.fn().mockImplementation((url: string, options: MockStream['options']) => {
- const listeners: Record<string, Listener> = {};
- const stream: MockStream = {
- url,
- options,
- listeners,
- close: jest.fn(),
- emit: (type, data) => listeners[type]?.({ data: JSON.stringify(data) } as MessageEvent),
- };
- streams.push(stream);
- return {
- addEventListener: (type: string, listener: Listener) => {
- listeners[type] = listener;
- },
- close: stream.close,
- };
- }),
+ SSE: Object.assign(
+ jest.fn().mockImplementation((url: string, options: MockStream['options']) => {
+ const listeners: Record<string, Listener> = {};
+ const stream: MockStream = {
+ url,
+ options,
+ listeners,
+ close: jest.fn(),
+ emit: (type, data) => listeners[type]?.({ data: JSON.stringify(data) } as MessageEvent),
+ refuse: (status) =>
+ listeners.error?.({ data: '', responseCode: status } as unknown as MessageEvent),
+ end: () => listeners.readystatechange?.({ readyState: 2 } as unknown as MessageEvent),
+ };
+ streams.push(stream);
+ return {
+ addEventListener: (type: string, listener: Listener) => {
+ listeners[type] = listener;
+ },
+ close: stream.close,
+ stream: jest.fn(),
+ };
+ }),
+ { CLOSED: 2 },
+ ),
}));
const mockInvalidateQueries = jest.fn();
@@ -55,9 +71,14 @@ jest.mock('@tanstack/react-query', () => ({
useQueryClient: () => mockQueryClient,
}));
-jest.mock('~/hooks/AuthContext', () => ({
- useAuthContext: () => ({ token: 'token-1', isAuthenticated: true }),
-}));
+const host: StreamHost = {
+ useResumableServices: () => () => {
+ throw new Error('the activity feed attaches without a resumable binding');
+ },
+ useLegacyStream: () => undefined,
+ useTransport: () => transport,
+};
+const transport = createSSETransport({ token: 'token-1' });
const selection: ActiveSubagentPanel = {
host: 'conversation',
@@ -71,9 +92,15 @@ const selection: ActiveSubagentPanel = {
durable: { threadId: 'child/thread', taskId: 'task?1' },
};
-const wrapper = ({ children }: { children: React.ReactNode }) => (
- <IsolatedAtomStore>{children}</IsolatedAtomStore>
-);
+function Wrapper({ children }: { children: React.ReactNode }) {
+ const [store] = React.useState(createStore);
+ return (
+ <JotaiProvider store={store}>
+ <StreamHostProvider host={host}>{children}</StreamHostProvider>
+ </JotaiProvider>
+ );
+}
+const wrapper = Wrapper;
describe('useSubagentActivityStream', () => {
beforeEach(() => {
@@ -731,11 +758,96 @@ describe('useSubagentActivityStream', () => {
jest.useRealTimers();
});
+ it('keeps replayed history, the ready boundary and a live steer in wire order across a reconnect', () => {
+ jest.useFakeTimers();
+ const { result, unmount } = renderHook(
+ () => {
+ useSubagentActivityStream(selection);
+ return useAtomValue(
+ subagentProgressByToolCallId(
+ subagentProgressKey(
+ selection.parentMessageId,
+ selection.toolCallId,
+ selection.partIndex,
+ ),
+ ),
+ );
+ },
+ { wrapper },
+ );
+ const update = (sequence: number, phase: string, data: unknown) => ({
+ event: StepEvents.ON_SUBAGENT_UPDATE,
+ data: {
+ runId: 'parent',
+ subagentRunId: 'child',
+ subagentType: 'researcher',
+ subagentAgentId: 'agent-1',
+ parentToolCallId: selection.toolCallId,
+ activityEventId: `task:${sequence}`,
+ activitySequence: sequence,
+ phase,
+ timestamp: '2026-09-29T00:00:00.000Z',
+ data,
+ },
+ });
+ const text = (sequence: number) =>
+ update(sequence, 'message_delta', {
+ delta: { content: [{ type: ContentTypes.TEXT, text: `text-${sequence}` }] },
+ });
+ const steer = update(3, 'steer_applied', {
+ index: 1,
+ part: { type: ContentTypes.STEER, steer: 'parent guidance', steerId: 'steer-1' },
+ });
+ const summary = () =>
+ result.current?.contentParts.map((part) =>
+ part?.type === ContentTypes.STEER ? 'steer' : (part as { text?: string })?.text,
+ );
+
+ act(() => {
+ streams[0].emit('message', {
+ event: 'subagent_activity_replay',
+ data: [text(0), text(1)],
+ });
+ streams[0].emit('message', { ready: true, contentRecovery: true });
+ streams[0].emit('message', text(2));
+ streams[0].emit('message', steer);
+ streams[0].emit('message', text(4));
+ });
+ expect(result.current?.contentParts.map((part) => part?.type)).toEqual([
+ ContentTypes.TEXT,
+ ContentTypes.STEER,
+ ContentTypes.TEXT,
+ ]);
+ const live = summary();
+ expect(live).toEqual(['text-0text-1text-2', 'steer', 'text-4']);
+
+ act(() => {
+ streams[0].emit('error', {});
+ });
+ act(() => jest.advanceTimersByTime(500));
+ expect(streams).toHaveLength(2);
+ act(() => {
+ streams[1].emit('message', {
+ event: 'subagent_activity_replay',
+ data: [text(0), text(1), text(2), steer, text(4)],
+ });
+ streams[1].emit('message', { ready: true, contentRecovery: true });
+ streams[1].emit('message', text(5));
+ });
+ expect(summary()).toEqual(['text-0text-1text-2', 'steer', 'text-4text-5']);
+ expect(result.current?.lastActivitySequence).toBe(5);
+
+ unmount();
+ jest.useRealTimers();
+ });
+
it('reconnects with bounded backoff after a transient stream error', () => {
jest.useFakeTimers();
const { unmount } = renderHook(() => useSubagentActivityStream(selection), { wrapper });
- act(() => streams[0]?.emit('error', {}));
+ act(() => {
+ streams[0]?.emit('error', {});
+ });
expect(streams[0]?.close).toHaveBeenCalledTimes(1);
expect(streams).toHaveLength(1);
@@ -751,7 +863,9 @@ describe('useSubagentActivityStream', () => {
jest.useFakeTimers();
const { unmount } = renderHook(() => useSubagentActivityStream(selection), { wrapper });
- act(() => streams[0]?.emit('error', {}));
+ act(() => {
+ streams[0]?.emit('error', {});
+ });
act(() => jest.advanceTimersByTime(500));
expect(streams).toHaveLength(2);
@@ -769,6 +883,143 @@ describe('useSubagentActivityStream', () => {
jest.useRealTimers();
});
+ it.each([403, 410])(
+ 'stops for good when the activity route refuses the task with %s',
+ (status) => {
+ jest.useFakeTimers();
+ const { unmount } = renderHook(() => useSubagentActivityStream(selection), { wrapper });
+
+ act(() => {
+ streams[0].refuse(status);
+ });
+ expect(streams[0].close).toHaveBeenCalled();
+ act(() => jest.advanceTimersByTime(60_000));
+ expect(streams).toHaveLength(1);
+
+ unmount();
+ jest.useRealTimers();
+ },
+ );
+
+ it('keeps attaching through 404s while the child thread is still being reserved', () => {
+ jest.useFakeTimers();
+ const { unmount } = renderHook(() => useSubagentActivityStream(selection), { wrapper });
+
+ for (let attempt = 0; attempt < 12; attempt++) {
+ const before = streams.length;
+ act(() => {
+ streams[before - 1].refuse(404);
+ });
+ act(() => jest.advanceTimersByTime(5_000));
+ expect(streams).toHaveLength(before + 1);
+ }
+
+ unmount();
+ jest.useRealTimers();
+ });
+
+ it('stops on a 404 once the readiness window has passed', () => {
+ jest.useFakeTimers();
+ const { unmount } = renderHook(() => useSubagentActivityStream(selection), { wrapper });
+
+ act(() => jest.advanceTimersByTime(60_000));
+ act(() => {
+ streams[0].refuse(404);
+ });
+ act(() => jest.advanceTimersByTime(60_000));
+ expect(streams).toHaveLength(1);
+
+ unmount();
+ jest.useRealTimers();
+ });
+
+ it('still retries a rate-limited or timed-out attach', () => {
+ jest.useFakeTimers();
+ const { unmount } = renderHook(() => useSubagentActivityStream(selection), { wrapper });
+
+ act(() => {
+ streams[0].refuse(429);
+ });
+ act(() => jest.advanceTimersByTime(500));
+ expect(streams).toHaveLength(2);
+ act(() => {
+ streams[1].refuse(408);
+ });
+ act(() => jest.advanceTimersByTime(1_000));
+ expect(streams).toHaveLength(3);
+
+ unmount();
+ jest.useRealTimers();
+ });
+
+ it('bounds reconnects when the feed keeps ending as unavailable before any live update', () => {
+ jest.useFakeTimers();
+ const { unmount } = renderHook(() => useSubagentActivityStream(selection), { wrapper });
+ const unavailable = (index: number) => {
+ act(() => {
+ streams[index].emit('message', { error: 'Subagent activity stream unavailable' });
+ streams[index].end();
+ });
+ };
+
+ unavailable(0);
+ const delays: number[] = [];
+ for (let attempt = 0; attempt < 20; attempt++) {
+ const before = streams.length;
+ let waited = 0;
+ while (streams.length === before && waited < 60_000) {
+ act(() => jest.advanceTimersByTime(100));
+ waited += 100;
+ }
+ if (streams.length === before) break;
+ delays.push(waited);
+ unavailable(streams.length - 1);
+ }
+
+ expect(delays).toEqual([500, 1_000, 2_000, 4_000, 5_000, 5_000, 5_000, 5_000]);
+ expect(streams).toHaveLength(9);
+
+ unmount();
+ jest.useRealTimers();
+ });
+
+ it('resets the reconnect budget once a live update arrives', () => {
+ jest.useFakeTimers();
+ const { unmount } = renderHook(() => useSubagentActivityStream(selection), { wrapper });
+ const live = {
+ event: StepEvents.ON_SUBAGENT_UPDATE,
+ data: {
+ runId: 'parent',
+ subagentRunId: 'child',
+ subagentType: 'researcher',
+ subagentAgentId: 'agent-1',
+ parentToolCallId: selection.toolCallId,
+ activityEventId: 'task:0',
+ activitySequence: 0,
+ phase: 'message_delta',
+ timestamp: '2026-09-29T00:00:00.000Z',
+ data: { delta: { content: [{ type: ContentTypes.TEXT, text: 'alive' }] } },
+ },
+ };
+
+ for (let index = 0; index < 8; index++) {
+ act(() => {
+ streams[index].end();
+ });
+ act(() => jest.advanceTimersByTime(5_000));
+ }
+ expect(streams).toHaveLength(9);
+ act(() => {
+ streams[8].emit('message', live);
+ streams[8].end();
+ });
+ act(() => jest.advanceTimersByTime(500));
+ expect(streams).toHaveLength(10);
+
+ unmount();
+ jest.useRealTimers();
+ });
+
it('keeps one forward-only stream across metadata-only selection updates', () => {
const { rerender } = renderHook(({ value }) => useSubagentActivityStream(value), {
initialProps: { value: selection },
@@ -802,7 +1053,7 @@ describe('useSubagentActivityStream', () => {
it('treats content watermarks as invalidation only after the subscribed ready boundary', () => {
const { result } = renderHook(() => useSubagentActivityStream(selection), { wrapper });
- const stream = streams.at(-1)!;
+ const stream = streams[streams.length - 1];
expect(result.current.isReady).toBe(false);
act(() => stream.emit('message', { ready: true, contentRecovery: true }));
expect(result.current.isReady).toBe(true);
@@ -831,7 +1082,7 @@ it('treats content watermarks as invalidation only after the subscribed ready bo
it('skips already committed content notifications but still refreshes a newer revision or sequence', () => {
mockGetQueryData.mockReturnValue({ revision: 3, throughSequence: 118 });
const { unmount } = renderHook(() => useSubagentActivityStream(selection), { wrapper });
- const stream = streams.at(-1)!;
+ const stream = streams[streams.length - 1];
mockInvalidateQueries.mockClear();
const notify = (revision: number, throughSequence: number) =>
act(() =>
diff --git a/packages/chat/src/react/subagents/index.ts b/packages/chat/src/react/subagents/index.ts
new file mode 100644
index 0000000000..8011b2db35
--- /dev/null
+++ b/packages/chat/src/react/subagents/index.ts
@@ -0,0 +1,2 @@
+export * from './state';
+export * from './stream';
diff --git a/client/src/components/Chat/Subagents/state.ts b/packages/chat/src/react/subagents/state.ts
similarity index 95%
rename from client/src/components/Chat/Subagents/state.ts
rename to packages/chat/src/react/subagents/state.ts
index 4477e9592e..1b338c011d 100644
--- a/client/src/components/Chat/Subagents/state.ts
+++ b/packages/chat/src/react/subagents/state.ts
@@ -14,11 +14,8 @@ import type {
} from 'librechat-data-provider';
import type { Getter, PrimitiveAtom, WritableAtom } from 'jotai';
import type { SetStateAction } from 'react';
-import type {
- SubagentAggregatorState,
- SubagentContentPart,
- SubagentTickerState,
-} from '~/utils/subagentContent';
+import type { SubagentAggregatorState, SubagentContentPart, SubagentTickerState } from '../../core';
+import type { Family } from '../steer/family';
import {
reconcileSubagentMessagePhases,
reconcileSubagentToolTimings,
@@ -26,7 +23,7 @@ import {
foldSubagentEventIntoTicker,
initSubagentAggregatorState,
initSubagentTickerState,
-} from '~/utils/subagentContent';
+} from '../../core';
/**
* Progress bucket captured per subagent tool call. Populated as
@@ -108,7 +105,7 @@ const MAX_SINGLE_ACTIVITY_ENCODED_BYTES = MAX_LIVE_ACTIVITY_BYTES - 2;
const MAX_SINGLE_ACTIVITY_TEXT_BYTES = 60 * 1024;
/** Substituted for reasoning text by pre-retention servers; current servers
* transport the bounded reasoning text itself. */
-export const REDACTED_REASONING_MARKER = '…';
+export const REDACTED_REASONING_MARKER: string = '…';
const encodedBytes = (value: unknown): number =>
new TextEncoder().encode(JSON.stringify(value)).byteLength;
@@ -348,8 +345,9 @@ export type ActiveSubagentPanel = {
};
};
-export const activeSubagentPanel = atom<ActiveSubagentPanel | null>(null);
-export const subagentPanelFocusRequest = atom(0);
+export const activeSubagentPanel: PrimitiveAtom<ActiveSubagentPanel | null> =
+ atom<ActiveSubagentPanel | null>(null);
+export const subagentPanelFocusRequest: PrimitiveAtom<number> = atom(0);
export type SubagentControlUiReceipt = Omit<SubagentControlReceipt, 'status'> & {
status: SubagentControlReceipt['status'] | 'submitted';
@@ -469,34 +467,38 @@ const persistControlState = (identity: string, next: SubagentControlUiState | nu
* durable receipts clear both copies after authoritative reconciliation. */
const UNWRITTEN = Symbol('unwritten');
-export const subagentControlStateByTask = atomFamily<
- string,
- WritableAtom<SubagentControlUiState | null, [SetStateAction<SubagentControlUiState | null>], void>
->((identity: string) => {
- /** Restored per store rather than per family member: a member is created
- * once for the tab, and a reload has to see what the last one persisted. */
- const restored = atom(() => restoreControlState(identity));
- const held: PrimitiveAtom<SubagentControlUiState | null | typeof UNWRITTEN> = atom(
- UNWRITTEN as SubagentControlUiState | null | typeof UNWRITTEN,
- );
- const read = (get: Getter): SubagentControlUiState | null => {
- const current = get(held);
- return current === UNWRITTEN ? get(restored) : current;
- };
- return atom(read, (get, set, update: SetStateAction<SubagentControlUiState | null>) => {
- const next =
- typeof update === 'function'
- ? (update as (previous: SubagentControlUiState | null) => SubagentControlUiState | null)(
- read(get),
- )
- : update;
- set(held, next);
- persistControlState(identity, next);
+type ControlStateAtom = WritableAtom<
+ SubagentControlUiState | null,
+ [SetStateAction<SubagentControlUiState | null>],
+ void
+>;
+
+export const subagentControlStateByTask: Family<SubagentControlUiState | null, ControlStateAtom> =
+ atomFamily<string, ControlStateAtom>((identity: string) => {
+ /** Restored per store rather than per family member: a member is created
+ * once for the tab, and a reload has to see what the last one persisted. */
+ const restored = atom(() => restoreControlState(identity));
+ const held: PrimitiveAtom<SubagentControlUiState | null | typeof UNWRITTEN> = atom(
+ UNWRITTEN as SubagentControlUiState | null | typeof UNWRITTEN,
+ );
+ const read = (get: Getter): SubagentControlUiState | null => {
+ const current = get(held);
+ return current === UNWRITTEN ? get(restored) : current;
+ };
+ return atom(read, (get, set, update: SetStateAction<SubagentControlUiState | null>) => {
+ const next =
+ typeof update === 'function'
+ ? (update as (previous: SubagentControlUiState | null) => SubagentControlUiState | null)(
+ read(get),
+ )
+ : update;
+ set(held, next);
+ persistControlState(identity, next);
+ });
});
-});
/** Stable identity for one subagent invocation in the parent conversation. */
-export { subagentProgressKey } from '@librechat/chat';
+export { subagentProgressKey } from '../../core';
type NestedToolCallFields = {
id?: string;
@@ -567,29 +569,38 @@ export function collectNestedCalls(
* anything reads the member, since the bounded activity can evict a call that saved a file
* before a reader mounts.
*/
-export const subagentProgressByToolCallId = atomFamily((key: string) => {
- const progress = atom<SubagentProgress | null>(null);
- return atom(
- (get) => get(progress),
- (get, set, next: SetStateAction<SubagentProgress | null>) => {
- const value = typeof next === 'function' ? next(get(progress)) : next;
- if (value != null) {
- const segments = [value, ...(value.replaySegments ?? []).map(({ progress }) => progress)];
- rememberSubagentChildCalls(
- key,
- segments.flatMap((segment) => [
- ...(segment.aggregatorState?.evictedToolCalls ?? []),
- ...collectNestedCalls(segment.contentParts, [], segment.subagentAgentId),
- ]),
- );
- }
- set(progress, value);
- },
- );
-});
+type ProgressAtom = WritableAtom<
+ SubagentProgress | null,
+ [SetStateAction<SubagentProgress | null>],
+ void
+>;
+
+export const subagentProgressByToolCallId: Family<SubagentProgress | null, ProgressAtom> =
+ atomFamily((key: string): ProgressAtom => {
+ const progress = atom<SubagentProgress | null>(null);
+ return atom(
+ (get) => get(progress),
+ (get, set, next: SetStateAction<SubagentProgress | null>) => {
+ const value = typeof next === 'function' ? next(get(progress)) : next;
+ if (value != null) {
+ const segments = [value, ...(value.replaySegments ?? []).map(({ progress }) => progress)];
+ rememberSubagentChildCalls(
+ key,
+ segments.flatMap((segment) => [
+ ...(segment.aggregatorState?.evictedToolCalls ?? []),
+ ...collectNestedCalls(segment.contentParts, [], segment.subagentAgentId),
+ ]),
+ );
+ }
+ set(progress, value);
+ },
+ );
+ });
/** Parent delivery remains authoritative until its ordered SSE close boundary. */
-export const subagentParentStreamOpenByToolCallId = atomFamily((_key: string) => atom(false));
+export const subagentParentStreamOpenByToolCallId: Family<boolean> = atomFamily((_key: string) =>
+ atom(false),
+);
/**
* Invocation atoms populated by either the parent generation stream or the selected detached
@@ -905,7 +916,7 @@ export function reduceSubagentProgress(
previous: SubagentProgress | null,
events: SubagentUpdateEvent[],
source: 'parent' | 'detached' = 'parent',
- waitForEarlierSequences = source === 'parent',
+ waitForEarlierSequences: boolean = source === 'parent',
): SubagentProgress | null {
if (events.length === 0) return previous;
const repair =
diff --git a/client/src/data-provider/Subagents/useSubagentActivityStream.ts b/packages/chat/src/react/subagents/stream.ts
similarity index 75%
rename from client/src/data-provider/Subagents/useSubagentActivityStream.ts
rename to packages/chat/src/react/subagents/stream.ts
index 5f1acf999b..85075bf1dc 100644
--- a/client/src/data-provider/Subagents/useSubagentActivityStream.ts
+++ b/packages/chat/src/react/subagents/stream.ts
@@ -1,11 +1,14 @@
import { useEffect, useMemo, useRef } from 'react';
-import { SSE } from 'sse.js';
import { atomFamily, selectAtom } from 'jotai/utils';
import { useQueryClient } from '@tanstack/react-query';
import { atom, useAtom, useAtomValue, useSetAtom } from 'jotai';
import { QueryKeys, StepEvents, apiBaseUrl } from 'librechat-data-provider';
-import type { SubagentTaskContentSnapshot, SubagentUpdateEvent } from 'librechat-data-provider';
-import type { ActiveSubagentPanel } from '~/components/Chat/Subagents/state';
+import type {
+ ChatEvent,
+ SubagentUpdateEvent,
+ SubagentTaskContentSnapshot,
+} from 'librechat-data-provider';
+import type { ActiveSubagentPanel } from './state';
import {
closeParentSubagentProgress,
reduceSubagentProgress,
@@ -14,8 +17,8 @@ import {
subagentParentStreamOpenByToolCallId,
subagentProgressByToolCallId,
subagentProgressKey,
-} from '~/components/Chat/Subagents/state';
-import { useAuthContext } from '~/hooks/AuthContext';
+} from './state';
+import { useStreamHost } from '../stream/host';
type ActivityEnvelope = {
event?: unknown;
@@ -23,7 +26,6 @@ type ActivityEnvelope = {
final?: unknown;
subagentActivity?: unknown;
droppedCount?: unknown;
- ready?: unknown;
};
const contentReady = atomFamily((_key: string) => atom(false));
@@ -31,6 +33,18 @@ const readyReaders = new Map<string, number>();
const INITIAL_RECONNECT_MS = 500;
const MAX_RECONNECT_MS = 5_000;
+/** Reconnects in a row that deliver no live update before the feed gives up; the durable
+ * thread query keeps polling, so the panel still converges on the stored transcript.
+ * Internal retry hygiene with that fallback, not an operator lever, so not in configSchema. */
+const MAX_IDLE_RECONNECTS = 8;
+/** A child opened before its thread is reserved answers 404 until preparation finishes; the
+ * durable thread query treats that as pending for the same window, so the feed does too. */
+const CHILD_READY_WINDOW_MS = 60_000;
+
+/** A refusal no retry can clear: the task is gone or not the viewer's. 401 arrives here only
+ * after the transport's own refresh failed; 408 and 429 are worth retrying. */
+const isRefusal = (status?: number): boolean =>
+ status != null && status >= 400 && status < 500 && status !== 408 && status !== 429;
const isSubagentUpdate = (value: unknown): value is SubagentUpdateEvent => {
if (value == null || typeof value !== 'object') return false;
@@ -46,12 +60,16 @@ const isSubagentUpdate = (value: unknown): value is SubagentUpdateEvent => {
);
};
-/** Replay-then-live enhancement for the selected durable child; the durable query remains canonical. */
-export default function useSubagentActivityStream(
+/**
+ * Replay-then-live enhancement for the selected durable child; the durable query remains
+ * canonical. The feed attaches through the host's transport, which owns the connection,
+ * framing and token refresh.
+ */
+export function useSubagentActivityStream(
selection: ActiveSubagentPanel,
enabled = true,
): { isReady: boolean } {
- const { token, isAuthenticated } = useAuthContext();
+ const transport = useStreamHost().useTransport();
const queryClient = useQueryClient();
const key = subagentProgressKey(
selection.parentMessageId,
@@ -120,8 +138,7 @@ export default function useSubagentActivityStream(
threadId == null ||
taskId == null ||
!enabled ||
- !isAuthenticated ||
- token == null
+ transport == null
) {
return;
}
@@ -138,39 +155,49 @@ export default function useSubagentActivityStream(
};
if ((readyReaders.get(readyKey) ?? 0) <= 1) setReady(false);
const endpoint = `${apiBaseUrl()}/api/convos/${encodeURIComponent(selection.parentConversationId)}/subagents/${encodeURIComponent(threadId)}/tasks/${encodeURIComponent(taskId)}/activity`;
- let stream: SSE | undefined;
+ let stream: AbortController | undefined;
let retryTimer: ReturnType<typeof setTimeout> | undefined;
let retryAttempt = 0;
+ let idleReconnects = 0;
+ const readinessDeadline = Date.now() + CHILD_READY_WINDOW_MS;
let disposed = false;
let terminal = false;
const closeCurrent = () => {
const current = stream;
stream = undefined;
- current?.close();
+ current?.abort();
};
const connect = () => {
retryTimer = undefined;
if (disposed || terminal) return;
- const next = new SSE(endpoint, {
- method: 'GET',
- headers: { Authorization: `Bearer ${token}` },
- });
+ const next = new AbortController();
stream = next;
- next.addEventListener('message', (message: MessageEvent) => {
+ const onEvent = (event: ChatEvent) => {
if (stream !== next || disposed) return;
- let envelope: ActivityEnvelope;
- try {
- envelope = JSON.parse(message.data) as ActivityEnvelope;
- } catch {
+ if (event.type === 'error') {
+ setReady(true);
+ refreshContent();
+ if (event.status === 404 && Date.now() < readinessDeadline) {
+ reconnect(true);
+ return;
+ }
+ if (isRefusal(event.status)) {
+ terminal = true;
+ closeCurrent();
+ return;
+ }
+ reconnect();
return;
}
- if (envelope.ready === true) {
+ if (event.type === 'ready') {
setReady(true);
refreshContent();
return;
}
+ if (event.type !== 'step' && event.type !== 'final') return;
+ const envelope: ActivityEnvelope = event.data;
if (envelope.event === 'subagent_content_available') {
const watermark = envelope.data as
| {
@@ -224,25 +251,26 @@ export default function useSubagentActivityStream(
retryAttempt = 0;
return;
}
- const event = envelope.data;
- if (envelope.event !== StepEvents.ON_SUBAGENT_UPDATE || !isSubagentUpdate(event)) {
+ const update = envelope.data;
+ if (envelope.event !== StepEvents.ON_SUBAGENT_UPDATE || !isSubagentUpdate(update)) {
return;
}
if (
selection.event == null &&
- event.parentToolCallId != null &&
- event.parentToolCallId !== selection.toolCallId
+ update.parentToolCallId != null &&
+ update.parentToolCallId !== selection.toolCallId
) {
return;
}
retryAttempt = 0;
+ idleReconnects = 0;
registerSubagentProgressKey(key);
setProgress((previous) =>
reduceSubagentProgress(
previous,
[
{
- ...event,
+ ...update,
activityDroppedCount:
Number.isSafeInteger(envelope.droppedCount) &&
(envelope.droppedCount as number) > 0
@@ -254,18 +282,18 @@ export default function useSubagentActivityStream(
parentStreamOpenRef.current || previous?.activityReplayFrom != null,
),
);
- });
- next.addEventListener('error', () => {
- if (stream !== next) return;
- setReady(true);
- refreshContent();
- reconnect();
- });
+ };
+ transport.reconnectToStream({ url: endpoint }, { signal: next.signal, onEvent });
};
- const reconnect = () => {
+ const reconnect = (pending = false) => {
if (disposed || terminal || retryTimer != null) return;
closeCurrent();
+ if (!pending && idleReconnects >= MAX_IDLE_RECONNECTS) {
+ terminal = true;
+ return;
+ }
+ if (!pending) idleReconnects += 1;
const delay = Math.min(INITIAL_RECONNECT_MS * 2 ** retryAttempt, MAX_RECONNECT_MS);
retryAttempt += 1;
retryTimer = setTimeout(connect, delay);
@@ -280,7 +308,6 @@ export default function useSubagentActivityStream(
};
}, [
enabled,
- isAuthenticated,
key,
queryClient,
readyKey,
@@ -294,7 +321,7 @@ export default function useSubagentActivityStream(
setReady,
taskId,
threadId,
- token,
+ transport,
]);
return { isReady };
}
diff --git a/packages/data-provider/src/types/transport.ts b/packages/data-provider/src/types/transport.ts
index 752d293cb9..b2b2837935 100644
--- a/packages/data-provider/src/types/transport.ts
+++ b/packages/data-provider/src/types/transport.ts
@@ -235,7 +235,12 @@ export type ChatEvent =
*/
| { type: 'error'; data?: ChatErrorData | null; status?: number }
/** AI SDK: `abort`. The caller closed a stream that was still open. */
- | { type: 'abort' };
+ | { type: 'abort' }
+ /**
+ * No AI SDK equivalent: a feed that replays before going live (a subagent's activity) says
+ * the replay is delivered and what follows is live.
+ */
+ | { type: 'ready' };
export type ChatEventType = ChatEvent['type'];