Skip to content

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

🛶 fix: Preserve Canary Sync Resolutions (#16361)

Lia9dc8db0ea891
diff --git a/.github/scripts/playwright-matrix.test.mjs b/.github/scripts/playwright-matrix.test.mjs
index 346741a6d8..2a5d578ff8 100644
--- a/.github/scripts/playwright-matrix.test.mjs
+++ b/.github/scripts/playwright-matrix.test.mjs
@@ -100,6 +100,16 @@ test('nightly and default manual runs retain full-suite coverage on both stores'
assertPartition(defaults[1], 'redis', 'full', 2);
});
+test('PR and nightly matrices preserve both registered-email change modes on one memory shard', () => {
+ for (const matrix of [prMatrix, ...defaults]) {
+ const emailLanes = matrix.include.filter((lane) => lane.email_change === 'true');
+ assert.equal(emailLanes.length, 1);
+ assert.equal(emailLanes[0].stream_store, 'memory');
+ assert.match(emailLanes[0].shard, /^1\//);
+ }
+ assert.equal(shards.steps.filter((step) => step.if === "matrix.email_change == 'true'").length, 2);
+});
+
test('manual PR coverage opts into the PR fallback matrix without bypassing the PR author gate', () => {
assert.deepEqual(workflow.on.workflow_dispatch.inputs.coverage.options, ['full', 'pr']);
assert.match(
@@ -188,11 +198,12 @@ test('graduated spec skips keep the same pool across shards and remain opt-in',
test('the required gate still waits for all shards and rejects failures without fighting cancellation', () => {
const gate = workflow.jobs.e2e;
assert.equal(gate.name, 'e2e');
- assert.deepEqual(gate.needs, ['codegraph_select', 'e2e_shards', 'mcp_tool_list_changed']);
+ assert.deepEqual(gate.needs, ['codegraph_select', 'e2e_shards', 'mcp_tool_list_changed', 'mcp_apps']);
assert.equal(shards.strategy['fail-fast'], false);
assert.match(gate.if, /!cancelled\(\)/);
assert.match(shards.if, /!cancelled\(\)/);
assert.match(gate.steps[0].if, /needs\.e2e_shards\.result != 'success'/);
+ assert.match(gate.steps[0].if, /needs\.mcp_apps\.result != 'success'/);
assert.match(gate.steps[0].if, /needs\.mcp_tool_list_changed\.result != 'success'/);
assert.match(gate.steps[0].if, /needs\.codegraph_select\.outputs\.mcp_run == 'false'/);
assert.equal(gate.steps[0].run, 'exit 1');
diff --git a/.github/workflows/playwright-mock.yml b/.github/workflows/playwright-mock.yml
index eb28e256ce..ccfeac169a 100644
--- a/.github/workflows/playwright-mock.yml
+++ b/.github/workflows/playwright-mock.yml
@@ -70,7 +70,7 @@ jobs:
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
CHANGED: ${{ github.event.pull_request.changed_files }}
E2E_SKIP_ARMED: ${{ vars.CODEGRAPH_E2E_SKIP }}
- FULL_INCLUDE: '{"include":[{"name":"memory, shard 1/3","stream_store":"memory","redis_image":"","suite":"full","shard":"1/3","artifact":"memory-1-of-3","email_change":"true"},{"name":"memory, shard 2/3","stream_store":"memory","redis_image":"","suite":"full","shard":"2/3","artifact":"memory-2-of-3"},{"name":"memory, shard 3/3","stream_store":"memory","redis_image":"","suite":"full","shard":"3/3","artifact":"memory-3-of-3"},{"name":"redis transport","stream_store":"redis","redis_image":"redis:7-alpine","suite":"transport","shard":"","artifact":"redis-transport"}]}'
+ FULL_INCLUDE: '{"include":[{"name":"memory, shard 1/6","stream_store":"memory","redis_image":"","suite":"full","shard":"1/6","artifact":"memory-1-of-6","email_change":"true"},{"name":"memory, shard 2/6","stream_store":"memory","redis_image":"","suite":"full","shard":"2/6","artifact":"memory-2-of-6"},{"name":"memory, shard 3/6","stream_store":"memory","redis_image":"","suite":"full","shard":"3/6","artifact":"memory-3-of-6"},{"name":"memory, shard 4/6","stream_store":"memory","redis_image":"","suite":"full","shard":"4/6","artifact":"memory-4-of-6"},{"name":"memory, shard 5/6","stream_store":"memory","redis_image":"","suite":"full","shard":"5/6","artifact":"memory-5-of-6"},{"name":"memory, shard 6/6","stream_store":"memory","redis_image":"","suite":"full","shard":"6/6","artifact":"memory-6-of-6"},{"name":"redis transport, shard 1/2","stream_store":"redis","redis_image":"redis:7-alpine","suite":"transport","shard":"1/2","artifact":"redis-transport-1-of-2"},{"name":"redis transport, shard 2/2","stream_store":"redis","redis_image":"redis:7-alpine","suite":"transport","shard":"2/2","artifact":"redis-transport-2-of-2"}]}'
run: |
set +e
note() { echo "$1" >> "$GITHUB_STEP_SUMMARY"; }
@@ -177,8 +177,8 @@ jobs:
${{
(github.event_name == 'pull_request' && needs.codegraph_select.outputs.e2e_include != '' &&
fromJSON(needs.codegraph_select.outputs.e2e_include)) ||
- (github.event_name == 'pull_request' &&
- fromJSON('{"include":[{"name":"memory, shard 1/3","stream_store":"memory","redis_image":"","suite":"full","shard":"1/3","artifact":"memory-1-of-3","email_change":"true"},{"name":"memory, shard 2/3","stream_store":"memory","redis_image":"","suite":"full","shard":"2/3","artifact":"memory-2-of-3"},{"name":"memory, shard 3/3","stream_store":"memory","redis_image":"","suite":"full","shard":"3/3","artifact":"memory-3-of-3"},{"name":"redis transport","stream_store":"redis","redis_image":"redis:7-alpine","suite":"transport","shard":"","artifact":"redis-transport"}]}')) ||
+ ((github.event_name == 'pull_request' || inputs.coverage == 'pr') &&
+ fromJSON('{"include":[{"name":"memory, shard 1/6","stream_store":"memory","redis_image":"","suite":"full","shard":"1/6","artifact":"memory-1-of-6","email_change":"true"},{"name":"memory, shard 2/6","stream_store":"memory","redis_image":"","suite":"full","shard":"2/6","artifact":"memory-2-of-6"},{"name":"memory, shard 3/6","stream_store":"memory","redis_image":"","suite":"full","shard":"3/6","artifact":"memory-3-of-6"},{"name":"memory, shard 4/6","stream_store":"memory","redis_image":"","suite":"full","shard":"4/6","artifact":"memory-4-of-6"},{"name":"memory, shard 5/6","stream_store":"memory","redis_image":"","suite":"full","shard":"5/6","artifact":"memory-5-of-6"},{"name":"memory, shard 6/6","stream_store":"memory","redis_image":"","suite":"full","shard":"6/6","artifact":"memory-6-of-6"},{"name":"redis transport, shard 1/2","stream_store":"redis","redis_image":"redis:7-alpine","suite":"transport","shard":"1/2","artifact":"redis-transport-1-of-2"},{"name":"redis transport, shard 2/2","stream_store":"redis","redis_image":"redis:7-alpine","suite":"transport","shard":"2/2","artifact":"redis-transport-2-of-2"}]}')) ||
fromJSON('{"include":[{"name":"memory, shard 1/2","stream_store":"memory","redis_image":"","suite":"full","shard":"1/2","artifact":"memory-1-of-2","email_change":"true"},{"name":"memory, shard 2/2","stream_store":"memory","redis_image":"","suite":"full","shard":"2/2","artifact":"memory-2-of-2"},{"name":"redis, shard 1/2","stream_store":"redis","redis_image":"redis:7-alpine","suite":"full","shard":"1/2","artifact":"redis-1-of-2"},{"name":"redis, shard 2/2","stream_store":"redis","redis_image":"redis:7-alpine","suite":"full","shard":"2/2","artifact":"redis-2-of-2"}]}')
}}
services:
@@ -639,7 +639,7 @@ jobs:
# run superseded by `cancel-in-progress` has nothing to adjudicate. Under `always()` it was
# still dispatched onto a fresh runner while every other job went `cancelled`, then read
# `needs.e2e_shards.result == 'cancelled'` and exited 1 — so each superseded push left this
- # required check red instead of cancelled. Matches the two lanes it gates.
+ # required check red instead of cancelled. Matches all three lanes it gates.
if: >-
!cancelled() &&
(github.event_name == 'schedule' ||
diff --git a/api/app/clients/tools/util/handleTools.js b/api/app/clients/tools/util/handleTools.js
index a247f71323..0613f4df0d 100644
--- a/api/app/clients/tools/util/handleTools.js
+++ b/api/app/clients/tools/util/handleTools.js
@@ -666,89 +666,35 @@ const loadTools = async ({
}),
});
- for (const [serverName, toolConfigs] of Object.entries(requestedMCPTools)) {
- index++;
- /** @type {LCAvailableTools} */
- let availableTools = options.mcpAvailableTools?.[serverName];
- for (const config of toolConfigs) {
- try {
- if (failedMCPServers.has(serverName)) {
- continue;
- }
- const mcpParams = {
- mcpPermissionContext,
- index,
- signal,
- user: safeUser,
- userMCPAuthMap,
- configServers,
- requestBody: options.requestBody ?? options.req?.body,
- requestScopedConnections,
- res: options.res,
- upstreamTokenProvider,
- mcpApps: admittedMCPAppsPolicy,
- upstreamTokenProviderResolver,
- oboIdentityContext,
- streamId: options.req?._resumableStreamId || null,
- jobCreatedAt: options.jobCreatedAt,
- model: agent?.model ?? model,
- serverName: config.serverName,
- provider: agent?.provider ?? endpoint,
- config: config.config,
- };
-
- if (config.type === 'all' && toolConfigs.length === 1) {
- /** Handle async loading for single 'all' tool config */
- mcpToolPromises.push(
- createMCPTools(mcpParams).catch((error) => {
- logger.error(`Error loading ${serverName} tools:`, error);
- return null;
- }),
- );
- continue;
- }
- if (!availableTools) {
- try {
- availableTools = await getMCPServerTools(
- safeUser.id,
- serverName,
- config.config,
- capabilityProfile,
- );
- } catch (error) {
- logger.error(`Error fetching available tools for MCP server ${serverName}:`, error);
- }
- }
-
- /** Handle synchronous loading */
- const mcpTool =
- config.type === 'all'
- ? await createMCPTools(mcpParams)
- : await createMCPTool({
- ...mcpParams,
- availableTools,
- toolKey: config.toolKey,
- onAvailableTools: (tools) => {
- availableTools = tools;
- },
- });
-
- if (Array.isArray(mcpTool)) {
- loadedTools.push(...mcpTool);
- } else if (mcpTool) {
- loadedTools.push(mcpTool);
- } else {
- failedMCPServers.add(serverName);
- logger.warn(
- `MCP tool creation failed for "${config.toolKey}", server may be unavailable or unauthenticated.`,
- );
- }
- } catch (error) {
- logger.error(`Error loading MCP tool for server ${serverName}:`, error);
- }
- }
- }
- loadedTools.push(...(await Promise.all(mcpToolPromises)).flatMap((plugin) => plugin || []));
+ loadedTools.push(
+ ...(await loadMCPTools({
+ userId: user,
+ requestedTools: requestedMCPTools,
+ availableTools: options.mcpAvailableTools,
+ createTools: createMCPTools,
+ createTool: createMCPTool,
+ getAvailableTools: (userId, serverName, config) =>
+ getMCPServerTools(userId, serverName, config, capabilityProfile),
+ context: {
+ mcpPermissionContext,
+ signal,
+ user: safeUser,
+ userMCPAuthMap,
+ mcpApps: admittedMCPAppsPolicy,
+ configServers,
+ requestBody: options.requestBody ?? options.req?.body,
+ requestScopedConnections,
+ res: options.res,
+ upstreamTokenProvider,
+ upstreamTokenProviderResolver,
+ oboIdentityContext,
+ streamId: options.req?._resumableStreamId || null,
+ jobCreatedAt: options.jobCreatedAt,
+ model: agent?.model ?? model,
+ provider: agent?.provider ?? endpoint,
+ },
+ })),
+ );
return { loadedTools, toolContextMap, dynamicToolContextMap, primedCodeFiles };
};
diff --git a/api/server/controllers/agents/v1.js b/api/server/controllers/agents/v1.js
index 1e3dd11f14..bfa486c102 100644
--- a/api/server/controllers/agents/v1.js
+++ b/api/server/controllers/agents/v1.js
@@ -17,10 +17,7 @@ const {
replaceEdgeSourceId,
mergeDeploymentSkillIds,
getAgentListAccess,
- isFullAgentListAvatarCacheEntry,
getAgentListAvatarRefreshKey,
- refreshAgentListAvatarsBeforePage,
- refreshManagedAgentListPageAvatars,
mergeAgentOcrConversion,
sanitizeModelParameters,
collectToolResourceFileIds,
@@ -1841,16 +1838,6 @@ const getListAgentsHandler = async (req, res) => {
return res.json(data);
}
- const cachedRefresh = await refreshManagedAgentListPageAvatars({
- accessibleIds,
- agents,
- cachedEntry: cachedRefreshBeforePage,
- refreshS3Url,
- cacheSet: cache.set.bind(cache),
- cacheKey: refreshKey,
- ttl: Time.THIRTY_MINUTES,
- });
-
const accessibleSkillSet = canReturnSkillConfig
? null
: new Set(mergeDeploymentSkillIds(accessibleSkillIds).map((oid) => oid.toString()));
diff --git a/api/server/controllers/agents/v1.spec.js b/api/server/controllers/agents/v1.spec.js
index 80b71d7aa6..73fc387d96 100644
--- a/api/server/controllers/agents/v1.spec.js
+++ b/api/server/controllers/agents/v1.spec.js
@@ -4204,6 +4204,68 @@ describe('Agent Controllers - Mass Assignment Protection', () => {
});
});
+ test('refreshes only manager search results without writing or losing later cursor pages', async () => {
+ const db = require('~/models');
+ const name = 'Paged Manager Avatar';
+ const firstAgent = await Agent.create({
+ id: `agent_${nanoid(12)}`,
+ name,
+ provider: 'openai',
+ model: 'gpt-4',
+ author: userA,
+ avatar: { source: FileSources.s3, filepath: 'first.jpg' },
+ });
+ const secondAgent = await Agent.create({
+ id: `agent_${nanoid(12)}`,
+ name,
+ provider: 'openai',
+ model: 'gpt-4',
+ author: userA,
+ avatar: { source: FileSources.s3, filepath: 'second.jpg' },
+ });
+ await db.grantCapability({
+ principalType: PrincipalType.ROLE,
+ principalId: 'LIST_AVATAR_MANAGER',
+ capability: SystemCapabilities.MANAGE_AGENTS,
+ });
+ const mockReq = {
+ user: { id: userB.toString(), role: 'LIST_AVATAR_MANAGER', idOnTheSource: null },
+ query: { search: name, limit: '1' },
+ };
+ const mockRes = { status: jest.fn().mockReturnThis(), json: jest.fn().mockReturnThis() };
+ const listSpy = jest.spyOn(db, 'getListAgentsByAccess');
+ const updateSpy = jest.spyOn(db, 'updateAgent');
+ findAccessibleResources.mockResolvedValue([]);
+ findPubliclyAccessibleResources.mockResolvedValue([]);
+ refreshS3Url.mockImplementation(async ({ filepath }) => `signed:${filepath}`);
+
+ try {
+ await getListAgentsHandler(mockReq, mockRes);
+ const pageOne = mockRes.json.mock.calls[0][0];
+ expect(pageOne.data).toHaveLength(1);
+ expect(pageOne.after).toBeTruthy();
+ expect(pageOne.data[0].avatar.filepath).toMatch(/^signed:/);
+ expect(listSpy).toHaveBeenCalledTimes(1);
+ expect(refreshS3Url).toHaveBeenCalledTimes(1);
+ expect(updateSpy).not.toHaveBeenCalled();
+
+ mockRes.json.mockClear();
+ mockReq.query.cursor = pageOne.after;
+ await getListAgentsHandler(mockReq, mockRes);
+ const pageTwo = mockRes.json.mock.calls[0][0];
+ expect(pageTwo.data).toHaveLength(1);
+ expect([pageOne.data[0].id, pageTwo.data[0].id].sort()).toEqual(
+ [firstAgent.id, secondAgent.id].sort(),
+ );
+ expect(pageTwo.data[0].avatar.filepath).toMatch(/^signed:/);
+ expect(refreshS3Url).toHaveBeenCalledTimes(2);
+ expect(updateSpy).not.toHaveBeenCalled();
+ } finally {
+ listSpy.mockRestore();
+ updateSpy.mockRestore();
+ }
+ });
+
test('should skip avatar refresh if cache already covers the page', async () => {
/* Coverage is only coverage while it names the filepath it was taken for: a cached
URL for a replaced avatar is a link to a file the agent no longer shows. */
@@ -4332,8 +4394,7 @@ describe('Agent Controllers - Mass Assignment Protection', () => {
const responseData = mockRes.json.mock.calls[0][0];
const agent = responseData.data.find((a) => a.id === agentId);
- /** The refresh runs alongside the list query, so the refreshed path must reach the
- * response through `urlCache` rather than through what the list query read. */
+ /** The page was read before avatar refresh, so the new path must be applied from the cache. */
expect(agent.avatar.filepath).toBe('new-s3-path.jpg');
});
diff --git a/api/server/routes/config.js b/api/server/routes/config.js
index 38bfd4ee7f..6a585bfb2d 100644
--- a/api/server/routes/config.js
+++ b/api/server/routes/config.js
@@ -15,10 +15,11 @@ const {
isFileSnapshotEnabled,
getEndpointsDropParamsMap,
resolveCodeEnvironmentDecisionVersion,
- resolveCodeEnvironmentMoveVersion,
isPasskeyEnabled,
buildPreLoginInterface,
resolveMaxPasskeysPerUser,
+ resolveCodeEnvironmentMoveCapabilities,
+ resolveCodeEnvironmentTransitionVersion,
loadConversationListLimits,
} = require('@librechat/api');
const {
@@ -335,8 +336,10 @@ router.get('/', async function (req, res) {
appConfig?.mcpAppSandbox?.url,
appConfig?.mcpAppSandbox?.maxActiveViews,
appConfig?.mcpAppSandbox?.maxActionPreviewChars,
+ appConfig?.mcpAppSandbox?.operationLimits,
),
- ...(codeEnvironmentMoveVersion != null ? { codeEnvironmentMoveVersion } : {}),
+ ...codeEnvironmentMoveCapabilities,
+ ...(codeEnvironmentTransitionVersion != null ? { codeEnvironmentTransitionVersion } : {}),
...(cloudFront ? { cloudFront } : {}),
...(rum ? { rum } : {}),
fileUploadSseEnabled: isEnabled(process.env.FILE_UPLOAD_SSE_ENABLED),
diff --git a/api/server/routes/convos.js b/api/server/routes/convos.js
index dd2eb0249d..f901e48dbf 100644
--- a/api/server/routes/convos.js
+++ b/api/server/routes/convos.js
@@ -159,6 +159,14 @@ const markConvoSeenHandler = createMarkConvoSeenHandler({ markConvoSeen: db.mark
const markConvoUnreadHandler = createMarkConvoUnreadHandler({
markConvoUnread: db.markConvoUnread,
});
+const backgroundTaskPolicy = createBackgroundTaskPolicyMiddleware({ getAppConfig });
+const backgroundTaskIndexHandler = createBackgroundTaskIndexHandler({
+ registry: backgroundTaskRegistry,
+ pending: pendingBackgroundToolCompletions,
+});
+const backgroundTaskCancelHandler = createBackgroundTaskCancelHandler({
+ registry: backgroundTaskRegistry,
+});
router.use(requireJwtAuth);
const isValidProjectFilter = (projectId) =>
diff --git a/api/server/services/MCP.spec.js b/api/server/services/MCP.spec.js
index 622de2c12f..b1fc7814d3 100644
--- a/api/server/services/MCP.spec.js
+++ b/api/server/services/MCP.spec.js
@@ -1664,6 +1664,44 @@ describe('User parameter passing tests', () => {
).resolves.toBe('ordinary output');
});
+ it('records a typed OBO failure against the scheduled generation before returning an error', async () => {
+ const user = { id: 'scheduled-owner', role: 'USER' };
+ const missing = new Error('Unattended provider not configured');
+ const error = Object.assign(new Error('MCP tool error'), { cause: missing });
+ const receipt = require('~/server/services/Schedules').recordMCPToolAuthFailure;
+ require('~/models').getRoleByName.mockResolvedValue({
+ permissions: { [PermissionTypes.MCP_SERVERS]: { [Permissions.USE]: true } },
+ });
+ mockGetMCPManager.mockReturnValue({ callTool: jest.fn().mockRejectedValue(error) });
+ const tool = await createMCPTool({
+ user,
+ toolKey: `test-tool${D}test-server`,
+ provider: 'openai',
+ streamId: 'scheduled-conversation',
+ jobCreatedAt: 42,
+ config: { type: 'streamable-http', url: 'https://mcp.example.com' },
+ availableTools: {
+ [`test-tool${D}test-server`]: {
+ function: { description: 'Test MCP', parameters: { type: 'object', properties: {} } },
+ },
+ },
+ });
+ await expect(
+ tool.func({}, undefined, {
+ configurable: { user },
+ metadata: { provider: 'openai', thread_id: 'scheduled-conversation', run_id: 'run-1' },
+ toolCall: {},
+ }),
+ ).rejects.toThrow();
+ expect(receipt).toHaveBeenCalledWith({
+ error,
+ streamId: 'scheduled-conversation',
+ jobCreatedAt: 42,
+ userId: 'scheduled-owner',
+ serverName: 'test-server',
+ });
+ });
+
it('keeps shared OAuth recovery alive when one tool caller aborts', async () => {
const mockUser = { id: 'shared-recovery-user', role: 'USER' };
const mockRes = { write: jest.fn(), flush: jest.fn() };
diff --git a/api/server/services/Tools/mcp.js b/api/server/services/Tools/mcp.js
index 35dfeac193..8c721bf158 100644
--- a/api/server/services/Tools/mcp.js
+++ b/api/server/services/Tools/mcp.js
@@ -10,6 +10,7 @@ const {
isMCPInitializationError,
prepareMCPAuthorizationMutation,
resolveMCPClientCapabilityProfile,
+ recordScheduledMCPToolAuthFailure,
} = require('@librechat/api');
const { CacheKeys, Constants } = require('librechat-data-provider');
const { getMCPManager, getMCPServersRegistry, getFlowStateManager } = require('~/config');
@@ -159,6 +160,8 @@ async function reinitMCPServer({
oauthEnd,
recoveryPolicy,
mcpApps,
+ streamId,
+ jobCreatedAt,
}) {
const capabilityProfile = resolveMCPClientCapabilityProfile(mcpApps);
/** @type {MCPConnection | null} */
diff --git a/client/src/components/Chat/BackgroundTasks/Button.tsx b/client/src/components/Chat/BackgroundTasks/Button.tsx
index d6b102a1dc..f304526827 100644
--- a/client/src/components/Chat/BackgroundTasks/Button.tsx
+++ b/client/src/components/Chat/BackgroundTasks/Button.tsx
@@ -109,7 +109,12 @@ function BackgroundTasksButton({
{(activeCount > 0 || awaitingCount > 0 || failedCount > 0 || incomplete) && (
<span
aria-hidden="true"
- className="bg-status-info ring-presentation absolute -top-0.5 -right-0.5 size-2 animate-pulse rounded-full ring-2 motion-reduce:animate-none"
+ data-testid="background-tasks-indicator"
+ className={cn(
+ 'ring-presentation absolute -top-0.5 -right-0.5 size-2 rounded-full ring-2',
+ failedCount > 0 || incomplete ? 'bg-status-warning' : 'bg-status-info',
+ activeCount > 0 && 'animate-pulse motion-reduce:animate-none',
+ )}
/>
)}
</Ariakit.PopoverDisclosure>
@@ -151,7 +156,7 @@ function BackgroundTasksButton({
</div>
<div className="space-y-4 overflow-y-auto px-3 pb-3">
{incomplete && (
- <p role="status" className="text-sm text-status-warning">
+ <p role="status" className="text-status-warning text-sm">
{localize('com_ui_background_tasks_incomplete')}
</p>
)}
diff --git a/client/src/components/Chat/ChatView.tsx b/client/src/components/Chat/ChatView.tsx
index feaccb0b01..7cddaa218e 100644
--- a/client/src/components/Chat/ChatView.tsx
+++ b/client/src/components/Chat/ChatView.tsx
@@ -24,6 +24,7 @@ import {
useFileMapContext,
ComposerRestoreProvider,
} from '~/Providers';
+import { QueuedTurnPortalProvider } from './Steering/QueuedTurnPortal';
import ApprovalProvider from './Messages/Content/ApprovalContext';
import ConversationStarters from './Input/ConversationStarters';
import { pendingApprovalActionFamily } from './approval/state';
@@ -176,13 +177,14 @@ function ChatView({ index = 0, project }: { index?: number; project?: TChatProje
<AskAnswerHostProvider saveDrafts={saveDrafts}>
<ChatFormProvider {...methods}>
<ComposerRestoreProvider>
- <ChatContext.Provider value={chatHelpers}>
- <AddedChatContext.Provider value={addedChatHelpers}>
- <ApprovalProvider pendingAction={pendingAction}>
- <Presentation>
- <TraceSurface conversationId={conversationId}>
- <h1 className="sr-only">{pageHeading}</h1>
- {/* Marks the header's controls as this pane's, so a pane-scoped
+ <QueuedTurnPortalProvider>
+ <ChatContext.Provider value={chatHelpers}>
+ <AddedChatContext.Provider value={addedChatHelpers}>
+ <ApprovalProvider pendingAction={pendingAction}>
+ <Presentation>
+ <TraceSurface conversationId={conversationId}>
+ <h1 className="sr-only">{pageHeading}</h1>
+ {/* Marks the header's controls as this pane's, so a pane-scoped
shortcut pressed from them acts here, not on the first pane. */}
<div data-chat-pane-portal={index} className="contents">
<Header
@@ -222,49 +224,52 @@ function ChatView({ index = 0, project }: { index?: number; project?: TChatProje
popover ⇄ chat-card morph) paints the whole composer band
over the travelling card instead of letting it show
through below the composer. The background matches the
- page, so normal rendering is unchanged. */}
- <div
- className={cn(
- 'bg-surface-primary-alt w-full [view-transition-name:chat-form]',
- !isLandingPage && 'scrollbar-gutter-spacer',
- isLandingPage && 'max-w-3xl transition-all duration-200 xl:max-w-4xl',
- )}
- >
- {isLandingPage && <ConversationStarters />}
- {isSubagentThreadReadOnly ? (
- <div
- className="text-text-secondary mx-auto w-full max-w-3xl px-4 py-3 text-center text-sm xl:max-w-4xl"
- role="note"
- >
- {localize('com_ui_subagent_thread_read_only')}
- </div>
- ) : (
- <ChatForm
- index={index}
- placeholder={chatFormPlaceholder}
- project={isProjectLandingPage ? project : undefined}
- isLandingPage={isLandingPage}
- showComposerTips={showComposerTips}
- enterToSend={enterToSend}
- autoSendText={autoSendText}
- speechSettingsInitialized={speechSettingsInitialized}
- footerBelow={footerBelow}
- centerFormOnLanding={centerFormOnLanding}
- />
- )}
- {/* The generic disclaimer and the policy links are the
+ page, so normal rendering is unchanged. The named surface
+ is a stacking context; keep it above positioned tool glyphs
+ so they cannot paint through the approval preview. */}
+ <div
+ className={cn(
+ 'bg-surface-primary-alt relative z-10 w-full [view-transition-name:chat-form]',
+ !isLandingPage && 'scrollbar-gutter-spacer',
+ isLandingPage && 'max-w-3xl transition-all duration-200 xl:max-w-4xl',
+ )}
+ >
+ {isLandingPage && <ConversationStarters />}
+ {isSubagentThreadReadOnly ? (
+ <div
+ className="text-text-secondary mx-auto w-full max-w-3xl px-4 py-3 text-center text-sm xl:max-w-4xl"
+ role="note"
+ >
+ {localize('com_ui_subagent_thread_read_only')}
+ </div>
+ ) : (
+ <ChatForm
+ index={index}
+ placeholder={chatFormPlaceholder}
+ project={isProjectLandingPage ? project : undefined}
+ isLandingPage={isLandingPage}
+ showComposerTips={showComposerTips}
+ enterToSend={enterToSend}
+ autoSendText={autoSendText}
+ speechSettingsInitialized={speechSettingsInitialized}
+ footerBelow={footerBelow}
+ centerFormOnLanding={centerFormOnLanding}
+ />
+ )}
+ {/* The generic disclaimer and the policy links are the
welcome screen's; a deployment's own footer stays
with the conversation that always showed it. */}
- {!isLandingPage && configuredFooter && <Footer configuredOnly />}
+ {!isLandingPage && configuredFooter && <Footer configuredOnly />}
+ </div>
</div>
- </div>
- {isLandingPage && <Footer />}
- </>
- </TraceSurface>
- </Presentation>
- </ApprovalProvider>
- </AddedChatContext.Provider>
- </ChatContext.Provider>
+ {isLandingPage && <Footer />}
+ </>
+ </TraceSurface>
+ </Presentation>
+ </ApprovalProvider>
+ </AddedChatContext.Provider>
+ </ChatContext.Provider>
+ </QueuedTurnPortalProvider>
</ComposerRestoreProvider>
</ChatFormProvider>
</AskAnswerHostProvider>
diff --git a/client/src/components/Chat/Input/__tests__/QueuedTurnPortal.spec.tsx b/client/src/components/Chat/Input/__tests__/QueuedTurnPortal.spec.tsx
index 2fa54aaa93..e658271345 100644
--- a/client/src/components/Chat/Input/__tests__/QueuedTurnPortal.spec.tsx
+++ b/client/src/components/Chat/Input/__tests__/QueuedTurnPortal.spec.tsx
@@ -1,33 +1,19 @@
import React from 'react';
-import { RecoilRoot, useSetRecoilState } from 'recoil';
+import { RecoilRoot } from 'recoil';
import { EModelEndpoint } from 'librechat-data-provider';
+import { act, render, screen } from '@testing-library/react';
import { Provider as JotaiProvider, createStore } from 'jotai';
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
-import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
-import type { TConversation, TMessage } from 'librechat-data-provider';
-import type { SteeringControls } from '~/hooks/Chat/useSteering';
-import type { RevealedQueuedTurn } from '~/store/steer';
-import type { QueuedMessage } from '~/store/families';
-import { QueuedTurnPortalProvider } from '~/components/Chat/Steering/QueuedTurnPortal';
+import type { TConversation } from 'librechat-data-provider';
+import {
+ QueuedTurnPortalProvider,
+ useQueuedTurnPortal,
+} from '~/components/Chat/Steering/QueuedTurnPortal';
import PendingTurn from '~/components/Chat/Messages/PendingTurn';
import { revealedQueuedTurnFamily } from '~/store/steer';
-import PendingSteerChips from '../PendingSteerChips';
import { ChatContext } from '~/Providers';
-import store from '~/store';
-
-const CONVO_ID = 'convo-queued-turn';
-const RESPONSE_ID = 'completed-response';
-const removeQueued = jest.fn();
-const discardQueued = jest.fn(async (_message: QueuedMessage) => true);
-const restoreToComposer = jest.fn(() => true);
-const editToComposer = jest.fn();
-const sendQueuedNow = jest.fn();
-const mockShowToast = jest.fn();
jest.mock('~/hooks', () => ({ useLocalize: () => (key: string) => key }));
-jest.mock('~/hooks/AuthContext', () => ({
- useAuthContext: () => ({ user: { name: 'Danny' } }),
-}));
+jest.mock('~/hooks/AuthContext', () => ({ useAuthContext: () => ({ user: { name: 'Danny' } }) }));
jest.mock('~/components/Chat/Messages/MessageIcon', () => ({
__esModule: true,
default: () => <span data-testid="message-icon" />,
@@ -36,215 +22,52 @@ jest.mock('~/components/Chat/Messages/Content/Container', () => ({
__esModule: true,
default: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
}));
-jest.mock('~/components/Chat/Messages/Content/MarkdownLite', () => ({
- __esModule: true,
- default: ({ content }: { content: string }) => <span>{content}</span>,
-}));
-jest.mock('@librechat/client', () => {
- const { createSteerMorphIconMock } = jest.requireActual('~/../test/mockMorphIcon');
- return {
- useToastContext: () => ({ showToast: mockShowToast }),
- TooltipAnchor: jest.requireActual('@librechat/client').TooltipAnchor,
- MorphIcon: createSteerMorphIconMock(),
- };
-});
+const conversationId = 'convo-queued-turn';
const conversation = {
- conversationId: CONVO_ID,
+ conversationId,
endpoint: EModelEndpoint.agents,
model: 'gpt-x',
} as TConversation;
-const serverRow = (requestId: string, status: 'queued' | 'claimed' = 'queued'): QueuedMessage => ({
- id: `row-${requestId}`,
- text: `queued ${requestId}`,
- createdAt: 1,
- clientRequestId: requestId,
- server: { id: `server-${requestId}`, status, revision: 1 },
-});
-
-const reveal = (requestId: string): RevealedQueuedTurn => ({
- clientRequestId: requestId,
- parentMessageId: RESPONSE_ID,
- text: `queued ${requestId}`,
- revealedAt: '2026-09-14T00:00:00.000Z',
-});
-
-function QueueState({ onSet }: { onSet: (setter: (id: string) => void) => void }) {
- const setQueue = useSetRecoilState(store.queuedMessagesByConvoId(CONVO_ID));
- onSet((id) => setQueue((items) => items.filter((item) => item.id !== id)));
- return null;
+function PortalTarget() {
+ const target = useQueuedTurnPortal()?.target;
+ return <span data-testid="portal-target">{target?.clientRequestId ?? ''}</span>;
}
-function renderQueue(rows: QueuedMessage[], latestMessageId = RESPONSE_ID) {
- const jotaiStore = createStore();
- const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
- const steering = {
- queueKey: CONVO_ID,
- defaultAction: 'steer',
- duringRunActive: false,
- canSendQueuedNow: true,
- canSteer: false,
- pausedOnApproval: false,
- removeQueued,
- discardQueued,
- sendQueuedNow,
- setDefaultAction: jest.fn(),
- } as unknown as SteeringControls;
- let setQueueById: (id: string) => void = () => undefined;
- removeQueued.mockImplementation((id: string) => setQueueById(id));
- const view = (tail: string, messages?: TMessage[]) => (
- <QueryClientProvider client={queryClient}>
- <RecoilRoot initializeState={({ set }) => set(store.queuedMessagesByConvoId(CONVO_ID), rows)}>
- <JotaiProvider store={jotaiStore}>
- <ChatContext.Provider
- value={
- { conversation, latestMessageId: tail, index: 0 } as React.ContextType<
- typeof ChatContext
- >
- }
- >
- <QueuedTurnPortalProvider>
- <PendingTurn messages={messages} />
- <PendingSteerChips
- conversationId={CONVO_ID}
- steering={steering}
- onEditToComposer={editToComposer}
- onRestoreToComposer={restoreToComposer}
- />
- <QueueState onSet={(setter) => (setQueueById = setter)} />
- </QueuedTurnPortalProvider>
- </ChatContext.Provider>
- </JotaiProvider>
- </RecoilRoot>
- </QueryClientProvider>
- );
- const result = render(view(latestMessageId));
- return {
- jotaiStore,
- renderView: (tail: string, messages?: TMessage[]) => result.rerender(view(tail, messages)),
+it('registers the revealed user turn action target only while it is visible', () => {
+ const jotai = createStore();
+ const reveal = {
+ clientRequestId: 'queued-request',
+ parentMessageId: 'response',
+ text: 'queued follow-up',
+ revealedAt: '2026-09-14T00:00:00.000Z',
};
-}
-
-describe('queued starting turn controls', () => {
- beforeEach(() => {
- jest.clearAllMocks();
- });
-
- it('replaces only the matching queue row with a user turn carrying Edit and Remove', () => {
- const { jotaiStore } = renderQueue([serverRow('first'), serverRow('second')]);
- expect(screen.getAllByTestId('queued-message-row')).toHaveLength(2);
-
- act(() => jotaiStore.set(revealedQueuedTurnFamily(CONVO_ID), reveal('first')));
-
- const turn = screen.getByTestId('pending-turn');
- expect(turn).toHaveTextContent('queued first');
- expect(within(turn).getByRole('status')).toHaveTextContent('com_ui_queued_turn_starting');
- expect(within(turn).getByRole('button', { name: 'com_ui_edit_message' })).toBeEnabled();
- expect(within(turn).getByRole('button', { name: 'com_ui_remove_queued' })).toBeEnabled();
- expect(within(turn).queryByRole('button', { name: 'com_ui_send_now' })).toBeNull();
- expect(screen.getAllByTestId('queued-message-row')).toHaveLength(1);
- expect(screen.getByTestId('queued-message-row')).toHaveTextContent('queued second');
- expect(screen.getAllByText('queued first')).toHaveLength(1);
- });
-
- it('edits a starting turn only after cancelling its durable copy', async () => {
- const row = {
- ...serverRow('first'),
- files: [{ file_id: 'file-1' }],
- quotes: ['quote'],
- manualSkills: ['skill'],
- };
- const { jotaiStore } = renderQueue([row]);
- act(() => jotaiStore.set(revealedQueuedTurnFamily(CONVO_ID), reveal('first')));
- fireEvent.click(screen.getByRole('button', { name: 'com_ui_edit_message' }));
-
- await waitFor(() => expect(discardQueued).toHaveBeenCalledWith(row));
- await waitFor(() => expect(removeQueued).toHaveBeenCalledWith(row.id));
- expect(restoreToComposer).toHaveBeenCalledWith(
- row.text,
- row.files,
- { quotes: ['quote'], manualSkills: ['skill'] },
- CONVO_ID,
- );
- expect(editToComposer).not.toHaveBeenCalled();
- });
-
- it('keeps a claimed turn removable but never offers edit or a second send', () => {
- const { jotaiStore } = renderQueue([serverRow('first', 'claimed')]);
- act(() => jotaiStore.set(revealedQueuedTurnFamily(CONVO_ID), reveal('first')));
-
- const turn = screen.getByTestId('pending-turn');
- expect(within(turn).queryByRole('button', { name: 'com_ui_edit_message' })).toBeNull();
- expect(within(turn).getByRole('button', { name: 'com_ui_remove_queued' })).toBeEnabled();
- expect(screen.queryByTestId('pending-steer-chips')).toBeNull();
- expect(sendQueuedNow).not.toHaveBeenCalled();
- });
-
- it('does not lose the in-flight cancellation lock when the row moves to the turn', async () => {
- let finish: (accepted: boolean) => void = () => undefined;
- discardQueued.mockImplementationOnce(
- () => new Promise<boolean>((resolve) => (finish = resolve)),
- );
- const { jotaiStore } = renderQueue([serverRow('first')]);
- fireEvent.click(screen.getByRole('button', { name: 'com_ui_remove_queued' }));
- expect(discardQueued).toHaveBeenCalledTimes(1);
-
- act(() => jotaiStore.set(revealedQueuedTurnFamily(CONVO_ID), reveal('first')));
- const turn = screen.getByTestId('pending-turn');
- expect(within(turn).getByRole('button', { name: 'com_ui_remove_queued' })).toBeDisabled();
- expect(within(turn).getByRole('button', { name: 'com_ui_edit_message' })).toBeDisabled();
- fireEvent.click(within(turn).getByRole('button', { name: 'com_ui_remove_queued' }));
- expect(discardQueued).toHaveBeenCalledTimes(1);
-
- await act(async () => finish(false));
- expect(within(turn).getByRole('button', { name: 'com_ui_remove_queued' })).toBeEnabled();
- expect(removeQueued).not.toHaveBeenCalled();
- expect(restoreToComposer).not.toHaveBeenCalled();
- });
-
- it('restores the full context after confirmed removal, never on failed cancellation', async () => {
- const row = {
- ...serverRow('first'),
- files: [{ file_id: 'file-1' }],
- quotes: ['q'],
- manualSkills: ['s'],
- };
- discardQueued.mockResolvedValueOnce(false).mockResolvedValueOnce(true);
- const { jotaiStore } = renderQueue([row]);
- act(() => jotaiStore.set(revealedQueuedTurnFamily(CONVO_ID), reveal('first')));
- const remove = screen.getByRole('button', { name: 'com_ui_remove_queued' });
-
- fireEvent.click(remove);
- await waitFor(() => expect(remove).toBeEnabled());
- expect(restoreToComposer).not.toHaveBeenCalled();
- expect(removeQueued).not.toHaveBeenCalled();
-
- fireEvent.click(remove);
- await waitFor(() => expect(removeQueued).toHaveBeenCalledWith(row.id));
- expect(restoreToComposer).toHaveBeenCalledWith(
- row.text,
- row.files,
- { quotes: ['q'], manualSkills: ['s'] },
- CONVO_ID,
- );
- act(() => jotaiStore.set(revealedQueuedTurnFamily(CONVO_ID), null));
- expect(screen.queryByTestId('pending-turn')).toBeNull();
- expect(screen.queryByTestId('queued-message-row')).toBeNull();
- });
-
- it('returns the queue row when the bubble is hidden by a different tail or real successor', () => {
- const { jotaiStore, renderView } = renderQueue([serverRow('first')]);
- act(() => jotaiStore.set(revealedQueuedTurnFamily(CONVO_ID), reveal('first')));
- expect(screen.queryByTestId('queued-message-row')).toBeNull();
+ jotai.set(revealedQueuedTurnFamily(conversationId), reveal);
+ const view = (latestMessageId: string) => (
+ <RecoilRoot>
+ <JotaiProvider store={jotai}>
+ <ChatContext.Provider
+ value={
+ { conversation, latestMessageId, index: 0 } as React.ContextType<typeof ChatContext>
+ }
+ >
+ <QueuedTurnPortalProvider>
+ <PendingTurn />
+ <PortalTarget />
+ </QueuedTurnPortalProvider>
+ </ChatContext.Provider>
+ </JotaiProvider>
+ </RecoilRoot>
+ );
+ const { rerender } = render(view('response'));
+ expect(screen.getByTestId('pending-turn')).toHaveTextContent('queued follow-up');
+ expect(screen.getByTestId('portal-target')).toHaveTextContent('queued-request');
- renderView('another-response');
- expect(screen.queryByTestId('pending-turn')).toBeNull();
- expect(screen.getByTestId('queued-message-row')).toHaveTextContent('queued first');
+ rerender(view('different-branch'));
+ expect(screen.queryByTestId('pending-turn')).toBeNull();
+ expect(screen.getByTestId('portal-target')).toBeEmptyDOMElement();
- renderView(RESPONSE_ID, [{ messageId: 'real-user', parentMessageId: RESPONSE_ID } as TMessage]);
- expect(screen.queryByTestId('pending-turn')).toBeNull();
- expect(screen.getByTestId('queued-message-row')).toHaveTextContent('queued first');
- expect(sendQueuedNow).not.toHaveBeenCalled();
- });
+ act(() => jotai.set(revealedQueuedTurnFamily(conversationId), null));
+ expect(screen.getByTestId('portal-target')).toBeEmptyDOMElement();
});
diff --git a/client/src/components/Chat/Messages/Content/Parts/BackgroundTaskCall.tsx b/client/src/components/Chat/Messages/Content/Parts/BackgroundTaskCall.tsx
index bcbaa5d939..7488d9e868 100644
--- a/client/src/components/Chat/Messages/Content/Parts/BackgroundTaskCall.tsx
+++ b/client/src/components/Chat/Messages/Content/Parts/BackgroundTaskCall.tsx
@@ -7,6 +7,7 @@ import { useMCPIconMap, useMCPServerNames } from '~/hooks/MCP';
import { useLocalize, useLazyCollapseBody } from '~/hooks';
import { toolPanelSpacingClassName } from '../disclosure';
import { ToolIcon, OutputRenderer } from '../ToolOutput';
+import { MCPAppViews } from '~/components/MCPUIResource';
import BackgroundTaskCard from '../BackgroundTaskCard';
import useToolCallState from './useToolCallState';
import { AttachmentGroup } from './Attachment';
@@ -135,7 +136,7 @@ export default function BackgroundTaskCall({
<div
className={cn(
toolPanelSpacingClassName,
- 'overflow-hidden rounded-lg border border-border-light bg-surface-secondary',
+ 'border-border-light bg-surface-secondary overflow-hidden rounded-lg border',
)}
>
{display?.kind === 'task' && (
@@ -149,9 +150,9 @@ export default function BackgroundTaskCall({
)}
{display?.kind === 'list' && (
<div className="p-2.5">
- <div className="mb-2 flex items-center gap-2 text-xs font-medium text-text-secondary">
+ <div className="text-text-secondary mb-2 flex items-center gap-2 text-xs font-medium">
{localize('com_ui_background_tasks')}
- <span className="rounded-full bg-surface-tertiary px-1.5 tabular-nums">
+ <span className="bg-surface-tertiary rounded-full px-1.5 tabular-nums">
{display.tasks.length}
</span>
</div>
@@ -159,7 +160,7 @@ export default function BackgroundTaskCall({
<ul
tabIndex={0}
aria-label={localize('com_ui_background_tasks')}
- className="flex max-h-96 flex-col gap-2 overflow-y-auto pr-1 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-heavy"
+ className="focus-visible:ring-border-heavy flex max-h-96 flex-col gap-2 overflow-y-auto pr-1 focus-visible:ring-2 focus-visible:outline-none"
>
{display.tasks.map((task) => (
<li key={task.taskId}>
@@ -172,17 +173,17 @@ export default function BackgroundTaskCall({
))}
</ul>
) : (
- <p className="text-sm text-text-secondary">
+ <p className="text-text-secondary text-sm">
{localize('com_ui_background_tasks_empty')}
</p>
)}
{(display.partial || display.warning) && (
- <p role="alert" className="mt-2 text-xs text-status-warning">
+ <p role="alert" className="text-status-warning mt-2 text-xs">
{localize('com_ui_background_tasks_incomplete')}
</p>
)}
{listGuidance.map((key) => (
- <p key={key} className="mt-2 text-xs text-text-secondary">
+ <p key={key} className="text-text-secondary mt-2 text-xs">
{localize(key)}
</p>
))}
@@ -201,24 +202,20 @@ export default function BackgroundTaskCall({
</p>
)}
{(display == null || hasParams) && (
- <div className={cn(display != null && 'border-t border-border-light')}>
- <ToolCallInfo
- input={input}
- output={display == null ? output : undefined}
- attachments={attachments}
- />
+ <div className={cn(display != null && 'border-border-light border-t')}>
+ <ToolCallInfo input={input} output={display == null ? output : undefined} />
</div>
)}
{display != null && (
<details
- className="border-t border-border-light px-3 py-2"
+ className="border-border-light border-t px-3 py-2"
onToggle={(event) => setShowRaw(event.currentTarget.open)}
>
- <summary className="cursor-pointer rounded text-xs text-text-secondary hover:text-text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-heavy">
+ <summary className="text-text-secondary hover:text-text-primary focus-visible:ring-border-heavy cursor-pointer rounded text-xs focus-visible:ring-2 focus-visible:outline-none">
{localize('com_ui_background_tasks_raw_details')}
</summary>
{showRaw && (
- <div className="mt-2 rounded-md bg-surface-primary p-2.5">
+ <div className="bg-surface-primary mt-2 rounded-md p-2.5">
<OutputRenderer text={output} copyText={output} />
</div>
)}
@@ -229,7 +226,10 @@ export default function BackgroundTaskCall({
</div>
</div>
{!hideAttachments && attachments && attachments.length > 0 && (
- <AttachmentGroup attachments={attachments} />
+ <>
+ <AttachmentGroup attachments={attachments} />
+ <MCPAppViews attachments={attachments} />
+ </>
)}
</>
);
diff --git a/client/src/components/Chat/Messages/Content/Parts/Reasoning.tsx b/client/src/components/Chat/Messages/Content/Parts/Reasoning.tsx
index e2fc0e1e29..57e577dff7 100644
--- a/client/src/components/Chat/Messages/Content/Parts/Reasoning.tsx
+++ b/client/src/components/Chat/Messages/Content/Parts/Reasoning.tsx
@@ -90,6 +90,7 @@ export const StreamingThoughtPeek = memo(({ text }: { text: string }) => {
<div
aria-hidden="true"
className="border-border-light mt-1 overflow-hidden rounded-2xl border px-4 py-3"
+ data-testid="streaming-thought-peek"
>
<div
ref={ref}
diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/BackgroundTaskCall.test.tsx b/client/src/components/Chat/Messages/Content/Parts/__tests__/BackgroundTaskCall.test.tsx
index 0f1f6921e6..dd613c8782 100644
--- a/client/src/components/Chat/Messages/Content/Parts/__tests__/BackgroundTaskCall.test.tsx
+++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/BackgroundTaskCall.test.tsx
@@ -74,6 +74,12 @@ jest.mock('../Attachment', () => ({
AttachmentGroup: () => <div data-testid="task-attachments" />,
}));
+jest.mock('~/components/MCPUIResource', () => ({
+ MCPAppViews: ({ attachments }: { attachments?: unknown[] }) => (
+ <div data-testid="task-app-views" data-count={attachments?.length ?? 0} />
+ ),
+}));
+
const completed = {
background_task_id: 'bg-1',
tool: 'bash_tool',
@@ -99,6 +105,27 @@ function renderCall(
}
describe('BackgroundTaskCall', () => {
+ it('renders App attachments once on a standalone card and leaves grouped cards to their parent', () => {
+ const attachments = [{ type: 'ui_resources' }] as NonNullable<
+ React.ComponentProps<typeof BackgroundTaskCall>['attachments']
+ >;
+ const { rerender } = renderCall(JSON.stringify(completed), { attachments });
+ expect(screen.getByTestId('task-app-views')).toHaveAttribute('data-count', '1');
+
+ rerender(
+ <RecoilRoot>
+ <BackgroundTaskCall
+ args={'{"background_task_id":"bg-1"}'}
+ output={JSON.stringify(completed)}
+ isSubmitting={false}
+ attachments={attachments}
+ hideAttachments
+ />
+ </RecoilRoot>,
+ );
+ expect(screen.queryByTestId('task-app-views')).not.toBeInTheDocument();
+ });
+
it('presents a completed code task as a native result without leaking its JSON envelope', () => {
renderCall(JSON.stringify(completed));
const header = screen.getByTestId('task-header');
diff --git a/client/src/components/Chat/Messages/Content/Wakeup.tsx b/client/src/components/Chat/Messages/Content/Wakeup.tsx
index c7cb63b8b2..59343eb184 100644
--- a/client/src/components/Chat/Messages/Content/Wakeup.tsx
+++ b/client/src/components/Chat/Messages/Content/Wakeup.tsx
@@ -223,17 +223,29 @@ const Wakeup = memo(function Wakeup({
{shouldRenderBody && (
<div className="overflow-hidden" ref={expandRef}>
<div className="pb-1">
- <div className="text-text-secondary mt-1 text-xs">
- {localize('com_ui_wakeup_explainer')}
- </div>
- {display.tasks.map((task) => (
- <WakeupTaskCard
- key={task.taskId}
- task={task}
- kind={display.kind}
- conversationId={conversationId}
- />
- ))}
+ {display.kind === 'subagent' && (
+ <div className="text-text-secondary mt-1 text-xs">
+ {localize('com_ui_wakeup_explainer')}
+ </div>
+ )}
+ {display.tasks.map((task) =>
+ display.kind === 'background_tool' ? (
+ <div key={task.taskId} className="my-2">
+ <BackgroundTaskCard
+ task={{
+ taskId: task.taskId,
+ toolName: task.toolName ?? '',
+ status: task.status,
+ result: task.result,
+ }}
+ mcpIconMap={mcpIconMap}
+ mcpServerNames={mcpServerNames}
+ />
+ </div>
+ ) : (
+ <WakeupTaskCard key={task.taskId} task={task} conversationId={conversationId} />
+ ),
+ )}
</div>
</div>
)}
diff --git a/client/src/components/Conversations/Conversations.tsx b/client/src/components/Conversations/Conversations.tsx
index be4dce2c64..4e21b8307b 100644
--- a/client/src/components/Conversations/Conversations.tsx
+++ b/client/src/components/Conversations/Conversations.tsx
@@ -33,6 +33,7 @@ import {
useUnpinDroppedConversation,
} from './dnd';
import { useLocalize, TranslationKeys, useElementSize, useOuterScrollWindow } from '~/hooks';
+import { groupConversationsWithRunning, RUNNING_CHATS_GROUP } from './running';
import { facetFilterCountAtom, resetFacetsAtom } from './facets';
import { groupConversations, cn } from '~/utils';
import { useActiveJobs } from '~/data-provider';
@@ -172,10 +173,14 @@ const DateLabel: FC<{ groupName: string; isFirst?: boolean; isAlphabetical?: boo
const displayName = localize(groupName as TranslationKeys) || groupName;
return (
<h2
- aria-label={localize(
- isAlphabetical ? 'com_a11y_chats_alpha_section' : 'com_a11y_chats_date_section',
- isAlphabetical ? { letter: displayName } : { date: displayName },
- )}
+ aria-label={
+ groupName === RUNNING_CHATS_GROUP
+ ? localize('com_a11y_chats_running_section')
+ : localize(
+ isAlphabetical ? 'com_a11y_chats_alpha_section' : 'com_a11y_chats_date_section',
+ isAlphabetical ? { letter: displayName } : { date: displayName },
+ )
+ }
className={cn(
'text-text-secondary pt-0.5 pl-1 text-xs',
isFirst === true ? 'mt-0' : 'mt-1.5',
diff --git a/client/src/components/SidePanel/Schedules/ScheduleCard.tsx b/client/src/components/SidePanel/Schedules/ScheduleCard.tsx
index bae0842d0e..b3d5898bf5 100644
--- a/client/src/components/SidePanel/Schedules/ScheduleCard.tsx
+++ b/client/src/components/SidePanel/Schedules/ScheduleCard.tsx
@@ -396,7 +396,9 @@ export default function ScheduleCard({ schedule, projectName }: ScheduleCardProp
to get an MCP server back. A healthy schedule shows neither. */}
{schedule.disabledReason != null && (
<div className="mt-1.5">
- <Chip tone="error">{localize(DISABLED_REASON_LABELS[schedule.disabledReason])}</Chip>
+ <Chip tone="error">
+ {localize(disabledMCPLabel ?? DISABLED_REASON_LABELS[schedule.disabledReason])}
+ </Chip>
</div>
)}
<ScheduleMCPRecovery
diff --git a/client/src/components/UnifiedSidebar/__tests__/ConversationsSection.spec.tsx b/client/src/components/UnifiedSidebar/__tests__/ConversationsSection.spec.tsx
index 4fc5b35d20..b7701396e1 100644
--- a/client/src/components/UnifiedSidebar/__tests__/ConversationsSection.spec.tsx
+++ b/client/src/components/UnifiedSidebar/__tests__/ConversationsSection.spec.tsx
@@ -126,9 +126,28 @@ jest.mock('~/components/Conversations', () => {
const { memo } = jest.requireActual('react');
const ConversationsStub = memo(function ConversationsStub(props: {
accountHasProjects?: boolean;
+ conversations: Array<{ conversationId: string; title: string }>;
+ isSearchLoading: boolean;
+ isError: boolean;
+ onRetry: () => void;
}) {
+ const { conversations, isSearchLoading, isError, onRetry } = props;
mockConversationsRender(props);
- return <div data-testid="conversations-stub" />;
+ const localize: (key: string) => string = jest.requireMock('~/hooks').useLocalize();
+ let body: React.ReactNode = conversations.map((convo) => (
+ <span key={convo.conversationId}>{convo.title}</span>
+ ));
+ if (isError && conversations.length === 0) {
+ body = (
+ <button type="button" onClick={onRetry}>
+ {localize('com_ui_retry')}
+ </button>
+ );
+ }
+ if (isSearchLoading) {
+ body = <div data-testid="search-spinner" />;
+ }
+ return <div data-testid="conversations-stub">{body}</div>;
});
return { __esModule: true, Conversations: ConversationsStub };
});
@@ -382,6 +401,153 @@ describe('ConversationsSection empty Chats wording', () => {
});
});
+describe('ConversationsSection search refetch', () => {
+ it('does not display old matches as unfiltered chats while clearing the search', async () => {
+ const previousData = mockConversationsResult.data;
+ mockConversationsResult.data = {
+ pages: [
+ {
+ conversations: [{ conversationId: 'chat-1', title: 'Old search match' }],
+ nextCursor: null,
+ },
+ ],
+ };
+
+ try {
+ renderSection('draft');
+ await settleRenders();
+ expect(screen.getByText('Old search match')).toBeInTheDocument();
+
+ act(() => {
+ setSearchState({
+ query: '',
+ debouncedQuery: 'draft',
+ enabled: true,
+ isTyping: true,
+ isSearching: false,
+ });
+ });
+
+ expect(screen.getByTestId('projects-stub')).toBeInTheDocument();
+ expect(screen.queryByText('Old search match')).not.toBeInTheDocument();
+ expect(screen.getByTestId('search-spinner')).toBeInTheDocument();
+ } finally {
+ mockConversationsResult.data = previousData;
+ }
+ });
+
+ it('shows progress while retrying a failed cached search with no results', async () => {
+ const previousData = mockConversationsResult.data;
+ mockConversationsResult.isError = true;
+
+ try {
+ renderSection('draft');
+ await settleRenders();
+ expect(screen.getByRole('button', { name: 'com_ui_retry' })).toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_retry' }));
+ expect(mockConversationsResult.refetch).toHaveBeenCalledTimes(1);
+
+ act(() => {
+ mockConversationsResult.isFetching = true;
+ setStreamTick((prev) => prev + 1);
+ });
+
+ expect(screen.getByTestId('search-spinner')).toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'com_ui_retry' })).not.toBeInTheDocument();
+
+ act(() => {
+ mockConversationsResult.isFetching = false;
+ mockConversationsResult.isError = false;
+ mockConversationsResult.data = {
+ pages: [
+ {
+ conversations: [{ conversationId: 'chat-1', title: 'Found match' }],
+ nextCursor: null,
+ },
+ ],
+ };
+ setStreamTick((prev) => prev + 1);
+ });
+
+ expect(screen.getByText('Found match')).toBeInTheDocument();
+ expect(screen.queryByTestId('search-spinner')).not.toBeInTheDocument();
+ } finally {
+ mockConversationsResult.data = previousData;
+ mockConversationsResult.isError = false;
+ mockConversationsResult.isFetching = false;
+ mockConversationsResult.refetch.mockClear();
+ }
+ });
+
+ it('shows loading for an uncached search', async () => {
+ const previousData = mockConversationsResult.data;
+ mockConversationsResult.data = undefined;
+ mockConversationsResult.isLoading = true;
+
+ try {
+ renderSection('draft');
+ await settleRenders();
+ expect(screen.getByTestId('search-spinner')).toBeInTheDocument();
+ } finally {
+ mockConversationsResult.data = previousData;
+ mockConversationsResult.isLoading = false;
+ }
+ });
+
+ it('does not show results from the previous search while the next one loads', async () => {
+ const previousData = mockConversationsResult.data;
+ mockConversationsResult.data = {
+ pages: [
+ {
+ conversations: [{ conversationId: 'chat-1', title: 'Previous match' }],
+ nextCursor: null,
+ },
+ ],
+ };
+ mockConversationsResult.isPreviousData = true;
+
+ try {
+ renderSection('new term');
+ await settleRenders();
+ expect(screen.getByTestId('search-spinner')).toBeInTheDocument();
+ expect(screen.queryByText('Previous match')).not.toBeInTheDocument();
+ } finally {
+ mockConversationsResult.data = previousData;
+ mockConversationsResult.isPreviousData = false;
+ }
+ });
+
+ it('keeps cached results visible when a message triggers a background list refetch', async () => {
+ const previousData = mockConversationsResult.data;
+ mockConversationsResult.data = {
+ pages: [
+ {
+ conversations: [{ conversationId: 'chat-1', title: 'Matching chat' }],
+ nextCursor: null,
+ },
+ ],
+ };
+
+ try {
+ renderSection('draft');
+ await settleRenders();
+ expect(screen.getByText('Matching chat')).toBeInTheDocument();
+
+ act(() => {
+ mockConversationsResult.isFetching = true;
+ setStreamTick((prev) => prev + 1);
+ });
+
+ expect(screen.getByText('Matching chat')).toBeInTheDocument();
+ expect(screen.queryByTestId('search-spinner')).not.toBeInTheDocument();
+ } finally {
+ mockConversationsResult.isFetching = false;
+ mockConversationsResult.data = previousData;
+ }
+ });
+});
+
describe('ConversationsSection shared scroll surface', () => {
/** Searching swaps what the one surface holds — Projects and Pinned leave,
* the chats become results — and a position kept from the previous contents
diff --git a/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx b/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx
index bbb06f1a43..5c8111a384 100644
--- a/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx
+++ b/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx
@@ -195,6 +195,7 @@ function renderAsk(
getMessages,
setMessages,
setSubmission,
+ setConversation: mockSetConversation,
}),
{ wrapper },
);
@@ -834,6 +835,7 @@ describe('useChatFunctions ask attachments', () => {
getMessages: () => [],
setMessages,
setSubmission,
+ setConversation: mockSetConversation,
files,
setFiles,
}),
@@ -880,6 +882,7 @@ describe('useChatFunctions ask attachments', () => {
getMessages: () => [],
setMessages: jest.fn(),
setSubmission,
+ setConversation: mockSetConversation,
files,
setFiles: jest.fn(),
}),
@@ -913,6 +916,7 @@ describe('useChatFunctions ask attachments', () => {
getMessages: () => [],
setMessages: jest.fn(),
setSubmission,
+ setConversation: mockSetConversation,
files,
setFiles: jest.fn(),
}),
diff --git a/client/src/hooks/Chat/__tests__/useQueueDrain.spec.tsx b/client/src/hooks/Chat/__tests__/useQueueDrain.spec.tsx
index 924667b1f5..21974dd80c 100644
--- a/client/src/hooks/Chat/__tests__/useQueueDrain.spec.tsx
+++ b/client/src/hooks/Chat/__tests__/useQueueDrain.spec.tsx
@@ -16,6 +16,7 @@ import {
acquireQueueSendLock,
releaseQueueSendLock,
} from '~/utils/queueIntent';
+import { recoveryDispositionsFamily } from '~/components/Chat/Steering/recovery';
import { revealedQueuedTurnFamily } from '~/store/steer';
import useQueueDrain from '../useQueueDrain';
import store from '~/store';
diff --git a/client/src/hooks/Chat/__tests__/useSteering.spec.tsx b/client/src/hooks/Chat/__tests__/useSteering.spec.tsx
index b72d70c36c..b99d3b24fe 100644
--- a/client/src/hooks/Chat/__tests__/useSteering.spec.tsx
+++ b/client/src/hooks/Chat/__tests__/useSteering.spec.tsx
@@ -9,7 +9,7 @@ import {
LocalStorageKeys,
ReasoningEffort,
} from 'librechat-data-provider';
-import type { TConversation, TFile, TMessage } from 'librechat-data-provider';
+import type { CodeApprovalMode, TConversation, TFile, TMessage } from 'librechat-data-provider';
import type { QueuedMessage } from '~/store/families';
import type { ExtendedFile } from '~/common';
import {
@@ -19,6 +19,7 @@ import {
import { revealedQueuedTurnFamily, pendingSteerCancelClientIdsFamily } from '~/store/steer';
import useSteering, { hasLiveRunPause, mergeQueuedTurnFileMetadata } from '../useSteering';
import { clearAllDrafts, getPendingDraftId, getNewConversationDraftId } from '~/utils';
+import { recoveryDispositionsFamily } from '~/components/Chat/Steering/recovery';
import { claimQueuedIntent, releaseQueuedIntent } from '~/utils/queueIntent';
import useUpdateFiles from '~/hooks/Files/useUpdateFiles';
import ChatSettingsProvider from '~/routes/ChatSettings';
@@ -3227,6 +3228,63 @@ describe('useSteering', () => {
expect(result.current.queue.map((item) => item.id)).toEqual(['second', 'first', 'third']);
});
+ it('confirms a discarded recovery but keeps it held until the guarded UI action succeeds', async () => {
+ mockCancelSteer.mockResolvedValueOnce({
+ removed: true,
+ generationProtocolVersion: 2,
+ });
+ const before: QueuedMessage = {
+ id: 'queued-before',
+ text: 'before',
+ createdAt: 0,
+ };
+ const recovered: QueuedMessage = {
+ id: 'queued-leftover',
+ text: 'edit this next',
+ createdAt: 1,
+ clientRequestId: 'recovery-attempt',
+ recoverySteerId: 'server-leftover',
+ recoveryClientSteerId: 'client-leftover',
+ expectedPredecessorCreatedAt: 41,
+ files: [
+ {
+ file_id: 'file-1',
+ filepath: '/uploads/file-1.txt',
+ type: 'text/plain',
+ },
+ ],
+ quotes: ['keep quote'],
+ manualSkills: ['keep skill'],
+ priority: true,
+ };
+ const after: QueuedMessage = {
+ id: 'queued-after',
+ text: 'after',
+ createdAt: 2,
+ };
+ const { result } = setupWithState({}, ({ set }) => {
+ set(store.queuedMessagesByConvoId(CONVO_ID), [before, recovered, after]);
+ });
+
+ let discarded = false;
+ await act(async () => {
+ discarded = await result.current.steering.discardQueued(recovered);
+ });
+
+ expect(discarded).toBe(true);
+ expect(mockCancelSteer).toHaveBeenCalledWith({
+ conversationId: CONVO_ID,
+ steerId: 'server-leftover',
+ clientSteerId: 'client-leftover',
+ });
+ expect(result.current.queue).toEqual([before, recovered, after]);
+ expect(getDefaultStore().get(recoveryDispositionsFamily(CONVO_ID))).toEqual({
+ 'server-leftover': 'cancelled',
+ });
+ act(() => result.current.steering.sendQueuedNow(recovered));
+ expect(mockMutate).not.toHaveBeenCalled();
+ });
+
it('atomically discards a recovered source and downgrades its row in place', async () => {
mockCancelSteer.mockResolvedValueOnce({
removed: true,
diff --git a/client/src/hooks/Chat/useChatFunctions.ts b/client/src/hooks/Chat/useChatFunctions.ts
index 77580b9242..ee2d349ced 100644
--- a/client/src/hooks/Chat/useChatFunctions.ts
+++ b/client/src/hooks/Chat/useChatFunctions.ts
@@ -875,6 +875,14 @@ export default function useChatFunctions({
setMessages([...submissionMessages, currentMsg, initialResponse]);
}
+ /** Carry the submitted choice through the first saved-chat event instead of re-deriving it
+ * from agent defaults. This is optimistic: the SSE error path reconciles an existing chat
+ * with its authoritative server decision if admission fails. */
+ setConversation((current) =>
+ current == null || current.conversationId !== conversation?.conversationId
+ ? current
+ : withSubmittedCodeDecision(current, workspaceSubmission),
+ );
/** Armed at the point of no return: every refusal above returns before it,
* so a rejected send never has to unwind the guard, and `ask` runs to
* completion synchronously, which is the whole window it has to cover. */
diff --git a/client/src/hooks/Chat/useQueueDrain.ts b/client/src/hooks/Chat/useQueueDrain.ts
index d31c2ece6d..6e5aad6a1a 100644
--- a/client/src/hooks/Chat/useQueueDrain.ts
+++ b/client/src/hooks/Chat/useQueueDrain.ts
@@ -1,10 +1,15 @@
import { useRef, useEffect, useMemo } from 'react';
-import { useAtomValue } from 'jotai';
+import { useAtomValue, useStore } from 'jotai';
import { useRecoilValue, useRecoilCallback } from 'recoil';
import { Constants, DEFAULT_QUEUED_SEND_LOCK_TIMEOUT_MS } from 'librechat-data-provider';
import type { DrainAfterAbort, QueuedMessage, QueuedMessageOrigin, RunEnd } from '~/store/families';
import type { QueueSendLock } from '~/utils/queueIntent';
import type { TAskFunction } from '~/common';
+import {
+ recoveryDispositionsFamily,
+ recoveryDisposition,
+ canRestoreRecovery,
+} from '~/components/Chat/Steering/recovery';
import { acquireQueueSendLock, releaseQueueSendLock, hasQueuedIntent } from '~/utils/queueIntent';
import { useGetStartupConfig, useMarkFilesUsageMutation } from '~/data-provider';
import { selectQueuedTurnReveal } from '~/hooks/Chat/useQueuedTurnReveal';
@@ -346,8 +351,22 @@ export default function useQueueDrain(
return reveal == null ? null : { kind: 'reveal', item: reveal, end };
}
- // Consume only after server authority has yielded the boundary: a
- // hard double-fire guard even if the effect re-runs before propagation.
+ const head = merged[0];
+ if (
+ shouldDrain &&
+ head != null &&
+ recoveryDisposition(jotaiStore.get(recoveryDispositionsFamily(conversationId)), head) !=
+ null
+ ) {
+ // The first row still owns this boundary. Keep it until dismissal, even when
+ // a later local row is immediately sendable; a user must choose its fate.
+ if (shouldMigrate && newConvoQueue.length > 0) {
+ set(store.queuedMessagesByConvoId(Constants.NEW_CONVO), []);
+ set(store.queuedMessagesByConvoId(conversationId), merged);
+ }
+ return null;
+ }
+ // Intent-held and explicitly refused rows are skipped by the redesigned rail.
consumeEnd();
/** A row the rail is mid-edit or mid-remove on is spoken for: its words
@@ -359,7 +378,15 @@ export default function useQueueDrain(
* Both are skipped rather than blocking the whole queue, so an
* untouched follow-up behind them still goes on this run end. */
const nextIndex = shouldDrain
- ? merged.findIndex((item) => !hasQueuedIntent(item.id) && item.needsExplicitSend !== true)
+ ? merged.findIndex(
+ (item) =>
+ !hasQueuedIntent(item.id) &&
+ item.needsExplicitSend !== true &&
+ recoveryDisposition(
+ jotaiStore.get(recoveryDispositionsFamily(conversationId)),
+ item,
+ ) == null,
+ )
: -1;
const next = nextIndex >= 0 ? merged[nextIndex] : null;
const remainder = nextIndex >= 0 ? merged.filter((_, at) => at !== nextIndex) : merged;
@@ -391,6 +418,8 @@ export default function useQueueDrain(
const restoreQueued = useRecoilCallback(
({ set }) =>
(convoId: string, origin: QueuedMessageOrigin) => {
+ if (!canRestoreRecovery(jotaiStore.get(recoveryDispositionsFamily(convoId)), origin.item))
+ return;
set(store.queuedMessagesByConvoId(convoId), (prev) => insertQueuedOrigin(prev, origin));
},
[jotaiStore],
diff --git a/client/src/hooks/Chat/useSteerConvert.ts b/client/src/hooks/Chat/useSteerConvert.ts
index 8f2593763d..df92972918 100644
--- a/client/src/hooks/Chat/useSteerConvert.ts
+++ b/client/src/hooks/Chat/useSteerConvert.ts
@@ -124,7 +124,7 @@ export default function useSteerConvert() {
* already created a receipt-bound item before the claim reached an
* old replica, that source no longer exists. Downgrade the existing
* item in place to an ordinary local follow-up. */
- const existing = shouldBindRecoverySource
+ const existing: QueuedMessage[] = shouldBindRecoverySource
? prev
: prev.map((item) => {
const matchesClaimedSource =
@@ -166,17 +166,20 @@ export default function useSteerConvert() {
local?.files,
fileMapRef.current,
);
- const recoveryFields = shouldBindRecoverySource
- ? {
- // One UUID is stable for this queued attempt and all of
- // its POST retries. A later failed generation re-converts
- // the durable source and receives a new key, so the old
- // started idempotency tombstone cannot make it unsendable.
- clientRequestId: v4(),
- recoverySteerId: steer.steerId,
- ...(steer.clientSteerId && { recoveryClientSteerId: steer.clientSteerId }),
- }
- : {};
+ const held =
+ jotaiStore.get(recoveryDispositionsFamily(conversationId))[steer.steerId] != null;
+ const recoveryFields =
+ shouldBindRecoverySource || held
+ ? {
+ // One UUID is stable for this queued attempt and all of
+ // its POST retries. A later failed generation re-converts
+ // the durable source and receives a new key, so the old
+ // started idempotency tombstone cannot make it unsendable.
+ clientRequestId: v4(),
+ recoverySteerId: steer.steerId,
+ ...(steer.clientSteerId && { recoveryClientSteerId: steer.clientSteerId }),
+ }
+ : {};
const explicitSend = needsExplicitSend === true ? { needsExplicitSend: true } : {};
const item =
queuedOrigin != null
diff --git a/client/src/hooks/Chat/useSteering.ts b/client/src/hooks/Chat/useSteering.ts
index 82a5719abe..bbd919f17b 100644
--- a/client/src/hooks/Chat/useSteering.ts
+++ b/client/src/hooks/Chat/useSteering.ts
@@ -49,6 +49,12 @@ import {
hydrateFileDeliveryMetadata,
mergeRestagedQuotes,
} from '~/utils';
+import {
+ recoveryDispositionsFamily,
+ recoveryDisposition,
+ canRestoreRecovery,
+ blockRecovery,
+} from '~/components/Chat/Steering/recovery';
import {
getReasoningStateKey,
pendingReasoningOverrideFamily,
@@ -1202,6 +1208,7 @@ export default function useSteering({
item.manualSkills.length > 0 && {
manualSkills: item.manualSkills,
}),
+ ...(codeApprovalMode != null && { codeApprovalMode }),
...(item.reasoningOverride != null && {
reasoningOverride: item.reasoningOverride,
}),
@@ -1512,36 +1519,6 @@ export default function useSteering({
[queueKey],
);
- /** Once a parked source is discarded it must never be retried as a recovery
- * attempt. Downgrade the row in place so a guarded Edit that finds a newer
- * draft can leave the same words, context, identity, and queue position as
- * an ordinary local follow-up. */
- const downgradeQueuedRecovery = useRecoilCallback(
- ({ snapshot, set }) =>
- (id: string): boolean => {
- const queue = snapshot.getLoadable(store.queuedMessagesByConvoId(queueKey)).getValue();
- let found = false;
- const next = queue.map((item) => {
- if (item.id !== id) {
- return item;
- }
- found = true;
- const {
- clientRequestId: _clientRequestId,
- recoverySteerId: _recoverySteerId,
- recoveryClientSteerId: _recoveryClientSteerId,
- ...ordinary
- } = item;
- return ordinary;
- });
- if (found) {
- set(store.queuedMessagesByConvoId(queueKey), next);
- }
- return found;
- },
- [queueKey],
- );
-
/** Settle a queued row's terminal recovery source before an Edit/Remove.
* Ordinary rows have no server copy. A v2 leftover first uses its durable
* receipt to atomically discard the parked copy, then becomes an ordinary
@@ -2384,7 +2361,10 @@ export default function useSteering({
* boundary; it only means something on the live-run path. */
const sendLocalQueuedNow = useCallback(
(item: QueuedMessage, opts?: { preempt?: boolean }) => {
- if (hasQueuedIntent(item.id)) {
+ if (
+ hasQueuedIntent(item.id) ||
+ recoveryDisposition(jotaiStore.get(recoveryDispositionsFamily(queueKey)), item) != null
+ ) {
return;
}
/** In answer mode (and any other submission-owned non-steerable state)
@@ -2651,6 +2631,7 @@ export default function useSteering({
removeQueued,
holdQueued,
discardQueued,
+ dismissRecovery,
rewakeDrain,
reorderQueued,
restoreQueuedOrder,
@@ -2683,6 +2664,7 @@ export default function useSteering({
removeQueued,
holdQueued,
discardQueued,
+ dismissRecovery,
rewakeDrain,
reorderQueued,
restoreQueuedOrder,
diff --git a/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts b/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts
index 7cd24ef385..7fa4a9ceb8 100644
--- a/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts
+++ b/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts
@@ -20,6 +20,7 @@ import {
pendingUsageFamily,
removeUsageAtoms,
} from '~/store/usage';
+import { recoveryDispositionsFamily } from '~/components/Chat/Steering/recovery';
import { pendingApprovalActionFamily } from '~/components/Chat/approval/state';
type SSEEventListener = (e: Partial<MessageEvent> & { responseCode?: number }) => void;
diff --git a/client/src/hooks/SSE/useEventHandlers.ts b/client/src/hooks/SSE/useEventHandlers.ts
index 3e1dfe6385..f1fc248529 100644
--- a/client/src/hooks/SSE/useEventHandlers.ts
+++ b/client/src/hooks/SSE/useEventHandlers.ts
@@ -47,16 +47,16 @@ import {
isEmptyContentPart,
getPartKeyIndex,
} from '~/utils';
-import {
- getReasoningStateKey,
- pendingReasoningOverrideFamily,
-} from '~/components/Chat/Input/Composer/state';
import {
startupConfigKey,
queueTitleGeneration,
markTitleGenerationProcessed,
useReconcileConversationCodeEnvironmentMutation,
} from '~/data-provider';
+import {
+ getReasoningStateKey,
+ pendingReasoningOverrideFamily,
+} from '~/components/Chat/Input/Composer/state';
import {
getFailedCodeDecisionRequest,
withSubmittedCodeDecision,
@@ -1321,6 +1321,7 @@ export default function useEventHandlers({
attachmentHandler,
setSubmissionStart,
restorePendingContext,
+ reconcileFailedCodeDecision,
],
);
diff --git a/client/src/hooks/SSE/useResumableSSE.ts b/client/src/hooks/SSE/useResumableSSE.ts
index 1fe3856c46..723513b8e0 100644
--- a/client/src/hooks/SSE/useResumableSSE.ts
+++ b/client/src/hooks/SSE/useResumableSSE.ts
@@ -3399,17 +3399,35 @@ export default function useResumableSSE(
!createdStreamIdsRef.current.has(currentStreamId) &&
optimisticStreamIdsRef.current.has(currentStreamId)
) {
- if (isResume) {
- // A resumed subscribe attaches to an already-adopted stream (e.g. a deduped
- // start request). A 404 means the job is gone, but the conversation may be
- // persisted (the original completed and was cleaned up) or may never have
- // existed (the winner died before persisting). Don't guess: reconcile against
- // the server so a real conversation stays and a phantom is dropped.
- invalidateConversationLists(queryClient);
- queryClient.invalidateQueries({ queryKey: [QueryKeys.pinnedConversations] });
- } else {
- // Fresh optimistic stream that never started: prune immediately.
- removeConvoFromAllQueries(queryClient, currentStreamId);
+ // Both fresh and resumed subscriptions can miss every event of a fast turn.
+ // A missing job proves neither that the conversation was saved nor that it failed.
+ try {
+ const persisted = await dataService.getConversationById(recoveryConvoId);
+ if (!isCurrentSubscription()) return;
+ if (persisted?.conversationId === recoveryConvoId) {
+ queryClient.setQueryData([QueryKeys.conversation, recoveryConvoId], persisted);
+ upsertConvoInAllQueries(queryClient, persisted);
+ if (!isAddedRequest) {
+ setConversation?.((current) => {
+ if (
+ current?.conversationId != null &&
+ current.conversationId !== Constants.NEW_CONVO &&
+ current.conversationId !== recoveryConvoId
+ )
+ return current;
+ return keepLocalCodeApprovalMode(
+ { ...current, ...persisted },
+ current,
+ current?.conversationId,
+ );
+ });
+ }
+ }
+ } catch (error) {
+ if (!isCurrentSubscription()) return;
+ if (toStartGenerationError(error)?.response?.status === 404) {
+ removeConvoFromAllQueries(queryClient, currentStreamId);
+ }
}
// An inconclusive read must not turn a saved chat into a phantom.
invalidateConversationLists(queryClient);
diff --git a/e2e/setup/fake-model.js b/e2e/setup/fake-model.js
index c226b3ee87..62bc084e08 100644
--- a/e2e/setup/fake-model.js
+++ b/e2e/setup/fake-model.js
@@ -115,6 +115,8 @@ const SLOW_REPLY_CONTINUATION_TEXT = 'E2E slow reply continued';
const ACTIVITY_FINAL_TEXT = 'E2E activity reply done';
const ACTIVITY_PHASE_FINAL_TEXT = 'E2E activity phase reply done';
const MCP_APP_PHASE_FINAL_TEXT = 'E2E MCP App phase complete';
+const ACTIVITY_FAILED_FINAL_TEXT = 'E2E activity failed reply done';
+const SLOW_ECHO_TOOL_NAME_PREFIX = 'slow_echo';
const STEER_TOOL_NAME_PREFIX = 'remember_fact';
const MCP_APP_TOOL_NAME_PREFIX = 'show_app';
const ASK_USER_QUESTION_TOOL_NAME = 'ask_user_question';
diff --git a/eslint-suppressions.json b/eslint-suppressions.json
index 7a0d93e661..dfcb80aa3a 100644
--- a/eslint-suppressions.json
+++ b/eslint-suppressions.json
@@ -417,9 +417,6 @@
},
"shadcn/no-raw-colors": {
"count": 1
- },
- "shadcn/no-restyle": {
- "count": 13
}
},
"client/src/components/Chat/Messages/Content/AgentHandoff.tsx": {
@@ -692,9 +689,6 @@
"client/src/components/Chat/Messages/Content/ToolCallGroup.tsx": {
"shadcn/no-inline-styles": {
"count": 1
- },
- "shadcn/no-restyle": {
- "count": 11
}
},
"client/src/components/Chat/Messages/Content/ToolCallInfo.tsx": {
diff --git a/packages/api/src/agents/client.spec.ts b/packages/api/src/agents/client.spec.ts
index a1b27779d1..9ffb3a7d9e 100644
--- a/packages/api/src/agents/client.spec.ts
+++ b/packages/api/src/agents/client.spec.ts
@@ -3,6 +3,9 @@ import { Providers, StandardGraph } from '@librechat/agents';
import { HumanMessage, SystemMessage } from '@librechat/agents/langchain/messages';
import { ContentTypes, DEFAULT_MAX_RETAINED_TOOL_COUNT_CHARS } from 'librechat-data-provider';
import type { TMessage } from 'librechat-data-provider';
+import type { LCTool } from '@librechat/agents';
+import type { FormattedMessageWithContent } from './client';
+import type { EncodingName } from '~/utils/tokenizer';
import type { ServerRequest } from '~/types';
import {
collectToolCallIds,
diff --git a/packages/api/src/agents/queuedTurnHttp.ts b/packages/api/src/agents/queuedTurnHttp.ts
index 1b0743f5d0..76048bc326 100644
--- a/packages/api/src/agents/queuedTurnHttp.ts
+++ b/packages/api/src/agents/queuedTurnHttp.ts
@@ -10,12 +10,6 @@ import {
AgentQueuedTurnConflictError,
AgentQueuedTurnLaneRetiredError,
} from '@librechat/data-schemas';
-import type {
- AgentQueuedTurnActiveRecord,
- AgentQueuedTurnMethods,
- AgentQueuedTurnRecord,
- IMongoFile,
-} from '@librechat/data-schemas';
import type {
CodeApprovalMode,
TAgentQueuedTurnFileRef,
@@ -23,6 +17,12 @@ import type {
TFile,
TReasoningOverride,
} from 'librechat-data-provider';
+import type {
+ AgentQueuedTurnActiveRecord,
+ AgentQueuedTurnMethods,
+ AgentQueuedTurnRecord,
+ IMongoFile,
+} from '@librechat/data-schemas';
import type { Request, RequestHandler } from 'express';
import type { AgentQueuedTurnLifecycle } from './queuedTurns';
import type { SteerFileFetcher } from './steering/request';
@@ -92,6 +92,7 @@ function receipt(
...(turn.files != null && { files: turn.files }),
...(turn.quotes != null && { quotes: turn.quotes }),
...(turn.manualSkills != null && { manualSkills: turn.manualSkills }),
+ ...(turn.codeApprovalMode != null && { codeApprovalMode: turn.codeApprovalMode }),
...(turn.reasoningOverride != null && { reasoningOverride: turn.reasoningOverride }),
priority: turn.priority,
...(turn.expectedPredecessorCreatedAt != null && {
@@ -153,6 +154,7 @@ function matchesReplayIntent(
clientRequestId: string;
files?: readonly TAgentQueuedTurnFileRef[];
manualSkills?: readonly string[];
+ codeApprovalMode?: CodeApprovalMode;
reasoningOverride?: TReasoningOverride;
expectedPredecessorCreatedAt?: number;
},
@@ -169,6 +171,7 @@ function matchesReplayIntent(
) &&
sameStrings(turn.quotes, quotes) &&
sameStrings(turn.manualSkills, uniqueStrings(input.manualSkills)) &&
+ turn.codeApprovalMode === input.codeApprovalMode &&
sameReasoningOverride(turn.reasoningOverride, input.reasoningOverride) &&
turn.expectedPredecessorCreatedAt === input.expectedPredecessorCreatedAt
);
@@ -357,6 +360,7 @@ export async function handleAgentQueuedTurnEnqueue(
...(resolvedFiles.files != null && { files: resolvedFiles.files }),
...(quotes != null && { quotes }),
...(input.manualSkills != null && { manualSkills: input.manualSkills }),
+ ...(input.codeApprovalMode != null && { codeApprovalMode: input.codeApprovalMode }),
...(input.reasoningOverride != null && { reasoningOverride: input.reasoningOverride }),
priority: false,
...(input.expectedPredecessorCreatedAt != null && {
diff --git a/packages/api/src/agents/queuedTurns.ts b/packages/api/src/agents/queuedTurns.ts
index 6230b84041..68c9a0f4f3 100644
--- a/packages/api/src/agents/queuedTurns.ts
+++ b/packages/api/src/agents/queuedTurns.ts
@@ -647,6 +647,7 @@ function createAgentQueuedTurnResolver({
...(claim.files != null && { files: claim.files }),
...(claim.quotes != null && { quotes: claim.quotes }),
...(claim.manualSkills != null && { manualSkills: claim.manualSkills }),
+ ...(claim.codeApprovalMode != null && { codeApprovalMode: claim.codeApprovalMode }),
...(claim.reasoningOverride != null && { reasoningOverride: claim.reasoningOverride }),
admissionSource: {
source: AGENT_QUEUED_TURN_SOURCE,
diff --git a/packages/api/src/agents/triggers/host.spec.ts b/packages/api/src/agents/triggers/host.spec.ts
index b86de1484a..ecc1a74023 100644
--- a/packages/api/src/agents/triggers/host.spec.ts
+++ b/packages/api/src/agents/triggers/host.spec.ts
@@ -645,6 +645,7 @@ describe('createAgentTriggerExecutionHost continue adapter', () => {
files: [{ file_id: 'file-1' }],
quotes: ['quoted context'],
manualSkills: ['research'],
+ codeApprovalMode: 'acceptEdits' as const,
reasoningOverride: { key: 'reasoning_effort' as const, value: ReasoningEffort.high },
admissionSource,
settleOnAdmission,
@@ -667,6 +668,7 @@ describe('createAgentTriggerExecutionHost continue adapter', () => {
files: [{ file_id: 'file-1' }],
quotes: ['quoted context'],
manualSkills: ['research'],
+ codeApprovalMode: 'acceptEdits',
reasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.high },
agentContinuationAdmission: admissionSource,
});
diff --git a/packages/api/src/agents/triggers/host.ts b/packages/api/src/agents/triggers/host.ts
index 93e32d0467..6bf30f70b8 100644
--- a/packages/api/src/agents/triggers/host.ts
+++ b/packages/api/src/agents/triggers/host.ts
@@ -1,6 +1,6 @@
import { logger, tenantStorage } from '@librechat/data-schemas';
import { Constants, EModelEndpoint } from 'librechat-data-provider';
-import type { TFile, TReasoningOverride } from 'librechat-data-provider';
+import type { CodeApprovalMode, TFile, TReasoningOverride } from 'librechat-data-provider';
import type {
AgentContinueTriggerEnvelope,
AgentFireTriggerEnvelope,
@@ -58,6 +58,9 @@ export type AgentTriggerContinuePreparation =
files?: Partial<TFile>[];
quotes?: string[];
manualSkills?: string[];
+ /** Parent-selected coding preference for a completion turn. Admission
+ * revalidates it against live policy; event payloads cannot supply it. */
+ codeApprovalMode?: CodeApprovalMode;
reasoningOverride?: TReasoningOverride;
/** Trusted source identity committed by execution enrollment before the
* provider-start fence opens. */
diff --git a/packages/api/src/mcp/MCPManager.ts b/packages/api/src/mcp/MCPManager.ts
index f63c90b092..cc30d4ee54 100644
--- a/packages/api/src/mcp/MCPManager.ts
+++ b/packages/api/src/mcp/MCPManager.ts
@@ -64,6 +64,7 @@ import { MCPConnectionFactory } from './MCPConnectionFactory';
import { processMCPEnv, isPluginSourced } from '~/utils/env';
import { OAuthLifecycleRelay } from './oauth/pending';
import { isOwnedAbortError } from '~/utils/errors';
+import { withMCPRequestSignal } from './signal';
import { MCPConnection } from './connection';
import { mcpConfig } from './mcpConfig';
diff --git a/packages/api/src/stream/jobStoreCapabilities.ts b/packages/api/src/stream/jobStoreCapabilities.ts
index 7603c983f0..9c403928f7 100644
--- a/packages/api/src/stream/jobStoreCapabilities.ts
+++ b/packages/api/src/stream/jobStoreCapabilities.ts
@@ -36,7 +36,7 @@ export const JOB_STORE_V2_REQUIRED_METHODS = [
'claimFirstSubscriber',
'detachSubscriber',
'hasActiveSubscriber',
-] as const satisfies ReadonlyArray<keyof IJobStoreV2>;
+] as const;
export type JobStoreV2RequiredMethod = (typeof JOB_STORE_V2_REQUIRED_METHODS)[number];
@@ -52,6 +52,9 @@ type SameUnion<Left, Right> = [Left] extends [Right]
type AssertTrue<Value extends true> = Value;
/** Compile-time tripwire: adding a v2-only method requires updating the runtime assertion. */
type _AllV2MethodsHaveRuntimeChecks = AssertTrue<SameUnion<V2OnlyMethod, JobStoreV2RequiredMethod>>;
+type _AllRuntimeChecksBelongToV2 = AssertTrue<
+ Exclude<JobStoreV2RequiredMethod, keyof IJobStoreV2> extends never ? true : false
+>;
/** Return the v2 capabilities absent from a legacy-compatible store. */
export function getMissingJobStoreV2Methods(store: IJobStore): JobStoreV2RequiredMethod[] {
diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.ts
index c0fff79cd6..a6eb88a251 100644
--- a/packages/data-provider/src/config.ts
+++ b/packages/data-provider/src/config.ts
@@ -42,7 +42,12 @@ import {
resolveMCPAppCspLimits,
type MCPAppCspLimits,
} from './mcp/csp';
-import { CODE_ENVIRONMENT_DECISION_VERSION, CODE_ENVIRONMENT_MOVE_VERSION } from './code/workspace';
+import {
+ CODE_ENVIRONMENT_DECISION_VERSION,
+ CODE_ENVIRONMENT_MOVE_VERSION,
+ CODE_ENVIRONMENT_TRANSITION_VERSION,
+ CODE_WORKSPACE_RECOVERY_VERSION,
+} from './code/workspace';
import { ComponentTypes, SettingTypes, OptionTypes } from './generate';
import { STATEFUL_CODE_ENVIRONMENTS } from './stateful-code';
import { specsConfigSchema, TSpecsConfig } from './models';
@@ -2340,6 +2345,23 @@ export type TThemeDefinitionConfig = z.infer<typeof themeDefinitionSchema>;
/** A bundled theme name or an inline theme definition applied to every user. */
export const deploymentThemeSchema = z.union([z.string().trim().min(1), themeDefinitionSchema]);
+/** Single source for the agents panel selector's unsearched list cap; the
+ * schema default and the client fallback both read it. */
+export const DEFAULT_AGENT_SELECTOR_LIMIT = 10;
+export const AGENT_SELECTOR_LIMIT_MIN = 1;
+export const AGENT_SELECTOR_LIMIT_MAX = 100;
+
+/** Runtime guard for values that bypass `interfaceSchema`: raw librechat.yaml
+ * reads and principal-scoped admin overrides reach the client unparsed, so an
+ * out-of-bounds value falls back to the default instead of emptying the list. */
+export function normalizeAgentSelectorLimit(value: unknown): number {
+ return typeof value === 'number' &&
+ Number.isInteger(value) &&
+ value >= AGENT_SELECTOR_LIMIT_MIN &&
+ value <= AGENT_SELECTOR_LIMIT_MAX
+ ? value
+ : DEFAULT_AGENT_SELECTOR_LIMIT;
+}
/** Retention modes that apply expiration deadlines to all data, not just user-marked temporary chats. */
export const isAllDataRetention = (mode?: RetentionMode | null): boolean =>
diff --git a/packages/data-provider/src/types/queuedTurns.ts b/packages/data-provider/src/types/queuedTurns.ts
index 5baa3ae250..ee37706dc3 100644
--- a/packages/data-provider/src/types/queuedTurns.ts
+++ b/packages/data-provider/src/types/queuedTurns.ts
@@ -1,4 +1,5 @@
import { z } from 'zod';
+import { CODE_APPROVAL_MODES } from '../code/approval';
import { reasoningOverrideSchema } from '../schemas';
export const agentQueuedTurnStatuses = [
@@ -31,6 +32,8 @@ export const enqueueAgentQueuedTurnSchema = z.object({
files: z.array(agentQueuedTurnFileRefSchema).optional(),
quotes: z.array(z.string()).optional(),
manualSkills: z.array(z.string().trim().min(1)).optional(),
+ /** Selected when queued, revalidated against live policy at turn admission. */
+ codeApprovalMode: z.enum(CODE_APPROVAL_MODES).optional(),
reasoningOverride: reasoningOverrideSchema.optional(),
priority: z.boolean().optional(),
expectedPredecessorCreatedAt: z.number().int().nonnegative().optional(),
diff --git a/packages/data-schemas/src/app/interface.spec.ts b/packages/data-schemas/src/app/interface.spec.ts
index f8c519869d..78760b0b99 100644
--- a/packages/data-schemas/src/app/interface.spec.ts
+++ b/packages/data-schemas/src/app/interface.spec.ts
@@ -36,6 +36,30 @@ describe('loadDefaultInterface', () => {
expect(interfaceConfig?.codeHighlightThrottleMs).toBe(100);
});
+ it('uses the schema default for the agent selector list cap when not configured', async () => {
+ const interfaceConfig = await loadDefaultInterface({
+ config: {},
+ configDefaults: getConfigDefaults(),
+ });
+
+ expect(interfaceConfig?.agentSelectorLimit).toBe(10);
+ });
+
+ it('forwards a configured agent selector list cap to the served interface', async () => {
+ const config: Partial<TCustomConfig> = {
+ interface: {
+ agentSelectorLimit: 4,
+ },
+ };
+
+ const interfaceConfig = await loadDefaultInterface({
+ config,
+ configDefaults: getConfigDefaults(),
+ });
+
+ expect(interfaceConfig?.agentSelectorLimit).toBe(4);
+ });
+
it('uses and preserves the schema default for queued-turn reconciliation', async () => {
const configDefaults = getConfigDefaults();
const defaultInterface = await loadDefaultInterface({
diff --git a/packages/data-schemas/src/methods/agent.ts b/packages/data-schemas/src/methods/agent.ts
index 6f10b2f8d5..29c5959275 100644
--- a/packages/data-schemas/src/methods/agent.ts
+++ b/packages/data-schemas/src/methods/agent.ts
@@ -1951,13 +1951,11 @@ export function createAgentMethods(
}
/**
- * Get accessible agents with cursor pagination. Pages default to 100 items, and a
- * caller that asks for no mode gets `'recent'` — the most-recently-edited order this
- * endpoint has always served. Pass `limit: null` to opt out of pagination.
- *
- * All modes preserve the same projected response shape. Popularity counts are
- * computed from compact candidate rows and unique tenant-scoped users before
- * the selected page is fetched.
+ * Get agents by accessible IDs with cursor pagination. Pass `accessibleIds: null`
+ * only after a management-capability check, with the authenticated tenantId
+ * (or null for legacy agents); `[]` and omitted IDs match nothing.
+ * Defaults to the most-recently-edited order and a 100-page limit (max 1000);
+ * pass `limit: null` to opt out entirely. Other sort modes preserve the projection.
*/
async function getListAgentsByAccess({
accessibleIds = [],
diff --git a/packages/data-schemas/src/methods/message.ts b/packages/data-schemas/src/methods/message.ts
index ffbd43a77b..762950c1c6 100644
--- a/packages/data-schemas/src/methods/message.ts
+++ b/packages/data-schemas/src/methods/message.ts
@@ -897,6 +897,48 @@ function agentOwnershipFilter(prefix: string, agentId: string): Record<string, u
};
}
+type UpdateToolCallResultInput = {
+ userId: string;
+ messageId: string;
+ conversationId: string;
+ toolCallId: string;
+ stepId?: string;
+ /** Scopes the part match when provider tool-call ids repeat across
+ * agents in one response message (e.g. `call_0` per response); a part
+ * without agent identity matches any caller (single-agent runs). */
+ agentId?: string;
+ output?: string;
+ attachments?: unknown[];
+ /**
+ * Stamps `backgrounded: true` onto the patched tool call. Replacing the
+ * dispatch-handle output with the settled task's stdout destroys the only
+ * signal renderers had that this call ran detached (the handle JSON and
+ * the live status-marker attachment are both transient), so the patch
+ * that erases it must persist a durable one alongside.
+ */
+ markBackgrounded?: boolean;
+ backgroundTask?: {
+ taskId: string;
+ toolName: string;
+ status: 'completed' | 'error';
+ cancelled?: true;
+ settledAt: Date;
+ completionWakeup?: true;
+ completionReceipt?: true;
+ resultClaim?: {
+ kind: 'manual' | 'wakeup';
+ claimId: string;
+ claimedAt: Date;
+ generationId?: string;
+ };
+ };
+};
+
+type SteplessToolCallFallback = {
+ content: NonNullable<IMessage['content']>;
+ hasResultClaim: boolean;
+};
+
export interface MessageDependencies {
/** Read from deployment config, never from a message/request or a principal override. */
getMCPAppMessageBudget?: () => Promise<number | undefined>;
@@ -1594,7 +1636,7 @@ export function createMessageMethods(
};
const settleUpdate = {
$inc: { __v: 1 },
- ...(Object.keys(partPatch).length > 0 ? { $set: partPatch } : {}),
+ ...(Object.keys(settlePatch).length > 0 ? { $set: settlePatch } : {}),
...(disarmWakeup
? { $unset: { 'content.$[part].tool_call.backgroundTask.completionWakeup': 1 } }
: {}),
@@ -1779,7 +1821,7 @@ export function createMessageMethods(
},
{
...settleUpdate,
- $set: { ...partPatch, attachments: admitted },
+ $set: { ...settlePatch, attachments: admitted },
},
settleOptions,
).lean<{ unfinished?: boolean } | null>();
diff --git a/packages/data-schemas/src/methods/queuedTurn.spec.ts b/packages/data-schemas/src/methods/queuedTurn.spec.ts
index 4a9e8cb2b2..2cc1c6e379 100644
--- a/packages/data-schemas/src/methods/queuedTurn.spec.ts
+++ b/packages/data-schemas/src/methods/queuedTurn.spec.ts
@@ -173,10 +173,15 @@ describe('agent queued turn methods', () => {
it('keeps the selected approval mode on queued, claimed, and retried turns', async () => {
const input = enqueueInput({
codeApprovalMode: 'fullAccess',
+ reasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.high },
deliveryReservation: { queuedTurnId: '507f191e810c19729de860ea', deliveryKey: 'v2-key' },
});
const first = await methods.enqueueAgentQueuedTurn(input);
expect(first.turn.codeApprovalMode).toBe('fullAccess');
+ expect(first.turn.reasoningOverride).toEqual({
+ key: 'reasoning_effort',
+ value: ReasoningEffort.high,
+ });
expect(first.turn).toMatchObject({ deliveryKey: 'v2-key', deliveryState: 'publishing' });
const scope = {
user,
@@ -195,9 +200,20 @@ describe('agent queued turn methods', () => {
await expect(
methods.enqueueAgentQueuedTurn({ ...input, codeApprovalMode: 'ask' }),
).rejects.toBeInstanceOf(AgentQueuedTurnConflictError);
+ await expect(
+ methods.enqueueAgentQueuedTurn({
+ ...input,
+ reasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.low },
+ }),
+ ).rejects.toBeInstanceOf(AgentQueuedTurnConflictError);
const claimed = await methods.claimNextAgentQueuedTurn(claimInput(first.turn.queuedTurnId));
expect(claimed.outcome).toBe('acquired');
- if (claimed.outcome === 'acquired') expect(claimed.claim.codeApprovalMode).toBe('fullAccess');
+ if (claimed.outcome === 'acquired') {
+ expect(claimed.claim).toMatchObject({
+ codeApprovalMode: 'fullAccess',
+ reasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.high },
+ });
+ }
const listed = await methods.listActiveAgentQueuedTurns({
user,
tenantId: 'tenant-1',
diff --git a/packages/data-schemas/src/methods/queuedTurn.ts b/packages/data-schemas/src/methods/queuedTurn.ts
index 17ddf42730..07f66fc5cf 100644
--- a/packages/data-schemas/src/methods/queuedTurn.ts
+++ b/packages/data-schemas/src/methods/queuedTurn.ts
@@ -1,6 +1,8 @@
import { createHash, randomUUID } from 'node:crypto';
+import { CODE_APPROVAL_MODES } from 'librechat-data-provider';
import { reasoningOverrideSchema } from 'librechat-data-provider';
import type { TReasoningOverride } from 'librechat-data-provider';
+import type { CodeApprovalMode } from 'librechat-data-provider';
import type { FilterQuery, Model, Types } from 'mongoose';
import type {
AgentQueuedTurnActiveRecord,
@@ -110,6 +112,9 @@ export interface EnqueueAgentQueuedTurnInput extends AgentQueuedTurnConversation
files?: readonly AgentQueuedTurnFileRef[];
quotes?: readonly string[];
manualSkills?: readonly string[];
+ codeApprovalMode?: CodeApprovalMode;
+ /** Internal publication fence, committed with approval-bearing rows. */
+ deliveryReservation?: { queuedTurnId: string; deliveryKey: string };
reasoningOverride?: TReasoningOverride;
expectedPredecessorCreatedAt?: number;
priority?: boolean;
@@ -554,6 +559,9 @@ function normalizeEnqueue(input: EnqueueAgentQueuedTurnInput) {
files: normalizeFiles(input.files),
quotes: normalizeQuotes(input.quotes),
manualSkills: normalizeManualSkills(input.manualSkills),
+ ...(input.codeApprovalMode != null && {
+ codeApprovalMode: requireCodeApprovalMode(input.codeApprovalMode),
+ }),
reasoningOverride: normalizeReasoningOverride(input.reasoningOverride),
expectedPredecessorCreatedAt: normalizePredecessor(input.expectedPredecessorCreatedAt),
priority: input.priority === true,
@@ -627,6 +635,7 @@ function toRecord(turn: IAgentQueuedTurn): AgentQueuedTurnRecord {
...(turn.files != null && { files: turn.files }),
...(turn.quotes != null && { quotes: turn.quotes }),
...(turn.manualSkills != null && { manualSkills: turn.manualSkills }),
+ ...(turn.codeApprovalMode != null && { codeApprovalMode: turn.codeApprovalMode }),
...(turn.reasoningOverride != null && { reasoningOverride: turn.reasoningOverride }),
...(turn.expectedPredecessorCreatedAt != null && {
expectedPredecessorCreatedAt: turn.expectedPredecessorCreatedAt,
@@ -689,6 +698,7 @@ function toActiveRecord(turn: IAgentQueuedTurn): AgentQueuedTurnActiveRecord {
...(record.files != null && { files: record.files }),
...(record.quotes != null && { quotes: record.quotes }),
...(record.manualSkills != null && { manualSkills: record.manualSkills }),
+ ...(record.codeApprovalMode != null && { codeApprovalMode: record.codeApprovalMode }),
...(record.reasoningOverride != null && { reasoningOverride: record.reasoningOverride }),
...(record.expectedPredecessorCreatedAt != null && {
expectedPredecessorCreatedAt: record.expectedPredecessorCreatedAt,
diff --git a/packages/data-schemas/src/schema/queuedTurn.ts b/packages/data-schemas/src/schema/queuedTurn.ts
index 0fd6f32f51..09699ebb0c 100644
--- a/packages/data-schemas/src/schema/queuedTurn.ts
+++ b/packages/data-schemas/src/schema/queuedTurn.ts
@@ -86,6 +86,7 @@ const queuedTurnSchema: Schema<IAgentQueuedTurnDocument> = new Schema(
files: { type: [fileRefSchema], default: undefined },
quotes: { type: [String], default: undefined },
manualSkills: { type: [String], default: undefined },
+ codeApprovalMode: { type: String, enum: [...CODE_APPROVAL_MODES] },
reasoningOverride: { type: reasoningOverrideSchema },
expectedPredecessorCreatedAt: { type: Number, min: 0 },
attempts: { type: Number, required: true, default: 0, min: 0 },
diff --git a/packages/data-schemas/src/types/queuedTurn.ts b/packages/data-schemas/src/types/queuedTurn.ts
index 75a418e63f..61010c061d 100644
--- a/packages/data-schemas/src/types/queuedTurn.ts
+++ b/packages/data-schemas/src/types/queuedTurn.ts
@@ -1,4 +1,5 @@
import type { TReasoningOverride } from 'librechat-data-provider';
+import type { CodeApprovalMode } from 'librechat-data-provider';
import type { Document, Types } from 'mongoose';
export type AgentQueuedTurnStatus =
@@ -73,6 +74,8 @@ export interface IAgentQueuedTurn {
files?: AgentQueuedTurnFileRef[];
quotes?: string[];
manualSkills?: string[];
+ /** Per-turn selection, absent on legacy queue rows. Not a permission grant. */
+ codeApprovalMode?: CodeApprovalMode;
reasoningOverride?: TReasoningOverride;
expectedPredecessorCreatedAt?: number;
attempts: number;
@@ -150,6 +153,7 @@ export type AgentQueuedTurnActiveRecord = Pick<
| 'files'
| 'quotes'
| 'manualSkills'
+ | 'codeApprovalMode'
| 'reasoningOverride'
| 'expectedPredecessorCreatedAt'
| 'attempts'