🚚 refactor: Move the Subagent Thread Panel Into @librechat/chat (#17781)

* refactor: Read the Thread Panel's Jotai State Through the Chat Surface

* refactor: Move the Subagent Thread Panel Into @librechat/chat

* test: Spec the Subagent Thread Panel Against Fake Hosts

* test: Cover the App Subagents Host Adapters the Panel Move Relies On

* fix: Style the Moved Subagent Panel With Shared Variants

* test: Pin the Shared Variants the Panel Draws Its Picker and Inline Actions With

* perf: Keep the Subagent Thread Panel Out of the Boot Bundle
This commit is contained in:
Marco Beretta 2026-11-08 00:29:26 +01:00 • committed by GitHub
parent 4a3b3a2e1a
commit ce35dc25e1
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
17 changed files with 572 additions and 297 deletions

View file

@ -1,22 +1,55 @@
import { renderHook } from '@testing-library/react';
import { ForkOptions } from 'librechat-data-provider';
import type { TConversation } from 'librechat-data-provider';
import { appSubagentsHost } from '../SubagentsHostContext';
const mockThreadRefetch = jest.fn();
const mockPartRefetch = jest.fn();
const mockUseSubagentThreadQuery = jest.fn();
const mockForkMutate = jest.fn();
const mockNavigate = jest.fn();
const mockNavigateToConvo = jest.fn();
const mockMediaQuery = jest.fn();
let mockRemScale = 1;
jest.mock('~/data-provider', () => ({
...jest.requireActual('~/data-provider'),
useSubagentThreadQuery: () => ({
data: undefined,
isLoading: false,
isError: false,
isPreviousData: false,
isReadinessPending: false,
refetch: mockThreadRefetch,
}),
useSubagentThreadQuery: (...args: unknown[]) => {
mockUseSubagentThreadQuery(...args);
return {
data: undefined,
isLoading: false,
isError: false,
isPreviousData: false,
isReadinessPending: false,
refetch: mockThreadRefetch,
};
},
useToolCallPartQuery: () => ({ data: undefined, isError: false, refetch: mockPartRefetch }),
useForkConvoMutation: () => ({ mutate: mockForkMutate, isLoading: false }),
}));
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useNavigate: () => mockNavigate,
}));
jest.mock('~/hooks/Conversations/useNavigateToConvo', () => ({
__esModule: true,
default: () => ({ navigateToConvo: mockNavigateToConvo }),
}));
jest.mock('@librechat/client', () => ({
...jest.requireActual('@librechat/client'),
useRemScale: () => mockRemScale,
useMediaQuery: (query: string) => mockMediaQuery(query),
}));
beforeEach(() => {
jest.clearAllMocks();
mockRemScale = 1;
});
describe('appSubagentsHost reads', () => {
/** The thread panel revalidates in an effect that depends on `refetch`; a callback that
* changed every render would refetch on every fetch-state render instead of once. */
@ -42,4 +75,79 @@ describe('appSubagentsHost reads', () => {
expect(result.current.refetch).toBe(first);
expect(first).toBe(mockPartRefetch);
});
/** A plain read keeps the query's own readiness schedule: it passes no options at all. */
it('reads a thread without options when the panel asks for none', () => {
renderHook(() => appSubagentsHost.useThread('parent', 'thread', 'task', {}));
expect(mockUseSubagentThreadQuery).toHaveBeenCalledWith('parent', 'thread', 'task');
expect(mockUseSubagentThreadQuery.mock.calls[0]).toHaveLength(3);
});
it('forwards the selected task view options', () => {
renderHook(() =>
appSubagentsHost.useThread('parent', 'thread', 'task', {
keepPreviousData: true,
refetchInterval: 2000,
}),
);
expect(mockUseSubagentThreadQuery).toHaveBeenCalledWith('parent', 'thread', 'task', {
keepPreviousData: true,
refetchInterval: 2000,
});
});
});
describe('appSubagentsHost writes and navigation', () => {
/** A child thread is view-only on the server, so continuing it forks the direct path to
* the selected task's reply into a conversation of the reader's own. */
it('continues a thread as a direct-path fork of the task reply', () => {
const { result } = renderHook(() => appSubagentsHost.useContinueChat({}));
result.current.mutate({ conversationId: 'child-thread', messageId: 'task:assistant' });
expect(mockForkMutate).toHaveBeenCalledTimes(1);
expect(mockForkMutate).toHaveBeenCalledWith({
conversationId: 'child-thread',
messageId: 'task:assistant',
option: ForkOptions.DIRECT_PATH,
});
});
it('opens the parent conversation by its encoded chat path', () => {
const { result } = renderHook(() => appSubagentsHost.useNavigation());
result.current.openConversationId('parent conversation/1');
expect(mockNavigate).toHaveBeenCalledWith('/c/parent%20conversation%2F1');
});
it('opens a forked conversation the way the chat list does', () => {
const conversation: TConversation = {
conversationId: 'continued-chat',
title: 'Continued',
endpoint: null,
createdAt: '2026-11-03T00:00:00.000Z',
updatedAt: '2026-11-03T00:00:00.000Z',
};
const { result } = renderHook(() => appSubagentsHost.useNavigation());
result.current.openConversation(conversation);
expect(mockNavigateToConvo).toHaveBeenCalledWith(conversation);
});
});
describe('appSubagentsHost layout', () => {
/** The panel turns into a modal sheet at the artifacts breakpoint, measured in the units
* the layout uses: 868 px at the default rem scale, wider when the reader scales text up. */
it.each([
[1, '(max-width: 868px)'],
[1.25, '(max-width: 1085px)'],
])('measures the sheet breakpoint at rem scale %s', (scale, query) => {
mockRemScale = scale;
mockMediaQuery.mockReturnValue(true);
const { result } = renderHook(() => appSubagentsHost.useSheetLayout());
expect(mockMediaQuery).toHaveBeenCalledWith(query);
expect(result.current).toBe(true);
});
it('is a side region when the viewport is wider than the sheet breakpoint', () => {
mockMediaQuery.mockReturnValue(false);
const { result } = renderHook(() => appSubagentsHost.useSheetLayout());
expect(result.current).toBe(false);
});
});

View file

@ -51,21 +51,26 @@ jest.mock('~/components/Artifacts/Artifacts', () => {
};
});
jest.mock('~/components/Chat/Subagents/SubagentThreadPanel', () => {
jest.mock('@librechat/chat/components', () => {
const { useParentSubagents } =
jest.requireActual<typeof import('@librechat/chat/react')>('@librechat/chat/react');
return {
__esModule: true,
default: function MockSubagentThreadPanel() {
const parent = useParentSubagents();
return (
<aside>
{mockChildPanelLabel}
<span data-testid="panel-parent">{parent.conversationId}</span>
<input aria-label="Panel draft" />
</aside>
);
},
...jest.requireActual<typeof import('@librechat/chat/components')>(
'@librechat/chat/components',
),
loadSubagentThreadPanel: () =>
Promise.resolve({
default: function MockSubagentThreadPanel() {
const parent = useParentSubagents();
return (
<aside>
{mockChildPanelLabel}
<span data-testid="panel-parent">{parent.conversationId}</span>
<input aria-label="Panel draft" />
</aside>
);
},
}),
};
});

View file

@ -21,8 +21,8 @@ import { migrateStoredFileDeletions } from '~/utils';
import store from '~/store';
const Artifacts = lazyWithRecovery(() => import('~/components/Artifacts/Artifacts'));
const SubagentThreadPanel = lazyWithRecovery(
() => import('~/components/Chat/Subagents/SubagentThreadPanel'),
const SubagentThreadPanel = lazyWithRecovery(() =>
import('@librechat/chat/components').then((module) => module.loadSubagentThreadPanel()),
);
export default function Presentation({

View file

@ -29,7 +29,7 @@ export { default as useTimeout } from './useTimeout';
export { default as useNewConvo } from './useNewConvo';
export { default as useLocalize } from './useLocalize';
export { default as useGreeting } from './useGreeting';
export { default as useFocusTrap } from './useFocusTrap';
export { useFocusTrap } from '@librechat/client';
export { default as useFavorites } from './useFavorites';
export { default as useToolFavorites } from './useToolFavorites';
export { default as useAdaptiveIcon } from './useAdaptiveIcon';

View file

@ -365,11 +365,6 @@
"count": 1
}
},
"client/src/components/Chat/Subagents/SubagentThreadPanel.tsx": {
"shadcn/no-restyle": {
"count": 7
}
},
"client/src/components/Chat/Trace/Button.tsx": {
"shadcn/no-restyle": {
"count": 3

View file

@ -250,3 +250,4 @@ export {
} from './components/subagents/transcript';
export { default as SubagentConversation } from './components/subagents/conversation';
export { default as SharedSubagentActivityDialog } from './components/subagents/shared';
export { loadSubagentThreadPanel } from './components/subagents/load';

View file

@ -1,35 +1,46 @@
import React from 'react';
import { useAtomValue, useSetAtom } from 'jotai';
/**
* @jest-environment jsdom
*/
import React, { useEffect, useState } from 'react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { initSubagentAggregatorState, initSubagentTickerState } from '@librechat/chat';
import { ContentTypes, EModelEndpoint, QueryKeys } from 'librechat-data-provider';
import { Provider as JotaiProvider, createStore, useAtomValue, useSetAtom } from 'jotai';
import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { ContentTypes, EModelEndpoint, ForkOptions, QueryKeys } from 'librechat-data-provider';
import {
activeSubagentPanel,
subagentProgressByToolCallId,
subagentProgressKey,
useOpenSubagentPanel,
} from '@librechat/chat/react';
import type {
Agent,
TMessage,
SubagentControlResponse,
ToolCallPartResponse,
SubagentThreadView,
TMessageContentParts,
ParentSubagentSummary,
} from 'librechat-data-provider';
import type { ActiveSubagentPanel } from '@librechat/chat/react';
import type { JotaiStore } from 'test/harness';
import { ChatSurfaceHarness, testChatSurface } from 'test/harness';
import SubagentThreadPanel from './SubagentThreadPanel';
import { getDraft } from '~/utils';
import '~/Providers/MessagePartsHostContext';
import '~/Providers/MessagesHostContext';
import '~/Providers/SubagentsHostContext';
import type { ChatSurface, SubagentPanelState } from '../../../react/subagents/surface';
import type { ActiveSubagentPanel } from '../../../react/subagents/state';
import type { SubagentsHost } from '../../../react/subagents/host';
import type { MessagePartsHost } from '../../../react/host';
import {
activeSubagentPanel,
subagentProgressKey,
subagentProgressByToolCallId,
} from '../../../react/subagents/state';
import { useOpenSubagentPanel, SubagentPanelStateContext } from '../../../react/subagents/surface';
import { initSubagentAggregatorState, initSubagentTickerState } from '../../../core';
import { createSubagentsHost } from '../../../__fixtures__/subagentsHost';
import { ChatSurfaceProvider } from '../../../react/subagents/provider';
import { createMessagesHost } from '../../../__fixtures__/messagesHost';
import { SubagentsHostProvider } from '../../../react/subagents/host';
import { subagentPanelState } from '../../../react/subagents/runtime';
import { MessagesHostProvider } from '../../../react/messages/host';
import { MessagePartsHostProvider } from '../../../react/host';
import SubagentThreadPanel from '../panel';
type JotaiStore = ReturnType<typeof createStore>;
const mockUseSubagentThreadQuery = jest.fn();
const mockUseToolCallPartQuery = jest.fn(
(
..._args: unknown[]
): { data?: unknown; isError: boolean; refetch?: () => Promise<unknown> } => ({
): { data?: ToolCallPartResponse; isError: boolean; refetch?: () => Promise<unknown> } => ({
data: undefined,
isError: false,
}),
@ -60,6 +71,135 @@ const mockHandOffComposerText = jest.fn();
* conversation's loaded thread, the cache main chat itself renders from. */
let queryClient = new QueryClient();
/** The width at which the app lays the panel out as a sheet, before the reader's text scale. */
const SHEET_MAX_WIDTH = 868;
const agentFixture = (id: string, name: string, filepath?: string): Agent => ({
id,
name,
description: null,
created_at: 0,
avatar: filepath == null ? null : { filepath, source: 'local' },
provider: 'openAI',
model: null,
model_parameters: {
temperature: null,
maxContextTokens: null,
max_context_tokens: null,
max_output_tokens: null,
top_p: null,
frequency_penalty: null,
presence_penalty: null,
},
});
/** The agents map the app's subagents host reads. */
const agentsMap: Record<string, Agent | undefined> = {
'agent-1': agentFixture('agent-1', 'Analyst One', '/analyst.png'),
'agent-2': agentFixture('agent-2', 'Analyst Two'),
};
/** The agent's avatar face, or an empty one: what main chat's author glyph and the actor picker
* both reduce to here. */
function AuthorFace({ src }: { src?: string }) {
return src != null ? (
<img src={src} alt="" data-testid="author-face" />
) : (
<span data-testid="author-face" />
);
}
const partsHost: MessagePartsHost = {
useMessage: () => ({ messageId: 'parent-message' }),
renderMarkdown: ({ content }) => <div>{content}</div>,
useSmoothStreaming: () => false,
useAgent: (agentId) => agentsMap[agentId],
renderAgentIcon: () => null,
renderAgentAvatar: (agent) => <AuthorFace src={agent?.avatar?.filepath} />,
renderContentParts: () => null,
renderImage: () => null,
renderFilePreview: () => null,
useFontSize: () => 'text-base',
useShowThinking: () => false,
useAutoExpandTools: () => false,
useLaTeXParsing: () => false,
useChatDirection: () => 'ltr',
useUserTextPreferences: () => ({
usernameDisplay: false,
enableUserMsgMarkdown: false,
collapseLongUserMessages: false,
}),
useUser: () => undefined,
useFileMap: () => undefined,
useToast: () => jest.fn(),
useSandboxStarting: () => false,
useToolArtifactClaim: () => [null, jest.fn()],
useSteerEscalating: () => false,
usePaneConversationId: () => null,
useLiveAppliedSteer: () => [false, jest.fn()],
useShare: () => ({}),
};
/** Main chat's author glyph, reduced to the face it draws: the agent's avatar
* when it has one. */
const messagesHost = createMessagesHost({
renderMessageIcon: ({ agent, iconData }) => (
<AuthorFace src={iconData?.iconURL ?? agent?.avatar?.filepath} />
),
});
/** The app's approval scope, reduced to the one thing the panel relies on: it mounts per key. */
function ApprovalScopeProbe({ children }: { children: React.ReactNode }) {
useEffect(() => {
mockApprovalProviderMounted();
return () => mockApprovalProviderUnmounted();
}, []);
return children;
}
const subagentsHost: SubagentsHost = createSubagentsHost({
useAgentsMap: () => agentsMap,
useThread: (...args) => mockUseSubagentThreadQuery(...args),
loadThread: (...args) => mockGetSubagentThread(...args),
useToolCallPart: (...args) => {
const query = mockUseToolCallPartQuery(...args);
return {
data: query.data,
isError: query.isError,
refetch: () => void query.refetch?.(),
};
},
useContinueChat: (options) => ({
mutate: (payload) => mockForkMutate(payload, options),
isLoading: false,
}),
useControl: (options) => ({
mutate: (variables) =>
mockControlMutate(variables, {
onSuccess: (result: SubagentControlResponse) => options.onSuccess?.(result, variables),
onError: (error: unknown) => options.onError?.(error, variables),
}),
isLoading: false,
}),
useNavigation: () => ({
openConversation: (conversation) => mockNavigateToConvo(conversation),
openConversationId: (conversationId) => mockNavigate(conversationId),
}),
/** The app scales the sheet breakpoint by the reader's text size before it asks. */
useSheetLayout: () =>
mockViewportWidth == null ? mockIsMobile : mockViewportWidth <= SHEET_MAX_WIDTH * mockRemScale,
renderApprovalScope: ({ scopeKey, children }) => (
<ApprovalScopeProbe key={scopeKey}>{children}</ApprovalScopeProbe>
),
});
/** The panel's own state: the real atoms, except the activity stream, which would open a
* transport. */
const panelState: SubagentPanelState = {
...subagentPanelState,
useActivityStream: (...args) => mockUseSubagentActivityStream(...args),
};
function Root({
seed,
children,
@ -67,73 +207,44 @@ function Root({
seed?: (store: JotaiStore) => void;
children: React.ReactNode;
}) {
const [store] = useState(() => {
const created = createStore();
seed?.(created);
return created;
});
const surface: ChatSurface = {
enterToSend: mockEnterToSend,
maximizeChatSpace: false,
showScrollButton: true,
composerBindings: {
shortcutsEnabled: true,
submitOverride: undefined,
yieldedChords: new Set<string>(),
},
claimForeground: mockClaimForeground,
handOffComposerText: mockHandOffComposerText,
};
return (
<QueryClientProvider client={queryClient}>
<ChatSurfaceHarness
seed={seed}
surface={testChatSurface({
enterToSend: mockEnterToSend,
claimForeground: mockClaimForeground,
handOffComposerText: mockHandOffComposerText,
})}
>
{children}
</ChatSurfaceHarness>
<JotaiProvider store={store}>
<MessagePartsHostProvider host={partsHost}>
<MessagesHostProvider host={messagesHost}>
<SubagentsHostProvider host={subagentsHost}>
<ChatSurfaceProvider value={surface}>
<SubagentPanelStateContext.Provider value={panelState}>
{children}
</SubagentPanelStateContext.Provider>
</ChatSurfaceProvider>
</SubagentsHostProvider>
</MessagesHostProvider>
</MessagePartsHostProvider>
</JotaiProvider>
</QueryClientProvider>
);
}
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useNavigate: () => mockNavigate,
}));
jest.mock('librechat-data-provider', () => {
const actual = jest.requireActual('librechat-data-provider');
return {
...actual,
dataService: {
...actual.dataService,
getSubagentThread: (...args: unknown[]) => mockGetSubagentThread(...args),
},
};
});
jest.mock('~/data-provider', () => ({
ACTIVE_THREAD_REFRESH_MS: 2000,
/** The panel's bottom clearance follows the conversation's configured footer
* (`useConfiguredFooter`), so the panel now reads the startup config. */
useGetStartupConfig: () => ({ data: undefined }),
useSubagentThreadQuery: (...args: unknown[]) => mockUseSubagentThreadQuery(...args),
useToolCallPartQuery: (...args: unknown[]) => mockUseToolCallPartQuery(...args),
subagentThreadHasTaskEvidence: (view: SubagentThreadView | undefined, taskId: string): boolean =>
view?.messages.some(
(message) =>
message.messageId === `${taskId}:user` || message.messageId === `${taskId}:assistant`,
) === true,
useForkConvoMutation: (options: {
onSuccess: (result: unknown) => void;
onError: () => void;
}) => ({
mutate: (payload: unknown) => mockForkMutate(payload, options),
isLoading: false,
}),
useSubagentControlMutation: (options: {
onSuccess: (result: unknown, variables: unknown) => void;
onError: (error: unknown, variables: unknown) => void;
}) => ({
mutate: (variables: unknown) =>
mockControlMutate(variables, {
onSuccess: (result: unknown) => options.onSuccess(result, variables),
onError: (error: unknown) => options.onError(error, variables),
}),
isLoading: false,
}),
}));
jest.mock('@librechat/chat/react', () => ({
...jest.requireActual('@librechat/chat/react'),
useSubagentActivityStream: (...args: unknown[]) => mockUseSubagentActivityStream(...args),
jest.mock('../../../react/subagents/parents', () => ({
...jest.requireActual('../../../react/subagents/parents'),
useParentSubagents: () => ({
byMessageId: mockParentChildrenByMessage,
byThreadId: mockParentChildrenByThread,
@ -141,68 +252,9 @@ jest.mock('@librechat/chat/react', () => ({
}),
}));
jest.mock('~/hooks', () => ({
/** The real trap: its Escape listener is native and sits on the panel, so it
* runs before the panel's own React handler. Stubbing it made the panel's
* Escape assertions pass in both directions. */
useFocusTrap: jest.requireActual('~/hooks/useFocusTrap').default,
useLocalize: () => (key: string, values?: { 0: string }) =>
values == null ? key : `${key}: ${values[0]}`,
}));
jest.mock('~/hooks/Conversations/useNavigateToConvo', () => ({
jest.mock('../conversation', () => ({
__esModule: true,
default: () => ({ navigateToConvo: mockNavigateToConvo }),
}));
/** The agents map the app's subagents host reads. */
jest.mock('~/Providers/AgentsMapContext', () => ({
useAgentsMapContext: () => ({
'agent-1': { id: 'agent-1', name: 'Analyst One', avatar: { filepath: '/analyst.png' } },
'agent-2': { id: 'agent-2', name: 'Analyst Two' },
}),
}));
/** Main chat's author glyph, reduced to the face it draws: the agent's avatar
* when it has one. */
jest.mock('~/components/Chat/Messages/MessageIcon', () => ({
__esModule: true,
default: ({
agent,
iconData,
}: {
agent?: { avatar?: { filepath?: string } };
iconData?: { iconURL?: string };
}) => {
const src = iconData?.iconURL ?? agent?.avatar?.filepath;
return src != null ? (
<img src={src} alt="" data-testid="author-face" />
) : (
<span data-testid="author-face" />
);
},
}));
jest.mock('~/components/Chat/Messages/Content/ApprovalContext', () => ({
__esModule: true,
default: ({ children }: { children: React.ReactNode }) => {
const mockReact = jest.requireActual<typeof import('react')>('react');
mockReact.useEffect(() => {
mockApprovalProviderMounted();
return () => mockApprovalProviderUnmounted();
}, []);
return children;
},
}));
jest.mock('~/components/Chat/Messages/Content/MarkdownLite', () => ({
__esModule: true,
default: ({ content }: { content: string }) => <div>{content}</div>,
}));
jest.mock('@librechat/chat/components', () => ({
...jest.requireActual('@librechat/chat/components'),
SubagentConversation: function MockConversation({
default: function MockConversation({
turns,
author,
parentAuthor,
@ -224,8 +276,8 @@ jest.mock('@librechat/chat/components', () => ({
}) {
const { useContext } = jest.requireActual<typeof import('react')>('react');
const { TaskContentScopeContext } = jest.requireActual<
typeof import('~/data-provider/Subagents/content')
>('~/data-provider/Subagents/content');
typeof import('../../../react/subagents/scope')
>('../../../react/subagents/scope');
const scope = useContext(TaskContentScopeContext);
return (
<div
@ -253,6 +305,9 @@ jest.mock('@librechat/chat/components', () => ({
</div>
);
},
}));
jest.mock('../transcript', () => ({
SubagentActivityScrollSurface: ({ children }: { children: React.ReactNode }) => (
<div data-testid="shared-scroll-surface">{children}</div>
),
@ -274,8 +329,8 @@ jest.mock('@librechat/chat/components', () => ({
}) {
const { useContext } = jest.requireActual<typeof import('react')>('react');
const { TaskContentScopeContext } = jest.requireActual<
typeof import('~/data-provider/Subagents/content')
>('~/data-provider/Subagents/content');
typeof import('../../../react/subagents/scope')
>('../../../react/subagents/scope');
const scope = useContext(TaskContentScopeContext);
return (
<div
@ -317,6 +372,7 @@ const mockComposerVerdict = (
};
jest.mock('@librechat/client', () => ({
...jest.requireActual('@librechat/client'),
Alert: ({ children, ...props }: React.ComponentProps<'div'>) => (
<div role="alert" {...props}>
{children}
@ -336,7 +392,9 @@ jest.mock('@librechat/client', () => ({
displayValue,
onOpenChange,
disabled,
variant,
}: {
variant?: string;
items: { value: string; label: string }[];
setValue: (value: string) => void;
ariaLabel: string;
@ -351,6 +409,7 @@ jest.mock('@librechat/client', () => ({
aria-controls="mock-combobox-options"
aria-expanded="true"
aria-label={ariaLabel}
data-variant={variant}
disabled={disabled}
onClick={() => onOpenChange?.(true)}
>
@ -462,12 +521,13 @@ jest.mock('@librechat/client', () => ({
)}
</div>
),
useRemScale: () => mockRemScale,
useMediaQuery: (query: string) => {
if (query.includes('hover')) return mockCoarsePointer;
if (mockViewportWidth == null) return mockIsMobile;
return mockViewportWidth <= Number(/max-width:\s*([\d.]+)/.exec(query)?.[1]);
},
useMediaQuery: (query: string) => query.includes('hover') && mockCoarsePointer,
/** The real trap: its Escape listener is native and sits on the panel, so it
* runs before the panel's own React handler. Stubbing it made the panel's
* Escape assertions pass in both directions. */
useFocusTrap: jest.requireActual('@librechat/client').useFocusTrap,
useLocalize: () => (key: string, values?: { 0: string }) =>
values == null ? key : `${key}: ${values[0]}`,
useToastContext: () => ({ showToast: mockShowToast }),
}));
@ -541,8 +601,11 @@ const completedTurns: SubagentThreadView['turns'] = [
describe('SubagentThreadPanel', () => {
beforeEach(() => {
/** The app's jest config clears mock calls between tests; this package's does not. */
jest.clearAllMocks();
queryClient = new QueryClient();
window.sessionStorage.clear();
window.localStorage.clear();
mockIsMobile = false;
mockCoarsePointer = false;
mockViewportWidth = null;
@ -682,7 +745,7 @@ describe('SubagentThreadPanel', () => {
model: 'agent-2',
sender: 'Analyst Two',
text: '',
} as unknown as TMessage,
},
],
);
const { container } = render(
@ -1511,7 +1574,7 @@ describe('SubagentThreadPanel', () => {
expect(screen.getByRole('region', { name: 'com_ui_subagent_thread_panel' })).toHaveFocus();
expect(mockNavigate).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole('button', { name: 'com_ui_subagent_go_to_parent' }));
expect(mockNavigate).toHaveBeenCalledWith('/c/parent-conversation');
expect(mockNavigate).toHaveBeenCalledWith('parent-conversation');
});
it('returns focus to the task disclosure when its originating call is not loaded', async () => {
@ -1698,7 +1761,7 @@ describe('SubagentThreadPanel', () => {
model: 'agent-2',
sender: 'Analyst Two',
text: '',
} as unknown as TMessage,
},
],
);
render(
@ -1708,7 +1771,7 @@ describe('SubagentThreadPanel', () => {
);
/** One name for the child everywhere it appears, and the dispatching agent
* as the author of every briefing — never an id or a role. */
* as the author of every briefing, never an id or a role. */
const conversation = screen.getByTestId('subagent-conversation');
expect(conversation).toHaveAttribute('data-author', 'Analyst One');
expect(conversation).toHaveAttribute('data-parent-author', 'Analyst Two');
@ -1781,7 +1844,7 @@ describe('SubagentThreadPanel', () => {
/** A delivery re-keys the query to its new task and the task view blanks for
* the render or two that takes. Measured against the live panel, the
* composer used to unmount and remount inside 10ms there — taking focus and
* composer used to unmount and remount inside 10ms there, taking focus and
* a half-typed steer with it. */
it('keeps the composer mounted while a delivery re-keys the task view', () => {
mockUseSubagentThreadQuery.mockReturnValue({
@ -1820,9 +1883,9 @@ describe('SubagentThreadPanel', () => {
/** A task on its way to an executor is live: withdrawing the composer until
* the first token lands is the swap this panel exists to avoid. But the
* server can only address a task that has a durable input row — it answers
* server can only address a task that has a durable input row, it answers
* 404 otherwise, which this panel reads as inaccessible and closes controls
* for good — so the field stays and submission waits instead. */
* for good, so the field stays and submission waits instead. */
it.each([
['has its durable input row', completedView.messages, 1],
['has not been written yet', [], 0],
@ -1854,7 +1917,7 @@ describe('SubagentThreadPanel', () => {
expect(mockControlMutate).toHaveBeenCalledTimes(invocations);
});
/** Every door onto a command answers to the same gate — including the inline
/** Every door onto a command answers to the same gate, including the inline
* controls a touch reader gets instead of the hovercard. */
it('withholds the inline actions while a dispatched task is unaddressable', () => {
mockCoarsePointer = true;
@ -1881,7 +1944,7 @@ describe('SubagentThreadPanel', () => {
});
/** While the panel is a focus-trapped modal the portaled list sits outside
* the `aside` the trap knows, so Tab never reaches it — the actions come
* the `aside` the trap knows, so Tab never reaches it, the actions come
* inside the panel instead, hover or no hover. */
it('keeps the actions inside the panel while it is a modal', () => {
mockIsMobile = true;
@ -1964,8 +2027,8 @@ describe('SubagentThreadPanel', () => {
expect(mockControlMutate.mock.calls[0][0].command.action).toBe('steer');
});
/** Where there is no hover, the send control's action list cannot be opened —
* a tap on that anchor submits — so those readers get the actions as
/** Where there is no hover, the send control's action list cannot be opened:
* a tap on that anchor submits, so those readers get the actions as
* controls of their own instead. */
it('offers the alternate submissions inline when the pointer cannot hover', () => {
mockIsMobile = true;
@ -1986,13 +2049,16 @@ describe('SubagentThreadPanel', () => {
fireEvent.change(screen.getByLabelText('com_ui_message_input'), {
target: { value: 'Check the primary source.' },
});
/** The inline actions sit beside the send control, so they take its corner: the shared
* round shape, not a hand-set radius. */
expect(screen.getByRole('button', { name: 'com_ui_queue' })).toHaveAttribute('shape', 'round');
fireEvent.click(screen.getByRole('button', { name: 'com_ui_queue' }));
expect(mockControlMutate).toHaveBeenCalledTimes(1);
expect(mockControlMutate.mock.calls[0][0].command.action).toBe('queue');
});
/** Queue and interrupt keep a pointer of their own — a touch reader, or one
/** Queue and interrupt keep a pointer of their own, a touch reader, or one
* whose shortcuts are off or rebound, still has to reach them. */
it.each([
['com_ui_queue', 'queue'],
@ -2041,14 +2107,14 @@ describe('SubagentThreadPanel', () => {
fireEvent.keyDown(composer, { key: 'Enter', ctrlKey: true });
expect(mockControlMutate).toHaveBeenCalledTimes(1);
const [variables, callbacks] = mockControlMutate.mock.calls[0] as [
const [variables, callbacks]: [
{
parentConversationId: string;
threadId: string;
command: { taskId: string; invocationId: string; action: string; message: string };
},
{ onSuccess: (value: unknown) => void },
];
] = mockControlMutate.mock.calls[0];
expect(variables).toEqual({
parentConversationId: 'parent-conversation',
threadId: 'child-thread',
@ -2294,8 +2360,8 @@ describe('SubagentThreadPanel', () => {
screen.getByText('com_ui_subagent_control_reason_owner_unavailable'),
).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'com_ui_retry' })).toBeInTheDocument();
/** The settled child leaves the composer standing — Enter continues the
* thread from here — but nothing in it still addresses the finished run. */
/** The settled child leaves the composer standing, Enter continues the
* thread from here, but nothing in it still addresses the finished run. */
expect(screen.queryByRole('button', { name: 'com_ui_steer_send' })).not.toBeInTheDocument();
expect(
screen.queryByRole('button', { name: 'com_ui_subagent_cancel_task' }),
@ -2546,9 +2612,7 @@ describe('SubagentThreadPanel', () => {
partIndex: 3,
subagentType: 'researcher',
prompt: 'Review this change.',
persistedContent: [
{ type: 'text', text: 'Review complete.' },
] as unknown as TMessageContentParts[],
persistedContent: [{ type: ContentTypes.TEXT, text: 'Review complete.' }],
initialProgress: 1,
isSubmitting: false,
};
@ -2629,7 +2693,7 @@ describe('SubagentThreadPanel', () => {
name: 'subagent',
args: '{"prompt":"Review this change, including the migration and its rollback."}',
output: 'Full final answer.',
subagent_content: [{ type: 'text', text: 'Stored review transcript.' }],
subagent_content: [{ type: ContentTypes.TEXT, text: 'Stored review transcript.' }],
},
},
isError: false,
@ -2708,7 +2772,6 @@ describe('SubagentThreadPanel', () => {
{
conversationId: 'child-thread',
messageId: 'task:assistant',
option: ForkOptions.DIRECT_PATH,
},
expect.objectContaining({ onSuccess: expect.any(Function), onError: expect.any(Function) }),
);
@ -2729,7 +2792,11 @@ describe('SubagentThreadPanel', () => {
'continued-chat',
'Take this further, starting from the endgame.',
);
expect(getDraft('continued-chat')).toBe('');
expect(
[window.localStorage, window.sessionStorage].flatMap((storage) =>
Object.keys(storage).filter((key) => key.includes('continued-chat')),
),
).toEqual([]);
});
/** The composer is shared across selections, so a continuation that lands
@ -2753,7 +2820,7 @@ describe('SubagentThreadPanel', () => {
});
fireEvent.click(screen.getByRole('button', { name: 'com_ui_subagent_continue_new_chat' }));
/** A different selection owns the composer now — same child thread, but the
/** A different selection owns the composer now, same child thread, but the
* panel is showing it for another parent, so its control identity (and its
* draft) is not the one the fork was sent from. */
const laterSelection = { ...selection, parentConversationId: 'other-parent-conversation' };
@ -2850,6 +2917,10 @@ describe('SubagentThreadPanel', () => {
</Root>,
);
expect(screen.getByRole('combobox', { name: 'com_ui_subagent_actor' })).toHaveAttribute(
'data-variant',
'field',
);
expect(screen.getByRole('combobox', { name: 'com_ui_subagent_actor' })).toBeEnabled();
fireEvent.click(screen.getByRole('button', { name: 'com_ui_subagent_continue_new_chat' }));
expect(screen.getByRole('combobox', { name: 'com_ui_subagent_actor' })).toBeDisabled();
@ -2941,7 +3012,7 @@ describe('SubagentThreadPanel', () => {
});
/** Emptying the field after asking to continue is the reader withdrawing the
* words, not leaving them behind — the destination must not reinstate what
* words, not leaving them behind, the destination must not reinstate what
* they deleted. */
it('hands over nothing when the draft is cleared before the fork lands', () => {
mockUseSubagentThreadQuery.mockReturnValue({
@ -3057,9 +3128,7 @@ describe('SubagentThreadPanel', () => {
);
const detachedSelection: ActiveSubagentPanel = {
...selection,
persistedContent: [
{ type: ContentTypes.TEXT, text: 'Dispatch-time snapshot.' },
] as TMessageContentParts[],
persistedContent: [{ type: ContentTypes.TEXT, text: 'Dispatch-time snapshot.' }],
};
render(
@ -3383,6 +3452,7 @@ describe('SubagentThreadPanel', () => {
'parent-conversation',
'child-thread',
'task-earlier',
{},
);
fireEvent.click(screen.getByRole('option', { name: /Analyst Two/ }));
@ -3402,11 +3472,11 @@ describe('SubagentThreadPanel', () => {
/** The picker's popover renders inside the panel so the mobile focus trap can
* see it. That same trap closes the panel on Escape, which would take the
* composer's text with it — so an Escape aimed at the open picker has to
* composer's text with it, so an Escape aimed at the open picker has to
* stop there. */
/** The picker's popover renders inside the panel so the mobile focus trap can
* see it. That same trap closes the panel on Escape, which would take the
* composer's text with it — so an Escape aimed at the OPEN picker has to stop
* composer's text with it, so an Escape aimed at the OPEN picker has to stop
* there, while an Escape anywhere else still closes the panel. */
it.each([
['closes the panel when the actor picker is shut', false, true],
@ -3535,7 +3605,7 @@ describe('SubagentThreadPanel', () => {
latestTaskId: 'task-new',
tasks: [{ taskId: 'task-new', status: 'running' }],
tasksTruncated: false,
} as ParentSubagentSummary,
},
],
]);
mockUseSubagentThreadQuery.mockReturnValue({

View file

@ -0,0 +1,8 @@
/**
* The panel is the one subagent surface that opens on demand, so it loads through a dynamic
* import: exporting it statically would put its code in the components entry, which every page
* loads. The app wraps this in its own lazy boundary.
*/
export function loadSubagentThreadPanel(): Promise<typeof import('./panel')> {
return import('./panel');
}

View file

@ -1,65 +1,69 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { v4 } from 'uuid';
import { useAtom, useAtomValue, useSetAtom, useStore } from 'jotai';
import { isMacPlatform, resolveComposerKeyDown } from '@librechat/chat';
import { ArrowUpRight, Clock, OctagonPause, X, Zap } from 'lucide-react';
import {
cn,
Alert,
Button,
Composer,
ControlCombobox,
useLocalize,
useFocusTrap,
useMediaQuery,
ControlCombobox,
useToastContext,
} from '@librechat/client';
import {
SubagentActivity,
SubagentConversation,
SubagentActivityScrollSurface,
} from '@librechat/chat/components';
import {
activeSubagentPanel,
subagentPanelFocusRequest,
subagentControlStateByTask,
subagentControlStateKey,
subagentProgressKey,
useSubagentProgress,
useSubagentActivityStream,
adaptDurableThreadActivity,
adaptDurableThreadConversation,
adaptLivePersistedActivity,
mergeChildConversationTurns,
retainBoundedMovingWindowTurns,
eventSubagentSelection,
resolveSubagentAgentId,
isLiveSubagentStatus,
getSubagentPrompt,
useParentSubagents,
agentAuthor,
resolveSubagentAuthor,
isSelfSpawn as isSelfSpawnType,
resolveChildAgent,
readableSubagentType,
useParentAuthor,
useChatSurface,
useSubagentsHost,
useMessagePartsHost,
TaskContentScopeContext,
ACTIVE_THREAD_REFRESH_MS,
subagentThreadHasTaskEvidence,
} from '@librechat/chat/react';
import type {
ParentSubagentTaskSummary,
SubagentControlAction,
SubagentControlReceipt,
SubagentControlRequest,
} from 'librechat-data-provider';
import type { ComposerKeyVerdict, ComposerStopProps, SendAction } from '@librechat/client';
import type { ActiveSubagentPanel, SubagentControlUiState } from '@librechat/chat/react';
import type {
SendAction,
OptionWithIcon,
ComposerStopProps,
ComposerKeyVerdict,
} from '@librechat/client';
import type { KeyboardEvent as ReactKeyboardEvent, ReactNode } from 'react';
import type { ComposerKeyAction } from '@librechat/chat';
import type { OptionWithIcon } from '@librechat/client';
import { useFocusTrap, useLocalize } from '~/hooks';
import { cn } from '~/utils';
import type { ActiveSubagentPanel } from '../../react/subagents/state';
import type { ComposerKeyAction } from '../../core/shortcuts';
import {
adaptDurableThreadActivity,
adaptLivePersistedActivity,
mergeChildConversationTurns,
adaptDurableThreadConversation,
retainBoundedMovingWindowTurns,
} from '../../react/subagents/adapters';
import {
agentAuthor,
useParentAuthor,
resolveChildAgent,
readableSubagentType,
resolveSubagentAuthor,
isSelfSpawn as isSelfSpawnType,
} from '../../react/subagents/author';
import {
subagentControlStateKey,
ACTIVE_THREAD_REFRESH_MS,
subagentThreadHasTaskEvidence,
} from '../../react/subagents/thread';
import {
useChatSurface,
useSubagentPanelState,
useSubagentPanelActions,
} from '../../react/subagents/surface';
import { SubagentActivity, SubagentActivityScrollSurface } from './transcript';
import { eventSubagentSelection } from '../../react/subagents/eventSelection';
import { isMacPlatform, resolveComposerKeyDown } from '../../core/shortcuts';
import { resolveSubagentAgentId } from '../../react/subagents/identity';
import { TaskContentScopeContext } from '../../react/subagents/scope';
import { isLiveSubagentStatus } from '../../react/subagents/status';
import { useParentSubagents } from '../../react/subagents/parents';
import { getSubagentPrompt } from '../../react/subagents/prompt';
import { useSubagentsHost } from '../../react/subagents/host';
import { subagentProgressKey } from '../../core/stream/state';
import { useMessagePartsHost } from '../../react/host';
import SubagentConversation from './conversation';
const EVENT_TASK_PAGE_SIZE = 3;
const TERMINAL_CONTROL_REASONS = new Set([
@ -112,7 +116,11 @@ const failedControlLocaleKey = (reason?: string) => {
return 'com_ui_subagent_control_reason_invalid_command';
};
export default function SubagentThreadPanel({ selection }: { selection: ActiveSubagentPanel }) {
export default function SubagentThreadPanel({
selection,
}: {
selection: ActiveSubagentPanel;
}): ReactNode {
/** The shell carries the deployment's answer, so this surface lays out once,
* like the composer beside it. */
const host = useSubagentsHost();
@ -120,8 +128,9 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
const { renderAgentAvatar } = useMessagePartsHost();
const clearsFooter = host.useClearsFooter();
const localize = useLocalize();
const panelStore = useStore();
const focusRequest = useAtomValue(subagentPanelFocusRequest);
const panelStore = useSubagentPanelState();
const panelActions = useSubagentPanelActions();
const focusRequest = panelStore.useFocusRequest();
const { showToast } = useToastContext();
const navigation = host.useNavigation();
const panelRef = useRef<HTMLDivElement>(null);
@ -146,11 +155,14 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
/** Unsent words in the composer are enough on their own: whatever put them
* there, an advance would change the control identity and wipe them. */
const selectionHeldForDraft = continuationPending || controlMessage.trim() !== '';
const setSelection = useSetAtom(activeSubagentPanel);
const setSelection = useCallback(
(next: ActiveSubagentPanel | null) => panelActions?.update(next),
[panelActions],
);
const resetSelection = useCallback(() => setSelection(null), [setSelection]);
const agentsMap = host.useAgentsMap();
const { byMessageId, byThreadId, refresh } = useParentSubagents();
const progress = useSubagentProgress(
const progress = panelStore.useProgress(
subagentProgressKey(
selection.parentMessageId,
selection.event?.progressKey ?? selection.toolCallId,
@ -175,12 +187,8 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
[selection.host, selection.parentConversationId, threadId, taskId],
);
const controlIdentity = subagentControlStateKey(selection.parentConversationId, threadId, taskId);
const [controlState, setControlState] = useAtom(subagentControlStateByTask(controlIdentity));
const setControlStateForIdentity = useCallback(
(identity: string, state: SubagentControlUiState | null) =>
panelStore.set(subagentControlStateByTask(identity), state),
[panelStore],
);
const [controlState, setControlState] = panelStore.useControlState(controlIdentity);
const setControlStateForIdentity = panelStore.useControlStateWriter();
const transientControl = controlState?.receipt ?? null;
const retryControl = controlState?.retry ?? null;
const eventSummary = selection.event == null ? undefined : byThreadId.get(threadId);
@ -286,7 +294,10 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
taskView?.status === 'interrupted' ||
taskView?.status === 'cancelled');
const priorTerminalRef = useRef(false);
const contentStream = useSubagentActivityStream(selection, !durableTerminal || eventTaskRunning);
const contentStream = panelStore.useActivityStream(
selection,
!durableTerminal || eventTaskRunning,
);
useEffect(() => {
if (selection.event == null) return;
@ -819,23 +830,27 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
}
}, [focusRequest]);
/** Escape is handled on the element rather than through the trap's own
* native listener: that listener sits on this `aside`, so it runs BEFORE any
* React handler inside it and would close the whole panel out from under a
* nested popover that meant to dismiss only itself. As a React handler it
* bubbles in DOM order, so an inner control can stop it or mark it handled. */
/** Escape is not handed to the trap's own native listener: that listener sits
* on this panel, so it runs BEFORE any React handler inside it and would close
* the whole panel out from under a nested popover that meant to dismiss only
* itself. Listening on the document instead runs after React has dispatched the
* key through the panel, so an inner control can still stop it or mark it handled. */
useFocusTrap(panelRef, isMobile);
useEffect(() => {
if (!isMobile) panelRef.current?.focus({ preventScroll: true });
}, [focusRequest, isMobile]);
const handlePanelKeyDown = useCallback(
(event: ReactKeyboardEvent<HTMLElement>) => {
if (!isMobile || event.key !== 'Escape' || event.defaultPrevented) return;
useEffect(() => {
if (!isMobile) return;
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key !== 'Escape' || event.defaultPrevented) return;
const panel = panelRef.current;
if (panel == null || !(event.target instanceof Node) || !panel.contains(event.target)) return;
event.preventDefault();
close();
},
[close, isMobile],
);
};
document.addEventListener('keydown', handleKeyDown);
return () => document.removeEventListener('keydown', handleKeyDown);
}, [close, isMobile]);
useEffect(() => {
const activeElement = document.activeElement;
@ -1594,7 +1609,6 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
role={isMobile ? 'dialog' : 'region'}
aria-modal={isMobile || undefined}
aria-label={localize('com_ui_subagent_thread_panel')}
onKeyDown={handlePanelKeyDown}
className="bg-surface-primary-alt text-text-primary relative flex h-full w-full flex-col overflow-hidden"
>
{/* The main chat header's own shape: a 3.25rem bar that floats over the
@ -1633,8 +1647,9 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
behind it. */
portal={false}
onOpenChange={setActorPickerOpen}
containerClassName="min-w-0 flex-1 px-0"
className="hover:bg-surface-hover h-9 w-full border-transparent bg-transparent font-semibold"
variant="field"
containerClassName="min-w-0 flex-1"
className="h-9 w-full"
showCarat
/>
</div>
@ -1692,8 +1707,8 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
two end on one line when the panel is open beside the thread. */
<div className={cn('shrink-0 px-3 pt-2', clearsFooter ? 'pb-10' : 'pb-4')}>
{transientControl?.status === 'failed' && (
<Alert variant="error" className="mb-2 flex items-center gap-2">
<span className="min-w-0 flex-1">
<Alert variant="error" className="mb-2 flex items-center">
<span className="me-2 min-w-0 flex-1">
{localize(failedControlLocaleKey(transientControl.reason))}
</span>
{retryControl != null && (
@ -1743,11 +1758,11 @@ export default function SubagentThreadPanel({ selection }: { selection: ActiveSu
key={action.key}
type="button"
size="icon"
shape="round"
variant="quiet"
aria-label={action.label}
disabled={action.disabled}
onClick={action.onClick}
className="size-9 rounded-full"
>
{action.icon}
</Button>

View file

@ -1,7 +1,7 @@
import { createContext } from 'react';
import type { Context, Dispatch, SetStateAction } from 'react';
import type { ActiveSubagentPanel, SubagentControlUiState, SubagentProgress } from './state';
import type { ComposerBindings } from '../../core/shortcuts';
import type { ActiveSubagentPanel } from './state';
/**
* Everything this feature needs from the application hosting it, and nothing
@ -33,6 +33,26 @@ export type SubagentPanelActions = {
update: Dispatch<SetStateAction<ActiveSubagentPanel | null>>;
};
/**
* The activity panel's own state, which lives in atoms. The panel reads it through this
* contract instead of the atoms, so the component loads none. Members are hooks, called
* unconditionally, and the object never changes.
*/
export interface SubagentPanelState {
/** Bumped each time a caller asks the panel to take focus. */
useFocusRequest: () => number;
/** The live progress of one invocation, retained while the caller is mounted. */
useProgress: (invocationKey: string) => SubagentProgress | null;
/** The pending or failed control command of one task, persisted across reloads. */
useControlState: (
identity: string,
) => [SubagentControlUiState | null, Dispatch<SetStateAction<SubagentControlUiState | null>>];
/** Writes another task's control state, for a response that lands after the reader moved on. */
useControlStateWriter: () => (identity: string, state: SubagentControlUiState | null) => void;
/** Replays, then follows, the selected child's activity while `enabled`. */
useActivityStream: (selection: ActiveSubagentPanel, enabled?: boolean) => { isReady: boolean };
}
/**
* Written by `ChatSurfaceProvider` and read by the hooks in `surface.tsx`, apart from the
* provider, so a component reading the surface loads no atom: the components entry stays free
@ -43,3 +63,5 @@ export const ChatSurfaceContext: Context<ChatSurface | null> = createContext<Cha
);
export const SubagentPanelActionsContext: Context<SubagentPanelActions | null> =
createContext<SubagentPanelActions | null>(null);
export const SubagentPanelStateContext: Context<SubagentPanelState | null> =
createContext<SubagentPanelState | null>(null);

View file

@ -2,8 +2,13 @@ import { useMemo } from 'react';
import { useSetAtom } from 'jotai';
import type { ReactNode } from 'react';
import type { ChatSurface, SubagentPanelActions } from './context';
import { ChatSurfaceContext, SubagentPanelActionsContext } from './context';
import {
ChatSurfaceContext,
SubagentPanelStateContext,
SubagentPanelActionsContext,
} from './context';
import { activeSubagentPanel, subagentPanelFocusRequest } from './state';
import { subagentPanelState } from './runtime';
/** Mounts the host's surface and binds the activity panel's actions to it. */
export function ChatSurfaceProvider({
@ -30,7 +35,9 @@ export function ChatSurfaceProvider({
return (
<ChatSurfaceContext.Provider value={value}>
<SubagentPanelActionsContext.Provider value={actions}>
{children}
<SubagentPanelStateContext.Provider value={subagentPanelState}>
{children}
</SubagentPanelStateContext.Provider>
</SubagentPanelActionsContext.Provider>
</ChatSurfaceContext.Provider>
);

View file

@ -0,0 +1,28 @@
import { useCallback } from 'react';
import { useAtom, useAtomValue, useStore } from 'jotai';
import type { SubagentControlUiState } from './state';
import type { SubagentPanelState } from './context';
import {
subagentControlStateByTask,
subagentPanelFocusRequest,
useSubagentProgress,
} from './state';
import { useSubagentActivityStream } from './stream';
function useControlStateWriter(): (identity: string, state: SubagentControlUiState | null) => void {
const store = useStore();
return useCallback(
(identity: string, state: SubagentControlUiState | null) =>
store.set(subagentControlStateByTask(identity), state),
[store],
);
}
/** The panel state `ChatSurfaceProvider` supplies: the atoms behind `SubagentPanelState`. */
export const subagentPanelState: SubagentPanelState = {
useFocusRequest: () => useAtomValue(subagentPanelFocusRequest),
useProgress: useSubagentProgress,
useControlState: (identity) => useAtom(subagentControlStateByTask(identity)),
useControlStateWriter,
useActivityStream: useSubagentActivityStream,
};

View file

@ -358,12 +358,6 @@ export type SubagentControlUiState = {
retry?: SubagentControlRequest;
};
export const subagentControlStateKey = (
parentConversationId: string,
threadId: string,
taskId: string,
): string => `${parentConversationId}\u0000${threadId}\u0000${taskId}`;
const SUBAGENT_CONTROL_STORAGE_PREFIX = 'librechat.subagent-control:';
const CONTROL_ACTIONS = new Set(['steer', 'queue', 'interrupt', 'cancel', 'cancel_message']);
const storedControlState = (value: unknown): SubagentControlUiState | null => {

View file

@ -1,9 +1,14 @@
import { useContext } from 'react';
import type { ChatSurface, SubagentPanelActions } from './context';
import type { ChatSurface, SubagentPanelState, SubagentPanelActions } from './context';
import type { ActiveSubagentPanel } from './state';
import { ChatSurfaceContext, SubagentPanelActionsContext } from './context';
import {
ChatSurfaceContext,
SubagentPanelStateContext,
SubagentPanelActionsContext,
} from './context';
export type { ChatSurface, SubagentPanelActions } from './context';
export type { ChatSurface, SubagentPanelState, SubagentPanelActions } from './context';
export { SubagentPanelStateContext } from './context';
export function useChatSurface(): ChatSurface {
const surface = useContext(ChatSurfaceContext);
@ -35,3 +40,12 @@ export function useSubagentPanelActions(): SubagentPanelActions | null {
export function useOpenSubagentPanel(): ((selection: ActiveSubagentPanel) => void) | null {
return useSubagentPanelActions()?.open ?? null;
}
/** The activity panel's state; the panel renders only inside a `ChatSurfaceProvider`. */
export function useSubagentPanelState(): SubagentPanelState {
const state = useContext(SubagentPanelStateContext);
if (state == null) {
throw new Error('useSubagentPanelState must be used within a ChatSurfaceProvider');
}
return state;
}

View file

@ -13,3 +13,10 @@ export const subagentThreadHasTaskEvidence = (
(message) =>
message.messageId === `${taskId}:user` || message.messageId === `${taskId}:assistant`,
) === true;
/** Names one task's control state: the parent conversation, the child thread and the task. */
export const subagentControlStateKey = (
parentConversationId: string,
threadId: string,
taskId: string,
): string => `${parentConversationId}\u0000${threadId}\u0000${taskId}`;

View file

@ -9,6 +9,7 @@ export { default as useCombobox } from './useCombobox';
export { default as useLocalize } from './useLocalize';
export { default as useLanguage } from './useLanguage';
export { default as useMediaQuery } from './useMediaQuery';
export { default as useFocusTrap } from './useFocusTrap';
export { default as useDelayedRender } from './useDelayedRender';
export { default as useInputModality } from './useInputModality';
export { default as useOnClickOutside } from './useOnClickOutside';

View file

@ -7,7 +7,7 @@ export default function useFocusTrap(
containerRef: RefObject<HTMLElement | null>,
active: boolean,
onEscape?: () => void,
) {
): void {
const onEscapeRef = useRef(onEscape);
useEffect(() => {
onEscapeRef.current = onEscape;