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
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🧪 refactor: Move Test-Only Helpers Out of Production Modules (#17139)
Marco Beretta07299822e5ec
diff --git a/client/src/components/Chat/Input/Composer/__tests__/Queue.spec.tsx b/client/src/components/Chat/Input/Composer/__tests__/Queue.spec.tsxindex 06387ccaf7..e3f58bb6b5 100644--- a/client/src/components/Chat/Input/Composer/__tests__/Queue.spec.tsx+++ b/client/src/components/Chat/Input/Composer/__tests__/Queue.spec.tsx@@ -5,15 +5,19 @@ import { getDefaultStore, useSetAtom } from 'jotai';import { HTML5Backend } from 'react-dnd-html5-backend';import { ReasoningEffort } from 'librechat-data-provider';import { hasQueuedIntent, releaseQueuedIntent } from '@librechat/chat';-import { revealedQueuedTurnFamily, resetSteerFamilies } from '@librechat/chat/react';import { act, render, screen, within, waitFor, fireEvent } from '@testing-library/react';+import {+ revealedQueuedTurnFamily,+ resetSteerFamilies,+ resetQueueFamilies,+} from '@librechat/chat/react';import type { SteeringControls } from '~/hooks/Chat/useSteering';import type { QueuedMessage } from '~/hooks/Chat/queue';import {QueuedTurnPortalProvider,useQueuedTurnPortal,} from '~/components/Chat/Steering/QueuedTurnPortal';-import { queuedMessagesByConvoId, resetQueueFamilies } from '~/hooks/Chat/queue';+import { queuedMessagesByConvoId } from '~/hooks/Chat/queue';import Queue from '../Queue';jest.mock('~/hooks', () => ({useLocalize: () => (key: string, options?: Record<string, string | number>) => {diff --git a/client/src/components/Chat/Subagents/adapters.test.ts b/client/src/components/Chat/Subagents/adapters.test.tsindex 3d86322767..99478285f7 100644--- a/client/src/components/Chat/Subagents/adapters.test.ts+++ b/client/src/components/Chat/Subagents/adapters.test.ts@@ -12,11 +12,8 @@ import {mergeChildConversationTurns,retainBoundedMovingWindowTurns,} from './adapters';-import {- aggregateSubagentContent,- initSubagentAggregatorState,- initSubagentTickerState,-} from '~/utils/subagentContent';+import { initSubagentAggregatorState, initSubagentTickerState } from '~/utils/subagentContent';+import { aggregateSubagentContent } from 'test/subagents';describe('child activity adapters', () => {it('passes child dispatch and completed durations to the generic tool card', () => {diff --git a/client/src/hooks/Chat/__tests__/abort.spec.tsx b/client/src/hooks/Chat/__tests__/abort.spec.tsxindex 7cb3d6f34d..e78ff6c139 100644--- a/client/src/hooks/Chat/__tests__/abort.spec.tsx+++ b/client/src/hooks/Chat/__tests__/abort.spec.tsx@@ -10,15 +10,11 @@ import {activeGenerationProtocolVersionByConvoId,submissionByIndex,clearSubmissions,+ resetQueueFamilies,} from '@librechat/chat/react';import type { TSubmission, TConversation } from 'librechat-data-provider';import type { DrainAfterAbort, RunEnd } from '~/hooks/Chat/queue';-import {- stopRequestedByConvoId,- drainAfterAbortByIndex,- resetQueueFamilies,- runEndByIndex,-} from '~/hooks/Chat/queue';+import { stopRequestedByConvoId, drainAfterAbortByIndex, runEndByIndex } from '~/hooks/Chat/queue';import useChatHelpers from '../useChatHelpers';import { useAbortCleanup } from '../abort';import store from '~/store';diff --git a/client/src/hooks/Chat/__tests__/transport.spec.tsx b/client/src/hooks/Chat/__tests__/transport.spec.tsxindex 7bf8155486..80f3d26980 100644--- a/client/src/hooks/Chat/__tests__/transport.spec.tsx+++ b/client/src/hooks/Chat/__tests__/transport.spec.tsx@@ -12,6 +12,7 @@ import {resetSteerFamilies,submissionByIndex,clearSubmissions,+ resetQueueFamilies,} from '@librechat/chat/react';import type {TEnqueueAgentQueuedTurnRequest,@@ -25,11 +26,11 @@ import type { StreamStatusResponse } from '~/data-provider';import type { ChatContract } from '~/hooks/Chat/contract';import type { Transport } from '~/hooks/Chat/contract';import type { PendingSteer } from '~/hooks/Chat/queue';-import { queuedMessagesByConvoId, resetQueueFamilies } from '~/hooks/Chat/queue';import { ChatTransportContext } from '~/Providers/ChatTransportContext';import { ChatContext, useChatContext } from '~/Providers/ChatContext';import { startupConfigKey } from '~/data-provider/Endpoints/queries';import { useSteerReclaim } from '~/hooks/Chat/useSteerCancel';+import { queuedMessagesByConvoId } from '~/hooks/Chat/queue';import useSteerEscalate from '~/hooks/Chat/useSteerEscalate';import useResumableSSE from '~/hooks/SSE/useResumableSSE';import useResumeOnLoad from '~/hooks/SSE/useResumeOnLoad';diff --git a/client/src/hooks/Chat/__tests__/useQueueDrain.spec.tsx b/client/src/hooks/Chat/__tests__/useQueueDrain.spec.tsxindex 582f851012..70cfcfad06 100644--- a/client/src/hooks/Chat/__tests__/useQueueDrain.spec.tsx+++ b/client/src/hooks/Chat/__tests__/useQueueDrain.spec.tsx@@ -5,7 +5,11 @@ import { act, renderHook, waitFor } from '@testing-library/react';import { Constants, ReasoningEffort } from 'librechat-data-provider';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { isSubmittingFamily, resetSubmitting } from '@librechat/chat/react';-import { revealedQueuedTurnFamily, resetSteerFamilies } from '@librechat/chat/react';+import {+ revealedQueuedTurnFamily,+ resetSteerFamilies,+ resetQueueFamilies,+} from '@librechat/chat/react';import {claimQueuedIntent,releaseQueuedIntent,@@ -24,7 +28,6 @@ import {pendingRunEndByConvoId,drainAfterAbortByIndex,runEndByIndex,- resetQueueFamilies,} from '~/hooks/Chat/queue';import { recoveryDispositionsFamily } from '~/components/Chat/Steering/recovery';import useQueueDrain from '../useQueueDrain';diff --git a/client/src/hooks/Chat/__tests__/useSteerCancel.spec.tsx b/client/src/hooks/Chat/__tests__/useSteerCancel.spec.tsxindex 7a66e4ca73..52b34a84f8 100644--- a/client/src/hooks/Chat/__tests__/useSteerCancel.spec.tsx+++ b/client/src/hooks/Chat/__tests__/useSteerCancel.spec.tsx@@ -7,6 +7,7 @@ import {activeGenerationCreatedAtByConvoId,pendingSteersByConvoId,resetSteerFamilies,+ resetQueueFamilies,} from '@librechat/chat/react';import type { RestoreToComposer } from '~/Providers/ComposerRestoreContext';import type { PendingSteer } from '~/hooks/Chat/queue';@@ -14,9 +15,9 @@ import {ComposerRestoreProvider,useComposerRestoreHost,} from '~/Providers/ComposerRestoreContext';-import { queuedMessagesByConvoId, resetQueueFamilies } from '~/hooks/Chat/queue';import useSteerCancel, { useSteerMoveToQueue } from '../useSteerCancel';import '~/Providers/SteerHostContext';+import { queuedMessagesByConvoId } from '~/hooks/Chat/queue';const mockCancelAsync = jest.fn();diff --git a/client/src/hooks/Chat/__tests__/useSteerConvert.spec.tsx b/client/src/hooks/Chat/__tests__/useSteerConvert.spec.tsxindex 413c683188..eb32ff2a98 100644--- a/client/src/hooks/Chat/__tests__/useSteerConvert.spec.tsx+++ b/client/src/hooks/Chat/__tests__/useSteerConvert.spec.tsx@@ -7,9 +7,10 @@ import {appliedSteerIdsByConvoId,pendingSteersByConvoId,resetSteerFamilies,+ resetQueueFamilies,} from '@librechat/chat/react';import { recoveryDispositionsFamily } from '~/components/Chat/Steering/recovery';-import { queuedMessagesByConvoId, resetQueueFamilies } from '~/hooks/Chat/queue';+import { queuedMessagesByConvoId } from '~/hooks/Chat/queue';import useSteerConvert from '../useSteerConvert';import '~/Providers/SteerHostContext';diff --git a/client/src/hooks/Chat/__tests__/useSteerRecovery.spec.tsx b/client/src/hooks/Chat/__tests__/useSteerRecovery.spec.tsxindex 0ba0fe88aa..01a5548e62 100644--- a/client/src/hooks/Chat/__tests__/useSteerRecovery.spec.tsx+++ b/client/src/hooks/Chat/__tests__/useSteerRecovery.spec.tsx@@ -10,6 +10,7 @@ import {appliedSteerIdsByConvoId,pendingSteersByConvoId,resetSteerFamilies,+ resetQueueFamilies,} from '@librechat/chat/react';import type { RewakeDrain } from '~/Providers/ComposerRestoreContext';import {@@ -17,7 +18,7 @@ import {useComposerRestoreHost,} from '~/Providers/ComposerRestoreContext';import { ChatSettingsContext, defaultChatSettings } from '~/Providers/ChatSettingsContext';-import { queuedMessagesByConvoId, resetQueueFamilies } from '~/hooks/Chat/queue';+import { queuedMessagesByConvoId } from '~/hooks/Chat/queue';import { usePaneConversations } from '~/routes/ChatSettings';import useSteerRecovery from '../useSteerRecovery';import store from '~/store';diff --git a/client/src/hooks/Chat/__tests__/useSteering.spec.tsx b/client/src/hooks/Chat/__tests__/useSteering.spec.tsxindex bd353ee6d7..f8848adfa6 100644--- a/client/src/hooks/Chat/__tests__/useSteering.spec.tsx+++ b/client/src/hooks/Chat/__tests__/useSteering.spec.tsx@@ -26,6 +26,7 @@ import {appliedSteerIdsByConvoId,pendingSteersByConvoId,resetSteerFamilies,+ resetQueueFamilies,} from '@librechat/chat/react';import type { CodeApprovalMode, TConversation, TFile, TMessage } from 'librechat-data-provider';import type { QueuedMessage } from '~/hooks/Chat/queue';@@ -37,7 +38,6 @@ import {pendingRunEndByConvoId,drainAfterAbortByIndex,runEndByIndex,- resetQueueFamilies,} from '~/hooks/Chat/queue';import {getReasoningStateKey,diff --git a/client/src/hooks/Chat/queue.ts b/client/src/hooks/Chat/queue.tsindex 4370cc9190..11e43d2f0e 100644--- a/client/src/hooks/Chat/queue.ts+++ b/client/src/hooks/Chat/queue.ts@@ -1,7 +1,6 @@export { isStoppedRun, resolveDetachedRunEnd } from '@librechat/chat';export {runEndByIndex,- resetQueueFamilies,isDetachedRunManual,detachedRunByConvoId,drainAfterAbortByIndex,diff --git a/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts b/client/src/hooks/SSE/__tests__/useResumableSSE.spec.tsindex b5c41c121f..63f2591ce9 100644--- a/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts+++ b/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts@@ -320,8 +320,8 @@ import {queuedMessagesByConvoId,stopRequestedByConvoId,detachedRunByConvoId,- resetQueueFamilies,} from '~/hooks/Chat/queue';+import { resetQueueFamilies } from '@librechat/chat/react';const CONV_ID = 'conv-abc-123';diff --git a/client/src/hooks/SSE/__tests__/useResumeOnLoad.spec.tsx b/client/src/hooks/SSE/__tests__/useResumeOnLoad.spec.tsxindex d24abca803..1f6e8f68ed 100644--- a/client/src/hooks/SSE/__tests__/useResumeOnLoad.spec.tsx+++ b/client/src/hooks/SSE/__tests__/useResumeOnLoad.spec.tsx@@ -15,6 +15,7 @@ import {pendingSteersByConvoId,activeGenerationCreatedAtByConvoId,submissionStartFamily,+ resetQueueFamilies,} from '@librechat/chat/react';import type { Agents, TMessage, TConversation, TSubmission } from 'librechat-data-provider';import type { MutableSnapshot } from 'recoil';@@ -26,7 +27,6 @@ import {stopRequestedByConvoId,pendingRunEndByConvoId,detachedRunByConvoId,- resetQueueFamilies,} from '~/hooks/Chat/queue';import { siblingIdxFamily, siblingKey } from '~/components/Chat/Messages/Thread/state';import { pendingApprovalActionFamily } from '~/components/Chat/approval/state';diff --git a/client/src/hooks/useKeyboardShortcuts.spec.tsx b/client/src/hooks/useKeyboardShortcuts.spec.tsxindex a1299fb984..ce65fa7d6a 100644--- a/client/src/hooks/useKeyboardShortcuts.spec.tsx+++ b/client/src/hooks/useKeyboardShortcuts.spec.tsx@@ -6,16 +6,18 @@ import type { SettingDefinition, TConversation } from 'librechat-data-provider';import type { MutableSnapshot } from 'recoil';import type { ReactNode } from 'react';import type * as ReasoningModule from '~/components/Chat/Input/Reasoning';+import type { ShortcutActionId } from './useKeyboardShortcuts';+import type { ShortcutOverride } from '~/store/misc';import useKeyboardShortcuts, {+ isMac,isOverridden,- effectiveBinding,+ resolveShortcutBindings,useShortcutHint,useShortcutActions,- getShortcutDisplay,- getShortcutAriaKey,useShortcutDisplay,useShortcutAriaKey,} from './useKeyboardShortcuts';+import { bindingDisplayString, bindingToString } from '~/utils/shortcuts';import { ReasoningControl } from '~/components/Chat/Input/Reasoning';import Thinking from '~/components/Chat/Input/Composer/Thinking';import store from '~/store';@@ -221,47 +223,46 @@ function appendPortalFocus(paneIndex: number, tag: 'button' | 'input' = 'button'}describe('binding resolution helpers', () => {+ const bindingFor = (id: ShortcutActionId, overrides: Record<string, ShortcutOverride> = {}) =>+ resolveShortcutBindings(overrides).get(id) ?? null;+ const displayFor = (id: ShortcutActionId, overrides: Record<string, ShortcutOverride> = {}) => {+ const binding = bindingFor(id, overrides);+ return binding ? bindingDisplayString(binding, isMac) : '';+ };+ const ariaFor = (id: ShortcutActionId, overrides: Record<string, ShortcutOverride> = {}) => {+ const binding = bindingFor(id, overrides);+ return binding ? (bindingToString(binding) ?? '') : '';+ };+it('falls back to the default binding when there is no override', () => {- const binding = effectiveBinding('newChat');- expect(binding).toMatchObject({ ctrl: true, shift: true, key: 'O' });- expect(getShortcutDisplay('newChat')).toBe('Ctrl+Shift+O');- expect(getShortcutAriaKey('newChat')).toBe('Control+Shift+O');+ expect(bindingFor('newChat')).toMatchObject({ ctrl: true, shift: true, key: 'O' });+ expect(displayFor('newChat')).toBe('Ctrl+Shift+O');+ expect(ariaFor('newChat')).toBe('Control+Shift+O');});- it('honors a stored custom binding for the current platform', () => {- window.localStorage.setItem(- STORAGE_KEY,- JSON.stringify({ newChat: { mac: 'Meta+Shift+P', other: 'Control+Shift+P' } }),- );- expect(effectiveBinding('newChat')).toMatchObject({ ctrl: true, shift: true, key: 'P' });- expect(getShortcutAriaKey('newChat')).toBe('Control+Shift+P');+ it('honors a custom binding for the current platform', () => {+ const overrides = { newChat: { mac: 'Meta+Shift+P', other: 'Control+Shift+P' } };+ expect(bindingFor('newChat', overrides)).toMatchObject({ ctrl: true, shift: true, key: 'P' });+ expect(ariaFor('newChat', overrides)).toBe('Control+Shift+P');});it('treats a null platform override as an unbound shortcut', () => {- window.localStorage.setItem(- STORAGE_KEY,- JSON.stringify({ newChat: { mac: null, other: null } }),- );- expect(effectiveBinding('newChat')).toBeNull();- expect(getShortcutDisplay('newChat')).toBe('');+ const overrides = { newChat: { mac: null, other: null } };+ expect(bindingFor('newChat', overrides)).toBeNull();+ expect(displayFor('newChat', overrides)).toBe('');});it('keeps a persisted custom chord when a new default later claims the same keys', () => {- window.localStorage.setItem(- STORAGE_KEY,- JSON.stringify({- toggleSidebar: { mac: 'Meta+Shift+.', other: 'Control+Shift+.' },- }),- );+ const overrides = { toggleSidebar: { mac: 'Meta+Shift+.', other: 'Control+Shift+.' } };- expect(effectiveBinding('toggleSidebar')).toMatchObject({+ expect(bindingFor('toggleSidebar', overrides)).toMatchObject({ctrl: true,shift: true,key: '.',});- expect(effectiveBinding('escalateSteer')).toBeNull();- expect(getShortcutDisplay('escalateSteer')).toBe('');- expect(getShortcutAriaKey('escalateSteer')).toBe('');+ expect(bindingFor('escalateSteer', overrides)).toBeNull();+ expect(displayFor('escalateSteer', overrides)).toBe('');+ expect(ariaFor('escalateSteer', overrides)).toBe('');});it("does not treat an other-platform edit's copied default as a custom claim", () => {@@ -270,12 +271,12 @@ describe('binding resolution helpers', () => {toggleSidebar: { mac: 'Meta+Shift+O', other: 'Control+Shift+O' },};- expect(effectiveBinding('toggleSidebar', overrides)).toMatchObject({+ expect(bindingFor('toggleSidebar', overrides)).toMatchObject({ctrl: true,shift: true,key: 'O',});- expect(effectiveBinding('newChat', overrides)).toBeNull();+ expect(bindingFor('newChat', overrides)).toBeNull();});it('detects whether an override diverges from the default', () => {diff --git a/client/src/hooks/useKeyboardShortcuts.ts b/client/src/hooks/useKeyboardShortcuts.tsindex ffd82ad37b..f4487b2e05 100644--- a/client/src/hooks/useKeyboardShortcuts.ts+++ b/client/src/hooks/useKeyboardShortcuts.ts@@ -26,7 +26,6 @@ import { getFocusedChatPane } from '~/utils/pane';import store from '~/store';const isMac = isMacPlatform;-const CUSTOM_STORAGE_KEY = 'customKeyboardShortcuts';export type ShortcutDefinition = {labelKey: string;@@ -487,49 +486,6 @@ export function resolveShortcutBindings(return resolved;}-function readOverridesFromStorage(): Record<string, ShortcutOverride> {- if (typeof window === 'undefined') {- return {};- }- try {- const raw = window.localStorage.getItem(CUSTOM_STORAGE_KEY);- if (!raw) return {};- const parsed = JSON.parse(raw);- return typeof parsed === 'object' && parsed !== null ? parsed : {};- } catch {- return {};- }-}--export function effectiveBinding(- actionId: ShortcutActionId,- overrides?: Record<string, ShortcutOverride>,-): ShortcutBinding | null {- const map = overrides ?? readOverridesFromStorage();- return resolveShortcutBindings(map).get(actionId) ?? null;-}--export function getShortcutDisplay(actionId: ShortcutActionId): string {- const binding = effectiveBinding(actionId);- if (!binding) {- return '';- }- return bindingDisplayString(binding, isMac);-}--export function getShortcutAriaKey(actionId: ShortcutActionId): string {- const binding = effectiveBinding(actionId);- if (!binding) {- return '';- }- return bindingToString(binding) ?? '';-}--export function getShortcutHint(actionId: ShortcutActionId, label: string): string {- const display = getShortcutDisplay(actionId);- return display ? `${label} (${display})` : label;-}-export function isOverridden(actionId: ShortcutActionId, override?: ShortcutOverride): boolean {if (!override) return false;const platformValue = isMac ? override.mac : override.other;diff --git a/client/src/utils/__tests__/subagentContent.test.ts b/client/src/utils/__tests__/subagentContent.test.tsindex cea6c98b8f..5f1d244701 100644--- a/client/src/utils/__tests__/subagentContent.test.ts+++ b/client/src/utils/__tests__/subagentContent.test.ts@@ -1,6 +1,6 @@import { ContentTypes } from 'librechat-data-provider';import type { SubagentUpdateEvent } from 'librechat-data-provider';-import { aggregateSubagentContent, buildSubagentTickerLines } from '../subagentContent';+import { aggregateSubagentContent, buildSubagentTickerLines } from 'test/subagents';const makeEvent = (overrides: Partial<SubagentUpdateEvent>): SubagentUpdateEvent => ({runId: 'parent-run',diff --git a/client/src/utils/subagentContent.ts b/client/src/utils/subagentContent.tsindex fa3a595108..4dea780034 100644--- a/client/src/utils/subagentContent.ts+++ b/client/src/utils/subagentContent.ts@@ -3,18 +3,18 @@ import type { SubagentUpdateEvent, ToolTimingStamps } from 'librechat-data-provi/*** Client-side helpers for rendering the live `SubagentCall` UI while- * `ON_SUBAGENT_UPDATE` events stream in. Exports two pure transforms:+ * `ON_SUBAGENT_UPDATE` events stream in. Exports two incremental folds:*- * - `aggregateSubagentContent` — folds the raw event stream into an- * ordered array of TEXT / THINK / TOOL_CALL parts so the dialog can- * render the child's activity through the same `<Part />` pipeline- * the parent conversation uses. Frontend-only: on the backend we- * fold directly into the SDK's `createContentAggregator` in the- * `ON_SUBAGENT_UPDATE` handler, so no shared aggregator is needed.- * - `buildSubagentTickerLines` — short, user-readable status lines- * for the collapsed ticker. Aggregates message/reasoning deltas- * into running previews, surfaces tool-call lifecycle with- * args/output snippets, drops low-signal events.+ * - `foldSubagentEvent` folds one raw event into an ordered array of+ * TEXT / THINK / TOOL_CALL parts so the dialog can render the child's+ * activity through the same `<Part />` pipeline the parent conversation+ * uses. Frontend-only: on the backend we fold directly into the SDK's+ * `createContentAggregator` in the `ON_SUBAGENT_UPDATE` handler, so no+ * shared aggregator is needed.+ * - `foldSubagentEventIntoTicker` folds one raw event into the short,+ * user-readable status lines for the collapsed ticker. Aggregates+ * message/reasoning deltas into running previews, surfaces tool-call+ * lifecycle with args/output snippets, drops low-signal events.*/type RunStepData = {@@ -664,20 +664,6 @@ export function reconcileSubagentToolTimings(return next;}-/**- * Batch wrapper around {@link foldSubagentEvent}: folds an entire event- * stream in one go and returns just the parts. Kept for tests and for- * legacy call-sites that don't need cursor state.- */-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;-}-/*** Discriminated-union ticker line. Keeping the label tokens + body/snippets* separate from their rendered strings lets the caller localize at@@ -897,16 +883,3 @@ export function foldSubagentEventIntoTicker(return state;}--/**- * Batch wrapper around {@link foldSubagentEventIntoTicker} — folds an- * entire event stream in one shot. Kept for tests and any legacy- * consumer that prefers a one-call API.- */-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/test/subagents.ts b/client/test/subagents.tsnew file mode 100644index 0000000000..ccdb4a1d9f--- /dev/null+++ b/client/test/subagents.ts@@ -0,0 +1,27 @@+import type { SubagentUpdateEvent } from 'librechat-data-provider';+import type { SubagentContentPart, SubagentTickerLine } from '~/utils/subagentContent';+import {+ foldSubagentEvent,+ initSubagentTickerState,+ foldSubagentEventIntoTicker,+ initSubagentAggregatorState,+} from '~/utils/subagentContent';++/** 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/packages/api/src/agents/client.ts b/packages/api/src/agents/client.tsindex 86b0ad37b0..e83836bd2d 100644--- a/packages/api/src/agents/client.ts+++ b/packages/api/src/agents/client.ts@@ -481,14 +481,6 @@ export function collectToolCallIds(return ids;}-export function createTokenCounter(- encoding: Parameters<typeof Tokenizer.getTokenCount>[1],-): TokenCounter {- return createMessageTokenCounter(encoding, (text: string) =>- Tokenizer.getTokenCount(text, encoding),- );-}-function createMessageTokenCounter(encoding: Parameters<typeof Tokenizer.getTokenCount>[1],countTokens: (text: string) => number,diff --git a/packages/api/src/agents/hitl/__fixtures__/approval.ts b/packages/api/src/agents/hitl/__fixtures__/approval.tsnew file mode 100644index 0000000000..f59ab1ece9--- /dev/null+++ b/packages/api/src/agents/hitl/__fixtures__/approval.ts@@ -0,0 +1,32 @@+import type { Agents } from 'librechat-data-provider';++const DEFAULT_REVIEW_DECISIONS: Agents.ToolApprovalDecisionType[] = ['approve', 'reject', 'edit'];++/** Tool-call shape consumed by {@link buildToolApprovalPayload}. */+export interface ToolApprovalCallInput {+ name: string;+ arguments: string | Record<string, unknown>;+ tool_call_id: string;+ description?: string;+}++/** Builds a tool-approval interrupt payload from one or more paused tool calls, as the SDK emits it. */+export function buildToolApprovalPayload(+ toolCalls: ToolApprovalCallInput[],+ decisionsByToolName?: Record<string, Agents.ToolApprovalDecisionType[]>,+): Agents.ToolApprovalInterruptPayload {+ return {+ type: 'tool_approval',+ action_requests: toolCalls.map((tc) => ({+ name: tc.name,+ arguments: tc.arguments,+ tool_call_id: tc.tool_call_id,+ description: tc.description,+ })),+ review_configs: toolCalls.map((tc) => ({+ action_name: tc.name,+ tool_call_id: tc.tool_call_id,+ allowed_decisions: decisionsByToolName?.[tc.name] ?? DEFAULT_REVIEW_DECISIONS,+ })),+ };+}diff --git a/packages/api/src/agents/hitl/allow.spec.ts b/packages/api/src/agents/hitl/allow.spec.tsindex 905dbd7453..9f2de3278a 100644--- a/packages/api/src/agents/hitl/allow.spec.ts+++ b/packages/api/src/agents/hitl/allow.spec.ts@@ -13,8 +13,9 @@ import {buildEffectiveToolApprovalPolicy,} from './allow';import { registerToolApprovalHook, clearToolApprovalHooks } from './hooks';-import { buildToolApprovalPayload, mapToolApprovalPolicy } from './policy';+import { buildToolApprovalPayload } from './__fixtures__/approval';import { resolveToolApprovalResume } from './resume';+import { mapToolApprovalPolicy } from './policy';import { canAgentGraphPause } from './admission';import { buildHITLRunWiring } from './runtime';diff --git a/packages/api/src/agents/hitl/modes.spec.ts b/packages/api/src/agents/hitl/modes.spec.tsindex 5146bae4b3..e23cc76174 100644--- a/packages/api/src/agents/hitl/modes.spec.ts+++ b/packages/api/src/agents/hitl/modes.spec.ts@@ -8,9 +8,10 @@ import {describeRememberedToolApprovals,} from './modes';import { bindToolApproval, bindToolApprovalIdentity } from '~/tools/approval';-import { buildToolApprovalPayload, toClientPendingAction } from './policy';+import { buildToolApprovalPayload } from './__fixtures__/approval';import { buildEffectiveToolApprovalPolicy } from './allow';import { bindToolReviewAuthority } from '~/tools/approval';+import { toClientPendingAction } from './policy';import { buildHITLRunWiring } from './runtime';const scope = { userId: 'user-a', tenantId: 'tenant-a', conversationId: 'chat-a' };diff --git a/packages/api/src/agents/hitl/policy.spec.ts b/packages/api/src/agents/hitl/policy.spec.tsindex 5f3b0fba55..39d8402fb5 100644--- a/packages/api/src/agents/hitl/policy.spec.ts+++ b/packages/api/src/agents/hitl/policy.spec.ts@@ -6,7 +6,6 @@ import {isHITLEnabled,healToolApprovalPolicy,mapToolApprovalPolicy,- buildToolApprovalPayload,buildPendingAction,isToolApprovalPayloadValid,toClientPendingAction,@@ -203,69 +202,6 @@ describe('mapToolApprovalPolicy', () => {});});-describe('buildToolApprovalPayload', () => {- const calls = [- {- name: 'shell',- arguments: { command: 'ls' },- tool_call_id: 'call_abc',- description: 'List files',- },- ];-- test('produces a tool_approval-discriminated payload', () => {- const payload = buildToolApprovalPayload(calls);- expect(payload.type).toBe('tool_approval');- expect(payload.action_requests).toEqual([- {- name: 'shell',- arguments: { command: 'ls' },- tool_call_id: 'call_abc',- description: 'List files',- },- ]);- });-- test("default decisions exclude 'respond' (reserved for AskUserQuestion semantics)", () => {- const payload = buildToolApprovalPayload(calls);- expect(payload.review_configs[0].allowed_decisions).toEqual(['approve', 'reject', 'edit']);- });-- test('respects per-tool decision overrides', () => {- const payload = buildToolApprovalPayload(calls, {- shell: ['approve', 'reject'],- });- expect(payload.review_configs[0].allowed_decisions).toEqual(['approve', 'reject']);- });-- test('produces one review_config per call, in order', () => {- const payload = buildToolApprovalPayload([- { name: 'a', arguments: {}, tool_call_id: '1' },- { name: 'b', arguments: {}, tool_call_id: '2' },- ]);- expect(payload.review_configs.map((r) => r.action_name)).toEqual(['a', 'b']);- });-- test('carries tool_call_id on each review_config (join key for duplicate-tool batches)', () => {- const payload = buildToolApprovalPayload([- { name: 'mcp:server:search', arguments: { q: 'a' }, tool_call_id: 'call_1' },- { name: 'mcp:server:search', arguments: { q: 'b' }, tool_call_id: 'call_2' },- ]);- expect(payload.review_configs).toEqual([- {- action_name: 'mcp:server:search',- tool_call_id: 'call_1',- allowed_decisions: ['approve', 'reject', 'edit'],- },- {- action_name: 'mcp:server:search',- tool_call_id: 'call_2',- allowed_decisions: ['approve', 'reject', 'edit'],- },- ]);- });-});-describe('buildPendingAction', () => {const ctx = {streamId: 'stream-1',diff --git a/packages/api/src/agents/hitl/policy.ts b/packages/api/src/agents/hitl/policy.tsindex 2db29004cb..8cad7a3a04 100644--- a/packages/api/src/agents/hitl/policy.ts+++ b/packages/api/src/agents/hitl/policy.ts@@ -9,15 +9,6 @@ import type { Agents, TReasoningOverride, TToolApprovalPolicy } from 'librechat-import type { ToolPolicyConfig } from '@librechat/agents';import type { MCPToolAlias } from '~/tools/classification';-/**- * Default decisions offered to the user for a paused tool call.- *- * `'respond'` is intentionally NOT in the default set: it represents the agent- * substituting a synthetic tool result, which is rarely the right ergonomic for- * a stock approval prompt. Hosts that want it can pass an override.- */-const DEFAULT_REVIEW_DECISIONS: Agents.ToolApprovalDecisionType[] = ['approve', 'reject', 'edit'];-/*** Layered sources that combine into the effective tool-approval policy for a turn.*@@ -260,40 +251,6 @@ export function mapToolApprovalPolicy(return Object.keys(config).length > 0 ? config : undefined;}-/** Tool-call shape consumed by {@link buildToolApprovalPayload}. */-export interface ToolApprovalCallInput {- name: string;- arguments: string | Record<string, unknown>;- tool_call_id: string;- description?: string;-}--/**- * Build a tool-approval interrupt payload from one or more paused tool calls.- *- * Mirrors the SDK's `ToolApprovalInterruptPayload` shape so this can be used- * to synthesize payloads in tests, or by the host before the SDK upgrade ships.- */-export function buildToolApprovalPayload(- toolCalls: ToolApprovalCallInput[],- decisionsByToolName?: Record<string, Agents.ToolApprovalDecisionType[]>,-): Agents.ToolApprovalInterruptPayload {- return {- type: 'tool_approval',- action_requests: toolCalls.map((tc) => ({- name: tc.name,- arguments: tc.arguments,- tool_call_id: tc.tool_call_id,- description: tc.description,- })),- review_configs: toolCalls.map((tc) => ({- action_name: tc.name,- tool_call_id: tc.tool_call_id,- allowed_decisions: decisionsByToolName?.[tc.name] ?? DEFAULT_REVIEW_DECISIONS,- })),- };-}-/** Require one uniquely identified review policy for every paused tool call. */export function isToolApprovalPayloadValid(payload: Agents.ToolApprovalInterruptPayload): boolean {if (payload.action_requests.length !== payload.review_configs.length) {diff --git a/packages/api/src/agents/steering/__tests__/request.spec.ts b/packages/api/src/agents/steering/__tests__/request.spec.tsindex 85958885a7..607d980abb 100644--- a/packages/api/src/agents/steering/__tests__/request.spec.ts+++ b/packages/api/src/agents/steering/__tests__/request.spec.ts@@ -1,11 +1,12 @@import type { IMongoFile } from '@librechat/data-schemas';import { InMemoryEventTransport } from '~/stream/implementations/InMemoryEventTransport';-import { buildPendingAction, buildToolApprovalPayload } from '~/agents/hitl/policy';import { handleSteerRequest, handleSteerCancel, handleSteerArm } from '../request';+import { buildToolApprovalPayload } from '~/agents/hitl/__fixtures__/approval';import { InMemoryJobStore } from '~/stream/implementations/InMemoryJobStore';import { isSteeringSupported, isSteerPreemptSupported } from '../runtime';import { STEER_QUEUE_MAX_DEPTH } from '~/stream/interfaces/IJobStore';import { GenerationJobManager } from '~/stream/GenerationJobManager';+import { buildPendingAction } from '~/agents/hitl/policy';jest.mock('../runtime', () => ({...jest.requireActual('../runtime'),diff --git a/packages/api/src/agents/triggers/engine.ts b/packages/api/src/agents/triggers/engine.tsindex 8785a6babb..569288d6dd 100644--- a/packages/api/src/agents/triggers/engine.ts+++ b/packages/api/src/agents/triggers/engine.ts@@ -101,7 +101,6 @@ export interface AgentTriggerDeliveryRecord {coalesceKey?: string;coalesceFrom?: Date;coalesceUntil?: Date;- batchSize?: number;batchBytes?: number;batchMemberIds?: Array<{ toString(): string } | string>;batchRootId?: { toString(): string } | string;diff --git a/packages/api/src/schedules/lifecycle.spec.ts b/packages/api/src/schedules/lifecycle.spec.tsindex f8623042ca..4849f408c8 100644--- a/packages/api/src/schedules/lifecycle.spec.ts+++ b/packages/api/src/schedules/lifecycle.spec.ts@@ -1,9 +1,10 @@import type { SchedulesServiceDeps } from './service';import { InMemoryEventTransport } from '~/stream/implementations/InMemoryEventTransport';import { createSchedulesService, recordScheduledMCPToolAuthFailure } from './service';-import { buildPendingAction, buildToolApprovalPayload } from '~/agents/hitl/policy';+import { buildToolApprovalPayload } from '~/agents/hitl/__fixtures__/approval';import { InMemoryJobStore } from '~/stream/implementations/InMemoryJobStore';import { GenerationJobManager } from '~/stream/GenerationJobManager';+import { buildPendingAction } from '~/agents/hitl/policy';import { ScheduledMCPBearerError } from './bearer';const scheduledFor = '2026-10-01T00:00:00.000Z';diff --git a/packages/api/src/stream/__tests__/generationSettled.spec.ts b/packages/api/src/stream/__tests__/generationSettled.spec.tsindex 473b548dce..55adb5e7f9 100644--- a/packages/api/src/stream/__tests__/generationSettled.spec.ts+++ b/packages/api/src/stream/__tests__/generationSettled.spec.ts@@ -4,7 +4,8 @@* the generation's owner — and a failing listener must never disturb cleanup.*/import type { GenerationSettledEvent } from '../GenerationJobManager';-import { buildPendingAction, buildToolApprovalPayload } from '~/agents/hitl/policy';+import { buildToolApprovalPayload } from '~/agents/hitl/__fixtures__/approval';+import { buildPendingAction } from '~/agents/hitl/policy';/** Suppress winston Console transport output (survives jest.resetModules) */jest.spyOn(console, 'log').mockImplementation();diff --git a/packages/api/src/stream/__tests__/idempotencyClaim.spec.ts b/packages/api/src/stream/__tests__/idempotencyClaim.spec.tsindex 117d858e30..ace6ad620f 100644--- a/packages/api/src/stream/__tests__/idempotencyClaim.spec.ts+++ b/packages/api/src/stream/__tests__/idempotencyClaim.spec.ts@@ -14,8 +14,9 @@ import {} from '~/stream/GenerationJobManager';import { InMemoryEventTransport } from '~/stream/implementations/InMemoryEventTransport';import { registerChunkPublicationCapability } from '~/stream/internal/chunkPublication';-import { buildPendingAction, buildToolApprovalPayload } from '~/agents/hitl/policy';+import { buildToolApprovalPayload } from '~/agents/hitl/__fixtures__/approval';import { InMemoryJobStore } from '~/stream/implementations/InMemoryJobStore';+import { buildPendingAction } from '~/agents/hitl/policy';jest.spyOn(console, 'log').mockImplementation();diff --git a/packages/api/src/stream/__tests__/pendingAction.spec.ts b/packages/api/src/stream/__tests__/pendingAction.spec.tsindex d1bb5df09d..4933cbb9a2 100644--- a/packages/api/src/stream/__tests__/pendingAction.spec.ts+++ b/packages/api/src/stream/__tests__/pendingAction.spec.ts@@ -5,9 +5,10 @@ import {} from '~/stream/interfaces/IJobStore';import { ApprovalLifecycle, PendingActionExpiredError } from '~/stream/ApprovalLifecycle';import { InMemoryEventTransport } from '~/stream/implementations/InMemoryEventTransport';-import { buildPendingAction, buildToolApprovalPayload } from '~/agents/hitl/policy';+import { buildToolApprovalPayload } from '~/agents/hitl/__fixtures__/approval';import { InMemoryJobStore } from '~/stream/implementations/InMemoryJobStore';import { GenerationJobManagerClass } from '~/stream/GenerationJobManager';+import { buildPendingAction } from '~/agents/hitl/policy';jest.spyOn(console, 'log').mockImplementation();diff --git a/packages/api/src/stream/__tests__/startup.spec.ts b/packages/api/src/stream/__tests__/startup.spec.tsindex fc78e718ea..a595f76974 100644--- a/packages/api/src/stream/__tests__/startup.spec.ts+++ b/packages/api/src/stream/__tests__/startup.spec.ts@@ -14,9 +14,10 @@ import {} from '~/stream/GenerationJobManager';import { InMemoryEventTransport } from '~/stream/implementations/InMemoryEventTransport';import { registerChunkPublicationCapability } from '~/stream/internal/chunkPublication';-import { buildPendingAction, buildToolApprovalPayload } from '~/agents/hitl/policy';import { GenerationPublicationFencedError } from '~/stream/interfaces/IJobStore';+import { buildToolApprovalPayload } from '~/agents/hitl/__fixtures__/approval';import { InMemoryJobStore } from '~/stream/implementations/InMemoryJobStore';+import { buildPendingAction } from '~/agents/hitl/policy';function createTelemetry(): jest.Mocked<AgentStartupTelemetry> {return {diff --git a/packages/api/src/stream/__tests__/steering.spec.ts b/packages/api/src/stream/__tests__/steering.spec.tsindex e1df4e1751..f97572c507 100644--- a/packages/api/src/stream/__tests__/steering.spec.ts+++ b/packages/api/src/stream/__tests__/steering.spec.ts@@ -15,8 +15,9 @@ import {import { PARKED_STEERS_TTL_MS, InMemoryJobStore } from '~/stream/implementations/InMemoryJobStore';import { synthesizeAppliedSteerEvents, toPendingSteer } from '~/stream/SteeringLifecycle';import { InMemoryEventTransport } from '~/stream/implementations/InMemoryEventTransport';-import { buildPendingAction, buildToolApprovalPayload } from '~/agents/hitl/policy';+import { buildToolApprovalPayload } from '~/agents/hitl/__fixtures__/approval';import { GenerationJobManagerClass } from '~/stream/GenerationJobManager';+import { buildPendingAction } from '~/agents/hitl/policy';jest.spyOn(console, 'log').mockImplementation();diff --git a/packages/api/src/stream/__tests__/terminalHostAction.spec.ts b/packages/api/src/stream/__tests__/terminalHostAction.spec.tsindex 80e0e5f91a..a8a535c2aa 100644--- a/packages/api/src/stream/__tests__/terminalHostAction.spec.ts+++ b/packages/api/src/stream/__tests__/terminalHostAction.spec.ts@@ -4,9 +4,10 @@ import {createAgentEventDetachedResumeHandler,} from '~/agents/triggers/detachedAction';import { InMemoryEventTransport } from '~/stream/implementations/InMemoryEventTransport';-import { buildPendingAction, buildToolApprovalPayload } from '~/agents/hitl/policy';+import { buildToolApprovalPayload } from '~/agents/hitl/__fixtures__/approval';import { InMemoryJobStore } from '~/stream/implementations/InMemoryJobStore';import { GenerationJobManagerClass } from '~/stream/GenerationJobManager';+import { buildPendingAction } from '~/agents/hitl/policy';describe('GenerationJobManager terminal host actions', () => {let manager: GenerationJobManagerClass;