Skip to content

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

💬 refactor: ChatForm UI redesign with unified palette (#14473)

Marco Beretta2be35b2f915c
diff --git a/api/app/clients/BaseClient.js b/api/app/clients/BaseClient.js
index c00ed262fe..dc37997ffe 100644
--- a/api/app/clients/BaseClient.js
+++ b/api/app/clients/BaseClient.js
@@ -32,6 +32,7 @@ const {
announceReply,
needsRetentionConversation,
getConversationWriteContext,
+ persistedReasoningOverrideFields,
} = require('@librechat/api');
const {
Constants,
@@ -611,6 +612,15 @@ class BaseClient {
}
}
+ Object.assign(
+ userMessage,
+ persistedReasoningOverrideFields({
+ rawReasoningOverride: this.options.req?.body?.reasoningOverride,
+ isEdited: opts.isEdited,
+ isCompaction: opts.isCompaction,
+ }),
+ );
+
if (typeof opts?.getReqData === 'function') {
opts.getReqData({
userMessage,
diff --git a/api/app/clients/specs/BaseClient.test.js b/api/app/clients/specs/BaseClient.test.js
index bf74718b09..d6e1549ade 100644
--- a/api/app/clients/specs/BaseClient.test.js
+++ b/api/app/clients/specs/BaseClient.test.js
@@ -3542,6 +3542,62 @@ describe('BaseClient', () => {
);
expect(userSave[0].text).toBe('Just a question');
expect(userSave[0].quotes).toBeUndefined();
+ expect(userSave[0].reasoningOverride).toBeUndefined();
+ });
+
+ test('persists only a validated request-scoped reasoning override on the user turn', async () => {
+ TestClient.options.req = {
+ body: { reasoningOverride: { key: 'reasoning_effort', value: 'high' } },
+ };
+ TestClient.saveMessageToDatabase = jest.fn().mockResolvedValue({ message: {} });
+ await TestClient.sendMessage('Think carefully');
+
+ const userSave = TestClient.saveMessageToDatabase.mock.calls.find(
+ ([message]) => message.isCreatedByUser === true,
+ );
+ expect(userSave[0].reasoningOverride).toEqual({
+ key: 'reasoning_effort',
+ value: 'high',
+ });
+ });
+
+ test('drops an invalid request-scoped reasoning override from message metadata', async () => {
+ TestClient.options.req = {
+ body: { reasoningOverride: { key: 'model', value: 'secret-model' } },
+ };
+ TestClient.saveMessageToDatabase = jest.fn().mockResolvedValue({ message: {} });
+ await TestClient.sendMessage('Do not trust this');
+
+ const userSave = TestClient.saveMessageToDatabase.mock.calls.find(
+ ([message]) => message.isCreatedByUser === true,
+ );
+ expect(userSave[0].reasoningOverride).toBeUndefined();
+ });
+
+ test('does not add a request-scoped reasoning override to a rerun turn', async () => {
+ const rerunClient = initializeFakeClient(apiKey, options, [
+ ...messageHistory,
+ {
+ role: 'assistant',
+ isCreatedByUser: false,
+ text: 'Previous response',
+ messageId: 'response-0',
+ parentMessageId: '3',
+ },
+ ]);
+ rerunClient.options.req = {
+ body: { reasoningOverride: { key: 'reasoning_effort', value: 'high' } },
+ };
+
+ const result = await rerunClient.handleStartMethods('Rerun this', {
+ conversationId: 'conversation-1',
+ parentMessageId: '3',
+ responseMessageId: 'response-0',
+ isEdited: true,
+ isContinued: true,
+ });
+
+ expect(result.userMessage.reasoningOverride).toBeUndefined();
});
});
@@ -4308,6 +4364,9 @@ describe('BaseClient compaction turns', () => {
});
test('presents the leaf as the user message and never re-saves it', async () => {
+ CompactClient.options.req = {
+ body: { reasoningOverride: { key: 'reasoning_effort', value: 'high' } },
+ };
const result = await CompactClient.handleStartMethods('', {
conversationId: 'convo-compact',
parentMessageId: 'a1',
diff --git a/api/server/controllers/agents/__tests__/request.partialDisconnect.spec.js b/api/server/controllers/agents/__tests__/request.partialDisconnect.spec.js
index 43e0f23daa..3c3e23f74d 100644
--- a/api/server/controllers/agents/__tests__/request.partialDisconnect.spec.js
+++ b/api/server/controllers/agents/__tests__/request.partialDisconnect.spec.js
@@ -50,6 +50,8 @@ jest.mock('@librechat/api', () => ({
getAgentErrorMetadata: (...args) =>
jest.requireActual('@librechat/api').getAgentErrorMetadata(...args),
sendEvent: jest.fn(),
+ persistedReasoningOverrideFields:
+ jest.requireActual('@librechat/api').persistedReasoningOverrideFields,
isScheduleFireRequest: jest.fn(() => false),
exemptFromConcurrencyLimiter: jest.fn(() => false),
toPendingSteer: jest.fn((item) => item),
diff --git a/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js b/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js
index 14ecdf1908..da907e363e 100644
--- a/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js
+++ b/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js
@@ -263,6 +263,8 @@ jest.mock('@librechat/api', () => ({
isAnnounceableReply: jest.requireActual('@librechat/api').isAnnounceableReply,
announceReply: jest.requireActual('@librechat/api').announceReply,
announceErrorTurn: jest.requireActual('@librechat/api').announceErrorTurn,
+ persistedReasoningOverrideFields:
+ jest.requireActual('@librechat/api').persistedReasoningOverrideFields,
logAgentMemorySnapshot: jest.fn(),
isScheduleFireRequest: (...args) => mockIsScheduleFireRequest(...args),
exemptFromConcurrencyLimiter: (...args) => mockExemptFromConcurrencyLimiter(...args),
diff --git a/api/server/controllers/agents/client.js b/api/server/controllers/agents/client.js
index ae72f09200..16fe1ee9b3 100644
--- a/api/server/controllers/agents/client.js
+++ b/api/server/controllers/agents/client.js
@@ -4283,7 +4283,10 @@ class AgentClient extends BaseClient {
// the resolved llmConfig fills gaps and is sanitized — it carries provider secrets
// (apiKey, credentials) and gateway config — resume re-resolves those server-side.
// (Saved agents source params from the DB record, so this is belt-and-suspenders.)
- const resumeContext = pickResumeContext(this.options.req?.body);
+ const resumeContext = pickResumeContext(
+ this.options.req?.body,
+ this.options.req?.reasoningOverrideBase,
+ );
const resumeModelParameters = captureResumeModelParameters(
this.options.req?.body,
this.options.agent?.model_parameters,
diff --git a/api/server/controllers/agents/request.js b/api/server/controllers/agents/request.js
index ae7dbaeabf..eca096527c 100644
--- a/api/server/controllers/agents/request.js
+++ b/api/server/controllers/agents/request.js
@@ -9,6 +9,7 @@ const {
} = require('librechat-data-provider');
const {
toPendingSteer,
+ persistedReasoningOverrideFields,
getViolationInfo,
buildMessageFiles,
getReferencedQuotes,
@@ -240,7 +241,16 @@ function resolvePreallocatedUserMessageId({
}
function getPreliminaryUserMessage(
- { messageId, parentMessageId, text, quotes, files, manualSkills, alwaysAppliedSkills },
+ {
+ messageId,
+ parentMessageId,
+ text,
+ quotes,
+ files,
+ manualSkills,
+ alwaysAppliedSkills,
+ reasoningOverride,
+ },
conversationId,
subagentTriggerProjection,
) {
@@ -273,6 +283,9 @@ function getPreliminaryUserMessage(
...(Array.isArray(manualSkills) && manualSkills.length > 0 && { manualSkills }),
...(Array.isArray(alwaysAppliedSkills) &&
alwaysAppliedSkills.length > 0 && { alwaysAppliedSkills }),
+ /* A preliminary message is always a fresh turn: edits and regenerations reuse
+ the live user message, and compaction is projected before reaching here. */
+ ...persistedReasoningOverrideFields({ rawReasoningOverride: reasoningOverride }),
...(subagentTriggerProjection != null && { subagentTriggerProjection }),
};
}
@@ -2319,6 +2332,7 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit
conversationId: userMsg.conversationId,
text: userMsg.text,
quotes: userMsg.quotes,
+ reasoningOverride: userMsg.reasoningOverride,
// Persist the turn's uploaded files here (authoritative job metadata) so a
// HITL resume sources them from the job, not the user DB row — which the
// approval prompt can race (the row save may still be in flight when a fast
diff --git a/api/server/middleware/abortMiddleware.js b/api/server/middleware/abortMiddleware.js
index f4a22087ff..52fd6b2857 100644
--- a/api/server/middleware/abortMiddleware.js
+++ b/api/server/middleware/abortMiddleware.js
@@ -126,6 +126,7 @@ async function abortMessage(req, res) {
conversationId: jobData.userMessage.conversationId,
text: jobData.userMessage.text,
quotes: jobData.userMessage.quotes,
+ reasoningOverride: jobData.userMessage.reasoningOverride,
isCreatedByUser: true,
})
: null,
diff --git a/api/server/middleware/buildEndpointOption.js b/api/server/middleware/buildEndpointOption.js
index 58154adedc..4ff306ccab 100644
--- a/api/server/middleware/buildEndpointOption.js
+++ b/api/server/middleware/buildEndpointOption.js
@@ -6,6 +6,7 @@ const {
inspectContent,
extractChatContent,
contentFilterBlockResponse,
+ applyRequestReasoningOverride,
} = require('@librechat/api');
const { logger } = require('@librechat/data-schemas');
const {
@@ -84,6 +85,7 @@ async function buildEndpointOption(req, res, next) {
const appConfig = req.config;
let appliedModelSpecPrivateFields = new Set();
+ let enforcedModelSpecFields = new Set();
if (appConfig.modelSpecs?.list?.length && appConfig.modelSpecs?.enforce) {
/** @type {{ list: TModelSpec[] }}*/
const { list } = appConfig.modelSpecs;
@@ -126,6 +128,7 @@ async function buildEndpointOption(req, res, next) {
});
parsedBody = result.parsedBody;
appliedModelSpecPrivateFields = result.appliedPrivateFields;
+ enforcedModelSpecFields = result.enforcedFields;
} catch (error) {
logger.error('Error parsing model spec', error);
return handleError(res, { text: 'Error parsing model spec' });
@@ -180,6 +183,21 @@ async function buildEndpointOption(req, res, next) {
req.body = req.body || {}; // Express 5: ensure req.body exists
req.body.endpointOption = await builder(endpoint, parsedBody, endpointType);
+ const reasoningApplied = await applyRequestReasoningOverride(req, {
+ reasoningOverride: req.body.reasoningOverride,
+ endpoint,
+ endpointType,
+ parsedModel: parsedBody.model,
+ isAgent: isAgents,
+ endpointsConfig,
+ defaultParamsEndpoint,
+ appliedModelSpecPrivateFields,
+ enforcedModelSpecFields,
+ });
+ if (!reasoningApplied) {
+ return handleError(res, { text: 'Invalid reasoning override' });
+ }
+
if (req.body.files && !isAgents) {
req.body.endpointOption.attachments = updateFilesUsage(req.body.files, undefined, {
user: req.user.id,
diff --git a/api/server/middleware/buildEndpointOption.spec.js b/api/server/middleware/buildEndpointOption.spec.js
index 9330cd0e70..b4ecd4cd61 100644
--- a/api/server/middleware/buildEndpointOption.spec.js
+++ b/api/server/middleware/buildEndpointOption.spec.js
@@ -150,6 +150,58 @@ describe('buildEndpointOption - defaultParamsEndpoint parsing', () => {
expect(parsedResult.temperature).toBe(0.7);
});
+ describe('request-scoped reasoning override wiring', () => {
+ it('passes an accepted override through to model_parameters', async () => {
+ mockGetEndpointsConfig.mockResolvedValue({});
+ mockAgentBuildOptions.mockReturnValueOnce({
+ endpoint: EModelEndpoint.openAI,
+ model_parameters: { model: 'gpt-5.1', reasoning_effort: 'low' },
+ agent: Promise.resolve({ provider: EModelEndpoint.openAI, model: 'gpt-5.1' }),
+ });
+ const req = createReq(
+ {
+ endpoint: EModelEndpoint.openAI,
+ model: 'gpt-5.1',
+ reasoningOverride: { key: 'reasoning_effort', value: 'high' },
+ },
+ { modelSpecs: null },
+ );
+ req.baseUrl = '/api/agents/chat';
+ const next = jest.fn();
+
+ await buildEndpointOption(req, createRes(), next);
+
+ expect(req.body.endpointOption.model_parameters.reasoning_effort).toBe('high');
+ expect(next).toHaveBeenCalled();
+ });
+
+ it('turns a rejected override into an error response without calling next', async () => {
+ mockGetEndpointsConfig.mockResolvedValue({});
+ mockAgentBuildOptions.mockReturnValueOnce({
+ endpoint: EModelEndpoint.openAI,
+ model_parameters: { model: 'gpt-5.1', reasoning_effort: 'low' },
+ agent: Promise.resolve({ provider: EModelEndpoint.openAI, model: 'gpt-5.1' }),
+ });
+ const req = createReq(
+ {
+ endpoint: EModelEndpoint.openAI,
+ model: 'gpt-5.1',
+ reasoningOverride: { key: 'effort', value: 'high' },
+ },
+ { modelSpecs: null },
+ );
+ req.baseUrl = '/api/agents/chat';
+ const res = createRes();
+ const next = jest.fn();
+ const { handleError } = require('@librechat/api');
+
+ await buildEndpointOption(req, res, next);
+
+ expect(handleError).toHaveBeenCalledWith(res, { text: 'Invalid reasoning override' });
+ expect(next).not.toHaveBeenCalled();
+ });
+ });
+
it('should strip bedrock region from custom endpoint without defaultParamsEndpoint', async () => {
mockGetEndpointsConfig.mockResolvedValue({
MyEndpoint: {
diff --git a/api/server/routes/__tests__/config.spec.js b/api/server/routes/__tests__/config.spec.js
index 2b8e6c02e6..f792ca35ad 100644
--- a/api/server/routes/__tests__/config.spec.js
+++ b/api/server/routes/__tests__/config.spec.js
@@ -560,6 +560,22 @@ describe('GET /api/config', () => {
expect(response.body.interface).toEqual(baseAppConfig.interfaceConfig);
});
+ it('delivers the configured steer arm confirmation timeout to authenticated clients', async () => {
+ mockGetAppConfig.mockResolvedValue({
+ ...baseAppConfig,
+ interfaceConfig: {
+ ...baseAppConfig.interfaceConfig,
+ steerArmConfirmationTimeoutMs: 30_000,
+ },
+ });
+ const app = createApp(mockUser);
+
+ const response = await request(app).get('/api/config');
+
+ expect(response.statusCode).toBe(200);
+ expect(response.body.interface.steerArmConfirmationTimeoutMs).toBe(30_000);
+ });
+
it('should include authenticated-only env var fields', async () => {
mockGetAppConfig.mockResolvedValue(baseAppConfig);
process.env.SANDPACK_BUNDLER_URL = 'https://bundler.test';
diff --git a/api/server/routes/agents/__tests__/chat.contentFilter.spec.js b/api/server/routes/agents/__tests__/chat.contentFilter.spec.js
index b6439ee18d..01602cb7b7 100644
--- a/api/server/routes/agents/__tests__/chat.contentFilter.spec.js
+++ b/api/server/routes/agents/__tests__/chat.contentFilter.spec.js
@@ -16,7 +16,7 @@ jest.mock('@librechat/api', () => ({
createMessageFilterPii: mockCreateMessageFilterPii,
generateCheckAccess: jest.fn(() => (_req, _res, next) => next()),
skipAgentCheck: jest.fn(),
- applyResumeContext: jest.fn(),
+ applyResumeRequest: jest.fn(),
GenerationJobManager: {
getJob: jest.fn(),
},
diff --git a/api/server/routes/agents/__tests__/responses.spec.js b/api/server/routes/agents/__tests__/responses.spec.js
index cddeaf95b7..07812ec85e 100644
--- a/api/server/routes/agents/__tests__/responses.spec.js
+++ b/api/server/routes/agents/__tests__/responses.spec.js
@@ -77,7 +77,9 @@ jest.mock('~/config', () => ({
createMCPManager: jest.fn().mockResolvedValue({
getAppToolFunctions: jest.fn().mockResolvedValue({}),
}),
- getMCPManager: jest.fn().mockReturnValue({}),
+ getMCPManager: jest.fn(() => ({
+ formatInstructionsForContext: jest.fn().mockResolvedValue(''),
+ })),
}));
const express = require('express');
diff --git a/api/server/routes/agents/chat.js b/api/server/routes/agents/chat.js
index 16ecf54fd0..6f64883aec 100644
--- a/api/server/routes/agents/chat.js
+++ b/api/server/routes/agents/chat.js
@@ -5,8 +5,7 @@ const {
reportLocatorTraversalFailure,
generateCheckAccess,
skipAgentCheck,
- applyResumeContext,
- applyResumeModelParameters,
+ applyResumeRequest,
GenerationJobManager,
getSafeErrorMetadata,
} = require('@librechat/api');
@@ -53,16 +52,7 @@ const restoreResumeContext = async (req, res, next) => {
const streamId = req.body?.conversationId;
if (streamId) {
const job = await GenerationJobManager.getJob(streamId);
- const resumeContext = job?.metadata?.pendingAction?.resumeContext;
- applyResumeContext(req.body, resumeContext);
- // Replay the paused turn's resolved model parameters. Ephemeral agents derive these
- // (temperature, max tokens, custom endpoint params) from the request body, which the
- // resume payload omits — without this the continuation runs with defaults. They're
- // scattered top-level fields (folded into model_parameters by buildOptions' rest
- // spread), not part of the RESUME_CONTEXT_KEYS allowlist, so merge them back here.
- // Generation params are authoritative, but routing, graph identity, and resume-action
- // fields remain owned by the restored context/request envelope.
- applyResumeModelParameters(req.body, resumeContext?.model_parameters);
+ applyResumeRequest(req, job?.metadata?.pendingAction?.resumeContext);
}
} catch (err) {
logger.warn('[agents/chat] Failed to restore resume context', getSafeErrorMetadata(err));
diff --git a/api/server/routes/files/files.js b/api/server/routes/files/files.js
index f6b97e587f..8e90bd15fc 100644
--- a/api/server/routes/files/files.js
+++ b/api/server/routes/files/files.js
@@ -5,6 +5,7 @@ const {
logAxiosError,
getSafeErrorMetadata,
getApprovalTtlMs,
+ handleFileListRequest,
refreshS3FileUrls,
handleFilesUsageRequest,
buildDeleteFilesResponse,
@@ -24,9 +25,7 @@ const {
resolveDownloadPath,
} = require('@librechat/api');
const {
- Time,
isUUID,
- CacheKeys,
FileSources,
ResourceType,
EModelEndpoint,
@@ -55,8 +54,8 @@ const { hasCapability } = require('~/server/middleware/roles/capabilities');
const { getRoleByName } = require('~/models');
const { checkPermission } = require('~/server/services/PermissionService');
const { cleanFileName, getContentDisposition } = require('~/server/utils/files');
-const { getLogStores } = require('~/cache');
const { Readable } = require('stream');
+const { getLogStores } = require('~/cache');
const db = require('~/models');
const router = express.Router();
@@ -71,23 +70,23 @@ const AGENT_TOOL_RESOURCE_KEYS = new Set([
const isAgentToolResourceKey = (toolResource) =>
typeof toolResource === 'string' && AGENT_TOOL_RESOURCE_KEYS.has(toolResource);
+/** Register the list endpoint as a thin adapter around the shared file-list policy. */
router.get('/', async (req, res) => {
try {
- const appConfig = req.config;
- const files = await db.getFiles({ user: req.user.id });
- if (appConfig.fileStrategy === FileSources.s3) {
- try {
- const cache = getLogStores(CacheKeys.S3_EXPIRY_INTERVAL);
- const alreadyChecked = await cache.get(req.user.id);
- if (!alreadyChecked) {
- await refreshS3FileUrls(files, db.batchUpdateFiles);
- await cache.set(req.user.id, true, Time.THIRTY_MINUTES);
- }
- } catch (error) {
- logger.warn('[/files] Error refreshing S3 file URLs:', error);
- }
- }
- res.status(200).send(files);
+ const responseFiles = await handleFileListRequest({
+ userId: req.user.id,
+ rawLimit: req.query.limit,
+ fileStrategy: req.config?.fileStrategy,
+ maxLimit: req.config?.fileListLimit,
+ dependencies: {
+ getFiles: db.getFiles,
+ batchUpdateFiles: db.batchUpdateFiles,
+ refreshS3FileUrls,
+ getLogStores,
+ logger,
+ },
+ });
+ res.status(200).send(responseFiles);
} catch (error) {
logger.error('[/files] Error getting files:', error);
res.status(400).json({ message: 'Error in request', error: error.message });
diff --git a/api/server/routes/files/list.spec.js b/api/server/routes/files/list.spec.js
new file mode 100644
index 0000000000..ce6302ce2a
--- /dev/null
+++ b/api/server/routes/files/list.spec.js
@@ -0,0 +1,123 @@
+/**
+ * GET /files is intentionally covered as wiring only. The list policy lives in
+ * packages/api and has its behavioral coverage in files/list.spec.ts.
+ */
+
+jest.mock('@librechat/data-schemas', () => ({
+ logger: { warn: jest.fn(), debug: jest.fn(), error: jest.fn(), info: jest.fn() },
+ SystemCapabilities: {},
+}));
+
+const mockHandleFileListRequest = jest.fn();
+const mockRefreshS3FileUrls = jest.fn();
+jest.mock('@librechat/api', () => ({
+ handleFileListRequest: (...args) => mockHandleFileListRequest(...args),
+ refreshS3FileUrls: (...args) => mockRefreshS3FileUrls(...args),
+ resolveUploadErrorMessage: jest.fn(),
+ verifyAgentUploadPermission: jest.fn(),
+}));
+
+jest.mock('~/models', () => ({
+ findFileById: jest.fn(),
+ getFiles: jest.fn(),
+ updateFile: jest.fn(),
+ getAgents: jest.fn().mockResolvedValue([]),
+ batchUpdateFiles: jest.fn(),
+}));
+
+jest.mock('~/server/services/Files/process', () => ({
+ filterFile: jest.fn(),
+ processFileUpload: jest.fn(),
+ processDeleteRequest: jest.fn().mockResolvedValue({ deletedFileIds: [], failedFileIds: [] }),
+ processAgentFileUpload: jest.fn(),
+}));
+
+jest.mock('~/server/services/Files/strategies', () => ({
+ getStrategyFunctions: jest.fn(() => ({})),
+}));
+
+jest.mock('~/server/controllers/assistants/helpers', () => ({
+ getOpenAIClient: jest.fn(),
+}));
+
+jest.mock('~/server/middleware/roles/capabilities', () => ({
+ hasCapability: jest.fn(() => (_req, _res, next) => next()),
+}));
+
+jest.mock('~/server/services/PermissionService', () => ({
+ checkPermission: jest.fn(() => (_req, _res, next) => next()),
+ getEffectivePermissions: jest.fn().mockResolvedValue(0),
+}));
+
+jest.mock('~/server/services/Files', () => ({
+ hasAccessToFilesViaAgent: jest.fn(),
+}));
+
+const mockGetLogStores = jest.fn();
+jest.mock('~/cache', () => ({
+ getLogStores: (...args) => mockGetLogStores(...args),
+}));
+
+const express = require('express');
+const request = require('supertest');
+const { FileSources } = require('librechat-data-provider');
+const filesRouter = require('./files');
+
+function buildApp(config = { fileStrategy: FileSources.local, fileListLimit: 100 }) {
+ const app = express();
+ app.use(express.json());
+ app.use((req, _res, next) => {
+ req.user = { id: 'user-123', role: 'user' };
+ req.config = config;
+ next();
+ });
+ app.use('/files', filesRouter);
+ return app;
+}
+
+describe('GET /files wiring', () => {
+ beforeEach(() => {
+ mockHandleFileListRequest.mockReset();
+ mockGetLogStores.mockReset();
+ });
+
+ it('sends the list returned by the shared policy and threads request configuration', async () => {
+ const files = [{ file_id: 'f1' }];
+ mockHandleFileListRequest.mockResolvedValue(files);
+ const config = { fileStrategy: FileSources.s3, fileListLimit: 250 };
+
+ const res = await request(buildApp(config)).get('/files?limit=12');
+
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual(files);
+ expect(mockHandleFileListRequest).toHaveBeenCalledWith(
+ expect.objectContaining({
+ userId: 'user-123',
+ rawLimit: '12',
+ fileStrategy: FileSources.s3,
+ maxLimit: 250,
+ }),
+ );
+ expect(mockHandleFileListRequest.mock.calls[0][0].dependencies).toEqual(
+ expect.objectContaining({
+ getFiles: expect.any(Function),
+ batchUpdateFiles: expect.any(Function),
+ refreshS3FileUrls: expect.any(Function),
+ getLogStores: expect.any(Function),
+ logger: expect.any(Object),
+ }),
+ );
+ });
+
+ it('keeps the route error response when the shared policy rejects', async () => {
+ mockHandleFileListRequest.mockRejectedValue(new Error('database unavailable'));
+
+ const res = await request(buildApp()).get('/files');
+
+ expect(res.status).toBe(400);
+ expect(res.body).toEqual({
+ message: 'Error in request',
+ error: 'database unavailable',
+ });
+ });
+});
diff --git a/client/src/Providers/BadgeRowContext.tsx b/client/src/Providers/BadgeRowContext.tsx
index 59388825a2..8229a2dfd1 100644
--- a/client/src/Providers/BadgeRowContext.tsx
+++ b/client/src/Providers/BadgeRowContext.tsx
@@ -280,19 +280,38 @@ export default function BadgeRowProvider({
observeToolAuthorization,
});
- const value: BadgeRowContextType = {
- skills,
- memory,
- webSearch,
- artifacts,
- fileSearch,
- agentsConfig,
- conversationId,
- storageContextKey,
- codeInterpreter,
- searchApiKeyForm,
- mcpServerManager,
- };
+ /* Memoized because this is an inline child of `ChatForm`, which re-renders on
+ every keystroke: a fresh value here invalidated every consumer's memo, and
+ the palette rebuilt its whole tool, skill and server catalog per character
+ typed. */
+ const value = useMemo<BadgeRowContextType>(
+ () => ({
+ skills,
+ memory,
+ webSearch,
+ artifacts,
+ fileSearch,
+ agentsConfig,
+ conversationId,
+ storageContextKey,
+ codeInterpreter,
+ searchApiKeyForm,
+ mcpServerManager,
+ }),
+ [
+ skills,
+ memory,
+ webSearch,
+ artifacts,
+ fileSearch,
+ agentsConfig,
+ conversationId,
+ storageContextKey,
+ codeInterpreter,
+ searchApiKeyForm,
+ mcpServerManager,
+ ],
+ );
return <BadgeRowContext.Provider value={value}>{children}</BadgeRowContext.Provider>;
}
diff --git a/client/src/Providers/ComposerRestoreContext.tsx b/client/src/Providers/ComposerRestoreContext.tsx
new file mode 100644
index 0000000000..fdab9589ae
--- /dev/null
+++ b/client/src/Providers/ComposerRestoreContext.tsx
@@ -0,0 +1,81 @@
+import { createContext, useCallback, useContext, useMemo, useRef } from 'react';
+import type { TMessage } from 'librechat-data-provider';
+import type { ReactNode } from 'react';
+import type { QueuedMessageContext } from '~/hooks/Chat/useSteering';
+
+/** Restores a message's text, attachments and compose-time context into the
+ * composer, or refuses (false) when the composer is occupied, unmounted, or
+ * showing another chat. A refusal means the caller must re-home the words
+ * somewhere else rather than drop them. */
+export type RestoreToComposer = (
+ text: string,
+ files: TMessage['files'],
+ context: QueuedMessageContext,
+ originConversationId: string,
+) => boolean;
+
+/** Re-posts a conversation's spent run-end signal so its queue drain wakes. */
+export type RewakeDrain = (conversationId: string) => void;
+
+interface ComposerRestoreHost {
+ /** The composer publishes its guarded restore here while it is mounted. */
+ publish: (restore: RestoreToComposer | null) => void;
+ /** Resolved at call time: a recovery round-trip can settle long after the
+ * composer that started it has gone. */
+ restore: RestoreToComposer;
+ /** The composer publishes its drain wake-up here while it is mounted. */
+ publishRewake: (rewake: RewakeDrain | null) => void;
+ /** Resolved at call time like `restore`; a no-op with no composer mounted,
+ * which leaves a queued row for the next run end or an explicit send. */
+ rewakeDrain: RewakeDrain;
+}
+
+const refuse: RestoreToComposer = () => false;
+
+const ComposerRestoreContext = createContext<ComposerRestoreHost>({
+ publish: () => {},
+ restore: refuse,
+ publishRewake: () => {},
+ rewakeDrain: () => {},
+});
+
+/**
+ * Lets surfaces outside the composer hand a message back to it: into the
+ * draft, or into the queue with the drain woken to pick it up.
+ *
+ * The composer is a sibling of the message list, not its ancestor, so a
+ * pending steer cancelled from the thread cannot reach the restore the queue
+ * rail gets as a prop. The pane's host holds the reference instead, and both
+ * sides read it here: the thread never reaches into composer state, and a
+ * restore that resolves after the composer unmounted refuses rather than
+ * writing into a dead form.
+ */
+export function ComposerRestoreProvider({ children }: { children?: ReactNode }) {
+ const restoreRef = useRef<RestoreToComposer | null>(null);
+ const publish = useCallback((restore: RestoreToComposer | null) => {
+ restoreRef.current = restore;
+ }, []);
+ const restore = useCallback<RestoreToComposer>(
+ (text, files, context, originConversationId) =>
+ restoreRef.current?.(text, files, context, originConversationId) ?? false,
+ [],
+ );
+ const rewakeRef = useRef<RewakeDrain | null>(null);
+ const publishRewake = useCallback((rewake: RewakeDrain | null) => {
+ rewakeRef.current = rewake;
+ }, []);
+ const rewakeDrain = useCallback<RewakeDrain>((conversationId) => {
+ rewakeRef.current?.(conversationId);
+ }, []);
+ const value = useMemo(
+ () => ({ publish, restore, publishRewake, rewakeDrain }),
+ [publish, restore, publishRewake, rewakeDrain],
+ );
+ return (
+ <ComposerRestoreContext.Provider value={value}>{children}</ComposerRestoreContext.Provider>
+ );
+}
+
+export function useComposerRestoreHost(): ComposerRestoreHost {
+ return useContext(ComposerRestoreContext);
+}
diff --git a/client/src/Providers/__tests__/BadgeRowContext.spec.tsx b/client/src/Providers/__tests__/BadgeRowContext.spec.tsx
new file mode 100644
index 0000000000..9d0cf5e3fa
--- /dev/null
+++ b/client/src/Providers/__tests__/BadgeRowContext.spec.tsx
@@ -0,0 +1,110 @@
+import React from 'react';
+import { RecoilRoot } from 'recoil';
+import { render } from '@testing-library/react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import BadgeRowProvider, { useBadgeRowContext } from '../BadgeRowContext';
+
+/**
+ * `BadgeRowProvider` is an inline child of `ChatForm`, which re-renders on every
+ * keystroke in the composer. Its context value is memoized for exactly that
+ * reason, but a memo is only worth as much as its dependencies, and two of them
+ * were hooks handing back a fresh object literal every render. The value changed
+ * on each character typed, and every consumer of it rebuilt: the palette's whole
+ * tool, skill and MCP server catalog, per keystroke.
+ */
+
+/* Held outside the factory so it is one function for the whole test, the way
+ the real `ToastProvider` sits above the composer and does not re-render with
+ it. A fresh `showToast` per render would be the mock's instability, not the
+ provider's. */
+const mockShowToast = jest.fn();
+jest.mock('@librechat/client', () => ({
+ useToastContext: () => ({ showToast: mockShowToast }),
+}));
+
+/* The suite-wide `react-i18next` stub builds a new `t` on every render, which
+ the real one does not: it holds `t` in state and replaces it only when the
+ language or namespace changes. Left as-is, every `useLocalize` consumer here
+ would look unstable for a reason that does not exist outside the tests. */
+const mockTranslate = (key: string) => key;
+const mockToolAuth = { authenticated: false };
+jest.mock('react-i18next', () => ({
+ ...jest.requireActual('react-i18next'),
+ useTranslation: () => ({ t: mockTranslate, i18n: { changeLanguage: jest.fn() } }),
+}));
+
+/* Startup config and the server catalog are external HTTP queries. Their
+ contents do not matter to this identity test, and leaving them live lets a
+ rejected `/api/config` request report after Jest has torn the test down. */
+jest.mock('~/data-provider', () => ({
+ ...jest.requireActual('~/data-provider'),
+ useGetEndpointsQuery: () => ({ data: undefined }),
+ useGetStartupConfig: () => ({ data: undefined }),
+ useMCPServersQuery: () => ({ data: undefined, isLoading: false }),
+ useVerifyAgentToolAuth: () => ({ data: mockToolAuth }),
+}));
+
+function renderProvider() {
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false, cacheTime: 0 } },
+ });
+ let value: ReturnType<typeof useBadgeRowContext>;
+ const Consumer = () => {
+ value = useBadgeRowContext();
+ return null;
+ };
+ const Tree = ({ marker }: { marker: number }) => (
+ <QueryClientProvider client={client}>
+ <RecoilRoot>
+ <BadgeRowProvider conversationId="convo-badge-row">
+ {/* Re-rendered along with the provider, the way `Bar` is. */}
+ <span>{marker}</span>
+ <Consumer />
+ </BadgeRowProvider>
+ </RecoilRoot>
+ </QueryClientProvider>
+ );
+ const { rerender } = render(<Tree marker={0} />);
+ return {
+ getValue: () => value,
+ retype: (marker: number) => rerender(<Tree marker={marker} />),
+ };
+}
+
+describe('BadgeRowProvider', () => {
+ it('hands consumers the same value across a parent re-render', () => {
+ const { getValue, retype } = renderProvider();
+ const first = getValue();
+ retype(1);
+ expect(getValue()).toBe(first);
+ retype(2);
+ expect(getValue()).toBe(first);
+ });
+
+ /* The two that were rebuilding: both are carried into the context value
+ whole, so an unstable reference from either defeats the memo by itself. */
+ it('keeps the search form and MCP manager referentially stable', () => {
+ const { getValue, retype } = renderProvider();
+ const first = getValue();
+ retype(1);
+
+ const last = getValue();
+ expect(last?.searchApiKeyForm).toBe(first?.searchApiKeyForm);
+ expect(last?.mcpServerManager).toBe(first?.mcpServerManager);
+ });
+
+ /* Without this the cases above would still pass against a provider that had
+ stopped providing: every value would be `undefined`, and identical. */
+ it('is undefined outside the provider, and an object inside it', () => {
+ let outside: unknown = 'unset';
+ const Consumer = () => {
+ outside = useBadgeRowContext();
+ return null;
+ };
+ render(<Consumer />);
+ expect(outside).toBeUndefined();
+
+ const { getValue } = renderProvider();
+ expect(getValue()).toEqual(expect.objectContaining({ conversationId: 'convo-badge-row' }));
+ });
+});
diff --git a/client/src/Providers/index.ts b/client/src/Providers/index.ts
index f0803f4b15..a0c3771c4f 100644
--- a/client/src/Providers/index.ts
+++ b/client/src/Providers/index.ts
@@ -28,5 +28,6 @@ export * from './ArtifactsContext';
export * from './PromptGroupsContext';
export * from './MessagesViewContext';
export * from './MCPAppsPolicyContext';
+export * from './ComposerRestoreContext';
export * from './MediaContext';
export { default as BadgeRowProvider } from './BadgeRowContext';
diff --git a/client/src/common/types.ts b/client/src/common/types.ts
index 15fefa73c5..4ba4299949 100644
--- a/client/src/common/types.ts
+++ b/client/src/common/types.ts
@@ -370,6 +370,8 @@ export type TOptions = {
* context even though the references still show on the user bubble.
*/
overrideQuotes?: string[];
+ /** Request-scoped reasoning selection for this exact submission. */
+ overrideReasoning?: t.TReasoningOverride | null;
/** Added conversation for multi-convo feature - sent to server as part of submission payload */
addedConvo?: t.TConversation;
/** Reuse a durable submission identity (terminal steer recovery). */
diff --git a/client/src/components/Chat/ChatView.tsx b/client/src/components/Chat/ChatView.tsx
index 9a1b3f0f69..fbf26cf3e9 100644
--- a/client/src/components/Chat/ChatView.tsx
+++ b/client/src/components/Chat/ChatView.tsx
@@ -17,11 +17,18 @@ import {
useQueuedTurnReveal,
useLocalize,
} from '~/hooks';
-import { ChatContext, AddedChatContext, ChatFormProvider, useFileMapContext } from '~/Providers';
-import { QueuedTurnPortalProvider } from './Steering/QueuedTurnPortal';
+import {
+ ChatContext,
+ AddedChatContext,
+ ChatFormProvider,
+ useFileMapContext,
+ ComposerRestoreProvider,
+} from '~/Providers';
import ApprovalProvider from './Messages/Content/ApprovalContext';
import ConversationStarters from './Input/ConversationStarters';
import { pendingApprovalActionFamily } from './approval/state';
+import { composerLiftFamily } from './Input/Composer/state';
+import { showComposerTipsAtom } from '~/store/composerTips';
import { useGetMessagesByConvoId } from '~/data-provider';
import Footer, { useConfiguredFooter } from './Footer';
import { AskAnswerHostProvider } from './ask/state';
@@ -50,6 +57,10 @@ function ChatView({ index = 0, project }: { index?: number; project?: TChatProje
const rootSubmission = useRecoilValue(store.submissionByIndex(index));
const isSubmitting = useRecoilValue(store.isSubmittingFamily(index));
const saveDrafts = useRecoilValue(store.saveDrafts);
+ const showComposerTips = useAtomValue(showComposerTipsAtom);
+ const enterToSend = useRecoilValue(store.enterToSend);
+ const autoSendText = useRecoilValue(store.autoSendText);
+ const speechSettingsInitialized = useRecoilValue(store.speechSettingsInitialized);
const centerFormOnLanding = useRecoilValue(store.centerFormOnLanding);
const pendingAction = useAtomValue(
pendingApprovalActionFamily(conversationId ?? Constants.NEW_CONVO),
@@ -64,6 +75,9 @@ function ChatView({ index = 0, project }: { index?: number; project?: TChatProje
* before the config answers, so a cold load does not jump. */
const configuredFooter = useConfiguredFooter();
+ /** Room an open composer popover needs below the composer; see the atom. */
+ const composerLift = useAtomValue(composerLiftFamily(index));
+
const methods = useForm<ChatFormValues>({
defaultValues: { text: '' },
});
@@ -159,19 +173,29 @@ function ChatView({ index = 0, project }: { index?: number; project?: TChatProje
return (
<AskAnswerHostProvider saveDrafts={saveDrafts}>
<ChatFormProvider {...methods}>
- <ChatContext.Provider value={chatHelpers}>
- <AddedChatContext.Provider value={addedChatHelpers}>
- <ApprovalProvider pendingAction={pendingAction}>
- <QueuedTurnPortalProvider>
+ <ComposerRestoreProvider>
+ <ChatContext.Provider value={chatHelpers}>
+ <AddedChatContext.Provider value={addedChatHelpers}>
+ <ApprovalProvider pendingAction={pendingAction}>
<Presentation>
<TraceSurface conversationId={conversationId}>
<h1 className="sr-only">{pageHeading}</h1>
- <Header
- parentConversationId={parentConversationId}
- readOnly={isSubagentThreadReadOnly}
- />
+ {/* 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
+ parentConversationId={parentConversationId}
+ readOnly={isSubagentThreadReadOnly}
+ />
+ </div>
<>
<div
+ data-chat-pane={index}
+ style={
+ isLandingPage && composerLift > 0
+ ? { transform: `translateY(-${composerLift}px)` }
+ : undefined
+ }
className={cn(
'flex flex-col',
isLandingPage
@@ -192,12 +216,10 @@ 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. The named surface
- is a stacking context; keep it above positioned tool glyphs
- so they cannot paint through the approval preview. */}
+ page, so normal rendering is unchanged. */}
<div
className={cn(
- 'bg-surface-primary-alt relative z-10 w-full [view-transition-name:chat-form]',
+ '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',
)}
@@ -216,13 +238,17 @@ function ChatView({ index = 0, project }: { index?: number; project?: TChatProje
placeholder={chatFormPlaceholder}
project={isProjectLandingPage ? project : undefined}
isLandingPage={isLandingPage}
+ showComposerTips={showComposerTips}
+ enterToSend={enterToSend}
+ autoSendText={autoSendText}
+ speechSettingsInitialized={speechSettingsInitialized}
footerBelow={footerBelow}
centerFormOnLanding={centerFormOnLanding}
/>
)}
- {/* The generic disclaimer is the welcome screen's; a
- deployment's own footer, privacy policy and terms
- stay with the conversation that always showed them. */}
+ {/* 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 />}
</div>
</div>
@@ -230,10 +256,10 @@ function ChatView({ index = 0, project }: { index?: number; project?: TChatProje
</>
</TraceSurface>
</Presentation>
- </QueuedTurnPortalProvider>
- </ApprovalProvider>
- </AddedChatContext.Provider>
- </ChatContext.Provider>
+ </ApprovalProvider>
+ </AddedChatContext.Provider>
+ </ChatContext.Provider>
+ </ComposerRestoreProvider>
</ChatFormProvider>
</AskAnswerHostProvider>
);
diff --git a/client/src/components/Chat/Input/Artifacts.tsx b/client/src/components/Chat/Input/Artifacts.tsx
deleted file mode 100644
index f60202a5c2..0000000000
--- a/client/src/components/Chat/Input/Artifacts.tsx
+++ /dev/null
@@ -1,182 +0,0 @@
-import React, { memo, useState, useCallback, useMemo, useEffect } from 'react';
-import * as Ariakit from '@ariakit/react';
-import { CheckboxButton } from '@librechat/client';
-import { WandSparkles, ChevronDown } from 'lucide-react';
-import { ArtifactModes, defaultAgentCapabilities } from 'librechat-data-provider';
-import { useLocalize, useAgentCapabilities } from '~/hooks';
-import { useBadgeRowContext } from '~/Providers';
-import { badgeAccents } from './accents';
-import { cn } from '~/utils';
-
-interface ArtifactsToggleState {
- enabled: boolean;
- mode: string;
-}
-
-function Artifacts() {
- const localize = useLocalize();
- const context = useBadgeRowContext();
- const { toggleState, debouncedChange, isPinned } = context?.artifacts ?? {};
-
- const { artifactsEnabled } = useAgentCapabilities(
- context?.agentsConfig?.capabilities ?? defaultAgentCapabilities,
- );
-
- const [isPopoverOpen, setIsPopoverOpen] = useState(false);
- const [isButtonExpanded, setIsButtonExpanded] = useState(false);
-
- const currentState = useMemo<ArtifactsToggleState>(() => {
- if (typeof toggleState === 'string' && toggleState) {
- return { enabled: true, mode: toggleState };
- }
- return { enabled: false, mode: '' };
- }, [toggleState]);
-
- const isEnabled = currentState.enabled;
- const isShadcnEnabled = currentState.mode === ArtifactModes.SHADCNUI;
- const isCustomEnabled = currentState.mode === ArtifactModes.CUSTOM;
-
- const handleToggle = useCallback(() => {
- if (!debouncedChange) return;
- if (isEnabled) {
- debouncedChange({ value: '' });
- setIsButtonExpanded(false);
- } else {
- debouncedChange({ value: ArtifactModes.DEFAULT });
- }
- }, [isEnabled, debouncedChange]);
-
- const handleMenuButtonClick = useCallback(
- (e: React.MouseEvent) => {
- e.stopPropagation();
- setIsButtonExpanded(!isButtonExpanded);
- },
- [isButtonExpanded],
- );
-
- useEffect(() => {
- if (!isPopoverOpen) {
- setIsButtonExpanded(false);
- }
- }, [isPopoverOpen]);
-
- const handleShadcnToggle = useCallback(() => {
- if (!debouncedChange) return;
- if (isShadcnEnabled) {
- debouncedChange({ value: ArtifactModes.DEFAULT });
- } else {
- debouncedChange({ value: ArtifactModes.SHADCNUI });
- }
- }, [isShadcnEnabled, debouncedChange]);
-
- const handleCustomToggle = useCallback(() => {
- if (!debouncedChange) return;
- if (isCustomEnabled) {
- debouncedChange({ value: ArtifactModes.DEFAULT });
- } else {
- debouncedChange({ value: ArtifactModes.CUSTOM });
- }
- }, [isCustomEnabled, debouncedChange]);
-
- if (!artifactsEnabled) {
- return null;
- }
-
- if (!isEnabled && !isPinned) {
- return null;
- }
-
- return (
- <div className="flex">
- <CheckboxButton
- className={cn(isEnabled && 'rounded-r-none border-r-0')}
- checked={isEnabled}
- setValue={handleToggle}
- label={localize('com_ui_artifacts')}
- isCheckedClassName={badgeAccents.amber}
- icon={<WandSparkles className="icon-md" aria-hidden="true" />}
- />
-
- {isEnabled && (
- <Ariakit.MenuProvider open={isPopoverOpen} setOpen={setIsPopoverOpen}>
- <Ariakit.MenuButton
- className={cn(
- 'border-border-light w-7 rounded-l-none rounded-r-full border-t border-r border-b border-l-0 md:w-6',
- badgeAccents.amber,
- 'transition-colors',
- )}
- onClick={handleMenuButtonClick}
- >
- <ChevronDown
- className={cn(
- 'text-text-secondary ml-1 h-4 w-4 transition-transform duration-300 md:ml-0.5',
- isButtonExpanded && 'rotate-180',
- )}
- aria-hidden="true"
- />
- </Ariakit.MenuButton>
-
- <Ariakit.Menu
- gutter={4}
- className={cn(
- 'animate-popover-top-left z-40 flex min-w-[250px] flex-col rounded-xl',
- 'border-border-light bg-surface-secondary border shadow-lg',
- )}
- portal={true}
- unmountOnHide={true}
- >
- <div className="px-2 py-1.5">
- <div className="text-text-secondary mb-2 text-xs font-medium">
- {localize('com_ui_artifacts_options')}
- </div>
-
- {/* Include shadcn/ui Option */}
- <Ariakit.MenuItem
- hideOnClick={false}
- onClick={(event) => {
- event.preventDefault();
- event.stopPropagation();
- handleShadcnToggle();
- }}
- className={cn(
- 'mb-1 flex items-center justify-between gap-2 rounded-lg px-2 py-2',
- 'bg-surface-secondary text-text-primary cursor-pointer outline-hidden transition-colors',
- 'hover:bg-surface-hover data-[active-item]:bg-surface-hover',
- isShadcnEnabled && 'bg-surface-active',
- )}
- >
- <span className="text-sm">{localize('com_ui_include_shadcnui' as any)}</span>
- <div className="ml-auto flex items-center">
- <Ariakit.MenuItemCheck checked={isShadcnEnabled} />
- </div>
- </Ariakit.MenuItem>
-
- {/* Custom Prompt Mode Option */}
- <Ariakit.MenuItem
- hideOnClick={false}
- onClick={(event) => {
- event.preventDefault();
- event.stopPropagation();
- handleCustomToggle();
- }}
- className={cn(
- 'mb-1 flex items-center justify-between gap-2 rounded-lg px-2 py-2',
- 'bg-surface-secondary text-text-primary cursor-pointer outline-hidden transition-colors',
- 'hover:bg-surface-hover data-[active-item]:bg-surface-hover',
- isCustomEnabled && 'bg-surface-active',
- )}
- >
- <span className="text-sm">{localize('com_ui_custom_prompt_mode' as any)}</span>
- <div className="ml-auto flex items-center">
- <Ariakit.MenuItemCheck checked={isCustomEnabled} />
- </div>
- </Ariakit.MenuItem>
- </div>
- </Ariakit.Menu>
- </Ariakit.MenuProvider>
- )}
- </div>
- );
-}
-
-export default memo(Artifacts);
diff --git a/client/src/components/Chat/Input/ArtifactsSubMenu.tsx b/client/src/components/Chat/Input/ArtifactsSubMenu.tsx
deleted file mode 100644
index e4f22f6e2c..0000000000
--- a/client/src/components/Chat/Input/ArtifactsSubMenu.tsx
+++ /dev/null
@@ -1,157 +0,0 @@
-import React from 'react';
-import * as Ariakit from '@ariakit/react';
-import { PinIcon } from '@librechat/client';
-import { ArtifactModes } from 'librechat-data-provider';
-import { ChevronRight, WandSparkles } from 'lucide-react';
-import { useLocalize } from '~/hooks';
-import { cn } from '~/utils';
-
-interface ArtifactsSubMenuProps extends React.HTMLAttributes<HTMLButtonElement> {
- isArtifactsPinned: boolean;
- setIsArtifactsPinned: (value: boolean) => void;
- artifactsMode: string;
- handleArtifactsToggle: () => void;
- handleShadcnToggle: () => void;
- handleCustomToggle: () => void;
-}
-
-const ArtifactsSubMenu = React.forwardRef<HTMLButtonElement, ArtifactsSubMenuProps>(
- (
- {
- isArtifactsPinned,
- setIsArtifactsPinned,
- artifactsMode,
- handleArtifactsToggle,
- handleShadcnToggle,
- handleCustomToggle,
- className,
- ...props
- },
- ref,
- ) => {
- const localize = useLocalize();
-
- const menuStore = Ariakit.useMenuStore({
- focusLoop: true,
- showTimeout: 100,
- placement: 'right',
- });
-
- const isEnabled = artifactsMode !== '' && artifactsMode !== undefined;
- const isShadcnEnabled = artifactsMode === ArtifactModes.SHADCNUI;
- const isCustomEnabled = artifactsMode === ArtifactModes.CUSTOM;
-
- return (
- <>
- <Ariakit.MenuProvider store={menuStore}>
- <Ariakit.MenuButton
- ref={ref}
- {...props}
- onClick={(e: React.MouseEvent<HTMLButtonElement>) => {
- e.stopPropagation();
- handleArtifactsToggle();
- }}
- onMouseEnter={() => {
- if (isEnabled) {
- menuStore.show();
- }
- }}
- className={cn(
- 'hover:bg-surface-hover flex w-full cursor-pointer items-center justify-between rounded-lg p-2',
- className,
- )}
- >
- <div className="flex items-center gap-2">
- <WandSparkles className="icon-md" aria-hidden="true" />
- <span>{localize('com_ui_artifacts')}</span>
- {isEnabled && <ChevronRight className="ml-auto h-3 w-3" aria-hidden="true" />}
- </div>
- <button
- type="button"
- onClick={(e) => {
- e.stopPropagation();
- setIsArtifactsPinned(!isArtifactsPinned);
- }}
- className={cn(
- 'rounded p-1 transition-all duration-200',
- 'hover:bg-surface-tertiary hover:shadow-xs',
- !isArtifactsPinned && 'text-text-secondary hover:text-text-primary',
- )}
- aria-label={isArtifactsPinned ? 'Unpin' : 'Pin'}
- >
- <div className="h-4 w-4">
- <PinIcon unpin={isArtifactsPinned} />
- </div>
- </button>
- </Ariakit.MenuButton>
-
- {isEnabled && (
- <Ariakit.Menu
- portal={true}
- unmountOnHide={true}
- gutter={12}
- shift={24}
- flip="left bottom-end top-end"
- className={cn(
- 'animate-popover-left z-40 flex max-w-[calc(100vw-1rem)] min-w-[min(250px,calc(100vw-1rem))] flex-col rounded-xl',
- 'border-border-light bg-surface-secondary border shadow-lg',
- )}
- >
- <div className="px-2 py-1.5">
- <div className="text-text-secondary mb-2 text-xs font-medium">
- {localize('com_ui_artifacts_options')}
- </div>
-
- {/* Include shadcn/ui Option */}
- <Ariakit.MenuItem
- hideOnClick={false}
- onClick={(event) => {
- event.preventDefault();
- event.stopPropagation();
- handleShadcnToggle();
- }}
- className={cn(
- 'mb-1 flex items-center justify-between gap-2 rounded-lg px-2 py-2',
- 'bg-surface-secondary text-text-primary cursor-pointer outline-hidden transition-colors',
- 'hover:bg-surface-hover data-[active-item]:bg-surface-hover',
- isShadcnEnabled && 'bg-surface-active',
- )}
- >
- <span className="text-sm">{localize('com_ui_include_shadcnui' as any)}</span>
- <div className="ml-auto flex items-center">
- <Ariakit.MenuItemCheck checked={isShadcnEnabled} />
- </div>
- </Ariakit.MenuItem>
-
- {/* Custom Prompt Mode Option */}
- <Ariakit.MenuItem
- hideOnClick={false}
- onClick={(event) => {
- event.preventDefault();
- event.stopPropagation();
- handleCustomToggle();
- }}
- className={cn(
- 'mb-1 flex items-center justify-between gap-2 rounded-lg px-2 py-2',
- 'bg-surface-secondary text-text-primary cursor-pointer outline-hidden transition-colors',
- 'hover:bg-surface-hover data-[active-item]:bg-surface-hover',
- isCustomEnabled && 'bg-surface-active',
- )}
- >
- <span className="text-sm">{localize('com_ui_custom_prompt_mode' as any)}</span>
- <div className="ml-auto flex items-center">
- <Ariakit.MenuItemCheck checked={isCustomEnabled} />
- </div>
- </Ariakit.MenuItem>
- </div>
- </Ariakit.Menu>
- )}
- </Ariakit.MenuProvider>
- </>
- );
- },
-);
-
-ArtifactsSubMenu.displayName = 'ArtifactsSubMenu';
-
-export default React.memo(ArtifactsSubMenu);
diff --git a/client/src/components/Chat/Input/AudioRecorder.tsx b/client/src/components/Chat/Input/AudioRecorder.tsx
deleted file mode 100644
index 3e5774b46a..0000000000
--- a/client/src/components/Chat/Input/AudioRecorder.tsx
+++ /dev/null
@@ -1,155 +0,0 @@
-import { memo, useCallback, useEffect, useRef } from 'react';
-import { MicOff } from 'lucide-react';
-import { useRecoilValue } from 'recoil';
-import {
- IconButton,
- useToastContext,
- TooltipAnchor,
- ListeningIcon,
- Spinner,
-} from '@librechat/client';
-import { useLocalize, useSpeechToText, useGetAudioSettings } from '~/hooks';
-import { globalAudioId, type TAskFunction } from '~/common';
-import { useChatFormContext } from '~/Providers';
-import store from '~/store';
-
-const isExternalSTT = (speechToTextEndpoint: string) => speechToTextEndpoint === 'external';
-export default memo(function AudioRecorder({
- disabled,
- ask,
- methods,
- isSubmitting,
-}: {
- disabled: boolean;
- ask: TAskFunction;
- methods: ReturnType<typeof useChatFormContext>;
- isSubmitting: boolean;
-}) {
- const { setValue, reset, getValues } = methods;
- const localize = useLocalize();
- const { showToast } = useToastContext();
- const { speechToTextEndpoint } = useGetAudioSettings();
- const speechSettingsInitialized = useRecoilValue(store.speechSettingsInitialized);
- const recorderDisabled = disabled || !speechSettingsInitialized;
-
- const existingTextRef = useRef<string>('');
- const isSubmittingRef = useRef(isSubmitting);
- isSubmittingRef.current = isSubmitting;
-
- const onTranscriptionComplete = useCallback(
- (text: string) => {
- if (isSubmittingRef.current) {
- showToast({
- message: localize('com_ui_speech_while_submitting'),
- status: 'error',
- });
- return;
- }
- if (text) {
- const globalAudio = document.getElementById(globalAudioId) as HTMLAudioElement | null;
- if (globalAudio) {
- console.log('Unmuting global audio');
- globalAudio.muted = false;
- }
- /** For external STT, append existing text to the transcription */
- const finalText =
- isExternalSTT(speechToTextEndpoint) && existingTextRef.current
- ? `${existingTextRef.current} ${text}`
- : text;
- const submitted = ask({ text: finalText });
- if (submitted === false) {
- return;
- }
- reset({ text: '' });
- existingTextRef.current = '';
- }
- },
- [ask, reset, showToast, localize, speechToTextEndpoint],
- );
-
- const setText = useCallback(
- (text: string) => {
- let newText = text;
- if (isExternalSTT(speechToTextEndpoint)) {
- /** For external STT, the text comes as a complete transcription, so append to existing */
- newText = existingTextRef.current ? `${existingTextRef.current} ${text}` : text;
- } else {
- /** For browser STT, the transcript is cumulative, so we only need to prepend the existing text once */
- newText = existingTextRef.current ? `${existingTextRef.current} ${text}` : text;
- }
- setValue('text', newText, {
- shouldValidate: true,
- });
- },
- [setValue, speechToTextEndpoint],
- );
-
- const { isListening, isLoading, startRecording, stopRecording } = useSpeechToText(
- setText,
- onTranscriptionComplete,
- );
-
- const handleStartRecording = useCallback(() => {
- existingTextRef.current = getValues('text') || '';
- startRecording();
- }, [getValues, startRecording]);
-
- const handleStopRecording = useCallback(() => {
- stopRecording();
- /** For browser STT, clear the reference since text was already being updated */
- if (!isExternalSTT(speechToTextEndpoint)) {
- existingTextRef.current = '';
- }
- }, [speechToTextEndpoint, stopRecording]);
-
- useEffect(() => {
- const handleKeyDown = (event: KeyboardEvent) => {
- if (!event.shiftKey || !event.altKey || event.code !== 'KeyL' || recorderDisabled) {
- return;
- }
-
- event.preventDefault();
- if (isListening === true) {
- handleStopRecording();
- return;
- }
-
- handleStartRecording();
- };
-
- window.addEventListener('keydown', handleKeyDown);
- return () => window.removeEventListener('keydown', handleKeyDown);
- }, [handleStartRecording, handleStopRecording, isListening, recorderDisabled]);
-
- const renderIcon = () => {
- if (isListening === true) {
- return <MicOff className="stroke-status-error" />;
- }
- if (isLoading === true) {
- return <Spinner className="stroke-text-secondary" />;
- }
- return <ListeningIcon className="stroke-text-secondary" />;
- };
-
- return (
- <TooltipAnchor
- description={localize('com_ui_use_micrphone')}
- render={
- <IconButton
- id="audio-recorder"
- type="button"
- variant="ghost"
- size="theme"
- shape="theme"
- label={localize('com_ui_use_micrphone')}
- onClick={isListening === true ? handleStopRecording : handleStartRecording}
- disabled={recorderDisabled}
- className="p-1 hover:bg-surface-composer-hover"
- aria-pressed={isListening}
- >
- {renderIcon()}
- </IconButton>
- }
- />
- );
-});
diff --git a/client/src/components/Chat/Input/BadgeRow.tsx b/client/src/components/Chat/Input/BadgeRow.tsx
deleted file mode 100644
index 2a0e010012..0000000000
--- a/client/src/components/Chat/Input/BadgeRow.tsx
+++ /dev/null
@@ -1,415 +0,0 @@
-import React, {
- memo,
- useRef,
- useMemo,
- useState,
- useEffect,
- forwardRef,
- useReducer,
- useCallback,
-} from 'react';
-import { Badge } from '@librechat/client';
-import { useRecoilValue, useRecoilCallback } from 'recoil';
-import type { LucideIcon } from 'lucide-react';
-import type { BadgeItem } from '~/common';
-import CodeInterpreter from './CodeInterpreter';
-import { BadgeRowProvider } from '~/Providers';
-import ToolsDropdown from './ToolsDropdown';
-import { useChatBadges } from '~/hooks';
-import ToolDialogs from './ToolDialogs';
-import FileSearch from './FileSearch';
-import Artifacts from './Artifacts';
-import MCPSelect from './MCPSelect';
-import WebSearch from './WebSearch';
-import Memory from './Memory';
-import Skills from './Skills';
-import store from '~/store';
-
-interface BadgeRowProps {
- showEphemeralBadges?: boolean;
- onChange: (badges: Pick<BadgeItem, 'id'>[]) => void;
- onToggle?: (badgeId: string, currentActive: boolean) => void;
- conversationId?: string | null;
- specName?: string | null;
- isSubmitting?: boolean;
- isInChat: boolean;
-}
-
-interface BadgeWrapperProps {
- badge: BadgeItem;
- isEditing: boolean;
- isInChat: boolean;
- onToggle: (badge: BadgeItem) => void;
- onDelete: (id: string) => void;
- onMouseDown: (e: React.MouseEvent, badge: BadgeItem, isActive: boolean) => void;
- badgeRefs: React.MutableRefObject<Record<string, HTMLDivElement>>;
-}
-
-const BadgeWrapper = React.memo(
- forwardRef<HTMLDivElement, BadgeWrapperProps>(
- ({ badge, isEditing, isInChat, onToggle, onDelete, onMouseDown, badgeRefs }, ref) => {
- const atomBadge = useRecoilValue(badge.atom);
- const isActive = badge.atom ? atomBadge : false;
-
- return (
- <div
- ref={(el) => {
- if (el) {
- badgeRefs.current[badge.id] = el;
- }
- if (typeof ref === 'function') {
- ref(el);
- } else if (ref) {
- ref.current = el;
- }
- }}
- onMouseDown={(e) => onMouseDown(e, badge, isActive)}
- className={isEditing ? 'ios-wiggle badge-icon h-full' : 'badge-icon h-full'}
- >
- <Badge
- id={badge.id}
- icon={badge.icon as LucideIcon}
- label={badge.label}
- isActive={isActive}
- isEditing={isEditing}
- isAvailable={badge.isAvailable}
- isInChat={isInChat}
- onToggle={() => onToggle(badge)}
- onBadgeAction={() => onDelete(badge.id)}
- />
- </div>
- );
- },
- ),
- (prevProps, nextProps) =>
- prevProps.badge.id === nextProps.badge.id &&
- prevProps.isEditing === nextProps.isEditing &&
- prevProps.isInChat === nextProps.isInChat &&
- prevProps.onToggle === nextProps.onToggle &&
- prevProps.onDelete === nextProps.onDelete &&
- prevProps.onMouseDown === nextProps.onMouseDown &&
- prevProps.badgeRefs === nextProps.badgeRefs,
-);
-
-BadgeWrapper.displayName = 'BadgeWrapper';
-
-interface DragState {
- draggedBadge: BadgeItem | null;
- mouseX: number;
- offsetX: number;
- insertIndex: number | null;
- draggedBadgeActive: boolean;
-}
-
-type DragAction =
- | {
- type: 'START_DRAG';
- badge: BadgeItem;
- mouseX: number;
- offsetX: number;
- insertIndex: number;
- isActive: boolean;
- }
- | { type: 'UPDATE_POSITION'; mouseX: number; insertIndex: number }
- | { type: 'END_DRAG' };
-
-const dragReducer = (state: DragState, action: DragAction): DragState => {
- switch (action.type) {
- case 'START_DRAG':
- return {
- draggedBadge: action.badge,
- mouseX: action.mouseX,
- offsetX: action.offsetX,
- insertIndex: action.insertIndex,
- draggedBadgeActive: action.isActive,
- };
- case 'UPDATE_POSITION':
- return {
- ...state,
- mouseX: action.mouseX,
- insertIndex: action.insertIndex,
- };
- case 'END_DRAG':
- return {
- draggedBadge: null,
- mouseX: 0,
- offsetX: 0,
- insertIndex: null,
- draggedBadgeActive: false,
- };
- default:
- return state;
- }
-};
-
-function BadgeRow({
- showEphemeralBadges,
- conversationId,
- specName,
- isSubmitting,
- onChange,
- onToggle,
- isInChat,
-}: BadgeRowProps) {
- const [orderedBadges, setOrderedBadges] = useState<BadgeItem[]>([]);
- const [dragState, dispatch] = useReducer(dragReducer, {
- draggedBadge: null,
- mouseX: 0,
- offsetX: 0,
- insertIndex: null,
- draggedBadgeActive: false,
- });
-
- const badgeRefs = useRef<Record<string, HTMLDivElement>>({});
- const containerRef = useRef<HTMLDivElement>(null);
- const animationFrame = useRef<number | null>(null);
- const containerRectRef = useRef<DOMRect | null>(null);
-
- const allBadges = useChatBadges();
- const isEditing = useRecoilValue(store.isEditingBadges);
-
- const badges = useMemo(
- () => allBadges.filter((badge) => badge.isAvailable !== false),
- [allBadges],
- );
-
- const toggleBadge = useRecoilCallback(
- ({ snapshot, set }) =>
- async (badgeAtom: any) => {
- const current = await snapshot.getPromise(badgeAtom);
- set(badgeAtom, !current);
- },
- [],
- );
-
- useEffect(() => {
- setOrderedBadges((prev) => {
- const currentIds = new Set(prev.map((b) => b.id));
- const newBadges = badges.filter((b) => !currentIds.has(b.id));
- return newBadges.length > 0 ? [...prev, ...newBadges] : prev;
- });
- }, [badges]);
-
- const tempBadges = dragState.draggedBadge
- ? orderedBadges.filter((b) => b.id !== dragState.draggedBadge?.id)
- : orderedBadges;
- const ghostBadge = dragState.draggedBadge || null;
-
- const calculateInsertIndex = useCallback(
- (currentMouseX: number): number => {
- if (!dragState.draggedBadge || !containerRef.current || !containerRectRef.current) {
- return 0;
- }
- const relativeMouseX = currentMouseX - containerRectRef.current.left;
- const refs = tempBadges.map((b) => badgeRefs.current[b.id]).filter(Boolean);
- if (refs.length === 0) {
- return 0;
- }
- let idx = 0;
- for (let i = 0; i < refs.length; i++) {
- const rect = refs[i].getBoundingClientRect();
- const relativeLeft = rect.left - containerRectRef.current.left;
- const relativeCenter = relativeLeft + rect.width / 2;
- if (relativeMouseX < relativeCenter) {
- break;
- }
- idx = i + 1;
- }
- return idx;
- },
- [dragState.draggedBadge, tempBadges],
- );
-
- const handleMouseDown = useCallback(
- (e: React.MouseEvent, badge: BadgeItem, isActive: boolean) => {
- if (!isEditing || !containerRef.current) {
- return;
- }
- const el = badgeRefs.current[badge.id];
- if (!el) {
- return;
- }
- const rect = el.getBoundingClientRect();
- const offsetX = e.clientX - rect.left;
- const mouseX = e.clientX;
- const initialIndex = orderedBadges.findIndex((b) => b.id === badge.id);
- containerRectRef.current = containerRef.current.getBoundingClientRect();
- dispatch({
- type: 'START_DRAG',
- badge,
- mouseX,
- offsetX,
- insertIndex: initialIndex,
- isActive,
- });
- },
- [isEditing, orderedBadges],
- );
-
- const handleMouseMove = useCallback(
- (e: MouseEvent) => {
- if (!dragState.draggedBadge) {
- return;
- }
- if (animationFrame.current) {
- cancelAnimationFrame(animationFrame.current);
- }
- animationFrame.current = requestAnimationFrame(() => {
- const newMouseX = e.clientX;
- const newInsertIndex = calculateInsertIndex(newMouseX);
- if (newInsertIndex !== dragState.insertIndex) {
- dispatch({ type: 'UPDATE_POSITION', mouseX: newMouseX, insertIndex: newInsertIndex });
- } else {
- dispatch({
- type: 'UPDATE_POSITION',
- mouseX: newMouseX,
- insertIndex: dragState.insertIndex,
- });
- }
- });
- },
- [dragState.draggedBadge, dragState.insertIndex, calculateInsertIndex],
- );
-
- const handleMouseUp = useCallback(() => {
- if (dragState.draggedBadge && dragState.insertIndex !== null) {
- const otherBadges = orderedBadges.filter((b) => b.id !== dragState.draggedBadge?.id);
- const newBadges = [
- ...otherBadges.slice(0, dragState.insertIndex),
- dragState.draggedBadge,
- ...otherBadges.slice(dragState.insertIndex),
- ];
- setOrderedBadges(newBadges);
- onChange(newBadges.map((badge) => ({ id: badge.id })));
- }
- dispatch({ type: 'END_DRAG' });
- containerRectRef.current = null;
- }, [dragState.draggedBadge, dragState.insertIndex, orderedBadges, onChange]);
-
- const handleDelete = useCallback(
- (badgeId: string) => {
- const newBadges = orderedBadges.filter((b) => b.id !== badgeId);
- setOrderedBadges(newBadges);
- onChange(newBadges.map((badge) => ({ id: badge.id })));
- },
- [orderedBadges, onChange],
- );
-
- const handleBadgeToggle = useCallback(
- (badge: BadgeItem) => {
- if (badge.atom) {
- toggleBadge(badge.atom);
- }
- if (onToggle) {
- onToggle(badge.id, !!badge.atom);
- }
- },
- [toggleBadge, onToggle],
- );
-
- useEffect(() => {
- if (!dragState.draggedBadge) {
- return;
- }
- document.addEventListener('mousemove', handleMouseMove);
- document.addEventListener('mouseup', handleMouseUp);
- return () => {
- document.removeEventListener('mousemove', handleMouseMove);
- document.removeEventListener('mouseup', handleMouseUp);
- if (animationFrame.current) {
- cancelAnimationFrame(animationFrame.current);
- animationFrame.current = null;
- }
- };
- }, [dragState.draggedBadge, handleMouseMove, handleMouseUp]);
-
- return (
- <BadgeRowProvider
- conversationId={conversationId}
- specName={specName}
- isSubmitting={isSubmitting}
- observeToolAuthorization={showEphemeralBadges === true}
- >
- <div ref={containerRef} className="relative flex flex-wrap items-center gap-2">
- {showEphemeralBadges === true && <ToolsDropdown />}
- {tempBadges.map((badge, index) => (
- <React.Fragment key={badge.id}>
- {dragState.draggedBadge && dragState.insertIndex === index && ghostBadge && (
- <div className="badge-icon h-full">
- <Badge
- id={ghostBadge.id}
- icon={ghostBadge.icon as LucideIcon}
- label={ghostBadge.label}
- isActive={dragState.draggedBadgeActive}
- isEditing={isEditing}
- isAvailable={ghostBadge.isAvailable}
- isInChat={isInChat}
- />
- </div>
- )}
- <BadgeWrapper
- badge={badge}
- isEditing={isEditing}
- isInChat={isInChat}
- onToggle={handleBadgeToggle}
- onDelete={handleDelete}
- onMouseDown={handleMouseDown}
- badgeRefs={badgeRefs}
- />
- </React.Fragment>
- ))}
- {dragState.draggedBadge && dragState.insertIndex === tempBadges.length && ghostBadge && (
- <div className="badge-icon h-full">
- <Badge
- id={ghostBadge.id}
- icon={ghostBadge.icon as LucideIcon}
- label={ghostBadge.label}
- isActive={dragState.draggedBadgeActive}
- isEditing={isEditing}
- isAvailable={ghostBadge.isAvailable}
- isInChat={isInChat}
- />
- </div>
- )}
- {showEphemeralBadges === true && (
- <>
- <WebSearch />
- <CodeInterpreter />
- <FileSearch />
- <Skills />
- <Memory />
- <Artifacts />
- <MCPSelect />
- </>
- )}
- {ghostBadge && (
- <div
- className="ghost-badge h-full"
- style={{
- position: 'absolute',
- top: 0,
- left: 0,
- transform: `translateX(${dragState.mouseX - dragState.offsetX - (containerRectRef.current?.left || 0)}px)`,
- zIndex: 10,
- pointerEvents: 'none',
- }}
- >
- <Badge
- id={ghostBadge.id}
- icon={ghostBadge.icon as LucideIcon}
- label={ghostBadge.label}
- isActive={dragState.draggedBadgeActive}
- isAvailable={ghostBadge.isAvailable}
- isInChat={isInChat}
- isEditing
- isDragging
- />
- </div>
- )}
- </div>
- <ToolDialogs />
- </BadgeRowProvider>
- );
-}
-
-export default memo(BadgeRow);
diff --git a/client/src/components/Chat/Input/ChatForm.tsx b/client/src/components/Chat/Input/ChatForm.tsx
index 3676a2a272..6060475310 100644
--- a/client/src/components/Chat/Input/ChatForm.tsx
+++ b/client/src/components/Chat/Input/ChatForm.tsx
@@ -1,11 +1,17 @@
import { memo, useRef, useMemo, useEffect, useState, useCallback } from 'react';
import { useWatch } from 'react-hook-form';
-import { useRecoilState, useRecoilValue, useRecoilCallback } from 'recoil';
-import { Constants, isAssistantsEndpoint, isAgentsEndpoint } from 'librechat-data-provider';
+import { useRecoilState, useRecoilValue } from 'recoil';
import { composerSurfaceClasses, composerSurfaceShadow, TextareaAutosize } from '@librechat/client';
+import {
+ Constants,
+ Permissions,
+ PermissionTypes,
+ isAgentsEndpoint,
+ isAssistantsEndpoint,
+} from 'librechat-data-provider';
import type { TChatProject, TMessage, TConversation } from 'librechat-data-provider';
import type { SetterOrUpdater } from 'recoil';
-import type { ExtendedFile, FileSetter, ConvoGenerator } from '~/common';
+import type { ExtendedFile, FileSetter, ConvoGenerator, TAskFunction } from '~/common';
import type { QueuedMessageContext } from '~/hooks/Chat/useSteering';
import {
cn,
@@ -34,42 +40,54 @@ import {
useChatFormContext,
useAddedChatContext,
useAssistantsMapContext,
+ useComposerRestoreHost,
+ BadgeRowProvider,
} from '~/Providers';
+import {
+ cn,
+ getModelSpec,
+ hasIncompleteFiles,
+ removeFocusRings,
+ getComposerDraftId,
+ getFilesDraftCached,
+ isPastedTextFileMarked,
+} from '~/utils';
import {
PendingToolApprovalButton,
PendingToolApprovalPanel,
} from '~/components/Chat/approval/Review';
-import PendingManualSkillsChips from './PendingManualSkillsChips';
+import useComposerRestore from '~/hooks/Input/useComposerRestore';
import usePastedTextEdit from '~/hooks/Files/usePastedTextEdit';
import useAskAnswerMode from '~/hooks/Input/useAskAnswerMode';
import AskUserQuestionPopover from './AskUserQuestionPopover';
+import useComposerItems from '~/hooks/Input/useComposerItems';
+import useAttachTarget from '~/hooks/Input/useAttachTarget';
import InterruptSteerButton from './InterruptSteerButton';
+import Hints, { composerHintId } from './Composer/Hints';
import PastedTextDialog from './Files/PastedTextDialog';
import DuringRunSendButton from './DuringRunSendButton';
import ProjectLandingChip from '../ProjectLandingChip';
+import useHasAccess from '~/hooks/Roles/useHasAccess';
+import useDictation from '~/hooks/Input/useDictation';
import { useGetStartupConfig } from '~/data-provider';
-import { mainTextareaId, BadgeItem } from '~/common';
-import PendingSteerChips from './PendingSteerChips';
-import PendingQuoteChips from './PendingQuoteChips';
-import AttachFileChat from './Files/AttachFileChat';
import CodeWorkspaceMenu from './CodeWorkspaceMenu';
import useSteering from '~/hooks/Chat/useSteering';
import CodeApprovalMenu from './CodeApprovalMenu';
-import FileFormChat from './Files/FileFormChat';
-import InFlightSteers from './InFlightSteers';
import TextareaHeader from './TextareaHeader';
import PromptsCommand from './PromptsCommand';
import { submitFromComposer } from './submit';
import SkillsCommand from './SkillsCommand';
-import AudioRecorder from './AudioRecorder';
import AutoPlayAudio from './AutoPlayAudio';
+import Waveform from './Composer/Waveform';
+import { mainTextareaId } from '~/common';
import CollapseChat from './CollapseChat';
import QuoteButton from './QuoteButton';
-import TokenUsage from './TokenUsage';
+import ToolDialogs from './ToolDialogs';
import StopButton from './StopButton';
import SendButton from './SendButton';
-import EditBadges from './EditBadges';
-import BadgeRow from './BadgeRow';
+import Queue from './Composer/Queue';
+import Tray from './Composer/Tray';
+import Bar from './Composer/Bar';
import Mention from './Mention';
import store from '~/store';
@@ -100,6 +118,16 @@ interface ChatFormProps {
/** Owned by ChatView: which layout the composer sits in — the welcome screen
* floats or bottoms it out, a conversation ends the page with it. */
isLandingPage: boolean;
+ /** Owned by the host: the persisted preference for showing keyboard hints. */
+ showComposerTips: boolean;
+ /** Owned by the host: the persisted preference for whether Enter sends the
+ * message (vs. queues a newline). The composer only consumes it. */
+ enterToSend: boolean;
+ /** Owned by the host: the Auto Send Text preference dictation consumes. */
+ autoSendText: number;
+ /** Owned by the host: whether the shell has loaded the speech settings yet;
+ * dictation stays off until it has. */
+ speechSettingsInitialized: boolean;
/** Owned by the host: the app-level preference for where the welcome-screen
* composer sits. The chat feature only consumes it. */
centerFormOnLanding: boolean;
@@ -143,6 +171,10 @@ const ChatForm = memo(function ChatForm({
placeholder,
project,
isLandingPage,
+ showComposerTips,
+ enterToSend,
+ autoSendText,
+ speechSettingsInitialized,
footerBelow,
centerFormOnLanding,
files,
@@ -157,6 +189,9 @@ const ChatForm = memo(function ChatForm({
}: ChatFormProps) {
const submitButtonRef = useRef<HTMLButtonElement>(null);
const textAreaRef = useRef<HTMLTextAreaElement>(null);
+ /** The palette anchors to the whole composer, not to its own button, so it
+ * spans the composer width and sits flush above it. */
+ const composerBoxRef = useRef<HTMLDivElement>(null);
useFocusChatEffect(textAreaRef);
const localize = useLocalize();
@@ -164,7 +199,9 @@ const ChatForm = memo(function ChatForm({
const [, setIsScrollable] = useState(false);
const [visualRowCount, setVisualRowCount] = useState(1);
const [isTextAreaFocused, setIsTextAreaFocused] = useState(false);
- const [backupBadges, setBackupBadges] = useState<Pick<BadgeItem, 'id'>[]>([]);
+ /** Last measured row count, so an unchanged measurement never schedules a
+ * render at all rather than relying on a state-equality bailout. */
+ const measuredRowCountRef = useRef(1);
const SpeechToText = useRecoilValue(store.speechToText);
const TextToSpeech = useRecoilValue(store.textToSpeech);
@@ -173,8 +210,6 @@ const ChatForm = memo(function ChatForm({
const maximizeChatSpace = useRecoilValue(store.maximizeChatSpace);
const isTemporary = useRecoilValue(store.isTemporary);
- const [badges, setBadges] = useRecoilState(store.chatBadges);
- const [isEditingBadges, setIsEditingBadges] = useRecoilState(store.isEditingBadges);
const [showStopButton, setShowStopButton] = useRecoilState(store.showStopButtonByIndex(index));
const plusPopoverAtom = useMemo(() => store.showPlusPopoverFamily(index), [index]);
const mentionPopoverAtom = useMemo(() => store.showMentionPopoverFamily(index), [index]);
@@ -197,8 +232,18 @@ const ChatForm = memo(function ChatForm({
() => getModelSpec({ specName: conversation?.spec, startupConfig }),
[conversation?.spec, startupConfig],
);
- const hideBadgeRow = modelSpec?.hideBadgeRow === true;
const filesLoading = useMemo(() => hasIncompleteFiles(files), [files]);
+ /** Agents and assistants carry their own tool configuration, so the composer's
+ * ephemeral tool controls only apply elsewhere, and a spec can suppress them
+ * outright. Same gate the old `showEphemeralBadges` prop applied. */
+ const showTools = useMemo(
+ () =>
+ !!endpoint &&
+ modelSpec?.hideBadgeRow !== true &&
+ !isAgentsEndpoint(endpoint) &&
+ !isAssistantsEndpoint(endpoint),
+ [endpoint, modelSpec?.hideBadgeRow],
+ );
const conversationId = useMemo(
() => conversation?.conversationId ?? Constants.NEW_CONVO,
[conversation?.conversationId],
@@ -206,7 +251,7 @@ const ChatForm = memo(function ChatForm({
const isNewConversation = conversationId === '' || conversationId === Constants.NEW_CONVO;
/**
* The quote feature merges excerpts server-side in `BaseClient.sendMessage`,
- * which the Assistants endpoints bypass — so hide the UI there rather than
+ * which the Assistants endpoints bypass, so hide the UI there rather than
* letting users queue quotes the assistant never receives.
*/
const quotesEnabled = useMemo(() => !isAssistantsEndpoint(endpoint), [endpoint]);
@@ -280,7 +325,7 @@ const ChatForm = memo(function ChatForm({
: (answerMode.otherLabel ?? localize('com_ui_something_else'));
/** The composer is not a plain chat composer: it either IS this pause's
* answer box, or is locked behind the batch card that owns the answer. A
- * collapsed batch is neither — it hands the composer back to the thread. */
+ * collapsed batch is neither, it hands the composer back to the thread. */
const composerReserved = answerMode.composerAnswers || answerMode.composerLocked;
const consumeDraft = useAutoSave({
@@ -334,6 +379,7 @@ const ChatForm = memo(function ChatForm({
overrideFiles,
overrideQuotes: context?.quotes ?? [],
overrideManualSkills: context?.manualSkills ?? [],
+ overrideReasoning: context?.reasoningOverride ?? null,
overrideClientRequestId: context?.clientRequestId,
overrideRecoverySteerId: context?.recoverySteerId,
overrideExpectedPredecessorCreatedAt: context?.expectedPredecessorCreatedAt,
@@ -341,49 +387,24 @@ const ChatForm = memo(function ChatForm({
}),
[submitMessage],
);
- /** Chip "Edit message" restore: quote chips + skill picks merge back into
- * their compose-time atoms (the chips above the textarea re-render them). */
- const restoreComposerContext = useRecoilCallback(
- ({ set }) =>
- (context?: QueuedMessageContext) => {
- const { quotes, manualSkills } = context ?? {};
- if (quotes != null && quotes.length > 0) {
- set(store.pendingQuotesByConvoId(conversationId), (prev) => [
- ...new Set([...prev, ...quotes]),
- ]);
- }
- if (manualSkills != null && manualSkills.length > 0) {
- set(store.pendingManualSkillsByConvoId(conversationId), (prev) => [
- ...new Set([...prev, ...manualSkills]),
- ]);
- }
- },
- [conversationId],
- );
- /** Chip "Edit message": the text replaces the composer draft and the chip's
- * attachments merge back into the composer file map (already uploaded, so
- * they restore as completed entries — same shape as draft recovery). */
- const editToComposer = useCallback(
- (text: string, chipFiles?: TMessage['files'], context?: QueuedMessageContext) => {
- methods.setValue('text', text, { shouldDirty: true });
- if (chipFiles != null && chipFiles.length > 0) {
- setFiles((prev) => {
- const next = new Map(prev);
- for (const file of chipFiles) {
- const restoredFile = toRestoredComposerFile(file);
- if (restoredFile == null) {
- continue;
- }
- next.set(restoredFile.file_id, restoredFile);
- }
- return next;
- });
- }
- restoreComposerContext(context);
- textAreaRef.current?.focus();
- },
- [methods, setFiles, restoreComposerContext],
- );
+ const { restoreReclaimedSteer, canRestoreToComposer } = useComposerRestore({
+ index,
+ conversationId,
+ methods,
+ files,
+ setFiles,
+ textAreaRef,
+ answerModeActive: composerReserved,
+ });
+ /* Surfaces outside the composer (a steer cancelled from the thread) re-home
+ their words through the same guarded restore the queue rail gets as a
+ prop. Published while this composer is mounted; a recovery that resolves
+ after it has gone finds nothing and falls back to the queue. */
+ const { publish: publishComposerRestore, publishRewake } = useComposerRestoreHost();
+ useEffect(() => {
+ publishComposerRestore(restoreReclaimedSteer);
+ return () => publishComposerRestore(null);
+ }, [publishComposerRestore, restoreReclaimedSteer]);
const steering = useSteering({
consumeDraft,
addedConversation: addedConvo,
@@ -398,87 +419,18 @@ const ChatForm = memo(function ChatForm({
sendNow,
stopGenerating,
});
-
- /** Read at call time, not captured: a reclaim resolves into the callback from
- * the render it was clicked in, so the closure's `conversationId` is the OLD
- * chat — comparing it against itself would pass while `methods` (one form,
- * reused across conversations) writes into the chat now on screen. */
- const liveConversationIdRef = useRef(conversationId);
- liveConversationIdRef.current = conversationId;
- /** Same reason: attachments staged after the click must be seen. */
- const liveFilesRef = useRef(files);
- liveFilesRef.current = files;
- /** Same reason: the run can pause on `ask_user_question` mid-reclaim. */
- const liveAnswerModeRef = useRef(composerReserved);
- liveAnswerModeRef.current = composerReserved;
- /** A reclaim can resolve after this form unmounts (left the route, closed the
- * pane). Its refs still hold the origin chat, so the restore would pass its
- * checks and write into a dead form — reporting success and making the caller
- * drop the steer, losing the text. Track mount so the restore refuses and the
- * caller queues it instead. */
- const composerMountedRef = useRef(true);
- useEffect(
- () => () => {
- composerMountedRef.current = false;
- },
- [],
- );
-
- /** A draft is anything the user has staged, not just typed: `editToComposer`
- * MERGES the steer's attachments into the composer's file map and its quotes
- * and skill picks into their atoms, so restoring over staged context would
- * glue the two submissions together. */
- const hasStagedComposerContext = useRecoilCallback(
- ({ snapshot }) =>
- (convoId: string) =>
- snapshot.getLoadable(store.pendingQuotesByConvoId(convoId)).getValue().length > 0 ||
- snapshot.getLoadable(store.pendingManualSkillsByConvoId(convoId)).getValue().length > 0,
- [],
- );
-
- /**
- * `editToComposer` for a steer whose reclaim was a round-trip: by the time it
- * resolves the composer may have moved on. Refuses (returning false, so the
- * caller re-homes the words instead of dropping them) rather than overwrite a
- * draft the user has since staged, or drop a steer into whatever chat they
- * navigated to.
- */
- const restoreReclaimedSteer = useCallback(
- (
- text: string,
- steerFiles: TMessage['files'],
- context: QueuedMessageContext,
- originConversationId: string,
- ): boolean => {
- if (!composerMountedRef.current) {
- return false;
- }
- const liveConversationId = liveConversationIdRef.current;
- if (originConversationId !== liveConversationId) {
- return false;
- }
- /** Answer mode owns the composer: `onSubmit` hands its text to
- * `answerMode.submitText` before any send/steer routing, so restoring
- * here would turn the steer into the tool's answer on the next Enter. */
- if (liveAnswerModeRef.current) {
- return false;
- }
- if (
- (methods.getValues('text') ?? '').trim().length > 0 ||
- (liveFilesRef.current?.size ?? 0) > 0 ||
- hasStagedComposerContext(liveConversationId)
- ) {
- return false;
- }
- editToComposer(text, steerFiles, context);
- return true;
- },
- [methods, editToComposer, hasStagedComposerContext],
- );
+ /* A steer retried from the thread can land in the queue after the run it
+ belonged to has ended and spent its one-shot drain signal; the thread
+ reaches the drain through the same host as the restore above. */
+ const { rewakeDrain: steeringRewakeDrain } = steering;
+ useEffect(() => {
+ publishRewake(steeringRewakeDrain);
+ return () => publishRewake(null);
+ }, [publishRewake, steeringRewakeDrain]);
/** ⌘/Ctrl+Enter = the non-default during-run action, ⌥/Alt+Enter =
* interrupt & send (discards the answer), ⌘/Ctrl+Shift+Enter = interrupt &
- * steer (keeps it) — all counterparts of Enter's `submitDuringRun`. */
+ * steer (keeps it): all counterparts of Enter's `submitDuringRun`. */
const handleDuringRunModifier = useCallback(
(kind: 'other' | 'interrupt' | 'preempt') => {
const text = methods.getValues('text');
@@ -513,13 +465,14 @@ const ChatForm = memo(function ChatForm({
textAreaRef,
submitButtonRef,
setIsScrollable,
- disabled: disableInputs,
+ disabled: disableInputs || answerMode.composerLocked,
// The composer IS the free-form answer box while a question pause is live.
placeholder: composerReserved ? answerPlaceholder : placeholder,
// Enter stays live during a run when it can steer/queue instead of send.
- allowSubmitWhileGenerating: steering.duringRunActive,
+ allowSubmitWhileGenerating: steering.duringRunActive || answerMode.composerAnswers,
onDuringRunModifier: steering.duringRunActive ? handleDuringRunModifier : undefined,
answerModeActive: answerMode.composerAnswers,
+ enterToSend,
});
useQueryParams({ textAreaRef });
@@ -541,57 +494,189 @@ const ChatForm = memo(function ChatForm({
const textValue = useWatch({ control: methods.control, name: 'text' });
+ /** The composer commits once per keystroke for the row count and the send
+ * button; a second commit for a row count that did not move (or that no
+ * layout engine can measure, where `lineHeight` is not a number) doubles the
+ * cost of the app's busiest surface for nothing. */
useEffect(() => {
- if (textAreaRef.current) {
- const style = window.getComputedStyle(textAreaRef.current);
- const lineHeight = parseFloat(style.lineHeight);
- setVisualRowCount(Math.floor(textAreaRef.current.scrollHeight / lineHeight));
+ const textarea = textAreaRef.current;
+ if (!textarea) {
+ return;
}
- }, [textValue]);
-
- useEffect(() => {
- if (isEditingBadges && backupBadges.length === 0) {
- setBackupBadges([...badges]);
+ const lineHeight = parseFloat(window.getComputedStyle(textarea).lineHeight);
+ if (!(lineHeight > 0)) {
+ return;
}
- }, [isEditingBadges, badges, backupBadges.length]);
+ const nextRowCount = Math.floor(textarea.scrollHeight / lineHeight);
+ if (nextRowCount === measuredRowCountRef.current) {
+ return;
+ }
+ measuredRowCountRef.current = nextRowCount;
+ setVisualRowCount(nextRowCount);
+ }, [textValue]);
- const handleSaveBadges = useCallback(() => {
- setIsEditingBadges(false);
- setBackupBadges([]);
- }, [setIsEditingBadges, setBackupBadges]);
+ const isMoreThanThreeRows = visualRowCount > 3;
- const handleCancelBadges = useCallback(() => {
- if (backupBadges.length > 0) {
- setBadges([...backupBadges]);
+ const composerItems = useComposerItems(conversationId, quotesEnabled);
+ const attachTarget = useAttachTarget(conversation, disableInputs);
+ const hasPromptsAccess = useHasAccess({
+ permissionType: PermissionTypes.PROMPTS,
+ permission: Permissions.USE,
+ });
+ const slashCommandEnabled = useRecoilValue(store.slashCommand);
+ const atCommandEnabled = useRecoilValue(store.atCommand);
+ const idleActions = useMemo(
+ () => ({
+ prompts: hasPromptsAccess && slashCommandEnabled,
+ mentions: atCommandEnabled,
+ attach: attachTarget.canAttach,
+ }),
+ [hasPromptsAccess, slashCommandEnabled, atCommandEnabled, attachTarget.canAttach],
+ );
+ const { submitText: submitAnswerText } = answerMode;
+ const dictationAnswerModeActive = answerMode.composerAnswers;
+ const speechDisabled =
+ !speechSettingsInitialized || disableInputs || isNotAppendable || answerMode.composerLocked;
+ /** The same gate `onSubmit` applies: while a question pause is live the
+ * composer IS the answer box, so a dictated turn has to answer it rather
+ * than start a turn the paused run would drop. */
+ const dictationAsk = useCallback<TAskFunction>(
+ (props) => {
+ if (dictationAnswerModeActive && submitAnswerText(props.text)) {
+ return;
+ }
+ return submitMessage({ text: props.text });
+ },
+ [dictationAnswerModeActive, submitAnswerText, submitMessage],
+ );
+ const dictation = useDictation({
+ ask: dictationAsk,
+ duringRunSubmit: steering.duringRunActive ? steering.submitDuringRun : undefined,
+ methods,
+ /* Answer mode leaves the run submitting while handing the composer over,
+ which is exactly when speech must still reach it: the send button is
+ enabled on the same terms. */
+ isSubmitting: (isSubmitting && !dictationAnswerModeActive) || answerMode.composerLocked,
+ filesLoading,
+ /* A dictated question answer is cleared by answer mode only after the
+ resume succeeds. A transient failure must leave the transcript intact. */
+ deferComposerReset: dictationAnswerModeActive,
+ disabled: speechDisabled,
+ autoSendText,
+ speechToText: SpeechToText,
+ index,
+ });
+ const uploadingCount = useMemo(() => {
+ let count = 0;
+ for (const file of files.values()) {
+ if (file.progress < 1) {
+ count++;
+ }
}
- setIsEditingBadges(false);
- setBackupBadges([]);
- }, [backupBadges, setBadges, setIsEditingBadges]);
+ return count;
+ }, [files]);
- const isMoreThanThreeRows = visualRowCount > 3;
+ /* The abort is generation-scoped and inert until the start POST installs the
+ epoch; assistants abort through their own path and need no epoch. */
+ const canStop = steering.canControlGeneration || isAssistantsEndpoint(endpoint);
/** One button slot while a run is generating: with composer text the send
* button takes over (Enter steers/queues; hover reveals all actions);
* clearing the text restores Stop. */
- const duringRunSlot = (() => {
- if (steering.duringRunActive && (textValue?.trim() ?? '') !== '') {
+ /* Memoized for `memo(Bar)`: an inline element is a new identity every render,
+ and this component re-renders on every keystroke. */
+ const duringRunSlot = useMemo(() => {
+ const sendOwnsSlot = steering.duringRunActive && (textValue?.trim() ?? '') !== '';
+ /* Stays mounted (hidden) behind the during-run send button: the stop
+ shortcut resolves against the focused form, so a half-typed steer would
+ otherwise leave it reaching into another pane or doing nothing. */
+ const stopButton = showStopButton ? (
+ <StopButton
+ stop={handleStopGenerating}
+ setShowStopButton={setShowStopButton}
+ canStop={canStop}
+ hidden={sendOwnsSlot}
+ />
+ ) : null;
+ if (sendOwnsSlot) {
return (
- <DuringRunSendButton
- ref={submitButtonRef}
- control={methods.control}
- steering={steering}
- isNewConversation={isNewConversation}
- getText={() => methods.getValues('text')}
- onConsumed={consumeComposer}
- disabled={filesLoading}
- />
+ <>
+ {steering.canControlGeneration && (
+ <InterruptSteerButton
+ steering={steering}
+ getText={() => methods.getValues('text')}
+ onConsumed={consumeComposer}
+ disabled={filesLoading}
+ />
+ )}
+ <DuringRunSendButton
+ ref={submitButtonRef}
+ control={methods.control}
+ steering={steering}
+ getText={() => methods.getValues('text')}
+ onConsumed={consumeComposer}
+ disabled={filesLoading}
+ enterToSend={enterToSend}
+ />
+ {stopButton}
+ </>
);
}
- if (showStopButton) {
- return <StopButton stop={handleStopGenerating} setShowStopButton={setShowStopButton} />;
- }
- return null;
- })();
+ return stopButton;
+ }, [
+ consumeComposer,
+ steering,
+ textValue,
+ methods,
+ submitButtonRef,
+ filesLoading,
+ showStopButton,
+ setShowStopButton,
+ handleStopGenerating,
+ canStop,
+ enterToSend,
+ ]);
+
+ /* Memoized for `memo(Bar)`: an inline element is a new identity every render,
+ and this component re-renders on every keystroke. */
+ /* Gated on the slot having something to show rather than on `showStopButton`:
+ that flag only flips once the start POST installs the generation epoch, and
+ until then Enter already queues while this slot still offered the ordinary
+ send button, disabled. The slot decides for itself between the during-run
+ control, Stop, and nothing, so an empty one falls through to send. */
+ const actionSlot = useMemo(
+ () =>
+ isSubmitting && !answerMode.composerAnswers && duringRunSlot != null
+ ? duringRunSlot
+ : endpoint && (
+ <SendButton
+ ref={submitButtonRef}
+ control={methods.control}
+ fileCount={submittableFileCount}
+ disabled={
+ filesLoading ||
+ disableInputs ||
+ !codeWorkspace.canSubmit ||
+ isNotAppendable ||
+ answerMode.composerLocked ||
+ (isSubmitting && !answerMode.composerAnswers)
+ }
+ />
+ ),
+ [
+ codeWorkspace.canSubmit,
+ endpoint,
+ duringRunSlot,
+ filesLoading,
+ disableInputs,
+ isNotAppendable,
+ isSubmitting,
+ answerMode.composerAnswers,
+ answerMode.composerLocked,
+ submittableFileCount,
+ methods.control,
+ ],
+ );
const baseClasses = useMemo(
() =>
@@ -661,19 +746,21 @@ const ChatForm = memo(function ChatForm({
bottomClearance,
)}
>
+ {/* `min-w-0`: a flex item's automatic minimum size is its content's
+ min-content width, and one long unbroken word in a queued message
+ propagates all the way up here: the composer stretched past the
+ thread and its chips ran off the side. Zeroing it lets the width come
+ from the form, so the chips inside truncate instead. */}
<div className="relative flex h-full min-w-0 flex-1 items-stretch md:flex-col">
{/* Primary composer owns the selection popup so split-view doesn't double it. */}
{index === 0 && quotesEnabled && <QuoteButton conversationId={conversationId} />}
- {/* `relative` anchors the in-flight steer overlay, which floats above
- the composer (`bottom-full`) over the bottom of the thread. */}
<div className="relative flex w-full flex-col">
- {/* Run-scoped: `enabled` alone is any primary composer on a steerable
- endpoint, so a chip that outlives the run would strand a bubble. */}
- {steering.enabled && isSubmitting && (
- <InFlightSteers
+ {steering.enabled && (
+ <Queue
steering={steering}
conversationId={conversationId}
onRestoreToComposer={restoreReclaimedSteer}
+ canRestoreToComposer={canRestoreToComposer}
/>
)}
{(project || codeWorkspace.visible) && (
@@ -727,6 +814,7 @@ const ChatForm = memo(function ChatForm({
agentId={conversation?.agent_id}
/>
<div
+ ref={composerBoxRef}
data-testid="composer-surface"
onClick={handleContainerClick}
className={cn(
@@ -751,31 +839,15 @@ const ChatForm = memo(function ChatForm({
)}
>
<TextareaHeader addedConvo={addedConvo} setAddedConvo={setAddedConvo} />
- <PendingManualSkillsChips conversationId={conversationId} />
- {quotesEnabled && (
- <PendingQuoteChips conversationId={conversationId} focusComposer={focusTextArea} />
- )}
- {steering.enabled && (
- <PendingSteerChips
- conversationId={conversationId}
- steering={steering}
- onEditToComposer={editToComposer}
- onRestoreToComposer={restoreReclaimedSteer}
- />
- )}
- {/* WIP */}
- <EditBadges
- isEditingChatBadges={isEditingBadges}
- handleCancelBadges={handleCancelBadges}
- handleSaveBadges={handleSaveBadges}
- setBadges={setBadges}
- />
- <FileFormChat
- index={index}
+ <Tray
+ items={composerItems}
+ focusComposer={focusTextArea}
conversation={conversation}
files={files}
setFiles={setFiles}
setFilesLoading={setFilesLoading}
+ isRTL={isRTL}
+ index={index}
isPastedTextFile={isPastedTextFile}
isPasteActionPending={isPasteActionPending}
onEditPastedText={pastedTextEdit.openEditor}
@@ -828,6 +900,11 @@ const ChatForm = memo(function ChatForm({
onFocus={handleTextareaFocus}
onBlur={handleTextareaBlur}
aria-label={localize('com_ui_message_input')}
+ aria-describedby={cn(
+ composerHintId(index),
+ (codeWorkspace.state === 'choose' || codeWorkspace.state === 'missing') &&
+ `code-workspace-hint-${index}`,
+ )}
onClick={handleFocusOrClick}
style={{ height: 44, overflowY: 'auto' }}
className={cn(
@@ -836,103 +913,117 @@ const ChatForm = memo(function ChatForm({
'scrollbar-hover transition-[max-height] duration-200 disabled:cursor-not-allowed',
)}
/>
- </div>
- <div className="flex flex-col items-start justify-start pt-1.5 pr-2.5">
- <CollapseChat
- isCollapsed={isCollapsed}
- isScrollable={isMoreThanThreeRows}
- setIsCollapsed={setIsCollapsed}
- />
+ {dictation.active && (textValue?.trim() ?? '') === '' && (
+ /* Stands in for the placeholder: same inset, same line, so
+ it reads as the input listening rather than as a widget
+ bolted on. Once words arrive the transcript takes over. */
+ <Waveform
+ active={dictation.active}
+ className={cn(
+ 'pointer-events-none absolute inset-y-0 h-full',
+ isMoreThanThreeRows ? 'right-2 left-5' : 'inset-x-5',
+ )}
+ />
+ )}
+ {/* Sits over the fade scrim in the corner of the input
+ rather than in its own column beside it, so a long draft
+ does not push an orphaned control off to the side. */}
+ <div className="absolute right-2 bottom-1 z-10">
+ <CollapseChat
+ isCollapsed={isCollapsed}
+ isScrollable={isMoreThanThreeRows}
+ setIsCollapsed={setIsCollapsed}
+ />
+ </div>
</div>
</div>
)}
- <div
- className={cn(
- 'flex flex-wrap items-center gap-2 px-2 pb-2',
- isRTL ? 'flex-row-reverse' : 'flex-row',
- )}
+ {(codeWorkspace.state === 'choose' || codeWorkspace.state === 'missing') && (
+ <p
+ id={`code-workspace-hint-${index}`}
+ role="status"
+ className="text-text-secondary px-5 pb-2 text-sm"
+ >
+ {localize('com_error_code_workspace_required')}
+ </p>
+ )}
+ {/* The composer is what keeps MCP connection and authorization state
+ current wherever its ephemeral tools apply; the Agent Builder's
+ tool library reads the same cache, so without this a server it
+ lists reads as unknown and offers to connect instead of toggling. */}
+ <BadgeRowProvider
+ conversationId={conversationId}
+ specName={conversation?.spec}
+ isSubmitting={isSubmitting}
+ observeToolAuthorization={showTools}
>
- <div className="shrink-0">
- <AttachFileChat
- conversation={conversation}
- disableInputs={disableInputs}
- files={files}
- setFiles={setFiles}
- setFilesLoading={setFilesLoading}
- />
- </div>
- <BadgeRow
- showEphemeralBadges={
- !!endpoint &&
- !hideBadgeRow &&
- !isAgentsEndpoint(endpoint) &&
- !isAssistantsEndpoint(endpoint)
- }
- isSubmitting={isSubmitting}
+ <Bar
+ index={index}
+ isRTL={isRTL}
+ disabled={disableInputs}
+ agentId={conversation?.agent_id}
+ /* The RAW endpoint, not the effective type above: the attach
+ destinations resolve the provider from its name, so a
+ custom endpoint reduced to `custom` loses the uploads its
+ provider actually takes (OpenRouter's video and audio).
+ `endpointType` beside it carries the resolved type. */
+ endpoint={conversation?.endpoint}
+ endpointType={attachTarget.endpointType}
+ endpointFileConfig={attachTarget.endpointFileConfig}
+ useResponsesApi={attachTarget.useResponsesApi}
conversationId={conversationId}
- specName={conversation?.spec}
- onChange={setBadges}
- isInChat={
- Array.isArray(conversation?.messages) && conversation.messages.length >= 1
- }
- />
- <CodeApprovalMenu
conversation={conversation}
- addedConversation={addedConvo}
- setConversation={setConversation}
- disabled={disableInputs}
- />
- {index === 0 && conversationId != null && (
- <PendingToolApprovalButton conversationId={conversationId} />
- )}
- <div className="grow" />
- <TokenUsage index={index} conversation={conversation} isSubmitting={isSubmitting} />
- {SpeechToText && (
- <AudioRecorder
- methods={methods}
- ask={submitComposerText}
- disabled={disableInputs || isNotAppendable}
- isSubmitting={isSubmitting}
- />
- )}
- {steering.duringRunActive &&
- steering.canControlGeneration &&
- (textValue?.trim() ?? '') !== '' && (
- <div className="shrink-0">
- <InterruptSteerButton
- steering={steering}
- isNewConversation={isNewConversation}
- getText={() => methods.getValues('text')}
- onConsumed={consumeComposer}
- disabled={filesLoading}
+ files={files}
+ setFiles={setFiles}
+ setFilesLoading={setFilesLoading}
+ canAttach={attachTarget.canAttach}
+ anchorRef={composerBoxRef}
+ showTools={showTools}
+ isSubmitting={isSubmitting}
+ showSpeech={SpeechToText}
+ speechDisabled={speechDisabled}
+ dictation={dictation}
+ approvalSlot={
+ <div className={cn('flex items-center gap-1.5', isRTL && 'flex-row-reverse')}>
+ <CodeApprovalMenu
+ conversation={conversation}
+ addedConversation={addedConvo}
+ setConversation={setConversation}
+ disabled={disableInputs}
/>
- </div>
- )}
- <div className={cn('shrink-0', isRTL ? 'mr-auto' : 'ml-auto')}>
- {isSubmitting &&
- (showStopButton || steering.duringRunActive) &&
- !answerMode.composerAnswers
- ? duringRunSlot
- : endpoint && (
- <SendButton
- ref={submitButtonRef}
- control={methods.control}
- fileCount={submittableFileCount}
- disabled={
- filesLoading ||
- disableInputs ||
- !codeWorkspace.canSubmit ||
- isNotAppendable ||
- answerMode.composerLocked ||
- (isSubmitting && !answerMode.composerAnswers)
- }
- />
+ {index === 0 && conversationId != null && (
+ <PendingToolApprovalButton conversationId={conversationId} />
)}
- </div>
- </div>
+ </div>
+ }
+ actionSlot={actionSlot}
+ hasAddedConversation={addedConvo != null}
+ />
+ <ToolDialogs />
+ </BadgeRowProvider>
{TextToSpeech && automaticPlayback && <AutoPlayAudio index={index} />}
</div>
</div>
+ {/* Sibling of the composer row, not a child: inside that flex-row it
+ would lay out as a narrow column beside the box. */}
+ <Hints
+ index={index}
+ enterToSend={enterToSend}
+ showTips={showComposerTips}
+ hasText={(textValue?.trim() ?? '') !== ''}
+ isSubmitting={isSubmitting}
+ duringRunActive={steering.duringRunActive}
+ canControlGeneration={steering.canControlGeneration}
+ canStop={canStop}
+ steerInterruptsByDefault={steering.steerInterruptsByDefault}
+ duringRunAction={steering.effectiveAction}
+ /* A staged reasoning choice forces the message to queue, and the
+ send-now chord then queues too; do not advertise it. */
+ canSteer={steering.canSteer && steering.pendingReasoningOverride == null}
+ answerModeActive={answerMode.active}
+ uploadingCount={uploadingCount}
+ idleActions={idleActions}
+ />
</div>
</div>
</form>
@@ -943,19 +1034,32 @@ ChatForm.displayName = 'ChatForm';
/**
* Wrapper that subscribes to ChatContext and passes stable individual values
* to the memo'd ChatForm. This prevents ChatForm from re-rendering on every
- * streaming chunk — it only re-renders when the specific values it uses change.
+ * streaming chunk: it only re-renders when the specific values it uses change.
*/
function ChatFormWrapper({
index = 0,
placeholder,
project,
isLandingPage,
+ showComposerTips,
+ /** Defaults to the atom's own default (`atomWithLocalStorage('enterToSend',
+ * true)`) so call sites that predate this prop, mainly tests, keep their
+ * prior behavior without passing it explicitly. */
+ enterToSend = true,
+ /** Same reason, from `atomWithLocalStorage('autoSendText', -1)`. */
+ autoSendText = -1,
+ /** Same reason, from the `speechSettingsInitialized` atom's `false`. */
+ speechSettingsInitialized = false,
footerBelow,
centerFormOnLanding,
}: {
index?: number;
placeholder?: string;
project?: TChatProject;
+ showComposerTips: boolean;
+ enterToSend?: boolean;
+ autoSendText?: number;
+ speechSettingsInitialized?: boolean;
isLandingPage: boolean;
footerBelow: boolean;
centerFormOnLanding: boolean;
@@ -993,6 +1097,16 @@ function ChatFormWrapper({
conversation?.codeApprovalMode,
conversation?.codeEnvironmentMode,
conversation?.codeWorkspaces,
+ /** The composer's reasoning control reads its configured value off this
+ * object. Leaving these out held the old level on screen after a
+ * Parameters-panel edit, while the next send already used the new one. */
+ conversation?.reasoning_effort,
+ conversation?.effort,
+ conversation?.thinkingLevel,
+ conversation?.thinkingBudget,
+ /** The attach picker resolves the upload route from it, and a Responses
+ * routing policy can send web-search turns to a different route. */
+ conversation?.web_search,
hasMessages,
],
);
@@ -1022,6 +1136,10 @@ function ChatFormWrapper({
return (
<ChatForm
index={index}
+ showComposerTips={showComposerTips}
+ enterToSend={enterToSend}
+ autoSendText={autoSendText}
+ speechSettingsInitialized={speechSettingsInitialized}
placeholder={placeholder}
project={project}
isLandingPage={isLandingPage}
diff --git a/client/src/components/Chat/Input/CodeInterpreter.tsx b/client/src/components/Chat/Input/CodeInterpreter.tsx
deleted file mode 100644
index 89dcef00c2..0000000000
--- a/client/src/components/Chat/Input/CodeInterpreter.tsx
+++ /dev/null
@@ -1,36 +0,0 @@
-import React, { memo } from 'react';
-import { TerminalSquareIcon } from 'lucide-react';
-import { CheckboxButton } from '@librechat/client';
-import { PermissionTypes, Permissions } from 'librechat-data-provider';
-import { useLocalize, useHasAccess } from '~/hooks';
-import { useBadgeRowContext } from '~/Providers';
-import { badgeAccents } from './accents';
-
-function CodeInterpreter() {
- const localize = useLocalize();
- const context = useBadgeRowContext();
- const { toggleState: runCode, debouncedChange, isPinned } = context?.codeInterpreter ?? {};
-
- const canRunCode = useHasAccess({
- permissionType: PermissionTypes.RUN_CODE,
- permission: Permissions.USE,
- });
-
- if (!canRunCode) {
- return null;
- }
-
- return (
- (runCode || isPinned) && (
- <CheckboxButton
- checked={runCode}
- setValue={debouncedChange}
- label={localize('com_ui_run_code')}
- isCheckedClassName={badgeAccents.purple}
- icon={<TerminalSquareIcon className="icon-md" aria-hidden="true" />}
- />
- )
- );
-}
-
-export default memo(CodeInterpreter);
diff --git a/client/src/components/Chat/Input/Composer/Bar.tsx b/client/src/components/Chat/Input/Composer/Bar.tsx
new file mode 100644
index 0000000000..51e8cac378
--- /dev/null
+++ b/client/src/components/Chat/Input/Composer/Bar.tsx
@@ -0,0 +1,610 @@
+import React, { memo, useMemo, useState, useCallback } from 'react';
+import * as Ariakit from '@ariakit/react';
+import { Mic, Plus, Check, Square, ChevronDown } from 'lucide-react';
+import { MCPIcon, IconButton, TooltipAnchor, SendIcon } from '@librechat/client';
+import type { TConversation, EModelEndpoint, EndpointFileConfig } from 'librechat-data-provider';
+import type { PaletteEntry, PaletteMode } from '~/hooks/Input/usePaletteEntries';
+import type { Dictation } from '~/hooks/Input/useDictation';
+import type { ExtendedFile, FileSetter } from '~/common';
+import usePaletteEntries from '~/hooks/Input/usePaletteEntries';
+import MCPConfigDialog from '~/components/MCP/MCPConfigDialog';
+import useToolFavorites from '~/hooks/Input/useToolFavorites';
+import useElementSize from '~/hooks/Generic/useElementSize';
+import useChipPacking from '~/hooks/Input/useChipPacking';
+import { useBadgeRowContext } from '~/Providers';
+import TokenUsage from '../TokenUsage';
+import { useLocalize } from '~/hooks';
+import Thinking from './Thinking';
+import Palette from './Palette';
+import { cn } from '~/utils';
+import Chip from './Chip';
+
+/** Stable identity so the memo below is not defeated when tools are hidden. */
+const EMPTY_ENTRIES: PaletteEntry[] = [];
+
+/** Matches the rows' `gap-1.5`, which the split arithmetic has to account for. */
+const CHIP_GAP = 6;
+/**
+ * Key of the aggregate MCP menu chip. Server rows are keyed `mcp:${serverName}`
+ * (`usePaletteEntries`), so this cannot live in that namespace: a server named
+ * `pinned` would produce the same key, and the bar would render two entries
+ * with one React key and one packing-width slot.
+ */
+export const PINNED_MCP_KEY = 'aggregate:mcp';
+
+/**
+ * Whether every chip fits on the button row beside the `+` and the controls.
+ *
+ * All or nothing: chips share that row only while they are few enough to need
+ * no row of their own. Once they do not fit they all move to a row above, so
+ * the buttons keep a row of their own rather than being crowded by whichever
+ * two or three chips happened to be left over.
+ */
+export function chipsFitInline<T extends { key: string }>(
+ entries: T[],
+ widths: Record<string, number>,
+ capacity: number,
+): boolean {
+ if (entries.length === 0) {
+ return true;
+ }
+ if (capacity <= 0) {
+ return false;
+ }
+ let used = 0;
+ for (const entry of entries) {
+ const width = widths[entry.key];
+ /* Before the first measuring pass nothing is known, so everything stays on
+ one row, the same unmeasured state the packing order starts from. */
+ if (width == null) {
+ return true;
+ }
+ used += width + (used > 0 ? CHIP_GAP : 0);
+ if (used > capacity) {
+ return false;
+ }
+ }
+ return true;
+}
+
+export function formatElapsed(seconds: number): string {
+ return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`;
+}
+
+/** Named sub-modes stay on the chip (Artifacts, MCP). Icon-only actions such
+ * as web-search Configure belong on the palette row, not behind a chevron. */
+export function chipMenuModes(modes?: PaletteMode[]) {
+ return modes?.filter((mode) => mode.icon == null) ?? [];
+}
+
+/** Projects palette state into the persistent quick controls in one pass. */
+export function projectBarEntries(
+ entries: PaletteEntry[],
+ pinnedMcpEntry?: PaletteEntry,
+): PaletteEntry[] {
+ const projected: PaletteEntry[] = [];
+ const mcpModes: PaletteMode[] = [];
+
+ for (const entry of entries) {
+ if (entry.section === 'skill') {
+ continue;
+ }
+ if (entry.section === 'mcp') {
+ mcpModes.push({
+ id: entry.itemId,
+ label: entry.label,
+ active: entry.active,
+ onSelect: entry.onSelect,
+ });
+ }
+ if (entry.active || entry.pinned) {
+ projected.push(entry);
+ }
+ }
+
+ if (pinnedMcpEntry != null && mcpModes.length > 0) {
+ projected.push({ ...pinnedMcpEntry, modes: mcpModes });
+ }
+
+ return projected;
+}
+
+interface RoundButtonProps {
+ label: string;
+ onClick: () => void;
+ children: React.ReactNode;
+ primary?: boolean;
+ disabled?: boolean;
+}
+
+function RoundButton({
+ label,
+ onClick,
+ children,
+ primary = false,
+ disabled = false,
+}: RoundButtonProps) {
+ return (
+ <TooltipAnchor
+ description={label}
+ disabled={disabled}
+ render={
+ <IconButton
+ label={label}
+ size="md"
+ variant={primary ? 'primary' : 'ghost'}
+ onClick={onClick}
+ disabled={disabled}
+ >
+ {/* IconButton owns its own text color; this fills the button so the
+ icon (currentColor) starts muted and brightens on hover, without
+ restyling the primitive itself. */}
+ <span
+ className={cn(
+ 'flex h-full w-full items-center justify-center',
+ !primary && 'text-text-secondary hover:text-text-primary transition-colors',
+ )}
+ >
+ {children}
+ </span>
+ </IconButton>
+ }
+ />
+ );
+}
+
+/**
+ * Sub-mode switch carried on the chip itself, so Artifacts' generation mode can
+ * be changed without reopening the palette. Real menu items, unlike the
+ * pointer-only pills inside the palette's `option` rows.
+ */
+interface ChipModesProps {
+ modes: PaletteMode[];
+ menuLabel?: string;
+}
+
+export function ChipModes({ modes, menuLabel }: ChipModesProps) {
+ const localize = useLocalize();
+ const [open, setOpen] = useState(false);
+ const active = modes.find((mode) => mode.active);
+
+ return (
+ <Ariakit.MenuProvider open={open} setOpen={setOpen} placement="bottom">
+ <Ariakit.MenuButton
+ aria-label={
+ active != null
+ ? localize('com_ui_mode_value', { 0: active.label })
+ : (menuLabel ?? localize('com_ui_mode'))
+ }
+ onClick={(e) => e.stopPropagation()}
+ className="text-text-secondary hover:bg-surface-tertiary hover:text-text-primary focus-visible:ring-border-xheavy -mr-0.5 flex shrink-0 items-center gap-0.5 rounded px-1 text-xs transition-colors focus-visible:ring-2 focus-visible:outline-hidden"
+ >
+ {active != null && <span className="max-w-[7rem] truncate">{active.label}</span>}
+ <ChevronDown
+ className={cn('animate-composer-icon size-3 shrink-0 opacity-70', open && '-rotate-180')}
+ aria-hidden="true"
+ />
+ </Ariakit.MenuButton>
+ {/* Same entrance as the palette and the thinking popup, and the same
+ anchored origin, so it grows out of the chip in whichever direction it
+ ends up opening. */}
+ <Ariakit.Menu
+ portal
+ gutter={6}
+ unmountOnHide
+ onClick={(event) => event.stopPropagation()}
+ className="animate-composer-popover border-border-light bg-presentation z-50 min-w-[10rem] rounded-xl border p-1 shadow-lg outline-hidden"
+ >
+ {modes.map((mode) => (
+ <Ariakit.MenuItem
+ key={mode.id}
+ hideOnClick={false}
+ role="menuitemradio"
+ aria-checked={mode.active}
+ onClick={mode.onSelect}
+ className="text-text-secondary data-[active-item]:bg-surface-hover data-[active-item]:text-text-primary flex cursor-pointer items-center justify-between gap-3 rounded-lg px-2 py-1.5 text-sm"
+ >
+ <span className="truncate">{mode.label}</span>
+ {mode.active && <Check className="size-4 shrink-0" aria-hidden="true" />}
+ </Ariakit.MenuItem>
+ ))}
+ </Ariakit.Menu>
+ </Ariakit.MenuProvider>
+ );
+}
+
+interface BarProps {
+ index: number;
+ isRTL: boolean;
+ disabled: boolean;
+ agentId?: string | null;
+ endpoint?: string | null;
+ endpointType?: EModelEndpoint | string;
+ endpointFileConfig?: EndpointFileConfig;
+ useResponsesApi?: boolean;
+ conversationId: string;
+ conversation: TConversation | null;
+ files: Map<string, ExtendedFile>;
+ setFiles: FileSetter;
+ setFilesLoading: React.Dispatch<React.SetStateAction<boolean>>;
+ canAttach: boolean;
+ /** The composer box, which the palette anchors to instead of its own button. */
+ anchorRef: React.RefObject<HTMLElement>;
+ /** Mirrors the old `showEphemeralBadges` gate: agents and assistants carry
+ * their own tool config, and a spec can suppress the row outright. */
+ showTools: boolean;
+ isSubmitting: boolean;
+ showSpeech: boolean;
+ speechDisabled: boolean;
+ hasAddedConversation: boolean;
+ /** Code approval and review controls supplied by the composer shell. */
+ approvalSlot?: React.ReactNode;
+ /** Send, stop or the during-run split button, decided by the caller. */
+ actionSlot: React.ReactNode;
+ /** Owned by `ChatForm`, which also paints the trace over the textarea. */
+ dictation: Dictation;
+}
+
+/**
+ * The composer's action bar. The palette and the chips for whatever tools are
+ * currently on sit left; model/effort, context, speech and send sit right.
+ * Inactive tools appear only when pinned as persistent quick controls.
+ */
+function Bar({
+ index,
+ isRTL,
+ disabled,
+ agentId,
+ endpoint,
+ endpointType,
+ endpointFileConfig,
+ useResponsesApi,
+ conversationId,
+ conversation,
+ files,
+ setFiles,
+ setFilesLoading,
+ canAttach,
+ anchorRef,
+ showTools,
+ isSubmitting,
+ showSpeech,
+ speechDisabled,
+ hasAddedConversation,
+ approvalSlot,
+ actionSlot,
+ dictation,
+}: BarProps) {
+ const localize = useLocalize();
+ const context = useBadgeRowContext();
+ /* Latched on the palette's first open and never released: the skills catalog
+ is only walked for composers whose palette was actually used, and closing
+ it keeps the pages cached rather than refetching per open. */
+ const [catalogWanted, setCatalogWanted] = useState(false);
+ const [catalogOpenRevision, setCatalogOpenRevision] = useState(0);
+ const onPaletteOpen = useCallback(() => {
+ setCatalogWanted(true);
+ setCatalogOpenRevision((revision) => revision + 1);
+ }, []);
+ const favorites = useToolFavorites();
+ const allEntries = usePaletteEntries({
+ conversationId,
+ agentId,
+ enabled: showTools || agentId != null,
+ toolsEnabled: showTools,
+ catalogEnabled: catalogWanted,
+ catalogOpenRevision,
+ favoriteKeys: favorites.keys,
+ });
+
+ /* Servers with required variables open this before they can be selected; it
+ lives here rather than in the palette so dismissing the popover mid-config
+ does not unmount the dialog. */
+ const mcpConfigProps = context?.mcpServerManager?.getConfigDialogProps();
+ /* `usePaletteEntries` already returns nothing once `enabled` is false, so the
+ gate lives in one place rather than being re-applied to its result here. */
+ const entries = allEntries;
+
+ const manager = context?.mcpServerManager;
+ const pinnedMcpEntry = useMemo<PaletteEntry | undefined>(() => {
+ if (manager?.isPinned !== true) {
+ return undefined;
+ }
+ const { placeholderText, setIsPinned } = manager;
+ return {
+ key: PINNED_MCP_KEY,
+ itemType: 'mcp',
+ itemId: 'mcp',
+ label: placeholderText || localize('com_ui_mcp_servers'),
+ icon: <MCPIcon className="h-4 w-4" aria-hidden="true" />,
+ section: 'mcp',
+ active: true,
+ pinned: true,
+ onSelect: () => setIsPinned(false),
+ };
+ }, [manager, localize]);
+
+ /* Catalog skills are excluded: a picked skill is staged context for the next
+ turn, so it belongs in the tray above the textarea with files and quotes.
+ Built-in tool pins remain visible while off. The legacy aggregate MCP pin
+ remains one server menu alongside any selected server chips. */
+ const barEntries = useMemo(
+ () => projectBarEntries(entries, pinnedMcpEntry),
+ [entries, pinnedMcpEntry],
+ );
+ /* Catalog order puts long skill and MCP names mid-row, stranding the rest of
+ that row; packing widest-first fills the rows instead. */
+ const { ordered: packedEntries, rootRef, widths } = useChipPacking(barEntries);
+
+ const { ref: rowRef, width: rowWidth } = useElementSize<HTMLDivElement>();
+ const { ref: plusRef, width: plusWidth } = useElementSize<HTMLSpanElement>();
+ const { ref: controlsRef, width: controlsWidth } = useElementSize<HTMLDivElement>();
+
+ /* A row of their own once they need one, and it runs the full width of the
+ composer (the `+` corner included), since the buttons are on the row below
+ it rather than in the flow. */
+ const inlineChips = useMemo(
+ () =>
+ chipsFitInline(packedEntries, widths, rowWidth - plusWidth - controlsWidth - CHIP_GAP * 2),
+ [packedEntries, widths, rowWidth, plusWidth, controlsWidth],
+ );
+ const dictating = dictation.active || dictation.transcribing;
+
+ /* Spoken rather than shown: the recording state is otherwise carried only by
+ two buttons quietly changing their names, which a reader will not re-read
+ for a control that already has focus. The elapsed seconds stay out of it,
+ since a region that changes every second is read every second. */
+ let dictationStatus = '';
+ if (dictation.transcribing) {
+ dictationStatus = localize('com_ui_transcribing');
+ } else if (dictating) {
+ dictationStatus = localize('com_ui_listening');
+ }
+
+ /* The arrangement is frozen for the length of a recording. The controls
+ shrink to just the elapsed time while one runs, which would otherwise let
+ chips qualify for the bottom row and re-mount there mid-animation: a chip
+ that changes parent restarts from its new parent's resting state, which is
+ no transition at all. */
+ const [restingInline, setRestingInline] = useState(true);
+ if (!dictating && restingInline !== inlineChips) {
+ setRestingInline(inlineChips);
+ }
+ const chipsInline = dictating ? restingInline : inlineChips;
+ const above = chipsInline ? EMPTY_ENTRIES : packedEntries;
+ const inline = chipsInline ? packedEntries : EMPTY_ENTRIES;
+
+ const rowClass = cn(
+ 'flex flex-wrap items-center gap-1.5',
+ isRTL ? 'flex-row-reverse' : 'flex-row',
+ );
+ const barClass = 'flex flex-col gap-1.5 px-2 pb-2';
+
+ const renderChip = (entry: PaletteEntry) => {
+ const pinnedInactive = entry.pinned && !entry.active;
+ const isPinnedMcp = entry.key === PINNED_MCP_KEY;
+ const menuModes = chipMenuModes(entry.modes);
+ const modeMenu =
+ menuModes.length > 0 ? (
+ <ChipModes modes={menuModes} menuLabel={isPinnedMcp ? entry.label : undefined} />
+ ) : null;
+ const activate = pinnedInactive ? (
+ <IconButton
+ label={localize('com_ui_select_var', { 0: entry.label })}
+ size="xs"
+ className="-mr-1"
+ onClick={entry.onSelect}
+ >
+ {/* Matches the chip's own `tone="surface"` text color: IconButton owns
+ its own color, so the glyph carries it directly rather than
+ inheriting through the button. */}
+ <Plus className="text-text-secondary size-3" aria-hidden="true" />
+ </IconButton>
+ ) : null;
+
+ return (
+ <Chip
+ key={entry.key}
+ label={entry.label}
+ icon={entry.icon}
+ trailing={
+ modeMenu != null || activate != null ? (
+ <span className="flex items-center gap-0.5">
+ {modeMenu}
+ {activate}
+ </span>
+ ) : undefined
+ }
+ onRemove={pinnedInactive ? entry.onUnpin : entry.onSelect}
+ removeLabel={
+ isPinnedMcp || pinnedInactive
+ ? localize('com_ui_unpin')
+ : localize('com_ui_remove_var', { 0: entry.label })
+ }
+ data-testid={`composer-active-${entry.itemType}`}
+ />
+ );
+ };
+
+ return (
+ <div ref={rootRef} className={barClass}>
+ {/* Full-width rows, so the chips run right across the composer including
+ the corner the `+` sits in. Labelled the same as the row below: one
+ set of tools that happens to need two rows to fit.
+
+ Wrapped in a `0fr`/`1fr` grid rather than dropped outright while
+ dictating: height has nothing to animate between unless something
+ supplies the two ends, and this supplies them without measuring. */}
+ <div
+ aria-hidden={above.length === 0 || dictating}
+ {...(above.length === 0 || dictating ? { inert: '' } : {})}
+ className={cn(
+ 'grid transition-all duration-200 ease-out motion-reduce:transition-none',
+ above.length > 0 && !dictating
+ ? 'grid-rows-[1fr] opacity-100'
+ : 'grid-rows-[0fr] opacity-0',
+ )}
+ >
+ <div className="overflow-hidden">
+ {/* Travels down as the row above closes over it, so the chips read as
+ moving out of the way rather than being wiped from the bottom up. */}
+ <div
+ role="list"
+ aria-label={localize('com_ui_composer_tools')}
+ className={cn(
+ rowClass,
+ 'pb-1.5 transition-transform duration-200 ease-out',
+ dictating ? 'translate-y-3' : 'translate-y-0',
+ )}
+ >
+ {above.map(renderChip)}
+ </div>
+ </div>
+ </div>
+ <div ref={rowRef} className={rowClass}>
+ {/* Never unmounted, so its glyph can turn into the close mark rather
+ than one icon being swapped for another. */}
+ <span ref={plusRef} className="shrink-0">
+ <Palette
+ index={index}
+ entries={entries}
+ disabled={disabled}
+ dictating={dictating}
+ onOpened={onPaletteOpen}
+ onCancel={dictation.cancel}
+ agentId={agentId}
+ endpoint={endpoint}
+ endpointType={endpointType}
+ endpointFileConfig={endpointFileConfig}
+ useResponsesApi={useResponsesApi}
+ conversationId={conversationId}
+ conversation={conversation}
+ files={files}
+ setFiles={setFiles}
+ setFilesLoading={setFilesLoading}
+ canAttach={canAttach}
+ anchorRef={anchorRef}
+ />
+ </span>
+ {/* A box rather than `contents` so it has something to move: the split
+ only puts chips here when they all fit on this line, so wrapping as
+ one unit and wrapping as siblings come to the same layout. */}
+ <div
+ role="list"
+ aria-label={localize('com_ui_composer_tools')}
+ aria-hidden={dictating}
+ /* Hidden from a reader and unreachable by a pointer, but every chip
+ still holds a remove button that Tab would land on. `inert` is what
+ takes those out of the tab order along with everything else. */
+ {...(dictating ? { inert: '' } : {})}
+ className={cn(
+ 'flex min-w-0 flex-wrap items-center gap-1.5',
+ 'transition duration-200 ease-out motion-reduce:transition-none',
+ dictating ? 'pointer-events-none translate-y-3 opacity-0' : 'translate-y-0 opacity-100',
+ )}
+ >
+ {inline.map(renderChip)}
+ </div>
+ {/* Auto margin on the main-start side, so the group sits at the end of
+ the row whether or not chips share it.
+
+ The mic and the send button hold their places through a recording:
+ each takes over the job next to it (stop, and stop-and-send) rather
+ than being replaced by a control that slides in somewhere else. Only
+ what has no job during a recording actually moves. */}
+ <div
+ ref={controlsRef}
+ className={cn('flex shrink-0 items-center gap-1.5', isRTL ? 'mr-auto' : 'ml-auto')}
+ >
+ {/* One cell holding both: the settled controls drop out of it as the
+ elapsed time rises into their place, and the row keeps one width
+ throughout so nothing beside it shifts. */}
+ <div className="grid">
+ <div
+ aria-hidden={dictating}
+ {...(dictating ? { inert: '' } : {})}
+ className={cn(
+ 'col-start-1 row-start-1 flex items-center justify-end gap-1.5',
+ 'transition duration-200 ease-out motion-reduce:transition-none',
+ dictating
+ ? 'pointer-events-none translate-y-3 opacity-0'
+ : 'translate-y-0 opacity-100',
+ )}
+ >
+ <Thinking
+ index={index}
+ disabled={disabled}
+ hasAddedConversation={hasAddedConversation}
+ />
+ <TokenUsage index={index} conversation={conversation} isSubmitting={isSubmitting} />
+ </div>
+ {/* Arrives and leaves in depth. The elapsed time is not one of the
+ things that stepped aside, so it has nowhere to travel from:
+ it comes forward into the row and recedes back out of it. */}
+ <div
+ aria-hidden={!dictating}
+ {...(dictating ? {} : { inert: '' })}
+ className={cn(
+ 'col-start-1 row-start-1 flex origin-center items-center justify-end px-1',
+ 'transition duration-200 ease-out motion-reduce:transition-none',
+ dictating ? 'scale-100 opacity-100' : 'pointer-events-none scale-90 opacity-0',
+ )}
+ >
+ <span className="text-text-secondary text-xs tabular-nums" aria-hidden="true">
+ {dictation.transcribing
+ ? localize('com_ui_transcribing')
+ : formatElapsed(dictation.elapsed)}
+ </span>
+ </div>
+ </div>
+ {approvalSlot}
+ <span role="status" aria-live="polite" className="sr-only">
+ {dictationStatus}
+ </span>
+ {showSpeech && (
+ <RoundButton
+ label={dictating ? localize('com_ui_stop') : localize('com_ui_use_micrphone')}
+ onClick={dictating ? dictation.stopToComposer : dictation.start}
+ /* Once the take is handed to the transcriber there is nothing left
+ to stop, and pressing either of these again would only rewrite
+ how a take that has already been committed gets spent. Cancel,
+ on the `+`, stays live: an external transcription in flight can
+ still be thrown away. */
+ disabled={
+ dictation.transcribing ||
+ (!dictating && (speechDisabled || dictation.startDisabled))
+ }
+ >
+ {dictating ? (
+ <Square className="size-4 fill-current" aria-hidden="true" />
+ ) : (
+ <Mic className="size-5" aria-hidden="true" />
+ )}
+ </RoundButton>
+ )}
+ {dictating ? (
+ <RoundButton
+ primary
+ label={localize('com_nav_send_message')}
+ onClick={dictation.stopAndSend}
+ disabled={dictation.transcribing}
+ >
+ <SendIcon size={18} />
+ </RoundButton>
+ ) : (
+ actionSlot
+ )}
+ </div>
+ </div>
+ {mcpConfigProps && (
+ <MCPConfigDialog
+ {...mcpConfigProps}
+ conversationId={conversationId}
+ storageContextKey={context?.storageContextKey}
+ />
+ )}
+ </div>
+ );
+}
+
+export default memo(Bar);
diff --git a/client/src/components/Chat/Input/Composer/Chip.tsx b/client/src/components/Chat/Input/Composer/Chip.tsx
new file mode 100644
index 0000000000..4945b02576
--- /dev/null
+++ b/client/src/components/Chat/Input/Composer/Chip.tsx
@@ -0,0 +1,53 @@
+import { memo } from 'react';
+import { Chip as SharedChip } from '@librechat/client';
+import type { ReactNode } from 'react';
+
+export interface ChipProps {
+ label: string;
+ /** Full text for the native tooltip when `label` is truncated. */
+ title?: string;
+ icon?: ReactNode;
+ /** Rendered between the label and the remove button. */
+ trailing?: ReactNode;
+ onRemove?: () => void;
+ removeLabel?: string;
+ className?: string;
+ 'data-testid'?: string;
+}
+
+function Chip({
+ label,
+ title,
+ icon,
+ trailing,
+ onRemove,
+ removeLabel,
+ className,
+ 'data-testid': testId,
+}: ChipProps) {
+ return (
+ <SharedChip
+ role="listitem"
+ data-testid={testId}
+ tone="surface"
+ size="md"
+ shape="theme"
+ title={title ?? label}
+ leading={
+ icon != null ? (
+ <span className="flex shrink-0 items-center" aria-hidden="true">
+ {icon}
+ </span>
+ ) : undefined
+ }
+ trailing={trailing}
+ onRemove={onRemove}
+ removeLabel={removeLabel}
+ className={className}
+ >
+ <span className="text-sm font-normal">{label}</span>
+ </SharedChip>
+ );
+}
+
+export default memo(Chip);
diff --git a/client/src/components/Chat/Input/Composer/Effort.tsx b/client/src/components/Chat/Input/Composer/Effort.tsx
new file mode 100644
index 0000000000..ca65d275ec
--- /dev/null
+++ b/client/src/components/Chat/Input/Composer/Effort.tsx
@@ -0,0 +1,512 @@
+import { memo, useRef, useMemo, useState, useEffect, useCallback, useLayoutEffect } from 'react';
+import { CircleHelp } from 'lucide-react';
+import { Constants, reasoningOverrideSchema } from 'librechat-data-provider';
+import {
+ HoverCard,
+ IconButton,
+ HoverCardTrigger,
+ HoverCardContent,
+ HoverCardPortal,
+} from '@librechat/client';
+import type { SettingDefinition, TConversation, TReasoningOverride } from 'librechat-data-provider';
+import type { CSSProperties } from 'react';
+import type { LocalizeFunction } from '~/common';
+import type { TranslationKeys } from '~/hooks';
+import { useLocalize } from '~/hooks';
+import { cn } from '~/utils';
+
+/** Values represented outside the graded track. Their provider mapping names
+ * the separate mode, which can be Auto, Off, or another provider label, while
+ * the slider itself only expresses "how much".
+ *
+ * `none` is deliberately NOT here: it is a real setting meaning "do not reason
+ * at all", and swallowing it hid the track's own first stop. */
+const UNGRADED_VALUES = new Set(['unset', 'auto', '']);
+
+const TRACK_H = 24;
+/** The thumb overhangs the rail slightly at rest and grows while held, so the
+ * row is sized to the largest it can get and the rail is banded inside it. */
+const THUMB = 28;
+const THUMB_ACTIVE = 32;
+/** Which way each arrow key moves along the track. */
+const ARROW_STEP: Record<string, number | undefined> = {
+ ArrowLeft: -1,
+ ArrowUp: -1,
+ ArrowRight: 1,
+ ArrowDown: 1,
+};
+
+/**
+ * `enumMappings` maps a raw value to a translation KEY, not to display text:
+ * rendering it directly is what leaks `com_ui_medium` into the UI. Shared with
+ * the trigger button, which is the only place the level is named.
+ */
+export function resolveEffortLabel(
+ setting: SettingDefinition,
+ value: string,
+ localize: LocalizeFunction,
+): string {
+ const mapped = setting.enumMappings?.[value];
+ if (mapped != null) {
+ const key = String(mapped);
+ const translated = localize(key as TranslationKeys);
+ if (translated !== '' && translated !== key) {
+ return translated;
+ }
+ }
+ if (UNGRADED_VALUES.has(value)) {
+ return localize('com_ui_auto');
+ }
+ return value.charAt(0).toUpperCase() + value.slice(1);
+}
+
+interface EffortProps {
+ setting: SettingDefinition;
+ conversation: TConversation | null;
+ value?: TReasoningOverride;
+ onChange: (value: TReasoningOverride) => void;
+}
+
+/**
+ * Reasoning effort as a filled track running from faster to smarter.
+ *
+ * The stops are named choices, not a continuum, so the interactive layer is a
+ * radiogroup of segment hit-targets, giving correct arrow-key and screen-reader
+ * behaviour for free, with pointer drag layered on top so the thumb can also
+ * be swept the way a touch control behaves.
+ *
+ * The level is deliberately not named in here: the button that opens this owns
+ * that, so the value never appears in two places at once.
+ */
+function Effort({ setting, conversation, value, onChange }: EffortProps) {
+ const localize = useLocalize();
+ const trackRef = useRef<HTMLDivElement>(null);
+ /** Ref drives the gesture (pointermove fires before a state flush would land);
+ * the state only feeds styling. */
+ const draggingRef = useRef(false);
+ /** One per stop, so an arrow key can move focus along with the selection. */
+ const stopRefs = useRef<(HTMLButtonElement | null)[]>([]);
+ const [dragging, setDragging] = useState(false);
+
+ const { levels, ungradedValue } = useMemo(() => {
+ const options = (setting.options ?? []).map(String);
+ return {
+ levels: options.filter((option) => !UNGRADED_VALUES.has(option)),
+ ungradedValue: options.find((option) => UNGRADED_VALUES.has(option)),
+ };
+ }, [setting.options]);
+
+ /* Same resolution as the trigger: an untouched conversation falls back to
+ the setting's possibly admin-overridden default, not to the separate mode. */
+ const raw =
+ value?.key === setting.key
+ ? value.value
+ : (conversation?.[setting.key as keyof TConversation] ?? setting.default);
+ const current = raw == null ? undefined : String(raw);
+ const isUngraded = current == null || UNGRADED_VALUES.has(current);
+ const activeIndex = isUngraded ? -1 : levels.indexOf(current);
+
+ /* The graded level the separate mode was turned on from. Two jobs: that mode
+ has no position on the rail, so the fill and thumb hold this one while they
+ fade (without it the thumb unmounted instantly and left the fill briefly
+ naked, which flashed green), and switching the separate mode off returns here
+ instead of dumping the user on the lowest level.
+
+ Held as a value rather than an index, and scoped to the conversation it was
+ seen in: the option list differs per model, so an index carried across a
+ model switch would point at a different level or none at all. Anything that
+ no longer resolves falls back to the first level. */
+ const conversationKey = conversation?.conversationId ?? '';
+ const settingKey = `${setting.key}\u0000${conversation?.endpoint ?? ''}\u0000${conversation?.model ?? ''}\u0000${conversation?.spec ?? ''}`;
+ const [remembered, setRemembered] = useState<{
+ conversationKey: string;
+ settingKey: string;
+ value: string;
+ } | null>(null);
+ if (
+ activeIndex >= 0 &&
+ current != null &&
+ (remembered?.value !== current ||
+ remembered.conversationKey !== conversationKey ||
+ remembered.settingKey !== settingKey)
+ ) {
+ setRemembered({ conversationKey, settingKey, value: current });
+ } else if (
+ remembered != null &&
+ remembered.settingKey === settingKey &&
+ remembered.conversationKey !== conversationKey &&
+ (remembered.conversationKey === '' || remembered.conversationKey === Constants.NEW_CONVO)
+ ) {
+ /* A new chat carries a placeholder id until its first message lands. The
+ level chosen before sending is still the same user in the same thread, so
+ it follows the conversation into its real id rather than being dropped. */
+ setRemembered({ conversationKey, settingKey, value: remembered.value });
+ }
+ const rememberedIndex =
+ remembered != null &&
+ remembered.conversationKey === conversationKey &&
+ remembered.settingKey === settingKey
+ ? levels.indexOf(remembered.value)
+ : -1;
+ const restoreIndex = rememberedIndex >= 0 ? rememberedIndex : 0;
+ const shownIndex = activeIndex >= 0 ? activeIndex : restoreIndex;
+ const initialShownIndex = useRef(shownIndex);
+
+ useLayoutEffect(() => {
+ stopRefs.current[initialShownIndex.current]?.focus();
+ }, []);
+
+ const select = useCallback(
+ (nextValue: string) => {
+ const parsed = reasoningOverrideSchema.safeParse({ key: setting.key, value: nextValue });
+ if (parsed.success) {
+ onChange(parsed.data);
+ }
+ },
+ [onChange, setting.key],
+ );
+ const label = useCallback(
+ (value: string) => resolveEffortLabel(setting, value, localize),
+ [setting, localize],
+ );
+ const activeUngradedValue =
+ current != null && UNGRADED_VALUES.has(current) ? current : ungradedValue;
+ const ungradedLabel =
+ activeUngradedValue != null ? label(activeUngradedValue) : localize('com_ui_auto');
+
+ /**
+ * Nearest stop to a pointer position, so a sweep snaps rather than drifts.
+ *
+ * Writes are coalesced to one per frame: a burst of moves within a single
+ * task would each write from the same stale conversation snapshot, and an
+ * earlier value could land last. Only the newest index is ever committed.
+ */
+ const pendingRef = useRef<number | null>(null);
+ const frameRef = useRef<number | null>(null);
+ const selectFromPointer = useCallback(
+ (clientX: number) => {
+ const track = trackRef.current;
+ if (!track || levels.length === 0) {
+ return;
+ }
+ const rect = track.getBoundingClientRect();
+ const usable = rect.width - THUMB;
+ if (usable <= 0) {
+ return;
+ }
+ const ratio = (clientX - rect.left - THUMB / 2) / usable;
+ pendingRef.current = Math.round(Math.min(1, Math.max(0, ratio)) * (levels.length - 1));
+ if (frameRef.current != null) {
+ return;
+ }
+ frameRef.current = requestAnimationFrame(() => {
+ frameRef.current = null;
+ const index = pendingRef.current;
+ pendingRef.current = null;
+ if (index != null && levels[index] != null) {
+ select(levels[index]);
+ }
+ });
+ },
+ [levels, select],
+ );
+
+ useEffect(
+ () => () => {
+ if (frameRef.current != null) {
+ cancelAnimationFrame(frameRef.current);
+ }
+ },
+ [],
+ );
+
+ if (levels.length === 0) {
+ return null;
+ }
+
+ const ratioOf = (index: number) => (levels.length === 1 ? 1 : index / (levels.length - 1));
+ const offset = (ratio: number, fromRight = false) => {
+ const percent = (fromRight ? 1 - ratio : ratio) * 100;
+ const pixels = THUMB * (fromRight ? ratio - 0.5 : 0.5 - ratio);
+ const roundedPercent = Number(percent.toFixed(6));
+ const roundedPixels = Number(Math.abs(pixels).toFixed(6));
+ return `calc(${roundedPercent}% ${pixels < 0 ? '-' : '+'} ${roundedPixels}px)`;
+ };
+ const hitArea = (index: number): CSSProperties => {
+ const previousBoundary = ratioOf(index - 0.5);
+ const nextBoundary = ratioOf(index + 0.5);
+ return {
+ left: index === 0 ? 0 : offset(previousBoundary),
+ right: index === levels.length - 1 ? 0 : offset(nextBoundary, true),
+ };
+ };
+ /* Anchored on the resting thumb size so its edge is flush with the rail at
+ either end; while held it grows a couple of pixels past, which reads as the
+ thumb lifting rather than as a misaligned track. */
+ const centerOf = (index: number) =>
+ `calc(${THUMB / 2}px + ${ratioOf(index)} * (100% - ${THUMB}px))`;
+ /* Ends half a rail-height PAST the thumb's centre, which puts the fill's own
+ rounded cap concentric with the thumb. The cap's radius (TRACK_H / 2) is
+ smaller than the thumb's, so the thumb geometrically contains it at every
+ position, including the first stop where the fill disappears entirely
+ beneath it.
+ That containment holds mid-animation too, because the offset is constant:
+ collapsing to zero at the first stop instead left the fill briefly wider
+ than the thumb could cover, which flashed green on the way down. */
+ const fillWidth = (index: number) =>
+ `calc(${THUMB / 2 + TRACK_H / 2}px + ${ratioOf(index)} * (100% - ${THUMB}px))`;
+
+ /* `descriptionCode` is what says whether this is a translation key or the
+ literal text an admin wrote. Translating it either way sent literal text
+ through i18next, which reads anything before a colon as a namespace and
+ silently drops it. */
+ let descriptionText: string | undefined;
+ if (setting.description != null && setting.description !== '') {
+ descriptionText =
+ setting.descriptionCode === true
+ ? localize(setting.description as TranslationKeys)
+ : setting.description;
+ }
+ const thumbSize = dragging ? THUMB_ACTIVE : THUMB;
+
+ return (
+ <div className="w-[268px] p-3">
+ <div
+ ref={trackRef}
+ role="radiogroup"
+ aria-label={localize('com_ui_composer_thinking')}
+ /* The rail is built on physical left offsets and clientX math, so the
+ axis is explicitly LTR; the hint row below carries the same dir so
+ "Faster" stays over the low end in RTL locales too. */
+ dir="ltr"
+ style={{ height: THUMB_ACTIVE }}
+ onPointerDown={(e) => {
+ /* Capture keeps the sweep alive past the track's edges. It throws for
+ pointers the element never saw, which must not abort the gesture. */
+ try {
+ e.currentTarget.setPointerCapture(e.pointerId);
+ } catch {
+ /* no capture available: the drag still tracks via pointermove */
+ }
+ draggingRef.current = true;
+ setDragging(true);
+ selectFromPointer(e.clientX);
+ }}
+ onPointerMove={(e) => {
+ if (draggingRef.current) {
+ selectFromPointer(e.clientX);
+ }
+ }}
+ onPointerUp={(e) => {
+ try {
+ e.currentTarget.releasePointerCapture(e.pointerId);
+ } catch {
+ /* nothing was captured */
+ }
+ draggingRef.current = false;
+ setDragging(false);
+ }}
+ onPointerCancel={() => {
+ draggingRef.current = false;
+ setDragging(false);
+ }}
+ className={cn(
+ 'relative w-full touch-none transition-opacity duration-200 select-none',
+ dragging ? 'cursor-grabbing' : 'cursor-pointer',
+ /* Muted while the provider is deciding, so it reads as "not set by
+ you" instead of "set to the lowest". Touching it takes over. */
+ isUngraded && 'opacity-60',
+ )}
+ >
+ <span
+ aria-hidden="true"
+ style={{ height: TRACK_H }}
+ className={cn(
+ 'absolute inset-x-0 top-1/2 -translate-y-1/2 rounded-full transition-colors',
+ /* The border is always present and only its colour changes. Adding
+ the border class on the way into the separate mode flipped its width 0 -> 1px
+ with the colour animating up from `currentColor`, which flashed
+ white, and the extra pixel nudged the centred label. */
+ 'border border-dashed',
+ /* Not `surface-tertiary`: the popover itself is that colour now,
+ and the rail would vanish into it. */
+ isUngraded
+ ? 'border-border-heavy bg-transparent'
+ : 'bg-border-medium border-transparent',
+ )}
+ />
+ {/* The semantic accent keeps the track intentional in every theme.
+ Always mounted: unmounting it at the first stop made the fill snap
+ out of existence on the way down instead of shrinking, which reads
+ as a glitch. Width and opacity run on their own layers so they can
+ keep their own clocks: the fill clears fast (nearest scale to
+ 90ms) so it is already gone before the thumb starts uncovering
+ the rail. */}
+ <span
+ aria-hidden="true"
+ style={{ height: TRACK_H, width: fillWidth(shownIndex) }}
+ className={cn(
+ 'absolute top-1/2 left-0 -translate-y-1/2 transition-all ease-out motion-reduce:duration-0',
+ dragging ? 'duration-75' : 'duration-150',
+ )}
+ >
+ <span
+ className={cn(
+ 'bg-accent-primary block h-full w-full rounded-full transition-opacity duration-100 ease-out motion-reduce:duration-0',
+ isUngraded ? 'opacity-0' : 'opacity-100',
+ )}
+ />
+ </span>
+
+ {!isUngraded &&
+ levels.map((value, index) => (
+ <span
+ key={`stop-${value}`}
+ aria-hidden="true"
+ style={{ left: centerOf(index) }}
+ className={cn(
+ 'absolute top-1/2 h-1 w-1 -translate-x-1/2 -translate-y-1/2 rounded-full opacity-50 transition-colors',
+ index < activeIndex ? 'bg-surface-fixed' : 'bg-text-secondary',
+ )}
+ />
+ ))}
+
+ {/* The ungraded mode has no position on the track, so the rail names it
+ outright rather than looking broken. */}
+ {isUngraded && (
+ <span
+ aria-hidden="true"
+ className="text-text-secondary pointer-events-none absolute inset-0 flex items-center justify-center text-xs font-medium tracking-wide uppercase"
+ >
+ {ungradedLabel}
+ </span>
+ )}
+
+ {/* Always mounted: unmounting it on the way into the ungraded mode pulled
+ the cover off the fill mid-fade. It holds still until the fill has
+ gone, then fades itself: its own opacity leg (nearest scale to
+ 140ms) is delayed on the way in (nearest scale to the fill's
+ 90ms), so the cover does not lift before the rail underneath is
+ clean. */}
+ <span
+ aria-hidden="true"
+ style={{ left: centerOf(shownIndex), height: thumbSize, width: thumbSize }}
+ className={cn(
+ 'absolute top-1/2 -translate-x-1/2 -translate-y-1/2 transition-all ease-out motion-reduce:duration-0',
+ dragging ? 'duration-75' : 'duration-150',
+ )}
+ >
+ <span
+ className={cn(
+ 'bg-surface-fixed block h-full w-full rounded-full shadow-md transition-opacity duration-150 ease-out motion-reduce:delay-0 motion-reduce:duration-0',
+ isUngraded ? 'opacity-0 delay-100' : 'opacity-100 delay-0',
+ )}
+ />
+ </span>
+
+ {levels.map((value, index) => {
+ /* Spread as a literal rather than passed through: an object built by
+ a helper call cannot be checked property-by-property, so it is
+ destructured here where `left`/`right` are visibly the only keys. */
+ const { left, right } = hitArea(index);
+ return (
+ <button
+ key={value}
+ type="button"
+ role="radio"
+ aria-checked={!isUngraded && index === activeIndex}
+ aria-label={label(value)}
+ /* One stop for the whole group, as a radiogroup is meant to have:
+ Tab reaches the current level and leaves, and the arrow keys move
+ between them. In the ungraded mode no level is checked, so the one that
+ would be restored takes the tab stop. */
+ tabIndex={index === shownIndex ? 0 : -1}
+ onKeyDown={(event) => {
+ const step = ARROW_STEP[event.key];
+ if (step === undefined) {
+ return;
+ }
+ event.preventDefault();
+ const next = Math.min(Math.max(index + step, 0), levels.length - 1);
+ select(levels[next]);
+ stopRefs.current[next]?.focus();
+ }}
+ ref={(node) => {
+ stopRefs.current[index] = node;
+ }}
+ onClick={() => select(value)}
+ style={{ left, right }}
+ className="focus-visible:ring-text-primary absolute inset-y-0 rounded-full focus-visible:ring-2 focus-visible:outline-hidden focus-visible:ring-inset"
+ />
+ );
+ })}
+ </div>
+
+ {/* One slot holding both footers: the axis hints belong to the gesture and
+ the Thinking row to the resting state, so they crossfade in place
+ rather than stacking. Grid keeps the height of the taller of the two. */}
+ <div className="mt-1.5 grid">
+ <div
+ aria-hidden="true"
+ dir="ltr"
+ className={cn(
+ 'text-text-secondary col-start-1 row-start-1 flex items-center justify-between text-xs transition-opacity duration-150',
+ dragging ? 'opacity-100' : 'pointer-events-none opacity-0',
+ )}
+ >
+ <span>{localize('com_ui_composer_effort_faster')}</span>
+ <span>{localize('com_ui_composer_effort_smarter')}</span>
+ </div>
+
+ <div
+ className={cn(
+ 'col-start-1 row-start-1 flex items-center justify-between gap-2 transition-opacity duration-150',
+ dragging ? 'pointer-events-none opacity-0' : 'opacity-100',
+ )}
+ >
+ <span className="text-text-secondary text-sm">
+ {localize('com_ui_composer_thinking')}
+ </span>
+ <span className="flex shrink-0 items-center gap-2">
+ {/* Always present so the separate mode reads as something the user
+ can turn on and off rather than as a one-way escape hatch. */}
+ {ungradedValue != null && (
+ <button
+ type="button"
+ aria-pressed={isUngraded}
+ onClick={() => select(isUngraded ? levels[restoreIndex] : ungradedValue)}
+ className={cn(
+ 'rounded-full px-2 py-0.5 text-xs transition-colors',
+ isUngraded
+ ? 'bg-accent-primary/15 text-accent-primary'
+ : 'text-text-secondary hover:bg-surface-hover hover:text-text-primary',
+ )}
+ >
+ {label(ungradedValue)}
+ </button>
+ )}
+ {descriptionText != null && descriptionText !== '' && (
+ <HoverCard openDelay={200}>
+ <HoverCardTrigger asChild>
+ {/* A button rather than a bare span: this is the only place
+ the provider's own explanation of the parameter appears,
+ and hovering was the only way to reach it. */}
+ <IconButton label={localize('com_ui_more_info')} size="xs">
+ <CircleHelp className="text-text-secondary h-3.5 w-3.5" aria-hidden="true" />
+ </IconButton>
+ </HoverCardTrigger>
+ <HoverCardPortal>
+ <HoverCardContent side="top" className="w-72">
+ <span className="text-sm">{descriptionText}</span>
+ </HoverCardContent>
+ </HoverCardPortal>
+ </HoverCard>
+ )}
+ </span>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+export default memo(Effort);
diff --git a/client/src/components/Chat/Input/Composer/Hints.tsx b/client/src/components/Chat/Input/Composer/Hints.tsx
new file mode 100644
index 0000000000..53400b5303
--- /dev/null
+++ b/client/src/components/Chat/Input/Composer/Hints.tsx
@@ -0,0 +1,52 @@
+import { memo } from 'react';
+import type { ComposerHintState } from '~/hooks/Input/useComposerHint';
+import useComposerHint from '~/hooks/Input/useComposerHint';
+
+/** Scoped per pane: split view mounts one composer per index, and a shared id
+ * would point every textarea's `aria-describedby` at the first pane's hint. */
+export const composerHintId = (index: number) => `composer-hint-${index}`;
+
+/**
+ * The dim line under the composer carrying whatever the current state affords:
+ * most importantly the during-run modifiers (`⌘⏎` queue, `⌥⏎` interrupt & send),
+ * which had no on-screen presence at all before.
+ *
+ * Ambient tips are opt-in and off by default: they are discovery copy, and the
+ * row they sit on costs the thread height on every turn. Live state (uploads, a
+ * paused question, the during-run modifiers) reports itself either way; those
+ * are things happening now, not things worth teaching.
+ *
+ * The visible line is `aria-hidden`; the same string is mirrored into a
+ * visually-hidden node that the textarea points at via `aria-describedby`, which
+ * is why hiding the line costs a screen reader nothing. An `aria-live` region
+ * here would re-announce on every keystroke as the hint flips between idle and
+ * typing, so the description channel carries it instead.
+ */
+function Hints({
+ index,
+ enterToSend,
+ showTips,
+ ...state
+}: ComposerHintState & { index: number; showTips: boolean }) {
+ const hint = useComposerHint({ ...state, enterToSend });
+ const visible = showTips || hint.kind === 'state';
+
+ return (
+ <>
+ {visible && (
+ <div
+ aria-hidden="true"
+ data-testid="composer-hints"
+ className="text-text-secondary pointer-events-none px-3 pt-1.5 text-center text-xs leading-4 select-none"
+ >
+ {hint.text}
+ </div>
+ )}
+ <span id={composerHintId(index)} className="sr-only">
+ {hint.text}
+ </span>
+ </>
+ );
+}
+
+export default memo(Hints);
diff --git a/client/src/components/Chat/Input/Composer/Palette.tsx b/client/src/components/Chat/Input/Composer/Palette.tsx
new file mode 100644
index 0000000000..991fccd035
--- /dev/null
+++ b/client/src/components/Chat/Input/Composer/Palette.tsx
@@ -0,0 +1,1325 @@
+import React, {
+ memo,
+ useRef,
+ useMemo,
+ useState,
+ useEffect,
+ useCallback,
+ useLayoutEffect,
+} from 'react';
+import { useSetAtom } from 'jotai';
+import * as Ariakit from '@ariakit/react';
+import { AutoSizer, List } from 'react-virtualized';
+import { Star, Plus, Search, ChevronDown } from 'lucide-react';
+import { FileUpload, IconButton, TooltipAnchor } from '@librechat/client';
+import type {
+ TFile,
+ TConversation,
+ EModelEndpoint,
+ EndpointFileConfig,
+} from 'librechat-data-provider';
+import type { PaletteEntry, PaletteSection } from '~/hooks/Input/usePaletteEntries';
+import type { AttachEntry } from '~/hooks/Input/useAttachItems';
+import type { ExtendedFile, FileSetter } from '~/common';
+import type { TranslationKeys } from '~/hooks';
+import FilePreview from '~/components/Chat/Input/Files/FilePreview';
+import { SharePointPickerDialog } from '~/components/SharePoint';
+import useReducedMotion from '~/hooks/Generic/useReducedMotion';
+import { getFileType, isUnifiedUploadMode, cn } from '~/utils';
+import useToolFavorites from '~/hooks/Input/useToolFavorites';
+import useElementSize from '~/hooks/Generic/useElementSize';
+import useRecentFiles from '~/hooks/Input/useRecentFiles';
+import useAttachItems from '~/hooks/Input/useAttachItems';
+import { useMCPRefresh } from '~/hooks/MCP/useMCPRefresh';
+import { isMacPlatform } from '~/utils/shortcuts';
+import { useBadgeRowContext } from '~/Providers';
+import { composerLiftFamily } from './state';
+import { useLocalize } from '~/hooks';
+
+const HEADER_HEIGHT = 26;
+const ROW_HEIGHT = 34;
+const ROW_HEIGHT_DESC = 46;
+/* Kept short enough that the popup clears the space below the composer, so it
+ opens downward instead of Ariakit flipping it up over the thread. */
+const LIST_MAX_HEIGHT = 300;
+/** Gap between the composer and the popup, and between the popup and the
+ * bottom of the window. Shared with the `gutter` prop so the room the page
+ * makes and the room the popup takes cannot drift apart. */
+const POPOVER_GUTTER = 8;
+const VIEWPORT_PADDING = 12;
+/** Length of the landing screen's lift transition; see `ChatView`'s
+ * `duration-200` on the same element. */
+const LIFT_MS = 200;
+/** Ariakit portals to document.body by default, which puts the palette outside every landmark. */
+const getMainLandmark = () => document.querySelector<HTMLElement>('main');
+/** Hidden on hover-capable pointers until the row is hovered or focused.
+ * Touch keeps them visible. `transition-none` overrides IconButton's color
+ * fade so the reveal is an appear, not a tint. */
+const ROW_ACTION_REVEAL =
+ 'transition-none opacity-100 group-focus-within/row:opacity-100 group-hover/row:opacity-100 [@media(hover:hover)]:opacity-0';
+/** How long the folded destinations take to fade before they give up their
+ * space; matches `.animate-composer-palette-row-out` in `style.css`. */
+const ROW_FADE_MS = 110;
+const MORE_ROW_KEY = 'attach:more';
+/** How long a row takes to reach a new offset, and on what curve. */
+const ROW_SHIFT_MS = 260;
+const ROW_SHIFT_EASING = 'cubic-bezier(0.32, 0.72, 0, 1)';
+/** Separator for the row-set signature; cannot occur in a row key. */
+const KEY_SEP = '\u0000';
+const NO_ENTERING: ReadonlySet<string> = new Set();
+const NO_ROWS: PaletteRow[] = [];
+/** Spelled out for the platform, since this is read aloud: "Mod" is a
+ * developer's shorthand and not a key on anybody's keyboard. */
+const FAVORITE_MODIFIER = isMacPlatform ? '\u2318' : 'Ctrl';
+
+/** A row's element id, derived from its identity so the combobox keeps naming
+ * the same row as the list rearranges under it. Scoped per composer index:
+ * split view mounts one palette per pane, and a shared id would point the
+ * secondary combobox's `aria-controls` and `aria-activedescendant` at the
+ * primary pane's list. */
+const rowElementId = (index: number, key: string) => {
+ let encodedKey = '';
+ for (let i = 0; i < key.length; i++) {
+ encodedKey += key.charCodeAt(i).toString(16).padStart(4, '0');
+ }
+ return `palette-row-${index}-${encodedKey}`;
+};
+
+const SECTION_LABEL: Record<PaletteSection, TranslationKeys> = {
+ tool: 'com_ui_composer_tools',
+ skill: 'com_ui_skills',
+ mcp: 'com_ui_composer_mcp',
+};
+
+type PaletteRow =
+ | { type: 'header'; key: string; label: string }
+ | { type: 'attach'; key: string; entry: AttachEntry }
+ | { type: 'more'; key: string; label: string }
+ | { type: 'file'; key: string; file: TFile }
+ | { type: 'entry'; key: string; entry: PaletteEntry; isFavorite: boolean };
+
+const isSelectable = (row: PaletteRow) => row.type !== 'header';
+
+/** Ranks a match so exact prefixes float above incidental description hits. */
+function scoreEntry(label: string, description: string | undefined, query: string): number {
+ const lower = label.toLowerCase();
+ if (lower.startsWith(query)) {
+ return 0;
+ }
+ if (lower.includes(query)) {
+ return 1;
+ }
+ if (description?.toLowerCase().includes(query) === true) {
+ return 2;
+ }
+ return -1;
+}
+
+/** The file's own date, in the user's locale, as the row's second line. */
+function formatFileDate(file: TFile): string {
+ const raw = file.updatedAt ?? file.createdAt;
+ if (raw == null) {
+ return '';
+ }
+ return new Date(raw).toLocaleDateString(undefined, {
+ day: 'numeric',
+ month: 'short',
+ year: 'numeric',
+ });
+}
+
+function rowHeight(row: PaletteRow): number {
+ if (row.type === 'header') {
+ return HEADER_HEIGHT;
+ }
+ if (row.type === 'entry' && row.entry.description != null && row.entry.description !== '') {
+ return ROW_HEIGHT_DESC;
+ }
+ if (row.type === 'file') {
+ return ROW_HEIGHT_DESC;
+ }
+ return ROW_HEIGHT;
+}
+
+interface PaletteProps {
+ /** Composer index, so a split view lifts only the side that opened a popup. */
+ index: number;
+ disabled?: boolean;
+ /** A recording is running: the button drops the take instead of opening the
+ * palette, and its glyph turns into the close mark to say so. */
+ dictating?: boolean;
+ /** Fired when the popover opens; the bar uses the first call to start
+ * loading the full skills catalog. */
+ onOpened?: () => void;
+ onCancel?: () => void;
+ agentId?: string | null;
+ endpoint?: string | null;
+ endpointType?: EModelEndpoint | string;
+ endpointFileConfig?: EndpointFileConfig;
+ useResponsesApi?: boolean;
+ conversationId: string;
+ conversation: TConversation | null;
+ files: Map<string, ExtendedFile>;
+ setFiles: FileSetter;
+ setFilesLoading: React.Dispatch<React.SetStateAction<boolean>>;
+ /** Attach destinations are hidden when the endpoint cannot take uploads. */
+ canAttach: boolean;
+ /** Owned by `Bar`, which also renders the active ones as chips (derived once
+ * there so the skills catalog is not walked twice per render). */
+ entries: PaletteEntry[];
+ /** The composer box the popover anchors to, so it matches its width. */
+ anchorRef: React.RefObject<HTMLElement>;
+}
+
+/**
+ * The composer's single entry point for everything that is not typing: upload
+ * destinations, built-in tools, skills and MCP servers, all searchable from one
+ * input and all favouritable.
+ *
+ * Replaces the old split between the attach `+` menu and the tools gear, and
+ * the pin/drag/wiggle badge row: a starred row floats into Favourites, which
+ * is server-persisted and shared with the tools marketplace.
+ *
+ * The list is virtualized (catalogs run to hundreds of skills and MCP servers),
+ * so keyboard navigation is driven manually against the flat row model rather
+ * than by an Ariakit composite, mirroring `SkillsCommand`. Favouriting is a
+ * pointer action on the star and `Mod+D` on the active row, keeping each row a
+ * single valid `option` rather than nesting a button inside it.
+ */
+function Palette({
+ index,
+ disabled,
+ dictating = false,
+ onOpened,
+ onCancel,
+ agentId,
+ endpoint,
+ endpointType,
+ endpointFileConfig,
+ useResponsesApi,
+ conversationId,
+ conversation,
+ files,
+ setFiles,
+ setFilesLoading,
+ canAttach,
+ entries,
+ anchorRef,
+}: PaletteProps) {
+ const localize = useLocalize();
+ /* Ariakit owns the open state rather than a controlled `open`/`setOpen` pair:
+ with the controlled form, hide-on-interact-outside fired on mousedown and
+ the disclosure's own click re-opened it, so clicking `+` while the palette
+ was up reopened it instead of closing it. */
+ const popover = Ariakit.usePopoverStore({ placement: 'bottom-start' });
+ const open = popover.useState('open');
+ const context = useBadgeRowContext();
+ const mcpManager = context?.mcpServerManager;
+ const configDialogOpen = mcpManager?.getConfigDialogProps()?.isOpen === true;
+ useMCPRefresh({
+ enabled: (open || configDialogOpen) && (mcpManager?.availableMCPServers.length ?? 0) > 0,
+ });
+ useEffect(() => {
+ if (open) {
+ onOpened?.();
+ }
+ }, [open, onOpened]);
+ const mounted = popover.useState('mounted');
+ const [search, setSearch] = useState('');
+ /* Kept across openings rather than reset with the search: someone who uploads
+ to a tool once will do it again, and re-expanding every time is the cost of
+ hiding it. */
+ const [showAllAttach, setShowAllAttach] = useState(false);
+ /* Closing runs in two beats, so the rows below never slide up through a hole
+ where the folded destinations used to be: they fade where they stand, and
+ only once they are gone does the list close over them. */
+ const [collapsing, setCollapsing] = useState(false);
+ /* What the disclosure says it is: the moment it is clicked shut it reads as
+ closed, while the rows it is closing over are still fading out. */
+ const expanded = showAllAttach && !collapsing;
+ /* The row itself, not where it currently sits. A row that moves (starred
+ into favourites, pushed down by a disclosure) keeps the highlight, and the
+ id the combobox points at keeps naming something that exists. */
+ const [activeKey, setActiveKey] = useState('');
+ /* Only a keyboard move scrolls the list. Driving this from the highlight
+ alone let hovering a half-visible row scroll it into view, which moved the
+ rows under a resting pointer. */
+ const [scrollToActive, setScrollToActive] = useState(false);
+ const inputRef = useRef<HTMLInputElement>(null);
+ const listRef = useRef<List>(null);
+ const listBodyRef = useRef<HTMLDivElement>(null);
+ const disclosureRef = useRef<HTMLButtonElement>(null);
+ /** Whether the latest interaction with the palette was a touch or pen press,
+ * or `null` before any. The device's primary pointer cannot answer this: a
+ * tablet with a hardware keyboard stays `(pointer: coarse)` while typing. */
+ const touchInteractionRef = useRef<boolean | null>(null);
+ const recordPointer = useCallback((event: { pointerType?: string }) => {
+ if (typeof event.pointerType === 'string') {
+ touchInteractionRef.current = event.pointerType !== 'mouse';
+ }
+ }, []);
+ const recordKeyboard = useCallback(() => {
+ touchInteractionRef.current = false;
+ }, []);
+ /* Window capture sees every press and key while the palette is up, including
+ the outside press that closes it, whatever event shape Ariakit acts on. */
+ useEffect(() => {
+ if (!mounted) {
+ return;
+ }
+ window.addEventListener('pointerdown', recordPointer, true);
+ window.addEventListener('keydown', recordKeyboard, true);
+ return () => {
+ window.removeEventListener('pointerdown', recordPointer, true);
+ window.removeEventListener('keydown', recordKeyboard, true);
+ };
+ }, [mounted, recordPointer, recordKeyboard]);
+ const liftAtom = useMemo(() => composerLiftFamily(index), [index]);
+ const setLift = useSetAtom(liftAtom);
+ const { ref: popoverRef, height: popupHeight } = useElementSize<HTMLDivElement>();
+ const reducedMotion = useReducedMotion();
+
+ /* Rather than let the popup push the document taller (which puts a scrollbar
+ on a page that had none), the landing screen raises itself by whatever the
+ popup cannot fit, and follows the popup as searching grows and shrinks it.
+
+ The room needed is measured against where the composer sits *unlifted*,
+ captured on opening while the lift is still zero. Measuring it live would
+ read a composer that has already moved out of the way: the overflow would
+ look solved, the page would drop back, and the two would fight. */
+ /* The composer moves under a transform, which is not a layout change and so
+ nothing tells the popup its anchor has shifted. Repositioning it for the
+ length of the lift keeps the two glued together for the whole ride. */
+ const followRef = useRef<number | null>(null);
+ const follow = useCallback(() => {
+ if (followRef.current != null) {
+ cancelAnimationFrame(followRef.current);
+ }
+ const start = performance.now();
+ const step = () => {
+ popover.render();
+ followRef.current = performance.now() - start < LIFT_MS ? requestAnimationFrame(step) : null;
+ };
+ followRef.current = requestAnimationFrame(step);
+ }, [popover]);
+
+ useEffect(
+ () => () => {
+ if (followRef.current != null) {
+ cancelAnimationFrame(followRef.current);
+ }
+ },
+ [],
+ );
+
+ /* The popup stays "mounted" through its leave transition, so a composer
+ unmounted inside that window never reaches the reset below and leaves the
+ landing screen holding a lift with no popup under it. */
+ const appliedLiftRef = useRef(0);
+ const applyLift = useCallback(
+ (nextLift: number) => {
+ appliedLiftRef.current = nextLift;
+ setLift(nextLift);
+ },
+ [setLift],
+ );
+ useEffect(() => () => applyLift(0), [applyLift]);
+ const baselineRef = useRef<number | null>(null);
+ const updateLift = useCallback(() => {
+ if (!mounted) {
+ baselineRef.current = null;
+ applyLift(0);
+ return;
+ }
+ if (baselineRef.current == null) {
+ const anchor = anchorRef.current;
+ if (!anchor) {
+ return;
+ }
+ baselineRef.current = anchor.getBoundingClientRect().bottom;
+ }
+ if (popupHeight === 0) {
+ return;
+ }
+ const needed = popupHeight + POPOVER_GUTTER + VIEWPORT_PADDING;
+ const viewport = window.visualViewport;
+ const viewportBottom =
+ viewport != null ? viewport.offsetTop + viewport.height : window.innerHeight;
+ applyLift(Math.max(0, Math.ceil(needed - (viewportBottom - baselineRef.current))));
+ follow();
+ }, [mounted, popupHeight, applyLift, anchorRef, follow]);
+
+ useLayoutEffect(updateLift, [updateLift]);
+
+ useEffect(() => {
+ if (!mounted) {
+ return;
+ }
+ const viewport = window.visualViewport;
+ const handleLayoutResize = () => {
+ const anchor = anchorRef.current;
+ if (anchor != null) {
+ baselineRef.current = anchor.getBoundingClientRect().bottom + appliedLiftRef.current;
+ }
+ updateLift();
+ };
+ window.addEventListener('resize', handleLayoutResize);
+ viewport?.addEventListener('resize', updateLift);
+ viewport?.addEventListener('scroll', updateLift);
+ return () => {
+ window.removeEventListener('resize', handleLayoutResize);
+ viewport?.removeEventListener('resize', updateLift);
+ viewport?.removeEventListener('scroll', updateLift);
+ };
+ }, [mounted, updateLift, anchorRef]);
+
+ const favorites = useToolFavorites();
+ const query = search.trim().toLowerCase();
+ const recent = useRecentFiles(
+ mounted && canAttach,
+ {
+ files,
+ setFiles,
+ conversation,
+ endpoint,
+ endpointType,
+ endpointFileConfig,
+ },
+ search,
+ );
+ const isUnifiedMode = isUnifiedUploadMode(endpointFileConfig, canAttach);
+ const attach = useAttachItems({
+ agentId,
+ endpoint,
+ endpointType,
+ endpointFileConfig,
+ useResponsesApi,
+ conversationId,
+ conversation,
+ files,
+ setFiles,
+ setFilesLoading,
+ isUnifiedMode,
+ });
+
+ /** One pass over each source: filter by query, split favourites out, then
+ * flatten to the row model the virtualized list renders from. */
+ const rows = useMemo<PaletteRow[]>(() => {
+ /* The disclosure button lives here too, so this component stays mounted for
+ the whole conversation. Deriving the list while the popup is down meant
+ walking the entire catalog on every keystroke in the message box, for
+ rows nobody was looking at. */
+ if (!mounted) {
+ return NO_ROWS;
+ }
+ const favoriteMatches: PaletteEntry[] = [];
+ const buckets: Record<PaletteSection, PaletteEntry[]> = { tool: [], skill: [], mcp: [] };
+
+ for (const entry of entries) {
+ if (query !== '' && scoreEntry(entry.label, entry.description, query) < 0) {
+ continue;
+ }
+ if (entry.favoritable !== false && favorites.keys.has(entry.key)) {
+ favoriteMatches.push(entry);
+ continue;
+ }
+ buckets[entry.section].push(entry);
+ }
+
+ if (query !== '') {
+ const rank = (entry: PaletteEntry) => scoreEntry(entry.label, entry.description, query);
+ const byRank = (a: PaletteEntry, b: PaletteEntry) => rank(a) - rank(b);
+ favoriteMatches.sort(byRank);
+ buckets.tool.sort(byRank);
+ buckets.skill.sort(byRank);
+ buckets.mcp.sort(byRank);
+ }
+
+ const next: PaletteRow[] = [];
+
+ if (favoriteMatches.length > 0) {
+ next.push({
+ type: 'header',
+ key: 'h:favorites',
+ label: localize('com_ui_tools_view_favorites'),
+ });
+ for (const entry of favoriteMatches) {
+ next.push({ type: 'entry', key: entry.key, entry, isFavorite: true });
+ }
+ }
+
+ if (canAttach) {
+ /* Searching reaches every destination: the disclosure is there to keep the
+ resting list short, not to make a row unfindable by name. */
+ const matched =
+ query === ''
+ ? attach.entries.filter((item) => showAllAttach || item.primary === true)
+ : attach.entries.filter((item) => item.label.toLowerCase().includes(query));
+ const folded = query === '' && attach.entries.some((item) => item.primary !== true);
+ if (matched.length > 0 || folded) {
+ next.push({ type: 'header', key: 'h:attach', label: localize('com_ui_composer_attach') });
+ for (const entry of matched) {
+ next.push({ type: 'attach', key: entry.id, entry });
+ }
+ if (folded) {
+ next.push({
+ type: 'more',
+ key: MORE_ROW_KEY,
+ /* The label carries the state rather than `aria-expanded`, which an
+ `option` may not have: the word is what a screen reader reads and
+ what a sighted user sees, so neither has to infer it from the
+ chevron alone. */
+ label: expanded
+ ? localize('com_ui_composer_attach_less')
+ : localize('com_ui_composer_attach_more'),
+ });
+ }
+ }
+ }
+
+ const pushSection = (section: PaletteSection) => {
+ const list = buckets[section];
+ if (list.length === 0) {
+ return;
+ }
+ next.push({
+ type: 'header',
+ key: `h:${section}`,
+ label: localize(SECTION_LABEL[section]),
+ });
+ for (const entry of list) {
+ next.push({ type: 'entry', key: entry.key, entry, isFavorite: false });
+ }
+ };
+
+ pushSection('tool');
+ pushSection('skill');
+ pushSection('mcp');
+
+ if (canAttach && recent.files.length > 0) {
+ next.push({ type: 'header', key: 'h:files', label: localize('com_ui_composer_files') });
+ for (const file of recent.files) {
+ next.push({ type: 'file', key: `file:${file.file_id}`, file });
+ }
+ }
+
+ return next;
+ }, [
+ mounted,
+ entries,
+ favorites.keys,
+ query,
+ attach.entries,
+ showAllAttach,
+ expanded,
+ recent.files,
+ canAttach,
+ localize,
+ ]);
+
+ /** Where every row sits and how tall the list is, in one pass. */
+ const layout = useMemo(() => {
+ const tops = new Map<string, number>();
+ let height = 0;
+ for (const row of rows) {
+ tops.set(row.key, height);
+ height += rowHeight(row);
+ }
+ return { tops, height };
+ }, [rows]);
+
+ /** The row set itself, ignoring anything that changes inside a row. */
+ const signature = useMemo(() => rows.map((row) => row.key).join(KEY_SEP), [rows]);
+
+ /* Rows that gain or lose a neighbour travel to their new offsets, and the
+ rows that caused it fade in where they land. Any change to the row set
+ earns this (a starred entry moving up into favourites, an upload landing
+ in the files section, the attach disclosure folding) except one: a change
+ that came with the query. Under a search the list is being replaced rather
+ than rearranged, and sliding one set of contents into the place of another
+ reads as the list lagging behind the typing.
+
+ Written as a suppression rather than as an opt-in so that the ordinary
+ case needs no signal to reach the move: anything that rearranges the list,
+ from anywhere, is carried by it. */
+ const [settled, setSettled] = useState({ signature, query });
+ const [entering, setEntering] = useState<ReadonlySet<string>>(NO_ENTERING);
+ const [instant, setInstant] = useState(false);
+ if (settled.signature !== signature) {
+ const rearranged = settled.query === query;
+ setSettled({ signature, query });
+ setInstant(!rearranged);
+ if (!rearranged) {
+ setEntering(NO_ENTERING);
+ } else {
+ const before = new Set(settled.signature.split(KEY_SEP));
+ const arrived = new Set<string>();
+ for (const row of rows) {
+ if (!before.has(row.key)) {
+ arrived.add(row.key);
+ }
+ }
+ setEntering(arrived);
+ }
+ }
+
+ /* Held for the one frame the suppressed change is drawn in, so the next
+ rearrangement moves rather than jumps. */
+ useEffect(() => {
+ if (!instant) {
+ return;
+ }
+ const frame = requestAnimationFrame(() => setInstant(false));
+ return () => cancelAnimationFrame(frame);
+ }, [instant]);
+
+ /* Two things happen here, both after the list has already been redrawn.
+
+ The list measures each row once and keeps the offsets, so a row that
+ changes height in place (a two-line entry starred into a section that
+ starts one row higher) is drawn at a stale offset and lands on top of its
+ neighbour. Only the widget holds that cache, so only the widget can drop
+ it.
+
+ Then every row that changed place is sent back to where it was and let go,
+ which is the only way to move these rows that survives what starring one
+ does to the DOM. A row jumping from its section up into favourites makes
+ React re-insert every row it passed, and a re-inserted node loses the
+ transition it was about to run: starring an entry jumped while unstarring
+ the same entry animated. Playing the move after the re-insertion, rather
+ than asking the browser to notice it, is what makes the two symmetric. */
+ const previousTops = useRef(layout.tops);
+ const measuredSignature = useRef(signature);
+ useLayoutEffect(() => {
+ /* Dropping the cache re-walks every offset from the top of the list, so it
+ is worth doing only when the rows themselves changed. */
+ if (measuredSignature.current !== signature) {
+ measuredSignature.current = signature;
+ listRef.current?.recomputeRowHeights(0);
+ }
+ const before = previousTops.current;
+ previousTops.current = layout.tops;
+ const body = listBodyRef.current;
+ /* Where there is no Web Animations API to play the move with, the rows just
+ arrive where they belong, the same as asking for no motion. */
+ if (instant || body == null || typeof body.animate !== 'function' || reducedMotion) {
+ return;
+ }
+ for (const element of body.querySelectorAll<HTMLElement>('[data-row-key]')) {
+ const key = element.dataset.rowKey;
+ const from = key == null ? undefined : before.get(key);
+ const to = key == null ? undefined : layout.tops.get(key);
+ if (from == null || to == null || from === to) {
+ continue;
+ }
+ element.animate([{ transform: `translateY(${from - to}px)` }, { transform: 'none' }], {
+ duration: ROW_SHIFT_MS,
+ easing: ROW_SHIFT_EASING,
+ });
+ }
+ }, [layout, signature, instant, reducedMotion]);
+
+ /** Second beat of the close: the faded rows give up their space. */
+ useEffect(() => {
+ if (!collapsing) {
+ return;
+ }
+ const timer = window.setTimeout(() => {
+ setCollapsing(false);
+ setShowAllAttach(false);
+ }, ROW_FADE_MS);
+ return () => window.clearTimeout(timer);
+ }, [collapsing]);
+
+ const firstSelectable = useMemo(() => rows.findIndex(isSelectable), [rows]);
+
+ /** Where the active row sits now, falling back to the first row that can be
+ * chosen once the query has filtered the old one away. */
+ const activeIndex = useMemo(() => {
+ const found = activeKey === '' ? -1 : rows.findIndex((row) => row.key === activeKey);
+ if (found !== -1) {
+ return found;
+ }
+ return firstSelectable === -1 ? 0 : firstSelectable;
+ }, [activeKey, rows, firstSelectable]);
+
+ const activeRow = rows[activeIndex];
+
+ /* Stable across renders: the list compares this by identity and throws away
+ its whole style cache whenever it changes. */
+ const measureRow = useCallback(
+ ({ index: row }: { index: number }) => rowHeight(rows[row]),
+ [rows],
+ );
+
+ /* Cleared on unmount rather than on close: the popup stays up through its
+ leave animation, so clearing on close emptied the field and repopulated the
+ list in full view of the user. */
+ const [wasMounted, setWasMounted] = useState(false);
+ if (mounted !== wasMounted) {
+ setWasMounted(mounted);
+ if (!mounted) {
+ setSearch('');
+ }
+ }
+
+ const step = useCallback(
+ (direction: 1 | -1) => {
+ if (rows.length === 0) {
+ return;
+ }
+ let next = activeIndex;
+ for (let i = 0; i < rows.length; i++) {
+ next = (next + direction + rows.length) % rows.length;
+ if (isSelectable(rows[next])) {
+ setActiveKey(rows[next].key);
+ setScrollToActive(true);
+ return;
+ }
+ }
+ },
+ [rows, activeIndex],
+ );
+
+ const activate = useCallback(
+ (index: number) => {
+ const row = rows[index];
+ if (!row || row.type === 'header') {
+ return;
+ }
+ if (row.type === 'attach') {
+ popover.hide();
+ row.entry.onSelect();
+ return;
+ }
+ /* Reveals the rest of the section in place, so the palette stays open.
+ The disclosure slides down past the rows it just revealed, so the
+ highlight is asked to follow it rather than snap back to the top. */
+ if (row.type === 'more') {
+ if (showAllAttach) {
+ setCollapsing(true);
+ return;
+ }
+ setShowAllAttach(true);
+ return;
+ }
+ /* Terminal like an upload destination: the file lands in the tray, which
+ the open palette is covering. */
+ if (row.type === 'file') {
+ popover.hide();
+ recent.attach(row.file);
+ return;
+ }
+ /* Every catalog row is a toggle, so the palette stays open and several can
+ be flipped in one visit. Only an attach destination, which hands off to
+ a file picker, dismisses it. */
+ row.entry.onSelect();
+ },
+ [rows, popover, recent, showAllAttach],
+ );
+
+ /**
+ * The popup is portaled but still a React descendant of the composer box, so
+ * a row's click bubbles into the box's own "focus the textarea" handler. On a
+ * row that leaves the palette open (a disclosure, or a catalog toggle meant to
+ * be flipped several times in one visit) that pulls focus off the combobox
+ * mid-visit and can dismiss the popup. Rows that dismiss it themselves are
+ * left alone: handing focus back to the composer is exactly what should
+ * happen there.
+ */
+ const handleRowClick = useCallback(
+ (event: React.MouseEvent, index: number) => {
+ const row = rows[index];
+ if (row != null && row.type !== 'attach' && row.type !== 'file') {
+ event.stopPropagation();
+ }
+ activate(index);
+ },
+ [rows, activate],
+ );
+
+ const toggleFavoriteAt = useCallback(
+ (index: number) => {
+ const row = rows[index];
+ if (!row || row.type !== 'entry' || row.entry.favoritable === false) {
+ return;
+ }
+ favorites.toggleFavorite(row.entry.itemType, row.entry.itemId);
+ },
+ [rows, favorites],
+ );
+
+ const handleKeyDown = useCallback(
+ (e: React.KeyboardEvent<HTMLInputElement>) => {
+ if (e.key === 'ArrowDown') {
+ e.preventDefault();
+ step(1);
+ return;
+ }
+ if (e.key === 'ArrowUp') {
+ e.preventDefault();
+ step(-1);
+ return;
+ }
+ if (e.key === 'Enter') {
+ e.preventDefault();
+ activate(activeIndex);
+ return;
+ }
+ if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'd') {
+ e.preventDefault();
+ toggleFavoriteAt(activeIndex);
+ return;
+ }
+ if (e.key === 'Backspace' && search === '') {
+ popover.hide();
+ return;
+ }
+ if (e.key === 'Escape') {
+ popover.hide();
+ }
+ },
+ [step, activate, activeIndex, toggleFavoriteAt, search, popover],
+ );
+
+ /* Keyed by the row's own identity rather than by the index the list hands
+ out. Under index keys a row that changes place is a box that stays put
+ while its contents are swapped, so nothing about the change is animatable;
+ keyed this way the box follows its row and its offset can be moved to. */
+ /* Bound to the pane here because the renderer's own `index` parameter is the
+ row index. */
+ const paletteRowId = useCallback((key: string) => rowElementId(index, key), [index]);
+ const listId = `composer-palette-list-${index}`;
+ const helpId = `composer-palette-help-${index}`;
+
+ const rowRenderer = useCallback(
+ ({ index, style }: { index: number; style: React.CSSProperties }) => {
+ const row = rows[index];
+ /* A row that had no neighbour to arrive from (a section header the
+ starred entry brought with it, the destinations behind the fold)
+ appears where it lands rather than travelling there. */
+ const arrived = entering.has(row.key);
+ if (row.type === 'header') {
+ return (
+ <div
+ key={row.key}
+ data-row-key={row.key}
+ style={style}
+ role="row"
+ aria-rowindex={index + 1}
+ className={cn('flex', arrived && 'animate-composer-palette-row')}
+ >
+ <div
+ role="columnheader"
+ className="text-text-secondary flex flex-1 items-end px-2 pb-1 text-xs font-medium tracking-wide uppercase"
+ >
+ {row.label}
+ </div>
+ </div>
+ );
+ }
+
+ const isActive = index === activeIndex;
+
+ if (row.type === 'more') {
+ return (
+ <div
+ key={row.key}
+ data-row-key={row.key}
+ style={style}
+ role="row"
+ aria-rowindex={index + 1}
+ onClick={(event) => handleRowClick(event, index)}
+ onMouseEnter={() => {
+ setActiveKey(row.key);
+ setScrollToActive(false);
+ }}
+ className={cn(
+ 'text-text-secondary flex rounded-lg text-sm',
+ isActive && 'bg-surface-hover',
+ arrived && 'animate-composer-palette-row',
+ )}
+ >
+ <div
+ id={paletteRowId(row.key)}
+ role="gridcell"
+ aria-selected={isActive}
+ className="min-w-0 flex-1"
+ >
+ <button
+ type="button"
+ tabIndex={-1}
+ className="flex h-full w-full cursor-pointer items-center gap-2.5 rounded-lg px-2 text-left"
+ >
+ <ChevronDown
+ aria-hidden="true"
+ className={cn('animate-composer-icon size-4 shrink-0', expanded && '-rotate-180')}
+ />
+ <span className="truncate">{row.label}</span>
+ </button>
+ </div>
+ </div>
+ );
+ }
+
+ if (row.type === 'file') {
+ const { file } = row;
+ return (
+ <div
+ key={row.key}
+ data-row-key={row.key}
+ style={style}
+ role="row"
+ aria-rowindex={index + 1}
+ onClick={(event) => handleRowClick(event, index)}
+ onMouseEnter={() => {
+ setActiveKey(row.key);
+ setScrollToActive(false);
+ }}
+ className={cn(
+ 'text-text-secondary flex rounded-lg text-sm',
+ isActive && 'bg-surface-hover',
+ arrived && 'animate-composer-palette-row',
+ )}
+ >
+ <div
+ id={paletteRowId(row.key)}
+ role="gridcell"
+ aria-selected={isActive}
+ className="min-w-0 flex-1"
+ >
+ <button
+ type="button"
+ tabIndex={-1}
+ className="flex h-full w-full cursor-pointer items-center gap-2.5 rounded-lg px-2 text-left"
+ >
+ {/* The wrapper carries the fallback tile color; the image itself
+ hides on error so an unreachable thumbnail (remote storage,
+ expired links) degrades to an empty tile instead of a broken
+ glyph. */}
+ {file.type?.startsWith('image') === true ? (
+ <span
+ aria-hidden="true"
+ className="bg-surface-tertiary size-7 shrink-0 overflow-hidden rounded-md"
+ >
+ {/* Keyed by the path so a virtualized row that is reused for
+ another file gets a fresh image, not one still hidden by
+ the previous file's failed load. */}
+ <img
+ key={file.filepath}
+ src={file.filepath}
+ alt=""
+ className="h-full w-full object-cover"
+ onError={(event) => {
+ event.currentTarget.classList.add('hidden');
+ }}
+ />
+ </span>
+ ) : (
+ <FilePreview
+ file={file}
+ fileType={getFileType(file.type)}
+ className="size-7 rounded-md"
+ />
+ )}
+ <span className="flex min-w-0 flex-1 flex-col justify-center">
+ <span className="truncate">{file.filename}</span>
+ <span className="text-text-secondary truncate text-xs opacity-80">
+ {formatFileDate(file)}
+ </span>
+ </span>
+ </button>
+ </div>
+ </div>
+ );
+ }
+
+ const isEntry = row.type === 'entry';
+ /* The folded destinations are the one departure the list can wait for:
+ the disclosure is closing them itself, rather than reacting to a change
+ that has already happened. */
+ const departing = row.type === 'attach' && row.entry.primary !== true && collapsing;
+ const { label, icon } = row.entry;
+ const description = isEntry ? row.entry.description : undefined;
+ const checked = isEntry ? row.entry.active : false;
+ const favorited = isEntry && row.isFavorite;
+ const canFavorite = isEntry && row.entry.favoritable !== false;
+ const modes = isEntry ? row.entry.modes : undefined;
+
+ return (
+ <div
+ key={row.key}
+ data-row-key={row.key}
+ style={style}
+ role="row"
+ aria-rowindex={index + 1}
+ onClick={(event) => handleRowClick(event, index)}
+ onMouseEnter={() => {
+ setActiveKey(row.key);
+ setScrollToActive(false);
+ }}
+ className={cn(
+ 'group/row relative flex items-stretch gap-1 rounded-lg text-sm',
+ /* On-state reads as a left accent plus full-strength text, rather
+ than a tick competing with the keyboard highlight for meaning. */
+ checked ? 'text-text-primary' : 'text-text-secondary',
+ isActive && 'bg-surface-hover',
+ arrived && !departing && 'animate-composer-palette-row',
+ departing && 'animate-composer-palette-row-out pointer-events-none',
+ )}
+ >
+ <div
+ id={paletteRowId(row.key)}
+ role="gridcell"
+ aria-selected={isActive}
+ className="flex min-w-0 flex-1 items-center"
+ >
+ {checked && (
+ <span
+ aria-hidden="true"
+ className="bg-text-primary absolute inset-y-1 left-0 w-0.5 rounded-full"
+ />
+ )}
+ <button
+ type="button"
+ tabIndex={-1}
+ aria-pressed={isEntry ? checked : undefined}
+ aria-label={
+ favorited ? `${label}, ${localize('com_ui_tools_view_favorites')}` : undefined
+ }
+ className="flex h-full min-w-0 flex-1 cursor-pointer items-center gap-2.5 rounded-lg px-2 text-left"
+ >
+ <span className="shrink-0" aria-hidden="true">
+ {icon}
+ </span>
+ <span className="flex min-w-0 flex-1 flex-col justify-center">
+ <span className={cn('truncate', checked && 'font-medium')}>{label}</span>
+ {description != null && description !== '' && (
+ <span className="text-text-secondary truncate text-xs opacity-80">
+ {description}
+ </span>
+ )}
+ </span>
+ </button>
+ </div>
+ {modes != null && modes.length > 0 && (
+ <div role="gridcell" className="flex shrink-0 items-center gap-1">
+ {modes.map((mode) =>
+ mode.icon != null ? (
+ <span key={mode.id} className={ROW_ACTION_REVEAL}>
+ <IconButton
+ size="xs"
+ shape="square"
+ label={mode.label}
+ className="group"
+ onClick={(event) => {
+ event.stopPropagation();
+ mode.onSelect();
+ }}
+ >
+ <span
+ aria-hidden="true"
+ className="text-text-secondary group-hover:text-text-primary"
+ >
+ {mode.icon}
+ </span>
+ </IconButton>
+ </span>
+ ) : (
+ <button
+ key={mode.id}
+ type="button"
+ aria-pressed={mode.active}
+ onClick={(event) => {
+ event.stopPropagation();
+ mode.onSelect();
+ }}
+ className={cn(
+ 'focus-visible:ring-text-primary min-h-6 shrink-0 rounded-full border px-2 py-0.5 text-xs transition-colors focus-visible:ring-2 focus-visible:outline-hidden',
+ mode.active
+ ? 'bg-surface-active-alt text-text-primary border-transparent'
+ : 'border-border-medium text-text-secondary hover:bg-surface-hover hover:text-text-primary',
+ )}
+ >
+ {mode.label}
+ </button>
+ ),
+ )}
+ </div>
+ )}
+ {canFavorite && (
+ <div role="gridcell" className="flex shrink-0 items-center pr-1">
+ <span className={ROW_ACTION_REVEAL}>
+ <IconButton
+ size="xs"
+ shape="square"
+ label={localize(favorited ? 'com_ui_unfavorite' : 'com_ui_favorite')}
+ aria-pressed={favorited}
+ onClick={(event) => {
+ event.stopPropagation();
+ favorites.toggleFavorite(row.entry.itemType, row.entry.itemId);
+ }}
+ className="group"
+ >
+ <Star
+ className={cn(
+ 'h-4 w-4',
+ favorited
+ ? 'text-accent-primary group-hover:text-accent-primary-hover'
+ : 'text-text-secondary group-hover:text-text-primary',
+ )}
+ fill={favorited ? 'currentColor' : 'none'}
+ aria-hidden="true"
+ />
+ </IconButton>
+ </span>
+ </div>
+ )}
+ </div>
+ );
+ },
+ [
+ rows,
+ activeIndex,
+ handleRowClick,
+ favorites,
+ localize,
+ expanded,
+ entering,
+ collapsing,
+ paletteRowId,
+ ],
+ );
+
+ const disclosureLabel = dictating
+ ? localize('com_ui_cancel')
+ : localize('com_ui_composer_palette');
+
+ return (
+ <>
+ <FileUpload ref={attach.inputRef} handleFileChange={attach.onFileChange}>
+ {/* Opens downward like the thinking popup; Ariakit flips it above on
+ its own once the composer sits too low for it to fit below. */}
+ <Ariakit.PopoverProvider store={popover}>
+ {/* The disclosure is the outer component and the tooltip is what it
+ renders through, not the other way round: passing a
+ `PopoverDisclosure` as `TooltipAnchor`'s `render` swallowed the
+ disclosure's own click handler and the popover never opened.
+ The IconButton renders transparent (`ghost`) by default, so this
+ wrapper's own background is what shows through it for the
+ open/dictating state, rather than restyling the button itself. */}
+ <span
+ className={cn(
+ 'group inline-flex rounded-full',
+ (open || dictating) && 'bg-surface-hover',
+ )}
+ >
+ <Ariakit.PopoverDisclosure
+ ref={disclosureRef}
+ /* The upload-file shortcut clicks this control, resolving it by the
+ `data-testid` below rather than by an `id`: both split panes
+ mount a composer, so a shared `id` is invalid HTML and pins the
+ shortcut to whichever pane comes first in the document. A test id
+ may repeat, which lets the shortcut scope itself to the focused
+ form. */
+ disabled={disabled}
+ aria-label={disclosureLabel}
+ /* Kept as the disclosure while dictating rather than swapped for a
+ plain cancel button: a swap would mount a fresh element already
+ at its final angle, and the turn is the whole point. Ariakit
+ honours `defaultPrevented`, so claiming the click here stops the
+ popover from opening. */
+ onPointerDown={recordPointer}
+ onKeyDown={recordKeyboard}
+ onClick={(event) => {
+ if (!dictating) {
+ return;
+ }
+ event.preventDefault();
+ onCancel?.();
+ }}
+ render={
+ <TooltipAnchor
+ description={disclosureLabel}
+ render={<IconButton label={disclosureLabel} size="md" />}
+ />
+ }
+ data-testid="composer-palette-button"
+ data-upload-shortcut={String(!dictating)}
+ >
+ {/* The same glyph turned a quarter of the way round is the close
+ mark, so the button reads as one control changing state rather
+ than two icons swapping. */}
+ <Plus
+ className={cn(
+ 'animate-composer-icon size-5',
+ open || dictating
+ ? 'text-text-primary rotate-45'
+ : 'text-text-secondary group-hover:text-text-primary',
+ )}
+ aria-hidden="true"
+ />
+ </Ariakit.PopoverDisclosure>
+ </span>
+ <Ariakit.Popover
+ portal
+ portalElement={getMainLandmark}
+ data-chat-pane-portal={index}
+ preserveTabOrder
+ fixed
+ gutter={POPOVER_GUTTER}
+ ref={popoverRef}
+ unmountOnHide
+ initialFocus={inputRef}
+ /* Ariakit otherwise restores focus to the disclosure, leaving the
+ composer inert after Escape, an outside click, or a terminal
+ upload row. Keep a touch close from summoning the on-screen
+ keyboard, but return keyboard users to the message field for
+ every close path through the popover itself. */
+ autoFocusOnHide={false}
+ onClose={() => {
+ window.requestAnimationFrame(() => {
+ /* Reopened within the frame: that session owns the input and
+ the field must not take focus from it. */
+ if (popover.getState().open) {
+ return;
+ }
+ const touch =
+ touchInteractionRef.current ?? window.matchMedia('(pointer: coarse)').matches;
+ /* Each opening answers for itself: a later one opened by the
+ upload shortcut must not inherit this session's input. */
+ touchInteractionRef.current = null;
+ if (touch) {
+ return;
+ }
+ anchorRef.current
+ ?.querySelector<HTMLElement>('[data-testid="text-input"]')
+ ?.focus();
+ });
+ }}
+ /* Without this the trigger could not close the palette: mousedown on
+ * it counts as "outside", so Ariakit hid the popup and the button's
+ * own click immediately re-opened it. */
+ hideOnInteractOutside={(event) =>
+ !disclosureRef.current?.contains(event.target as Node)
+ }
+ /* Anchored to the composer, not the `+` button, so the menu spans
+ the composer's width and sits flush above it. */
+ getAnchorRect={() => anchorRef.current?.getBoundingClientRect() ?? null}
+ aria-label={localize('com_ui_composer_palette')}
+ style={{ width: 'var(--popover-anchor-width)' }}
+ className="animate-composer-popover border-border-light bg-presentation z-50 flex max-w-[95vw] flex-col overflow-hidden rounded-2xl border shadow-lg outline-hidden"
+ >
+ {/* The whole row is the search target, not just the input: the icon
+ and the padding around it read as part of the field, so clicking
+ them has to land in the field too.
+
+ The popup is portaled but still a React descendant of the
+ composer box, so its clicks bubble through the React tree into
+ the box's own "focus the textarea" handler, which would take
+ the focus straight back off the field. */}
+ <div
+ onClick={(event) => {
+ event.stopPropagation();
+ inputRef.current?.focus();
+ }}
+ className="border-border-light flex cursor-text items-center gap-2 border-b px-3 py-2"
+ >
+ <Search className="text-text-secondary h-4 w-4 shrink-0" aria-hidden="true" />
+ <input
+ ref={inputRef}
+ role="combobox"
+ /* The input only exists while the popover is open, and the
+ grid below stays mounted (empty on a dry search), so the
+ widget state cannot contradict what is on screen. */
+ aria-expanded="true"
+ aria-haspopup="grid"
+ autoComplete="off"
+ aria-controls={listId}
+ aria-activedescendant={
+ activeRow != null && isSelectable(activeRow)
+ ? paletteRowId(activeRow.key)
+ : undefined
+ }
+ aria-describedby={helpId}
+ aria-label={localize('com_ui_composer_palette_search')}
+ placeholder={localize('com_ui_composer_palette_search')}
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ onKeyDown={handleKeyDown}
+ data-testid="composer-palette-search"
+ className="text-text-primary placeholder:text-text-secondary focus-visible:ring-text-primary w-full rounded-md border-0 bg-transparent text-sm shadow-none ring-0 focus:border-0 focus:ring-0 focus:outline-hidden focus-visible:ring-2 focus-visible:outline-hidden"
+ />
+ <span id={helpId} className="sr-only">
+ {localize('com_ui_composer_palette_help', { 0: FAVORITE_MODIFIER })}
+ </span>
+ </div>
+ {rows.length === 0 && (
+ /* A search that matches nothing is a state change with nothing
+ to focus, so it has to be said rather than only drawn. A
+ sibling of the grid, not a replacement: the combobox keeps
+ pointing at the empty collection it controls. */
+ <div
+ role="status"
+ aria-live="polite"
+ className="text-text-secondary px-2 py-6 text-center text-sm"
+ >
+ {localize('com_ui_composer_no_results')}
+ </div>
+ )}
+ <div
+ ref={listBodyRef}
+ className={cn(
+ 'composer-palette-rows',
+ rows.length > 0 && 'p-1.5',
+ instant && 'composer-palette-instant',
+ )}
+ >
+ <AutoSizer disableHeight>
+ {({ width }) => (
+ <List
+ ref={listRef}
+ width={width}
+ overscanRowCount={8}
+ rowCount={rows.length}
+ /* The virtualized scroller is the grid itself, so its rows
+ are owned by it directly. A presentational scroller
+ between a wrapper grid and the rows cannot be made
+ transparent: it always renders `aria-label` and
+ `aria-readonly`, which only a grid may carry. */
+ id={listId}
+ role="grid"
+ aria-label={localize('com_ui_composer_palette')}
+ containerRole="rowgroup"
+ /* Only the rows in view are mounted, so the grid states
+ the total and each row its position within it. */
+ containerProps={{ 'aria-rowcount': rows.length }}
+ tabIndex={-1}
+ scrollToIndex={scrollToActive ? activeIndex : undefined}
+ rowRenderer={rowRenderer}
+ rowHeight={measureRow}
+ height={Math.min(layout.height, LIST_MAX_HEIGHT)}
+ className={cn(
+ 'focus:outline-hidden',
+ layout.height > LIST_MAX_HEIGHT && 'composer-palette-scroll',
+ )}
+ />
+ )}
+ </AutoSizer>
+ </div>
+ </Ariakit.Popover>
+ </Ariakit.PopoverProvider>
+ </FileUpload>
+ <SharePointPickerDialog
+ isOpen={attach.isSharePointDialogOpen}
+ onOpenChange={attach.setIsSharePointDialogOpen}
+ onFilesSelected={attach.onSharePointFilesSelected}
+ isDownloading={attach.isProcessing}
+ downloadProgress={attach.downloadProgress}
+ maxSelectionCount={attach.maxSelectionCount}
+ />
+ </>
+ );
+}
+
+export default memo(Palette);
diff --git a/client/src/components/Chat/Input/Composer/Queue.tsx b/client/src/components/Chat/Input/Composer/Queue.tsx
new file mode 100644
index 0000000000..c8903d4dbe
--- /dev/null
+++ b/client/src/components/Chat/Input/Composer/Queue.tsx
@@ -0,0 +1,664 @@
+import { memo, useId, useRef, useMemo, useState, useCallback } from 'react';
+import { useAtomValue } from 'jotai';
+import { useRecoilValue } from 'recoil';
+import { useDrag, useDrop } from 'react-dnd';
+import { X, Pencil, TextQuote, TriangleAlert, GripVertical, Clock } from 'lucide-react';
+import {
+ Button,
+ IconButton,
+ TooltipAnchor,
+ useMediaQuery,
+ useToastContext,
+} from '@librechat/client';
+import type { RestoreToComposer } from '~/Providers/ComposerRestoreContext';
+import type { SteeringControls } from '~/hooks/Chat/useSteering';
+import type { QueuedMessage } from '~/store/families';
+import { escalatingSteerFamily, revealedQueuedTurnFamily } from '~/store/steer';
+import { claimQueuedIntent, releaseQueuedIntent } from '~/utils/queueIntent';
+import EscalateNowButton from '~/components/Chat/Input/EscalateNowButton';
+import { useLocalize } from '~/hooks';
+import { cn } from '~/utils';
+import store from '~/store';
+
+const DRAG_TYPE = 'queued-message';
+
+interface DragItem {
+ id: string;
+ index: number;
+ /** The order the drag started from, so abandoning it puts things back. */
+ order: string[];
+ /** Avoid repeating the same refusal while the pointer remains over a blocked row. */
+ blockedTarget?: number;
+}
+
+interface QueueProps {
+ steering: SteeringControls;
+ conversationId: string;
+ onRestoreToComposer: RestoreToComposer;
+ /** Whether the composer would take this conversation's words right now. */
+ canRestoreToComposer: (conversationId: string) => boolean;
+}
+
+interface QueueRowProps {
+ message: QueuedMessage;
+ index: number;
+ total: number;
+ /** Every queued id in order, captured when a drag starts so abandoning it
+ * can put the queue back the way it was. */
+ order: string[];
+ /** A server-owned row is a durable ordering boundary. */
+ serverOwnedIds: ReadonlySet<string>;
+ steering: SteeringControls;
+ conversationId: string;
+ /** One interrupt at a time: an arm is already unresolved somewhere. */
+ interruptPending: boolean;
+ /** Owned by the rail, so the keys are stated once rather than once per row,
+ * and scoped to THIS rail, so a split view has one hint per pane. */
+ reorderHintId: string;
+ onRestoreToComposer: RestoreToComposer;
+ canRestoreToComposer: (conversationId: string) => boolean;
+ /** The server has revealed this row as the next user turn; only removal remains meaningful. */
+ revealed?: boolean;
+ onAnnounce: (message: string) => void;
+}
+
+function QueuedIcon({ warning, hint }: { warning: boolean; hint?: string }) {
+ if (warning) {
+ return <TriangleAlert className="text-status-warning h-4 w-4 shrink-0" aria-hidden="true" />;
+ }
+ if (!hint) {
+ return <Clock className="text-text-secondary h-4 w-4 shrink-0" aria-hidden="true" />;
+ }
+ return (
+ <TooltipAnchor
+ description={hint}
+ render={
+ <span
+ role="img"
+ aria-label={hint}
+ tabIndex={0}
+ className="focus-visible:ring-text-primary flex shrink-0 cursor-help rounded-full focus-visible:ring-2 focus-visible:outline-hidden"
+ >
+ <Clock className="text-text-secondary h-4 w-4" aria-hidden="true" />
+ </span>
+ }
+ />
+ );
+}
+
+function QueueRow({
+ message,
+ index,
+ total,
+ order,
+ serverOwnedIds,
+ steering,
+ conversationId,
+ interruptPending,
+ reorderHintId,
+ onRestoreToComposer,
+ canRestoreToComposer,
+ onAnnounce,
+ revealed = false,
+}: QueueRowProps) {
+ const localize = useLocalize();
+ const { showToast } = useToastContext();
+ const rowRef = useRef<HTMLDivElement>(null);
+ const gripRef = useRef<HTMLButtonElement>(null);
+ const { reorderQueued, restoreQueuedOrder } = steering;
+ const [actionPending, setActionPending] = useState(false);
+ const isRejected = message.server?.status === 'rejected';
+ const isIndeterminate = message.server?.status === 'indeterminate';
+ const isUnconfirmed =
+ message.server?.status === 'uncertain' && message.server.reconciliationExpired === true;
+ const serverActionable =
+ message.server == null ||
+ isRejected ||
+ (message.server.id != null && message.server.status === 'queued');
+ let statusLabel:
+ | 'com_ui_queued_turn_reconciliation_required'
+ | 'com_ui_steer_delivery_unconfirmed'
+ | 'com_ui_queued_turn_failed' = 'com_ui_queued_turn_failed';
+ if (isIndeterminate) {
+ statusLabel = 'com_ui_queued_turn_reconciliation_required';
+ } else if (isUnconfirmed) {
+ statusLabel = 'com_ui_steer_delivery_unconfirmed';
+ }
+ /* A server-owned row is a durable ordering boundary. Local rows may move
+ only within their contiguous local segment; the client cannot persist a
+ position change across an acknowledged row. */
+ const canMoveTo = useCallback(
+ (sourceIndex: number, target: number, sourceId: string) => {
+ if (target < 0 || target >= total || target === sourceIndex || serverOwnedIds.has(sourceId)) {
+ return false;
+ }
+ const start = Math.min(sourceIndex, target);
+ const end = Math.max(sourceIndex, target);
+ for (let position = start; position <= end; position++) {
+ if (serverOwnedIds.has(order[position])) {
+ return false;
+ }
+ }
+ return true;
+ },
+ [order, serverOwnedIds, total],
+ );
+ const reorderable =
+ message.server == null && order.some((_, target) => canMoveTo(index, target, message.id));
+ /* HTML5 drag needs a hover-capable pointer; on touch it would take the
+ gesture away from scrolling the rail. Arrow keys reorder either way. */
+ const canDrag = useMediaQuery('(hover: hover)');
+ const refuseReorder = useCallback(() => {
+ const message = localize('com_ui_queue_reorder_blocked');
+ showToast({ message, status: 'warning' });
+ onAnnounce(message);
+ }, [localize, onAnnounce, showToast]);
+
+ const [, drop] = useDrop<DragItem>({
+ accept: DRAG_TYPE,
+ hover(item, monitor) {
+ const bounds = rowRef.current?.getBoundingClientRect();
+ const pointer = monitor.getClientOffset();
+ if (item.index === index || bounds == null || pointer == null) {
+ return;
+ }
+ /* Swap on the crossing of the midpoint rather than on entry, so a row
+ * does not flip back and forth under a pointer resting on its edge. */
+ const middle = (bounds.bottom - bounds.top) / 2;
+ const offset = pointer.y - bounds.top;
+ if (item.index < index ? offset < middle : offset > middle) {
+ return;
+ }
+ if (!canMoveTo(item.index, index, item.id)) {
+ if (item.blockedTarget !== index) {
+ refuseReorder();
+ item.blockedTarget = index;
+ }
+ return;
+ }
+ item.blockedTarget = undefined;
+ reorderQueued(item.id, index);
+ item.index = index;
+ },
+ /* Mark releases over the rail as successful after hover has applied the
+ validated reorder; releases outside every row still restore in `end`. */
+ drop: () => ({}),
+ });
+
+ const move = useCallback(
+ (offset: number) => {
+ const target = index + offset;
+ if (target < 0 || target >= total) {
+ return;
+ }
+ if (!canMoveTo(index, target, message.id)) {
+ refuseReorder();
+ return;
+ }
+ reorderQueued(message.id, target);
+ onAnnounce(localize('com_ui_queue_moved', { 0: String(target + 1), 1: String(total) }));
+ /* The row travels with its message, so the handle keeps the focus it
+ * had; the position it reports is what changed. */
+ gripRef.current?.focus();
+ },
+ [canMoveTo, index, total, reorderQueued, message.id, onAnnounce, localize, refuseReorder],
+ );
+
+ const [{ isDragging }, drag] = useDrag({
+ type: DRAG_TYPE,
+ canDrag: reorderable && canDrag,
+ item: (): DragItem => ({ id: message.id, index, order }),
+ collect: (monitor) => ({ isDragging: monitor.isDragging() }),
+ /* The rows are moved as the pointer crosses them, so a drag the user
+ abandons (Escape, or a release outside the rail) has already changed
+ the queue. Dropping nowhere puts the order back. */
+ end: (item, monitor) => {
+ if (!monitor.didDrop()) {
+ restoreQueuedOrder(item.order);
+ }
+ },
+ });
+ /* Edit and Remove both hand this row's words somewhere else across an await
+ (discarding the parked server copy) and only drop the row afterwards. The
+ run-end drain can land inside that gap and send the very message being
+ taken back, so the row is claimed for the whole handoff and the drain skips
+ anything claimed. A second click while one is open is refused rather than
+ racing it. */
+ const handOff = useCallback(
+ async (transfer: () => Promise<boolean>) => {
+ if (!claimQueuedIntent(message.id)) {
+ return;
+ }
+ setActionPending(true);
+ let handedOff = false;
+ try {
+ handedOff = await transfer();
+ } finally {
+ releaseQueuedIntent(message.id);
+ setActionPending(false);
+ /* The row is going back to the queue. A run end that landed while it was
+ claimed found nothing unclaimed to drain and spent its one-shot
+ signal on nothing, so put one back: otherwise these words sit here
+ until some later generation finishes. */
+ if (!handedOff) {
+ steering.rewakeDrain(conversationId);
+ }
+ }
+ },
+ [message.id, steering, conversationId],
+ );
+
+ /* The composer can change while the parked copy is being cancelled, so a
+ refusal after that await would leave the words only in memory, gone on the
+ next reload. Put a row that had a server copy back on the durable queue,
+ in its place, instead of keeping the downgraded local one. */
+ const requeueDurably = useCallback(() => {
+ if (message.server == null) {
+ return;
+ }
+ steering.removeQueued(message.id);
+ steering.enqueue(message.text, {
+ id: message.id,
+ createdAt: message.createdAt,
+ files: message.files,
+ quotes: message.quotes,
+ manualSkills: message.manualSkills,
+ ...(message.reasoningOverride != null && { reasoningOverride: message.reasoningOverride }),
+ ...(message.parentMessageId != null &&
+ message.expectedPredecessorCreatedAt != null && {
+ lineage: {
+ parentMessageId: message.parentMessageId,
+ predecessorCreatedAt: message.expectedPredecessorCreatedAt,
+ },
+ }),
+ skipUsageMark: true,
+ });
+ }, [message, steering]);
+
+ /* Edit and Remove both move the row's words into the composer; they differ
+ only in what the refusal says. */
+ const handToComposer = useCallback(
+ (blockedKey: 'com_ui_queue_edit_blocked' | 'com_ui_queue_remove_blocked') =>
+ handOff(async () => {
+ /* Refuse before the parked copy is given up: once it is discarded the
+ row only lives in memory, and a composer that then refused would
+ leave the words to vanish on the next reload. */
+ if (!canRestoreToComposer(conversationId)) {
+ showToast({ message: localize(blockedKey), status: 'warning' });
+ return false;
+ }
+ const restore = () =>
+ onRestoreToComposer(
+ message.text,
+ message.files,
+ {
+ quotes: message.quotes,
+ manualSkills: message.manualSkills,
+ ...(message.reasoningOverride != null && {
+ reasoningOverride: message.reasoningOverride,
+ }),
+ },
+ conversationId,
+ );
+ /* A recovered row's only durable copy is the steer parked on the
+ server, and nothing can re-create it: its run ended, so there is no
+ live generation to queue behind. The composer takes the words first,
+ and the parked copy is cancelled only once they are there. */
+ if (message.server == null && message.recoverySteerId != null) {
+ if (!restore()) {
+ showToast({ message: localize(blockedKey), status: 'warning' });
+ return false;
+ }
+ if (await steering.discardQueued(message)) {
+ steering.removeQueued(message.id);
+ return true;
+ }
+ /* The words are in the composer and the parked copy survived, so the
+ row stays for the user to settle; the drain must not send it too. */
+ steering.holdQueued(message.id);
+ return false;
+ }
+ /* A server row still has a parked copy; discard it through its durable
+ receipt first, or the edited words would come back as a second
+ message on the next reload. */
+ if (!(await steering.discardQueued(message))) {
+ return false;
+ }
+ /* Dropped only once the words are somewhere else. A paused question
+ owns the composer, and removing the row anyway would leave the
+ message nowhere at all. */
+ if (restore()) {
+ steering.removeQueued(message.id);
+ return true;
+ }
+ /* Refusing silently reads as a dead button: the row stays, nothing
+ moves, and the reason (a draft in the box, another chat on screen)
+ is somewhere the click was not. */
+ requeueDurably();
+ showToast({ message: localize(blockedKey), status: 'warning' });
+ return false;
+ }),
+ [
+ handOff,
+ steering,
+ message,
+ onRestoreToComposer,
+ canRestoreToComposer,
+ requeueDurably,
+ conversationId,
+ showToast,
+ localize,
+ ],
+ );
+
+ const editToComposer = useCallback(
+ () => handToComposer('com_ui_queue_edit_blocked'),
+ [handToComposer],
+ );
+
+ const removeToComposer = useCallback(
+ () => handToComposer('com_ui_queue_remove_blocked'),
+ [handToComposer],
+ );
+
+ drop(rowRef);
+ drag(gripRef);
+
+ const fileCount = message.files?.length ?? 0;
+ const quoteCount = message.quotes?.length ?? 0;
+ /** Any submission-owned non-steerable state (approval pause, answer mode,
+ * Assistants still generating): `sendQueuedNow` has no immediate route and
+ * would no-op. Prefer the flag the hook already exposes over re-deriving it. */
+ /* A recovered item is consumed atomically only when it starts a normal
+ generation. Escalating it would leave or duplicate the parked source. */
+ const isRecovered = message.recoverySteerId != null;
+ const reasoningRequiresNewGeneration =
+ steering.duringRunActive && message.reasoningOverride != null;
+ const sendDisabled =
+ actionPending ||
+ !serverActionable ||
+ reasoningRequiresNewGeneration ||
+ !steering.canSendQueuedNow ||
+ (isRecovered && steering.duringRunActive);
+ /** Shown for the whole run, disabled whenever steering cannot reach it:
+ * an approval pause, or the window before the start POST installs the
+ * generation epoch. Both are states the control must sit out, and hiding it
+ * through them is the discoverability gap this button closes: the pause is
+ * exactly when cutting the reply short is wanted, and the epoch window is
+ * short enough that appearing and vanishing again just reads as a flicker. */
+ const showEscalate = !isRecovered && (steering.pausedOnApproval || steering.duringRunActive);
+
+ return (
+ <div
+ ref={rowRef}
+ role="listitem"
+ data-testid="queued-message-row"
+ className={cn(
+ 'border-border-light flex items-center gap-2 border-b px-3 py-1.5 text-sm last:border-b-0',
+ isDragging && 'opacity-40',
+ )}
+ >
+ <IconButton
+ ref={gripRef}
+ label={localize('com_ui_queue_reorder', {
+ 0: String(index + 1),
+ 1: String(total),
+ })}
+ size="xs"
+ data-testid="queued-message-grip"
+ /* Kept even when there is nowhere to move to, rather than swapped for
+ an icon: a queue that drains to one message would otherwise unmount
+ the handle a keyboard user was holding, dropping focus to the top of
+ the page. */
+ aria-disabled={!reorderable}
+ /* A handle announces what it is but not how to work it, and the keys
+ are the only way through it without a pointer. */
+ aria-describedby={reorderable ? reorderHintId : undefined}
+ onKeyDown={(event) => {
+ if (event.key !== 'ArrowUp' && event.key !== 'ArrowDown') {
+ return;
+ }
+ /* Both keys scroll the rail's container otherwise, which would
+ chase the row the press just moved. */
+ event.preventDefault();
+ move(event.key === 'ArrowUp' ? -1 : 1);
+ }}
+ className={cn(
+ 'group',
+ reorderable ? 'cursor-grab active:cursor-grabbing' : 'cursor-default',
+ canDrag && reorderable && 'touch-none',
+ )}
+ >
+ <GripVertical
+ className={cn(
+ 'text-text-secondary group-hover:text-text-primary h-4 w-4 transition-colors',
+ !reorderable && 'opacity-40',
+ )}
+ aria-hidden="true"
+ />
+ </IconButton>
+ <QueuedIcon
+ warning={isRejected || isUnconfirmed || isIndeterminate}
+ hint={steering.duringRunActive ? localize('com_ui_steer_queued_info') : undefined}
+ />
+ <span className="text-text-primary min-w-0 flex-1 truncate" title={message.text}>
+ {message.text}
+ </span>
+ {quoteCount > 0 && (
+ <span className="text-text-secondary flex shrink-0 items-center gap-0.5 text-xs">
+ <TextQuote className="h-3.5 w-3.5" aria-hidden="true" />
+ <span aria-hidden="true">{quoteCount}</span>
+ <span className="sr-only">
+ {localize('com_ui_queued_quote_count', { 0: String(quoteCount) })}
+ </span>
+ </span>
+ )}
+ {fileCount > 0 && (
+ <span
+ className="text-text-secondary shrink-0 text-xs"
+ title={localize('com_ui_queued_attachment_count', { 0: String(fileCount) })}
+ >
+ <span className="sr-only">
+ {localize('com_ui_queued_attachment_count', { 0: String(fileCount) })}
+ </span>
+ <span aria-hidden="true">
+ {localize(fileCount === 1 ? 'com_ui_attachment_count_one' : 'com_ui_attachment_count', {
+ count: fileCount,
+ })}
+ </span>
+ </span>
+ )}
+ {(isRejected || isUnconfirmed || isIndeterminate) && (
+ <span className="text-status-warning shrink-0 text-xs">{localize(statusLabel)}</span>
+ )}
+ {revealed && (
+ <span className="text-text-secondary shrink-0 text-xs">
+ {localize('com_ui_queued_turn_starting')}
+ </span>
+ )}
+ {!revealed && (
+ <>
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={sendDisabled}
+ aria-disabled={sendDisabled}
+ title={
+ !steering.canSendQueuedNow || reasoningRequiresNewGeneration
+ ? localize('com_ui_send_now_paused')
+ : undefined
+ }
+ onClick={() => steering.sendQueuedNow(message)}
+ className="h-auto shrink-0 disabled:pointer-events-auto disabled:cursor-not-allowed"
+ >
+ <span className="text-text-primary">{localize('com_ui_send_now')}</span>
+ </Button>
+ {showEscalate && (
+ <EscalateNowButton
+ surface="queued"
+ messageText={message.text}
+ disabled={
+ !steering.canSteer ||
+ interruptPending ||
+ actionPending ||
+ reasoningRequiresNewGeneration ||
+ !serverActionable
+ }
+ onClick={() => steering.sendQueuedNow(message, { preempt: true })}
+ />
+ )}
+ <IconButton
+ label={localize('com_ui_edit_message')}
+ size="xs"
+ disabled={actionPending || !serverActionable}
+ onClick={editToComposer}
+ className="group"
+ >
+ <Pencil
+ className="text-text-secondary group-hover:text-text-primary h-4 w-4 transition-colors"
+ aria-hidden="true"
+ />
+ </IconButton>
+ </>
+ )}
+ <IconButton
+ label={localize(
+ isUnconfirmed ? 'com_ui_dismiss_unconfirmed_delivery' : 'com_ui_remove_queued',
+ )}
+ size="xs"
+ disabled={
+ actionPending ||
+ (!serverActionable &&
+ !isUnconfirmed &&
+ !(message.server?.id != null && message.server.status === 'claimed' && revealed))
+ }
+ onClick={isUnconfirmed ? () => steering.removeQueued(message.id) : removeToComposer}
+ className="group"
+ >
+ <X
+ className="text-text-secondary group-hover:text-text-primary h-4 w-4 transition-colors"
+ aria-hidden="true"
+ />
+ </IconButton>
+ </div>
+ );
+}
+
+/**
+ * Messages waiting for the current reply to finish, as a rail tucked behind
+ * the composer's top edge. One row per message, its actions all visible and no
+ * overflow menu: the menu is where the old design hid a global preference
+ * among item actions. That preference ("steering interrupts generation") lives
+ * in Settings now; what stays on the row is only what acts on THAT message.
+ *
+ * The rail is also the running order: whatever sits at the top is what gets
+ * sent when the reply lands, so local rows can be dragged past one another by
+ * the handle, or moved with the arrow keys while it holds focus. Acknowledged
+ * server rows are durable boundaries and cannot be crossed by either control.
+ * Only the drag is pointer-bound, which is why the keys are on the handle
+ * rather than under it.
+ *
+ * Send-now resolves itself: `sendQueuedNow` steers into the live reply when
+ * the run accepts it, or sends right away once nothing is running. While a
+ * run is paused on a pending approval it would only re-queue the message at
+ * the front with no visible effect, so the button disables itself for that
+ * case instead of pretending to act.
+ */
+function Queue({
+ steering,
+ conversationId,
+ onRestoreToComposer,
+ canRestoreToComposer,
+}: QueueProps) {
+ const localize = useLocalize();
+ /* A revealed server turn is already shown in the live thread. Keep its
+ queue receipt visible only long enough to offer safe cancellation. */
+ const revealed = useAtomValue(revealedQueuedTurnFamily(steering.queueKey));
+ /* Per rail, not per module: split view mounts two composers at once, and a
+ shared constant id would duplicate the element and point every handle's
+ `aria-describedby` at whichever copy the document happened to keep. */
+ const reorderHintId = useId();
+ const queued = useRecoilValue(store.queuedMessagesByConvoId(steering.queueKey));
+ const pendingSteers = useRecoilValue(store.pendingSteersByConvoId(conversationId));
+ const escalating = useAtomValue(escalatingSteerFamily(conversationId));
+ /* Only one interrupt can be unresolved at a time: a second arm would seal the
+ same run twice. The escalating flag covers an arm's round trip, before its
+ chip can show `preempt`. */
+ const interruptPending = useMemo(
+ () =>
+ escalating ||
+ pendingSteers.some((steer) => steer.preempt === true && steer.status !== 'failed'),
+ [escalating, pendingSteers],
+ );
+ /* Spoken only for the keys. A drag reorders on every crossing, and a reader
+ narrating each one would be behind the pointer and in the way of it. */
+ const [announcement, setAnnouncement] = useState('');
+ const order = useMemo(() => queued.map((message) => message.id), [queued]);
+ const serverOwnedIds = useMemo(
+ () => new Set(queued.filter((message) => message.server != null).map((message) => message.id)),
+ [queued],
+ );
+
+ /* Cleared when the rail empties or the conversation changes: the region is
+ removed with the rail and re-inserted with its old text still in it, which
+ readers announce on insertion, so an unrelated new message replayed the
+ last move. */
+ const [spokenFor, setSpokenFor] = useState(steering.queueKey);
+ if (spokenFor !== steering.queueKey || (queued.length === 0 && announcement !== '')) {
+ setSpokenFor(steering.queueKey);
+ setAnnouncement('');
+ }
+
+ if (queued.length === 0) {
+ return null;
+ }
+
+ return (
+ /* Inset and only rounded on top: the rail reads as paper tucked behind
+ the composer rather than a second composer stacked on it.
+
+ The rows are the list; the hint and the live region are not items, and a
+ list that owns them reports the wrong count. */
+ <div className="border-border-light bg-surface-secondary mx-3 overflow-hidden rounded-t-2xl border border-b-0">
+ <div
+ role="list"
+ aria-label={localize('com_ui_queued_messages')}
+ data-testid="composer-queue"
+ className="flex flex-col"
+ >
+ {queued.map((message: QueuedMessage, index: number) => (
+ <QueueRow
+ key={message.id}
+ message={message}
+ index={index}
+ total={queued.length}
+ order={order}
+ serverOwnedIds={serverOwnedIds}
+ steering={steering}
+ conversationId={conversationId}
+ interruptPending={interruptPending}
+ reorderHintId={reorderHintId}
+ onRestoreToComposer={onRestoreToComposer}
+ canRestoreToComposer={canRestoreToComposer}
+ revealed={
+ revealed != null &&
+ message.clientRequestId != null &&
+ revealed.clientRequestId === message.clientRequestId
+ }
+ onAnnounce={setAnnouncement}
+ />
+ ))}
+ </div>
+ {queued.length > 1 && (
+ <span id={reorderHintId} className="sr-only">
+ {localize('com_ui_queue_reorder_hint')}
+ </span>
+ )}
+ <span role="status" aria-live="polite" className="sr-only">
+ {announcement}
+ </span>
+ </div>
+ );
+}
+
+export default memo(Queue);
diff --git a/client/src/components/Chat/Input/Composer/Thinking.tsx b/client/src/components/Chat/Input/Composer/Thinking.tsx
new file mode 100644
index 0000000000..b98fbe2f0e
--- /dev/null
+++ b/client/src/components/Chat/Input/Composer/Thinking.tsx
@@ -0,0 +1,243 @@
+import { memo, useRef, useMemo, useState, useLayoutEffect } from 'react';
+import * as Ariakit from '@ariakit/react';
+import { ChevronDown } from 'lucide-react';
+import { TooltipAnchor } from '@librechat/client';
+import type { SettingDefinition, TConversation, TReasoningOverride } from 'librechat-data-provider';
+import { ReasoningControl, useComposerReasoning } from '../Reasoning';
+import Effort, { resolveEffortLabel } from './Effort';
+import { useGetStartupConfig } from '~/data-provider';
+import { useChatContext } from '~/Providers';
+import { cn, getModelSpec } from '~/utils';
+import { useLocalize } from '~/hooks';
+
+interface ThinkingControlProps {
+ index: number;
+ setting: SettingDefinition;
+ conversation: TConversation | null;
+ value?: TReasoningOverride;
+ disabled: boolean;
+ onChange: (value: TReasoningOverride) => void;
+}
+
+function ThinkingControl({
+ index,
+ setting,
+ conversation,
+ value,
+ disabled,
+ onChange,
+}: ThinkingControlProps) {
+ const localize = useLocalize();
+ /* Ariakit owns the open state rather than a controlled `open`/`setOpen` pair:
+ with the controlled form, hide-on-interact-outside fired on mousedown and
+ the disclosure's own click re-opened it, so a second click never closed the
+ popup. */
+ const popover = Ariakit.usePopoverStore({ placement: 'bottom' });
+ const open = popover.useState('open');
+ const disclosureRef = useRef<HTMLButtonElement>(null);
+ const ghostsRef = useRef<HTMLSpanElement>(null);
+ const currentRef = useRef<HTMLSpanElement>(null);
+ const [slotWidth, setSlotWidth] = useState<number>();
+
+ /* The conversation only holds a value once the user touches the control; an
+ admin can still override the setting's default (e.g. reasoning_effort:
+ high), and labelling that state Auto would disagree with what actually
+ runs, and with the Parameters panel. */
+ const raw =
+ value?.key === setting.key
+ ? value.value
+ : (conversation?.[setting.key as keyof TConversation] ?? setting.default);
+ const currentValue = raw == null ? undefined : String(raw);
+ const display =
+ currentValue == null
+ ? localize('com_ui_auto')
+ : resolveEffortLabel(setting, currentValue, localize);
+
+ /* Every label this button can show, in the active language. All of them get
+ measured rather than picking by character count: the longest string is not
+ the widest one in a proportional font, and even less so across languages. */
+ const optionLabels = useMemo(() => {
+ const seen = new Set<string>([localize('com_ui_auto')]);
+ for (const option of setting.options ?? []) {
+ const raw = String(option);
+ seen.add(resolveEffortLabel(setting, raw, localize));
+ }
+ return [...seen];
+ }, [setting, localize]);
+
+ /* Both candidate widths come from out-of-flow ghosts. The visible label is a
+ block that fills the slot, so measuring it just returned the slot's current
+ width and the button never shrank back down.
+ Measured after commit, not during render: a ref read mid-render returns the
+ previous layout, so closing right after a level change animated to the old
+ label's width. */
+ useLayoutEffect(() => {
+ const ghosts = ghostsRef.current;
+ const widest =
+ ghosts != null
+ ? Math.max(0, ...Array.from(ghosts.children, (el) => (el as HTMLElement).offsetWidth))
+ : 0;
+ const measured = open ? widest : (currentRef.current?.offsetWidth ?? 0);
+ if (measured > 0) {
+ setSlotWidth(measured);
+ }
+ }, [open, display, optionLabels]);
+
+ /* Opens downward; Ariakit flips it above on its own once the composer sits
+ low enough in the viewport that there is no room below. */
+ return (
+ <Ariakit.PopoverProvider store={popover}>
+ {/* Named on hover like the mic and send buttons: closed, the trigger shows
+ only the level, which says nothing about what it sets. */}
+ <Ariakit.PopoverDisclosure
+ ref={disclosureRef}
+ data-testid="composer-thinking-button"
+ onClick={(event) => event.stopPropagation()}
+ disabled={disabled}
+ aria-label={localize('com_ui_composer_thinking_value', { 0: display })}
+ render={
+ <TooltipAnchor
+ description={localize('com_ui_composer_thinking')}
+ render={
+ <button
+ type="button"
+ className={cn(
+ 'text-text-primary gap-1 rounded-full px-2.5 text-sm transition-colors',
+ 'hover:bg-surface-hover focus-visible:ring-text-primary focus-visible:ring-2 focus-visible:outline-hidden',
+ open && 'bg-surface-hover',
+ )}
+ />
+ }
+ />
+ }
+ className="flex h-8 shrink-0 items-center"
+ >
+ {/* Closed, the button hugs its label so it takes no more room in the bar
+ than it needs. Open, it widens to the longest label and the text
+ centres, so changing levels while the popup is up never shifts the
+ row. The label itself swaps plainly: a keyed crossfade dipped it to
+ transparent mid-change, which read as a flicker rather than polish. */}
+ <span
+ /* `composer-slot-resize` runs on `animate-composer-popover`'s clock,
+ so the button and the popup resize together. */
+ className="composer-slot-resize relative block overflow-hidden"
+ style={{ width: slotWidth }}
+ >
+ <span
+ ref={ghostsRef}
+ aria-hidden="true"
+ className="pointer-events-none invisible absolute top-0 left-0 w-max"
+ >
+ {optionLabels.map((text) => (
+ <span key={text} className="block whitespace-nowrap">
+ {text}
+ </span>
+ ))}
+ </span>
+ <span
+ ref={currentRef}
+ aria-hidden="true"
+ className="pointer-events-none invisible absolute top-0 left-0 w-max whitespace-nowrap"
+ >
+ {display}
+ </span>
+ {/* Always centred: flipping alignment as the width animated made the
+ label jump sideways mid-transition. Closed the slot is exactly the
+ label's width, so centred and left are identical anyway. */}
+ <span className="block text-center whitespace-nowrap">{display}</span>
+ </span>
+ {/* Turns to point at the popup, which is the only cue that the button
+ and the panel below it are one control. */}
+ <ChevronDown
+ className={cn('animate-composer-icon size-3 shrink-0 opacity-60', open && '-rotate-180')}
+ aria-hidden="true"
+ />
+ </Ariakit.PopoverDisclosure>
+ <Ariakit.Popover
+ portal
+ data-chat-pane-portal={index}
+ gutter={8}
+ unmountOnHide
+ onClick={(event) => event.stopPropagation()}
+ /* Without this the trigger could not close the popup: mousedown on it
+ counts as "outside", so Ariakit hid the popup and the button's own
+ click immediately re-opened it. Excluding the trigger leaves a single
+ clean toggle. */
+ hideOnInteractOutside={(event) => !disclosureRef.current?.contains(event.target as Node)}
+ aria-label={localize('com_ui_composer_thinking_value', { 0: display })}
+ /* `border-light` resolves to the same value as `surface-tertiary`, so
+ the edge was invisible against the popup's own background. */
+ className="animate-composer-popover border-border-medium bg-surface-tertiary z-50 rounded-2xl border shadow-lg outline-hidden"
+ >
+ <Effort setting={setting} conversation={conversation} value={value} onChange={onChange} />
+ </Ariakit.Popover>
+ </Ariakit.PopoverProvider>
+ );
+}
+
+/**
+ * Reasoning effort in the composer footer, the one model parameter worth
+ * reaching for mid-conversation, which otherwise lives three clicks away in the
+ * parameters panel under a different name per provider.
+ *
+ * Model and agent selection deliberately stay in the header; this owns effort
+ * only. Renders nothing at all for models that expose no reasoning parameter,
+ * and nothing when `interface.parameters` is off (the same gate as the
+ * Parameters side panel; model specs default that flag to false).
+ *
+ * Split in two so the control's hooks are never behind that early return.
+ */
+interface ThinkingProps {
+ index: number;
+ disabled: boolean;
+ hasAddedConversation: boolean;
+}
+
+function Thinking({ index, disabled, hasAddedConversation }: ThinkingProps) {
+ const { conversation } = useChatContext();
+ const { data: startupConfig } = useGetStartupConfig();
+ const parametersEnabled = startupConfig?.interface?.parameters;
+ const modelSpec = getModelSpec({ specName: conversation?.spec, startupConfig });
+ const blockedReasoningKeys = useMemo(() => {
+ if (startupConfig?.modelSpecs?.enforce !== true || modelSpec?.preset == null) {
+ return undefined;
+ }
+ return new Set(Object.keys(modelSpec.preset));
+ }, [modelSpec?.preset, startupConfig?.modelSpecs?.enforce]);
+ const reasoning = useComposerReasoning({
+ conversation: conversation ?? null,
+ index,
+ hasAddedConversation,
+ enabled: parametersEnabled,
+ blockedReasoningKeys,
+ });
+
+ if (parametersEnabled !== true || reasoning == null) {
+ return null;
+ }
+
+ if (reasoning.setting.type !== 'enum' || reasoning.setting.options?.length === 0) {
+ return (
+ <ReasoningControl
+ index={index}
+ setting={reasoning.setting}
+ value={reasoning.value}
+ disabled={disabled}
+ onChange={reasoning.setValue}
+ />
+ );
+ }
+
+ return (
+ <ThinkingControl
+ index={index}
+ setting={reasoning.setting}
+ conversation={conversation ?? null}
+ value={reasoning.value}
+ disabled={disabled}
+ onChange={reasoning.setValue}
+ />
+ );
+}
+
+export default memo(Thinking);
diff --git a/client/src/components/Chat/Input/Composer/Tray.tsx b/client/src/components/Chat/Input/Composer/Tray.tsx
new file mode 100644
index 0000000000..a0c71c1423
--- /dev/null
+++ b/client/src/components/Chat/Input/Composer/Tray.tsx
@@ -0,0 +1,159 @@
+import { memo, useCallback, useEffect, useRef } from 'react';
+import { TextQuote, WandSparkles } from 'lucide-react';
+import type { TConversation } from 'librechat-data-provider';
+import type { ComposerItem, ComposerItemKind } from '~/hooks/Input/useComposerItems';
+import type { ExtendedFile, FileSetter } from '~/common';
+import { useFileHandlingNoChatContext, useLocalize } from '~/hooks';
+import FileRow from '../Files/FileRow';
+import Chip from './Chip';
+
+const KIND_ICON: Record<ComposerItemKind, JSX.Element> = {
+ quote: <TextQuote className="h-4 w-4" aria-hidden="true" />,
+ skill: <WandSparkles className="h-4 w-4" aria-hidden="true" />,
+};
+
+const KIND_REMOVE_KEY = {
+ quote: 'com_ui_remove_quote',
+ skill: 'com_ui_remove_skill',
+} as const;
+
+interface ItemChipProps {
+ item: ComposerItem;
+ onRemove: () => void;
+}
+
+function ItemChip({ item, onRemove }: ItemChipProps) {
+ const localize = useLocalize();
+
+ return (
+ <Chip
+ label={item.label}
+ title={item.title}
+ icon={KIND_ICON[item.kind]}
+ onRemove={onRemove}
+ removeLabel={localize(KIND_REMOVE_KEY[item.kind])}
+ data-testid={`composer-chip-${item.kind}`}
+ />
+ );
+}
+
+interface TrayProps {
+ items: ComposerItem[];
+ conversation: TConversation | null;
+ /** Staged uploads, rendered by `FileRow` with their own delete semantics. */
+ files: Map<string, ExtendedFile>;
+ setFiles: FileSetter;
+ setFilesLoading: React.Dispatch<React.SetStateAction<boolean>>;
+ isRTL: boolean;
+ index: number;
+ isPastedTextFile: (file: ExtendedFile) => boolean;
+ isPasteActionPending: (file: ExtendedFile) => boolean;
+ onEditPastedText: (file: ExtendedFile) => void;
+ onMovePastedTextInline: (file: ExtendedFile) => void;
+ /** Guarded focus restore after the last staged quote is dismissed. */
+ focusComposer?: () => void;
+}
+
+/**
+ * The composer's staged-context region: file cards first, then the quote and
+ * manual-skill pills. Queued and failed-steer rows live elsewhere (the Queue
+ * rail and the thread, respectively).
+ *
+ * Files keep `FileRow` rather than being flattened into pills: the card is
+ * where an image preview opens full size, where upload progress and the storage
+ * source are drawn, and where aborting a part-done upload differs from deleting
+ * a finished one.
+ */
+function Tray({
+ items,
+ conversation,
+ files,
+ setFiles,
+ setFilesLoading,
+ isRTL,
+ index,
+ isPastedTextFile,
+ isPasteActionPending,
+ onEditPastedText,
+ onMovePastedTextInline,
+ focusComposer,
+}: TrayProps) {
+ const localize = useLocalize();
+ const quoteFocusIndexRef = useRef<number | null>(null);
+ const chipListRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ const index = quoteFocusIndexRef.current;
+ if (index == null) {
+ return;
+ }
+ quoteFocusIndexRef.current = null;
+ const buttons = chipListRef.current?.querySelectorAll<HTMLButtonElement>(
+ '[data-testid="composer-chip-quote"] button',
+ );
+ if (buttons?.length) {
+ buttons[Math.min(index, buttons.length - 1)].focus();
+ }
+ }, [items]);
+
+ const removeItem = useCallback(
+ (item: ComposerItem) => {
+ if (item.kind !== 'quote') {
+ item.remove();
+ return;
+ }
+ const quoteItems = items.filter((candidate) => candidate.kind === 'quote');
+ const quoteIndex = quoteItems.findIndex((candidate) => candidate.id === item.id);
+ item.remove();
+ /* Every quote is its own chip, so focus moves to a remaining quote's remove
+ control and only returns to the composer once the last one is gone. */
+ if (quoteItems.length <= 1) {
+ focusComposer?.();
+ return;
+ }
+ quoteFocusIndexRef.current = quoteIndex;
+ },
+ [items, focusComposer],
+ );
+ const { abortUpload } = useFileHandlingNoChatContext(undefined, {
+ files,
+ setFiles,
+ setFilesLoading,
+ conversation,
+ });
+
+ if (items.length === 0 && files.size === 0) {
+ return null;
+ }
+
+ return (
+ <div data-testid="composer-tray" className="flex flex-col gap-1.5 px-2 pt-2">
+ <FileRow
+ files={files}
+ setFiles={setFiles}
+ isRTL={isRTL}
+ abortUpload={abortUpload}
+ setFilesLoading={setFilesLoading}
+ index={index}
+ isPastedTextFile={isPastedTextFile}
+ isPasteActionPending={isPasteActionPending}
+ onEditPastedText={onEditPastedText}
+ onMovePastedTextInline={onMovePastedTextInline}
+ />
+ {items.length > 0 && (
+ <div
+ ref={chipListRef}
+ role="list"
+ aria-label={localize('com_ui_composer_staged_context')}
+ className="flex flex-wrap gap-1.5"
+ >
+ {items.map((item) => (
+ <ItemChip key={item.id} item={item} onRemove={() => removeItem(item)} />
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
+
+export default memo(Tray);
diff --git a/client/src/components/Chat/Input/Composer/Waveform.tsx b/client/src/components/Chat/Input/Composer/Waveform.tsx
new file mode 100644
index 0000000000..ca20f732e0
--- /dev/null
+++ b/client/src/components/Chat/Input/Composer/Waveform.tsx
@@ -0,0 +1,40 @@
+import { memo } from 'react';
+import useAudioLevels from '~/hooks/Input/useAudioLevels';
+import { cn } from '~/utils';
+
+/** Bars never collapse to nothing, so silence still reads as a live line. */
+const MIN_BAR = 0.1;
+
+interface WaveformProps {
+ /** Whether the microphone is running; the levels are sampled from here. */
+ active: boolean;
+ className?: string;
+}
+
+/**
+ * Live microphone trace. Spreads a fixed bar count across whatever width it is
+ * given, so it fills its container rather than overflowing and being clipped.
+ *
+ * Samples the microphone itself rather than being handed the levels: at ~18
+ * samples a second, holding them any higher up re-rendered the whole composer,
+ * and every tool and skill row with it, to move these bars.
+ */
+function Waveform({ active, className }: WaveformProps) {
+ const levels = useAudioLevels(active);
+ return (
+ <div
+ aria-hidden="true"
+ className={cn('flex w-full items-center justify-between overflow-hidden', className)}
+ >
+ {levels.map((level, index) => (
+ <span
+ key={index}
+ style={{ height: `${Math.max(MIN_BAR, level) * 100}%` }}
+ className="bg-text-primary w-[3px] shrink-0 rounded-full opacity-70 transition-all duration-100 ease-out motion-reduce:transition-none"
+ />
+ ))}
+ </div>
+ );
+}
+
+export default memo(Waveform);
diff --git a/client/src/components/Chat/Input/Composer/__tests__/Bar.interactions.spec.tsx b/client/src/components/Chat/Input/Composer/__tests__/Bar.interactions.spec.tsx
new file mode 100644
index 0000000000..e61c2c5403
--- /dev/null
+++ b/client/src/components/Chat/Input/Composer/__tests__/Bar.interactions.spec.tsx
@@ -0,0 +1,28 @@
+import React from 'react';
+import userEvent from '@testing-library/user-event';
+import { render, screen } from '@testing-library/react';
+import { ChipModes } from '../Bar';
+
+jest.mock('~/hooks', () => ({
+ useLocalize: () => (key: string) => key,
+}));
+
+describe('ChipModes', () => {
+ it('keeps a portaled menu choice from reaching the composer', async () => {
+ const user = userEvent.setup();
+ const onComposerClick = jest.fn();
+ const onSelect = jest.fn();
+ render(
+ <div onClick={onComposerClick}>
+ <ChipModes modes={[{ id: 'high', label: 'High', active: false, onSelect }]} />
+ </div>,
+ );
+
+ await user.click(screen.getByRole('button', { name: 'com_ui_mode' }));
+ onComposerClick.mockClear();
+ await user.click(screen.getByRole('menuitemradio', { name: 'High' }));
+
+ expect(onSelect).toHaveBeenCalledTimes(1);
+ expect(onComposerClick).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/components/Chat/Input/Composer/__tests__/Bar.spec.ts b/client/src/components/Chat/Input/Composer/__tests__/Bar.spec.ts
new file mode 100644
index 0000000000..728e5fc2ff
--- /dev/null
+++ b/client/src/components/Chat/Input/Composer/__tests__/Bar.spec.ts
@@ -0,0 +1,165 @@
+import type { PaletteEntry } from '~/hooks/Input/usePaletteEntries';
+import {
+ PINNED_MCP_KEY,
+ chipMenuModes,
+ chipsFitInline,
+ formatElapsed,
+ projectBarEntries,
+} from '../Bar';
+
+/** Pure decisions behind the bar's tool projection, layout and elapsed time. */
+
+const chip = (key: string) => ({ key });
+const entry = (key: string, overrides: Partial<PaletteEntry> = {}): PaletteEntry => ({
+ key,
+ itemType: 'builtin',
+ itemId: key,
+ label: key,
+ icon: null,
+ section: 'tool',
+ active: false,
+ pinned: false,
+ onSelect: jest.fn(),
+ ...overrides,
+});
+
+describe('projectBarEntries', () => {
+ it('keeps active and pinned tools but excludes staged skills', () => {
+ const active = entry('active', { active: true });
+ const pinned = entry('pinned', { pinned: true });
+ const inactive = entry('inactive');
+ const skill = entry('skill', { section: 'skill', active: true, pinned: true });
+
+ expect(projectBarEntries([active, pinned, inactive, skill])).toEqual([active, pinned]);
+ });
+
+ it('keeps a pinned MCP menu alongside selected server chips', () => {
+ const github = entry('mcp:github', {
+ itemType: 'mcp',
+ itemId: 'github',
+ section: 'mcp',
+ });
+ const pinnedMcp = entry(PINNED_MCP_KEY, {
+ itemType: 'mcp',
+ itemId: 'mcp',
+ section: 'mcp',
+ active: true,
+ pinned: true,
+ });
+
+ const projected = projectBarEntries([github], pinnedMcp);
+ expect(projected).toHaveLength(1);
+ expect(projected[0]).toEqual(
+ expect.objectContaining({
+ key: PINNED_MCP_KEY,
+ modes: [expect.objectContaining({ id: 'github', label: 'mcp:github', active: false })],
+ }),
+ );
+
+ const selected = { ...github, active: true };
+ const selectedProjection = projectBarEntries([selected], pinnedMcp);
+ expect(selectedProjection).toHaveLength(2);
+ expect(selectedProjection[0]).toBe(selected);
+ expect(selectedProjection[1]).toEqual(
+ expect.objectContaining({
+ key: PINNED_MCP_KEY,
+ modes: [expect.objectContaining({ id: 'github', active: true })],
+ }),
+ );
+ });
+
+ /* Chip keys are React keys and packing-width slots: two entries sharing one
+ would let a chip or its menu be measured as the other. A server may be
+ named anything, including the word the aggregate pin used to key on. */
+ it('keeps the aggregate MCP chip distinct from a server named pinned', () => {
+ const server = entry('mcp:pinned', {
+ itemType: 'mcp',
+ itemId: 'pinned',
+ section: 'mcp',
+ active: true,
+ });
+ const aggregate = entry(PINNED_MCP_KEY, {
+ itemType: 'mcp',
+ itemId: 'mcp',
+ section: 'mcp',
+ active: true,
+ pinned: true,
+ });
+
+ const projected = projectBarEntries([server], aggregate);
+ const keys = projected.map((projectedEntry) => projectedEntry.key);
+
+ expect(keys).toEqual(['mcp:pinned', PINNED_MCP_KEY]);
+ expect(new Set(keys).size).toBe(keys.length);
+ });
+});
+
+describe('chipMenuModes', () => {
+ it('keeps named sub-modes and drops icon-only actions', () => {
+ expect(
+ chipMenuModes([
+ { id: 'configure', label: 'Configure', active: false, icon: 'gear', onSelect: jest.fn() },
+ { id: 'default', label: 'Default', active: true, onSelect: jest.fn() },
+ ]),
+ ).toEqual([expect.objectContaining({ id: 'default' })]);
+ });
+
+ it('returns nothing when every mode is an icon action', () => {
+ expect(
+ chipMenuModes([
+ { id: 'configure', label: 'Configure', active: false, icon: 'gear', onSelect: jest.fn() },
+ ]),
+ ).toEqual([]);
+ });
+});
+
+describe('chipsFitInline', () => {
+ const widths = { a: 40, b: 60, c: 100 };
+
+ it('keeps an empty row inline, whatever the room', () => {
+ expect(chipsFitInline([], widths, 0)).toBe(true);
+ expect(chipsFitInline([], widths, 500)).toBe(true);
+ });
+
+ it('gives chips a row of their own once there is no room at all', () => {
+ expect(chipsFitInline([chip('a')], widths, 0)).toBe(false);
+ expect(chipsFitInline([chip('a')], widths, -10)).toBe(false);
+ });
+
+ /* On the first pass nothing has been measured, and guessing would move the
+ chips twice: once on the guess and again on the measurement. */
+ it('keeps everything inline until anything has been measured', () => {
+ expect(chipsFitInline([chip('a'), chip('b')], {}, 10)).toBe(true);
+ });
+
+ /* Once the measured ones already overflow, the answer is known without the
+ rest: the row cannot hold them whatever the unmeasured chip turns out to be. */
+ it('wraps as soon as the measured chips alone do not fit', () => {
+ expect(chipsFitInline([chip('c'), chip('unmeasured')], widths, 50)).toBe(false);
+ });
+
+ it('counts the gap between chips, not just the chips', () => {
+ /* 40 + 60 alone would fit exactly; the gap between them is what does not. */
+ expect(chipsFitInline([chip('a'), chip('b')], widths, 100)).toBe(false);
+ expect(chipsFitInline([chip('a'), chip('b')], widths, 108)).toBe(true);
+ });
+
+ it('takes a row that fills the space exactly', () => {
+ expect(chipsFitInline([chip('c')], widths, 100)).toBe(true);
+ expect(chipsFitInline([chip('c')], widths, 99)).toBe(false);
+ });
+});
+
+describe('formatElapsed', () => {
+ it.each([
+ [0, '0:00'],
+ [5, '0:05'],
+ [59, '0:59'],
+ [60, '1:00'],
+ [61, '1:01'],
+ [600, '10:00'],
+ [3599, '59:59'],
+ ])('reads %i seconds as %s', (seconds, expected) => {
+ expect(formatElapsed(seconds)).toBe(expected);
+ });
+});
diff --git a/client/src/components/Chat/Input/Composer/__tests__/Palette.spec.tsx b/client/src/components/Chat/Input/Composer/__tests__/Palette.spec.tsx
new file mode 100644
index 0000000000..f429cb35fc
--- /dev/null
+++ b/client/src/components/Chat/Input/Composer/__tests__/Palette.spec.tsx
@@ -0,0 +1,810 @@
+import React from 'react';
+import { RecoilRoot } from 'recoil';
+import { getDefaultStore } from 'jotai';
+import userEvent from '@testing-library/user-event';
+import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';
+import type { TConversation } from 'librechat-data-provider';
+import type { PaletteEntry } from '~/hooks/Input/usePaletteEntries';
+import type { AttachEntry } from '~/hooks/Input/useAttachItems';
+import { composerLiftFamily } from '../state';
+import Palette from '../Palette';
+
+/**
+ * The palette's row model: what the list is made of, in what order, and what a
+ * search does to it. The list is virtualized and the motion is measured in a
+ * browser, so this covers the part that decides rows rather than draws them.
+ */
+
+/* AutoSizer measures its parent, which is zero in jsdom, and a zero width
+ renders no rows at all. */
+jest.mock('react-virtualized', () => {
+ const actual = jest.requireActual('react-virtualized');
+ return {
+ ...actual,
+ AutoSizer: ({ children }: { children: (size: { width: number }) => React.ReactNode }) =>
+ children({ width: 640 }),
+ };
+});
+
+jest.mock('~/hooks/Generic/useElementSize', () => ({
+ __esModule: true,
+ default: () => ({ ref: { current: null }, height: mockPopupHeight, width: 0 }),
+}));
+
+jest.mock('~/components/SharePoint', () => ({ SharePointPickerDialog: () => null }));
+
+const mockToggleFavorite = jest.fn();
+jest.mock('~/hooks/Input/useToolFavorites', () => ({
+ __esModule: true,
+ default: () => ({
+ keys: new Set(mockFavoriteKeys),
+ toggleFavorite: mockToggleFavorite,
+ isFavorite: (key: string) => mockFavoriteKeys.includes(key),
+ }),
+}));
+
+jest.mock('~/hooks/Input/useRecentFiles', () => ({
+ __esModule: true,
+ default: () => ({ files: mockRecentFiles, attach: jest.fn() }),
+}));
+
+jest.mock('~/hooks/Input/useAttachItems', () => ({
+ __esModule: true,
+ default: () => ({
+ entries: mockAttachEntries,
+ inputRef: { current: null },
+ onFileChange: jest.fn(),
+ isSharePointDialogOpen: false,
+ setIsSharePointDialogOpen: jest.fn(),
+ onSharePointFilesSelected: jest.fn(),
+ isProcessing: false,
+ downloadProgress: undefined,
+ maxSelectionCount: 10,
+ }),
+}));
+jest.mock('~/hooks/MCP/useMCPRefresh', () => {
+ const useMCPRefresh = jest.fn();
+ return { useMCPRefresh };
+});
+const mcpRefreshModule = jest.requireMock('~/hooks/MCP/useMCPRefresh') as {
+ useMCPRefresh: jest.Mock;
+};
+const mockMCPRefresh = mcpRefreshModule.useMCPRefresh;
+
+jest.mock('~/Providers', () => ({
+ useBadgeRowContext: () => ({
+ mcpServerManager: {
+ availableMCPServers: [{ serverName: 'github' }],
+ getConfigDialogProps: () => ({ isOpen: false }),
+ },
+ }),
+}));
+
+jest.mock('~/hooks', () => ({
+ useLocalize: () => (key: string, options?: Record<string, string | number>) =>
+ options ? `${key}:${options['0'] ?? options.count}` : key,
+}));
+
+let mockFavoriteKeys: string[] = [];
+let mockRecentFiles: Array<Record<string, unknown>> = [];
+let mockAttachEntries: AttachEntry[] = [];
+let mockPopupHeight = 0;
+const defaultInnerHeight = window.innerHeight;
+let portalMain: HTMLElement;
+
+const attachEntry = (id: string, label: string, primary = false): AttachEntry => ({
+ id,
+ label,
+ primary,
+ icon: null,
+ onSelect: jest.fn(),
+});
+
+const entry = (over: Partial<PaletteEntry> & Pick<PaletteEntry, 'key'>): PaletteEntry => ({
+ itemType: 'tool',
+ itemId: over.key,
+ label: over.key,
+ icon: null,
+ section: 'tool',
+ active: false,
+ pinned: false,
+ onSelect: jest.fn(),
+ ...over,
+});
+
+const ENTRIES: PaletteEntry[] = [
+ entry({ key: 'web_search', label: 'Web Search', section: 'tool' }),
+ entry({ key: 'execute_code', label: 'Run Code', section: 'tool' }),
+ entry({ key: 'skill:writer', label: 'writing-helper', section: 'skill', description: 'Drafts' }),
+ entry({ key: 'mcp:github', label: 'Github', section: 'mcp' }),
+];
+
+const ATTACH: AttachEntry[] = [
+ attachEntry('local:provider', 'Upload to Provider', true),
+ attachEntry('local:context', 'Upload as Text'),
+ attachEntry('local:file_search', 'Upload for File Search'),
+ attachEntry('local:execute_code', 'Upload to Code Environment'),
+];
+
+function renderPalette(
+ over: {
+ canAttach?: boolean;
+ entries?: PaletteEntry[];
+ onContainerClick?: () => void;
+ dictating?: boolean;
+ onCancel?: () => void;
+ anchorBottom?: number | (() => number);
+ anchor?: HTMLElement;
+ } = {},
+) {
+ const anchorRef = { current: over.anchor ?? document.createElement('div') };
+ if (over.anchorBottom != null) {
+ jest.spyOn(anchorRef.current, 'getBoundingClientRect').mockImplementation(
+ () =>
+ ({
+ bottom: typeof over.anchorBottom === 'function' ? over.anchorBottom() : over.anchorBottom,
+ }) as DOMRect,
+ );
+ }
+ const liftStore = getDefaultStore();
+ liftStore.set(composerLiftFamily(0), 0);
+ const view = render(
+ <RecoilRoot>
+ {/* Stands in for the composer box, whose own click handler focuses the
+ textarea. The popup is portaled but still a React descendant of it, so
+ this is the handler a row's click bubbles into. */}
+ <div onClick={over.onContainerClick}>
+ <Palette
+ index={0}
+ conversationId="convo-1"
+ conversation={{ conversationId: 'convo-1' } as TConversation}
+ files={new Map()}
+ setFiles={jest.fn()}
+ setFilesLoading={jest.fn()}
+ canAttach={over.canAttach ?? true}
+ entries={over.entries ?? ENTRIES}
+ dictating={over.dictating}
+ onCancel={over.onCancel}
+ anchorRef={anchorRef as React.RefObject<HTMLElement>}
+ />
+ </div>
+ </RecoilRoot>,
+ );
+ fireEvent.click(screen.getByTestId('composer-palette-button'));
+ return { ...view, liftStore };
+}
+
+/** Row labels in list order, headers included, as the user reads them. The
+ * list's own containers are presentational too, so rows are found by the
+ * identity attribute rather than by role alone. */
+const rows = () =>
+ Array.from(document.querySelectorAll('[id^="composer-palette-list"] [data-row-key]')).map(
+ (row) => row.textContent?.trim() ?? '',
+ );
+
+/** Just the section headers, which is what carries the order. */
+const headers = () =>
+ Array.from(
+ document.querySelectorAll<HTMLElement>('[id^="composer-palette-list"] [data-row-key^="h:"]'),
+ ).map((row) => row.textContent?.trim() ?? '');
+
+/** Row identities in list order, which is what the model actually decides. */
+const keys = () =>
+ Array.from(
+ document.querySelectorAll<HTMLElement>('[id^="composer-palette-list"] [data-row-key]'),
+ ).map((row) => row.dataset.rowKey ?? '');
+
+const search = (text: string) => {
+ const input = screen.getByTestId('composer-palette-search');
+ fireEvent.change(input, { target: { value: text } });
+};
+
+describe('Palette', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ mockFavoriteKeys = [];
+ mockRecentFiles = [];
+ mockAttachEntries = ATTACH;
+
+ mockPopupHeight = 0;
+ Object.defineProperty(window, 'visualViewport', {
+ configurable: true,
+ value: undefined,
+ });
+ Object.defineProperty(window, 'innerHeight', {
+ configurable: true,
+ writable: true,
+ value: defaultInnerHeight,
+ });
+ portalMain = document.createElement('main');
+ document.body.append(portalMain);
+ });
+ it('refreshes MCP state while the palette is open', () => {
+ renderPalette();
+ expect(mockMCPRefresh).toHaveBeenLastCalledWith({ enabled: true });
+ });
+
+ afterEach(() => {
+ portalMain.remove();
+ jest.restoreAllMocks();
+ });
+
+ it('recalculates the landing lift when the visual viewport changes', () => {
+ jest.spyOn(window, 'requestAnimationFrame').mockReturnValue(0);
+ mockPopupHeight = 100;
+ let viewportHeight = 700;
+ const resizeListeners: EventListener[] = [];
+ const viewport = {
+ addEventListener: jest.fn((type: string, listener: EventListener) => {
+ if (type === 'resize') {
+ resizeListeners.push(listener);
+ }
+ }),
+ removeEventListener: jest.fn(),
+ };
+ Object.defineProperties(viewport, {
+ height: { get: () => viewportHeight },
+ offsetTop: { value: 0 },
+ });
+ Object.defineProperty(window, 'visualViewport', {
+ configurable: true,
+ value: viewport,
+ });
+ const { liftStore } = renderPalette({ anchorBottom: 650 });
+ expect(liftStore.get(composerLiftFamily(0))).toBe(70);
+
+ viewportHeight = 600;
+ const updateLift = resizeListeners[0];
+ expect(updateLift).toBeDefined();
+ act(() => updateLift?.(new Event('resize')));
+
+ expect(liftStore.get(composerLiftFamily(0))).toBe(170);
+ });
+
+ it('rebases the lift when the window layout moves the composer', () => {
+ jest.spyOn(window, 'requestAnimationFrame').mockReturnValue(0);
+ const resizeListeners: EventListener[] = [];
+ const addEventListener = window.addEventListener.bind(window);
+ jest.spyOn(window, 'addEventListener').mockImplementation((type, listener, options) => {
+ if (type === 'resize' && typeof listener === 'function') {
+ resizeListeners.push(listener);
+ }
+ addEventListener(type, listener, options);
+ });
+ mockPopupHeight = 100;
+ let anchorBottom = 650;
+ Object.defineProperty(window, 'innerHeight', {
+ configurable: true,
+ writable: true,
+ value: 700,
+ });
+ const { liftStore } = renderPalette({ anchorBottom: () => anchorBottom });
+ expect(liftStore.get(composerLiftFamily(0))).toBe(70);
+
+ anchorBottom = 600;
+ const handleLayoutResize = resizeListeners.find((listener) =>
+ listener.toString().includes('baselineRef'),
+ );
+ expect(handleLayoutResize).toBeDefined();
+ act(() => handleLayoutResize?.(new Event('resize')));
+
+ expect(liftStore.get(composerLiftFamily(0))).toBe(90);
+ });
+
+ it('does not advertise its cancel state as the upload shortcut target', () => {
+ const onCancel = jest.fn();
+ renderPalette({ dictating: true, onCancel });
+
+ expect(screen.getByTestId('composer-palette-button')).toHaveAttribute(
+ 'data-upload-shortcut',
+ 'false',
+ );
+ expect(onCancel).toHaveBeenCalledTimes(1);
+ });
+
+ it('marks its portal with the owning chat pane', async () => {
+ renderPalette();
+ await waitFor(() =>
+ expect(document.querySelector('[data-chat-pane-portal]')).toHaveAttribute(
+ 'data-chat-pane-portal',
+ '0',
+ ),
+ );
+ });
+
+ describe('section order', () => {
+ it('reads attach, tools, skills, servers, files', () => {
+ mockRecentFiles = [{ file_id: 'f1', filename: 'notes.pdf', type: 'application/pdf' }];
+ renderPalette();
+ expect(headers()).toEqual([
+ 'com_ui_composer_attach',
+ 'com_ui_composer_tools',
+ 'com_ui_skills',
+ 'com_ui_composer_mcp',
+ 'com_ui_composer_files',
+ ]);
+ });
+
+ it('puts favourites above everything, out of their own sections', () => {
+ mockFavoriteKeys = ['mcp:github'];
+ renderPalette();
+ const listed = rows();
+ expect(listed[0]).toBe('com_ui_tools_view_favorites');
+ expect(listed[1]).toBe('Github');
+ /* And not left behind in the section it came from. */
+ expect(listed.filter((row) => row === 'Github')).toHaveLength(1);
+ });
+
+ it('drops a section whose only member was starred', () => {
+ mockFavoriteKeys = ['mcp:github'];
+ renderPalette();
+ expect(rows()).not.toContain('com_ui_composer_mcp');
+ });
+
+ it('offers no upload destinations when the endpoint cannot take them', () => {
+ renderPalette({ canAttach: false });
+ expect(rows()).not.toContain('com_ui_composer_attach');
+ expect(rows()).not.toContain('Upload to Provider');
+ });
+ });
+
+ describe('the folded upload destinations', () => {
+ it('shows the ordinary destination and folds the rest away', () => {
+ renderPalette();
+ const listed = rows();
+ expect(listed).toContain('Upload to Provider');
+ expect(listed).toContain('com_ui_composer_attach_more');
+ expect(listed).not.toContain('Upload to Code Environment');
+ });
+
+ it('reveals them in place, and folds them back', async () => {
+ renderPalette();
+ fireEvent.click(screen.getByText('com_ui_composer_attach_more'));
+ expect(rows()).toContain('Upload to Code Environment');
+ expect(rows()).toContain('com_ui_composer_attach_less');
+
+ fireEvent.click(screen.getByText('com_ui_composer_attach_less'));
+ /* Closing waits for the rows to fade before taking their space back, so
+ the list still holds them for the length of that fade. */
+ expect(rows()).toContain('Upload to Code Environment');
+ await waitFor(() => expect(rows()).not.toContain('Upload to Code Environment'));
+ });
+
+ it('offers no disclosure when there is nothing to fold', () => {
+ mockAttachEntries = [attachEntry('local:provider', 'Upload to Provider', true)];
+ renderPalette();
+ expect(rows()).toContain('Upload to Provider');
+ expect(rows()).not.toContain('com_ui_composer_attach_more');
+ });
+ });
+
+ describe('clicks reaching the composer box', () => {
+ const clickRow = (key: string) => {
+ const row = document.querySelector<HTMLElement>(`[data-row-key="${key}"]`);
+ expect(row).not.toBeNull();
+ fireEvent.click(row as HTMLElement);
+ };
+
+ /* The click that opens the palette is itself on the disclosure, which sits
+ in the composer box and is meant to reach it. Only what a row does after
+ that is under test. */
+ const openPalette = () => {
+ const onContainerClick = jest.fn();
+ renderPalette({ onContainerClick });
+ onContainerClick.mockClear();
+ return onContainerClick;
+ };
+
+ it('keeps a catalog toggle from reaching the composer, so focus stays in the palette', () => {
+ const onContainerClick = openPalette();
+
+ clickRow('web_search');
+
+ expect(onContainerClick).not.toHaveBeenCalled();
+ });
+
+ it('keeps the disclosure from reaching the composer', () => {
+ const onContainerClick = openPalette();
+
+ clickRow('attach:more');
+
+ expect(onContainerClick).not.toHaveBeenCalled();
+ });
+
+ it('lets a destination that dismisses the palette hand focus back', () => {
+ const onContainerClick = openPalette();
+
+ clickRow(ATTACH[0].id);
+
+ expect(onContainerClick).toHaveBeenCalled();
+ });
+ });
+
+ /* A tablet with a hardware keyboard stays `(pointer: coarse)` while it types,
+ so the device's primary pointer cannot decide whether closing may focus the
+ message field; the interaction that closed the palette does. */
+ describe('focus after closing on a touch-primary device', () => {
+ const realMatchMedia = window.matchMedia;
+ beforeEach(() => {
+ window.matchMedia = ((query: string) => ({
+ matches: query === '(pointer: coarse)',
+ media: query,
+ onchange: null,
+ addListener: jest.fn(),
+ removeListener: jest.fn(),
+ addEventListener: jest.fn(),
+ removeEventListener: jest.fn(),
+ dispatchEvent: jest.fn(),
+ })) as unknown as typeof window.matchMedia;
+ });
+ afterEach(() => {
+ window.matchMedia = realMatchMedia;
+ });
+
+ /** jsdom has no PointerEvent, so `pointerType` is defined on the event by hand. */
+ const press = (target: Element, pointerType: string) => {
+ const event = new MouseEvent('pointerdown', { bubbles: true, cancelable: true });
+ Object.defineProperty(event, 'pointerType', { value: pointerType });
+ act(() => {
+ target.dispatchEvent(event);
+ });
+ };
+
+ const composer = () => {
+ const anchor = document.createElement('div');
+ const field = document.createElement('textarea');
+ field.dataset.testid = 'text-input';
+ anchor.appendChild(field);
+ document.body.appendChild(anchor);
+ return { anchor, field };
+ };
+
+ it('returns a keyboard close to the message field', async () => {
+ const { anchor, field } = composer();
+ renderPalette({ anchor });
+ const input = await screen.findByTestId('composer-palette-search');
+ await waitFor(() => expect(document.activeElement).toBe(input));
+
+ await userEvent.keyboard('{Escape}');
+
+ await waitFor(() =>
+ expect(screen.queryByTestId('composer-palette-search')).not.toBeInTheDocument(),
+ );
+ await waitFor(() => expect(document.activeElement).toBe(field));
+ anchor.remove();
+ });
+
+ it('returns a mouse press outside to the message field after a touch inside', async () => {
+ const { anchor, field } = composer();
+ renderPalette({ anchor });
+ const input = await screen.findByTestId('composer-palette-search');
+
+ press(input, 'touch');
+ press(document.body, 'mouse');
+ fireEvent.mouseDown(document.body);
+ fireEvent.click(document.body);
+
+ await waitFor(() =>
+ expect(screen.queryByTestId('composer-palette-search')).not.toBeInTheDocument(),
+ );
+ await waitFor(() => expect(document.activeElement).toBe(field));
+ anchor.remove();
+ });
+
+ it('does not carry a touch session into the next opening', async () => {
+ const { anchor, field } = composer();
+ renderPalette({ anchor });
+ const row = await waitFor(() => {
+ const found = document.querySelector<HTMLElement>(`[data-row-key="${ATTACH[0].id}"]`);
+ expect(found).not.toBeNull();
+ return found as HTMLElement;
+ });
+ press(row, 'touch');
+ fireEvent.click(row);
+ await waitFor(() =>
+ expect(screen.queryByTestId('composer-palette-search')).not.toBeInTheDocument(),
+ );
+ await act(() => new Promise((resolve) => window.requestAnimationFrame(resolve)));
+ field.blur();
+ window.matchMedia = realMatchMedia;
+
+ fireEvent.click(screen.getByTestId('composer-palette-button'));
+ await screen.findByTestId('composer-palette-search');
+ act(() => {
+ screen.getByTestId('composer-palette-button').click();
+ });
+
+ await waitFor(() => expect(document.activeElement).toBe(field));
+ anchor.remove();
+ });
+
+ it('leaves focus alone when a touch press closes it', async () => {
+ const { anchor, field } = composer();
+ renderPalette({ anchor });
+ const row = await waitFor(() => {
+ const found = document.querySelector<HTMLElement>(`[data-row-key="${ATTACH[0].id}"]`);
+ expect(found).not.toBeNull();
+ return found as HTMLElement;
+ });
+
+ press(row, 'touch');
+ fireEvent.click(row);
+
+ await waitFor(() =>
+ expect(screen.queryByTestId('composer-palette-search')).not.toBeInTheDocument(),
+ );
+ await act(() => new Promise((resolve) => window.requestAnimationFrame(resolve)));
+ expect(document.activeElement).not.toBe(field);
+ anchor.remove();
+ });
+ });
+
+ describe('searching', () => {
+ it('reaches a folded destination by name', () => {
+ renderPalette();
+ search('code environment');
+ const listed = rows();
+ expect(listed).toContain('Upload to Code Environment');
+ /* The disclosure is there to keep the resting list short, not to make a
+ row unfindable, so it steps out of the way of a search. */
+ expect(listed).not.toContain('com_ui_composer_attach_more');
+ });
+
+ it('drops sections with nothing left in them', () => {
+ renderPalette();
+ search('github');
+ expect(keys()).toEqual(['h:mcp', 'mcp:github']);
+ });
+
+ it('floats a label match above a description-only match', () => {
+ renderPalette({
+ canAttach: false,
+ entries: [
+ entry({ key: 'a', label: 'Notes', description: 'nothing to do with drafting' }),
+ entry({ key: 'b', label: 'Drafting', description: 'unrelated' }),
+ ],
+ });
+ search('draft');
+ expect(keys()).toEqual(['h:tool', 'b', 'a']);
+ });
+
+ it('says so when nothing matches, out loud as well as on screen', () => {
+ renderPalette();
+ search('nothing matches this');
+ const empty = screen.getByText('com_ui_composer_no_results');
+ expect(empty).toBeInTheDocument();
+ expect(empty).toHaveAttribute('role', 'status');
+ /* The widget stays expanded and keeps controlling its (now empty)
+ list: collapsing mid-search while the popover is still on screen
+ reported a contradictory state exactly when the results changed. */
+ const input = screen.getByTestId('composer-palette-search');
+ expect(input).toHaveAttribute('aria-expanded', 'true');
+ expect(document.getElementById(input.getAttribute('aria-controls') ?? '')).not.toBeNull();
+ });
+ });
+
+ describe('keyboard', () => {
+ it('starts on the first row that can be chosen, never on a header', () => {
+ renderPalette();
+ const input = screen.getByTestId('composer-palette-search');
+ expect(input.getAttribute('aria-activedescendant')).toBe(
+ 'palette-row-0-006c006f00630061006c003a00700072006f00760069006400650072',
+ );
+ });
+
+ /* An id that names nothing is the failure mode here: screen readers lose
+ the active option entirely and announce nothing in its place. */
+ it('always points at a row that is in the document', () => {
+ renderPalette();
+ const input = screen.getByTestId('composer-palette-search');
+ const pointsAtSomething = () => {
+ const id = input.getAttribute('aria-activedescendant');
+ return id != null && document.getElementById(id) != null;
+ };
+ expect(pointsAtSomething()).toBe(true);
+ fireEvent.keyDown(input, { key: 'ArrowDown' });
+ expect(pointsAtSomething()).toBe(true);
+ search('code');
+ expect(pointsAtSomething()).toBe(true);
+ });
+
+ it('supports malformed surrogate keys and keeps punctuation-distinct row ids unique', () => {
+ const loneHighSurrogateKey = 'mcp:\ud800';
+ const loneLowSurrogateKey = 'mcp:\udc00';
+ renderPalette({
+ canAttach: false,
+ entries: [
+ entry({ key: 'mcp:foo.bar', itemType: 'mcp', itemId: 'foo.bar', section: 'mcp' }),
+ entry({ key: 'mcp:foo_bar', itemType: 'mcp', itemId: 'foo_bar', section: 'mcp' }),
+ entry({
+ key: loneHighSurrogateKey,
+ itemType: 'mcp',
+ itemId: '\ud800',
+ section: 'mcp',
+ }),
+ entry({
+ key: loneLowSurrogateKey,
+ itemType: 'mcp',
+ itemId: '\udc00',
+ section: 'mcp',
+ }),
+ ],
+ });
+ const input = screen.getByTestId('composer-palette-search');
+ const rows = Array.from(document.querySelectorAll<HTMLElement>('[data-row-key]'));
+ const findCell = (key: string) =>
+ rows
+ .find((row) => row.dataset.rowKey === key)
+ ?.querySelector<HTMLElement>('[role="gridcell"][id]');
+ const dotted = findCell('mcp:foo.bar');
+ const underscored = findCell('mcp:foo_bar');
+ const loneHighSurrogate = findCell(loneHighSurrogateKey);
+ const loneLowSurrogate = findCell(loneLowSurrogateKey);
+
+ expect(dotted?.id).toBeTruthy();
+ expect(underscored?.id).toBeTruthy();
+ expect(loneHighSurrogate?.id).toBeTruthy();
+ expect(loneLowSurrogate?.id).toBeTruthy();
+ expect(dotted?.id).not.toBe(underscored?.id);
+ expect(loneHighSurrogate?.id).not.toBe(loneLowSurrogate?.id);
+ expect(input).toHaveAttribute('aria-activedescendant', dotted?.id);
+
+ fireEvent.keyDown(input, { key: 'ArrowDown' });
+ expect(input).toHaveAttribute('aria-activedescendant', underscored?.id);
+ });
+
+ it('keeps the highlight on a row that moved rather than on its old position', () => {
+ mockFavoriteKeys = [];
+ renderPalette({ canAttach: false });
+ const input = screen.getByTestId('composer-palette-search');
+ fireEvent.keyDown(input, { key: 'ArrowDown' });
+ const moved = input.getAttribute('aria-activedescendant');
+ expect(moved).toBe('palette-row-0-0065007800650063007500740065005f0063006f00640065');
+
+ /* Starring it lifts the row into favourites without changing the row
+ count, which is exactly the case a positional highlight got wrong. */
+ mockFavoriteKeys = ['execute_code'];
+ fireEvent.keyDown(input, { key: 'd', metaKey: true });
+ expect(input.getAttribute('aria-activedescendant')).toBe(moved);
+ });
+
+ it('leaves the list alone when the pointer moves over it', () => {
+ renderPalette();
+ const list = document.querySelector('.ReactVirtualized__Grid');
+ expect(list?.getAttribute('tabindex')).toBe('-1');
+ expect(list).toBe(screen.getByRole('grid', { name: 'com_ui_composer_palette' }));
+ expect(screen.getByTestId('composer-palette-search').getAttribute('aria-controls')).toBe(
+ list?.id,
+ );
+ const rendered = list?.querySelectorAll('[role="rowgroup"] [role="row"]') ?? [];
+ expect(rendered.length).toBeGreaterThan(0);
+ expect(rendered[0].getAttribute('aria-rowindex')).toBe('1');
+ expect(Number(list?.getAttribute('aria-rowcount'))).toBeGreaterThanOrEqual(rendered.length);
+ });
+
+ it('steps over headers on the way down', () => {
+ renderPalette();
+ const input = screen.getByTestId('composer-palette-search');
+ const active = () =>
+ document.querySelector('[aria-selected="true"]')?.textContent?.trim() ?? '';
+
+ expect(active()).toBe('Upload to Provider');
+ fireEvent.keyDown(input, { key: 'ArrowDown' });
+ expect(active()).toBe('com_ui_composer_attach_more');
+ fireEvent.keyDown(input, { key: 'ArrowDown' });
+ /* The tools header sits between them and is skipped. */
+ expect(active()).toBe('Web Search');
+ });
+
+ it('wraps from the last row back to the first', () => {
+ renderPalette({ canAttach: false, entries: [entry({ key: 'only', label: 'Only Tool' })] });
+ const input = screen.getByTestId('composer-palette-search');
+ fireEvent.keyDown(input, { key: 'ArrowUp' });
+ expect(document.querySelector('[aria-selected="true"]')?.textContent?.trim()).toBe(
+ 'Only Tool',
+ );
+ });
+
+ it('chooses the active row on Enter', () => {
+ const onSelect = jest.fn();
+ renderPalette({
+ canAttach: false,
+ entries: [entry({ key: 'only', label: 'Only Tool', onSelect })],
+ });
+ const input = screen.getByTestId('composer-palette-search');
+ fireEvent.keyDown(input, { key: 'Enter' });
+ expect(onSelect).toHaveBeenCalledTimes(1);
+ });
+
+ it('stars the active row on Mod+D', () => {
+ renderPalette({ canAttach: false, entries: [entry({ key: 'only', label: 'Only Tool' })] });
+ const input = screen.getByTestId('composer-palette-search');
+ fireEvent.keyDown(input, { key: 'd', metaKey: true });
+ expect(mockToggleFavorite).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not favorite a temporary catalog placeholder', () => {
+ renderPalette({
+ canAttach: false,
+ entries: [entry({ key: 'temporary', label: 'Temporary', favoritable: false })],
+ });
+ const input = screen.getByTestId('composer-palette-search');
+ fireEvent.keyDown(input, { key: 'd', metaKey: true });
+
+ expect(mockToggleFavorite).not.toHaveBeenCalled();
+ expect(screen.queryByRole('button', { name: 'com_ui_favorite' })).not.toBeInTheDocument();
+ });
+
+ it('exposes named keyboard controls for secondary row actions', async () => {
+ const user = userEvent.setup();
+ const onSelect = jest.fn();
+ const onConfigure = jest.fn();
+ renderPalette({
+ canAttach: false,
+ entries: [
+ entry({
+ key: 'only',
+ label: 'Only Tool',
+ onSelect,
+ modes: [
+ {
+ id: 'configure',
+ label: 'Configure Tool',
+ active: false,
+ icon: <span aria-hidden="true" />,
+ onSelect: onConfigure,
+ },
+ ],
+ }),
+ ],
+ });
+
+ const configure = screen.getByRole('button', { name: 'Configure Tool' });
+ expect(configure.closest('[role="gridcell"]')).not.toHaveAttribute('id');
+ expect(configure.parentElement).toHaveClass(
+ 'transition-none',
+ 'opacity-100',
+ '[@media(hover:hover)]:opacity-0',
+ );
+
+ await waitFor(() => expect(screen.getByTestId('composer-palette-search')).toHaveFocus());
+ await user.tab();
+ expect(configure).toHaveFocus();
+ await user.keyboard(' ');
+ expect(onConfigure).toHaveBeenCalledTimes(1);
+ expect(onSelect).not.toHaveBeenCalled();
+ });
+
+ it('exposes a touch-visible named favorite action outside the active gridcell', async () => {
+ const user = userEvent.setup();
+ const onSelect = jest.fn();
+ renderPalette({
+ canAttach: false,
+ entries: [entry({ key: 'only', label: 'Only Tool', onSelect })],
+ });
+
+ expect(screen.getByRole('grid')).toBeVisible();
+ const favorite = screen.getByRole('button', { name: 'com_ui_favorite' });
+ expect(favorite).toHaveAttribute('aria-pressed', 'false');
+ expect(favorite.parentElement).toHaveClass(
+ 'transition-none',
+ 'opacity-100',
+ '[@media(hover:hover)]:opacity-0',
+ );
+ expect(favorite.parentElement).not.toHaveClass('transition-opacity');
+ expect(favorite.closest('[role="gridcell"]')).not.toHaveAttribute('id');
+
+ await waitFor(() => expect(screen.getByTestId('composer-palette-search')).toHaveFocus());
+ await user.tab();
+ expect(favorite).toHaveFocus();
+ await user.keyboard('{Enter}');
+ expect(mockToggleFavorite).toHaveBeenCalledWith('tool', 'only');
+ expect(onSelect).not.toHaveBeenCalled();
+
+ mockToggleFavorite.mockClear();
+ await user.click(favorite);
+ expect(mockToggleFavorite).toHaveBeenCalledWith('tool', 'only');
+ expect(onSelect).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/client/src/components/Chat/Input/Composer/__tests__/Queue.spec.tsx b/client/src/components/Chat/Input/Composer/__tests__/Queue.spec.tsx
new file mode 100644
index 0000000000..e0c778b294
--- /dev/null
+++ b/client/src/components/Chat/Input/Composer/__tests__/Queue.spec.tsx
@@ -0,0 +1,941 @@
+import React from 'react';
+import { DndProvider } from 'react-dnd';
+import { getDefaultStore } from 'jotai';
+import { RecoilRoot, useSetRecoilState } from 'recoil';
+import { HTML5Backend } from 'react-dnd-html5-backend';
+import { ReasoningEffort } from 'librechat-data-provider';
+import { act, render, screen, within, fireEvent } from '@testing-library/react';
+import type { SteeringControls } from '~/hooks/Chat/useSteering';
+import type { QueuedMessage } from '~/store/families';
+import { hasQueuedIntent, releaseQueuedIntent } from '~/utils/queueIntent';
+import { revealedQueuedTurnFamily } from '~/store/steer';
+import Queue from '../Queue';
+import store from '~/store';
+jest.mock('~/hooks', () => ({
+ useLocalize: () => (key: string, options?: Record<string, string | number>) => {
+ if (!options) {
+ return key;
+ }
+ const value = options.count ?? options['0'];
+ return `${key}:${value}`;
+ },
+}));
+
+const mockShowToast = jest.fn();
+jest.mock('@librechat/client', () => {
+ const ReactActual = jest.requireActual('react') as typeof React;
+ const IconButton = ReactActual.forwardRef(
+ (
+ {
+ label,
+ children,
+ ...props
+ }: { label?: string; children?: React.ReactNode } & Record<string, unknown>,
+ ref: React.Ref<HTMLButtonElement>,
+ ) =>
+ ReactActual.createElement(
+ 'button',
+ { ...props, ref, type: 'button', 'aria-label': label },
+ children,
+ ),
+ );
+ IconButton.displayName = 'IconButton';
+ return {
+ Button: ({ children, ...props }: { children?: React.ReactNode } & Record<string, unknown>) =>
+ ReactActual.createElement('button', { type: 'button', ...props }, children),
+ IconButton,
+ TooltipAnchor: ({
+ children,
+ render,
+ ...props
+ }: {
+ children?: React.ReactNode;
+ render?: React.ReactElement;
+ } & Record<string, unknown>) =>
+ render
+ ? ReactActual.cloneElement(render, props)
+ : ReactActual.createElement('span', props, children),
+ useMediaQuery: () => true,
+ useToastContext: () => ({ showToast: mockShowToast }),
+ };
+});
+
+const CONVO_ID = 'convo-1';
+const mockSendQueuedNow = jest.fn();
+const mockRemoveQueued = jest.fn();
+const mockReorderQueued = jest.fn();
+const mockRestoreQueuedOrder = jest.fn();
+const mockDiscardQueued = jest.fn().mockResolvedValue(true);
+const mockRewakeDrain = jest.fn();
+const mockHoldQueued = jest.fn();
+const mockEnqueue = jest.fn();
+
+/** Only what the rail reads, filled out against the real type so a change to
+ * the contract breaks compilation rather than passing quietly. */
+const steeringWith = (over: Partial<SteeringControls> = {}): SteeringControls =>
+ ({
+ queueKey: CONVO_ID,
+ duringRunActive: true,
+ canSteer: true,
+ canSendQueuedNow: true,
+ sendQueuedNow: mockSendQueuedNow,
+ removeQueued: mockRemoveQueued,
+ reorderQueued: mockReorderQueued,
+ restoreQueuedOrder: mockRestoreQueuedOrder,
+ discardQueued: mockDiscardQueued,
+ rewakeDrain: mockRewakeDrain,
+ holdQueued: mockHoldQueued,
+ enqueue: mockEnqueue,
+ ...over,
+ }) as SteeringControls;
+
+const steering = steeringWith();
+const pausedSteering = steeringWith({ canSteer: false, canSendQueuedNow: false });
+/** Paused on a tool approval: steering is unavailable, but the escalation
+ * control stays visible-and-disabled rather than vanishing mid-pause. */
+const approvalPausedSteering = steeringWith({
+ canSteer: false,
+ canSendQueuedNow: false,
+ pausedOnApproval: true,
+});
+
+const queued = (over: Partial<QueuedMessage> = {}): QueuedMessage =>
+ ({
+ id: 'q1',
+ text: 'follow up on this',
+ files: [],
+ quotes: [],
+ manualSkills: [],
+ ...over,
+ }) as QueuedMessage;
+
+function renderQueue(
+ items: QueuedMessage[],
+ steeringOverride: SteeringControls = steering,
+ handlers: {
+ onEditToComposer?: jest.Mock;
+ onRestoreToComposer?: jest.Mock;
+ canRestoreToComposer?: jest.Mock;
+ } = {},
+) {
+ return render(
+ <RecoilRoot initializeState={({ set }) => set(store.queuedMessagesByConvoId(CONVO_ID), items)}>
+ {/* Mirrors `App`, which mounts the provider around the whole tree. */}
+ <DndProvider backend={HTML5Backend}>
+ <Queue
+ steering={steeringOverride}
+ conversationId={CONVO_ID}
+ onRestoreToComposer={
+ handlers.onRestoreToComposer ?? handlers.onEditToComposer ?? jest.fn()
+ }
+ canRestoreToComposer={handlers.canRestoreToComposer ?? jest.fn().mockReturnValue(true)}
+ />
+ </DndProvider>
+ </RecoilRoot>,
+ );
+}
+
+describe('Queue', () => {
+ beforeEach(() => jest.clearAllMocks());
+
+ it('renders nothing when the queue is empty', () => {
+ const { container } = renderQueue([]);
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it('renders a row per queued message with every action visible, none behind a menu', () => {
+ renderQueue([queued({ id: 'q1' }), queued({ id: 'q2' })]);
+ const rows = screen.getAllByTestId('queued-message-row');
+ expect(rows).toHaveLength(2);
+
+ const firstRow = within(rows[0]);
+ expect(firstRow.getByRole('button', { name: 'com_ui_send_now' })).toBeInTheDocument();
+ expect(firstRow.getByTestId('queued-interrupt-now')).toBeInTheDocument();
+ expect(firstRow.getByLabelText('com_ui_edit_message')).toBeInTheDocument();
+ expect(firstRow.getByLabelText('com_ui_remove_queued')).toBeInTheDocument();
+ expect(firstRow.queryByLabelText('com_ui_more_options')).not.toBeInTheDocument();
+ });
+
+ it('sends the row that was clicked, not the first one', () => {
+ renderQueue([queued({ id: 'q1' }), queued({ id: 'q2', text: 'the second one' })]);
+ fireEvent.click(screen.getAllByRole('button', { name: 'com_ui_send_now' })[1]);
+ expect(mockSendQueuedNow).toHaveBeenCalledWith(
+ expect.objectContaining({ id: 'q2', text: 'the second one' }),
+ );
+ });
+
+ it('disables send now while the run is paused on approval', () => {
+ renderQueue([queued()], pausedSteering);
+ const sendButton = screen.getByRole('button', { name: 'com_ui_send_now' });
+ expect(sendButton).toBeDisabled();
+ expect(sendButton).toHaveAttribute('title', 'com_ui_send_now_paused');
+
+ fireEvent.click(sendButton);
+ expect(mockSendQueuedNow).not.toHaveBeenCalled();
+ });
+
+ /* Answer mode (and Assistants still generating) leave duringRunActive false
+ while isSubmitting is true; sendQueuedNow would no-op, so the control must
+ not look actionable. */
+ it('disables send now when no immediate send route exists', () => {
+ renderQueue(
+ [queued()],
+ steeringWith({ duringRunActive: false, canSteer: false, canSendQueuedNow: false }),
+ );
+ const sendButton = screen.getByRole('button', { name: 'com_ui_send_now' });
+ expect(sendButton).toBeDisabled();
+ fireEvent.click(sendButton);
+ expect(mockSendQueuedNow).not.toHaveBeenCalled();
+ });
+
+ it('disables send now for a receipt-bound recovery during a live run', () => {
+ renderQueue([queued({ recoverySteerId: 'srv-1' })]);
+ const sendButton = screen.getByRole('button', { name: 'com_ui_send_now' });
+
+ expect(sendButton).toBeDisabled();
+ fireEvent.click(sendButton);
+ expect(mockSendQueuedNow).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['local', {}],
+ ['server-owned', { server: { id: 'server-q1', status: 'queued' as const, revision: 1 } }],
+ ])('disables live actions for a reasoning override on a %s row', (_kind, row) => {
+ renderQueue([
+ queued({
+ ...row,
+ reasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.high },
+ }),
+ ]);
+ const sendButton = screen.getByRole('button', { name: 'com_ui_send_now' });
+ const interruptButton = screen.getByTestId('queued-interrupt-now');
+
+ expect(sendButton).toBeDisabled();
+ expect(interruptButton).toBeDisabled();
+ expect(sendButton).toHaveAttribute('title', 'com_ui_send_now_paused');
+ fireEvent.click(sendButton);
+ fireEvent.click(interruptButton);
+ expect(mockSendQueuedNow).not.toHaveBeenCalled();
+ });
+
+ it('allows a reasoning override to start a new generation while idle', () => {
+ renderQueue(
+ [
+ queued({
+ reasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.high },
+ }),
+ ],
+ steeringWith({ duringRunActive: false, canSteer: false, canSendQueuedNow: true }),
+ );
+ const sendButton = screen.getByRole('button', { name: 'com_ui_send_now' });
+
+ expect(sendButton).toBeEnabled();
+ fireEvent.click(sendButton);
+ expect(mockSendQueuedNow).toHaveBeenCalledWith(
+ expect.objectContaining({
+ reasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.high },
+ }),
+ );
+ });
+
+ it('moves a message down the queue with the arrow keys', () => {
+ renderQueue([queued({ id: 'q1' }), queued({ id: 'q2' })]);
+ const grips = screen.getAllByTestId('queued-message-grip');
+
+ fireEvent.keyDown(grips[0], { key: 'ArrowDown' });
+ expect(mockReorderQueued).toHaveBeenCalledWith('q1', 1);
+
+ fireEvent.keyDown(grips[1], { key: 'ArrowUp' });
+ expect(mockReorderQueued).toHaveBeenCalledWith('q2', 0);
+ });
+
+ it('refuses to reorder across an acknowledged server-owned row', () => {
+ renderQueue([
+ queued({ id: 'q1' }),
+ queued({ id: 'server-q1', server: { id: 'server-q1', status: 'queued', revision: 1 } }),
+ queued({ id: 'q2' }),
+ ]);
+ const grips = screen.getAllByTestId('queued-message-grip');
+ expect(grips[0]).toHaveAttribute('aria-disabled', 'true');
+ expect(grips[1]).toHaveAttribute('aria-disabled', 'true');
+ fireEvent.keyDown(grips[0], { key: 'ArrowDown' });
+ expect(mockReorderQueued).not.toHaveBeenCalled();
+ expect(mockShowToast).toHaveBeenCalledWith(
+ expect.objectContaining({
+ message: 'com_ui_queue_reorder_blocked',
+ status: 'warning',
+ }),
+ );
+ expect(screen.getByRole('status')).toHaveTextContent('com_ui_queue_reorder_blocked');
+ });
+
+ it('refuses to move a message past either end of the queue', () => {
+ renderQueue([queued({ id: 'q1' }), queued({ id: 'q2' })]);
+ const grips = screen.getAllByTestId('queued-message-grip');
+
+ fireEvent.keyDown(grips[0], { key: 'ArrowUp' });
+ fireEvent.keyDown(grips[1], { key: 'ArrowDown' });
+ expect(mockReorderQueued).not.toHaveBeenCalled();
+ });
+
+ it('announces where a moved message landed', () => {
+ renderQueue([queued({ id: 'q1' }), queued({ id: 'q2' })]);
+ fireEvent.keyDown(screen.getAllByTestId('queued-message-grip')[0], { key: 'ArrowDown' });
+ expect(screen.getByRole('status')).toHaveTextContent('com_ui_queue_moved:2');
+ });
+
+ /* Swapping the handle out from under a keyboard user is how focus gets
+ dropped to the top of the page when a drain shrinks the queue. */
+ it('keeps the handle when the only message has nowhere to go, and refuses to move it', () => {
+ renderQueue([queued()]);
+ const grip = screen.getByTestId('queued-message-grip');
+ expect(grip).toHaveAttribute('aria-disabled', 'true');
+
+ fireEvent.keyDown(grip, { key: 'ArrowDown' });
+ fireEvent.keyDown(grip, { key: 'ArrowUp' });
+ expect(mockReorderQueued).not.toHaveBeenCalled();
+ });
+
+ it('keeps the live region and the hint out of the list itself', () => {
+ renderQueue([queued({ id: 'q1' }), queued({ id: 'q2' })]);
+ const list = screen.getByTestId('composer-queue');
+ expect(within(list).queryByRole('status')).not.toBeInTheDocument();
+ expect(screen.getByRole('status')).toBeInTheDocument();
+ /* Every child of the list is one of its items. */
+ for (const child of Array.from(list.children)) {
+ expect(child).toHaveAttribute('role', 'listitem');
+ }
+ });
+
+ it('returns a trashed message to the composer before dropping it', async () => {
+ const onRestore = jest.fn().mockReturnValue(true);
+ renderQueue(
+ [
+ queued({
+ id: 'q1',
+ files: [{ file_id: 'f1' }] as never,
+ reasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.high },
+ }),
+ ],
+ steering,
+ { onRestoreToComposer: onRestore },
+ );
+ await act(async () => {
+ fireEvent.click(screen.getByLabelText('com_ui_remove_queued'));
+ });
+ expect(onRestore).toHaveBeenCalledWith(
+ 'follow up on this',
+ [{ file_id: 'f1' }],
+ {
+ quotes: [],
+ manualSkills: [],
+ reasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.high },
+ },
+ CONVO_ID,
+ );
+ expect(mockRemoveQueued).toHaveBeenCalledWith('q1');
+ });
+
+ /* The composer refuses when it is occupied or the user has moved on. Dropping
+ the message anyway is the only path here that can destroy text outright. */
+ it('keeps the message queued when the composer refuses to take it back', async () => {
+ const onRestore = jest.fn().mockReturnValue(false);
+ renderQueue([queued({ id: 'q1' })], steering, { onRestoreToComposer: onRestore });
+ await act(async () => {
+ fireEvent.click(screen.getByLabelText('com_ui_remove_queued'));
+ });
+ expect(onRestore).toHaveBeenCalled();
+ expect(mockRemoveQueued).not.toHaveBeenCalled();
+ /* Keeping the words is right; saying nothing about it is not. Without this
+ the row simply does not react and the button reads as broken. */
+ expect(mockShowToast).toHaveBeenCalledWith(
+ expect.objectContaining({ message: 'com_ui_queue_remove_blocked' }),
+ );
+ /* A run end that landed while this row was claimed had no unclaimed row to
+ drain and spent its one-shot signal. The row is back in the queue, so a
+ signal has to go back with it or these words wait for another run. */
+ expect(mockRewakeDrain).toHaveBeenCalledWith(CONVO_ID);
+ });
+
+ /* Discarding the parked server copy leaves the row only in memory, so a
+ composer that refuses has to refuse before that copy is given up. */
+ it.each([
+ ['com_ui_remove_queued', 'com_ui_queue_remove_blocked'],
+ ['com_ui_edit_message', 'com_ui_queue_edit_blocked'],
+ ])('keeps the parked copy when the composer would refuse (%s)', async (label, toast) => {
+ const onRestore = jest.fn().mockReturnValue(true);
+ renderQueue([queued({ id: 'q1' })], steering, {
+ onRestoreToComposer: onRestore,
+ canRestoreToComposer: jest.fn().mockReturnValue(false),
+ });
+ await act(async () => {
+ fireEvent.click(screen.getByLabelText(label));
+ });
+ expect(mockDiscardQueued).not.toHaveBeenCalled();
+ expect(onRestore).not.toHaveBeenCalled();
+ expect(mockRemoveQueued).not.toHaveBeenCalled();
+ expect(mockShowToast).toHaveBeenCalledWith(expect.objectContaining({ message: toast }));
+ });
+
+ /* The composer passed the precheck but changed while the parked copy was
+ being cancelled: the words go back on the durable queue in their place
+ rather than living only in memory until the next reload. */
+ it.each([
+ ['com_ui_remove_queued', 'com_ui_queue_remove_blocked'],
+ ['com_ui_edit_message', 'com_ui_queue_edit_blocked'],
+ ])(
+ 're-queues a durable row the composer refuses after cancelling it (%s)',
+ async (label, toast) => {
+ const row = queued({
+ id: 'q1',
+ createdAt: 42,
+ quotes: ['a quote'],
+ server: { id: 'server-q1', status: 'queued' },
+ parentMessageId: 'original-parent',
+ expectedPredecessorCreatedAt: 41,
+ });
+ renderQueue([row], steering, {
+ onRestoreToComposer: jest.fn().mockReturnValue(false),
+ canRestoreToComposer: jest.fn().mockReturnValue(true),
+ });
+ await act(async () => {
+ fireEvent.click(screen.getByLabelText(label));
+ });
+ expect(mockDiscardQueued).toHaveBeenCalled();
+ expect(mockRemoveQueued).toHaveBeenCalledWith('q1');
+ expect(mockEnqueue).toHaveBeenCalledWith(
+ 'follow up on this',
+ expect.objectContaining({
+ id: 'q1',
+ createdAt: 42,
+ quotes: ['a quote'],
+ skipUsageMark: true,
+ lineage: { parentMessageId: 'original-parent', predecessorCreatedAt: 41 },
+ }),
+ );
+ expect(mockShowToast).toHaveBeenCalledWith(expect.objectContaining({ message: toast }));
+ },
+ );
+
+ /* A recovered row's parked steer is its only durable copy and cannot be
+ re-created once its run has ended, so the composer has to take the words
+ before that copy is cancelled. */
+ describe('handing a recovered row to the composer', () => {
+ const recovered = () =>
+ queued({ id: 'q1', recoverySteerId: 'steer-1', recoveryClientSteerId: 'client-1' });
+
+ it.each([
+ ['com_ui_remove_queued', 'com_ui_queue_remove_blocked'],
+ ['com_ui_edit_message', 'com_ui_queue_edit_blocked'],
+ ])('keeps the parked copy when the composer refuses (%s)', async (label, toast) => {
+ renderQueue([recovered()], steering, {
+ onRestoreToComposer: jest.fn().mockReturnValue(false),
+ canRestoreToComposer: jest.fn().mockReturnValue(true),
+ });
+ await act(async () => {
+ fireEvent.click(screen.getByLabelText(label));
+ });
+ expect(mockDiscardQueued).not.toHaveBeenCalled();
+ expect(mockRemoveQueued).not.toHaveBeenCalled();
+ expect(mockEnqueue).not.toHaveBeenCalled();
+ expect(mockShowToast).toHaveBeenCalledWith(expect.objectContaining({ message: toast }));
+ });
+
+ it('cancels the parked copy only after the composer took the words', async () => {
+ const onRestore = jest.fn().mockReturnValue(true);
+ mockDiscardQueued.mockImplementationOnce(async () => {
+ expect(onRestore).toHaveBeenCalled();
+ return true;
+ });
+ renderQueue([recovered()], steering, { onRestoreToComposer: onRestore });
+ await act(async () => {
+ fireEvent.click(screen.getByLabelText('com_ui_edit_message'));
+ });
+ expect(mockDiscardQueued).toHaveBeenCalledWith(expect.objectContaining({ id: 'q1' }));
+ expect(mockRemoveQueued).toHaveBeenCalledWith('q1');
+ expect(mockHoldQueued).not.toHaveBeenCalled();
+ });
+
+ it('holds the row out of the drain when the parked copy cannot be cancelled', async () => {
+ mockDiscardQueued.mockResolvedValueOnce(false);
+ renderQueue([recovered()], steering, {
+ onRestoreToComposer: jest.fn().mockReturnValue(true),
+ });
+ await act(async () => {
+ fireEvent.click(screen.getByLabelText('com_ui_remove_queued'));
+ });
+ expect(mockRemoveQueued).not.toHaveBeenCalled();
+ expect(mockHoldQueued).toHaveBeenCalledWith('q1');
+ expect(mockEnqueue).not.toHaveBeenCalled();
+ });
+ });
+
+ it('keeps a local-only row in place when the composer refuses it', async () => {
+ renderQueue([queued({ id: 'q1' })], steering, {
+ onRestoreToComposer: jest.fn().mockReturnValue(false),
+ });
+ await act(async () => {
+ fireEvent.click(screen.getByLabelText('com_ui_remove_queued'));
+ });
+ expect(mockEnqueue).not.toHaveBeenCalled();
+ expect(mockRemoveQueued).not.toHaveBeenCalled();
+ });
+
+ it('hands the whole message to the composer to edit', async () => {
+ const onEdit = jest.fn().mockReturnValue(true);
+ renderQueue(
+ [
+ queued({
+ id: 'q1',
+ quotes: ['a quote'],
+ manualSkills: ['writer'],
+ reasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.high },
+ }),
+ ],
+ steering,
+ { onEditToComposer: onEdit },
+ );
+ await act(async () => {
+ fireEvent.click(screen.getByLabelText('com_ui_edit_message'));
+ });
+ expect(onEdit).toHaveBeenCalledWith(
+ 'follow up on this',
+ [],
+ {
+ quotes: ['a quote'],
+ manualSkills: ['writer'],
+ reasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.high },
+ },
+ CONVO_ID,
+ );
+ expect(mockRemoveQueued).toHaveBeenCalledWith('q1');
+ });
+
+ /* Edit used to drop the row first and hand the words over second, so a
+ composer that refuses (a paused question owns it) destroyed the message
+ outright. Same restore-then-remove order as the trash. */
+ it('keeps the message queued when the composer refuses to take it for editing', async () => {
+ const onEdit = jest.fn().mockReturnValue(false);
+ renderQueue([queued({ id: 'q1' })], steering, { onEditToComposer: onEdit });
+ await act(async () => {
+ fireEvent.click(screen.getByLabelText('com_ui_edit_message'));
+ });
+ expect(onEdit).toHaveBeenCalled();
+ expect(mockRemoveQueued).not.toHaveBeenCalled();
+ expect(mockShowToast).toHaveBeenCalledWith(
+ expect.objectContaining({ message: 'com_ui_queue_edit_blocked' }),
+ );
+ });
+
+ it('waits for discard before using the conversation-guarded edit restore', async () => {
+ let settleDiscard: (value: boolean) => void = () => undefined;
+ mockDiscardQueued.mockReturnValueOnce(
+ new Promise<boolean>((resolve) => {
+ settleDiscard = resolve;
+ }),
+ );
+ const onRestore = jest.fn().mockReturnValue(true);
+ renderQueue([queued({ id: 'q1' })], steering, { onRestoreToComposer: onRestore });
+
+ fireEvent.click(screen.getByLabelText('com_ui_edit_message'));
+ expect(onRestore).not.toHaveBeenCalled();
+
+ await act(async () => settleDiscard(true));
+ expect(onRestore).toHaveBeenCalledWith(
+ 'follow up on this',
+ [],
+ { quotes: [], manualSkills: [] },
+ CONVO_ID,
+ );
+ });
+
+ /* The drain takes the head at run end, and both handoffs above span an await
+ before the row is dropped. Claiming the row for the whole handoff is what
+ stops the drain sending a message the user is taking back. */
+ describe('claiming a row for the handoff', () => {
+ afterEach(() => releaseQueuedIntent('q1'));
+
+ it.each(['com_ui_edit_message', 'com_ui_remove_queued'] as const)(
+ 'holds the row across %s and lets it go afterwards',
+ async (label) => {
+ let settleDiscard: (value: boolean) => void = () => undefined;
+ mockDiscardQueued.mockReturnValueOnce(
+ new Promise<boolean>((resolve) => {
+ settleDiscard = resolve;
+ }),
+ );
+ renderQueue([queued({ id: 'q1' })], steering, {
+ onRestoreToComposer: jest.fn().mockReturnValue(true),
+ });
+
+ fireEvent.click(screen.getByLabelText(label));
+ expect(hasQueuedIntent('q1')).toBe(true);
+
+ await act(async () => settleDiscard(true));
+ expect(hasQueuedIntent('q1')).toBe(false);
+ expect(mockRemoveQueued).toHaveBeenCalledWith('q1');
+ },
+ );
+
+ it('lets the row go when the handoff is refused', async () => {
+ renderQueue([queued({ id: 'q1' })], steering, {
+ onRestoreToComposer: jest.fn().mockReturnValue(false),
+ });
+ await act(async () => {
+ fireEvent.click(screen.getByLabelText('com_ui_remove_queued'));
+ });
+ expect(hasQueuedIntent('q1')).toBe(false);
+ });
+ });
+
+ /* Split view mounts two composers at once. A module-global id duplicated the
+ hint element and pointed every handle at whichever copy won. */
+ it('scopes the reorder hint to its own rail', () => {
+ render(
+ <DndProvider backend={HTML5Backend}>
+ <RecoilRoot
+ initializeState={({ set }) =>
+ set(store.queuedMessagesByConvoId(CONVO_ID), [
+ queued({ id: 'q1' }),
+ queued({ id: 'q2' }),
+ ])
+ }
+ >
+ <Queue
+ steering={steering}
+ conversationId={CONVO_ID}
+ onRestoreToComposer={jest.fn()}
+ canRestoreToComposer={() => true}
+ />
+ </RecoilRoot>
+ <RecoilRoot
+ initializeState={({ set }) =>
+ set(store.queuedMessagesByConvoId(CONVO_ID), [
+ queued({ id: 'q3' }),
+ queued({ id: 'q4' }),
+ ])
+ }
+ >
+ <Queue
+ steering={steering}
+ conversationId={CONVO_ID}
+ onRestoreToComposer={jest.fn()}
+ canRestoreToComposer={() => true}
+ />
+ </RecoilRoot>
+ </DndProvider>,
+ );
+
+ const hints = screen.getAllByText('com_ui_queue_reorder_hint');
+ expect(hints).toHaveLength(2);
+ expect(hints[0].id).not.toBe(hints[1].id);
+
+ const rails = screen.getAllByTestId('composer-queue');
+ for (const [railIndex, rail] of rails.entries()) {
+ for (const grip of within(rail).getAllByTestId('queued-message-grip')) {
+ expect(grip).toHaveAttribute('aria-describedby', hints[railIndex].id);
+ }
+ }
+ });
+
+ /* The region is removed with the rail and re-inserted with its old text
+ still in it, which readers announce on insertion. */
+ it('forgets its last announcement once the queue empties', () => {
+ let setQueue: (items: QueuedMessage[]) => void = () => undefined;
+ const Driver = () => {
+ setQueue = useSetRecoilState(store.queuedMessagesByConvoId(CONVO_ID));
+ return null;
+ };
+ render(
+ <RecoilRoot
+ initializeState={({ set }) =>
+ set(store.queuedMessagesByConvoId(CONVO_ID), [queued({ id: 'q1' }), queued({ id: 'q2' })])
+ }
+ >
+ <Driver />
+ <DndProvider backend={HTML5Backend}>
+ <Queue
+ steering={steering}
+ conversationId={CONVO_ID}
+ onRestoreToComposer={jest.fn()}
+ canRestoreToComposer={() => true}
+ />
+ </DndProvider>
+ </RecoilRoot>,
+ );
+
+ fireEvent.keyDown(screen.getAllByTestId('queued-message-grip')[0], { key: 'ArrowDown' });
+ expect(screen.getByRole('status')).toHaveTextContent('com_ui_queue_moved:2');
+
+ act(() => setQueue([]));
+ act(() => setQueue([queued({ id: 'q3', text: 'a new message' })]));
+ expect(screen.getByRole('status')).toHaveTextContent('');
+ });
+
+ /* The rows move as the pointer crosses them, so the queue has already changed
+ by the time a drag ends. Only a drag that never landed anywhere puts it
+ back; and `didDrop` reports a landing even though the rows declare no
+ `drop` handler, which is what makes the plain `hover` sortable work. */
+ describe('drag reordering', () => {
+ /* The handle only drags on a hover-capable pointer, and the suite's
+ `matchMedia` answers `false` to everything, which is the touch device
+ the rail deliberately refuses to drag on. */
+ const realMatchMedia = window.matchMedia;
+ beforeEach(() => {
+ window.matchMedia = ((query: string) =>
+ ({
+ matches: query === '(hover: hover)',
+ media: query,
+ onchange: null,
+ addListener: jest.fn(),
+ removeListener: jest.fn(),
+ addEventListener: jest.fn(),
+ removeEventListener: jest.fn(),
+ dispatchEvent: jest.fn(),
+ }) as unknown as MediaQueryList) as typeof window.matchMedia;
+ });
+ afterEach(() => {
+ window.matchMedia = realMatchMedia;
+ });
+
+ /* jsdom has no DataTransfer, and the HTML5 backend reads one off every
+ event it handles. */
+ const dataTransfer = () => ({
+ dropEffect: 'move',
+ effectAllowed: 'move',
+ files: [],
+ items: [],
+ types: [],
+ setData: () => undefined,
+ getData: () => '',
+ setDragImage: () => undefined,
+ });
+
+ const dragFirstRowOntoSecond = (drop: boolean) => {
+ renderQueue([queued({ id: 'q1' }), queued({ id: 'q2' })]);
+ const grip = screen.getAllByTestId('queued-message-grip')[0];
+ const secondRow = screen.getAllByTestId('queued-message-row')[1];
+ const dt = dataTransfer();
+
+ fireEvent.dragStart(grip, { dataTransfer: dt });
+ fireEvent.dragOver(secondRow, { dataTransfer: dt, clientY: 1 });
+ if (drop) {
+ fireEvent.drop(secondRow, { dataTransfer: dt, clientY: 1 });
+ }
+ fireEvent.dragEnd(grip, { dataTransfer: dt });
+ };
+
+ it('reorders a local row when dragged onto another local row', () => {
+ dragFirstRowOntoSecond(true);
+ expect(mockReorderQueued).toHaveBeenCalledWith('q1', 1);
+ expect(mockRestoreQueuedOrder).not.toHaveBeenCalled();
+ });
+
+ it('puts the order back when the drag is abandoned', () => {
+ dragFirstRowOntoSecond(false);
+ expect(mockRestoreQueuedOrder).toHaveBeenCalledWith(['q1', 'q2']);
+ });
+ it('refuses a pointer reorder onto a server-owned row', () => {
+ renderQueue([
+ queued({ id: 'q1' }),
+ queued({ id: 'q2' }),
+ queued({ id: 'server-q1', server: { id: 'server-q1', status: 'queued', revision: 1 } }),
+ ]);
+ const grip = screen.getAllByTestId('queued-message-grip')[0];
+ const serverRow = screen.getAllByTestId('queued-message-row')[2];
+ const dt = dataTransfer();
+
+ fireEvent.dragStart(grip, { dataTransfer: dt });
+ fireEvent.dragOver(serverRow, { dataTransfer: dt, clientY: 1 });
+ fireEvent.drop(serverRow, { dataTransfer: dt, clientY: 1 });
+ fireEvent.dragEnd(grip, { dataTransfer: dt });
+
+ expect(mockReorderQueued).not.toHaveBeenCalled();
+ expect(mockShowToast).toHaveBeenCalledWith(
+ expect.objectContaining({
+ message: 'com_ui_queue_reorder_blocked',
+ status: 'warning',
+ }),
+ );
+ });
+ });
+
+ it('shows an attachment count when files ride along', () => {
+ renderQueue([queued({ files: [{ file_id: 'f1' }, { file_id: 'f2' }] as never })]);
+ const attachmentLabel = screen.getByText('com_ui_attachment_count:2');
+ expect(attachmentLabel).toBeInTheDocument();
+ expect(attachmentLabel.parentElement).toHaveAttribute(
+ 'title',
+ 'com_ui_queued_attachment_count:2',
+ );
+ expect(attachmentLabel.parentElement).not.toHaveAttribute('aria-label');
+ expect(screen.getByText('com_ui_queued_attachment_count:2')).toHaveClass('sr-only');
+ });
+
+ it('shows a quoted-excerpt count when quotes ride along', () => {
+ renderQueue([queued({ quotes: ['first', 'second'] })]);
+
+ expect(screen.getByText('2')).toHaveAttribute('aria-hidden', 'true');
+ expect(screen.getByText('com_ui_queued_quote_count:2')).toHaveClass('sr-only');
+ });
+
+ it('puts the during-run hint on each queued row', () => {
+ renderQueue([queued({ id: 'q1' }), queued({ id: 'q2' })]);
+
+ const rows = screen.getAllByTestId('queued-message-row');
+ expect(screen.getAllByRole('img', { name: 'com_ui_steer_queued_info' })).toHaveLength(2);
+ rows.forEach((row) => {
+ expect(
+ within(row).getByRole('img', { name: 'com_ui_steer_queued_info' }),
+ ).toBeInTheDocument();
+ });
+ expect(screen.queryByTestId('queued-caption')).not.toBeInTheDocument();
+ });
+
+ it('hides the queued hint after the run ends', () => {
+ renderQueue([queued()], steeringWith({ duringRunActive: false }));
+ expect(screen.queryByRole('img', { name: 'com_ui_steer_queued_info' })).not.toBeInTheDocument();
+ });
+ it('reveals an admitted claimed row with only cancellation available', () => {
+ const jotaiStore = getDefaultStore();
+ jotaiStore.set(revealedQueuedTurnFamily(CONVO_ID), {
+ clientRequestId: 'req-1',
+ parentMessageId: 'response-1',
+ text: 'follow up on this',
+ revealedAt: '2024-01-01T00:00:00.000Z',
+ });
+
+ try {
+ renderQueue(
+ [
+ queued({
+ id: 'q1',
+ clientRequestId: 'req-1',
+ server: { id: 'server-q1', status: 'claimed' },
+ }),
+ queued({ id: 'q2' }),
+ ],
+ steeringWith({ canSendQueuedNow: false, canSteer: false }),
+ );
+
+ const firstRow = within(screen.getAllByTestId('queued-message-row')[0]);
+ expect(firstRow.getByText('com_ui_queued_turn_starting')).toBeInTheDocument();
+ expect(firstRow.queryByRole('button', { name: 'com_ui_send_now' })).not.toBeInTheDocument();
+ expect(firstRow.queryByLabelText('com_ui_edit_message')).not.toBeInTheDocument();
+ expect(firstRow.getByLabelText('com_ui_remove_queued')).toBeEnabled();
+ } finally {
+ jotaiStore.set(revealedQueuedTurnFamily(CONVO_ID), null);
+ }
+ });
+
+ describe('server-owned queue states', () => {
+ it.each(['sending', 'claimed', 'uncertain'] as const)(
+ 'disables local actions while a %s row remains server-owned',
+ (status) => {
+ renderQueue([queued({ server: { id: 'server-q1', status } })]);
+
+ expect(screen.getByRole('button', { name: 'com_ui_send_now' })).toBeDisabled();
+ expect(screen.getByLabelText('com_ui_edit_message')).toBeDisabled();
+ expect(screen.getByLabelText('com_ui_remove_queued')).toBeDisabled();
+ expect(screen.getByTestId('queued-interrupt-now')).toBeDisabled();
+ },
+ );
+
+ it('keeps a rejected row actionable and labels its failure', () => {
+ renderQueue([queued({ server: { status: 'rejected' } })]);
+
+ expect(screen.getByText('com_ui_queued_turn_failed')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'com_ui_send_now' })).toBeEnabled();
+ expect(screen.getByLabelText('com_ui_edit_message')).toBeEnabled();
+ expect(screen.getByLabelText('com_ui_remove_queued')).toBeEnabled();
+ });
+
+ it('keeps an acknowledged queued server row actionable', () => {
+ renderQueue([queued({ server: { id: 'server-q1', status: 'queued' } })]);
+
+ expect(screen.getByRole('button', { name: 'com_ui_send_now' })).toBeEnabled();
+ expect(screen.getByLabelText('com_ui_edit_message')).toBeEnabled();
+ expect(screen.getByLabelText('com_ui_remove_queued')).toBeEnabled();
+ });
+
+ it('requires reconciliation and blocks removal for an indeterminate row', () => {
+ renderQueue([queued({ server: { id: 'server-q1', status: 'indeterminate' } })]);
+
+ expect(screen.getByText('com_ui_queued_turn_reconciliation_required')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'com_ui_send_now' })).toBeDisabled();
+ expect(screen.getByLabelText('com_ui_edit_message')).toBeDisabled();
+ expect(screen.getByLabelText('com_ui_remove_queued')).toBeDisabled();
+ });
+
+ it('dismisses an expired uncertain row without discarding or restoring it', () => {
+ const onRestore = jest.fn();
+ renderQueue(
+ [
+ queued({
+ server: {
+ id: 'server-q1',
+ status: 'uncertain',
+ reconciliationExpired: true,
+ },
+ }),
+ ],
+ steering,
+ { onRestoreToComposer: onRestore },
+ );
+
+ expect(screen.getByText('com_ui_steer_delivery_unconfirmed')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'com_ui_send_now' })).toBeDisabled();
+ expect(screen.getByLabelText('com_ui_edit_message')).toBeDisabled();
+
+ fireEvent.click(screen.getByLabelText('com_ui_dismiss_unconfirmed_delivery'));
+ expect(mockRemoveQueued).toHaveBeenCalledWith('q1');
+ expect(mockDiscardQueued).not.toHaveBeenCalled();
+ expect(onRestore).not.toHaveBeenCalled();
+ });
+ });
+
+ /* Escalation is the only way to make a waiting message interrupt the reply
+ rather than wait for its next tool step. Send now sends it as an ordinary
+ steer; this sends it as an interrupt. */
+ describe('interrupt escalation', () => {
+ it('escalates the row that was clicked, as a preempt', () => {
+ renderQueue([queued({ id: 'q1' }), queued({ id: 'q2', text: 'the second one' })]);
+ fireEvent.click(screen.getAllByTestId('queued-interrupt-now')[1]);
+ expect(mockSendQueuedNow).toHaveBeenCalledWith(expect.objectContaining({ id: 'q2' }), {
+ preempt: true,
+ });
+ });
+
+ it('leaves Send now as an ordinary steer', () => {
+ renderQueue([queued({ id: 'q1' })]);
+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_send_now' }));
+ expect(mockSendQueuedNow).toHaveBeenCalledWith(expect.objectContaining({ id: 'q1' }));
+ });
+
+ /* Hiding it during the pause is the discoverability gap this button
+ closes: the pause is exactly when a user wants to cut the reply short. */
+ it('stays visible but disabled while paused on an approval', () => {
+ renderQueue([queued()], approvalPausedSteering);
+ expect(screen.getByTestId('queued-interrupt-now')).toBeDisabled();
+ });
+
+ /* The drain starts the next run before its epoch lands, so a control that
+ hid itself here would appear and vanish between queued sends. */
+ it('stays visible but disabled before the generation epoch lands', () => {
+ renderQueue([queued()], steeringWith({ canSteer: false }));
+ expect(screen.getByTestId('queued-interrupt-now')).toBeDisabled();
+ });
+
+ it('offers nothing once the run is over', () => {
+ renderQueue([queued()], steeringWith({ duringRunActive: false, canSteer: false }));
+ expect(screen.queryByTestId('queued-interrupt-now')).not.toBeInTheDocument();
+ });
+
+ /* A recovered row is consumed atomically only by a normal generation, so
+ escalating it would leave or duplicate its parked server copy. */
+ it('offers nothing on a recovered row', () => {
+ renderQueue([queued({ recoverySteerId: 'srv-1' })]);
+ expect(screen.queryByTestId('queued-interrupt-now')).not.toBeInTheDocument();
+ });
+ });
+});
diff --git a/client/src/components/Chat/Input/Composer/__tests__/Thinking.spec.tsx b/client/src/components/Chat/Input/Composer/__tests__/Thinking.spec.tsx
new file mode 100644
index 0000000000..795d1a380f
--- /dev/null
+++ b/client/src/components/Chat/Input/Composer/__tests__/Thinking.spec.tsx
@@ -0,0 +1,245 @@
+import React, { createRef } from 'react';
+import { ReasoningEffort } from 'librechat-data-provider';
+import { fireEvent, render, screen } from '@testing-library/react';
+import type { SettingDefinition, TConversation, TReasoningOverride } from 'librechat-data-provider';
+import type * as ReasoningModule from '../../Reasoning';
+import Thinking from '../Thinking';
+
+const mockSetValue = jest.fn();
+let mockPendingOverride: TReasoningOverride | undefined;
+let mockSetting = {
+ key: 'reasoning_effort',
+ type: 'enum',
+ default: 'low',
+ options: ['auto', 'low', 'high'],
+} as SettingDefinition;
+let mockConversation = {
+ conversationId: 'convo-1',
+ reasoning_effort: 'low',
+} as TConversation;
+const mockChatContext = React.createContext<{ conversation: TConversation | null }>({
+ conversation: mockConversation,
+});
+
+jest.mock('../../Reasoning', () => ({
+ ReasoningControl: jest.requireActual<typeof ReasoningModule>('../../Reasoning').ReasoningControl,
+ useComposerReasoning: () => ({
+ setting: mockSetting,
+ value:
+ mockPendingOverride ??
+ ({
+ key: mockSetting.key,
+ value: mockConversation[mockSetting.key as keyof TConversation] ?? mockSetting.default,
+ } as TReasoningOverride),
+ setValue: mockSetValue,
+ }),
+}));
+
+jest.mock('~/hooks/Generic/useReducedMotion', () => ({
+ __esModule: true,
+ default: () => true,
+}));
+
+jest.mock('~/hooks', () => ({
+ useLocalize: () => (key: string, options?: Record<string, string | number>) => {
+ if (options) {
+ return `${key}:${options['0'] ?? options.count}`;
+ }
+ return (
+ (
+ {
+ com_ui_auto: 'Auto',
+ com_ui_off: 'Off',
+ com_ui_low: 'Low',
+ com_ui_medium: 'Medium',
+ com_ui_high: 'High',
+ } as Record<string, string>
+ )[key] ?? key
+ );
+ },
+}));
+
+jest.mock('~/data-provider', () => ({
+ useGetStartupConfig: () => ({ data: { interface: { parameters: true } } }),
+}));
+
+jest.mock('~/Providers', () => ({
+ useChatContext: () =>
+ jest.requireActual<typeof import('react')>('react').useContext(mockChatContext),
+}));
+
+function renderInComposer({
+ disabled = false,
+ index = 0,
+}: { disabled?: boolean; index?: number } = {}) {
+ const textareaRef = createRef<HTMLTextAreaElement>();
+ const onComposerClick = jest.fn(() => textareaRef.current?.focus());
+ const tree = () => (
+ <mockChatContext.Provider value={{ conversation: mockConversation }}>
+ <div onClick={onComposerClick}>
+ <textarea ref={textareaRef} aria-label="Message input" />
+ <Thinking index={index} disabled={disabled} hasAddedConversation={false} />
+ </div>
+ </mockChatContext.Provider>
+ );
+ const view = render(tree());
+ return { ...view, onComposerClick, rerenderConversation: () => view.rerender(tree()) };
+}
+
+describe('Thinking', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ mockPendingOverride = undefined;
+ mockSetting = {
+ key: 'reasoning_effort',
+ type: 'enum',
+ default: 'low',
+ options: ['auto', 'low', 'high'],
+ } as unknown as SettingDefinition;
+ mockConversation = {
+ conversationId: 'convo-1',
+ reasoning_effort: 'low',
+ } as unknown as TConversation;
+ });
+
+ it('forwards the composer disabled state to the enum control', () => {
+ renderInComposer({ disabled: true });
+ const disclosure = screen.getByTestId('composer-thinking-button');
+
+ expect(disclosure).toBeDisabled();
+ expect(screen.queryByRole('radiogroup')).not.toBeInTheDocument();
+ });
+
+ it('stages a numeric budget selected from the secondary composer', () => {
+ mockSetting = {
+ key: 'thinkingBudget',
+ type: 'number',
+ default: 4096,
+ range: { min: -1, positiveMin: 128, max: 32768, step: 128 },
+ } as SettingDefinition;
+ renderInComposer({ index: 1 });
+
+ fireEvent.click(screen.getByRole('button', { name: /com_ui_reasoning_for_next_message/ }));
+ const slider = screen.getByRole('slider');
+ slider.focus();
+ fireEvent.keyDown(slider, { key: 'ArrowRight' });
+
+ expect(mockSetValue).toHaveBeenLastCalledWith({ key: 'thinkingBudget', value: 4224 });
+ });
+
+ it('shows staged one-shot effort without mutating the conversation', () => {
+ mockPendingOverride = { key: 'reasoning_effort', value: ReasoningEffort.high };
+ renderInComposer();
+
+ expect(screen.getByTestId('composer-thinking-button')).toHaveAccessibleName(
+ 'com_ui_composer_thinking_value:High',
+ );
+ fireEvent.click(screen.getByTestId('composer-thinking-button'));
+ fireEvent.click(screen.getByRole('radio', { name: 'Low' }));
+
+ expect(mockSetValue).toHaveBeenCalledWith({ key: 'reasoning_effort', value: 'low' });
+ expect(mockConversation.reasoning_effort).toBe('low');
+ });
+
+ it('keeps activation inside the control and supports arrow-key navigation', () => {
+ const { onComposerClick } = renderInComposer();
+ const disclosure = screen.getByTestId('composer-thinking-button');
+
+ disclosure.focus();
+ fireEvent.click(disclosure);
+
+ expect(onComposerClick).not.toHaveBeenCalled();
+ expect(screen.getByRole('radiogroup')).toBeVisible();
+ const low = screen.getByRole('radio', { name: 'Low' });
+ low.focus();
+ expect(low).toHaveFocus();
+
+ fireEvent.keyDown(low, { key: 'ArrowRight' });
+ expect(screen.getByRole('radio', { name: 'High' })).toHaveFocus();
+ });
+
+ it('keeps effort selection clicks from reaching the composer focus handler', () => {
+ const { onComposerClick } = renderInComposer();
+
+ fireEvent.click(screen.getByTestId('composer-thinking-button'));
+ onComposerClick.mockClear();
+ fireEvent.click(screen.getByRole('radio', { name: 'High' }));
+
+ expect(mockSetValue).toHaveBeenCalledWith({ key: 'reasoning_effort', value: 'high' });
+ expect(onComposerClick).not.toHaveBeenCalled();
+ });
+
+ it('aligns three radio hit areas with the visual stop midpoints', () => {
+ mockSetting = {
+ key: 'reasoning_effort',
+ type: 'enum',
+ default: 'low',
+ options: ['auto', 'low', 'medium', 'high'],
+ } as unknown as SettingDefinition;
+ renderInComposer();
+
+ fireEvent.click(screen.getByTestId('composer-thinking-button'));
+ const [low, medium, high] = screen.getAllByRole('radio');
+
+ expect(low.style.left).toBe('0px');
+ expect(low.style.right).toBe('calc(75% - 7px)');
+ expect(medium.style.left).toBe('calc(25% + 7px)');
+ expect(medium.style.right).toBe('calc(25% + 7px)');
+ expect(high.style.left).toBe('calc(75% - 7px)');
+ expect(high.style.right).toBe('0px');
+ });
+
+ it('uses the provider mapping for an unset Bedrock effort', () => {
+ mockSetting = {
+ key: 'reasoning_effort',
+ type: 'enum',
+ default: 'unset',
+ options: ['unset', 'low', 'medium', 'high'],
+ enumMappings: {
+ unset: 'com_ui_off',
+ low: 'com_ui_low',
+ medium: 'com_ui_medium',
+ high: 'com_ui_high',
+ },
+ } as unknown as SettingDefinition;
+ mockConversation = {
+ conversationId: 'convo-1',
+ reasoning_effort: 'unset',
+ } as unknown as TConversation;
+ renderInComposer();
+
+ expect(screen.getByTestId('composer-thinking-button')).toHaveAccessibleName(
+ 'com_ui_composer_thinking_value:Off',
+ );
+
+ fireEvent.click(screen.getByTestId('composer-thinking-button'));
+ const off = screen.getByRole('button', { name: 'Off' });
+ expect(off).toHaveAttribute('aria-pressed', 'true');
+ fireEvent.click(off);
+ expect(mockSetValue).toHaveBeenCalledWith({ key: 'reasoning_effort', value: 'low' });
+ });
+
+ it('does not carry a remembered level across model settings', () => {
+ mockConversation = {
+ conversationId: 'convo-1',
+ endpoint: 'openAI',
+ model: 'model-a',
+ reasoning_effort: 'high',
+ } as unknown as TConversation;
+ const { rerenderConversation } = renderInComposer();
+
+ fireEvent.click(screen.getByTestId('composer-thinking-button'));
+ expect(screen.getByRole('radio', { name: 'High' })).toHaveAttribute('tabindex', '0');
+
+ mockConversation = {
+ ...mockConversation,
+ reasoning_effort: 'auto',
+ } as unknown as TConversation;
+ rerenderConversation();
+ expect(screen.getByRole('radio', { name: 'High' })).toHaveAttribute('tabindex', '0');
+
+ mockConversation = { ...mockConversation, model: 'model-b' };
+ rerenderConversation();
+ expect(screen.getByRole('radio', { name: 'Low' })).toHaveAttribute('tabindex', '0');
+ });
+});
diff --git a/client/src/components/Chat/Input/Composer/__tests__/Tray.spec.tsx b/client/src/components/Chat/Input/Composer/__tests__/Tray.spec.tsx
new file mode 100644
index 0000000000..d1a17149d9
--- /dev/null
+++ b/client/src/components/Chat/Input/Composer/__tests__/Tray.spec.tsx
@@ -0,0 +1,145 @@
+import React from 'react';
+import { render, screen, fireEvent, within } from '@testing-library/react';
+import type { ComposerItem } from '~/hooks/Input/useComposerItems';
+import type { ExtendedFile } from '~/common';
+import Tray from '../Tray';
+
+const mockFileRow = jest.fn();
+const mockIsPastedTextFile = jest.fn(() => false);
+const mockIsPasteActionPending = jest.fn(() => false);
+const mockEditPastedText = jest.fn();
+const mockMovePastedTextInline = jest.fn();
+
+jest.mock('~/hooks', () => ({
+ useLocalize: () => (key: string) => key,
+ useFileHandlingNoChatContext: () => ({ abortUpload: jest.fn() }),
+}));
+
+/* Files keep their own component, with its own upload/delete stack; the tray's
+ job is to hand it the staged map, which is what is asserted here. */
+jest.mock('../../Files/FileRow', () => ({
+ __esModule: true,
+ default: (props: { files: Map<string, unknown> } & Record<string, unknown>) => {
+ mockFileRow(props);
+ return props.files.size > 0 ? <div data-testid="file-row">{props.files.size}</div> : null;
+ },
+}));
+
+const item = (overrides: Partial<ComposerItem> = {}): ComposerItem => ({
+ id: 'quote:0',
+ kind: 'quote',
+ label: 'the second paragraph',
+ title: 'the second paragraph',
+ remove: jest.fn(),
+ ...overrides,
+});
+
+function renderTray(
+ items: ComposerItem[],
+ files: Map<string, ExtendedFile> = new Map(),
+ focusComposer?: jest.Mock,
+) {
+ return render(
+ <Tray
+ items={items}
+ conversation={null}
+ files={files}
+ setFiles={jest.fn()}
+ setFilesLoading={jest.fn()}
+ isRTL={false}
+ index={0}
+ isPastedTextFile={mockIsPastedTextFile}
+ isPasteActionPending={mockIsPasteActionPending}
+ onEditPastedText={mockEditPastedText}
+ onMovePastedTextInline={mockMovePastedTextInline}
+ focusComposer={focusComposer}
+ />,
+ );
+}
+
+describe('Tray', () => {
+ beforeEach(() => jest.clearAllMocks());
+
+ it('renders nothing when no context is staged', () => {
+ const { container } = renderTray([]);
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it('groups every staged kind under one labelled chip list', () => {
+ renderTray(
+ [
+ item({ id: 'quote:0', kind: 'quote', label: 'the second paragraph' }),
+ item({ id: 'skill:a', kind: 'skill', label: 'code-review' }),
+ ],
+ new Map([['f1', {} as ExtendedFile]]),
+ );
+
+ expect(screen.getByTestId('composer-tray')).toBeInTheDocument();
+ expect(screen.getByTestId('file-row')).toBeInTheDocument();
+ const chipList = screen.getByRole('list', { name: 'com_ui_composer_staged_context' });
+ expect(chipList).toContainElement(screen.getByTestId('composer-chip-quote'));
+ expect(chipList).toContainElement(screen.getByTestId('composer-chip-skill'));
+ });
+
+ it('labels each remove button for its own kind', () => {
+ renderTray([
+ item({ id: 'quote:0', kind: 'quote', label: 'excerpt' }),
+ item({ id: 'skill:a', kind: 'skill', label: 'code-review' }),
+ ]);
+
+ expect(screen.getByLabelText('com_ui_remove_quote')).toBeInTheDocument();
+ expect(screen.getByLabelText('com_ui_remove_skill')).toBeInTheDocument();
+ });
+
+ it('invokes the item own remove handler', () => {
+ const remove = jest.fn();
+ renderTray([item({ remove })]);
+ fireEvent.click(screen.getByLabelText('com_ui_remove_quote'));
+ expect(remove).toHaveBeenCalledTimes(1);
+ });
+ it('returns focus to the composer when the last quote is dismissed', () => {
+ const focusComposer = jest.fn();
+ const remove = jest.fn();
+ renderTray([item({ id: 'quote:0', remove })], new Map(), focusComposer);
+
+ fireEvent.click(screen.getByLabelText('com_ui_remove_quote'));
+ expect(remove).toHaveBeenCalledTimes(1);
+ expect(focusComposer).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps focus on the quotes while another one remains', () => {
+ const focusComposer = jest.fn();
+ const remove = jest.fn();
+ renderTray(
+ [item({ id: 'quote:0', remove }), item({ id: 'quote:1', label: 'another excerpt' })],
+ new Map(),
+ focusComposer,
+ );
+
+ fireEvent.click(
+ within(screen.getAllByTestId('composer-chip-quote')[0]).getByLabelText('com_ui_remove_quote'),
+ );
+ expect(remove).toHaveBeenCalledTimes(1);
+ expect(focusComposer).not.toHaveBeenCalled();
+ });
+
+ it('opens for staged files even with nothing else in it', () => {
+ renderTray([], new Map([['f1', {} as ExtendedFile]]));
+ expect(screen.getByTestId('composer-tray')).toBeInTheDocument();
+ expect(screen.getByTestId('file-row')).toBeInTheDocument();
+ });
+
+ it('forwards pasted-text actions to the staged file row', () => {
+ renderTray([], new Map([['f1', {} as ExtendedFile]]));
+
+ expect(mockFileRow).toHaveBeenCalledWith(
+ expect.objectContaining({
+ index: 0,
+ isPastedTextFile: mockIsPastedTextFile,
+ isPasteActionPending: mockIsPasteActionPending,
+ onEditPastedText: mockEditPastedText,
+ onMovePastedTextInline: mockMovePastedTextInline,
+ }),
+ );
+ });
+});
diff --git a/client/src/components/Chat/Input/Composer/__tests__/semanticTokens.spec.ts b/client/src/components/Chat/Input/Composer/__tests__/semanticTokens.spec.ts
new file mode 100644
index 0000000000..6b100c3f82
--- /dev/null
+++ b/client/src/components/Chat/Input/Composer/__tests__/semanticTokens.spec.ts
@@ -0,0 +1,40 @@
+import { join } from 'node:path';
+import { readdirSync, readFileSync } from 'node:fs';
+
+const composerRoot = join(__dirname, '..');
+
+const collectSourceModules = (directory: string): string[] =>
+ readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
+ const sourcePath = join(directory, entry.name);
+
+ if (entry.isDirectory()) {
+ return entry.name === '__tests__' ? [] : collectSourceModules(sourcePath);
+ }
+
+ return entry.isFile() && /\.tsx?$/.test(entry.name) ? [sourcePath] : [];
+ });
+
+const composerModules = collectSourceModules(composerRoot);
+
+const protectedModules = [
+ ...composerModules,
+ join(__dirname, '..', '..', 'Reasoning.tsx'),
+ join(__dirname, '..', '..', 'EscalateNowButton.tsx'),
+ join(__dirname, '..', '..', '..', 'Messages', 'Content', 'Parts', 'PendingSteers.tsx'),
+ join(__dirname, '..', '..', '..', '..', '..', 'hooks', 'Input', 'usePaletteEntries.tsx'),
+];
+
+describe('composer semantic color guardrail', () => {
+ it('keeps the composer seam free of direct palette and raw colors', () => {
+ const directPalette =
+ /(?:bg|text|border|ring|from|via|to|fill|stroke)-(?:(?:slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d|white\b|black\b)/;
+ const rawColor = /#[0-9a-f]{3,8}\b|(?:rgb|hsl)a?\(/i;
+
+ protectedModules.forEach((modulePath) => {
+ const source = readFileSync(modulePath, 'utf8');
+
+ expect(source).not.toMatch(directPalette);
+ expect(source).not.toMatch(rawColor);
+ });
+ });
+});
diff --git a/client/src/components/Chat/Input/Composer/__tests__/state.spec.ts b/client/src/components/Chat/Input/Composer/__tests__/state.spec.ts
new file mode 100644
index 0000000000..996d6797d3
--- /dev/null
+++ b/client/src/components/Chat/Input/Composer/__tests__/state.spec.ts
@@ -0,0 +1,19 @@
+import { createStore } from 'jotai';
+import { Constants, ReasoningEffort } from 'librechat-data-provider';
+import { getReasoningStateKey, pendingReasoningOverrideFamily } from '../state';
+
+describe('composer reasoning state', () => {
+ it('isolates unsaved split panes that share the new-conversation sentinel', () => {
+ const firstKey = getReasoningStateKey(Constants.NEW_CONVO, 0);
+ const secondKey = getReasoningStateKey(Constants.NEW_CONVO, 1);
+ const store = createStore();
+
+ store.set(pendingReasoningOverrideFamily(firstKey), {
+ key: 'reasoning_effort',
+ value: ReasoningEffort.high,
+ });
+
+ expect(firstKey).not.toBe(secondKey);
+ expect(store.get(pendingReasoningOverrideFamily(secondKey))).toBeUndefined();
+ });
+});
diff --git a/client/src/components/Chat/Input/Composer/state.ts b/client/src/components/Chat/Input/Composer/state.ts
new file mode 100644
index 0000000000..712b716e77
--- /dev/null
+++ b/client/src/components/Chat/Input/Composer/state.ts
@@ -0,0 +1,40 @@
+import { atom } from 'jotai';
+import { atomFamily } from 'jotai/utils';
+import { Constants } from 'librechat-data-provider';
+import type { TMessage } from 'librechat-data-provider';
+import type { createStore } from 'jotai';
+
+/** Unsaved split panes share the sentinel conversation id, so include the pane
+ * index until a durable id exists. Saved conversations keep their stable id. */
+export const getReasoningStateKey = (
+ conversationId: string | null | undefined,
+ index: string | number,
+) =>
+ conversationId == null || conversationId === '' || conversationId === Constants.NEW_CONVO
+ ? `${Constants.NEW_CONVO}:${index}`
+ : conversationId;
+
+/** One-shot reasoning selection owned by the composer for its next full turn. */
+export const pendingReasoningOverrideFamily = atomFamily((_conversationId: string) =>
+ atom<TMessage['reasoningOverride']>(undefined),
+);
+
+/** Landing-page lift is composer-owned UI state, scoped to its split pane. */
+export const composerLiftFamily = atomFamily((_index: number) => atom(0));
+
+/** Release every staged reasoning selection except the `keep` keys. A selection
+ * survives navigation by design, so members of conversations no longer on
+ * screen still hold one; clearing only the mounted panes would carry them
+ * across a sign-out. */
+export const clearPendingReasoningOverrides = (
+ jotaiStore: ReturnType<typeof createStore>,
+ keep: ReadonlySet<string> = new Set(),
+) => {
+ for (const key of Array.from(pendingReasoningOverrideFamily.getParams())) {
+ if (keep.has(key)) {
+ continue;
+ }
+ jotaiStore.set(pendingReasoningOverrideFamily(key), undefined);
+ pendingReasoningOverrideFamily.remove(key);
+ }
+};
diff --git a/client/src/components/Chat/Input/DuringRunSendButton.tsx b/client/src/components/Chat/Input/DuringRunSendButton.tsx
index 2b09f60c2d..0d75215496 100644
--- a/client/src/components/Chat/Input/DuringRunSendButton.tsx
+++ b/client/src/components/Chat/Input/DuringRunSendButton.tsx
@@ -24,26 +24,26 @@ type DuringRunSendButtonProps = {
onConsumed: () => void;
/** External hold (e.g. uploads in flight), mirroring the normal send button. */
disabled?: boolean;
+ /** Host-owned: whether Enter sends, so the rows advertise what the key handler does. */
+ enterToSend: boolean;
};
/**
* The send button while a run is generating: it takes over the send/stop slot
* (and `submitButtonRef`, so Enter's synthetic click routes here) whenever the
- * composer holds text — submitting steers or queues per the effective action.
+ * composer holds text: submitting steers or queues per the effective action.
* Hovering it reveals the full action list with its shortcuts: steer, queue
* (⌘/Ctrl+Enter routes to the non-default action), interrupt & steer
- * (⌘/Ctrl+Shift+Enter — requests an earlier safe point when a conversation
- * exists, otherwise stops and sends a new turn), and
- * interrupt & send (⌥/Alt+Enter — discards the answer and starts over).
+ * (⌘/Ctrl+Shift+Enter: stops writing now but keeps what is written), and
+ * interrupt & send (⌥/Alt+Enter: discards the answer and starts over).
* Clearing the composer restores the Stop button.
*/
const DuringRunSendButton = React.memo(
forwardRef((props: DuringRunSendButtonProps, ref: React.ForwardedRef<HTMLButtonElement>) => {
const localize = useLocalize();
const steerInterruptsByDefault = useRecoilValue(store.steerInterruptsByDefault);
- const enterToSend = useRecoilValue(store.enterToSend);
const { shortcutsEnabled, submitOverride, yieldedChords } = useComposerBindings();
- const { steering } = props;
+ const { steering, enterToSend } = props;
const data = useWatch({ control: props.control });
const content = data?.text?.trim();
const primary = steering.effectiveAction;
@@ -126,17 +126,16 @@ const DuringRunSendButton = React.memo(
key: 'steer',
label: localize('com_ui_steer'),
kbd: steerKbd,
- icon: <Zap className="h-4 w-4 text-status-warning" aria-hidden="true" />,
- // Gate on availability, not the default action — the row exists to
- // override a queue-preferring default with an explicit steer.
- disabled: !steering.canSteer,
+ icon: <Zap className="text-status-warning h-4 w-4" aria-hidden="true" />,
+ // A staged reasoning choice is a queued full turn, not a live steer.
+ disabled: !steering.canSteer || steering.pendingReasoningOverride != null,
onClick: () => runAction((text) => steering.steerFromComposer(text)),
};
const queueRow: ActionRow = {
key: 'queue',
label: localize('com_ui_queue'),
kbd: primary === 'queue' ? submitHint : alternateHint,
- icon: <Clock className="h-4 w-4 text-status-info" aria-hidden="true" />,
+ icon: <Clock className="text-status-info h-4 w-4" aria-hidden="true" />,
onClick: () => runAction((text) => steering.queueFromComposer(text)),
};
/** When steering is available, keeps visible text; a new chat instead hard-stops. */
@@ -146,19 +145,18 @@ const DuringRunSendButton = React.memo(
props.isNewConversation ? 'com_ui_steer_first_turn_stop' : 'com_ui_interrupt_steer',
),
kbd: interruptSteerKbd,
- icon: <ZapOff className="h-4 w-4 text-status-warning" aria-hidden="true" />,
- // Matches the standalone button's gate, and deliberately NOT
- // `!canSteer` like the steer row above: `canSteer` is also false before
- // a conversation exists, where `interruptSteer` falls back to interrupt
- // & send and this row must stay live for the whole first turn.
- disabled: steering.pausedOnApproval || !steering.canControlGeneration,
+ icon: <ZapOff className="text-status-warning h-4 w-4" aria-hidden="true" />,
+ disabled:
+ steering.pausedOnApproval ||
+ !steering.canControlGeneration ||
+ steering.pendingReasoningOverride != null,
onClick: () => runAction((text) => steering.interruptSteer(text)),
};
const interruptRow: ActionRow = {
key: 'interrupt',
label: localize('com_ui_interrupt_send'),
kbd: verdicts.altEnter === 'interrupt' ? altEnter : undefined,
- icon: <OctagonPause className="h-4 w-4 text-status-error" aria-hidden="true" />,
+ icon: <OctagonPause className="text-status-error h-4 w-4" aria-hidden="true" />,
disabled: !steering.canControlGeneration,
onClick: () => runAction((text) => steering.interruptAndSend(text)),
};
@@ -176,7 +174,6 @@ const DuringRunSendButton = React.memo(
<button
ref={ref}
aria-label={label}
- id="during-run-send-button"
disabled={!content || props.disabled === true}
className={composerSubmitClasses()}
data-testid="during-run-send-button"
diff --git a/client/src/components/Chat/Input/EditBadges.tsx b/client/src/components/Chat/Input/EditBadges.tsx
deleted file mode 100644
index dcf5bb471f..0000000000
--- a/client/src/components/Chat/Input/EditBadges.tsx
+++ /dev/null
@@ -1,87 +0,0 @@
-import React, { useCallback } from 'react';
-import { Edit3, Check, X } from 'lucide-react';
-import { Button, Badge } from '@librechat/client';
-import type { LucideIcon } from 'lucide-react';
-import type { BadgeItem } from '~/common';
-import { useChatBadges, useLocalize } from '~/hooks';
-
-interface EditBadgesProps {
- isEditingChatBadges: boolean;
- handleCancelBadges: () => void;
- handleSaveBadges: () => void;
- setBadges: React.Dispatch<React.SetStateAction<Pick<BadgeItem, 'id'>[]>>;
-}
-
-const EditBadgesComponent = ({
- isEditingChatBadges,
- handleCancelBadges,
- handleSaveBadges,
- setBadges,
-}: EditBadgesProps) => {
- const localize = useLocalize();
- const allBadges = useChatBadges() || [];
- const unavailableBadges = allBadges.filter((badge) => !badge.isAvailable);
-
- const handleRestoreBadge = useCallback(
- (badgeId: string) => {
- setBadges((prev: Pick<BadgeItem, 'id'>[]) => [...prev, { id: badgeId }]);
- },
- [setBadges],
- );
-
- if (!isEditingChatBadges) {
- return null;
- }
-
- return (
- <div className="bg-surface-secondary-alt m-1.5 flex flex-col overflow-hidden rounded-t-2xl rounded-b-lg">
- <div className="flex items-center gap-4 py-2 pr-1.5 pl-3 text-sm">
- <span className="mt-0 flex size-6 shrink-0 items-center justify-center">
- <div className="icon-md">
- <Edit3 className="icon-md" aria-hidden="true" />
- </div>
- </span>
- <span className="text-text-secondary line-clamp-3 flex-1 py-0.5 font-semibold">
- {localize('com_ui_save_badge_changes')}
- </span>
- <div className="flex h-8 gap-2">
- <Button
- size="sm"
- variant="destructive"
- aria-label="Cancel"
- onClick={handleCancelBadges}
- className="h-8"
- >
- <X className="icon-md" aria-hidden="true" />
- </Button>
- <Button
- size="sm"
- variant="submit"
- aria-label="Save changes"
- onClick={handleSaveBadges}
- className="h-8 rounded-tr-xl rounded-b-lg"
- >
- <Check className="icon-md" aria-hidden="true" />
- </Button>
- </div>
- </div>
- {unavailableBadges && unavailableBadges.length > 0 && (
- <div className="flex flex-wrap items-center gap-2 p-2">
- {unavailableBadges.map((badge) => (
- <div key={badge.id} className="badge-icon">
- <Badge
- icon={badge.icon as unknown as LucideIcon}
- label={badge.label}
- isAvailable={false}
- isEditing={true}
- onBadgeAction={() => handleRestoreBadge(badge.id)}
- />
- </div>
- ))}
- </div>
- )}
- </div>
- );
-};
-
-export default React.memo(EditBadgesComponent);
diff --git a/client/src/components/Chat/Input/EscalateNowButton.tsx b/client/src/components/Chat/Input/EscalateNowButton.tsx
new file mode 100644
index 0000000000..985b4626a5
--- /dev/null
+++ b/client/src/components/Chat/Input/EscalateNowButton.tsx
@@ -0,0 +1,176 @@
+import { useEffect, useId, useSyncExternalStore } from 'react';
+import { ArrowUp } from 'lucide-react';
+import * as Ariakit from '@ariakit/react';
+import { IconButton } from '@librechat/client';
+import { useShortcutAriaKey, useShortcutDisplay } from '~/hooks/useKeyboardShortcuts';
+import { getChatPane, getFocusedChatPane } from '~/utils/pane';
+import { useLocalize } from '~/hooks';
+import { cn } from '~/utils';
+
+/** Longest message excerpt spoken as part of the button's accessible name;
+ * past this the row is identified by its opening words rather than read out. */
+const MESSAGE_LABEL_MAX_LENGTH = 80;
+
+/* Which escalation control the keyboard shortcut acts on. Module state rather
+ than context: the shortcut handler lives at the document level and only ever
+ needs the single hovered/focused target, so every button subscribing to one
+ store is cheaper than a provider spanning both surfaces. Focus wins over
+ hover, matching what a keyboard user is actually pointed at. A hovered button
+ in a pane that does not hold focus is not the target, since the shortcut acts
+ in the focused pane; focus moves re-evaluate that. */
+const listeners = new Set<() => void>();
+let hovered: { id: string; element: Element } | null = null;
+let focusedTarget: string | null = null;
+
+function isInFocusedPane(element: Element) {
+ const focusedPane = getFocusedChatPane();
+ return focusedPane == null || getChatPane(element) === focusedPane;
+}
+
+function getActiveTarget() {
+ if (focusedTarget != null) {
+ return focusedTarget;
+ }
+ return hovered != null && isInFocusedPane(hovered.element) ? hovered.id : null;
+}
+
+function notify() {
+ listeners.forEach((listener) => listener());
+}
+
+function subscribeToActiveTarget(listener: () => void) {
+ if (listeners.size === 0) {
+ document.addEventListener('focusin', notify);
+ document.addEventListener('focusout', notify);
+ }
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ if (listeners.size === 0) {
+ document.removeEventListener('focusin', notify);
+ document.removeEventListener('focusout', notify);
+ }
+ };
+}
+
+function updateActiveTarget(
+ kind: 'hover' | 'focus',
+ targetId: string,
+ active: boolean,
+ element?: Element,
+) {
+ const previous = getActiveTarget();
+ if (kind === 'hover') {
+ if (active && element != null) {
+ hovered = { id: targetId, element };
+ } else if (hovered?.id === targetId) {
+ hovered = null;
+ }
+ } else if (active) {
+ focusedTarget = targetId;
+ } else if (focusedTarget === targetId) {
+ focusedTarget = null;
+ }
+ if (previous !== getActiveTarget()) {
+ notify();
+ }
+}
+
+function clearActiveTarget(targetId: string) {
+ const previous = getActiveTarget();
+ if (hovered?.id === targetId) {
+ hovered = null;
+ }
+ if (focusedTarget === targetId) {
+ focusedTarget = null;
+ }
+ if (previous !== getActiveTarget()) {
+ notify();
+ }
+}
+
+interface EscalateNowButtonProps {
+ /** Which waiting surface this row belongs to; the `escalateSteer` shortcut
+ * prefers a bubble over a queued row when nothing is hovered or focused. */
+ surface: 'bubble' | 'queued';
+ disabled: boolean;
+ messageText: string;
+ onClick: (event: React.MouseEvent<HTMLButtonElement>) => void;
+}
+
+/**
+ * The escalation control on a waiting message: interrupt & steer it now, at
+ * the next safe token boundary. The tooltip teaches this action's OWN shortcut
+ * (registry-aware, so a rebinding shows correctly). Hover/focus marks this
+ * exact button as the shortcut's target; with no active row the shortcut keeps
+ * its newest-waiting-message fallback.
+ */
+export default function EscalateNowButton({
+ surface,
+ disabled,
+ messageText,
+ onClick,
+}: EscalateNowButtonProps) {
+ const localize = useLocalize();
+ const chord = useShortcutDisplay('escalateSteer');
+ const ariaKey = useShortcutAriaKey('escalateSteer');
+ const targetId = useId();
+ const activeTarget = useSyncExternalStore(subscribeToActiveTarget, getActiveTarget, () => null);
+ const isActive = !disabled && activeTarget === targetId;
+ const label = localize('com_ui_interrupt_steer_now');
+ const normalized = messageText.trim().replace(/\s+/g, ' ');
+ const characters = Array.from(normalized);
+ const excerpt =
+ characters.length > MESSAGE_LABEL_MAX_LENGTH
+ ? `${characters
+ .slice(0, MESSAGE_LABEL_MAX_LENGTH - 1)
+ .join('')
+ .trimEnd()}…`
+ : normalized;
+ const accessibleLabel = excerpt.length > 0 ? `${label}: ${excerpt}` : label;
+
+ /* A disabled button keeps neither hover nor focus, so a row that locks while
+ the pointer rests on it would otherwise leave the shortcut aimed at a
+ control that can no longer run. */
+ useEffect(() => {
+ if (disabled) {
+ clearActiveTarget(targetId);
+ }
+ return () => clearActiveTarget(targetId);
+ }, [disabled, targetId]);
+
+ return (
+ <Ariakit.TooltipProvider placement="top" timeout={300}>
+ {/* The disabled IconButton already renders at half opacity; 70% of that
+ is the 35% this control has always dimmed to. */}
+ <span className={cn('transition-opacity', disabled && 'opacity-70')}>
+ <Ariakit.TooltipAnchor
+ render={
+ <IconButton
+ label={accessibleLabel}
+ size="xs"
+ variant="primary"
+ aria-keyshortcuts={isActive ? ariaKey : undefined}
+ data-escalate-steer={surface}
+ data-escalate-steer-active={isActive ? 'true' : undefined}
+ data-testid={surface === 'queued' ? 'queued-interrupt-now' : 'steer-escalate-now'}
+ disabled={disabled}
+ onPointerEnter={(event) =>
+ !disabled && updateActiveTarget('hover', targetId, true, event.currentTarget)
+ }
+ onPointerLeave={() => updateActiveTarget('hover', targetId, false)}
+ onFocus={() => !disabled && updateActiveTarget('focus', targetId, true)}
+ onBlur={() => updateActiveTarget('focus', targetId, false)}
+ onClick={onClick}
+ >
+ <ArrowUp className="h-3.5 w-3.5" strokeWidth={2.4} aria-hidden="true" />
+ </IconButton>
+ }
+ />
+ </span>
+ <Ariakit.Tooltip className="bg-surface-tertiary text-text-primary z-50 rounded-lg px-2 py-1 text-xs shadow-lg">
+ {chord && isActive ? `${label} · ${chord}` : label}
+ </Ariakit.Tooltip>
+ </Ariakit.TooltipProvider>
+ );
+}
diff --git a/client/src/components/Chat/Input/FileSearch.tsx b/client/src/components/Chat/Input/FileSearch.tsx
deleted file mode 100644
index a0f359d517..0000000000
--- a/client/src/components/Chat/Input/FileSearch.tsx
+++ /dev/null
@@ -1,37 +0,0 @@
-import React, { memo } from 'react';
-import { CheckboxButton, VectorIcon } from '@librechat/client';
-import { PermissionTypes, Permissions } from 'librechat-data-provider';
-import { useLocalize, useHasAccess } from '~/hooks';
-import { useBadgeRowContext } from '~/Providers';
-import { badgeAccents } from './accents';
-
-function FileSearch() {
- const localize = useLocalize();
- const context = useBadgeRowContext();
- const { toggleState: fileSearchEnabled, debouncedChange, isPinned } = context?.fileSearch ?? {};
-
- const canUseFileSearch = useHasAccess({
- permissionType: PermissionTypes.FILE_SEARCH,
- permission: Permissions.USE,
- });
-
- if (!canUseFileSearch) {
- return null;
- }
-
- return (
- <>
- {(fileSearchEnabled || isPinned) && (
- <CheckboxButton
- checked={fileSearchEnabled}
- setValue={debouncedChange}
- label={localize('com_assistants_file_search')}
- isCheckedClassName={badgeAccents.green}
- icon={<VectorIcon className="icon-md" />}
- />
- )}
- </>
- );
-}
-
-export default memo(FileSearch);
diff --git a/client/src/components/Chat/Input/Files/AttachFileChat.tsx b/client/src/components/Chat/Input/Files/AttachFileChat.tsx
deleted file mode 100644
index 5395b8351b..0000000000
--- a/client/src/components/Chat/Input/Files/AttachFileChat.tsx
+++ /dev/null
@@ -1,114 +0,0 @@
-import { memo, useMemo } from 'react';
-import {
- Constants,
- supportsFiles,
- mergeFileConfig,
- isAgentsEndpoint,
- isEphemeralAgentId,
- isAssistantsEndpoint,
- getEndpointFileConfig,
-} from 'librechat-data-provider';
-import type { TConversation } from 'librechat-data-provider';
-import type { ExtendedFile, FileSetter } from '~/common';
-import useAgentUploadTarget from '~/hooks/Agents/useAgentUploadTarget';
-import { useGetFileConfig } from '~/data-provider';
-import { isUnifiedUploadMode } from '~/utils';
-import AttachFileMenu from './AttachFileMenu';
-import AttachFile from './AttachFile';
-
-function AttachFileChat({
- disableInputs,
- conversation,
- files,
- setFiles,
- setFilesLoading,
-}: {
- disableInputs: boolean;
- conversation: TConversation | null;
- files: Map<string, ExtendedFile>;
- setFiles: FileSetter;
- setFilesLoading: React.Dispatch<React.SetStateAction<boolean>>;
-}) {
- const conversationId = conversation?.conversationId ?? Constants.NEW_CONVO;
- const { endpoint } = conversation ?? { endpoint: null };
- const isAgents = useMemo(() => isAgentsEndpoint(endpoint), [endpoint]);
- const isAssistants = useMemo(() => isAssistantsEndpoint(endpoint), [endpoint]);
-
- const { agentProvider, endpointType, useResponsesApi } = useAgentUploadTarget(conversation);
-
- /* Success, not merely settled: a failed or paused fetch leaves the built-in defaults in
- * place, where the absent opt-out reads as unified. */
- const { data: fileConfig = null, isSuccess: isFileConfigLoaded } = useGetFileConfig({
- select: (data) => mergeFileConfig(data),
- });
-
- const fileConfigEndpoint = useMemo(
- () => (isAgents && agentProvider ? agentProvider : endpoint),
- [isAgents, agentProvider, endpoint],
- );
- const endpointFileConfig = useMemo(
- () =>
- getEndpointFileConfig({
- fileConfig,
- endpointType,
- endpoint: fileConfigEndpoint,
- }),
- [fileConfigEndpoint, fileConfig, endpointType],
- );
- const endpointSupportsFiles: boolean = useMemo(
- () => supportsFiles[endpointType ?? endpoint ?? ''] ?? false,
- [endpointType, endpoint],
- );
- const isUploadDisabled = useMemo(
- () => (disableInputs || endpointFileConfig?.disabled) ?? false,
- [disableInputs, endpointFileConfig?.disabled],
- );
- /* A saved agent's policy lives under its provider, so nothing is resolved for it until
- * that provider is known; until then endpointFileConfig is the generic agents entry.
- * An ephemeral agent has no record to fetch, so waiting on one never ends. */
- const isSavedAgent =
- isAgents && conversation?.agent_id != null && !isEphemeralAgentId(conversation.agent_id);
- const isPolicyResolved = isFileConfigLoaded && (!isSavedAgent || agentProvider != null);
-
- /* Resolved here rather than in the menu: an unresolved config reads as unified, which
- * would show the wrong uploader on a legacy deployment. */
- const isUnifiedMode = useMemo(
- () => isUnifiedUploadMode(endpointFileConfig, isPolicyResolved),
- [endpointFileConfig, isPolicyResolved],
- );
-
- if (isAssistants && endpointSupportsFiles && !isUploadDisabled) {
- return (
- <AttachFile
- disabled={disableInputs}
- files={files}
- setFiles={setFiles}
- setFilesLoading={setFilesLoading}
- conversation={conversation}
- />
- );
- } else if ((isAgents || endpointSupportsFiles) && !isUploadDisabled) {
- return (
- <AttachFileMenu
- endpoint={endpoint}
- /* Inert until the config resolves: the menu is an action, not just a display, and
- * offering the chooser here submits an explicit destination a unified deployment
- * would have inferred. The drag and paste paths hold for the same reason. */
- disabled={disableInputs || !isPolicyResolved}
- endpointType={endpointType}
- conversationId={conversationId}
- agentId={conversation?.agent_id}
- endpointFileConfig={endpointFileConfig}
- isUnifiedMode={isUnifiedMode}
- useResponsesApi={useResponsesApi}
- files={files}
- setFiles={setFiles}
- setFilesLoading={setFilesLoading}
- conversation={conversation}
- />
- );
- }
- return null;
-}
-
-export default memo(AttachFileChat);
diff --git a/client/src/components/Chat/Input/Files/AttachFileMenu.tsx b/client/src/components/Chat/Input/Files/AttachFileMenu.tsx
deleted file mode 100644
index e3c259f4e9..0000000000
--- a/client/src/components/Chat/Input/Files/AttachFileMenu.tsx
+++ /dev/null
@@ -1,471 +0,0 @@
-import React, { useRef, useState, useMemo, useCallback } from 'react';
-import { useRecoilState } from 'recoil';
-import * as Ariakit from '@ariakit/react';
-import {
- FileSearch,
- ImageUpIcon,
- FileType2Icon,
- FileImageIcon,
- TerminalSquareIcon,
-} from 'lucide-react';
-import {
- IconButton,
- FileUpload,
- TooltipAnchor,
- DropdownPopup,
- AttachmentIcon,
- SharePointIcon,
-} from '@librechat/client';
-import {
- Providers,
- EToolResources,
- EModelEndpoint,
- isExplicitMimeConfig,
- getConfiguredMimeAccept,
- bedrockDocumentMimeTypes,
- defaultAgentCapabilities,
- bedrockDocumentExtensions,
- isDocumentSupportedProvider,
-} from 'librechat-data-provider';
-import type {
- TConversation,
- EndpointFileConfig,
- MimeUploadCapability,
-} from 'librechat-data-provider';
-import type { ExtendedFile, FileSetter } from '~/common';
-import {
- useAgentToolPermissions,
- useAgentCapabilities,
- useGetAgentsConfig,
- useFileHandlingNoChatContext,
- useLocalize,
-} from '~/hooks';
-import { useSharePointFileHandlingNoChatContext } from '~/hooks/Files/useSharePointFileHandling';
-import { useShortcutAriaKey, useShortcutHint } from '~/hooks/useKeyboardShortcuts';
-import { SharePointPickerDialog } from '~/components/SharePoint';
-import { useGetStartupConfig } from '~/data-provider';
-import { ephemeralAgentByConvoId } from '~/store';
-import { MenuItemProps } from '~/common';
-import { cn } from '~/utils';
-
-type FileUploadType =
- | 'image'
- | 'document'
- | 'image_document'
- | 'image_document_extended'
- | 'image_document_video_audio'
- | 'image_document_video_audio_configured';
-
-/** What each provider upload path can actually send, used to scope the picker filter to selectable files. */
-const fileTypeCapabilities: Record<FileUploadType, MimeUploadCapability> = {
- image: { categories: ['image'] },
- document: { categories: ['document'] },
- image_document: { categories: ['image', 'document'] },
- image_document_extended: {
- categories: ['image', 'document'],
- documentMimeTypes: bedrockDocumentMimeTypes,
- },
- /** Google/Vertex/OpenRouter media path: documents are limited to PDF (see isProviderAttachType). */
- image_document_video_audio: {
- categories: ['image', 'document', 'audio', 'video'],
- documentMimeTypes: ['application/pdf'],
- },
- /** Custom endpoint with an admin-configured allowlist: the config decides, including video/audio. */
- image_document_video_audio_configured: {
- categories: ['image', 'document', 'audio', 'video'],
- },
-};
-
-interface AttachFileMenuProps {
- agentId?: string | null;
- endpoint?: string | null;
- disabled?: boolean | null;
- conversationId: string;
- endpointType?: EModelEndpoint | string;
- endpointFileConfig?: EndpointFileConfig;
- /** Resolved by the parent, which knows whether the file config has landed. */
- isUnifiedMode: boolean;
- useResponsesApi?: boolean;
- files: Map<string, ExtendedFile>;
- setFiles: FileSetter;
- setFilesLoading: React.Dispatch<React.SetStateAction<boolean>>;
- conversation: TConversation | null;
-}
-
-const AttachFileMenu = ({
- agentId,
- endpoint,
- disabled,
- endpointType,
- conversationId,
- endpointFileConfig,
- isUnifiedMode,
- useResponsesApi,
- files,
- setFiles,
- setFilesLoading,
- conversation,
-}: AttachFileMenuProps) => {
- const localize = useLocalize();
- const isUploadDisabled = disabled ?? false;
- const inputRef = useRef<HTMLInputElement>(null);
- const [isPopoverActive, setIsPopoverActive] = useState(false);
- const uploadFileTooltip = useShortcutHint('uploadFile', localize('com_sidepanel_attach_files'));
- const uploadFileAriaKey = useShortcutAriaKey('uploadFile');
- const [ephemeralAgent, setEphemeralAgent] = useRecoilState(
- ephemeralAgentByConvoId(conversationId),
- );
- const toolResourceRef = useRef<EToolResources | undefined>();
- const { handleFileChange } = useFileHandlingNoChatContext(undefined, {
- files,
- setFiles,
- setFilesLoading,
- conversation,
- });
- const { handleSharePointFiles, isProcessing, downloadProgress } =
- useSharePointFileHandlingNoChatContext(
- { toolResource: toolResourceRef.current },
- { files, setFiles, setFilesLoading, conversation },
- );
-
- const { agentsConfig } = useGetAgentsConfig();
- const { data: startupConfig } = useGetStartupConfig();
- const sharePointEnabled = startupConfig?.sharePointFilePickerEnabled;
-
- const [isSharePointDialogOpen, setIsSharePointDialogOpen] = useState(false);
-
- /** TODO: Ephemeral Agent Capabilities
- * Allow defining agent capabilities on a per-endpoint basis
- * Use definition for agents endpoint for ephemeral agents
- * */
- const capabilities = useAgentCapabilities(agentsConfig?.capabilities ?? defaultAgentCapabilities);
-
- const { fileSearchAllowedByAgent, codeAllowedByAgent, provider } = useAgentToolPermissions(
- agentId,
- ephemeralAgent,
- );
-
- const handleUploadClick = useCallback(
- (fileType?: FileUploadType) => {
- if (!inputRef.current) {
- return;
- }
- inputRef.current.value = '';
- const configuredAccept =
- fileType !== undefined
- ? getConfiguredMimeAccept(
- endpointFileConfig?.supportedMimeTypes,
- fileTypeCapabilities[fileType],
- )
- : undefined;
- if (configuredAccept != null) {
- inputRef.current.accept = configuredAccept;
- } else if (fileType === 'image') {
- inputRef.current.accept = 'image/*,.heif,.heic';
- } else if (fileType === 'document') {
- inputRef.current.accept = '.pdf,application/pdf';
- } else if (fileType === 'image_document') {
- inputRef.current.accept = 'image/*,.heif,.heic,.pdf,application/pdf';
- } else if (fileType === 'image_document_extended') {
- inputRef.current.accept = `image/*,.heif,.heic,${bedrockDocumentExtensions}`;
- } else if (fileType === 'image_document_video_audio') {
- inputRef.current.accept = 'image/*,.heif,.heic,.pdf,application/pdf,video/*,audio/*';
- } else if (fileType === 'image_document_video_audio_configured') {
- /** Only reached with an explicit allowlist the accept string cannot represent; leave the
- * picker open so it never hides a file the admin allowed (backend still enforces). */
- inputRef.current.accept = '';
- } else {
- inputRef.current.accept = '';
- }
- inputRef.current.click();
- },
- [endpointFileConfig?.supportedMimeTypes],
- );
-
- /** Unified mode: single click triggers file upload with no tool_resource */
- const handleUnifiedUpload = useCallback(() => {
- toolResourceRef.current = undefined;
- handleUploadClick();
- }, [handleUploadClick]);
-
- /** Unified mode removed the destination chooser, not the source chooser. SharePoint has
- * no trigger of its own, so without this the picker becomes unreachable whenever the
- * composer is in unified mode. Destination stays implicit on both sources. */
- const unifiedSourceItems = useMemo<MenuItemProps[]>(
- () => [
- {
- label: localize('com_files_upload_local_machine'),
- onClick: handleUnifiedUpload,
- icon: <FileImageIcon className="icon-md" />,
- },
- {
- label: localize('com_files_upload_sharepoint'),
- onClick: () => {
- toolResourceRef.current = undefined;
- setIsSharePointDialogOpen(true);
- },
- icon: <SharePointIcon className="icon-md" />,
- },
- ],
- [localize, handleUnifiedUpload, setIsSharePointDialogOpen],
- );
-
- const dropdownItems = useMemo(() => {
- const setToolResource = (value: EToolResources | undefined) => {
- toolResourceRef.current = value;
- };
-
- const createMenuItems = (onAction: (fileType?: FileUploadType) => void) => {
- const items: MenuItemProps[] = [];
-
- let currentProvider = provider || endpoint;
-
- // This will be removed in a future PR to formally normalize Providers comparisons to be case insensitive
- if (currentProvider?.toLowerCase() === Providers.OPENROUTER) {
- currentProvider = Providers.OPENROUTER;
- }
-
- const isAzureWithResponsesApi =
- (currentProvider === EModelEndpoint.azureOpenAI ||
- endpointType === EModelEndpoint.azureOpenAI) &&
- useResponsesApi === true;
-
- if (
- isDocumentSupportedProvider(endpointType) ||
- isDocumentSupportedProvider(currentProvider) ||
- isAzureWithResponsesApi
- ) {
- items.push({
- label: localize('com_ui_upload_provider'),
- onClick: () => {
- setToolResource(undefined);
- let fileType: Exclude<FileUploadType, 'image' | 'document'> = 'image_document';
- if (currentProvider === Providers.GOOGLE || currentProvider === Providers.OPENROUTER) {
- fileType = 'image_document_video_audio';
- } else if (
- currentProvider === Providers.BEDROCK ||
- endpointType === EModelEndpoint.bedrock
- ) {
- fileType = 'image_document_extended';
- } else if (
- endpointType === EModelEndpoint.custom &&
- isExplicitMimeConfig(endpointFileConfig?.supportedMimeTypes)
- ) {
- fileType = 'image_document_video_audio_configured';
- }
- onAction(fileType);
- },
- icon: <FileImageIcon className="icon-md" />,
- });
- } else {
- items.push({
- label: localize('com_ui_upload_image_input'),
- onClick: () => {
- setToolResource(undefined);
- onAction('image');
- },
- icon: <ImageUpIcon className="icon-md" />,
- });
- }
-
- if (capabilities.contextEnabled) {
- items.push({
- label: localize('com_ui_upload_ocr_text'),
- onClick: () => {
- setToolResource(EToolResources.context);
- onAction();
- },
- icon: <FileType2Icon className="icon-md" />,
- });
- }
-
- if (capabilities.fileSearchEnabled && fileSearchAllowedByAgent) {
- items.push({
- label: localize('com_ui_upload_file_search'),
- onClick: () => {
- setToolResource(EToolResources.file_search);
- setEphemeralAgent((prev) => ({
- ...prev,
- [EToolResources.file_search]: true,
- }));
- onAction();
- },
- icon: <FileSearch className="icon-md" />,
- });
- }
-
- if (capabilities.codeEnabled && codeAllowedByAgent) {
- items.push({
- label: localize('com_ui_upload_code_environment'),
- onClick: () => {
- setToolResource(EToolResources.execute_code);
- setEphemeralAgent((prev) => ({
- ...prev,
- [EToolResources.execute_code]: true,
- }));
- onAction();
- },
- icon: <TerminalSquareIcon className="icon-md" />,
- });
- }
-
- return items;
- };
-
- const localItems = createMenuItems(handleUploadClick);
-
- if (sharePointEnabled) {
- const sharePointItems = createMenuItems(() => {
- setIsSharePointDialogOpen(true);
- // Note: toolResource will be set by the specific item clicked
- });
- localItems.push({
- label: localize('com_files_upload_sharepoint'),
- onClick: () => {},
- icon: <SharePointIcon className="icon-md" />,
- subItems: sharePointItems,
- });
- return localItems;
- }
-
- return localItems;
- }, [
- localize,
- endpoint,
- provider,
- endpointType,
- capabilities,
- useResponsesApi,
- handleUploadClick,
- setEphemeralAgent,
- sharePointEnabled,
- endpointFileConfig?.supportedMimeTypes,
- codeAllowedByAgent,
- fileSearchAllowedByAgent,
- setIsSharePointDialogOpen,
- ]);
-
- const menuTrigger = (
- <TooltipAnchor
- render={
- <Ariakit.MenuButton
- disabled={isUploadDisabled}
- id="attach-file-menu-button"
- aria-label="Attach File Options"
- aria-keyshortcuts={uploadFileAriaKey}
- className={cn(
- 'size-theme-control rounded-theme-control-round duration-theme-fast hover:bg-surface-composer-hover focus-visible:ring-text-primary/50 flex items-center justify-center p-1 transition-colors focus-visible:ring-2 focus-visible:outline-hidden',
- isPopoverActive && 'bg-surface-composer-hover',
- )}
- >
- <div className="flex w-full items-center justify-center gap-2">
- <AttachmentIcon />
- </div>
- </Ariakit.MenuButton>
- }
- id="attach-file-menu-button"
- description={uploadFileTooltip}
- disabled={isUploadDisabled}
- />
- );
- const handleSharePointFilesSelected = async (sharePointFiles: any[]) => {
- try {
- await handleSharePointFiles(sharePointFiles);
- setIsSharePointDialogOpen(false);
- } catch (error) {
- console.error('SharePoint file processing error:', error);
- }
- };
-
- if (isUnifiedMode) {
- return (
- <>
- <FileUpload
- ref={inputRef}
- handleFileChange={(e) => {
- handleFileChange(e, toolResourceRef.current);
- }}
- >
- {sharePointEnabled === true ? (
- <DropdownPopup
- menuId="attach-file-menu"
- className="overflow-visible"
- isOpen={isPopoverActive}
- setIsOpen={setIsPopoverActive}
- modal={false}
- portal={true}
- unmountOnHide={true}
- trigger={menuTrigger}
- items={unifiedSourceItems}
- iconClassName="mr-0"
- />
- ) : (
- <TooltipAnchor
- render={
- <IconButton
- type="button"
- size="theme"
- shape="theme"
- disabled={isUploadDisabled}
- id="attach-file-button"
- label={localize('com_sidepanel_attach_files')}
- onClick={handleUnifiedUpload}
- aria-keyshortcuts={uploadFileAriaKey}
- className="hover:bg-surface-composer-hover p-1"
- >
- <AttachmentIcon />
- </IconButton>
- }
- id="attach-file-button"
- description={uploadFileTooltip}
- disabled={isUploadDisabled}
- />
- )}
- </FileUpload>
- <SharePointPickerDialog
- isOpen={isSharePointDialogOpen}
- onOpenChange={setIsSharePointDialogOpen}
- onFilesSelected={handleSharePointFilesSelected}
- isDownloading={isProcessing}
- downloadProgress={downloadProgress}
- maxSelectionCount={endpointFileConfig?.fileLimit}
- />
- </>
- );
- }
-
- return (
- <>
- <FileUpload
- ref={inputRef}
- handleFileChange={(e) => {
- handleFileChange(e, toolResourceRef.current);
- toolResourceRef.current = undefined;
- }}
- >
- <DropdownPopup
- menuId="attach-file-menu"
- className="overflow-visible"
- isOpen={isPopoverActive}
- setIsOpen={setIsPopoverActive}
- modal={false}
- portal={true}
- unmountOnHide={true}
- trigger={menuTrigger}
- items={dropdownItems}
- iconClassName="mr-0"
- />
- </FileUpload>
- <SharePointPickerDialog
- isOpen={isSharePointDialogOpen}
- onOpenChange={setIsSharePointDialogOpen}
- onFilesSelected={handleSharePointFilesSelected}
- isDownloading={isProcessing}
- downloadProgress={downloadProgress}
- maxSelectionCount={endpointFileConfig?.fileLimit}
- />
- </>
- );
-};
-
-export default React.memo(AttachFileMenu);
diff --git a/client/src/components/Chat/Input/Files/FileFormChat.tsx b/client/src/components/Chat/Input/Files/FileFormChat.tsx
deleted file mode 100644
index e93e37131b..0000000000
--- a/client/src/components/Chat/Input/Files/FileFormChat.tsx
+++ /dev/null
@@ -1,73 +0,0 @@
-import { memo } from 'react';
-import { useRecoilValue } from 'recoil';
-import type { TConversation } from 'librechat-data-provider';
-import type { ExtendedFile, FileSetter } from '~/common';
-import { useFileHandlingNoChatContext } from '~/hooks';
-import FileRow from './FileRow';
-import store from '~/store';
-
-/**
- * Declared at module scope so its identity is stable across renders. An inline
- * wrapper is a new component type on every render, which remounts the whole file
- * row and silently drops keyboard focus mid-upload.
- */
-const ChatFileRowWrapper = ({ children }: { children: React.ReactNode }) => (
- <div className="mx-2 mt-2 flex flex-wrap gap-2">{children}</div>
-);
-
-function FileFormChat({
- index,
- conversation,
- files,
- setFiles,
- setFilesLoading,
- isPastedTextFile,
- isPasteActionPending,
- onEditPastedText,
- onMovePastedTextInline,
-}: {
- index: number;
- conversation: TConversation | null;
- files: Map<string, ExtendedFile>;
- setFiles: FileSetter;
- setFilesLoading: React.Dispatch<React.SetStateAction<boolean>>;
- /** Marks chips the composer generated from a long paste, so only those offer the paste
- * affordances. Filenames cannot carry that decision: users can upload a `pasted-text.txt`. */
- isPastedTextFile?: (file: ExtendedFile) => boolean;
- /** Hides the paste actions while a replacement upload or inline move is in flight for the
- * chip, so the same original cannot be acted on twice. */
- isPasteActionPending?: (file: ExtendedFile) => boolean;
- onEditPastedText?: (file: ExtendedFile) => void;
- onMovePastedTextInline?: (file: ExtendedFile) => void;
-}) {
- const chatDirection = useRecoilValue(store.chatDirection).toLowerCase();
- const { endpoint: _endpoint } = conversation ?? { endpoint: null };
- const { abortUpload } = useFileHandlingNoChatContext(undefined, {
- files,
- setFiles,
- setFilesLoading,
- conversation,
- });
-
- const isRTL = chatDirection === 'rtl';
-
- return (
- <>
- <FileRow
- files={files}
- index={index}
- setFiles={setFiles}
- abortUpload={abortUpload}
- setFilesLoading={setFilesLoading}
- isRTL={isRTL}
- Wrapper={ChatFileRowWrapper}
- isPastedTextFile={isPastedTextFile}
- isPasteActionPending={isPasteActionPending}
- onEditPastedText={onEditPastedText}
- onMovePastedTextInline={onMovePastedTextInline}
- />
- </>
- );
-}
-
-export default memo(FileFormChat);
diff --git a/client/src/components/Chat/Input/Files/FileRow.tsx b/client/src/components/Chat/Input/Files/FileRow.tsx
index 3e8d53ad1e..95d43b2ac9 100644
--- a/client/src/components/Chat/Input/Files/FileRow.tsx
+++ b/client/src/components/Chat/Input/Files/FileRow.tsx
@@ -116,20 +116,22 @@ export default function FileRow({
display: 'flex',
flexDirection: 'row-reverse',
flexWrap: 'wrap',
- gap: '4px',
+ gap: '6px',
width: '100%',
maxWidth: '100%',
}
: {
display: 'flex',
flexWrap: 'wrap',
- gap: '4px',
+ gap: '6px',
width: '100%',
maxWidth: '100%',
};
return (
- <div style={rowStyle as React.CSSProperties}>
+ /* `items-center` so a card and a thumbnail of different heights share
+ one baseline instead of hanging from the top of the tallest row. */
+ <div className="items-center" style={rowStyle as React.CSSProperties}>
{files
.reduce(
(acc, current) => {
@@ -166,14 +168,14 @@ export default function FileRow({
!isPasteActionPending?.(file);
return (
- <div
- key={fileIndex}
- style={{
- flexBasis: '70px',
- flexGrow: 0,
- flexShrink: 0,
- }}
- >
+ /* Sized by its content, not parked in a fixed 70px slot: a 56px
+ thumbnail in a 70px slot left 14px of dead space beside it, so
+ the gap between two images read as far wider than the gap
+ beside a file card, which overflowed the same slot. */
+ /* `flex`, not the default block: `Image`'s root is inline-block,
+ which sits on a text baseline and adds descender space under
+ the thumbnail, floating it above the cards beside it. */
+ <div key={fileIndex} className="flex shrink-0">
{isImage ? (
<Image
url={getCachedPreview(file.file_id) ?? file.preview ?? file.filepath}
@@ -182,9 +184,13 @@ export default function FileRow({
source={file.source}
/>
) : (
+ /* `ImagePreview`'s `size-14` plus the 1px border its wrapper
+ adds, so a card and a thumbnail are exactly the same height
+ in a mixed row. */
<FileContainer
file={file}
onDelete={handleDelete}
+ buttonClassName="h-[58px]"
onClick={isEditablePaste ? () => onEditPastedText(file) : undefined}
ariaLabel={
isEditablePaste
diff --git a/client/src/components/Chat/Input/Files/Image.tsx b/client/src/components/Chat/Input/Files/Image.tsx
index 0a2cfe9010..f13e6e744d 100644
--- a/client/src/components/Chat/Input/Files/Image.tsx
+++ b/client/src/components/Chat/Input/Files/Image.tsx
@@ -16,8 +16,11 @@ const Image = ({
source?: FileSources;
}) => {
return (
- <div className="group relative inline-block text-sm text-text-secondary">
- <div className="relative overflow-hidden rounded-2xl border border-border-medium">
+ <div className="group text-text-secondary relative inline-block text-sm">
+ {/* `flex`, so the button inside is not laid out on a text baseline: the
+ descender space added ~5px under every thumbnail, which is what left
+ them sitting higher than the file cards beside them. */}
+ <div className="border-border-medium relative flex overflow-hidden rounded-2xl border">
<ImagePreview source={source} imageBase64={imageBase64} url={url} progress={progress} />
</div>
<RemoveFile onRemove={onDelete} />
diff --git a/client/src/components/Chat/Input/Files/MyFilesModal.spec.tsx b/client/src/components/Chat/Input/Files/MyFilesModal.spec.tsx
new file mode 100644
index 0000000000..b253a82948
--- /dev/null
+++ b/client/src/components/Chat/Input/Files/MyFilesModal.spec.tsx
@@ -0,0 +1,56 @@
+import { useState } from 'react';
+import userEvent from '@testing-library/user-event';
+import { render, screen, waitFor } from '@testing-library/react';
+import { MyFilesModal } from './MyFilesModal';
+
+jest.mock('~/data-provider', () => ({
+ useGetFiles: () => ({ data: [] }),
+}));
+
+jest.mock('~/hooks', () => ({
+ useLocalize: () => (key: string) => key,
+}));
+
+jest.mock('./Table', () => ({
+ columns: [],
+ DataTable: () => <div data-testid="files-table" />,
+}));
+
+function Harness({ trigger }: { trigger: HTMLElement }) {
+ const [open, setOpen] = useState(true);
+ return <MyFilesModal open={open} onOpenChange={setOpen} triggerRef={{ current: trigger }} />;
+}
+
+describe('MyFilesModal focus restoration', () => {
+ it('returns focus to the shortcut invoker instead of the account button', async () => {
+ const user = userEvent.setup();
+ const invoker = document.createElement('button');
+ const inertSidebar = document.createElement('div');
+ const accountButton = document.createElement('button');
+ inertSidebar.setAttribute('inert', '');
+ inertSidebar.append(accountButton);
+ document.body.append(invoker, inertSidebar);
+ invoker.focus();
+
+ render(<Harness trigger={accountButton} />);
+ await user.click(await screen.findByRole('button', { name: 'Close' }));
+
+ await waitFor(() => expect(invoker).toHaveFocus());
+ });
+
+ it('falls back to the account button when the dialog opens from its menu', async () => {
+ const user = userEvent.setup();
+ const menu = document.createElement('div');
+ const menuItem = document.createElement('button');
+ const accountButton = document.createElement('button');
+ menu.setAttribute('role', 'menu');
+ menu.append(menuItem);
+ document.body.append(menu, accountButton);
+ menuItem.focus();
+
+ render(<Harness trigger={accountButton} />);
+ await user.click(await screen.findByRole('button', { name: 'Close' }));
+
+ await waitFor(() => expect(accountButton).toHaveFocus());
+ });
+});
diff --git a/client/src/components/Chat/Input/Files/MyFilesModal.tsx b/client/src/components/Chat/Input/Files/MyFilesModal.tsx
index f33013338a..3001a283be 100644
--- a/client/src/components/Chat/Input/Files/MyFilesModal.tsx
+++ b/client/src/components/Chat/Input/Files/MyFilesModal.tsx
@@ -1,3 +1,4 @@
+import { useCallback, useRef } from 'react';
import { FileSources, FileContext } from 'librechat-data-provider';
import { OGDialog, OGDialogContent, OGDialogHeader, OGDialogTitle } from '@librechat/client';
import type { TFile } from 'librechat-data-provider';
@@ -12,9 +13,23 @@ export function MyFilesModal({
}: {
open: boolean;
onOpenChange: (open: boolean) => void;
- triggerRef?: React.RefObject<HTMLButtonElement | HTMLDivElement | null>;
+ triggerRef?: React.RefObject<HTMLElement | null>;
}) {
const localize = useLocalize();
+ const returnFocusRef = useRef<HTMLElement | null>(null);
+
+ const captureReturnFocus = useCallback(() => {
+ const activeElement = document.activeElement;
+ const canRestoreShortcutFocus =
+ activeElement instanceof HTMLElement &&
+ activeElement !== document.body &&
+ activeElement.isConnected &&
+ activeElement.closest('[inert]') == null &&
+ activeElement.closest('[role="menu"]') == null;
+ returnFocusRef.current = canRestoreShortcutFocus
+ ? activeElement
+ : (triggerRef?.current ?? null);
+ }, [triggerRef]);
const { data: files = [] } = useGetFiles<TFile[]>({
select: (files) =>
@@ -26,10 +41,11 @@ export function MyFilesModal({
});
return (
- <OGDialog open={open} onOpenChange={onOpenChange} triggerRef={triggerRef}>
+ <OGDialog open={open} onOpenChange={onOpenChange} triggerRef={returnFocusRef}>
<OGDialogContent
title={localize('com_nav_my_files')}
- className="w-11/12 bg-surface-dialog text-text-primary shadow-2xl"
+ onOpenAutoFocus={captureReturnFocus}
+ className="bg-surface-dialog text-text-primary w-11/12 shadow-2xl"
>
<OGDialogHeader>
<OGDialogTitle>{localize('com_nav_my_files')}</OGDialogTitle>
diff --git a/client/src/components/Chat/Input/Files/__tests__/AttachFileChat.spec.tsx b/client/src/components/Chat/Input/Files/__tests__/AttachFileChat.spec.tsx
deleted file mode 100644
index eef31f49db..0000000000
--- a/client/src/components/Chat/Input/Files/__tests__/AttachFileChat.spec.tsx
+++ /dev/null
@@ -1,369 +0,0 @@
-import React from 'react';
-import { RecoilRoot } from 'recoil';
-import { render, screen } from '@testing-library/react';
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
-import { EModelEndpoint, mergeFileConfig } from 'librechat-data-provider';
-import type { TEndpointsConfig, Agent } from 'librechat-data-provider';
-import AttachFileChat from '../AttachFileChat';
-
-const mockEndpointsConfig: TEndpointsConfig = {
- [EModelEndpoint.openAI]: { userProvide: false, order: 0 },
- [EModelEndpoint.agents]: { userProvide: false, order: 1 },
- [EModelEndpoint.assistants]: { userProvide: false, order: 2 },
- Moonshot: { type: EModelEndpoint.custom, userProvide: false, order: 9999 },
-};
-
-const defaultFileConfig = mergeFileConfig({
- endpoints: {
- Moonshot: { fileLimit: 5 },
- [EModelEndpoint.agents]: { fileLimit: 20 },
- default: { fileLimit: 10 },
- },
-});
-
-let mockFileConfig = defaultFileConfig;
-
-let mockAgentsMap: Record<string, Partial<Agent>> = {};
-let mockAgentQueryData: Partial<Agent> | undefined;
-let mockFileConfigLoaded = true;
-
-jest.mock('~/data-provider', () => ({
- useGetEndpointsQuery: () => ({ data: mockEndpointsConfig }),
- useGetFileConfig: ({ select }: { select?: (data: unknown) => unknown }) => ({
- data: select != null ? select(mockFileConfig) : mockFileConfig,
- isSuccess: mockFileConfigLoaded,
- }),
- useGetAgentByIdQuery: () => ({ data: mockAgentQueryData }),
-}));
-
-jest.mock('~/Providers', () => ({
- useAgentsMapContext: () => mockAgentsMap,
-}));
-
-/* The shared upload-target hook reads the module directly rather than the barrel, so
- * the barrel mock alone leaves it with no agents map. */
-jest.mock('~/Providers/AgentsMapContext', () => ({
- useAgentsMapContext: () => mockAgentsMap,
-}));
-
-/** Capture the props passed to AttachFileMenu */
-let mockAttachFileMenuProps: Record<string, unknown> = {};
-jest.mock('../AttachFileMenu', () => {
- return function MockAttachFileMenu(props: Record<string, unknown>) {
- mockAttachFileMenuProps = props;
- return <div data-testid="attach-file-menu" data-endpoint-type={String(props.endpointType)} />;
- };
-});
-
-jest.mock('../AttachFile', () => {
- return function MockAttachFile() {
- return <div data-testid="attach-file" />;
- };
-});
-
-const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
-
-function renderComponent(conversation: Record<string, unknown> | null, disableInputs = false) {
- return render(
- <QueryClientProvider client={queryClient}>
- <RecoilRoot>
- <AttachFileChat
- conversation={conversation as never}
- disableInputs={disableInputs}
- files={new Map()}
- setFiles={() => {}}
- setFilesLoading={() => {}}
- />
- </RecoilRoot>
- </QueryClientProvider>,
- );
-}
-
-describe('AttachFileChat', () => {
- beforeEach(() => {
- mockFileConfig = defaultFileConfig;
- mockAgentsMap = {};
- mockAgentQueryData = undefined;
- mockAttachFileMenuProps = {};
- mockFileConfigLoaded = true;
- });
-
- describe('rendering decisions', () => {
- it('renders AttachFileMenu for agents endpoint', () => {
- renderComponent({ endpoint: EModelEndpoint.agents, agent_id: 'agent-1' });
- expect(screen.getByTestId('attach-file-menu')).toBeInTheDocument();
- });
-
- it('renders AttachFileMenu for custom endpoint with file support', () => {
- renderComponent({ endpoint: 'Moonshot' });
- expect(screen.getByTestId('attach-file-menu')).toBeInTheDocument();
- });
-
- it('renders null for null conversation', () => {
- const { container } = renderComponent(null);
- expect(container.innerHTML).toBe('');
- });
- });
-
- describe('endpointType resolution for agents', () => {
- it('passes custom endpointType when agent provider is a custom endpoint', () => {
- mockAgentsMap = {
- 'agent-1': { provider: 'Moonshot', model_parameters: {} } as Partial<Agent>,
- };
- renderComponent({ endpoint: EModelEndpoint.agents, agent_id: 'agent-1' });
- expect(mockAttachFileMenuProps.endpointType).toBe(EModelEndpoint.custom);
- });
-
- it('passes openAI endpointType when agent provider is openAI', () => {
- mockAgentsMap = {
- 'agent-1': { provider: EModelEndpoint.openAI, model_parameters: {} } as Partial<Agent>,
- };
- renderComponent({ endpoint: EModelEndpoint.agents, agent_id: 'agent-1' });
- expect(mockAttachFileMenuProps.endpointType).toBe(EModelEndpoint.openAI);
- });
-
- it('passes agents endpointType when no agent provider', () => {
- renderComponent({ endpoint: EModelEndpoint.agents, agent_id: 'agent-1' });
- expect(mockAttachFileMenuProps.endpointType).toBe(EModelEndpoint.agents);
- });
-
- it('passes agents endpointType when no agent_id', () => {
- renderComponent({ endpoint: EModelEndpoint.agents });
- expect(mockAttachFileMenuProps.endpointType).toBe(EModelEndpoint.agents);
- });
-
- it('uses agentData query when agent not in agentsMap', () => {
- mockAgentQueryData = { provider: 'Moonshot' } as Partial<Agent>;
- renderComponent({ endpoint: EModelEndpoint.agents, agent_id: 'agent-2' });
- expect(mockAttachFileMenuProps.endpointType).toBe(EModelEndpoint.custom);
- });
-
- it('falls back to agentsMap provider when fetched agent omits provider', () => {
- mockAgentsMap = {
- 'agent-1': { provider: EModelEndpoint.openAI, model_parameters: {} } as Partial<Agent>,
- };
- mockAgentQueryData = {} as Partial<Agent>;
- renderComponent({ endpoint: EModelEndpoint.agents, agent_id: 'agent-1' });
- expect(mockAttachFileMenuProps.endpointType).toBe(EModelEndpoint.openAI);
- });
- });
-
- describe('useResponsesApi resolution for agents', () => {
- it('passes useResponsesApi from fetched agent model parameters', () => {
- mockAgentQueryData = {
- provider: EModelEndpoint.azureOpenAI,
- model_parameters: { useResponsesApi: true },
- } as Partial<Agent>;
- renderComponent({ endpoint: EModelEndpoint.agents, agent_id: 'agent-1' });
- expect(mockAttachFileMenuProps.useResponsesApi).toBe(true);
- });
-
- it('falls back to agentsMap model parameters when fetched agent omits them', () => {
- mockAgentsMap = {
- 'agent-1': {
- provider: EModelEndpoint.azureOpenAI,
- model_parameters: { useResponsesApi: true },
- } as Partial<Agent>,
- };
- mockAgentQueryData = { provider: EModelEndpoint.azureOpenAI } as Partial<Agent>;
- renderComponent({ endpoint: EModelEndpoint.agents, agent_id: 'agent-1' });
- expect(mockAttachFileMenuProps.useResponsesApi).toBe(true);
- });
-
- it('lets the saved agent decide over the conversation', () => {
- /* Execution reads the agent's own model parameters, so the attach menu must offer
- * what the turn will actually do rather than what the conversation says. */
- mockAgentQueryData = {
- provider: EModelEndpoint.azureOpenAI,
- model_parameters: { useResponsesApi: true },
- } as Partial<Agent>;
- renderComponent({
- endpoint: EModelEndpoint.agents,
- agent_id: 'agent-1',
- useResponsesApi: false,
- });
- expect(mockAttachFileMenuProps.useResponsesApi).toBe(true);
- });
-
- it('keeps the conversation setting when the agent states none', () => {
- mockAgentQueryData = {
- provider: EModelEndpoint.azureOpenAI,
- model_parameters: {},
- } as Partial<Agent>;
- renderComponent({
- endpoint: EModelEndpoint.agents,
- agent_id: 'agent-1',
- useResponsesApi: true,
- });
- expect(mockAttachFileMenuProps.useResponsesApi).toBe(true);
- });
- });
-
- describe('endpointType resolution for non-agents', () => {
- it('passes custom endpointType for a custom endpoint', () => {
- renderComponent({ endpoint: 'Moonshot' });
- expect(mockAttachFileMenuProps.endpointType).toBe(EModelEndpoint.custom);
- });
-
- it('passes openAI endpointType for openAI endpoint', () => {
- renderComponent({ endpoint: EModelEndpoint.openAI });
- expect(mockAttachFileMenuProps.endpointType).toBe(EModelEndpoint.openAI);
- });
- });
-
- describe('consistency: same endpoint type for direct vs agent usage', () => {
- it('resolves Moonshot the same way whether used directly or through an agent', () => {
- renderComponent({ endpoint: 'Moonshot' });
- const directType = mockAttachFileMenuProps.endpointType;
-
- mockAgentsMap = {
- 'agent-1': { provider: 'Moonshot', model_parameters: {} } as Partial<Agent>,
- };
- renderComponent({ endpoint: EModelEndpoint.agents, agent_id: 'agent-1' });
- const agentType = mockAttachFileMenuProps.endpointType;
-
- expect(directType).toBe(agentType);
- });
- });
-
- describe('upload disabled rendering', () => {
- it('renders null for agents endpoint when fileConfig.agents.disabled is true', () => {
- mockFileConfig = mergeFileConfig({
- endpoints: {
- [EModelEndpoint.agents]: { disabled: true },
- },
- });
- const { container } = renderComponent({
- endpoint: EModelEndpoint.agents,
- agent_id: 'agent-1',
- });
- expect(container.innerHTML).toBe('');
- });
-
- it('renders null for agents endpoint when disableInputs is true', () => {
- const { container } = renderComponent(
- { endpoint: EModelEndpoint.agents, agent_id: 'agent-1' },
- true,
- );
- expect(container.innerHTML).toBe('');
- });
-
- it('renders AttachFile for assistants endpoint when not disabled', () => {
- renderComponent({ endpoint: EModelEndpoint.assistants });
- expect(screen.getByTestId('attach-file')).toBeInTheDocument();
- });
-
- it('renders AttachFileMenu when provider-specific config overrides agents disabled', () => {
- mockFileConfig = mergeFileConfig({
- endpoints: {
- Moonshot: { disabled: false, fileLimit: 5 },
- [EModelEndpoint.agents]: { disabled: true },
- },
- });
- mockAgentsMap = {
- 'agent-1': { provider: 'Moonshot', model_parameters: {} } as Partial<Agent>,
- };
- renderComponent({ endpoint: EModelEndpoint.agents, agent_id: 'agent-1' });
- expect(screen.getByTestId('attach-file-menu')).toBeInTheDocument();
- });
-
- it('renders null for assistants endpoint when fileConfig.assistants.disabled is true', () => {
- mockFileConfig = mergeFileConfig({
- endpoints: {
- [EModelEndpoint.assistants]: { disabled: true },
- },
- });
- const { container } = renderComponent({
- endpoint: EModelEndpoint.assistants,
- });
- expect(container.innerHTML).toBe('');
- });
- });
-
- describe('endpointFileConfig resolution', () => {
- it('passes Moonshot-specific file config for agent with Moonshot provider', () => {
- mockAgentsMap = {
- 'agent-1': { provider: 'Moonshot', model_parameters: {} } as Partial<Agent>,
- };
- renderComponent({ endpoint: EModelEndpoint.agents, agent_id: 'agent-1' });
- const config = mockAttachFileMenuProps.endpointFileConfig as { fileLimit?: number };
- expect(config?.fileLimit).toBe(5);
- });
-
- it('passes agents file config when agent has no specific provider config', () => {
- mockAgentsMap = {
- 'agent-1': { provider: EModelEndpoint.openAI, model_parameters: {} } as Partial<Agent>,
- };
- renderComponent({ endpoint: EModelEndpoint.agents, agent_id: 'agent-1' });
- const config = mockAttachFileMenuProps.endpointFileConfig as { fileLimit?: number };
- expect(config?.fileLimit).toBe(10);
- });
-
- it('passes agents file config when no agent provider', () => {
- renderComponent({ endpoint: EModelEndpoint.agents });
- const config = mockAttachFileMenuProps.endpointFileConfig as { fileLimit?: number };
- expect(config?.fileLimit).toBe(20);
- });
- });
-});
-
-describe('AttachFileChat upload config gating', () => {
- beforeEach(() => {
- mockFileConfig = defaultFileConfig;
- mockAgentsMap = {};
- mockAgentQueryData = undefined;
- mockAttachFileMenuProps = {};
- });
-
- it('leaves the attach menu inert until the file config resolves', () => {
- /* The menu is an action, not just a display: offering the chooser here submits an
- * explicit destination a unified deployment would have inferred, and after a failed
- * fetch it would keep offering it. */
- mockFileConfigLoaded = false;
-
- renderComponent({ endpoint: EModelEndpoint.agents });
-
- expect(mockAttachFileMenuProps.disabled).toBe(true);
- });
-
- it('enables it once the config lands', () => {
- mockFileConfigLoaded = true;
-
- renderComponent({ endpoint: EModelEndpoint.agents });
-
- expect(mockAttachFileMenuProps.disabled).toBe(false);
- });
-
- it('keeps it inert while a saved agent provider is still being fetched', () => {
- /* The config can succeed before the agent does, and until then endpointFileConfig is
- * the generic agents entry rather than the provider's. */
- mockFileConfigLoaded = true;
- mockAgentsMap = {};
- mockAgentQueryData = undefined;
-
- renderComponent({ endpoint: EModelEndpoint.agents, agent_id: 'agent_saved01' });
-
- expect(mockAttachFileMenuProps.disabled).toBe(true);
- });
-
- it('does not wait on a provider an ephemeral agent will never have', () => {
- /* There is no record to fetch for one, so gating on its provider never lifts and the
- * attach control stays disabled for the whole conversation. */
- mockFileConfigLoaded = true;
- mockAgentsMap = {};
- mockAgentQueryData = undefined;
-
- renderComponent({ endpoint: EModelEndpoint.agents, agent_id: 'ephemeral-convo-1' });
-
- expect(mockAttachFileMenuProps.disabled).toBe(false);
- });
-
- it('enables it once that provider resolves', () => {
- mockFileConfigLoaded = true;
- mockAgentQueryData = { provider: 'openAI' } as Partial<Agent>;
-
- renderComponent({ endpoint: EModelEndpoint.agents, agent_id: 'agent_saved01' });
-
- expect(mockAttachFileMenuProps.disabled).toBe(false);
- });
-});
diff --git a/client/src/components/Chat/Input/Files/__tests__/AttachFileMenu.spec.tsx b/client/src/components/Chat/Input/Files/__tests__/AttachFileMenu.spec.tsx
deleted file mode 100644
index 7fcd7ba32b..0000000000
--- a/client/src/components/Chat/Input/Files/__tests__/AttachFileMenu.spec.tsx
+++ /dev/null
@@ -1,551 +0,0 @@
-import React from 'react';
-import { RecoilRoot } from 'recoil';
-import { render, screen, fireEvent } from '@testing-library/react';
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
-import { EModelEndpoint, EToolResources, Providers } from 'librechat-data-provider';
-import AttachFileMenu from '../AttachFileMenu';
-
-jest.mock('~/hooks', () => ({
- useAgentToolPermissions: jest.fn(),
- useAgentCapabilities: jest.fn(),
- useGetAgentsConfig: jest.fn(),
- useFileHandlingNoChatContext: jest.fn(),
- useLocalize: jest.fn(),
-}));
-
-jest.mock('~/hooks/Files/useSharePointFileHandling', () => ({
- __esModule: true,
- default: jest.fn(),
- useSharePointFileHandlingNoChatContext: jest.fn(),
-}));
-
-jest.mock('~/data-provider', () => ({
- useGetStartupConfig: jest.fn(),
-}));
-
-jest.mock('~/components/SharePoint', () => ({
- SharePointPickerDialog: () => null,
-}));
-
-jest.mock('@librechat/client', () => {
- // eslint-disable-next-line @typescript-eslint/no-require-imports
- const R = require('react');
- return {
- FileUpload: R.forwardRef((props, ref) =>
- R.createElement(
- 'div',
- { 'data-testid': 'file-upload' },
- props.children,
- R.createElement('input', {
- ref,
- multiple: true,
- type: 'file',
- 'data-testid': 'file-input',
- onChange: props.handleFileChange,
- }),
- ),
- ),
- TooltipAnchor: (props) => props.render,
- /* Mirrors the real primitive closely enough for these assertions: it applies
- * `label` as the accessible name, which is how the trigger is queried. */
- IconButton: R.forwardRef((props, ref) => {
- const { label, size: _size, shape: _shape, variant: _variant, children, ...rest } = props;
- return R.createElement('button', { ref, 'aria-label': label, ...rest }, children);
- }),
- DropdownPopup: (props) =>
- R.createElement(
- 'div',
- {
- 'data-testid': 'dropdown-popup',
- 'data-modal': props.modal,
- 'data-portal': props.portal,
- },
- R.createElement('div', { onClick: () => props.setIsOpen(!props.isOpen) }, props.trigger),
- props.isOpen &&
- R.createElement(
- 'div',
- { 'data-testid': 'dropdown-menu' },
- props.items.map((item, idx) =>
- R.createElement(
- 'button',
- { key: idx, onClick: item.onClick, 'data-testid': `menu-item-${idx}` },
- item.label,
- ),
- ),
- ),
- ),
- AttachmentIcon: () => R.createElement('span', { 'data-testid': 'attachment-icon' }),
- SharePointIcon: () => R.createElement('span', { 'data-testid': 'sharepoint-icon' }),
- useToastContext: () => ({ showToast: jest.fn() }),
- };
-});
-
-jest.mock('@ariakit/react', () => {
- // eslint-disable-next-line @typescript-eslint/no-require-imports
- const R = require('react');
- return {
- MenuButton: (props) => R.createElement('button', props, props.children),
- };
-});
-
-const mockUseAgentToolPermissions = jest.requireMock('~/hooks').useAgentToolPermissions;
-const mockUseAgentCapabilities = jest.requireMock('~/hooks').useAgentCapabilities;
-const mockUseGetAgentsConfig = jest.requireMock('~/hooks').useGetAgentsConfig;
-const mockUseFileHandlingNoChatContext = jest.requireMock('~/hooks').useFileHandlingNoChatContext;
-const mockUseLocalize = jest.requireMock('~/hooks').useLocalize;
-const mockUseSharePointFileHandling = jest.requireMock(
- '~/hooks/Files/useSharePointFileHandling',
-).default;
-const mockUseSharePointFileHandlingNoChatContext = jest.requireMock(
- '~/hooks/Files/useSharePointFileHandling',
-).useSharePointFileHandlingNoChatContext;
-const mockUseGetStartupConfig = jest.requireMock('~/data-provider').useGetStartupConfig;
-
-const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
-
-function setupMocks(overrides: { provider?: string } = {}) {
- const translations: Record<string, string> = {
- com_files_upload_local_machine: 'From Local Computer',
- com_files_upload_sharepoint: 'Upload from SharePoint',
- com_sidepanel_attach_files: 'Attach Files',
- com_ui_upload_code_environment: 'Upload to Code Environment',
- com_ui_upload_file_search: 'Upload for File Search',
- com_ui_upload_image_input: 'Upload Image',
- com_ui_upload_ocr_text: 'Upload as Text',
- com_ui_upload_provider: 'Upload to Provider',
- };
- mockUseLocalize.mockReturnValue((key: string) => translations[key] || key);
- mockUseAgentCapabilities.mockReturnValue({
- contextEnabled: false,
- fileSearchEnabled: false,
- codeEnabled: false,
- });
- mockUseGetAgentsConfig.mockReturnValue({ agentsConfig: {} });
- mockUseFileHandlingNoChatContext.mockReturnValue({ handleFileChange: jest.fn() });
- const sharePointReturnValue = {
- handleSharePointFiles: jest.fn(),
- isProcessing: false,
- downloadProgress: 0,
- error: null,
- };
- mockUseSharePointFileHandling.mockReturnValue(sharePointReturnValue);
- mockUseSharePointFileHandlingNoChatContext.mockReturnValue(sharePointReturnValue);
- mockUseGetStartupConfig.mockReturnValue({ data: { sharePointFilePickerEnabled: false } });
- mockUseAgentToolPermissions.mockReturnValue({
- fileSearchAllowedByAgent: false,
- codeAllowedByAgent: false,
- provider: overrides.provider ?? undefined,
- });
-}
-
-function renderMenu(props: Record<string, unknown> = {}) {
- return render(
- <QueryClientProvider client={queryClient}>
- <RecoilRoot>
- <AttachFileMenu
- conversationId="test-convo"
- files={new Map()}
- setFiles={() => {}}
- setFilesLoading={() => {}}
- conversation={null}
- isUnifiedMode={false}
- {...props}
- />
- </RecoilRoot>
- </QueryClientProvider>,
- );
-}
-
-function openMenu() {
- fireEvent.click(screen.getByRole('button', { name: /attach file options/i }));
-}
-
-describe('AttachFileMenu', () => {
- beforeEach(jest.clearAllMocks);
-
- describe('unified mode upload sources', () => {
- it('uses a single upload button when SharePoint is disabled', () => {
- setupMocks();
- renderMenu({ isUnifiedMode: true });
-
- expect(screen.getByRole('button', { name: /attach files/i })).toBeInTheDocument();
- expect(
- screen.queryByRole('button', { name: /attach file options/i }),
- ).not.toBeInTheDocument();
- });
-
- it('offers SharePoint alongside local upload when SharePoint is enabled', () => {
- setupMocks();
- mockUseGetStartupConfig.mockReturnValue({ data: { sharePointFilePickerEnabled: true } });
- renderMenu({ isUnifiedMode: true });
-
- openMenu();
-
- expect(screen.getByText('From Local Computer')).toBeInTheDocument();
- expect(screen.getByText('Upload from SharePoint')).toBeInTheDocument();
- });
-
- it('does not offer a destination choice on either source', () => {
- setupMocks();
- mockUseAgentCapabilities.mockReturnValue({
- contextEnabled: true,
- fileSearchEnabled: true,
- codeEnabled: true,
- });
- mockUseAgentToolPermissions.mockReturnValue({
- fileSearchAllowedByAgent: true,
- codeAllowedByAgent: true,
- provider: undefined,
- });
- mockUseGetStartupConfig.mockReturnValue({ data: { sharePointFilePickerEnabled: true } });
- renderMenu({ isUnifiedMode: true });
-
- openMenu();
-
- expect(screen.queryByText('Upload to Code Environment')).not.toBeInTheDocument();
- expect(screen.queryByText('Upload for File Search')).not.toBeInTheDocument();
- expect(screen.queryByText('Upload as Text')).not.toBeInTheDocument();
- });
- });
-
- describe('Upload to Provider picker filter', () => {
- /** `accept` is reset right after `click()`, so capture it at click time. */
- const captureAcceptOnClick = () => {
- const seen: string[] = [];
- const spy = jest.spyOn(HTMLInputElement.prototype, 'click').mockImplementation(function (
- this: HTMLInputElement,
- ) {
- seen.push(this.accept);
- });
- return { seen, spy };
- };
-
- it('keeps images and PDFs only for a custom endpoint with the inherited default config', () => {
- const { seen, spy } = captureAcceptOnClick();
- setupMocks({ provider: 'MyGateway' });
- renderMenu({ endpointType: EModelEndpoint.custom, endpointFileConfig: {} });
- openMenu();
- fireEvent.click(screen.getByText('Upload to Provider'));
- expect(seen).toEqual(['image/*,.heif,.heic,.pdf,application/pdf']);
- spy.mockRestore();
- });
-
- it('adds video when a custom endpoint config explicitly allows it', () => {
- const { seen, spy } = captureAcceptOnClick();
- setupMocks({ provider: 'MyGateway' });
- renderMenu({
- endpointType: EModelEndpoint.custom,
- endpointFileConfig: {
- supportedMimeTypes: [/^image\/.*$/, /^application\/pdf$/, /^video\/.*$/],
- },
- });
- openMenu();
- fireEvent.click(screen.getByText('Upload to Provider'));
- expect(seen).toHaveLength(1);
- expect(seen[0]).toContain('video/*');
- expect(seen[0]).not.toContain('audio/*');
- spy.mockRestore();
- });
- });
-
- describe('Upload to Provider vs Upload Image', () => {
- it('shows "Upload to Provider" when endpointType is custom (resolved from agent provider)', () => {
- setupMocks({ provider: 'Moonshot' });
- renderMenu({ endpointType: EModelEndpoint.custom });
- openMenu();
- expect(screen.getByText('Upload to Provider')).toBeInTheDocument();
- expect(screen.queryByText('Upload Image')).not.toBeInTheDocument();
- });
-
- it('shows "Upload to Provider" when endpointType is openAI', () => {
- setupMocks({ provider: EModelEndpoint.openAI });
- renderMenu({ endpointType: EModelEndpoint.openAI });
- openMenu();
- expect(screen.getByText('Upload to Provider')).toBeInTheDocument();
- });
-
- it('shows "Upload to Provider" when endpointType is anthropic', () => {
- setupMocks({ provider: EModelEndpoint.anthropic });
- renderMenu({ endpointType: EModelEndpoint.anthropic });
- openMenu();
- expect(screen.getByText('Upload to Provider')).toBeInTheDocument();
- });
-
- it('shows "Upload to Provider" when endpointType is google', () => {
- setupMocks({ provider: Providers.GOOGLE });
- renderMenu({ endpointType: EModelEndpoint.google });
- openMenu();
- expect(screen.getByText('Upload to Provider')).toBeInTheDocument();
- });
-
- it('shows "Upload Image" when endpointType is agents (no provider resolution)', () => {
- setupMocks();
- renderMenu({ endpointType: EModelEndpoint.agents });
- openMenu();
- expect(screen.getByText('Upload Image')).toBeInTheDocument();
- expect(screen.queryByText('Upload to Provider')).not.toBeInTheDocument();
- });
-
- it('shows "Upload Image" when neither endpointType nor provider supports documents', () => {
- setupMocks({ provider: 'unknown-provider' });
- renderMenu({ endpointType: 'unknown-type' });
- openMenu();
- expect(screen.getByText('Upload Image')).toBeInTheDocument();
- });
-
- it('shows "Upload to Provider" for azureOpenAI with useResponsesApi', () => {
- setupMocks({ provider: EModelEndpoint.azureOpenAI });
- renderMenu({ endpointType: EModelEndpoint.azureOpenAI, useResponsesApi: true });
- openMenu();
- expect(screen.getByText('Upload to Provider')).toBeInTheDocument();
- });
-
- it('shows "Upload to Provider" for azureOpenAI endpointType with useResponsesApi', () => {
- setupMocks();
- renderMenu({
- endpoint: EModelEndpoint.agents,
- endpointType: EModelEndpoint.azureOpenAI,
- useResponsesApi: true,
- });
- openMenu();
- expect(screen.getByText('Upload to Provider')).toBeInTheDocument();
- });
-
- it('shows "Upload Image" for azureOpenAI without useResponsesApi', () => {
- setupMocks({ provider: EModelEndpoint.azureOpenAI });
- renderMenu({ endpointType: EModelEndpoint.azureOpenAI, useResponsesApi: false });
- openMenu();
- expect(screen.getByText('Upload Image')).toBeInTheDocument();
- });
- });
-
- describe('agent provider resolution scenario', () => {
- it('shows "Upload to Provider" when agents endpoint has custom endpointType from provider', () => {
- setupMocks({ provider: 'Moonshot' });
- renderMenu({
- endpoint: EModelEndpoint.agents,
- endpointType: EModelEndpoint.custom,
- });
- openMenu();
- expect(screen.getByText('Upload to Provider')).toBeInTheDocument();
- });
-
- it('shows "Upload Image" when agents endpoint has no resolved provider type', () => {
- setupMocks();
- renderMenu({
- endpoint: EModelEndpoint.agents,
- endpointType: EModelEndpoint.agents,
- });
- openMenu();
- expect(screen.getByText('Upload Image')).toBeInTheDocument();
- });
- });
-
- describe('Basic Rendering', () => {
- it('renders the attachment button', () => {
- setupMocks();
- renderMenu();
- expect(screen.getByRole('button', { name: /attach file options/i })).toBeInTheDocument();
- });
-
- it('is disabled when disabled prop is true', () => {
- setupMocks();
- renderMenu({ disabled: true });
- expect(screen.getByRole('button', { name: /attach file options/i })).toBeDisabled();
- });
-
- it('is not disabled when disabled prop is false', () => {
- setupMocks();
- renderMenu({ disabled: false });
- expect(screen.getByRole('button', { name: /attach file options/i })).not.toBeDisabled();
- });
-
- it('portals the menu without making the conversation tree inert', () => {
- setupMocks();
- renderMenu();
- expect(screen.getByTestId('dropdown-popup')).toHaveAttribute('data-modal', 'false');
- expect(screen.getByTestId('dropdown-popup')).toHaveAttribute('data-portal', 'true');
- });
-
- it('renders the unified upload button when legacyFileUploadUX is not true', () => {
- setupMocks();
- renderMenu({ isUnifiedMode: true });
- expect(screen.getByRole('button', { name: /attach files/i })).toBeInTheDocument();
- expect(
- screen.queryByRole('button', { name: /attach file options/i }),
- ).not.toBeInTheDocument();
- });
- });
-
- describe('Agent Capabilities', () => {
- it('shows OCR Text option when context is enabled', () => {
- setupMocks();
- mockUseAgentCapabilities.mockReturnValue({
- contextEnabled: true,
- fileSearchEnabled: false,
- codeEnabled: false,
- });
- renderMenu({ endpointType: EModelEndpoint.openAI });
- openMenu();
- expect(screen.getByText('Upload as Text')).toBeInTheDocument();
- });
-
- it('shows File Search option when enabled and allowed by agent', () => {
- setupMocks();
- mockUseAgentCapabilities.mockReturnValue({
- contextEnabled: false,
- fileSearchEnabled: true,
- codeEnabled: false,
- });
- mockUseAgentToolPermissions.mockReturnValue({
- fileSearchAllowedByAgent: true,
- codeAllowedByAgent: false,
- provider: undefined,
- });
- renderMenu({ endpointType: EModelEndpoint.openAI });
- openMenu();
- expect(screen.getByText('Upload for File Search')).toBeInTheDocument();
- });
-
- it('does NOT show File Search when enabled but not allowed by agent', () => {
- setupMocks();
- mockUseAgentCapabilities.mockReturnValue({
- contextEnabled: false,
- fileSearchEnabled: true,
- codeEnabled: false,
- });
- renderMenu({ endpointType: EModelEndpoint.openAI });
- openMenu();
- expect(screen.queryByText('Upload for File Search')).not.toBeInTheDocument();
- });
-
- it('shows Code Files option when enabled and allowed by agent', () => {
- setupMocks();
- mockUseAgentCapabilities.mockReturnValue({
- contextEnabled: false,
- fileSearchEnabled: false,
- codeEnabled: true,
- });
- mockUseAgentToolPermissions.mockReturnValue({
- fileSearchAllowedByAgent: false,
- codeAllowedByAgent: true,
- provider: undefined,
- });
- renderMenu({ endpointType: EModelEndpoint.openAI });
- openMenu();
- expect(screen.getByText('Upload to Code Environment')).toBeInTheDocument();
- });
-
- it('shows all options when all capabilities are enabled', () => {
- setupMocks();
- mockUseAgentCapabilities.mockReturnValue({
- contextEnabled: true,
- fileSearchEnabled: true,
- codeEnabled: true,
- });
- mockUseAgentToolPermissions.mockReturnValue({
- fileSearchAllowedByAgent: true,
- codeAllowedByAgent: true,
- provider: undefined,
- });
- renderMenu({ endpointType: EModelEndpoint.openAI });
- openMenu();
- expect(screen.getByText('Upload to Provider')).toBeInTheDocument();
- expect(screen.getByText('Upload as Text')).toBeInTheDocument();
- expect(screen.getByText('Upload for File Search')).toBeInTheDocument();
- expect(screen.getByText('Upload to Code Environment')).toBeInTheDocument();
- });
-
- it('passes File Search resource when the file input changes before React state commits', () => {
- setupMocks();
- const handleFileChange = jest.fn();
- mockUseFileHandlingNoChatContext.mockReturnValue({ handleFileChange });
- mockUseAgentCapabilities.mockReturnValue({
- contextEnabled: false,
- fileSearchEnabled: true,
- codeEnabled: false,
- });
- mockUseAgentToolPermissions.mockReturnValue({
- fileSearchAllowedByAgent: true,
- codeAllowedByAgent: false,
- provider: undefined,
- });
- const originalClick = HTMLInputElement.prototype.click;
- const file = new File(['data'], 'sheet.xlsx', {
- type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
- });
-
- HTMLInputElement.prototype.click = function click() {
- Object.defineProperty(this, 'files', {
- configurable: true,
- value: [file],
- });
- fireEvent.change(this);
- };
-
- try {
- renderMenu({ endpointType: EModelEndpoint.openAI });
- openMenu();
- fireEvent.click(screen.getByText('Upload to Provider'));
- fireEvent.click(screen.getByText('Upload for File Search'));
- } finally {
- HTMLInputElement.prototype.click = originalClick;
- }
-
- expect(handleFileChange).toHaveBeenNthCalledWith(1, expect.any(Object), undefined);
- expect(handleFileChange).toHaveBeenNthCalledWith(
- 2,
- expect.any(Object),
- EToolResources.file_search,
- );
- });
- });
-
- describe('SharePoint Integration', () => {
- it('shows SharePoint option when enabled', () => {
- setupMocks();
- mockUseGetStartupConfig.mockReturnValue({
- data: { sharePointFilePickerEnabled: true },
- });
- renderMenu({ endpointType: EModelEndpoint.openAI });
- openMenu();
- expect(screen.getByText('Upload from SharePoint')).toBeInTheDocument();
- });
-
- it('does NOT show SharePoint option when disabled', () => {
- setupMocks();
- renderMenu({ endpointType: EModelEndpoint.openAI });
- openMenu();
- expect(screen.queryByText('Upload from SharePoint')).not.toBeInTheDocument();
- });
- });
-
- describe('Edge Cases', () => {
- it('handles undefined endpoint and provider gracefully', () => {
- setupMocks();
- renderMenu({ endpoint: undefined, endpointType: undefined });
- const button = screen.getByRole('button', { name: /attach file options/i });
- expect(button).toBeInTheDocument();
- fireEvent.click(button);
- expect(screen.getByText('Upload Image')).toBeInTheDocument();
- });
-
- it('handles null endpoint and provider gracefully', () => {
- setupMocks();
- renderMenu({ endpoint: null, endpointType: null });
- expect(screen.getByRole('button', { name: /attach file options/i })).toBeInTheDocument();
- });
-
- it('handles missing agentId gracefully', () => {
- setupMocks();
- renderMenu({ agentId: undefined, endpointType: EModelEndpoint.openAI });
- expect(screen.getByRole('button', { name: /attach file options/i })).toBeInTheDocument();
- });
-
- it('handles empty string agentId', () => {
- setupMocks();
- renderMenu({ agentId: '', endpointType: EModelEndpoint.openAI });
- expect(screen.getByRole('button', { name: /attach file options/i })).toBeInTheDocument();
- });
- });
-});
diff --git a/client/src/components/Chat/Input/InFlightSteers.tsx b/client/src/components/Chat/Input/InFlightSteers.tsx
deleted file mode 100644
index a981f276f4..0000000000
--- a/client/src/components/Chat/Input/InFlightSteers.tsx
+++ /dev/null
@@ -1,733 +0,0 @@
-import { memo, useId, useRef, useMemo, useState, useEffect, useCallback } from 'react';
-import { X, Clock, Pencil } from 'lucide-react';
-import { useSetAtom, useAtomValue } from 'jotai';
-import { useRecoilValue, useRecoilCallback } from 'recoil';
-import { Zap, ZapOff, ChevronUp, ChevronDown } from 'lucide';
-import { MorphIcon, useToastContext } from '@librechat/client';
-import type { TFile, TMessage } from 'librechat-data-provider';
-import type { SteeringControls, QueuedMessageContext } from '~/hooks/Chat/useSteering';
-import type { SteerReceiptState } from '~/components/Chat/Steering/Receipt';
-import type { PendingSteer } from '~/store/families';
-import type { MenuEntry } from './SteerMenu';
-import {
- RowMenu,
- EscalateNowButton,
- useDefaultToggleEntry,
- useInterruptToggleEntry,
-} from './SteerMenu';
-import { carriedSteerContext, cn, hydrateFileDeliveryMetadata, usesImagePreview } from '~/utils';
-import FilePreviewDialog from '~/components/Chat/Messages/Content/FilePreviewDialog';
-import { supportsGenerationProtocolV2, useArmSteerMutation } from '~/data-provider';
-import { steerOverlayHeightFamily, escalatingSteerFamily } from '~/store/steer';
-import MessageQuotes from '~/components/Chat/Messages/Content/MessageQuotes';
-import { QUEUE_ICON, STEER_ICON } from '~/components/Chat/Steering/identity';
-import MarkdownLite from '~/components/Chat/Messages/Content/MarkdownLite';
-import FileContainer from '~/components/Chat/Input/Files/FileContainer';
-import { useSteerCancel, useSteerReclaim, useLocalize } from '~/hooks';
-import ImagePreview from '~/components/Chat/Input/Files/ImagePreview';
-import SteerReceipt from '~/components/Chat/Steering/Receipt';
-import { useFileMapContext } from '~/Providers';
-import store from '~/store';
-
-/** Restores a message's text into the composer, or refuses (false) when the
- * composer is occupied / on another chat — see `restoreReclaimedSteer` in
- * `ChatForm`. Shared by the in-flight cancel and the queued trash safety net. */
-export type RestoreToComposer = (
- text: string,
- files: TMessage['files'],
- context: QueuedMessageContext,
- originConversationId: string,
-) => boolean;
-
-const splitFiles = (files?: TMessage['files']) => {
- const images: NonNullable<TMessage['files']> = [];
- const others: NonNullable<TMessage['files']> = [];
- for (const file of files ?? []) {
- (usesImagePreview(file) ? images : others).push(file);
- }
- return { images, others };
-};
-
-/** Collapsed preview height (px) for a long steer before "Show more". Matched
- * to the JS overflow check below so the toggle appears exactly when clipped;
- * the tolerance absorbs the trailing markdown margin so content that fits but
- * for its own bottom margin does not trip a pointless toggle. */
-const STEER_COLLAPSED_MAX_HEIGHT = 128;
-const STEER_OVERFLOW_TOLERANCE = 8;
-/** Axios has no default request timeout. Bound the UI lock while preserving an
- * honest unknown outcome; the idempotent arm may still complete server-side. */
-const ARM_CONFIRM_TIMEOUT_MS = 10_000;
-
-/** Live-region copy per receipt state, announced on transitions only. */
-const RECEIPT_ANNOUNCEMENTS = {
- sending: 'com_ui_steer_sending',
- delivered: 'com_ui_steer_delivered',
- interrupting: 'com_ui_steer_in_flight_preempt',
- applied: 'com_ui_steer_applied_info',
-} as const;
-
-/** The control rail flanking a bubble. `py-3` reproduces the bubble's own
- * first-line band — its `py-2.5` padding, its 1px border, and half the gap
- * between the 24px control and the taller text line box — so a 24px control
- * centers on the first line: visually centered beside a one-line steer, and
- * aligned to the opening line of a tall one rather than adrift in its middle.
- * `sticky` then keeps it in view while a tall steer scrolls past (the stack
- * scrolls once it passes 35vh); the matching `pt-2` on the overlay means the
- * topmost rail already clears the sticky inset, so it is not shoved down at
- * rest while the rails below it — which never trip the inset — stay put. */
-const STEER_CONTROL_RAIL = 'sticky top-2 flex shrink-0 items-center py-3';
-
-type ArmFailure = {
- name?: string;
- response?: { data?: { code?: string } };
-};
-
-/** Only a failure without an HTTP response leaves the server-side outcome
- * unknown. An HTTP rejection is a known response and must not replay the arm. */
-const isAmbiguousArmFailure = (error: unknown): boolean => {
- const failure = error as ArmFailure | null | undefined;
- return failure?.name !== 'AbortError' && failure?.response == null;
-};
-
-const armFailureCode = (error: unknown): string | undefined =>
- (error as ArmFailure | null | undefined)?.response?.data?.code;
-
-/**
- * One steer on its way into the run, anchored above the composer as a message
- * bubble rather than a control chip — the words are already part of the
- * conversation, they just have no in-thread index yet. It leaves on
- * `on_steer_applied`, when the persisted STEER part lands at its authoritative
- * position in the response.
- *
- * Text and attachments render through the same leaves as the applied
- * `SteerPart` (markdown toggle, file preview) so the words don't reformat the
- * moment the server injects them.
- *
- * `sending` is still awaiting its 202 ACK (no server id yet, so nothing to
- * cancel); `pending` is acknowledged and waiting on the next tool-batch
- * boundary. Every control here reclaims the steer from the server queue first,
- * so they are offered only once `pending` — while `sending` there is no id to
- * reclaim with, and the words cannot be held back.
- */
-const InFlightSteer = memo(function InFlightSteer({
- steer,
- steering,
- conversationId,
- interruptPending,
- onRestoreToComposer,
-}: {
- steer: PendingSteer;
- steering: SteeringControls;
- conversationId: string;
- interruptPending: boolean;
- onRestoreToComposer: RestoreToComposer;
-}) {
- const localize = useLocalize();
- const { showToast } = useToastContext();
- const cancelSteer = useSteerCancel(conversationId);
- const reclaimSteer = useSteerReclaim(conversationId);
- const toggleEntry = useDefaultToggleEntry(steering);
- const interruptToggle = useInterruptToggleEntry();
- const enableUserMsgMarkdown = useRecoilValue<boolean>(store.enableUserMsgMarkdown);
- const activeGenerationCreatedAt = useRecoilValue(
- store.activeGenerationCreatedAtByConvoId(conversationId),
- );
- const activeGenerationProtocolVersion = useRecoilValue(
- store.activeGenerationProtocolVersionByConvoId(conversationId),
- );
- const [selectedFile, setSelectedFile] = useState<Partial<TFile> | null>(null);
- const optionsButtonRef = useRef<HTMLButtonElement>(null);
- const [escalationAnnouncement, setEscalationAnnouncement] = useState('');
- const handlePreviewClose = useCallback((open: boolean) => {
- if (!open) {
- setSelectedFile(null);
- }
- }, []);
-
- const { images, others } = useMemo(() => splitFiles(steer.files), [steer.files]);
- const sending = steer.status === 'sending';
- const preempting = steer.preempt === true;
- /** This row's own arm request is in flight (the convo-scoped escalating flag
- * cannot say WHICH row asked). The receipt must react on the click, not the
- * ACK — the silent round trip is exactly what reads as broken. */
- const [arming, setArming] = useState(false);
- /** An interrupt shows as interrupting even before its confirmation (the
- * click must react instantly); `confirmed` withholds the check until the
- * server durably acknowledged the enqueue/arm. A relabelled chip
- * (`preempt` true past `sending`) IS that confirmation — the SSE
- * `steer_updated` can deliver it while the arm HTTP response is still in
- * flight, and the check must not wait out that round trip. */
- let receiptState: SteerReceiptState = 'delivered';
- if (preempting || arming) {
- receiptState = 'interrupting';
- } else if (sending) {
- receiptState = 'sending';
- }
- const receiptConfirmed = preempting ? !sending : !arming;
-
- /** Mirrors each receipt TRANSITION into the row's polite live region so
- * keyboard and screen-reader users get the same immediate confirmation the
- * visible marks give; the initial state is not replayed on mount. */
- const prevReceiptStateRef = useRef(receiptState);
- useEffect(() => {
- if (prevReceiptStateRef.current === receiptState) {
- return;
- }
- prevReceiptStateRef.current = receiptState;
- setEscalationAnnouncement(localize(RECEIPT_ANNOUNCEMENTS[receiptState]));
- }, [receiptState, localize]);
-
- /** Long steers (several paragraphs) collapse to a preview so the stack stays
- * scannable; the toggle is offered only once the content actually overflows
- * the cap. `scrollHeight` reports the full height even while clamped, so the
- * same check holds whether expanded or not, and the observer re-measures on
- * the width reflows that change wrapped-line count. */
- const contentRef = useRef<HTMLDivElement>(null);
- const contentId = useId();
- const [expanded, setExpanded] = useState(false);
- const [overflowing, setOverflowing] = useState(false);
- useEffect(() => {
- const el = contentRef.current;
- if (el == null) {
- return;
- }
- const measure = () =>
- setOverflowing(el.scrollHeight - STEER_COLLAPSED_MAX_HEIGHT > STEER_OVERFLOW_TOLERANCE);
- measure();
- if (typeof ResizeObserver === 'undefined') {
- return;
- }
- const observer = new ResizeObserver(measure);
- observer.observe(el);
- return () => observer.disconnect();
- }, []);
-
- /** Relabels the chip in place once the server confirms the durable arm —
- * same steerId, same position, only the `preempt` flag flips. */
- const markSteerPreempt = useRecoilCallback(
- ({ set }) =>
- (steerId: string, revision: number) =>
- set(store.pendingSteersByConvoId(conversationId), (prev) =>
- prev.map((item) =>
- item.steerId === steerId && revision >= (item.preemptRevision ?? 0)
- ? { ...item, preempt: true, preemptRevision: revision }
- : item,
- ),
- ),
- [conversationId],
- );
- const { mutateAsync: armSteer } = useArmSteerMutation();
- const setEscalating = useSetAtom(escalatingSteerFamily(conversationId));
-
- /**
- * Escalate this waiting steer to an interrupt: one idempotent server op
- * flips `preempt` on the EXISTING queued item, so its FIFO position, id, and
- * timestamp survive and there is no reclaim window to race. A transport
- * failure is retried once because the first request may have committed even
- * though its response was lost. Every "too late" interleaving (drained,
- * cancelled, run ended or replaced) is the same honest `armed: false`, and
- * the chip is only relabelled on a confirmed durable arm. The escalating
- * flag flips synchronously, before the request: the chip-derived gate cannot
- * see this arm until the response lands, and the other escalation controls
- * advertise "one interrupt at a time".
- */
- const escalate = useCallback(
- (event: React.MouseEvent<HTMLButtonElement>) => {
- const generationCreatedAt =
- steer.generationCreatedAt ?? activeGenerationCreatedAt ?? undefined;
- if (generationCreatedAt == null) {
- return;
- }
- const trigger = event.currentTarget;
- setEscalationAnnouncement('');
- setEscalating(true);
- setArming(true);
- const params = {
- conversationId,
- steerId: steer.steerId,
- ...(generationCreatedAt != null && { generationCreatedAt }),
- };
- const requestArm = async () => {
- let firstResponseWasLost = false;
- let acceptingRetry = true;
- let timeout: ReturnType<typeof setTimeout> | undefined;
- try {
- const firstAttempt = armSteer(params);
- const attempts =
- activeGenerationProtocolVersion === 2
- ? firstAttempt.catch((error) => {
- /** If the overall confirmation window already closed, do not let a
- * very late rejection launch a detached retry behind the user's
- * back. The first request itself may still have committed. */
- if (!acceptingRetry) {
- throw error;
- }
- if (!isAmbiguousArmFailure(error)) {
- throw error;
- }
- firstResponseWasLost = true;
- return armSteer(params);
- })
- : firstAttempt;
- const response = await Promise.race([
- attempts,
- new Promise<never>((_resolve, reject) => {
- timeout = setTimeout(
- () => reject(new Error('Steer arm confirmation timed out')),
- ARM_CONFIRM_TIMEOUT_MS,
- );
- }),
- ]);
- const responseSupportsNegotiatedProtocol =
- activeGenerationProtocolVersion === 1 || supportsGenerationProtocolV2(response);
- if (responseSupportsNegotiatedProtocol && response.armed === true) {
- /** The successful state removes the arm button. Move focus to the
- * stable options control only if the user has not moved elsewhere
- * while the request was pending. */
- if (document.activeElement === trigger) {
- optionsButtonRef.current?.focus();
- }
- setEscalationAnnouncement(localize('com_ui_steer_in_flight_preempt'));
- markSteerPreempt(steer.steerId, response.preemptRevision ?? 0);
- return;
- }
- if (!responseSupportsNegotiatedProtocol) {
- showToast({ message: localize('com_ui_steer_arm_unconfirmed'), status: 'warning' });
- return;
- }
- /** Once a response was lost, a later `armed: false` cannot prove the
- * first request did not commit: the steer may have drained or the job
- * may have paused between attempts. Keep the chip event-driven and
- * report the result as unknown instead of claiming a lost race. */
- if (firstResponseWasLost) {
- showToast({ message: localize('com_ui_steer_arm_unconfirmed'), status: 'warning' });
- return;
- }
- /* `armed: false` is deliberately ambiguous — injected, cancelled,
- * re-homed, or run over — so the message only says the escalation
- * lost, and the chip defers to the events for what happened. */
- showToast({
- message: localize(
- response.code === 'PREEMPT_UNSUPPORTED'
- ? 'com_ui_steer_preempt_unsupported'
- : 'com_ui_steer_arm_lost_race',
- ),
- status: 'info',
- });
- } catch (error) {
- const ambiguous = isAmbiguousArmFailure(error);
- if (ambiguous) {
- showToast({
- message: localize('com_ui_steer_arm_unconfirmed'),
- status: 'warning',
- });
- return;
- }
- showToast({
- message: localize(
- armFailureCode(error) === 'PREEMPT_UNSUPPORTED'
- ? 'com_ui_steer_preempt_unsupported'
- : 'com_ui_steer_arm_lost_race',
- ),
- status: 'info',
- });
- } finally {
- acceptingRetry = false;
- clearTimeout(timeout);
- }
- };
- void requestArm().finally(() => {
- setEscalating(false);
- setArming(false);
- });
- },
- [
- armSteer,
- conversationId,
- steer.steerId,
- steer.generationCreatedAt,
- activeGenerationCreatedAt,
- activeGenerationProtocolVersion,
- setEscalating,
- markSteerPreempt,
- showToast,
- localize,
- ],
- );
-
- /**
- * Takes the steer back off the server queue so its words can be re-homed.
- * The chip is left alone until the answer is known: only `reclaimed` proves
- * the words never entered the run, and the re-homing callers below own the
- * removal from there.
- */
- const reclaim = useCallback(async (): Promise<boolean> => {
- const outcome = await reclaimSteer(steer);
- if (outcome === 'reclaimed') {
- return true;
- }
- showToast({
- message: localize(
- outcome === 'applied' ? 'com_ui_steer_already_applied' : 'com_ui_steer_cancel_failed',
- ),
- status: outcome === 'applied' ? 'info' : 'error',
- });
- return false;
- }, [reclaimSteer, steer, showToast, localize]);
-
- const entries: MenuEntry[] = [
- {
- key: 'edit',
- label: localize('com_ui_edit_message'),
- icon: <Pencil className="h-4 w-4" aria-hidden="true" />,
- onClick: () => {
- void reclaim().then((reclaimed) => {
- if (!reclaimed) {
- return;
- }
- const restored = onRestoreToComposer(
- steer.text,
- steer.files,
- carriedSteerContext(steer),
- conversationId,
- );
- if (restored) {
- steering.removeSteer(steer.steerId);
- return;
- }
- /* The composer moved on while the reclaim was in flight. The words
- * are already off the server, so queue them rather than overwrite a
- * newer draft — neither text is the one to throw away. */
- steering.queueReclaimedSteer(steer);
- showToast({ message: localize('com_ui_steer_edit_queued'), status: 'info' });
- });
- },
- },
- {
- /* Non-destructive, but only when it is safe: cancel reliably first (the
- * optimistic hook removes the chip and restores it if the server would
- * still inject), then hand the words back to the composer ONLY on a
- * `reclaimed` outcome. On `applied` (cancel lost the race) or `failed`
- * the steer may still reach the run, so restoring would duplicate the
- * text — in the response, or beside the restored bubble. The gated
- * restore also refuses rather than clobber a draft typed meanwhile. */
- key: 'cancel',
- label: localize('com_ui_steer_cancel'),
- icon: <X className="h-4 w-4" aria-hidden="true" />,
- onClick: () => {
- void cancelSteer(steer).then((outcome) => {
- if (outcome !== 'reclaimed') {
- return;
- }
- // useSteerReclaim has tombstoned both ids and removed any terminal
- // recovery copy, so exactly one client destination is restored here.
- const restored = onRestoreToComposer(
- steer.text,
- steer.files,
- carriedSteerContext(steer),
- conversationId,
- );
- if (!restored) {
- /* Reclaimed, but the composer moved on (draft typed, answer mode,
- * navigated). The chip is already gone, so queue the words as Edit
- * does rather than drop them — never lost, just re-homed. */
- steering.queueReclaimedSteer(steer);
- showToast({ message: localize('com_ui_steer_edit_queued'), status: 'info' });
- }
- });
- },
- },
- {
- key: 'queue',
- label: localize('com_ui_convert_to_queue'),
- icon: <Clock className={cn('h-4 w-4', QUEUE_ICON)} aria-hidden="true" />,
- onClick: () => {
- void reclaim().then((reclaimed) => {
- if (reclaimed) {
- steering.queueReclaimedSteer(steer);
- }
- });
- },
- },
- ];
- const preferences: MenuEntry[] = [toggleEntry, interruptToggle];
-
- return (
- <div
- role="listitem"
- data-testid="in-flight-steer"
- data-steer-status={steer.status}
- data-steer-preempt={preempting ? 'true' : undefined}
- /* pointer-events-auto: the overlay container disables events so wheeling
- * over the gaps reaches the messages behind; each bubble re-enables them
- * for its own controls and internal scroll. */
- className="group pointer-events-auto flex max-w-full flex-col items-end gap-1.5"
- >
- {(images.length > 0 || others.length > 0) && (
- <div className="flex flex-wrap items-center justify-end gap-2">
- {others.map((file) => (
- <FileContainer
- key={file.file_id}
- file={file as TFile}
- onClick={() => setSelectedFile(file)}
- />
- ))}
- {images.map((file) => (
- <div
- key={file.file_id}
- className="border-border-light overflow-hidden rounded-xl border"
- >
- <ImagePreview
- url={file.preview ?? file.filepath}
- alt={file.filename ?? localize('com_ui_attached_image')}
- />
- </div>
- ))}
- </div>
- )}
- {/* Mirrors the user turn: the whole group hugs the right edge like every
- * other message the user wrote. The two controls flank the bubble rather
- * than stacking beside each other — the overflow menu outboard-left, the
- * send-now arrow outboard-right — so neither can read as belonging to
- * the other, and the pairing repeats cleanly when steers stack.
- * items-start so the sticky controls have room to travel — see below. */}
- <div className="flex max-w-full items-start gap-1.5">
- {!sending && (
- /* One always-visible affordance: a label-less menu hidden until hover
- * is undiscoverable, and edit/queue/cancel all live inside it now, so
- * the menu shows at rest on every pointer (matching the always-on
- * controls on the queued rows). `sticky` keeps it in view while the
- * user scrolls through a tall, expanded steer (the stack scrolls once
- * it passes 35vh). */
- <div data-testid="steer-controls" className={cn(STEER_CONTROL_RAIL, 'gap-1')}>
- <RowMenu
- label={localize('com_ui_more_options')}
- entries={entries}
- preferences={preferences}
- buttonRef={optionsButtonRef}
- />
- </div>
- )}
- <div
- className={cn(
- /* Same bubble geometry as the applied `SteerPart` and every user
- * turn, so the words don't reshape when the server injects them. */
- 'rounded-theme-surface rounded-br-theme-control flex min-w-0 items-start gap-2',
- /* Outlined, not just filled: an in-flight steer is provisional —
- * the fill alone reads as a settled message. */
- 'border-border-medium bg-surface-secondary border',
- 'px-theme-normal text-text-primary py-2.5 text-sm',
- sending && 'opacity-70',
- )}
- >
- <MorphIcon
- icon={preempting ? ZapOff : Zap}
- className={cn('mt-1 h-3.5 w-3.5 shrink-0', STEER_ICON)}
- />
- <span className="sr-only">
- {localize(preempting ? 'com_ui_steer_in_flight_preempt' : 'com_ui_steer_in_flight')}
- </span>
- <div className="flex min-w-0 flex-col items-start gap-1">
- {/* Same reference blocks the applied `SteerPart` shows, outside the
- * collapse so the excerpts stay visible while a long steer clips. */}
- <MessageQuotes quotes={steer.quotes} />
- <div
- ref={contentRef}
- id={contentId}
- className={cn('relative w-full', !expanded && 'overflow-hidden')}
- style={!expanded ? { maxHeight: STEER_COLLAPSED_MAX_HEIGHT } : undefined}
- >
- <div
- className={cn(
- 'markdown prose message-content dark:prose-invert light min-w-0 break-words',
- 'text-text-primary!',
- !enableUserMsgMarkdown && 'whitespace-pre-wrap',
- )}
- >
- {/* No code execution: this bubble sits outside MessageContext, so
- * Run Code would fire with no message/part to target. */}
- {enableUserMsgMarkdown ? (
- <MarkdownLite content={steer.text} codeExecution={false} />
- ) : (
- steer.text
- )}
- </div>
- {!expanded && overflowing && (
- <div
- className="from-surface-secondary pointer-events-none absolute inset-x-0 bottom-0 h-10 bg-gradient-to-t to-transparent"
- aria-hidden="true"
- />
- )}
- </div>
- {overflowing && (
- <button
- type="button"
- onClick={() => setExpanded((prev) => !prev)}
- aria-expanded={expanded}
- aria-controls={contentId}
- className="text-text-secondary hover:text-text-primary focus-visible:ring-border-xheavy inline-flex items-center gap-1 rounded text-xs font-medium focus-visible:ring-2 focus-visible:outline-hidden"
- >
- <MorphIcon icon={expanded ? ChevronUp : ChevronDown} className="h-3.5 w-3.5" />
- {expanded ? localize('com_ui_show_less') : localize('com_ui_show_more')}
- </button>
- )}
- </div>
- </div>
- {!sending && !preempting && (
- /* Sticky for the same reason as the menu: a tall, expanded steer must
- * never scroll its send-now out of reach. */
- <div className={STEER_CONTROL_RAIL}>
- <EscalateNowButton
- surface="bubble"
- messageText={steer.text}
- disabled={interruptPending || steering.pausedOnApproval || !steering.duringRunActive}
- onClick={escalate}
- />
- </div>
- )}
- </div>
- {/* Delivery receipt under the bubble, iMessage-style: present from the
- * first frame so the status never flickers in from nothing, and every
- * advance (Sending → Delivered ✓ → Interrupting) is an event the server
- * actually confirmed. The margin re-aligns it under the bubble's right
- * edge when the outboard send-now rail (24px control + 6px gap) is
- * present; the rail hides while sending or already escalated. */}
- <SteerReceipt
- state={receiptState}
- confirmed={receiptConfirmed}
- className={!sending && !preempting ? 'mr-[30px]' : undefined}
- />
- <span role="status" aria-live="polite" aria-atomic="true" className="sr-only">
- {escalationAnnouncement}
- </span>
- {others.length > 0 && (
- <FilePreviewDialog
- open={selectedFile !== null}
- onOpenChange={handlePreviewClose}
- fileName={selectedFile?.filename ?? ''}
- fileId={selectedFile?.file_id}
- filePath={selectedFile?.filepath}
- fileType={selectedFile?.type ?? undefined}
- fileSource={selectedFile?.source}
- fileSize={(selectedFile as TFile | null)?.bytes}
- deliveryPath={selectedFile?.llmDeliveryPath}
- />
- )}
- </div>
- );
-});
-
-/**
- * Steers the server hasn't applied yet, stacked directly above the composer.
- * Anchoring them here (instead of guessing an in-thread injection point on the
- * streaming message) keeps the thread showing only what the server actually
- * committed, while the user still sees their words land somewhere stable.
- */
-const InFlightSteers = memo(function InFlightSteers({
- steering,
- conversationId,
- onRestoreToComposer,
-}: {
- steering: SteeringControls;
- conversationId: string;
- onRestoreToComposer: RestoreToComposer;
-}) {
- const localize = useLocalize();
- const steers = useRecoilValue(store.pendingSteersByConvoId(conversationId));
- const fileMap = useFileMapContext();
- const inFlight = useMemo(
- () =>
- steers
- .filter((steer) => steer.status !== 'failed')
- .map((steer) => {
- const files = hydrateFileDeliveryMetadata(steer.files, undefined, fileMap);
- return files === steer.files ? steer : { ...steer, files };
- }),
- [fileMap, steers],
- );
- /** Mirrors `PendingSteerChips`: while one interrupt is unresolved, every
- * other escalation control disables rather than arming a second seal. The
- * escalating flag covers an arm request's round trip, before its chip
- * relabels for the chip-derived check to see. */
- const escalating = useAtomValue(escalatingSteerFamily(conversationId));
- const interruptPending = useMemo(
- () => escalating || inFlight.some((steer) => steer.preempt === true),
- [escalating, inFlight],
- );
- const setOverlayHeight = useSetAtom(steerOverlayHeightFamily(conversationId));
-
- /** Steers append newest-last, so an overflowing stack would sit scrolled to
- * the oldest — the steer just submitted (and its cancel) would be below the
- * fold and read as dropped. Keyed on the newest id, not every render. */
- const listRef = useRef<HTMLDivElement>(null);
- const newestId = inFlight[inFlight.length - 1]?.steerId;
- useEffect(() => {
- const list = listRef.current;
- if (list != null) {
- list.scrollTop = list.scrollHeight;
- }
- }, [newestId]);
-
- /** The overlay is pulled out of flow (absolute), so the messages no longer
- * shrink to fit it. Publish its rendered height so the message scroll area
- * can reserve an equal band of bottom padding — keeping the newest message
- * clear of the overlay at rest while older ones scroll behind it. */
- useEffect(() => {
- const list = listRef.current;
- if (list == null) {
- setOverlayHeight(0);
- return;
- }
- const publish = () => setOverlayHeight(list.offsetHeight);
- publish();
- if (typeof ResizeObserver === 'undefined') {
- return;
- }
- const observer = new ResizeObserver(publish);
- observer.observe(list);
- return () => observer.disconnect();
- }, [setOverlayHeight, inFlight.length]);
-
- /** Drop the reserved band when the overlay leaves (run ends while steers are
- * still in flight, or conversation switch) — the measure effect above only
- * resets when it re-runs, which unmount does not do. */
- useEffect(() => () => setOverlayHeight(0), [setOverlayHeight]);
-
- if (inFlight.length === 0) {
- return null;
- }
-
- return (
- <div
- ref={listRef}
- role="list"
- aria-label={localize('com_ui_steer_in_flight')}
- data-testid="in-flight-steers"
- /* Floats above the composer over the bottom of the thread instead of
- * displacing it, so scrolling up reveals the messages behind. Height is
- * capped: a steer runs to 16k chars and a run takes up to 10 of them;
- * unbounded it would cover the whole thread. Width is not — `inset-x-0`
- * takes the width of the composer the steer was typed into, so the stack
- * ends where that composer ends at every desktop width (`xl:max-w-4xl`,
- * maximized chat space) instead of drifting inboard against a second,
- * narrower cap of its own; `p-2` then lands the send-now arrow in the
- * same column as the composer's own send button (`mr-2` + border).
- * pointer-events-none lets wheeling over the gaps reach those messages
- * (each bubble opts back in). */
- className="pointer-events-none absolute inset-x-0 bottom-full flex max-h-[35vh] flex-col items-end gap-2 overflow-y-auto p-2"
- >
- {inFlight.map((steer) => (
- <InFlightSteer
- key={steer.steerId}
- steer={steer}
- steering={steering}
- conversationId={conversationId}
- interruptPending={interruptPending}
- onRestoreToComposer={onRestoreToComposer}
- />
- ))}
- </div>
- );
-});
-
-export default InFlightSteers;
diff --git a/client/src/components/Chat/Input/MCPSelect.tsx b/client/src/components/Chat/Input/MCPSelect.tsx
deleted file mode 100644
index 38d6914019..0000000000
--- a/client/src/components/Chat/Input/MCPSelect.tsx
+++ /dev/null
@@ -1,172 +0,0 @@
-import React, { memo, useRef, useMemo, useEffect } from 'react';
-import * as Ariakit from '@ariakit/react';
-import { ChevronDown } from 'lucide-react';
-import { PermissionTypes, Permissions } from 'librechat-data-provider';
-import { TooltipAnchor, composerControlClasses } from '@librechat/client';
-import MCPServerMenuItem from '~/components/MCP/MCPServerMenuItem';
-import MCPConfigDialog from '~/components/MCP/MCPConfigDialog';
-import StackedMCPIcons from '~/components/MCP/StackedMCPIcons';
-import { useMCPRefresh } from '~/hooks/MCP/useMCPRefresh';
-import { useHasAccess, useLocalize } from '~/hooks';
-import { useBadgeRowContext } from '~/Providers';
-import { cn } from '~/utils';
-
-function MCPSelectContent() {
- const localize = useLocalize();
- const context = useBadgeRowContext();
- const { conversationId, storageContextKey, mcpServerManager: manager } = context ?? {};
-
- const menuStore = Ariakit.useMenuStore({ focusLoop: true });
- const isOpen = menuStore.useState('open');
- const configDialogOpen = manager?.getConfigDialogProps()?.isOpen === true;
- useMCPRefresh({
- enabled: (isOpen || configDialogOpen) && (manager?.availableMCPServers.length ?? 0) > 0,
- });
-
- /**
- * The menu closes with the dialog it launched. Ariakit only takes Escape for
- * a menu when the event target is the menu, its trigger, or `body`, so while
- * the config dialog holds focus the menu never sees it — the Escape that
- * closes the dialog leaves the menu open behind it, and `disabled={isOpen}`
- * then makes its trigger unclickable, stranding the reader
- * (`mcp-oauth-readiness` e2e). Keyed on the dialog CLOSING, not opening: the
- * menu stays mounted underneath while the dialog is up, which is where its
- * server rows are read from.
- */
- const configDialogWasOpen = useRef(false);
- useEffect(() => {
- if (configDialogWasOpen.current && !configDialogOpen) {
- menuStore.hide();
- }
- configDialogWasOpen.current = configDialogOpen;
- }, [configDialogOpen, menuStore]);
-
- const selectedServers = useMemo(() => {
- if (!manager?.mcpValues || manager.mcpValues.length === 0) {
- return [];
- }
- const selectedSet = new Set(manager.mcpValues);
- return manager.selectableServers?.filter((s) => selectedSet.has(s.serverName)) ?? [];
- }, [manager?.selectableServers, manager?.mcpValues]);
-
- /** Counts what the menu actually offers, never the raw selection: a name the
- * catalog has not returned — or one the admin has hidden — renders no row,
- * and billing it to the badge reads as a server that cannot be turned off. */
- const displayText = useMemo(() => {
- const selectedCount = selectedServers.length;
- if (selectedCount === 0) {
- return null;
- }
- if (selectedCount === 1) {
- const server = selectedServers[0];
- return server.config?.title || server.serverName;
- }
- return localize('com_ui_x_selected', { 0: selectedCount });
- }, [selectedServers, localize]);
-
- if (!manager) {
- return null;
- }
-
- const {
- isPinned,
- mcpValues,
- isInitializing,
- placeholderText,
- connectionStatus,
- selectableServers,
- getConfigDialogProps,
- toggleServerSelection,
- getServerStatusIconProps,
- } = manager;
-
- if (!isPinned && mcpValues?.length === 0) {
- return null;
- }
-
- const configDialogProps = getConfigDialogProps();
-
- return (
- <>
- <Ariakit.MenuProvider store={menuStore}>
- <TooltipAnchor
- description={placeholderText}
- disabled={isOpen}
- render={
- <Ariakit.MenuButton
- className={cn(
- composerControlClasses(),
- 'min-w-theme-control px-2.5 md:w-fit md:justify-start md:px-theme-normal',
- isOpen && 'bg-surface-hover',
- )}
- />
- }
- >
- <StackedMCPIcons selectedServers={selectedServers} maxIcons={3} iconSize="sm" />
- <span className="hidden truncate text-text-primary md:block">
- {displayText || placeholderText}
- </span>
- <ChevronDown
- className={cn(
- 'hidden h-3 w-3 text-text-secondary transition-transform md:block',
- isOpen && 'rotate-180',
- )}
- />
- </TooltipAnchor>
-
- <Ariakit.Menu
- portal={true}
- gutter={8}
- modal={true}
- unmountOnHide={true}
- aria-label={localize('com_ui_mcp_servers')}
- className={cn(
- 'z-50 flex min-w-[260px] max-w-[320px] flex-col rounded-xl',
- 'border border-border-light bg-presentation p-1.5 shadow-lg',
- 'origin-top opacity-0 transition-[opacity,transform] duration-200 ease-out',
- 'data-[enter]:scale-100 data-[enter]:opacity-100',
- 'scale-95 data-[leave]:scale-95 data-[leave]:opacity-0',
- )}
- >
- <div className="flex max-h-[320px] flex-col gap-1 overflow-y-auto">
- {selectableServers.map((server) => (
- <MCPServerMenuItem
- key={server.serverName}
- server={server}
- isSelected={mcpValues?.includes(server.serverName) ?? false}
- connectionStatus={connectionStatus}
- isInitializing={isInitializing}
- statusIconProps={getServerStatusIconProps(server.serverName)}
- onToggle={toggleServerSelection}
- />
- ))}
- </div>
- </Ariakit.Menu>
- </Ariakit.MenuProvider>
- {configDialogProps && (
- <MCPConfigDialog
- {...configDialogProps}
- conversationId={conversationId}
- storageContextKey={storageContextKey}
- />
- )}
- </>
- );
-}
-
-function MCPSelect() {
- const context = useBadgeRowContext();
- const { selectableServers } = context?.mcpServerManager ?? {};
- const canUseMcp = useHasAccess({
- permissionType: PermissionTypes.MCP_SERVERS,
- permission: Permissions.USE,
- });
-
- if (!canUseMcp || !selectableServers || selectableServers.length === 0) {
- return null;
- }
-
- return <MCPSelectContent />;
-}
-
-export default memo(MCPSelect);
diff --git a/client/src/components/Chat/Input/MCPSubMenu.tsx b/client/src/components/Chat/Input/MCPSubMenu.tsx
deleted file mode 100644
index e91dad0c79..0000000000
--- a/client/src/components/Chat/Input/MCPSubMenu.tsx
+++ /dev/null
@@ -1,133 +0,0 @@
-import React from 'react';
-import * as Ariakit from '@ariakit/react';
-import { ChevronRight } from 'lucide-react';
-import { MCPIcon, PinIcon } from '@librechat/client';
-import MCPServerMenuItem from '~/components/MCP/MCPServerMenuItem';
-import MCPConfigDialog from '~/components/MCP/MCPConfigDialog';
-import { useMCPRefresh } from '~/hooks/MCP/useMCPRefresh';
-import { useBadgeRowContext } from '~/Providers';
-import { useLocalize } from '~/hooks';
-import { cn } from '~/utils';
-
-interface MCPSubMenuProps extends React.HTMLAttributes<HTMLButtonElement> {
- placeholder?: string;
-}
-
-const MCPSubMenu = React.forwardRef<HTMLButtonElement, MCPSubMenuProps>(
- ({ placeholder, className, ...props }, ref) => {
- const localize = useLocalize();
- const context = useBadgeRowContext();
- const { storageContextKey, mcpServerManager } = context ?? {};
-
- const menuStore = Ariakit.useMenuStore({
- focusLoop: true,
- showTimeout: 100,
- placement: 'right',
- });
-
- const isOpen = menuStore.useState('open');
- const configDialogOpen = mcpServerManager?.getConfigDialogProps()?.isOpen === true;
- useMCPRefresh({
- enabled:
- (isOpen || configDialogOpen) && (mcpServerManager?.selectableServers.length ?? 0) > 0,
- });
-
- if (!mcpServerManager) {
- return null;
- }
-
- const {
- isPinned,
- mcpValues,
- setIsPinned,
- isInitializing,
- placeholderText,
- connectionStatus,
- selectableServers,
- getConfigDialogProps,
- toggleServerSelection,
- getServerStatusIconProps,
- } = mcpServerManager;
-
- if (!selectableServers || selectableServers.length === 0) {
- return null;
- }
-
- const configDialogProps = getConfigDialogProps();
-
- return (
- <>
- <Ariakit.MenuProvider store={menuStore}>
- <Ariakit.MenuButton
- ref={ref}
- {...props}
- onClick={(e: React.MouseEvent<HTMLButtonElement>) => {
- e.stopPropagation();
- menuStore.toggle();
- }}
- className={cn(
- 'hover:bg-surface-hover flex w-full cursor-pointer items-center justify-between rounded-lg p-2',
- className,
- )}
- >
- <div className="flex items-center gap-2">
- <MCPIcon className="text-text-primary h-5 w-5 shrink-0" aria-hidden="true" />
- <span>{placeholder || placeholderText}</span>
- <ChevronRight className="h-3 w-3 shrink-0" aria-hidden="true" />
- </div>
- <button
- type="button"
- onClick={(e) => {
- e.stopPropagation();
- setIsPinned(!isPinned);
- }}
- className={cn(
- 'rounded p-1 transition-all duration-200',
- 'hover:bg-surface-tertiary hover:shadow-xs',
- !isPinned && 'text-text-secondary hover:text-text-primary',
- )}
- aria-label={isPinned ? localize('com_ui_unpin') : localize('com_ui_pin')}
- >
- <div className="h-4 w-4">
- <PinIcon unpin={isPinned} />
- </div>
- </button>
- </Ariakit.MenuButton>
-
- <Ariakit.Menu
- portal={true}
- unmountOnHide={true}
- gutter={12}
- flip="left bottom-end top-end"
- aria-label={localize('com_ui_mcp_servers')}
- className={cn(
- 'animate-popover-left z-40 flex max-w-[min(320px,calc(100vw-1rem))] min-w-[min(260px,calc(100vw-1rem))] flex-col rounded-xl',
- 'border-border-light bg-presentation border p-1.5 shadow-lg',
- )}
- >
- <div className="flex max-h-[320px] flex-col gap-1 overflow-y-auto">
- {selectableServers.map((server) => (
- <MCPServerMenuItem
- key={server.serverName}
- server={server}
- isSelected={mcpValues?.includes(server.serverName) ?? false}
- connectionStatus={connectionStatus}
- isInitializing={isInitializing}
- statusIconProps={getServerStatusIconProps(server.serverName)}
- onToggle={toggleServerSelection}
- />
- ))}
- </div>
- </Ariakit.Menu>
- </Ariakit.MenuProvider>
- {configDialogProps && (
- <MCPConfigDialog {...configDialogProps} storageContextKey={storageContextKey} />
- )}
- </>
- );
- },
-);
-
-MCPSubMenu.displayName = 'MCPSubMenu';
-
-export default React.memo(MCPSubMenu);
diff --git a/client/src/components/Chat/Input/Memory.tsx b/client/src/components/Chat/Input/Memory.tsx
deleted file mode 100644
index c99484241c..0000000000
--- a/client/src/components/Chat/Input/Memory.tsx
+++ /dev/null
@@ -1,40 +0,0 @@
-import React, { memo } from 'react';
-import { Brain } from 'lucide-react';
-import { CheckboxButton } from '@librechat/client';
-import { defaultAgentCapabilities } from 'librechat-data-provider';
-import { useLocalize, useHasMemoryAccess, useAgentCapabilities, useAuthContext } from '~/hooks';
-import { useBadgeRowContext } from '~/Providers';
-import { badgeAccents } from './accents';
-
-function Memory() {
- const localize = useLocalize();
- const { user } = useAuthContext();
- const context = useBadgeRowContext();
- const { toggleState: memoryActive, debouncedChange, isPinned } = context?.memory ?? {};
-
- const canUseMemory = useHasMemoryAccess();
-
- const { memoryEnabled } = useAgentCapabilities(
- context?.agentsConfig?.capabilities ?? defaultAgentCapabilities,
- );
-
- const hasOptedOut = user?.personalization?.memories === false;
-
- if (!canUseMemory || !memoryEnabled || hasOptedOut) {
- return null;
- }
-
- return (
- (memoryActive || isPinned) && (
- <CheckboxButton
- checked={memoryActive}
- setValue={debouncedChange}
- label={localize('com_ui_memory')}
- isCheckedClassName={badgeAccents.purple}
- icon={<Brain className="icon-md" aria-hidden="true" />}
- />
- )
- );
-}
-
-export default memo(Memory);
diff --git a/client/src/components/Chat/Input/PendingManualSkillsChips.tsx b/client/src/components/Chat/Input/PendingManualSkillsChips.tsx
deleted file mode 100644
index 29396723c0..0000000000
--- a/client/src/components/Chat/Input/PendingManualSkillsChips.tsx
+++ /dev/null
@@ -1,61 +0,0 @@
-import { memo, useCallback } from 'react';
-import { ScrollText, X } from 'lucide-react';
-import { useRecoilValue, useSetRecoilState } from 'recoil';
-import { useLocalize } from '~/hooks';
-import store from '~/store';
-
-/**
- * Chip row rendered above the textarea showing skills the user picked in
- * the `$` popover for the next submission. Each chip has an × button to
- * remove that skill before sending — primary purpose is new-chat UX where
- * there's no submitted user message yet to render `SkillPills` on.
- *
- * Reads + writes `pendingManualSkillsByConvoId` atom directly. The atom
- * gets drained in `useChatFunctions.ask` on submit, so chips naturally
- * disappear once the message is sent.
- */
-function PendingManualSkillsChips({ conversationId }: { conversationId: string }) {
- const localize = useLocalize();
- const skills = useRecoilValue(store.pendingManualSkillsByConvoId(conversationId));
- const setSkills = useSetRecoilState(store.pendingManualSkillsByConvoId(conversationId));
-
- const remove = useCallback(
- (name: string) => {
- setSkills((prev) => prev.filter((s) => s !== name));
- },
- [setSkills],
- );
-
- if (skills.length === 0) {
- return null;
- }
-
- return (
- <div
- className="flex flex-wrap gap-1.5 px-2 pt-2"
- role="list"
- aria-label={localize('com_ui_skills_queued')}
- >
- {skills.map((name) => (
- <span
- key={name}
- role="listitem"
- className="inline-flex items-center gap-1 rounded-full border border-border-light bg-surface-secondary px-2 py-0.5 text-xs text-text-secondary"
- >
- <ScrollText className="h-3 w-3 text-status-info" aria-hidden="true" />
- <span className="max-w-[12rem] truncate">{name}</span>
- <button
- type="button"
- aria-label={localize('com_ui_remove_skill_var', { 0: name })}
- onClick={() => remove(name)}
- className="-mr-0.5 ml-0.5 rounded-full p-0.5 text-text-secondary hover:bg-surface-tertiary hover:text-text-primary"
- >
- <X className="h-3 w-3" aria-hidden="true" />
- </button>
- </span>
- ))}
- </div>
- );
-}
-
-export default memo(PendingManualSkillsChips);
diff --git a/client/src/components/Chat/Input/PendingQuoteChips.tsx b/client/src/components/Chat/Input/PendingQuoteChips.tsx
deleted file mode 100644
index 1f00c53ec1..0000000000
--- a/client/src/components/Chat/Input/PendingQuoteChips.tsx
+++ /dev/null
@@ -1,211 +0,0 @@
-import { memo, useRef, useState, useEffect, useCallback } from 'react';
-import * as Ariakit from '@ariakit/react';
-import { TextQuote, X } from 'lucide-react';
-import { useRecoilValue, useSetRecoilState } from 'recoil';
-import { useLocalize } from '~/hooks';
-import store from '~/store';
-
-const CHIP_CLASS =
- 'inline-flex max-w-full items-center gap-1 rounded-2xl border border-border-light bg-surface-secondary px-2.5 py-1.5 text-sm text-text-secondary';
-const REMOVE_BTN_CLASS =
- '-mr-0.5 shrink-0 rounded-full p-0.5 text-text-secondary hover:bg-surface-tertiary hover:text-text-primary focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-border-xheavy';
-const TRIGGER_CLASS =
- 'inline-flex min-w-0 items-center gap-1.5 rounded-full focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-border-xheavy';
-/**
- * Quote mark. Semantic `status-info` rather than `cyan-500`, matching the queue
- * identity in `Chat/Steering/identity.ts`: the raw hue lands at 2.43:1 on the
- * high contrast light composer, under the 3:1 floor for a chip whose only type
- * cue is this icon.
- */
-const QUOTE_ICON_CLASS = 'h-4 w-4 shrink-0 text-status-info';
-/** Grace period so moving the pointer between the chip and the popup doesn't close it. */
-const CLOSE_DELAY_MS = 120;
-
-/**
- * Chip row rendered above the textarea for excerpts the user quoted via the
- * "Add to chat" selection popup. Shows a single chip: the excerpt text for one
- * selection, or a collapsed "{n} selections" pill for multiple — so the
- * composer never fills with a row of chips.
- *
- * The collapsed pill is an Ariakit `Popover` disclosure: it opens on
- * click / Enter / Space (keyboard users tab through the excerpts, Escape closes
- * and Ariakit restores focus to the trigger) and on hover for mouse users.
- * `autoFocusOnShow` is disabled so opening never pulls focus off the composer;
- * `autoFocusOnHide` still returns focus to the trigger when focus was inside.
- *
- * Reads + writes `pendingQuotesByConvoId` directly; the atom is drained on
- * every submit route — `useChatFunctions.ask` for a fresh send, and the
- * during-run steer/queue/interrupt paths in `useSteering` — so chips disappear
- * once the message is sent (the excerpts then re-render as `MessageQuotes` on
- * the user bubble, or inside the steer bubble for a mid-run injection).
- */
-function PendingQuoteChips({
- conversationId,
- focusComposer,
-}: {
- conversationId: string;
- /** The composer's guarded refocus, which skips touchscreens. */
- focusComposer?: () => void;
-}) {
- const localize = useLocalize();
- const quotes = useRecoilValue(store.pendingQuotesByConvoId(conversationId));
- const setQuotes = useSetRecoilState(store.pendingQuotesByConvoId(conversationId));
-
- const popover = Ariakit.usePopoverStore({ placement: 'top-start' });
- const closeTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
- /**
- * Ariakit only restores focus to the trigger on hide when it took focus on
- * show, so keep `autoFocusOnShow` on for keyboard/click opens (Escape returns
- * focus to the trigger) and off for hover so it never pulls focus off the
- * composer mid-typing.
- */
- const [focusOnShow, setFocusOnShow] = useState(true);
-
- const cancelClose = useCallback(() => {
- if (closeTimerRef.current != null) {
- clearTimeout(closeTimerRef.current);
- closeTimerRef.current = null;
- }
- }, []);
- const openByPointer = useCallback(() => {
- cancelClose();
- setFocusOnShow(false);
- popover.show();
- }, [cancelClose, popover]);
- const scheduleClose = useCallback(() => {
- cancelClose();
- closeTimerRef.current = setTimeout(() => popover.hide(), CLOSE_DELAY_MS);
- }, [cancelClose, popover]);
-
- useEffect(() => cancelClose, [cancelClose]);
-
- const clearAll = useCallback(() => setQuotes([]), [setQuotes]);
- /** The clicked remove button unmounts with its row, and the composer surface
- * does not refocus the textarea for clicks inside popup content, so restore
- * focus here: to the composer once the popup collapses, otherwise to the
- * remove button now at the same row (or the last one) once React has
- * re-rendered the list. */
- const pendingFocusIndexRef = useRef<number | null>(null);
- useEffect(() => {
- const index = pendingFocusIndexRef.current;
- if (index == null) {
- return;
- }
- pendingFocusIndexRef.current = null;
- const buttons = popover.getState().contentElement?.querySelectorAll('button');
- if (!buttons?.length) {
- return;
- }
- buttons[Math.min(index, buttons.length - 1)].focus();
- }, [quotes, popover]);
- const removeAt = useCallback(
- (index: number) => {
- setQuotes((prev) => prev.filter((_, i) => i !== index));
- if (quotes.length <= 2) {
- focusComposer?.();
- return;
- }
- pendingFocusIndexRef.current = index;
- },
- [setQuotes, quotes.length, focusComposer],
- );
-
- if (quotes.length === 0) {
- return null;
- }
-
- const isMulti = quotes.length > 1;
-
- return (
- <div
- className="flex flex-wrap gap-1.5 px-2 pt-2"
- role="list"
- aria-label={localize('com_ui_quotes_queued')}
- data-testid="pending-quote-chips"
- data-quote-count={quotes.length}
- >
- {!isMulti ? (
- <span role="listitem" className={CHIP_CLASS}>
- <TextQuote className={QUOTE_ICON_CLASS} aria-hidden="true" />
- <span className="max-w-[16rem] truncate" title={quotes[0]}>
- {quotes[0]}
- </span>
- <button
- type="button"
- aria-label={localize('com_ui_remove_quote')}
- onClick={clearAll}
- className={REMOVE_BTN_CLASS}
- >
- <X className="h-3.5 w-3.5" aria-hidden="true" />
- </button>
- </span>
- ) : (
- <>
- <span
- role="listitem"
- className={CHIP_CLASS}
- onPointerEnter={openByPointer}
- onPointerLeave={scheduleClose}
- >
- <Ariakit.PopoverDisclosure
- store={popover}
- className={TRIGGER_CLASS}
- aria-label={localize('com_ui_quote_selections', { 0: quotes.length })}
- onClick={() => setFocusOnShow(true)}
- >
- <TextQuote className={QUOTE_ICON_CLASS} aria-hidden="true" />
- <span className="truncate">
- {localize('com_ui_quote_selections', { 0: quotes.length })}
- </span>
- </Ariakit.PopoverDisclosure>
- <button
- type="button"
- aria-label={localize('com_ui_remove_all_quotes')}
- onClick={clearAll}
- className={REMOVE_BTN_CLASS}
- >
- <X className="h-3.5 w-3.5" aria-hidden="true" />
- </button>
- </span>
- <Ariakit.Popover
- store={popover}
- portal
- gutter={8}
- autoFocusOnShow={focusOnShow}
- data-testid="quote-selections-popup"
- onPointerEnter={cancelClose}
- onPointerLeave={scheduleClose}
- className="border-border-light bg-surface-secondary text-text-primary z-50 w-80 max-w-[90vw] rounded-xl border p-2 shadow-lg outline-hidden"
- >
- <ul className="flex flex-col gap-1" aria-label={localize('com_ui_referenced_quotes')}>
- {quotes.map((text, index) => (
- <li
- key={`${index}-${text.slice(0, 24)}`}
- className="hover:bg-surface-tertiary flex items-start gap-1.5 rounded-xl px-1.5 py-1"
- >
- <TextQuote
- className="text-text-tertiary mt-0.5 h-3.5 w-3.5 shrink-0"
- aria-hidden="true"
- />
- <span className="text-text-secondary line-clamp-2 flex-1 text-sm break-words whitespace-pre-wrap">
- {text}
- </span>
- <button
- type="button"
- aria-label={localize('com_ui_remove_quote')}
- onClick={() => removeAt(index)}
- className="text-text-secondary hover:bg-surface-hover hover:text-text-primary focus-visible:ring-border-xheavy mt-0.5 shrink-0 rounded-full p-0.5 focus-visible:ring-2 focus-visible:outline-hidden"
- >
- <X className="h-3.5 w-3.5" aria-hidden="true" />
- </button>
- </li>
- ))}
- </ul>
- </Ariakit.Popover>
- </>
- )}
- </div>
- );
-}
-
-export default memo(PendingQuoteChips);
diff --git a/client/src/components/Chat/Input/PendingSteerChips.tsx b/client/src/components/Chat/Input/PendingSteerChips.tsx
deleted file mode 100644
index b5986ad183..0000000000
--- a/client/src/components/Chat/Input/PendingSteerChips.tsx
+++ /dev/null
@@ -1,632 +0,0 @@
-import { memo, useMemo, useRef, useState, useCallback } from 'react';
-import { useAtomValue } from 'jotai';
-import { useRecoilValue } from 'recoil';
-import { createPortal } from 'react-dom';
-import { TooltipAnchor, useToastContext } from '@librechat/client';
-import {
- X,
- Zap,
- Send,
- Clock,
- Pencil,
- Trash2,
- Paperclip,
- RotateCcw,
- TextQuote,
- TriangleAlert,
-} from 'lucide-react';
-import type { TMessage } from 'librechat-data-provider';
-import type { ReactNode } from 'react';
-import type { SteeringControls, QueuedMessageContext } from '~/hooks/Chat/useSteering';
-import type { PendingSteer, QueuedMessage } from '~/store/families';
-import type { RestoreToComposer } from './InFlightSteers';
-import type { MenuEntry } from './SteerMenu';
-import {
- RowMenu,
- ICON_BTN_CLASS,
- PRIMARY_BTN_CLASS,
- EscalateNowButton,
- useDefaultToggleEntry,
- useInterruptToggleEntry,
-} from './SteerMenu';
-import {
- recoveryDispositionsFamily,
- recoveryDisposition,
-} from '~/components/Chat/Steering/recovery';
-import { useQueuedTurnPortal } from '~/components/Chat/Steering/QueuedTurnPortal';
-import { escalatingSteerFamily, revealedQueuedTurnFamily } from '~/store/steer';
-import { QUEUE_ICON, STEER_ICON } from '~/components/Chat/Steering/identity';
-import { useLocalize } from '~/hooks';
-import { cn } from '~/utils';
-import store from '~/store';
-
-const ROW_CLASS =
- 'flex w-full items-center gap-2 rounded-xl border border-border-light bg-surface-secondary px-3 py-2 text-sm text-text-primary';
-
-function ContextCount({
- icon,
- count,
- label,
-}: {
- icon: React.ReactNode;
- count: number;
- label: string;
-}) {
- if (count === 0) {
- return null;
- }
- return (
- <span className="text-text-secondary flex shrink-0 items-center gap-0.5 text-xs">
- {icon}
- {count}
- <span className="sr-only">{label}</span>
- </span>
- );
-}
-
-function AttachmentCount({ count, label }: { count: number; label: string }) {
- return (
- <ContextCount
- icon={<Paperclip className="h-3.5 w-3.5" aria-hidden="true" />}
- count={count}
- label={label}
- />
- );
-}
-
-function QuoteCount({ count, label }: { count: number; label: string }) {
- return (
- <ContextCount
- icon={<TextQuote className="h-3.5 w-3.5" aria-hidden="true" />}
- count={count}
- label={label}
- />
- );
-}
-
-/**
- * The one fact a queued row needs to convey ("did my message vanish?" it did
- * not) rides the clock as a hover hint and its accessible name while a run is
- * pending, instead of a caption row that costs composer height at rest. The
- * anchor is a tab stop with a visible ring so keyboard users reach the same
- * hint: the tooltip opens on focus-visible as well as on hover.
- */
-function QueuedIcon({ warning, hint }: { warning: boolean; hint?: string }) {
- if (warning) {
- return <TriangleAlert className="text-text-warning h-4 w-4 shrink-0" aria-hidden="true" />;
- }
- if (!hint) {
- return <Clock className={cn('h-4 w-4 shrink-0', QUEUE_ICON)} aria-hidden="true" />;
- }
- return (
- <TooltipAnchor
- focusOutline="hidden"
- description={hint}
- role="img"
- aria-label={hint}
- tabIndex={0}
- className="focus-visible:ring-border-xheavy flex shrink-0 cursor-help rounded-full focus-visible:ring-2"
- >
- <Clock className={cn('h-4 w-4', QUEUE_ICON)} aria-hidden="true" />
- </TooltipAnchor>
- );
-}
-
-function QueuedRow({
- message,
- steering,
- conversationId,
- interruptPending,
- inTurn = false,
- starting = false,
- actionPending,
- afterDiscard,
- onEditToComposer,
- onRestoreToComposer,
-}: {
- message: QueuedMessage;
- steering: SteeringControls;
- conversationId: string;
- interruptPending: boolean;
- /** A visible pending turn takes the place of this queue row. */
- inTurn?: boolean;
- starting?: boolean;
- actionPending: boolean;
- afterDiscard: (message: QueuedMessage, action: () => boolean) => void;
- onEditToComposer: (
- text: string,
- files?: TMessage['files'],
- context?: QueuedMessageContext,
- ) => void;
- onRestoreToComposer: RestoreToComposer;
-}) {
- const localize = useLocalize();
- const { showToast } = useToastContext();
- const toggleEntry = useDefaultToggleEntry(steering);
- const interruptToggle = useInterruptToggleEntry();
- const fileCount = message.files?.length ?? 0;
- const quoteCount = message.quotes?.length ?? 0;
- const dispositions = useAtomValue(recoveryDispositionsFamily(steering.queueKey));
- const disposition = recoveryDisposition(dispositions, message);
- const recoveryHeld = disposition != null;
- const recoveryBlocked = disposition === 'blocked' || disposition === 'cancelled';
- const recoveryPending = disposition === 'cancelling';
- actionPending = actionPending || recoveryPending;
- const isRecovered = message.recoverySteerId != null;
- const isRejected = message.server?.status === 'rejected';
- const isIndeterminate = message.server?.status === 'indeterminate';
- const isUnconfirmed =
- message.server?.status === 'uncertain' && message.server.reconciliationExpired === true;
- let statusLabel:
- | 'com_ui_queued_turn_reconciliation_required'
- | 'com_ui_steer_delivery_unconfirmed'
- | 'com_ui_queued_turn_failed'
- | 'com_ui_steer_recovery_held' = 'com_ui_queued_turn_failed';
- if (recoveryHeld) {
- statusLabel = 'com_ui_steer_recovery_held';
- } else if (isIndeterminate) {
- statusLabel = 'com_ui_queued_turn_reconciliation_required';
- } else if (isUnconfirmed) {
- statusLabel = 'com_ui_steer_delivery_unconfirmed';
- }
- const requiresDiscard = isRecovered || message.server?.id != null;
- const serverActionable =
- message.server == null ||
- message.server.status === 'rejected' ||
- (message.server.id != null && message.server.status === 'queued');
- // A recovered item is consumed atomically only when it starts a normal
- // generation. Re-steering it would leave or duplicate the parked source;
- // Edit/remove are safe because `afterDiscard` tombstones that source first.
- const canSteerNow = steering.duringRunActive && steering.canSteer && !isRecovered;
- const showPrimary =
- !starting &&
- !recoveryHeld &&
- serverActionable &&
- (canSteerNow || (!steering.duringRunActive && steering.canSendQueuedNow));
- /** `canSteer` is defined as false while paused on approval, but the
- * escalation control must stay visible-and-disabled there — hiding it
- * during the pause is exactly the discoverability gap this button fixes. */
- const showEscalate =
- !starting &&
- !isRecovered &&
- (steering.pausedOnApproval || (steering.duringRunActive && steering.canSteer));
-
- const edit = () => {
- const context = { quotes: message.quotes, manualSkills: message.manualSkills };
- if (!requiresDiscard) {
- steering.removeQueued(message.id);
- onEditToComposer(message.text, message.files, context);
- return;
- }
- afterDiscard(message, () => {
- const restored = onRestoreToComposer(message.text, message.files, context, conversationId);
- if (!restored) {
- showToast({ message: localize('com_ui_steer_edit_queued'), status: 'info' });
- return false;
- }
- steering.removeQueued(message.id);
- return true;
- });
- };
- const remove = () => {
- if (isUnconfirmed) {
- steering.removeQueued(message.id);
- return;
- }
- const finish = () => {
- onRestoreToComposer(
- message.text,
- message.files,
- { quotes: message.quotes, manualSkills: message.manualSkills },
- conversationId,
- );
- steering.removeQueued(message.id);
- return true;
- };
- if (!requiresDiscard) {
- finish();
- return;
- }
- afterDiscard(message, finish);
- };
- const removeDisabled =
- actionPending ||
- (!serverActionable &&
- !isUnconfirmed &&
- !(message.server?.id != null && message.server.status === 'claimed'));
- if (inTurn) {
- const actionClass = cn(ICON_BTN_CLASS, 'disabled:cursor-not-allowed disabled:opacity-50');
- return (
- <>
- {message.server?.status === 'queued' && (
- <button
- type="button"
- className={actionClass}
- aria-label={localize('com_ui_edit_message')}
- disabled={actionPending}
- onClick={edit}
- >
- <Pencil className="h-4 w-4" aria-hidden="true" />
- </button>
- )}
- {!removeDisabled || actionPending ? (
- <button
- type="button"
- className={actionClass}
- aria-label={localize('com_ui_remove_queued')}
- disabled={removeDisabled}
- onClick={remove}
- >
- <Trash2 className="h-4 w-4" aria-hidden="true" />
- </button>
- ) : null}
- </>
- );
- }
-
- const entries: MenuEntry[] = [
- {
- key: 'edit',
- label: localize('com_ui_edit_message'),
- icon: <Pencil className="h-4 w-4" aria-hidden="true" />,
- disabled: actionPending || !serverActionable,
- onClick: edit,
- },
- ];
- if (recoveryBlocked) {
- entries.push(
- {
- key: 'copy-recovery',
- label: localize('com_ui_steer_copy_to_composer'),
- icon: <Pencil className="h-4 w-4" aria-hidden="true" />,
- disabled: actionPending,
- onClick: () => {
- const copied = onRestoreToComposer(
- message.text,
- message.files,
- {
- quotes: message.quotes,
- manualSkills: message.manualSkills,
- },
- conversationId,
- );
- showToast(
- copied
- ? { message: localize('com_ui_steer_recovery_review'), status: 'info' }
- : { message: localize('com_ui_steer_recovery_copy_refused'), status: 'error' },
- );
- },
- },
- {
- key: 'dismiss-recovery',
- label: localize('com_ui_steer_dismiss_recovery'),
- icon: <X className="h-4 w-4" aria-hidden="true" />,
- disabled: actionPending,
- onClick: () => steering.dismissRecovery(message),
- },
- );
- }
- const preferences: MenuEntry[] = [toggleEntry, interruptToggle];
-
- return (
- <div role="listitem" className={ROW_CLASS} data-testid="queued-message-row">
- <QueuedIcon
- warning={recoveryHeld || isRejected || isUnconfirmed || isIndeterminate}
- hint={steering.duringRunActive ? localize('com_ui_steer_queued_info') : undefined}
- />
- <span className="min-w-0 flex-1 truncate" title={message.text}>
- {message.text}
- </span>
- <QuoteCount
- count={quoteCount}
- label={localize('com_ui_queued_quote_count', { 0: String(quoteCount) })}
- />
- <AttachmentCount
- count={fileCount}
- label={localize('com_ui_queued_attachment_count', {
- 0: String(fileCount),
- })}
- />
- {(recoveryHeld || isRejected || isUnconfirmed || isIndeterminate) && (
- <span
- className="text-text-warning shrink-0 text-xs"
- title={recoveryHeld ? localize('com_ui_steer_recovery_review') : undefined}
- >
- {localize(statusLabel)}
- </span>
- )}
- {showPrimary && (
- <button
- type="button"
- className={PRIMARY_BTN_CLASS}
- disabled={actionPending || !serverActionable}
- onClick={() => steering.sendQueuedNow(message)}
- >
- {canSteerNow ? (
- <>
- <Zap className={cn('h-4 w-4', STEER_ICON)} aria-hidden="true" />
- {localize('com_ui_steer')}
- </>
- ) : (
- <>
- <Send className="h-4 w-4" aria-hidden="true" />
- {localize('com_ui_send_now')}
- </>
- )}
- </button>
- )}
- {showEscalate && (
- <EscalateNowButton
- surface="queued"
- messageText={message.text}
- disabled={
- steering.pausedOnApproval || interruptPending || actionPending || !serverActionable
- }
- onClick={() => steering.sendQueuedNow(message, { preempt: true })}
- />
- )}
- <button
- type="button"
- aria-label={localize(
- isUnconfirmed ? 'com_ui_dismiss_unconfirmed_delivery' : 'com_ui_remove_queued',
- )}
- disabled={removeDisabled}
- onClick={remove}
- className={ICON_BTN_CLASS}
- >
- <Trash2 className="h-4 w-4" aria-hidden="true" />
- </button>
- <RowMenu
- label={localize('com_ui_more_options')}
- entries={entries}
- preferences={preferences}
- />
- </div>
- );
-}
-
-function FailedSteerRow({
- steer,
- steering,
- onEditToComposer,
-}: {
- steer: PendingSteer;
- steering: SteeringControls;
- onEditToComposer: (
- text: string,
- files?: TMessage['files'],
- context?: QueuedMessageContext,
- ) => void;
-}) {
- const localize = useLocalize();
- const toggleEntry = useDefaultToggleEntry(steering);
- const interruptToggle = useInterruptToggleEntry();
- const canRetry = !steer.deliveryUncertain || steer.generationProtocolVersion === 2;
-
- const entries: MenuEntry[] = steer.deliveryUncertain
- ? []
- : [
- {
- key: 'edit',
- label: localize('com_ui_edit_message'),
- icon: <Pencil className="h-4 w-4" aria-hidden="true" />,
- onClick: () => {
- steering.removeSteer(steer.steerId);
- onEditToComposer(steer.text, steer.files, {
- quotes: steer.quotes,
- manualSkills: steer.manualSkills,
- });
- },
- },
- {
- key: 'queue',
- label: localize('com_ui_convert_to_queue'),
- icon: <Clock className={cn('h-4 w-4', QUEUE_ICON)} aria-hidden="true" />,
- onClick: () =>
- steering.convertSteerToQueue(
- steer.steerId,
- steer.text,
- steer.files,
- { quotes: steer.quotes, manualSkills: steer.manualSkills },
- steer.queuedOrigin,
- ),
- },
- ];
- const preferences: MenuEntry[] = [toggleEntry, interruptToggle];
-
- return (
- <div
- role="listitem"
- className={cn(ROW_CLASS, 'border-border-destructive')}
- data-testid="steer-message-row"
- >
- <Zap className="text-text-destructive h-4 w-4 shrink-0" aria-hidden="true" />
- <span className="min-w-0 flex-1 truncate" title={steer.text}>
- {steer.text}
- </span>
- <QuoteCount
- count={steer.quotes?.length ?? 0}
- label={localize('com_ui_queued_quote_count', {
- 0: String(steer.quotes?.length ?? 0),
- })}
- />
- <span className="text-text-destructive shrink-0 text-xs">
- {localize(
- steer.deliveryUncertain ? 'com_ui_steer_delivery_unconfirmed' : 'com_ui_steer_failed',
- )}
- </span>
- {canRetry && (
- <button
- type="button"
- className={PRIMARY_BTN_CLASS}
- onClick={() =>
- steering.retrySteer(
- steer.steerId,
- steer.text,
- steer.files,
- { quotes: steer.quotes, manualSkills: steer.manualSkills },
- {
- preempt: steer.preempt === true,
- createdAt: steer.createdAt,
- generationProtocolVersion: steer.generationProtocolVersion,
- ...(steer.generationCreatedAt != null && {
- generationCreatedAt: steer.generationCreatedAt,
- }),
- ...(steer.queuedOrigin && { queuedOrigin: steer.queuedOrigin }),
- },
- )
- }
- >
- <RotateCcw className="h-4 w-4" aria-hidden="true" />
- {localize('com_ui_steer_retry')}
- </button>
- )}
- {!steer.deliveryUncertain && (
- <button
- type="button"
- aria-label={localize('com_ui_remove_queued')}
- onClick={() => steering.removeSteer(steer.steerId)}
- className={ICON_BTN_CLASS}
- >
- <X className="h-4 w-4" aria-hidden="true" />
- </button>
- )}
- <RowMenu
- label={localize('com_ui_more_options')}
- entries={entries}
- preferences={preferences}
- />
- </div>
- );
-}
-
-/**
- * Stacked rows above the composer for during-run messages, mirroring the
- * reference UI: each row shows the message, a primary action, delete, and an
- * overflow menu with Edit message + the default-mode toggle.
- * (In-flight steers read as messages, not controls — `InFlightSteers` renders
- * them as bubbles anchored above the composer box.)
- * - Failed steer rows (Zap, red): the POST failed, so the text never entered
- * the thread — kept recoverable with retry / edit / queue actions.
- * - Queued rows (Clock): client-side follow-ups auto-sent after the run.
- */
-function PendingSteerChips({
- conversationId,
- steering,
- onEditToComposer,
- onRestoreToComposer,
-}: {
- conversationId: string;
- steering: SteeringControls;
- onEditToComposer: (
- text: string,
- files?: TMessage['files'],
- context?: QueuedMessageContext,
- ) => void;
- onRestoreToComposer: RestoreToComposer;
-}) {
- const localize = useLocalize();
- const steers = useRecoilValue(store.pendingSteersByConvoId(conversationId));
- const queued = useRecoilValue(store.queuedMessagesByConvoId(steering.queueKey));
- const revealed = useAtomValue(revealedQueuedTurnFamily(steering.queueKey));
- const portal = useQueuedTurnPortal();
- const actionLocks = useRef(new Set<string>());
- const [pendingActions, setPendingActions] = useState<ReadonlySet<string>>(new Set());
- /** The lock lives with the composer, not the row: reparenting an action
- * during a cancellation cannot open a second request window. */
- const afterDiscard = useCallback(
- (message: QueuedMessage, action: () => boolean) => {
- const key = `${steering.queueKey}\u0000${message.id}`;
- if (actionLocks.current.has(key)) return;
- actionLocks.current.add(key);
- setPendingActions(new Set(actionLocks.current));
- void (async () => {
- try {
- if (await steering.discardQueued(message)) action();
- } catch {
- // The steering hook reports failures; leave the row available for retry.
- } finally {
- actionLocks.current.delete(key);
- setPendingActions(new Set(actionLocks.current));
- }
- })();
- },
- [steering],
- );
- const failedSteers = useMemo(() => steers.filter((steer) => steer.status === 'failed'), [steers]);
- /** Only one interrupt can be in flight: a second preempt while one is
- * unresolved would arm a second seal, so escalation buttons disable. The
- * escalating flag covers a bubble arm's round trip, before its chip
- * relabels for the chip-derived check to see. */
- const escalating = useAtomValue(escalatingSteerFamily(conversationId));
- const interruptPending = useMemo(
- () => escalating || steers.some((steer) => steer.preempt === true && steer.status !== 'failed'),
- [escalating, steers],
- );
-
- const queuedRows: ReactNode[] = [];
- const portaledActions: ReactNode[] = [];
- const target = portal?.target;
- for (const message of queued) {
- const starting =
- revealed != null &&
- message.clientRequestId != null &&
- revealed.clientRequestId === message.clientRequestId;
- const inTurn =
- starting &&
- target != null &&
- target.conversationId === conversationId &&
- target.clientRequestId === message.clientRequestId;
- const actionKey = `${steering.queueKey}\u0000${message.id}`;
- const row = (
- <QueuedRow
- key={message.id}
- message={message}
- steering={steering}
- conversationId={conversationId}
- interruptPending={interruptPending}
- starting={starting}
- inTurn={inTurn}
- actionPending={pendingActions.has(actionKey)}
- afterDiscard={afterDiscard}
- onEditToComposer={onEditToComposer}
- onRestoreToComposer={onRestoreToComposer}
- />
- );
- if (inTurn && target != null) {
- portaledActions.push(createPortal(row, target.element, message.id));
- } else {
- queuedRows.push(row);
- }
- }
- if (failedSteers.length === 0 && queuedRows.length === 0 && portaledActions.length === 0) {
- return null;
- }
-
- return (
- <>
- {(failedSteers.length > 0 || queuedRows.length > 0) && (
- <div className="flex flex-col gap-1.5 px-2 pt-2" data-testid="pending-steer-chips">
- <div
- className="flex flex-col gap-1.5"
- role="list"
- aria-label={localize('com_ui_queued_messages')}
- >
- {failedSteers.map((steer) => (
- <FailedSteerRow
- key={steer.steerId}
- steer={steer}
- steering={steering}
- onEditToComposer={onEditToComposer}
- />
- ))}
- {queuedRows}
- </div>
- </div>
- )}
- {portaledActions}
- </>
- );
-}
-
-export default memo(PendingSteerChips);
diff --git a/client/src/components/Chat/Input/Reasoning.tsx b/client/src/components/Chat/Input/Reasoning.tsx
new file mode 100644
index 0000000000..0a6f6ddeef
--- /dev/null
+++ b/client/src/components/Chat/Input/Reasoning.tsx
@@ -0,0 +1,419 @@
+import { useEffect, useId, useMemo, useRef, useState } from 'react';
+import { useRecoilValue } from 'recoil';
+import { useAtom, useStore } from 'jotai';
+import * as Popover from '@radix-ui/react-popover';
+import { Button, Input, Slider } from '@librechat/client';
+import { BrainCircuit, ChevronDown, X } from 'lucide-react';
+import {
+ Constants,
+ ReasoningParameterFormat,
+ clampSettingRange,
+ getEndpointField,
+ isAgentsEndpoint,
+ isAssistantsEndpoint,
+ reasoningOverrideSchema,
+ isReasoningOverrideSupported,
+ resolveReasoningSettingForTarget,
+} from 'librechat-data-provider';
+import type {
+ Agent,
+ SettingDefinition,
+ TConversation,
+ TReasoningOverride,
+} from 'librechat-data-provider';
+import type { TranslationKeys } from '~/hooks';
+import { getReasoningStateKey, pendingReasoningOverrideFamily } from './Composer/state';
+import { useGetAgentByIdQuery, useGetEndpointsQuery } from '~/data-provider';
+import { formatTokens, resolveAgentTarget } from '~/utils';
+import { useAgentsMapContext } from '~/Providers';
+import { useLocalize } from '~/hooks';
+import store from '~/store';
+
+type ReasoningControlProps = {
+ index: number;
+ setting: SettingDefinition;
+ value?: TReasoningOverride;
+ disabled?: boolean;
+ onChange: (value: TReasoningOverride) => void;
+};
+
+const translated = (
+ value: string | number | boolean | undefined,
+ localize: ReturnType<typeof useLocalize>,
+) =>
+ typeof value === 'string' && value.startsWith('com_')
+ ? localize(value as TranslationKeys)
+ : String(value ?? '');
+
+export function ReasoningControl({
+ index,
+ setting,
+ value,
+ disabled = false,
+ onChange,
+}: ReasoningControlProps) {
+ const localize = useLocalize();
+ const labelId = useId();
+ const options = setting.options ?? [];
+ const isEnum = setting.type === 'enum' && options.length > 0;
+ const label = translated(setting.label ?? setting.key, localize);
+ const selectedValue = value?.key === setting.key ? value.value : setting.default;
+ const selectedIndex = isEnum ? Math.max(0, options.indexOf(String(selectedValue ?? ''))) : 0;
+ let displayValue = String(selectedValue ?? localize('com_ui_auto'));
+ if (isEnum) {
+ displayValue = translated(
+ setting.enumMappings?.[options[selectedIndex]] ?? options[selectedIndex],
+ localize,
+ );
+ } else if (selectedValue === -1) {
+ displayValue = localize('com_ui_auto');
+ } else if (typeof selectedValue === 'number') {
+ displayValue = `${formatTokens(selectedValue)} ${localize('com_ui_tokens')}`;
+ }
+ const [numericValue, setNumericValue] = useState(String(selectedValue ?? -1));
+
+ useEffect(() => {
+ if (!isEnum) {
+ setNumericValue(String(selectedValue ?? -1));
+ }
+ }, [isEnum, selectedValue]);
+
+ const emit = (nextValue: string | number) => {
+ const parsed = reasoningOverrideSchema.safeParse({ key: setting.key, value: nextValue });
+ if (parsed.success) {
+ onChange(parsed.data);
+ }
+ };
+
+ const range = useMemo(() => setting.range ?? { min: -1, max: 200000, step: 1 }, [setting.range]);
+ const numericMin = range.positiveMin ?? Math.max(0, range.min);
+ const parsedNumericValue = Number(numericValue);
+ const numericScaleValue = Number.isFinite(parsedNumericValue)
+ ? Math.min(range.max, Math.max(numericMin, parsedNumericValue))
+ : numericMin;
+ const isAuto = range.min === -1 && numericValue === '-1';
+
+ const emitNumericValue = (nextValue: number) => {
+ setNumericValue(String(nextValue));
+ emit(nextValue);
+ };
+
+ const commitNumericValue = () => {
+ const parsed = numericValue.trim() === '' ? range.min : Number(numericValue);
+ const nextValue = clampSettingRange(
+ Number.isFinite(parsed) ? Math.round(parsed) : range.min,
+ range,
+ );
+ setNumericValue(String(nextValue));
+ if (nextValue !== (selectedValue ?? range.min)) {
+ emit(nextValue);
+ }
+ };
+
+ return (
+ <Popover.Root modal>
+ <Popover.Trigger asChild>
+ {/* Styled as the composer control it sits beside (the Thinking pill in
+ `Composer/Thinking.tsx`) rather than as a restyled `Button`: the
+ open state keeps it lit while its popover is up, which no `Button`
+ variant expresses. */}
+ <button
+ type="button"
+ disabled={disabled}
+ aria-label={`${localize('com_ui_reasoning_for_next_message')} ${displayValue}`}
+ className="text-text-secondary hover:bg-surface-hover hover:text-text-primary focus-visible:ring-text-primary data-[state=open]:bg-surface-hover data-[state=open]:text-text-primary inline-flex h-8 items-center justify-center gap-1.5 rounded-xl px-2 text-sm font-medium whitespace-nowrap transition-colors focus-visible:ring-2 focus-visible:outline-hidden disabled:pointer-events-none disabled:opacity-50"
+ >
+ <BrainCircuit className="size-4" aria-hidden="true" />
+ <ChevronDown className="size-3" aria-hidden="true" />
+ </button>
+ </Popover.Trigger>
+ <Popover.Portal>
+ <Popover.Content
+ data-chat-pane-portal={index}
+ role="dialog"
+ aria-label={label}
+ align="end"
+ sideOffset={6}
+ className="border-border-light bg-surface-secondary text-text-primary data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 z-50 w-72 max-w-[calc(100vw-2rem)] origin-[--radix-popover-content-transform-origin] overflow-hidden rounded-2xl border shadow-xl motion-reduce:animate-none"
+ >
+ <div className="flex items-center gap-2 px-4 py-3">
+ <BrainCircuit className="text-text-secondary size-4 shrink-0" aria-hidden="true" />
+ <div className="min-w-0 flex-1">
+ <div id={labelId} className="truncate text-sm font-medium">
+ {label}
+ </div>
+ <div className="text-text-secondary truncate text-xs">
+ {localize('com_ui_reasoning_for_next_message')}
+ </div>
+ </div>
+ <Popover.Close asChild>
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ aria-label={localize('com_ui_close')}
+ className="group -mr-1 shrink-0"
+ >
+ <X
+ className="text-text-secondary group-hover:text-text-primary size-4"
+ aria-hidden="true"
+ />
+ </Button>
+ </Popover.Close>
+ </div>
+ <div className="border-border-light border-t px-4 pt-3 pb-4">
+ {isEnum ? (
+ <>
+ <div className="text-text-primary mb-4 text-sm font-medium">{displayValue}</div>
+ <div className="py-1">
+ <Slider
+ aria-labelledby={labelId}
+ aria-valuetext={displayValue}
+ value={[selectedIndex]}
+ min={0}
+ max={options.length - 1}
+ step={1}
+ onValueChange={([nextIndex]) => emit(options[nextIndex])}
+ />
+ </div>
+ <div className="text-text-secondary mt-2.5 flex justify-between gap-4 text-xs">
+ <span className="truncate">
+ {translated(setting.enumMappings?.[options[0]] ?? options[0], localize)}
+ </span>
+ <span className="truncate text-right">
+ {translated(
+ setting.enumMappings?.[options[options.length - 1]] ??
+ options[options.length - 1],
+ localize,
+ )}
+ </span>
+ </div>
+ </>
+ ) : (
+ <>
+ <div className="mb-4 flex items-center justify-between gap-3">
+ <div className="flex min-w-0 items-center gap-1.5">
+ <div className="bg-surface-primary h-8 w-24 shrink-0 rounded-lg font-medium shadow-xs">
+ <Input
+ type="number"
+ aria-label={label}
+ value={numericValue === '-1' ? '' : numericValue}
+ placeholder={formatTokens(numericMin)}
+ min={numericMin}
+ max={range.max}
+ step={range.step ?? 1}
+ onChange={(event) => setNumericValue(event.target.value)}
+ onBlur={commitNumericValue}
+ className="h-8 w-24 text-right"
+ />
+ </div>
+ <span className="text-text-secondary truncate text-xs">
+ {localize('com_ui_tokens')}
+ </span>
+ </div>
+ {range.min === -1 && (
+ <Button
+ type="button"
+ variant={isAuto ? 'default' : 'ghost'}
+ size="sm"
+ aria-pressed={isAuto}
+ onClick={() => emitNumericValue(-1)}
+ className="h-8 shrink-0"
+ >
+ <span className="text-xs">{localize('com_ui_auto')}</span>
+ </Button>
+ )}
+ </div>
+ <div className="py-1">
+ <Slider
+ aria-labelledby={labelId}
+ aria-valuetext={
+ isAuto
+ ? localize('com_ui_auto')
+ : `${formatTokens(numericScaleValue)} ${localize('com_ui_tokens')}`
+ }
+ value={[numericScaleValue]}
+ min={numericMin}
+ max={range.max}
+ step={range.step ?? 1}
+ onValueChange={([nextValue]) => emitNumericValue(nextValue)}
+ />
+ </div>
+ <div className="text-text-secondary mt-2.5 flex justify-between gap-4 text-xs">
+ <span>{formatTokens(numericMin)}</span>
+ <span>{formatTokens(range.max)}</span>
+ </div>
+ </>
+ )}
+ </div>
+ </Popover.Content>
+ </Popover.Portal>
+ </Popover.Root>
+ );
+}
+
+type ComposerReasoningOptions = {
+ conversation: TConversation | null;
+ index: number;
+ hasAddedConversation?: boolean;
+ enabled?: boolean;
+ blockedReasoningKeys?: ReadonlySet<string>;
+};
+
+type ComposerReasoningState = {
+ setting: SettingDefinition;
+ value?: TReasoningOverride;
+ setValue: (value: TReasoningOverride) => void;
+};
+
+export function useComposerReasoning({
+ conversation,
+ index,
+ hasAddedConversation = false,
+ enabled = true,
+ blockedReasoningKeys,
+}: ComposerReasoningOptions): ComposerReasoningState | null {
+ const agentsMap = useAgentsMapContext();
+ const { data: fetchedAgent } = useGetAgentByIdQuery(conversation?.agent_id);
+ const endpointsQuery = useGetEndpointsQuery();
+ const endpointsConfig = useMemo(() => endpointsQuery.data ?? {}, [endpointsQuery.data]);
+ const conversationId = conversation?.conversationId ?? Constants.NEW_CONVO;
+ const reasoningStateKey = getReasoningStateKey(conversationId, index);
+ const [value, setValue] = useAtom(pendingReasoningOverrideFamily(reasoningStateKey));
+ const reasoningStore = useStore();
+ const placeholderStateKey = getReasoningStateKey(null, index);
+ const submission = useRecoilValue(store.submissionByIndex(index));
+ const submissionConversationId =
+ submission?.conversation?.conversationId ?? submission?.userMessage?.conversationId;
+ const submittedConversationRef = useRef<string | null>(null);
+ useEffect(() => {
+ if (submission?.userMessage == null) {
+ submittedConversationRef.current = null;
+ return;
+ }
+ submittedConversationRef.current = getReasoningStateKey(submissionConversationId, index);
+ }, [index, submission, submissionConversationId]);
+ const previousStateKey = useRef(reasoningStateKey);
+
+ /* A new chat holds its selection under the placeholder key until the
+ `created`/`sync` event assigns a durable id. Only migrate while this pane
+ still has the live submission that started under that placeholder (or a
+ submission already stamped with the incoming id); navigation clears or
+ replaces the pane submission, so it cannot move a new-chat choice into an
+ unrelated conversation. Declared before the cleanup effect below so the
+ moved value is in place before that effect judges it. */
+ useEffect(() => {
+ const previous = previousStateKey.current;
+ previousStateKey.current = reasoningStateKey;
+ const hasLiveSubmission =
+ submission?.userMessage != null &&
+ (submissionConversationId === conversationId ||
+ submittedConversationRef.current === placeholderStateKey);
+ if (previous === reasoningStateKey || previous !== placeholderStateKey || !hasLiveSubmission) {
+ return;
+ }
+ const pending = reasoningStore.get(pendingReasoningOverrideFamily(previous));
+ if (pending == null) {
+ return;
+ }
+ reasoningStore.set(pendingReasoningOverrideFamily(previous), undefined);
+ /* Never overwrite a choice already made under the durable key: a restore
+ path (queued-message edit) can have written there first. */
+ if (reasoningStore.get(pendingReasoningOverrideFamily(reasoningStateKey)) == null) {
+ reasoningStore.set(pendingReasoningOverrideFamily(reasoningStateKey), pending);
+ }
+ }, [
+ conversationId,
+ placeholderStateKey,
+ reasoningStateKey,
+ reasoningStore,
+ submission,
+ submissionConversationId,
+ ]);
+ const endpoint = conversation?.endpointType ?? conversation?.endpoint ?? '';
+ const agent = (fetchedAgent ?? agentsMap?.[conversation?.agent_id ?? '']) as Agent | undefined;
+ const isAgent = isAgentsEndpoint(endpoint);
+ const agentTarget = isAgent ? resolveAgentTarget(conversation?.agent_id, agent) : undefined;
+ const provider = isAgent ? (agentTarget?.provider ?? '') : (conversation?.endpoint ?? '');
+ const model = isAgent ? (agentTarget?.model ?? '') : (conversation?.model ?? '');
+ const endpointType = getEndpointField(endpointsConfig, provider, 'type');
+ const setting = useMemo(() => {
+ const customParams = endpointsConfig[provider]?.customParams ?? {};
+ return resolveReasoningSettingForTarget({
+ endpoint: endpointType ?? provider,
+ model,
+ isAgent,
+ defaultParamsEndpoint: customParams.defaultParamsEndpoint,
+ reasoningFormat: customParams.reasoningFormat,
+ paramDefinitions: customParams.paramDefinitions,
+ blockedReasoningKeys,
+ });
+ }, [blockedReasoningKeys, endpointType, endpointsConfig, isAgent, model, provider]);
+ const settingFingerprint =
+ setting == null
+ ? ''
+ : `${setting.key}:${setting.type}:${setting.options?.join(',') ?? ''}:${setting.range?.min ?? ''}:${setting.range?.positiveMin ?? ''}:${setting.range?.max ?? ''}:${setting.range?.step ?? ''}`;
+ const targetResolved =
+ endpoint !== '' &&
+ (!isAgent || agentTarget != null) &&
+ (setting != null || endpointsQuery.data != null);
+ const targetFingerprint = targetResolved
+ ? `${isAgent ? conversation?.agent_id : provider}:${model}:${settingFingerprint}`
+ : null;
+ const previousTarget = useRef({ key: reasoningStateKey, fingerprint: targetFingerprint });
+ const explicitlyUnavailable =
+ enabled === false ||
+ hasAddedConversation ||
+ isAssistantsEndpoint(endpoint) ||
+ endpointsConfig[provider]?.customParams?.reasoningFormat === ReasoningParameterFormat.disabled;
+ const available =
+ enabled === true &&
+ !explicitlyUnavailable &&
+ (!isAgent || agentTarget != null) &&
+ setting != null;
+
+ useEffect(() => {
+ let targetChanged = false;
+ if (targetFingerprint != null) {
+ const previous = previousTarget.current;
+ targetChanged =
+ previous.key === reasoningStateKey &&
+ previous.fingerprint != null &&
+ previous.fingerprint !== targetFingerprint;
+ previousTarget.current = { key: reasoningStateKey, fingerprint: targetFingerprint };
+ }
+ const unsupportedResolved = targetResolved && setting == null;
+ /* A restored override can predate a capability change on the same target: its
+ key may survive while its enum value or number no longer does. */
+ const mismatchedSetting =
+ setting != null && value != null && !isReasoningOverrideSupported(value, setting);
+ if (
+ (explicitlyUnavailable || unsupportedResolved || targetChanged || mismatchedSetting) &&
+ value != null
+ ) {
+ setValue(undefined);
+ }
+ }, [
+ explicitlyUnavailable,
+ reasoningStateKey,
+ setValue,
+ setting,
+ targetFingerprint,
+ targetResolved,
+ value,
+ ]);
+
+ if (!available || setting == null) {
+ return null;
+ }
+
+ const configuredValue =
+ isAgent && agent != null ? agent.model_parameters?.[setting.key] : conversation?.[setting.key];
+ const displayedValue =
+ value ??
+ reasoningOverrideSchema.safeParse({
+ key: setting.key,
+ value: configuredValue ?? setting.default,
+ }).data;
+
+ return { setting, value: displayedValue, setValue };
+}
diff --git a/client/src/components/Chat/Input/SendButton.tsx b/client/src/components/Chat/Input/SendButton.tsx
index 5f286840bb..98c447a84a 100644
--- a/client/src/components/Chat/Input/SendButton.tsx
+++ b/client/src/components/Chat/Input/SendButton.tsx
@@ -1,6 +1,6 @@
import React, { forwardRef } from 'react';
import { useWatch } from 'react-hook-form';
-import { composerSubmitClasses, SendIcon, TooltipAnchor } from '@librechat/client';
+import { SendIcon, IconButton, TooltipAnchor } from '@librechat/client';
import type { Control } from 'react-hook-form';
import { isSubmittableMessage } from '~/utils';
import { useLocalize } from '~/hooks';
@@ -19,25 +19,25 @@ const SubmitButton = React.memo(
<TooltipAnchor
description={localize('com_nav_send_message')}
render={
- <button
+ <IconButton
ref={ref}
- aria-label={localize('com_nav_send_message')}
- id="send-button"
+ label={localize('com_nav_send_message')}
+ variant="submit"
+ size="theme"
+ shape="theme"
disabled={props.disabled}
- className={composerSubmitClasses()}
data-testid="send-button"
type="submit"
>
<span className="" data-state="closed">
<SendIcon size={24} />
</span>
- </button>
+ </IconButton>
}
/>
);
}),
);
-
const SendButton = React.memo(
forwardRef((props: SendButtonProps, ref: React.ForwardedRef<HTMLButtonElement>) => {
const data = useWatch({ control: props.control });
diff --git a/client/src/components/Chat/Input/Skills.tsx b/client/src/components/Chat/Input/Skills.tsx
deleted file mode 100644
index e23bd1d2f8..0000000000
--- a/client/src/components/Chat/Input/Skills.tsx
+++ /dev/null
@@ -1,40 +0,0 @@
-import React, { memo } from 'react';
-import { ScrollText } from 'lucide-react';
-import { CheckboxButton } from '@librechat/client';
-import { Permissions, PermissionTypes, defaultAgentCapabilities } from 'librechat-data-provider';
-import { useLocalize, useHasAccess, useAgentCapabilities } from '~/hooks';
-import { useBadgeRowContext } from '~/Providers';
-import { badgeAccents } from './accents';
-
-function Skills() {
- const localize = useLocalize();
- const context = useBadgeRowContext();
- const { toggleState: skillsActive, debouncedChange, isPinned } = context?.skills ?? {};
-
- const canUseSkills = useHasAccess({
- permissionType: PermissionTypes.SKILLS,
- permission: Permissions.USE,
- });
-
- const { skillsEnabled } = useAgentCapabilities(
- context?.agentsConfig?.capabilities ?? defaultAgentCapabilities,
- );
-
- if (!canUseSkills || !skillsEnabled) {
- return null;
- }
-
- return (
- (skillsActive || isPinned) && (
- <CheckboxButton
- checked={skillsActive}
- setValue={debouncedChange}
- label={localize('com_ui_skills')}
- isCheckedClassName={badgeAccents.cyan}
- icon={<ScrollText className="icon-md" aria-hidden="true" />}
- />
- )
- );
-}
-
-export default memo(Skills);
diff --git a/client/src/components/Chat/Input/SteerMenu.tsx b/client/src/components/Chat/Input/SteerMenu.tsx
deleted file mode 100644
index e4534809c3..0000000000
--- a/client/src/components/Chat/Input/SteerMenu.tsx
+++ /dev/null
@@ -1,341 +0,0 @@
-import { Fragment, useEffect, useId, useMemo, useState, useSyncExternalStore } from 'react';
-import { useRecoilState } from 'recoil';
-import * as Ariakit from '@ariakit/react';
-import { Zap, ZapOff, Clock } from 'lucide';
-import { MorphIcon } from '@librechat/client';
-import { ArrowUp, CircleHelp, MoreHorizontal } from 'lucide-react';
-import type { Ref } from 'react';
-import type { SteeringControls } from '~/hooks/Chat/useSteering';
-import { useShortcutAriaKey, useShortcutDisplay } from '~/hooks/useKeyboardShortcuts';
-import { QUEUE_ICON, STEER_ICON } from '~/components/Chat/Steering/identity';
-import { useLocalize } from '~/hooks';
-import { cn } from '~/utils';
-import store from '~/store';
-
-/** Shared row/bubble affordances for the during-run surfaces: the in-flight
- * steer bubbles (`InFlightSteers`) and the queued/failed rows
- * (`PendingSteerChips`) offer the same actions, so they share one menu. */
-export const ICON_BTN_CLASS =
- 'shrink-0 rounded-full p-1 text-text-secondary hover:bg-surface-tertiary hover:text-text-primary focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-border-xheavy';
-export const PRIMARY_BTN_CLASS =
- 'flex shrink-0 items-center gap-1.5 rounded-lg px-2 py-1 text-sm text-text-secondary hover:bg-surface-tertiary hover:text-text-primary focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-border-xheavy';
-const MENU_CLASS =
- 'z-50 min-w-[13rem] rounded-xl border border-border-light bg-surface-secondary p-1.5 text-text-primary shadow-lg outline-hidden';
-const MENU_ITEM_CLASS =
- 'flex w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-1.5 text-sm text-text-primary data-[active-item]:bg-surface-tertiary aria-disabled:cursor-not-allowed aria-disabled:opacity-50';
-const ESCALATION_MESSAGE_LABEL_MAX_LENGTH = 80;
-
-const activeEscalateListeners = new Set<() => void>();
-let hoveredEscalateTarget: string | null = null;
-let focusedEscalateTarget: string | null = null;
-
-function getActiveEscalateTarget() {
- return focusedEscalateTarget ?? hoveredEscalateTarget;
-}
-
-function subscribeToActiveEscalateTarget(listener: () => void) {
- activeEscalateListeners.add(listener);
- return () => activeEscalateListeners.delete(listener);
-}
-
-function updateActiveEscalateTarget(kind: 'hover' | 'focus', targetId: string, active: boolean) {
- const previous = getActiveEscalateTarget();
- if (kind === 'hover') {
- if (active) {
- hoveredEscalateTarget = targetId;
- } else if (hoveredEscalateTarget === targetId) {
- hoveredEscalateTarget = null;
- }
- } else {
- if (active) {
- focusedEscalateTarget = targetId;
- } else if (focusedEscalateTarget === targetId) {
- focusedEscalateTarget = null;
- }
- }
- if (previous !== getActiveEscalateTarget()) {
- activeEscalateListeners.forEach((listener) => listener());
- }
-}
-
-function clearActiveEscalateTarget(targetId: string) {
- const previous = getActiveEscalateTarget();
- if (hoveredEscalateTarget === targetId) {
- hoveredEscalateTarget = null;
- }
- if (focusedEscalateTarget === targetId) {
- focusedEscalateTarget = null;
- }
- if (previous !== getActiveEscalateTarget()) {
- activeEscalateListeners.forEach((listener) => listener());
- }
-}
-
-export type MenuEntry = {
- key: string;
- label: string;
- icon: React.ReactNode;
- onClick: () => void;
- disabled?: boolean;
- /** Localized description announced on the action and exposed by a help disclosure. */
- info?: string;
-};
-
-/**
- * Per-row "…" overflow menu: message actions first, then a visually separated
- * "Preferences" section for the sticky mode toggles, so one-off actions and
- * persistent behavior changes never read as the same kind of choice.
- */
-export function RowMenu({
- label,
- entries,
- preferences,
- buttonRef,
-}: {
- label: string;
- entries: MenuEntry[];
- preferences?: MenuEntry[];
- buttonRef?: Ref<HTMLButtonElement>;
-}) {
- const localize = useLocalize();
- const menu = Ariakit.useMenuStore({ placement: 'top-end' });
- const descriptionPrefix = useId();
- const preferencesLabelId = `${descriptionPrefix}-preferences`;
- const [expandedInfoKey, setExpandedInfoKey] = useState<string | null>(null);
- const renderEntry = (entry: MenuEntry) => {
- const descriptionId = entry.info == null ? undefined : `${descriptionPrefix}-${entry.key}`;
- const infoExpanded = entry.info != null && expandedInfoKey === entry.key;
- const action = (
- <Ariakit.MenuItem
- className={MENU_ITEM_CLASS}
- disabled={entry.disabled === true}
- accessibleWhenDisabled
- aria-describedby={descriptionId}
- onClick={() => {
- entry.onClick();
- setExpandedInfoKey(null);
- menu.hide();
- }}
- >
- {entry.icon}
- {entry.label}
- </Ariakit.MenuItem>
- );
-
- if (entry.info == null || descriptionId == null) {
- return <Fragment key={entry.key}>{action}</Fragment>;
- }
-
- return (
- <div key={entry.key} role="none">
- <div role="none" className="flex items-center gap-0.5">
- <div role="none" className="min-w-0 flex-1">
- {action}
- </div>
- <Ariakit.MenuItem
- aria-label={`${localize('com_ui_more_info')}: ${entry.label}`}
- aria-expanded={infoExpanded}
- aria-controls={descriptionId}
- hideOnClick={false}
- className="text-text-secondary hover:bg-surface-tertiary hover:text-text-primary focus-visible:ring-border-xheavy data-[active-item]:bg-surface-tertiary flex size-8 shrink-0 items-center justify-center rounded-lg focus-visible:ring-2 focus-visible:outline-hidden"
- onClick={() =>
- setExpandedInfoKey((current) => (current === entry.key ? null : entry.key))
- }
- >
- <CircleHelp className="h-3.5 w-3.5" aria-hidden="true" />
- </Ariakit.MenuItem>
- </div>
- <div
- id={descriptionId}
- className={cn(
- infoExpanded
- ? 'bg-surface-tertiary text-text-secondary mx-2 mb-1 rounded-lg px-2 py-1.5 text-xs leading-relaxed'
- : 'sr-only',
- )}
- >
- {entry.info}
- </div>
- </div>
- );
- };
- return (
- <>
- <Ariakit.MenuButton
- ref={buttonRef}
- store={menu}
- aria-label={label}
- className={ICON_BTN_CLASS}
- >
- <MoreHorizontal className="h-4 w-4" aria-hidden="true" />
- </Ariakit.MenuButton>
- <Ariakit.Menu store={menu} portal gutter={6} className={MENU_CLASS}>
- {entries.map(renderEntry)}
- {preferences != null && preferences.length > 0 && (
- <>
- <div role="separator" className="border-border-light mx-2 my-1 border-t" />
- <div role="group" aria-labelledby={preferencesLabelId}>
- <div
- id={preferencesLabelId}
- className="text-text-secondary px-2 pt-1 pb-0.5 text-[11px] font-medium tracking-wide uppercase"
- >
- {localize('com_ui_preferences')}
- </div>
- {preferences.map(renderEntry)}
- </div>
- </>
- )}
- </Ariakit.Menu>
- </>
- );
-}
-
-/**
- * The always-visible escalation control on a waiting message: interrupt &
- * steer it now, at the next safe token boundary. The tooltip teaches this
- * action's OWN shortcut (registry-aware, so a rebinding shows correctly).
- * Hover/focus marks this exact button as the active shortcut target; without
- * an active row the shortcut retains its newest-waiting-message fallback.
- */
-export function EscalateNowButton({
- surface,
- disabled,
- messageText,
- onClick,
-}: {
- surface: 'bubble' | 'queued';
- disabled: boolean;
- messageText: string;
- onClick: (event: React.MouseEvent<HTMLButtonElement>) => void;
-}) {
- const localize = useLocalize();
- const chord = useShortcutDisplay('escalateSteer');
- const ariaKey = useShortcutAriaKey('escalateSteer');
- const targetId = useId();
- const activeTarget = useSyncExternalStore(
- subscribeToActiveEscalateTarget,
- getActiveEscalateTarget,
- () => null,
- );
- const isActive = !disabled && activeTarget === targetId;
- const label = localize('com_ui_interrupt_steer_now');
- const normalizedMessageLabel = messageText.trim().replace(/\s+/g, ' ');
- const messageCharacters = Array.from(normalizedMessageLabel);
- const messageLabel =
- messageCharacters.length > ESCALATION_MESSAGE_LABEL_MAX_LENGTH
- ? `${messageCharacters
- .slice(0, ESCALATION_MESSAGE_LABEL_MAX_LENGTH - 1)
- .join('')
- .trimEnd()}…`
- : normalizedMessageLabel;
- const accessibleLabel = messageLabel.length > 0 ? `${label}: ${messageLabel}` : label;
-
- useEffect(() => {
- if (disabled) {
- clearActiveEscalateTarget(targetId);
- }
- return () => clearActiveEscalateTarget(targetId);
- }, [disabled, targetId]);
-
- return (
- <Ariakit.TooltipProvider placement="top" timeout={300}>
- <Ariakit.TooltipAnchor
- render={
- <button
- type="button"
- aria-label={accessibleLabel}
- aria-keyshortcuts={isActive ? ariaKey : undefined}
- data-escalate-steer={surface}
- data-escalate-steer-active={isActive ? 'true' : undefined}
- data-testid={surface === 'queued' ? 'queued-interrupt-now' : 'steer-escalate-now'}
- disabled={disabled}
- onPointerEnter={() => !disabled && updateActiveEscalateTarget('hover', targetId, true)}
- onPointerLeave={() => updateActiveEscalateTarget('hover', targetId, false)}
- onFocus={() => !disabled && updateActiveEscalateTarget('focus', targetId, true)}
- onBlur={() => updateActiveEscalateTarget('focus', targetId, false)}
- onClick={onClick}
- className={cn(
- 'flex size-6 shrink-0 items-center justify-center rounded-full',
- 'bg-text-primary text-surface-primary transition-opacity hover:opacity-85',
- 'focus-visible:ring-border-xheavy focus-visible:ring-2 focus-visible:outline-hidden',
- 'disabled:cursor-not-allowed disabled:opacity-35 disabled:hover:opacity-35',
- )}
- >
- <ArrowUp className="h-3.5 w-3.5" strokeWidth={2.4} aria-hidden="true" />
- </button>
- }
- />
- <Ariakit.Tooltip className="bg-surface-tertiary text-text-primary z-50 rounded-lg px-2 py-1 text-xs shadow-lg">
- {chord && isActive ? `${label} · ${chord}` : label}
- </Ariakit.Tooltip>
- </Ariakit.TooltipProvider>
- );
-}
-
-/**
- * The overflow item that flips the Enter-during-run default. Shown as the
- * OPPOSITE of the current default (the action you would switch to), matching
- * the reference UX ("Turn on queueing" while steer is the default).
- */
-export function useDefaultToggleEntry(steering: SteeringControls): MenuEntry {
- const localize = useLocalize();
- return useMemo(() => {
- const next = steering.defaultAction === 'steer' ? 'queue' : 'steer';
- return {
- key: 'toggle-default',
- label:
- next === 'queue'
- ? localize('com_ui_turn_on_queueing')
- : localize('com_ui_turn_on_steering'),
- icon: (
- <MorphIcon
- icon={next === 'queue' ? Clock : Zap}
- className={cn('h-4 w-4', next === 'queue' ? QUEUE_ICON : STEER_ICON)}
- />
- ),
- info: localize('com_nav_info_during_run_action'),
- onClick: () => steering.setDefaultAction(next),
- };
- }, [steering, localize]);
-}
-
-/**
- * The overflow item that flips whether a default steer interrupts generation
- * (`steerInterruptsByDefault`). Worded as the mode you would switch to, like
- * the queue/steer toggle above.
- */
-export function useInterruptToggleEntry(): MenuEntry {
- const localize = useLocalize();
- const [interrupts, setInterrupts] = useRecoilState(store.steerInterruptsByDefault);
- const [defaultAction, setDefaultAction] = useRecoilState(store.duringRunDefaultAction);
- const interruptsByDefault = defaultAction === 'steer' && interrupts;
- return useMemo(
- () => ({
- key: 'toggle-interrupt',
- label: interruptsByDefault
- ? localize('com_ui_wait_for_tool_steps')
- : localize('com_ui_always_interrupt'),
- icon: (
- <MorphIcon
- icon={interruptsByDefault ? Zap : ZapOff}
- className={cn('h-4 w-4', STEER_ICON)}
- />
- ),
- info: localize(
- !interruptsByDefault && defaultAction === 'queue'
- ? 'com_ui_steer_interrupts_enable_info'
- : 'com_ui_steer_interrupts_default_info',
- ),
- onClick: () => {
- if (interruptsByDefault) {
- setInterrupts(false);
- return;
- }
- if (defaultAction === 'queue') {
- setDefaultAction('steer');
- }
- setInterrupts(true);
- },
- }),
- [defaultAction, interruptsByDefault, localize, setDefaultAction, setInterrupts],
- );
-}
diff --git a/client/src/components/Chat/Input/StopButton.tsx b/client/src/components/Chat/Input/StopButton.tsx
index b3556f7e69..63b54a9f67 100644
--- a/client/src/components/Chat/Input/StopButton.tsx
+++ b/client/src/components/Chat/Input/StopButton.tsx
@@ -1,13 +1,25 @@
import { memo } from 'react';
-import { composerSubmitClasses, TooltipAnchor } from '@librechat/client';
+import { IconButton, TooltipAnchor } from '@librechat/client';
import { useLocalize } from '~/hooks';
export default memo(function StopButton({
stop,
setShowStopButton,
+ canStop = true,
+ hidden = false,
}: {
stop: (e: React.MouseEvent<HTMLButtonElement>) => void;
setShowStopButton: (value: boolean) => void;
+ /** False while the abort would be a no-op (the generation epoch is not
+ * installed yet). Hiding the button then would strand the user with a run
+ * they cannot stop, so stay visible and disabled instead. */
+ canStop?: boolean;
+ /** Kept mounted but out of the layout (and so out of the accessibility tree)
+ * while the during-run send button owns the slot. The stop shortcut looks
+ * for this control inside the focused form, so dropping it while the user
+ * types a steer is what made the shortcut reach into another pane or do
+ * nothing at all, which is exactly when a hard stop is wanted. */
+ hidden?: boolean;
}) {
const localize = useLocalize();
@@ -15,12 +27,20 @@ export default memo(function StopButton({
<TooltipAnchor
description={localize('com_nav_stop_generating')}
render={
- <button
+ <IconButton
type="button"
+ label={localize('com_nav_stop_generating')}
+ variant="submit"
+ size="theme"
+ shape="theme"
data-testid="stop-generation-button"
- className={composerSubmitClasses()}
+ hidden={hidden}
+ disabled={!canStop}
aria-label={localize('com_nav_stop_generating')}
onClick={(e) => {
+ if (!canStop) {
+ return;
+ }
setShowStopButton(false);
stop(e);
}}
@@ -31,11 +51,11 @@ export default memo(function StopButton({
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
- className="icon-lg text-surface-primary"
+ className="size-6"
>
<rect x="7" y="7" width="10" height="10" rx="1.25" fill="currentColor"></rect>
</svg>
- </button>
+ </IconButton>
}
></TooltipAnchor>
);
diff --git a/client/src/components/Chat/Input/TokenUsage/index.tsx b/client/src/components/Chat/Input/TokenUsage/index.tsx
index 41d51f91f9..a6d2f80369 100644
--- a/client/src/components/Chat/Input/TokenUsage/index.tsx
+++ b/client/src/components/Chat/Input/TokenUsage/index.tsx
@@ -224,6 +224,10 @@ function TokenUsageIndicator({
unmountOnHide
autoFocusOnShow={focusOnShow}
finalFocus={disclosureRef}
+ /* Without this the gauge could not close its own popup: mousedown on
+ the trigger counts as "outside", so Ariakit hid the popup and the
+ button's own click immediately re-opened it. */
+ hideOnInteractOutside={(event) => !disclosureRef.current?.contains(event.target as Node)}
aria-label={localize('com_ui_context_usage')}
onPointerEnter={cancelTimers}
onPointerLeave={(e) => {
diff --git a/client/src/components/Chat/Input/ToolsDropdown.tsx b/client/src/components/Chat/Input/ToolsDropdown.tsx
deleted file mode 100644
index e1f45d1b78..0000000000
--- a/client/src/components/Chat/Input/ToolsDropdown.tsx
+++ /dev/null
@@ -1,419 +0,0 @@
-import React, { useState, useMemo, useCallback } from 'react';
-import * as Ariakit from '@ariakit/react';
-import { TooltipAnchor, DropdownPopup, PinIcon, VectorIcon } from '@librechat/client';
-import { Brain, Globe, ScrollText, Settings, Settings2, TerminalSquareIcon } from 'lucide-react';
-import {
- AuthType,
- Permissions,
- ArtifactModes,
- PermissionTypes,
- defaultAgentCapabilities,
-} from 'librechat-data-provider';
-import type { MenuItemProps } from '~/common';
-import {
- useLocalize,
- useHasAccess,
- useAuthContext,
- useHasMemoryAccess,
- useAgentCapabilities,
-} from '~/hooks';
-import ArtifactsSubMenu from '~/components/Chat/Input/ArtifactsSubMenu';
-import MCPSubMenu from '~/components/Chat/Input/MCPSubMenu';
-import { useGetStartupConfig } from '~/data-provider';
-import { useBadgeRowContext } from '~/Providers';
-import { cn } from '~/utils';
-
-interface ToolsDropdownProps {
- disabled?: boolean;
-}
-
-/** Ariakit portals to document.body by default, which puts the menu outside every landmark.
- * Returning null falls back to that default. */
-const getMainLandmark = () => document.querySelector<HTMLElement>('main');
-
-const ToolsDropdown = ({ disabled }: ToolsDropdownProps) => {
- const localize = useLocalize();
- const { user } = useAuthContext();
- const context = useBadgeRowContext();
- const { data: startupConfig } = useGetStartupConfig();
-
- const {
- codeEnabled,
- memoryEnabled,
- webSearchEnabled,
- artifactsEnabled,
- fileSearchEnabled,
- skillsEnabled,
- } = useAgentCapabilities(context?.agentsConfig?.capabilities ?? defaultAgentCapabilities);
-
- const canUseWebSearch = useHasAccess({
- permissionType: PermissionTypes.WEB_SEARCH,
- permission: Permissions.USE,
- });
-
- const canRunCode = useHasAccess({
- permissionType: PermissionTypes.RUN_CODE,
- permission: Permissions.USE,
- });
-
- const canUseFileSearch = useHasAccess({
- permissionType: PermissionTypes.FILE_SEARCH,
- permission: Permissions.USE,
- });
-
- const canUseMcp = useHasAccess({
- permissionType: PermissionTypes.MCP_SERVERS,
- permission: Permissions.USE,
- });
-
- const canUseSkills = useHasAccess({
- permissionType: PermissionTypes.SKILLS,
- permission: Permissions.USE,
- });
-
- const canUseMemory = useHasMemoryAccess();
- const showMemory = canUseMemory && memoryEnabled && user?.personalization?.memories !== false;
-
- const [isPopoverActive, setIsPopoverActive] = useState(false);
- const isDisabled = disabled ?? false;
- const {
- skills,
- memory,
- webSearch,
- artifacts,
- fileSearch,
- mcpServerManager,
- codeInterpreter,
- searchApiKeyForm,
- } = context ?? {};
-
- const { setIsDialogOpen: setIsSearchDialogOpen, menuTriggerRef: searchMenuTriggerRef } =
- searchApiKeyForm ?? {};
- const {
- isPinned: isSearchPinned,
- setIsPinned: setIsSearchPinned,
- authData: webSearchAuthData,
- } = webSearch ?? {};
- const { isPinned: isCodePinned, setIsPinned: setIsCodePinned } = codeInterpreter ?? {};
- const { isPinned: isFileSearchPinned, setIsPinned: setIsFileSearchPinned } = fileSearch ?? {};
- const { isPinned: isArtifactsPinned, setIsPinned: setIsArtifactsPinned } = artifacts ?? {};
- const { isPinned: isSkillsPinned, setIsPinned: setIsSkillsPinned } = skills ?? {};
- const { isPinned: isMemoryPinned, setIsPinned: setIsMemoryPinned } = memory ?? {};
-
- const showWebSearchSettings = useMemo(() => {
- const authTypes = webSearchAuthData?.authTypes ?? [];
- if (authTypes.length === 0) return true;
- return !authTypes.every(([, authType]) => authType === AuthType.SYSTEM_DEFINED);
- }, [webSearchAuthData?.authTypes]);
-
- const handleWebSearchToggle = useCallback(() => {
- const newValue = !webSearch?.toggleState;
- webSearch?.debouncedChange({ value: newValue });
- }, [webSearch]);
-
- const handleCodeInterpreterToggle = useCallback(() => {
- const newValue = !codeInterpreter?.toggleState;
- codeInterpreter?.debouncedChange({ value: newValue });
- }, [codeInterpreter]);
-
- const handleFileSearchToggle = useCallback(() => {
- const newValue = !fileSearch?.toggleState;
- fileSearch?.debouncedChange({ value: newValue });
- }, [fileSearch]);
-
- const handleArtifactsToggle = useCallback(() => {
- const currentState = artifacts?.toggleState;
- if (!currentState || currentState === '') {
- artifacts?.debouncedChange({ value: ArtifactModes.DEFAULT });
- } else {
- artifacts?.debouncedChange({ value: '' });
- }
- }, [artifacts]);
-
- const handleShadcnToggle = useCallback(() => {
- const currentState = artifacts?.toggleState;
- if (currentState === ArtifactModes.SHADCNUI) {
- artifacts?.debouncedChange({ value: ArtifactModes.DEFAULT });
- } else {
- artifacts?.debouncedChange({ value: ArtifactModes.SHADCNUI });
- }
- }, [artifacts]);
-
- const handleCustomToggle = useCallback(() => {
- const currentState = artifacts?.toggleState;
- if (currentState === ArtifactModes.CUSTOM) {
- artifacts?.debouncedChange({ value: ArtifactModes.DEFAULT });
- } else {
- artifacts?.debouncedChange({ value: ArtifactModes.CUSTOM });
- }
- }, [artifacts]);
-
- const handleSkillsToggle = useCallback(() => {
- const newValue = !skills?.toggleState;
- skills?.debouncedChange({ value: newValue });
- }, [skills]);
-
- const handleMemoryToggle = useCallback(() => {
- const newValue = !memory?.toggleState;
- memory?.debouncedChange({ value: newValue });
- }, [memory]);
-
- const mcpPlaceholder = startupConfig?.interface?.mcpServers?.placeholder;
-
- const dropdownItems: MenuItemProps[] = [];
-
- if (fileSearchEnabled && canUseFileSearch) {
- dropdownItems.push({
- onClick: handleFileSearchToggle,
- hideOnClick: false,
- render: (props) => (
- <div {...props} data-testid="tools-menu-file-search">
- <div className="flex items-center gap-2">
- <VectorIcon className="icon-md" />
- <span>{localize('com_assistants_file_search')}</span>
- </div>
- <button
- type="button"
- onClick={(e) => {
- e.stopPropagation();
- setIsFileSearchPinned?.(!isFileSearchPinned);
- }}
- className={cn(
- 'rounded p-1 transition-all duration-200',
- 'hover:bg-surface-secondary hover:shadow-xs',
- !isFileSearchPinned && 'text-text-secondary hover:text-text-primary',
- )}
- aria-label={isFileSearchPinned ? 'Unpin' : 'Pin'}
- >
- <div className="h-4 w-4">
- <PinIcon unpin={isFileSearchPinned} />
- </div>
- </button>
- </div>
- ),
- });
- }
-
- if (canUseWebSearch && webSearchEnabled) {
- dropdownItems.push({
- onClick: handleWebSearchToggle,
- hideOnClick: false,
- render: (props) => (
- <div {...props}>
- <div className="flex items-center gap-2">
- <Globe className="icon-md" aria-hidden="true" />
- <span>{localize('com_ui_web_search')}</span>
- </div>
- <div className="flex items-center gap-1">
- {showWebSearchSettings && (
- <button
- type="button"
- onClick={(e) => {
- e.stopPropagation();
- setIsSearchDialogOpen?.(true);
- }}
- className={cn(
- 'rounded p-1 transition-all duration-200',
- 'hover:bg-surface-secondary hover:shadow-xs',
- 'text-text-secondary hover:text-text-primary',
- )}
- aria-label="Configure web search"
- ref={searchMenuTriggerRef}
- >
- <div className="h-4 w-4">
- <Settings className="h-4 w-4" aria-hidden="true" />
- </div>
- </button>
- )}
- <button
- type="button"
- onClick={(e) => {
- e.stopPropagation();
- setIsSearchPinned?.(!isSearchPinned);
- }}
- className={cn(
- 'rounded p-1 transition-all duration-200',
- 'hover:bg-surface-secondary hover:shadow-xs',
- !isSearchPinned && 'text-text-secondary hover:text-text-primary',
- )}
- aria-label={isSearchPinned ? 'Unpin' : 'Pin'}
- >
- <div className="h-4 w-4">
- <PinIcon unpin={isSearchPinned} />
- </div>
- </button>
- </div>
- </div>
- ),
- });
- }
-
- if (canUseSkills && skillsEnabled) {
- dropdownItems.push({
- onClick: handleSkillsToggle,
- hideOnClick: false,
- render: (props) => (
- <div {...props} data-testid="tools-menu-skills">
- <div className="flex items-center gap-2">
- <ScrollText className="icon-md" aria-hidden="true" />
- <span>{localize('com_ui_skills')}</span>
- </div>
- <button
- type="button"
- onClick={(e) => {
- e.stopPropagation();
- setIsSkillsPinned?.(!isSkillsPinned);
- }}
- className={cn(
- 'rounded p-1 transition-all duration-200',
- 'hover:bg-surface-secondary hover:shadow-xs',
- !isSkillsPinned && 'text-text-secondary hover:text-text-primary',
- )}
- aria-label={isSkillsPinned ? localize('com_ui_unpin') : localize('com_ui_pin')}
- >
- <div className="h-4 w-4">
- <PinIcon unpin={isSkillsPinned} />
- </div>
- </button>
- </div>
- ),
- });
- }
-
- if (showMemory) {
- dropdownItems.push({
- onClick: handleMemoryToggle,
- hideOnClick: false,
- render: (props) => (
- <div {...props} data-testid="tools-menu-memory">
- <div className="flex items-center gap-2">
- <Brain className="icon-md" aria-hidden="true" />
- <span>{localize('com_ui_memory')}</span>
- </div>
- <button
- type="button"
- onClick={(e) => {
- e.stopPropagation();
- setIsMemoryPinned?.(!isMemoryPinned);
- }}
- className={cn(
- 'rounded p-1 transition-all duration-200',
- 'hover:bg-surface-secondary hover:shadow-xs',
- !isMemoryPinned && 'text-text-secondary hover:text-text-primary',
- )}
- aria-label={isMemoryPinned ? localize('com_ui_unpin') : localize('com_ui_pin')}
- >
- <div className="h-4 w-4">
- <PinIcon unpin={isMemoryPinned} />
- </div>
- </button>
- </div>
- ),
- });
- }
-
- if (canRunCode && codeEnabled) {
- dropdownItems.push({
- onClick: handleCodeInterpreterToggle,
- hideOnClick: false,
- render: (props) => (
- <div {...props} data-testid="tools-menu-run-code">
- <div className="flex items-center gap-2">
- <TerminalSquareIcon className="icon-md" aria-hidden="true" />
- <span>{localize('com_ui_run_code')}</span>
- </div>
- <div className="flex items-center gap-1">
- <button
- type="button"
- onClick={(e) => {
- e.stopPropagation();
- setIsCodePinned?.(!isCodePinned);
- }}
- className={cn(
- 'rounded p-1 transition-all duration-200',
- 'hover:bg-surface-secondary hover:shadow-xs',
- !isCodePinned && 'text-text-primary hover:text-text-primary',
- )}
- aria-label={isCodePinned ? 'Unpin' : 'Pin'}
- >
- <div className="h-4 w-4">
- <PinIcon unpin={isCodePinned} />
- </div>
- </button>
- </div>
- </div>
- ),
- });
- }
-
- if (artifactsEnabled && setIsArtifactsPinned != null) {
- dropdownItems.push({
- hideOnClick: false,
- render: (props) => (
- <ArtifactsSubMenu
- {...props}
- isArtifactsPinned={isArtifactsPinned ?? false}
- setIsArtifactsPinned={setIsArtifactsPinned}
- artifactsMode={artifacts?.toggleState as string}
- handleArtifactsToggle={handleArtifactsToggle}
- handleShadcnToggle={handleShadcnToggle}
- handleCustomToggle={handleCustomToggle}
- />
- ),
- });
- }
-
- const { availableMCPServers } = mcpServerManager ?? {};
- if (canUseMcp && availableMCPServers && availableMCPServers.length > 0) {
- dropdownItems.push({
- hideOnClick: false,
- render: (props) => <MCPSubMenu {...props} placeholder={mcpPlaceholder} />,
- });
- }
-
- if (dropdownItems.length === 0) {
- return null;
- }
-
- const menuTrigger = (
- <TooltipAnchor
- render={
- <Ariakit.MenuButton
- disabled={isDisabled}
- id="tools-dropdown-button"
- aria-label="Tools Options"
- className={cn(
- 'size-theme-control rounded-theme-control-round duration-theme-fast hover:bg-surface-composer-hover focus-visible:ring-text-primary/50 flex items-center justify-center p-1 transition-colors focus-visible:ring-2 focus-visible:outline-hidden',
- isPopoverActive && 'bg-surface-composer-hover',
- )}
- >
- <div className="flex w-full items-center justify-center gap-2">
- <Settings2 className="size-5" aria-hidden="true" />
- </div>
- </Ariakit.MenuButton>
- }
- id="tools-dropdown-button"
- description={localize('com_ui_tools')}
- disabled={isDisabled}
- />
- );
-
- return (
- <DropdownPopup
- itemClassName="flex w-full cursor-pointer rounded-lg items-center justify-between hover:bg-surface-hover gap-5"
- menuId="tools-dropdown-menu"
- isOpen={isPopoverActive}
- setIsOpen={setIsPopoverActive}
- modal={false}
- portal={true}
- portalElement={getMainLandmark}
- preserveTabOrder={false}
- unmountOnHide={true}
- trigger={menuTrigger}
- items={dropdownItems}
- iconClassName="mr-0"
- />
- );
-};
-
-export default React.memo(ToolsDropdown);
diff --git a/client/src/components/Chat/Input/WebSearch.tsx b/client/src/components/Chat/Input/WebSearch.tsx
deleted file mode 100644
index a991d6e903..0000000000
--- a/client/src/components/Chat/Input/WebSearch.tsx
+++ /dev/null
@@ -1,40 +0,0 @@
-import React, { memo } from 'react';
-import { Globe } from 'lucide-react';
-import { CheckboxButton } from '@librechat/client';
-import { Permissions, PermissionTypes } from 'librechat-data-provider';
-import { useLocalize, useHasAccess } from '~/hooks';
-import { useBadgeRowContext } from '~/Providers';
-import { badgeAccents } from './accents';
-
-function WebSearch() {
- const localize = useLocalize();
- const canUseWebSearch = useHasAccess({
- permissionType: PermissionTypes.WEB_SEARCH,
- permission: Permissions.USE,
- });
- const context = useBadgeRowContext();
- if (!canUseWebSearch) {
- return null;
- }
- if (!context) {
- return null;
- }
- const { webSearch: webSearchData, searchApiKeyForm } = context;
- const { toggleState: webSearch, debouncedChange, isPinned, authData } = webSearchData;
- const { badgeTriggerRef } = searchApiKeyForm;
-
- return (
- (isPinned || (webSearch && authData?.authenticated)) && (
- <CheckboxButton
- ref={badgeTriggerRef}
- checked={webSearch}
- setValue={debouncedChange}
- label={localize('com_ui_search')}
- isCheckedClassName={badgeAccents.blue}
- icon={<Globe className="icon-md" aria-hidden="true" />}
- />
- )
- );
-}
-
-export default memo(WebSearch);
diff --git a/client/src/components/Chat/Input/__tests__/AudioRecorder.spec.tsx b/client/src/components/Chat/Input/__tests__/AudioRecorder.spec.tsx
deleted file mode 100644
index 96c86d2ff2..0000000000
--- a/client/src/components/Chat/Input/__tests__/AudioRecorder.spec.tsx
+++ /dev/null
@@ -1,181 +0,0 @@
-import React from 'react';
-import { RecoilRoot } from 'recoil';
-import { act, render, screen } from '@testing-library/react';
-import AudioRecorder from '../AudioRecorder';
-import store from '~/store';
-
-let mockSpeechToTextEndpoint = 'browser';
-let mockBrowserIsListening = false;
-let mockExternalIsListening = false;
-let mockSetText: ((text: string) => void) | undefined;
-
-const mockStartSpeechRecordingBrowser = jest.fn();
-const mockStopSpeechRecordingBrowser = jest.fn();
-const mockStartSpeechRecordingExternal = jest.fn();
-const mockStopSpeechRecordingExternal = jest.fn();
-const mockSetValue = jest.fn();
-const mockReset = jest.fn();
-const mockGetValues = jest.fn(() => 'existing draft');
-const mockAsk = jest.fn(() => true);
-
-type MockButtonProps = React.ComponentProps<'button'> & {
- label?: string;
- variant?: string;
- size?: string;
- shape?: string;
-};
-
-jest.mock('@librechat/client', () => ({
- IconButton: ({
- children,
- label,
- variant: _variant,
- size: _size,
- shape: _shape,
- ...props
- }: MockButtonProps) => (
- <button aria-label={label} {...props}>
- {children}
- </button>
- ),
- TooltipAnchor: ({ render }: { render: React.ReactElement }) => render,
- ListeningIcon: () => <span />,
- Spinner: () => <span />,
- useToastContext: () => ({ showToast: jest.fn() }),
-}));
-
-jest.mock('~/hooks/Input/useSpeechToTextBrowser', () => ({
- __esModule: true,
- default: (setText: (text: string) => void) => {
- mockSetText = setText;
- return {
- isListening: mockBrowserIsListening,
- isLoading: false,
- startRecording: mockStartSpeechRecordingBrowser,
- stopRecording: mockStopSpeechRecordingBrowser,
- };
- },
-}));
-
-jest.mock('~/hooks/Input/useSpeechToTextExternal', () => ({
- __esModule: true,
- default: (setText: (text: string) => void) => {
- mockSetText = setText;
- return {
- isListening: mockExternalIsListening,
- isLoading: false,
- externalStartRecording: mockStartSpeechRecordingExternal,
- externalStopRecording: mockStopSpeechRecordingExternal,
- };
- },
-}));
-
-jest.mock('~/hooks/Input/useGetAudioSettings', () => ({
- __esModule: true,
- default: () => ({ speechToTextEndpoint: mockSpeechToTextEndpoint }),
-}));
-
-jest.mock('~/hooks', () => ({
- useLocalize: () => (key: string) => key,
- useGetAudioSettings: () => ({ speechToTextEndpoint: mockSpeechToTextEndpoint }),
- useSpeechToText: jest.requireActual('~/hooks/Input/useSpeechToText').default,
-}));
-
-jest.mock('~/common', () => ({
- ...jest.requireActual('~/common'),
- globalAudioId: 'global-audio',
-}));
-
-const dispatchSpeechShortcut = () => {
- const event = new KeyboardEvent('keydown', {
- shiftKey: true,
- altKey: true,
- code: 'KeyL',
- bubbles: true,
- cancelable: true,
- });
-
- act(() => window.dispatchEvent(event));
- return event;
-};
-
-const renderRecorder = ({ disabled = false, initialized = true } = {}) =>
- render(
- <RecoilRoot initializeState={({ set }) => set(store.speechSettingsInitialized, initialized)}>
- <AudioRecorder
- disabled={disabled}
- ask={mockAsk as never}
- methods={
- {
- setValue: mockSetValue,
- reset: mockReset,
- getValues: mockGetValues,
- } as never
- }
- isSubmitting={false}
- />
- </RecoilRoot>,
- );
-
-describe('AudioRecorder speech shortcut', () => {
- beforeEach(() => {
- jest.clearAllMocks();
- mockSpeechToTextEndpoint = 'browser';
- mockBrowserIsListening = false;
- mockExternalIsListening = false;
- mockSetText = undefined;
- });
-
- it('preserves the existing draft when browser recording starts from the shortcut', () => {
- renderRecorder();
-
- const event = dispatchSpeechShortcut();
- act(() => mockSetText?.('transcript'));
-
- expect(mockStartSpeechRecordingBrowser).toHaveBeenCalledTimes(1);
- expect(mockSetValue).toHaveBeenCalledWith('text', 'existing draft transcript', {
- shouldValidate: true,
- });
- expect(event.defaultPrevented).toBe(true);
- });
-
- it('does not invoke either recorder while the control is disabled', () => {
- renderRecorder({ disabled: true });
-
- dispatchSpeechShortcut();
-
- expect(mockStartSpeechRecordingBrowser).not.toHaveBeenCalled();
- expect(mockStopSpeechRecordingBrowser).not.toHaveBeenCalled();
- });
-
- it('does not start browser recording before speech settings initialization completes', () => {
- renderRecorder({ initialized: false });
-
- dispatchSpeechShortcut();
-
- expect(mockStartSpeechRecordingBrowser).not.toHaveBeenCalled();
- expect(mockStartSpeechRecordingExternal).not.toHaveBeenCalled();
- expect(screen.getByRole('button', { name: 'com_ui_use_micrphone' })).toBeDisabled();
- });
-
- it('stops the selected engine from the shortcut', () => {
- mockSpeechToTextEndpoint = 'external';
- mockExternalIsListening = true;
- renderRecorder();
-
- dispatchSpeechShortcut();
-
- expect(mockStopSpeechRecordingExternal).toHaveBeenCalledTimes(1);
- expect(mockStopSpeechRecordingBrowser).not.toHaveBeenCalled();
- });
-
- it('does not stop a recorder while the control is disabled', () => {
- mockSpeechToTextEndpoint = 'external';
- mockExternalIsListening = true;
- renderRecorder({ disabled: true });
-
- dispatchSpeechShortcut();
-
- expect(mockStopSpeechRecordingExternal).not.toHaveBeenCalled();
- });
-});
diff --git a/client/src/components/Chat/Input/__tests__/ChatForm.approvalMode.spec.tsx b/client/src/components/Chat/Input/__tests__/ChatForm.approvalMode.spec.tsx
index b0d2ba31e9..76295c54a0 100644
--- a/client/src/components/Chat/Input/__tests__/ChatForm.approvalMode.spec.tsx
+++ b/client/src/components/Chat/Input/__tests__/ChatForm.approvalMode.spec.tsx
@@ -75,7 +75,13 @@ function Harness() {
return (
<ChatFormProvider {...methods}>
<ChatContext.Provider value={chatHelpers}>
- <ChatForm index={0} isLandingPage={false} footerBelow={false} centerFormOnLanding={false} />
+ <ChatForm
+ index={0}
+ isLandingPage={false}
+ showComposerTips={false}
+ footerBelow={false}
+ centerFormOnLanding={false}
+ />
</ChatContext.Provider>
</ChatFormProvider>
);
diff --git a/client/src/components/Chat/Input/__tests__/ChatForm.attachments.spec.tsx b/client/src/components/Chat/Input/__tests__/ChatForm.attachments.spec.tsx
index cf7d206569..e4d60c236e 100644
--- a/client/src/components/Chat/Input/__tests__/ChatForm.attachments.spec.tsx
+++ b/client/src/components/Chat/Input/__tests__/ChatForm.attachments.spec.tsx
@@ -70,7 +70,9 @@ let commits = 0;
function Harness() {
const [files, setFiles] = useRecoilState(store.filesByIndex(0));
- const [isSubmitting, setIsSubmitting] = useRecoilState(store.isSubmittingFamily(0));
+ const [isSubmitting] = useRecoilState(store.isSubmittingFamily(0));
+ /* ChatView owns this read and passes it in; the harness stands in for it. */
+ const [speechSettingsInitialized] = useRecoilState(store.speechSettingsInitialized);
const [, setFilesLoading] = useState(false);
const methods = useForm<ChatFormValues>({ defaultValues: { text: '' } });
@@ -121,6 +123,8 @@ function Harness() {
<ChatForm
index={0}
isLandingPage={false}
+ showComposerTips={false}
+ speechSettingsInitialized={speechSettingsInitialized}
footerBelow={false}
centerFormOnLanding={false}
/>
@@ -133,7 +137,8 @@ function Harness() {
function renderComposer({
submitting = false,
quotes = [],
-}: { submitting?: boolean; quotes?: string[] } = {}) {
+ speechSettingsInitialized = false,
+}: { submitting?: boolean; quotes?: string[]; speechSettingsInitialized?: boolean } = {}) {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
});
@@ -151,13 +156,16 @@ function renderComposer({
<RecoilRoot
initializeState={({ set }) => {
set(store.isSubmittingFamily(0), submitting);
+ set(store.speechSettingsInitialized, speechSettingsInitialized);
set(store.pendingQuotesByConvoId(conversation.conversationId ?? ''), quotes);
}}
>
<Router>
<AuthContextProvider authConfig={{ loginRedirect: '', test: true }}>
<DndProvider backend={HTML5Backend}>
- <Harness />
+ <main>
+ <Harness />
+ </main>
</DndProvider>
</AuthContextProvider>
</Router>
@@ -204,6 +212,18 @@ describe('ChatForm attachments', () => {
});
});
+ test('keeps the mic disabled until speech settings hydrate', async () => {
+ const pending = renderComposer({ speechSettingsInitialized: false });
+ const micName = 'Use microphone';
+
+ expect(await screen.findByRole('button', { name: micName })).toBeDisabled();
+
+ pending.unmount();
+ renderComposer({ speechSettingsInitialized: true });
+
+ expect(await screen.findByRole('button', { name: micName })).toBeEnabled();
+ }, 20000);
+
test('re-enables send once an attachment finishes uploading', async () => {
const { container } = renderComposer();
@@ -221,7 +241,7 @@ describe('ChatForm attachments', () => {
test('does not steal focus when clicking the nested attachment icon', async () => {
renderComposer();
const textarea = await screen.findByTestId('text-input');
- const trigger = screen.getByRole('button', { name: 'Attach File Options' });
+ const trigger = screen.getByTestId('composer-palette-button');
expect(trigger).toBeEnabled();
const icon = trigger.querySelector('svg');
expect(icon).not.toBeNull();
@@ -230,19 +250,19 @@ describe('ChatForm attachments', () => {
await userEvent.click(icon as SVGElement);
expect(focus).not.toHaveBeenCalled();
- expect(await screen.findByRole('menu', { name: 'Attach File Options' })).toBeInTheDocument();
+ expect(await screen.findByRole('dialog', { name: 'Attach and tools' })).toBeInTheDocument();
}, 20000);
test('closes an open menu when the textarea is clicked', async () => {
renderComposer();
const textarea = await screen.findByTestId('text-input');
- await userEvent.click(screen.getByRole('button', { name: 'Attach File Options' }));
- expect(await screen.findByRole('menu', { name: 'Attach File Options' })).toBeInTheDocument();
+ await userEvent.click(screen.getByTestId('composer-palette-button'));
+ expect(await screen.findByRole('dialog', { name: 'Attach and tools' })).toBeInTheDocument();
await userEvent.click(textarea);
await waitFor(() =>
- expect(screen.queryByRole('menu', { name: 'Attach File Options' })).not.toBeInTheDocument(),
+ expect(screen.queryByRole('dialog', { name: 'Attach and tools' })).not.toBeInTheDocument(),
);
expect(textarea).toHaveFocus();
}, 20000);
@@ -324,54 +344,62 @@ describe('ChatForm attachments', () => {
expect(textarea).toHaveFocus();
}, 20000);
- test('returns focus to the textarea when removing a quote collapses the popup', async () => {
- renderComposer({ quotes: ['alpha', 'beta'] });
+ test('returns focus to the textarea when the last quote is removed', async () => {
+ renderComposer({ quotes: ['alpha'] });
const textarea = await screen.findByTestId('text-input');
- // Hover opens this disclosure too; test the click path without a synthetic hover toggle.
- await userEvent.click(screen.getByRole('button', { name: '2 selections' }), {
- skipHover: true,
- });
- const popup = await screen.findByRole('dialog');
- await userEvent.click(within(popup).getAllByRole('button', { name: 'Remove quote' })[0]);
+ await userEvent.click(screen.getByRole('button', { name: 'Remove quote' }));
- await waitFor(() => expect(screen.queryByTestId('quote-selections-popup')).toBeNull());
- expect(screen.getByText('beta')).toBeInTheDocument();
+ await waitFor(() => expect(screen.queryAllByTestId('composer-chip-quote')).toHaveLength(0));
expect(textarea).toHaveFocus();
}, 20000);
+ test('moves focus to the remaining quote when one of two is removed', async () => {
+ renderComposer({ quotes: ['alpha', 'beta'] });
+ await screen.findByTestId('text-input');
+ const firstChip = () => screen.getAllByTestId('composer-chip-quote')[0];
+
+ await userEvent.click(within(firstChip()).getByRole('button', { name: 'Remove quote' }));
+
+ await waitFor(() => expect(screen.getAllByTestId('composer-chip-quote')).toHaveLength(1));
+ expect(screen.getByText('beta')).toBeInTheDocument();
+ expect(
+ within(screen.getByTestId('composer-chip-quote')).getByRole('button', {
+ name: 'Remove quote',
+ }),
+ ).toHaveFocus();
+ }, 20000);
+
test('keeps focus inside the popup when removing a quote leaves several', async () => {
renderComposer({ quotes: ['alpha', 'beta', 'gamma'] });
await screen.findByTestId('text-input');
- // Hover opens this disclosure too; test the click path without a synthetic hover toggle.
- await userEvent.click(screen.getByRole('button', { name: '3 selections' }), {
- skipHover: true,
- });
- const popup = await screen.findByRole('dialog');
+ const firstChip = () => screen.getAllByTestId('composer-chip-quote')[0];
- await userEvent.click(within(popup).getAllByRole('button', { name: 'Remove quote' })[0]);
+ await userEvent.click(within(firstChip()).getByRole('button', { name: 'Remove quote' }));
- await waitFor(() => expect(within(popup).getAllByRole('button')).toHaveLength(2));
- expect(within(popup).getAllByRole('button', { name: 'Remove quote' })[0]).toHaveFocus();
+ await waitFor(() => expect(screen.getAllByTestId('composer-chip-quote')).toHaveLength(2));
+ expect(
+ within(screen.getAllByTestId('composer-chip-quote')[0]).getByRole('button', {
+ name: 'Remove quote',
+ }),
+ ).toHaveFocus();
}, 20000);
test('does not raise the keyboard when a quote removal collapses the popup on touch', async () => {
const matchMedia = window.matchMedia;
- window.matchMedia = jest
- .fn()
- .mockReturnValue({ matches: true }) as unknown as typeof matchMedia;
+ window.matchMedia = jest.fn().mockReturnValue({
+ matches: true,
+ addEventListener: jest.fn(),
+ removeEventListener: jest.fn(),
+ }) as unknown as typeof matchMedia;
try {
renderComposer({ quotes: ['alpha', 'beta'] });
const textarea = await screen.findByTestId('text-input');
- // Hover opens this disclosure too; test the click path without a synthetic hover toggle.
- await userEvent.click(screen.getByRole('button', { name: '2 selections' }), {
- skipHover: true,
- });
- const popup = await screen.findByRole('dialog');
+ const firstChip = () => screen.getAllByTestId('composer-chip-quote')[0];
- await userEvent.click(within(popup).getAllByRole('button', { name: 'Remove quote' })[0]);
+ await userEvent.click(within(firstChip()).getByRole('button', { name: 'Remove quote' }));
- await waitFor(() => expect(screen.queryByTestId('quote-selections-popup')).toBeNull());
+ await waitFor(() => expect(screen.getAllByTestId('composer-chip-quote')).toHaveLength(1));
expect(textarea).not.toHaveFocus();
} finally {
window.matchMedia = matchMedia;
diff --git a/client/src/components/Chat/Input/__tests__/ChatForm.enterToSend.spec.tsx b/client/src/components/Chat/Input/__tests__/ChatForm.enterToSend.spec.tsx
new file mode 100644
index 0000000000..e4cd6841b9
--- /dev/null
+++ b/client/src/components/Chat/Input/__tests__/ChatForm.enterToSend.spec.tsx
@@ -0,0 +1,136 @@
+import React, { useMemo, useState } from 'react';
+import '@testing-library/jest-dom';
+import { DndProvider } from 'react-dnd';
+import { useForm } from 'react-hook-form';
+import { RecoilRoot, useRecoilState } from 'recoil';
+import userEvent from '@testing-library/user-event';
+import { HTML5Backend } from 'react-dnd-html5-backend';
+import { render, screen } from '@testing-library/react';
+import { BrowserRouter as Router } from 'react-router-dom';
+import { QueryKeys, EModelEndpoint } from 'librechat-data-provider';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import type { TFile, TConversation } from 'librechat-data-provider';
+import type { ChatFormValues } from '~/common';
+import { ChatContext, ChatFormProvider } from '~/Providers';
+import { AuthContextProvider } from '~/hooks/AuthContext';
+import ChatForm from '../ChatForm';
+import store from '~/store';
+
+const conversation = {
+ conversationId: 'new',
+ endpoint: EModelEndpoint.openAI,
+ model: 'gpt-4o',
+ title: 'New Chat',
+} as TConversation;
+
+/**
+ * The atom default (`atomWithLocalStorage('enterToSend', true)`) always stays
+ * true here: these tests prove the composer follows the `enterToSend` prop
+ * ChatView passes it, not the atom it used to read directly, so the prop is
+ * deliberately set opposite to that default.
+ */
+function Harness({ enterToSend }: { enterToSend: boolean }) {
+ const [files, setFiles] = useRecoilState(store.filesByIndex(0));
+ const [isSubmitting] = useRecoilState(store.isSubmittingFamily(0));
+ const [, setFilesLoading] = useState(false);
+ const methods = useForm<ChatFormValues>({ defaultValues: { text: '' } });
+
+ const chatHelpers = useMemo(
+ () =>
+ ({
+ index: 0,
+ conversation,
+ setConversation: () => undefined,
+ files,
+ setFiles,
+ isSubmitting,
+ setIsSubmitting: () => undefined,
+ filesLoading: false,
+ setFilesLoading,
+ newConversation: () => undefined,
+ handleStopGenerating: () => undefined,
+ stopGenerating: () => undefined,
+ getMessages: () => undefined,
+ setMessages: () => undefined,
+ ask: () => undefined,
+ regenerate: () => undefined,
+ setSiblingIdx: () => undefined,
+ showPopover: false,
+ setShowPopover: () => undefined,
+ abortScroll: false,
+ setAbortScroll: () => undefined,
+ preset: null,
+ setPreset: () => undefined,
+ optionSettings: {},
+ setOptionSettings: () => undefined,
+ handleRegenerate: () => undefined,
+ handleContinue: () => undefined,
+ }) as unknown as React.ContextType<typeof ChatContext>,
+ [files, setFiles, isSubmitting],
+ );
+
+ return (
+ <ChatFormProvider {...methods}>
+ <ChatContext.Provider value={chatHelpers}>
+ <ChatForm
+ index={0}
+ isLandingPage={false}
+ showComposerTips
+ enterToSend={enterToSend}
+ footerBelow={false}
+ centerFormOnLanding={false}
+ />
+ </ChatContext.Provider>
+ </ChatFormProvider>
+ );
+}
+
+function renderComposer({ enterToSend }: { enterToSend: boolean }) {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ });
+ queryClient.setQueryData<TFile[]>([QueryKeys.files], []);
+ queryClient.setQueryData([QueryKeys.endpoints], { [EModelEndpoint.openAI]: { order: 0 } });
+
+ return render(
+ <QueryClientProvider client={queryClient}>
+ <RecoilRoot>
+ <Router>
+ <AuthContextProvider authConfig={{ loginRedirect: '', test: true }}>
+ <DndProvider backend={HTML5Backend}>
+ <Harness enterToSend={enterToSend} />
+ </DndProvider>
+ </AuthContextProvider>
+ </Router>
+ </RecoilRoot>
+ </QueryClientProvider>,
+ );
+}
+
+describe('ChatForm enterToSend prop', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ });
+
+ test('follows the prop when it disagrees with the persisted default', async () => {
+ renderComposer({ enterToSend: false });
+
+ const textarea = await screen.findByTestId('text-input');
+ await userEvent.type(textarea, 'hi');
+
+ const hint = await screen.findByTestId('composer-hints');
+ expect(hint).toHaveTextContent('to send');
+ expect(hint).toHaveTextContent('for newline');
+ expect(hint).not.toHaveTextContent('Enter to send');
+ }, 20000);
+
+ test('reflects the prop when it agrees with the persisted default', async () => {
+ renderComposer({ enterToSend: true });
+
+ const textarea = await screen.findByTestId('text-input');
+ await userEvent.type(textarea, 'hi');
+
+ const hint = await screen.findByTestId('composer-hints');
+ expect(hint).toHaveTextContent('Enter to send');
+ }, 20000);
+});
diff --git a/client/src/components/Chat/Input/__tests__/ChatForm.pasteUpload.spec.tsx b/client/src/components/Chat/Input/__tests__/ChatForm.pasteUpload.spec.tsx
index d29222cbda..94a93470b1 100644
--- a/client/src/components/Chat/Input/__tests__/ChatForm.pasteUpload.spec.tsx
+++ b/client/src/components/Chat/Input/__tests__/ChatForm.pasteUpload.spec.tsx
@@ -111,6 +111,7 @@ function Harness() {
<ChatForm
index={0}
isLandingPage={false}
+ showComposerTips={false}
footerBelow={false}
centerFormOnLanding={false}
/>
diff --git a/client/src/components/Chat/Input/__tests__/DuringRunSendButton.test.tsx b/client/src/components/Chat/Input/__tests__/DuringRunSendButton.test.tsx
index bf768de632..fa003b0a26 100644
--- a/client/src/components/Chat/Input/__tests__/DuringRunSendButton.test.tsx
+++ b/client/src/components/Chat/Input/__tests__/DuringRunSendButton.test.tsx
@@ -52,13 +52,7 @@ const steeringStub = ({
interruptAndSend: mockInterruptAndSend,
}) as unknown as SteeringControls;
-function Harness({
- steering,
- isNewConversation,
-}: {
- steering: SteeringControls;
- isNewConversation: boolean;
-}) {
+function Harness({ steering, enterToSend }: { steering: SteeringControls; enterToSend: boolean }) {
const methods = useForm<{ text: string }>({ defaultValues: { text: TEXT } });
return (
<DuringRunSendButton
@@ -67,6 +61,7 @@ function Harness({
isNewConversation={isNewConversation}
getText={() => TEXT}
onConsumed={mockOnConsumed}
+ enterToSend={enterToSend}
/>
);
}
@@ -92,12 +87,11 @@ function openMenu(options: MenuOptions = {}) {
<RecoilRoot
initializeState={({ set }) => {
set(store.steerInterruptsByDefault, enterInterrupts);
- set(store.enterToSend, enterToSend);
set(store.shortcutsEnabled, shortcutsEnabled);
set(store.customShortcuts, customShortcuts);
}}
>
- <Harness steering={steeringStub(stub)} isNewConversation={isNewConversation} />
+ <Harness steering={steeringStub(stub)} enterToSend={enterToSend} />
</RecoilRoot>,
);
expect(
diff --git a/client/src/components/Chat/Input/__tests__/EscalateNowButton.spec.tsx b/client/src/components/Chat/Input/__tests__/EscalateNowButton.spec.tsx
new file mode 100644
index 0000000000..6f7b380d62
--- /dev/null
+++ b/client/src/components/Chat/Input/__tests__/EscalateNowButton.spec.tsx
@@ -0,0 +1,60 @@
+import { render, screen, fireEvent, act } from '@testing-library/react';
+import EscalateNowButton from '../EscalateNowButton';
+
+jest.mock('~/hooks', () => ({
+ useLocalize: () => (key: string) => key,
+}));
+
+jest.mock('~/hooks/useKeyboardShortcuts', () => ({
+ useShortcutDisplay: () => 'Ctrl+Shift+.',
+ useShortcutAriaKey: () => 'Control+Shift+.',
+}));
+
+function Pane({ index }: { index: number }) {
+ return (
+ <section data-chat-pane={index}>
+ <textarea aria-label={`composer ${index}`} />
+ <EscalateNowButton
+ surface="bubble"
+ disabled={false}
+ messageText={`waiting ${index}`}
+ onClick={jest.fn()}
+ />
+ </section>
+ );
+}
+
+const escalation = (index: number) =>
+ screen.getByRole('button', { name: `com_ui_interrupt_steer_now: waiting ${index}` });
+
+describe('EscalateNowButton', () => {
+ it('advertises a hovered button as the shortcut target only in the focused pane', () => {
+ render(
+ <>
+ <Pane index={0} />
+ <Pane index={1} />
+ </>,
+ );
+ act(() => screen.getByLabelText('composer 0').focus());
+
+ fireEvent.pointerEnter(escalation(1));
+ expect(escalation(1)).not.toHaveAttribute('data-escalate-steer-active');
+ expect(escalation(1)).not.toHaveAttribute('aria-keyshortcuts');
+
+ act(() => screen.getByLabelText('composer 1').focus());
+ expect(escalation(1)).toHaveAttribute('data-escalate-steer-active', 'true');
+ expect(escalation(1)).toHaveAttribute('aria-keyshortcuts', 'Control+Shift+.');
+
+ fireEvent.pointerLeave(escalation(1));
+ expect(escalation(1)).not.toHaveAttribute('data-escalate-steer-active');
+ });
+
+ it('advertises a hovered button while focus sits outside every pane', () => {
+ render(<Pane index={0} />);
+
+ fireEvent.pointerEnter(escalation(0));
+
+ expect(escalation(0)).toHaveAttribute('data-escalate-steer-active', 'true');
+ fireEvent.pointerLeave(escalation(0));
+ });
+});
diff --git a/client/src/components/Chat/Input/__tests__/InFlightSteers.test.tsx b/client/src/components/Chat/Input/__tests__/InFlightSteers.test.tsx
deleted file mode 100644
index e0c7ab75ec..0000000000
--- a/client/src/components/Chat/Input/__tests__/InFlightSteers.test.tsx
+++ /dev/null
@@ -1,1308 +0,0 @@
-import React from 'react';
-import { getDefaultStore } from 'jotai';
-import { RecoilRoot, useRecoilValue, useSetRecoilState } from 'recoil';
-import { render, screen, fireEvent, act } from '@testing-library/react';
-import type { PendingSteer, QueuedMessage } from '~/store/families';
-import type { SteeringControls } from '~/hooks/Chat/useSteering';
-import { steerOverlayHeightFamily, escalatingSteerFamily } from '~/store/steer';
-import useSteerConvert from '~/hooks/Chat/useSteerConvert';
-import InFlightSteers from '../InFlightSteers';
-import store from '~/store';
-
-const mockCancelMutateAsync = jest.fn();
-const mockShowToast = jest.fn();
-const mockQueueReclaimedSteer = jest.fn();
-const mockRemoveSteer = jest.fn();
-const mockRetrySteer = jest.fn();
-const mockArmMutateAsync = jest.fn();
-const mockSetDefaultAction = jest.fn();
-const mockRestoreToComposer = jest.fn();
-let convertSteersForTest: ReturnType<typeof useSteerConvert>;
-let observedQueueForTest: QueuedMessage[];
-let setSteersForTest: (updater: (prev: PendingSteer[]) => PendingSteer[]) => void;
-let mockFileMap: Record<string, { llmDeliveryPath?: 'provider' | 'text' | 'none' }> = {};
-
-jest.mock('~/Providers', () => ({
- useFileMapContext: () => mockFileMap,
-}));
-
-jest.mock('~/hooks', () => ({
- useLocalize: () => (key: string) => key,
- useSteerCancel: jest.requireActual('~/hooks/Chat/useSteerCancel').default,
- useSteerReclaim: jest.requireActual('~/hooks/Chat/useSteerCancel').useSteerReclaim,
-}));
-
-jest.mock('~/../test/mockMorphIcon', () => jest.requireActual('~/../test/mockMorphIcon'));
-
-jest.mock('@librechat/client', () => {
- const { createSteerMorphIconMock } = jest.requireActual('~/../test/mockMorphIcon');
- return {
- useToastContext: () => ({ showToast: mockShowToast }),
- /** Trigger-only stand-in: the receipt renders its marks as the hover card's
- * custom trigger, so the mock must render children under the accessible
- * name rather than swallowing them. */
- InfoHoverCard: ({ text, children }: { text: string; children?: React.ReactNode }) => (
- <button type="button" aria-label={text}>
- {children}
- </button>
- ),
- ESide: { Top: 'top', Bottom: 'bottom' },
- MorphIcon: createSteerMorphIconMock(),
- };
-});
-
-jest.mock('~/data-provider', () => ({
- useCancelSteerMutation: () => ({ mutateAsync: mockCancelMutateAsync }),
- useArmSteerMutation: () => ({ mutateAsync: mockArmMutateAsync }),
- getGenerationProtocolVersion: (value: unknown) =>
- value != null &&
- typeof value === 'object' &&
- (value as { generationProtocolVersion?: unknown }).generationProtocolVersion === 2
- ? 2
- : 1,
- supportsGenerationProtocolV2: (value: unknown) =>
- value != null &&
- typeof value === 'object' &&
- (value as { generationProtocolVersion?: unknown }).generationProtocolVersion === 2,
-}));
-
-jest.mock('~/components/Chat/Input/Files/FileContainer', () => ({
- __esModule: true,
- default: ({ file, onClick }: { file: { filename?: string }; onClick?: () => void }) => (
- <button type="button" data-testid="steer-file" onClick={onClick}>
- {file.filename}
- </button>
- ),
-}));
-
-/** The composer thumbnail path: a fixed-size button painted with a background
- * image, not an <img> — assert on the url it was handed. */
-jest.mock('~/components/Chat/Input/Files/ImagePreview', () => ({
- __esModule: true,
- default: ({ url, alt }: { url?: string; alt?: string }) => (
- <button type="button" data-testid="steer-image" data-url={url} aria-label={alt} />
- ),
-}));
-
-jest.mock('~/components/Chat/Messages/Content/FilePreviewDialog', () => ({
- __esModule: true,
- default: ({
- open,
- fileName,
- deliveryPath,
- }: {
- open: boolean;
- fileName: string;
- deliveryPath?: string;
- }) =>
- open ? (
- <div data-testid="steer-file-preview" data-delivery-path={deliveryPath}>
- {fileName}
- </div>
- ) : null,
-}));
-
-jest.mock('~/components/Chat/Messages/Content/MarkdownLite', () => ({
- __esModule: true,
- default: ({ content, codeExecution }: { content: string; codeExecution?: boolean }) => (
- <span data-testid="steer-markdown" data-code-execution={String(codeExecution)}>
- {content}
- </span>
- ),
-}));
-
-const CONVO_ID = 'convo-in-flight';
-
-const steeringStub = (defaultAction: 'steer' | 'queue' = 'steer', duringRunActive = true) =>
- ({
- defaultAction,
- duringRunActive,
- pausedOnApproval: false,
- removeSteer: mockRemoveSteer,
- retrySteer: mockRetrySteer,
- setDefaultAction: mockSetDefaultAction,
- queueReclaimedSteer: mockQueueReclaimedSteer,
- }) as unknown as SteeringControls;
-
-type RenderOptions = {
- enableUserMsgMarkdown?: boolean;
- appliedSteerIds?: string[];
- defaultAction?: 'steer' | 'queue';
- duringRunActive?: boolean;
- activeGenerationCreatedAt?: number | null;
- activeGenerationProtocolVersion?: 1 | 2;
-};
-
-/** Element builder shared by first render and rerenders — `initializeState`
- * only applies on mount, so a rerender just swaps the steering controls. */
-function steersElement(steers: PendingSteer[], options?: RenderOptions) {
- const SteerRaceProbe = () => {
- convertSteersForTest = useSteerConvert();
- observedQueueForTest = useRecoilValue(store.queuedMessagesByConvoId(CONVO_ID));
- setSteersForTest = useSetRecoilState(store.pendingSteersByConvoId(CONVO_ID));
- return null;
- };
- return (
- <RecoilRoot
- initializeState={({ set }) => {
- set(store.pendingSteersByConvoId(CONVO_ID), steers);
- const activeGenerationCreatedAt =
- options?.activeGenerationCreatedAt === undefined ? 41 : options.activeGenerationCreatedAt;
- if (options?.appliedSteerIds != null) {
- set(store.appliedSteerIdsByConvoId(CONVO_ID), options.appliedSteerIds);
- }
- if (options?.enableUserMsgMarkdown != null) {
- set(store.enableUserMsgMarkdown, options.enableUserMsgMarkdown);
- }
- if (activeGenerationCreatedAt != null) {
- set(store.activeGenerationCreatedAtByConvoId(CONVO_ID), activeGenerationCreatedAt);
- }
- set(
- store.activeGenerationProtocolVersionByConvoId(CONVO_ID),
- options?.activeGenerationProtocolVersion ?? 2,
- );
- }}
- >
- <SteerRaceProbe />
- <InFlightSteers
- conversationId={CONVO_ID}
- steering={steeringStub(options?.defaultAction, options?.duringRunActive)}
- onRestoreToComposer={mockRestoreToComposer}
- />
- </RecoilRoot>
- );
-}
-
-function renderSteers(steers: PendingSteer[], options?: RenderOptions) {
- return render(steersElement(steers, options));
-}
-
-/** Opens a bubble's "…" menu and clicks one of its items, flushing the reclaim
- * round-trip the action awaits before it re-homes the text. */
-async function clickMenuItem(label: string) {
- fireEvent.click(screen.getByLabelText('com_ui_more_options'));
- const item = await screen.findByText(label);
- await act(async () => {
- fireEvent.click(item);
- });
-}
-
-describe('InFlightSteers', () => {
- beforeEach(() => {
- jest.clearAllMocks();
- mockFileMap = {};
- mockCancelMutateAsync.mockResolvedValue({ removed: true });
- mockRestoreToComposer.mockReturnValue(true);
- observedQueueForTest = [];
- });
-
- it('renders nothing when no steer is in flight', () => {
- renderSteers([]);
- expect(screen.queryByTestId('in-flight-steers')).toBeNull();
- });
-
- it('anchors sending and pending steers above the composer, not in-thread', () => {
- renderSteers([
- { steerId: 's1', text: 'first correction', status: 'sending', createdAt: 1 },
- { steerId: 's2', text: 'second correction', status: 'pending', createdAt: 2 },
- ]);
- expect(screen.getAllByTestId('in-flight-steer')).toHaveLength(2);
- expect(screen.getByText('first correction')).toBeInTheDocument();
- expect(screen.getByText('second correction')).toBeInTheDocument();
- // The in-thread SteerPart is reserved for server-applied steers.
- expect(screen.queryByTestId('steer-part')).toBeNull();
- });
-
- it('leaves failed steers to the composer recovery rows', () => {
- renderSteers([{ steerId: 's3', text: 'never sent', status: 'failed', createdAt: 1 }]);
- expect(screen.queryByTestId('in-flight-steers')).toBeNull();
- });
-
- it('renders carried quotes as the same reference blocks the applied part shows', () => {
- renderSteers([
- {
- steerId: 's-quoted',
- text: 'about the selection',
- status: 'pending',
- createdAt: 1,
- quotes: ['the selected excerpt'],
- },
- ]);
- expect(screen.getByTestId('message-quotes')).toHaveTextContent('the selected excerpt');
- });
-
- it('shows the menu at rest on every pointer, without hover-gating', () => {
- renderSteers([
- { steerId: 's-ack', text: 'waiting on boundary', status: 'pending', createdAt: 1 },
- ]);
- // The menu is the single control now (Cancel folded in), so a label-less ⋯
- // hidden until hover would be undiscoverable — and unreachable on touch,
- // where there is no hover. It must be visible at rest.
- const controls = screen.getByTestId('steer-controls');
- expect(controls.className).not.toContain('opacity-0');
- expect(screen.getByLabelText('com_ui_more_options')).toBeInTheDocument();
- });
-
- it('only offers the menu once the steer is acknowledged', () => {
- renderSteers([
- { steerId: 'local-1', text: 'still posting', status: 'sending', createdAt: 1 },
- { steerId: 's-ack', text: 'waiting on boundary', status: 'pending', createdAt: 2 },
- ]);
- // A 'sending' entry has no server id yet, so there is nothing to act on —
- // cancel and the re-homing actions all need to reclaim it first.
- expect(screen.getAllByLabelText('com_ui_more_options')).toHaveLength(1);
- });
-
- it('cancels a pending steer from the menu and drops the bubble', async () => {
- renderSteers([
- { steerId: 's-ack', text: 'waiting on boundary', status: 'pending', createdAt: 1 },
- ]);
- await clickMenuItem('com_ui_steer_cancel');
-
- expect(mockCancelMutateAsync).toHaveBeenCalledWith({
- conversationId: CONVO_ID,
- steerId: 's-ack',
- generationCreatedAt: 41,
- });
- await act(async () => {});
- expect(screen.queryByText('waiting on boundary')).toBeNull();
- });
-
- it('fences cancel to the generation recorded on the steer', async () => {
- renderSteers(
- [
- {
- steerId: 's-epoch',
- text: 'belongs to the old turn',
- status: 'pending',
- createdAt: 1,
- generationCreatedAt: 41,
- },
- ],
- { activeGenerationCreatedAt: 99 },
- );
- await clickMenuItem('com_ui_steer_cancel');
-
- expect(mockCancelMutateAsync).toHaveBeenCalledWith({
- conversationId: CONVO_ID,
- steerId: 's-epoch',
- generationCreatedAt: 41,
- });
- });
-
- it('does not send a cancel before any generation epoch is known', async () => {
- renderSteers(
- [{ steerId: 's-no-epoch', text: 'wait for start', status: 'pending', createdAt: 1 }],
- { activeGenerationCreatedAt: null },
- );
- await clickMenuItem('com_ui_steer_cancel');
-
- expect(mockCancelMutateAsync).not.toHaveBeenCalled();
- expect(screen.getByText('wait for start')).toBeInTheDocument();
- });
-
- it('hands the words back to the composer once the cancel reclaims them', async () => {
- // Cancel is non-destructive: on a `reclaimed` outcome (removed:true) the
- // steer never reached the run, so its words return to the composer (the
- // gated restore refuses on its own when the composer is occupied).
- mockCancelMutateAsync.mockResolvedValue({ removed: true });
- renderSteers([{ steerId: 's-ack', text: 'second thoughts', status: 'pending', createdAt: 1 }]);
- await clickMenuItem('com_ui_steer_cancel');
- await act(async () => {});
- expect(mockRestoreToComposer).toHaveBeenCalledWith('second thoughts', undefined, {}, CONVO_ID);
- });
-
- it('queues the words when cancel reclaims but the composer refuses the restore', async () => {
- // Reclaimed (removed:true) yet the composer moved on, so the gated restore
- // refuses. The chip is already gone — queue the words like Edit rather than
- // drop them.
- mockCancelMutateAsync.mockResolvedValue({ removed: true });
- mockRestoreToComposer.mockReturnValue(false);
- const steer: PendingSteer = {
- steerId: 's-ack',
- text: 'keep me',
- status: 'pending',
- createdAt: 1,
- };
- renderSteers([steer]);
- await clickMenuItem('com_ui_steer_cancel');
- await act(async () => {});
- expect(mockQueueReclaimedSteer).toHaveBeenCalledWith(steer);
- expect(mockShowToast).toHaveBeenCalledWith(
- expect.objectContaining({ message: 'com_ui_steer_edit_queued' }),
- );
- });
-
- it('does not restore when the cancel loses its race (steer already reached the run)', async () => {
- // removed:false → the steer will still inject; restoring would put the same
- // words in the composer alongside the copy in the response.
- mockCancelMutateAsync.mockResolvedValue({ removed: false });
- renderSteers([{ steerId: 's-ack', text: 'too late', status: 'pending', createdAt: 1 }]);
- await clickMenuItem('com_ui_steer_cancel');
- await act(async () => {});
- expect(mockRestoreToComposer).not.toHaveBeenCalled();
- // Receiptless v1 cannot distinguish an injected steer from a terminal
- // conversion race, so keep the original metadata until an event proves
- // which path won.
- expect(mockCancelMutateAsync).toHaveBeenCalled();
- expect(screen.getByText('too late')).toBeInTheDocument();
- });
-
- it('does not restore when the cancel POST fails', async () => {
- // The POST failed, so the server may still inject it and the bubble is
- // restored — restoring to the composer too would duplicate the words.
- mockCancelMutateAsync.mockRejectedValue(new Error('network'));
- renderSteers([{ steerId: 's-ack', text: 'unknown fate', status: 'pending', createdAt: 1 }]);
- await clickMenuItem('com_ui_steer_cancel');
- await act(async () => {});
- expect(mockRestoreToComposer).not.toHaveBeenCalled();
- });
-
- it('restores the bubble when the cancel POST fails', async () => {
- mockCancelMutateAsync.mockRejectedValue(new Error('network'));
- renderSteers([{ steerId: 's-err', text: 'network flake', status: 'pending', createdAt: 1 }]);
- await clickMenuItem('com_ui_steer_cancel');
- // Optimistic remove, then the reject restores it.
- await act(async () => {});
- expect(screen.getByText('network flake')).toBeInTheDocument();
- });
-
- it('keeps the terminal recovery copy when an in-flight cancel POST fails', async () => {
- let rejectCancel: ((reason?: unknown) => void) | undefined;
- mockCancelMutateAsync.mockReturnValue(
- new Promise((_resolve, reject) => {
- rejectCancel = reject;
- }),
- );
- const steer = {
- steerId: 's-settled',
- clientSteerId: 'local-settled',
- text: 'already queued',
- status: 'pending' as const,
- createdAt: 1,
- };
- renderSteers([steer]);
- await clickMenuItem('com_ui_steer_cancel');
-
- act(() => {
- convertSteersForTest(CONVO_ID, [steer]);
- });
- expect(observedQueueForTest).toEqual([
- expect.objectContaining({
- id: steer.steerId,
- recoverySteerId: steer.steerId,
- recoveryClientSteerId: steer.clientSteerId,
- }),
- ]);
-
- await act(async () => {
- rejectCancel?.(new Error('network'));
- await Promise.resolve();
- });
- expect(screen.queryByText('already queued')).toBeNull();
- expect(observedQueueForTest).toHaveLength(1);
- expect(mockRestoreToComposer).not.toHaveBeenCalled();
- expect(mockQueueReclaimedSteer).not.toHaveBeenCalled();
- });
-
- it('keeps the terminal recovery copy when cancel reports an applied race', async () => {
- let resolveCancel: ((value: { removed: boolean }) => void) | undefined;
- mockCancelMutateAsync.mockReturnValue(
- new Promise((resolve) => {
- resolveCancel = resolve;
- }),
- );
- const steer = {
- steerId: 's-terminal-race',
- clientSteerId: 'local-terminal-race',
- text: 'terminal recovery wins',
- status: 'pending' as const,
- createdAt: 1,
- };
- renderSteers([steer]);
- await clickMenuItem('com_ui_steer_cancel');
-
- act(() => {
- convertSteersForTest(CONVO_ID, [steer]);
- });
- expect(observedQueueForTest).toHaveLength(1);
-
- await act(async () => {
- resolveCancel?.({ removed: false });
- await Promise.resolve();
- });
-
- expect(screen.queryByText(steer.text)).toBeNull();
- expect(observedQueueForTest).toEqual([
- expect.objectContaining({
- id: steer.steerId,
- recoverySteerId: steer.steerId,
- recoveryClientSteerId: steer.clientSteerId,
- }),
- ]);
- expect(mockRestoreToComposer).not.toHaveBeenCalled();
- expect(mockQueueReclaimedSteer).not.toHaveBeenCalled();
- });
-
- it('reclaims a pending steer before queueing it for after the response', async () => {
- const steer: PendingSteer = {
- steerId: 's-ack',
- text: 'do this after',
- status: 'pending',
- createdAt: 1,
- };
- renderSteers([steer]);
- await clickMenuItem('com_ui_convert_to_queue');
-
- // Reclaim first: the server would otherwise still inject the steer, and the
- // queued copy would say the same words a second time.
- expect(mockCancelMutateAsync).toHaveBeenCalledWith({
- conversationId: CONVO_ID,
- steerId: 's-ack',
- generationCreatedAt: 41,
- });
- // Routed through the shared conversion, which preserves the steer's id and
- // createdAt so it drains ahead of a follow-up queued after it.
- expect(mockQueueReclaimedSteer).toHaveBeenCalledWith(steer);
- });
-
- it('hands the whole steer to the conversion so attachments and context survive', async () => {
- const steer: PendingSteer = {
- steerId: 's-ack',
- text: 'see notes',
- status: 'pending',
- createdAt: 1,
- files: [{ file_id: 'f1', filename: 'notes.pdf', type: 'application/pdf' }],
- quotes: ['quoted line'],
- manualSkills: ['skill-1'],
- };
- renderSteers([steer]);
- await clickMenuItem('com_ui_convert_to_queue');
-
- expect(mockQueueReclaimedSteer).toHaveBeenCalledWith(steer);
- });
-
- it('reclaims a pending steer before editing it back into the composer', async () => {
- const files = [{ file_id: 'f1', filename: 'notes.pdf', type: 'application/pdf' }];
- renderSteers([
- {
- steerId: 's-ack',
- text: 'reword this',
- status: 'pending',
- createdAt: 1,
- files,
- quotes: ['quoted line'],
- },
- ]);
- await clickMenuItem('com_ui_edit_message');
-
- // The origin conversation rides along so a restore cannot land in whatever
- // chat the user navigated to while the reclaim was in flight.
- expect(mockRestoreToComposer).toHaveBeenCalledWith(
- 'reword this',
- files,
- { quotes: ['quoted line'] },
- CONVO_ID,
- );
- expect(mockRemoveSteer).toHaveBeenCalledWith('s-ack');
- });
-
- it('queues a reclaimed steer instead of overwriting a composer that moved on', async () => {
- // The reclaim is a round-trip: the user can type a new draft (or navigate)
- // before it resolves. The words are already off the server, so neither the
- // steer nor the newer draft is the one to throw away.
- mockRestoreToComposer.mockReturnValue(false);
- const steer: PendingSteer = {
- steerId: 's-ack',
- text: 'reword this',
- status: 'pending',
- createdAt: 1,
- };
- renderSteers([steer]);
- await clickMenuItem('com_ui_edit_message');
-
- expect(mockQueueReclaimedSteer).toHaveBeenCalledWith(steer);
- expect(mockRemoveSteer).not.toHaveBeenCalled();
- expect(mockShowToast).toHaveBeenCalledWith(
- expect.objectContaining({ message: 'com_ui_steer_edit_queued' }),
- );
- });
-
- it('removes a competing terminal recovery copy before restoring a confirmed reclaim', async () => {
- let resolveCancel: ((value: { removed: boolean }) => void) | undefined;
- mockCancelMutateAsync.mockReturnValue(
- new Promise((resolve) => {
- resolveCancel = resolve;
- }),
- );
- const steer = {
- steerId: 's-ack',
- clientSteerId: 'local-ack',
- text: 'already queued',
- status: 'pending' as const,
- createdAt: 1,
- };
- renderSteers([steer]);
- await clickMenuItem('com_ui_edit_message');
-
- act(() => {
- convertSteersForTest(CONVO_ID, [steer]);
- });
- expect(observedQueueForTest).toHaveLength(1);
-
- await act(async () => {
- resolveCancel?.({ removed: true });
- await Promise.resolve();
- });
-
- expect(observedQueueForTest).toEqual([]);
- expect(mockRestoreToComposer).toHaveBeenCalledWith(steer.text, undefined, {}, CONVO_ID);
- expect(mockQueueReclaimedSteer).not.toHaveBeenCalled();
- });
-
- it('never re-homes a steer the server already applied', async () => {
- // `removed: false` means the cancel lost its race to the injection
- // boundary: the words are in the run, so queueing them would send twice.
- mockCancelMutateAsync.mockResolvedValue({ removed: false });
- renderSteers([{ steerId: 's-ack', text: 'too late', status: 'pending', createdAt: 1 }]);
- await clickMenuItem('com_ui_convert_to_queue');
-
- expect(mockShowToast).toHaveBeenCalledWith(
- expect.objectContaining({ message: 'com_ui_steer_already_applied' }),
- );
- expect(mockQueueReclaimedSteer).not.toHaveBeenCalled();
- });
-
- it('never re-homes a steer whose cancel failed', async () => {
- // The POST failed, so the server may still inject it — its fate is unknown,
- // so the bubble stays and the text must not also land in the composer.
- mockCancelMutateAsync.mockRejectedValue(new Error('network'));
- renderSteers([{ steerId: 's-ack', text: 'unknown fate', status: 'pending', createdAt: 1 }]);
- await clickMenuItem('com_ui_edit_message');
-
- expect(mockShowToast).toHaveBeenCalledWith(
- expect.objectContaining({ message: 'com_ui_steer_cancel_failed', status: 'error' }),
- );
- expect(mockRestoreToComposer).not.toHaveBeenCalled();
- expect(mockQueueReclaimedSteer).not.toHaveBeenCalled();
- // The menu actions leave the chip alone until the outcome is known.
- expect(screen.getByText('unknown fate')).toBeInTheDocument();
- });
-
- it('offers the mode toggle as the action the user would switch to', async () => {
- renderSteers([{ steerId: 's-ack', text: 'waiting', status: 'pending', createdAt: 1 }], {
- defaultAction: 'steer',
- });
- await clickMenuItem('com_ui_turn_on_queueing');
- expect(mockSetDefaultAction).toHaveBeenCalledWith('queue');
- });
-
- it('renders images through the composer thumbnail path, not the full-size message image', () => {
- renderSteers([
- {
- steerId: 's1',
- text: 'see attached',
- status: 'pending',
- createdAt: 1,
- files: [
- { file_id: 'f2', filename: 'shot.png', type: 'image/png', filepath: '/images/shot.png' },
- ],
- },
- ]);
- // The message `Image` reserves height from the file's dimensions, so it
- // cannot be clipped down to a thumbnail; ImagePreview is fixed-size.
- expect(screen.getByTestId('steer-image')).toHaveAttribute('data-url', '/images/shot.png');
- });
-
- it('prefers the local preview url for an image that is still uploading', () => {
- renderSteers([
- {
- steerId: 's1',
- text: 'see attached',
- status: 'pending',
- createdAt: 1,
- files: [
- {
- file_id: 'f2',
- filename: 'shot.png',
- type: 'image/png',
- preview: 'blob:local-preview',
- filepath: '/images/shot.png',
- },
- ],
- },
- ]);
- expect(screen.getByTestId('steer-image')).toHaveAttribute('data-url', 'blob:local-preview');
- });
-
- it('keeps non-image attachments previewable while the steer waits', () => {
- renderSteers([
- {
- steerId: 's1',
- text: 'see attached',
- status: 'pending',
- createdAt: 1,
- files: [{ file_id: 'f1', filename: 'notes.pdf', type: 'application/pdf' }],
- },
- ]);
- expect(screen.getByTestId('steer-file')).toHaveTextContent('notes.pdf');
- expect(screen.queryByTestId('steer-file-preview')).toBeNull();
-
- fireEvent.click(screen.getByTestId('steer-file'));
- expect(screen.getByTestId('steer-file-preview')).toHaveTextContent('notes.pdf');
- });
-
- it.each(['application/pdf', 'image/png'])(
- 'hydrates %s preview metadata after the steer',
- (type) => {
- const steer: PendingSteer = {
- steerId: 's1',
- text: 'see attached',
- status: 'pending',
- createdAt: 1,
- files: [{ file_id: 'f1', filename: 'notes.pdf', type }],
- };
- const rendered = renderSteers([steer]);
-
- mockFileMap = { f1: { llmDeliveryPath: 'text' } };
- rendered.rerender(steersElement([steer]));
-
- fireEvent.click(screen.getByTestId('steer-file'));
- expect(screen.getByTestId('steer-file-preview')).toHaveAttribute(
- 'data-delivery-path',
- 'text',
- );
- },
- );
-
- it('renders markdown the same way the applied part will, so text does not reflow on apply', () => {
- renderSteers([{ steerId: 's1', text: '**bold** steer', status: 'pending', createdAt: 1 }], {
- enableUserMsgMarkdown: true,
- });
- expect(screen.getByTestId('steer-markdown')).toHaveTextContent('**bold** steer');
- });
-
- it('disables code execution: the bubble has no message/part for Run Code to target', () => {
- renderSteers([{ steerId: 's1', text: '```js\nrun()\n```', status: 'pending', createdAt: 1 }], {
- enableUserMsgMarkdown: true,
- });
- // This component renders outside MessageContext, so an executable code
- // block would fire the tool mutation with no messageId/conversationId.
- expect(screen.getByTestId('steer-markdown')).toHaveAttribute('data-code-execution', 'false');
- });
-
- it('keeps the newest steer in view when the capped stack overflows', () => {
- // jsdom does no layout, so scrollHeight is 0 unless stubbed — without it
- // the assertion would pass vacuously against a scrollTop of 0.
- const scrollHeight = jest
- .spyOn(HTMLElement.prototype, 'scrollHeight', 'get')
- .mockReturnValue(600);
- try {
- const { rerender } = renderSteers([
- { steerId: 's1', text: 'first', status: 'pending', createdAt: 1 },
- ]);
- // A newly submitted steer appends BELOW the existing ones, so a stack
- // left scrolled to the top would hide it and its cancel control.
- rerender(
- <RecoilRoot
- initializeState={({ set }) => {
- set(store.pendingSteersByConvoId(CONVO_ID), [
- { steerId: 's1', text: 'first', status: 'pending', createdAt: 1 },
- { steerId: 's2', text: 'just submitted', status: 'pending', createdAt: 2 },
- ]);
- }}
- >
- <InFlightSteers
- conversationId={CONVO_ID}
- steering={steeringStub()}
- onRestoreToComposer={mockRestoreToComposer}
- />
- </RecoilRoot>,
- );
- expect(screen.getByTestId('in-flight-steers').scrollTop).toBe(600);
- } finally {
- scrollHeight.mockRestore();
- }
- });
-
- it('caps the stack so a long steer cannot push the composer off-screen', () => {
- renderSteers([{ steerId: 's1', text: 'x'.repeat(4000), status: 'pending', createdAt: 1 }]);
- // A steer runs to 16k chars, and a run takes up to 10 of them.
- const stack = screen.getByTestId('in-flight-steers');
- expect(stack.className).toContain('max-h-[35vh]');
- expect(stack.className).toContain('overflow-y-auto');
- });
-
- it('renders raw text when user-message markdown is off', () => {
- renderSteers([{ steerId: 's1', text: '**bold** steer', status: 'pending', createdAt: 1 }], {
- enableUserMsgMarkdown: false,
- });
- expect(screen.queryByTestId('steer-markdown')).toBeNull();
- expect(screen.getByText('**bold** steer')).toBeInTheDocument();
- });
-
- it('hugs the composer edge instead of a narrower cap of its own', () => {
- renderSteers([{ steerId: 's1', text: 'flush right', status: 'pending', createdAt: 1 }]);
- const stack = screen.getByTestId('in-flight-steers');
- // `inset-x-0` inherits the composer's width, so the stack ends where the
- // composer ends at every desktop width. A cap of its own (the old
- // `max-w-3xl`) drifts inboard the moment the composer is wider —
- // `xl:max-w-4xl`, or maximized chat space.
- expect(stack.className).toContain('inset-x-0');
- expect(stack.className).toContain('items-end');
- expect(stack.className).not.toMatch(/\bmax-w-/);
- });
-
- it('floats the stack over the thread instead of displacing it', () => {
- // Anchored above the composer and pulled out of flow so the messages keep
- // their full height and slide behind it when the user scrolls up.
- renderSteers([{ steerId: 's1', text: 'scroll behind me', status: 'pending', createdAt: 1 }]);
- const stack = screen.getByTestId('in-flight-steers');
- expect(stack.className).toContain('absolute');
- expect(stack.className).toContain('bottom-full');
- // Wheeling over the gaps must reach the messages behind; bubbles opt back in.
- expect(stack.className).toContain('pointer-events-none');
- expect(screen.getByTestId('in-flight-steer').className).toContain('pointer-events-auto');
- });
-
- it('offers show more for a long steer and expands it in place', () => {
- // jsdom does no layout, so stub scrollHeight above the collapse cap (128px)
- // to make the content read as overflowing.
- const scrollHeight = jest
- .spyOn(HTMLElement.prototype, 'scrollHeight', 'get')
- .mockReturnValue(500);
- try {
- renderSteers([
- { steerId: 's1', text: 'paragraph\n\n'.repeat(20), status: 'pending', createdAt: 1 },
- ]);
- const toggle = screen.getByRole('button', { name: 'com_ui_show_more' });
- expect(toggle).toHaveAttribute('aria-expanded', 'false');
- expect(toggle.querySelector('[data-icon="chevron-down"]')).not.toBeNull();
- fireEvent.click(toggle);
- const collapse = screen.getByRole('button', { name: 'com_ui_show_less' });
- expect(collapse).toHaveAttribute('aria-expanded', 'true');
- expect(collapse.querySelector('[data-icon="chevron-up"]')).not.toBeNull();
- } finally {
- scrollHeight.mockRestore();
- }
- });
-
- it('does not offer a toggle for a steer that fits the preview', () => {
- // Left unstubbed, jsdom scrollHeight is 0, i.e. never overflows.
- renderSteers([{ steerId: 's1', text: 'thank you', status: 'pending', createdAt: 1 }]);
- expect(screen.queryByRole('button', { name: 'com_ui_show_more' })).toBeNull();
- expect(screen.queryByRole('button', { name: 'com_ui_show_less' })).toBeNull();
- });
-
- it('sticks the options menu so it stays reachable while scrolling long content', () => {
- renderSteers([{ steerId: 's1', text: 'x'.repeat(4000), status: 'pending', createdAt: 1 }]);
- expect(screen.getByTestId('steer-controls').className).toContain('sticky');
- });
-
- it('publishes its height for the messages to reserve, and clears it on unmount', () => {
- // The overlay no longer takes layout space, so it hands its measured height
- // to `steerOverlayHeightFamily`; `MessagesView` reserves an equal band of
- // bottom padding so the newest message rests clear of it.
- const jotaiStore = getDefaultStore();
- const offsetHeight = jest
- .spyOn(HTMLElement.prototype, 'offsetHeight', 'get')
- .mockReturnValue(96);
- try {
- const { unmount } = renderSteers([
- { steerId: 's1', text: 'reserve for me', status: 'pending', createdAt: 1 },
- ]);
- expect(jotaiStore.get(steerOverlayHeightFamily(CONVO_ID))).toBe(96);
- unmount();
- expect(jotaiStore.get(steerOverlayHeightFamily(CONVO_ID))).toBe(0);
- } finally {
- offsetHeight.mockRestore();
- }
- });
-});
-
-/**
- * The bubble's "Interrupt now" escalation is ONE atomic server op: `preempt`
- * flips on the existing queued item, so its FIFO position, id, and timestamp
- * survive and no reclaim window exists to race. `armed: false` is the honest
- * answer for every "too late" interleaving (drained, cancelled, run ended or
- * replaced) and for a deployment that cannot seal mid-stream.
- */
-describe('InFlightSteers — interrupt-now escalation', () => {
- beforeEach(() => {
- jest.clearAllMocks();
- mockArmMutateAsync.mockReset();
- mockCancelMutateAsync.mockResolvedValue({ removed: true });
- mockArmMutateAsync.mockResolvedValue({ armed: true, generationProtocolVersion: 2 });
- mockRestoreToComposer.mockReturnValue(true);
- act(() => {
- getDefaultStore().set(escalatingSteerFamily(CONVO_ID), false);
- });
- });
-
- it("arms the interrupt in place, keeping the steer's id and position", async () => {
- renderSteers([{ steerId: 's1', text: 'hold on', status: 'pending', createdAt: 1 }]);
- const armButton = screen.getByTestId('steer-escalate-now');
- act(() => armButton.focus());
- await act(async () => {
- fireEvent.click(armButton);
- });
-
- expect(mockArmMutateAsync).toHaveBeenCalledWith({
- conversationId: CONVO_ID,
- steerId: 's1',
- generationCreatedAt: 41,
- });
- /** No cancel, no resubmission: the durable item never left the queue. */
- expect(mockCancelMutateAsync).not.toHaveBeenCalled();
- expect(mockRetrySteer).not.toHaveBeenCalled();
- expect(screen.getByText('hold on')).toBeInTheDocument();
-
- /** The chip relabelled in place: an interrupting steer offers no further
- * escalation, so its arrow control is gone. */
- expect(screen.queryByTestId('steer-escalate-now')).toBeNull();
- expect(document.activeElement).toBe(screen.getByLabelText('com_ui_more_options'));
- expect(screen.getByRole('status')).toHaveTextContent('com_ui_steer_in_flight_preempt');
- // Preempting steers use ZapOff; non-preempt uses Zap.
- expect(
- screen.getByTestId('in-flight-steer').querySelector('[data-icon="zap-off"]'),
- ).not.toBeNull();
- });
-
- it('flips the receipt to interrupting on the click, confirming its check only on the ACK', async () => {
- let resolveArm: (value: unknown) => void = () => {};
- mockArmMutateAsync.mockReturnValue(
- new Promise((resolve) => {
- resolveArm = resolve;
- }),
- );
- renderSteers([{ steerId: 's1', text: 'hold on', status: 'pending', createdAt: 1 }]);
- expect(screen.getByTestId('steer-receipt')).toHaveAttribute('data-receipt-state', 'delivered');
-
- fireEvent.click(screen.getByTestId('steer-escalate-now'));
- // The silent round trip is what reads as broken: the label and pulse react
- // on the click, while the check waits for the confirmed durable arm.
- const receipt = screen.getByTestId('steer-receipt');
- expect(receipt).toHaveAttribute('data-receipt-state', 'interrupting');
- expect(receipt.querySelector('svg')).toBeNull();
-
- await act(async () => {
- resolveArm({ armed: true, generationProtocolVersion: 2, preemptRevision: 1 });
- });
- expect(receipt).toHaveAttribute('data-receipt-state', 'interrupting');
- expect(receipt.querySelector('svg')).not.toBeNull();
- });
-
- it('returns the receipt to delivered when the arm loses its race', async () => {
- mockArmMutateAsync.mockResolvedValue({ armed: false, generationProtocolVersion: 2 });
- renderSteers([{ steerId: 's1', text: 'hold on', status: 'pending', createdAt: 1 }]);
-
- await act(async () => {
- fireEvent.click(screen.getByTestId('steer-escalate-now'));
- });
- expect(screen.getByTestId('steer-receipt')).toHaveAttribute('data-receipt-state', 'delivered');
- });
-
- it('names each escalation control with the message it will interrupt for', () => {
- renderSteers([
- { steerId: 's1', text: 'correct the city', status: 'pending', createdAt: 1 },
- { steerId: 's2', text: 'use metric units', status: 'pending', createdAt: 2 },
- ]);
-
- expect(
- screen.getByRole('button', {
- name: 'com_ui_interrupt_steer_now: correct the city',
- }),
- ).toBeInTheDocument();
- expect(
- screen.getByRole('button', {
- name: 'com_ui_interrupt_steer_now: use metric units',
- }),
- ).toBeInTheDocument();
- });
-
- it('bounds and normalizes the message suffix in an escalation control name', () => {
- renderSteers([
- {
- steerId: 's-long-label',
- text: ` one two\n${'x'.repeat(100)} `,
- status: 'pending',
- createdAt: 1,
- },
- ]);
-
- expect(screen.getByTestId('steer-escalate-now')).toHaveAccessibleName(
- `com_ui_interrupt_steer_now: one two ${'x'.repeat(71)}…`,
- );
- });
-
- it('fences escalation to the generation recorded on the steer', async () => {
- renderSteers(
- [
- {
- steerId: 's-epoch',
- text: 'old generation steer',
- status: 'pending',
- createdAt: 1,
- generationCreatedAt: 41,
- },
- ],
- { activeGenerationCreatedAt: 99 },
- );
- await act(async () => {
- fireEvent.click(screen.getByTestId('steer-escalate-now'));
- });
-
- expect(mockArmMutateAsync).toHaveBeenCalledWith({
- conversationId: CONVO_ID,
- steerId: 's-epoch',
- generationCreatedAt: 41,
- });
- });
-
- it('does not arm an interrupt before any generation epoch is known', async () => {
- renderSteers(
- [{ steerId: 's-no-epoch', text: 'wait for start', status: 'pending', createdAt: 1 }],
- { activeGenerationCreatedAt: null },
- );
- await act(async () => {
- fireEvent.click(screen.getByTestId('steer-escalate-now'));
- });
-
- expect(mockArmMutateAsync).not.toHaveBeenCalled();
- });
-
- it('does not offer escalation on a steer that is already interrupting', async () => {
- renderSteers([
- { steerId: 's1', text: 'already sealing', status: 'pending', createdAt: 1, preempt: true },
- ]);
- expect(screen.queryByTestId('steer-escalate-now')).toBeNull();
- fireEvent.click(screen.getByLabelText('com_ui_more_options'));
- expect(await screen.findByText('com_ui_steer_cancel')).toBeInTheDocument();
- });
-
- it('keeps the chip an ordinary steer when the deployment cannot seal', async () => {
- mockArmMutateAsync.mockResolvedValue({
- armed: false,
- code: 'PREEMPT_UNSUPPORTED',
- generationProtocolVersion: 2,
- });
- renderSteers([{ steerId: 's1', text: 'no seal here', status: 'pending', createdAt: 1 }]);
- await act(async () => {
- fireEvent.click(screen.getByTestId('steer-escalate-now'));
- });
-
- expect(mockShowToast).toHaveBeenCalledWith(
- expect.objectContaining({ message: 'com_ui_steer_preempt_unsupported' }),
- );
- /** Still an ordinary steer: escalation stays offered. */
- expect(screen.getByTestId('steer-escalate-now')).toBeEnabled();
- });
-
- it('stays neutral when the arm loses its race, whatever the reason', async () => {
- /** `armed: false` covers injected, cancelled, re-homed, and run-over
- * alike, so the toast must not claim one specific outcome. */
- mockArmMutateAsync.mockResolvedValue({ armed: false, generationProtocolVersion: 2 });
- renderSteers([{ steerId: 's1', text: 'too late', status: 'pending', createdAt: 1 }]);
- await act(async () => {
- fireEvent.click(screen.getByTestId('steer-escalate-now'));
- });
-
- expect(mockRetrySteer).not.toHaveBeenCalled();
- expect(mockShowToast).toHaveBeenCalledWith(
- expect.objectContaining({ message: 'com_ui_steer_arm_lost_race' }),
- );
- });
-
- it('retries an indeterminate arm and relabels after confirmation', async () => {
- mockArmMutateAsync
- .mockRejectedValueOnce(new Error('response lost'))
- .mockResolvedValueOnce({ armed: true, generationProtocolVersion: 2 });
- renderSteers([{ steerId: 's1', text: 'still queued', status: 'pending', createdAt: 1 }]);
- await act(async () => {
- fireEvent.click(screen.getByTestId('steer-escalate-now'));
- });
-
- expect(mockArmMutateAsync).toHaveBeenCalledTimes(2);
- expect(mockShowToast).not.toHaveBeenCalled();
- expect(screen.queryByTestId('steer-escalate-now')).toBeNull();
- });
-
- it.each([400, 403, 409])('does not retry a definitive HTTP %s rejection', async (status) => {
- mockArmMutateAsync.mockRejectedValue({
- response: { status, data: { code: 'RUN_PAUSED' } },
- });
- renderSteers([{ steerId: 's1', text: 'pause conflict', status: 'pending', createdAt: 1 }]);
-
- await act(async () => {
- fireEvent.click(screen.getByTestId('steer-escalate-now'));
- });
-
- expect(mockArmMutateAsync).toHaveBeenCalledTimes(1);
- expect(mockShowToast).toHaveBeenCalledWith({
- message: 'com_ui_steer_arm_lost_race',
- status: 'info',
- });
- });
-
- it('does not automatically retry an indeterminate arm on protocol v1', async () => {
- mockArmMutateAsync.mockRejectedValue(new Error('response lost'));
- renderSteers([{ steerId: 's1', text: 'legacy arm', status: 'pending', createdAt: 1 }], {
- activeGenerationProtocolVersion: 1,
- });
-
- await act(async () => {
- fireEvent.click(screen.getByTestId('steer-escalate-now'));
- });
-
- expect(mockArmMutateAsync).toHaveBeenCalledTimes(1);
- expect(mockShowToast).toHaveBeenCalledWith(
- expect.objectContaining({ message: 'com_ui_steer_arm_unconfirmed', status: 'warning' }),
- );
- });
-
- it('reports an indeterminate result after two transport failures', async () => {
- mockArmMutateAsync.mockRejectedValue(new Error('network'));
- renderSteers([{ steerId: 's1', text: 'status unknown', status: 'pending', createdAt: 1 }]);
- await act(async () => {
- fireEvent.click(screen.getByTestId('steer-escalate-now'));
- });
-
- expect(mockArmMutateAsync).toHaveBeenCalledTimes(2);
- expect(mockShowToast).toHaveBeenCalledWith(
- expect.objectContaining({ message: 'com_ui_steer_arm_unconfirmed', status: 'warning' }),
- );
- expect(screen.getByText('status unknown')).toBeInTheDocument();
- });
-
- it('keeps a rejected-then-missing retry indeterminate', async () => {
- mockArmMutateAsync
- .mockRejectedValueOnce(new Error('response lost after commit'))
- .mockResolvedValueOnce({ armed: false, generationProtocolVersion: 2 });
- renderSteers([{ steerId: 's1', text: 'possibly armed', status: 'pending', createdAt: 1 }]);
- await act(async () => {
- fireEvent.click(screen.getByTestId('steer-escalate-now'));
- });
-
- expect(mockArmMutateAsync).toHaveBeenCalledTimes(2);
- expect(mockShowToast).toHaveBeenCalledWith(
- expect.objectContaining({ message: 'com_ui_steer_arm_unconfirmed', status: 'warning' }),
- );
- expect(screen.getByText('possibly armed')).toBeInTheDocument();
- });
-
- it('locks every escalation control while an arm request is in flight', async () => {
- /** The chip-derived gate cannot see an arm until its response lands, so
- * the flag flips synchronously at click — otherwise two bubbles could
- * both arm on a slow connection, belying the disabled controls. */
- let resolveArm: (value: {
- armed: boolean;
- generationProtocolVersion: number;
- }) => void = () => {};
- mockArmMutateAsync.mockImplementationOnce(
- () =>
- new Promise((resolve) => {
- resolveArm = resolve;
- }),
- );
- renderSteers([
- { steerId: 's1', text: 'first', status: 'pending', createdAt: 1 },
- { steerId: 's2', text: 'second', status: 'pending', createdAt: 2 },
- ]);
- const buttons = screen.getAllByTestId('steer-escalate-now');
- fireEvent.click(buttons[0]);
-
- expect(buttons[1]).toBeDisabled();
- await act(async () => {
- fireEvent.click(buttons[1]);
- });
-
- await act(async () => {
- resolveArm({ armed: true, generationProtocolVersion: 2 });
- });
- expect(mockArmMutateAsync).toHaveBeenCalledTimes(1);
- expect(mockArmMutateAsync).toHaveBeenCalledWith({
- conversationId: CONVO_ID,
- steerId: 's1',
- generationCreatedAt: 41,
- });
- });
-
- it('warns and unlocks when arm confirmation never settles', async () => {
- jest.useFakeTimers();
- try {
- mockArmMutateAsync.mockImplementation(() => new Promise(() => undefined));
- renderSteers([
- { steerId: 's1', text: 'stalled arm', status: 'pending', createdAt: 1 },
- { steerId: 's2', text: 'still available later', status: 'pending', createdAt: 2 },
- ]);
- const buttons = screen.getAllByTestId('steer-escalate-now');
- fireEvent.click(buttons[0]);
- expect(buttons[1]).toBeDisabled();
-
- await act(async () => {
- jest.advanceTimersByTime(10_000);
- await Promise.resolve();
- });
-
- expect(mockShowToast).toHaveBeenCalledWith(
- expect.objectContaining({ message: 'com_ui_steer_arm_unconfirmed', status: 'warning' }),
- );
- expect(buttons[1]).not.toBeDisabled();
- expect(mockArmMutateAsync).toHaveBeenCalledTimes(1);
- } finally {
- jest.useRealTimers();
- }
- });
-
- it('disables escalation on every bubble while an interrupt is unresolved', async () => {
- renderSteers([
- { steerId: 's1', text: 'plain steer', status: 'pending', createdAt: 1 },
- { steerId: 's2', text: 'sealing now', status: 'pending', createdAt: 2, preempt: true },
- ]);
- const button = screen.getByTestId('steer-escalate-now');
- expect(button).toBeDisabled();
-
- await act(async () => {
- fireEvent.click(button);
- });
- expect(mockArmMutateAsync).not.toHaveBeenCalled();
- });
-});
-
-/**
- * Answer mode (`ask_user_question`) sets `duringRunActive` false while
- * `pausedOnApproval` stays false (it only detects approval-bearing tool
- * calls). The entry disables there as a UX gate; the server-side arm is the
- * correctness backstop for states the client cannot see.
- */
-describe('InFlightSteers — escalation while the run cannot accept a steer', () => {
- beforeEach(() => {
- jest.clearAllMocks();
- mockArmMutateAsync.mockResolvedValue({ armed: true, generationProtocolVersion: 2 });
- });
-
- it('disables escalation in answer mode', async () => {
- renderSteers([{ steerId: 's1', text: 'waiting', status: 'pending', createdAt: 1 }], {
- duringRunActive: false,
- });
- const button = screen.getByTestId('steer-escalate-now');
- expect(button).toBeDisabled();
-
- await act(async () => {
- fireEvent.click(button);
- });
- expect(mockArmMutateAsync).not.toHaveBeenCalled();
- });
-});
-
-/**
- * One-off message actions and sticky behavior changes must never read as the
- * same kind of choice: actions first (edit, cancel, queue), then a separated
- * "Preferences" section holding the two mode toggles. Escalation is not a
- * menu entry at all — it has its own always-visible arrow control.
- */
-describe('InFlightSteers — menu structure', () => {
- beforeEach(() => {
- jest.clearAllMocks();
- mockCancelMutateAsync.mockResolvedValue({ removed: true });
- });
-
- it('orders actions above a separated Preferences section, with no escalation entry', async () => {
- renderSteers([{ steerId: 's1', text: 'structured', status: 'pending', createdAt: 1 }]);
- fireEvent.click(screen.getByLabelText('com_ui_more_options'));
- await screen.findByText('com_ui_edit_message');
-
- const items = screen
- .getAllByRole('menuitem')
- .filter((item) => !item.getAttribute('aria-label')?.startsWith('com_ui_more_info:'))
- .map((item) => item.textContent);
- expect(items).toEqual([
- 'com_ui_edit_message',
- 'com_ui_steer_cancel',
- 'com_ui_convert_to_queue',
- 'com_ui_turn_on_queueing',
- 'com_ui_always_interrupt',
- ]);
- const preferences = screen.getByRole('group', { name: 'com_ui_preferences' });
- expect(preferences).toContainElement(
- screen.getByRole('menuitem', { name: 'com_ui_turn_on_queueing' }),
- );
- expect(preferences).toContainElement(
- screen.getByRole('menuitem', { name: 'com_ui_always_interrupt' }),
- );
- expect(screen.queryByRole('menuitem', { name: 'com_ui_interrupt_steer_now' })).toBeNull();
- });
-});
-
-describe('InFlightSteers delivery receipts', () => {
- beforeEach(() => {
- jest.clearAllMocks();
- });
-
- it('labels a sending steer with the muted in-progress state and no check', () => {
- renderSteers([{ steerId: 'local-1', text: 'still posting', status: 'sending', createdAt: 1 }]);
- const receipt = screen.getByTestId('steer-receipt');
- expect(receipt).toHaveAttribute('data-receipt-state', 'sending');
- expect(receipt).toHaveTextContent('com_ui_steer_sending');
- expect(receipt.querySelector('svg')).toBeNull();
- });
-
- it('shows the delivered check once the server durably queued the steer', () => {
- renderSteers([{ steerId: 's-ack', text: 'waiting', status: 'pending', createdAt: 1 }]);
- const receipt = screen.getByTestId('steer-receipt');
- expect(receipt).toHaveAttribute('data-receipt-state', 'delivered');
- expect(receipt.querySelector('svg')).not.toBeNull();
- expect(screen.getByLabelText('com_ui_steer_delivered_info')).toBeInTheDocument();
- });
-
- it('relabels to the interrupting state when the steer is armed to preempt', () => {
- renderSteers([
- { steerId: 's-armed', text: 'stop now', status: 'pending', createdAt: 1, preempt: true },
- ]);
- const receipt = screen.getByTestId('steer-receipt');
- expect(receipt).toHaveAttribute('data-receipt-state', 'interrupting');
- // A confirmed arm keeps its check alongside the pulsing dot.
- expect(receipt.querySelector('svg')).not.toBeNull();
- expect(screen.getByLabelText('com_ui_steer_interrupting_info')).toBeInTheDocument();
- });
-
- it('shows interrupting without a check while the preempting POST is unacknowledged', () => {
- renderSteers([
- { steerId: 'local-2', text: 'stop', status: 'sending', createdAt: 1, preempt: true },
- ]);
- const receipt = screen.getByTestId('steer-receipt');
- expect(receipt).toHaveAttribute('data-receipt-state', 'interrupting');
- // The label and pulse react instantly; the check waits for the 202.
- expect(receipt.querySelector('svg')).toBeNull();
- });
-
- it('honors an SSE-delivered preempt confirmation while the arm response is still pending', async () => {
- mockArmMutateAsync.mockReturnValue(new Promise(() => {}));
- renderSteers([{ steerId: 's1', text: 'hold on', status: 'pending', createdAt: 1 }]);
- fireEvent.click(screen.getByTestId('steer-escalate-now'));
- expect(screen.getByTestId('steer-receipt').querySelector('svg')).toBeNull();
-
- // steer_updated relabels the chip before the arm HTTP response returns:
- // that IS durable confirmation, and the check must not wait out the
- // round-trip timeout.
- await act(async () => {
- setSteersForTest((prev) =>
- prev.map((steer) => ({ ...steer, preempt: true, preemptRevision: 1 })),
- );
- });
- const receipt = screen.getByTestId('steer-receipt');
- expect(receipt).toHaveAttribute('data-receipt-state', 'interrupting');
- expect(receipt.querySelector('svg')).not.toBeNull();
- });
-
- it('announces receipt transitions through the polite live region', async () => {
- renderSteers([{ steerId: 's1', text: 'hold on', status: 'sending', createdAt: 1 }]);
- // Mount state is not replayed: the region starts empty.
- expect(screen.getByRole('status')).toHaveTextContent('');
-
- await act(async () => {
- setSteersForTest((prev) => prev.map((steer) => ({ ...steer, status: 'pending' as const })));
- });
- expect(screen.getByRole('status')).toHaveTextContent('com_ui_steer_delivered');
- });
-});
diff --git a/client/src/components/Chat/Input/__tests__/MCPSelect.spec.tsx b/client/src/components/Chat/Input/__tests__/MCPSelect.spec.tsx
deleted file mode 100644
index 115aad71cc..0000000000
--- a/client/src/components/Chat/Input/__tests__/MCPSelect.spec.tsx
+++ /dev/null
@@ -1,180 +0,0 @@
-import React from 'react';
-import userEvent from '@testing-library/user-event';
-import { render, screen, within } from '@testing-library/react';
-import MCPSelect from '../MCPSelect';
-
-const mockToggleServerSelection = jest.fn();
-
-const defaultMcpServerManager = {
- localize: (key: string) => key,
- isPinned: true,
- mcpValues: [] as string[],
- placeholderText: 'MCP Servers',
- selectableServers: [
- { serverName: 'server-a', config: { title: 'Server A' } },
- { serverName: 'server-b', config: { title: 'Server B' } },
- ],
- availableMCPServers: [{ serverName: 'server-a' }, { serverName: 'server-b' }],
- connectionStatus: {},
- isInitializing: () => false,
- getConfigDialogProps: () => null,
- toggleServerSelection: mockToggleServerSelection,
- getServerStatusIconProps: () => null,
-};
-
-let mockCanUseMcp = true;
-let mockMcpServerManager = { ...defaultMcpServerManager };
-
-const mockMCPRefresh = jest.fn();
-
-jest.mock('~/hooks/MCP/useMCPRefresh', () => ({
- useMCPRefresh: (options: { enabled: boolean; tools?: boolean }) => mockMCPRefresh(options),
-}));
-
-jest.mock('~/Providers', () => ({
- useBadgeRowContext: () => ({
- conversationId: 'test-conv',
- storageContextKey: undefined,
- mcpServerManager: mockMcpServerManager,
- }),
-}));
-
-jest.mock('~/hooks', () => ({
- useLocalize: () => (key: string) => key,
- useHasAccess: () => mockCanUseMcp,
-}));
-
-jest.mock('@librechat/client', () => {
- // eslint-disable-next-line @typescript-eslint/no-require-imports
- const R = require('react');
- return {
- /** The real recipe, so the geometry assertions below cover shipped classes. */
- composerControlClasses: jest.requireActual('@librechat/client').composerControlClasses,
- TooltipAnchor: ({
- children,
- render,
- }: {
- children: React.ReactNode;
- render: React.ReactElement;
- }) => R.cloneElement(render, {}, ...(Array.isArray(children) ? children : [children])),
- MCPIcon: ({ className }: { className?: string }) => R.createElement('span', { className }),
- Spinner: ({ className }: { className?: string }) => R.createElement('span', { className }),
- };
-});
-
-jest.mock('~/components/MCP/MCPConfigDialog', () => ({
- __esModule: true,
- default: () => null,
-}));
-
-describe('MCPSelect', () => {
- beforeEach(() => {
- jest.clearAllMocks();
- mockCanUseMcp = true;
- mockMcpServerManager = { ...defaultMcpServerManager };
- });
-
- it('renders the menu button', () => {
- render(<MCPSelect />);
- expect(mockMCPRefresh).toHaveBeenLastCalledWith({ enabled: false });
- expect(screen.getByRole('button', { name: /MCP Servers/i })).toHaveClass(
- 'h-theme-control',
- 'min-w-theme-control',
- 'rounded-theme-control-round',
- 'gap-theme-compact',
- );
- });
-
- it('opens menu on button click and shows server items', async () => {
- const user = userEvent.setup();
- render(<MCPSelect />);
-
- await user.click(screen.getByRole('button', { name: /MCP Servers/i }));
-
- expect(mockMCPRefresh).toHaveBeenLastCalledWith({ enabled: true });
- const menu = screen.getByRole('menu', { name: /com_ui_mcp_servers/i });
- expect(menu).toBeVisible();
- expect(within(menu).getByRole('menuitemcheckbox', { name: /Server A/i })).toBeInTheDocument();
- expect(within(menu).getByRole('menuitemcheckbox', { name: /Server B/i })).toBeInTheDocument();
- });
-
- it('closes menu on Escape', async () => {
- const user = userEvent.setup();
- render(<MCPSelect />);
-
- await user.click(screen.getByRole('button', { name: /MCP Servers/i }));
- expect(screen.getByRole('menu', { name: /com_ui_mcp_servers/i })).toBeVisible();
-
- await user.keyboard('{Escape}');
- expect(screen.getByRole('button', { name: /MCP Servers/i })).toHaveAttribute(
- 'aria-expanded',
- 'false',
- );
- });
-
- it('keeps menu open after toggling a server item', async () => {
- const user = userEvent.setup();
- render(<MCPSelect />);
-
- await user.click(screen.getByRole('button', { name: /MCP Servers/i }));
- await user.click(screen.getByRole('menuitemcheckbox', { name: /Server A/i }));
-
- expect(mockToggleServerSelection).toHaveBeenCalledWith('server-a');
- expect(screen.getByRole('menu', { name: /com_ui_mcp_servers/i })).toBeVisible();
- });
-
- it('arrow-key navigation wraps from last item to first', async () => {
- const user = userEvent.setup();
- render(<MCPSelect />);
-
- await user.click(screen.getByRole('button', { name: /MCP Servers/i }));
- const items = screen.getAllByRole('menuitemcheckbox');
- expect(items).toHaveLength(2);
-
- await user.keyboard('{ArrowDown}');
- await user.keyboard('{ArrowDown}');
- await user.keyboard('{ArrowDown}');
- expect(items[0]).toHaveFocus();
- });
-
- it('labels the badge from the servers the menu offers, not the raw selection', () => {
- mockMcpServerManager = {
- ...defaultMcpServerManager,
- mcpValues: ['server-a', 'hidden-server'],
- };
- render(<MCPSelect />);
-
- expect(screen.getByRole('button', { name: /Server A/i })).toBeInTheDocument();
- expect(screen.queryByText('com_ui_x_selected')).not.toBeInTheDocument();
- });
-
- it('shows no label when every selected server is hidden from the menu', () => {
- mockMcpServerManager = {
- ...defaultMcpServerManager,
- mcpValues: ['hidden-server'],
- };
- render(<MCPSelect />);
-
- expect(screen.getByRole('button', { name: /MCP Servers/i })).toBeInTheDocument();
- expect(screen.queryByText('hidden-server')).not.toBeInTheDocument();
- });
-
- it('renders nothing when user lacks MCP access', () => {
- mockCanUseMcp = false;
- const { container } = render(<MCPSelect />);
- expect(container.firstChild).toBeNull();
- expect(screen.queryByRole('button')).not.toBeInTheDocument();
- });
-
- it('renders nothing when selectableServers is empty', () => {
- mockMcpServerManager = { ...defaultMcpServerManager, selectableServers: [] };
- const { container } = render(<MCPSelect />);
- expect(container.firstChild).toBeNull();
- });
-
- it('renders nothing when not pinned and no servers selected', () => {
- mockMcpServerManager = { ...defaultMcpServerManager, isPinned: false, mcpValues: [] };
- const { container } = render(<MCPSelect />);
- expect(container.firstChild).toBeNull();
- });
-});
diff --git a/client/src/components/Chat/Input/__tests__/MCPSubMenu.spec.tsx b/client/src/components/Chat/Input/__tests__/MCPSubMenu.spec.tsx
deleted file mode 100644
index 6a2c1bb10d..0000000000
--- a/client/src/components/Chat/Input/__tests__/MCPSubMenu.spec.tsx
+++ /dev/null
@@ -1,166 +0,0 @@
-import React from 'react';
-import * as Ariakit from '@ariakit/react';
-import userEvent from '@testing-library/user-event';
-import { render, screen, within, waitFor } from '@testing-library/react';
-import MCPSubMenu from '../MCPSubMenu';
-
-const mockToggleServerSelection = jest.fn();
-const mockSetIsPinned = jest.fn();
-const mockMCPRefresh = jest.fn();
-
-jest.mock('~/hooks/MCP/useMCPRefresh', () => ({
- useMCPRefresh: (options: { enabled: boolean }) => mockMCPRefresh(options),
-}));
-
-const defaultMcpServerManager = {
- isPinned: true,
- mcpValues: [] as string[],
- setIsPinned: mockSetIsPinned,
- placeholderText: 'MCP Servers',
- selectableServers: [
- { serverName: 'server-a', config: { title: 'Server A' } },
- { serverName: 'server-b', config: { title: 'Server B', description: 'Second server' } },
- ],
- connectionStatus: {},
- isInitializing: () => false,
- getConfigDialogProps: () => null,
- toggleServerSelection: mockToggleServerSelection,
- getServerStatusIconProps: () => null,
-};
-
-let mockMcpServerManager = { ...defaultMcpServerManager };
-
-jest.mock('~/Providers', () => ({
- useBadgeRowContext: () => ({
- storageContextKey: undefined,
- mcpServerManager: mockMcpServerManager,
- }),
-}));
-
-jest.mock('~/hooks', () => ({
- useLocalize: () => (key: string) => key,
- useHasAccess: () => true,
-}));
-
-jest.mock('@librechat/client', () => {
- // eslint-disable-next-line @typescript-eslint/no-require-imports
- const R = require('react');
- return {
- MCPIcon: ({ className }: { className?: string }) => R.createElement('span', { className }),
- PinIcon: ({ unpin }: { unpin?: boolean }) =>
- R.createElement('span', { 'data-testid': unpin ? 'unpin-icon' : 'pin-icon' }),
- Spinner: ({ className }: { className?: string }) => R.createElement('span', { className }),
- };
-});
-
-jest.mock('~/components/MCP/MCPConfigDialog', () => ({
- __esModule: true,
- default: () => null,
-}));
-
-function ParentMenu({ children }: { children: React.ReactNode }) {
- return (
- <Ariakit.MenuProvider>
- {/* eslint-disable-next-line i18next/no-literal-string */}
- <Ariakit.MenuButton>Parent</Ariakit.MenuButton>
- <Ariakit.Menu open={true}>{children}</Ariakit.Menu>
- </Ariakit.MenuProvider>
- );
-}
-
-function renderSubMenu(props: React.ComponentProps<typeof MCPSubMenu> = {}) {
- return render(
- <ParentMenu>
- <MCPSubMenu {...props} />
- </ParentMenu>,
- );
-}
-
-describe('MCPSubMenu', () => {
- beforeEach(() => {
- jest.clearAllMocks();
- mockMcpServerManager = { ...defaultMcpServerManager };
- });
-
- it('renders nothing when selectableServers is empty', () => {
- mockMcpServerManager = { ...defaultMcpServerManager, selectableServers: [] };
- renderSubMenu();
- expect(screen.queryByText('MCP Servers')).not.toBeInTheDocument();
- });
-
- it('renders the submenu trigger with default placeholder', () => {
- renderSubMenu();
- expect(mockMCPRefresh).toHaveBeenLastCalledWith({ enabled: false });
- expect(screen.getByText('MCP Servers')).toBeInTheDocument();
- });
-
- it('renders custom placeholder when provided', () => {
- renderSubMenu({ placeholder: 'Custom Label' });
- expect(screen.getByText('Custom Label')).toBeInTheDocument();
- expect(screen.queryByText('MCP Servers')).not.toBeInTheDocument();
- });
-
- it('refreshes the unpinned submenu while open and stops on close', async () => {
- const user = userEvent.setup();
- mockMcpServerManager = { ...defaultMcpServerManager, isPinned: false };
- renderSubMenu();
-
- await user.click(screen.getByText('MCP Servers'));
-
- expect(mockMCPRefresh).toHaveBeenLastCalledWith({ enabled: true });
- const menu = screen.getByRole('menu', { name: /com_ui_mcp_servers/i });
- expect(menu).toBeVisible();
- expect(within(menu).getByRole('menuitemcheckbox', { name: /Server A/i })).toBeInTheDocument();
- expect(within(menu).getByRole('menuitemcheckbox', { name: /Server B/i })).toBeInTheDocument();
- await user.keyboard('{Escape}');
- await waitFor(() => expect(mockMCPRefresh).toHaveBeenLastCalledWith({ enabled: false }));
- });
-
- it('keeps menu open after toggling a server item', async () => {
- const user = userEvent.setup();
- renderSubMenu();
-
- await user.click(screen.getByText('MCP Servers'));
- await user.click(screen.getByRole('menuitemcheckbox', { name: /Server A/i }));
-
- expect(mockToggleServerSelection).toHaveBeenCalledWith('server-a');
- expect(screen.getByRole('menu', { name: /com_ui_mcp_servers/i })).toBeVisible();
- });
-
- it('calls setIsPinned with toggled value when pin button is clicked', async () => {
- const user = userEvent.setup();
- mockMcpServerManager = { ...defaultMcpServerManager, isPinned: false };
- renderSubMenu();
-
- await user.click(screen.getByRole('button', { name: /com_ui_pin/i }));
-
- expect(mockSetIsPinned).toHaveBeenCalledWith(true);
- });
-
- it('arrow-key navigation wraps from last item to first', async () => {
- const user = userEvent.setup();
- renderSubMenu();
-
- await user.click(screen.getByText('MCP Servers'));
- const items = screen.getAllByRole('menuitemcheckbox');
- expect(items).toHaveLength(2);
-
- await user.click(items[1]);
- expect(items[1]).toHaveFocus();
-
- await user.keyboard('{ArrowDown}');
- expect(items[0]).toHaveFocus();
- });
-
- it('pin button shows unpin label when pinned', () => {
- mockMcpServerManager = { ...defaultMcpServerManager, isPinned: true };
- renderSubMenu();
- expect(screen.getByRole('button', { name: /com_ui_unpin/i })).toBeInTheDocument();
- });
-
- it('pin button shows pin label when not pinned', () => {
- mockMcpServerManager = { ...defaultMcpServerManager, isPinned: false };
- renderSubMenu();
- expect(screen.getByRole('button', { name: /com_ui_pin/i })).toBeInTheDocument();
- });
-});
diff --git a/client/src/components/Chat/Input/__tests__/PendingManualSkillsChips.spec.tsx b/client/src/components/Chat/Input/__tests__/PendingManualSkillsChips.spec.tsx
deleted file mode 100644
index 36e0899780..0000000000
--- a/client/src/components/Chat/Input/__tests__/PendingManualSkillsChips.spec.tsx
+++ /dev/null
@@ -1,60 +0,0 @@
-import React from 'react';
-import userEvent from '@testing-library/user-event';
-import { RecoilRoot, MutableSnapshot } from 'recoil';
-import { render, screen } from '@testing-library/react';
-
-jest.mock('~/hooks', () => ({
- useLocalize: () => (key: string, params?: Record<string, unknown>) =>
- `${key}:${params?.[0] ?? ''}`,
-}));
-
-import PendingManualSkillsChips from '../PendingManualSkillsChips';
-import store from '~/store';
-
-const CONVO_ID = 'convo-1';
-
-const renderWithSkills = (initialSkills: string[]) => {
- const initializeState = (snapshot: MutableSnapshot) => {
- snapshot.set(store.pendingManualSkillsByConvoId(CONVO_ID), initialSkills);
- };
- return render(
- <RecoilRoot initializeState={initializeState}>
- <PendingManualSkillsChips conversationId={CONVO_ID} />
- </RecoilRoot>,
- );
-};
-
-describe('PendingManualSkillsChips', () => {
- it('renders nothing when no skills are queued', () => {
- const { container } = renderWithSkills([]);
- expect(container.firstChild).toBeNull();
- });
-
- it('renders one chip per queued skill', () => {
- const { container } = renderWithSkills(['brand-guidelines', 'pptx']);
- const items = screen.getAllByRole('listitem');
- expect(items).toHaveLength(2);
- expect(items[0]).toHaveTextContent('brand-guidelines');
- expect(items[1]).toHaveTextContent('pptx');
- expect(container.querySelector('svg')).toHaveClass('text-status-info');
- });
-
- it('removes the chip when its × button is clicked', async () => {
- const user = userEvent.setup();
- renderWithSkills(['brand-guidelines', 'pptx']);
- const removeBrand = screen.getByRole('button', {
- name: 'com_ui_remove_skill_var:brand-guidelines',
- });
- await user.click(removeBrand);
- const items = screen.getAllByRole('listitem');
- expect(items).toHaveLength(1);
- expect(items[0]).toHaveTextContent('pptx');
- });
-
- it('clears the list when every chip is dismissed', async () => {
- const user = userEvent.setup();
- const { container } = renderWithSkills(['a']);
- await user.click(screen.getByRole('button', { name: 'com_ui_remove_skill_var:a' }));
- expect(container.firstChild).toBeNull();
- });
-});
diff --git a/client/src/components/Chat/Input/__tests__/PendingQuoteChips.test.tsx b/client/src/components/Chat/Input/__tests__/PendingQuoteChips.test.tsx
deleted file mode 100644
index 6e863cf372..0000000000
--- a/client/src/components/Chat/Input/__tests__/PendingQuoteChips.test.tsx
+++ /dev/null
@@ -1,57 +0,0 @@
-import React from 'react';
-import { RecoilRoot } from 'recoil';
-import { render, screen, fireEvent } from '@testing-library/react';
-
-jest.mock('~/hooks', () => ({
- useLocalize: () => (key: string, params?: Record<string, unknown>) =>
- `${key}:${params?.[0] ?? ''}`,
-}));
-
-import store from '~/store';
-import PendingQuoteChips from '../PendingQuoteChips';
-
-const CONVO_ID = 'convo-1';
-
-const renderWithQuotes = (quotes: string[]) =>
- render(
- <RecoilRoot initializeState={({ set }) => set(store.pendingQuotesByConvoId(CONVO_ID), quotes)}>
- <PendingQuoteChips conversationId={CONVO_ID} />
- </RecoilRoot>,
- );
-
-describe('PendingQuoteChips', () => {
- it('renders nothing when there are no pending quotes', () => {
- const { container } = renderWithQuotes([]);
- expect(container.firstChild).toBeNull();
- });
-
- it('shows the excerpt text for a single selection', () => {
- renderWithQuotes(['alpha excerpt']);
- const chips = screen.getByTestId('pending-quote-chips');
- expect(chips).toHaveAttribute('data-quote-count', '1');
- expect(chips).toHaveTextContent('alpha excerpt');
- });
-
- it('collapses multiple selections into a single "{n} selections" chip', () => {
- renderWithQuotes(['alpha excerpt', 'beta excerpt']);
- const chips = screen.getByTestId('pending-quote-chips');
- expect(chips).toHaveAttribute('data-quote-count', '2');
- // Collapsed label (the localize mock renders "<key>:<count>").
- expect(chips).toHaveTextContent('com_ui_quote_selections:2');
- // The composer shows ONE chip, not a row of two (the per-excerpt list lives
- // in the hover popup, which only mounts on hover).
- expect(screen.getAllByRole('listitem')).toHaveLength(1);
- });
-
- it('removes the single selection when its × is clicked', () => {
- const { container } = renderWithQuotes(['only one']);
- fireEvent.click(screen.getByRole('button', { name: /com_ui_remove_quote/ }));
- expect(container.firstChild).toBeNull();
- });
-
- it('clears all selections from the collapsed chip', () => {
- const { container } = renderWithQuotes(['first', 'second']);
- fireEvent.click(screen.getByRole('button', { name: /com_ui_remove_all_quotes/ }));
- expect(container.firstChild).toBeNull();
- });
-});
diff --git a/client/src/components/Chat/Input/__tests__/PendingSteerChips.test.tsx b/client/src/components/Chat/Input/__tests__/PendingSteerChips.test.tsx
deleted file mode 100644
index e9749212a3..0000000000
--- a/client/src/components/Chat/Input/__tests__/PendingSteerChips.test.tsx
+++ /dev/null
@@ -1,870 +0,0 @@
-import React from 'react';
-import { getDefaultStore } from 'jotai';
-import userEvent from '@testing-library/user-event';
-import { RecoilRoot, useRecoilValue, useSetRecoilState } from 'recoil';
-import { render, screen, fireEvent, act, waitFor, within } from '@testing-library/react';
-import type { PendingSteer, QueuedMessage } from '~/store/families';
-import type { SteeringControls } from '~/hooks/Chat/useSteering';
-import { recoveryDispositionsFamily } from '~/components/Chat/Steering/recovery';
-import { escalatingSteerFamily, revealedQueuedTurnFamily } from '~/store/steer';
-import PendingSteerChips from '../PendingSteerChips';
-import store from '~/store';
-
-const mockRemoveQueued = jest.fn();
-const mockDismissRecovery = jest.fn();
-const mockDiscardQueued = jest.fn(async (_message: QueuedMessage) => true);
-const mockSendQueuedNow = jest.fn();
-const mockRetrySteer = jest.fn();
-const mockRestoreToComposer = jest.fn(() => true);
-const mockEditToComposer = jest.fn();
-const mockShowToast = jest.fn();
-
-// SteerMenu (rendered under PendingSteerChips) uses MorphIcon; map icon
-// identity so inverted Zap/Clock ternaries fail tests instead of going silent.
-jest.mock('@librechat/client', () => {
- const { createSteerMorphIconMock } = jest.requireActual('~/../test/mockMorphIcon');
- return {
- useToastContext: () => ({ showToast: mockShowToast }),
- TooltipAnchor: jest.requireActual('@librechat/client').TooltipAnchor,
- MorphIcon: createSteerMorphIconMock(),
- };
-});
-
-jest.mock('~/hooks', () => ({
- useLocalize: () => (key: string) => key,
-}));
-
-const CONVO_ID = 'convo-q';
-let updateQueueForTest:
- | ((updater: (current: QueuedMessage[]) => QueuedMessage[]) => void)
- | undefined;
-
-function QueueState() {
- const queue = useRecoilValue(store.queuedMessagesByConvoId(CONVO_ID));
- const setQueue = useSetRecoilState(store.queuedMessagesByConvoId(CONVO_ID));
- updateQueueForTest = (updater) => setQueue(updater);
- return <output data-testid="queue-state">{JSON.stringify(queue)}</output>;
-}
-
-function PreferenceState() {
- const defaultAction = useRecoilValue(store.duringRunDefaultAction);
- const interrupts = useRecoilValue(store.steerInterruptsByDefault);
- return (
- <>
- <output data-testid="default-action-state">{defaultAction}</output>
- <output data-testid="interrupts-state">{String(interrupts)}</output>
- </>
- );
-}
-
-const steeringStub = (overrides: Partial<SteeringControls> = {}) =>
- ({
- queueKey: CONVO_ID,
- defaultAction: 'steer',
- duringRunActive: false,
- canSendQueuedNow: true,
- canSteer: false,
- pausedOnApproval: false,
- removeQueued: mockRemoveQueued,
- discardQueued: mockDiscardQueued,
- dismissRecovery: mockDismissRecovery,
- sendQueuedNow: mockSendQueuedNow,
- retrySteer: mockRetrySteer,
- setDefaultAction: jest.fn(),
- ...overrides,
- }) as unknown as SteeringControls;
-
-function renderChips(
- queued: QueuedMessage[],
- options?: {
- steering?: Partial<SteeringControls>;
- steers?: PendingSteer[];
- interrupts?: boolean;
- },
-) {
- return render(
- <RecoilRoot
- initializeState={({ set }) => {
- set(store.queuedMessagesByConvoId(CONVO_ID), queued);
- set(store.duringRunDefaultAction, options?.steering?.defaultAction ?? 'steer');
- set(store.steerInterruptsByDefault, options?.interrupts ?? false);
- if (options?.steers != null) {
- set(store.pendingSteersByConvoId(CONVO_ID), options.steers);
- }
- }}
- >
- <PendingSteerChips
- conversationId={CONVO_ID}
- steering={steeringStub(options?.steering)}
- onEditToComposer={mockEditToComposer}
- onRestoreToComposer={mockRestoreToComposer}
- />
- <PreferenceState />
- <QueueState />
- </RecoilRoot>,
- );
-}
-
-describe('PendingSteerChips — ambiguous delivery retry', () => {
- beforeEach(() => {
- jest.clearAllMocks();
- });
-
- it('hides same-id Retry for a legacy ambiguous delivery', () => {
- renderChips([], {
- steers: [
- {
- steerId: 'legacy-uncertain',
- text: 'may already be queued',
- status: 'failed',
- deliveryUncertain: true,
- generationProtocolVersion: 1,
- createdAt: 1,
- },
- ],
- });
-
- expect(screen.queryByText('com_ui_steer_retry')).toBeNull();
- });
-
- it('offers same-id Retry only after protocol v2 was negotiated', () => {
- renderChips([], {
- steers: [
- {
- steerId: 'v2-uncertain',
- text: 'dedupe this retry',
- status: 'failed',
- deliveryUncertain: true,
- generationProtocolVersion: 2,
- createdAt: 1,
- },
- ],
- });
-
- fireEvent.click(screen.getByText('com_ui_steer_retry'));
- expect(mockRetrySteer).toHaveBeenCalledWith(
- 'v2-uncertain',
- 'dedupe this retry',
- undefined,
- { quotes: undefined, manualSkills: undefined },
- { preempt: false, createdAt: 1, generationProtocolVersion: 2 },
- );
- });
-
- it('uses semantic destructive roles for a failed steer', () => {
- renderChips([], {
- steers: [
- {
- steerId: 'failed-steer',
- text: 'failed message',
- status: 'failed',
- createdAt: 1,
- },
- ],
- });
-
- const row = screen.getByTestId('steer-message-row');
- expect(row).toHaveClass('border-border-destructive');
- expect(row.querySelector('svg')).toHaveClass('text-text-destructive');
- expect(screen.getByText('com_ui_steer_failed')).toHaveClass('text-text-destructive');
- });
-});
-
-describe('PendingSteerChips — queued primary availability', () => {
- beforeEach(() => {
- jest.clearAllMocks();
- });
-
- it('does not offer Send now while answer mode owns the submission slot', () => {
- renderChips([{ id: 'answer-queued', text: 'wait until the answer resumes', createdAt: 1 }], {
- steering: {
- duringRunActive: false,
- canSendQueuedNow: false,
- canSteer: false,
- pausedOnApproval: true,
- },
- });
-
- expect(screen.queryByText('com_ui_send_now')).toBeNull();
- expect(screen.getByTestId('queued-interrupt-now')).toBeDisabled();
- expect(mockSendQueuedNow).not.toHaveBeenCalled();
- });
-});
-
-describe('PendingSteerChips — terminal server state', () => {
- beforeEach(() => {
- jest.clearAllMocks();
- });
-
- it('shows a durable rejection as failed work', () => {
- renderChips([
- {
- id: 'rejected-turn',
- text: 'could not be admitted',
- createdAt: 1,
- server: { status: 'rejected', errorCode: 'ADMISSION_FAILED' },
- },
- ]);
-
- expect(screen.getByText('com_ui_queued_turn_failed')).toBeInTheDocument();
- });
-
- it('shows indeterminate admission as non-actionable reconciliation work', () => {
- renderChips([
- {
- id: 'indeterminate-turn',
- text: 'external result unknown',
- createdAt: 1,
- server: {
- id: 'server-indeterminate-1',
- status: 'indeterminate',
- errorCode: 'ADMISSION_INDETERMINATE',
- },
- },
- ]);
-
- expect(screen.getByText('com_ui_queued_turn_reconciliation_required')).toBeInTheDocument();
- expect(screen.getByLabelText('com_ui_remove_queued')).toBeDisabled();
- expect(screen.queryByText('com_ui_send_now')).toBeNull();
- });
-
- it('dismisses an expired ambiguous receipt without restoring or resending it', () => {
- renderChips([
- {
- id: 'uncertain-turn',
- text: 'delivery outcome unknown',
- createdAt: 1,
- server: {
- status: 'uncertain',
- uncertainSince: 1,
- reconciliationExpired: true,
- },
- },
- ]);
-
- expect(screen.getByText('com_ui_steer_delivery_unconfirmed')).toBeInTheDocument();
- fireEvent.click(screen.getByLabelText('com_ui_dismiss_unconfirmed_delivery'));
-
- expect(mockRemoveQueued).toHaveBeenCalledWith('uncertain-turn');
- expect(mockDiscardQueued).not.toHaveBeenCalled();
- expect(mockRestoreToComposer).not.toHaveBeenCalled();
- expect(mockSendQueuedNow).not.toHaveBeenCalled();
- });
-});
-
-describe('PendingSteerChips — queued trash', () => {
- beforeEach(() => {
- jest.clearAllMocks();
- window.localStorage.clear();
- });
-
- it('returns the words to the composer when removing a queued message', async () => {
- // The trash is non-destructive: it hands the text (and its carried context)
- // to the gated restore once removal succeeds, so the words are not gone forever.
- renderChips([
- {
- id: 'q1',
- text: 'later thought',
- createdAt: 1,
- quotes: ['a quote'],
- manualSkills: ['a-skill'],
- },
- ]);
- fireEvent.click(screen.getByLabelText('com_ui_remove_queued'));
-
- await waitFor(() => {
- expect(mockRestoreToComposer).toHaveBeenCalledWith(
- 'later thought',
- undefined,
- { quotes: ['a quote'], manualSkills: ['a-skill'] },
- CONVO_ID,
- );
- expect(mockRemoveQueued).toHaveBeenCalledWith('q1');
- });
- });
-
- it('still removes the message even when the composer refuses the restore', async () => {
- // Occupied composer / other chat: the gated restore returns false, but the
- // trash must reliably remove either way.
- mockRestoreToComposer.mockReturnValueOnce(false);
- renderChips([{ id: 'q2', text: 'drop me', createdAt: 1 }]);
- fireEvent.click(screen.getByLabelText('com_ui_remove_queued'));
-
- await waitFor(() => {
- expect(mockRestoreToComposer).toHaveBeenCalled();
- expect(mockRemoveQueued).toHaveBeenCalledWith('q2');
- });
- });
-
- it('discards a recovered source before restoring and removing its queued row', async () => {
- let confirmDiscard: ((discarded: boolean) => void) | undefined;
- mockDiscardQueued.mockImplementationOnce(
- () =>
- new Promise<boolean>((resolve) => {
- confirmDiscard = resolve;
- }),
- );
- const recovered = {
- id: 'q-recovered',
- text: 'recovered words',
- createdAt: 1,
- recoverySteerId: 'server-source',
- recoveryClientSteerId: 'client-source',
- };
- renderChips([recovered]);
-
- fireEvent.click(screen.getByLabelText('com_ui_remove_queued'));
- expect(mockDiscardQueued).toHaveBeenCalledWith(recovered);
- expect(mockRestoreToComposer).not.toHaveBeenCalled();
-
- await act(async () => {
- confirmDiscard?.(true);
- });
- expect(mockRestoreToComposer).toHaveBeenCalledWith(
- 'recovered words',
- undefined,
- { quotes: undefined, manualSkills: undefined },
- CONVO_ID,
- );
- expect(mockRemoveQueued).toHaveBeenCalledWith('q-recovered');
- });
-
- it('discards a dead server row before restoring and removing it', async () => {
- const dead = {
- id: 'q-dead',
- text: 'recover dead work',
- createdAt: 1,
- clientRequestId: 'client-dead',
- server: {
- id: 'server-dead',
- status: 'rejected' as const,
- errorCode: 'ADMISSION_FAILED',
- },
- };
- renderChips([dead]);
-
- fireEvent.click(screen.getByLabelText('com_ui_remove_queued'));
-
- await waitFor(() => expect(mockDiscardQueued).toHaveBeenCalledWith(dead));
- expect(mockRestoreToComposer).toHaveBeenCalledWith(
- 'recover dead work',
- undefined,
- { quotes: undefined, manualSkills: undefined },
- CONVO_ID,
- );
- expect(mockRemoveQueued).toHaveBeenCalledWith('q-dead');
- });
-
- it('offers Edit for a recovered row and leaves it untouched when discard is refused', async () => {
- const user = userEvent.setup();
- mockDiscardQueued.mockResolvedValueOnce(false);
- const recovered = {
- id: 'q-recovered',
- text: 'safe to edit only after discard',
- createdAt: 1,
- recoverySteerId: 'server-source',
- recoveryClientSteerId: 'client-source',
- };
- renderChips([recovered]);
-
- await user.click(screen.getByLabelText('com_ui_more_options'));
- await user.click(await screen.findByRole('menuitem', { name: 'com_ui_edit_message' }));
-
- await waitFor(() => expect(mockDiscardQueued).toHaveBeenCalledWith(recovered));
- expect(mockRestoreToComposer).not.toHaveBeenCalled();
- expect(mockEditToComposer).not.toHaveBeenCalled();
- expect(mockRemoveQueued).not.toHaveBeenCalled();
- expect(screen.getByText('safe to edit only after discard')).toBeInTheDocument();
- });
-
- it('uses the guarded composer restore only after recovered Edit confirms discard', async () => {
- const user = userEvent.setup();
- let confirmDiscard: ((discarded: boolean) => void) | undefined;
- mockDiscardQueued.mockImplementationOnce(
- () =>
- new Promise<boolean>((resolve) => {
- confirmDiscard = resolve;
- }),
- );
- const recovered = {
- id: 'q-recovered-edit',
- text: 'edit recovered words',
- createdAt: 1,
- recoverySteerId: 'server-source',
- recoveryClientSteerId: 'client-source',
- quotes: ['kept quote'],
- manualSkills: ['kept skill'],
- };
- renderChips([recovered]);
-
- await user.click(screen.getByLabelText('com_ui_more_options'));
- await user.click(await screen.findByRole('menuitem', { name: 'com_ui_edit_message' }));
- expect(mockEditToComposer).not.toHaveBeenCalled();
-
- await act(async () => {
- confirmDiscard?.(true);
- });
- expect(mockRestoreToComposer).toHaveBeenCalledWith(
- 'edit recovered words',
- undefined,
- { quotes: ['kept quote'], manualSkills: ['kept skill'] },
- CONVO_ID,
- );
- expect(mockEditToComposer).not.toHaveBeenCalled();
- expect(mockRemoveQueued).toHaveBeenCalledWith('q-recovered-edit');
- });
-
- it('keeps a safely discarded Edit queued when live composer state changes during cancel', async () => {
- const user = userEvent.setup();
- let confirmDiscard: (() => void) | undefined;
- const recovered = {
- id: 'q-recovered-race',
- text: 'preserve after async race',
- createdAt: 1,
- clientRequestId: 'recovery-attempt',
- recoverySteerId: 'server-source',
- recoveryClientSteerId: 'client-source',
- quotes: ['kept quote'],
- };
- mockDiscardQueued.mockImplementationOnce(
- () =>
- new Promise<boolean>((resolve) => {
- confirmDiscard = () => {
- updateQueueForTest?.((current) =>
- current.map((item) => {
- if (item.id !== recovered.id) {
- return item;
- }
- const {
- clientRequestId: _clientRequestId,
- recoverySteerId: _recoverySteerId,
- recoveryClientSteerId: _recoveryClientSteerId,
- ...ordinary
- } = item;
- return ordinary;
- }),
- );
- resolve(true);
- };
- }),
- );
- renderChips([recovered]);
-
- await user.click(screen.getByLabelText('com_ui_more_options'));
- await user.click(await screen.findByRole('menuitem', { name: 'com_ui_edit_message' }));
- expect(mockDiscardQueued).toHaveBeenCalledWith(recovered);
- expect(mockRestoreToComposer).not.toHaveBeenCalled();
-
- // The live guard can change while the durable cancel request is pending.
- mockRestoreToComposer.mockReturnValueOnce(false);
- await act(async () => {
- confirmDiscard?.();
- });
-
- expect(mockRestoreToComposer).toHaveBeenCalledWith(
- 'preserve after async race',
- undefined,
- { quotes: ['kept quote'], manualSkills: undefined },
- CONVO_ID,
- );
- expect(mockEditToComposer).not.toHaveBeenCalled();
- expect(mockRemoveQueued).not.toHaveBeenCalled();
- expect(screen.getByText('preserve after async race')).toBeInTheDocument();
- expect(JSON.parse(screen.getByTestId('queue-state').textContent ?? 'null')).toEqual([
- {
- id: 'q-recovered-race',
- text: 'preserve after async race',
- createdAt: 1,
- quotes: ['kept quote'],
- },
- ]);
- expect(mockShowToast).toHaveBeenCalledWith({
- message: 'com_ui_steer_edit_queued',
- status: 'info',
- });
- });
-});
-
-/**
- * The queued row's escalation: interrupt & steer this one message now, at the
- * next safe token boundary, instead of waiting for the run to end. Offered
- * only while a live run can accept a steer; disabled while another interrupt
- * is unresolved or the run is paused on approval, since a second preempt
- * would race the same seal (or draw the server's 409).
- */
-describe('PendingSteerChips — queued interrupt-now', () => {
- const liveRun = { duringRunActive: true, canSteer: true };
- const queuedMessage: QueuedMessage = { id: 'q1', text: 'urgent one', createdAt: 1 };
-
- beforeEach(() => {
- jest.clearAllMocks();
- window.localStorage.clear();
- });
-
- it('escalates a queued message as an interrupt steer', () => {
- renderChips([queuedMessage], { steering: liveRun });
- fireEvent.click(screen.getByTestId('queued-interrupt-now'));
-
- expect(mockSendQueuedNow).toHaveBeenCalledWith(expect.objectContaining({ id: 'q1' }), {
- preempt: true,
- });
- });
-
- it('offers no escalation outside a steerable run', () => {
- renderChips([queuedMessage]);
- expect(screen.queryByTestId('queued-interrupt-now')).toBeNull();
- });
-
- it('disables escalation while another interrupt is unresolved', () => {
- renderChips([queuedMessage], {
- steering: liveRun,
- steers: [{ steerId: 'p1', text: 'sealing', status: 'pending', createdAt: 1, preempt: true }],
- });
- const button = screen.getByTestId('queued-interrupt-now');
- expect(button).toBeDisabled();
-
- fireEvent.click(button);
- expect(mockSendQueuedNow).not.toHaveBeenCalled();
- });
-
- it('disables escalation while a bubble arm request is in flight', () => {
- const jotai = getDefaultStore();
- act(() => {
- jotai.set(escalatingSteerFamily(CONVO_ID), true);
- });
- try {
- renderChips([queuedMessage], { steering: liveRun });
- expect(screen.getByTestId('queued-interrupt-now')).toBeDisabled();
- } finally {
- act(() => {
- jotai.set(escalatingSteerFamily(CONVO_ID), false);
- });
- }
- });
-
- it('stays visible but disabled while the run is paused on approval', () => {
- /** The real hook invariant: `canSteer = hasRealConvoId && !pausedOnApproval`,
- * so a paused run always reads `canSteer: false`. The control must remain
- * discoverable-but-disabled there, not vanish with the primary. */
- renderChips([queuedMessage], {
- steering: { duringRunActive: true, canSteer: false, pausedOnApproval: true },
- });
- const button = screen.getByTestId('queued-interrupt-now');
- expect(button).toBeDisabled();
-
- fireEvent.click(button);
- expect(mockSendQueuedNow).not.toHaveBeenCalled();
- });
-
- it('stays visible but disabled while ask-user answer mode owns the composer', () => {
- renderChips([queuedMessage], {
- steering: { duringRunActive: false, canSteer: false, pausedOnApproval: true },
- });
- const button = screen.getByTestId('queued-interrupt-now');
- expect(button).toBeDisabled();
-
- fireEvent.click(button);
- expect(mockSendQueuedNow).not.toHaveBeenCalled();
- });
-
- it('makes the hovered row the only advertised shortcut target', () => {
- renderChips([queuedMessage, { id: 'q2', text: 'urgent two', createdAt: 2 }], {
- steering: liveRun,
- });
- const [first, second] = screen.getAllByTestId('queued-interrupt-now');
-
- expect(first).not.toHaveAttribute('aria-keyshortcuts');
- expect(second).not.toHaveAttribute('aria-keyshortcuts');
-
- fireEvent.pointerEnter(first);
- expect(first).toHaveAttribute('data-escalate-steer-active', 'true');
- expect(first).toHaveAttribute('aria-keyshortcuts');
- expect(second).not.toHaveAttribute('data-escalate-steer-active');
- expect(second).not.toHaveAttribute('aria-keyshortcuts');
-
- fireEvent.pointerEnter(second);
- expect(first).not.toHaveAttribute('data-escalate-steer-active');
- expect(first).not.toHaveAttribute('aria-keyshortcuts');
- expect(second).toHaveAttribute('data-escalate-steer-active', 'true');
- expect(second).toHaveAttribute('aria-keyshortcuts');
- });
-
- it('names each queued escalation control with its target message', () => {
- renderChips([queuedMessage, { id: 'q2', text: 'urgent two', createdAt: 2 }], {
- steering: liveRun,
- });
-
- expect(
- screen.getByRole('button', { name: 'com_ui_interrupt_steer_now: urgent one' }),
- ).toBeInTheDocument();
- expect(
- screen.getByRole('button', { name: 'com_ui_interrupt_steer_now: urgent two' }),
- ).toBeInTheDocument();
- });
-
- it.each(['pointer', 'keyboard'] as const)(
- 'keeps preference help visibly open after %s activation',
- async (activation) => {
- const user = userEvent.setup();
- renderChips([queuedMessage], { steering: liveRun });
- const menuButton = screen.getByLabelText('com_ui_more_options');
- await user.click(menuButton);
-
- const preference = await screen.findByRole('menuitem', {
- name: 'com_ui_turn_on_queueing',
- });
- expect(preference).toHaveAccessibleDescription('com_nav_info_during_run_action');
- const help = screen.getByRole('menuitem', {
- name: 'com_ui_more_info: com_ui_turn_on_queueing',
- });
-
- if (activation === 'pointer') {
- await user.click(help);
- } else {
- act(() => help.focus());
- expect(document.activeElement).toBe(help);
- await user.keyboard('{Enter}');
- }
-
- const menu = screen.getByRole('menu');
- const description = screen.getByText('com_nav_info_during_run_action');
- expect(menuButton).toHaveAttribute('aria-expanded', 'true');
- expect(menu).toBeVisible();
- expect(help).toHaveAttribute('aria-expanded', 'true');
- expect(description).not.toHaveClass('sr-only');
- expect(description).toBeVisible();
- },
- );
-
- it.each([false, true])(
- 'makes steering the default when enabling always-interrupt from queue mode (latent=%s)',
- async (interrupts) => {
- renderChips([queuedMessage], {
- steering: { ...liveRun, defaultAction: 'queue' },
- interrupts,
- });
- fireEvent.click(screen.getByLabelText('com_ui_more_options'));
- const preference = await screen.findByRole('menuitem', { name: 'com_ui_always_interrupt' });
- expect(preference).toHaveAccessibleDescription('com_ui_steer_interrupts_enable_info');
- fireEvent.click(preference);
-
- expect(screen.getByTestId('default-action-state')).toHaveTextContent('steer');
- expect(screen.getByTestId('interrupts-state')).toHaveTextContent('true');
-
- fireEvent.click(screen.getByLabelText('com_ui_more_options'));
- expect(await screen.findByText('com_ui_wait_for_tool_steps')).toBeInTheDocument();
- },
- );
-});
-
-describe('PendingSteerChips — queued hint', () => {
- beforeEach(() => {
- jest.clearAllMocks();
- });
-
- const queuedItem = { id: 'q1', text: 'follow up later', createdAt: 1 };
- const hintName = 'com_ui_steer_queued_info';
-
- it('explains when a queued message will send as a hover hint on its clock icon', async () => {
- renderChips([queuedItem], { steering: { duringRunActive: true } });
- const clock = screen.getByRole('img', { name: hintName });
- fireEvent.mouseEnter(clock);
- /** Ariakit only counts a pointer as moving when consecutive events differ
- * in screen coordinates (its NODE_ENV=test shortcut is off under CI's
- * NODE_ENV), and it opens the tooltip on a timer after that. */
- fireEvent.mouseMove(clock, { screenX: 10, screenY: 10 });
- fireEvent.mouseMove(clock, { screenX: 20, screenY: 20 });
- const tooltip = await screen.findByRole('tooltip', {}, { timeout: 3000 });
- expect(tooltip).toHaveTextContent(hintName);
- });
-
- it('reaches the same hint from the keyboard: the clock is a tab stop and opens on focus', async () => {
- const user = userEvent.setup();
- renderChips([queuedItem], { steering: { duringRunActive: true } });
- const clock = screen.getByRole('img', { name: hintName });
- await user.tab();
- expect(clock).toHaveFocus();
- const tooltip = await screen.findByRole('tooltip');
- expect(tooltip).toHaveTextContent(hintName);
- });
-
- it('renders no always-visible caption, so the hint costs no composer height at rest', () => {
- renderChips([queuedItem], { steering: { duringRunActive: true } });
- expect(screen.queryByText(hintName)).toBeNull();
- expect(screen.queryByRole('tooltip')).toBeNull();
- });
-
- it('keeps the hint inside each queued row as its icon, never as a stray child of the list', () => {
- renderChips([queuedItem, { id: 'q2', text: 'and another', createdAt: 2 }], {
- steering: { duringRunActive: true },
- });
- const rows = screen.getAllByTestId('queued-message-row');
- const clocks = screen.getAllByRole('img', { name: hintName });
- expect(clocks).toHaveLength(2);
- rows.forEach((row, index) => expect(row).toContainElement(clocks[index]));
- });
-
- it('omits the hint once the run is over, when rows drain on their own terms', () => {
- renderChips([queuedItem], { steering: { duringRunActive: false } });
- expect(screen.queryByRole('img', { name: hintName })).toBeNull();
- });
-});
-
-describe('PendingSteerChips — revealed queued turn', () => {
- const revealedFamily = () => revealedQueuedTurnFamily(CONVO_ID);
-
- beforeEach(() => {
- jest.clearAllMocks();
- act(() => {
- getDefaultStore().set(revealedFamily(), null);
- });
- });
-
- afterEach(() => {
- act(() => {
- getDefaultStore().set(revealedFamily(), null);
- });
- });
-
- const serverRow = (clientRequestId: string): QueuedMessage => ({
- id: `q-${clientRequestId}`,
- text: `queued ${clientRequestId}`,
- createdAt: 1,
- clientRequestId,
- server: { id: `server-${clientRequestId}`, status: 'queued', revision: 1 },
- });
-
- it('keeps an ordinary queue row when no matching pending message is visible', () => {
- getDefaultStore().set(revealedFamily(), {
- clientRequestId: 'req-1',
- parentMessageId: 'response-1',
- text: 'queued req-1',
- revealedAt: '2026-09-14T00:00:00.000Z',
- });
- renderChips([serverRow('req-1'), serverRow('req-2')], {
- steering: { duringRunActive: true, canSendQueuedNow: false, canSteer: false },
- });
-
- const rows = screen.getAllByTestId('queued-message-row');
- expect(rows).toHaveLength(2);
- expect(rows[0]).not.toHaveTextContent('com_ui_queued_turn_starting');
- expect(
- within(rows[0]).getByRole('button', { name: 'com_ui_more_options' }),
- ).toBeInTheDocument();
- expect(within(rows[0]).getByRole('button', { name: /com_ui_remove/ })).toBeInTheDocument();
- expect(rows[1]).not.toHaveTextContent('com_ui_queued_turn_starting');
- expect(
- within(rows[1]).getByRole('button', { name: 'com_ui_more_options' }),
- ).toBeInTheDocument();
- });
- it.each([true, false])(
- 'attempts claimed cancellation and respects acceptance=%s',
- async (accepted) => {
- const message = serverRow('req-1');
- message.server!.status = 'claimed';
- getDefaultStore().set(revealedFamily(), {
- clientRequestId: 'req-1',
- parentMessageId: 'response-1',
- text: message.text,
- revealedAt: new Date().toISOString(),
- });
- mockDiscardQueued.mockResolvedValueOnce(accepted);
- renderChips([message], { steering: { duringRunActive: true, canSendQueuedNow: false } });
- const remove = screen.getByRole('button', { name: /com_ui_remove/ });
- expect(remove).toBeEnabled();
- await userEvent.click(remove);
- await waitFor(() => expect(mockDiscardQueued).toHaveBeenCalledWith(message));
- expect(mockRemoveQueued).toHaveBeenCalledTimes(accepted ? 1 : 0);
- expect(mockRestoreToComposer).toHaveBeenCalledTimes(accepted ? 1 : 0);
- expect(mockSendQueuedNow).not.toHaveBeenCalled();
- },
- );
-});
-
-describe('held steer recovery controls', () => {
- beforeEach(() => {
- jest.clearAllMocks();
- getDefaultStore().set(recoveryDispositionsFamily(CONVO_ID), { source: 'blocked' });
- });
- afterEach(() => {
- act(() => {
- getDefaultStore().set(recoveryDispositionsFamily(CONVO_ID), {});
- });
- });
-
- const item: QueuedMessage = {
- id: 'held',
- text: 'original words',
- createdAt: 1,
- recoverySteerId: 'source',
- quotes: ['original excerpt'],
- files: [{ file_id: 'file' }],
- };
-
- it('shows a held state and no automatic or manual send shortcut', () => {
- renderChips([item]);
- expect(screen.getByText('com_ui_steer_recovery_held')).toBeTruthy();
- expect(screen.queryByText('com_ui_send_now')).toBeNull();
- expect(screen.queryByText('com_ui_steer')).toBeNull();
- });
-
- it('copies the original context for review without cancelling or sending it', async () => {
- mockRestoreToComposer.mockReturnValueOnce(true);
- const user = userEvent.setup();
- renderChips([item]);
- await user.click(screen.getByRole('button', { name: 'com_ui_more_options' }));
- await user.click(screen.getByText('com_ui_steer_copy_to_composer'));
- expect(mockRestoreToComposer).toHaveBeenCalledWith(
- item.text,
- item.files,
- {
- quotes: item.quotes,
- manualSkills: undefined,
- },
- CONVO_ID,
- );
- expect(mockShowToast).toHaveBeenCalledWith({
- message: 'com_ui_steer_recovery_review',
- status: 'info',
- });
- expect(mockSendQueuedNow).not.toHaveBeenCalled();
- expect(mockDiscardQueued).not.toHaveBeenCalled();
- expect(mockRemoveQueued).not.toHaveBeenCalled();
- });
-
- it('leaves the recovery untouched and explains a refused copy to the occupied composer', async () => {
- mockRestoreToComposer.mockReturnValueOnce(false);
- const user = userEvent.setup();
- renderChips([item]);
- await user.click(screen.getByRole('button', { name: 'com_ui_more_options' }));
- await user.click(screen.getByText('com_ui_steer_copy_to_composer'));
- expect(mockRestoreToComposer).toHaveBeenCalledWith(
- item.text,
- item.files,
- { quotes: item.quotes, manualSkills: undefined },
- CONVO_ID,
- );
- expect(mockShowToast).toHaveBeenCalledWith({
- message: 'com_ui_steer_recovery_copy_refused',
- status: 'error',
- });
- expect(mockShowToast).not.toHaveBeenCalledWith({
- message: 'com_ui_steer_recovery_review',
- status: 'info',
- });
- expect(screen.getByText('com_ui_steer_recovery_held')).toBeTruthy();
- expect(mockDismissRecovery).not.toHaveBeenCalled();
- expect(mockSendQueuedNow).not.toHaveBeenCalled();
- expect(mockRemoveQueued).not.toHaveBeenCalled();
- });
-
- it('labels dismissal as tab-local and does not claim to cancel server work', async () => {
- const user = userEvent.setup();
- renderChips([item]);
- await user.click(screen.getByRole('button', { name: 'com_ui_more_options' }));
- await user.click(screen.getByText('com_ui_steer_dismiss_recovery'));
- expect(mockDismissRecovery).toHaveBeenCalledWith(item);
- expect(mockDiscardQueued).not.toHaveBeenCalled();
- expect(mockSendQueuedNow).not.toHaveBeenCalled();
- });
-});
diff --git a/client/src/components/Chat/Input/__tests__/Reasoning.spec.tsx b/client/src/components/Chat/Input/__tests__/Reasoning.spec.tsx
new file mode 100644
index 0000000000..3031f2f87f
--- /dev/null
+++ b/client/src/components/Chat/Input/__tests__/Reasoning.spec.tsx
@@ -0,0 +1,802 @@
+import { RecoilRoot } from 'recoil';
+import { Provider as JotaiProvider, createStore } from 'jotai';
+import { Constants, ReasoningEffort } from 'librechat-data-provider';
+import { act, fireEvent, render, renderHook, screen, waitFor } from '@testing-library/react';
+import type {
+ SettingDefinition,
+ TConversation,
+ TReasoningOverride,
+ TSubmission,
+} from 'librechat-data-provider';
+import type { ReactNode } from 'react';
+import { getReasoningStateKey, pendingReasoningOverrideFamily } from '../Composer/state';
+import { ReasoningControl, useComposerReasoning } from '../Reasoning';
+import store from '~/store';
+
+type MockEndpointConfig = {
+ type?: string;
+ customParams?: {
+ defaultParamsEndpoint?: string;
+ paramDefinitions?: SettingDefinition[];
+ };
+};
+let mockEndpointsConfig: Record<string, MockEndpointConfig> | undefined = {};
+
+jest.mock('~/data-provider', () => ({
+ useGetAgentByIdQuery: () => ({ data: undefined }),
+ useGetEndpointsQuery: () => ({ data: mockEndpointsConfig }),
+}));
+
+jest.mock('~/Providers', () => ({
+ useAgentsMapContext: () => ({}),
+}));
+
+jest.mock('~/hooks', () => ({
+ useLocalize: () => (key: string) => key,
+}));
+
+beforeEach(() => {
+ mockEndpointsConfig = {};
+});
+
+const enumSetting: SettingDefinition = {
+ key: 'reasoning_effort',
+ label: 'com_endpoint_reasoning_effort',
+ labelCode: true,
+ description: 'com_endpoint_openai_reasoning_effort',
+ descriptionCode: true,
+ type: 'enum',
+ component: 'slider',
+ default: ReasoningEffort.unset,
+ options: [
+ ReasoningEffort.unset,
+ ReasoningEffort.minimal,
+ ReasoningEffort.low,
+ ReasoningEffort.medium,
+ ReasoningEffort.high,
+ ],
+ enumMappings: {
+ [ReasoningEffort.unset]: 'com_ui_auto',
+ [ReasoningEffort.minimal]: 'com_ui_minimal',
+ [ReasoningEffort.low]: 'com_ui_low',
+ [ReasoningEffort.medium]: 'com_ui_medium',
+ [ReasoningEffort.high]: 'com_ui_high',
+ },
+};
+
+const budgetSetting: SettingDefinition = {
+ key: 'thinkingBudget',
+ label: 'com_endpoint_thinking_budget',
+ labelCode: true,
+ description: 'com_endpoint_google_thinking_budget',
+ descriptionCode: true,
+ type: 'number',
+ component: 'input',
+ range: { min: -1, positiveMin: 128, max: 32768, step: 128 },
+};
+
+describe('ReasoningControl', () => {
+ it('renders a compact, localized disclosure for the next message', async () => {
+ render(
+ <ReasoningControl
+ index={0}
+ setting={enumSetting}
+ value={{ key: 'reasoning_effort', value: 'medium' } as TReasoningOverride}
+ onChange={jest.fn()}
+ />,
+ );
+
+ const trigger = screen.getByRole('button', {
+ name: 'com_ui_reasoning_for_next_message com_ui_medium',
+ });
+
+ fireEvent.click(trigger);
+ expect(
+ await screen.findByRole('dialog', { name: 'com_endpoint_reasoning_effort' }),
+ ).toBeVisible();
+ expect(screen.queryByText('com_endpoint_openai_reasoning_effort')).not.toBeInTheDocument();
+ });
+
+ it('stages the next vendor-native enum value from an accessible effort scale', async () => {
+ const onChange = jest.fn();
+ render(
+ <ReasoningControl
+ index={0}
+ setting={enumSetting}
+ value={{ key: 'reasoning_effort', value: 'medium' } as TReasoningOverride}
+ onChange={onChange}
+ />,
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: /com_ui_reasoning_for_next_message/ }));
+ const slider = screen.getByRole('slider', { name: 'com_endpoint_reasoning_effort' });
+ expect(slider).toHaveAttribute('aria-valuenow', '3');
+ expect(slider).toHaveAttribute('aria-valuetext', 'com_ui_medium');
+ slider.focus();
+ fireEvent.keyDown(slider, { key: 'ArrowRight' });
+
+ await waitFor(() =>
+ expect(onChange).toHaveBeenLastCalledWith({ key: 'reasoning_effort', value: 'high' }),
+ );
+ });
+
+ it('renders a modal dialog with an explicit close control', () => {
+ render(
+ <ReasoningControl
+ index={0}
+ setting={enumSetting}
+ value={{ key: 'reasoning_effort', value: 'medium' } as TReasoningOverride}
+ onChange={jest.fn()}
+ />,
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: /com_ui_reasoning_for_next_message/ }));
+ const dialog = screen.getByRole('dialog', { name: 'com_endpoint_reasoning_effort' });
+
+ expect(dialog).toBeVisible();
+ expect(screen.getByRole('button', { name: 'com_ui_close' })).toBeVisible();
+ });
+
+ it('normalizes numeric thinking budgets onto the same scale with exact input and auto', () => {
+ const onChange = jest.fn();
+ render(
+ <ReasoningControl
+ index={0}
+ setting={budgetSetting}
+ value={{ key: 'thinkingBudget', value: 4096 }}
+ onChange={onChange}
+ />,
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: /com_ui_reasoning_for_next_message/ }));
+ const slider = screen.getByRole('slider', { name: 'com_endpoint_thinking_budget' });
+ expect(slider).toHaveAttribute('aria-valuemin', '128');
+ expect(slider).toHaveAttribute('aria-valuemax', '32768');
+ expect(slider).toHaveAttribute('aria-valuenow', '4096');
+
+ slider.focus();
+ fireEvent.keyDown(slider, { key: 'ArrowRight' });
+ expect(onChange).toHaveBeenLastCalledWith({ key: 'thinkingBudget', value: 4224 });
+
+ const input = screen.getByRole('spinbutton', { name: 'com_endpoint_thinking_budget' });
+ fireEvent.change(input, { target: { value: '8192' } });
+ fireEvent.blur(input);
+ expect(onChange).toHaveBeenLastCalledWith({ key: 'thinkingBudget', value: 8192 });
+
+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_auto' }));
+ expect(onChange).toHaveBeenLastCalledWith({ key: 'thinkingBudget', value: -1 });
+ });
+
+ it('clamps an invalid positive budget to the model-specific floor', () => {
+ const onChange = jest.fn();
+ render(
+ <ReasoningControl
+ index={0}
+ setting={budgetSetting}
+ value={{ key: 'thinkingBudget', value: -1 }}
+ onChange={onChange}
+ />,
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: /com_ui_reasoning_for_next_message/ }));
+ const input = screen.getByRole('spinbutton', { name: 'com_endpoint_thinking_budget' });
+ fireEvent.change(input, { target: { value: '16' } });
+ fireEvent.blur(input);
+
+ expect(onChange).toHaveBeenLastCalledWith({ key: 'thinkingBudget', value: 128 });
+ });
+
+ it.each([undefined, -1, 4096])('does not stage an unchanged numeric budget (%s)', (value) => {
+ const onChange = jest.fn();
+ render(
+ <ReasoningControl
+ index={0}
+ setting={budgetSetting}
+ value={value == null ? undefined : { key: 'thinkingBudget', value }}
+ onChange={onChange}
+ />,
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: /com_ui_reasoning_for_next_message/ }));
+ const input = screen.getByRole('spinbutton', { name: 'com_endpoint_thinking_budget' });
+ fireEvent.focus(input);
+ fireEvent.blur(input);
+
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it.each([-1, 0])(
+ 'restores the supported minimum (%s) when the numeric field is cleared',
+ (min) => {
+ const onChange = jest.fn();
+ render(
+ <ReasoningControl
+ index={0}
+ setting={{ ...budgetSetting, range: { ...budgetSetting.range!, min } }}
+ value={{ key: 'thinkingBudget', value: 4096 }}
+ onChange={onChange}
+ />,
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: /com_ui_reasoning_for_next_message/ }));
+ const input = screen.getByRole('spinbutton', { name: 'com_endpoint_thinking_budget' });
+ fireEvent.change(input, { target: { value: '' } });
+ fireEvent.blur(input);
+
+ expect(onChange).toHaveBeenLastCalledWith({ key: 'thinkingBudget', value: min });
+ },
+ );
+});
+
+describe('useComposerReasoning', () => {
+ it('owns one-shot state in Jotai and clears it when the model changes', async () => {
+ const reasoningStore = createStore();
+ const conversation = {
+ conversationId: 'reasoning-conversation',
+ endpoint: 'openAI',
+ model: 'gpt-5',
+ reasoning_effort: ReasoningEffort.medium,
+ } as TConversation;
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <RecoilRoot>
+ <JotaiProvider store={reasoningStore}>{children}</JotaiProvider>
+ </RecoilRoot>
+ );
+ const rendered = renderHook(
+ ({
+ activeConversation,
+ enabled,
+ hasAddedConversation,
+ }: {
+ activeConversation: TConversation;
+ enabled: boolean;
+ hasAddedConversation: boolean;
+ }) =>
+ useComposerReasoning({
+ conversation: activeConversation,
+ index: 0,
+ hasAddedConversation,
+ enabled,
+ }),
+ {
+ initialProps: {
+ activeConversation: conversation,
+ enabled: true,
+ hasAddedConversation: false,
+ },
+ wrapper,
+ },
+ );
+
+ expect(rendered.result.current?.setting.key).toBe('reasoning_effort');
+ act(() => {
+ rendered.result.current?.setValue({
+ key: 'reasoning_effort',
+ value: ReasoningEffort.high,
+ });
+ });
+ expect(reasoningStore.get(pendingReasoningOverrideFamily('reasoning-conversation'))).toEqual({
+ key: 'reasoning_effort',
+ value: ReasoningEffort.high,
+ });
+ expect(conversation.reasoning_effort).toBe(ReasoningEffort.medium);
+
+ rendered.rerender({
+ activeConversation: { ...conversation, model: 'gpt-5-mini' },
+ enabled: true,
+ hasAddedConversation: false,
+ });
+ await waitFor(() =>
+ expect(
+ reasoningStore.get(pendingReasoningOverrideFamily('reasoning-conversation')),
+ ).toBeUndefined(),
+ );
+
+ rendered.rerender({
+ activeConversation: conversation,
+ enabled: true,
+ hasAddedConversation: false,
+ });
+ await waitFor(() => expect(rendered.result.current).not.toBeNull());
+ act(() => {
+ rendered.result.current?.setValue({
+ key: 'reasoning_effort',
+ value: ReasoningEffort.high,
+ });
+ });
+ expect(reasoningStore.get(pendingReasoningOverrideFamily('reasoning-conversation'))).toEqual({
+ key: 'reasoning_effort',
+ value: ReasoningEffort.high,
+ });
+ rendered.rerender({
+ activeConversation: conversation,
+ enabled: false,
+ hasAddedConversation: false,
+ });
+ await waitFor(() =>
+ expect(
+ reasoningStore.get(pendingReasoningOverrideFamily('reasoning-conversation')),
+ ).toBeUndefined(),
+ );
+
+ rendered.rerender({
+ activeConversation: conversation,
+ enabled: true,
+ hasAddedConversation: false,
+ });
+ await waitFor(() => expect(rendered.result.current).not.toBeNull());
+ act(() => {
+ rendered.result.current?.setValue({
+ key: 'reasoning_effort',
+ value: ReasoningEffort.high,
+ });
+ });
+ rendered.rerender({
+ activeConversation: conversation,
+ enabled: true,
+ hasAddedConversation: true,
+ });
+ await waitFor(() =>
+ expect(
+ reasoningStore.get(pendingReasoningOverrideFamily('reasoning-conversation')),
+ ).toBeUndefined(),
+ );
+ });
+ it('keeps a staged selection when the user returns from a conversation on another model', async () => {
+ const reasoningStore = createStore();
+ const staged = { key: 'reasoning_effort' as const, value: ReasoningEffort.high };
+ const first = {
+ conversationId: 'staged-conversation',
+ endpoint: 'openAI',
+ model: 'gpt-5',
+ } as TConversation;
+ const second = {
+ conversationId: 'other-conversation',
+ endpoint: 'openAI',
+ model: 'gpt-5-mini',
+ } as TConversation;
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <RecoilRoot>
+ <JotaiProvider store={reasoningStore}>{children}</JotaiProvider>
+ </RecoilRoot>
+ );
+ const rendered = renderHook(
+ ({ activeConversation }: { activeConversation: TConversation }) =>
+ useComposerReasoning({
+ conversation: activeConversation,
+ index: 0,
+ hasAddedConversation: false,
+ enabled: true,
+ }),
+ { initialProps: { activeConversation: first }, wrapper },
+ );
+
+ await waitFor(() => expect(rendered.result.current).not.toBeNull());
+ act(() => {
+ rendered.result.current?.setValue(staged);
+ });
+
+ rendered.rerender({ activeConversation: second });
+ await waitFor(() => expect(rendered.result.current?.setting.key).toBe('reasoning_effort'));
+ rendered.rerender({ activeConversation: first });
+ await waitFor(() => expect(rendered.result.current).not.toBeNull());
+ expect(reasoningStore.get(pendingReasoningOverrideFamily('staged-conversation'))).toEqual(
+ staged,
+ );
+ });
+
+ it('resolves the control for an ephemeral agent from its encoded target', async () => {
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <RecoilRoot>
+ <JotaiProvider store={createStore()}>{children}</JotaiProvider>
+ </RecoilRoot>
+ );
+ const rendered = renderHook(
+ ({ agentId }: { agentId: string }) =>
+ useComposerReasoning({
+ conversation: {
+ conversationId: 'ephemeral-agent-conversation',
+ endpoint: 'agents',
+ agent_id: agentId,
+ } as TConversation,
+ index: 0,
+ hasAddedConversation: false,
+ enabled: true,
+ }),
+ { initialProps: { agentId: 'openAI__gpt-5___GPT-5' }, wrapper },
+ );
+
+ await waitFor(() => expect(rendered.result.current?.setting.key).toBe('reasoning_effort'));
+
+ rendered.rerender({ agentId: 'agent_not_loaded_yet' });
+ await waitFor(() => expect(rendered.result.current).toBeNull());
+ });
+
+ it('keeps secondary-pane reasoning selection isolated and clears it on target changes', async () => {
+ const reasoningStore = createStore();
+ const conversation = {
+ conversationId: Constants.NEW_CONVO,
+ endpoint: 'openAI',
+ model: 'gpt-5',
+ reasoning_effort: ReasoningEffort.medium,
+ } as TConversation;
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <RecoilRoot>
+ <JotaiProvider store={reasoningStore}>{children}</JotaiProvider>
+ </RecoilRoot>
+ );
+ type ReasoningProps = { activeConversation: TConversation };
+ const primary = renderHook(
+ ({ activeConversation }: ReasoningProps) =>
+ useComposerReasoning({
+ conversation: activeConversation,
+ index: 0,
+ hasAddedConversation: false,
+ enabled: true,
+ }),
+ {
+ initialProps: { activeConversation: conversation },
+ wrapper,
+ },
+ );
+ const secondary = renderHook(
+ ({ activeConversation }: ReasoningProps) =>
+ useComposerReasoning({
+ conversation: activeConversation,
+ index: 1,
+ hasAddedConversation: false,
+ enabled: true,
+ }),
+ {
+ initialProps: { activeConversation: conversation },
+ wrapper,
+ },
+ );
+ const primaryKey = getReasoningStateKey(Constants.NEW_CONVO, 0);
+ const secondaryKey = getReasoningStateKey(Constants.NEW_CONVO, 1);
+
+ expect(primary.result.current).not.toBeNull();
+ expect(secondary.result.current).not.toBeNull();
+ act(() => {
+ primary.result.current?.setValue({
+ key: 'reasoning_effort',
+ value: ReasoningEffort.high,
+ });
+ secondary.result.current?.setValue({
+ key: 'reasoning_effort',
+ value: ReasoningEffort.low,
+ });
+ });
+ expect(reasoningStore.get(pendingReasoningOverrideFamily(primaryKey))).toEqual({
+ key: 'reasoning_effort',
+ value: ReasoningEffort.high,
+ });
+ expect(reasoningStore.get(pendingReasoningOverrideFamily(secondaryKey))).toEqual({
+ key: 'reasoning_effort',
+ value: ReasoningEffort.low,
+ });
+
+ secondary.rerender({
+ activeConversation: { ...conversation, model: 'gpt-5-mini' },
+ });
+ await waitFor(() =>
+ expect(reasoningStore.get(pendingReasoningOverrideFamily(secondaryKey))).toBeUndefined(),
+ );
+ expect(reasoningStore.get(pendingReasoningOverrideFamily(primaryKey))).toEqual({
+ key: 'reasoning_effort',
+ value: ReasoningEffort.high,
+ });
+ });
+
+ /* The window between the first submit and the `created`/`sync` event: the
+ selection for the next turn is written under the placeholder key, and the
+ durable id arrives afterwards. */
+ it('carries a selection made before the id resolves onto the saved conversation', async () => {
+ const reasoningStore = createStore();
+ const conversation = {
+ conversationId: Constants.NEW_CONVO,
+ endpoint: 'openAI',
+ model: 'gpt-5',
+ reasoning_effort: ReasoningEffort.medium,
+ } as TConversation;
+ const submission = {
+ conversation: { conversationId: Constants.NEW_CONVO },
+ userMessage: { conversationId: Constants.NEW_CONVO },
+ } as TSubmission;
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <RecoilRoot
+ initializeState={(snapshot) => snapshot.set(store.submissionByIndex(0), submission)}
+ >
+ <JotaiProvider store={reasoningStore}>{children}</JotaiProvider>
+ </RecoilRoot>
+ );
+ const rendered = renderHook(
+ ({ activeConversation }: { activeConversation: TConversation }) =>
+ useComposerReasoning({
+ conversation: activeConversation,
+ index: 0,
+ hasAddedConversation: false,
+ enabled: true,
+ }),
+ { initialProps: { activeConversation: conversation }, wrapper },
+ );
+ const placeholderKey = getReasoningStateKey(Constants.NEW_CONVO, 0);
+
+ act(() => {
+ rendered.result.current?.setValue({
+ key: 'reasoning_effort',
+ value: ReasoningEffort.high,
+ });
+ });
+ expect(reasoningStore.get(pendingReasoningOverrideFamily(placeholderKey))).toEqual({
+ key: 'reasoning_effort',
+ value: ReasoningEffort.high,
+ });
+
+ rendered.rerender({
+ activeConversation: { ...conversation, conversationId: 'settled-conversation' },
+ });
+
+ await waitFor(() =>
+ expect(reasoningStore.get(pendingReasoningOverrideFamily('settled-conversation'))).toEqual({
+ key: 'reasoning_effort',
+ value: ReasoningEffort.high,
+ }),
+ );
+ expect(rendered.result.current?.value).toEqual({
+ key: 'reasoning_effort',
+ value: ReasoningEffort.high,
+ });
+ /* Left behind, the placeholder value would leak into the next new chat in
+ this pane. */
+ expect(reasoningStore.get(pendingReasoningOverrideFamily(placeholderKey))).toBeUndefined();
+ });
+
+ it('does not carry a new-chat selection into an unrelated conversation', async () => {
+ const reasoningStore = createStore();
+ const conversation = {
+ conversationId: Constants.NEW_CONVO,
+ endpoint: 'openAI',
+ model: 'gpt-5',
+ reasoning_effort: ReasoningEffort.medium,
+ } as TConversation;
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <RecoilRoot>
+ <JotaiProvider store={reasoningStore}>{children}</JotaiProvider>
+ </RecoilRoot>
+ );
+ const rendered = renderHook(
+ ({ activeConversation }: { activeConversation: TConversation }) =>
+ useComposerReasoning({
+ conversation: activeConversation,
+ index: 0,
+ hasAddedConversation: false,
+ enabled: true,
+ }),
+ { initialProps: { activeConversation: conversation }, wrapper },
+ );
+ const placeholderKey = getReasoningStateKey(Constants.NEW_CONVO, 0);
+
+ act(() => {
+ rendered.result.current?.setValue({
+ key: 'reasoning_effort',
+ value: ReasoningEffort.high,
+ });
+ });
+
+ rendered.rerender({
+ activeConversation: { ...conversation, conversationId: 'unrelated-conversation' },
+ });
+
+ await waitFor(() =>
+ expect(
+ reasoningStore.get(pendingReasoningOverrideFamily('unrelated-conversation')),
+ ).toBeUndefined(),
+ );
+ expect(reasoningStore.get(pendingReasoningOverrideFamily(placeholderKey))).toEqual({
+ key: 'reasoning_effort',
+ value: ReasoningEffort.high,
+ });
+ });
+
+ it('merges custom definitions and clears values removed by a capability change', async () => {
+ mockEndpointsConfig = {
+ custom: {
+ type: 'openAI',
+ customParams: {
+ defaultParamsEndpoint: 'openAI',
+ paramDefinitions: [
+ { key: 'reasoning_effort', default: ReasoningEffort.high } as SettingDefinition,
+ ],
+ },
+ },
+ };
+ const reasoningStore = createStore();
+ const conversation = {
+ conversationId: 'custom-reasoning-conversation',
+ endpoint: 'custom',
+ model: 'gpt-5',
+ } as TConversation;
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <RecoilRoot>
+ <JotaiProvider store={reasoningStore}>{children}</JotaiProvider>
+ </RecoilRoot>
+ );
+ const rendered = renderHook(
+ () =>
+ useComposerReasoning({
+ conversation,
+ index: 0,
+ hasAddedConversation: false,
+ enabled: true,
+ }),
+ { wrapper },
+ );
+
+ expect(rendered.result.current?.setting.default).toBe(ReasoningEffort.high);
+ expect(rendered.result.current?.setting.options).toContain(ReasoningEffort.low);
+ act(() => {
+ rendered.result.current?.setValue({
+ key: 'reasoning_effort',
+ value: ReasoningEffort.high,
+ });
+ });
+
+ mockEndpointsConfig = {
+ custom: {
+ type: 'openAI',
+ customParams: {
+ defaultParamsEndpoint: 'openAI',
+ paramDefinitions: [
+ {
+ key: 'reasoning_effort',
+ options: [ReasoningEffort.low],
+ } as SettingDefinition,
+ ],
+ },
+ },
+ };
+ rendered.rerender();
+
+ await waitFor(() =>
+ expect(
+ reasoningStore.get(pendingReasoningOverrideFamily('custom-reasoning-conversation')),
+ ).toBeUndefined(),
+ );
+ });
+
+ it('exposes the declared effort control for the mock custom endpoint', () => {
+ mockEndpointsConfig = {
+ 'Mock Provider A': {
+ type: 'custom',
+ customParams: {
+ defaultParamsEndpoint: 'anthropic',
+ paramDefinitions: [{ key: 'effort' } as SettingDefinition],
+ },
+ },
+ };
+ const reasoningStore = createStore();
+ /* A named custom endpoint: the label is not an `EModelEndpoint` member, which
+ is exactly the shape this case is about. */
+ const conversation = {
+ conversationId: 'mock-provider-conversation',
+ endpoint: 'Mock Provider A',
+ endpointType: 'custom',
+ model: 'mock-model-a',
+ } as unknown as TConversation;
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <RecoilRoot>
+ <JotaiProvider store={reasoningStore}>{children}</JotaiProvider>
+ </RecoilRoot>
+ );
+
+ const rendered = renderHook(
+ () =>
+ useComposerReasoning({
+ conversation,
+ index: 0,
+ hasAddedConversation: false,
+ enabled: true,
+ }),
+ { wrapper },
+ );
+
+ expect(rendered.result.current?.setting).toMatchObject({
+ key: 'effort',
+ options: expect.arrayContaining(['low', 'high']),
+ });
+ });
+
+ it('preserves restored reasoning while custom endpoint capabilities are loading', async () => {
+ mockEndpointsConfig = undefined;
+ const reasoningStore = createStore();
+ const conversation = {
+ conversationId: 'loading-reasoning-conversation',
+ endpoint: 'custom',
+ model: 'gpt-5',
+ } as TConversation;
+ reasoningStore.set(pendingReasoningOverrideFamily('loading-reasoning-conversation'), {
+ key: 'reasoning_effort',
+ value: ReasoningEffort.high,
+ });
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <RecoilRoot>
+ <JotaiProvider store={reasoningStore}>{children}</JotaiProvider>
+ </RecoilRoot>
+ );
+ const rendered = renderHook(
+ () =>
+ useComposerReasoning({
+ conversation,
+ index: 0,
+ hasAddedConversation: false,
+ enabled: true,
+ }),
+ { wrapper },
+ );
+
+ expect(rendered.result.current).toBeNull();
+ expect(
+ reasoningStore.get(pendingReasoningOverrideFamily('loading-reasoning-conversation')),
+ ).toEqual({ key: 'reasoning_effort', value: ReasoningEffort.high });
+
+ mockEndpointsConfig = {
+ custom: {
+ type: 'openAI',
+ customParams: { defaultParamsEndpoint: 'openAI' },
+ },
+ };
+ rendered.rerender();
+
+ await waitFor(() =>
+ expect(rendered.result.current?.value).toEqual({
+ key: 'reasoning_effort',
+ value: ReasoningEffort.high,
+ }),
+ );
+ expect(
+ reasoningStore.get(pendingReasoningOverrideFamily('loading-reasoning-conversation')),
+ ).toEqual({ key: 'reasoning_effort', value: ReasoningEffort.high });
+ });
+
+ it('clears a restored override whose value the current setting no longer offers', async () => {
+ mockEndpointsConfig = {
+ custom: {
+ type: 'openAI',
+ customParams: { defaultParamsEndpoint: 'openAI' },
+ },
+ };
+ const reasoningStore = createStore();
+ const conversation = {
+ conversationId: 'stale-reasoning-conversation',
+ endpoint: 'custom',
+ model: 'gpt-5',
+ } as TConversation;
+ reasoningStore.set(pendingReasoningOverrideFamily('stale-reasoning-conversation'), {
+ key: 'reasoning_effort',
+ value: 'retired-effort' as ReasoningEffort,
+ });
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <RecoilRoot>
+ <JotaiProvider store={reasoningStore}>{children}</JotaiProvider>
+ </RecoilRoot>
+ );
+ const rendered = renderHook(
+ () =>
+ useComposerReasoning({
+ conversation,
+ index: 0,
+ hasAddedConversation: false,
+ enabled: true,
+ }),
+ { wrapper },
+ );
+
+ await waitFor(() =>
+ expect(
+ reasoningStore.get(pendingReasoningOverrideFamily('stale-reasoning-conversation')),
+ ).toBeUndefined(),
+ );
+ expect(rendered.result.current?.setting.key).toBe('reasoning_effort');
+ });
+});
diff --git a/client/src/components/Chat/Input/__tests__/StopButton.spec.tsx b/client/src/components/Chat/Input/__tests__/StopButton.spec.tsx
new file mode 100644
index 0000000000..afc5d636b2
--- /dev/null
+++ b/client/src/components/Chat/Input/__tests__/StopButton.spec.tsx
@@ -0,0 +1,48 @@
+import { render, screen, fireEvent } from '@testing-library/react';
+import StopButton from '../StopButton';
+
+jest.mock('~/hooks', () => ({
+ useLocalize: () => (key: string) => key,
+}));
+
+describe('StopButton', () => {
+ it('hides itself and aborts the run on click', () => {
+ const stop = jest.fn();
+ const setShowStopButton = jest.fn();
+ render(<StopButton stop={stop} setShowStopButton={setShowStopButton} />);
+
+ fireEvent.click(screen.getByTestId('stop-generation-button'));
+
+ expect(setShowStopButton).toHaveBeenCalledWith(false);
+ expect(stop).toHaveBeenCalledTimes(1);
+ });
+
+ it('stays visible but inert while the abort would be a no-op', () => {
+ const stop = jest.fn();
+ const setShowStopButton = jest.fn();
+ render(<StopButton stop={stop} setShowStopButton={setShowStopButton} canStop={false} />);
+
+ const button = screen.getByTestId('stop-generation-button');
+ expect(button).toBeDisabled();
+
+ fireEvent.click(button);
+
+ expect(setShowStopButton).not.toHaveBeenCalled();
+ expect(stop).not.toHaveBeenCalled();
+ });
+
+ it('keeps an out-of-layout control the stop shortcut can still reach', () => {
+ const stop = jest.fn();
+ const setShowStopButton = jest.fn();
+ render(<StopButton stop={stop} setShowStopButton={setShowStopButton} hidden />);
+
+ const button = screen.getByTestId('stop-generation-button');
+ /* The preflight hides `[hidden]` with `!important`, over the slot's `flex`. */
+ expect(button).toHaveAttribute('hidden');
+
+ button.click();
+
+ expect(setShowStopButton).toHaveBeenCalledWith(false);
+ expect(stop).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/client/src/components/Chat/Input/__tests__/appearanceTokens.spec.ts b/client/src/components/Chat/Input/__tests__/appearanceTokens.spec.ts
index f6c54294df..2d7e7768b1 100644
--- a/client/src/components/Chat/Input/__tests__/appearanceTokens.spec.ts
+++ b/client/src/components/Chat/Input/__tests__/appearanceTokens.spec.ts
@@ -4,31 +4,29 @@ import { readFileSync } from 'node:fs';
const inputRoot = join(__dirname, '..');
const source = (file: string): string => readFileSync(join(inputRoot, file), 'utf8');
+/** Send and stop take the slot's recipe from IconButton's `submit` variant,
+ * which is built from `composerSubmitClasses()`. */
+const submitControls = ['SendButton.tsx', 'StopButton.tsx'] as const;
+
const themedControls = [
- /** The submit slot's three faces share one recipe, which owns the coarse-pointer
- * tap-target floor as well as the geometry; its tokens are asserted where it
- * lives (`composer.spec.ts`). Copying the class string back into any of them
- * would take that floor off a phone silently, so the recipe is what is checked. */
- ['SendButton.tsx', ['composerSubmitClasses()']],
- ['StopButton.tsx', ['composerSubmitClasses()']],
+ /** The submit slot's faces share one recipe, which owns the coarse-pointer
+ * tap-target floor as well as the geometry. */
['DuringRunSendButton.tsx', ['composerSubmitClasses()']],
['InterruptSteerButton.tsx', ['size-theme-control', 'rounded-theme-control-round']],
- ['AudioRecorder.tsx', ['size="theme"', 'shape="theme"']],
- /** Controls that draw their shape from `composerControlClasses()` prove it by
- * consuming the shared recipe; its own tokens are asserted where it lives. */
- ['MCPSelect.tsx', ['composerControlClasses()', 'min-w-theme-control', 'md:px-theme-normal']],
- ['CodeApprovalMenu.tsx', ['composerControlClasses()', 'md:px-theme-normal']],
['TokenUsage/index.tsx', ['size-theme-control', 'rounded-theme-control-round']],
['Files/AttachFile.tsx', ['size-theme-control', 'rounded-theme-control-round']],
- ['Files/AttachFileMenu.tsx', ['size-theme-control', 'rounded-theme-control-round']],
- ['ToolsDropdown.tsx', ['size-theme-control', 'rounded-theme-control-round']],
- /** Floats over the thread rather than sitting in the composer, but stacks
- * over Send on the same rail, so it takes the row's geometry from the shared
- * `Button` recipe; the tokens behind those variants are asserted in `Button.spec`. */
- ['../../Messages/ScrollToBottom.tsx', ['size="icon-theme"', 'shape="round"']],
+ ['CodeApprovalMenu.tsx', ['composerControlClasses()', 'md:px-theme-normal']],
] as const;
describe('Composer appearance tokens', () => {
+ it.each(submitControls)('%s composes the shared submit-slot control', (file) => {
+ const contents = source(file);
+
+ ['IconButton', 'variant="submit"', 'size="theme"', 'shape="theme"'].forEach((token) =>
+ expect(contents).toContain(token),
+ );
+ });
+
it.each(themedControls)('%s uses shared control geometry', (file, expectedTokens) => {
const contents = source(file);
diff --git a/client/src/components/Chat/Input/overlay.ts b/client/src/components/Chat/Input/overlay.ts
index 393187796c..3a3a49d652 100644
--- a/client/src/components/Chat/Input/overlay.ts
+++ b/client/src/components/Chat/Input/overlay.ts
@@ -10,8 +10,8 @@ import { atom, useSetAtom } from 'jotai';
* composer is taller than ~92px, which it always is. The control stands down
* while the count is above zero. Each panel registers through
* {@link useComposerOverlay} for exactly as long as it renders, so the count
- * can never go stale; like `steerOverlayHeightFamily`, the family is never
- * GC'd but holds one number per visited conversation.
+ * can never go stale; the family is never GC'd but holds one number per
+ * visited conversation.
*/
export const composerOverlayCountFamily = atomFamily((_conversationId: string) => atom<number>(0));
diff --git a/client/src/components/Chat/Messages/Content/EditContentParts.tsx b/client/src/components/Chat/Messages/Content/EditContentParts.tsx
index 2fb564d62c..0f25001a0e 100644
--- a/client/src/components/Chat/Messages/Content/EditContentParts.tsx
+++ b/client/src/components/Chat/Messages/Content/EditContentParts.tsx
@@ -245,6 +245,7 @@ export default function EditContentParts({
overrideFiles: editedMessage.files,
overrideManualSkills: editedMessage.manualSkills,
overrideQuotes: editedMessage.quotes,
+ overrideReasoning: editedMessage.reasoningOverride ?? null,
addedConvo: getAddedConvo() || undefined,
},
) === false;
@@ -269,6 +270,7 @@ export default function EditContentParts({
targetResponseMessageId: messageId,
overrideManualSkills: parentMessage.manualSkills,
overrideQuotes: parentMessage.quotes,
+ overrideReasoning: parentMessage.reasoningOverride ?? null,
addedConvo: getAddedConvo() || undefined,
},
) === false;
@@ -295,6 +297,7 @@ export default function EditContentParts({
isEdited: true,
overrideManualSkills: parentMessage.manualSkills,
overrideQuotes: parentMessage.quotes,
+ overrideReasoning: parentMessage.reasoningOverride ?? null,
addedConvo: getAddedConvo() || undefined,
},
) === false;
diff --git a/client/src/components/Chat/Messages/Content/EditMessage.tsx b/client/src/components/Chat/Messages/Content/EditMessage.tsx
index f9b1611d06..58499fb1ce 100644
--- a/client/src/components/Chat/Messages/Content/EditMessage.tsx
+++ b/client/src/components/Chat/Messages/Content/EditMessage.tsx
@@ -86,6 +86,7 @@ const EditMessage = ({
/** Carry the edited user message's quoted excerpts forward so the new
* turn sends the same referenced context the pills still show. */
overrideQuotes: message.quotes,
+ overrideReasoning: message.reasoningOverride ?? null,
addedConvo: getAddedConvo() || undefined,
},
);
@@ -124,6 +125,7 @@ const EditMessage = ({
* the regenerated response is primed and given the same context as the first. */
overrideManualSkills: parentMessage.manualSkills,
overrideQuotes: parentMessage.quotes,
+ overrideReasoning: parentMessage.reasoningOverride ?? null,
addedConvo: getAddedConvo() || undefined,
},
);
diff --git a/client/src/components/Chat/Messages/Content/Parts/PendingSteers.tsx b/client/src/components/Chat/Messages/Content/Parts/PendingSteers.tsx
new file mode 100644
index 0000000000..95bbd14441
--- /dev/null
+++ b/client/src/components/Chat/Messages/Content/Parts/PendingSteers.tsx
@@ -0,0 +1,269 @@
+import { memo, useMemo, useRef, useState } from 'react';
+import { useAtomValue } from 'jotai';
+import { useRecoilValue } from 'recoil';
+import { TextQuote } from 'lucide-react';
+import { useToastContext } from '@librechat/client';
+import { useQueryClient } from '@tanstack/react-query';
+import { QueryKeys, type TMessage } from 'librechat-data-provider';
+import type { SteerReceiptState } from '~/components/Chat/Steering/Receipt';
+import useSteerCancel, { useSteerMoveToQueue, useSteerRehome } from '~/hooks/Chat/useSteerCancel';
+import EscalateNowButton from '~/components/Chat/Input/EscalateNowButton';
+import useSteerEscalate from '~/hooks/Chat/useSteerEscalate';
+import useSteerRecovery from '~/hooks/Chat/useSteerRecovery';
+import { hasLiveRunPause } from '~/hooks/Chat/useSteering';
+import { useGetMessagesByConvoId } from '~/data-provider';
+import { cn, isLegacyDeliveryUncertain } from '~/utils';
+import { escalatingSteerFamily } from '~/store/steer';
+import { useLatestMessage } from '~/hooks/Messages';
+import { useLocalize } from '~/hooks';
+import SteerPart from './SteerPart';
+import store from '~/store';
+
+const ACTION_CLASS =
+ 'rounded text-xs font-medium text-text-secondary hover:text-text-primary focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-border-xheavy';
+
+/**
+ * Steers that have not been confirmed by the server yet, rendered at the tail
+ * of the streaming reply (the place the words will land) instead of in a
+ * floating overlay over the composer. Confirmation swaps them for the real
+ * `ContentTypes.STEER` part (`useResumableSSE` removes the pending entry), so
+ * the row's whole job is to hold the position and admit it is provisional.
+ */
+interface PendingSteersProps {
+ conversationId: string;
+ /** The pane rendering this tree: its sibling selection picks the branch the
+ * pause check reads, which another pane's selection would get wrong. */
+ index?: number;
+}
+
+function PendingSteers({ conversationId, index = 0 }: PendingSteersProps) {
+ const localize = useLocalize();
+ const { showToast } = useToastContext();
+ const steers = useRecoilValue(store.pendingSteersByConvoId(conversationId));
+ const { retry, sendAsNew } = useSteerRecovery(conversationId);
+ const cancelSteer = useSteerCancel(conversationId);
+ const escalate = useSteerEscalate(conversationId);
+ const moveToQueue = useSteerMoveToQueue(conversationId);
+ const rehomeSteer = useSteerRehome(conversationId);
+ const [movingId, setMovingId] = useState<string | null>(null);
+ const escalating = useAtomValue(escalatingSteerFamily(conversationId));
+ /* Resolve the cache to the branch the user is viewing before applying the
+ shared pause predicate. The cache contains every sibling branch, while
+ `useLatestMessage` follows the same selection state as the message view. */
+ const queryClient = useQueryClient();
+ const cachedMessages =
+ queryClient.getQueryData<TMessage[]>([QueryKeys.messages, conversationId]) ?? [];
+ const latestMessage = useLatestMessage(index, conversationId);
+ const paneConversationId = useRecoilValue(store.conversationIdByIndex(index));
+ const { data: fallbackPaused } = useGetMessagesByConvoId<boolean>(conversationId, {
+ select: hasLiveRunPause,
+ });
+ /* A one-message cache is necessarily the active branch. Until the
+ conversation atom reaches useLatestMessage, retain the query's established
+ single-branch result so a live question cannot re-enable escalation. The
+ branch tail is keyed by the pane's conversation, which can still name the
+ previous chat while this one renders from cache; until the pane owns this
+ conversation, a pause on any branch keeps escalation off. */
+ const resolvePaused = (): boolean => {
+ if (cachedMessages.length > 1) {
+ if (paneConversationId === conversationId && latestMessage != null) {
+ return hasLiveRunPause(latestMessage);
+ }
+ return cachedMessages.some((message) => hasLiveRunPause(message));
+ }
+ if (fallbackPaused != null) {
+ return fallbackPaused;
+ }
+ return cachedMessages.length === 1 && hasLiveRunPause(cachedMessages[0]);
+ };
+ /** Arming removes the control that was activated, so the row's Cancel button
+ * (which survives the `preempt` flip) is where keyboard focus goes next. */
+ const cancelButtonRefs = useRef(new Map<string, HTMLButtonElement | null>());
+ const interruptPending = useMemo(
+ () => escalating || steers.some((steer) => steer.preempt === true && steer.status !== 'failed'),
+ [escalating, steers],
+ );
+
+ if (steers.length === 0) {
+ return null;
+ }
+ const paused = resolvePaused();
+
+ const queueSteer = async (steer: (typeof steers)[number]) => {
+ if (movingId != null) {
+ return;
+ }
+ setMovingId(steer.steerId);
+ try {
+ const outcome = await moveToQueue(steer);
+ if (outcome === 'applied') {
+ showToast({ message: localize('com_ui_steer_already_applied'), status: 'info' });
+ } else if (outcome === 'failed') {
+ showToast({ message: localize('com_ui_steer_cancel_failed'), status: 'error' });
+ }
+ } finally {
+ setMovingId(null);
+ }
+ };
+ /** A definitively rejected steer can be corrected: the whole message comes
+ * back through the shared recovery boundary, so its attachments, quoted
+ * excerpts and skill picks come with it. Withheld while delivery is
+ * uncertain, like every other action that assumes the server does not hold
+ * these words. */
+ const editFailedSteer = (steer: (typeof steers)[number]) => {
+ if (rehomeSteer(steer, { rejectedByServer: true }) === 'queue') {
+ showToast({ message: localize('com_ui_steer_moved_to_queue'), status: 'info' });
+ }
+ };
+ const cancelPendingSteer = async (steer: (typeof steers)[number]) => {
+ if (movingId != null) {
+ return;
+ }
+ setMovingId(steer.steerId);
+ try {
+ const outcome = await cancelSteer(steer);
+ if (outcome === 'applied') {
+ showToast({ message: localize('com_ui_steer_already_applied'), status: 'info' });
+ } else if (outcome === 'failed') {
+ showToast({ message: localize('com_ui_steer_cancel_failed'), status: 'error' });
+ }
+ } finally {
+ setMovingId(null);
+ }
+ };
+
+ return (
+ <div role="list" aria-label={localize('com_ui_steer_in_flight')} data-testid="pending-steers">
+ {steers.map((steer) => {
+ const deliveryUncertain = steer.deliveryUncertain === true;
+ const retrySafe = !isLegacyDeliveryUncertain(steer);
+ const quoteCount = steer.quotes?.length ?? 0;
+ let receiptState: SteerReceiptState = 'delivered';
+ if (steer.status === 'sending') {
+ receiptState = 'sending';
+ } else if (steer.preempt === true) {
+ receiptState = 'interrupting';
+ }
+ return (
+ <div
+ key={steer.steerId}
+ role="listitem"
+ className={cn(steer.status !== 'failed' && 'opacity-60')}
+ >
+ <SteerPart
+ steer={steer.text}
+ files={steer.files}
+ steerId={steer.steerId}
+ createdAt={steer.createdAt}
+ receiptState={receiptState}
+ />
+ {steer.status === 'failed' ? (
+ <div className="-mt-2 mb-2 flex items-center gap-3 pl-9 text-xs">
+ {quoteCount > 0 && (
+ <span className="text-text-secondary flex items-center gap-0.5">
+ <TextQuote className="h-3.5 w-3.5" aria-hidden="true" />
+ <span aria-hidden="true">{quoteCount}</span>
+ <span className="sr-only">
+ {localize('com_ui_queued_quote_count', { 0: String(quoteCount) })}
+ </span>
+ </span>
+ )}
+ <span className="text-text-destructive">
+ {localize(
+ deliveryUncertain
+ ? 'com_ui_steer_delivery_uncertain'
+ : 'com_ui_steer_failed_inline',
+ )}
+ </span>
+ {retrySafe && (
+ <button
+ type="button"
+ onClick={() => retry(steer.steerId)}
+ className={ACTION_CLASS}
+ >
+ {localize('com_ui_retry')}
+ </button>
+ )}
+ {!deliveryUncertain && (
+ <button
+ type="button"
+ onClick={() => editFailedSteer(steer)}
+ className={ACTION_CLASS}
+ >
+ {localize('com_ui_edit')}
+ </button>
+ )}
+ {!deliveryUncertain && (
+ <button
+ type="button"
+ onClick={() => sendAsNew(steer.steerId)}
+ className={ACTION_CLASS}
+ >
+ {localize('com_ui_send_as_new')}
+ </button>
+ )}
+ </div>
+ ) : (
+ <div className="text-text-secondary -mt-2 mb-2 flex items-center gap-2 pl-9 text-xs">
+ <span>
+ {localize(
+ steer.preempt === true ? 'com_ui_steer_in_flight_preempt' : 'com_ui_sending',
+ )}
+ </span>
+ {/* Only a `pending` steer can be armed: `sending` has no server id
+ yet, and one already interrupting has nothing left to escalate. */}
+ {steer.status === 'pending' && steer.preempt !== true && (
+ <EscalateNowButton
+ surface="bubble"
+ messageText={steer.text}
+ disabled={paused === true || interruptPending}
+ onClick={() =>
+ escalate(
+ {
+ steerId: steer.steerId,
+ generationCreatedAt: steer.generationCreatedAt,
+ },
+ () => cancelButtonRefs.current.get(steer.steerId)?.focus(),
+ )
+ }
+ />
+ )}
+ {steer.status === 'pending' && (
+ <>
+ <button
+ type="button"
+ disabled={movingId != null}
+ onClick={() => void queueSteer(steer)}
+ className={ACTION_CLASS}
+ >
+ {localize('com_ui_convert_to_queue')}
+ </button>
+ </>
+ )}
+ {(steer.status === 'pending' || steer.status === 'sending') && (
+ <button
+ type="button"
+ ref={(node) => {
+ if (node == null) {
+ cancelButtonRefs.current.delete(steer.steerId);
+ return;
+ }
+ cancelButtonRefs.current.set(steer.steerId, node);
+ }}
+ disabled={movingId != null}
+ onClick={() => void cancelPendingSteer(steer)}
+ className={ACTION_CLASS}
+ >
+ {localize('com_ui_cancel')}
+ </button>
+ )}
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ );
+}
+
+export default memo(PendingSteers);
diff --git a/client/src/components/Chat/Messages/Content/Parts/SteerPart.tsx b/client/src/components/Chat/Messages/Content/Parts/SteerPart.tsx
index 7838a0c160..1fb2fe7232 100644
--- a/client/src/components/Chat/Messages/Content/Parts/SteerPart.tsx
+++ b/client/src/components/Chat/Messages/Content/Parts/SteerPart.tsx
@@ -1,6 +1,7 @@
import { memo, useMemo, useState, useEffect, useCallback } from 'react';
import { useRecoilValue, useSetRecoilState } from 'recoil';
import type { TFile, TMessage } from 'librechat-data-provider';
+import SteerReceipt, { type SteerReceiptState } from '~/components/Chat/Steering/Receipt';
import FilePreviewDialog from '~/components/Chat/Messages/Content/FilePreviewDialog';
import MessageTimestamp from '~/components/Chat/Messages/ui/MessageTimestamp';
import MessageQuotes from '~/components/Chat/Messages/Content/MessageQuotes';
@@ -8,7 +9,6 @@ import { cn, hydrateFileDeliveryMetadata, usesImagePreview } from '~/utils';
import MarkdownLite from '~/components/Chat/Messages/Content/MarkdownLite';
import FileContainer from '~/components/Chat/Input/Files/FileContainer';
import { useFileMapContext, useShareContext } from '~/Providers';
-import SteerReceipt from '~/components/Chat/Steering/Receipt';
import Image from '~/components/Chat/Messages/Content/Image';
import CollapsibleText from './CollapsibleText';
import { useLocalize } from '~/hooks';
@@ -30,6 +30,7 @@ const SteerPart = memo(function SteerPart({
steerId,
createdAt,
isSubmitting = false,
+ receiptState = 'applied',
}: {
steer: string;
files?: TMessage['files'];
@@ -43,6 +44,8 @@ const SteerPart = memo(function SteerPart({
* steering identity while it is the live thing at the end, then settles
* to timestamp gray (always settled on reload, share, and search). */
isSubmitting?: boolean;
+ /** Pending renderer state must never claim server application early. */
+ receiptState?: SteerReceiptState;
}) {
const localize = useLocalize();
/** Read the atom rather than the auth context: AuthContextProvider mirrors the
@@ -167,7 +170,7 @@ const SteerPart = memo(function SteerPart({
* width changes as the relative string ticks. */}
<div className="text-text-secondary mt-1 flex min-h-8 items-center justify-end gap-2">
<MessageTimestamp value={timestamp} className="ml-0" />
- <SteerReceipt state="applied" live={isSubmitting} animateIn={animateIn} />
+ <SteerReceipt state={receiptState} live={isSubmitting} animateIn={animateIn} />
</div>
</div>
{otherFiles.length > 0 && (
diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/PendingSteers.test.tsx b/client/src/components/Chat/Messages/Content/Parts/__tests__/PendingSteers.test.tsx
new file mode 100644
index 0000000000..b57d6d310e
--- /dev/null
+++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/PendingSteers.test.tsx
@@ -0,0 +1,460 @@
+import React from 'react';
+import { RecoilRoot } from 'recoil';
+import { MemoryRouter } from 'react-router-dom';
+import { Provider as JotaiProvider, createStore } from 'jotai';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { Constants, ContentTypes, QueryKeys } from 'librechat-data-provider';
+import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';
+import type { Agents, TConversation, TMessage } from 'librechat-data-provider';
+import type { PendingSteer } from '~/store/families';
+import { siblingIdxFamily, siblingKey } from '~/components/Chat/Messages/Thread/state';
+import { hasLiveRunPause } from '~/hooks/Chat/useSteering';
+import { applyPendingAction } from '~/utils/approval';
+import PendingSteers from '../PendingSteers';
+import store from '~/store';
+
+const mockRetry = jest.fn();
+const mockSendAsNew = jest.fn();
+const mockEscalate = jest.fn();
+const mockMoveToQueue = jest.fn();
+const mockRehome = jest.fn(() => 'composer' as const);
+const mockShowToast = jest.fn();
+
+jest.mock('@librechat/client', () => ({
+ ...jest.requireActual('@librechat/client'),
+ useToastContext: () => ({ showToast: mockShowToast }),
+}));
+
+jest.mock('~/hooks', () => ({
+ useLocalize: () => (key: string) => key,
+}));
+
+jest.mock('~/hooks/Chat/useSteerEscalate', () => ({
+ __esModule: true,
+ default: () => mockEscalate,
+}));
+
+jest.mock('~/hooks/Chat/useSteerRecovery', () => ({
+ __esModule: true,
+ default: () => ({ retry: mockRetry, sendAsNew: mockSendAsNew }),
+}));
+
+jest.mock('~/hooks/Chat/useSteerCancel', () => ({
+ __esModule: true,
+ default: () => jest.fn(),
+ useSteerMoveToQueue: () => mockMoveToQueue,
+ useSteerRehome: () => mockRehome,
+}));
+
+jest.mock('../SteerPart', () => ({
+ __esModule: true,
+ default: ({ steer }: { steer: string }) => <div data-testid="steer-part">{steer}</div>,
+}));
+
+const CONVO_ID = 'convo-1';
+
+const pending = (over: Partial<PendingSteer> = {}): PendingSteer => ({
+ steerId: 's1',
+ text: 'change of plan',
+ status: 'sending',
+ createdAt: 1,
+ ...over,
+});
+
+function renderPending(
+ steers: PendingSteer[],
+ messages?: TMessage[],
+ activeSiblingIndex?: number,
+ /** Split view: this tree renders in `index`, while pane 0 shows another chat. */
+ pane?: { index: number; siblingKeyId: string; otherConversationId: string },
+ /** Pane 0 still names the previous chat while this one renders from cache. */
+ stalePaneConversationId?: string,
+) {
+ /* The escalation control resolves the cache through the branch-aware
+ latest-message hook, using the same providers the chat view supplies. */
+ const queryClient = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false, staleTime: Infinity },
+ mutations: { retry: false },
+ },
+ });
+ queryClient.setQueryData([QueryKeys.messages, CONVO_ID], messages ?? []);
+ const jotaiStore = createStore();
+ if (activeSiblingIndex != null) {
+ jotaiStore.set(
+ siblingIdxFamily(
+ siblingKey(
+ pane?.siblingKeyId ?? (stalePaneConversationId != null ? CONVO_ID : 'root-user'),
+ ),
+ ),
+ activeSiblingIndex,
+ );
+ }
+ return render(
+ <MemoryRouter>
+ <QueryClientProvider client={queryClient}>
+ <JotaiProvider store={jotaiStore}>
+ <RecoilRoot
+ initializeState={({ set }) => {
+ set(store.conversationByIndex(0), {
+ conversationId: pane?.otherConversationId ?? stalePaneConversationId ?? CONVO_ID,
+ } as TConversation);
+ if (pane != null) {
+ set(store.conversationByIndex(pane.index), {
+ conversationId: CONVO_ID,
+ } as TConversation);
+ }
+ set(store.pendingSteersByConvoId(CONVO_ID), steers);
+ }}
+ >
+ <PendingSteers conversationId={CONVO_ID} index={pane?.index} />
+ </RecoilRoot>
+ </JotaiProvider>
+ </QueryClientProvider>
+ </MemoryRouter>,
+ );
+}
+
+describe('PendingSteers', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ mockMoveToQueue.mockResolvedValue('reclaimed');
+ });
+
+ it('renders nothing with no pending steers', () => {
+ const { container } = renderPending([]);
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it('renders a dimmed steer part with sending status', () => {
+ renderPending([pending()]);
+ expect(screen.getByTestId('steer-part')).toHaveTextContent('change of plan');
+ expect(screen.getByText('com_ui_sending')).toBeInTheDocument();
+ });
+
+ it('offers retry and send-as-new on failure', () => {
+ renderPending([pending({ status: 'failed' })]);
+ expect(screen.getByText('com_ui_steer_failed_inline')).toBeInTheDocument();
+ expect(screen.getByText('com_ui_retry')).toBeInTheDocument();
+ expect(screen.getByText('com_ui_send_as_new')).toBeInTheDocument();
+ });
+
+ it('shows the quote count carried by a failed steer', () => {
+ renderPending([pending({ status: 'failed', quotes: ['first', 'second'] })]);
+
+ expect(screen.getByText('2')).toHaveAttribute('aria-hidden', 'true');
+ expect(screen.getByText('com_ui_queued_quote_count')).toHaveClass('sr-only');
+ });
+
+ it('locks recovery actions while a protocol-v1 delivery is uncertain', () => {
+ renderPending([
+ pending({
+ status: 'failed',
+ deliveryUncertain: true,
+ generationProtocolVersion: 1,
+ }),
+ ]);
+
+ expect(screen.getByText('com_ui_steer_delivery_uncertain')).toBeInTheDocument();
+ expect(screen.queryByText('com_ui_retry')).not.toBeInTheDocument();
+ expect(screen.queryByText('com_ui_send_as_new')).not.toBeInTheDocument();
+ });
+
+ it('offers only same-id retry for an uncertain protocol-v2 delivery', () => {
+ renderPending([
+ pending({
+ status: 'failed',
+ deliveryUncertain: true,
+ generationProtocolVersion: 2,
+ }),
+ ]);
+
+ expect(screen.getByText('com_ui_steer_delivery_uncertain')).toBeInTheDocument();
+ expect(screen.getByText('com_ui_retry')).toBeInTheDocument();
+ expect(screen.queryByText('com_ui_send_as_new')).not.toBeInTheDocument();
+ });
+
+ it('reclaims an acknowledged steer before moving it to the queue', async () => {
+ const steer = pending({ status: 'pending', steerId: 's-ack' });
+ renderPending([steer]);
+
+ fireEvent.click(screen.getByText('com_ui_convert_to_queue'));
+
+ await waitFor(() => expect(mockMoveToQueue).toHaveBeenCalledWith(steer));
+ });
+
+ it('reports when a steer reached the agent before it could be reclaimed', async () => {
+ mockMoveToQueue.mockResolvedValue('applied');
+ renderPending([pending({ status: 'pending' })]);
+
+ fireEvent.click(screen.getByText('com_ui_convert_to_queue'));
+
+ await waitFor(() =>
+ expect(mockShowToast).toHaveBeenCalledWith({
+ message: 'com_ui_steer_already_applied',
+ status: 'info',
+ }),
+ );
+ });
+
+ it('retries the failed steer by id', () => {
+ renderPending([pending({ status: 'failed', steerId: 's-failed' })]);
+ fireEvent.click(screen.getByText('com_ui_retry'));
+ expect(mockRetry).toHaveBeenCalledWith('s-failed');
+ expect(mockSendAsNew).not.toHaveBeenCalled();
+ });
+
+ it('sends the failed steer as new by id', () => {
+ renderPending([pending({ status: 'failed', steerId: 's-failed' })]);
+ fireEvent.click(screen.getByText('com_ui_send_as_new'));
+ expect(mockSendAsNew).toHaveBeenCalledWith('s-failed');
+ expect(mockRetry).not.toHaveBeenCalled();
+ });
+
+ it('returns a definitively failed steer whole so it can be corrected', () => {
+ const steer = pending({ status: 'failed', steerId: 's-failed', quotes: ['excerpt'] });
+ renderPending([steer]);
+ fireEvent.click(screen.getByText('com_ui_edit'));
+ /* Queued as a fallback it must wait for an explicit send: the server
+ refused this payload, so the run-end drain must not send it anyway. */
+ expect(mockRehome).toHaveBeenCalledWith(steer, { rejectedByServer: true });
+ expect(mockSendAsNew).not.toHaveBeenCalled();
+ expect(mockRetry).not.toHaveBeenCalled();
+ });
+
+ /* An uncertain delivery may still be held by the server, so every action that
+ assumes the words are the client's again stays hidden, editing included. */
+ it('withholds editing while delivery is uncertain', () => {
+ renderPending([pending({ status: 'failed', deliveryUncertain: true })]);
+ expect(screen.queryByText('com_ui_edit')).not.toBeInTheDocument();
+ });
+
+ /* The escalation control is the in-thread half of the `escalateSteer`
+ shortcut: it only exists on a steer the server can still be asked to
+ interrupt, so the shortcut never aims at a row that cannot act. */
+ describe('interrupt escalation', () => {
+ it('offers escalation on an acknowledged steer', () => {
+ renderPending([pending({ status: 'pending', steerId: 's-ack' })]);
+ expect(screen.getByTestId('steer-escalate-now')).toBeEnabled();
+ });
+
+ it('arms the steer by id, carrying its own generation', () => {
+ renderPending([pending({ status: 'pending', steerId: 's-ack', generationCreatedAt: 4141 })]);
+ fireEvent.click(screen.getByTestId('steer-escalate-now'));
+ expect(mockEscalate).toHaveBeenCalledWith(
+ {
+ steerId: 's-ack',
+ generationCreatedAt: 4141,
+ },
+ expect.any(Function),
+ );
+ });
+
+ /* Arming removes the control that was just activated, so a keyboard user
+ would be dropped on the document body in the middle of the thread. */
+ it('moves focus to the row`s cancel action once the arm is confirmed', () => {
+ renderPending([pending({ status: 'pending', steerId: 's-ack' })]);
+ fireEvent.click(screen.getByTestId('steer-escalate-now'));
+
+ const onArmed = mockEscalate.mock.calls[0][1] as () => void;
+ act(() => {
+ onArmed();
+ });
+
+ expect(screen.getByRole('button', { name: 'com_ui_cancel' })).toHaveFocus();
+ });
+
+ it.each([
+ ['still sending, so it has no server id to arm', { status: 'sending' as const }],
+ ['already interrupting', { status: 'pending' as const, preempt: true }],
+ ['failed, where retry is the offer instead', { status: 'failed' as const }],
+ ])('offers nothing on a steer that is %s', (_label, over) => {
+ renderPending([pending(over)]);
+ expect(screen.queryByTestId('steer-escalate-now')).not.toBeInTheDocument();
+ });
+
+ /* One interrupt at a time: a second arm would seal the same run twice. */
+ it('disables escalation while another steer is already interrupting', () => {
+ renderPending([
+ pending({ status: 'pending', steerId: 's-arming', preempt: true }),
+ pending({ status: 'pending', steerId: 's-other' }),
+ ]);
+ expect(screen.getByTestId('steer-escalate-now')).toBeDisabled();
+ });
+
+ /* Both an unresolved tool approval and a live `ask_user_question` suspend
+ the generation while keeping its submission slot occupied, so an arm
+ would be refused either way. Gating on approvals alone left this control
+ enabled through a question while the composer correctly refused. */
+ it('disables escalation while the run is paused on a question', () => {
+ const askAction = {
+ actionId: 'a1',
+ streamId: 's1',
+ createdAt: 0,
+ payload: { type: 'ask_user_question', question: { question: 'Which one?' } },
+ } as unknown as Agents.PendingAction;
+ const paused = applyPendingAction(
+ {
+ messageId: 'm1',
+ parentMessageId: 'root-user',
+ conversationId: CONVO_ID,
+ isCreatedByUser: false,
+ content: [],
+ } as unknown as TMessage,
+ askAction,
+ );
+ expect(hasLiveRunPause([paused])).toBe(true);
+ renderPending([pending({ status: 'pending', steerId: 's-paused' })], [paused]);
+ expect(screen.getByTestId('steer-escalate-now')).toBeDisabled();
+ });
+
+ it('ignores a pause on an inactive sibling branch', () => {
+ const root = {
+ messageId: 'root-user',
+ parentMessageId: '',
+ conversationId: CONVO_ID,
+ isCreatedByUser: true,
+ content: [],
+ } as unknown as TMessage;
+ const active = {
+ messageId: 'active',
+ parentMessageId: root.messageId,
+ conversationId: CONVO_ID,
+ isCreatedByUser: false,
+ content: [],
+ } as unknown as TMessage;
+ const inactive = {
+ messageId: 'inactive',
+ parentMessageId: root.messageId,
+ conversationId: CONVO_ID,
+ isCreatedByUser: false,
+ content: [
+ {
+ type: ContentTypes.TOOL_CALL,
+ tool_call: {
+ id: 'inactive-call',
+ name: 'shell',
+ approval: { actionId: 'inactive' },
+ output: '',
+ },
+ },
+ ],
+ } as unknown as TMessage;
+
+ renderPending([pending({ status: 'pending' })], [root, active, inactive], 1);
+ expect(screen.getByTestId('steer-escalate-now')).toBeEnabled();
+ });
+
+ it('disables escalation for a pause on the active sibling branch', () => {
+ const root = {
+ messageId: 'root-user',
+ parentMessageId: '',
+ conversationId: CONVO_ID,
+ isCreatedByUser: true,
+ content: [],
+ } as unknown as TMessage;
+ const active = {
+ messageId: 'active-approval',
+ parentMessageId: root.messageId,
+ conversationId: CONVO_ID,
+ isCreatedByUser: false,
+ content: [
+ {
+ type: ContentTypes.TOOL_CALL,
+ tool_call: {
+ id: 'active-call',
+ name: 'shell',
+ approval: { actionId: 'active' },
+ output: '',
+ },
+ },
+ ],
+ } as unknown as TMessage;
+ const inactive = {
+ messageId: 'inactive-no-pause',
+ parentMessageId: root.messageId,
+ conversationId: CONVO_ID,
+ isCreatedByUser: false,
+ content: [],
+ } as unknown as TMessage;
+
+ renderPending([pending({ status: 'pending' })], [root, active, inactive], 1);
+ expect(screen.getByTestId('steer-escalate-now')).toBeDisabled();
+ });
+
+ it('reads the pause from the branch its own pane has selected', () => {
+ const paused = {
+ messageId: 'root-paused',
+ parentMessageId: Constants.NO_PARENT,
+ conversationId: CONVO_ID,
+ isCreatedByUser: false,
+ content: [
+ {
+ type: ContentTypes.TOOL_CALL,
+ tool_call: {
+ id: 'root-call',
+ name: 'shell',
+ approval: { actionId: 'root' },
+ output: '',
+ },
+ },
+ ],
+ } as unknown as TMessage;
+ const plain = {
+ messageId: 'root-plain',
+ parentMessageId: Constants.NO_PARENT,
+ conversationId: CONVO_ID,
+ isCreatedByUser: false,
+ content: [],
+ } as unknown as TMessage;
+
+ renderPending([pending({ status: 'pending' })], [paused, plain], 1, {
+ index: 1,
+ siblingKeyId: CONVO_ID,
+ otherConversationId: 'other-conversation',
+ });
+ expect(screen.getByTestId('steer-escalate-now')).toBeDisabled();
+ });
+
+ it('keeps escalation off until the pane owns the rendered conversation', () => {
+ const plain = {
+ messageId: 'root-plain',
+ parentMessageId: Constants.NO_PARENT,
+ conversationId: CONVO_ID,
+ isCreatedByUser: false,
+ content: [],
+ } as unknown as TMessage;
+ const paused = {
+ messageId: 'root-paused',
+ parentMessageId: Constants.NO_PARENT,
+ conversationId: CONVO_ID,
+ isCreatedByUser: false,
+ content: [
+ {
+ type: ContentTypes.TOOL_CALL,
+ tool_call: {
+ id: 'root-call',
+ name: 'shell',
+ approval: { actionId: 'root' },
+ output: '',
+ },
+ },
+ ],
+ } as unknown as TMessage;
+
+ renderPending(
+ [pending({ status: 'pending' })],
+ [paused, plain],
+ 1,
+ undefined,
+ 'previous-conversation',
+ );
+ expect(screen.getByTestId('steer-escalate-now')).toBeDisabled();
+ });
+
+ it('labels a steer that is already interrupting', () => {
+ renderPending([pending({ status: 'pending', preempt: true })]);
+ expect(screen.getByText('com_ui_steer_in_flight_preempt')).toBeInTheDocument();
+ });
+ });
+});
diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/SteerPart.test.tsx b/client/src/components/Chat/Messages/Content/Parts/__tests__/SteerPart.test.tsx
index 53e973ebe1..25b6a15dbc 100644
--- a/client/src/components/Chat/Messages/Content/Parts/__tests__/SteerPart.test.tsx
+++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/SteerPart.test.tsx
@@ -1,6 +1,8 @@
import React from 'react';
import { RecoilRoot, useRecoilValue } from 'recoil';
+import { QueryKeys } from 'librechat-data-provider';
import { render, screen, fireEvent } from '@testing-library/react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import type { TMessage } from 'librechat-data-provider';
import { STEER_ICON } from '~/components/Chat/Steering/identity';
import SteerPart from '../SteerPart';
@@ -70,10 +72,15 @@ function renderPart(
* silently test the signed-in state instead of the anonymous share route. */
user: { name: string; username: string } | null = SEEDED_USER,
) {
+ const queryClient = new QueryClient();
+ queryClient.setQueryData([QueryKeys.endpoints], {});
+
return render(
- <RecoilRoot initializeState={({ set }) => user && set(store.user, user as never)}>
- <SteerPart steer="steered words" steerId="s1" createdAt={1} files={files} />
- </RecoilRoot>,
+ <QueryClientProvider client={queryClient}>
+ <RecoilRoot initializeState={({ set }) => user && set(store.user, user as never)}>
+ <SteerPart steer="steered words" steerId="s1" createdAt={1} files={files} />
+ </RecoilRoot>
+ </QueryClientProvider>,
);
}
diff --git a/client/src/components/Chat/Messages/Content/ToolCallLimitNotice.tsx b/client/src/components/Chat/Messages/Content/ToolCallLimitNotice.tsx
index 4695393f3f..a28501adf7 100644
--- a/client/src/components/Chat/Messages/Content/ToolCallLimitNotice.tsx
+++ b/client/src/components/Chat/Messages/Content/ToolCallLimitNotice.tsx
@@ -60,7 +60,15 @@ export default function ToolCallLimitNotice({ message }: { message: TMessage })
* staged in the composer. The agent and MCP server selection remains in scope.
*/
const recover = (text: string) =>
- chat?.ask({ text }, { overrideFiles: [], overrideManualSkills: [], overrideQuotes: [] });
+ chat?.ask(
+ { text },
+ {
+ overrideFiles: [],
+ overrideManualSkills: [],
+ overrideQuotes: [],
+ overrideReasoning: null,
+ },
+ );
return (
<div
diff --git a/client/src/components/Chat/Messages/Content/__tests__/ContentParts.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ContentParts.test.tsx
index 1faae36721..63f12ca082 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/ContentParts.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/ContentParts.test.tsx
@@ -188,7 +188,7 @@ beforeEach(() => {
.mockImplementation((parts) => parts.map((part) => ({ type: 'single', part })));
});
-describe('ContentParts — interim skill cards', () => {
+describe('ContentParts: interim skill cards', () => {
it('renders stateful workspace changes once at message level', () => {
const content: TMessageContentParts[] = [
{ type: ContentTypes.TEXT, text: 'done' } as TMessageContentParts,
@@ -308,7 +308,7 @@ describe('ContentParts — interim skill cards', () => {
});
});
-describe('ContentParts — thinking-dot header alignment', () => {
+describe('ContentParts: thinking-dot header alignment', () => {
const submittingProps = { ...baseProps, isSubmitting: true, isLatestMessage: true };
const memoryAttachment = {
type: Tools.memory,
@@ -363,7 +363,7 @@ describe('ContentParts — thinking-dot header alignment', () => {
});
});
-describe('ContentParts — post-steer author re-attribution', () => {
+describe('ContentParts: post-steer author re-attribution', () => {
const steerPart = {
type: ContentTypes.STEER,
steer: 'go left',
@@ -728,7 +728,7 @@ describe('ContentParts — activity phase state', () => {
});
});
-describe('ContentParts — settled content identity across compaction', () => {
+describe('ContentParts: settled content identity across compaction', () => {
/** Mirrors a captured run: the aggregator leaves holes at the source indexes
* of steps that produced nothing, and `finalHandler` swaps in the server's
* compacted array. Without the streamed-index stamp every index-derived key
diff --git a/client/src/components/Chat/Messages/Content/__tests__/ToolCallLimitNotice.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ToolCallLimitNotice.test.tsx
index 90606209c3..9e12115639 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/ToolCallLimitNotice.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/ToolCallLimitNotice.test.tsx
@@ -75,6 +75,7 @@ describe('ToolCallLimitNotice', () => {
overrideFiles: [],
overrideManualSkills: [],
overrideQuotes: [],
+ overrideReasoning: null,
},
);
});
@@ -93,6 +94,7 @@ describe('ToolCallLimitNotice', () => {
overrideFiles: [],
overrideManualSkills: [],
overrideQuotes: [],
+ overrideReasoning: null,
},
);
});
diff --git a/client/src/components/Chat/Messages/MessagesView.tsx b/client/src/components/Chat/Messages/MessagesView.tsx
index 58e76476af..d5d666813a 100644
--- a/client/src/components/Chat/Messages/MessagesView.tsx
+++ b/client/src/components/Chat/Messages/MessagesView.tsx
@@ -14,7 +14,7 @@ import { MessagesViewProvider, useChatContext, useFileMapContext } from '~/Provi
import { RowMountProvider, useProgressiveRowMount } from '~/hooks/Messages';
import { useChatSurface } from '~/components/Chat/Subagents/surface';
import useThreadRows from '~/hooks/Messages/useThreadRows';
-import { steerOverlayHeightFamily } from '~/store/steer';
+import PendingSteers from './Content/Parts/PendingSteers';
import { autoScrollAtom } from '~/store/autoScroll';
import { FLAT_THREAD, ThreadList } from './Thread';
import { fontSizeAtom } from '~/store/fontSize';
@@ -52,7 +52,7 @@ function MessagesViewContent({
const { conversationId } = conversation ?? {};
const fileMap = useFileMapContext();
const threadRows = useThreadRows(FLAT_THREAD ? messages : null, conversationId, fileMap);
- const { index, latestMessageId, latestMessageDepth } = useChatContext();
+ const { index, latestMessageId, latestMessageDepth, messagesKey } = useChatContext();
const isSubmitting = useRecoilValue(store.isSubmittingFamily(index));
const { showScrollButton, maximizeChatSpace } = useChatSurface();
const autoScroll = useAtomValue(autoScrollAtom);
@@ -107,8 +107,9 @@ function MessagesViewContent({
/** Re-arm from the conversation that owns the RENDERED tree: the Recoil
* conversation id lags the route during warm-cache navigation, and keying
* off it would first mount the new tree unwindowed, then narrow it after
- * the fact — visibly unmounting rows the user is already reading. */
- const treeConversationId = _messagesTree?.[0]?.conversationId ?? conversationId;
+ * the fact, visibly unmounting rows the user is already reading. An empty
+ * tree has no message to name its owner, so the route's key stands in. */
+ const treeConversationId = _messagesTree?.[0]?.conversationId ?? (messagesKey || conversationId);
const mountWindow = useProgressiveRowMount({
tailDepth: latestMessageDepth,
anchorBottom: autoScroll || isSubmitting,
@@ -123,12 +124,12 @@ function MessagesViewContent({
}
}, [latestMessageId, measureNearBottom, mountWindow, reportNearBottom, _messagesTree]);
- /** The in-flight steer overlay floats above the composer over the bottom of
- * the thread (see `InFlightSteers`); reserve an equal band here so the
- * newest message rests above it and older ones scroll behind. */
+ /* The redesign renders pending steers inside the streaming reply rather than
+ as a stack floating over the bottom of the thread, so there is no band to
+ reserve here and nothing publishes an overlay height. Composer panels that
+ do float (an answer popover, a tool-approval review) are handled by
+ ScrollButton through `composerOverlayCountFamily`. */
const overlayConversationId = conversationId ?? Constants.NEW_CONVO;
- const steerOverlayHeight = useAtomValue(steerOverlayHeightFamily(overlayConversationId));
-
return (
<>
<div className="relative flex-1 overflow-hidden overflow-y-auto">
@@ -147,15 +148,7 @@ function MessagesViewContent({
overflowAnchor: mountWindow != null ? 'none' : undefined,
}}
>
- <div
- ref={contentRef}
- className="flex flex-col pt-14 pb-9"
- style={
- steerOverlayHeight > 0
- ? { paddingBottom: `calc(2.25rem + ${steerOverlayHeight}px)` }
- : undefined
- }
- >
+ <div ref={contentRef} className="flex flex-col pt-14 pb-9">
{(_messagesTree && _messagesTree.length == 0) || _messagesTree === null ? (
<div
className={cn(
@@ -192,6 +185,19 @@ function MessagesViewContent({
/>
</>
)}
+ {/** The pending surface is renderer-independent: both ThreadList
+ * and MultiMessage end at this shared thread tail. Keeping its
+ * mount here also preserves recovery controls when the message
+ * tree is temporarily empty during navigation or delivery.
+ *
+ * It keys off the RENDERED tree for the same reason the mount
+ * window does: during warm-cache navigation the Recoil
+ * conversation id still names the source chat, and its Cancel
+ * and Escalate actions would mutate that run while sitting at
+ * the destination thread's tail. */}
+ {treeConversationId != null && (
+ <PendingSteers conversationId={treeConversationId} index={index} />
+ )}
<div id="messages-end" className="group h-0 w-full shrink-0" ref={messagesEndRef} />
</div>
</div>
@@ -204,7 +210,6 @@ function MessagesViewContent({
messagesEndRef={messagesEndRef}
scrollHandler={handleSmoothToRef}
onNearBottomChange={handleNearBottom}
- overlayHeight={steerOverlayHeight}
/>
<MessageNav scrollableRef={scrollableRef} />
diff --git a/client/src/components/Chat/Messages/ScrollButton.tsx b/client/src/components/Chat/Messages/ScrollButton.tsx
index 39da1701a9..747f94d0b3 100644
--- a/client/src/components/Chat/Messages/ScrollButton.tsx
+++ b/client/src/components/Chat/Messages/ScrollButton.tsx
@@ -16,9 +16,11 @@ const visibilityDebounceRate = 150;
* Stands down while a composer panel (an `ask_user_question` popover, a
* tool-approval review) is open over the bottom of the thread: the panel
* floats up from the composer and the button up from the thread's edge, so
- * the two would meet on the panel's footer. The in-flight steer stack is the
- * one overlay the button lifts clear of instead — it publishes its height as
- * `overlayHeight` and stays short enough for that to read well.
+ * the two would meet on the panel's footer.
+ *
+ * `overlayHeight` lifts the button clear of a short overlay that floats over
+ * the thread's bottom edge. Nothing publishes one since pending steers moved
+ * inside the streaming reply, so it defaults to no lift.
*/
const ScrollButton = memo(function ScrollButton({
conversationId,
@@ -28,7 +30,7 @@ const ScrollButton = memo(function ScrollButton({
messagesEndRef,
scrollHandler,
onNearBottomChange,
- overlayHeight,
+ overlayHeight = 0,
}: {
conversationId: string;
/** The user's show-scroll-button preference, handed down by the host. */
@@ -39,7 +41,7 @@ const ScrollButton = memo(function ScrollButton({
messagesEndRef: React.RefObject<HTMLDivElement | null>;
scrollHandler: (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void;
onNearBottomChange: (isNearBottom: boolean) => void;
- overlayHeight: number;
+ overlayHeight?: number;
}) {
const panelOpen = useAtomValue(composerOverlayCountFamily(conversationId)) > 0;
const [showScrollButton, setShowScrollButton] = useState(false);
diff --git a/client/src/components/Chat/Messages/__tests__/MessagesView.spec.tsx b/client/src/components/Chat/Messages/__tests__/MessagesView.spec.tsx
new file mode 100644
index 0000000000..6d87d0c508
--- /dev/null
+++ b/client/src/components/Chat/Messages/__tests__/MessagesView.spec.tsx
@@ -0,0 +1,141 @@
+import React from 'react';
+import { render, screen } from '@testing-library/react';
+import type { TMessage } from 'librechat-data-provider';
+
+let mockMessagesKey = 'convo-1';
+
+jest.mock('jotai', () => ({
+ ...jest.requireActual('jotai'),
+ useAtomValue: () => false,
+}));
+
+jest.mock('recoil', () => ({
+ useRecoilValue: () => false,
+}));
+
+jest.mock('~/hooks', () => ({
+ useScreenshot: () => ({ screenshotTargetRef: { current: null } }),
+ useMessageScrolling: () => ({
+ conversation: { conversationId: 'convo-1' },
+ contentRef: { current: null },
+ scrollableRef: { current: null },
+ messagesEndRef: { current: null },
+ handleSmoothToRef: jest.fn(),
+ debouncedHandleScroll: jest.fn(),
+ handleNearBottomChange: jest.fn(),
+ }),
+ useScrollbarGutter: jest.fn(),
+ useConversationSeen: () => jest.fn(),
+ useLocalize: () => (key: string) => key,
+}));
+
+jest.mock('~/Providers', () => ({
+ MessagesViewProvider: ({ children }: { children: React.ReactNode }) => <>{children}</>,
+ useChatContext: () => ({ index: 0, latestMessageDepth: 0, messagesKey: mockMessagesKey }),
+ useFileMapContext: () => ({}),
+}));
+
+jest.mock('~/hooks/Messages', () => ({
+ RowMountProvider: ({ children }: { children: React.ReactNode }) => <>{children}</>,
+ useProgressiveRowMount: () => null,
+}));
+
+jest.mock('~/hooks/Messages/useThreadRows', () => ({
+ __esModule: true,
+ default: () => [],
+}));
+
+jest.mock('~/components/Chat/Subagents/surface', () => ({
+ useChatSurface: () => ({ showScrollButton: false, maximizeChatSpace: false }),
+}));
+
+jest.mock('~/store/autoScroll', () => ({ autoScrollAtom: {} }));
+jest.mock('~/store', () => ({
+ __esModule: true,
+ default: { isSubmittingFamily: () => ({}) },
+}));
+
+jest.mock('../Thread', () => ({
+ FLAT_THREAD: false,
+ ThreadList: () => <div data-testid="flat-thread" />,
+}));
+
+jest.mock('../MultiMessage', () => ({
+ __esModule: true,
+ default: () => <div data-testid="multi-message" />,
+}));
+
+jest.mock('../Content/Parts/PendingSteers', () => ({
+ __esModule: true,
+ default: ({ conversationId }: { conversationId: string }) => (
+ <div data-testid="pending-steers" data-conversation-id={conversationId} />
+ ),
+}));
+
+jest.mock('../PendingTurn', () => ({
+ __esModule: true,
+ default: () => null,
+}));
+jest.mock('../ScrollButton', () => ({
+ __esModule: true,
+ default: () => null,
+}));
+jest.mock('../MessageNav', () => ({
+ __esModule: true,
+ default: () => null,
+}));
+
+jest.mock('~/utils', () => ({
+ cn: (...classes: Array<string | false | null | undefined>) => classes.filter(Boolean).join(' '),
+}));
+
+import MessagesView from '../MessagesView';
+
+const messageTree = [
+ {
+ messageId: 'assistant-1',
+ conversationId: 'convo-1',
+ },
+] as unknown as TMessage[];
+
+describe('MessagesView pending steers', () => {
+ beforeEach(() => {
+ mockMessagesKey = 'convo-1';
+ });
+
+ it('keeps the failed-steer surface mounted in the recursive renderer', () => {
+ render(<MessagesView messagesTree={messageTree} messages={messageTree} />);
+
+ expect(screen.getByTestId('multi-message')).toBeInTheDocument();
+ expect(screen.getByTestId('pending-steers')).toHaveAttribute('data-conversation-id', 'convo-1');
+ expect(screen.queryByTestId('flat-thread')).not.toBeInTheDocument();
+ });
+
+ it('keys the pending surface to the rendered tree, not the lagging context', () => {
+ /** Warm-cache navigation renders the destination tree while the Recoil
+ * conversation still names the source chat. Cancel and Escalate must act
+ * on the run the reader is looking at. */
+ const destinationTree = [
+ { messageId: 'assistant-2', conversationId: 'convo-2' },
+ ] as unknown as TMessage[];
+
+ render(<MessagesView messagesTree={destinationTree} messages={destinationTree} />);
+
+ expect(screen.getByTestId('pending-steers')).toHaveAttribute('data-conversation-id', 'convo-2');
+ });
+
+ it('keeps recovery visible while the message tree is temporarily empty', () => {
+ render(<MessagesView messagesTree={[]} messages={[]} />);
+
+ expect(screen.getByTestId('pending-steers')).toHaveAttribute('data-conversation-id', 'convo-1');
+ });
+
+ it('keys an empty destination to the route, not the lagging context', () => {
+ /** Warm navigation to a chat whose tree is still empty: no message names the
+ * destination, and the context still names the source run. */
+ mockMessagesKey = 'convo-2';
+ render(<MessagesView messagesTree={[]} messages={[]} />);
+
+ expect(screen.getByTestId('pending-steers')).toHaveAttribute('data-conversation-id', 'convo-2');
+ });
+});
diff --git a/client/src/components/Chat/__tests__/ChatView.spec.tsx b/client/src/components/Chat/__tests__/ChatView.spec.tsx
index e44ebf3302..1be3ca02a8 100644
--- a/client/src/components/Chat/__tests__/ChatView.spec.tsx
+++ b/client/src/components/Chat/__tests__/ChatView.spec.tsx
@@ -5,6 +5,7 @@ import ChatView from '../ChatView';
const mockParams = jest.fn();
const mockConversation = jest.fn();
+const mockChatFormProps = jest.fn();
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
@@ -49,7 +50,13 @@ jest.mock('../Footer', () => ({
}));
jest.mock('../Landing', () => ({ __esModule: true, default: () => <div /> }));
jest.mock('../Messages/MessagesView', () => ({ __esModule: true, default: () => <div /> }));
-jest.mock('../Input/ChatForm', () => ({ __esModule: true, default: () => <div /> }));
+jest.mock('../Input/ChatForm', () => ({
+ __esModule: true,
+ default: (props: Record<string, unknown>) => {
+ mockChatFormProps(props);
+ return <div />;
+ },
+}));
jest.mock('../Input/ConversationStarters', () => ({ __esModule: true, default: () => <div /> }));
describe('ChatView page heading', () => {
@@ -116,6 +123,44 @@ describe('ChatView page heading', () => {
});
});
+describe('ChatView composer preferences', () => {
+ beforeEach(() => {
+ mockParams.mockReturnValue({});
+ mockConversation.mockReturnValue(null);
+ mockChatFormProps.mockClear();
+ localStorage.clear();
+ });
+
+ /** ChatForm used to read this preference itself via `useRecoilValue(store.enterToSend)`,
+ * reaching into app-global state the composer only consumes. ChatView now owns the
+ * read and passes it down, the same boundary `showComposerTips` already follows. */
+ test('reads the persisted enterToSend preference and passes it into ChatForm', () => {
+ localStorage.setItem('enterToSend', JSON.stringify(false));
+
+ render(<ChatView />);
+
+ expect(mockChatFormProps).toHaveBeenCalledWith(expect.objectContaining({ enterToSend: false }));
+ });
+
+ /** The same boundary for the dictation preferences: ChatForm consumes them
+ * but ChatView owns the reads. */
+ test('passes the persisted Auto Send Text preference and the speech init state', () => {
+ localStorage.setItem('autoSendText', JSON.stringify(3));
+
+ render(<ChatView />);
+
+ expect(mockChatFormProps).toHaveBeenCalledWith(
+ expect.objectContaining({ autoSendText: 3, speechSettingsInitialized: false }),
+ );
+ });
+
+ test('falls back to the atom default when nothing is persisted', () => {
+ render(<ChatView />);
+
+ expect(mockChatFormProps).toHaveBeenCalledWith(expect.objectContaining({ enterToSend: true }));
+ });
+});
+
describe('ChatView composer column', () => {
beforeEach(() => {
mockParams.mockReturnValue({ conversationId: 'convo-1' });
diff --git a/client/src/components/Chat/__tests__/ChatView.subagent.spec.tsx b/client/src/components/Chat/__tests__/ChatView.subagent.spec.tsx
index 310c773cb0..f8527fa1d2 100644
--- a/client/src/components/Chat/__tests__/ChatView.subagent.spec.tsx
+++ b/client/src/components/Chat/__tests__/ChatView.subagent.spec.tsx
@@ -49,6 +49,7 @@ jest.mock('~/Providers', () => {
ChatContext: Context,
AddedChatContext: Context,
ChatFormProvider: Passthrough,
+ ComposerRestoreProvider: Passthrough,
useFileMapContext: () => new Map(),
};
});
diff --git a/client/src/components/Chat/approval/Review.tsx b/client/src/components/Chat/approval/Review.tsx
index 75dbca58ab..679b568b54 100644
--- a/client/src/components/Chat/approval/Review.tsx
+++ b/client/src/components/Chat/approval/Review.tsx
@@ -95,12 +95,15 @@ export const PendingToolApprovalPanel = memo(function PendingToolApprovalPanel({
return (
<div
id="pending-tool-approval-panel"
- className="absolute bottom-28 z-10 w-full"
+ /* The absolute review layer spans the composer width, but only its card
+ * is painted and interactive. Let the thread receive clicks through the
+ * transparent remainder of the layer. */
+ className="pointer-events-none absolute bottom-28 z-10 w-full"
role="region"
aria-labelledby="pending-tool-approval-title"
aria-live="polite"
>
- <div className="popover border-border-light bg-surface-primary-alt flex max-h-[70vh] flex-col rounded-2xl border shadow-lg">
+ <div className="popover border-border-light bg-surface-primary-alt pointer-events-auto flex max-h-[70vh] flex-col rounded-2xl border shadow-lg">
<div className="border-border-light flex shrink-0 items-center justify-between gap-2 border-b px-3 py-2">
<p id="pending-tool-approval-title" className="text-text-primary text-sm font-medium">
{localize(reviews.length === 1 ? 'com_ui_review_action' : 'com_ui_review_actions', {
diff --git a/client/src/components/Nav/AccountSettings.tsx b/client/src/components/Nav/AccountSettings.tsx
index 35d5c37bc6..f350491c9f 100644
--- a/client/src/components/Nav/AccountSettings.tsx
+++ b/client/src/components/Nav/AccountSettings.tsx
@@ -1,4 +1,5 @@
import { useState, memo, useRef } from 'react';
+import { useSetAtom } from 'jotai';
import { useSetRecoilState } from 'recoil';
import * as Menu from '@ariakit/react/menu';
import { GearIcon, DropdownMenuSeparator, Avatar } from '@librechat/client';
@@ -6,6 +7,7 @@ import {
Archive,
ChevronRight,
CircleHelp,
+ Files,
Keyboard,
LifeBuoy,
LogOut,
@@ -13,6 +15,7 @@ import {
ShieldCheck,
} from 'lucide-react';
import { ArchivedChatsModal } from '~/components/Nav/SettingsTabs/General/ArchivedChatsModal';
+import { filesDialogTriggerAtom, showFilesDialogAtom } from '~/store/filesDialog';
import { useGetStartupConfig, useGetUserBalance } from '~/data-provider';
import { useAuthContext } from '~/hooks/AuthContext';
import { openInNewTab } from '~/utils';
@@ -99,6 +102,8 @@ function AccountSettings({ collapsed = false }: { collapsed?: boolean }) {
enabled: !!isAuthenticated && startupConfig?.balance?.enabled,
});
const [showSettings, setShowSettings] = useState(false);
+ const setShowFiles = useSetAtom(showFilesDialogAtom);
+ const setFilesDialogTrigger = useSetAtom(filesDialogTriggerAtom);
const setShowShortcutsDialog = useSetRecoilState(store.showShortcutsDialog);
const [showArchived, setShowArchived] = useState(false);
const accountSettingsButtonRef = useRef<HTMLButtonElement>(null);
@@ -160,6 +165,21 @@ function AccountSettings({ collapsed = false }: { collapsed?: boolean }) {
<Archive className="icon-md" aria-hidden="true" />
{localize('com_nav_archived_chats')}
</Menu.MenuItem>
+
+ <Menu.MenuItem
+ onClick={() => {
+ /** The menu is gone by the time the dialog captures focus, so the
+ * account button has to be named here or focus returns to the
+ * document body when the dialog closes. */
+ setFilesDialogTrigger(accountSettingsButtonRef);
+ setShowFiles(true);
+ }}
+ className="select-item text-sm"
+ data-testid="nav-files"
+ >
+ <Files className="icon-md" aria-hidden="true" />
+ {localize('com_nav_my_files')}
+ </Menu.MenuItem>
<Menu.MenuItem
onClick={() => setShowSettings(true)}
className="select-item text-sm"
diff --git a/client/src/components/Nav/KeyboardShortcutsDialog.tsx b/client/src/components/Nav/KeyboardShortcutsDialog.tsx
index 0c06278fbd..fbc4d4cf6c 100644
--- a/client/src/components/Nav/KeyboardShortcutsDialog.tsx
+++ b/client/src/components/Nav/KeyboardShortcutsDialog.tsx
@@ -1,6 +1,6 @@
import { memo, useCallback, useId, useMemo, useState } from 'react';
import { Plus, X } from 'lucide-react';
-import { useRecoilState } from 'recoil';
+import { useRecoilState, useRecoilValue } from 'recoil';
import {
Label,
Switch,
@@ -24,6 +24,29 @@ type GroupedBindings = Record<string, ShortcutBindingInfo[]>;
const PANELS_GROUP = 'com_shortcut_group_panels';
+const PLAIN_ENTER: ShortcutBinding = {
+ meta: false,
+ ctrl: false,
+ alt: false,
+ shift: false,
+ key: 'Enter',
+};
+
+/**
+ * What the composer actually submits on. With "Enter to send" active, plain
+ * Enter is the submit key and the registered modifier chord writes a newline
+ * there instead, so advertising the chord would name an action it does not
+ * perform where the user would reach for it. The binding itself is untouched:
+ * only its presentation follows the preference, so rebinding and conflict
+ * detection still operate on the real chord.
+ */
+function displayedBinding(info: ShortcutBindingInfo, enterToSend: boolean): ShortcutBinding | null {
+ if (info.id !== 'submitMessage' || info.isCustom || !enterToSend) {
+ return info.binding;
+ }
+ return PLAIN_ENTER;
+}
+
function EditingRow({
info,
label,
@@ -110,7 +133,11 @@ function ShortcutRow({
}) {
const localize = useLocalize();
const label = localize(info.labelKey as TranslationKeys);
- const displayKeys = useMemo(() => bindingDisplayKeys(info.binding, isMac), [info.binding]);
+ const enterToSend = useRecoilValue<boolean>(store.enterToSend);
+ const displayKeys = useMemo(
+ () => bindingDisplayKeys(displayedBinding(info, enterToSend), isMac),
+ [info, enterToSend],
+ );
const editAriaLabel = localize('com_shortcut_edit_aria', { 0: label });
const isUnset = displayKeys.length === 0;
diff --git a/client/src/components/Nav/Settings/registry.tsx b/client/src/components/Nav/Settings/registry.tsx
index df6568e7d8..019d69dd92 100644
--- a/client/src/components/Nav/Settings/registry.tsx
+++ b/client/src/components/Nav/Settings/registry.tsx
@@ -49,6 +49,7 @@ import { RevokeKeys } from '../SettingsTabs/Data/RevokeKeys';
import { ClearChats } from '../SettingsTabs/Data/ClearChats';
import { TokenCredits, AutoRefill } from './BillingControls';
import AdminPanel from '../SettingsTabs/General/AdminPanel';
+import { showComposerTipsAtom } from '~/store/composerTips';
import SharedLinks from '../SettingsTabs/Data/SharedLinks';
import ImageResize from '../SettingsTabs/Chat/ImageResize';
import Passkeys from '../SettingsTabs/Account/Passkeys';
@@ -146,6 +147,17 @@ export const registry: SettingEntry[] = [
switchId: 'centerFormOnLanding',
}),
},
+ {
+ id: 'showComposerTips',
+ tab: GENERAL,
+ section: 'layout',
+ labelKey: 'com_nav_composer_tips',
+ Component: toggleControl({
+ stateAtom: showComposerTipsAtom,
+ localizationKey: 'com_nav_composer_tips',
+ switchId: 'showComposerTips',
+ }),
+ },
{
id: 'showScrollButton',
tab: GENERAL,
diff --git a/client/src/components/SidePanel/Files/Panel.tsx b/client/src/components/SidePanel/Files/Panel.tsx
deleted file mode 100644
index f3b2dbfd2c..0000000000
--- a/client/src/components/SidePanel/Files/Panel.tsx
+++ /dev/null
@@ -1,14 +0,0 @@
-import type { TFile } from 'librechat-data-provider';
-import { useGetFiles } from '~/data-provider';
-import { columns } from './PanelColumns';
-import DataTable from './PanelTable';
-
-export default function FilesPanel() {
- const { data: files = [] } = useGetFiles<TFile[]>();
-
- return (
- <div className="h-auto w-full px-3 pb-3 pt-2">
- <DataTable columns={columns} data={files} />
- </div>
- );
-}
diff --git a/client/src/components/SidePanel/Files/PanelColumns.tsx b/client/src/components/SidePanel/Files/PanelColumns.tsx
deleted file mode 100644
index ee72015c2b..0000000000
--- a/client/src/components/SidePanel/Files/PanelColumns.tsx
+++ /dev/null
@@ -1,58 +0,0 @@
-/* eslint-disable react-hooks/rules-of-hooks */
-import { ArrowUpDown } from 'lucide-react';
-import { Button } from '@librechat/client';
-import type { ColumnDef } from '@tanstack/react-table';
-import type { TFile } from 'librechat-data-provider';
-import PanelFileCell from './PanelFileCell';
-import { useLocalize } from '~/hooks';
-import { formatDate } from '~/utils';
-
-export const columns: ColumnDef<TFile | undefined>[] = [
- {
- accessorKey: 'filename',
- header: ({ column }) => {
- const localize = useLocalize();
- return (
- <Button
- variant="ghost"
- className="hover:bg-surface-hover"
- onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
- aria-label={localize('com_ui_name')}
- >
- {localize('com_ui_name')}
- <ArrowUpDown className="ml-2 h-4 w-4" aria-hidden="true" />
- </Button>
- );
- },
- meta: {
- size: '150px',
- },
- cell: ({ row }) => <PanelFileCell row={row} />,
- },
- {
- accessorKey: 'updatedAt',
- meta: {
- size: '10%',
- },
- header: ({ column }) => {
- const localize = useLocalize();
- return (
- <Button
- variant="ghost"
- size="sm"
- className="h-auto px-1 py-0.5 hover:bg-surface-hover"
- onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
- aria-label={localize('com_ui_date')}
- >
- {localize('com_ui_date')}
- <ArrowUpDown className="ml-1 h-3 w-3" />
- </Button>
- );
- },
- cell: ({ row }) => (
- <span className="flex justify-end text-xs">
- {formatDate(row.original?.updatedAt?.toString() ?? '')}
- </span>
- ),
- },
-];
diff --git a/client/src/components/SidePanel/Files/PanelFileCell.tsx b/client/src/components/SidePanel/Files/PanelFileCell.tsx
deleted file mode 100644
index 5552be5645..0000000000
--- a/client/src/components/SidePanel/Files/PanelFileCell.tsx
+++ /dev/null
@@ -1,28 +0,0 @@
-import type { TFile } from 'librechat-data-provider';
-import type { Row } from '@tanstack/react-table';
-import ImagePreview from '~/components/Chat/Input/Files/ImagePreview';
-import FilePreview from '~/components/Chat/Input/Files/FilePreview';
-import { getFileType } from '~/utils';
-
-export default function PanelFileCell({ row }: { row: Row<TFile | undefined> }) {
- const file = row.original;
- return (
- <div className="flex w-full items-center gap-2">
- {file?.type?.startsWith('image') === true ? (
- <ImagePreview
- url={file.filepath}
- className="h-8 w-8 shrink-0"
- source={file.source}
- alt={file.filename}
- />
- ) : (
- <FilePreview fileType={getFileType(file?.type)} file={file} />
- )}
- <div className="min-w-0 flex-1 overflow-hidden">
- <span className="block w-full truncate overflow-hidden text-xs text-ellipsis whitespace-nowrap">
- {file?.filename}
- </span>
- </div>
- </div>
- );
-}
diff --git a/client/src/components/SidePanel/Files/PanelTable.tsx b/client/src/components/SidePanel/Files/PanelTable.tsx
deleted file mode 100644
index 6f038bdaf6..0000000000
--- a/client/src/components/SidePanel/Files/PanelTable.tsx
+++ /dev/null
@@ -1,397 +0,0 @@
-import { useState, useCallback, useMemo, useRef } from 'react';
-import { useSetRecoilState } from 'recoil';
-import { ArrowUpLeft } from 'lucide-react';
-import {
- Table,
- Button,
- TableRow,
- TableHead,
- TableBody,
- TableCell,
- FilterInput,
- TableHeader,
- useToastContext,
-} from '@librechat/client';
-import {
- flexRender,
- getCoreRowModel,
- getFilteredRowModel,
- getPaginationRowModel,
- getSortedRowModel,
- useReactTable,
- type ColumnDef,
- type SortingState,
- type VisibilityState,
- type ColumnFiltersState,
-} from '@tanstack/react-table';
-import {
- megabyte,
- Constants,
- EToolResources,
- mergeFileConfig,
- checkOpenAIStorage,
- isEphemeralAgentId,
- isAssistantsEndpoint,
- getEndpointFileConfig,
- defaultAgentCapabilities,
- fileConfig as defaultFileConfig,
-} from 'librechat-data-provider';
-import type { TFile } from 'librechat-data-provider';
-import { useLocalize, useUpdateFiles, useGetAgentsConfig, useAgentCapabilities } from '~/hooks';
-import { MyFilesModal } from '~/components/Chat/Input/Files/MyFilesModal';
-import { useFileMapContext, useChatContext } from '~/Providers';
-import { useGetFileConfig } from '~/data-provider';
-import { ephemeralAgentByConvoId } from '~/store';
-
-interface DataTableProps<TData, TValue> {
- columns: ColumnDef<TData, TValue>[];
- data: TData[];
-}
-
-export default function DataTable<TData, TValue>({ columns, data }: DataTableProps<TData, TValue>) {
- const localize = useLocalize();
- const [sorting, setSorting] = useState<SortingState>([]);
- const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([]);
- const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({});
- const [{ pageIndex, pageSize }, setPagination] = useState({ pageIndex: 0, pageSize: 10 });
- const [showFilesModal, setShowFilesModal] = useState(false);
- const manageFilesRef = useRef<HTMLButtonElement>(null);
-
- const pagination = useMemo(
- () => ({
- pageIndex,
- pageSize,
- }),
- [pageIndex, pageSize],
- );
-
- const table = useReactTable({
- data,
- columns,
- state: {
- sorting,
- columnFilters,
- columnVisibility,
- pagination,
- },
- onSortingChange: setSorting,
- onPaginationChange: setPagination,
- getCoreRowModel: getCoreRowModel(),
- getSortedRowModel: getSortedRowModel(),
- onColumnFiltersChange: setColumnFilters,
- getFilteredRowModel: getFilteredRowModel(),
- onColumnVisibilityChange: setColumnVisibility,
- getPaginationRowModel: getPaginationRowModel(),
- defaultColumn: {
- minSize: 0,
- size: 10,
- maxSize: 10,
- enableResizing: true,
- },
- });
-
- const fileMap = useFileMapContext();
- const { showToast } = useToastContext();
- const { files, setFiles, conversation } = useChatContext();
- const { data: fileConfig = null } = useGetFileConfig({
- select: (data) => mergeFileConfig(data),
- });
- const { addFile } = useUpdateFiles(setFiles);
- const setEphemeralAgent = useSetRecoilState(
- ephemeralAgentByConvoId(conversation?.conversationId ?? Constants.NEW_CONVO),
- );
- const { agentsConfig } = useGetAgentsConfig();
- const capabilities = useAgentCapabilities(agentsConfig?.capabilities ?? defaultAgentCapabilities);
-
- const handleFileClick = useCallback(
- (file: TFile) => {
- if (!fileMap?.[file.file_id] || !conversation?.endpoint) {
- showToast({
- message: localize('com_ui_attach_error'),
- status: 'error',
- });
- return;
- }
-
- const fileData = fileMap[file.file_id];
- const endpoint = conversation.endpoint;
- const endpointType = conversation.endpointType;
-
- if (!fileData.source) {
- return;
- }
-
- const isOpenAIStorage = checkOpenAIStorage(fileData.source);
- const isAssistants = isAssistantsEndpoint(endpoint);
-
- if (isOpenAIStorage && !isAssistants) {
- showToast({
- message: localize('com_ui_attach_error_openai'),
- status: 'error',
- });
- return;
- }
-
- if (!isOpenAIStorage && isAssistants) {
- showToast({
- message: localize('com_ui_attach_warn_endpoint'),
- status: 'warning',
- });
- }
-
- const endpointFileConfig = getEndpointFileConfig({
- fileConfig,
- endpoint,
- endpointType,
- });
-
- if (endpointFileConfig.disabled === true) {
- showToast({
- message: localize('com_ui_attach_error_disabled'),
- status: 'error',
- });
- return;
- }
-
- if (endpointFileConfig.fileLimit && files.size >= endpointFileConfig.fileLimit) {
- showToast({
- message: `${localize('com_ui_attach_error_limit')} ${endpointFileConfig.fileLimit} files (${endpoint})`,
- status: 'error',
- });
- return;
- }
-
- if (fileData.bytes >= (endpointFileConfig.fileSizeLimit ?? Number.MAX_SAFE_INTEGER)) {
- showToast({
- message: `${localize('com_ui_attach_error_size')} ${
- (endpointFileConfig.fileSizeLimit ?? 0) / megabyte
- } MB (${endpoint})`,
- status: 'error',
- });
- return;
- }
-
- if (!defaultFileConfig.checkType(file.type, endpointFileConfig.supportedMimeTypes ?? [])) {
- showToast({
- message: `${localize('com_ui_attach_error_type')} ${file.type} (${endpoint})`,
- status: 'error',
- });
- return;
- }
-
- if (endpointFileConfig.totalSizeLimit) {
- const existing = files.get(fileData.file_id);
- let currentTotalSize = 0;
- for (const f of files.values()) {
- currentTotalSize += f.size;
- }
- currentTotalSize -= existing?.size ?? 0;
- if (currentTotalSize + fileData.bytes > endpointFileConfig.totalSizeLimit) {
- showToast({
- message: `${localize('com_ui_attach_error_total_size')} ${endpointFileConfig.totalSizeLimit / megabyte} MB (${endpoint})`,
- status: 'error',
- });
- return;
- }
- }
-
- /** Mirror `AttachFileMenu`: an embedded file is unreadable unless file search is on.
- * The ephemeral flag governs direct chats only — a saved agent's own `tools` decide,
- * so writing it there would be dead state the badge row still reflects. */
- if (
- fileData.embedded === true &&
- capabilities.fileSearchEnabled &&
- isEphemeralAgentId(conversation.agent_id)
- ) {
- setEphemeralAgent((prev) => ({
- ...prev,
- [EToolResources.file_search]: true,
- }));
- }
-
- addFile({
- progress: 1,
- attached: true,
- file_id: fileData.file_id,
- filepath: fileData.filepath,
- preview: fileData.filepath,
- type: fileData.type,
- height: fileData.height,
- width: fileData.width,
- filename: fileData.filename,
- source: fileData.source,
- size: fileData.bytes,
- metadata: fileData.metadata,
- llmDeliveryPath: fileData.llmDeliveryPath,
- });
- },
- [
- addFile,
- files,
- fileMap,
- conversation,
- localize,
- showToast,
- fileConfig,
- setEphemeralAgent,
- capabilities.fileSearchEnabled,
- ],
- );
-
- const filenameFilter = table.getColumn('filename')?.getFilterValue() as string;
-
- return (
- <div role="region" aria-label={localize('com_files_table')} className="space-y-2">
- <FilterInput
- inputId="filename-filter"
- label={localize('com_files_filter')}
- value={filenameFilter ?? ''}
- onChange={(event) => table.getColumn('filename')?.setFilterValue(event.target.value)}
- />
-
- <div className="rounded-lg bg-transparent transition-colors">
- <div className="overflow-hidden">
- <Table className="table-fixed">
- <TableHeader>
- {table.getHeaderGroups().map((headerGroup) => (
- <TableRow key={headerGroup.id}>
- {headerGroup.headers.map((header, index) => (
- <TableHead
- key={header.id}
- size="sm"
- style={{ width: index === 0 ? '75%' : '25%' }}
- className="py-2"
- >
- <div className={index === 0 ? 'px-2' : 'flex justify-end px-1'}>
- {header.isPlaceholder
- ? null
- : flexRender(header.column.columnDef.header, header.getContext())}
- </div>
- </TableHead>
- ))}
- </TableRow>
- ))}
- </TableHeader>
- <TableBody>
- {table.getRowModel().rows.length ? (
- table.getRowModel().rows.map((row) => (
- <TableRow key={row.id} data-state={row.getIsSelected() && 'selected'}>
- {row.getVisibleCells().map((cell) => {
- const isFilenameCell = cell.column.id === 'filename';
-
- return (
- <TableCell
- style={{
- width: isFilenameCell ? '75%' : '25%',
- maxWidth: 0,
- overflow: 'hidden',
- textOverflow: 'ellipsis',
- whiteSpace: 'nowrap',
- }}
- className={
- isFilenameCell
- ? 'focus-visible:outline-text-primary focus-visible:outline-2 focus-visible:outline-offset-[-2px]'
- : ''
- }
- data-skip-refocus="true"
- key={cell.id}
- role={isFilenameCell ? 'button' : undefined}
- tabIndex={isFilenameCell ? 0 : undefined}
- onClick={(e) => {
- if (isFilenameCell) {
- const clickedElement = e.target as HTMLElement;
- // Check if clicked element is within cell and not a button/link
- if (
- clickedElement.closest('td') &&
- !clickedElement.closest('button, a')
- ) {
- e.preventDefault();
- e.stopPropagation();
- handleFileClick(row.original as TFile);
- }
- }
- }}
- onKeyDown={(e) => {
- if (isFilenameCell && (e.key === 'Enter' || e.key === ' ')) {
- const clickedElement = e.target as HTMLElement;
- if (
- clickedElement.closest('td') &&
- !clickedElement.closest('button, a')
- ) {
- e.preventDefault();
- e.stopPropagation();
- handleFileClick(row.original as TFile);
- }
- }
- }}
- >
- {flexRender(cell.column.columnDef.cell, cell.getContext())}
- </TableCell>
- );
- })}
- </TableRow>
- ))
- ) : (
- <TableRow>
- <TableCell
- colSpan={columns.length}
- className="text-text-secondary h-24 text-center text-sm"
- >
- {localize('com_files_no_results')}
- </TableCell>
- </TableRow>
- )}
- </TableBody>
- </Table>
- </div>
- </div>
-
- <div className="space-y-2">
- <Button
- ref={manageFilesRef}
- variant="outline"
- size="sm"
- className="w-full"
- onClick={() => setShowFilesModal(true)}
- aria-label={localize('com_sidepanel_manage_files')}
- >
- <ArrowUpLeft className="h-4 w-4" aria-hidden="true" />
- <span className="ml-2">{localize('com_sidepanel_manage_files')}</span>
- </Button>
-
- <div
- className="flex items-center justify-between"
- role="navigation"
- aria-label="Pagination"
- >
- <Button
- variant="outline"
- size="sm"
- onClick={() => table.previousPage()}
- disabled={!table.getCanPreviousPage()}
- aria-label={localize('com_ui_prev')}
- >
- {localize('com_ui_prev')}
- </Button>
- <div aria-live="polite" className="text-sm">
- {`${pageIndex + 1} / ${table.getPageCount()}`}
- </div>
- <Button
- variant="outline"
- size="sm"
- onClick={() => table.nextPage()}
- disabled={!table.getCanNextPage()}
- aria-label={localize('com_ui_next')}
- >
- {localize('com_ui_next')}
- </Button>
- </div>
- </div>
- <MyFilesModal
- open={showFilesModal}
- onOpenChange={setShowFilesModal}
- triggerRef={manageFilesRef}
- />
- </div>
- );
-}
diff --git a/client/src/components/SidePanel/Files/__tests__/PanelTable.spec.tsx b/client/src/components/SidePanel/Files/__tests__/PanelTable.spec.tsx
deleted file mode 100644
index 2e46f2b83e..0000000000
--- a/client/src/components/SidePanel/Files/__tests__/PanelTable.spec.tsx
+++ /dev/null
@@ -1,367 +0,0 @@
-import React from 'react';
-import { render, screen, fireEvent } from '@testing-library/react';
-import {
- FileSources,
- FileContext,
- EToolResources,
- AgentCapabilities,
-} from 'librechat-data-provider';
-import type { TFile } from 'librechat-data-provider';
-import type { ExtendedFile } from '~/common';
-import { columns } from '../PanelColumns';
-import DataTable from '../PanelTable';
-
-const mockShowToast = jest.fn();
-const mockAddFile = jest.fn();
-const mockSetEphemeralAgent = jest.fn();
-
-let mockFileMap: Record<string, TFile> = {};
-let mockFiles: Map<string, ExtendedFile> = new Map();
-let mockConversation: Record<string, unknown> | null = { endpoint: 'openAI' };
-let mockAgentsConfig: { capabilities?: string[] } | null = {
- capabilities: [AgentCapabilities.file_search],
-};
-let mockRawFileConfig: Record<string, unknown> | null = {
- endpoints: {
- openAI: { fileLimit: 10, supportedMimeTypes: ['application/pdf', 'text/plain'] },
- },
-};
-
-jest.mock('@librechat/client', () => ({
- Table: ({ children, ...props }: { children: React.ReactNode }) => (
- <table {...props}>{children}</table>
- ),
- Button: ({
- children,
- ...props
- }: { children: React.ReactNode } & React.ButtonHTMLAttributes<HTMLButtonElement>) => (
- <button {...props}>{children}</button>
- ),
- TableRow: ({ children, ...props }: { children: React.ReactNode }) => (
- <tr {...props}>{children}</tr>
- ),
- TableHead: ({ children, ...props }: { children: React.ReactNode }) => (
- <th {...props}>{children}</th>
- ),
- TableBody: ({ children, ...props }: { children: React.ReactNode }) => (
- <tbody {...props}>{children}</tbody>
- ),
- TableCell: ({
- children,
- ...props
- }: { children: React.ReactNode } & React.TdHTMLAttributes<HTMLTableCellElement>) => (
- <td {...props}>{children}</td>
- ),
- FilterInput: () => <input data-testid="filter" />,
- TableHeader: ({ children, ...props }: { children: React.ReactNode }) => (
- <thead {...props}>{children}</thead>
- ),
- useToastContext: () => ({ showToast: mockShowToast }),
-}));
-
-jest.mock('~/Providers', () => ({
- useFileMapContext: () => mockFileMap,
- useChatContext: () => ({
- files: mockFiles,
- setFiles: jest.fn(),
- conversation: mockConversation,
- }),
-}));
-
-jest.mock('recoil', () => ({
- useSetRecoilState: () => mockSetEphemeralAgent,
-}));
-
-jest.mock('~/store', () => ({
- ephemeralAgentByConvoId: (conversationId: string) => ({ key: conversationId }),
-}));
-
-jest.mock('~/hooks', () => ({
- useLocalize: () => (key: string) => key,
- useUpdateFiles: () => ({ addFile: mockAddFile }),
- useGetAgentsConfig: () => ({ agentsConfig: mockAgentsConfig }),
- useAgentCapabilities: (capabilities?: string[]) => ({
- fileSearchEnabled: capabilities?.includes('file_search') ?? false,
- }),
-}));
-
-jest.mock('~/data-provider', () => ({
- useGetFileConfig: ({ select }: { select?: (d: unknown) => unknown }) => ({
- data: select != null ? select(mockRawFileConfig) : mockRawFileConfig,
- }),
-}));
-
-jest.mock('~/components/Chat/Input/Files/MyFilesModal', () => ({
- MyFilesModal: () => null,
-}));
-
-jest.mock('../PanelFileCell', () => ({ row }: { row: { original: TFile } }) => (
- <span>{row.original?.filename}</span>
-));
-
-function makeFile(overrides: Partial<TFile> = {}): TFile {
- return {
- user: 'user-1',
- file_id: 'file-1',
- bytes: 1024,
- embedded: false,
- filename: 'test.pdf',
- filepath: '/files/test.pdf',
- object: 'file',
- type: 'application/pdf',
- usage: 0,
- source: FileSources.local,
- ...overrides,
- };
-}
-
-function makeExtendedFile(overrides: Partial<ExtendedFile> = {}): ExtendedFile {
- return {
- file_id: 'ext-1',
- size: 1024,
- progress: 1,
- source: FileSources.local,
- ...overrides,
- };
-}
-
-function renderTable(data: TFile[]) {
- return render(<DataTable columns={columns} data={data} />);
-}
-
-function clickFilenameCell() {
- const cells = screen.getAllByRole('button');
- const filenameCell = cells.find(
- (cell) => cell.tagName === 'TD' && cell.textContent && !cell.textContent.includes('com_ui_'),
- );
- if (!filenameCell) {
- throw new Error('Could not find filename cell with role="button" — check mock setup');
- }
- fireEvent.click(filenameCell);
- return filenameCell;
-}
-
-describe('PanelTable handleFileClick', () => {
- beforeEach(() => {
- mockShowToast.mockClear();
- mockAddFile.mockClear();
- mockSetEphemeralAgent.mockClear();
- mockAgentsConfig = { capabilities: [AgentCapabilities.file_search] };
- mockFiles = new Map();
- mockConversation = { endpoint: 'openAI' };
- mockRawFileConfig = {
- endpoints: {
- openAI: {
- fileLimit: 5,
- totalSizeLimit: 10,
- supportedMimeTypes: ['application/pdf', 'text/plain'],
- },
- },
- };
- });
-
- it('calls addFile when within file limits', () => {
- const file = makeFile();
- mockFileMap = { [file.file_id]: file };
-
- renderTable([file]);
- clickFilenameCell();
-
- expect(mockAddFile).toHaveBeenCalledTimes(1);
- expect(mockAddFile).toHaveBeenCalledWith(
- expect.objectContaining({
- file_id: file.file_id,
- attached: true,
- progress: 1,
- }),
- );
- expect(mockShowToast).not.toHaveBeenCalledWith(expect.objectContaining({ status: 'error' }));
- });
-
- it('reattaches a persisted published file with its durable identity and provenance', () => {
- const runFile = {
- runId: 'run-1',
- executionId: 'child-execution',
- parentExecutionId: 'parent-execution',
- agentId: 'child-agent',
- sourceFileId: 'private-file',
- publishedAt: '2026-09-11T16:00:00.000Z',
- inputFileIds: ['input-pdf'],
- };
- const file = makeFile({
- file_id: 'published-report',
- filename: 'report.pdf',
- context: FileContext.run_artifact,
- metadata: { runFile },
- llmDeliveryPath: 'text',
- });
- mockFileMap = { [file.file_id]: file };
-
- renderTable([file]);
- clickFilenameCell();
-
- expect(mockAddFile).toHaveBeenCalledWith(
- expect.objectContaining({
- file_id: 'published-report',
- filename: 'report.pdf',
- filepath: file.filepath,
- metadata: { runFile },
- llmDeliveryPath: 'text',
- attached: true,
- progress: 1,
- }),
- );
- });
-
- it('blocks attachment when fileLimit is reached', () => {
- const file = makeFile({ file_id: 'new-file', filename: 'new.pdf' });
- mockFileMap = { [file.file_id]: file };
-
- mockFiles = new Map(
- Array.from({ length: 5 }, (_, i) => [
- `existing-${i}`,
- makeExtendedFile({ file_id: `existing-${i}` }),
- ]),
- );
-
- renderTable([file]);
- clickFilenameCell();
-
- expect(mockAddFile).not.toHaveBeenCalled();
- expect(mockShowToast).toHaveBeenCalledWith(
- expect.objectContaining({
- message: expect.stringContaining('com_ui_attach_error_limit'),
- status: 'error',
- }),
- );
- });
-
- it('blocks attachment when totalSizeLimit would be exceeded', () => {
- const MB = 1024 * 1024;
- const largeFile = makeFile({ file_id: 'large-file', bytes: 6 * MB });
- mockFileMap = { [largeFile.file_id]: largeFile };
-
- mockFiles = new Map([
- ['existing-1', makeExtendedFile({ file_id: 'existing-1', size: 5 * MB })],
- ]);
-
- renderTable([largeFile]);
- clickFilenameCell();
-
- expect(mockAddFile).not.toHaveBeenCalled();
- expect(mockShowToast).toHaveBeenCalledWith(
- expect.objectContaining({
- message: expect.stringContaining('com_ui_attach_error_total_size'),
- status: 'error',
- }),
- );
- });
-
- it('does not double-count size of already-attached file', () => {
- const MB = 1024 * 1024;
- const file = makeFile({ file_id: 'reattach', bytes: 5 * MB });
- mockFileMap = { [file.file_id]: file };
-
- mockFiles = new Map([
- ['reattach', makeExtendedFile({ file_id: 'reattach', size: 5 * MB })],
- ['other', makeExtendedFile({ file_id: 'other', size: 4 * MB })],
- ]);
-
- renderTable([file]);
- clickFilenameCell();
-
- expect(mockAddFile).toHaveBeenCalledTimes(1);
- expect(mockShowToast).not.toHaveBeenCalledWith(
- expect.objectContaining({
- message: expect.stringContaining('com_ui_attach_error_total_size'),
- }),
- );
- });
-
- it('allows attachment when just under fileLimit', () => {
- const file = makeFile({ file_id: 'under-limit' });
- mockFileMap = { [file.file_id]: file };
-
- mockFiles = new Map(
- Array.from({ length: 4 }, (_, i) => [
- `existing-${i}`,
- makeExtendedFile({ file_id: `existing-${i}` }),
- ]),
- );
-
- renderTable([file]);
- clickFilenameCell();
-
- expect(mockAddFile).toHaveBeenCalledTimes(1);
- });
-
- it('turns on file search when attaching an embedded file', () => {
- const file = makeFile({ file_id: 'embedded-file', embedded: true });
- mockFileMap = { [file.file_id]: file };
-
- renderTable([file]);
- clickFilenameCell();
-
- expect(mockAddFile).toHaveBeenCalledTimes(1);
- expect(mockSetEphemeralAgent).toHaveBeenCalledTimes(1);
-
- const updater = mockSetEphemeralAgent.mock.calls[0][0];
- expect(updater({ web_search: true })).toEqual({
- web_search: true,
- [EToolResources.file_search]: true,
- });
- });
-
- it('leaves file search alone for a file that was never embedded', () => {
- const file = makeFile({ file_id: 'plain-file', embedded: false });
- mockFileMap = { [file.file_id]: file };
-
- renderTable([file]);
- clickFilenameCell();
-
- expect(mockAddFile).toHaveBeenCalledTimes(1);
- expect(mockSetEphemeralAgent).not.toHaveBeenCalled();
- });
-
- it('leaves file search alone when the capability is disabled', () => {
- mockAgentsConfig = { capabilities: [] };
- const file = makeFile({ file_id: 'embedded-file', embedded: true });
- mockFileMap = { [file.file_id]: file };
-
- renderTable([file]);
- clickFilenameCell();
-
- expect(mockAddFile).toHaveBeenCalledTimes(1);
- expect(mockSetEphemeralAgent).not.toHaveBeenCalled();
- });
-
- it('leaves file search alone when a saved agent owns the conversation', () => {
- mockConversation = { endpoint: 'openAI', agent_id: 'agent_abc123' };
- const file = makeFile({ file_id: 'embedded-file', embedded: true });
- mockFileMap = { [file.file_id]: file };
-
- renderTable([file]);
- clickFilenameCell();
-
- expect(mockAddFile).toHaveBeenCalledTimes(1);
- expect(mockSetEphemeralAgent).not.toHaveBeenCalled();
- });
-
- it('leaves file search alone when the attachment itself is rejected', () => {
- const file = makeFile({ file_id: 'embedded-file', embedded: true });
- mockFileMap = { [file.file_id]: file };
-
- mockFiles = new Map(
- Array.from({ length: 5 }, (_, i) => [
- `existing-${i}`,
- makeExtendedFile({ file_id: `existing-${i}` }),
- ]),
- );
-
- renderTable([file]);
- clickFilenameCell();
-
- expect(mockAddFile).not.toHaveBeenCalled();
- expect(mockSetEphemeralAgent).not.toHaveBeenCalled();
- });
-});
diff --git a/client/src/components/Skills/dialogs/__tests__/UploadSkillDialog.spec.tsx b/client/src/components/Skills/dialogs/__tests__/UploadSkillDialog.spec.tsx
index f4fe40cf11..69823618a1 100644
--- a/client/src/components/Skills/dialogs/__tests__/UploadSkillDialog.spec.tsx
+++ b/client/src/components/Skills/dialogs/__tests__/UploadSkillDialog.spec.tsx
@@ -1,3 +1,6 @@
+/**
+ * @jest-environment jsdom
+ */
import { act, fireEvent, render, screen } from '@testing-library/react';
import type { FileConfigInput } from 'librechat-data-provider';
import type { ReactNode } from 'react';
@@ -106,14 +109,16 @@ jest.mock('~/utils', () => ({
cn: (...classes: Array<string | false | null | undefined>) => classes.filter(Boolean).join(' '),
}));
-function getFileInput(container: HTMLElement): HTMLInputElement {
- /** Prefer the local render container used by the lightweight dialog mock,
- * then the active portal. Exiting Headless UI portals can leave older file
- * inputs in `document.body`; a document-wide first/last match is unstable. */
+/** Prefer the rendered dialog's current file input, whether the dialog content
+ * is inline in the test stub or mounted through a portal in the real shell.
+ * Restricting the selector avoids stale inputs left behind by an exiting
+ * Headless UI portal. */
+function getFileInput(container?: HTMLElement): HTMLInputElement {
const selector = 'input[type="file"][accept=".zip,.skill,.md"]';
const input =
- container.querySelector<HTMLInputElement>(selector) ??
- document.querySelector<HTMLInputElement>(`[role="dialog"][data-state="open"] ${selector}`);
+ container?.querySelector<HTMLInputElement>(selector) ??
+ document.querySelector<HTMLInputElement>(`[role="dialog"][data-state="open"] ${selector}`) ??
+ document.querySelector<HTMLInputElement>('input[type="file"]');
if (input == null) {
throw new Error('Upload input was not rendered');
}
@@ -185,15 +190,13 @@ describe('UploadSkillDialog', () => {
});
it('rejects files above the configured skill import limit before upload', () => {
- const { container } = render(<UploadSkillDialog isOpen={true} setIsOpen={mockSetIsOpen} />);
+ render(<UploadSkillDialog isOpen={true} setIsOpen={mockSetIsOpen} />);
const file = new File([new Uint8Array(1024 * 1024 + 1)], 'too-large.skill', {
type: 'application/zip',
});
- fireEvent.change(getFileInput(container), {
- target: {
- files: [file],
- },
+ fireEvent.change(getFileInput(), {
+ target: { files: [file] },
});
expect(mockMutate).not.toHaveBeenCalled();
@@ -205,15 +208,13 @@ describe('UploadSkillDialog', () => {
it('uploads files exactly at the configured skill import limit', () => {
const appendSpy = jest.spyOn(FormData.prototype, 'append');
- const { container } = render(<UploadSkillDialog isOpen={true} setIsOpen={mockSetIsOpen} />);
+ render(<UploadSkillDialog isOpen={true} setIsOpen={mockSetIsOpen} />);
const file = new File([new Uint8Array(1024 * 1024)], 'exact-limit.skill', {
type: 'application/zip',
});
- fireEvent.change(getFileInput(container), {
- target: {
- files: [file],
- },
+ fireEvent.change(getFileInput(), {
+ target: { files: [file] },
});
expect(mockShowToast).not.toHaveBeenCalled();
@@ -383,15 +384,13 @@ describe('UploadSkillDialog', () => {
it('uploads files under the configured skill import limit', () => {
const appendSpy = jest.spyOn(FormData.prototype, 'append');
- const { container } = render(<UploadSkillDialog isOpen={true} setIsOpen={mockSetIsOpen} />);
+ render(<UploadSkillDialog isOpen={true} setIsOpen={mockSetIsOpen} />);
const file = new File([new Uint8Array(1024)], 'small.skill', {
type: 'application/zip',
});
- fireEvent.change(getFileInput(container), {
- target: {
- files: [file],
- },
+ fireEvent.change(getFileInput(), {
+ target: { files: [file] },
});
expect(mockShowToast).not.toHaveBeenCalled();
diff --git a/client/src/components/UnifiedSidebar/UnifiedSidebar.tsx b/client/src/components/UnifiedSidebar/UnifiedSidebar.tsx
index 70eca92b77..2adbef4e64 100644
--- a/client/src/components/UnifiedSidebar/UnifiedSidebar.tsx
+++ b/client/src/components/UnifiedSidebar/UnifiedSidebar.tsx
@@ -1,4 +1,5 @@
import { useCallback, useState, useEffect, useRef, memo } from 'react';
+import { useAtom } from 'jotai';
import { useForm } from 'react-hook-form';
import { useMediaQuery } from '@librechat/client';
import { useLocation, useNavigate } from 'react-router-dom';
@@ -15,8 +16,10 @@ import {
MOBILE_DRAWER_WIDTH,
DRAWER_UNPAINTED,
} from './constants';
+import { filesDialogTriggerAtom, showFilesDialogAtom } from '~/store/filesDialog';
import { ChatContext, ChatFormProvider, ActivePanelProvider } from '~/Providers';
import { MobileHeader, MobileBottomBar, MobileShortcutTargets } from './mobile';
+import { MyFilesModal } from '~/components/Chat/Input/Files/MyFilesModal';
import useUnifiedSidebarLinks from '~/hooks/Nav/useUnifiedSidebarLinks';
import useSidebarToggle from '~/hooks/Nav/useSidebarToggle';
import useSidebarState from '~/hooks/Nav/useSidebarState';
@@ -51,6 +54,8 @@ function UnifiedSidebar({ isSliding = false }: { isSliding?: boolean }) {
const location = useLocation();
const navigate = useNavigate();
const { isSmallScreen, expanded } = useSidebarState();
+ const [showFiles, setShowFiles] = useAtom(showFilesDialogAtom);
+ const [filesDialogTrigger, setFilesDialogTrigger] = useAtom(filesDialogTriggerAtom);
const { setSidebarOpen } = useSidebarToggle();
const prefersReducedMotion = useMediaQuery('(prefers-reduced-motion: reduce)');
const [sidebarWidth, setSidebarWidth] = useState(getInitialWidth);
@@ -184,61 +189,57 @@ function UnifiedSidebar({ isSliding = false }: { isSliding?: boolean }) {
return () => document.removeEventListener('keydown', handler);
}, [isSmallScreen, expanded, handleCollapse]);
- if (isSmallScreen) {
- return (
- <div
- id={MOBILE_DRAWER_ID}
- className={cn(
- /** The close swipe reads horizontal touches here (the drawer holds no
- * horizontal scrollers), while pinch-zoom stays with the browser —
- * this full-viewport surface must not disable zooming entirely. */
- 'bg-surface-primary-alt fixed inset-y-0 left-0 flex touch-pan-y touch-pinch-zoom flex-col',
- expanded ? 'translate-x-0' : '-translate-x-full',
- )}
- style={{
- width: MOBILE_DRAWER_WIDTH,
- /** The strip setting changes the width without passing through the
- * snap path, so the preference has to reach the declarative style
- * too or that one change still animates. */
- transition: prefersReducedMotion ? undefined : MOBILE_DRAWER_TRANSITION,
- zIndex: DRAWER_Z_INDEX,
- /** Why a closed drawer is not painted at all: see DRAWER_UNPAINTED.
- * The travel stays painted — `isSliding` covers the frames Recoil's
- * deferred flip leaves uncovered at both ends, and a drag claims
- * painting inline (see useDrawerSwipe), which hands this value back
- * explicitly because React cannot re-assert it on its own. */
- visibility: expanded || isSliding ? undefined : DRAWER_UNPAINTED,
- }}
- inert={!expanded ? '' : undefined}
- >
- <SidebarChatProvider>
- <ActivePanelProvider>
- <MobileHeader
- links={links}
- expanded={expanded}
- onClose={handleCollapse}
- onLeaveInsights={handleLeaveInsights}
- routeActiveId={isInsightsRoute ? 'insights' : undefined}
- />
- <nav
- id="chat-history-nav"
- className="bg-surface-primary-alt min-h-0 flex-1 overflow-hidden"
- >
- <SidePanelNav links={links} />
- </nav>
- <MobileShortcutTargets
- links={links}
- onLeaveInsights={handleLeaveInsights}
- routeActiveId={isInsightsRoute ? 'insights' : undefined}
- />
- <MobileBottomBar links={links} onNewChat={handleCollapse} />
- </ActivePanelProvider>
- </SidebarChatProvider>
- </div>
- );
- }
-
- return (
+ const sidebarContent = isSmallScreen ? (
+ <div
+ id={MOBILE_DRAWER_ID}
+ className={cn(
+ /** The close swipe reads horizontal touches here (the drawer holds no
+ * horizontal scrollers), while pinch-zoom stays with the browser —
+ * this full-viewport surface must not disable zooming entirely. */
+ 'bg-surface-primary-alt fixed inset-y-0 left-0 flex touch-pan-y touch-pinch-zoom flex-col',
+ expanded ? 'translate-x-0' : '-translate-x-full',
+ )}
+ style={{
+ width: MOBILE_DRAWER_WIDTH,
+ /** The strip setting changes the width without passing through the
+ * snap path, so the preference has to reach the declarative style
+ * too or that one change still animates. */
+ transition: prefersReducedMotion ? undefined : MOBILE_DRAWER_TRANSITION,
+ zIndex: DRAWER_Z_INDEX,
+ /** Why a closed drawer is not painted at all: see DRAWER_UNPAINTED.
+ * The travel stays painted — `isSliding` covers the frames Recoil's
+ * deferred flip leaves uncovered at both ends, and a drag claims
+ * painting inline (see useDrawerSwipe), which hands this value back
+ * explicitly because React cannot re-assert it on its own. */
+ visibility: expanded || isSliding ? undefined : DRAWER_UNPAINTED,
+ }}
+ inert={!expanded ? '' : undefined}
+ >
+ <SidebarChatProvider>
+ <ActivePanelProvider>
+ <MobileHeader
+ links={links}
+ expanded={expanded}
+ onClose={handleCollapse}
+ onLeaveInsights={handleLeaveInsights}
+ routeActiveId={isInsightsRoute ? 'insights' : undefined}
+ />
+ <nav
+ id="chat-history-nav"
+ className="bg-surface-primary-alt min-h-0 flex-1 overflow-hidden"
+ >
+ <SidePanelNav links={links} />
+ </nav>
+ <MobileShortcutTargets
+ links={links}
+ onLeaveInsights={handleLeaveInsights}
+ routeActiveId={isInsightsRoute ? 'insights' : undefined}
+ />
+ <MobileBottomBar links={links} onNewChat={handleCollapse} />
+ </ActivePanelProvider>
+ </SidebarChatProvider>
+ </div>
+ ) : (
<SidebarChatProvider>
<ActivePanelProvider>
<aside
@@ -269,6 +270,31 @@ function UnifiedSidebar({ isSliding = false }: { isSliding?: boolean }) {
</ActivePanelProvider>
</SidebarChatProvider>
);
+
+ const closeFiles = useCallback(
+ (open: boolean) => {
+ setShowFiles(open);
+ if (!open) {
+ /** A stale opener would capture focus for the NEXT open, which the
+ * shortcut path deliberately leaves to the composer. */
+ setFilesDialogTrigger(null);
+ }
+ },
+ [setFilesDialogTrigger, setShowFiles],
+ );
+
+ return (
+ <>
+ {sidebarContent}
+ {showFiles && (
+ <MyFilesModal
+ open={showFiles}
+ onOpenChange={closeFiles}
+ triggerRef={filesDialogTrigger ?? undefined}
+ />
+ )}
+ </>
+ );
}
export default memo(UnifiedSidebar);
diff --git a/client/src/data-provider/Files/__tests__/mutations.spec.tsx b/client/src/data-provider/Files/__tests__/mutations.spec.tsx
new file mode 100644
index 0000000000..388dbe7f27
--- /dev/null
+++ b/client/src/data-provider/Files/__tests__/mutations.spec.tsx
@@ -0,0 +1,189 @@
+import React from 'react';
+import { RecoilRoot } from 'recoil';
+import { QueryKeys } from 'librechat-data-provider';
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import type { TFile, BatchFile } from 'librechat-data-provider';
+import type { ReactNode } from 'react';
+import { useUploadFileMutation, useDeleteFilesMutation } from '../mutations';
+import { useGetRecentFiles } from '../queries';
+
+/**
+ * The composer palette reads its "your files" section from
+ * `[QueryKeys.files, 'recent', limit]`, a query that is only enabled while the
+ * palette is open. These cover both halves of the staleness question: a file
+ * arriving while the palette watches, and one arriving while it is shut.
+ */
+
+const mockGetFiles = jest.fn();
+const mockUploadFile = jest.fn();
+const mockDeleteFiles = jest.fn();
+
+jest.mock('librechat-data-provider', () => {
+ const actual = jest.requireActual('librechat-data-provider');
+ return {
+ ...actual,
+ dataService: {
+ ...actual.dataService,
+ getFiles: (...args: unknown[]) => mockGetFiles(...args),
+ uploadFile: (...args: unknown[]) => mockUploadFile(...args),
+ deleteFiles: (...args: unknown[]) => mockDeleteFiles(...args),
+ },
+ };
+});
+
+jest.mock('@librechat/client', () => ({
+ useToastContext: () => ({ showToast: jest.fn() }),
+}));
+
+jest.mock('~/hooks', () => ({
+ useLocalize: () => (key: string) => key,
+}));
+
+jest.mock('../../Endpoints', () => ({
+ useGetStartupConfig: () => ({ data: undefined }),
+}));
+
+const RECENT_LIMIT = 5;
+
+const makeFile = (over: Partial<TFile> = {}): TFile =>
+ ({
+ user: 'user-1',
+ file_id: 'file-old',
+ filename: 'old.pdf',
+ filepath: '/files/old.pdf',
+ type: 'application/pdf',
+ bytes: 1024,
+ embedded: false,
+ object: 'file',
+ ...over,
+ }) as TFile;
+
+const createClient = () =>
+ new QueryClient({
+ defaultOptions: {
+ queries: { retry: false },
+ mutations: { retry: false },
+ },
+ });
+
+const wrapperFor = (queryClient: QueryClient) =>
+ function Wrapper({ children }: { children: ReactNode }) {
+ return (
+ <RecoilRoot>
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ </RecoilRoot>
+ );
+ };
+
+const renderPalette = (queryClient: QueryClient, initialOpen: boolean) =>
+ renderHook(
+ ({ open }: { open: boolean }) => ({
+ recent: useGetRecentFiles(RECENT_LIMIT, { enabled: open }),
+ upload: useUploadFileMutation(),
+ remove: useDeleteFilesMutation(),
+ }),
+ { wrapper: wrapperFor(queryClient), initialProps: { open: initialOpen } },
+ );
+
+const uploadForm = (): FormData => {
+ const body = new FormData();
+ body.append('endpoint', 'openAI');
+ return body;
+};
+
+describe('recent-files cache after file mutations', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ mockGetFiles.mockResolvedValue([makeFile()]);
+ mockDeleteFiles.mockResolvedValue({ message: 'deleted' });
+ });
+
+ it('keys the recent page separately from the full file list', async () => {
+ const queryClient = createClient();
+ const { result } = renderPalette(queryClient, true);
+
+ await waitFor(() => expect(result.current.recent.data).toHaveLength(1));
+
+ expect(mockGetFiles).toHaveBeenCalledWith({ limit: RECENT_LIMIT });
+ expect(queryClient.getQueryData([QueryKeys.files, 'recent', RECENT_LIMIT])).toHaveLength(1);
+ expect(queryClient.getQueryData([QueryKeys.files])).toBeUndefined();
+ });
+
+ it('refreshes the open palette when a file is uploaded onto the composer', async () => {
+ const queryClient = createClient();
+ const { result } = renderPalette(queryClient, true);
+
+ await waitFor(() => expect(result.current.recent.data).toHaveLength(1));
+ expect(mockGetFiles).toHaveBeenCalledTimes(1);
+
+ const uploaded = makeFile({ file_id: 'file-new', filename: 'new.pdf' });
+ mockUploadFile.mockResolvedValue(uploaded);
+ mockGetFiles.mockResolvedValue([uploaded, makeFile()]);
+
+ await act(async () => {
+ await result.current.upload.mutateAsync(uploadForm());
+ });
+
+ await waitFor(() =>
+ expect(result.current.recent.data?.map((file) => file.file_id)).toEqual([
+ 'file-new',
+ 'file-old',
+ ]),
+ );
+ expect(mockGetFiles).toHaveBeenCalledTimes(2);
+ });
+
+ /* The palette component holds the disclosure button, so it stays mounted for
+ the whole conversation and closing it only flips `enabled`. React Query
+ refetches when a mounted observer goes from disabled to enabled over stale
+ data, which is a different path from `refetchOnMount` and is why the
+ invalidation above does not need a matching `setQueriesData`. */
+ it('refreshes the palette on reopen when the upload landed while it was shut', async () => {
+ const queryClient = createClient();
+ const { result, rerender } = renderPalette(queryClient, true);
+
+ await waitFor(() => expect(result.current.recent.data).toHaveLength(1));
+ expect(mockGetFiles).toHaveBeenCalledTimes(1);
+
+ rerender({ open: false });
+
+ const uploaded = makeFile({ file_id: 'file-new', filename: 'new.pdf' });
+ mockUploadFile.mockResolvedValue(uploaded);
+ mockGetFiles.mockResolvedValue([uploaded, makeFile()]);
+
+ await act(async () => {
+ await result.current.upload.mutateAsync(uploadForm());
+ });
+
+ expect(mockGetFiles).toHaveBeenCalledTimes(1);
+
+ rerender({ open: true });
+
+ await waitFor(() =>
+ expect(result.current.recent.data?.map((file) => file.file_id)).toEqual([
+ 'file-new',
+ 'file-old',
+ ]),
+ );
+ expect(mockGetFiles).toHaveBeenCalledTimes(2);
+ });
+
+ it('drops a deleted file from the recent page while the palette is open', async () => {
+ const queryClient = createClient();
+ const { result } = renderPalette(queryClient, true);
+
+ await waitFor(() => expect(result.current.recent.data).toHaveLength(1));
+
+ mockGetFiles.mockResolvedValue([]);
+
+ await act(async () => {
+ await result.current.remove.mutateAsync({
+ files: [{ file_id: 'file-old', filepath: '/files/old.pdf' } as BatchFile],
+ });
+ });
+
+ await waitFor(() => expect(result.current.recent.data).toEqual([]));
+ expect(mockGetFiles).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/client/src/data-provider/Files/mutations.ts b/client/src/data-provider/Files/mutations.ts
index 900cb10629..c7902a9bd9 100644
--- a/client/src/data-provider/Files/mutations.ts
+++ b/client/src/data-provider/Files/mutations.ts
@@ -10,6 +10,7 @@ import {
} from 'librechat-data-provider';
import type { UseMutationResult } from '@tanstack/react-query';
import type * as t from 'librechat-data-provider';
+import { invalidateRecentFiles } from '~/utils/files';
import { useGetStartupConfig } from '../Endpoints';
import { useLocalize } from '~/hooks';
@@ -58,6 +59,7 @@ export const useUploadFileMutation = (
file,
...(_files ?? []),
]);
+ invalidateRecentFiles(queryClient);
const endpoint = formData.get('endpoint');
const message_file = formData.get('message_file');
@@ -211,6 +213,7 @@ export const useDeleteFilesMutation = (
(file) => !requested.has(file.file_id) || failed.has(file.file_id),
);
});
+ invalidateRecentFiles(queryClient);
/** A storage failure still answers 200, so reporting success off the status alone would
* tell the user a file is gone while it is sitting on disk and back in their list. */
diff --git a/client/src/data-provider/Files/queries.ts b/client/src/data-provider/Files/queries.ts
index 3c455a4bef..e9a7e7e97c 100644
--- a/client/src/data-provider/Files/queries.ts
+++ b/client/src/data-provider/Files/queries.ts
@@ -25,6 +25,29 @@ export const useGetFiles = <TData = t.TFile[] | boolean>(
});
};
+/**
+ * A short, server-sorted page of the user's files for surfaces that only show
+ * a handful of recent uploads (composer palette). Kept on a separate query key
+ * so it never replaces the full `QueryKeys.files` list used by the files panel.
+ */
+export const useGetRecentFiles = <TData = t.TFile[]>(
+ limit: number,
+ config?: UseQueryOptions<t.TFile[], unknown, TData>,
+): QueryObserverResult<TData, unknown> => {
+ const queriesEnabled = useRecoilValue<boolean>(store.queriesEnabled);
+ return useQuery<t.TFile[], unknown, TData>(
+ [QueryKeys.files, 'recent', limit],
+ () => dataService.getFiles({ limit }),
+ {
+ refetchOnWindowFocus: false,
+ refetchOnReconnect: false,
+ refetchOnMount: false,
+ ...config,
+ enabled: (config?.enabled ?? true) === true && queriesEnabled && limit > 0,
+ },
+ );
+};
+
export const useGetAgentFiles = <TData = t.TFile[]>(
agentId: string | undefined,
config?: UseQueryOptions<t.TFile[], unknown, TData>,
diff --git a/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx b/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx
index d715d4c606..bbb06f1a43 100644
--- a/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx
+++ b/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx
@@ -1,14 +1,24 @@
-import { getDefaultStore } from 'jotai';
import { renderHook, act } from '@testing-library/react';
-import { Constants, ContentTypes, EModelEndpoint, createPayload } from 'librechat-data-provider';
+import { Provider as JotaiProvider, createStore } from 'jotai';
+import {
+ Constants,
+ ContentTypes,
+ EModelEndpoint,
+ QueryKeys,
+ createPayload,
+} from 'librechat-data-provider';
import type {
+ Agent,
CodeEnvironmentMode,
CodeWorkspaceSelection,
TConversation,
TMessage,
TSubmission,
+ TReasoningOverride,
TEphemeralAgent,
} from 'librechat-data-provider';
+import type { ReactNode } from 'react';
+import { pendingReasoningOverrideFamily } from '~/components/Chat/Input/Composer/state';
import { activeUsageResponseIdFamily, pendingUsageFamily } from '~/store/usage';
import { revealedQueuedTurnFamily } from '~/store/steer';
import useChatFunctions from '../useChatFunctions';
@@ -21,7 +31,17 @@ const mockGetEphemeralAgent = jest.fn((): TEphemeralAgent | null => null);
const mockSetFilesToDelete = jest.fn();
const mockGetSender = jest.fn(() => 'Assistant');
const mockGetExpiry = jest.fn(() => 'expiry-key');
-const mockGetQueryData = jest.fn(() => ({}));
+const mockAgentQueryData: { current?: Agent } = {};
+const mockEndpointsQueryData: { current?: Record<string, unknown> } = {};
+const mockGetQueryData = jest.fn((queryKey: readonly unknown[]) => {
+ if (queryKey[0] === QueryKeys.agent) {
+ return mockAgentQueryData.current;
+ }
+ if (queryKey[0] === QueryKeys.endpoints) {
+ return mockEndpointsQueryData.current ?? {};
+ }
+ return {};
+});
const mockLoggerWarn = jest.fn();
const mockGetLatestConversation = jest.fn(() => null as TConversation | null);
const mockSetConversation = jest.fn();
@@ -53,7 +73,10 @@ jest.mock('recoil', () => ({
useRecoilCallback: (factory: any) =>
factory({
snapshot: {
- getLoadable: () => ({ state: 'hasValue', contents: [] }),
+ getLoadable: (_atom: unknown) => ({
+ state: 'hasValue',
+ contents: [],
+ }),
},
set: jest.fn(),
reset: jest.fn(),
@@ -72,6 +95,14 @@ jest.mock('~/hooks/Input/useUserKey', () => () => ({ getExpiry: mockGetExpiry })
jest.mock('~/hooks', () => ({
useAuthContext: () => ({ user: null }),
}));
+jest.mock('~/Providers/AgentsMapContext', () => ({
+ useAgentsMapContext: () => ({
+ 'agent-1': {
+ provider: 'openAI',
+ model: 'gpt-5.1',
+ },
+ }),
+}));
jest.mock('~/store', () => ({
__esModule: true,
default: {
@@ -129,7 +160,13 @@ const conversation = (conversationId: string) =>
function renderAsk(
messages: TMessage[] | undefined,
conversationId = 'conversation-1',
- options: { endpoint?: TConversation['endpoint']; isSubmitting?: boolean } = {},
+ options: {
+ endpoint?: TConversation['endpoint'];
+ model?: string;
+ isSubmitting?: boolean;
+ reasoningOverride?: TReasoningOverride;
+ agentId?: string;
+ } = {},
) {
const setMessages = jest.fn();
const setSubmission = jest.fn();
@@ -138,25 +175,38 @@ function renderAsk(
if ('endpoint' in options) {
immutableConversation.endpoint = options.endpoint ?? null;
}
- const hook = renderHook(() =>
- useChatFunctions({
- isSubmitting: options.isSubmitting ?? false,
- latestMessage: messages?.at(-1) ?? null,
- conversation: immutableConversation,
- getMessages,
- setMessages,
- setSubmission,
- setConversation: mockSetConversation,
- }),
+ if (options.model != null) {
+ immutableConversation.model = options.model;
+ }
+ if (options.agentId != null) {
+ immutableConversation.agent_id = options.agentId;
+ }
+ const reasoningStore = createStore();
+ reasoningStore.set(pendingReasoningOverrideFamily(conversationId), options.reasoningOverride);
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <JotaiProvider store={reasoningStore}>{children}</JotaiProvider>
+ );
+ const hook = renderHook(
+ () =>
+ useChatFunctions({
+ isSubmitting: options.isSubmitting ?? false,
+ latestMessage: messages?.at(-1) ?? null,
+ conversation: immutableConversation,
+ getMessages,
+ setMessages,
+ setSubmission,
+ }),
+ { wrapper },
);
- return { ...hook, getMessages, setMessages, setSubmission };
+ return { ...hook, getMessages, setMessages, setSubmission, reasoningStore };
}
describe('useChatFunctions ask', () => {
beforeEach(() => {
+ mockEndpointsQueryData.current = undefined;
jest.clearAllMocks();
- mockGetQueryData.mockReturnValue({});
+ mockAgentQueryData.current = undefined;
mockGetLatestConversation.mockReturnValue(null);
mockResolveCodeWorkspaceSubmission.mockReturnValue({});
});
@@ -164,8 +214,13 @@ describe('useChatFunctions ask', () => {
it.each([EModelEndpoint.agents, EModelEndpoint.openAI])(
'binds the optimistic %s response before publishing its messages',
(endpoint) => {
- const { result, setMessages, setSubmission } = renderAsk([], 'conversation-1', { endpoint });
- const store = getDefaultStore();
+ /* The helper renders under its own Jotai store; the hook writes there. */
+ const {
+ result,
+ setMessages,
+ setSubmission,
+ reasoningStore: store,
+ } = renderAsk([], 'conversation-1', { endpoint });
store.set(activeUsageResponseIdFamily('conversation-1'), null);
setMessages.mockImplementation((messages: TMessage[]) => {
expect(store.get(activeUsageResponseIdFamily('conversation-1'))).toBe(
@@ -286,7 +341,8 @@ describe('useChatFunctions ask', () => {
it('refuses every direct send before consuming composer context during handoff', () => {
const family = revealedQueuedTurnFamily('conversation-1');
- getDefaultStore().set(family, {
+ const { result, setSubmission, getMessages, reasoningStore } = renderAsk([]);
+ reasoningStore.set(family, {
clientRequestId: 'queued',
parentMessageId: 'response',
generationCreatedAt: 41,
@@ -294,7 +350,6 @@ describe('useChatFunctions ask', () => {
revealedAt: new Date().toISOString(),
});
try {
- const { result, setSubmission, getMessages } = renderAsk([]);
expect(result.current.ask({ text: 'direct' })).toBe(false);
expect(
result.current.ask({ text: 'rerun', parentMessageId: 'earlier' }, { isRegenerate: true }),
@@ -304,7 +359,7 @@ describe('useChatFunctions ask', () => {
expect(setSubmission).not.toHaveBeenCalled();
expect(mockSetFilesToDelete).not.toHaveBeenCalled();
} finally {
- getDefaultStore().set(family, null);
+ reasoningStore.set(family, null);
}
});
@@ -351,6 +406,40 @@ describe('useChatFunctions ask', () => {
expect(mockSetShowStopButton).not.toHaveBeenCalled();
});
+ it('refuses a second submit fired in the same task, before isSubmitting commits', () => {
+ const { result, setSubmission } = renderAsk([]);
+
+ let first: ReturnType<typeof result.current.ask>;
+ let second: ReturnType<typeof result.current.ask>;
+ act(() => {
+ first = result.current.ask({ text: 'double enter', conversationId: 'conversation-1' });
+ second = result.current.ask({ text: 'double enter', conversationId: 'conversation-1' });
+ });
+
+ expect(first!).not.toBe(false);
+ expect(second!).toBe(false);
+ expect(setSubmission).toHaveBeenCalledTimes(1);
+ });
+
+ it('releases the in-flight guard on the next commit rather than latching it', () => {
+ const { result, rerender, setSubmission } = renderAsk([]);
+
+ act(() => {
+ result.current.ask({ text: 'first turn', conversationId: 'conversation-1' });
+ });
+ /* `isSubmitting` never turns true here, standing in for a start that fails
+ outright: the next commit has to release the guard on its own instead of
+ latching the composer shut. */
+ act(() => {
+ rerender();
+ });
+ act(() => {
+ result.current.ask({ text: 'second turn', conversationId: 'conversation-1' });
+ });
+
+ expect(setSubmission).toHaveBeenCalledTimes(2);
+ });
+
it('reports a refusal when no endpoint is available', () => {
const { result, setMessages, setSubmission } = renderAsk([], 'conversation-1', {
endpoint: null,
@@ -420,12 +509,134 @@ describe('useChatFunctions ask', () => {
expect(setMessages).toHaveBeenCalled();
expect(setSubmission).toHaveBeenCalled();
});
+
+ it('stores an explicit reasoning override on only the submitted user turn', () => {
+ const { result, setSubmission } = renderAsk([]);
+ const override = { key: 'reasoning_effort', value: 'high' } as TReasoningOverride;
+
+ act(() => {
+ result.current.ask({ text: 'Think carefully' }, { overrideReasoning: override });
+ });
+
+ const submission = setSubmission.mock.calls.at(-1)?.[0] as TSubmission;
+ expect(submission.userMessage.reasoningOverride).toEqual(override);
+ expect(submission.conversation).not.toHaveProperty('reasoning_effort', 'high');
+ expect(submission.endpointOption).not.toHaveProperty('reasoning_effort', 'high');
+ });
+
+ /* A manual compaction is an internal summarization turn, like a regenerate:
+ the staged choice belongs to the user's next real message. */
+ it('leaves a staged reasoning override for the next message across a manual compaction', () => {
+ const override = { key: 'reasoning_effort', value: 'high' } as TReasoningOverride;
+ const { result, setSubmission, reasoningStore } = renderAsk(
+ [{ messageId: 'msg-1', parentMessageId: Constants.NO_PARENT } as TMessage],
+ 'conversation-1',
+ { reasoningOverride: override },
+ );
+
+ act(() => {
+ result.current.ask(
+ {
+ text: '',
+ conversationId: 'conversation-1',
+ messageId: 'msg-1',
+ parentMessageId: 'msg-1',
+ },
+ { compact: true },
+ );
+ });
+
+ const submission = setSubmission.mock.calls.at(-1)?.[0] as TSubmission | undefined;
+ expect(submission?.userMessage?.reasoningOverride).toBeUndefined();
+ expect(reasoningStore.get(pendingReasoningOverrideFamily('conversation-1'))).toEqual(override);
+ });
+
+ it('drains a staged reasoning override onto a fresh submission exactly once', () => {
+ const override = { key: 'reasoning_effort', value: 'high' } as TReasoningOverride;
+ const { result, setSubmission, reasoningStore } = renderAsk([], 'conversation-1', {
+ reasoningOverride: override,
+ });
+
+ act(() => {
+ result.current.ask({ text: 'Think carefully' });
+ });
+
+ const submission = setSubmission.mock.calls.at(-1)?.[0] as TSubmission;
+ expect(submission.userMessage.reasoningOverride).toEqual(override);
+ expect(reasoningStore.get(pendingReasoningOverrideFamily('conversation-1'))).toBeUndefined();
+ });
+ it('keeps a staged override for an ephemeral agent resolved from its encoded target', () => {
+ const override = { key: 'reasoning_effort', value: 'high' } as TReasoningOverride;
+ const { result, setSubmission } = renderAsk([], 'conversation-1', {
+ reasoningOverride: override,
+ agentId: 'openAI__gpt-5___GPT-5',
+ });
+
+ act(() => {
+ result.current.ask({ text: 'Think carefully' });
+ });
+
+ const submission = setSubmission.mock.calls.at(-1)?.[0] as TSubmission;
+ expect(submission.userMessage.reasoningOverride).toEqual(override);
+ });
+
+ it('submits the declared effort override for the mock custom endpoint', () => {
+ mockEndpointsQueryData.current = {
+ 'Mock Provider A': {
+ type: 'custom',
+ customParams: {
+ defaultParamsEndpoint: 'anthropic',
+ paramDefinitions: [{ key: 'effort' }],
+ },
+ },
+ };
+ const override = { key: 'effort', value: 'high' } as TReasoningOverride;
+ const { result, setSubmission } = renderAsk([], 'mock-provider-conversation', {
+ /* The lab's endpoint is a named custom endpoint, so its label is not an
+ `EModelEndpoint` member; that is the configuration under test. */
+ endpoint: 'Mock Provider A' as TConversation['endpoint'],
+ model: 'mock-model-a',
+ reasoningOverride: override,
+ });
+
+ act(() => {
+ result.current.ask({ text: 'Think with effort' });
+ });
+
+ const submission = setSubmission.mock.calls.at(-1)?.[0] as TSubmission;
+ expect(submission.userMessage.reasoningOverride).toEqual(override);
+ });
+
+ it('uses hydrated per-agent query data when the agent catalog is unavailable', () => {
+ const agentId = 'agent-uncatalogued';
+ const override = { key: 'reasoning_effort', value: 'high' } as TReasoningOverride;
+ mockAgentQueryData.current = {
+ id: agentId,
+ provider: 'openAI',
+ model: 'gpt-5.1',
+ } as Agent;
+ const { result, setSubmission, reasoningStore } = renderAsk([], 'conversation-uncatalogued', {
+ agentId,
+ reasoningOverride: override,
+ });
+
+ act(() => {
+ result.current.ask({ text: 'Think carefully' });
+ });
+
+ const submission = setSubmission.mock.calls.at(-1)?.[0] as TSubmission;
+ expect(submission.userMessage.reasoningOverride).toEqual(override);
+ expect(
+ reasoningStore.get(pendingReasoningOverrideFamily('conversation-uncatalogued')),
+ ).toBeUndefined();
+ expect(mockGetQueryData).toHaveBeenCalledWith([QueryKeys.agent, agentId]);
+ });
});
describe('useChatFunctions regenerate', () => {
beforeEach(() => {
jest.clearAllMocks();
- mockGetQueryData.mockReturnValue({});
+ mockAgentQueryData.current = undefined;
});
it('keys a non-tail regenerate to the selected assistant response', () => {
@@ -517,12 +728,41 @@ describe('useChatFunctions regenerate', () => {
expect(submission.initialResponse?.clientQueueParentMessageId).toBe('user-1');
},
);
+ it('replays the original user turn reasoning override on regenerate', () => {
+ const parent = {
+ ...userMessage('user-reasoning'),
+ reasoningOverride: { key: 'reasoning_effort', value: 'high' },
+ } as TMessage;
+ const response = assistantMessage('assistant-reasoning', parent.messageId);
+ const { result, setSubmission } = renderAsk([parent, response]);
+
+ act(() => {
+ result.current.regenerate(response);
+ });
+
+ const submission = setSubmission.mock.calls.at(-1)?.[0] as TSubmission;
+ expect(submission.userMessage.reasoningOverride).toEqual(parent.reasoningOverride);
+ });
+
+ it('drops a replayed reasoning override that the selected model no longer supports', () => {
+ const parent = {
+ ...userMessage('user-reasoning'),
+ reasoningOverride: { key: 'effort', value: 'max' },
+ } as TMessage;
+ const response = assistantMessage('assistant-reasoning', parent.messageId);
+ const { result, setSubmission } = renderAsk([parent, response]);
+
+ act(() => result.current.regenerate(response));
+
+ const submission = setSubmission.mock.calls.at(-1)?.[0] as TSubmission;
+ expect(submission.userMessage.reasoningOverride).toBeUndefined();
+ });
});
describe('useChatFunctions ask attachments', () => {
beforeEach(() => {
jest.clearAllMocks();
- mockGetQueryData.mockReturnValue({});
+ mockAgentQueryData.current = undefined;
});
afterEach(() => {
mockGetEphemeralAgent.mockReturnValue(null);
diff --git a/client/src/hooks/Chat/__tests__/useQueueDrain.spec.tsx b/client/src/hooks/Chat/__tests__/useQueueDrain.spec.tsx
index 40246872fa..924667b1f5 100644
--- a/client/src/hooks/Chat/__tests__/useQueueDrain.spec.tsx
+++ b/client/src/hooks/Chat/__tests__/useQueueDrain.spec.tsx
@@ -1,7 +1,7 @@
import React from 'react';
import { getDefaultStore } from 'jotai';
-import { Constants } from 'librechat-data-provider';
import { act, renderHook, waitFor } from '@testing-library/react';
+import { Constants, ReasoningEffort } from 'librechat-data-provider';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { RecoilRoot, useRecoilValue, useSetRecoilState, type MutableSnapshot } from 'recoil';
import type {
@@ -10,7 +10,12 @@ import type {
QueuedMessage,
SettledQueuedTurnReceipt,
} from '~/store/families';
-import { recoveryDispositionsFamily } from '~/components/Chat/Steering/recovery';
+import {
+ claimQueuedIntent,
+ releaseQueuedIntent,
+ acquireQueueSendLock,
+ releaseQueueSendLock,
+} from '~/utils/queueIntent';
import { revealedQueuedTurnFamily } from '~/store/steer';
import useQueueDrain from '../useQueueDrain';
import store from '~/store';
@@ -37,6 +42,7 @@ function setup(
setNewConvoQueue?: (value: QueuedMessage[]) => void;
setSettledReceipts?: (value: SettledQueuedTurnReceipt[]) => void;
setInterruptFlag?: (value: DrainAfterAbort | false) => void;
+ queueRef?: { current: QueuedMessage[] };
queue?: QueuedMessage[];
newConvoQueue?: QueuedMessage[];
settledReceipts?: SettledQueuedTurnReceipt[];
@@ -47,6 +53,9 @@ function setup(
setters.setRunEnd = useSetRecoilState(store.runEndByIndex(INDEX));
setters.setIsSubmitting = useSetRecoilState(store.isSubmittingFamily(INDEX));
setters.setQueue = useSetRecoilState(store.queuedMessagesByConvoId(CONVO_ID));
+ setters.queueRef = {
+ current: useRecoilValue(store.queuedMessagesByConvoId(CONVO_ID)),
+ };
setters.setNewConvoQueue = useSetRecoilState(
store.queuedMessagesByConvoId(Constants.NEW_CONVO),
);
@@ -83,6 +92,7 @@ const emptyOverrides = expect.objectContaining({
overrideFiles: [],
overrideQuotes: [],
overrideManualSkills: [],
+ overrideReasoning: null,
overrideQueuedMessageOrigin: expect.any(Object),
});
@@ -195,6 +205,37 @@ describe('useQueueDrain', () => {
expect(ask).toHaveBeenCalledWith({ text: 'first follow-up' }, emptyOverrides);
});
+ it('leaves a rejected steer for an explicit send and drains the row behind it', async () => {
+ const { ask, setters } = setup(({ set }) => {
+ set(store.queuedMessagesByConvoId(CONVO_ID), [
+ { ...queuedMessage('q-rejected', 'the server refused this'), needsExplicitSend: true },
+ queuedMessage('q2', 'second follow-up'),
+ ]);
+ });
+
+ act(() => {
+ setters.setRunEnd!(runEnd({ generationCreatedAt: 1234 }));
+ });
+
+ await waitFor(() => expect(ask).toHaveBeenCalledTimes(1));
+ expect(ask).toHaveBeenCalledWith({ text: 'second follow-up' }, emptyOverrides);
+ });
+
+ it('sends nothing when every queued row awaits an explicit send', async () => {
+ const { ask, setters } = setup(({ set }) => {
+ set(store.queuedMessagesByConvoId(CONVO_ID), [
+ { ...queuedMessage('q-rejected', 'the server refused this'), needsExplicitSend: true },
+ ]);
+ });
+
+ act(() => {
+ setters.setRunEnd!(runEnd({ generationCreatedAt: 1234 }));
+ });
+
+ await new Promise((resolve) => setTimeout(resolve, 25));
+ expect(ask).not.toHaveBeenCalled();
+ });
+
it('does not locally drain or renew server-owned Agent rows', async () => {
const { ask, setters } = setup(({ set }) => {
set(store.queuedMessagesByConvoId(CONVO_ID), [
@@ -800,13 +841,14 @@ describe('useQueueDrain', () => {
expect(sent).toEqual(['only-once']);
});
- it('passes carried quotes + manual skills through as overrides', async () => {
+ it('passes carried quotes, skills, and reasoning through as overrides', async () => {
const { ask, setters } = setup(({ set }) => {
set(store.queuedMessagesByConvoId(CONVO_ID), [
{
...queuedMessage('q1', 'with context'),
quotes: ['quoted excerpt'],
manualSkills: ['skill-1'],
+ reasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.high },
},
]);
});
@@ -822,6 +864,7 @@ describe('useQueueDrain', () => {
overrideFiles: [],
overrideQuotes: ['quoted excerpt'],
overrideManualSkills: ['skill-1'],
+ overrideReasoning: { key: 'reasoning_effort', value: ReasoningEffort.high },
overrideQueuedMessageOrigin: expect.any(Object),
}),
);
@@ -1040,6 +1083,26 @@ describe('useQueueDrain', () => {
);
});
+ it('preserves a manually reordered NEW_CONVO queue during migration', async () => {
+ const { ask, setters } = setup(({ set }) => {
+ set(store.queuedMessagesByConvoId(Constants.NEW_CONVO), [
+ { id: 'second', text: 'send this first', createdAt: 2 },
+ { id: 'first', text: 'send this second', createdAt: 1 },
+ ]);
+ set(store.queuedMessagesByConvoId(CONVO_ID), [
+ { id: 'third', text: 'send this third', createdAt: 3 },
+ ]);
+ });
+
+ act(() => {
+ setters.setRunEnd!(runEnd({ startedAsNewConvo: true }));
+ });
+
+ await waitFor(() =>
+ expect(ask).toHaveBeenCalledWith({ text: 'send this first' }, emptyOverrides),
+ );
+ });
+
it('keeps an interrupt queued after URL resolution ahead of pre-migration follow-ups', async () => {
const { ask, setters } = setup(({ set }) => {
set(store.queuedMessagesByConvoId(Constants.NEW_CONVO), [
@@ -1185,4 +1248,98 @@ describe('useQueueDrain', () => {
await new Promise((resolve) => setTimeout(resolve, 25));
expect(ask).toHaveBeenCalledTimes(1);
});
+
+ /* Edit and Remove on the rail hand a row's words to the composer across an
+ await, and the run end can land inside that gap. Dequeuing there sent the
+ very message the user was in the middle of taking back. */
+ describe('rows the rail has claimed', () => {
+ afterEach(() => {
+ releaseQueuedIntent('q-claimed');
+ releaseQueuedIntent('q-only');
+ });
+
+ it('skips a claimed row and sends the next one instead', async () => {
+ claimQueuedIntent('q-claimed');
+ const { ask, setters } = setup(({ set }) => {
+ set(store.queuedMessagesByConvoId(CONVO_ID), [
+ queuedMessage('q-claimed', 'being taken back'),
+ queuedMessage('q-next', 'still wanted'),
+ ]);
+ });
+
+ act(() => {
+ setters.setRunEnd!(runEnd());
+ });
+ await waitFor(() =>
+ expect(ask).toHaveBeenCalledWith({ text: 'still wanted' }, emptyOverrides),
+ );
+ expect(ask).toHaveBeenCalledTimes(1);
+ });
+
+ it('restores a refused skipped row after its claimed predecessor', async () => {
+ claimQueuedIntent('q-claimed');
+ const { ask, setters } = setup(({ set }) => {
+ set(store.queuedMessagesByConvoId(CONVO_ID), [
+ queuedMessage('q-claimed', 'being taken back'),
+ queuedMessage('q-next', 'temporarily refused'),
+ queuedMessage('q-tail', 'still last'),
+ ]);
+ });
+ ask.mockReturnValue(false);
+
+ act(() => {
+ setters.setRunEnd!(runEnd());
+ });
+
+ await waitFor(() => expect(ask).toHaveBeenCalledTimes(1));
+ await waitFor(() =>
+ expect(setters.queueRef?.current.map((item) => item.id)).toEqual([
+ 'q-claimed',
+ 'q-next',
+ 'q-tail',
+ ]),
+ );
+ });
+
+ it('sends nothing when the only queued row is claimed', async () => {
+ claimQueuedIntent('q-only');
+ const { ask, setters } = setup(({ set }) => {
+ set(store.queuedMessagesByConvoId(CONVO_ID), [queuedMessage('q-only', 'mine for now')]);
+ });
+
+ act(() => {
+ setters.setRunEnd!(runEnd());
+ });
+ await new Promise((resolve) => setTimeout(resolve, 25));
+ expect(ask).not.toHaveBeenCalled();
+ });
+ });
+
+ /* `isSubmitting` is a render-old read on both sides, so the rail's own Send
+ now can already have called `ask` for this pane in the current task. */
+ it('refuses to drain while a queued send holds the pane', async () => {
+ const held = acquireQueueSendLock(String(INDEX));
+ const { ask, setters } = setup(({ set }) => {
+ set(store.queuedMessagesByConvoId(CONVO_ID), [queuedMessage('q-lock', 'after the hold')]);
+ });
+
+ act(() => {
+ setters.setRunEnd!(runEnd());
+ });
+ await new Promise((resolve) => setTimeout(resolve, 25));
+ expect(ask).not.toHaveBeenCalled();
+
+ /* The signal was never consumed, so the queue is reconsidered rather than
+ dropped as soon as the pane's submission state moves again. */
+ releaseQueueSendLock(held);
+ act(() => {
+ setters.setIsSubmitting!(true);
+ });
+ act(() => {
+ setters.setIsSubmitting!(false);
+ });
+ await waitFor(() =>
+ expect(ask).toHaveBeenCalledWith({ text: 'after the hold' }, emptyOverrides),
+ );
+ });
});
diff --git a/client/src/hooks/Chat/__tests__/useSteerCancel.spec.tsx b/client/src/hooks/Chat/__tests__/useSteerCancel.spec.tsx
new file mode 100644
index 0000000000..75d5ada469
--- /dev/null
+++ b/client/src/hooks/Chat/__tests__/useSteerCancel.spec.tsx
@@ -0,0 +1,290 @@
+import React from 'react';
+import { RecoilRoot, useRecoilValue } from 'recoil';
+import { act, renderHook } from '@testing-library/react';
+import { ReasoningEffort } from 'librechat-data-provider';
+import type { RestoreToComposer } from '~/Providers/ComposerRestoreContext';
+import type { PendingSteer } from '~/store/families';
+import {
+ ComposerRestoreProvider,
+ useComposerRestoreHost,
+} from '~/Providers/ComposerRestoreContext';
+import useSteerCancel, { useSteerMoveToQueue } from '../useSteerCancel';
+import store from '~/store';
+
+const mockCancelAsync = jest.fn();
+
+jest.mock('~/data-provider', () => ({
+ useCancelSteerMutation: () => ({ mutateAsync: mockCancelAsync }),
+ fetchStreamStatus: jest.fn(),
+ getGenerationProtocolVersion: jest.fn(),
+}));
+
+const CONVO_ID = 'convo-steer-cancel';
+
+const pending = (overrides: Partial<PendingSteer> = {}): PendingSteer => ({
+ steerId: 'srv-1',
+ clientSteerId: 'local-1',
+ text: 'move this later',
+ status: 'pending',
+ createdAt: 10,
+ generationCreatedAt: 100,
+ generationProtocolVersion: 2,
+ quotes: ['quoted context'],
+ manualSkills: ['skill-1'],
+ ...overrides,
+});
+
+function setup(steer: PendingSteer) {
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
+ <RecoilRoot
+ initializeState={({ set }) => {
+ set(store.activeGenerationCreatedAtByConvoId(CONVO_ID), 100);
+ set(store.pendingSteersByConvoId(CONVO_ID), [steer]);
+ }}
+ >
+ {children}
+ </RecoilRoot>
+ );
+ return renderHook(
+ () => ({
+ moveToQueue: useSteerMoveToQueue(CONVO_ID),
+ chips: useRecoilValue(store.pendingSteersByConvoId(CONVO_ID)),
+ queue: useRecoilValue(store.queuedMessagesByConvoId(CONVO_ID)),
+ }),
+ { wrapper },
+ );
+}
+
+describe('useSteerMoveToQueue', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it('moves only a confirmed reclaim into an ordinary queue row', async () => {
+ mockCancelAsync.mockResolvedValue({ removed: true });
+ const steer = pending();
+ const { result } = setup(steer);
+
+ let outcome: string | undefined;
+ await act(async () => {
+ outcome = await result.current.moveToQueue(steer);
+ });
+
+ expect(outcome).toBe('reclaimed');
+ expect(result.current.chips).toEqual([]);
+ expect(result.current.queue).toEqual([
+ {
+ id: 'srv-1',
+ text: 'move this later',
+ createdAt: 10,
+ quotes: ['quoted context'],
+ manualSkills: ['skill-1'],
+ },
+ ]);
+ });
+
+ it('restores a reclaimed queued origin without recovery fields', async () => {
+ mockCancelAsync.mockResolvedValue({ removed: true });
+ const original = {
+ id: 'queue-original',
+ text: 'move this later',
+ createdAt: 5,
+ priority: true,
+ };
+ const steer = pending({
+ queuedOrigin: { item: original, beforeIds: [], afterIds: [] },
+ });
+ const { result } = setup(steer);
+
+ await act(async () => {
+ await result.current.moveToQueue(steer);
+ });
+
+ expect(result.current.queue).toEqual([original]);
+ });
+
+ /* The run can finish while the cancel is in flight; its drain signal was
+ spent on a queue this row was not in yet, so the conversion re-posts it. */
+ it('re-arms the run-end drain after converting a reclaimed steer', async () => {
+ mockCancelAsync.mockResolvedValue({ removed: true });
+ const rewake = jest.fn();
+ const steer = pending();
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
+ <RecoilRoot
+ initializeState={({ set }) => {
+ set(store.activeGenerationCreatedAtByConvoId(CONVO_ID), 100);
+ set(store.pendingSteersByConvoId(CONVO_ID), [steer]);
+ }}
+ >
+ <ComposerRestoreProvider>
+ <RewakePublisher rewake={rewake}>{children}</RewakePublisher>
+ </ComposerRestoreProvider>
+ </RecoilRoot>
+ );
+ const { result } = renderHook(
+ () => ({
+ moveToQueue: useSteerMoveToQueue(CONVO_ID),
+ queue: useRecoilValue(store.queuedMessagesByConvoId(CONVO_ID)),
+ }),
+ { wrapper },
+ );
+
+ await act(async () => {
+ await result.current.moveToQueue(steer);
+ });
+
+ expect(result.current.queue).toHaveLength(1);
+ expect(rewake).toHaveBeenCalledWith(CONVO_ID);
+ });
+
+ it('leaves an already applied steer under server ownership', async () => {
+ mockCancelAsync.mockResolvedValue({ removed: false });
+ const steer = pending();
+ const { result } = setup(steer);
+
+ let outcome: string | undefined;
+ await act(async () => {
+ outcome = await result.current.moveToQueue(steer);
+ });
+
+ expect(outcome).toBe('applied');
+ expect(result.current.chips).toEqual([steer]);
+ expect(result.current.queue).toEqual([]);
+ });
+});
+
+/** Publishes a drain re-arm the way `ChatForm` does. */
+function RewakePublisher({
+ rewake,
+ children,
+}: {
+ rewake: (conversationId: string) => void;
+ children: React.ReactNode;
+}) {
+ const { publishRewake } = useComposerRestoreHost();
+ React.useEffect(() => {
+ publishRewake(rewake);
+ return () => publishRewake(null);
+ }, [publishRewake, rewake]);
+ return <>{children}</>;
+}
+
+/** Publishes a composer restore the way `ChatForm` does, so the cancel path
+ * runs against the real registry rather than a mocked module. */
+function Publisher({
+ restore,
+ children,
+}: {
+ restore: RestoreToComposer;
+ children: React.ReactNode;
+}) {
+ const { publish } = useComposerRestoreHost();
+ React.useEffect(() => {
+ publish(restore);
+ return () => publish(null);
+ }, [publish, restore]);
+ return <>{children}</>;
+}
+
+function setupCancel(
+ steer: PendingSteer,
+ restore: RestoreToComposer,
+ rewake: (conversationId: string) => void = () => {},
+) {
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
+ <RecoilRoot
+ initializeState={({ set }) => {
+ set(store.activeGenerationCreatedAtByConvoId(CONVO_ID), 100);
+ set(store.pendingSteersByConvoId(CONVO_ID), [steer]);
+ }}
+ >
+ <ComposerRestoreProvider>
+ <RewakePublisher rewake={rewake}>
+ <Publisher restore={restore}>{children}</Publisher>
+ </RewakePublisher>
+ </ComposerRestoreProvider>
+ </RecoilRoot>
+ );
+ return renderHook(
+ () => ({
+ cancel: useSteerCancel(CONVO_ID),
+ chips: useRecoilValue(store.pendingSteersByConvoId(CONVO_ID)),
+ queue: useRecoilValue(store.queuedMessagesByConvoId(CONVO_ID)),
+ }),
+ { wrapper },
+ );
+}
+
+describe('useSteerCancel', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it('hands the whole reclaimed steer back to the composer, not just its text', async () => {
+ mockCancelAsync.mockResolvedValue({ removed: true });
+ const restore = jest.fn().mockReturnValue(true);
+ const reasoningOverride = {
+ key: 'reasoning_effort',
+ value: ReasoningEffort.high,
+ } as const;
+ const steer = pending({
+ files: [{ file_id: 'file-1', filename: 'notes.txt' }],
+ reasoningOverride,
+ });
+ const { result } = setupCancel(steer, restore);
+
+ await act(async () => {
+ await result.current.cancel(steer);
+ });
+
+ expect(restore).toHaveBeenCalledWith(
+ 'move this later',
+ [{ file_id: 'file-1', filename: 'notes.txt' }],
+ { quotes: ['quoted context'], manualSkills: ['skill-1'], reasoningOverride },
+ CONVO_ID,
+ );
+ expect(result.current.chips).toEqual([]);
+ expect(result.current.queue).toEqual([]);
+ });
+
+ it('queues the whole steer when the composer refuses it', async () => {
+ mockCancelAsync.mockResolvedValue({ removed: true });
+ const restore = jest.fn().mockReturnValue(false);
+ const rewake = jest.fn();
+ const steer = pending();
+ const { result } = setupCancel(steer, restore, rewake);
+
+ await act(async () => {
+ await result.current.cancel(steer);
+ });
+
+ expect(rewake).toHaveBeenCalledWith(CONVO_ID);
+ expect(result.current.chips).toEqual([]);
+ expect(result.current.queue).toEqual([
+ {
+ id: 'srv-1',
+ text: 'move this later',
+ createdAt: 10,
+ quotes: ['quoted context'],
+ manualSkills: ['skill-1'],
+ },
+ ]);
+ });
+
+ it('leaves an applied steer alone instead of recovering it', async () => {
+ mockCancelAsync.mockResolvedValue({ removed: false });
+ const restore = jest.fn().mockReturnValue(true);
+ const steer = pending();
+ const { result } = setupCancel(steer, restore);
+
+ let outcome: string | undefined;
+ await act(async () => {
+ outcome = await result.current.cancel(steer);
+ });
+
+ expect(outcome).toBe('applied');
+ expect(restore).not.toHaveBeenCalled();
+ expect(result.current.chips).toEqual([steer]);
+ expect(result.current.queue).toEqual([]);
+ });
+});
diff --git a/client/src/hooks/Chat/__tests__/useSteerConvert.spec.tsx b/client/src/hooks/Chat/__tests__/useSteerConvert.spec.tsx
index e94880b4b9..6e9af61c66 100644
--- a/client/src/hooks/Chat/__tests__/useSteerConvert.spec.tsx
+++ b/client/src/hooks/Chat/__tests__/useSteerConvert.spec.tsx
@@ -229,6 +229,21 @@ describe('useSteerConvert', () => {
]);
});
+ it('keeps a local v2 failure ordinary when no server receipt exists', () => {
+ const { result } = setup();
+ act(() => {
+ result.current.convert(
+ CONVO_ID,
+ [{ steerId: 'local-failure', text: 'queue locally', createdAt: 1 }],
+ { generationProtocolVersion: 2, bindRecoverySource: false },
+ );
+ });
+
+ expect(result.current.queue).toEqual([
+ { id: 'local-failure', text: 'queue locally', createdAt: 1 },
+ ]);
+ });
+
it('correlates a terminal leftover that arrives before the 202 ACK', () => {
const original = {
id: 'queue-before-ack',
@@ -333,6 +348,44 @@ describe('useSteerConvert', () => {
expect(result.current.queue.map((item) => item.id)).toEqual(['urgent', 'old']);
});
+ /* The rail can be reordered by hand, and that order decides what sends next.
+ A conversion arriving afterwards may only place its own items; sorting the
+ whole list would quietly restore the order the messages were written in. */
+ it('leaves a hand-reordered queue in the order the user left it', () => {
+ const { result } = setup(({ set }) => {
+ set(store.pendingSteersByConvoId(CONVO_ID), [
+ { steerId: 'srv-late', text: 'converted', status: 'pending' as const, createdAt: 9 },
+ ]);
+ // As if the user had dragged the newest message to the front.
+ set(store.queuedMessagesByConvoId(CONVO_ID), [
+ { id: 'm3', text: 'third, promoted', createdAt: 3 },
+ { id: 'm1', text: 'first', createdAt: 1 },
+ { id: 'm2', text: 'second', createdAt: 2 },
+ ]);
+ });
+ act(() => {
+ result.current.convert(CONVO_ID, [{ steerId: 'srv-late', text: 'converted', createdAt: 9 }]);
+ });
+ expect(result.current.queue.map((item) => item.id)).toEqual(['m3', 'm1', 'm2', 'srv-late']);
+ });
+
+ it('still places a converted steer ahead of messages written after it', () => {
+ const { result } = setup(({ set }) => {
+ set(store.pendingSteersByConvoId(CONVO_ID), [
+ { steerId: 'srv-early', text: 'accepted first', status: 'pending' as const, createdAt: 1 },
+ ]);
+ set(store.queuedMessagesByConvoId(CONVO_ID), [
+ { id: 'later', text: 'queued afterwards', createdAt: 5 },
+ ]);
+ });
+ act(() => {
+ result.current.convert(CONVO_ID, [
+ { steerId: 'srv-early', text: 'accepted first', createdAt: 1 },
+ ]);
+ });
+ expect(result.current.queue.map((item) => item.id)).toEqual(['srv-early', 'later']);
+ });
+
it('is idempotent across double delivery (abort response + final SSE event)', () => {
const { result } = setup();
const steers = [{ steerId: 'srv-2', text: 'delivered twice', createdAt: 5 }];
diff --git a/client/src/hooks/Chat/__tests__/useSteerEscalate.spec.tsx b/client/src/hooks/Chat/__tests__/useSteerEscalate.spec.tsx
new file mode 100644
index 0000000000..06b7af7b44
--- /dev/null
+++ b/client/src/hooks/Chat/__tests__/useSteerEscalate.spec.tsx
@@ -0,0 +1,339 @@
+import React from 'react';
+import { RecoilRoot, useRecoilValue } from 'recoil';
+import { getDefaultStore, useAtomValue } from 'jotai';
+import { act, renderHook, waitFor } from '@testing-library/react';
+import type { MutableSnapshot } from 'recoil';
+import type { PendingSteer } from '~/store/families';
+import { escalatingSteerFamily } from '~/store/steer';
+import useSteerEscalate from '../useSteerEscalate';
+import store from '~/store';
+
+const mockArmMutateAsync = jest.fn();
+const mockShowToast = jest.fn();
+type StartupConfigStub = { data?: { interface?: { steerArmConfirmationTimeoutMs?: number } } };
+const mockGetStartupConfig = jest.fn<StartupConfigStub, []>(() => ({ data: undefined }));
+
+jest.mock('@librechat/client', () => ({
+ useToastContext: () => ({ showToast: mockShowToast }),
+}));
+
+jest.mock('~/data-provider', () => ({
+ DEFAULT_STEER_ARM_CONFIRMATION_TIMEOUT_MS: 10_000,
+ useArmSteerMutation: () => ({ mutateAsync: mockArmMutateAsync }),
+ useGetStartupConfig: () => mockGetStartupConfig(),
+ supportsGenerationProtocolV2: (value: unknown) =>
+ value != null &&
+ typeof value === 'object' &&
+ (value as { generationProtocolVersion?: unknown }).generationProtocolVersion === 2,
+}));
+
+jest.mock('~/hooks/useLocalize', () => ({
+ __esModule: true,
+ default: () => (key: string) => key,
+}));
+
+const CONVO_ID = 'convo-steer-escalate';
+
+interface SetupOptions {
+ activeGenerationCreatedAt?: number | null;
+ activeGenerationProtocolVersion?: 1 | 2;
+ steers?: PendingSteer[];
+}
+
+const pending = (over: Partial<PendingSteer> = {}): PendingSteer => ({
+ steerId: 'steer-1',
+ text: 'change direction',
+ status: 'pending',
+ createdAt: 1,
+ ...over,
+});
+
+function setup({
+ activeGenerationCreatedAt = 41,
+ activeGenerationProtocolVersion = 2,
+ steers = [pending()],
+}: SetupOptions = {}) {
+ const initializeState = (snapshot: MutableSnapshot) => {
+ snapshot.set(store.pendingSteersByConvoId(CONVO_ID), steers);
+ if (activeGenerationCreatedAt != null) {
+ snapshot.set(store.activeGenerationCreatedAtByConvoId(CONVO_ID), activeGenerationCreatedAt);
+ }
+ snapshot.set(
+ store.activeGenerationProtocolVersionByConvoId(CONVO_ID),
+ activeGenerationProtocolVersion,
+ );
+ };
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
+ <RecoilRoot initializeState={initializeState}>{children}</RecoilRoot>
+ );
+
+ return renderHook(
+ () => ({
+ escalate: useSteerEscalate(CONVO_ID),
+ steers: useRecoilValue(store.pendingSteersByConvoId(CONVO_ID)),
+ escalating: useAtomValue(escalatingSteerFamily(CONVO_ID)),
+ }),
+ { wrapper },
+ );
+}
+
+describe('useSteerEscalate', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ act(() => getDefaultStore().set(escalatingSteerFamily(CONVO_ID), false));
+ mockGetStartupConfig.mockReturnValue({ data: undefined });
+ });
+
+ afterEach(() => {
+ jest.useRealTimers();
+ });
+
+ it('does not arm before a generation epoch is known', () => {
+ const { result } = setup({ activeGenerationCreatedAt: null });
+
+ act(() => result.current.escalate({ steerId: 'steer-1' }));
+
+ expect(mockArmMutateAsync).not.toHaveBeenCalled();
+ expect(result.current.escalating).toBe(false);
+ });
+
+ it('arms the existing steer in place and calls the success callback', async () => {
+ const onArmed = jest.fn();
+ mockArmMutateAsync.mockResolvedValue({
+ armed: true,
+ preemptRevision: 3,
+ generationProtocolVersion: 2,
+ });
+ const { result } = setup();
+
+ act(() => result.current.escalate({ steerId: 'steer-1', generationCreatedAt: 37 }, onArmed));
+
+ expect(mockArmMutateAsync).toHaveBeenCalledWith({
+ conversationId: CONVO_ID,
+ steerId: 'steer-1',
+ generationCreatedAt: 37,
+ });
+ await waitFor(() =>
+ expect(result.current.steers).toEqual([
+ expect.objectContaining({ steerId: 'steer-1', preempt: true, preemptRevision: 3 }),
+ ]),
+ );
+ expect(onArmed).toHaveBeenCalledTimes(1);
+ expect(result.current.escalating).toBe(false);
+ expect(mockShowToast).not.toHaveBeenCalled();
+ });
+
+ it('does not let an older confirmation overwrite a newer preempt revision', async () => {
+ mockArmMutateAsync.mockResolvedValue({
+ armed: true,
+ preemptRevision: 4,
+ generationProtocolVersion: 2,
+ });
+ const { result } = setup({
+ steers: [pending({ preempt: false, preemptRevision: 5 })],
+ });
+
+ act(() => result.current.escalate({ steerId: 'steer-1' }));
+
+ await waitFor(() => expect(result.current.escalating).toBe(false));
+ expect(result.current.steers).toEqual([
+ expect.objectContaining({ steerId: 'steer-1', preempt: false, preemptRevision: 5 }),
+ ]);
+ });
+
+ it('reports an unsupported preempt without relabelling the steer', async () => {
+ mockArmMutateAsync.mockResolvedValue({
+ armed: false,
+ code: 'PREEMPT_UNSUPPORTED',
+ generationProtocolVersion: 2,
+ });
+ const { result } = setup();
+
+ act(() => result.current.escalate({ steerId: 'steer-1' }));
+
+ await waitFor(() =>
+ expect(mockShowToast).toHaveBeenCalledWith({
+ message: 'com_ui_steer_preempt_unsupported',
+ status: 'info',
+ }),
+ );
+ expect(result.current.steers[0]).not.toHaveProperty('preempt', true);
+ });
+
+ it('reports a known lost race without retrying', async () => {
+ mockArmMutateAsync.mockResolvedValue({
+ armed: false,
+ generationProtocolVersion: 2,
+ });
+ const { result } = setup();
+
+ act(() => result.current.escalate({ steerId: 'steer-1' }));
+
+ await waitFor(() =>
+ expect(mockShowToast).toHaveBeenCalledWith({
+ message: 'com_ui_steer_arm_lost_race',
+ status: 'info',
+ }),
+ );
+ expect(mockArmMutateAsync).toHaveBeenCalledTimes(1);
+ });
+
+ it('retries one ambiguous protocol-v2 transport failure', async () => {
+ mockArmMutateAsync.mockRejectedValueOnce(new Error('response lost')).mockResolvedValueOnce({
+ armed: true,
+ preemptRevision: 1,
+ generationProtocolVersion: 2,
+ });
+ const { result } = setup();
+
+ act(() => result.current.escalate({ steerId: 'steer-1' }));
+
+ await waitFor(() => expect(mockArmMutateAsync).toHaveBeenCalledTimes(2));
+ await waitFor(() => expect(result.current.steers[0]).toHaveProperty('preempt', true));
+ expect(mockShowToast).not.toHaveBeenCalled();
+ });
+
+ it.each([400, 403, 409])('does not retry a definitive HTTP %s rejection', async (status) => {
+ mockArmMutateAsync.mockRejectedValue({
+ response: { status, data: { code: 'RUN_PAUSED' } },
+ });
+ const { result } = setup();
+
+ act(() => result.current.escalate({ steerId: 'steer-1' }));
+
+ await waitFor(() =>
+ expect(mockShowToast).toHaveBeenCalledWith({
+ message: 'com_ui_steer_arm_lost_race',
+ status: 'info',
+ }),
+ );
+ expect(mockArmMutateAsync).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not retry an ambiguous failure under protocol v1', async () => {
+ mockArmMutateAsync.mockRejectedValue(new Error('response lost'));
+ const { result } = setup({ activeGenerationProtocolVersion: 1 });
+
+ act(() => result.current.escalate({ steerId: 'steer-1' }));
+
+ await waitFor(() =>
+ expect(mockShowToast).toHaveBeenCalledWith({
+ message: 'com_ui_steer_arm_unconfirmed',
+ status: 'warning',
+ }),
+ );
+ expect(mockArmMutateAsync).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps a rejected-then-missing retry indeterminate', async () => {
+ mockArmMutateAsync
+ .mockRejectedValueOnce(new Error('response lost after commit'))
+ .mockResolvedValueOnce({ armed: false, generationProtocolVersion: 2 });
+ const { result } = setup();
+
+ act(() => result.current.escalate({ steerId: 'steer-1' }));
+
+ await waitFor(() =>
+ expect(mockShowToast).toHaveBeenCalledWith({
+ message: 'com_ui_steer_arm_unconfirmed',
+ status: 'warning',
+ }),
+ );
+ expect(mockArmMutateAsync).toHaveBeenCalledTimes(2);
+ expect(result.current.steers[0]).not.toHaveProperty('preempt', true);
+ });
+
+ it('rejects an unversioned success under negotiated protocol v2', async () => {
+ mockArmMutateAsync.mockResolvedValue({ armed: true, preemptRevision: 1 });
+ const { result } = setup();
+
+ act(() => result.current.escalate({ steerId: 'steer-1' }));
+
+ await waitFor(() =>
+ expect(mockShowToast).toHaveBeenCalledWith({
+ message: 'com_ui_steer_arm_unconfirmed',
+ status: 'warning',
+ }),
+ );
+ expect(result.current.steers[0]).not.toHaveProperty('preempt', true);
+ });
+
+ it('uses the configured arm confirmation timeout', async () => {
+ jest.useFakeTimers();
+ mockGetStartupConfig.mockReturnValue({
+ data: { interface: { steerArmConfirmationTimeoutMs: 20_000 } },
+ });
+ mockArmMutateAsync.mockReturnValue(new Promise(() => undefined));
+ const { result } = setup();
+
+ act(() => result.current.escalate({ steerId: 'steer-1' }));
+ expect(result.current.escalating).toBe(true);
+
+ await act(async () => {
+ jest.advanceTimersByTime(10_000);
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+ expect(mockShowToast).not.toHaveBeenCalled();
+ expect(result.current.escalating).toBe(true);
+
+ await act(async () => {
+ jest.advanceTimersByTime(10_000);
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+
+ expect(mockShowToast).toHaveBeenCalledWith({
+ message: 'com_ui_steer_arm_unconfirmed',
+ status: 'warning',
+ });
+ expect(result.current.escalating).toBe(false);
+ });
+
+ it('warns and unlocks when arm confirmation times out', async () => {
+ jest.useFakeTimers();
+ mockArmMutateAsync.mockReturnValue(new Promise(() => undefined));
+ const { result } = setup();
+
+ act(() => result.current.escalate({ steerId: 'steer-1' }));
+ expect(result.current.escalating).toBe(true);
+
+ await act(async () => {
+ jest.advanceTimersByTime(10_000);
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+
+ expect(mockShowToast).toHaveBeenCalledWith({
+ message: 'com_ui_steer_arm_unconfirmed',
+ status: 'warning',
+ });
+ expect(result.current.escalating).toBe(false);
+ expect(mockArmMutateAsync).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not start a detached retry when the first request rejects after timeout', async () => {
+ jest.useFakeTimers();
+ let rejectArm: (reason?: unknown) => void = () => undefined;
+ mockArmMutateAsync.mockReturnValue(
+ new Promise((_resolve, reject) => {
+ rejectArm = reject;
+ }),
+ );
+ const { result } = setup();
+
+ act(() => result.current.escalate({ steerId: 'steer-1' }));
+ await act(async () => {
+ jest.advanceTimersByTime(10_000);
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+ await act(async () => {
+ rejectArm(new Error('late network failure'));
+ await Promise.resolve();
+ });
+
+ expect(mockArmMutateAsync).toHaveBeenCalledTimes(1);
+ expect(result.current.escalating).toBe(false);
+ });
+});
diff --git a/client/src/hooks/Chat/__tests__/useSteerRecovery.spec.tsx b/client/src/hooks/Chat/__tests__/useSteerRecovery.spec.tsx
new file mode 100644
index 0000000000..ed033ca567
--- /dev/null
+++ b/client/src/hooks/Chat/__tests__/useSteerRecovery.spec.tsx
@@ -0,0 +1,1006 @@
+import React from 'react';
+import { getDefaultStore } from 'jotai';
+import { act, render, renderHook } from '@testing-library/react';
+import { RecoilRoot, useRecoilValue, useSetRecoilState, type MutableSnapshot } from 'recoil';
+import type { RewakeDrain } from '~/Providers/ComposerRestoreContext';
+import {
+ ComposerRestoreProvider,
+ useComposerRestoreHost,
+} from '~/Providers/ComposerRestoreContext';
+import { pendingSteerCancelClientIdsFamily } from '~/store/steer';
+import useSteerRecovery from '../useSteerRecovery';
+import store from '~/store';
+
+const mockMutateAsync = jest.fn();
+const mockCancelSteer = jest.fn();
+
+jest.mock('~/data-provider', () => ({
+ useSteerMessageMutation: () => ({ mutateAsync: mockMutateAsync }),
+ useCancelSteerMutation: () => ({ mutateAsync: mockCancelSteer }),
+}));
+
+/** The POST settles through the returned promise, so every case has to let the
+ * microtask queue run before asserting. */
+const flush = () => act(async () => undefined);
+
+const CONVO_ID = 'convo-steer-recovery';
+
+/** The hook resolves "is the run over" from the conversation's own submitting
+ * state, not from its own unmount, so every case has to place the
+ * conversation in the store the way `ChatView` does. */
+const seedRun = (snapshot: MutableSnapshot, submitting: boolean) => {
+ snapshot.set(store.conversationKeysAtom, [0]);
+ snapshot.set(store.conversationByIndex(0), { conversationId: CONVO_ID } as never);
+ snapshot.set(store.isSubmittingFamily(0), submitting);
+};
+
+/** Publishes a drain wake-up the way `ChatForm` does, so the retry path runs
+ * against the real host rather than a mocked module. */
+function RewakePublisher({ rewake, children }: { rewake: RewakeDrain; children: React.ReactNode }) {
+ const { publishRewake } = useComposerRestoreHost();
+ React.useEffect(() => {
+ publishRewake(rewake);
+ return () => publishRewake(null);
+ }, [publishRewake, rewake]);
+ return <>{children}</>;
+}
+
+function setup(initialize?: (snapshot: MutableSnapshot) => void, rewake?: RewakeDrain) {
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
+ <RecoilRoot
+ initializeState={(snapshot) => {
+ seedRun(snapshot, true);
+ initialize?.(snapshot);
+ }}
+ >
+ <ComposerRestoreProvider>
+ {rewake ? <RewakePublisher rewake={rewake}>{children}</RewakePublisher> : children}
+ </ComposerRestoreProvider>
+ </RecoilRoot>
+ );
+ return renderHook(
+ () => ({
+ recovery: useSteerRecovery(CONVO_ID),
+ chips: useRecoilValue(store.pendingSteersByConvoId(CONVO_ID)),
+ queue: useRecoilValue(store.queuedMessagesByConvoId(CONVO_ID)),
+ applied: useRecoilValue(store.appliedSteerIdsByConvoId(CONVO_ID)),
+ accepted: useRecoilValue(store.acceptedSteerClientIdsByConvoId(CONVO_ID)),
+ }),
+ { wrapper },
+ );
+}
+
+describe('useSteerRecovery', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ getDefaultStore().set(pendingSteerCancelClientIdsFamily(CONVO_ID), []);
+ });
+
+ describe('retry', () => {
+ it('marks the chip sending immediately', () => {
+ mockMutateAsync.mockReturnValue(new Promise(() => undefined));
+ const { result } = setup(({ set }) => {
+ set(store.pendingSteersByConvoId(CONVO_ID), [
+ { steerId: 'local-1', text: 'redo this', status: 'failed', createdAt: 5 },
+ ]);
+ });
+ act(() => {
+ result.current.recovery.retry('local-1');
+ });
+ expect(result.current.chips).toEqual([
+ expect.objectContaining({ steerId: 'local-1', status: 'sending' }),
+ ]);
+ });
+
+ it('does not retry an uncertain protocol-v1 delivery', () => {
+ const { result } = setup(({ set }) => {
+ set(store.pendingSteersByConvoId(CONVO_ID), [
+ {
+ steerId: 'legacy-uncertain',
+ text: 'may already be committed',
+ status: 'failed',
+ deliveryUncertain: true,
+ generationProtocolVersion: 1,
+ createdAt: 5,
+ },
+ ]);
+ });
+
+ act(() => result.current.recovery.retry('legacy-uncertain'));
+
+ expect(mockMutateAsync).not.toHaveBeenCalled();
+ expect(result.current.chips).toEqual([
+ expect.objectContaining({ steerId: 'legacy-uncertain', status: 'failed' }),
+ ]);
+ });
+
+ it('swaps the local id for the server id on success, keeping it pending', async () => {
+ mockMutateAsync.mockResolvedValue({
+ steerId: 'srv-9',
+ status: 'queued',
+ position: 1,
+ conversationId: CONVO_ID,
+ });
+ const { result } = setup(({ set }) => {
+ set(store.pendingSteersByConvoId(CONVO_ID), [
+ { steerId: 'local-1', text: 'redo this', status: 'failed', createdAt: 5 },
+ ]);
+ });
+ act(() => {
+ result.current.recovery.retry('local-1');
+ });
+ await flush();
+ // The old local id must be gone entirely: leaving it behind is what let
+ // the applied SteerPart and a stale pending copy render together.
+ expect(result.current.chips).toEqual([
+ expect.objectContaining({ steerId: 'srv-9', text: 'redo this', status: 'pending' }),
+ ]);
+ });
+
+ it('clears delivery uncertainty after an idempotent retry succeeds', async () => {
+ mockMutateAsync.mockResolvedValue({
+ steerId: 'srv-safe',
+ status: 'queued',
+ position: 1,
+ conversationId: CONVO_ID,
+ });
+ const { result } = setup(({ set }) => {
+ set(store.pendingSteersByConvoId(CONVO_ID), [
+ {
+ steerId: 'local-safe',
+ text: 'retry safely',
+ status: 'failed',
+ deliveryUncertain: true,
+ generationProtocolVersion: 2,
+ createdAt: 5,
+ },
+ ]);
+ });
+
+ act(() => result.current.recovery.retry('local-safe'));
+ await flush();
+
+ expect(result.current.chips).toEqual([
+ expect.objectContaining({ steerId: 'srv-safe', status: 'pending' }),
+ ]);
+ expect(result.current.chips[0].deliveryUncertain).toBeUndefined();
+ });
+
+ it('routes to the queue on NO_ACTIVE_RUN instead of marking it failed again', async () => {
+ mockMutateAsync.mockRejectedValue({ response: { data: { code: 'NO_ACTIVE_RUN' } } });
+ const { result } = setup(({ set }) => {
+ set(store.pendingSteersByConvoId(CONVO_ID), [
+ { steerId: 'local-2', text: 'too late', status: 'failed', createdAt: 7 },
+ ]);
+ });
+ act(() => {
+ result.current.recovery.retry('local-2');
+ });
+ await flush();
+ expect(result.current.chips).toEqual([]);
+ expect(result.current.queue).toEqual([
+ expect.objectContaining({ id: 'local-2', text: 'too late' }),
+ ]);
+ });
+
+ /* A retry is kept out of the run-end sweep while it is `sending`, so a run
+ that finished during the POST has already spent its drain signal on a
+ queue this row was not in yet. Queueing it has to wake the drain. */
+ it('wakes the queue drain when a late retry lands in the queue', async () => {
+ mockMutateAsync.mockRejectedValue({ response: { data: { code: 'NO_ACTIVE_RUN' } } });
+ const rewake = jest.fn();
+ const { result } = setup(({ set }) => {
+ set(store.pendingSteersByConvoId(CONVO_ID), [
+ { steerId: 'local-late', text: 'after the end', status: 'failed', createdAt: 8 },
+ ]);
+ }, rewake);
+ act(() => {
+ result.current.recovery.retry('local-late');
+ });
+ await flush();
+ expect(result.current.queue).toEqual([
+ expect.objectContaining({ id: 'local-late', text: 'after the end' }),
+ ]);
+ expect(rewake).toHaveBeenCalledWith(CONVO_ID);
+ });
+
+ it('leaves the drain alone when a retry is accepted into a live run', async () => {
+ mockMutateAsync.mockResolvedValue({ steerId: 'srv-live', preempt: false });
+ const rewake = jest.fn();
+ const { result } = setup(({ set }) => {
+ set(store.pendingSteersByConvoId(CONVO_ID), [
+ { steerId: 'local-live', text: 'still running', status: 'failed', createdAt: 9 },
+ ]);
+ }, rewake);
+ act(() => {
+ result.current.recovery.retry('local-live');
+ });
+ await flush();
+ expect(result.current.queue).toEqual([]);
+ expect(rewake).not.toHaveBeenCalled();
+ });
+
+ /* The user can hit Cancel while a retry POST is already on the wire. The
+ marker the optimistic cancel arms has to be consulted when the POST
+ settles: accepting its ack would inject words the user asked back, and
+ clearing the marker without a deferred cancel loses them entirely. */
+ describe('a cancel that raced the retry POST', () => {
+ const armCancelMarker = (clientId: string) => {
+ getDefaultStore().set(pendingSteerCancelClientIdsFamily(CONVO_ID), [clientId]);
+ };
+
+ it('returns the words instead of injecting them when the cancel wins', async () => {
+ let settlePost: (value: unknown) => void = () => undefined;
+ mockMutateAsync.mockReturnValue(new Promise((resolve) => (settlePost = resolve)));
+ mockCancelSteer.mockResolvedValue({ removed: true });
+ const rewake = jest.fn();
+ let recovery: ReturnType<typeof useSteerRecovery> | undefined;
+ let chips: unknown[] = [];
+ let queue: unknown[] = [];
+ let accepted: unknown[] = [];
+ let cancelLikeTheUiDoes: () => void = () => undefined;
+ function Tree() {
+ recovery = useSteerRecovery(CONVO_ID);
+ chips = useRecoilValue(store.pendingSteersByConvoId(CONVO_ID));
+ queue = useRecoilValue(store.queuedMessagesByConvoId(CONVO_ID));
+ accepted = useRecoilValue(store.acceptedSteerClientIdsByConvoId(CONVO_ID));
+ const setChips = useSetRecoilState(store.pendingSteersByConvoId(CONVO_ID));
+ /* What the optimistic cancel does to a `sending` chip: hide it and
+ arm the marker the deferred settle has to consult. */
+ cancelLikeTheUiDoes = () =>
+ setChips((prev) => prev.filter((chip) => chip.steerId !== 'local-race'));
+ return null;
+ }
+ render(
+ <ComposerRestoreProvider>
+ <RecoilRoot
+ initializeState={(snapshot) => {
+ seedRun(snapshot, true);
+ snapshot.set(store.pendingSteersByConvoId(CONVO_ID), [
+ {
+ steerId: 'local-race',
+ text: 'changed my mind',
+ status: 'failed',
+ createdAt: 4,
+ },
+ ]);
+ }}
+ >
+ <RewakePublisher rewake={rewake}>
+ <Tree />
+ </RewakePublisher>
+ </RecoilRoot>
+ </ComposerRestoreProvider>,
+ );
+ act(() => {
+ recovery?.retry('local-race');
+ });
+ act(() => {
+ cancelLikeTheUiDoes();
+ armCancelMarker('local-race');
+ });
+ await act(async () => {
+ settlePost({ steerId: 'srv-race', preempt: false });
+ });
+ await flush();
+ expect(mockCancelSteer).toHaveBeenCalledWith(
+ expect.objectContaining({ steerId: 'srv-race', clientSteerId: 'local-race' }),
+ );
+ /* The words came back through the queue, not the run: no chip was
+ re-minted and no accepted id was recorded for the server steer. */
+ expect(chips).toEqual([]);
+ expect(queue).toEqual([
+ expect.objectContaining({ id: 'srv-race', text: 'changed my mind' }),
+ ]);
+ expect(accepted).toEqual([]);
+ expect(getDefaultStore().get(pendingSteerCancelClientIdsFamily(CONVO_ID))).toEqual([]);
+ });
+
+ it('settles the steer as live when the racing cancel lost', async () => {
+ mockMutateAsync.mockResolvedValue({ steerId: 'srv-kept', preempt: false });
+ mockCancelSteer.mockResolvedValue({ removed: false });
+ const { result } = setup(({ set }) => {
+ set(store.pendingSteersByConvoId(CONVO_ID), [
+ { steerId: 'local-kept', text: 'still wanted', status: 'failed', createdAt: 4 },
+ ]);
+ });
+ act(() => {
+ result.current.recovery.retry('local-kept');
+ });
+ armCancelMarker('local-kept');
+ await flush();
+ await flush();
+ expect(result.current.chips).toEqual([
+ expect.objectContaining({ steerId: 'srv-kept', status: 'pending' }),
+ ]);
+ expect(result.current.queue).toEqual([]);
+ });
+
+ it('treats the steer as live when the racing cancel POST fails', async () => {
+ mockMutateAsync.mockResolvedValue({ steerId: 'srv-unknown', preempt: false });
+ mockCancelSteer.mockRejectedValue(new Error('network'));
+ const { result } = setup(({ set }) => {
+ set(store.pendingSteersByConvoId(CONVO_ID), [
+ { steerId: 'local-unknown', text: 'unknown outcome', status: 'failed', createdAt: 4 },
+ ]);
+ });
+ act(() => {
+ result.current.recovery.retry('local-unknown');
+ });
+ armCancelMarker('local-unknown');
+ await flush();
+ await flush();
+ expect(result.current.chips).toEqual([
+ expect.objectContaining({ steerId: 'srv-unknown', status: 'pending' }),
+ ]);
+ expect(getDefaultStore().get(pendingSteerCancelClientIdsFamily(CONVO_ID))).toEqual([]);
+ });
+
+ /* The optimistic cancel removes the `sending` chip, and the failure path
+ settles by mapping chips that still exist: without the chip back the
+ words vanish, unsent and unqueued both. */
+ it('keeps the words when the POST fails after the user cancelled', async () => {
+ let rejectPost: (reason?: unknown) => void = () => undefined;
+ mockMutateAsync.mockReturnValue(new Promise((_resolve, reject) => (rejectPost = reject)));
+ let recovery: ReturnType<typeof useSteerRecovery> | undefined;
+ let chips: unknown[] = [];
+ let dropChip: () => void = () => undefined;
+ const Tree = () => {
+ recovery = useSteerRecovery(CONVO_ID);
+ chips = useRecoilValue(store.pendingSteersByConvoId(CONVO_ID));
+ const setChips = useSetRecoilState(store.pendingSteersByConvoId(CONVO_ID));
+ dropChip = () =>
+ setChips((prev) => prev.filter((chip) => chip.steerId !== 'local-vanish'));
+ return null;
+ };
+ render(
+ <ComposerRestoreProvider>
+ <RecoilRoot
+ initializeState={(snapshot) => {
+ seedRun(snapshot, true);
+ snapshot.set(store.pendingSteersByConvoId(CONVO_ID), [
+ {
+ steerId: 'local-vanish',
+ text: 'do not lose me',
+ status: 'failed',
+ createdAt: 4,
+ },
+ ]);
+ }}
+ >
+ <Tree />
+ </RecoilRoot>
+ </ComposerRestoreProvider>,
+ );
+ act(() => {
+ recovery?.retry('local-vanish');
+ });
+ act(() => {
+ dropChip();
+ armCancelMarker('local-vanish');
+ });
+ await act(async () => {
+ rejectPost(new Error('network'));
+ });
+ await flush();
+ expect(chips).toEqual([
+ expect.objectContaining({ steerId: 'local-vanish', status: 'failed' }),
+ ]);
+ expect(getDefaultStore().get(pendingSteerCancelClientIdsFamily(CONVO_ID))).toEqual([]);
+ });
+ });
+
+ /* Binding a queued retry to its durable receipt is a v2-only capability:
+ a v1 server never parks the receipt, and the drain's explicit send dies
+ mid-commit when the row points at machinery that is not there. */
+ it('binds a queued retry ack to its receipt only under protocol v2', async () => {
+ mockMutateAsync.mockResolvedValue({ steerId: 'srv-bound', preempt: false });
+ const bind = async (generationProtocolVersion: 1 | 2) => {
+ const { result, unmount } = setup(({ set }) => {
+ set(store.isSubmittingFamily(0), false);
+ set(store.pendingSteersByConvoId(CONVO_ID), [
+ {
+ steerId: `local-v${generationProtocolVersion}`,
+ text: 'landed after the end',
+ status: 'failed',
+ createdAt: 4,
+ generationProtocolVersion,
+ },
+ ]);
+ });
+ act(() => {
+ result.current.recovery.retry(`local-v${generationProtocolVersion}`);
+ });
+ await flush();
+ const row = result.current.queue[0];
+ unmount();
+ return row;
+ };
+ const v2Row = await bind(2);
+ expect(v2Row).toEqual(
+ expect.objectContaining({
+ recoverySteerId: 'srv-bound',
+ clientRequestId: expect.any(String),
+ }),
+ );
+ const v1Row = await bind(1);
+ expect(v1Row?.recoverySteerId).toBeUndefined();
+ expect(v1Row?.clientRequestId).toBeUndefined();
+ });
+
+ /* RUN_REPLACED belongs with the rest: the retry pins `generationCreatedAt`
+ to the chip's own generation, so once a newer run owns the conversation
+ every retry earns that same 409 and Retry would be dead for good. */
+ it('also routes to the queue on RUN_PAUSED / RUN_REPLACED / STEER_UNSUPPORTED / STEER_QUEUE_FULL', async () => {
+ for (const code of ['RUN_PAUSED', 'RUN_REPLACED', 'STEER_UNSUPPORTED', 'STEER_QUEUE_FULL']) {
+ mockMutateAsync.mockRejectedValue({ response: { data: { code } } });
+ const { result } = setup(({ set }) => {
+ set(store.pendingSteersByConvoId(CONVO_ID), [
+ { steerId: `local-${code}`, text: code, status: 'failed', createdAt: 1 },
+ ]);
+ });
+ act(() => {
+ result.current.recovery.retry(`local-${code}`);
+ });
+ await flush();
+ expect(result.current.queue).toEqual([expect.objectContaining({ id: `local-${code}` })]);
+ }
+ });
+
+ it('marks delivery uncertain after an ambiguous retry error', async () => {
+ mockMutateAsync.mockRejectedValue(new Error('network'));
+ const { result } = setup(({ set }) => {
+ set(store.pendingSteersByConvoId(CONVO_ID), [
+ { steerId: 'local-3', text: 'network flake', status: 'failed', createdAt: 1 },
+ ]);
+ });
+ act(() => {
+ result.current.recovery.retry('local-3');
+ });
+ await flush();
+ expect(result.current.chips).toEqual([
+ expect.objectContaining({
+ steerId: 'local-3',
+ status: 'failed',
+ deliveryUncertain: true,
+ }),
+ ]);
+ expect(result.current.queue).toEqual([]);
+ });
+
+ it('keeps a definite retry rejection ordinary', async () => {
+ mockMutateAsync.mockRejectedValue({ response: { status: 400 } });
+ const { result } = setup(({ set }) => {
+ set(store.pendingSteersByConvoId(CONVO_ID), [
+ {
+ steerId: 'local-rejected',
+ text: 'rejected',
+ status: 'failed',
+ deliveryUncertain: true,
+ generationProtocolVersion: 2,
+ createdAt: 1,
+ },
+ ]);
+ });
+
+ act(() => result.current.recovery.retry('local-rejected'));
+ await flush();
+
+ expect(result.current.chips[0]).toEqual(
+ expect.objectContaining({ steerId: 'local-rejected', status: 'failed' }),
+ );
+ expect(result.current.chips[0].deliveryUncertain).toBeUndefined();
+ });
+
+ /* A retry's ack tends to land right as the run ends, which is also when
+ the block this hook lives in unmounts. Whether the words go to the queue
+ turns on the run, not on the unmount. */
+ const lateAck = async (endRun: boolean) => {
+ let settle: (value: unknown) => void = () => undefined;
+ mockMutateAsync.mockReturnValue(new Promise((resolve) => (settle = resolve)));
+
+ let recovery: ReturnType<typeof useSteerRecovery> | undefined;
+ let setSubmitting: ((value: boolean) => void) | undefined;
+ let chips: unknown[] = [];
+ let queue: unknown[] = [];
+ const Recovery = () => {
+ recovery = useSteerRecovery(CONVO_ID);
+ return null;
+ };
+ /* Outlives the run, the way the store does: the hook's own tree goes
+ away while the conversation's state stays behind to be read. */
+ const Observer = () => {
+ chips = useRecoilValue(store.pendingSteersByConvoId(CONVO_ID));
+ queue = useRecoilValue(store.queuedMessagesByConvoId(CONVO_ID));
+ setSubmitting = useSetRecoilState(store.isSubmittingFamily(0));
+ return null;
+ };
+ const Tree = ({ live }: { live: boolean }) => (
+ <RecoilRoot
+ initializeState={(snapshot) => {
+ seedRun(snapshot, true);
+ snapshot.set(store.pendingSteersByConvoId(CONVO_ID), [
+ { steerId: 'local-late', text: 'landed too late', status: 'failed', createdAt: 3 },
+ ]);
+ }}
+ >
+ <Observer />
+ {live && <Recovery />}
+ </RecoilRoot>
+ );
+
+ const { rerender } = render(<Tree live={true} />);
+ act(() => {
+ recovery?.retry('local-late');
+ });
+ expect(chips).toEqual([expect.objectContaining({ status: 'sending' })]);
+
+ if (endRun) {
+ act(() => setSubmitting?.(false));
+ }
+ rerender(<Tree live={false} />);
+ await act(async () => {
+ settle({ steerId: 'srv-late', status: 'queued', position: 1, conversationId: CONVO_ID });
+ });
+
+ return { chips, queue };
+ };
+
+ it('queues a retry whose ack lands after the run ended', async () => {
+ const { chips, queue } = await lateAck(true);
+ expect(chips).toEqual([]);
+ expect(queue).toEqual([expect.objectContaining({ id: 'srv-late', text: 'landed too late' })]);
+ });
+
+ /* Navigating away unmounts the same block while the resumable run carries
+ on, and the server will still inject the accepted steer. Queueing it as
+ a follow-up here is what sent the same words twice. */
+ it('leaves the ack pending when the block unmounts on a still-live run', async () => {
+ const { chips, queue } = await lateAck(false);
+ expect(chips).toEqual([expect.objectContaining({ steerId: 'srv-late', status: 'pending' })]);
+ expect(queue).toEqual([]);
+ });
+
+ /* Navigating to another chat swaps the conversation held in the index slot,
+ so the run this steer belongs to is in no slot at all. Absence is not an
+ ending: the server is still injecting the accepted steer, and reading the
+ empty scan as "run over" queued the same words a second time. */
+ it('leaves the ack pending when the user has navigated to another chat', async () => {
+ let settle: (value: unknown) => void = () => undefined;
+ mockMutateAsync.mockReturnValue(new Promise((resolve) => (settle = resolve)));
+
+ let recovery: ReturnType<typeof useSteerRecovery> | undefined;
+ let navigateAway: (() => void) | undefined;
+ let chips: unknown[] = [];
+ let queue: unknown[] = [];
+ const Tree = () => {
+ recovery = useSteerRecovery(CONVO_ID);
+ chips = useRecoilValue(store.pendingSteersByConvoId(CONVO_ID));
+ queue = useRecoilValue(store.queuedMessagesByConvoId(CONVO_ID));
+ const setConvo = useSetRecoilState(store.conversationByIndex(0));
+ navigateAway = () => setConvo({ conversationId: 'a-different-chat' } as never);
+ return null;
+ };
+
+ render(
+ <RecoilRoot
+ initializeState={(snapshot) => {
+ seedRun(snapshot, true);
+ snapshot.set(store.pendingSteersByConvoId(CONVO_ID), [
+ { steerId: 'local-nav', text: 'still running', status: 'failed', createdAt: 2 },
+ ]);
+ }}
+ >
+ <Tree />
+ </RecoilRoot>,
+ );
+
+ act(() => {
+ recovery?.retry('local-nav');
+ });
+ act(() => navigateAway?.());
+ await act(async () => {
+ settle({ steerId: 'srv-nav', status: 'queued', position: 1, conversationId: CONVO_ID });
+ });
+
+ expect(chips).toEqual([expect.objectContaining({ steerId: 'srv-nav', status: 'pending' })]);
+ expect(queue).toEqual([]);
+ });
+
+ /* Comparison mode can hold the same conversation in two panes. An idle
+ first pane says nothing while the pane that owns the run is still
+ submitting: reading it as the end queued the accepted steer a second time. */
+ it('leaves the ack pending while any pane holding the conversation is still running', async () => {
+ let settle: (value: unknown) => void = () => undefined;
+ mockMutateAsync.mockReturnValue(new Promise((resolve) => (settle = resolve)));
+ const { result } = setup((snapshot) => {
+ snapshot.set(store.conversationKeysAtom, [0, 1]);
+ snapshot.set(store.conversationByIndex(1), { conversationId: CONVO_ID } as never);
+ snapshot.set(store.isSubmittingFamily(0), false);
+ snapshot.set(store.isSubmittingFamily(1), true);
+ snapshot.set(store.pendingSteersByConvoId(CONVO_ID), [
+ { steerId: 'local-pane', text: 'second pane owns it', status: 'failed', createdAt: 4 },
+ ]);
+ });
+
+ act(() => {
+ result.current.recovery.retry('local-pane');
+ });
+ await act(async () => {
+ settle({ steerId: 'srv-pane', status: 'queued', position: 1, conversationId: CONVO_ID });
+ });
+
+ expect(result.current.chips).toEqual([
+ expect.objectContaining({ steerId: 'srv-pane', status: 'pending' }),
+ ]);
+ expect(result.current.queue).toEqual([]);
+ });
+
+ /* An interrupt-steer that failed has to retry AS an interrupt: resent as an
+ ordinary steer it lands at the run's next tool step instead of sealing the
+ stream, which is not the action the chip says it is. */
+ it('resubmits a failed interrupt-steer as an interrupt', async () => {
+ mockMutateAsync.mockResolvedValue({
+ steerId: 'srv-preempt',
+ status: 'queued',
+ position: 1,
+ conversationId: CONVO_ID,
+ preempt: true,
+ });
+ const { result } = setup(({ set }) => {
+ set(store.pendingSteersByConvoId(CONVO_ID), [
+ {
+ steerId: 'local-preempt',
+ text: 'stop and read this',
+ status: 'failed',
+ createdAt: 6,
+ preempt: true,
+ },
+ ]);
+ });
+ act(() => {
+ result.current.recovery.retry('local-preempt');
+ });
+ await flush();
+ expect(mockMutateAsync).toHaveBeenCalledWith(
+ expect.objectContaining({ text: 'stop and read this', preempt: true }),
+ );
+ expect(result.current.chips).toEqual([
+ expect.objectContaining({ steerId: 'srv-preempt', preempt: true }),
+ ]);
+ });
+
+ it('leaves an ordinary steer non-preempting on retry', async () => {
+ mockMutateAsync.mockResolvedValue({
+ steerId: 'srv-plain',
+ status: 'queued',
+ position: 1,
+ conversationId: CONVO_ID,
+ });
+ const { result } = setup(({ set }) => {
+ set(store.pendingSteersByConvoId(CONVO_ID), [
+ { steerId: 'local-plain', text: 'just a steer', status: 'failed', createdAt: 6 },
+ ]);
+ });
+ act(() => {
+ result.current.recovery.retry('local-plain');
+ });
+ await flush();
+ expect(mockMutateAsync).toHaveBeenCalledWith(expect.not.objectContaining({ preempt: true }));
+ });
+
+ /* Capability degradation is a relabel, never an error: a server without the
+ seal still queues the steer and echoes `preempt: false`. */
+ it('follows the server down to an ordinary steer when the seal was not armed', async () => {
+ mockMutateAsync.mockResolvedValue({
+ steerId: 'srv-degraded',
+ status: 'queued',
+ position: 1,
+ conversationId: CONVO_ID,
+ preempt: false,
+ });
+ const { result } = setup(({ set }) => {
+ set(store.pendingSteersByConvoId(CONVO_ID), [
+ {
+ steerId: 'local-degraded',
+ text: 'seal it',
+ status: 'failed',
+ createdAt: 6,
+ preempt: true,
+ },
+ ]);
+ });
+ act(() => {
+ result.current.recovery.retry('local-degraded');
+ });
+ await flush();
+ expect(result.current.chips).toEqual([
+ expect.objectContaining({ steerId: 'srv-degraded', status: 'pending', preempt: false }),
+ ]);
+ });
+
+ /* The picks the message was written with have to survive the retry, or the
+ words are re-sent without the quotes and skills they referred to. */
+ it('carries the quotes and skills the steer was written with', async () => {
+ mockMutateAsync.mockResolvedValue({
+ steerId: 'srv-ctx',
+ status: 'queued',
+ position: 1,
+ conversationId: CONVO_ID,
+ });
+ const { result } = setup(({ set }) => {
+ set(store.pendingSteersByConvoId(CONVO_ID), [
+ {
+ steerId: 'local-ctx',
+ text: 'about that quote',
+ status: 'failed',
+ createdAt: 4,
+ quotes: ['carried quote'],
+ manualSkills: ['carried-skill'],
+ },
+ ]);
+ });
+ act(() => {
+ result.current.recovery.retry('local-ctx');
+ });
+ await flush();
+ expect(mockMutateAsync).toHaveBeenCalledWith(
+ expect.objectContaining({ quotes: ['carried quote'] }),
+ );
+ expect(result.current.chips).toEqual([
+ expect.objectContaining({
+ steerId: 'srv-ctx',
+ quotes: ['carried quote'],
+ manualSkills: ['carried-skill'],
+ }),
+ ]);
+ });
+
+ /* The identity fields are what make a retry safe. Without `clientSteerId`
+ the server cannot dedupe a POST that already committed, so an uncertain
+ transport applies the same words twice; without `generationCreatedAt` the
+ retry targets whichever turn currently occupies the conversation-scoped
+ stream id rather than the one the chip belongs to. The composer's retry
+ has always sent both, and the in-thread one sent neither. */
+ it('posts the same identity fields the composer retry sends', async () => {
+ mockMutateAsync.mockResolvedValue({
+ steerId: 'srv-id',
+ status: 'queued',
+ position: 1,
+ conversationId: CONVO_ID,
+ });
+ const { result } = setup(({ set }) => {
+ set(store.pendingSteersByConvoId(CONVO_ID), [
+ {
+ steerId: 'local-id',
+ text: 'pin me to my generation',
+ status: 'failed',
+ createdAt: 8,
+ generationCreatedAt: 4242,
+ },
+ ]);
+ });
+ act(() => {
+ result.current.recovery.retry('local-id');
+ });
+ await flush();
+ expect(mockMutateAsync).toHaveBeenCalledWith(
+ expect.objectContaining({
+ conversationId: CONVO_ID,
+ clientSteerId: 'local-id',
+ generationCreatedAt: 4242,
+ }),
+ );
+ });
+
+ /* A chip that was already acknowledged once carries the client id the
+ server knows it by; retrying under its server id instead would defeat the
+ dedupe the field exists for. */
+ it('keeps the client id an earlier ack already assigned', async () => {
+ mockMutateAsync.mockResolvedValue({
+ steerId: 'srv-again',
+ status: 'queued',
+ position: 1,
+ conversationId: CONVO_ID,
+ });
+ const { result } = setup(({ set }) => {
+ set(store.pendingSteersByConvoId(CONVO_ID), [
+ {
+ steerId: 'srv-known',
+ clientSteerId: 'local-known',
+ text: 'second attempt',
+ status: 'failed',
+ createdAt: 9,
+ },
+ ]);
+ });
+ act(() => {
+ result.current.recovery.retry('srv-known');
+ });
+ await flush();
+ expect(mockMutateAsync).toHaveBeenCalledWith(
+ expect.objectContaining({ clientSteerId: 'local-known' }),
+ );
+ });
+
+ /* The ack is resolved by the one implementation the composer also uses, so
+ these cover rules this hook used to approximate on its own. */
+ describe('consolidated ack resolution', () => {
+ const ack = (steerId: string) => ({
+ steerId,
+ status: 'queued',
+ position: 1,
+ conversationId: CONVO_ID,
+ });
+
+ /* A replacement generation already owns the conversation, so no apply
+ event for the source generation is ever coming, even though the chat
+ is still submitting and looks live. */
+ it('queues an ack whose source generation was replaced', async () => {
+ mockMutateAsync.mockResolvedValue(ack('srv-epoch'));
+ const { result } = setup(({ set }) => {
+ set(store.activeGenerationCreatedAtByConvoId(CONVO_ID), 900);
+ set(store.pendingSteersByConvoId(CONVO_ID), [
+ {
+ steerId: 'local-epoch',
+ text: 'older generation',
+ status: 'failed',
+ createdAt: 2,
+ generationCreatedAt: 100,
+ },
+ ]);
+ });
+ act(() => {
+ result.current.recovery.retry('local-epoch');
+ });
+ await flush();
+ expect(result.current.chips).toEqual([]);
+ expect(result.current.queue).toEqual([
+ expect.objectContaining({ id: 'srv-epoch', text: 'older generation' }),
+ ]);
+ });
+
+ /* The steer is still aimed at the generation that owns the conversation,
+ so the server will inject it and the chip waits for that event. */
+ it('keeps an ack pending while its own generation is still the active one', async () => {
+ mockMutateAsync.mockResolvedValue(ack('srv-live'));
+ const { result } = setup(({ set }) => {
+ set(store.activeGenerationCreatedAtByConvoId(CONVO_ID), 100);
+ set(store.pendingSteersByConvoId(CONVO_ID), [
+ {
+ steerId: 'local-live',
+ text: 'same generation',
+ status: 'failed',
+ createdAt: 2,
+ generationCreatedAt: 100,
+ },
+ ]);
+ });
+ act(() => {
+ result.current.recovery.retry('local-live');
+ });
+ await flush();
+ expect(result.current.chips).toEqual([
+ expect.objectContaining({ steerId: 'srv-live', status: 'pending' }),
+ ]);
+ expect(result.current.queue).toEqual([]);
+ });
+
+ /* `on_steer_applied` rides the SSE and can land before the HTTP response.
+ Minting a pending chip then strands it forever, and queueing the words
+ sends them a second time: the resolver must do neither. */
+ it('drops the chip without queueing when the apply event beat the ack', async () => {
+ mockMutateAsync.mockResolvedValue(ack('srv-applied'));
+ const { result } = setup(({ set }) => {
+ set(store.isSubmittingFamily(0), false);
+ set(store.appliedSteerIdsByConvoId(CONVO_ID), ['srv-applied']);
+ set(store.pendingSteersByConvoId(CONVO_ID), [
+ { steerId: 'local-applied', text: 'already injected', status: 'failed', createdAt: 3 },
+ ]);
+ });
+ act(() => {
+ result.current.recovery.retry('local-applied');
+ });
+ await flush();
+ expect(result.current.chips).toEqual([]);
+ expect(result.current.queue).toEqual([]);
+ });
+
+ /* Server ownership is recorded whatever the outcome, so a duplicate ack
+ for the same attempt cannot re-mint a chip that was already settled. */
+ it('records the accepted client id', async () => {
+ mockMutateAsync.mockResolvedValue(ack('srv-accepted'));
+ const { result } = setup(({ set }) => {
+ set(store.pendingSteersByConvoId(CONVO_ID), [
+ { steerId: 'local-accepted', text: 'note the id', status: 'failed', createdAt: 4 },
+ ]);
+ });
+ act(() => {
+ result.current.recovery.retry('local-accepted');
+ });
+ await flush();
+ expect(result.current.accepted).toEqual(['local-accepted']);
+ });
+ });
+
+ it('no-ops when the steer id is no longer pending', () => {
+ const { result } = setup();
+ act(() => {
+ result.current.recovery.retry('missing');
+ });
+ expect(mockMutateAsync).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('sendAsNew', () => {
+ it('does not reroute an uncertain protocol-v1 delivery', () => {
+ const { result } = setup(({ set }) => {
+ set(store.pendingSteersByConvoId(CONVO_ID), [
+ {
+ steerId: 'legacy-uncertain',
+ text: 'may already be committed',
+ status: 'failed',
+ deliveryUncertain: true,
+ generationProtocolVersion: 1,
+ createdAt: 0,
+ },
+ ]);
+ });
+
+ act(() => result.current.recovery.sendAsNew('legacy-uncertain'));
+
+ expect(result.current.chips).toHaveLength(1);
+ expect(result.current.queue).toEqual([]);
+ });
+
+ it('does not reroute an uncertain protocol-v2 delivery as a new turn', () => {
+ const { result } = setup(({ set }) => {
+ set(store.pendingSteersByConvoId(CONVO_ID), [
+ {
+ steerId: 'modern-uncertain',
+ text: 'retry only under the same id',
+ status: 'failed',
+ deliveryUncertain: true,
+ generationProtocolVersion: 2,
+ createdAt: 0,
+ },
+ ]);
+ });
+
+ act(() => result.current.recovery.sendAsNew('modern-uncertain'));
+
+ expect(result.current.chips).toHaveLength(1);
+ expect(result.current.queue).toEqual([]);
+ });
+
+ it('moves the chip to the queue, merged chronologically with existing items', () => {
+ const { result } = setup(({ set }) => {
+ set(store.pendingSteersByConvoId(CONVO_ID), [
+ { steerId: 's-old', text: 'older failed steer', status: 'failed', createdAt: 0 },
+ ]);
+ set(store.queuedMessagesByConvoId(CONVO_ID), [
+ { id: 'existing', text: 'first', createdAt: 1 },
+ ]);
+ });
+ act(() => {
+ result.current.recovery.sendAsNew('s-old');
+ });
+ expect(result.current.chips).toEqual([]);
+ // Chronological merge (not blind-append): the older steer sorts ahead
+ // of the already-queued, later item.
+ expect(result.current.queue.map((item) => item.id)).toEqual(['s-old', 'existing']);
+ });
+
+ it('records the id in appliedSteerIds so a late ACK cannot re-mint the chip', () => {
+ const { result } = setup(({ set }) => {
+ set(store.pendingSteersByConvoId(CONVO_ID), [
+ { steerId: 's-late', text: 'send me', status: 'failed', createdAt: 1 },
+ ]);
+ });
+ act(() => {
+ result.current.recovery.sendAsNew('s-late');
+ });
+ expect(result.current.applied).toEqual(['s-late']);
+ });
+ });
+});
diff --git a/client/src/hooks/Chat/__tests__/useSteering.spec.tsx b/client/src/hooks/Chat/__tests__/useSteering.spec.tsx
index 73c745f15b..fb687872ec 100644
--- a/client/src/hooks/Chat/__tests__/useSteering.spec.tsx
+++ b/client/src/hooks/Chat/__tests__/useSteering.spec.tsx
@@ -1,14 +1,27 @@
import React from 'react';
-import { getDefaultStore } from 'jotai';
-import { act, renderHook, waitFor } from '@testing-library/react';
+import { act, render, renderHook, waitFor } from '@testing-library/react';
import { RecoilRoot, useRecoilValue, useSetRecoilState, type MutableSnapshot } from 'recoil';
-import { Constants, ContentTypes, EModelEndpoint, LocalStorageKeys } from 'librechat-data-provider';
-import type { CodeApprovalMode, TConversation, TFile, TMessage } from 'librechat-data-provider';
+import { getDefaultStore, Provider as JotaiProvider, createStore, useAtomValue } from 'jotai';
+import {
+ Constants,
+ ContentTypes,
+ EModelEndpoint,
+ LocalStorageKeys,
+ ReasoningEffort,
+} from 'librechat-data-provider';
+import type { TConversation, TFile, TMessage } from 'librechat-data-provider';
import type { QueuedMessage } from '~/store/families';
+import type { ExtendedFile } from '~/common';
+import {
+ getReasoningStateKey,
+ pendingReasoningOverrideFamily,
+} from '~/components/Chat/Input/Composer/state';
+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 useSteering, { mergeQueuedTurnFileMetadata } from '../useSteering';
-import { revealedQueuedTurnFamily } from '~/store/steer';
+import { claimQueuedIntent, releaseQueuedIntent } from '~/utils/queueIntent';
+import useUpdateFiles from '~/hooks/Files/useUpdateFiles';
+import { applyPendingAction } from '~/utils/approval';
import useQueueDrain from '../useQueueDrain';
import store from '~/store';
@@ -39,7 +52,12 @@ jest.mock('~/Providers', () => ({
useFileMapContext: () => mockFileMap,
}));
+/** The reconciliation window is an operator lever; these specs exercise the
+ * shipped default unless a case overrides it. */
+let mockStartupConfig: { interface?: { queuedTurnReconciliationTimeoutMs?: number } } | undefined;
+
jest.mock('~/data-provider', () => ({
+ useGetStartupConfig: () => ({ data: mockStartupConfig }),
useCancelSteerMutation: () => ({ mutateAsync: mockCancelSteer }),
useSteerMessageMutation: () => ({ mutate: mockMutate }),
useAgentQueuedTurns: (...args: unknown[]) => mockUseAgentQueuedTurns(...args),
@@ -152,6 +170,19 @@ function useQueue(convoId: string) {
return useRecoilValue(store.queuedMessagesByConvoId(convoId));
}
+/** Puts a message in the queue and then sends it, which is the only order the
+ * rail can produce: Send now is offered for a message the queue is holding. */
+function sendFromQueue(
+ current: {
+ steering: ReturnType<typeof useSteering>;
+ setQueue: (items: QueuedMessage[]) => void;
+ },
+ item: QueuedMessage,
+) {
+ current.setQueue([item]);
+ current.steering.sendQueuedNow(item);
+}
+
describe('useSteering', () => {
beforeEach(() => {
getDefaultStore().set(recoveryDispositionsFamily(CONVO_ID), {});
@@ -389,14 +420,15 @@ describe('useSteering', () => {
set(store.duringRunDefaultAction, 'queue');
});
expect(result.current.effectiveAction).toBe('queue');
- // The per-send menu can still override to steer — availability is
+ // The per-send menu can still override to steer: availability is
// independent of the default action.
expect(result.current.canSteer).toBe(true);
});
it('degrades to queue without a real conversation id', () => {
- const { result } = setup({
- conversationId: Constants.NEW_CONVO as string,
+ // Explicitly request steer so this verifies the missing-id fallback to queue.
+ const { result } = setup({ conversationId: Constants.NEW_CONVO as string }, ({ set }) => {
+ set(store.duringRunDefaultAction, 'steer');
});
expect(result.current.effectiveAction).toBe('queue');
});
@@ -419,12 +451,85 @@ describe('useSteering', () => {
],
} as unknown as TMessage,
];
- const { result } = setup();
+ // Explicitly request steer so this verifies the pause fallback to queue.
+ const { result } = setup({}, ({ set }) => {
+ set(store.duringRunDefaultAction, 'steer');
+ });
expect(result.current.pausedOnApproval).toBe(true);
expect(result.current.effectiveAction).toBe('queue');
expect(result.current.canSteer).toBe(false);
});
+ it('applies pause predicates to the active branch tail only', () => {
+ const inactiveApproval = {
+ messageId: 'inactive-approval',
+ isCreatedByUser: false,
+ content: [
+ {
+ type: ContentTypes.TOOL_CALL,
+ tool_call: {
+ id: 'inactive-call',
+ name: 'shell',
+ approval: { actionId: 'inactive' },
+ output: '',
+ },
+ },
+ ],
+ } as unknown as TMessage;
+ const activeNoPause = {
+ messageId: 'active-no-pause',
+ isCreatedByUser: false,
+ content: [],
+ } as unknown as TMessage;
+ expect(hasLiveRunPause([activeNoPause, inactiveApproval], activeNoPause)).toBe(false);
+
+ const activeApproval = {
+ messageId: 'active-approval',
+ isCreatedByUser: false,
+ content: [
+ {
+ type: ContentTypes.TOOL_CALL,
+ tool_call: {
+ id: 'active-call',
+ name: 'shell',
+ approval: { actionId: 'active' },
+ output: '',
+ },
+ },
+ ],
+ } as unknown as TMessage;
+ const inactiveNoPause = {
+ messageId: 'inactive-no-pause',
+ isCreatedByUser: false,
+ content: [],
+ } as unknown as TMessage;
+ expect(hasLiveRunPause([activeApproval, inactiveNoPause], activeApproval)).toBe(true);
+ const questionAction = {
+ actionId: 'question',
+ streamId: 'question-stream',
+ createdAt: 0,
+ payload: { type: 'ask_user_question', question: { question: 'Which branch?' } },
+ } as unknown as Parameters<typeof applyPendingAction>[1];
+ const inactiveQuestion = applyPendingAction(
+ {
+ messageId: 'inactive-question',
+ isCreatedByUser: false,
+ content: [],
+ } as unknown as TMessage,
+ questionAction,
+ );
+ const activeQuestion = applyPendingAction(
+ {
+ messageId: 'active-question',
+ isCreatedByUser: false,
+ content: [],
+ } as unknown as TMessage,
+ questionAction,
+ );
+ expect(hasLiveRunPause([activeNoPause, inactiveQuestion], activeNoPause)).toBe(false);
+ expect(hasLiveRunPause([activeQuestion, inactiveNoPause], activeQuestion)).toBe(true);
+ });
+
it('queues during startup and exposes no live mutation until the generation epoch arrives', () => {
const { result, stopGenerating, setGenerationCreatedAt } = setup({}, ({ set }) => {
set(store.activeGenerationCreatedAtByConvoId(CONVO_ID), null);
@@ -572,6 +677,41 @@ describe('useSteering', () => {
expect(result.current.queue[0].server).toBeUndefined();
});
+ it('keeps a re-queued row durable on its own lineage once the run it waited on has ended', async () => {
+ const { result } = setupServerQueue(
+ withActiveGeneration(({ set }) => {
+ set(store.activeGenerationCreatedAtByConvoId(CONVO_ID), null);
+ }),
+ );
+
+ await act(async () => {
+ result.current.steering.enqueue('put back after a refused edit', {
+ id: 'queued-1',
+ createdAt: 7,
+ lineage: { parentMessageId: 'original-parent', predecessorCreatedAt: 42 },
+ skipUsageMark: true,
+ });
+ await Promise.resolve();
+ });
+
+ expect(result.current.queue).toEqual([
+ expect.objectContaining({
+ id: 'queued-1',
+ parentMessageId: 'original-parent',
+ expectedPredecessorCreatedAt: 42,
+ server: { status: 'sending' },
+ }),
+ ]);
+ expect(mockEnqueueQueuedTurn).toHaveBeenCalledWith(
+ expect.objectContaining({
+ parentMessageId: 'original-parent',
+ expectedPredecessorCreatedAt: 42,
+ text: 'put back after a refused edit',
+ }),
+ expect.anything(),
+ );
+ });
+
it('persists another follow-up against the original queue lineage after its completion boundary advances', async () => {
const family = revealedQueuedTurnFamily(CONVO_ID);
getDefaultStore().set(family, {
@@ -1662,7 +1802,7 @@ describe('useSteering', () => {
set(store.runEndByIndex(0), runEnd('completed'));
});
act(() => {
- // The drain ran against an empty queue and consumed the signal — the
+ // The drain ran against an empty queue and consumed the signal; the
// outcome was already captured during render.
result.current.consumeIndexSignal(null);
});
@@ -1981,7 +2121,9 @@ describe('useSteering', () => {
describe('submitDuringRun', () => {
it('routes to the steer POST with an optimistic sending chip', () => {
- const { result } = setup();
+ const { result } = setup({}, ({ set }) => {
+ set(store.duringRunDefaultAction, 'steer');
+ });
let consumed = false;
act(() => {
consumed = result.current.submitDuringRun('steer this');
@@ -2008,7 +2150,10 @@ describe('useSteering', () => {
});
it('ignores empty submissions', () => {
- const { result } = setup();
+ // Explicitly request steer so blank-text validation exercises the steer path.
+ const { result } = setup({}, ({ set }) => {
+ set(store.duringRunDefaultAction, 'steer');
+ });
let consumed = true;
act(() => {
consumed = result.current.submitDuringRun(' ');
@@ -2158,7 +2303,7 @@ describe('useSteering', () => {
/**
* `canSteer` is false while paused, but routing that into
* `interruptAndSend` would hard-abort the run and discard the partial
- * answer — the opposite of what the action promises.
+ * answer: the opposite of what the action promises.
*/
it('refuses while paused on tool approval instead of aborting', () => {
mockMessages = [
@@ -2207,21 +2352,13 @@ describe('useSteering', () => {
);
});
- it('retry resubmits a failed interrupt-steer AS an interrupt', () => {
- const { result } = setup();
- act(() => {
- result.current.retrySteer('chip-1', 'retry me', undefined, undefined, {
- preempt: true,
- });
- });
- expect(mockMutate).toHaveBeenCalledWith(
- expect.objectContaining({ text: 'retry me', preempt: true }),
- expect.anything(),
- );
- });
+ /* Retry lives in `useSteerRecovery` now, which owns the chip actions the
+ thread's pending block renders; its own spec covers the preempt carry. */
it('an ordinary steer does not preempt by default', () => {
- const { result } = setup();
+ const { result } = setup({}, ({ set }) => {
+ set(store.duringRunDefaultAction, 'steer');
+ });
act(() => {
result.current.submitDuringRun('just steer');
});
@@ -2233,6 +2370,7 @@ describe('useSteering', () => {
it('steerInterruptsByDefault makes the default Enter route preempt', () => {
const { result } = setup({}, ({ set }) => {
+ set(store.duringRunDefaultAction, 'steer');
set(store.steerInterruptsByDefault, true);
});
act(() => {
@@ -2436,6 +2574,7 @@ describe('useSteering', () => {
),
setAcceptedIds: useSetRecoilState(store.acceptedSteerClientIdsByConvoId(CONVO_ID)),
chips: useRecoilValue(store.pendingSteersByConvoId(CONVO_ID)),
+ setChips: useSetRecoilState(store.pendingSteersByConvoId(CONVO_ID)),
setAppliedIds: useSetRecoilState(store.appliedSteerIdsByConvoId(CONVO_ID)),
drainFlag: useRecoilValue(store.drainAfterAbortByIndex(0)),
}),
@@ -2470,11 +2609,75 @@ describe('useSteering', () => {
act(() => {
acknowledge?.();
});
- // No pending chip may survive — its only removal event already passed.
+ // No pending chip may survive; its only removal event already passed.
expect(result.current.chips).toEqual([]);
expect(result.current.queue).toEqual([]);
});
+ /* Cancel pressed while the POST was in flight is replayed once the 202
+ names the server id. When that replayed cancel does not remove the steer,
+ it is still live: hiding it would claim the words are gone while they
+ reach the agent anyway. */
+ it.each([
+ [
+ 'the server keeps the steer',
+ () => mockCancelSteer.mockResolvedValueOnce({ removed: false }),
+ 'info',
+ ],
+ [
+ 'the cancel request fails',
+ () => mockCancelSteer.mockRejectedValueOnce(new Error('offline')),
+ 'warning',
+ ],
+ ] as const)(
+ 'restores a live steer when a deferred cancel fails because %s',
+ async (_case, arrange, status) => {
+ arrange();
+ let acknowledge: (() => void) | undefined;
+ let clientSteerId = '';
+ mockMutate.mockImplementation((params, { onSuccess }) => {
+ clientSteerId = params.clientSteerId;
+ acknowledge = () =>
+ onSuccess({
+ steerId: 'srv-1',
+ status: 'queued',
+ position: 1,
+ conversationId: CONVO_ID,
+ });
+ });
+ const { result } = setupWithState();
+ act(() => {
+ result.current.steering.submitSteer('cancel me in flight');
+ });
+ /* What `useSteerCancel` does to a steer still sending: mark it and
+ hide its chip before the POST has answered. */
+ const marker = pendingSteerCancelClientIdsFamily(CONVO_ID);
+ getDefaultStore().set(marker, [clientSteerId]);
+ act(() => {
+ result.current.setChips([]);
+ });
+
+ await act(async () => {
+ acknowledge?.();
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+
+ expect(mockCancelSteer).toHaveBeenCalledWith(
+ expect.objectContaining({ steerId: 'srv-1', clientSteerId }),
+ );
+ expect(result.current.chips).toEqual([
+ expect.objectContaining({
+ steerId: 'srv-1',
+ status: 'pending',
+ text: 'cancel me in flight',
+ }),
+ ]);
+ expect(getDefaultStore().get(marker)).toEqual([]);
+ expect(mockShowToast).toHaveBeenCalledWith(expect.objectContaining({ status }));
+ },
+ );
+
it.each([
[
'a definite origin 400',
@@ -2639,7 +2842,7 @@ describe('useSteering', () => {
it('carries the submit time through the ACK so the pending chip is not re-timestamped', () => {
// A draft queued during the 202 round-trip must not drain ahead of a
- // steer submitted before it — so the ACK'd chip keeps its SUBMIT time,
+ // steer submitted before it, so the ACK'd chip keeps its SUBMIT time,
// not the (later) ACK time.
const now = jest.spyOn(Date, 'now').mockReturnValueOnce(1_000).mockReturnValue(9_000);
try {
@@ -2726,7 +2929,7 @@ describe('useSteering', () => {
});
const { result } = setupWithState({}, ({ set }) => {
// seedSteerChips already re-minted this chip from resumeState before
- // the 202 ACK landed — the ACK must upsert, not append.
+ // the 202 ACK landed; the ACK must upsert, not append.
set(store.pendingSteersByConvoId(CONVO_ID), [
{
steerId: 'srv-3',
@@ -2742,6 +2945,25 @@ describe('useSteering', () => {
expect(result.current.chips.filter((chip) => chip.steerId === 'srv-3')).toHaveLength(1);
});
+ it('leaves a queued row untouched while an edit or remove handoff owns it', () => {
+ const { result } = setupWithState();
+ act(() => {
+ result.current.steering.enqueue('claimed handoff');
+ });
+ const queued = result.current.queue[0];
+ expect(claimQueuedIntent(queued.id)).toBe(true);
+
+ try {
+ act(() => {
+ result.current.steering.sendQueuedNow(queued);
+ });
+ expect(result.current.queue).toEqual([queued]);
+ expect(mockMutate).not.toHaveBeenCalled();
+ } finally {
+ releaseQueuedIntent(queued.id);
+ }
+ });
+
it('restores the queued item (same id, original slot) when sendNow refuses', () => {
const refusingSendNow = jest.fn().mockReturnValue(false);
const { result } = setupWithState({
@@ -2768,7 +2990,7 @@ describe('useSteering', () => {
afterIds: [second.id],
},
});
- // `ask` refused without sending — the ORIGINAL item returns to its slot.
+ // `ask` refused without sending: the ORIGINAL item returns to its slot.
expect(result.current.queue.map((item) => item.id)).toEqual([first.id, second.id]);
expect(result.current.queue[0]).toEqual(first);
});
@@ -2805,7 +3027,7 @@ describe('useSteering', () => {
}),
}),
);
- // The chip is already gone — a refused send must land in the queue, not drop.
+ // The chip is already gone: a refused send must land in the queue, not drop.
expect(result.current.chips).toEqual([]);
expect(result.current.queue).toEqual([
expect.objectContaining({ text: 'refused words', files: steerFiles }),
@@ -2989,7 +3211,22 @@ describe('useSteering', () => {
expect(mockMutate).not.toHaveBeenCalled();
});
- it('confirms a discarded recovery but keeps it held until the guarded UI action succeeds', async () => {
+ it('preserves a manual queue order when another message is enqueued', () => {
+ const first: QueuedMessage = { id: 'first', text: 'first', createdAt: 1 };
+ const second: QueuedMessage = { id: 'second', text: 'second', createdAt: 2 };
+ const { result } = setupWithState({}, ({ set }) => {
+ set(store.queuedMessagesByConvoId(CONVO_ID), [first, second]);
+ });
+
+ act(() => {
+ result.current.steering.reorderQueued(first.id, 1);
+ result.current.steering.enqueue('third', { id: 'third', createdAt: 3 });
+ });
+
+ expect(result.current.queue.map((item) => item.id)).toEqual(['second', 'first', 'third']);
+ });
+
+ it('atomically discards a recovered source and downgrades its row in place', async () => {
mockCancelSteer.mockResolvedValueOnce({
removed: true,
generationProtocolVersion: 2,
@@ -3361,7 +3598,14 @@ describe('useSteering', () => {
};
const queuedFiles = [{ file_id: 'file-1', filepath: '/uploads/file-1.png', type: 'image/png' }];
- function setupWithFiles(params: HookParams = {}, generationCreatedAt: number | null = 41) {
+ /** Steering is gated on the active-generation epoch, so seed it by default
+ * or every steer here is refused as pre-epoch. `null` seeds nothing, which
+ * is the pre-epoch case itself; an initializer seeds the epoch and then
+ * whatever else that test needs. */
+ function setupWithFiles(
+ params: HookParams = {},
+ initialize?: ((snapshot: MutableSnapshot) => void) | null,
+ ) {
const setFiles = jest.fn();
const files = new Map([['file-1', composerFile]]) as unknown as NonNullable<
Parameters<typeof useSteering>[0]['files']
@@ -3370,11 +3614,14 @@ describe('useSteering', () => {
const stopGenerating = jest.fn();
const wrapper = ({ children }: { children: React.ReactNode }) => (
<RecoilRoot
- initializeState={({ set }) => {
- if (generationCreatedAt != null) {
- set(store.activeGenerationCreatedAtByConvoId(CONVO_ID), generationCreatedAt);
- }
- }}
+ initializeState={
+ initialize === null
+ ? undefined
+ : (snapshot) => {
+ snapshot.set(store.activeGenerationCreatedAtByConvoId(CONVO_ID), 41);
+ initialize?.(snapshot);
+ }
+ }
>
{children}
</RecoilRoot>
@@ -3403,7 +3650,9 @@ describe('useSteering', () => {
}
it('steers with the composer attachments as one unit', () => {
- const { result, setFiles } = setupWithFiles();
+ const { result, setFiles } = setupWithFiles({}, ({ set }) => {
+ set(store.duringRunDefaultAction, 'steer');
+ });
let consumed = false;
act(() => {
consumed = result.current.steering.submitDuringRun('look at this image');
@@ -3419,11 +3668,148 @@ describe('useSteering', () => {
expect.anything(),
);
expect(result.current.queue).toEqual([]);
- expect(setFiles).toHaveBeenCalledWith(new Map());
+ /* Functional, never a flat overwrite: uploads write through functional
+ updates of their own, and an assigned map races them. */
+ const clear = setFiles.mock.calls[0][0] as (
+ previous: Map<string, unknown>,
+ ) => Map<string, unknown>;
+ expect(typeof clear).toBe('function');
+ expect(clear(new Map([['file-1', composerFile]]))).toEqual(new Map());
+ /* Only the ids it took: anything staged since is left where it is. */
+ expect(clear(new Map<string, unknown>([['file-2', { file_id: 'file-2' }]]))).toEqual(
+ new Map([['file-2', { file_id: 'file-2' }]]),
+ );
+ });
+
+ /* An upload resolving between the read and the clear used to be reapplied
+ on top of the emptied map, so the attachment came back in the composer
+ and rode the user's next message as well. */
+ describe('uploads interleaved with a consuming submit', () => {
+ const extended = (file_id: string, progress: number): ExtendedFile => ({
+ file_id,
+ progress,
+ size: 128,
+ type: 'image/png',
+ });
+
+ function setupComposer() {
+ const sendNow = jest.fn();
+ const stopGenerating = jest.fn();
+ const observed: { files: Map<string, ExtendedFile> } = { files: new Map() };
+ let updates: ReturnType<typeof useUpdateFiles> | undefined;
+ let steering: ReturnType<typeof useSteering> | undefined;
+
+ /** Real composer state, so `useUpdateFiles` and `useSteering` write
+ * through the same setter they share in `ChatForm`. */
+ const Composer = () => {
+ const [files, setFiles] = React.useState<Map<string, ExtendedFile>>(new Map());
+ observed.files = files;
+ updates = useUpdateFiles(setFiles);
+ steering = useSteering({
+ consumeDraft: jest.fn(),
+ index: 0,
+ conversationId: CONVO_ID,
+ conversation: agentsConversation,
+ isSubmitting: true,
+ answerModeActive: false,
+ files,
+ setFiles,
+ sendNow,
+ stopGenerating,
+ });
+ return null;
+ };
+
+ render(
+ <RecoilRoot initializeState={withActiveGeneration()}>
+ <Composer />
+ </RecoilRoot>,
+ );
+ return {
+ observed,
+ getUpdates: () => updates!,
+ getSteering: () => steering!,
+ };
+ }
+
+ it('ignores a late callback for an attachment the steer already took', () => {
+ const { observed, getUpdates, getSteering } = setupComposer();
+
+ act(() => getUpdates().addFile(extended('file-consumed', 0.4)));
+ expect(observed.files.has('file-consumed')).toBe(true);
+
+ act(() => {
+ getSteering().steerFromComposer('use this image');
+ });
+ expect(mockMutate).toHaveBeenCalledWith(
+ expect.objectContaining({
+ files: [expect.objectContaining({ file_id: 'file-consumed' })],
+ }),
+ expect.anything(),
+ );
+ expect(observed.files.size).toBe(0);
+
+ act(() => getUpdates().replaceFile(extended('file-consumed', 1)));
+ expect(observed.files.size).toBe(0);
+ });
+
+ it('still accepts an upload the user starts after the steer', () => {
+ const { observed, getUpdates, getSteering } = setupComposer();
+
+ act(() => getUpdates().addFile(extended('file-first', 1)));
+ act(() => {
+ getSteering().steerFromComposer('first one');
+ });
+ expect(observed.files.size).toBe(0);
+
+ act(() => getUpdates().addFile(extended('file-second', 0.2)));
+ act(() => getUpdates().replaceFile(extended('file-second', 1)));
+ expect(observed.files.get('file-second')?.progress).toBe(1);
+ });
+
+ /* Re-attaching the same library file reuses its server id, so a
+ permanent mark would make that attachment silently impossible. */
+ it('accepts the same file again when it is deliberately re-attached', () => {
+ const { observed, getUpdates, getSteering } = setupComposer();
+
+ act(() => getUpdates().addFile(extended('file-library', 1)));
+ act(() => {
+ getSteering().steerFromComposer('about this one');
+ });
+ expect(observed.files.size).toBe(0);
+
+ act(() => getUpdates().addFile(extended('file-library', 1)));
+ expect(observed.files.has('file-library')).toBe(true);
+ act(() => getUpdates().replaceFile(extended('file-library', 0.9)));
+ expect(observed.files.get('file-library')?.progress).toBe(0.9);
+ });
+
+ /* The composer map the submit reads is a render-old snapshot: an upload
+ that started after it must not be wiped by the clear. */
+ it('leaves an attachment staged after the submit read the composer', () => {
+ const { observed, getUpdates, getSteering } = setupComposer();
+
+ act(() => getUpdates().addFile(extended('file-taken', 1)));
+ act(() => {
+ getUpdates().addFile(extended('file-newer', 0.3));
+ getSteering().steerFromComposer('take the first one');
+ });
+
+ expect(mockMutate).toHaveBeenCalledWith(
+ expect.objectContaining({ files: [expect.objectContaining({ file_id: 'file-taken' })] }),
+ expect.anything(),
+ );
+ expect(Array.from(observed.files.keys())).toEqual(['file-newer']);
+ });
});
it('holds during-run submits while uploads are in flight', () => {
- const { result } = setupWithFiles({ filesLoading: true });
+ // Seed 'steer' so this covers steerFromComposer's own filesLoading
+ // guard; the queue-path guard is covered separately (queueFromComposer
+ // is exercised directly with filesLoading in the composer-draft tests).
+ const { result } = setupWithFiles({ filesLoading: true }, ({ set }) => {
+ set(store.duringRunDefaultAction, 'steer');
+ });
let consumed = true;
act(() => {
consumed = result.current.steering.submitDuringRun('too early');
@@ -3446,10 +3832,26 @@ describe('useSteering', () => {
expect(setFiles).not.toHaveBeenCalled();
});
+ /* The drain can take the head between the click dispatching and the row
+ unmounting. Falling back to the captured item sent the same words twice. */
+ it('refuses to send a message the queue no longer holds', () => {
+ const { result, sendNow } = setupWithFiles({ isSubmitting: false });
+ act(() => {
+ result.current.steering.sendQueuedNow({
+ id: 'already-drained',
+ text: 'sent moments ago',
+ createdAt: Date.now(),
+ });
+ });
+ expect(sendNow).not.toHaveBeenCalled();
+ expect(mockMutate).not.toHaveBeenCalled();
+ expect(result.current.queue).toEqual([]);
+ });
+
it('steers a queued media item with its own files during a live run', () => {
const { result, sendNow } = setupWithFiles();
act(() => {
- result.current.steering.sendQueuedNow({
+ sendFromQueue(result.current, {
id: 'q-media',
text: 'media message',
createdAt: Date.now(),
@@ -3472,7 +3874,7 @@ describe('useSteering', () => {
it('sends a media item as a normal turn with its own files when idle', () => {
const { result, sendNow } = setupWithFiles({ isSubmitting: false });
act(() => {
- result.current.steering.sendQueuedNow({
+ sendFromQueue(result.current, {
id: 'q-media',
text: 'media message',
createdAt: Date.now(),
@@ -3525,7 +3927,9 @@ describe('useSteering', () => {
});
it('does not mark usage on the steer path (the 202 already marked)', () => {
- const { result } = setupWithFiles();
+ const { result } = setupWithFiles({}, ({ set }) => {
+ set(store.duringRunDefaultAction, 'steer');
+ });
act(() => {
result.current.steering.submitDuringRun('steer with media');
});
@@ -3535,7 +3939,7 @@ describe('useSteering', () => {
it('restores an unchanged queued media item without re-marking its files', () => {
// Paused on approval → steering unavailable while the run is live, so
- // sendQueuedNow restores the item unchanged — its files were already marked.
+ // sendQueuedNow restores the item unchanged: its files were already marked.
mockMessages = [
{
messageId: 'resp-1',
@@ -3576,11 +3980,23 @@ describe('useSteering', () => {
function setupWithContext(
params: HookParams = {},
initialize?: (snapshot: MutableSnapshot) => void,
+ initialReasoning?: TMessage['reasoningOverride'],
) {
const sendNow = jest.fn();
const stopGenerating = jest.fn();
+ const reasoningStore = createStore();
+ reasoningStore.set(
+ pendingReasoningOverrideFamily(getReasoningStateKey(params.conversationId ?? CONVO_ID, 0)),
+ initialReasoning,
+ );
const wrapper = ({ children }: { children: React.ReactNode }) => (
- <RecoilRoot initializeState={withActiveGeneration(initialize)}>{children}</RecoilRoot>
+ <JotaiProvider store={reasoningStore}>
+ <RecoilRoot
+ initializeState={withActiveGeneration(initialize, params.conversationId ?? CONVO_ID)}
+ >
+ {children}
+ </RecoilRoot>
+ </JotaiProvider>
);
const rendered = renderHook(
() => ({
@@ -3596,14 +4012,16 @@ describe('useSteering', () => {
...params,
}),
queue: useQueue(CONVO_ID),
+ setQueue: useSetRecoilState(store.queuedMessagesByConvoId(CONVO_ID)),
chips: useRecoilValue(store.pendingSteersByConvoId(CONVO_ID)),
pendingQuotes: useRecoilValue(store.pendingQuotesByConvoId(CONVO_ID)),
pendingSkills: useRecoilValue(store.pendingManualSkillsByConvoId(CONVO_ID)),
+ pendingReasoning: useAtomValue(pendingReasoningOverrideFamily(CONVO_ID)),
markApplied: useSetRecoilState(store.appliedSteerIdsByConvoId(CONVO_ID)),
}),
{ wrapper },
);
- return { ...rendered, sendNow };
+ return { ...rendered, sendNow, stopGenerating };
}
const stageContext = ({ set }: MutableSnapshot) => {
@@ -3611,6 +4029,61 @@ describe('useSteering', () => {
set(store.pendingManualSkillsByConvoId(CONVO_ID), ['skill-1']);
};
+ it('queues rather than steering when reasoning is staged for a new generation', () => {
+ const { result } = setupWithContext({}, undefined, {
+ key: 'reasoning_effort',
+ value: ReasoningEffort.high,
+ });
+
+ act(() => {
+ result.current.steering.steerFromComposer('reason about this');
+ });
+
+ expect(mockMutate).not.toHaveBeenCalled();
+ expect(result.current.queue[0]).toMatchObject({
+ text: 'reason about this',
+ reasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.high },
+ });
+ expect(result.current.pendingReasoning).toBeUndefined();
+ });
+
+ /* The interrupt-and-steer chord promises to keep the partial answer. With
+ reasoning staged it cannot steer, and aborting would break that promise,
+ so it declines like its disabled menu row instead of interrupting. */
+ it('interruptSteer declines without aborting when reasoning is staged', () => {
+ const staged = { key: 'reasoning_effort', value: ReasoningEffort.high } as const;
+ const { result, stopGenerating } = setupWithContext({}, undefined, staged);
+
+ let consumed: boolean | undefined;
+ act(() => {
+ consumed = result.current.steering.interruptSteer('stop and reason about this');
+ });
+
+ expect(consumed).toBe(false);
+ expect(stopGenerating).not.toHaveBeenCalled();
+ expect(mockMutate).not.toHaveBeenCalled();
+ expect(result.current.queue).toEqual([]);
+ expect(result.current.pendingReasoning).toEqual(staged);
+ });
+
+ it('interruptSteer declines on the first turn when reasoning is staged', () => {
+ const staged = { key: 'reasoning_effort', value: ReasoningEffort.high } as const;
+ const { result, stopGenerating } = setupWithContext(
+ { conversationId: Constants.NEW_CONVO as string },
+ undefined,
+ staged,
+ );
+
+ let consumed: boolean | undefined;
+ act(() => {
+ consumed = result.current.steering.interruptSteer('stop and reason about this');
+ });
+
+ expect(consumed).toBe(false);
+ expect(stopGenerating).not.toHaveBeenCalled();
+ expect(mockMutate).not.toHaveBeenCalled();
+ });
+
it('queueFromComposer consumes staged quotes + skills into the queued item', () => {
const { result } = setupWithContext({}, stageContext);
act(() => {
@@ -3705,6 +4178,29 @@ describe('useSteering', () => {
);
});
+ it('keeps a durable reasoning row untouched during a live run', () => {
+ const item: QueuedMessage = {
+ id: 'q-reasoning-live',
+ text: 'reason about this next',
+ createdAt: 1_000,
+ reasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.high },
+ server: { id: 'server-reasoning-live', status: 'queued', revision: 3 },
+ };
+ const { result, sendNow } = setupWithContext({}, ({ set }) => {
+ set(store.queuedMessagesByConvoId(CONVO_ID), [item]);
+ });
+
+ act(() => {
+ result.current.steering.sendQueuedNow(item);
+ });
+
+ expect(mockCancelQueuedTurn).not.toHaveBeenCalled();
+ expect(mockMutate).not.toHaveBeenCalled();
+ expect(sendNow).not.toHaveBeenCalled();
+ expect(result.current.queue).toEqual([item]);
+ expect(result.current.queue[0].server).toEqual(item.server);
+ });
+
it('queues without quotes/skills fields when nothing is staged', () => {
const { result } = setupWithContext();
act(() => {
@@ -3717,17 +4213,19 @@ describe('useSteering', () => {
it('sendQueuedNow passes the carried context to sendNow when idle', () => {
const { result, sendNow } = setupWithContext({ isSubmitting: false });
act(() => {
- result.current.steering.sendQueuedNow({
+ sendFromQueue(result.current, {
id: 'q-ctx',
text: 'context send',
createdAt: Date.now(),
quotes: ['carried quote'],
manualSkills: ['carried-skill'],
+ reasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.high },
});
});
expect(sendNow).toHaveBeenCalledWith('context send', [], {
quotes: ['carried quote'],
manualSkills: ['carried-skill'],
+ reasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.high },
clientRequestId: undefined,
recoverySteerId: undefined,
expectedPredecessorCreatedAt: undefined,
@@ -3738,6 +4236,7 @@ describe('useSteering', () => {
createdAt: expect.any(Number),
quotes: ['carried quote'],
manualSkills: ['carried-skill'],
+ reasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.high },
},
beforeIds: [],
afterIds: [],
@@ -3753,7 +4252,7 @@ describe('useSteering', () => {
});
const { result } = setupWithContext();
act(() => {
- result.current.steering.sendQueuedNow({
+ sendFromQueue(result.current, {
id: 'q-degraded',
text: 'carried context',
createdAt: Date.now(),
@@ -4124,7 +4623,7 @@ describe('useSteering', () => {
describe('composer draft consumption', () => {
/** `useAutoSave` drafts under PENDING_CONVO for the whole run, and the
- * composer clears via the form's programmatic `reset()` — which fires no
+ * composer clears via the form's programmatic `reset()`, which fires no
* `input` event, so nothing else drops the draft. Left behind, run end
* migrates it onto the conversation and restores it into the textarea,
* resurfacing text the user already sent. */
diff --git a/client/src/hooks/Chat/index.ts b/client/src/hooks/Chat/index.ts
index 589a942252..c6a7492b58 100644
--- a/client/src/hooks/Chat/index.ts
+++ b/client/src/hooks/Chat/index.ts
@@ -13,5 +13,4 @@ export { default as useFocusChatEffect } from './useFocusChatEffect';
export { default as useQueueDrain } from './useQueueDrain';
export { default as useQueuedTurnReveal } from './useQueuedTurnReveal';
export { default as useSteering } from './useSteering';
-export { default as useSteerCancel, useSteerReclaim } from './useSteerCancel';
export { default as useSteerConvert } from './useSteerConvert';
diff --git a/client/src/hooks/Chat/useChatFunctions.ts b/client/src/hooks/Chat/useChatFunctions.ts
index 98c3ed9693..77580b9242 100644
--- a/client/src/hooks/Chat/useChatFunctions.ts
+++ b/client/src/hooks/Chat/useChatFunctions.ts
@@ -1,3 +1,4 @@
+import { useCallback, useEffect, useRef } from 'react';
import { v4 } from 'uuid';
import { useStore } from 'jotai';
import { cloneDeep } from 'lodash';
@@ -15,8 +16,11 @@ import {
replaceSpecialVars,
isAssistantsEndpoint,
getDefaultParamsEndpoint,
+ isReasoningOverrideSupported,
+ resolveReasoningSettingForTarget,
} from 'librechat-data-provider';
import type {
+ Agent,
TMessage,
TSubmission,
TConversation,
@@ -30,6 +34,7 @@ import type { TAskFunction, ExtendedFile } from '~/common';
import {
logger,
requestChatFocus,
+ resolveAgentTarget,
markPasteSubmitted,
hasStreamStartFailed,
isSubmittableMessage,
@@ -37,11 +42,16 @@ import {
getRouteChatProjectId,
stripStreamedIndexStamps,
} from '~/utils';
+import {
+ getReasoningStateKey,
+ pendingReasoningOverrideFamily,
+} from '~/components/Chat/Input/Composer/state';
import useFocusRegeneratedResponse from '~/hooks/Chat/useFocusRegeneratedResponse';
import useGetConversation from '~/hooks/Conversations/useGetConversation';
import { withSubmittedCodeDecision } from '~/hooks/Agents/codeDecision';
import useCodeApprovalMode from '~/hooks/Agents/useCodeApprovalMode';
import useSetFilesToDelete from '~/hooks/Files/useSetFilesToDelete';
+import { useAgentsMapContext } from '~/Providers/AgentsMapContext';
import useCodeWorkspace from '~/hooks/Agents/useCodeWorkspace';
import useGetSender from '~/hooks/Conversations/useGetSender';
import { activeUsageResponseIdFamily } from '~/store/usage';
@@ -167,12 +177,12 @@ export function getRegenerateSubmissionMessages({
}): TMessage[] {
if (targetResponseMessage?.messageId) {
/**
- * Remove the response being regenerated and its descendants only — NOT a
+ * Remove the response being regenerated and its descendants only: NOT a
* flat `slice(0, targetIndex)`, which also drops unrelated sibling branches
* that merely sit later in the array. That collapse made the optimistic
* render briefly lose other branches mid-regenerate (visible flash, and the
- * scroll jumping to the shrunken content). Keeping them holds the thread —
- * and scroll — steady. This array is render-only; the server regenerates
+ * scroll jumping to the shrunken content). Keeping them holds the thread
+ * (and scroll) steady. This array is render-only; the server regenerates
* from `parentMessageId`, so removing by subtree never affects the payload.
*/
const removed = new Set<string>([targetResponseMessage.messageId]);
@@ -224,11 +234,13 @@ export default function useChatFunctions({
setConversation: SetterOrUpdater<TConversation | null>;
}) {
const navigate = useNavigate();
+ const reasoningStore = useStore();
const getSender = useGetSender();
const { user } = useAuthContext();
const queryClient = useQueryClient();
const setFilesToDelete = useSetFilesToDelete();
const getEphemeralAgent = useGetEphemeralAgent();
+ const agentsMap = useAgentsMapContext();
const isTemporary = useRecoilValue(store.isTemporary);
const { getExpiry } = useUserKey(immutableConversation?.endpoint ?? '');
const setIsSubmitting = useSetRecoilState(store.isSubmittingFamily(index));
@@ -244,6 +256,25 @@ export default function useChatFunctions({
);
const codeWorkspaceState = useCodeWorkspace(immutableConversation, addedConversation);
+ /**
+ * `ask` refuses while `isSubmitting`, but that Recoil value only reads true
+ * from the next commit onwards: a double Enter or a double click inside one
+ * browser task would both pass that check and start two generations. This
+ * ref closes the gap synchronously, matching the queue send lock shared by
+ * `useSteering` and `useQueueDrain`.
+ *
+ * Released on every commit that is not submitting rather than only on a
+ * `true -> false` transition: a start that never flips `isSubmitting` here
+ * (Assistants set it from the SSE handler, and a start that fails outright
+ * never sets it at all) would otherwise latch the composer shut for good.
+ */
+ const askInFlightRef = useRef(false);
+ useEffect(() => {
+ if (!isSubmitting) {
+ askInFlightRef.current = false;
+ }
+ });
+
/**
* Atomically read + reset the per-conversation queue of manually-invoked
* skills from the `$` popover. Reading and resetting in a single Recoil
@@ -287,6 +318,18 @@ export default function useChatFunctions({
[],
);
+ const drainPendingReasoning = useCallback(
+ (stateKey: string): TMessage['reasoningOverride'] => {
+ const reasoningAtom = pendingReasoningOverrideFamily(stateKey);
+ const reasoningOverride = reasoningStore.get(reasoningAtom);
+ if (reasoningOverride != null) {
+ reasoningStore.set(reasoningAtom, undefined);
+ }
+ return reasoningOverride;
+ },
+ [reasoningStore],
+ );
+
const ask: TAskFunction = (
{
text,
@@ -308,6 +351,7 @@ export default function useChatFunctions({
targetResponseMessageId,
overrideManualSkills,
overrideQuotes,
+ overrideReasoning,
addedConvo,
overrideClientRequestId,
overrideRecoverySteerId,
@@ -328,6 +372,7 @@ export default function useChatFunctions({
* with the response placeholder parented onto the leaf. */
const regenerateShaped = isRegenerate || compact;
if (
+ askInFlightRef.current ||
!!isSubmitting ||
jotaiStore.get(revealedQueuedTurnFamily(immutableConversation?.conversationId ?? '')) !=
null ||
@@ -378,7 +423,7 @@ export default function useChatFunctions({
* Warm-switch revalidation guard: a navigation invalidates the target's
* cache and renders it while a background refetch reconciles. Deriving
* parentMessageId from that cache could fork from an outdated tail, so
- * refuse (composer keeps the text) until the refetch settles — but only
+ * refuse (composer keeps the text) until the refetch settles, but only
* when the cache is actually old: a just-streamed cache (fresh
* `dataUpdatedAt`) is locally authoritative, and gating it would block
* rapid follow-ups during the post-run reconcile.
@@ -413,11 +458,15 @@ export default function useChatFunctions({
setShowStopButton(false);
const ephemeralAgent = getEphemeralAgent(conversationId ?? Constants.NEW_CONVO);
+ const endpointsConfig = queryClient.getQueryData<TEndpointsConfig>([QueryKeys.endpoints]);
+ const startupConfig = queryClient.getQueryData<TStartupConfig>(startupConfigKey(true));
+ const endpointType = getEndpointField(endpointsConfig, endpoint, 'type');
+ const defaultParamsEndpoint = getDefaultParamsEndpoint(endpointsConfig, endpoint);
/**
* Manual skill selection resolution:
* - Explicit `overrideManualSkills` wins (regenerate / save-and-submit
* pass the original user message's persisted `manualSkills` so the
- * resubmitted turn primes the same skills — the pills are still
+ * resubmitted turn primes the same skills: the pills are still
* visible to the user, it would be strange to quietly drop them).
* - Regenerate / continue / edit without an override → empty, and the
* compose-time atom is deliberately NOT drained (those flows replay
@@ -452,6 +501,38 @@ export default function useChatFunctions({
quotes = drainPendingQuotes(conversationId ?? Constants.NEW_CONVO);
}
}
+ let reasoningOverride = overrideReasoning ?? undefined;
+ if (overrideReasoning === undefined && !regenerateShaped && !isContinued && !isEdited) {
+ reasoningOverride = drainPendingReasoning(getReasoningStateKey(conversationId, index));
+ }
+ if (reasoningOverride != null) {
+ const isAgent = isAgentsEndpoint(endpoint);
+ const agentId = isAgent ? conversation?.agent_id : undefined;
+ const savedAgent =
+ agentId != null
+ ? (queryClient.getQueryData<Agent>([QueryKeys.agent, agentId]) ?? agentsMap?.[agentId])
+ : undefined;
+ const agentTarget = isAgent ? resolveAgentTarget(agentId, savedAgent) : undefined;
+ const effectiveEndpoint = isAgent ? agentTarget?.provider : endpoint;
+ const effectiveModel = isAgent ? agentTarget?.model : conversation?.model;
+ const effectiveEndpointType = getEndpointField(endpointsConfig, effectiveEndpoint, 'type');
+ const customParams =
+ effectiveEndpoint == null ? undefined : endpointsConfig?.[effectiveEndpoint]?.customParams;
+ const supportedSetting =
+ effectiveEndpoint == null
+ ? undefined
+ : resolveReasoningSettingForTarget({
+ endpoint: effectiveEndpointType ?? effectiveEndpoint,
+ model: effectiveModel,
+ isAgent,
+ defaultParamsEndpoint: customParams?.defaultParamsEndpoint,
+ reasoningFormat: customParams?.reasoningFormat,
+ paramDefinitions: customParams?.paramDefinitions,
+ });
+ if (!isReasoningOverrideSupported(reasoningOverride, supportedSetting)) {
+ reasoningOverride = undefined;
+ }
+ }
const isEditOrContinue = isEdited || isContinued;
let currentMessages: TMessage[] = overrideMessages ?? cachedMessages ?? [];
@@ -523,11 +604,7 @@ export default function useChatFunctions({
thread_id = currentMessages.find((message) => message.thread_id)?.thread_id;
}
- const endpointsConfig = queryClient.getQueryData<TEndpointsConfig>([QueryKeys.endpoints]);
- const startupConfig = queryClient.getQueryData<TStartupConfig>(startupConfigKey(true));
- const endpointType = getEndpointField(endpointsConfig, endpoint, 'type');
const iconURL = conversation?.iconURL;
- const defaultParamsEndpoint = getDefaultParamsEndpoint(endpointsConfig, endpoint);
/** This becomes part of the `endpointOption` */
const convo = parseCompactConvo({
@@ -587,6 +664,7 @@ export default function useChatFunctions({
* also merges these into the model-facing user text at request time.
*/
quotes: quotes.length > 0 ? quotes : undefined,
+ reasoningOverride,
};
/** The leaf's files already sit in history; a compaction re-attaches nothing. */
@@ -605,8 +683,8 @@ export default function useChatFunctions({
markPasteSubmitted(file.temp_file_id);
});
// Caller-supplied overrideFiles were consumed elsewhere (queued
- // during-run messages take theirs out of the composer at queue time,
- // so clearing here would eat attachments staged for the user's NEXT send.
+ // during-run messages take theirs out of the composer at queue time);
+ // clearing here would eat attachments staged for the user's NEXT send.
if (isRegenerate) {
setFiles(new Map());
setFilesToDelete({});
@@ -668,7 +746,7 @@ export default function useChatFunctions({
/**
* Seed the assistant placeholder with the turn's manually-invoked
* skill names so `ContentParts` can render interim `SkillCall` cards
- * from the very first render — no round-trip through the `created`
+ * from the very first render: no round-trip through the `created`
* SSE event required. Rides along with every subsequent spread
* (`useStepHandler` response construction, `updateContent` result
* spreads) and drops out naturally at `finalHandler` when the
@@ -797,14 +875,10 @@ 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. */
+ askInFlightRef.current = true;
setSubmissionStart(Date.now());
setSubmission(submission);
logger.dir('message_stream', submission, { depth: null });
@@ -837,6 +911,8 @@ export default function useChatFunctions({
/** Carry the original user message's quoted excerpts forward so the
* regenerated response is sent the same referenced context. */
overrideQuotes: parentMessage.quotes,
+ /** Replay the exact request-scoped reasoning selection used by this turn. */
+ overrideReasoning: parentMessage.reasoningOverride ?? null,
},
);
} else {
diff --git a/client/src/hooks/Chat/useChatHelpers.ts b/client/src/hooks/Chat/useChatHelpers.ts
index 5fbcd77c8b..41b1d13737 100644
--- a/client/src/hooks/Chat/useChatHelpers.ts
+++ b/client/src/hooks/Chat/useChatHelpers.ts
@@ -194,7 +194,17 @@ export default function useChatHelpers(index = 0, paramId?: string): ChatContrac
);
if (parentMessage && parentMessage.isCreatedByUser) {
- ask({ ...parentMessage }, { isContinued: true, isRegenerate: true, isEdited: true });
+ ask(
+ { ...parentMessage },
+ {
+ isContinued: true,
+ isRegenerate: true,
+ isEdited: true,
+ overrideManualSkills: parentMessage.manualSkills,
+ overrideQuotes: parentMessage.quotes,
+ overrideReasoning: parentMessage.reasoningOverride ?? null,
+ },
+ );
} else {
console.error(
'Failed to regenerate the message: parentMessage not found, or not created by user.',
diff --git a/client/src/hooks/Chat/useQueueDrain.ts b/client/src/hooks/Chat/useQueueDrain.ts
index 48d3b4f1ee..d31c2ece6d 100644
--- a/client/src/hooks/Chat/useQueueDrain.ts
+++ b/client/src/hooks/Chat/useQueueDrain.ts
@@ -1,17 +1,16 @@
-import { useEffect, useMemo } from 'react';
-import { useAtomValue, useStore } from 'jotai';
-import { Constants } from 'librechat-data-provider';
+import { useRef, useEffect, useMemo } from 'react';
+import { useAtomValue } 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';
-import { useMarkFilesUsageMutation } from '~/data-provider';
import { revealedQueuedTurnFamily } from '~/store/steer';
+import { mergeQueuedMessages } from '~/utils/queue';
+import { insertQueuedOrigin } from '~/utils/steer';
import store from '~/store';
/** Mirrors the server's per-request cap on a usage touch. */
@@ -47,9 +46,6 @@ const batchFileIds = (fileIds: string[]): string[][] => {
return batches;
};
-const compareQueuedMessages = (a: QueuedMessage, b: QueuedMessage): number =>
- Number(b.priority ?? false) - Number(a.priority ?? false) || a.createdAt - b.createdAt;
-
/** Interrupt intent belongs to one generation, never to whichever terminal
* event happens to occupy the shared pane slot next. The NEW_CONVO alias is
* the one exception: after its first successful start, the terminal event
@@ -69,7 +65,7 @@ const matchesInterruptArm = (armed: DrainAfterAbort | false, end: RunEnd): boole
*
* Consumes the one-shot `runEndByIndex` signal written by the SSE handlers.
* Rules:
- * - Drains only on a clean completion — a user Stop or an error leaves the
+ * - Drains only on a clean completion: a user Stop or an error leaves the
* queued chips for manual send, EXCEPT when the one-shot
* `drainAfterAbortByIndex` flag was armed by "interrupt & send".
* - Waits for `isSubmitting` to be false so `ask()` isn't dropped by its
@@ -91,7 +87,15 @@ export default function useQueueDrain(
store.pendingRunEndByConvoId(activeConversationId ?? Constants.NEW_CONVO),
);
const isSubmitting = useRecoilValue(store.isSubmittingFamily(index));
+ /** Keyed by pane, because the contended resource is this pane's submission
+ * slot: the rail's "Send now" reaches the same `ask` through the composer. */
+ const sendLockKey = String(index);
+ const sendLockRef = useRef<QueueSendLock | null>(null);
+ const revealLockRef = useRef(false);
const { mutate: markFilesUsage } = useMarkFilesUsageMutation();
+ const { data: startupConfig } = useGetStartupConfig();
+ const sendLockTimeoutMs =
+ startupConfig?.interface?.queuedSendLockTimeoutMs ?? DEFAULT_QUEUED_SEND_LOCK_TIMEOUT_MS;
const ownQueue = useRecoilValue(
store.queuedMessagesByConvoId(activeConversationId ?? Constants.NEW_CONVO),
);
@@ -218,7 +222,7 @@ export default function useQueueDrain(
end.conversationId !== activeConversationId
) {
/**
- * `ask` is the MOUNTED view's sender — draining another
+ * `ask` is the MOUNTED view's sender: draining another
* conversation's follow-up here would submit it into the wrong
* chat. Park the signal under ITS conversation (freeing the shared
* index slot so a later run cannot overwrite it) and drain when
@@ -272,9 +276,7 @@ export default function useQueueDrain(
/** Both queues are ordered independently, but migration crosses the
* key boundary: an interrupt queued under the resolved conversation
* must still outrank an ordinary follow-up captured under NEW_CONVO. */
- const merged = shouldMigrate
- ? [...newConvoQueue, ...ownQueue].sort(compareQueuedMessages)
- : ownQueue;
+ const merged = shouldMigrate ? mergeQueuedMessages(newConvoQueue, ownQueue) : ownQueue;
const shouldDrain = end.outcome === 'completed' || interruptArmed;
const settledReceipts = snapshot
@@ -344,27 +346,23 @@ export default function useQueueDrain(
return reveal == null ? null : { kind: 'reveal', item: reveal, end };
}
- const head = merged[0];
- const held =
- head != null &&
- recoveryDisposition(jotaiStore.get(recoveryDispositionsFamily(conversationId)), head) !=
- null;
- if (shouldDrain && held) {
- // The held source cannot spend this completion. Keep its one-shot
- // boundary so a successor can drain if the user dismisses the hold.
- if (shouldMigrate && newConvoQueue.length > 0) {
- set(store.queuedMessagesByConvoId(Constants.NEW_CONVO), []);
- set(store.queuedMessagesByConvoId(conversationId), merged);
- }
- return null;
- }
-
- // Consume only after server authority and held recoveries yield the
- // boundary. A later queue update cannot spend the same end twice.
+ // Consume only after server authority has yielded the boundary: a
+ // hard double-fire guard even if the effect re-runs before propagation.
consumeEnd();
- const next = shouldDrain ? (head ?? null) : null;
- const remainder = next ? merged.slice(1) : merged;
+ /** A row the rail is mid-edit or mid-remove on is spoken for: its words
+ * are already on their way to the composer, and sending them from here
+ * would deliver the message the user is in the middle of taking back.
+ * A row swept in from a REJECTED steer is spoken for too: it carries
+ * words the server refused, and its failure surface offers Retry and
+ * "Send as new" precisely so the user chooses.
+ * 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)
+ : -1;
+ const next = nextIndex >= 0 ? merged[nextIndex] : null;
+ const remainder = nextIndex >= 0 ? merged.filter((_, at) => at !== nextIndex) : merged;
if (shouldMigrate && newConvoQueue.length > 0) {
set(store.queuedMessagesByConvoId(Constants.NEW_CONVO), []);
@@ -379,8 +377,8 @@ export default function useQueueDrain(
conversationId,
queuedMessageOrigin: {
item: next,
- beforeIds: [],
- afterIds: remainder.map((item) => item.id),
+ beforeIds: merged.slice(0, nextIndex).map((item) => item.id),
+ afterIds: merged.slice(nextIndex + 1).map((item) => item.id),
},
expectedPredecessorCreatedAt:
end.generationCreatedAt ?? next.expectedPredecessorCreatedAt,
@@ -392,17 +390,29 @@ export default function useQueueDrain(
const restoreQueued = useRecoilCallback(
({ set }) =>
- (convoId: string, item: QueuedMessage) => {
- set(store.queuedMessagesByConvoId(convoId), (prev) =>
- !canRestoreRecovery(jotaiStore.get(recoveryDispositionsFamily(convoId)), item) ||
- prev.some((queued) => queued.id === item.id)
- ? prev
- : [item, ...prev],
- );
+ (convoId: string, origin: QueuedMessageOrigin) => {
+ set(store.queuedMessagesByConvoId(convoId), (prev) => insertQueuedOrigin(prev, origin));
},
[jotaiStore],
);
+ /** Held only until the pane's submission state moves or it changes chat: past
+ * either, both callers gate on `isSubmitting` directly and the claim is spent.
+ *
+ * Released from a cleanup rather than an effect body, because React runs every
+ * cleanup in a commit before any effect body: a stale claim can never starve
+ * the acquire below, and this release can never free a slot the composer's own
+ * submission in the same commit.
+ */
+ useEffect(
+ () => () => {
+ releaseQueueSendLock(sendLockRef.current);
+ sendLockRef.current = null;
+ revealLockRef.current = false;
+ },
+ [isSubmitting, sendLockKey, activeConversationId],
+ );
+
useEffect(() => {
if (
runEnd != null &&
@@ -412,15 +422,37 @@ export default function useQueueDrain(
parkForeignRunEnd();
return;
}
+ if (revealLockRef.current && revealedQueuedTurn == null) {
+ releaseQueueSendLock(sendLockRef.current);
+ sendLockRef.current = null;
+ revealLockRef.current = false;
+ }
if ((runEnd == null && parkedRunEnd == null) || isSubmitting) {
return;
}
+ /** `isSubmitting` above is a render-old read: the rail's own "Send now"
+ * can already have called `ask` for this pane in the current browser task.
+ * Claimed BEFORE the signal is consumed so a refusal leaves the run end
+ * armed for the next commit instead of dropping the queue on the floor. */
+ const lock = acquireQueueSendLock(sendLockKey, sendLockTimeoutMs);
+ if (lock == null) {
+ return;
+ }
const drained = drainNext();
if (drained == null) {
+ releaseQueueSendLock(lock);
return;
}
+ sendLockRef.current = lock;
+ revealLockRef.current = drained.kind === 'reveal';
if (drained.kind === 'reveal') {
- revealQueuedTurn?.(drained.item, drained.end);
+ if (revealQueuedTurn == null) {
+ releaseQueueSendLock(lock);
+ sendLockRef.current = null;
+ revealLockRef.current = false;
+ return;
+ }
+ revealQueuedTurn(drained.item, drained.end);
return;
}
const { next, conversationId, queuedMessageOrigin, expectedPredecessorCreatedAt } = drained;
@@ -441,6 +473,7 @@ export default function useQueueDrain(
overrideFiles: next.files ?? [],
overrideQuotes: next.quotes ?? [],
overrideManualSkills: next.manualSkills ?? [],
+ overrideReasoning: next.reasoningOverride ?? null,
overrideClientRequestId: next.clientRequestId,
overrideRecoverySteerId: next.recoverySteerId,
overrideExpectedPredecessorCreatedAt: expectedPredecessorCreatedAt,
@@ -448,11 +481,15 @@ export default function useQueueDrain(
},
);
if (accepted === false) {
+ releaseQueueSendLock(lock);
+ if (sendLockRef.current === lock) {
+ sendLockRef.current = null;
+ }
// `ask` refused without sending (e.g. the conversation history is not
// in the query cache yet, right after navigating back). Restore the
// item so the user's text is never silently dropped, the chip stays
// available for manual send.
- restoreQueued(conversationId, next);
+ restoreQueued(conversationId, queuedMessageOrigin);
/** Popping and restoring leaves the held set identical, so the renewal
* effect sees no change and will not re-run. Draining normally does
* change the set, and renews itself. Fire-and-forget: send-time
@@ -467,6 +504,8 @@ export default function useQueueDrain(
ownHeadId,
newConvoHeadId,
isSubmitting,
+ sendLockKey,
+ sendLockTimeoutMs,
activeConversationId,
parkForeignRunEnd,
drainNext,
diff --git a/client/src/hooks/Chat/useSteerCancel.ts b/client/src/hooks/Chat/useSteerCancel.ts
index 1d7bd76fb1..b004cce81a 100644
--- a/client/src/hooks/Chat/useSteerCancel.ts
+++ b/client/src/hooks/Chat/useSteerCancel.ts
@@ -1,36 +1,29 @@
import { useCallback } from 'react';
+import { useSetAtom } from 'jotai';
import { useRecoilCallback, useRecoilValue } from 'recoil';
import type { PendingSteer } from '~/store/families';
+import { useComposerRestoreHost } from '~/Providers/ComposerRestoreContext';
+import { appendAppliedSteerIds, carriedSteerContext } from '~/utils';
+import { pendingSteerCancelClientIdsFamily } from '~/store/steer';
+import useSteerConvert from '~/hooks/Chat/useSteerConvert';
import { useCancelSteerMutation } from '~/data-provider';
-import { appendAppliedSteerIds } from '~/utils';
import store from '~/store';
-/**
- * `reclaimed` — the cancel beat the boundary; the words never entered the run.
- * `applied` — the steer already injected (or the run ended): the events own it.
- * `failed` — the POST failed, so the entry is restored and the server may still
- * inject it.
- */
export type SteerCancelOutcome = 'reclaimed' | 'applied' | 'failed';
+/** Where a steer's words ended up once they stopped being a steer. */
+export type SteerRehomeTarget = 'composer' | 'queue';
+
/**
- * Asks the server to drop a steer before its injection boundary, touching no
- * chip state — the caller owns what happens to the words.
- *
- * A steer leaves the server queue only by injecting, so only `reclaimed` proves
- * the words never entered the run and are still the client's to re-home. Giving
- * an `applied` steer a second life (queueing it, editing it back into the
- * composer) would say the same thing twice; on `failed` the server may still
- * inject it, so its fate is unknown and it must be left alone.
+ * Asks the server to drop a steer before its injection boundary. Only a
+ * confirmed reclaim proves the words remain safe to move elsewhere.
*/
export function useSteerReclaim(conversationId: string) {
const cancelMutation = useCancelSteerMutation();
const activeGenerationCreatedAt = useRecoilValue(
store.activeGenerationCreatedAtByConvoId(conversationId),
);
- /** A confirmed reclaim is a terminal settlement too. Tombstone both ids so
- * a final payload captured before the server discard cannot requeue it, and
- * remove a recovered queue copy if the opposite ordering already occurred. */
+ const setPendingCancelIds = useSetAtom(pendingSteerCancelClientIdsFamily(conversationId));
const settleReclaimed = useRecoilCallback(
({ set }) =>
(steer: PendingSteer) => {
@@ -46,6 +39,7 @@ export function useSteerReclaim(conversationId: string) {
(item.clientSteerId == null || !settled.has(item.clientSteerId)),
),
);
+ setPendingCancelIds((prev) => prev.filter((id) => !ids.includes(id)));
set(store.queuedMessagesByConvoId(conversationId), (prev) =>
prev.filter(
(item) =>
@@ -55,7 +49,7 @@ export function useSteerReclaim(conversationId: string) {
),
);
},
- [conversationId],
+ [conversationId, setPendingCancelIds],
);
return useCallback(
@@ -85,35 +79,130 @@ export function useSteerReclaim(conversationId: string) {
);
}
+export function useSteerMoveToQueue(conversationId: string) {
+ const reclaim = useSteerReclaim(conversationId);
+ const convertSteersToQueued = useSteerConvert();
+ const { rewakeDrain } = useComposerRestoreHost();
+
+ return useCallback(
+ async (steer: PendingSteer): Promise<SteerCancelOutcome> => {
+ const outcome = await reclaim(steer);
+ if (outcome === 'reclaimed') {
+ convertSteersToQueued(conversationId, [steer], {
+ generationProtocolVersion: steer.generationProtocolVersion,
+ allowPreviouslyConvertedIds: [steer.steerId],
+ bindRecoverySource: false,
+ });
+ /* The run may have finished while the cancel was in flight, spending
+ the drain's one-shot signal on a queue this row was not in yet. */
+ rewakeDrain(conversationId);
+ }
+ return outcome;
+ },
+ [conversationId, convertSteersToQueued, reclaim, rewakeDrain],
+ );
+}
+
/**
- * Cancels a steer still waiting on its injection boundary. The chip stays
- * visible until the request settles so capability/update events can still
- * patch its current server revision while cancel is in flight. Only a
- * confirmed reclaim removes it here. `removed:false` is ambiguous in the v1
- * protocol (already injected OR terminal conversion won), so the event path
- * must decide whether to remove or recover that entry without discarding its
- * client-only files/quotes/skills first.
+ * The one place a steer stops being a steer and becomes the user's words
+ * again, whole: text, attachments, quoted excerpts, manual skill picks and the
+ * reasoning override travel together or not at all.
+ *
+ * The composer is preferred, because every path that reaches here is the user
+ * asking to take the message back rather than to send it later, but it is
+ * allowed to refuse: it may hold a draft, be showing another chat, be paused
+ * on a question that owns the box, or have unmounted while the reclaim was in
+ * flight. A refusal converts the steer into an ordinary queued follow-up,
+ * which carries the same context, so the words are never dropped on the floor.
+ *
+ * The chip goes either way. Once the words live somewhere else, a pending row
+ * claiming the server still holds them is a lie.
*/
-export default function useSteerCancel(conversationId: string) {
- const reclaim = useSteerReclaim(conversationId);
+export interface SteerRehomeOptions {
+ /** The server refused these words. Queued as a fallback they must wait for
+ * the user to send them, or the run-end drain would turn a refusal into an
+ * automatic new turn carrying the payload that was rejected. */
+ rejectedByServer?: boolean;
+}
- const removeEntry = useRecoilCallback(
+export function useSteerRehome(conversationId: string) {
+ const { restore, rewakeDrain } = useComposerRestoreHost();
+ const convertSteersToQueued = useSteerConvert();
+ const dropPendingSteer = useRecoilCallback(
({ set }) =>
- (steerId: string) => {
+ (steer: PendingSteer) => {
+ const ids = new Set([steer.steerId, ...(steer.clientSteerId ? [steer.clientSteerId] : [])]);
set(store.pendingSteersByConvoId(conversationId), (prev) =>
- prev.filter((item) => item.steerId !== steerId),
+ prev.filter(
+ (item) =>
+ !ids.has(item.steerId) &&
+ (item.clientSteerId == null || !ids.has(item.clientSteerId)),
+ ),
);
},
[conversationId],
);
+
+ return useCallback(
+ (steer: PendingSteer, options?: SteerRehomeOptions): SteerRehomeTarget => {
+ const taken = restore(steer.text, steer.files, carriedSteerContext(steer), conversationId);
+ if (taken) {
+ dropPendingSteer(steer);
+ return 'composer';
+ }
+ /* `useSteerConvert` drops the chip itself as part of the conversion and
+ carries the same context onto the queued row. */
+ convertSteersToQueued(conversationId, [steer], {
+ generationProtocolVersion: steer.generationProtocolVersion,
+ allowPreviouslyConvertedIds: [steer.steerId],
+ bindRecoverySource: false,
+ ...(options?.rejectedByServer === true && { needsExplicitSend: true }),
+ });
+ if (options?.rejectedByServer !== true) {
+ rewakeDrain(conversationId);
+ }
+ return 'queue';
+ },
+ [conversationId, convertSteersToQueued, dropPendingSteer, restore, rewakeDrain],
+ );
+}
+
+export default function useSteerCancel(conversationId: string) {
+ const reclaim = useSteerReclaim(conversationId);
+ const rehome = useSteerRehome(conversationId);
+ const setPendingCancelIds = useSetAtom(pendingSteerCancelClientIdsFamily(conversationId));
+ const markOptimisticCancel = useRecoilCallback(
+ ({ set }) =>
+ (steer: PendingSteer) => {
+ const clientId = steer.clientSteerId ?? steer.steerId;
+ setPendingCancelIds((prev) => (prev.includes(clientId) ? prev : [...prev, clientId]));
+ if (steer.status === 'sending') {
+ set(store.pendingSteersByConvoId(conversationId), (prev) =>
+ prev.filter((item) => item.steerId !== steer.steerId),
+ );
+ }
+ },
+ [conversationId, setPendingCancelIds],
+ );
+ const clearOptimisticCancel = useCallback(
+ (steer: PendingSteer) => {
+ const clientId = steer.clientSteerId ?? steer.steerId;
+ setPendingCancelIds((prev) => prev.filter((id) => id !== clientId));
+ },
+ [setPendingCancelIds],
+ );
return useCallback(
async (steer: PendingSteer): Promise<SteerCancelOutcome> => {
+ if (steer.status === 'sending') {
+ markOptimisticCancel(steer);
+ }
const outcome = await reclaim(steer);
if (outcome === 'reclaimed') {
- removeEntry(steer.steerId);
+ rehome(steer);
+ clearOptimisticCancel(steer);
}
return outcome;
},
- [reclaim, removeEntry],
+ [clearOptimisticCancel, markOptimisticCancel, reclaim, rehome],
);
}
diff --git a/client/src/hooks/Chat/useSteerConvert.ts b/client/src/hooks/Chat/useSteerConvert.ts
index e363354310..8f2593763d 100644
--- a/client/src/hooks/Chat/useSteerConvert.ts
+++ b/client/src/hooks/Chat/useSteerConvert.ts
@@ -40,12 +40,18 @@ interface SteerConvertOptions {
* consumed by THIS recovery generation. Never set for an arbitrary or
* pre-start status response: those can be stale after a successful start. */
allowPreviouslyConvertedIds?: readonly string[];
+ /** Local failures have no durable receipt to reclaim on a later send. */
+ bindRecoverySource?: boolean;
+ /** Mark the converted rows so the run-end drain leaves them for an explicit
+ * send. Set for steers the server rejected: sweeping them out of the chip
+ * surface must not turn a refusal into an automatic new turn. */
+ needsExplicitSend?: boolean;
}
/**
* Converts server-reported leftover steers into queued follow-up chips.
* Converted ids join the applied set so a 202 ACK that lands after the run
- * ended drops its chip instead of re-minting a stranded `pending` one — the
+ * ended drops its chip instead of re-minting a stranded `pending` one: the
* set must survive run end for exactly that race, so it is capped, not
* cleared. Safe to call from multiple delivery paths for the same steers
* (final SSE event AND abort HTTP response): chip removal and queue
@@ -69,6 +75,8 @@ export default function useSteerConvert() {
steers: ConvertibleSteer[],
generationProtocolVersion?: GenerationProtocolVersion,
allowPreviouslyConvertedIds: readonly string[] = [],
+ bindRecoverySource?: boolean,
+ needsExplicitSend?: boolean,
) => {
if (steers.length === 0) {
return;
@@ -78,7 +86,7 @@ export default function useSteerConvert() {
snapshot
.getLoadable(store.activeGenerationProtocolVersionByConvoId(conversationId))
.getValue();
- const bindRecoverySource = negotiatedVersion === 2;
+ const shouldBindRecoverySource = bindRecoverySource ?? negotiatedVersion === 2;
// Restore quotes/skill picks from the local chip (matched by id)
// before the chips are dropped below: the chip is the only carrier of
// skill picks, and of quotes accepted by an older server whose queue
@@ -98,7 +106,7 @@ export default function useSteerConvert() {
// Steers already settled (applied on the server OR converted here on an
// earlier delivery) must not re-enter the queue. Read BEFORE the append
// below so a first-time conversion still queues, but a redelivery whose
- // item was already DRAINED out of the queue is a no-op — without this,
+ // item was already DRAINED out of the queue is a no-op: without this,
// the queue-only dedup below misses a message the run-end drain already
// submitted and re-mints it as a stranded queued chip.
const settledSteerIds = new Set(
@@ -116,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: QueuedMessage[] = bindRecoverySource
+ const existing = shouldBindRecoverySource
? prev
: prev.map((item) => {
const matchesClaimedSource =
@@ -158,28 +166,32 @@ export default function useSteerConvert() {
local?.files,
fileMapRef.current,
);
- const held =
- jotaiStore.get(recoveryDispositionsFamily(conversationId))[steer.steerId] != null;
- const recoveryFields =
- bindRecoverySource || 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 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 explicitSend = needsExplicitSend === true ? { needsExplicitSend: true } : {};
const item =
queuedOrigin != null
- ? { ...queuedOrigin.item, ...recoveryFields, ...(files && { files }) }
+ ? {
+ ...queuedOrigin.item,
+ ...recoveryFields,
+ ...explicitSend,
+ ...(files && { files }),
+ }
: ({
id: steer.steerId,
text: steer.text,
createdAt: steer.createdAt ?? Date.now(),
...recoveryFields,
+ ...explicitSend,
...(files && files.length > 0 && { files }),
// The chip is the usual source, but a reclaimed steer may
// have lost its chip to a competing cancel mid-round-trip.
@@ -202,15 +214,27 @@ export default function useSteerConvert() {
if (fresh.length === 0) {
return existing;
}
- /** Ordinary steer leftovers merge chronologically. A steer that
- * originated in this queue restores its exact object/identity and
- * captured position instead of being re-minted under the server id. */
- const ordinary = fresh.filter(({ queuedOrigin }) => queuedOrigin == null);
- let merged: QueuedMessage[] = [...existing, ...ordinary.map(({ item }) => item)].sort(
- (a, b) =>
- Number(b.priority ?? false) - Number(a.priority ?? false) ||
- a.createdAt - b.createdAt,
- );
+ // Each new item is placed chronologically (a steer accepted BEFORE
+ // the user queued a later follow-up must drain first) EXCEPT explicit
+ // front-inserts ("Interrupt & send"), whose urgency outranks age.
+ //
+ // Placed rather than sorted: the queue can be reordered by hand from
+ // the rail, and sorting the whole list would quietly restore the order
+ // the messages were written in, changing which one sends next.
+ let merged: QueuedMessage[] = [...existing];
+ const ordinary = fresh
+ .filter(({ queuedOrigin }) => queuedOrigin == null)
+ .map(({ item }) => item)
+ .sort((a, b) => a.createdAt - b.createdAt);
+ for (const item of ordinary) {
+ const at = merged.findIndex(
+ (queued) => queued.priority !== true && queued.createdAt > item.createdAt,
+ );
+ merged.splice(at === -1 ? merged.length : at, 0, item);
+ }
+ /** A steer that originated in this queue restores its exact
+ * object/identity and captured position instead of being re-minted
+ * under the server id at a merely chronological spot. */
for (const { queuedOrigin } of fresh) {
if (queuedOrigin != null) {
merged = insertQueuedOrigin(merged, queuedOrigin);
@@ -229,6 +253,8 @@ export default function useSteerConvert() {
steers,
options?.generationProtocolVersion,
options?.allowPreviouslyConvertedIds,
+ options?.bindRecoverySource,
+ options?.needsExplicitSend,
);
if (options?.claimParked !== true || steers.length === 0) {
return;
diff --git a/client/src/hooks/Chat/useSteerEscalate.ts b/client/src/hooks/Chat/useSteerEscalate.ts
new file mode 100644
index 0000000000..95851d5eec
--- /dev/null
+++ b/client/src/hooks/Chat/useSteerEscalate.ts
@@ -0,0 +1,181 @@
+import { useCallback } from 'react';
+import { useSetAtom } from 'jotai';
+import { useToastContext } from '@librechat/client';
+import { useRecoilValue, useRecoilCallback } from 'recoil';
+import { DEFAULT_STEER_ARM_CONFIRMATION_TIMEOUT_MS } from 'librechat-data-provider';
+import {
+ supportsGenerationProtocolV2,
+ useArmSteerMutation,
+ useGetStartupConfig,
+} from '~/data-provider';
+import { escalatingSteerFamily } from '~/store/steer';
+import useLocalize from '~/hooks/useLocalize';
+import store from '~/store';
+
+type ArmFailure = {
+ name?: string;
+ response?: { data?: { code?: string } };
+};
+
+/** Only a failure without an HTTP response leaves the server-side outcome
+ * unknown. An HTTP rejection is a known response and must not replay the arm. */
+const isAmbiguousArmFailure = (error: unknown): boolean => {
+ const failure = error as ArmFailure | null | undefined;
+ return failure?.name !== 'AbortError' && failure?.response == null;
+};
+
+const armFailureCode = (error: unknown): string | undefined =>
+ (error as ArmFailure | null | undefined)?.response?.data?.code;
+
+export interface EscalateTarget {
+ steerId: string;
+ /** The generation that owns this steer receipt; falls back to the active one. */
+ generationCreatedAt?: number;
+}
+
+/**
+ * Escalates a waiting steer to an interrupt: one idempotent server op flips
+ * `preempt` on the EXISTING queued item, so its FIFO position, id, and
+ * timestamp survive and there is no reclaim window to race. A transport
+ * failure is retried once because the first request may have committed even
+ * though its response was lost. Every "too late" interleaving (drained,
+ * cancelled, run ended or replaced) is the same honest `armed: false`, and the
+ * chip is only relabelled on a confirmed durable arm.
+ *
+ * Extracted from the surfaces so the queue rail and the in-thread pending
+ * steers escalate through identical race rules rather than two approximations.
+ * `onArmed` lets a caller move focus off a control the success state removes.
+ */
+export default function useSteerEscalate(conversationId: string) {
+ const localize = useLocalize();
+ const { showToast } = useToastContext();
+ const { mutateAsync: armSteer } = useArmSteerMutation();
+ const { data: startupConfig } = useGetStartupConfig();
+ const armConfirmTimeoutMs =
+ startupConfig?.interface?.steerArmConfirmationTimeoutMs ??
+ DEFAULT_STEER_ARM_CONFIRMATION_TIMEOUT_MS;
+ const setEscalating = useSetAtom(escalatingSteerFamily(conversationId));
+ const activeGenerationCreatedAt = useRecoilValue(
+ store.activeGenerationCreatedAtByConvoId(conversationId),
+ );
+ const activeGenerationProtocolVersion = useRecoilValue(
+ store.activeGenerationProtocolVersionByConvoId(conversationId),
+ );
+
+ /** Relabels the chip in place once the server confirms the durable arm:
+ * same steerId, same position, only the `preempt` flag flips. */
+ const markSteerPreempt = useRecoilCallback(
+ ({ set }) =>
+ (steerId: string, revision: number) =>
+ set(store.pendingSteersByConvoId(conversationId), (prev) =>
+ prev.map((item) =>
+ item.steerId === steerId && revision >= (item.preemptRevision ?? 0)
+ ? { ...item, preempt: true, preemptRevision: revision }
+ : item,
+ ),
+ ),
+ [conversationId],
+ );
+
+ return useCallback(
+ (target: EscalateTarget, onArmed?: () => void) => {
+ const generationCreatedAt = target.generationCreatedAt ?? activeGenerationCreatedAt;
+ if (generationCreatedAt == null) {
+ return;
+ }
+ setEscalating(true);
+ const params = { conversationId, steerId: target.steerId, generationCreatedAt };
+ const requestArm = async () => {
+ let firstResponseWasLost = false;
+ let acceptingRetry = true;
+ let timeout: ReturnType<typeof setTimeout> | undefined;
+ try {
+ const firstAttempt = armSteer(params);
+ const attempts =
+ activeGenerationProtocolVersion === 2
+ ? firstAttempt.catch((error) => {
+ /** If the overall confirmation window already closed, do not let a
+ * very late rejection launch a detached retry behind the user's
+ * back. The first request itself may still have committed. */
+ if (!acceptingRetry) {
+ throw error;
+ }
+ if (!isAmbiguousArmFailure(error)) {
+ throw error;
+ }
+ firstResponseWasLost = true;
+ return armSteer(params);
+ })
+ : firstAttempt;
+ const response = await Promise.race([
+ attempts,
+ new Promise<never>((_resolve, reject) => {
+ timeout = setTimeout(
+ () => reject(new Error('Steer arm confirmation timed out')),
+ armConfirmTimeoutMs,
+ );
+ }),
+ ]);
+ const responseSupportsNegotiatedProtocol =
+ activeGenerationProtocolVersion === 1 || supportsGenerationProtocolV2(response);
+ if (responseSupportsNegotiatedProtocol && response.armed === true) {
+ markSteerPreempt(target.steerId, response.preemptRevision ?? 0);
+ onArmed?.();
+ return;
+ }
+ if (!responseSupportsNegotiatedProtocol) {
+ showToast({ message: localize('com_ui_steer_arm_unconfirmed'), status: 'warning' });
+ return;
+ }
+ /** Once a response was lost, a later `armed: false` cannot prove the
+ * first request did not commit: the steer may have drained or the job
+ * may have paused between attempts. Keep the chip event-driven and
+ * report the result as unknown instead of claiming a lost race. */
+ if (firstResponseWasLost) {
+ showToast({ message: localize('com_ui_steer_arm_unconfirmed'), status: 'warning' });
+ return;
+ }
+ /* `armed: false` is deliberately ambiguous (injected, cancelled,
+ * re-homed, or run over), so the message only says the escalation
+ * lost, and the chip defers to the events for what happened. */
+ showToast({
+ message: localize(
+ response.code === 'PREEMPT_UNSUPPORTED'
+ ? 'com_ui_steer_preempt_unsupported'
+ : 'com_ui_steer_arm_lost_race',
+ ),
+ status: 'info',
+ });
+ } catch (error) {
+ if (isAmbiguousArmFailure(error)) {
+ showToast({ message: localize('com_ui_steer_arm_unconfirmed'), status: 'warning' });
+ return;
+ }
+ showToast({
+ message: localize(
+ armFailureCode(error) === 'PREEMPT_UNSUPPORTED'
+ ? 'com_ui_steer_preempt_unsupported'
+ : 'com_ui_steer_arm_lost_race',
+ ),
+ status: 'info',
+ });
+ } finally {
+ acceptingRetry = false;
+ clearTimeout(timeout);
+ }
+ };
+ void requestArm().finally(() => setEscalating(false));
+ },
+ [
+ armSteer,
+ conversationId,
+ activeGenerationCreatedAt,
+ activeGenerationProtocolVersion,
+ armConfirmTimeoutMs,
+ setEscalating,
+ markSteerPreempt,
+ showToast,
+ localize,
+ ],
+ );
+}
diff --git a/client/src/hooks/Chat/useSteerRecovery.ts b/client/src/hooks/Chat/useSteerRecovery.ts
new file mode 100644
index 0000000000..ffd7c0c93c
--- /dev/null
+++ b/client/src/hooks/Chat/useSteerRecovery.ts
@@ -0,0 +1,332 @@
+import { useCallback } from 'react';
+import { useStore } from 'jotai';
+import { useRecoilCallback } from 'recoil';
+import type { Snapshot } from 'recoil';
+import type { PendingSteer } from '~/store/families';
+import {
+ getSteerErrorCode,
+ isDefiniteSteerRejection,
+ resolveAcknowledgedSteer,
+} from '~/hooks/Chat/useSteering';
+import { useSteerMessageMutation, useCancelSteerMutation } from '~/data-provider';
+import { useComposerRestoreHost } from '~/Providers/ComposerRestoreContext';
+import { carriedSteerContext, isLegacyDeliveryUncertain } from '~/utils';
+import { pendingSteerCancelClientIdsFamily } from '~/store/steer';
+import { useSteerRehome } from '~/hooks/Chat/useSteerCancel';
+import useSteerConvert from '~/hooks/Chat/useSteerConvert';
+import store from '~/store';
+
+/**
+ * Retry or re-route a pending steer from OUTSIDE the composer. The thread's
+ * pending block needs these actions without dragging the whole
+ * `SteeringControls` object through the message tree.
+ */
+export default function useSteerRecovery(conversationId: string) {
+ const { mutateAsync: steerMessage } = useSteerMessageMutation();
+ const { mutateAsync: cancelSteer } = useCancelSteerMutation();
+ const convertSteersToQueued = useSteerConvert();
+ const rehomeSteer = useSteerRehome(conversationId);
+ const { rewakeDrain } = useComposerRestoreHost();
+ const jotaiStore = useStore();
+
+ /** Whether the run this steer belongs to has finished, read live at ack time.
+ * Unmounting is not the same signal: `PendingSteers` also unmounts when the
+ * user navigates away from a run that is still going, and treating that as
+ * the end queued the accepted steer as a follow-up on top of the injection
+ * the server was already making. */
+ const isRunOver = useCallback(
+ (snapshot: Snapshot) => {
+ const keys = snapshot.getLoadable(store.conversationKeysAtom).getValue();
+ let held = false;
+ for (const key of keys) {
+ const convo = snapshot.getLoadable(store.conversationByIndex(key)).getValue();
+ if (convo?.conversationId !== conversationId) {
+ continue;
+ }
+ /* Comparison mode can hold one conversation in several panes, and only
+ the pane that owns the run is submitting: any live pane means the
+ run is still going, whichever slot comes first. */
+ if (snapshot.getLoadable(store.isSubmittingFamily(key)).getValue() === true) {
+ return false;
+ }
+ held = true;
+ }
+ /* Held by no slot at all: the user navigated to another chat, which says
+ nothing about the run they left behind. Reading that as the end is the
+ same mistake as reading the unmount as the end, one step further out. */
+ return held;
+ },
+ [conversationId],
+ );
+
+ const markStatus = useRecoilCallback(
+ ({ set }) =>
+ (steerId: string, status: PendingSteer['status']) => {
+ set(store.pendingSteersByConvoId(conversationId), (prev) =>
+ prev.map((steer) => (steer.steerId === steerId ? { ...steer, status } : steer)),
+ );
+ },
+ [conversationId],
+ );
+
+ const markFailure = useRecoilCallback(
+ ({ set }) =>
+ (steerId: string, deliveryUncertain: boolean) => {
+ set(store.pendingSteersByConvoId(conversationId), (prev) =>
+ prev.map((steer) => {
+ if (steer.steerId !== steerId) {
+ return steer;
+ }
+ const { deliveryUncertain: _deliveryUncertain, ...rest } = steer;
+ return {
+ ...rest,
+ status: 'failed',
+ ...(deliveryUncertain && { deliveryUncertain: true }),
+ };
+ }),
+ );
+ },
+ [conversationId],
+ );
+
+ /**
+ * The retry's 202 ACK, resolved by the SHARED implementation the composer
+ * uses so the two cannot drift on epoch replacement, already-accepted client
+ * ids, or the applied-id check. All this call site contributes is its own
+ * observation of ordinary terminal state.
+ *
+ * @returns true when the caller must route the steer into the queue.
+ */
+ const acknowledgeRetry = useRecoilCallback(
+ (cbInterface) =>
+ (localId: string, steer: PendingSteer): boolean =>
+ resolveAcknowledgedSteer(
+ cbInterface,
+ conversationId,
+ localId,
+ steer,
+ isRunOver(cbInterface.snapshot),
+ ),
+ [conversationId, isRunOver],
+ );
+
+ /** Routes a steer straight into the queue: reused for a retry that degrades
+ * (no active run / paused / unsupported / queue full), for an ACK the
+ * resolver reports as unresolvable, and for `sendAsNew`, so all three get
+ * the same id-dedup, chronological merge, and applied-id bookkeeping as
+ * every other steer-to-queue conversion, instead of a blind append that a
+ * late ACK could still re-mint a chip for. */
+ const queueSteer = useCallback(
+ (steer: PendingSteer, bindRecoverySource?: boolean) => {
+ convertSteersToQueued(
+ conversationId,
+ [
+ {
+ steerId: steer.steerId,
+ ...(steer.clientSteerId && { clientSteerId: steer.clientSteerId }),
+ text: steer.text,
+ createdAt: steer.createdAt,
+ ...(steer.files && steer.files.length > 0 && { files: steer.files }),
+ ...carriedSteerContext(steer),
+ },
+ ],
+ {
+ /** The receipt belongs to the generation that produced it. The
+ * conversation may already advertise a replacement generation by the
+ * time a late ACK lands, and reading the protocol off that one would
+ * bind (or strip) the wrong recovery identity. */
+ generationProtocolVersion: steer.generationProtocolVersion,
+ /** Left unset, binding follows that pinned version: only v2
+ * conversations can bind a queued follow-up to a durable receipt.
+ * Forcing it on a v1 row points the recovery source at machinery the
+ * v1 server never parks, and the drain's explicit send dies
+ * mid-commit. Local failures still pass `false` explicitly: they hold
+ * no receipt to bind. */
+ ...(bindRecoverySource != null && { bindRecoverySource }),
+ },
+ );
+ /* These conversions settle asynchronously. A retry left `sending` is kept
+ out of the run-end sweep, so if the run finished while the POST was in
+ flight the drain has already spent its one-shot signal on a queue this
+ row was not in yet. Re-post it; the composer ignores the call unless
+ that run completed cleanly and no newer signal is armed. */
+ rewakeDrain(conversationId);
+ },
+ [conversationId, convertSteersToQueued, rewakeDrain],
+ );
+
+ const retry = useRecoilCallback(
+ ({ snapshot, set }) =>
+ (steerId: string) => {
+ const steer = snapshot
+ .getLoadable(store.pendingSteersByConvoId(conversationId))
+ .getValue()
+ .find((item) => item.steerId === steerId);
+ if (!steer || isLegacyDeliveryUncertain(steer)) {
+ return;
+ }
+ markStatus(steerId, 'sending');
+ /* Resolved through the promise rather than through `mutate`'s
+ per-call callbacks, which react-query drops once the observer has no
+ listeners. This hook lives in the block that unmounts the moment the
+ run ends, which is exactly when a retry's ack tends to land: those
+ callbacks never ran, and the chip was left saying `sending` for the
+ rest of the conversation with the words neither sent nor queued. */
+ /* `preempt` rides along: a chip that failed as an interrupt-steer has to
+ retry AS one. Resent without it the words land at the run's next tool
+ step instead of sealing the stream, which is a different action than
+ the one the user asked for and the chip still claims to be. */
+ /* The same identity fields the composer's retry sends. `clientSteerId`
+ is what the server dedupes a committed POST on, so an uncertain
+ transport cannot apply these words twice, and `generationCreatedAt`
+ pins the attempt to the generation the chip belongs to rather than
+ whichever turn now occupies the conversation-scoped stream id. */
+ const clientSteerId = steer.clientSteerId ?? steerId;
+ steerMessage({
+ conversationId,
+ clientSteerId,
+ text: steer.text,
+ files: steer.files,
+ ...(steer.quotes != null && { quotes: steer.quotes }),
+ ...(steer.generationCreatedAt != null && {
+ generationCreatedAt: steer.generationCreatedAt,
+ }),
+ ...(steer.preempt === true && { preempt: true }),
+ })
+ .then((response) => {
+ const acceptAck = () => {
+ const { deliveryUncertain: _deliveryUncertain, ...resolvedSteer } = steer;
+ const acknowledged: PendingSteer = {
+ ...resolvedSteer,
+ steerId: response.steerId,
+ clientSteerId,
+ status: 'pending',
+ /* The server echoes what it actually armed: without the
+ capability it queues the steer and reports `preempt: false`,
+ which relabels the chip rather than failing it. */
+ preempt: response.preempt === true,
+ };
+ /* The resolver owns the decision: an ACK for a run that already
+ ended, or for a generation since replaced, has no later SSE event
+ left to settle a `pending` chip, so the words go to the queue
+ instead of being stranded. */
+ if (acknowledgeRetry(steerId, acknowledged)) {
+ queueSteer(acknowledged);
+ }
+ };
+ if (
+ !jotaiStore
+ .get(pendingSteerCancelClientIdsFamily(conversationId))
+ .includes(clientSteerId)
+ ) {
+ acceptAck();
+ return;
+ }
+ /* The user cancelled while the retry POST was in flight. The
+ composer settles this same race with a deferred cancel: clearing
+ the marker without one loses the words, and accepting the ACK
+ without one injects them after the user asked for them back. */
+ void cancelSteer({
+ conversationId,
+ steerId: response.steerId,
+ clientSteerId,
+ ...(steer.generationCreatedAt != null && {
+ generationCreatedAt: steer.generationCreatedAt,
+ }),
+ }).then(
+ ({ removed }) => {
+ jotaiStore.set(pendingSteerCancelClientIdsFamily(conversationId), (ids) =>
+ ids.filter((id) => id !== clientSteerId),
+ );
+ if (removed !== true) {
+ /* The server kept the steer: it is live and will still reach
+ the agent. The chip the optimistic cancel hid comes back
+ through the ordinary acknowledgement, so it settles like
+ any other accepted retry. */
+ acceptAck();
+ return;
+ }
+ /* The cancel beat the retry's POST, so the words are off the
+ server: they come back through the same boundary as an
+ immediate cancel, whole, and queued for an explicit send
+ when the composer will not take them. */
+ rehomeSteer({ ...steer, steerId: response.steerId });
+ },
+ () => {
+ jotaiStore.set(pendingSteerCancelClientIdsFamily(conversationId), (ids) =>
+ ids.filter((id) => id !== clientSteerId),
+ );
+ /* Unknown cancel outcome, but the retry POST was accepted:
+ treat the steer as live rather than claiming it is gone. */
+ acceptAck();
+ },
+ );
+ })
+ .catch((error: unknown) => {
+ if (
+ jotaiStore
+ .get(pendingSteerCancelClientIdsFamily(conversationId))
+ .includes(clientSteerId)
+ ) {
+ jotaiStore.set(pendingSteerCancelClientIdsFamily(conversationId), (ids) =>
+ ids.filter((id) => id !== clientSteerId),
+ );
+ /* The optimistic cancel removed the sending chip, and every
+ path below settles by mapping chips that still exist: without
+ the chip back the words vanish, unsent and unqueued both. */
+ set(store.pendingSteersByConvoId(conversationId), (prev) => [...prev, steer]);
+ }
+ const code = getSteerErrorCode(error);
+ // The run ended, is paused, was replaced, or can't accept a steer
+ // right now: none of that means the words are lost, just that a
+ // queued follow-up is the only way left to send them. `RUN_REPLACED`
+ // belongs here too, because the retry pins `generationCreatedAt` to
+ // the chip's own generation: once a newer run owns the conversation
+ // every retry earns that same 409 and the chip would be stuck failed
+ // forever. Queueing is what the composer does with it, and unlike
+ // the composer's normal-send fallback it cannot displace the
+ // replacement run.
+ if (
+ code === 'NO_ACTIVE_RUN' ||
+ code === 'RUN_PAUSED' ||
+ code === 'RUN_REPLACED' ||
+ code === 'STEER_UNSUPPORTED' ||
+ code === 'STEER_QUEUE_FULL'
+ ) {
+ queueSteer(steer, false);
+ return;
+ }
+ markFailure(steerId, !isDefiniteSteerRejection(error));
+ });
+ },
+ [
+ conversationId,
+ steerMessage,
+ cancelSteer,
+ rehomeSteer,
+ jotaiStore,
+ markStatus,
+ markFailure,
+ acknowledgeRetry,
+ queueSteer,
+ ],
+ );
+
+ /** Move a failed steer into the queue: it sends when the reply finishes. */
+ const sendAsNew = useRecoilCallback(
+ ({ snapshot }) =>
+ (steerId: string) => {
+ const steer = snapshot
+ .getLoadable(store.pendingSteersByConvoId(conversationId))
+ .getValue()
+ .find((item) => item.steerId === steerId);
+ if (!steer || steer.deliveryUncertain === true) {
+ return;
+ }
+ queueSteer(steer, false);
+ },
+ [conversationId, queueSteer],
+ );
+
+ return { retry, sendAsNew };
+}
diff --git a/client/src/hooks/Chat/useSteering.ts b/client/src/hooks/Chat/useSteering.ts
index 25931178a8..2e7beba585 100644
--- a/client/src/hooks/Chat/useSteering.ts
+++ b/client/src/hooks/Chat/useSteering.ts
@@ -8,6 +8,8 @@ import {
ContentTypes,
isAgentsEndpoint,
isAssistantsEndpoint,
+ DEFAULT_QUEUED_TURN_RECONCILIATION_TIMEOUT_MS,
+ DEFAULT_QUEUED_SEND_LOCK_TIMEOUT_MS,
} from 'librechat-data-provider';
import type {
TAgentQueuedTurnFileRef,
@@ -15,6 +17,7 @@ import type {
TConversation,
TMessageContentParts,
} from 'librechat-data-provider';
+import type { CallbackInterface } from 'recoil';
import type {
RunEnd,
PendingSteer,
@@ -23,8 +26,10 @@ import type {
SettledQueuedTurnReceipt,
} from '~/store/families';
import type { AgentQueuedTurnReceipt, GenerationProtocolVersion } from '~/data-provider';
+import type { QueueSendLock } from '~/utils/queueIntent';
import type { ExtendedFile, FileSetter } from '~/common';
import {
+ useGetStartupConfig,
useCancelSteerMutation,
useSteerMessageMutation,
useMarkFilesUsageMutation,
@@ -38,20 +43,22 @@ import {
import {
appendAppliedSteerIds,
carriedSteerContext,
+ findLiveAskUserQuestion,
insertQueuedOrigin,
hydrateFileDeliveryMetadata,
mergeRestagedQuotes,
} from '~/utils';
import {
- recoveryDispositionsFamily,
- recoveryDisposition,
- canRestoreRecovery,
- blockRecovery,
-} from '~/components/Chat/Steering/recovery';
-import useCodeApprovalMode from '../Agents/useCodeApprovalMode';
+ getReasoningStateKey,
+ pendingReasoningOverrideFamily,
+} from '~/components/Chat/Input/Composer/state';
+import { hasQueuedIntent, acquireQueueSendLock, releaseQueueSendLock } from '~/utils/queueIntent';
+import { revealedQueuedTurnFamily, pendingSteerCancelClientIdsFamily } from '~/store/steer';
+import { markComposerFilesTaken } from '~/utils/composerFiles';
+import { useSteerRehome } from '~/hooks/Chat/useSteerCancel';
import useSteerConvert from '~/hooks/Chat/useSteerConvert';
-import { revealedQueuedTurnFamily } from '~/store/steer';
import { useLatestMessage } from '~/hooks/Messages';
+import { insertQueuedMessage } from '~/utils/queue';
import { useSetFilesToDelete } from '~/hooks/Files';
import { useFileMapContext } from '~/Providers';
import useLocalize from '~/hooks/useLocalize';
@@ -64,6 +71,7 @@ export type DuringRunAction = 'steer' | 'queue';
export interface QueuedMessageContext {
quotes?: string[];
manualSkills?: string[];
+ reasoningOverride?: TMessage['reasoningOverride'];
clientRequestId?: string;
recoverySteerId?: string;
expectedPredecessorCreatedAt?: number;
@@ -72,12 +80,8 @@ export interface QueuedMessageContext {
/** Server-side cap on a usage touch (mirrors `FILES_USAGE_MAX_IDS`). */
const QUEUE_USAGE_MAX_FILES = 10;
-/** Bound transport-outcome reconciliation while still guaranteeing several
- * list reads after the enqueue promise settles. Focus/remount remains a later
- * reconciliation path for exceptionally slow intermediaries. */
-const QUEUED_TURN_RECONCILIATION_MS = 60_000;
-type SteerErrorCode =
+export type SteerErrorCode =
| 'NO_ACTIVE_RUN'
| 'RUN_PAUSED'
| 'RUN_REPLACED'
@@ -101,12 +105,12 @@ type SubmitSteerOptions = {
generationProtocolVersion?: GenerationProtocolVersion;
};
-function getSteerErrorCode(error: unknown): SteerErrorCode | undefined {
+export function getSteerErrorCode(error: unknown): SteerErrorCode | undefined {
const response = (error as { response?: { data?: { code?: string } } } | undefined)?.response;
return response?.data?.code;
}
-function isDefiniteSteerRejection(error: unknown): boolean {
+export function isDefiniteSteerRejection(error: unknown): boolean {
const status = (error as { response?: { status?: number } } | undefined)?.response?.status;
return (
status != null &&
@@ -129,9 +133,117 @@ function isSameRunEpoch(a: RunEnd | null, b: RunEnd): boolean {
return a.endedAt === b.endedAt;
}
-/** True when the latest assistant message carries an unresolved tool approval —
- * the run is (or is about to be) paused, so a steer POST would 409. */
-function hasLiveToolApproval(message: TMessage | null): boolean {
+/**
+ * Resolves a steer's 202 ACK against the applied-id set and the run's live
+ * state: on the common path the local chip is swapped for its server-assigned
+ * id (still `pending`, awaiting `on_steer_applied`). If an `on_steer_applied`
+ * event already beat the ACK, if the source generation was replaced, or if the
+ * run itself ended before the ACK landed, no later SSE event will ever resolve
+ * a `pending` chip, so the caller is told to route the words into the queue
+ * instead of stranding one.
+ *
+ * `ordinaryRunOver` is the caller's observation of ordinary terminal state
+ * (the visible pane is idle); epoch replacement is derived here so every
+ * caller applies the same rule.
+ *
+ * The single implementation for EVERY 202: the composer's own POST and an ACK
+ * originating outside it (`useSteerRecovery`'s retry, for a steer that already
+ * failed once) both resolve through this, instead of approximating each other.
+ *
+ * @returns true when the caller must route the steer into the queue.
+ */
+export function resolveAcknowledgedSteer(
+ { snapshot, set }: Pick<CallbackInterface, 'snapshot' | 'set'>,
+ conversationId: string,
+ localId: string,
+ steer: PendingSteer,
+ ordinaryRunOver: boolean,
+): boolean {
+ const applied = snapshot.getLoadable(store.appliedSteerIdsByConvoId(conversationId)).getValue();
+ const alreadyApplied = applied.includes(steer.steerId) || applied.includes(localId);
+ const alreadyAccepted = snapshot
+ .getLoadable(store.acceptedSteerClientIdsByConvoId(conversationId))
+ .getValue()
+ .includes(localId);
+ const activeEpoch = snapshot
+ .getLoadable(store.activeGenerationCreatedAtByConvoId(conversationId))
+ .getValue();
+ /** A replacement can already be submitting when an older generation's
+ * delayed 202 arrives. Ordinary submission state alone would re-mint the old
+ * chip after replacement reconciliation, with no old apply event left to
+ * settle it. Every POST reaching here captured a non-null source epoch before
+ * dispatch, so either a mismatch or a later clear proves that source
+ * generation is no longer active. */
+ const runReplaced =
+ steer.generationCreatedAt != null &&
+ (activeEpoch == null || steer.generationCreatedAt !== activeEpoch);
+ const runOver = ordinaryRunOver || runReplaced;
+ set(store.acceptedSteerClientIdsByConvoId(conversationId), (prev) =>
+ appendAppliedSteerIds(prev, [localId]),
+ );
+ set(store.pendingSteersByConvoId(conversationId), (prev) => {
+ const local = prev.find((item) => item.steerId === localId);
+ let acknowledged = steer;
+ if ((local?.preemptRevision ?? 0) > (steer.preemptRevision ?? 0)) {
+ const { preempt: _stalePreempt, ...withoutStaleLabel } = steer;
+ acknowledged = {
+ ...withoutStaleLabel,
+ ...(local?.preempt === true && { preempt: true }),
+ preemptRevision: local?.preemptRevision,
+ };
+ }
+ const next = prev.filter((item) => item.steerId !== localId);
+ // Upsert: an SSE reconnect may have reseeded the chip under the server id
+ // already; appending again would duplicate it.
+ const alreadySeeded = next.some((item) => item.steerId === steer.steerId);
+ return alreadyApplied || alreadyAccepted || runOver || alreadySeeded
+ ? next
+ : [...next, acknowledged];
+ });
+ /** `alreadyAccepted` can come from the correlation update that precedes the
+ * delayed HTTP response; it proves server ownership, not delivery. Once the
+ * source epoch is over/replaced we still must recover it. */
+ if (alreadyApplied || !runOver) {
+ return false;
+ }
+ // The server accepted but this run is already terminal. Its terminal close
+ // may have parked the item, so the caller must route it through the recovery
+ // converter (deterministic next-turn id), not an ordinary editable queue row.
+ return true;
+}
+
+/** The message the pause predicates judge: the caller's resolved active-branch
+ * tail when it passed one, else the latest assistant in the supplied cache.
+ * Passing the tail is what stops a cached sibling branch from deciding for
+ * the branch on screen. */
+function resolvePauseSubject(
+ messagesOrMessage: TMessage[] | TMessage | null | undefined,
+ activeTail?: TMessage | null,
+): TMessage | null | undefined {
+ if (activeTail !== undefined) {
+ return activeTail;
+ }
+ if (!Array.isArray(messagesOrMessage)) {
+ return messagesOrMessage;
+ }
+ for (let index = messagesOrMessage.length - 1; index >= 0; index--) {
+ if (messagesOrMessage[index].isCreatedByUser === false) {
+ return messagesOrMessage[index];
+ }
+ }
+ return null;
+}
+
+/** True when the latest assistant message carries an unresolved tool approval:
+ * the run is (or is about to be) paused, so a steer POST would 409.
+ *
+ * Pass the active branch tail whenever it has been resolved; without it this
+ * falls back to array order over the cache. */
+export function hasLiveToolApproval(
+ messagesOrMessage: TMessage[] | TMessage | null | undefined,
+ activeTail?: TMessage | null,
+): boolean {
+ const message = resolvePauseSubject(messagesOrMessage, activeTail);
if (message?.isCreatedByUser !== false) {
return false;
}
@@ -335,6 +447,9 @@ function reconcileServerQueuedTurns(
receipt.manualSkills.length > 0 && {
manualSkills: receipt.manualSkills,
}),
+ ...(receipt.reasoningOverride != null && {
+ reasoningOverride: receipt.reasoningOverride,
+ }),
...(receipt.priority === true && { priority: true }),
server: {
id: receipt.queuedTurnId,
@@ -377,6 +492,34 @@ function reconcileServerQueuedTurns(
});
return [...retained, ...projected].sort(compareQueuedMessages);
}
+/**
+ * The ONE during-run pause predicate. Both an unresolved tool approval and a
+ * live `ask_user_question` suspend the generation while keeping its submission
+ * slot occupied, so a steer POST would 409 in either case.
+ *
+ * Shared by the composer and the in-thread pending steers so a control is
+ * never enabled on one surface while the other correctly refuses. Callers
+ * should pass the active branch tail when they have resolved it; this prevents
+ * a cached sibling from changing the result.
+ */
+export function hasLiveRunPause(
+ messagesOrMessage: TMessage[] | TMessage | null | undefined,
+ activeTail?: TMessage | null,
+): boolean {
+ /* Legacy callers hand over the whole cache without a resolved tail; keep
+ scanning it for them, but once a caller resolves the active branch only
+ that branch decides. */
+ const questionSource =
+ activeTail === undefined && Array.isArray(messagesOrMessage)
+ ? messagesOrMessage
+ : [resolvePauseSubject(messagesOrMessage, activeTail)].filter(
+ (message): message is TMessage => message != null,
+ );
+ return (
+ hasLiveToolApproval(messagesOrMessage, activeTail) ||
+ findLiveAskUserQuestion(questionSource) != null
+ );
+}
export interface UseSteeringParams {
/** Consume the actual storage key selected by the composer’s autosave owner. */
@@ -387,13 +530,13 @@ export interface UseSteeringParams {
addedConversation?: TConversation | null;
isSubmitting: boolean;
answerModeActive: boolean;
- /** Composer attachments — consumed into queued items (steering is text-only). */
+ /** Composer attachments: consumed into queued items (steering is text-only). */
files?: Map<string, ExtendedFile>;
setFiles?: FileSetter;
/** Uploads still in flight: during-run submits are held like the send button. */
filesLoading?: boolean;
/** Submits text (and optional attachments/quotes/skills) as a normal new
- * turn. Overrides are always explicit — a queued item is the FULL
+ * turn. Overrides are always explicit; a queued item is the FULL
* submission context, so absent fields must send as empty, never vacuum
* the composer. Returns `false` when `ask` refused without sending
* (in-flight guard, history not cached yet) so callers can restore
@@ -410,8 +553,8 @@ export interface UseSteeringParams {
/**
* The composer's during-run brain: decides what Enter does while a run is
* generating (steer vs queue, per the user preference and run state), owns the
- * pending-steer / queued-message chip state, and implements the three actions
- * — steer (POST + optimistic chip), queue (client-side), and interrupt & send
+ * pending-steer / queued-message chip state, and implements the three actions:
+ * steer (POST + optimistic chip), queue (client-side), and interrupt & send
* (abort, then auto-send via the one-shot drain override).
*/
export default function useSteering({
@@ -429,11 +572,15 @@ export default function useSteering({
stopGenerating,
}: UseSteeringParams) {
const localize = useLocalize();
+ const reasoningStore = useStore();
const { showToast } = useToastContext();
const jotaiStore = useStore();
const fileMap = useFileMapContext();
const setFilesToDelete = useSetFilesToDelete();
const convertSteersToQueued = useSteerConvert();
+ /* The single boundary a steer's words return through, wherever the cancel
+ that reclaimed them was decided. */
+ const rehomeSteer = useSteerRehome(conversationId);
/** `mutate` is a stable callback; the mutation result objects are fresh
* every render and would defeat the memoized return value below. */
const { mutate: steerMessage } = useSteerMessageMutation();
@@ -454,8 +601,20 @@ export default function useSteering({
/** v1 gates the during-run UI to the primary composer, like the HITL popover. */
const enabled = steerable && index === 0;
const queueKey = hasRealConvoId ? conversationId : Constants.NEW_CONVO;
+ const reasoningStateKey = getReasoningStateKey(conversationId, index);
const queuedMessages = useRecoilValue(store.queuedMessagesByConvoId(queueKey));
+ const pendingReasoningOverride = useAtomValue(pendingReasoningOverrideFamily(reasoningStateKey));
const setQueuedMessages = useSetRecoilState(store.queuedMessagesByConvoId(queueKey));
+ const { data: startupConfig } = useGetStartupConfig();
+ /** Bound transport-outcome reconciliation while still guaranteeing several
+ * list reads after the enqueue promise settles. Focus/remount remains a later
+ * reconciliation path; a slow proxy or a delayed read replica needs the
+ * operator to widen this rather than wait for one. */
+ const reconciliationWindowMs =
+ startupConfig?.interface?.queuedTurnReconciliationTimeoutMs ??
+ DEFAULT_QUEUED_TURN_RECONCILIATION_TIMEOUT_MS;
+ const sendLockTimeoutMs =
+ startupConfig?.interface?.queuedSendLockTimeoutMs ?? DEFAULT_QUEUED_SEND_LOCK_TIMEOUT_MS;
const knownClientRequestIds = useMemo(
() =>
Array.from(
@@ -471,7 +630,7 @@ export default function useSteering({
if (item.server?.status !== 'uncertain' || item.server.uncertainSince == null) {
return latest;
}
- const until = item.server.uncertainSince + QUEUED_TURN_RECONCILIATION_MS;
+ const until = item.server.uncertainSince + reconciliationWindowMs;
return latest == null ? until : Math.max(latest, until);
}, undefined);
const nextReconciliationExpiry = queuedMessages.reduce<number | undefined>((earliest, item) => {
@@ -482,7 +641,7 @@ export default function useSteering({
) {
return earliest;
}
- const expiry = item.server.uncertainSince + QUEUED_TURN_RECONCILIATION_MS;
+ const expiry = item.server.uncertainSince + reconciliationWindowMs;
return earliest == null ? expiry : Math.min(earliest, expiry);
}, undefined);
/** An expired uncertain row is held for manual recovery only; nothing the
@@ -617,7 +776,7 @@ export default function useSteering({
item.server?.status !== 'uncertain' ||
item.server.uncertainSince == null ||
item.server.reconciliationExpired === true ||
- item.server.uncertainSince + QUEUED_TURN_RECONCILIATION_MS > observedAt
+ item.server.uncertainSince + reconciliationWindowMs > observedAt
) {
return item;
}
@@ -631,7 +790,7 @@ export default function useSteering({
const delay = Math.max(0, nextReconciliationExpiry - Date.now());
const timer = window.setTimeout(expire, delay);
return () => window.clearTimeout(timer);
- }, [nextReconciliationExpiry, serverQueueEnabled, setQueuedMessages]);
+ }, [nextReconciliationExpiry, reconciliationWindowMs, serverQueueEnabled, setQueuedMessages]);
/** The start POST installs this epoch before any live mutation may be sent.
* `isSubmitting` flips earlier so the user can keep typing; during that
* bounded interval submits degrade to the local queue and Stop/steer refuse. */
@@ -703,15 +862,27 @@ export default function useSteering({
);
/** `ask()` does not flip `isSubmitting` until the submission effect renders.
* Two queued-row clicks in the same browser task would otherwise both remove
- * their items and the second submission could overwrite the first. */
- const idleSendInFlightRef = useRef(false);
+ * their items and the second submission could overwrite the first; and the
+ * run-end drain, which submits into the SAME pane slot, cannot see a ref that
+ * lives in this hook. The claim is shared with `useQueueDrain` and keyed by
+ * pane, because the contended resource is `isSubmittingFamily(index)`. */
+ const sendLockKey = String(index);
+ const idleSendLockRef = useRef<QueueSendLock | null>(null);
const pendingSteers = useRecoilValue(store.pendingSteersByConvoId(queueKey));
- useEffect(() => {
- if (!isSubmitting) {
- idleSendInFlightRef.current = false;
- }
- }, [isSubmitting]);
+ /** Held only until the pane's submission state moves or it changes chat: past
+ * either, both callers gate on `isSubmitting` directly and the claim is spent.
+ *
+ * Released from a cleanup rather than an effect body, because React runs every
+ * cleanup in a commit before any effect body: this can never free a slot the
+ * drain's effect claimed in the same commit. */
+ useEffect(
+ () => () => {
+ releaseQueueSendLock(idleSendLockRef.current);
+ idleSendLockRef.current = null;
+ },
+ [isSubmitting, sendLockKey, queueKey],
+ );
/** Keep logical queue origins through the 202 ACK. They are needed to
* reconstruct FIFO if several accepted queue items later return as terminal
@@ -748,20 +919,16 @@ export default function useSteering({
* to know a live generation exists so they remain discoverable and disabled
* instead of looking as though the action disappeared. */
const pausedOnApproval =
- enabled && isSubmitting ? answerModeActive || (liveMessageState?.approval ?? false) : false;
-
- /** Whether a steer can reach the live run right now — independent of the
- * user's default action, so the per-send menu can always override to
- * steer when it's genuinely available. */
+ enabled && isSubmitting ? answerModeActive || hasLiveRunPause(latestMessage) : false;
const canSteer = hasRealConvoId && canControlGeneration && !pausedOnApproval;
- /** Whether a queued row has a real immediate-send path. Answer mode keeps
- * `isSubmitting` true while hiding during-run steering, so presenting Send
- * now there would be an enabled no-op. */
const canSendQueuedNow = (!isSubmitting && !revealPending) || (duringRunActive && canSteer);
- /** Steering needs a live server-side job; degrade to queue otherwise. */
- const effectiveAction: DuringRunAction = canSteer ? defaultAction : 'queue';
- /** Live submission state for POST callbacks — the closure value can be
+ /** A live steer cannot change the provider request already in flight.
+ * Stage a full queued turn instead, and expose that same effective action to
+ * Enter, the button and the hint. */
+ const effectiveAction: DuringRunAction =
+ canSteer && pendingReasoningOverride == null ? defaultAction : 'queue';
+ /** Live submission state for POST callbacks: the closure value can be
* stale by the time the steer response arrives. */
const isSubmittingRef = useRef(isSubmitting);
isSubmittingRef.current = isSubmitting;
@@ -769,17 +936,14 @@ export default function useSteering({
visibleConversationRef.current = conversationId;
/**
- * How each conversation's last run ended, kept because `useQueueDrain`
- * CONSUMES the one-shot signal — by the time a reclaim resolves it is already
- * gone. Every subscriber renders before the drain's effect nulls it, so the
- * outcome is captured first. Both carriers are watched: the index signal, and
- * the copy parked under the conversation when the run ended while the user
- * was looking elsewhere.
+ * The most recent run end seen for a conversation: either the live one for
+ * this pane's index, or the copy parked under the conversation when the run
+ * ended while the user was looking elsewhere.
*
* Keyed by conversation because this hook is REUSED across chats: a single
* slot would answer for whichever chat is on screen when the reclaim lands,
* not the one the words belong to. An entry is dropped once that conversation
- * starts another run — an older end no longer describes what is happening.
+ * starts another run; an older end no longer describes what is happening.
*/
const runEnd = useRecoilValue(store.runEndByIndex(index));
const parkedRunEnd = useRecoilValue(store.pendingRunEndByConvoId(queueKey));
@@ -821,73 +985,25 @@ export default function useSteering({
);
/**
- * Resolves the 202 ACK against the applied-id set: `on_steer_applied` rides
- * the SSE and can land BEFORE the HTTP response, in which case its removal
- * already passed — minting a `pending` chip here would strand it forever.
- * An ACK landing AFTER the run ended (final/abort/error already processed,
- * server queue drained or dropped) converts straight to a queued follow-up:
- * no later event will ever resolve a `pending` chip for a finished run.
+ * The composer's 202 ACK, resolved by the SHARED implementation so it cannot
+ * drift from the one `useSteerRecovery` uses for a retry's ACK.
+ *
+ * All this call site contributes is its observation of ordinary terminal
+ * state: this hook instance survives navigation, so the visible pane's idle
+ * flag says nothing about an off-screen origin run, and terminal state may
+ * only be inferred while the callback still belongs to the visible chat.
+ * Epoch replacement is derived inside the resolver for every caller.
*/
const acknowledgeSteer = useRecoilCallback(
- ({ snapshot, set }) =>
- (convoId: string, localId: string, steer: PendingSteer): boolean => {
- const applied = snapshot.getLoadable(store.appliedSteerIdsByConvoId(convoId)).getValue();
- const alreadyApplied = applied.includes(steer.steerId) || applied.includes(localId);
- const alreadyAccepted = snapshot
- .getLoadable(store.acceptedSteerClientIdsByConvoId(convoId))
- .getValue()
- .includes(localId);
- const activeEpoch = snapshot
- .getLoadable(store.activeGenerationCreatedAtByConvoId(convoId))
- .getValue();
- /** A replacement can already be submitting when an older generation's
- * delayed 202 arrives. `isSubmitting` alone would re-mint the old chip
- * after replacement reconciliation, with no old apply event left to
- * settle it. Every POST reaching this callback captured a non-null
- * source epoch before dispatch, so either a mismatch or a later clear
- * proves that source generation is no longer active. */
- const runReplaced =
- steer.generationCreatedAt != null &&
- (activeEpoch == null || steer.generationCreatedAt !== activeEpoch);
- // This hook instance survives navigation. The visible pane's idle flag
- // says nothing about an off-screen origin run, so only infer ordinary
- // terminal state while the callback still belongs to the visible chat.
- const runOver =
- runReplaced || (visibleConversationRef.current === convoId && !isSubmittingRef.current);
- set(store.acceptedSteerClientIdsByConvoId(convoId), (prev) =>
- appendAppliedSteerIds(prev, [localId]),
- );
- set(store.pendingSteersByConvoId(convoId), (prev) => {
- const local = prev.find((item) => item.steerId === localId);
- let acknowledged = steer;
- if ((local?.preemptRevision ?? 0) > (steer.preemptRevision ?? 0)) {
- const { preempt: _stalePreempt, ...withoutStaleLabel } = steer;
- acknowledged = {
- ...withoutStaleLabel,
- ...(local?.preempt === true && { preempt: true }),
- preemptRevision: local?.preemptRevision,
- };
- }
- const next = prev.filter((item) => item.steerId !== localId);
- // Upsert: an SSE reconnect may have reseeded the chip under the
- // server id already — appending again would duplicate it.
- const alreadySeeded = next.some((item) => item.steerId === steer.steerId);
- return alreadyApplied || alreadyAccepted || runOver || alreadySeeded
- ? next
- : [...next, acknowledged];
- });
- /** `alreadyAccepted` can come from the correlation update that precedes
- * the delayed HTTP response; it proves server ownership, not delivery.
- * Once the source epoch is over/replaced we still must recover it. */
- if (alreadyApplied || !runOver) {
- return false;
- }
- // The server accepted but this visible run is already terminal. Its
- // terminal close may have parked the item, so the caller must route it
- // through the recovery converter (deterministic next-turn id), not an
- // ordinary editable queue row.
- return true;
- },
+ (cbInterface) =>
+ (convoId: string, localId: string, steer: PendingSteer): boolean =>
+ resolveAcknowledgedSteer(
+ cbInterface,
+ convoId,
+ localId,
+ steer,
+ visibleConversationRef.current === convoId && !isSubmittingRef.current,
+ ),
[],
);
@@ -930,6 +1046,19 @@ export default function useSteering({
},
[],
);
+ const hasPendingSteerCancel = useCallback(
+ (convoId: string, clientSteerId: string) =>
+ jotaiStore.get(pendingSteerCancelClientIdsFamily(convoId)).includes(clientSteerId),
+ [jotaiStore],
+ );
+ const clearPendingSteerCancel = useCallback(
+ (convoId: string, clientSteerId: string) => {
+ jotaiStore.set(pendingSteerCancelClientIdsFamily(convoId), (prev) =>
+ prev.filter((id) => id !== clientSteerId),
+ );
+ },
+ [jotaiStore],
+ );
/** Fire-and-forget TTL hold for uploads entering the client queue: a
* queued message can outlive the upload window (long run, approval pause)
@@ -982,6 +1111,7 @@ export default function useSteering({
files?: TMessage['files'];
quotes?: string[];
manualSkills?: string[];
+ reasoningOverride?: TMessage['reasoningOverride'];
/** Set when the files were ALREADY queued/steered: their TTL was
* held when they first entered the queue (or at the steer 202). */
skipUsageMark?: boolean;
@@ -989,6 +1119,10 @@ export default function useSteering({
createdAt?: number;
clientRequestId?: string;
expectedPredecessorCreatedAt?: number;
+ /** The queue lineage of a row being put back after its parked copy was
+ * cancelled. The run it waited on may have ended meanwhile, which
+ * clears the live pair, and the row must stay durable regardless. */
+ lineage?: { parentMessageId: string; predecessorCreatedAt: number };
},
) => {
const trimmed = text.trim();
@@ -996,13 +1130,15 @@ export default function useSteering({
return;
}
const parentMessageId =
- pendingReveal != null
+ options?.lineage?.parentMessageId ??
+ (pendingReveal != null
? pendingReveal.queueParentMessageId
- : liveMessageState?.parentMessageId;
+ : liveMessageState?.parentMessageId);
const predecessorCreatedAt =
- pendingReveal != null
+ options?.lineage?.predecessorCreatedAt ??
+ (pendingReveal != null
? pendingReveal.queuePredecessorCreatedAt
- : activeGenerationCreatedAt;
+ : activeGenerationCreatedAt);
/** FINAL clears the active epoch before attachment. The revealed
* intent retains the queue's original parent/epoch pair. Its display
* parent and advancing completion boundary are not queue lineage.
@@ -1030,11 +1166,12 @@ export default function useSteering({
options.manualSkills.length > 0 && {
manualSkills: options.manualSkills,
}),
+ ...(options?.reasoningOverride != null && {
+ reasoningOverride: options.reasoningOverride,
+ }),
...(options?.front && { priority: true }),
};
- set(store.queuedMessagesByConvoId(queueKey), (prev) =>
- [...prev, item].sort(compareQueuedMessages),
- );
+ set(store.queuedMessagesByConvoId(queueKey), (prev) => insertQueuedMessage(prev, item));
if (options?.skipUsageMark !== true) {
markQueuedFilesUsage(options?.files);
}
@@ -1061,7 +1198,9 @@ export default function useSteering({
item.manualSkills.length > 0 && {
manualSkills: item.manualSkills,
}),
- ...(codeApprovalMode != null && { codeApprovalMode }),
+ ...(item.reasoningOverride != null && {
+ reasoningOverride: item.reasoningOverride,
+ }),
...(item.priority === true && { priority: true }),
...(item.expectedPredecessorCreatedAt != null && {
expectedPredecessorCreatedAt: item.expectedPredecessorCreatedAt,
@@ -1133,12 +1272,21 @@ export default function useSteering({
/** Consumes completed composer attachments into message file refs (clearing
* the composer) so they pair with THIS queued message instead of gluing
- * onto whatever `ask` vacuums up next. */
+ * onto whatever `ask` vacuums up next.
+ *
+ * Cleared by id through a FUNCTIONAL update, never by assigning an empty
+ * map: uploads dispatch their own functional updates, so a flat overwrite
+ * drops an attachment the user started after this read, and the upload's
+ * next callback puts it back on top of the emptied map. Removing exactly
+ * the ids taken leaves any newer upload alone, and marking them consumed
+ * stops a late callback for one of THESE files resurrecting it. */
const takeComposerFiles = useCallback((): TMessage['files'] => {
if (files == null || files.size === 0 || setFiles == null) {
return undefined;
}
- const taken = Array.from(files.values()).map((file) => ({
+ const staged = Array.from(files.values());
+ const takenIds = staged.map((file) => file.file_id);
+ const taken = staged.map((file) => ({
file_id: file.file_id,
filepath: file.filepath,
type: file.type ?? '',
@@ -1150,7 +1298,14 @@ export default function useSteering({
bytes: file.size,
llmDeliveryPath: file.llmDeliveryPath,
}));
- setFiles(new Map());
+ markComposerFilesTaken(takenIds);
+ setFiles((previous) => {
+ const remaining = new Map(previous);
+ for (const id of takenIds) {
+ remaining.delete(id);
+ }
+ return remaining;
+ });
setFilesToDelete({});
return taken;
}, [files, setFiles, setFilesToDelete]);
@@ -1167,18 +1322,25 @@ export default function useSteering({
const manualSkills = snapshot
.getLoadable(store.pendingManualSkillsByConvoId(conversationId))
.getValue();
+ const reasoningOverride = reasoningStore.get(
+ pendingReasoningOverrideFamily(reasoningStateKey),
+ );
if (quotes.length > 0) {
reset(store.pendingQuotesByConvoId(conversationId));
}
if (manualSkills.length > 0) {
reset(store.pendingManualSkillsByConvoId(conversationId));
}
+ if (reasoningOverride != null) {
+ reasoningStore.set(pendingReasoningOverrideFamily(reasoningStateKey), undefined);
+ }
return {
...(quotes.length > 0 && { quotes }),
...(manualSkills.length > 0 && { manualSkills }),
+ ...(reasoningOverride != null && { reasoningOverride }),
};
},
- [conversationId],
+ [conversationId, reasoningStateKey, reasoningStore],
);
/** Quotes-only drain for composer-origin steers: the excerpts ride the steer
@@ -1247,6 +1409,13 @@ export default function useSteering({
[],
);
+ /* The draft consumer is the host's (`useAutoSave`'s `consumeDraft`, threaded
+ in as `takeComposerDraft`): the composer clears via the form's `reset()`,
+ which is programmatic and never fires the `input` event `useAutoSave`
+ listens on, so the draft would otherwise outlive the submit and run end
+ would restore text the user already sent. Only autosave knows whether this
+ composer is parked on the pane's pending key or on the conversation key, so
+ the clear belongs there rather than being recomputed here. */
const removeQueued = useRecoilCallback(
({ set }) =>
(id: string) => {
@@ -1257,6 +1426,13 @@ export default function useSteering({
[queueKey],
);
+ /** Keeps a row in the queue but out of the run-end drain, for words that
+ * already reached the composer while their parked copy could not be let go. */
+ const holdQueued = useCallback(
+ (id: string) => updateQueuedMessage(id, (item) => ({ ...item, needsExplicitSend: true })),
+ [updateQueuedMessage],
+ );
+
const downgradeServerQueuedTurn = useRecoilCallback(
({ snapshot, set }) =>
(id: string): boolean => {
@@ -1278,6 +1454,90 @@ export default function useSteering({
[queueKey],
);
+ /**
+ * Moves a queued message to another place in the queue. The drain always
+ * takes the head, so the order of this list is the order the messages will be
+ * sent in: reordering it is the only way to change which one goes next
+ * without sending or deleting anything.
+ *
+ * Addressed by id rather than by the index the caller is holding, which a
+ * drain can invalidate between the drag starting and the drop landing.
+ */
+ const reorderQueued = useRecoilCallback(
+ ({ set }) =>
+ (id: string, targetIndex: number) => {
+ set(store.queuedMessagesByConvoId(queueKey), (prev) => {
+ const from = prev.findIndex((item) => item.id === id);
+ const to = Math.min(Math.max(targetIndex, 0), prev.length - 1);
+ if (from === -1 || from === to) {
+ return prev;
+ }
+ const next = prev.slice();
+ const [moved] = next.splice(from, 1);
+ next.splice(to, 0, moved);
+ return next;
+ });
+ },
+ [queueKey],
+ );
+
+ /**
+ * Puts the queue back in a remembered order, for a drag the user abandoned.
+ * Ids that have since drained are skipped rather than resurrected, and
+ * anything queued mid-drag keeps its place at the back.
+ */
+ const restoreQueuedOrder = useRecoilCallback(
+ ({ set }) =>
+ (ids: readonly string[]) => {
+ set(store.queuedMessagesByConvoId(queueKey), (prev) => {
+ const byId = new Map(prev.map((item) => [item.id, item]));
+ const restored: QueuedMessage[] = [];
+ for (const id of ids) {
+ const item = byId.get(id);
+ if (item != null) {
+ restored.push(item);
+ byId.delete(id);
+ }
+ }
+ if (restored.length === 0) {
+ return prev;
+ }
+ return [...restored, ...byId.values()];
+ });
+ },
+ [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
@@ -1495,7 +1755,7 @@ export default function useSteering({
*
* A signal for a DIFFERENT conversation is not that proof. The index slot is
* shared, and the drain parks a foreign signal under its own conversation and
- * then only inspects the active one's queue — this item would never be looked
+ * then only inspects the active one's queue; this item would never be looked
* at. Park ours alongside it.
*/
const rearmDrain = useRecoilCallback(
@@ -1511,6 +1771,23 @@ export default function useSteering({
[index],
);
+ /**
+ * Re-post the last completion this conversation saw, for the callers that put
+ * words back into the queue after a round-trip. The drain's signal is
+ * one-shot and may well have been spent while that round-trip was in flight,
+ * on a queue where every row was either absent or spoken for. Only a clean
+ * completion counts: an aborted or errored run never drains.
+ */
+ const rewakeDrain = useCallback(
+ (convoId: string) => {
+ const lastRunEnd = runEndsRef.current.get(convoId);
+ if (lastRunEnd?.outcome === 'completed') {
+ rearmDrain(convoId, lastRunEnd);
+ }
+ },
+ [rearmDrain],
+ );
+
/** Restore a server-owned steer as the same queued follow-up and wake a
* drain whose one-shot completion signal may already have been consumed
* while the recovery request was in flight. Shared by reclaim and durable
@@ -1538,12 +1815,9 @@ export default function useSteering({
generationProtocolVersion: steer.generationProtocolVersion,
},
);
- const lastRunEnd = runEndsRef.current.get(conversationId);
- if (lastRunEnd?.outcome === 'completed') {
- rearmDrain(conversationId, lastRunEnd);
- }
+ rewakeDrain(conversationId);
},
- [conversationId, convertSteersToQueued, rearmDrain],
+ [conversationId, convertSteersToQueued, rewakeDrain],
);
const armDrainAfterAbort = useRecoilCallback(
@@ -1592,7 +1866,7 @@ export default function useSteering({
const localId = opts?.clientSteerId ?? `local-${v4()}`;
/** The true submission time, carried through the ACK and failure chips so
* a later conversion sorts this steer by when it was SENT, not when its
- * 202 landed — otherwise a draft queued during the round-trip would drain
+ * 202 landed; otherwise a draft queued during the round-trip would drain
* ahead of a steer submitted before it. */
const createdAt = opts?.createdAt ?? Date.now();
/** If the steer loses its race with run finalization, its normal-send
@@ -1634,10 +1908,7 @@ export default function useSteering({
} else {
enqueue(trimmed, { id: localId, createdAt, files, ...context });
}
- const lastRunEnd = runEndsRef.current.get(conversationId);
- if (lastRunEnd?.outcome === 'completed') {
- rearmDrain(conversationId, lastRunEnd);
- }
+ rewakeDrain(conversationId);
};
if (opts?.queuedOrigin != null) {
registerQueuedOrigin(opts.queuedOrigin);
@@ -1672,80 +1943,139 @@ export default function useSteering({
{
onSuccess: (response) => {
try {
- /** A 202 without the echo means a pre-quotes replica queued
- * the words without their excerpts. The quotes are NOT
- * re-staged here — the steer has not injected yet, so they
- * stay carried on the pending chip: a quote-less applied
- * event re-stages them at the actual loss, and a terminal
- * leftover conversion carries them onto the recovered row
- * instead (its normal send delivers quotes on any server).
- * Only a settled replay — an already-injected steer with no
- * future event to re-home the chip — reclaims immediately. */
- const quotesRejected = carried.quotes != null && response.quotesAccepted !== true;
- const canUseV2Receipt =
- targetGenerationProtocolVersion === 2 && supportsGenerationProtocolV2(response);
- if (canUseV2Receipt && response.settled === true) {
- if (response.leftover === true) {
- queueRecoveredSteer({
- steerId: response.steerId,
- clientSteerId: localId,
- text: trimmed,
- status: 'pending',
- createdAt,
- ...(files && { files }),
- ...(targetGenerationCreatedAt != null && {
- generationCreatedAt: targetGenerationCreatedAt,
- }),
- generationProtocolVersion: targetGenerationProtocolVersion,
- ...(opts?.queuedOrigin && {
- queuedOrigin: opts.queuedOrigin,
- }),
- ...carried,
- });
- } else {
- if (quotesRejected) {
- reclaimRejectedChipQuotes(conversationId, [localId, response.steerId]);
+ const acceptResponse = () => {
+ /** A 202 without the echo means a pre-quotes replica queued
+ * the words without their excerpts. The quotes are NOT
+ * re-staged here: the steer has not injected yet, so they
+ * stay carried on the pending chip: a quote-less applied
+ * event re-stages them at the actual loss, and a terminal
+ * leftover conversion carries them onto the recovered row
+ * instead (its normal send delivers quotes on any server).
+ * Only a settled replay (an already-injected steer with no
+ * future event to re-home the chip) reclaims immediately. */
+ const quotesRejected = carried.quotes != null && response.quotesAccepted !== true;
+ const canUseV2Receipt =
+ targetGenerationProtocolVersion === 2 && supportsGenerationProtocolV2(response);
+ if (canUseV2Receipt && response.settled === true) {
+ if (response.leftover === true) {
+ queueRecoveredSteer({
+ steerId: response.steerId,
+ clientSteerId: localId,
+ text: trimmed,
+ status: 'pending',
+ createdAt,
+ ...(files && { files }),
+ ...(targetGenerationCreatedAt != null && {
+ generationCreatedAt: targetGenerationCreatedAt,
+ }),
+ generationProtocolVersion: targetGenerationProtocolVersion,
+ ...(opts?.queuedOrigin && {
+ queuedOrigin: opts.queuedOrigin,
+ }),
+ ...carried,
+ });
+ } else {
+ if (quotesRejected) {
+ reclaimRejectedChipQuotes(conversationId, [localId, response.steerId]);
+ }
+ settleReceiptReplay(conversationId, localId, response.steerId);
}
- settleReceiptReplay(conversationId, localId, response.steerId);
+ return;
}
+ /** The server's echo is authoritative: a deployment whose SDK
+ * cannot seal mid-stream still queues the steer and answers
+ * `preempt: false`, which relabels the chip to the ordinary
+ * wording instead of surfacing an error. */
+ const acknowledged = {
+ steerId: response.steerId,
+ clientSteerId: localId,
+ text: trimmed,
+ status: 'pending',
+ createdAt,
+ ...(files && { files }),
+ ...(response.preempt === true && { preempt: true }),
+ ...(response.preemptRevision != null && {
+ preemptRevision: response.preemptRevision,
+ }),
+ ...(targetGenerationCreatedAt != null && {
+ generationCreatedAt: targetGenerationCreatedAt,
+ }),
+ generationProtocolVersion: targetGenerationProtocolVersion,
+ ...(opts?.queuedOrigin && {
+ queuedOrigin: opts.queuedOrigin,
+ }),
+ ...carried,
+ } satisfies PendingSteer;
+ if (acknowledgeSteer(conversationId, localId, acknowledged)) {
+ /** Terminal conversion re-homes the words as a queued
+ * follow-up that sends via `ask`; the carried quotes ride
+ * it there, so nothing is re-staged. */
+ queueRecoveredSteer(acknowledged);
+ }
+ };
+ if (hasPendingSteerCancel(conversationId, localId)) {
+ void cancelSteer({
+ conversationId,
+ steerId: response.steerId,
+ clientSteerId: localId,
+ generationCreatedAt:
+ targetGenerationCreatedAt ?? activeGenerationCreatedAt ?? undefined,
+ }).then(
+ ({ removed }) => {
+ clearPendingSteerCancel(conversationId, localId);
+ if (removed === true) {
+ /* Cancel won the race against its own POST. The words are
+ off the server now, so they go back to the user through
+ the same boundary as an immediate cancel: whole, and
+ into the queue when the composer will not take them.
+ Clearing the marker without this loses the message. */
+ rehomeSteer({
+ steerId: response.steerId,
+ clientSteerId: localId,
+ text: trimmed,
+ status: 'pending',
+ createdAt,
+ ...(files && { files }),
+ ...(targetGenerationCreatedAt != null && {
+ generationCreatedAt: targetGenerationCreatedAt,
+ }),
+ generationProtocolVersion: targetGenerationProtocolVersion,
+ ...(opts?.queuedOrigin && { queuedOrigin: opts.queuedOrigin }),
+ ...carried,
+ });
+ return;
+ }
+ /* The server kept the steer: it is live and will still
+ reach the agent. The chip the optimistic cancel hid
+ comes back through the ordinary acknowledgement, so it
+ settles like any other accepted steer. */
+ acceptResponse();
+ showToast({
+ message: localize('com_ui_steer_already_applied'),
+ status: 'info',
+ });
+ },
+ () => {
+ clearPendingSteerCancel(conversationId, localId);
+ /* Unknown outcome, but the POST was accepted: treat the
+ steer as live rather than claiming it is gone. */
+ acceptResponse();
+ showToast({
+ message: localize('com_ui_steer_cancel_failed'),
+ status: 'warning',
+ });
+ },
+ );
return;
}
- /** The server's echo is authoritative: a deployment whose SDK
- * cannot seal mid-stream still queues the steer and answers
- * `preempt: false`, which relabels the chip to the ordinary
- * wording instead of surfacing an error. */
- const acknowledged = {
- steerId: response.steerId,
- clientSteerId: localId,
- text: trimmed,
- status: 'pending',
- createdAt,
- ...(files && { files }),
- ...(response.preempt === true && { preempt: true }),
- ...(response.preemptRevision != null && {
- preemptRevision: response.preemptRevision,
- }),
- ...(targetGenerationCreatedAt != null && {
- generationCreatedAt: targetGenerationCreatedAt,
- }),
- generationProtocolVersion: targetGenerationProtocolVersion,
- ...(opts?.queuedOrigin && {
- queuedOrigin: opts.queuedOrigin,
- }),
- ...carried,
- } satisfies PendingSteer;
- if (acknowledgeSteer(conversationId, localId, acknowledged)) {
- /** Terminal conversion re-homes the words as a queued
- * follow-up that sends via `ask` — the carried quotes ride
- * it there, so nothing is re-staged. */
- queueRecoveredSteer(acknowledged);
- }
+ acceptResponse();
} finally {
settleDispatch();
}
},
onError: (error) => {
try {
+ clearPendingSteerCancel(conversationId, localId);
if (isSteerAcceptedOrSettled(conversationId, localId)) {
replaceSteerChip(conversationId, localId, null);
return;
@@ -1755,10 +2085,10 @@ export default function useSteering({
if (code === 'NO_ACTIVE_RUN') {
// The run finished before the steer landed. While the final SSE
// is still settling, `ask()`'s in-flight guard would drop a
- // direct send — queue it so the run-end drain fires it instead.
+ // direct send: queue it so the run-end drain fires it instead.
// The explicit empty array stops `ask` from vacuuming composer
// files staged for a DIFFERENT draft. A refused send (`false`)
- // falls back to the queue too — the chip is already gone, so
+ // falls back to the queue too: the chip is already gone, so
// dropping the text here would lose it silently.
replaceSteerChip(conversationId, localId, null);
if (
@@ -1779,7 +2109,7 @@ export default function useSteering({
// The rejection can land AFTER the final SSE consumed the
// run-end signal (common on an unsupported SDK near run end):
// queueing then has nothing left to drain it, so mirror the
- // NO_ACTIVE_RUN fallback and send once submission settled —
+ // NO_ACTIVE_RUN fallback and send once submission settled:
// queueing the refusal instead of dropping the text.
if (originStillVisible && !isSubmittingRef.current) {
if (sendNow(trimmed, files ?? [], fallbackContext) === false) {
@@ -1875,14 +2205,18 @@ export default function useSteering({
acknowledgeSteer,
settleReceiptReplay,
queueRecoveredSteer,
+ rehomeSteer,
reclaimRejectedChipQuotes,
steerMessage,
sendNow,
enqueue,
restoreQueued,
- rearmDrain,
+ rewakeDrain,
registerQueuedOrigin,
isSteerAcceptedOrSettled,
+ hasPendingSteerCancel,
+ clearPendingSteerCancel,
+ cancelSteer,
showToast,
localize,
activeGenerationCreatedAt,
@@ -1902,6 +2236,16 @@ export default function useSteering({
if (trimmed.length === 0 || filesLoading || !canSteer) {
return false;
}
+ /** A live steer cannot change the provider request already in flight.
+ * Preserve a staged reasoning choice as a full queued turn. */
+ if (pendingReasoningOverride != null) {
+ enqueue(trimmed, {
+ files: takeComposerFiles(),
+ ...takeComposerContext(),
+ });
+ takeComposerDraft();
+ return true;
+ }
const consumed = submitSteer(trimmed, takeComposerFiles(), takeComposerQuotes(), {
preempt,
});
@@ -1910,7 +2254,17 @@ export default function useSteering({
}
return consumed;
},
- [filesLoading, canSteer, takeComposerFiles, takeComposerQuotes, takeComposerDraft, submitSteer],
+ [
+ filesLoading,
+ canSteer,
+ pendingReasoningOverride,
+ enqueue,
+ takeComposerFiles,
+ takeComposerContext,
+ takeComposerQuotes,
+ takeComposerDraft,
+ submitSteer,
+ ],
);
/** Composer-originated queue: carries the composer's attachments, quote
@@ -1940,7 +2294,7 @@ export default function useSteering({
context?: QueuedMessageContext,
opts?: SubmitSteerOptions,
) => {
- /** A failed interrupt-steer must retry AS an interrupt — resubmitting it
+ /** A failed interrupt-steer must retry AS an interrupt; resubmitting it
* as an ordinary steer would silently let generation run on. */
submitSteer(text, steerFiles, context, {
...opts,
@@ -1964,7 +2318,7 @@ export default function useSteering({
* Routed through the shared conversion rather than `enqueue` so it obeys the
* same invariant as the leftover-steer path: the item keeps its ORIGINAL id
* and `createdAt`, so a steer accepted before a later follow-up still drains
- * ahead of it — a fresh `Date.now()` would sort it last.
+ * ahead of it; a fresh `Date.now()` would sort it last.
*
* The reclaim is a round-trip, so the run can end while it is in flight and
* the drain can consume its one-shot run-end signal against an empty queue,
@@ -1993,12 +2347,9 @@ export default function useSteering({
skipUsageMark: true,
});
}
- const lastRunEnd = runEndsRef.current.get(conversationId);
- if (lastRunEnd?.outcome === 'completed') {
- rearmDrain(conversationId, lastRunEnd);
- }
+ rewakeDrain(conversationId);
},
- [conversationId, enqueue, rearmDrain, restoreQueued],
+ [conversationId, enqueue, rewakeDrain, restoreQueued],
);
/** Convert a failed/unsent steer chip into a queued follow-up. */
@@ -2021,7 +2372,7 @@ export default function useSteering({
);
/** Chip action: send a queued message into the live run instead. Keys on
- * steer availability, not the default action — a queue-preferring user
+ * steer availability, not the default action: a queue-preferring user
* clicking send-now explicitly asked to inject into the live run. The
* item's attachments ride the steer; its quotes/skills travel as the
* restore context so a degraded steer requeues/sends with them intact.
@@ -2029,7 +2380,7 @@ export default function useSteering({
* boundary; it only means something on the live-run path. */
const sendLocalQueuedNow = useCallback(
(item: QueuedMessage, opts?: { preempt?: boolean }) => {
- if (recoveryDisposition(jotaiStore.get(recoveryDispositionsFamily(queueKey)), item) != null) {
+ if (hasQueuedIntent(item.id)) {
return;
}
/** In answer mode (and any other submission-owned non-steerable state)
@@ -2038,13 +2389,18 @@ export default function useSteering({
if (isSubmitting && (!duringRunActive || !canSteer || item.recoverySteerId != null)) {
return;
}
- /** UI callers always find the item; a stale/direct caller has no original
- * neighbours, so restoration falls back to the queue's priority split. */
- const origin = takeQueued(item.id) ?? {
- item,
- beforeIds: [],
- afterIds: [],
- };
+ /** Keep request-scoped reasoning on a new generation; injecting this
+ * item into the active run would silently ignore the selection. */
+ if (duringRunActive && item.reasoningOverride != null) {
+ return;
+ }
+ /* No fallback to the captured item: the only way it is missing is that
+ something else already took it, likely the run-end drain moments before
+ this click landed. Re-sending it would send the same words twice. */
+ const origin = takeQueued(item.id);
+ if (origin == null) {
+ return;
+ }
const taken = origin.item;
if (duringRunActive && canSteer) {
const consumed = submitSteer(
@@ -2062,11 +2418,18 @@ export default function useSteering({
return;
}
if (!isSubmitting) {
- if (idleSendInFlightRef.current) {
+ const lock = acquireQueueSendLock(sendLockKey, sendLockTimeoutMs);
+ if (lock == null) {
restoreQueued(origin);
return;
}
- idleSendInFlightRef.current = true;
+ idleSendLockRef.current = lock;
+ const releaseLock = () => {
+ releaseQueueSendLock(lock);
+ if (idleSendLockRef.current === lock) {
+ idleSendLockRef.current = null;
+ }
+ };
// Explicit (possibly empty) overrides: the queued item is the full
// submission context, never the composer's staged files/quotes/picks.
let accepted: false | void;
@@ -2074,19 +2437,20 @@ export default function useSteering({
accepted = sendNow(taken.text, taken.files ?? [], {
quotes: taken.quotes,
manualSkills: taken.manualSkills,
+ reasoningOverride: taken.reasoningOverride,
clientRequestId: taken.clientRequestId,
recoverySteerId: taken.recoverySteerId,
expectedPredecessorCreatedAt: taken.expectedPredecessorCreatedAt,
queuedMessageOrigin: origin,
});
} catch (error) {
- idleSendInFlightRef.current = false;
+ releaseLock();
restoreQueued(origin);
throw error;
}
if (accepted === false) {
- idleSendInFlightRef.current = false;
- // `ask` refused without sending — restore the chip so the user's
+ releaseLock();
+ // `ask` refused without sending: restore the chip so the user's
// text is never silently dropped (mirrors useQueueDrain).
restoreQueued(origin);
} else {
@@ -2107,6 +2471,8 @@ export default function useSteering({
submitSteer,
isSubmitting,
sendNow,
+ sendLockKey,
+ sendLockTimeoutMs,
restoreQueued,
releaseQueuedOrigin,
],
@@ -2115,6 +2481,12 @@ export default function useSteering({
const queuedActionClaimsRef = useRef(new Set<string>());
const sendQueuedNow = useCallback(
(item: QueuedMessage, opts?: { preempt?: boolean }) => {
+ /* A reasoning override belongs to the next provider request and cannot
+ be injected into the one already running. Refuse before cancelling a
+ durable server row, so it keeps its crash-safe ownership. */
+ if (duringRunActive && item.reasoningOverride != null) {
+ return;
+ }
if (item.server == null) {
sendLocalQueuedNow(item, opts);
return;
@@ -2133,7 +2505,7 @@ export default function useSteering({
queuedActionClaimsRef.current.delete(item.id);
});
},
- [discardQueued, sendLocalQueuedNow],
+ [duringRunActive, discardQueued, sendLocalQueuedNow],
);
/** Abort the current run and auto-send this text once the abort settles. */
@@ -2167,7 +2539,7 @@ export default function useSteering({
/**
* Interrupt & steer: the same POST, queue, chip lifecycle and degradation
- * ladder as an ordinary steer — the only difference is that the server asks
+ * ladder as an ordinary steer: the only difference is that the server asks
* the generating replica to seal its model stream at the next
* provider-safe boundary instead of waiting for a tool step. The partial
* answer is kept and generation resumes in the same message.
@@ -2175,12 +2547,12 @@ export default function useSteering({
* Falls back to `interruptAndSend` ONLY before a conversation exists:
* steering needs a server-side job, so `submitSteer` hard-refuses without a
* real conversationId, and an always-visible button would otherwise be dead
- * for the entire first turn — exactly when a user most wants to stop a long
+ * for the entire first turn, exactly when a user most wants to stop a long
* answer.
*
* A run paused on tool approval refuses outright instead. `canSteer` is
* false there too, but routing that into `interruptAndSend` would hard-abort
- * the run and discard the partial answer — the exact opposite of what this
+ * the run and discard the partial answer: the exact opposite of what this
* action promises. The standalone button is disabled while paused; the
* keyboard and hovercard paths reach here, so the guard lives here.
*/
@@ -2190,6 +2562,15 @@ export default function useSteering({
if (trimmed.length === 0 || filesLoading || pausedOnApproval || !canControlGeneration) {
return false;
}
+ /* A staged reasoning choice belongs to a new generation, which a steer
+ into the live one cannot carry. Falling back to interruptAndSend here
+ would discard the partial answer this action promises to keep, so
+ decline exactly as the disabled menu row does, on the first turn too,
+ and leave the words in the composer, where Enter queues them as a
+ turn of their own. */
+ if (pendingReasoningOverride != null) {
+ return false;
+ }
if (!hasRealConvoId) {
return interruptAndSend(trimmed);
}
@@ -2206,6 +2587,7 @@ export default function useSteering({
pausedOnApproval,
canControlGeneration,
hasRealConvoId,
+ pendingReasoningOverride,
interruptAndSend,
takeComposerFiles,
takeComposerQuotes,
@@ -2221,7 +2603,7 @@ export default function useSteering({
return false;
}
if (effectiveAction === 'steer') {
- /** Only the DEFAULT route honours the preference — the explicit Steer
+ /** Only the DEFAULT route honours the preference: the explicit Steer
* row and the Ctrl/Cmd+Enter alternate stay non-preempting, or they
* would become indistinguishable from Interrupt & steer. */
return steerFromComposer(text, steerInterruptsByDefault);
@@ -2237,7 +2619,7 @@ export default function useSteering({
],
);
- /** Memoized so consumers like `memo(PendingSteerChips)` can bail on the
+ /** Memoized so consumers like `memo(Bar)` and `memo(Queue)` can bail on the
* `steering` prop; a fresh literal here would defeat them every render. */
return useMemo(
() => ({
@@ -2249,6 +2631,8 @@ export default function useSteering({
canSendQueuedNow,
effectiveAction,
defaultAction,
+ steerInterruptsByDefault,
+ pendingReasoningOverride,
pausedOnApproval,
setDefaultAction,
submitDuringRun,
@@ -2261,8 +2645,11 @@ export default function useSteering({
queueReclaimedSteer,
enqueue,
removeQueued,
+ holdQueued,
discardQueued,
- dismissRecovery,
+ rewakeDrain,
+ reorderQueued,
+ restoreQueuedOrder,
sendQueuedNow,
interruptAndSend,
interruptSteer,
@@ -2275,7 +2662,9 @@ export default function useSteering({
duringRunActive,
canSendQueuedNow,
effectiveAction,
+ steerInterruptsByDefault,
defaultAction,
+ pendingReasoningOverride,
pausedOnApproval,
setDefaultAction,
submitDuringRun,
@@ -2288,8 +2677,11 @@ export default function useSteering({
queueReclaimedSteer,
enqueue,
removeQueued,
+ holdQueued,
discardQueued,
- dismissRecovery,
+ rewakeDrain,
+ reorderQueued,
+ restoreQueuedOrder,
sendQueuedNow,
interruptAndSend,
interruptSteer,
diff --git a/client/src/hooks/Config/__tests__/useClearStates.spec.tsx b/client/src/hooks/Config/__tests__/useClearStates.spec.tsx
new file mode 100644
index 0000000000..f0c031b2b4
--- /dev/null
+++ b/client/src/hooks/Config/__tests__/useClearStates.spec.tsx
@@ -0,0 +1,56 @@
+import React from 'react';
+import { RecoilRoot } from 'recoil';
+import { act, renderHook } from '@testing-library/react';
+import { ReasoningEffort } from 'librechat-data-provider';
+import { createStore, Provider as JotaiProvider } from 'jotai';
+import { pendingReasoningOverrideFamily } from '~/components/Chat/Input/Composer/state';
+import { filesDialogTriggerAtom, showFilesDialogAtom } from '~/store/filesDialog';
+import useClearStates from '../useClearStates';
+
+describe('useClearStates', () => {
+ /* Jotai's default store outlives the authenticated route, so a file manager
+ left open at logout would otherwise reopen for the next session with the
+ previous session's opener still attached. */
+ it('closes the file manager and drops its opener at the session boundary', async () => {
+ const jotaiStore = createStore();
+ jotaiStore.set(showFilesDialogAtom, true);
+ jotaiStore.set(filesDialogTriggerAtom, { current: document.createElement('button') });
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
+ <JotaiProvider store={jotaiStore}>
+ <RecoilRoot>{children}</RecoilRoot>
+ </JotaiProvider>
+ );
+
+ const { result } = renderHook(() => useClearStates(), { wrapper });
+ await act(async () => {
+ await result.current();
+ });
+
+ expect(jotaiStore.get(showFilesDialogAtom)).toBe(false);
+ expect(jotaiStore.get(filesDialogTriggerAtom)).toBeNull();
+ });
+
+ /* A staged selection survives navigation, so a conversation that is no longer
+ on screen still holds one; only the mounted panes used to be cleared. */
+ it('drops staged reasoning for every conversation, mounted or not', async () => {
+ const jotaiStore = createStore();
+ const staged = { key: 'reasoning_effort' as const, value: ReasoningEffort.high };
+ jotaiStore.set(pendingReasoningOverrideFamily('unmounted-conversation'), staged);
+ jotaiStore.set(pendingReasoningOverrideFamily('new:1'), staged);
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
+ <JotaiProvider store={jotaiStore}>
+ <RecoilRoot>{children}</RecoilRoot>
+ </JotaiProvider>
+ );
+
+ const { result } = renderHook(() => useClearStates(), { wrapper });
+ await act(async () => {
+ await result.current();
+ });
+
+ expect(Array.from(pendingReasoningOverrideFamily.getParams())).toEqual([]);
+ expect(
+ jotaiStore.get(pendingReasoningOverrideFamily('unmounted-conversation')),
+ ).toBeUndefined();
+ });
+});
diff --git a/client/src/hooks/Config/useClearStates.ts b/client/src/hooks/Config/useClearStates.ts
index 0dde3e2630..1dfd234152 100644
--- a/client/src/hooks/Config/useClearStates.ts
+++ b/client/src/hooks/Config/useClearStates.ts
@@ -1,6 +1,11 @@
import { useStore } from 'jotai';
import { useRecoilCallback } from 'recoil';
+import {
+ getReasoningStateKey,
+ clearPendingReasoningOverrides,
+} from '~/components/Chat/Input/Composer/state';
import { siblingIdxFamily, siblingKey } from '~/components/Chat/Messages/Thread/state';
+import { showFilesDialogAtom, filesDialogTriggerAtom } from '~/store/filesDialog';
import { showSkillsPopoverFamily } from '~/components/Chat/Input/skillsState';
import { clearLocalStorage } from '~/utils/localStorage';
import store from '~/store';
@@ -15,8 +20,21 @@ export default function useClearStates() {
async (skipFirst?: boolean) => {
await clearSubmissions(skipFirst);
await clearConversations(skipFirst);
+ /* Jotai's default store outlives the authenticated route: left alone, a
+ file manager open at logout reopens for the next session, still
+ holding the previous session's unmounted opener. */
+ jotaiStore.set(showFilesDialogAtom, false);
+ jotaiStore.set(filesDialogTriggerAtom, null);
const keys = await snapshot.getPromise(store.conversationKeysAtom);
+ const keptReasoningKeys = new Set<string>();
+ if (skipFirst === true) {
+ const firstConvoId = (await snapshot.getPromise(store.conversationByIndex(0)))
+ ?.conversationId;
+ keptReasoningKeys.add(getReasoningStateKey(null, 0));
+ keptReasoningKeys.add(getReasoningStateKey(firstConvoId, 0));
+ }
+ clearPendingReasoningOverrides(jotaiStore, keptReasoningKeys);
for (const key of keys) {
if (skipFirst === true && key === 0) {
diff --git a/client/src/hooks/Files/__tests__/useAttachExisting.spec.tsx b/client/src/hooks/Files/__tests__/useAttachExisting.spec.tsx
new file mode 100644
index 0000000000..271c0e7465
--- /dev/null
+++ b/client/src/hooks/Files/__tests__/useAttachExisting.spec.tsx
@@ -0,0 +1,303 @@
+/* eslint jest/expect-expect: ["warn", { "assertFunctionNames": ["expect", "refused"] }] */
+import { renderHook } from '@testing-library/react';
+import { FileSources, EModelEndpoint, mergeFileConfig } from 'librechat-data-provider';
+import type { TFile } from 'librechat-data-provider';
+import type { ExtendedFile } from '~/common';
+import useAttachExisting from '../useAttachExisting';
+
+/**
+ * Re-attaching a file already on the server. Every branch here is a refusal,
+ * and an inverted one either blocks every re-attachment or stages a file the
+ * endpoint will reject at send time, when the words are already gone.
+ */
+
+const mockShowToast = jest.fn();
+const mockAddFile = jest.fn();
+let mockFileMap: Record<string, TFile | undefined>;
+let mockConversation: {
+ endpoint?: string | null;
+ endpointType?: string;
+ agent_id?: string;
+} | null;
+const mockSetEphemeralAgent = jest.fn();
+let mockFileSearchEnabled = true;
+let mockStaged: Map<string, ExtendedFile>;
+/** Raw, not merged: the hook's own `select` merges it, and merging twice
+ * scales the megabyte limits twice and puts them out of reach. */
+let mockFileConfig: Parameters<typeof mergeFileConfig>[0];
+
+jest.mock('@librechat/client', () => ({
+ useToastContext: () => ({ showToast: mockShowToast }),
+}));
+
+jest.mock('~/Providers', () => ({
+ useFileMapContext: () => mockFileMap,
+}));
+
+jest.mock('~/data-provider', () => ({
+ useGetFileConfig: ({ select }: { select?: (data: unknown) => unknown }) => ({
+ data: select != null ? select(mockFileConfig) : mockFileConfig,
+ }),
+}));
+
+jest.mock('~/hooks/Files/useUpdateFiles', () => ({
+ __esModule: true,
+ default: () => ({ addFile: mockAddFile }),
+}));
+
+jest.mock('~/hooks/useLocalize', () => ({
+ __esModule: true,
+ default: () => (key: string) => key,
+}));
+
+jest.mock('recoil', () => ({
+ useSetRecoilState: () => mockSetEphemeralAgent,
+}));
+
+jest.mock('~/store', () => ({
+ ephemeralAgentByConvoId: (conversationId: string) => ({ key: conversationId }),
+}));
+
+jest.mock('~/hooks/Agents', () => ({
+ useGetAgentsConfig: () => ({ agentsConfig: undefined }),
+ useAgentCapabilities: () => ({ fileSearchEnabled: mockFileSearchEnabled }),
+}));
+
+const MB = 1024 * 1024;
+/** The endpoint config is written in megabytes; it scales them itself. */
+
+const file = (over: Partial<TFile> = {}): TFile =>
+ ({
+ file_id: 'f1',
+ filename: 'notes.pdf',
+ filepath: '/files/notes.pdf',
+ type: 'application/pdf',
+ bytes: MB,
+ source: FileSources.local,
+ ...over,
+ }) as TFile;
+
+const staged = (over: Partial<ExtendedFile> = {}): ExtendedFile =>
+ ({ file_id: 'other', size: MB, progress: 1, ...over }) as ExtendedFile;
+
+const attach = (
+ target: TFile = file(),
+ resolved: Partial<Parameters<typeof useAttachExisting>[0]> = {},
+) => {
+ const { result } = renderHook(() =>
+ useAttachExisting({
+ files: mockStaged,
+ setFiles: jest.fn(),
+ conversation: mockConversation as never,
+ ...resolved,
+ }),
+ );
+ result.current(target);
+};
+
+describe('useAttachExisting', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ mockFileMap = { f1: file() };
+ mockConversation = { endpoint: EModelEndpoint.openAI };
+ mockFileSearchEnabled = true;
+ mockStaged = new Map();
+ mockFileConfig = {
+ endpoints: {
+ [EModelEndpoint.openAI]: {
+ fileLimit: 3,
+ fileSizeLimit: 5,
+ totalSizeLimit: 10,
+ supportedMimeTypes: ['application/pdf'],
+ },
+ },
+ };
+ });
+
+ /* An embedded file is unreadable without file search, so attaching one turns
+ it on for a direct chat, as the attach menu does (#16223). */
+ it('turns file search on for an embedded file in a direct chat', () => {
+ attach(file({ embedded: true }));
+ expect(mockSetEphemeralAgent).toHaveBeenCalledTimes(1);
+ const update = mockSetEphemeralAgent.mock.calls[0][0] as (prev: object) => object;
+ expect(update({ execute_code: true })).toEqual({ execute_code: true, file_search: true });
+ });
+
+ it('leaves file search alone for a saved agent, a plain file or a disabled capability', () => {
+ mockConversation = { endpoint: EModelEndpoint.agents, agent_id: 'agent_saved' };
+ attach(file({ embedded: true }), { endpoint: EModelEndpoint.openAI });
+ mockConversation = { endpoint: EModelEndpoint.openAI };
+ attach(file({ embedded: false }));
+ mockFileSearchEnabled = false;
+ attach(file({ embedded: true }));
+ expect(mockSetEphemeralAgent).not.toHaveBeenCalled();
+ expect(mockAddFile).toHaveBeenCalledTimes(3);
+ });
+
+ it('stages the file it was given, marked as already uploaded', () => {
+ attach();
+ expect(mockAddFile).toHaveBeenCalledWith(
+ expect.objectContaining({
+ file_id: 'f1',
+ filename: 'notes.pdf',
+ progress: 1,
+ attached: true,
+ size: MB,
+ }),
+ );
+ expect(mockShowToast).not.toHaveBeenCalled();
+ });
+
+ /* The palette's short recent request routinely beats the unbounded file-map
+ query on a cold load, so the row is clickable before `fileMap` has it. */
+ it('stages a file the shared file map has not caught up with yet', () => {
+ mockFileMap = {};
+ attach();
+ expect(mockAddFile).toHaveBeenCalledWith(
+ expect.objectContaining({ file_id: 'f1', filename: 'notes.pdf', size: MB }),
+ );
+ expect(mockShowToast).not.toHaveBeenCalled();
+ });
+
+ /* The recent-files request refreshes signed S3 URLs independently of the
+ full file-map query, so the visible row can be fresher than that cache. */
+ it('prefers the freshly signed row over a stale shared file-map record', () => {
+ mockFileMap = { f1: file({ filepath: 'https://s3.example/expired' }) };
+ attach(file({ filepath: 'https://s3.example/refreshed' }));
+ expect(mockAddFile).toHaveBeenCalledWith(
+ expect.objectContaining({
+ filepath: 'https://s3.example/refreshed',
+ preview: 'https://s3.example/refreshed',
+ }),
+ );
+ });
+
+ describe('refusals', () => {
+ const refused = (message: string) => {
+ expect(mockAddFile).not.toHaveBeenCalled();
+ expect(mockShowToast).toHaveBeenCalledWith(
+ expect.objectContaining({ message: expect.stringContaining(message), status: 'error' }),
+ );
+ };
+
+ it('refuses a file with nothing to identify where it is stored', () => {
+ mockFileMap = {};
+ attach(file({ source: undefined }));
+ refused('com_ui_attach_error');
+ });
+
+ it('refuses when there is no conversation to attach to', () => {
+ mockConversation = null;
+ attach();
+ refused('com_ui_attach_error');
+ });
+
+ it('refuses OpenAI-stored files outside the assistants endpoint', () => {
+ attach(file({ source: FileSources.openai }));
+ refused('com_ui_attach_error_openai');
+ });
+
+ it('refuses when the endpoint has uploads switched off', () => {
+ mockFileConfig = { endpoints: { [EModelEndpoint.openAI]: { disabled: true } } };
+ attach();
+ refused('com_ui_attach_error_disabled');
+ });
+
+ it('refuses once the endpoint is already holding its limit', () => {
+ mockStaged = new Map([
+ ['a', staged({ file_id: 'a' })],
+ ['b', staged({ file_id: 'b' })],
+ ['c', staged({ file_id: 'c' })],
+ ]);
+ attach();
+ refused('com_ui_attach_error_file_limit');
+ });
+
+ it('refuses a file bigger than the endpoint takes', () => {
+ attach(file({ bytes: 6 * MB }));
+ refused('com_ui_attach_error_size');
+ });
+
+ /* The upload path rejects only `size > fileSizeLimit` and the backend filter
+ accepts `bytes <= fileSizeLimit`, so a file sitting exactly on the limit
+ uploads fine and has to stay re-attachable from the palette. */
+ it('accepts a file sitting exactly on the endpoint limit', () => {
+ attach(file({ bytes: 5 * MB }));
+ expect(mockAddFile).toHaveBeenCalled();
+ });
+
+ it('refuses a type the endpoint does not accept', () => {
+ const zip = file({ type: 'application/zip' });
+ attach(zip);
+ refused('com_ui_attach_error_type');
+ });
+
+ it('refuses when it would put the staged files over the total', () => {
+ mockStaged = new Map([['big', staged({ file_id: 'big', size: 9.5 * MB })]]);
+ attach();
+ refused('com_ui_attach_error_total_size');
+ });
+ });
+
+ /* Re-attaching a file that is already staged replaces it, so its own size
+ must come out of the running total before the check. */
+ it('counts a file it is replacing out of the total', () => {
+ mockFileConfig = {
+ endpoints: {
+ [EModelEndpoint.openAI]: {
+ fileSizeLimit: 8,
+ totalSizeLimit: 10,
+ supportedMimeTypes: ['application/pdf'],
+ },
+ },
+ };
+ mockStaged = new Map([['f1', staged({ file_id: 'f1', size: 6 * MB })]]);
+ attach(file({ bytes: 6 * MB }));
+ expect(mockAddFile).toHaveBeenCalled();
+ });
+
+ /* addFile keys by file_id, so re-selecting a file already in the composer
+ replaces its entry rather than growing the map; the count check must not
+ treat that replacement as a new attachment. */
+ it('reattaches a file already holding the endpoint limit without refusing it', () => {
+ mockStaged = new Map([
+ ['f1', staged({ file_id: 'f1' })],
+ ['b', staged({ file_id: 'b' })],
+ ['c', staged({ file_id: 'c' })],
+ ]);
+ attach();
+ expect(mockAddFile).toHaveBeenCalled();
+ expect(mockShowToast).not.toHaveBeenCalledWith(
+ expect.objectContaining({
+ message: expect.stringContaining('com_ui_attach_error_file_limit'),
+ }),
+ );
+ });
+
+ it('warns but still attaches a non-OpenAI file on the assistants endpoint', () => {
+ mockConversation = { endpoint: EModelEndpoint.assistants };
+ mockFileConfig = {
+ endpoints: { [EModelEndpoint.assistants]: { supportedMimeTypes: ['application/pdf'] } },
+ };
+ attach();
+ expect(mockShowToast).toHaveBeenCalledWith(
+ expect.objectContaining({ message: 'com_ui_attach_warn_endpoint', status: 'warning' }),
+ );
+ expect(mockAddFile).toHaveBeenCalled();
+ });
+
+ it('uses the resolved agent provider instead of the stale conversation endpoint', () => {
+ attach(file({ source: FileSources.openai }), {
+ endpoint: EModelEndpoint.assistants,
+ endpointFileConfig: {
+ supportedMimeTypes: [/^application\/pdf$/],
+ fileSizeLimit: 5 * MB,
+ },
+ });
+
+ expect(mockAddFile).toHaveBeenCalled();
+ expect(mockShowToast).not.toHaveBeenCalledWith(
+ expect.objectContaining({ message: 'com_ui_attach_error_openai' }),
+ );
+ });
+});
diff --git a/client/src/hooks/Files/useAttachExisting.ts b/client/src/hooks/Files/useAttachExisting.ts
new file mode 100644
index 0000000000..cf6812e73d
--- /dev/null
+++ b/client/src/hooks/Files/useAttachExisting.ts
@@ -0,0 +1,206 @@
+import { useCallback } from 'react';
+import { useSetRecoilState } from 'recoil';
+import { useToastContext } from '@librechat/client';
+import {
+ megabyte,
+ Constants,
+ EToolResources,
+ mergeFileConfig,
+ checkOpenAIStorage,
+ isEphemeralAgentId,
+ isAssistantsEndpoint,
+ getEndpointFileConfig,
+ defaultAgentCapabilities,
+ fileConfig as defaultFileConfig,
+} from 'librechat-data-provider';
+import type {
+ TFile,
+ TConversation,
+ EModelEndpoint,
+ EndpointFileConfig,
+} from 'librechat-data-provider';
+import type { ExtendedFile, FileSetter } from '~/common';
+import { useAgentCapabilities, useGetAgentsConfig } from '~/hooks/Agents';
+import { useGetFileConfig } from '~/data-provider';
+import { ephemeralAgentByConvoId } from '~/store';
+import useLocalize from '~/hooks/useLocalize';
+import useUpdateFiles from './useUpdateFiles';
+
+/**
+ * Stages an already-uploaded file onto the next message.
+ *
+ * Every check the endpoint would apply to a fresh upload applies here too: the
+ * file exists, but nothing guarantees the endpoint the user has since switched
+ * to accepts its storage backend, type or size.
+ */
+export interface AttachExistingContext {
+ files: Map<string, ExtendedFile>;
+ setFiles: FileSetter;
+ conversation: TConversation | null;
+ endpoint?: string | null;
+ endpointType?: EModelEndpoint | string;
+ endpointFileConfig?: EndpointFileConfig;
+}
+
+/**
+ * Given rather than read from the chat context: the palette holds this hook and
+ * is mounted for the whole conversation, so subscribing there re-rendered the
+ * composer's whole tool catalog every time the context value changed.
+ */
+export default function useAttachExisting(context: AttachExistingContext): (file: TFile) => void {
+ const localize = useLocalize();
+ const { showToast } = useToastContext();
+ const {
+ files,
+ setFiles,
+ conversation,
+ endpoint: resolvedEndpoint,
+ endpointType: resolvedEndpointType,
+ endpointFileConfig: resolvedFileConfig,
+ } = context;
+ const { data: fileConfig = null } = useGetFileConfig({
+ select: (data) => mergeFileConfig(data),
+ });
+ const { addFile } = useUpdateFiles(setFiles);
+ const setEphemeralAgent = useSetRecoilState(
+ ephemeralAgentByConvoId(conversation?.conversationId ?? Constants.NEW_CONVO),
+ );
+ const { agentsConfig } = useGetAgentsConfig();
+ const { fileSearchEnabled } = useAgentCapabilities(
+ agentsConfig?.capabilities ?? defaultAgentCapabilities,
+ );
+
+ return useCallback(
+ (file: TFile) => {
+ /* The selected row is authoritative. Recent files use a separate query
+ that can refresh an S3 signed URL after the full file-map cache was
+ populated, so consulting that cache here can replace a valid row with
+ an expired path. */
+ const fileData = file;
+
+ const endpoint = resolvedEndpoint ?? conversation?.endpoint;
+ const endpointType = resolvedEndpointType ?? conversation?.endpointType;
+ if (!fileData.source || !endpoint) {
+ showToast({ message: localize('com_ui_attach_error'), status: 'error' });
+ return;
+ }
+
+ const isOpenAIStorage = checkOpenAIStorage(fileData.source);
+ const isAssistants = isAssistantsEndpoint(endpoint);
+
+ if (isOpenAIStorage && !isAssistants) {
+ showToast({ message: localize('com_ui_attach_error_openai'), status: 'error' });
+ return;
+ }
+
+ if (!isOpenAIStorage && isAssistants) {
+ showToast({ message: localize('com_ui_attach_warn_endpoint'), status: 'warning' });
+ }
+
+ const endpointFileConfig =
+ resolvedFileConfig ?? getEndpointFileConfig({ fileConfig, endpoint, endpointType });
+
+ if (endpointFileConfig.disabled === true) {
+ showToast({ message: localize('com_ui_attach_error_disabled'), status: 'error' });
+ return;
+ }
+
+ const isReattach = files.has(fileData.file_id);
+
+ if (
+ endpointFileConfig.fileLimit &&
+ !isReattach &&
+ files.size >= endpointFileConfig.fileLimit
+ ) {
+ showToast({
+ message: localize(
+ endpointFileConfig.fileLimit === 1
+ ? 'com_ui_attach_error_file_limit_one'
+ : 'com_ui_attach_error_file_limit',
+ { count: endpointFileConfig.fileLimit, 0: endpoint },
+ ),
+ status: 'error',
+ });
+ return;
+ }
+
+ if (fileData.bytes > (endpointFileConfig.fileSizeLimit ?? Number.MAX_SAFE_INTEGER)) {
+ showToast({
+ message: `${localize('com_ui_attach_error_size')} ${
+ (endpointFileConfig.fileSizeLimit ?? 0) / megabyte
+ } MB (${endpoint})`,
+ status: 'error',
+ });
+ return;
+ }
+
+ if (!defaultFileConfig.checkType(file.type, endpointFileConfig.supportedMimeTypes ?? [])) {
+ showToast({
+ message: `${localize('com_ui_attach_error_type')} ${file.type} (${endpoint})`,
+ status: 'error',
+ });
+ return;
+ }
+
+ if (endpointFileConfig.totalSizeLimit) {
+ const existing = files.get(fileData.file_id);
+ let currentTotalSize = 0;
+ for (const staged of files.values()) {
+ currentTotalSize += staged.size;
+ }
+ currentTotalSize -= existing?.size ?? 0;
+ if (currentTotalSize + fileData.bytes > endpointFileConfig.totalSizeLimit) {
+ showToast({
+ message: `${localize('com_ui_attach_error_total_size')} ${endpointFileConfig.totalSizeLimit / megabyte} MB (${endpoint})`,
+ status: 'error',
+ });
+ return;
+ }
+ }
+
+ /* An embedded file is unreadable unless file search is on, so attaching one
+ turns it on, as the attach menu does. The ephemeral flag governs direct
+ chats only: a saved agent's own tools decide, and writing it there would
+ be dead state the chips still reflect. */
+ if (
+ fileData.embedded === true &&
+ fileSearchEnabled &&
+ isEphemeralAgentId(conversation?.agent_id)
+ ) {
+ setEphemeralAgent((prev) => ({ ...prev, [EToolResources.file_search]: true }));
+ }
+
+ addFile({
+ progress: 1,
+ attached: true,
+ file_id: fileData.file_id,
+ filepath: fileData.filepath,
+ preview: fileData.filepath,
+ type: fileData.type,
+ height: fileData.height,
+ width: fileData.width,
+ filename: fileData.filename,
+ source: fileData.source,
+ size: fileData.bytes,
+ metadata: fileData.metadata,
+ /* Dev's extracted-text preview (#15946) staged this off the panel's own
+ * addFile call; the delivery path has to ride along here now that every
+ * attach-existing surface routes through this hook. */
+ llmDeliveryPath: fileData.llmDeliveryPath,
+ });
+ },
+ [
+ addFile,
+ files,
+ conversation,
+ resolvedEndpoint,
+ resolvedEndpointType,
+ resolvedFileConfig,
+ localize,
+ showToast,
+ fileConfig,
+ fileSearchEnabled,
+ setEphemeralAgent,
+ ],
+ );
+}
diff --git a/client/src/hooks/Files/useUpdateFiles.ts b/client/src/hooks/Files/useUpdateFiles.ts
index 1598c7e7b2..a773dca919 100644
--- a/client/src/hooks/Files/useUpdateFiles.ts
+++ b/client/src/hooks/Files/useUpdateFiles.ts
@@ -1,10 +1,18 @@
import type { ExtendedFile, FileSetter } from '~/common';
+import { isComposerFileTaken, releaseComposerFile } from '~/utils/composerFiles';
import useSetFilesToDelete from './useSetFilesToDelete';
export default function useUpdateFiles(setFiles: FileSetter) {
const setFilesToDelete = useSetFilesToDelete();
+ /**
+ * Always a deliberate attach: the first, synchronous step of an upload the
+ * user just started, or an explicit pick from the file panel. That intent
+ * outranks any earlier consumption of the same id: re-attaching a library
+ * file reuses its server id, so the mark is dropped rather than obeyed.
+ */
const addFile = (newFile: ExtendedFile) => {
+ releaseComposerFile(newFile.file_id);
setFiles((currentFiles) => {
const updatedFiles = new Map(currentFiles);
updatedFiles.set(newFile.file_id, newFile);
@@ -12,7 +20,17 @@ export default function useUpdateFiles(setFiles: FileSetter) {
});
};
+ /**
+ * Only ever a continuation of an upload already in the composer (conversion
+ * progress, resize, image measurement). A steer or a queued message can have
+ * consumed that attachment while those callbacks were in flight, and writing
+ * it back would resurrect a file the message already owns, so a consumed id
+ * is dropped here instead of re-entering the composer.
+ */
const replaceFile = (newFile: ExtendedFile) => {
+ if (isComposerFileTaken(newFile.file_id)) {
+ return;
+ }
setFiles((currentFiles) => {
const updatedFiles = new Map(currentFiles);
updatedFiles.set(newFile.file_id, newFile);
diff --git a/client/src/hooks/Files/useUploadOptions.ts b/client/src/hooks/Files/useUploadOptions.ts
index c2f401bb50..93894b139b 100644
--- a/client/src/hooks/Files/useUploadOptions.ts
+++ b/client/src/hooks/Files/useUploadOptions.ts
@@ -1,22 +1,21 @@
import { useCallback } from 'react';
import { useRecoilValue } from 'recoil';
import {
- Tools,
Constants,
mergeFileConfig,
isAgentsEndpoint,
+ isEphemeralAgentId,
getEndpointFileConfig,
defaultAgentCapabilities,
} from 'librechat-data-provider';
import type { EToolResources } from 'librechat-data-provider';
+import { getViableUploadOptions, getUploadToolAllowances, isUnifiedUploadMode } from '~/utils';
import useAgentToolPermissions from '~/hooks/Agents/useAgentToolPermissions';
import useAgentCapabilities from '~/hooks/Agents/useAgentCapabilities';
-import { getViableUploadOptions, isUnifiedUploadMode } from '~/utils';
import useGetAgentsConfig from '~/hooks/Agents/useGetAgentsConfig';
import { useGetFileConfig } from '~/data-provider';
import { ephemeralAgentByConvoId } from '~/store';
import { useDragDropContext } from '~/Providers';
-import { isEphemeralAgent } from '~/common';
/**
* Resolves which upload destinations a file set can be routed to, plus whether uploads are
@@ -42,13 +41,10 @@ export default function useUploadOptions() {
/** Destination checks read this config, so callers can tell "not viable" from "not known yet". */
const isConfigPending = !isFileConfigLoaded && !isFileConfigError && !isFileConfigPaused;
- /**
- * Tools are offerable unless a saved agent omits them; in direct/ephemeral chats selecting
- * one enables the ephemeral capability, matching the original drag-and-drop behavior.
- */
- const isSavedAgent = agentId != null && agentId !== '' && !isEphemeralAgent(agentId);
- const fileSearchAllowedByAgent = !isSavedAgent || (tools?.includes(Tools.file_search) ?? false);
- const codeAllowedByAgent = !isSavedAgent || (tools?.includes(Tools.execute_code) ?? false);
+ const { fileSearchAllowedByAgent, codeAllowedByAgent } = getUploadToolAllowances(agentId, tools);
+ /* Same predicate `getUploadToolAllowances` applies internally: only a saved
+ agent has a provider to wait for below. */
+ const isSavedAgent = agentId != null && agentId !== '' && !isEphemeralAgentId(agentId);
/* An agent conversation carries endpoint `agents`, but its file policy belongs to the
* provider it runs on, which is the entry a named custom endpoint configures. Resolved
diff --git a/client/src/hooks/Generic/index.ts b/client/src/hooks/Generic/index.ts
index 2a28c53bbc..34134a06d4 100644
--- a/client/src/hooks/Generic/index.ts
+++ b/client/src/hooks/Generic/index.ts
@@ -2,3 +2,4 @@ export * from './useLazyEffect';
export { default as useShiftKey } from './useShiftKey';
export { default as useElementSize } from './useElementSize';
export { default as useOuterScrollWindow } from './useOuterScrollWindow';
+export { default as useReducedMotion } from './useReducedMotion';
diff --git a/client/src/hooks/Generic/useReducedMotion.ts b/client/src/hooks/Generic/useReducedMotion.ts
new file mode 100644
index 0000000000..3cecb02fcb
--- /dev/null
+++ b/client/src/hooks/Generic/useReducedMotion.ts
@@ -0,0 +1,27 @@
+import { useState, useEffect } from 'react';
+
+const QUERY = '(prefers-reduced-motion: reduce)';
+
+/**
+ * Whether the person using this has asked for less movement.
+ *
+ * Stylesheets can answer that themselves, so this is for the motion they cannot
+ * reach: transitions written as inline styles, and animations played from
+ * script. It follows the setting rather than reading it once, since it can be
+ * changed while the page is open.
+ */
+export default function useReducedMotion(): boolean {
+ const [reduced, setReduced] = useState(
+ () => typeof window !== 'undefined' && window.matchMedia(QUERY).matches,
+ );
+
+ useEffect(() => {
+ const media = window.matchMedia(QUERY);
+ const update = () => setReduced(media.matches);
+ update();
+ media.addEventListener('change', update);
+ return () => media.removeEventListener('change', update);
+ }, []);
+
+ return reduced;
+}
diff --git a/client/src/hooks/Input/__tests__/useAttachItems.spec.tsx b/client/src/hooks/Input/__tests__/useAttachItems.spec.tsx
new file mode 100644
index 0000000000..7b22b6877b
--- /dev/null
+++ b/client/src/hooks/Input/__tests__/useAttachItems.spec.tsx
@@ -0,0 +1,448 @@
+import React from 'react';
+import { RecoilRoot } from 'recoil';
+import { act, renderHook } from '@testing-library/react';
+import { Tools, EToolResources, EModelEndpoint } from 'librechat-data-provider';
+import type { TConversation, EndpointFileConfig } from 'librechat-data-provider';
+import useAttachItems from '../useAttachItems';
+
+/**
+ * Ports the destination-visibility cases from the deleted `AttachFileMenu`
+ * spec, which is where this logic used to live. They cover the rule that
+ * decides which upload destinations exist at all: the one that silently lost
+ * both tool destinations when the palette stopped passing the ephemeral agent.
+ */
+
+jest.mock('~/hooks', () => ({
+ useAgentToolPermissions: jest.fn(),
+ useAgentCapabilities: jest.fn(),
+ useGetAgentsConfig: jest.fn(),
+}));
+
+jest.mock('~/hooks/useLocalize', () => ({
+ __esModule: true,
+ default: () => (key: string) => key,
+}));
+
+const mockHandleFileChange = jest.fn();
+jest.mock('~/hooks/Files', () => ({
+ useFileHandlingNoChatContext: () => ({ handleFileChange: mockHandleFileChange }),
+}));
+
+jest.mock('~/hooks/Files/useSharePointFileHandling', () => ({
+ __esModule: true,
+ default: jest.fn(),
+ useSharePointFileHandlingNoChatContext: () => ({
+ handleSharePointFiles: jest.fn(),
+ isProcessing: false,
+ downloadProgress: undefined,
+ }),
+}));
+
+jest.mock('~/data-provider', () => ({
+ useGetStartupConfig: jest.fn(),
+}));
+
+const mockUseAgentToolPermissions = jest.requireMock('~/hooks').useAgentToolPermissions;
+const mockUseAgentCapabilities = jest.requireMock('~/hooks').useAgentCapabilities;
+const mockUseGetAgentsConfig = jest.requireMock('~/hooks').useGetAgentsConfig;
+const mockUseGetStartupConfig = jest.requireMock('~/data-provider').useGetStartupConfig;
+
+const SAVED_AGENT = 'agent_abc123';
+
+interface Options {
+ agentId?: string | null;
+ endpoint?: string | null;
+ endpointType?: EModelEndpoint | string;
+ useResponsesApi?: boolean;
+ isUnifiedMode?: boolean;
+ endpointFileConfig?: EndpointFileConfig;
+ provider?: string;
+ tools?: string[];
+ contextEnabled?: boolean;
+ fileSearchEnabled?: boolean;
+ codeEnabled?: boolean;
+ sharePointEnabled?: boolean;
+}
+
+/** Row ids, which are what the palette keys and folds on. */
+function renderEntries(options: Options = {}): string[] {
+ const {
+ agentId = null,
+ endpoint = null,
+ endpointType,
+ useResponsesApi,
+ isUnifiedMode = false,
+ endpointFileConfig,
+ provider,
+ tools,
+ contextEnabled = false,
+ fileSearchEnabled = false,
+ codeEnabled = false,
+ sharePointEnabled = false,
+ } = options;
+
+ mockUseAgentToolPermissions.mockReturnValue({ tools, provider });
+ mockUseAgentCapabilities.mockReturnValue({ contextEnabled, fileSearchEnabled, codeEnabled });
+ mockUseGetAgentsConfig.mockReturnValue({ agentsConfig: { capabilities: [] } });
+ mockUseGetStartupConfig.mockReturnValue({
+ data: { sharePointFilePickerEnabled: sharePointEnabled },
+ });
+
+ const { result } = renderHook(
+ () =>
+ useAttachItems({
+ agentId,
+ endpoint,
+ endpointType,
+ useResponsesApi,
+ endpointFileConfig,
+ isUnifiedMode,
+ conversationId: 'convo-1',
+ conversation: { conversationId: 'convo-1' } as TConversation,
+ files: new Map(),
+ setFiles: jest.fn(),
+ setFilesLoading: jest.fn(),
+ }),
+ {
+ wrapper: ({ children }: { children: React.ReactNode }) => <RecoilRoot>{children}</RecoilRoot>,
+ },
+ );
+
+ return result.current.entries.map((entry) => entry.id);
+}
+
+const allCapabilities = { contextEnabled: true, fileSearchEnabled: true, codeEnabled: true };
+
+/** The hook, not just its entry labels, so a destination can be chosen. */
+function renderAttach(options: Options = {}) {
+ mockUseAgentToolPermissions.mockReturnValue({ tools: options.tools, provider: options.provider });
+ mockUseAgentCapabilities.mockReturnValue({
+ contextEnabled: options.contextEnabled ?? true,
+ fileSearchEnabled: options.fileSearchEnabled ?? true,
+ codeEnabled: options.codeEnabled ?? true,
+ });
+ mockUseGetAgentsConfig.mockReturnValue({ agentsConfig: { capabilities: [] } });
+ mockUseGetStartupConfig.mockReturnValue({ data: { sharePointFilePickerEnabled: false } });
+
+ return renderHook(
+ () =>
+ useAttachItems({
+ agentId: options.agentId ?? null,
+ endpoint: options.endpoint ?? null,
+ endpointType: options.endpointType,
+ useResponsesApi: options.useResponsesApi,
+ endpointFileConfig: options.endpointFileConfig,
+ isUnifiedMode: options.isUnifiedMode,
+ conversationId: 'convo-1',
+ conversation: { conversationId: 'convo-1' } as TConversation,
+ files: new Map(),
+ setFiles: jest.fn(),
+ setFilesLoading: jest.fn(),
+ }),
+ {
+ wrapper: ({ children }: { children: React.ReactNode }) => <RecoilRoot>{children}</RecoilRoot>,
+ },
+ );
+}
+
+/** Stands in for the picker: a real one cannot open in jsdom, and what matters
+ * is that the change event arrives while the chosen destination is still set. */
+const pickFile = (input: HTMLInputElement, onFileChange: (e: never) => void) => {
+ onFileChange({ target: input } as never);
+};
+
+describe('useAttachItems', () => {
+ beforeEach(() => jest.clearAllMocks());
+
+ describe('provider upload versus image-only upload', () => {
+ it('offers a provider upload for a custom endpoint type', () => {
+ expect(renderEntries({ endpointType: 'custom' })).toContain('local:provider');
+ });
+
+ it.each([EModelEndpoint.openAI, EModelEndpoint.anthropic, EModelEndpoint.google])(
+ 'offers a provider upload for %s',
+ (endpointType) => {
+ expect(renderEntries({ endpointType })).toContain('local:provider');
+ },
+ );
+
+ it('falls back to an image upload for the agents endpoint with no resolved provider', () => {
+ const ids = renderEntries({ endpointType: EModelEndpoint.agents });
+ expect(ids).toContain('local:image');
+ expect(ids).not.toContain('local:provider');
+ });
+
+ it('resolves the provider through a saved agent, not the agents endpoint', () => {
+ expect(
+ renderEntries({
+ agentId: SAVED_AGENT,
+ endpointType: EModelEndpoint.agents,
+ provider: EModelEndpoint.anthropic,
+ }),
+ ).toContain('local:provider');
+ });
+
+ it('offers a provider upload for azureOpenAI only with the responses API', () => {
+ expect(
+ renderEntries({ provider: EModelEndpoint.azureOpenAI, useResponsesApi: true }),
+ ).toContain('local:provider');
+ expect(
+ renderEntries({ endpointType: EModelEndpoint.azureOpenAI, useResponsesApi: true }),
+ ).toContain('local:provider');
+ expect(
+ renderEntries({ endpointType: EModelEndpoint.azureOpenAI, useResponsesApi: false }),
+ ).toContain('local:image');
+ });
+
+ /* Assistants carry their own file configuration and the old menu handed
+ them an unfiltered picker; scoping them to the image capability, which
+ the provider check would, silently dropped PDF support. */
+ it.each([EModelEndpoint.assistants, EModelEndpoint.azureAssistants])(
+ 'offers one unfiltered upload for %s and no tool destinations',
+ (endpoint) => {
+ const ids = renderEntries({
+ endpoint,
+ contextEnabled: true,
+ fileSearchEnabled: true,
+ codeEnabled: true,
+ });
+ expect(ids).toEqual(['local:assistants']);
+ },
+ );
+
+ it('reads a provider whatever its casing, which OpenRouter arrives in', () => {
+ expect(renderEntries({ provider: 'OpenRouter' })).toContain('local:provider');
+ });
+ it('offers local and SharePoint sources without destination choices in unified mode', () => {
+ expect(
+ renderEntries({
+ isUnifiedMode: true,
+ sharePointEnabled: true,
+ contextEnabled: true,
+ fileSearchEnabled: true,
+ codeEnabled: true,
+ }),
+ ).toEqual(['local:unified', 'sharepoint:unified']);
+ });
+ });
+
+ describe('destinations behind an agent capability', () => {
+ it('offers text extraction when the context capability is on', () => {
+ expect(renderEntries({ contextEnabled: true })).toContain('local:context');
+ expect(renderEntries({ contextEnabled: false })).not.toContain('local:context');
+ });
+
+ it('offers a tool destination only when its capability is on', () => {
+ const ids = renderEntries({ fileSearchEnabled: true });
+ expect(ids).toContain('local:file_search');
+ expect(ids).not.toContain('local:execute_code');
+ });
+
+ it('offers every destination when every capability is on', () => {
+ expect(renderEntries(allCapabilities)).toEqual([
+ 'local:image',
+ 'local:context',
+ 'local:file_search',
+ 'local:execute_code',
+ ]);
+ });
+ });
+
+ describe('which agent is allowed the tool destinations', () => {
+ /* The regression: an ordinary chat runs on an ephemeral agent, which has no
+ tool list. Reading one anyway hid both destinations, leaving drag and
+ drop as the only way to reach the code environment. */
+ it('offers both tool destinations in an ordinary chat', () => {
+ const ids = renderEntries({ ...allCapabilities, agentId: null, tools: undefined });
+ expect(ids).toContain('local:file_search');
+ expect(ids).toContain('local:execute_code');
+ });
+
+ it('offers both to an ephemeral agent, which carries no tool list', () => {
+ const ids = renderEntries({
+ ...allCapabilities,
+ agentId: 'openAI__gpt-5___GPT-5',
+ tools: undefined,
+ });
+ expect(ids).toContain('local:file_search');
+ expect(ids).toContain('local:execute_code');
+ });
+
+ it('offers a saved agent only the destinations it was built with', () => {
+ const ids = renderEntries({
+ ...allCapabilities,
+ agentId: SAVED_AGENT,
+ tools: [Tools.file_search],
+ });
+ expect(ids).toContain('local:file_search');
+ expect(ids).not.toContain('local:execute_code');
+ });
+
+ it('offers a saved agent with no tools neither destination', () => {
+ const ids = renderEntries({ ...allCapabilities, agentId: SAVED_AGENT, tools: [] });
+ expect(ids).not.toContain('local:file_search');
+ expect(ids).not.toContain('local:execute_code');
+ expect(ids).toContain('local:context');
+ });
+ });
+
+ describe('SharePoint', () => {
+ it('mirrors every local destination when it is enabled', () => {
+ expect(renderEntries({ ...allCapabilities, sharePointEnabled: true })).toEqual([
+ 'local:image',
+ 'local:context',
+ 'local:file_search',
+ 'local:execute_code',
+ 'sharepoint:image',
+ 'sharepoint:context',
+ 'sharepoint:file_search',
+ 'sharepoint:execute_code',
+ ]);
+ });
+
+ it('adds nothing when it is disabled', () => {
+ expect(renderEntries({ ...allCapabilities, sharePointEnabled: false })).toHaveLength(4);
+ });
+ });
+
+ describe('what the palette folds away', () => {
+ /* The disclosure keeps one row out and hides the rest, so exactly one row
+ may claim to be the ordinary destination. */
+ it('marks the provider row as the only primary destination', () => {
+ mockUseAgentToolPermissions.mockReturnValue({ tools: undefined, provider: undefined });
+ mockUseAgentCapabilities.mockReturnValue(allCapabilities);
+ mockUseGetAgentsConfig.mockReturnValue({ agentsConfig: { capabilities: [] } });
+ mockUseGetStartupConfig.mockReturnValue({
+ data: { sharePointFilePickerEnabled: true },
+ });
+
+ const { result } = renderHook(
+ () =>
+ useAttachItems({
+ agentId: null,
+ endpoint: EModelEndpoint.anthropic,
+ endpointType: EModelEndpoint.anthropic,
+ conversationId: 'convo-1',
+ conversation: { conversationId: 'convo-1' } as TConversation,
+ files: new Map(),
+ setFiles: jest.fn(),
+ setFilesLoading: jest.fn(),
+ }),
+ {
+ wrapper: ({ children }: { children: React.ReactNode }) => (
+ <RecoilRoot>{children}</RecoilRoot>
+ ),
+ },
+ );
+
+ const primary = result.current.entries.filter((entry) => entry.primary === true);
+ expect(primary.map((entry) => entry.id)).toEqual(['local:provider']);
+ /* Including the SharePoint copy of the provider row: it is a second way
+ to reach a destination that is already out. */
+ expect(
+ result.current.entries.find((entry) => entry.id === 'sharepoint:provider')?.primary,
+ ).toBe(false);
+ });
+ });
+
+ describe('where the picked file is routed', () => {
+ /* The destination is held in a ref precisely because the picker can fire
+ its change event before React has committed any state, so losing it here
+ lands a File Search upload as a plain provider attachment. */
+ it('carries the chosen destination through the picker and then forgets it', () => {
+ const { result } = renderAttach();
+ const input = document.createElement('input');
+ Object.defineProperty(result.current.inputRef, 'current', { value: input, writable: true });
+
+ act(() => {
+ result.current.entries.find((entry) => entry.id === 'local:file_search')?.onSelect();
+ });
+ act(() => pickFile(input, result.current.onFileChange));
+ expect(mockHandleFileChange).toHaveBeenLastCalledWith(
+ expect.anything(),
+ EToolResources.file_search,
+ );
+
+ /* And the next pick is a plain one unless a destination is chosen again. */
+ act(() => {
+ result.current.entries.find((entry) => entry.id === 'local:provider')?.onSelect();
+ });
+ act(() => pickFile(input, result.current.onFileChange));
+ expect(mockHandleFileChange).toHaveBeenLastCalledWith(expect.anything(), undefined);
+ });
+
+ /* A custom endpoint's own NAME is what identifies its provider; the
+ resolved `endpointType` flattens every one of them to `custom`. Handing
+ the palette the type in place of the name cost an OpenRouter endpoint the
+ video and audio it takes. */
+ it('reads the provider from a custom endpoint name, not its resolved type', () => {
+ const acceptFor = (endpoint: string) => {
+ const { result } = renderAttach({ endpoint, endpointType: EModelEndpoint.custom });
+ const input = document.createElement('input');
+ const accepts: string[] = [];
+ input.click = () => accepts.push(input.accept);
+ Object.defineProperty(result.current.inputRef, 'current', { value: input, writable: true });
+ act(() => {
+ result.current.entries.find((entry) => entry.id === 'local:provider')?.onSelect();
+ });
+ return accepts[0];
+ };
+
+ expect(acceptFor('OpenRouter')).toContain('video/');
+ expect(acceptFor('OpenRouter')).toContain('audio/');
+ /* The type on its own is a document-and-image provider and nothing more. */
+ expect(acceptFor(EModelEndpoint.custom)).not.toContain('video/');
+ });
+ it('uses an explicit custom-endpoint media allowlist', () => {
+ const { result } = renderAttach({
+ endpoint: 'MyGateway',
+ endpointType: EModelEndpoint.custom,
+ endpointFileConfig: {
+ supportedMimeTypes: [/^image\/.*$/, /^application\/pdf$/, /^video\/.*$/],
+ },
+ });
+ const input = document.createElement('input');
+ const accepts: string[] = [];
+ input.click = () => accepts.push(input.accept);
+ Object.defineProperty(result.current.inputRef, 'current', { value: input, writable: true });
+
+ act(() => {
+ result.current.entries.find((entry) => entry.id === 'local:provider')?.onSelect();
+ });
+
+ expect(accepts[0]).toContain('video/*');
+ expect(accepts[0]).not.toContain('audio/*');
+ });
+
+ it('scopes the picker to what the destination can send', () => {
+ const { result } = renderAttach({ endpointType: EModelEndpoint.bedrock });
+ const input = document.createElement('input');
+ const accepts: string[] = [];
+ input.click = () => accepts.push(input.accept);
+ Object.defineProperty(result.current.inputRef, 'current', { value: input, writable: true });
+
+ act(() => {
+ result.current.entries.find((entry) => entry.id === 'local:provider')?.onSelect();
+ });
+ expect(accepts[0]).toContain('image/');
+
+ act(() => {
+ result.current.entries.find((entry) => entry.id === 'local:context')?.onSelect();
+ });
+ /* Text extraction takes anything the server can read, so it does not
+ narrow the picker at all. */
+ expect(accepts[1]).toBe('');
+ });
+ });
+
+ describe('edge cases', () => {
+ it.each([
+ ['undefined endpoint and provider', { endpoint: undefined, provider: undefined }],
+ ['null endpoint', { endpoint: null }],
+ ['missing agent id', { agentId: undefined }],
+ ['empty agent id', { agentId: '' }],
+ ])('still resolves a destination with %s', (_label, options) => {
+ expect(renderEntries(options as Options).length).toBeGreaterThan(0);
+ });
+ });
+});
diff --git a/client/src/hooks/Input/__tests__/useAttachTarget.spec.ts b/client/src/hooks/Input/__tests__/useAttachTarget.spec.ts
new file mode 100644
index 0000000000..9200ce7291
--- /dev/null
+++ b/client/src/hooks/Input/__tests__/useAttachTarget.spec.ts
@@ -0,0 +1,276 @@
+import { renderHook } from '@testing-library/react';
+import { EModelEndpoint, mergeFileConfig } from 'librechat-data-provider';
+import type { TConversation, TEndpointsConfig } from 'librechat-data-provider';
+import useAttachTarget from '../useAttachTarget';
+
+/**
+ * Ports the resolution cases from the deleted `AttachFileChat` spec, which is
+ * where this logic lived before the palette needed it. What an agent uploads
+ * to is decided here, and every branch of it is a fallback that fires only when
+ * the layer above it is missing.
+ */
+
+let mockEndpointsConfig: TEndpointsConfig = {
+ [EModelEndpoint.openAI]: { userProvide: false, order: 0 },
+ [EModelEndpoint.agents]: { userProvide: false, order: 1 },
+ Moonshot: { type: EModelEndpoint.custom, userProvide: false, order: 9999 },
+};
+
+const defaultFileConfig = mergeFileConfig({
+ endpoints: {
+ Moonshot: { fileLimit: 5 },
+ [EModelEndpoint.agents]: { fileLimit: 20 },
+ default: { fileLimit: 10 },
+ },
+});
+
+let mockFileConfig = defaultFileConfig;
+let mockFileConfigLoaded = true;
+/** Only the two fields the resolution reads, so a fixture stays a fixture. */
+interface AgentFixture {
+ provider?: string;
+ model_parameters?: { useResponsesApi?: boolean };
+}
+
+let mockAgentsMap: Record<string, AgentFixture> = {};
+let mockFetchedAgent: AgentFixture | undefined;
+let mockAgentQueryEnabled: boolean | undefined;
+
+jest.mock('~/data-provider', () => ({
+ useGetEndpointsQuery: () => ({ data: mockEndpointsConfig }),
+ useGetFileConfig: ({ select }: { select?: (data: unknown) => unknown }) => ({
+ data: select != null ? select(mockFileConfig) : mockFileConfig,
+ isSuccess: mockFileConfigLoaded,
+ }),
+ useGetAgentByIdQuery: (_id: string | undefined, options?: { enabled?: boolean }) => {
+ mockAgentQueryEnabled = options?.enabled;
+ return { data: options?.enabled === false ? undefined : mockFetchedAgent };
+ },
+}));
+
+jest.mock('~/Providers', () => ({
+ useAgentsMapContext: () => mockAgentsMap,
+}));
+
+type ConversationFixture = Omit<Partial<TConversation>, 'endpoint'> & { endpoint?: string };
+
+const target = (conversation: ConversationFixture | null, disableInputs = false) =>
+ renderHook(() => useAttachTarget(conversation as TConversation | null, disableInputs)).result
+ .current;
+
+describe('useAttachTarget', () => {
+ beforeEach(() => {
+ mockFileConfig = defaultFileConfig;
+ mockFileConfigLoaded = true;
+ mockAgentsMap = {};
+ mockFetchedAgent = undefined;
+ mockAgentQueryEnabled = undefined;
+ mockEndpointsConfig = {
+ [EModelEndpoint.openAI]: { userProvide: false, order: 0 },
+ [EModelEndpoint.agents]: { userProvide: false, order: 1 },
+ Moonshot: { type: EModelEndpoint.custom, userProvide: false, order: 9999 },
+ };
+ });
+
+ /* The saved flag says what the conversation chose; the request the upload
+ rides may be auto-routed to Responses by policy, and the picker has to
+ follow the route or Azure chats lose provider-document uploads. */
+ describe('the effective responses route', () => {
+ const routedAzure = {
+ [EModelEndpoint.azureOpenAI]: {
+ userProvide: false,
+ order: 2,
+ responsesApiRouting: { '*': { default: true, on: true, off: false } },
+ },
+ } as unknown as TEndpointsConfig;
+
+ it('follows a routing policy that enables Responses by default', () => {
+ mockEndpointsConfig = { ...mockEndpointsConfig, ...routedAzure };
+ expect(
+ target({ endpoint: EModelEndpoint.azureOpenAI, model: 'gpt-5.2' }).useResponsesApi,
+ ).toBe(true);
+ });
+
+ it('keeps an explicit conversation opt-out off under the same policy', () => {
+ mockEndpointsConfig = { ...mockEndpointsConfig, ...routedAzure };
+ expect(
+ target({
+ endpoint: EModelEndpoint.azureOpenAI,
+ model: 'gpt-5.2',
+ useResponsesApi: false,
+ }).useResponsesApi,
+ ).toBe(false);
+ });
+
+ it('returns the saved flag when no policy applies', () => {
+ expect(
+ target({ endpoint: EModelEndpoint.azureOpenAI, model: 'gpt-5.2' }).useResponsesApi,
+ ).toBeUndefined();
+ });
+ });
+
+ describe('endpoint type behind an agent', () => {
+ it('resolves a custom provider to its endpoint type', () => {
+ mockAgentsMap = { 'agent-1': { provider: 'Moonshot', model_parameters: {} } };
+ expect(target({ endpoint: EModelEndpoint.agents, agent_id: 'agent-1' }).endpointType).toBe(
+ EModelEndpoint.custom,
+ );
+ });
+
+ it('resolves a first-party provider to itself', () => {
+ mockAgentsMap = { 'agent-1': { provider: EModelEndpoint.openAI, model_parameters: {} } };
+ expect(target({ endpoint: EModelEndpoint.agents, agent_id: 'agent-1' }).endpointType).toBe(
+ EModelEndpoint.openAI,
+ );
+ });
+
+ it('stays on the agents endpoint when the agent names no provider', () => {
+ mockAgentsMap = { 'agent-1': { model_parameters: {} } };
+ expect(target({ endpoint: EModelEndpoint.agents, agent_id: 'agent-1' }).endpointType).toBe(
+ EModelEndpoint.agents,
+ );
+ });
+
+ it('fetches the agent only when the map has no parameters for it', () => {
+ mockAgentsMap = { 'agent-1': { provider: 'Moonshot', model_parameters: {} } };
+ target({ endpoint: EModelEndpoint.agents, agent_id: 'agent-1' });
+ expect(mockAgentQueryEnabled).toBe(false);
+
+ mockAgentsMap = {};
+ mockFetchedAgent = { provider: 'Moonshot' };
+ const resolved = target({ endpoint: EModelEndpoint.agents, agent_id: 'agent-1' });
+ expect(mockAgentQueryEnabled).toBe(true);
+ expect(resolved.endpointType).toBe(EModelEndpoint.custom);
+ });
+
+ it('falls back to the map when the fetched agent omits its provider', () => {
+ mockAgentsMap = { 'agent-1': { provider: 'Moonshot' } };
+ mockFetchedAgent = { model_parameters: {} };
+ expect(target({ endpoint: EModelEndpoint.agents, agent_id: 'agent-1' }).endpointType).toBe(
+ EModelEndpoint.custom,
+ );
+ });
+ });
+
+ describe('the responses API flag', () => {
+ it('reads it from the fetched agent', () => {
+ mockFetchedAgent = { model_parameters: { useResponsesApi: true } };
+ expect(target({ endpoint: EModelEndpoint.agents, agent_id: 'agent-1' }).useResponsesApi).toBe(
+ true,
+ );
+ });
+
+ it('falls back to the map when the fetched agent omits it', () => {
+ mockAgentsMap = { 'agent-1': { model_parameters: { useResponsesApi: true } } };
+ mockFetchedAgent = { provider: EModelEndpoint.openAI };
+ expect(target({ endpoint: EModelEndpoint.agents, agent_id: 'agent-1' }).useResponsesApi).toBe(
+ true,
+ );
+ });
+
+ it('lets the saved agent override a copied conversation flag', () => {
+ mockAgentsMap = { 'agent-1': { model_parameters: { useResponsesApi: true } } };
+ mockFetchedAgent = { model_parameters: { useResponsesApi: true } };
+ expect(
+ target({
+ endpoint: EModelEndpoint.agents,
+ agent_id: 'agent-1',
+ useResponsesApi: false,
+ }).useResponsesApi,
+ ).toBe(true);
+ });
+
+ it('passes the conversation flag straight through outside the agents endpoint', () => {
+ expect(
+ target({ endpoint: EModelEndpoint.openAI, useResponsesApi: true }).useResponsesApi,
+ ).toBe(true);
+ });
+ });
+
+ describe('endpoint type without an agent', () => {
+ it('resolves a custom endpoint', () => {
+ expect(target({ endpoint: 'Moonshot' }).endpointType).toBe(EModelEndpoint.custom);
+ });
+
+ it('leaves a first-party endpoint alone', () => {
+ expect(target({ endpoint: EModelEndpoint.openAI }).endpointType).toBe(EModelEndpoint.openAI);
+ });
+
+ /* Same endpoint, reached directly or through an agent: the destination has
+ to be the same or a file would upload differently depending on the route. */
+ it('agrees with the agent route for the same custom endpoint', () => {
+ mockAgentsMap = { 'agent-1': { provider: 'Moonshot', model_parameters: {} } };
+ expect(target({ endpoint: EModelEndpoint.agents, agent_id: 'agent-1' }).endpointType).toBe(
+ target({ endpoint: 'Moonshot' }).endpointType,
+ );
+ });
+ });
+
+ describe('the file config the destination is scoped by', () => {
+ it('reads the config of the provider behind the agent, not of the agents endpoint', () => {
+ mockAgentsMap = { 'agent-1': { provider: 'Moonshot', model_parameters: {} } };
+ expect(
+ target({ endpoint: EModelEndpoint.agents, agent_id: 'agent-1' }).endpointFileConfig
+ ?.fileLimit,
+ ).toBe(5);
+ expect(target({ endpoint: EModelEndpoint.agents }).endpointFileConfig?.fileLimit).toBe(20);
+ });
+ });
+
+ describe('whether uploads are offered at all', () => {
+ it('offers them on the agents endpoint', () => {
+ expect(target({ endpoint: EModelEndpoint.agents, agent_id: 'agent-1' }).canAttach).toBe(true);
+ });
+
+ it('offers them on an endpoint that takes files', () => {
+ expect(target({ endpoint: EModelEndpoint.openAI }).canAttach).toBe(true);
+ });
+
+ it('withholds them while the composer is disabled', () => {
+ expect(target({ endpoint: EModelEndpoint.openAI }, true).canAttach).toBe(false);
+ });
+
+ it('withholds them when the endpoint config disables uploads', () => {
+ mockFileConfig = mergeFileConfig({
+ endpoints: { [EModelEndpoint.openAI]: { disabled: true }, default: { fileLimit: 10 } },
+ });
+ expect(target({ endpoint: EModelEndpoint.openAI }).canAttach).toBe(false);
+ });
+ it('withholds uploads until file policy has loaded', () => {
+ mockFileConfigLoaded = false;
+ expect(target({ endpoint: EModelEndpoint.openAI }).canAttach).toBe(false);
+ });
+
+ it('withholds uploads for a saved agent until its provider is known', () => {
+ mockAgentsMap = { agent_1: { model_parameters: {} } };
+ mockFetchedAgent = undefined;
+ expect(target({ endpoint: EModelEndpoint.agents, agent_id: 'agent_1' }).canAttach).toBe(
+ false,
+ );
+ });
+
+ it('does not wait for provider metadata on an ephemeral agent', () => {
+ expect(
+ target({ endpoint: EModelEndpoint.agents, agent_id: 'ephemeral-convo-1' }).canAttach,
+ ).toBe(true);
+ });
+
+ it('withholds them with no conversation at all', () => {
+ expect(target(null).canAttach).toBe(false);
+ });
+
+ it('keeps assistant uploads when the file config fails to load', () => {
+ mockFileConfigLoaded = false;
+ expect(target({ endpoint: EModelEndpoint.assistants }).canAttach).toBe(true);
+ expect(target({ endpoint: EModelEndpoint.azureAssistants }).canAttach).toBe(true);
+ });
+
+ it('still withholds policy-routed uploads when the file config fails to load', () => {
+ mockFileConfigLoaded = false;
+ expect(target({ endpoint: EModelEndpoint.openAI }).canAttach).toBe(false);
+ expect(
+ target({ endpoint: EModelEndpoint.agents, agent_id: 'ephemeral-convo-1' }).canAttach,
+ ).toBe(false);
+ });
+ });
+});
diff --git a/client/src/hooks/Input/__tests__/useChipPacking.spec.tsx b/client/src/hooks/Input/__tests__/useChipPacking.spec.tsx
new file mode 100644
index 0000000000..a03879111d
--- /dev/null
+++ b/client/src/hooks/Input/__tests__/useChipPacking.spec.tsx
@@ -0,0 +1,123 @@
+import React from 'react';
+import { render, act } from '@testing-library/react';
+import useChipPacking from '../useChipPacking';
+
+/**
+ * The chips are reordered from their measured widths, so the interesting cases
+ * are the ones before a measurement exists and the ones after it goes stale.
+ */
+
+/** jsdom lays nothing out, so each chip reports the width it was given. */
+const widthByLabel: Record<string, number> = {};
+Object.defineProperty(HTMLElement.prototype, 'offsetWidth', {
+ configurable: true,
+ get(this: HTMLElement) {
+ return widthByLabel[this.textContent ?? ''] ?? 0;
+ },
+});
+
+interface Chip {
+ key: string;
+}
+
+let seen: string[] = [];
+let measured: Record<string, number> = {};
+
+function Harness({ items }: { items: Chip[] }) {
+ const { ordered, rootRef, widths } = useChipPacking(items);
+ seen = ordered.map((item) => item.key);
+ measured = widths;
+ return (
+ <div ref={rootRef}>
+ {ordered.map((item) => (
+ <span key={item.key} role="listitem">
+ {item.key}
+ </span>
+ ))}
+ </div>
+ );
+}
+
+const chips = (...keys: string[]): Chip[] => keys.map((key) => ({ key }));
+
+describe('useChipPacking', () => {
+ beforeEach(() => {
+ for (const key of Object.keys(widthByLabel)) {
+ delete widthByLabel[key];
+ }
+ seen = [];
+ });
+
+ it('leaves the order alone while nothing can be measured', () => {
+ render(<Harness items={chips('a', 'b', 'c')} />);
+ expect(seen).toEqual(['a', 'b', 'c']);
+ });
+
+ it('puts the widest chip first once every chip has been measured', () => {
+ Object.assign(widthByLabel, { a: 40, b: 120, c: 80 });
+ render(<Harness items={chips('a', 'b', 'c')} />);
+ expect(seen).toEqual(['b', 'c', 'a']);
+ });
+
+ /* A partial sort would shuffle on each pass and never settle, so a chip that
+ has not been measured holds the whole order back. */
+ it('waits for the last chip rather than sorting what it has', () => {
+ Object.assign(widthByLabel, { a: 40, b: 120 });
+ render(<Harness items={chips('a', 'b', 'c')} />);
+ expect(seen).toEqual(['a', 'b', 'c']);
+ });
+
+ it('settles instead of oscillating', () => {
+ Object.assign(widthByLabel, { a: 40, b: 120, c: 80 });
+ const { rerender } = render(<Harness items={chips('a', 'b', 'c')} />);
+ const settled = seen;
+ rerender(<Harness items={chips('a', 'b', 'c')} />);
+ expect(seen).toEqual(settled);
+ });
+
+ it('reorders when a chip joins', () => {
+ Object.assign(widthByLabel, { a: 40, b: 120, c: 80, d: 200 });
+ const items = chips('a', 'b', 'c');
+ const { rerender } = render(<Harness items={items} />);
+ expect(seen).toEqual(['b', 'c', 'a']);
+
+ act(() => {
+ rerender(<Harness items={chips('a', 'b', 'c', 'd')} />);
+ });
+ expect(seen).toEqual(['d', 'b', 'c', 'a']);
+ });
+
+ /* Widths are keyed by chip id and would otherwise outlive the chip, growing
+ with every chip the composer has ever shown. */
+ it('forgets the width of a chip that left', () => {
+ Object.assign(widthByLabel, { a: 40, b: 120, c: 80 });
+ const { rerender } = render(<Harness items={chips('a', 'b', 'c')} />);
+ expect(Object.keys(measured).sort()).toEqual(['a', 'b', 'c']);
+
+ act(() => {
+ rerender(<Harness items={chips('a', 'c')} />);
+ });
+ expect(Object.keys(measured).sort()).toEqual(['a', 'c']);
+ });
+
+ it('re-measures a chip that left and came back narrower', () => {
+ Object.assign(widthByLabel, { a: 40, b: 120, c: 80 });
+ const { rerender } = render(<Harness items={chips('a', 'b', 'c')} />);
+ expect(seen).toEqual(['b', 'c', 'a']);
+
+ act(() => {
+ rerender(<Harness items={chips('a', 'c')} />);
+ });
+
+ widthByLabel.b = 10;
+ act(() => {
+ rerender(<Harness items={chips('a', 'b', 'c')} />);
+ });
+ expect(seen).toEqual(['c', 'a', 'b']);
+ });
+
+ it('handles an empty list', () => {
+ render(<Harness items={[]} />);
+ expect(seen).toEqual([]);
+ });
+});
diff --git a/client/src/hooks/Input/__tests__/useComposerHint.spec.ts b/client/src/hooks/Input/__tests__/useComposerHint.spec.ts
new file mode 100644
index 0000000000..57ea6393ee
--- /dev/null
+++ b/client/src/hooks/Input/__tests__/useComposerHint.spec.ts
@@ -0,0 +1,236 @@
+import type { ComposerHintState } from '../useComposerHint';
+import { composeHint } from '../useComposerHint';
+
+/** Echoes the key so assertions read against the key, not English copy. */
+const localize = ((key: string, options?: Record<string, string | number>) =>
+ options ? `${key}:${options[0] ?? options.count}` : key) as Parameters<typeof composeHint>[1];
+
+const baseState: ComposerHintState = {
+ hasText: false,
+ isSubmitting: false,
+ duringRunActive: false,
+ /** The common case: the epoch has landed, so the run is reachable. The
+ * pre-epoch window is exercised explicitly below. */
+ canControlGeneration: true,
+ duringRunAction: 'queue' as const,
+ canSteer: true,
+ answerModeActive: false,
+ uploadingCount: 0,
+ enterToSend: true,
+ idleActions: { prompts: true, mentions: true, attach: true },
+};
+
+/** What `useShortcutDisplay('stopGenerating')` resolves to by default on a Mac. */
+const STOP = '⌘ ⇧ X';
+
+const hint = (
+ overrides: Partial<ComposerHintState>,
+ isMac = true,
+ stop = STOP,
+ altEnterInterrupt = true,
+) =>
+ composeHint({ ...baseState, ...overrides }, localize, isMac, stop, undefined, altEnterInterrupt)
+ .text;
+
+const kindOf = (overrides: Partial<ComposerHintState>) =>
+ composeHint({ ...baseState, ...overrides }, localize, true, STOP).kind;
+
+describe('composeHint', () => {
+ it('shows discovery affordances on an untouched composer', () => {
+ expect(hint({})).toBe(
+ 'com_ui_composer_hint_prompts · com_ui_composer_hint_mentions · com_ui_composer_hint_attach',
+ );
+ });
+
+ /* The hint is also the textarea's description, so an affordance the
+ composer would refuse is named to screen-reader users as if it worked. */
+ it('names only the idle affordances that act', () => {
+ expect(hint({ idleActions: { prompts: false, mentions: true, attach: true } })).toBe(
+ 'com_ui_composer_hint_mentions · com_ui_composer_hint_attach',
+ );
+ expect(hint({ idleActions: { prompts: true, mentions: false, attach: false } })).toBe(
+ 'com_ui_composer_hint_prompts',
+ );
+ expect(hint({ idleActions: { prompts: false, mentions: false, attach: false } })).toBe('');
+ });
+
+ it('switches to send/newline once there is text', () => {
+ expect(hint({ hasText: true })).toBe('com_ui_composer_hint_typing');
+ });
+
+ /* The line used to read "Esc to stop", which no handler anywhere implements:
+ stopping is bound to the `stopGenerating` shortcut, and the user can rebind
+ it. Naming a key the composer does not answer to is worse than naming none. */
+ it('names the live stop binding while generating with an empty composer', () => {
+ expect(hint({ isSubmitting: true })).toBe('⌘ ⇧ X com_ui_composer_hint_stop');
+ expect(hint({ isSubmitting: true }, false, 'Ctrl+Shift+X')).toBe(
+ 'Ctrl+Shift+X com_ui_composer_hint_stop',
+ );
+ });
+
+ it('names no stop key until the stop control can act', () => {
+ expect(hint({ isSubmitting: true, canStop: false })).toBe('com_ui_composer_hint_running');
+ expect(hint({ isSubmitting: true, canStop: true })).toBe('⌘ ⇧ X com_ui_composer_hint_stop');
+ });
+
+ it('names no key at all once the binding is cleared', () => {
+ expect(hint({ isSubmitting: true }, true, '')).toBe('com_ui_composer_hint_running');
+ });
+
+ describe('during a run with text', () => {
+ it('leads with queue when queue is the default', () => {
+ const result = hint({ duringRunActive: true, hasText: true, isSubmitting: true });
+ expect(result).toContain('com_ui_composer_hint_queue_default');
+ expect(result).toContain('com_ui_composer_hint_send_now');
+ expect(result).toContain('com_ui_composer_hint_interrupt');
+ });
+
+ it('leads with steer when the setting is flipped', () => {
+ const result = hint({
+ duringRunActive: true,
+ hasText: true,
+ isSubmitting: true,
+ duringRunAction: 'steer',
+ });
+ expect(result).toContain('com_ui_composer_hint_steer');
+ expect(result).toContain('com_ui_composer_hint_queue');
+ expect(result).toContain('com_ui_composer_hint_interrupt');
+ });
+
+ it('uses platform-appropriate modifier glyphs', () => {
+ const state = { duringRunActive: true, hasText: true, isSubmitting: true };
+ expect(hint(state, true)).toContain('⌘⏎');
+ expect(hint(state, true)).toContain('⌥⏎');
+ expect(hint(state, false)).toContain('Ctrl+⏎');
+ expect(hint(state, false)).toContain('Alt+⏎');
+ });
+
+ it('falls back to stop when the modifiers have no text to act on', () => {
+ expect(hint({ duringRunActive: true, hasText: false, isSubmitting: true })).toBe(
+ '⌘ ⇧ X com_ui_composer_hint_stop',
+ );
+ });
+
+ /* `isSubmitting` flips the moment the user sends, but the start POST
+ installs the generation epoch a beat later. Through that window every
+ chord that reaches the live run refuses, so naming them would point at
+ keys that do nothing. Queueing is local and keeps working. */
+ describe('before the generation epoch lands', () => {
+ const preEpoch = {
+ duringRunActive: true,
+ hasText: true,
+ isSubmitting: true,
+ canControlGeneration: false,
+ };
+
+ it('promises only the queue, which is the one action that still works', () => {
+ expect(hint(preEpoch)).toBe('com_ui_composer_hint_queue_default');
+ });
+
+ it('names no chord that would refuse', () => {
+ const result = hint(preEpoch);
+ expect(result).not.toContain('com_ui_composer_hint_send_now');
+ expect(result).not.toContain('com_ui_composer_hint_interrupt');
+ expect(result).not.toContain('⌥⏎');
+ });
+
+ it('still names the chord when it IS the queue action', () => {
+ expect(hint({ ...preEpoch, enterToSend: false })).toBe(
+ '⌘⏎ com_ui_composer_hint_queue_verb',
+ );
+ });
+
+ it('restores the full line once the epoch arrives', () => {
+ const result = hint({ ...preEpoch, canControlGeneration: true });
+ expect(result).toContain('com_ui_composer_hint_send_now');
+ expect(result).toContain('com_ui_composer_hint_interrupt');
+ });
+
+ /* A submit rebound to Alt+Enter, a chord yielded to a global shortcut,
+ or disabled shortcuts each make the chord do something else; the hint
+ follows the same verdict the during-run button reads. */
+ it('omits the interrupt chord when the resolver no longer returns it', () => {
+ const result = hint({ ...preEpoch, canControlGeneration: true }, true, STOP, false);
+ expect(result).not.toContain('com_ui_composer_hint_interrupt');
+ expect(result).not.toContain('⌥⏎');
+ expect(result).toContain('com_ui_composer_hint_send_now');
+ });
+ });
+ });
+
+ describe('with Enter bound to a newline', () => {
+ it('names the chord as the send key while typing', () => {
+ const result = hint({ hasText: true, enterToSend: false });
+ expect(result).toContain('⌘⏎');
+ expect(result).toContain('com_ui_composer_hint_send');
+ expect(result).toContain('com_ui_composer_hint_newline');
+ expect(result).not.toContain('com_ui_composer_hint_typing');
+ });
+
+ it('names only the newline key once the send binding is cleared', () => {
+ const result = composeHint(
+ { ...baseState, hasText: true, enterToSend: false },
+ localize,
+ true,
+ STOP,
+ { customized: true, display: '' },
+ ).text;
+ expect(result).toBe('⏎ com_ui_composer_hint_newline');
+ });
+
+ it('drops the alternate during-run action, which the chord no longer reaches', () => {
+ const result = hint({
+ duringRunActive: true,
+ hasText: true,
+ isSubmitting: true,
+ duringRunAction: 'steer',
+ enterToSend: false,
+ });
+ expect(result).toContain('⌘⏎ com_ui_composer_hint_steer_verb');
+ expect(result).toContain('com_ui_composer_hint_interrupt');
+ expect(result).not.toContain('com_ui_composer_hint_queue');
+ });
+ });
+
+ describe('kind', () => {
+ it('marks the ambient copy as a tip, so a conversation can drop it', () => {
+ expect(kindOf({})).toBe('tip');
+ expect(kindOf({ hasText: true })).toBe('tip');
+ });
+
+ it('marks anything happening right now as state, which always shows', () => {
+ expect(kindOf({ isSubmitting: true })).toBe('state');
+ expect(kindOf({ uploadingCount: 1 })).toBe('state');
+ expect(kindOf({ answerModeActive: true })).toBe('state');
+ expect(kindOf({ duringRunActive: true, hasText: true })).toBe('state');
+ });
+ });
+
+ describe('precedence', () => {
+ it('lets a paused question outrank every other state', () => {
+ expect(
+ hint({
+ answerModeActive: true,
+ hasText: true,
+ isSubmitting: true,
+ duringRunActive: true,
+ uploadingCount: 3,
+ }),
+ ).toBe('com_ui_composer_hint_answer');
+ });
+
+ it('reports uploads ahead of the during-run modifiers', () => {
+ expect(hint({ uploadingCount: 2, duringRunActive: true, hasText: true })).toBe(
+ 'com_ui_composer_hint_uploading:2',
+ );
+ /* One file is one file, not "1 file(s)". */
+ expect(hint({ uploadingCount: 1, duringRunActive: true, hasText: true })).toBe(
+ 'com_ui_composer_hint_uploading_one:1',
+ );
+ });
+
+ it('stops reporting uploads once they settle', () => {
+ expect(hint({ uploadingCount: 0, hasText: true })).toBe('com_ui_composer_hint_typing');
+ });
+ });
+});
diff --git a/client/src/hooks/Input/__tests__/useComposerItems.spec.tsx b/client/src/hooks/Input/__tests__/useComposerItems.spec.tsx
new file mode 100644
index 0000000000..8accb68589
--- /dev/null
+++ b/client/src/hooks/Input/__tests__/useComposerItems.spec.tsx
@@ -0,0 +1,87 @@
+import React from 'react';
+import { act, renderHook } from '@testing-library/react';
+import { RecoilRoot, useRecoilValue, type MutableSnapshot } from 'recoil';
+import useComposerItems from '../useComposerItems';
+import store from '~/store';
+
+/**
+ * The tray's staged context. Removal is the whole surface here, and quotes are
+ * addressed by position, which is the way to dismiss the wrong one.
+ */
+
+const CONVO_ID = 'convo-items';
+
+function setup(initialize?: (snapshot: MutableSnapshot) => void) {
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
+ <RecoilRoot initializeState={initialize}>{children}</RecoilRoot>
+ );
+ return renderHook(
+ () => ({
+ items: useComposerItems(CONVO_ID),
+ quotes: useRecoilValue(store.pendingQuotesByConvoId(CONVO_ID)),
+ skills: useRecoilValue(store.pendingManualSkillsByConvoId(CONVO_ID)),
+ }),
+ { wrapper },
+ );
+}
+
+const withStaged = (quotes: string[], skills: string[] = []) =>
+ setup(({ set }) => {
+ set(store.pendingQuotesByConvoId(CONVO_ID), quotes);
+ set(store.pendingManualSkillsByConvoId(CONVO_ID), skills);
+ });
+
+describe('useComposerItems', () => {
+ it('stages nothing for an untouched composer', () => {
+ expect(setup().result.current.items).toEqual([]);
+ });
+
+ it('lists quotes ahead of skills', () => {
+ const { result } = withStaged(['a quote'], ['writer']);
+ expect(result.current.items.map((item) => item.kind)).toEqual(['quote', 'skill']);
+ expect(result.current.items.map((item) => item.label)).toEqual(['a quote', 'writer']);
+ });
+
+ it('removes the quote that was dismissed, not the first one', () => {
+ const { result } = withStaged(['first', 'second', 'third']);
+ act(() => result.current.items[1].remove());
+ expect(result.current.quotes).toEqual(['first', 'third']);
+ });
+
+ it('removes a skill by name', () => {
+ const { result } = withStaged([], ['writer', 'researcher']);
+ act(() => result.current.items[1].remove());
+ expect(result.current.skills).toEqual(['writer']);
+ });
+
+ /* Two identical excerpts are two separate stagings, and dismissing one has to
+ leave the other alone. */
+ it('keeps two identical quotes separately removable', () => {
+ const { result } = withStaged(['same words', 'same words']);
+ expect(new Set(result.current.items.map((item) => item.id)).size).toBe(2);
+
+ act(() => result.current.items[0].remove());
+ expect(result.current.quotes).toEqual(['same words']);
+ });
+
+ it('keeps repeated quote ids distinct from literal suffix text', () => {
+ const { result } = withStaged(['same words', 'same words', 'same words#1']);
+ expect(new Set(result.current.items.map((item) => item.id)).size).toBe(3);
+ });
+
+ /* An index inside the id rewrote every id after a removal, which remounts
+ those chips and drops focus off whichever one was being used. */
+ it('leaves the ids of the surviving chips alone', () => {
+ const { result } = withStaged(['first', 'second', 'third']);
+ const before = result.current.items.map((item) => item.id);
+
+ act(() => result.current.items[0].remove());
+ expect(result.current.items.map((item) => item.id)).toEqual(before.slice(1));
+ });
+
+ it('carries the full text for a chip that has to truncate it', () => {
+ const long = 'a quote long enough that the chip will have to cut it short somewhere';
+ const { result } = withStaged([long]);
+ expect(result.current.items[0].title).toBe(long);
+ });
+});
diff --git a/client/src/hooks/Input/__tests__/useComposerRestore.spec.tsx b/client/src/hooks/Input/__tests__/useComposerRestore.spec.tsx
new file mode 100644
index 0000000000..4e50429b24
--- /dev/null
+++ b/client/src/hooks/Input/__tests__/useComposerRestore.spec.tsx
@@ -0,0 +1,292 @@
+import React from 'react';
+import { RecoilRoot } from 'recoil';
+import { act, renderHook } from '@testing-library/react';
+import { ReasoningEffort } from 'librechat-data-provider';
+import { Provider as JotaiProvider, createStore } from 'jotai';
+import type { TMessage } from 'librechat-data-provider';
+import type { MutableSnapshot } from 'recoil';
+import type { ExtendedFile } from '~/common';
+import { pendingReasoningOverrideFamily } from '~/components/Chat/Input/Composer/state';
+import useComposerRestore from '../useComposerRestore';
+import store from '~/store';
+
+/**
+ * The guarded restore is the one path in the composer that can destroy text
+ * outright: it reports back whether it took the words, and a `true` it did not
+ * earn makes the caller drop them. Every refusal below is a round-trip that
+ * resolved into a composer that had moved on since the click.
+ */
+
+const CONVO_ID = 'convo-restore';
+const OTHER_CONVO = 'convo-elsewhere';
+
+const stagedFile = (file_id: string): ExtendedFile =>
+ ({ file_id, progress: 1, size: 1 }) as ExtendedFile;
+
+function setup({
+ conversationId = CONVO_ID,
+ draft = '',
+ files = new Map<string, ExtendedFile>(),
+ answerModeActive = false,
+ reasoningOverride,
+ initialize,
+}: {
+ conversationId?: string;
+ draft?: string;
+ files?: Map<string, ExtendedFile>;
+ answerModeActive?: boolean;
+ reasoningOverride?: TMessage['reasoningOverride'];
+ initialize?: (snapshot: MutableSnapshot) => void;
+} = {}) {
+ let text = draft;
+ const setFiles = jest.fn();
+ const methods = {
+ setValue: jest.fn((_name: string, value: string) => {
+ text = value;
+ }),
+ getValues: jest.fn(() => text),
+ };
+ const textAreaRef = { current: { focus: jest.fn() } };
+ const reasoningStore = createStore();
+ reasoningStore.set(pendingReasoningOverrideFamily(conversationId), reasoningOverride);
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
+ <JotaiProvider store={reasoningStore}>
+ <RecoilRoot initializeState={initialize}>{children}</RecoilRoot>
+ </JotaiProvider>
+ );
+ const view = renderHook(
+ (props: { conversationId: string; answerModeActive: boolean }) =>
+ useComposerRestore({
+ conversationId: props.conversationId,
+ methods: methods as never,
+ files,
+ setFiles,
+ textAreaRef: textAreaRef as never,
+ answerModeActive: props.answerModeActive,
+ }),
+ { wrapper, initialProps: { conversationId, answerModeActive } },
+ );
+ return { ...view, methods, setFiles, textAreaRef, reasoningStore, currentText: () => text };
+}
+
+const reclaim = (result: { current: ReturnType<typeof useComposerRestore> }, origin = CONVO_ID) =>
+ result.current.restoreReclaimedSteer('reclaimed words', [], {}, origin);
+
+describe('useComposerRestore', () => {
+ describe('restoreReclaimedSteer', () => {
+ it('takes the words into an empty composer', () => {
+ const { result, currentText, textAreaRef } = setup();
+ let taken = false;
+ act(() => {
+ taken = reclaim(result);
+ });
+ expect(taken).toBe(true);
+ expect(currentText()).toBe('reclaimed words');
+ expect(textAreaRef.current.focus).toHaveBeenCalled();
+ });
+
+ it('refuses rather than overwrite a draft typed while the reclaim was in flight', () => {
+ const { result, currentText } = setup({ draft: 'something I was writing' });
+ let taken = true;
+ act(() => {
+ taken = reclaim(result);
+ });
+ expect(taken).toBe(false);
+ expect(currentText()).toBe('something I was writing');
+ });
+
+ /* Whitespace is not a draft: refusing on it would strand the words for the
+ sake of a stray space. */
+ it('takes the words over a whitespace-only draft', () => {
+ const { result } = setup({ draft: ' \n ' });
+ let taken = false;
+ act(() => {
+ taken = reclaim(result);
+ });
+ expect(taken).toBe(true);
+ });
+
+ it('refuses when a file has been staged since', () => {
+ const { result } = setup({ files: new Map([['f1', stagedFile('f1')]]) });
+ let taken = true;
+ act(() => {
+ taken = reclaim(result);
+ });
+ expect(taken).toBe(false);
+ });
+
+ /* A quote or a skill pick is staged context the restore would MERGE with,
+ gluing two submissions together: the box being empty is not enough. */
+ it.each([
+ [
+ 'a quote',
+ (snapshot: MutableSnapshot) =>
+ snapshot.set(store.pendingQuotesByConvoId(CONVO_ID), ['an excerpt']),
+ ],
+ [
+ 'a skill pick',
+ (snapshot: MutableSnapshot) =>
+ snapshot.set(store.pendingManualSkillsByConvoId(CONVO_ID), ['writer']),
+ ],
+ ])('refuses when %s is staged', (_label, initialize) => {
+ const { result } = setup({ initialize });
+ let taken = true;
+ act(() => {
+ taken = reclaim(result);
+ });
+ expect(taken).toBe(false);
+ });
+
+ it('refuses when a reasoning override is staged', () => {
+ const { result } = setup({
+ reasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.high },
+ });
+ let taken = true;
+ act(() => {
+ taken = reclaim(result);
+ });
+ expect(taken).toBe(false);
+ });
+
+ /* One form object is reused across conversations, so a restore that does
+ not check would write the old chat's steer into the new chat's box. */
+ it('refuses once the user has navigated to another chat', () => {
+ const { result, rerender, currentText } = setup();
+ rerender({ conversationId: OTHER_CONVO, answerModeActive: false });
+ let taken = true;
+ act(() => {
+ taken = reclaim(result, CONVO_ID);
+ });
+ expect(taken).toBe(false);
+ expect(currentText()).toBe('');
+ });
+
+ /* The origin is read live, not captured: the same steer restored after the
+ user came BACK to its chat is still its chat. */
+ it('takes the words again once the user returns to the origin chat', () => {
+ const { result, rerender } = setup();
+ rerender({ conversationId: OTHER_CONVO, answerModeActive: false });
+ rerender({ conversationId: CONVO_ID, answerModeActive: false });
+ let taken = false;
+ act(() => {
+ taken = reclaim(result, CONVO_ID);
+ });
+ expect(taken).toBe(true);
+ });
+
+ /* Answer mode owns the composer: `onSubmit` hands its text to the paused
+ question, so a restore here becomes the tool's answer on the next Enter. */
+ it('refuses while a question pause owns the composer', () => {
+ const { result, rerender, currentText } = setup();
+ /* The pause can begin mid-reclaim, so the flag is read live rather than
+ captured when the restore was handed out. */
+ rerender({ conversationId: CONVO_ID, answerModeActive: true });
+ let taken = true;
+ act(() => {
+ taken = reclaim(result);
+ });
+ expect(taken).toBe(false);
+ expect(currentText()).toBe('');
+ });
+
+ /* Its refs still hold the origin chat after unmount, so every check above
+ would pass and the restore would report success into a dead form. */
+ it('refuses after the composer has unmounted', () => {
+ const { result, unmount } = setup();
+ unmount();
+ let taken = true;
+ act(() => {
+ taken = reclaim(result);
+ });
+ expect(taken).toBe(false);
+ });
+ });
+
+ describe('editToComposer', () => {
+ it('replaces the draft outright, unlike the guarded restore', () => {
+ const { result, currentText } = setup({ draft: 'half a thought' });
+ let taken = false;
+ act(() => {
+ taken = result.current.editToComposer('the queued message');
+ });
+ expect(taken).toBe(true);
+ expect(currentText()).toBe('the queued message');
+ });
+
+ /* The one thing it refuses: while a question pause is live the composer is
+ the answer box, so a queued message dropped in here reads as a draft and
+ answers the tool on the next Enter instead of being edited. */
+ it('refuses while a paused question owns the composer', () => {
+ const { result, currentText, setFiles } = setup({ answerModeActive: true });
+ let taken = true;
+ act(() => {
+ taken = result.current.editToComposer('the queued message', [
+ { file_id: 'f1', filename: 'notes.pdf', filepath: '/f1', type: 'application/pdf' },
+ ]);
+ });
+ expect(taken).toBe(false);
+ expect(currentText()).toBe('');
+ expect(setFiles).not.toHaveBeenCalled();
+ });
+
+ /* A question can start pausing the run between render and click. */
+ it('refuses on a pause that started after the last render it was read in', () => {
+ const { result, rerender, currentText } = setup();
+ rerender({ conversationId: CONVO_ID, answerModeActive: true });
+ let taken = true;
+ act(() => {
+ taken = result.current.editToComposer('too late');
+ });
+ expect(taken).toBe(false);
+ expect(currentText()).toBe('');
+ });
+
+ it('restores attachments as already-uploaded entries with delivery metadata', () => {
+ const { result, setFiles } = setup();
+ act(() => {
+ result.current.editToComposer('with a file', [
+ {
+ file_id: 'f9',
+ filename: 'notes.docx',
+ filepath: '/f9',
+ type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
+ llmDeliveryPath: 'text',
+ },
+ ]);
+ });
+ const next = setFiles.mock.calls[0][0](new Map()) as Map<string, ExtendedFile>;
+ expect(next.get('f9')).toEqual(
+ expect.objectContaining({
+ file_id: 'f9',
+ progress: 1,
+ attached: true,
+ llmDeliveryPath: 'text',
+ }),
+ );
+ });
+
+ it('restores the request-scoped reasoning override', () => {
+ const { result, reasoningStore } = setup();
+ act(() => {
+ result.current.editToComposer('reason about this', undefined, {
+ reasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.high },
+ });
+ });
+ expect(reasoningStore.get(pendingReasoningOverrideFamily(CONVO_ID))).toEqual({
+ key: 'reasoning_effort',
+ value: ReasoningEffort.high,
+ });
+ });
+
+ /* Skipped rather than stored under `undefined`, which would put an
+ unremovable card in the tray. */
+ it('skips an attachment with no id', () => {
+ const { result, setFiles } = setup();
+ act(() => {
+ result.current.editToComposer('with a broken file', [{ filename: 'ghost' } as never]);
+ });
+ const next = setFiles.mock.calls[0][0](new Map()) as Map<string, ExtendedFile>;
+ expect(next.size).toBe(0);
+ });
+ });
+});
diff --git a/client/src/hooks/Input/__tests__/useDictation.spec.tsx b/client/src/hooks/Input/__tests__/useDictation.spec.tsx
new file mode 100644
index 0000000000..8942879f84
--- /dev/null
+++ b/client/src/hooks/Input/__tests__/useDictation.spec.tsx
@@ -0,0 +1,503 @@
+import { act, renderHook } from '@testing-library/react';
+import type { TAskFunction } from '~/common';
+import useDictation from '../useDictation';
+
+/**
+ * The engines only report a completed transcription when Auto Send Text is
+ * configured, so the composer's own stop-and-send cannot be built on that
+ * callback alone. These cases pin the three ways a take can be spent, sent on
+ * request, sent by the setting, or thrown away, against both engines.
+ */
+
+let mockSpeechEndpoint: 'browser' | 'external';
+let mockSetTextCallback: (text: string) => void;
+let mockOnTranscriptionComplete: (text: string) => void;
+let mockOnTranscriptionSettled: () => void;
+const mockStart = jest.fn();
+const mockStop = jest.fn();
+const mockAbort = jest.fn();
+let mockIsListening: boolean;
+let mockIsLoading: boolean;
+
+jest.mock('../useSpeechToText', () => ({
+ __esModule: true,
+ default: (
+ setText: (text: string) => void,
+ complete: (text: string) => void,
+ settled: () => void,
+ ) => {
+ mockSetTextCallback = setText;
+ mockOnTranscriptionComplete = complete;
+ mockOnTranscriptionSettled = settled;
+ return {
+ isListening: mockIsListening,
+ isLoading: mockIsLoading,
+ startRecording: mockStart,
+ stopRecording: mockStop,
+ abortRecording: mockAbort,
+ };
+ },
+}));
+
+jest.mock('../useGetAudioSettings', () => ({
+ __esModule: true,
+ default: () => ({ speechToTextEndpoint: mockSpeechEndpoint }),
+}));
+
+const mockShowToast = jest.fn();
+
+jest.mock('@librechat/client', () => ({
+ useToastContext: () => ({ showToast: mockShowToast }),
+}));
+
+jest.mock('../../useLocalize', () => ({
+ __esModule: true,
+ default: () => (key: string) => key,
+}));
+
+const ask = jest.fn(() => true) as unknown as jest.Mock & TAskFunction;
+
+function setup({
+ autoSendText = -1,
+ speechToText = true,
+ draft = '',
+ isSubmitting = false,
+ filesLoading = false,
+ deferComposerReset = false,
+ disabled = false,
+ index,
+}: {
+ autoSendText?: number;
+ speechToText?: boolean;
+ draft?: string;
+ isSubmitting?: boolean;
+ filesLoading?: boolean;
+ deferComposerReset?: boolean;
+ disabled?: boolean;
+ index?: number;
+} = {}) {
+ let text = draft;
+ let uploading = filesLoading;
+ const methods = {
+ setValue: jest.fn((_name: string, value: string) => {
+ text = value;
+ }),
+ reset: jest.fn((values: { text: string }) => {
+ text = values.text;
+ }),
+ getValues: jest.fn(() => text),
+ };
+ const view = renderHook(() => {
+ const dictationOptions = {
+ ask: ask as unknown as TAskFunction,
+ methods: methods as never,
+ isSubmitting,
+ filesLoading: uploading,
+ deferComposerReset,
+ disabled,
+ autoSendText,
+ speechToText,
+ index,
+ };
+ return useDictation(dictationOptions);
+ });
+ return {
+ ...view,
+ methods,
+ currentText: () => text,
+ setFilesLoading: (value: boolean) => {
+ uploading = value;
+ },
+ };
+}
+
+/** Ends the take the way an engine does: listening clears, then the engine
+ * reports that its final transcript has landed. */
+const settle = async (rerender: () => void) => {
+ mockIsListening = false;
+ act(() => {
+ rerender();
+ });
+ act(() => mockOnTranscriptionSettled());
+};
+
+describe('useDictation', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ jest.useFakeTimers();
+ mockSpeechEndpoint = 'browser';
+ mockIsListening = false;
+ mockIsLoading = false;
+ });
+
+ afterEach(() => {
+ jest.useRealTimers();
+ });
+
+ it('sends on stop-and-send even with Auto Send Text off, which reports no transcription', async () => {
+ const { result, rerender, currentText } = setup();
+ act(() => result.current.start());
+ mockIsListening = true;
+ act(() => rerender());
+
+ act(() => mockSetTextCallback('take me somewhere'));
+ act(() => result.current.stopAndSend());
+ await settle(rerender);
+
+ expect(ask).toHaveBeenCalledWith({ text: 'take me somewhere' });
+ expect(currentText()).toBe('');
+ });
+
+ it('waits for the final browser transcript before sending', async () => {
+ const { result, rerender } = setup();
+ act(() => result.current.start());
+ mockIsListening = true;
+ act(() => rerender());
+
+ act(() => mockSetTextCallback('interim words'));
+ act(() => result.current.stopAndSend());
+ mockIsListening = false;
+ act(() => rerender());
+
+ expect(ask).not.toHaveBeenCalled();
+ act(() => mockSetTextCallback('final words'));
+ act(() => mockOnTranscriptionSettled());
+
+ expect(ask).toHaveBeenCalledWith({ text: 'final words' });
+ });
+
+ it('owns the Shift+Alt+L shortcut through the dictation lifecycle', () => {
+ const { result, rerender } = setup();
+
+ act(() => {
+ window.dispatchEvent(
+ new KeyboardEvent('keydown', { code: 'KeyL', shiftKey: true, altKey: true }),
+ );
+ });
+ expect(mockStart).toHaveBeenCalledTimes(1);
+
+ mockIsListening = true;
+ act(() => rerender());
+ act(() => {
+ window.dispatchEvent(
+ new KeyboardEvent('keydown', { code: 'KeyL', shiftKey: true, altKey: true }),
+ );
+ });
+
+ expect(mockStop).toHaveBeenCalledTimes(1);
+ expect(result.current.transcribing).toBe(true);
+ });
+
+ it('answers the shortcut only in the pane that holds focus', () => {
+ setup({ index: 1 });
+ const pressShortcut = () =>
+ act(() => {
+ window.dispatchEvent(
+ new KeyboardEvent('keydown', { code: 'KeyL', shiftKey: true, altKey: true }),
+ );
+ });
+ const pane = (index: number) => {
+ const section = document.createElement('section');
+ section.dataset.chatPane = String(index);
+ const input = document.createElement('input');
+ section.appendChild(input);
+ document.body.appendChild(section);
+ return { section, input };
+ };
+ const first = pane(0);
+ const second = pane(1);
+
+ pressShortcut();
+ first.input.focus();
+ pressShortcut();
+ expect(mockStart).not.toHaveBeenCalled();
+
+ second.input.focus();
+ pressShortcut();
+ expect(mockStart).toHaveBeenCalledTimes(1);
+
+ first.section.remove();
+ second.section.remove();
+ });
+
+ it('refuses both direct and shortcut starts while the host disables speech', () => {
+ const { result } = setup({ disabled: true });
+
+ act(() => result.current.start());
+ act(() => {
+ window.dispatchEvent(
+ new KeyboardEvent('keydown', { code: 'KeyL', shiftKey: true, altKey: true }),
+ );
+ });
+
+ expect(result.current.startDisabled).toBe(true);
+ expect(mockStart).not.toHaveBeenCalled();
+ });
+
+ it('leaves a plain stop in the composer', async () => {
+ const { result, rerender, currentText } = setup();
+ act(() => result.current.start());
+ mockIsListening = true;
+ act(() => rerender());
+
+ act(() => mockSetTextCallback('just a draft'));
+ act(() => result.current.stopToComposer());
+ await settle(rerender);
+
+ expect(ask).not.toHaveBeenCalled();
+ expect(currentText()).toBe('just a draft');
+ });
+
+ it('still honours Auto Send Text on a plain stop', async () => {
+ const { result, rerender } = setup({ autoSendText: 0 });
+ act(() => result.current.start());
+ mockIsListening = true;
+ act(() => rerender());
+
+ act(() => result.current.stopToComposer());
+ await settle(rerender);
+ act(() => mockOnTranscriptionComplete('send this for me'));
+
+ expect(ask).toHaveBeenCalledWith({ text: 'send this for me' });
+ });
+
+ it('spends a take once when the setting and the send button both reach it', async () => {
+ const { result, rerender } = setup({ autoSendText: 0 });
+ act(() => result.current.start());
+ mockIsListening = true;
+ act(() => rerender());
+
+ act(() => mockSetTextCallback('only once'));
+ act(() => result.current.stopAndSend());
+ await settle(rerender);
+ act(() => mockOnTranscriptionComplete('only once'));
+
+ expect(ask).toHaveBeenCalledTimes(1);
+ });
+
+ it('retains an accepted transcript until its deferred reset is confirmed', async () => {
+ const { result, rerender, currentText, methods } = setup({ deferComposerReset: true });
+ act(() => result.current.start());
+ mockIsListening = true;
+ act(() => rerender());
+
+ act(() => mockSetTextCallback('answer after confirmation'));
+ act(() => result.current.stopAndSend());
+ await settle(rerender);
+
+ expect(ask).toHaveBeenCalledWith({ text: 'answer after confirmation' });
+ expect(currentText()).toBe('answer after confirmation');
+ expect(methods.reset).not.toHaveBeenCalled();
+
+ act(() => mockOnTranscriptionComplete('answer after confirmation'));
+ expect(ask).toHaveBeenCalledTimes(1);
+ });
+
+ /* The bar disables stop and send once a take is being transcribed, and the
+ hook refuses them too: a second stop would rewrite how a take that was
+ already committed gets spent. */
+ it('ignores a stop that arrives after the take has ended', async () => {
+ const { result, rerender, currentText } = setup();
+ act(() => result.current.start());
+ mockIsListening = true;
+ act(() => rerender());
+
+ act(() => mockSetTextCallback('already committed'));
+ act(() => result.current.stopToComposer());
+ mockIsListening = false;
+ act(() => rerender());
+
+ mockStop.mockClear();
+ act(() => result.current.stopAndSend());
+ await settle(rerender);
+
+ expect(mockStop).not.toHaveBeenCalled();
+ expect(ask).not.toHaveBeenCalled();
+ expect(currentText()).toBe('already committed');
+ });
+
+ it('keeps the draft when a cancelled external transcription lands anyway', async () => {
+ mockSpeechEndpoint = 'external';
+ const { result, rerender, currentText } = setup({ draft: 'my unsent draft' });
+ act(() => result.current.start());
+ mockIsListening = true;
+ act(() => rerender());
+
+ act(() => result.current.cancel());
+ expect(currentText()).toBe('my unsent draft');
+
+ /* The mutation was already in flight, so aborting the recorder cannot stop
+ its success callback from arriving. */
+ act(() => mockOnTranscriptionComplete('words nobody asked for'));
+
+ expect(ask).not.toHaveBeenCalled();
+ expect(currentText()).toBe('my unsent draft');
+ });
+
+ it('exits a cancelled external transcription while its request is still loading', () => {
+ mockSpeechEndpoint = 'external';
+ const { result, rerender, currentText } = setup({ draft: 'my unsent draft' });
+ act(() => result.current.start());
+ mockIsListening = false;
+ mockIsLoading = true;
+ act(() => rerender());
+
+ expect(result.current.transcribing).toBe(true);
+ act(() => result.current.cancel());
+
+ expect(result.current.transcribing).toBe(false);
+ expect(result.current.startDisabled).toBe(true);
+ expect(currentText()).toBe('my unsent draft');
+
+ mockStart.mockClear();
+ act(() => result.current.start());
+ expect(mockStart).not.toHaveBeenCalled();
+
+ act(() => mockOnTranscriptionComplete('discarded words'));
+ expect(ask).not.toHaveBeenCalled();
+ expect(currentText()).toBe('my unsent draft');
+
+ mockIsLoading = false;
+ act(() => rerender());
+ expect(result.current.startDisabled).toBe(false);
+ act(() => result.current.start());
+ act(() => mockOnTranscriptionComplete('new words'));
+
+ expect(currentText()).toBe('my unsent draft new words');
+ });
+
+ /* A run in flight has nothing to send into, so the take is refused outright.
+ `ChatForm` reports a paused `ask_user_question` as NOT submitting for
+ exactly this reason: the run is still open, but the composer has become the
+ answer box and speech has to reach it the way typing does. */
+ it('refuses a take while a turn is in flight', async () => {
+ const { result, rerender, currentText } = setup({ draft: '', isSubmitting: true });
+ act(() => result.current.start());
+ mockIsListening = true;
+ act(() => rerender());
+
+ act(() => mockSetTextCallback('answer the question'));
+ act(() => result.current.stopAndSend());
+ await settle(rerender);
+
+ expect(ask).not.toHaveBeenCalled();
+ expect(currentText()).toBe('answer the question');
+ });
+
+ it('sends the take when the composer is free to submit', async () => {
+ const { result, rerender } = setup({ draft: '', isSubmitting: false });
+ act(() => result.current.start());
+ mockIsListening = true;
+ act(() => rerender());
+
+ act(() => mockSetTextCallback('answer the question'));
+ act(() => result.current.stopAndSend());
+ await settle(rerender);
+
+ expect(ask).toHaveBeenCalledWith({ text: 'answer the question' });
+ });
+
+ /* Send and steer both refuse to submit while an attachment is still
+ uploading, and a dictated turn must not be the one path that lets a
+ half-uploaded file ride along. */
+ describe('an attachment still uploading', () => {
+ it('refuses the dictated turn and says why', async () => {
+ const { result, rerender, currentText } = setup({ filesLoading: true });
+ act(() => result.current.start());
+ mockIsListening = true;
+ act(() => rerender());
+
+ act(() => mockSetTextCallback('describe this file'));
+ act(() => result.current.stopAndSend());
+ await settle(rerender);
+
+ expect(ask).not.toHaveBeenCalled();
+ expect(mockShowToast).toHaveBeenCalledWith({
+ message: 'com_ui_speech_while_uploading',
+ status: 'error',
+ });
+ /* Refused, not discarded: the words are still there to send by hand. */
+ expect(currentText()).toBe('describe this file');
+ });
+
+ it('sends once the upload finishes', async () => {
+ const { result, rerender, setFilesLoading } = setup({ filesLoading: true });
+ act(() => result.current.start());
+ mockIsListening = true;
+ act(() => rerender());
+
+ act(() => mockSetTextCallback('describe this file'));
+ act(() => result.current.stopAndSend());
+ await settle(rerender);
+ expect(ask).not.toHaveBeenCalled();
+
+ setFilesLoading(false);
+ act(() => rerender());
+
+ act(() => result.current.start());
+ mockIsListening = true;
+ act(() => rerender());
+ act(() => mockSetTextCallback('now send it'));
+ act(() => result.current.stopAndSend());
+ await settle(rerender);
+
+ expect(ask).toHaveBeenCalledWith({ text: 'describe this file now send it' });
+ });
+ });
+
+ /* The armed send reads whatever the transcript left in the composer. A take
+ that produced nothing leaves the draft that was there BEFORE recording, and
+ sending that is the user's own unfinished words going out as if dictated. */
+ describe('a take that produced nothing', () => {
+ it('stands the armed send down when the transcription fails', async () => {
+ mockSpeechEndpoint = 'external';
+ const { result, rerender, currentText } = setup({ draft: 'half a thought' });
+ act(() => result.current.start());
+ mockIsListening = true;
+ mockIsLoading = true;
+ act(() => rerender());
+
+ act(() => result.current.stopAndSend());
+ /* The request fails: the engine toasts, clears its loading flag, and
+ never reports a transcript. */
+ mockIsLoading = false;
+ await settle(rerender);
+
+ expect(ask).not.toHaveBeenCalled();
+ expect(currentText()).toBe('half a thought');
+ });
+
+ it('stands it down for a take too short to reach the engine', async () => {
+ const { result, rerender, currentText } = setup({ draft: 'half a thought' });
+ act(() => result.current.start());
+ mockIsListening = true;
+ act(() => rerender());
+
+ act(() => result.current.stopAndSend());
+ await settle(rerender);
+
+ expect(ask).not.toHaveBeenCalled();
+ expect(currentText()).toBe('half a thought');
+ });
+
+ /* The gate is per take, not for good. */
+ it('sends the next take that does produce words', async () => {
+ const { result, rerender } = setup({ draft: 'half a thought' });
+ act(() => result.current.start());
+ mockIsListening = true;
+ act(() => rerender());
+ act(() => result.current.stopAndSend());
+ await settle(rerender);
+ expect(ask).not.toHaveBeenCalled();
+
+ act(() => result.current.start());
+ mockIsListening = true;
+ act(() => rerender());
+ act(() => mockSetTextCallback('this time it heard me'));
+ act(() => result.current.stopAndSend());
+ await settle(rerender);
+
+ expect(ask).toHaveBeenCalledWith({ text: 'half a thought this time it heard me' });
+ });
+ });
+});
diff --git a/client/src/hooks/Input/__tests__/usePaletteEntries.spec.tsx b/client/src/hooks/Input/__tests__/usePaletteEntries.spec.tsx
new file mode 100644
index 0000000000..ce119895b4
--- /dev/null
+++ b/client/src/hooks/Input/__tests__/usePaletteEntries.spec.tsx
@@ -0,0 +1,592 @@
+import React from 'react';
+import { RecoilRoot } from 'recoil';
+import { renderHook, act } from '@testing-library/react';
+import { ArtifactModes, PermissionTypes } from 'librechat-data-provider';
+import usePaletteEntries from '../usePaletteEntries';
+import store from '~/store';
+
+/**
+ * What the palette is offered, before it decides how to draw it. Every row here
+ * is gated twice (by a permission and by an agent capability) and a row that
+ * appears without both is a tool the user cannot actually use.
+ */
+
+let mockPermissions: Record<string, boolean>;
+let mockMemoryAccess: boolean;
+let mockCapabilities: Record<string, boolean>;
+let mockContext: Record<string, unknown> | null;
+let mockSkills: Array<Record<string, unknown>>;
+let mockAgentsMap: Record<string, Record<string, unknown>>;
+let mockSkillsActive: boolean;
+let mockUser: { personalization?: { memories?: boolean } } | undefined;
+let mockSkillsQuery: Record<string, unknown>;
+let mockSkillsQueryEnabled: boolean | undefined;
+
+jest.mock('~/hooks', () => ({
+ useHasAccess: ({ permissionType }: { permissionType: string }) =>
+ mockPermissions[permissionType] ?? false,
+ useHasMemoryAccess: () => mockMemoryAccess,
+ useAuthContext: () => ({ user: mockUser }),
+ useAgentCapabilities: () => mockCapabilities,
+ /* The real popover filter is used here, and it drops anything the user
+ cannot invoke or that is not active for them. */
+ useSkillActiveState: () => ({ isActive: () => mockSkillsActive }),
+}));
+
+jest.mock('~/hooks/useLocalize', () => ({
+ __esModule: true,
+ default: () => (key: string) => key,
+}));
+
+jest.mock('~/Providers', () => ({
+ useBadgeRowContext: () => mockContext,
+ useAgentsMapContext: () => mockAgentsMap,
+}));
+
+jest.mock('~/data-provider', () => ({
+ useSkillsInfiniteQuery: (_params: unknown, options?: { enabled?: boolean }) => {
+ mockSkillsQueryEnabled = options?.enabled;
+ return mockSkillsQuery;
+ },
+}));
+
+const toggle = (state: unknown, isPinned = false): ToggleFixture => ({
+ toggleState: state,
+ isPinned,
+ debouncedChange: jest.fn(),
+ setIsPinned: jest.fn(),
+});
+
+interface ServerFixture {
+ serverName: string;
+ config?: { title?: string; description?: string; iconPath?: string };
+}
+
+interface ToggleFixture {
+ toggleState: unknown;
+ isPinned: boolean;
+ debouncedChange: jest.Mock;
+ setIsPinned: jest.Mock;
+}
+
+interface ContextFixture {
+ webSearch: ToggleFixture;
+ codeInterpreter: ToggleFixture;
+ artifacts: ToggleFixture;
+ mcpServerManager: {
+ selectableServers?: ServerFixture[];
+ mcpValues: string[];
+ toggleServerSelection: jest.Mock;
+ connectionStatus?: Record<string, { connectionState: string }>;
+ initializeServer?: jest.Mock;
+ getServerStatusIconProps?: jest.Mock;
+ };
+ [key: string]: unknown;
+}
+
+const fullContext = (): ContextFixture => ({
+ webSearch: toggle(false),
+ codeInterpreter: toggle(false),
+ fileSearch: toggle(false),
+ skills: toggle(false),
+ memory: toggle(false),
+ artifacts: toggle(''),
+ mcpServerManager: {
+ selectableServers: [
+ { serverName: 'github', config: { title: 'Github', description: 'Repos' } },
+ { serverName: 'spotify', config: {} },
+ ],
+ mcpValues: [],
+ toggleServerSelection: jest.fn(),
+ },
+ agentsConfig: { capabilities: [] },
+});
+
+const allPermissions = {
+ [PermissionTypes.WEB_SEARCH]: true,
+ [PermissionTypes.RUN_CODE]: true,
+ [PermissionTypes.FILE_SEARCH]: true,
+ [PermissionTypes.MCP_SERVERS]: true,
+ [PermissionTypes.SKILLS]: true,
+};
+
+const allCapabilities = {
+ codeEnabled: true,
+ memoryEnabled: true,
+ webSearchEnabled: true,
+ artifactsEnabled: true,
+ fileSearchEnabled: true,
+ skillsEnabled: true,
+};
+
+const wrapper = ({ children }: { children: React.ReactNode }) => (
+ <RecoilRoot>{children}</RecoilRoot>
+);
+
+const entries = (agentId?: string | null) =>
+ renderHook(() => usePaletteEntries({ conversationId: 'convo-1', agentId }), { wrapper });
+
+const keysOf = (result: { current: Array<{ key: string }> }) =>
+ result.current.map((item) => item.key);
+
+describe('usePaletteEntries', () => {
+ beforeEach(() => {
+ mockPermissions = { ...allPermissions };
+ mockMemoryAccess = true;
+ mockUser = { personalization: { memories: true } };
+ mockCapabilities = { ...allCapabilities };
+ mockContext = fullContext();
+ mockSkills = [];
+ mockAgentsMap = {};
+ mockSkillsActive = true;
+ mockSkillsQuery = {
+ get data() {
+ return { pages: [{ skills: mockSkills }] };
+ },
+ isError: false,
+ hasNextPage: false,
+ isFetchingNextPage: false,
+ fetchNextPage: jest.fn(),
+ refetch: jest.fn(),
+ };
+ });
+
+ it('retries a failed catalog walk when the palette opens again', () => {
+ const refetch = jest.fn();
+ mockSkillsQuery = {
+ data: undefined,
+ isError: true,
+ hasNextPage: true,
+ isFetchingNextPage: false,
+ fetchNextPage: jest.fn(),
+ refetch,
+ };
+ const { rerender } = renderHook(
+ ({ revision }) =>
+ usePaletteEntries({
+ conversationId: 'convo-1',
+ catalogEnabled: true,
+ catalogOpenRevision: revision,
+ }),
+ { wrapper, initialProps: { revision: 1 } },
+ );
+
+ expect(refetch).not.toHaveBeenCalled();
+ rerender({ revision: 2 });
+ expect(refetch).toHaveBeenCalledTimes(1);
+ });
+
+ it('offers nothing before the badge row has a context to read', () => {
+ mockContext = null;
+ expect(keysOf(entries().result)).toEqual([]);
+ });
+
+ it('lists the built-in tools in a fixed order, servers last', () => {
+ expect(keysOf(entries().result)).toEqual([
+ 'builtin:web_search',
+ 'builtin:execute_code',
+ 'builtin:file_search',
+ 'builtin:skills',
+ 'builtin:memory',
+ 'builtin:artifacts',
+ 'mcp:github',
+ 'mcp:spotify',
+ ]);
+ });
+
+ it('exposes an inactive built-in tool that is pinned to the prompt bar', () => {
+ const codeInterpreter = toggle(false, true);
+ mockContext = { ...fullContext(), codeInterpreter };
+
+ const row = entries().result.current.find((item) => item.key === 'builtin:execute_code');
+ expect(row).toEqual(expect.objectContaining({ active: false, pinned: true }));
+ act(() => row?.onUnpin?.());
+ expect(codeInterpreter.setIsPinned).toHaveBeenCalledWith(false);
+ });
+
+ describe('the two gates on every tool', () => {
+ it.each([
+ [PermissionTypes.WEB_SEARCH, 'builtin:web_search'],
+ [PermissionTypes.RUN_CODE, 'builtin:execute_code'],
+ [PermissionTypes.FILE_SEARCH, 'builtin:file_search'],
+ [PermissionTypes.SKILLS, 'builtin:skills'],
+ [PermissionTypes.MCP_SERVERS, 'mcp:github'],
+ ])('withholds %s without the permission', (permission, key) => {
+ mockPermissions = { ...allPermissions, [permission]: false };
+ expect(keysOf(entries().result)).not.toContain(key);
+ });
+
+ it.each([
+ ['webSearchEnabled', 'builtin:web_search'],
+ ['codeEnabled', 'builtin:execute_code'],
+ ['fileSearchEnabled', 'builtin:file_search'],
+ ['skillsEnabled', 'builtin:skills'],
+ ['memoryEnabled', 'builtin:memory'],
+ ['artifactsEnabled', 'builtin:artifacts'],
+ ])('withholds %s without the capability', (capability, key) => {
+ mockCapabilities = { ...allCapabilities, [capability]: false };
+ expect(keysOf(entries().result)).not.toContain(key);
+ });
+
+ it('withholds memory without access, whatever the capability says', () => {
+ mockMemoryAccess = false;
+ expect(keysOf(entries().result)).not.toContain('builtin:memory');
+ });
+
+ it('withholds memory from a user who opted out in personalization', () => {
+ mockUser = { personalization: { memories: false } };
+ expect(keysOf(entries().result)).not.toContain('builtin:memory');
+ });
+ });
+
+ describe('on state', () => {
+ it('reads each tool from its own toggle', () => {
+ mockContext = { ...fullContext(), webSearch: toggle(true) };
+ const listed = entries().result.current;
+ expect(listed.find((item) => item.key === 'builtin:web_search')?.active).toBe(true);
+ expect(listed.find((item) => item.key === 'builtin:execute_code')?.active).toBe(false);
+ });
+
+ it('marks a server on when it is among the selected values', () => {
+ const context = fullContext();
+ context.mcpServerManager.mcpValues = ['spotify'];
+ mockContext = context;
+ const listed = entries().result.current;
+ expect(listed.find((item) => item.key === 'mcp:spotify')?.active).toBe(true);
+ expect(listed.find((item) => item.key === 'mcp:github')?.active).toBe(false);
+ });
+ });
+
+ describe('choosing a row', () => {
+ it('flips each tool through its own toggle', () => {
+ const context = fullContext();
+ mockContext = context;
+ const listed = entries().result.current;
+ act(() => listed.find((item) => item.key === 'builtin:web_search')?.onSelect());
+ expect(context.webSearch.debouncedChange).toHaveBeenCalledWith({ value: true });
+ expect(context.codeInterpreter.debouncedChange).not.toHaveBeenCalled();
+ });
+
+ it('turns a tool back off from its on state', () => {
+ const context = { ...fullContext(), webSearch: toggle(true) };
+ mockContext = context;
+ const listed = entries().result.current;
+ act(() => listed.find((item) => item.key === 'builtin:web_search')?.onSelect());
+ expect(context.webSearch.debouncedChange).toHaveBeenCalledWith({ value: false });
+ });
+
+ it('returns a mode pill to the default when it is already the stored mode', () => {
+ const context = { ...fullContext(), artifacts: toggle(ArtifactModes.SHADCNUI) };
+ mockContext = context;
+ const modes = entries().result.current.find(
+ (item) => item.key === 'builtin:artifacts',
+ )?.modes;
+ act(() => modes?.find((mode) => mode.id === 'shadcn')?.onSelect());
+ expect(context.artifacts.debouncedChange).toHaveBeenCalledWith({
+ value: ArtifactModes.DEFAULT,
+ });
+ });
+ });
+
+ describe('artifacts, which carries its modes on the row', () => {
+ const artifactsRow = () =>
+ entries().result.current.find((item) => item.key === 'builtin:artifacts');
+
+ it('offers no modes while it is off', () => {
+ mockContext = { ...fullContext(), artifacts: toggle('') };
+ const row = artifactsRow();
+ expect(row?.active).toBe(false);
+ expect(row?.modes).toBeUndefined();
+ });
+
+ it('offers three modes once it is on', () => {
+ mockContext = { ...fullContext(), artifacts: toggle(ArtifactModes.DEFAULT) };
+ const row = artifactsRow();
+ expect(row?.active).toBe(true);
+ expect(row?.modes?.map((mode) => mode.id)).toEqual(['default', 'shadcn', 'custom']);
+ expect(row?.modes?.find((mode) => mode.id === 'default')?.active).toBe(true);
+ });
+
+ it('marks the stored mode, and only it', () => {
+ mockContext = { ...fullContext(), artifacts: toggle(ArtifactModes.SHADCNUI) };
+ const modes = artifactsRow()?.modes;
+ expect(modes?.find((mode) => mode.id === 'shadcn')?.active).toBe(true);
+ expect(modes?.find((mode) => mode.id === 'default')?.active).toBe(false);
+ });
+
+ /* The toggle has historically also held a bare `true`, which names no mode
+ and would otherwise leave every one of them unchecked. */
+ it('reads a bare true as the default mode', () => {
+ mockContext = { ...fullContext(), artifacts: toggle(true) };
+ const row = artifactsRow();
+ expect(row?.active).toBe(true);
+ expect(row?.modes?.find((mode) => mode.id === 'default')?.active).toBe(true);
+ });
+ });
+
+ describe('skills', () => {
+ beforeEach(() => {
+ mockSkills = [
+ { _id: 's1', name: 'writer', displayTitle: 'Writing Helper', description: 'Drafts' },
+ { _id: 's2', name: 'writer', displayTitle: 'Writing Helper (copy)' },
+ { _id: 's3', name: 'researcher' },
+ ];
+ });
+
+ /* Manual skills are primed by name server-side, so records sharing a name
+ are one selectable thing however many the catalog holds. */
+ it('lists one row per name, not per record', () => {
+ expect(keysOf(entries().result).filter((key) => key.startsWith('skill:'))).toEqual([
+ 'skill:s1',
+ 'skill:s3',
+ ]);
+ });
+
+ it('represents a shared name by the copy the user favorited', () => {
+ const { result } = renderHook(
+ () =>
+ usePaletteEntries({
+ conversationId: 'convo-1',
+ favoriteKeys: new Set(['skill:s2']),
+ }),
+ { wrapper },
+ );
+ expect(keysOf(result).filter((key) => key.startsWith('skill:'))).toEqual([
+ 'skill:s2',
+ 'skill:s3',
+ ]);
+ });
+
+ it('falls back to the name when a skill has no title', () => {
+ const listed = entries().result.current;
+ expect(listed.find((item) => item.key === 'skill:s3')?.label).toBe('researcher');
+ expect(listed.find((item) => item.key === 'skill:s1')?.label).toBe('Writing Helper');
+ });
+
+ it('marks a skill on once it is staged', () => {
+ const { result } = renderHook(
+ () => usePaletteEntries({ conversationId: 'convo-1', agentId: null }),
+ {
+ wrapper: ({ children }: { children: React.ReactNode }) => (
+ <RecoilRoot
+ initializeState={({ set }) =>
+ set(store.pendingManualSkillsByConvoId('convo-1'), ['writer'])
+ }
+ >
+ {children}
+ </RecoilRoot>
+ ),
+ },
+ );
+ expect(result.current.find((item) => item.key === 'skill:s1')?.active).toBe(true);
+ expect(result.current.find((item) => item.key === 'skill:s3')?.active).toBe(false);
+ });
+
+ it('stages and unstages a skill through the same row', () => {
+ const { result } = entries(null);
+ const row = () => result.current.find((item) => item.key === 'skill:s1');
+
+ act(() => row()?.onSelect());
+ expect(row()?.active).toBe(true);
+
+ act(() => row()?.onSelect());
+ expect(row()?.active).toBe(false);
+ });
+
+ it('lists none of them when skills are not listable', () => {
+ mockCapabilities = { ...allCapabilities, skillsEnabled: false };
+ expect(keysOf(entries().result).filter((key) => key.startsWith('skill:'))).toEqual([]);
+ });
+
+ it('marks a staged placeholder as non-favoritable before its record loads', () => {
+ mockSkills = [];
+ const { result } = renderHook(
+ () => usePaletteEntries({ conversationId: 'convo-1', agentId: null }),
+ {
+ wrapper: ({ children }: { children: React.ReactNode }) => (
+ <RecoilRoot
+ initializeState={({ set }) =>
+ set(store.pendingManualSkillsByConvoId('convo-1'), ['writer'])
+ }
+ >
+ {children}
+ </RecoilRoot>
+ ),
+ },
+ );
+
+ expect(result.current.find((item) => item.key === 'skill:staged:writer')).toEqual(
+ expect.objectContaining({ favoritable: false }),
+ );
+ });
+ });
+
+ /* A third gate, and the one that fails closed: a persisted agent sees only
+ the skills it was built with, and none at all until the map has loaded. */
+ describe('which skills an agent may see', () => {
+ beforeEach(() => {
+ mockSkills = [
+ { _id: 's1', name: 'writer', displayTitle: 'Writing Helper' },
+ { _id: 's2', name: 'researcher', displayTitle: 'Researcher' },
+ ];
+ });
+
+ const skillKeys = (agentId?: string | null) =>
+ keysOf(entries(agentId).result).filter((key) => key.startsWith('skill:'));
+
+ it('pages in the catalog only for an agent whose scope can show a skill', () => {
+ skillKeys('openAI__gpt-5___GPT-5');
+ expect(mockSkillsQueryEnabled).toBe(true);
+
+ mockAgentsMap = { agent_1: { skills_enabled: false } };
+ skillKeys('agent_1');
+ expect(mockSkillsQueryEnabled).toBe(false);
+
+ mockAgentsMap = { agent_1: { skills_enabled: true, skills_scope: 'none', skills: ['s1'] } };
+ skillKeys('agent_1');
+ expect(mockSkillsQueryEnabled).toBe(false);
+
+ mockAgentsMap = { agent_1: { skills_enabled: true, skills: ['s2'] } };
+ skillKeys('agent_1');
+ expect(mockSkillsQueryEnabled).toBe(true);
+ });
+
+ it('lists the whole catalog for an ephemeral agent', () => {
+ expect(skillKeys('openAI__gpt-5___GPT-5')).toEqual(['skill:s1', 'skill:s2']);
+ });
+
+ it('lists nothing for a persisted agent that has skills switched off', () => {
+ mockAgentsMap = { agent_1: { skills_enabled: false } };
+ expect(skillKeys('agent_1')).toEqual([]);
+ });
+
+ it('lists nothing while the agents map is still loading', () => {
+ mockAgentsMap = {};
+ expect(skillKeys('agent_1')).toEqual([]);
+ });
+
+ it('lists only the skills a persisted agent was built with', () => {
+ mockAgentsMap = { agent_1: { skills_enabled: true, skills: ['s2'] } };
+ expect(skillKeys('agent_1')).toEqual(['skill:s2']);
+ });
+
+ it('lists nothing when a persisted agent explicitly disables its skill catalog', () => {
+ mockAgentsMap = {
+ agent_1: { skills_enabled: true, skills_scope: 'none', skills: ['s1', 's2'] },
+ };
+ expect(skillKeys('agent_1')).toEqual([]);
+ });
+
+ it('lists nothing for a selected catalog with no selected skills', () => {
+ mockAgentsMap = { agent_1: { skills_enabled: true, skills_scope: 'selected', skills: [] } };
+ expect(skillKeys('agent_1')).toEqual([]);
+ });
+
+ it('lists the whole catalog for an all-scoped agent despite stale stored skills', () => {
+ mockAgentsMap = {
+ agent_1: { skills_enabled: true, skills_scope: 'all', skills: ['stale-skill'] },
+ };
+ expect(skillKeys('agent_1')).toEqual(['skill:s1', 'skill:s2']);
+ });
+
+ it('lists agent skills even when endpoint tools are hidden', () => {
+ mockAgentsMap = { agent_1: { skills_enabled: true, skills: ['s2'] } };
+ const { result } = renderHook(
+ () =>
+ usePaletteEntries({
+ conversationId: 'convo-1',
+ agentId: 'agent_1',
+ enabled: true,
+ toolsEnabled: false,
+ }),
+ { wrapper },
+ );
+
+ expect(keysOf(result)).toEqual(['skill:s2']);
+ });
+ });
+
+ describe('servers', () => {
+ it('titles a server by its config, falling back to its name', () => {
+ const listed = entries().result.current;
+ expect(listed.find((item) => item.key === 'mcp:github')?.label).toBe('Github');
+ expect(listed.find((item) => item.key === 'mcp:spotify')?.label).toBe('spotify');
+ });
+
+ it('toggles a server by its own name, not by its title', () => {
+ const context = fullContext();
+ /* Already connected, so the row goes straight to the toggle rather than
+ through the initialize/configure branch an unknown status now takes. */
+ context.mcpServerManager.connectionStatus = { github: { connectionState: 'connected' } };
+ mockContext = context;
+ const row = entries().result.current.find((item) => item.key === 'mcp:github');
+ act(() => row?.onSelect());
+ expect(context.mcpServerManager.toggleServerSelection).toHaveBeenCalledWith('github');
+ });
+
+ it('initializes rather than toggles a server whose connection status is still unknown', () => {
+ const context = fullContext();
+ context.mcpServerManager.initializeServer = jest.fn();
+ mockContext = context;
+ const row = entries().result.current.find((item) => item.key === 'mcp:github');
+ act(() => row?.onSelect());
+ expect(context.mcpServerManager.initializeServer).toHaveBeenCalledWith('github');
+ expect(context.mcpServerManager.toggleServerSelection).not.toHaveBeenCalled();
+ });
+
+ it('offers cancellation while an OAuth initialization is cancellable', () => {
+ const context = fullContext();
+ const onCancel = jest.fn();
+ context.mcpServerManager.getServerStatusIconProps = jest.fn(() => ({
+ isInitializing: true,
+ canCancel: true,
+ onCancel,
+ }));
+ mockContext = context;
+ const cancel = entries()
+ .result.current.find((item) => item.key === 'mcp:github')
+ ?.modes?.find((mode) => mode.id === 'cancel');
+
+ act(() => cancel?.onSelect());
+
+ expect(onCancel).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps a connected server with custom variables configurable', () => {
+ const context = fullContext();
+ const onConfigClick = jest.fn();
+ context.mcpServerManager.connectionStatus = { github: { connectionState: 'connected' } };
+ context.mcpServerManager.getServerStatusIconProps = jest.fn(() => ({
+ hasCustomUserVars: true,
+ onConfigClick,
+ }));
+ mockContext = context;
+ const row = entries().result.current.find((item) => item.key === 'mcp:github');
+
+ act(() => row?.modes?.find((mode) => mode.id === 'configure')?.onSelect());
+ expect(onConfigClick).toHaveBeenCalledTimes(1);
+
+ act(() => row?.onSelect());
+ expect(context.mcpServerManager.toggleServerSelection).toHaveBeenCalledWith('github');
+ });
+
+ it('offers no configure action for a connected server without custom variables', () => {
+ const context = fullContext();
+ context.mcpServerManager.connectionStatus = { github: { connectionState: 'connected' } };
+ context.mcpServerManager.getServerStatusIconProps = jest.fn(() => ({
+ hasCustomUserVars: false,
+ onConfigClick: jest.fn(),
+ }));
+ mockContext = context;
+ const row = entries().result.current.find((item) => item.key === 'mcp:github');
+ expect(row?.modes).toBeUndefined();
+ });
+
+ it('lists none while the manager has no selectable servers', () => {
+ const context = fullContext();
+ context.mcpServerManager = { ...context.mcpServerManager, selectableServers: undefined };
+ mockContext = context;
+ expect(keysOf(entries().result).filter((key) => key.startsWith('mcp:'))).toEqual([]);
+ });
+ });
+});
diff --git a/client/src/hooks/Input/__tests__/useRecentFiles.spec.tsx b/client/src/hooks/Input/__tests__/useRecentFiles.spec.tsx
new file mode 100644
index 0000000000..aecb2153a0
--- /dev/null
+++ b/client/src/hooks/Input/__tests__/useRecentFiles.spec.tsx
@@ -0,0 +1,103 @@
+import { renderHook } from '@testing-library/react';
+import { DEFAULT_COMPOSER_RECENT_FILES } from 'librechat-data-provider';
+import type { TFile } from 'librechat-data-provider';
+import useRecentFiles from '../useRecentFiles';
+
+/**
+ * The palette's "your files" section: a short server-sorted page while idle,
+ * the full list once the user starts searching.
+ */
+
+let mockRecent: TFile[] | undefined;
+let mockAll: TFile[] | undefined;
+let mockRecentEnabled: boolean | undefined;
+let mockAllEnabled: boolean | undefined;
+let mockLimit: number | undefined;
+let mockComposerRecentFiles: number | undefined;
+
+jest.mock('~/data-provider', () => ({
+ useGetRecentFiles: (limit: number, config?: { enabled?: boolean }) => {
+ mockLimit = limit;
+ mockRecentEnabled = config?.enabled;
+ return { data: mockRecent };
+ },
+ useGetFiles: (config?: { enabled?: boolean }) => {
+ mockAllEnabled = config?.enabled;
+ return { data: mockAll };
+ },
+ useGetStartupConfig: () => ({
+ data: { interface: { composerRecentFiles: mockComposerRecentFiles } },
+ }),
+}));
+
+jest.mock('~/hooks/Files/useAttachExisting', () => ({
+ __esModule: true,
+ default: () => jest.fn(),
+}));
+
+const file = (over: Partial<TFile>): TFile => ({ file_id: 'f', ...over }) as TFile;
+
+const context = {
+ files: new Map(),
+ setFiles: jest.fn(),
+ conversation: null,
+};
+
+const recent = (enabled = true, search = '') =>
+ renderHook(() => useRecentFiles(enabled, context, search)).result.current;
+
+describe('useRecentFiles', () => {
+ beforeEach(() => {
+ mockRecent = undefined;
+ mockAll = undefined;
+ mockRecentEnabled = undefined;
+ mockAllEnabled = undefined;
+ mockLimit = undefined;
+ mockComposerRecentFiles = undefined;
+ });
+
+ it('fetches the recent page only while the palette is open and unsearched', () => {
+ recent(false);
+ expect(mockRecentEnabled).toBe(false);
+ expect(mockAllEnabled).toBe(false);
+
+ recent(true);
+ expect(mockRecentEnabled).toBe(true);
+ expect(mockAllEnabled).toBe(false);
+ expect(mockLimit).toBe(DEFAULT_COMPOSER_RECENT_FILES);
+ });
+
+ it('requests the deployment-configured recent-files limit when set', () => {
+ mockComposerRecentFiles = 12;
+ recent(true);
+ expect(mockLimit).toBe(12);
+ });
+
+ it('switches to the full list once the user starts typing', () => {
+ recent(true, 'report');
+ expect(mockRecentEnabled).toBe(false);
+ expect(mockAllEnabled).toBe(true);
+ });
+
+ it('lists nothing before the files have loaded', () => {
+ expect(recent().files).toEqual([]);
+ });
+
+ it('returns the server-sorted recent page as-is when unsearched', () => {
+ mockRecent = [
+ file({ file_id: 'newest' }),
+ file({ file_id: 'middle' }),
+ file({ file_id: 'older' }),
+ ];
+ expect(recent().files.map((item) => item.file_id)).toEqual(['newest', 'middle', 'older']);
+ });
+
+ it('filters the full list by filename when searching', () => {
+ mockAll = [
+ file({ file_id: 'a', filename: 'alpha.pdf' }),
+ file({ file_id: 'b', filename: 'report-final.pdf' }),
+ file({ file_id: 'c', filename: 'notes.txt' }),
+ ];
+ expect(recent(true, 'report').files.map((item) => item.file_id)).toEqual(['b']);
+ });
+});
diff --git a/client/src/hooks/Input/__tests__/useSpeechToTextBrowser.spec.tsx b/client/src/hooks/Input/__tests__/useSpeechToTextBrowser.spec.tsx
new file mode 100644
index 0000000000..4e1430929b
--- /dev/null
+++ b/client/src/hooks/Input/__tests__/useSpeechToTextBrowser.spec.tsx
@@ -0,0 +1,190 @@
+import React from 'react';
+import { RecoilRoot } from 'recoil';
+import { act, renderHook } from '@testing-library/react';
+import useSpeechToTextBrowser from '../useSpeechToTextBrowser';
+
+/**
+ * Dropping a take. The auto-send timer is the load-bearing part: a transcript
+ * that already landed will fire it after the user has cancelled, sending words
+ * they just discarded.
+ */
+
+const mockAbortListening = jest.fn();
+const mockStopListening = jest.fn();
+const mockResetTranscript = jest.fn();
+let mockFinalTranscript = '';
+/** Delivers a recognizer result the way the library does: a reducer update that
+ * reaches the consumer only on React's next commit. */
+let mockDeliverFinal: (transcript: string) => void = () => undefined;
+
+jest.mock('react-speech-recognition', () => {
+ const { useState } = jest.requireActual<typeof import('react')>('react');
+ return {
+ __esModule: true,
+ default: {
+ startListening: jest.fn(),
+ stopListening: (...args: unknown[]) => mockStopListening(...args),
+ abortListening: (...args: unknown[]) => mockAbortListening(...args),
+ },
+ useSpeechRecognition: () => {
+ const [finalTranscript, setFinalTranscript] = useState(mockFinalTranscript);
+ mockDeliverFinal = setFinalTranscript;
+ return {
+ listening: true,
+ finalTranscript,
+ interimTranscript: '',
+ resetTranscript: mockResetTranscript,
+ isMicrophoneAvailable: true,
+ browserSupportsSpeechRecognition: true,
+ };
+ },
+ };
+});
+
+jest.mock('@librechat/client', () => ({
+ useToastContext: () => ({ showToast: jest.fn() }),
+}));
+
+jest.mock('librechat-data-provider/react-query', () => ({
+ useGetCustomConfigSpeechQuery: () => ({ data: { sttExternal: false } }),
+}));
+
+jest.mock('~/hooks', () => ({
+ useLocalize: () => (key: string) => key,
+}));
+
+const AUTO_SEND_SECONDS = 3;
+
+function setup() {
+ const setText = jest.fn();
+ const onTranscriptionComplete = jest.fn();
+ const onTranscriptionSettled = jest.fn();
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
+ <RecoilRoot>{children}</RecoilRoot>
+ );
+ const rendered = renderHook(
+ () =>
+ useSpeechToTextBrowser(
+ setText,
+ onTranscriptionComplete,
+ onTranscriptionSettled,
+ AUTO_SEND_SECONDS,
+ ),
+ { wrapper },
+ );
+ return { ...rendered, setText, onTranscriptionComplete, onTranscriptionSettled };
+}
+
+describe('useSpeechToTextBrowser', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ jest.useFakeTimers();
+ mockFinalTranscript = '';
+ });
+
+ afterEach(() => {
+ jest.useRealTimers();
+ });
+
+ it('sends a landed transcript once the auto-send delay passes', () => {
+ mockFinalTranscript = 'the words that landed';
+ const { onTranscriptionComplete } = setup();
+
+ act(() => {
+ jest.advanceTimersByTime(AUTO_SEND_SECONDS * 1000);
+ });
+ expect(onTranscriptionComplete).toHaveBeenCalledWith('the words that landed', undefined);
+ });
+
+ /* The take is cancelled after the transcript arrived but before the delay
+ elapsed, which is the window where the words are already staged. */
+ it('does not send a transcript after the take has been dropped', () => {
+ mockFinalTranscript = 'the words that landed';
+ const { result, onTranscriptionComplete } = setup();
+
+ act(() => {
+ result.current.abortRecording();
+ });
+ act(() => {
+ jest.advanceTimersByTime(AUTO_SEND_SECONDS * 1000);
+ });
+
+ expect(onTranscriptionComplete).not.toHaveBeenCalled();
+ expect(mockAbortListening).toHaveBeenCalled();
+ expect(mockResetTranscript).toHaveBeenCalled();
+ });
+
+ /* `abortListening` is optional on the recogniser module, and stopping still
+ has to drop the take rather than leaving the microphone running. */
+ it('falls back to stopping when the module cannot abort', () => {
+ const speech = jest.requireMock('react-speech-recognition').default as Record<string, unknown>;
+ const abort = speech.abortListening;
+ delete speech.abortListening;
+
+ mockFinalTranscript = 'the words that landed';
+ const { result, onTranscriptionComplete } = setup();
+ act(() => {
+ result.current.abortRecording();
+ });
+ act(() => {
+ jest.advanceTimersByTime(AUTO_SEND_SECONDS * 1000);
+ });
+
+ expect(mockStopListening).toHaveBeenCalled();
+ expect(onTranscriptionComplete).not.toHaveBeenCalled();
+ speech.abortListening = abort;
+ });
+
+ it('settles only after the recognizer finishes stopping', async () => {
+ let finishStop: () => void = () => undefined;
+ mockStopListening.mockReturnValueOnce(
+ new Promise<void>((resolve) => {
+ finishStop = resolve;
+ }),
+ );
+ const { result, onTranscriptionSettled } = setup();
+
+ let stopping: Promise<void> | undefined;
+ act(() => {
+ stopping = result.current.stopRecording();
+ });
+ expect(onTranscriptionSettled).not.toHaveBeenCalled();
+
+ await act(async () => {
+ finishStop();
+ await stopping;
+ });
+ expect(onTranscriptionSettled).toHaveBeenCalledTimes(1);
+ });
+
+ /* The final result arrives before the stop resolves, as the Web Speech API orders
+ `result` ahead of `end`, but React has not committed it yet. Settling in that gap
+ let an armed stop-and-send read the interim text, or nothing at all. */
+ it('settles only after the final transcript reaches the composer', async () => {
+ let finishStop: () => void = () => undefined;
+ mockStopListening.mockReturnValueOnce(
+ new Promise<void>((resolve) => {
+ finishStop = resolve;
+ }),
+ );
+ const { result, setText, onTranscriptionSettled } = setup();
+
+ let stopping: Promise<void> | undefined;
+ act(() => {
+ stopping = result.current.stopRecording();
+ });
+
+ await act(async () => {
+ mockDeliverFinal('the final words');
+ finishStop();
+ await stopping;
+ expect(onTranscriptionSettled).not.toHaveBeenCalled();
+ });
+
+ expect(setText).toHaveBeenCalledWith('the final words', undefined);
+ expect(onTranscriptionSettled).toHaveBeenCalledTimes(1);
+ expect(setText.mock.invocationCallOrder[0]).toBeLessThan(
+ onTranscriptionSettled.mock.invocationCallOrder[0],
+ );
+ });
+});
diff --git a/client/src/hooks/Input/__tests__/useSpeechToTextExternal.spec.tsx b/client/src/hooks/Input/__tests__/useSpeechToTextExternal.spec.tsx
new file mode 100644
index 0000000000..cb473d2a92
--- /dev/null
+++ b/client/src/hooks/Input/__tests__/useSpeechToTextExternal.spec.tsx
@@ -0,0 +1,339 @@
+import React from 'react';
+import { RecoilRoot } from 'recoil';
+import { act, renderHook } from '@testing-library/react';
+import useSpeechToTextExternal from '../useSpeechToTextExternal';
+import store from '~/store';
+
+/**
+ * Everything this hook holds open is a device resource: the recorder, the
+ * microphone tracks, the silence monitor's frame loop and its audio graph.
+ * Navigating away mid-take reaches none of the stop handlers, so these cases
+ * pin the teardown rather than the happy path.
+ */
+
+type SpeechMutationOptions = {
+ onSuccess?: (data: { text: string }) => void;
+ onError?: () => void;
+};
+const mockProcessAudio = jest.fn();
+const mockShowToast = jest.fn();
+jest.mock('~/data-provider', () => ({
+ useSpeechToTextMutation: (_options: SpeechMutationOptions) => {
+ return { mutate: mockProcessAudio, isLoading: false };
+ },
+}));
+
+jest.mock('@librechat/client', () => ({
+ useToastContext: () => ({ showToast: mockShowToast }),
+}));
+
+type RecorderListener = (event: BlobEvent) => void;
+
+class FakeMediaRecorder {
+ static supportedType = 'audio/webm';
+ static instances: FakeMediaRecorder[] = [];
+
+ static isTypeSupported(type: string): boolean {
+ return type === FakeMediaRecorder.supportedType;
+ }
+
+ state: 'inactive' | 'recording' = 'inactive';
+ readonly mimeType: string;
+ private readonly handlers = new Map<string, RecorderListener[]>();
+
+ constructor(_stream: MediaStream, options?: MediaRecorderOptions) {
+ this.mimeType = options?.mimeType ?? '';
+ FakeMediaRecorder.instances.push(this);
+ }
+
+ addEventListener(type: string, handler: RecorderListener) {
+ const existing = this.handlers.get(type) ?? [];
+ existing.push(handler);
+ this.handlers.set(type, existing);
+ }
+
+ start() {
+ this.state = 'recording';
+ }
+
+ stop() {
+ this.state = 'inactive';
+ this.emit('stop');
+ }
+
+ emitData(data: Blob) {
+ this.emit('dataavailable', { data } as BlobEvent);
+ }
+
+ private emit(type: string, event?: BlobEvent) {
+ for (const handler of this.handlers.get(type) ?? []) {
+ handler(event as BlobEvent);
+ }
+ }
+}
+
+class FakeAudioContext {
+ static instances: FakeAudioContext[] = [];
+
+ state: AudioContextState = 'running';
+ close = jest.fn(() => {
+ this.state = 'closed';
+ return Promise.resolve();
+ });
+
+ constructor() {
+ FakeAudioContext.instances.push(this);
+ }
+
+ createMediaStreamSource() {
+ return { connect: jest.fn() };
+ }
+
+ createAnalyser() {
+ return { minDecibels: 0, frequencyBinCount: 32, getByteFrequencyData: jest.fn() };
+ }
+}
+
+const makeStream = () => {
+ const track = { stop: jest.fn(), kind: 'audio' };
+ const stream = { getTracks: () => [track] } as unknown as MediaStream;
+ return { stream, track };
+};
+
+const AUTO_SEND_SECONDS = 2;
+
+let mockGetUserMedia: jest.Mock;
+let mockCancelAnimationFrame: jest.Mock;
+let currentTrack: { stop: jest.Mock };
+let originalRequestAnimationFrame: typeof window.requestAnimationFrame;
+let originalCancelAnimationFrame: typeof window.cancelAnimationFrame;
+let frameId = 0;
+
+function setup({ autoSendText = -1 }: { autoSendText?: number } = {}) {
+ const setText = jest.fn();
+ const onTranscriptionComplete = jest.fn();
+ const onTranscriptionSettled = jest.fn();
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
+ <RecoilRoot
+ initializeState={({ set }) => {
+ set(store.speechToText, true);
+ set(store.autoTranscribeAudio, true);
+ }}
+ >
+ {children}
+ </RecoilRoot>
+ );
+ const rendered = renderHook(
+ () =>
+ useSpeechToTextExternal(
+ setText,
+ onTranscriptionComplete,
+ onTranscriptionSettled,
+ autoSendText,
+ ),
+ { wrapper },
+ );
+ return { ...rendered, setText, onTranscriptionComplete, onTranscriptionSettled };
+}
+
+const start = async (begin: () => void) => {
+ await act(async () => {
+ begin();
+ });
+};
+
+describe('useSpeechToTextExternal', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ FakeMediaRecorder.instances = [];
+ FakeMediaRecorder.supportedType = 'audio/webm';
+ FakeAudioContext.instances = [];
+ frameId = 0;
+
+ const { stream, track } = makeStream();
+ currentTrack = track;
+ mockGetUserMedia = jest.fn(() => Promise.resolve(stream));
+ Object.defineProperty(navigator, 'mediaDevices', {
+ configurable: true,
+ value: { getUserMedia: mockGetUserMedia },
+ });
+
+ global.MediaRecorder = FakeMediaRecorder as unknown as typeof MediaRecorder;
+ global.AudioContext = FakeAudioContext as unknown as typeof AudioContext;
+
+ originalRequestAnimationFrame = window.requestAnimationFrame;
+ originalCancelAnimationFrame = window.cancelAnimationFrame;
+ mockCancelAnimationFrame = jest.fn();
+ /* The loop is registered but never run: what matters here is that the id it
+ leaves behind is the one the teardown cancels. */
+ window.requestAnimationFrame = jest.fn(() => {
+ frameId += 1;
+ return frameId;
+ }) as unknown as typeof window.requestAnimationFrame;
+ window.cancelAnimationFrame = mockCancelAnimationFrame;
+ });
+
+ afterEach(() => {
+ jest.useRealTimers();
+ window.requestAnimationFrame = originalRequestAnimationFrame;
+ window.cancelAnimationFrame = originalCancelAnimationFrame;
+ });
+
+ it('records with a mime type the browser reports as supported', async () => {
+ FakeMediaRecorder.supportedType = 'audio/mp4';
+ const { result } = setup();
+ await start(result.current.externalStartRecording);
+
+ expect(FakeMediaRecorder.instances).toHaveLength(1);
+ expect(FakeMediaRecorder.instances[0].mimeType).toBe('audio/mp4');
+ });
+
+ /* A webview can expose `getUserMedia` without `MediaRecorder`. Asking for the
+ microphone first left a live capture behind a UI with no Stop control,
+ because construction throws before `isListening` ever turns on. */
+ it('does not open the microphone where the browser has no MediaRecorder', async () => {
+ Reflect.deleteProperty(globalThis, 'MediaRecorder');
+ const { result } = setup();
+
+ await start(result.current.externalStartRecording);
+
+ expect(mockGetUserMedia).not.toHaveBeenCalled();
+ expect(result.current.isListening).toBe(false);
+ expect(mockShowToast).toHaveBeenCalledWith(
+ expect.objectContaining({ status: 'error' as const }),
+ );
+ });
+
+ it('releases the microphone when the recorder cannot be constructed', async () => {
+ global.MediaRecorder = class {
+ static isTypeSupported = FakeMediaRecorder.isTypeSupported;
+ constructor() {
+ throw new Error('MediaRecorder unavailable');
+ }
+ } as unknown as typeof MediaRecorder;
+ const { result } = setup();
+
+ await start(result.current.externalStartRecording);
+
+ expect(mockGetUserMedia).toHaveBeenCalledTimes(1);
+ expect(currentTrack.stop).toHaveBeenCalledTimes(1);
+ expect(result.current.isListening).toBe(false);
+ });
+
+ /* The recorder's `stop` handler runs from a listener registered at start, so
+ a mime type read from state there would be a render behind the recorder. */
+ it('uploads the take packed as the format it was recorded in', async () => {
+ FakeMediaRecorder.supportedType = 'audio/mp4';
+ const { result } = setup();
+ await start(result.current.externalStartRecording);
+
+ const recorder = FakeMediaRecorder.instances[0];
+ act(() => recorder.emitData(new Blob(['take'], { type: 'audio/mp4' })));
+ act(() => result.current.externalStopRecording());
+
+ expect(mockProcessAudio).toHaveBeenCalledTimes(1);
+ const formData: FormData = mockProcessAudio.mock.calls[0][0];
+ const uploaded = formData.get('audio') as File;
+ expect(uploaded.name).toBe('audio.m4a');
+ expect(uploaded.type).toBe('audio/mp4');
+ });
+
+ it('stops the recorder, the microphone and the silence monitor on unmount', async () => {
+ const { result, unmount } = setup();
+ await start(result.current.externalStartRecording);
+
+ const recorder = FakeMediaRecorder.instances[0];
+ expect(recorder.state).toBe('recording');
+ expect(window.requestAnimationFrame).toHaveBeenCalled();
+
+ act(() => unmount());
+
+ expect(recorder.state).toBe('inactive');
+ expect(currentTrack.stop).toHaveBeenCalled();
+ expect(mockCancelAnimationFrame).toHaveBeenCalledWith(frameId);
+ expect(FakeAudioContext.instances[0].close).toHaveBeenCalled();
+ /* The take was dropped, not transcribed: nothing is left to submit into. */
+ expect(mockProcessAudio).not.toHaveBeenCalled();
+ });
+
+ it('stops a microphone stream that arrives after the composer is gone', async () => {
+ const { stream, track } = makeStream();
+ let grant: () => void = () => undefined;
+ mockGetUserMedia.mockImplementation(
+ () =>
+ new Promise<MediaStream>((resolve) => {
+ grant = () => resolve(stream);
+ }),
+ );
+
+ const { result, unmount } = setup();
+ act(() => result.current.externalStartRecording());
+ act(() => unmount());
+
+ await act(async () => {
+ grant();
+ });
+
+ expect(track.stop).toHaveBeenCalled();
+ expect(FakeMediaRecorder.instances).toHaveLength(0);
+ });
+
+ it('drops a queued auto-send when the composer unmounts', async () => {
+ jest.useFakeTimers();
+ const { result, onTranscriptionComplete, unmount } = setup({ autoSendText: AUTO_SEND_SECONDS });
+ await start(result.current.externalStartRecording);
+
+ act(() => mockProcessAudio.mock.calls[0]?.[1]?.onSuccess?.({ text: 'words in flight' }));
+ act(() => unmount());
+ act(() => jest.advanceTimersByTime(AUTO_SEND_SECONDS * 1000));
+
+ expect(onTranscriptionComplete).not.toHaveBeenCalled();
+ });
+ it('settles after a transcription is written', async () => {
+ const { result, setText, onTranscriptionSettled } = setup();
+ await start(result.current.externalStartRecording);
+ const recorder = FakeMediaRecorder.instances[0];
+ act(() => recorder.emitData(new Blob(['take'], { type: 'audio/webm' })));
+ act(() => result.current.externalStopRecording());
+ act(() => mockProcessAudio.mock.calls[0]?.[1]?.onSuccess?.({ text: 'settled words' }));
+ expect(setText).toHaveBeenCalledWith('settled words', undefined);
+ expect(onTranscriptionSettled).toHaveBeenCalledTimes(1);
+ });
+
+ it('settles a take that is too short to upload', async () => {
+ const { result, onTranscriptionSettled } = setup();
+ await start(result.current.externalStartRecording);
+
+ act(() => result.current.externalStopRecording());
+
+ expect(mockProcessAudio).not.toHaveBeenCalled();
+ expect(onTranscriptionSettled).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not settle a discarded take', async () => {
+ const { result, onTranscriptionSettled } = setup();
+ await start(result.current.externalStartRecording);
+
+ act(() => result.current.externalAbortRecording());
+
+ expect(onTranscriptionSettled).not.toHaveBeenCalled();
+ });
+
+ /* The request outlives the composer, so its callback still arrives. */
+ it('ignores a transcription that lands after the composer is gone', async () => {
+ jest.useFakeTimers();
+ const { result, setText, onTranscriptionComplete, unmount } = setup({
+ autoSendText: AUTO_SEND_SECONDS,
+ });
+ await start(result.current.externalStartRecording);
+
+ act(() => unmount());
+ act(() =>
+ mockProcessAudio.mock.calls[0]?.[1]?.onSuccess?.({ text: 'words nobody is waiting for' }),
+ );
+ act(() => jest.advanceTimersByTime(AUTO_SEND_SECONDS * 1000));
+
+ expect(setText).not.toHaveBeenCalled();
+ expect(onTranscriptionComplete).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/hooks/Input/useAskAnswerMode.spec.ts b/client/src/hooks/Input/useAskAnswerMode.spec.ts
index 12e5cf0745..56b8b7f565 100644
--- a/client/src/hooks/Input/useAskAnswerMode.spec.ts
+++ b/client/src/hooks/Input/useAskAnswerMode.spec.ts
@@ -81,8 +81,14 @@ describe('useAskAnswerMode', () => {
wrapper: JotaiWrapper,
});
+ expect(mockUseGetMessages).toHaveBeenCalledWith(
+ 'conversation-1',
+ expect.objectContaining({ enabled: true, select: findLiveAskUserQuestion }),
+ );
expect(result.current.liveAsk).toBe(liveAsk);
expect(result.current.active).toBe(true);
+ expect(result.current.composerAnswers).toBe(true);
+ expect(result.current.composerLocked).toBe(false);
expect(result.current.popoverVisible).toBe(true);
});
@@ -95,6 +101,8 @@ describe('useAskAnswerMode', () => {
expect(result.current.liveAsk).toBeNull();
expect(result.current.active).toBe(false);
+ expect(result.current.composerAnswers).toBe(false);
+ expect(result.current.composerLocked).toBe(false);
expect(result.current.popoverVisible).toBe(false);
});
@@ -107,6 +115,7 @@ describe('useAskAnswerMode', () => {
expect(result.current.active).toBe(true);
expect(result.current.batchMode).toBe(true);
+ expect(result.current.composerLocked).toBe(true);
expect(result.current.options).toEqual([]);
expect(result.current.draftId).toBeNull();
/** The bounded form owns the answer, so the composer never speaks for it. */
@@ -149,10 +158,29 @@ describe('useAskAnswerMode', () => {
const { result } = renderHook(() => useAskAnswerMode('new'), {
wrapper: JotaiWrapper,
});
+ expect(mockUseGetMessages).toHaveBeenCalledWith(
+ '',
+ expect.objectContaining({ enabled: false, select: findLiveAskUserQuestion }),
+ );
expect(result.current.liveAsk).toBeNull();
expect(result.current.active).toBe(false);
});
+ it('yields typed Enter to the shared composer binding resolver', () => {
+ mockUseGetMessages.mockReturnValue({ data: liveAsk });
+ const { result } = renderHook(() => useAskAnswerMode('conversation-1'));
+
+ const handled = result.current.handleComposerKeyDown({
+ key: 'Enter',
+ keyCode: 13,
+ currentTarget: { value: 'typed answer' },
+ nativeEvent: { isComposing: false },
+ } as never);
+
+ expect(handled).toBe(false);
+ expect(mockSubmitAskAnswer).not.toHaveBeenCalled();
+ });
+
it('forces liveAsk null when there is no conversation id', () => {
mockUseGetMessages.mockReturnValue({ data: liveAsk });
@@ -471,6 +499,7 @@ describe('useAskAnswerMode', () => {
});
expect(result.current.submitText('answer from A')).toBe(true);
+ expect(mockResetComposer).not.toHaveBeenCalled();
act(() => finishAnswer?.());
expect(mockResetComposer).toHaveBeenCalledTimes(1);
diff --git a/client/src/hooks/Input/useAskAnswerMode.ts b/client/src/hooks/Input/useAskAnswerMode.ts
index 561830d229..a3e4b06de7 100644
--- a/client/src/hooks/Input/useAskAnswerMode.ts
+++ b/client/src/hooks/Input/useAskAnswerMode.ts
@@ -550,15 +550,9 @@ export default function useAskAnswerMode(conversationId?: string | null) {
}
const composerText = e.currentTarget.value;
if (composerText.trim().length > 0) {
- // The composer IS the free-form answer box: Enter submits the typed
- // text (before useTextarea's submitting-lock can swallow it). Not for
- // a batch, which answers in its card — its Enter belongs to the normal
- // send path, so leave the event untouched rather than preventDefault
- // an event we are about to decline.
- if (e.key === 'Enter' && !e.shiftKey && !batchMode) {
- e.preventDefault();
- return submitText(composerText);
- }
+ /* Typed answers follow the shared composer binding resolver. ChatForm
+ keeps that path live during a single-question pause, so Enter-to-send,
+ its inverse modifier, and a customized submit chord stay consistent. */
return false;
}
/**
@@ -611,12 +605,10 @@ export default function useAskAnswerMode(conversationId?: string | null) {
active,
options,
selected,
- batchMode,
multiSelect,
popoverVisible,
canSubmit,
submit,
- submitText,
toggleChecked,
collapse,
setSelected,
diff --git a/client/src/hooks/Input/useAttachItems.tsx b/client/src/hooks/Input/useAttachItems.tsx
new file mode 100644
index 0000000000..860ba6b6da
--- /dev/null
+++ b/client/src/hooks/Input/useAttachItems.tsx
@@ -0,0 +1,426 @@
+import React, { useRef, useMemo, useState, useCallback } from 'react';
+import { SharePointIcon } from '@librechat/client';
+import { useRecoilState, useRecoilValue } from 'recoil';
+import {
+ FileSearch,
+ ImageUpIcon,
+ FileType2Icon,
+ FileImageIcon,
+ TerminalSquareIcon,
+} from 'lucide-react';
+import {
+ Providers,
+ EToolResources,
+ EModelEndpoint,
+ getConfiguredMimeAccept,
+ isExplicitMimeConfig,
+ bedrockDocumentMimeTypes,
+ isAssistantsEndpoint,
+ defaultAgentCapabilities,
+ bedrockDocumentExtensions,
+ isDocumentSupportedProvider,
+} from 'librechat-data-provider';
+import type {
+ TConversation,
+ EndpointFileConfig,
+ MimeUploadCapability,
+} from 'librechat-data-provider';
+import type { SharePointFile } from '~/data-provider/Files/sharepoint';
+import type { ExtendedFile, FileSetter } from '~/common';
+import { useSharePointFileHandlingNoChatContext } from '~/hooks/Files/useSharePointFileHandling';
+import { useAgentToolPermissions, useAgentCapabilities, useGetAgentsConfig } from '~/hooks';
+import { useFileHandlingNoChatContext } from '~/hooks/Files';
+import { useGetStartupConfig } from '~/data-provider';
+import { getUploadToolAllowances } from '~/utils';
+import { ephemeralAgentByConvoId } from '~/store';
+import useLocalize from '~/hooks/useLocalize';
+
+type FileUploadType =
+ | 'image'
+ | 'document'
+ | 'image_document'
+ | 'image_document_extended'
+ | 'image_document_video_audio'
+ | 'image_document_video_audio_configured';
+
+/** What each provider upload path can actually send, used to scope the picker filter to selectable files. */
+const fileTypeCapabilities: Record<FileUploadType, MimeUploadCapability> = {
+ image: { categories: ['image'] },
+ document: { categories: ['document'] },
+ image_document: { categories: ['image', 'document'] },
+ image_document_extended: {
+ categories: ['image', 'document'],
+ documentMimeTypes: bedrockDocumentMimeTypes,
+ },
+ /** Google/Vertex/OpenRouter media path: documents are limited to PDF (see isProviderAttachType). */
+ image_document_video_audio: {
+ categories: ['image', 'document', 'audio', 'video'],
+ documentMimeTypes: ['application/pdf'],
+ },
+ /** An explicit custom-endpoint allowlist decides which media the picker can offer. */
+ image_document_video_audio_configured: {
+ categories: ['image', 'document', 'audio', 'video'],
+ },
+};
+
+export interface AttachEntry {
+ id: string;
+ label: string;
+ icon: React.ReactNode;
+ /** Sending the file to the model, which is what nearly every upload means.
+ * The rest go to a tool and are folded away behind a disclosure. */
+ primary?: boolean;
+ onSelect: () => void;
+}
+
+export interface UseAttachItems {
+ entries: AttachEntry[];
+ /** The picker lives outside the popover, so selecting a file cannot race it
+ * unmounting; the caller mounts it. */
+ inputRef: React.RefObject<HTMLInputElement>;
+ onFileChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
+ isSharePointDialogOpen: boolean;
+ setIsSharePointDialogOpen: React.Dispatch<React.SetStateAction<boolean>>;
+ onSharePointFilesSelected: (files: SharePointFile[]) => Promise<void>;
+ isProcessing: boolean;
+ downloadProgress: ReturnType<typeof useSharePointFileHandlingNoChatContext>['downloadProgress'];
+ maxSelectionCount: number | undefined;
+}
+
+interface UseAttachItemsParams {
+ agentId?: string | null;
+ endpoint?: string | null;
+ endpointType?: EModelEndpoint | string;
+ endpointFileConfig?: EndpointFileConfig;
+ /** Resolved unified mode hides tool destinations behind the implicit uploader. */
+ isUnifiedMode?: boolean;
+ useResponsesApi?: boolean;
+ conversationId: string;
+ conversation: TConversation | null;
+ files: Map<string, ExtendedFile>;
+ setFiles: FileSetter;
+ setFilesLoading: React.Dispatch<React.SetStateAction<boolean>>;
+}
+
+/**
+ * The attach half of the composer palette, extracted from the old
+ * `AttachFileMenu` so the palette can render upload destinations as ordinary
+ * searchable rows alongside tools, skills and MCP servers.
+ *
+ * Returns the entries plus the hidden file input and SharePoint dialog state
+ * the caller must mount: the picker has to live in the DOM outside the
+ * popover so selecting a file does not race the popover unmounting.
+ */
+export default function useAttachItems({
+ agentId,
+ endpoint,
+ endpointType,
+ endpointFileConfig,
+ isUnifiedMode = false,
+ useResponsesApi,
+ conversationId,
+ conversation,
+ files,
+ setFiles,
+ setFilesLoading,
+}: UseAttachItemsParams): UseAttachItems {
+ const localize = useLocalize();
+ const inputRef = useRef<HTMLInputElement>(null);
+ /* The local picker reads this at event time, where a ref is the only thing
+ fast enough: the change event can arrive before React has committed. The
+ SharePoint dialog reads it during render, which a ref cannot serve, so the
+ same choice is mirrored into state for it. */
+ const toolResourceRef = useRef<EToolResources | undefined>();
+ const [sharePointResource, setSharePointResource] = useState<EToolResources | undefined>();
+ const [isSharePointDialogOpen, setIsSharePointDialogOpen] = useState(false);
+ const [, setEphemeralAgent] = useRecoilState(ephemeralAgentByConvoId(conversationId));
+
+ const { handleFileChange } = useFileHandlingNoChatContext(undefined, {
+ files,
+ setFiles,
+ setFilesLoading,
+ conversation,
+ });
+ const { handleSharePointFiles, isProcessing, downloadProgress } =
+ useSharePointFileHandlingNoChatContext(
+ { toolResource: sharePointResource },
+ { files, setFiles, setFilesLoading, conversation },
+ );
+
+ const ephemeralAgent = useRecoilValue(ephemeralAgentByConvoId(conversationId));
+ const { agentsConfig } = useGetAgentsConfig();
+ const { data: startupConfig } = useGetStartupConfig();
+ const sharePointEnabled = startupConfig?.sharePointFilePickerEnabled;
+
+ /** TODO: Ephemeral Agent Capabilities
+ * Allow defining agent capabilities on a per-endpoint basis
+ * Use definition for agents endpoint for ephemeral agents
+ * */
+ /* Destructured rather than held whole: the hook returns a fresh object every
+ render, and depending on it rebuilt every destination, every icon and every
+ closure below on each keystroke. */
+ const { contextEnabled, fileSearchEnabled, codeEnabled } = useAgentCapabilities(
+ agentsConfig?.capabilities ?? defaultAgentCapabilities,
+ );
+ const { tools, provider } = useAgentToolPermissions(agentId, ephemeralAgent);
+ /* The same allowances the drag-and-drop router resolves, so a file reaches
+ the same destinations whether it is dropped on the composer or picked
+ through this menu. Passing no ephemeral agent here used to leave both tool
+ destinations permanently hidden in an ordinary chat. */
+ const { fileSearchAllowedByAgent, codeAllowedByAgent } = getUploadToolAllowances(agentId, tools);
+
+ const handleUploadClick = useCallback(
+ (fileType?: FileUploadType) => {
+ if (!inputRef.current) {
+ return;
+ }
+ inputRef.current.value = '';
+ const configuredAccept =
+ fileType !== undefined
+ ? getConfiguredMimeAccept(
+ endpointFileConfig?.supportedMimeTypes,
+ fileTypeCapabilities[fileType],
+ )
+ : undefined;
+ if (configuredAccept != null) {
+ inputRef.current.accept = configuredAccept;
+ } else if (fileType === 'image') {
+ inputRef.current.accept = 'image/*,.heif,.heic';
+ } else if (fileType === 'document') {
+ inputRef.current.accept = '.pdf,application/pdf';
+ } else if (fileType === 'image_document') {
+ inputRef.current.accept = 'image/*,.heif,.heic,.pdf,application/pdf';
+ } else if (fileType === 'image_document_extended') {
+ inputRef.current.accept = `image/*,.heif,.heic,${bedrockDocumentExtensions}`;
+ } else if (fileType === 'image_document_video_audio') {
+ inputRef.current.accept = 'image/*,.heif,.heic,.pdf,application/pdf,video/*,audio/*';
+ } else {
+ inputRef.current.accept = '';
+ }
+ inputRef.current.click();
+ inputRef.current.accept = '';
+ },
+ [endpointFileConfig?.supportedMimeTypes],
+ );
+
+ const entries = useMemo<AttachEntry[]>(() => {
+ const setToolResource = (value: EToolResources | undefined) => {
+ toolResourceRef.current = value;
+ setSharePointResource(value);
+ };
+
+ const build = (onAction: (fileType?: FileUploadType) => void, prefix: string) => {
+ const items: AttachEntry[] = [];
+ /* Unified mode keeps the destination implicit and exposes only the
+ available sources, so the palette never routes a source through a
+ legacy tool resource. */
+ if (isUnifiedMode) {
+ items.push({
+ id: `${prefix}:unified`,
+ label:
+ prefix === 'local'
+ ? localize('com_files_upload_local_machine')
+ : localize('com_files_upload_sharepoint'),
+ primary: true,
+ icon:
+ prefix === 'local' ? (
+ <FileImageIcon className="icon-md" aria-hidden="true" />
+ ) : (
+ <SharePointIcon className="icon-md" aria-hidden="true" />
+ ),
+ onSelect: () => {
+ setToolResource(undefined);
+ if (prefix === 'local') {
+ onAction();
+ } else {
+ setIsSharePointDialogOpen(true);
+ }
+ },
+ });
+ return items;
+ }
+ /* Assistants own their own file handling: whatever the assistant is
+ configured to accept goes up unfiltered, and none of the tool
+ destinations below apply. Scoping this to the image capability, as the
+ provider check would, silently dropped PDF support. */
+ if (isAssistantsEndpoint(endpoint)) {
+ items.push({
+ id: `${prefix}:assistants`,
+ label: localize('com_sidepanel_attach_files'),
+ primary: true,
+ icon: <FileImageIcon className="icon-md" aria-hidden="true" />,
+ onSelect: () => {
+ setToolResource(undefined);
+ onAction();
+ },
+ });
+ return items;
+ }
+
+ let currentProvider = provider || endpoint;
+
+ // This will be removed in a future PR to formally normalize Providers comparisons to be case insensitive
+ if (currentProvider?.toLowerCase() === Providers.OPENROUTER) {
+ currentProvider = Providers.OPENROUTER;
+ }
+
+ const isAzureWithResponsesApi =
+ (currentProvider === EModelEndpoint.azureOpenAI ||
+ endpointType === EModelEndpoint.azureOpenAI) &&
+ useResponsesApi === true;
+
+ if (
+ isDocumentSupportedProvider(endpointType) ||
+ isDocumentSupportedProvider(currentProvider) ||
+ isAzureWithResponsesApi
+ ) {
+ items.push({
+ id: `${prefix}:provider`,
+ label: localize('com_ui_upload_provider'),
+ primary: true,
+ icon: <FileImageIcon className="icon-md" aria-hidden="true" />,
+ onSelect: () => {
+ setToolResource(undefined);
+ let fileType: Exclude<FileUploadType, 'image' | 'document'> = 'image_document';
+ if (currentProvider === Providers.GOOGLE || currentProvider === Providers.OPENROUTER) {
+ fileType = 'image_document_video_audio';
+ } else if (
+ currentProvider === Providers.BEDROCK ||
+ endpointType === EModelEndpoint.bedrock
+ ) {
+ fileType = 'image_document_extended';
+ } else if (
+ endpointType === EModelEndpoint.custom &&
+ isExplicitMimeConfig(endpointFileConfig?.supportedMimeTypes)
+ ) {
+ fileType = 'image_document_video_audio_configured';
+ }
+ onAction(fileType);
+ },
+ });
+ } else {
+ items.push({
+ id: `${prefix}:image`,
+ label: localize('com_ui_upload_image_input'),
+ primary: true,
+ icon: <ImageUpIcon className="icon-md" aria-hidden="true" />,
+ onSelect: () => {
+ setToolResource(undefined);
+ onAction('image');
+ },
+ });
+ }
+
+ if (contextEnabled) {
+ items.push({
+ id: `${prefix}:context`,
+ label: localize('com_ui_upload_ocr_text'),
+ icon: <FileType2Icon className="icon-md" aria-hidden="true" />,
+ onSelect: () => {
+ setToolResource(EToolResources.context);
+ onAction();
+ },
+ });
+ }
+
+ if (fileSearchEnabled && fileSearchAllowedByAgent) {
+ items.push({
+ id: `${prefix}:file_search`,
+ label: localize('com_ui_upload_file_search'),
+ icon: <FileSearch className="icon-md" aria-hidden="true" />,
+ onSelect: () => {
+ setToolResource(EToolResources.file_search);
+ setEphemeralAgent((prev) => ({ ...prev, [EToolResources.file_search]: true }));
+ onAction();
+ },
+ });
+ }
+
+ if (codeEnabled && codeAllowedByAgent) {
+ items.push({
+ id: `${prefix}:execute_code`,
+ label: localize('com_ui_upload_code_environment'),
+ icon: <TerminalSquareIcon className="icon-md" aria-hidden="true" />,
+ onSelect: () => {
+ setToolResource(EToolResources.execute_code);
+ setEphemeralAgent((prev) => ({ ...prev, [EToolResources.execute_code]: true }));
+ onAction();
+ },
+ });
+ }
+
+ return items;
+ };
+
+ const local = build(handleUploadClick, 'local');
+ if (!sharePointEnabled) {
+ return local;
+ }
+ /* SharePoint mirrors every local destination; the tool resource is set by
+ the row itself, then the picker dialog takes over from the input. */
+ for (const item of build(() => setIsSharePointDialogOpen(true), 'sharepoint')) {
+ local.push({
+ ...item,
+ /* Legacy mode folds SharePoint behind the local destination; unified
+ mode keeps both source rows visible in the palette. */
+ primary: isUnifiedMode ? item.primary : false,
+ label: isUnifiedMode
+ ? item.label
+ : `${item.label} (${localize('com_files_upload_sharepoint')})`,
+ icon: <SharePointIcon className="icon-md" aria-hidden="true" />,
+ });
+ }
+ return local;
+ }, [
+ localize,
+ endpoint,
+ provider,
+ endpointType,
+ /* Read inside `onSelect` (line 294): a config change that alters the
+ explicit MIME allowlist has to rebuild these rows, or the click still
+ requests the previous upload type. */
+ endpointFileConfig?.supportedMimeTypes,
+ codeEnabled,
+ contextEnabled,
+ fileSearchEnabled,
+ useResponsesApi,
+ isUnifiedMode,
+ handleUploadClick,
+ setEphemeralAgent,
+ sharePointEnabled,
+ codeAllowedByAgent,
+ fileSearchAllowedByAgent,
+ ]);
+
+ const onFileChange = useCallback(
+ (e: React.ChangeEvent<HTMLInputElement>) => {
+ handleFileChange(e, toolResourceRef.current);
+ toolResourceRef.current = undefined;
+ },
+ [handleFileChange],
+ );
+
+ const onSharePointFilesSelected = useCallback(
+ async (sharePointFiles: unknown[]) => {
+ try {
+ await handleSharePointFiles(sharePointFiles as Parameters<typeof handleSharePointFiles>[0]);
+ setIsSharePointDialogOpen(false);
+ } catch (error) {
+ console.error('SharePoint file processing error:', error);
+ }
+ },
+ [handleSharePointFiles],
+ );
+
+ return {
+ entries,
+ inputRef,
+ onFileChange,
+ isSharePointDialogOpen,
+ setIsSharePointDialogOpen,
+ onSharePointFilesSelected,
+ isProcessing,
+ downloadProgress,
+ maxSelectionCount: endpointFileConfig?.fileLimit,
+ };
+}
diff --git a/client/src/hooks/Input/useAttachTarget.ts b/client/src/hooks/Input/useAttachTarget.ts
new file mode 100644
index 0000000000..2f5d215d6e
--- /dev/null
+++ b/client/src/hooks/Input/useAttachTarget.ts
@@ -0,0 +1,146 @@
+import { useMemo } from 'react';
+import {
+ supportsFiles,
+ mergeFileConfig,
+ isAgentsEndpoint,
+ isEphemeralAgentId,
+ isAssistantsEndpoint,
+ resolveEffectiveUseResponsesApi,
+ resolveEndpointType,
+ resolveUseResponsesApi,
+ getEndpointFileConfig,
+} from 'librechat-data-provider';
+import type { TConversation, EModelEndpoint, EndpointFileConfig } from 'librechat-data-provider';
+import { useGetFileConfig, useGetEndpointsQuery, useGetAgentByIdQuery } from '~/data-provider';
+import { useAgentsMapContext } from '~/Providers';
+
+export interface AttachTarget {
+ endpointType?: EModelEndpoint | string;
+ endpointFileConfig?: EndpointFileConfig;
+ useResponsesApi?: boolean;
+ /** Whether upload destinations should appear in the palette at all. */
+ canAttach: boolean;
+}
+
+/**
+ * Resolves where an upload would go for the active conversation: the endpoint
+ * type, its file config, and whether uploads are possible at all.
+ *
+ * Lifted out of `AttachFileChat` so the composer bar can pass it to the palette
+ * without the palette re-deriving provider and agent resolution.
+ */
+export default function useAttachTarget(
+ conversation: TConversation | null,
+ disableInputs: boolean,
+): AttachTarget {
+ const endpoint = conversation?.endpoint ?? null;
+ const isAgents = useMemo(() => isAgentsEndpoint(endpoint), [endpoint]);
+ const agentsMap = useAgentsMapContext();
+
+ const needsAgentFetch = useMemo(() => {
+ if (!isAgents || !conversation?.agent_id) {
+ return false;
+ }
+ return !agentsMap?.[conversation.agent_id]?.model_parameters;
+ }, [isAgents, conversation?.agent_id, agentsMap]);
+
+ const { data: agentData } = useGetAgentByIdQuery(conversation?.agent_id, {
+ enabled: needsAgentFetch,
+ });
+
+ const { data: fileConfig = null, isSuccess: isFileConfigLoaded } = useGetFileConfig({
+ select: (data) => mergeFileConfig(data),
+ });
+ const { data: endpointsConfig } = useGetEndpointsQuery();
+
+ const agentProvider = useMemo(() => {
+ if (!isAgents || !conversation?.agent_id) {
+ return undefined;
+ }
+ return agentData?.provider ?? agentsMap?.[conversation.agent_id]?.provider;
+ }, [isAgents, conversation?.agent_id, agentData, agentsMap]);
+
+ const endpointType = useMemo(
+ () => resolveEndpointType(endpointsConfig, endpoint, agentProvider),
+ [endpointsConfig, endpoint, agentProvider],
+ );
+
+ /* The effective route, not the saved flag: when responsesApiRouting turns the
+ * Responses API on by default for a model, the upload picker has to follow the
+ * route the request will actually take or Azure chats preflight against the
+ * chat-completions limits and lose provider-document uploads. Mirrors the
+ * resolution useAgentUploadTarget applies for the same decision. */
+ const useResponsesApi = useMemo(() => {
+ const mappedAgent = conversation?.agent_id ? agentsMap?.[conversation.agent_id] : undefined;
+ const savedValue =
+ isAgents && conversation?.agent_id
+ ? resolveUseResponsesApi(
+ agentData?.model_parameters?.useResponsesApi ??
+ mappedAgent?.model_parameters?.useResponsesApi,
+ conversation?.useResponsesApi,
+ )
+ : conversation?.useResponsesApi;
+ const model = isAgents
+ ? (agentData?.model_parameters?.model ??
+ mappedAgent?.model_parameters?.model ??
+ agentData?.model ??
+ mappedAgent?.model)
+ : conversation?.model;
+ return resolveEffectiveUseResponsesApi({
+ value: savedValue,
+ endpoint: endpointType,
+ model,
+ webSearch: isAgents
+ ? (agentData?.model_parameters?.web_search ?? mappedAgent?.model_parameters?.web_search)
+ : conversation?.web_search,
+ routing: endpointsConfig?.[agentProvider ?? endpoint ?? '']?.responsesApiRouting,
+ });
+ }, [
+ isAgents,
+ conversation?.agent_id,
+ conversation?.model,
+ conversation?.useResponsesApi,
+ conversation?.web_search,
+ agentData,
+ agentsMap,
+ endpointType,
+ endpoint,
+ agentProvider,
+ endpointsConfig,
+ ]);
+
+ const endpointFileConfig = useMemo(
+ () =>
+ getEndpointFileConfig({
+ fileConfig,
+ endpointType,
+ endpoint: isAgents && agentProvider ? agentProvider : endpoint,
+ }),
+ [isAgents, agentProvider, endpoint, fileConfig, endpointType],
+ );
+
+ const isSavedAgent =
+ isAgents && conversation?.agent_id != null && !isEphemeralAgentId(conversation.agent_id);
+ const isPolicyResolved = isFileConfigLoaded && (!isSavedAgent || agentProvider != null);
+ /* Assistants upload directly, with no destination policy to resolve, so a file
+ config that failed or is paused must not take their uploads away. */
+ const isAssistants = isAssistantsEndpoint(endpoint);
+
+ const canAttach = useMemo(() => {
+ const endpointSupportsFiles = supportsFiles[endpointType ?? endpoint ?? ''] ?? false;
+ const uploadDisabled = (disableInputs || endpointFileConfig?.disabled) ?? false;
+ return (
+ (isPolicyResolved || isAssistants) && (isAgents || endpointSupportsFiles) && !uploadDisabled
+ );
+ }, [
+ isAgents,
+ isAssistants,
+ endpointType,
+ endpoint,
+ disableInputs,
+ endpointFileConfig?.disabled,
+ isPolicyResolved,
+ ]);
+
+ return { endpointType, endpointFileConfig, useResponsesApi, canAttach };
+}
diff --git a/client/src/hooks/Input/useAudioLevels.ts b/client/src/hooks/Input/useAudioLevels.ts
new file mode 100644
index 0000000000..8223e29f31
--- /dev/null
+++ b/client/src/hooks/Input/useAudioLevels.ts
@@ -0,0 +1,85 @@
+import { useRef, useState, useEffect } from 'react';
+
+/** Bars kept on screen; the newest sample is appended and the oldest drops.
+ * Sized for a waveform spanning the composer rather than a small pill. */
+const BAR_COUNT = 96;
+/** Sampling cadence. Fast enough to feel live, slow enough not to thrash. */
+const SAMPLE_MS = 55;
+
+const SILENT: number[] = new Array(BAR_COUNT).fill(0);
+
+/**
+ * Rolling loudness history of the microphone, for drawing a live waveform.
+ *
+ * Deliberately opens its own stream rather than reaching into the speech hooks:
+ * the browser and external transcription paths are completely different (the
+ * Web Speech API never exposes audio at all), and a visualiser has no business
+ * interfering with either. The stream is torn down the moment `active` goes
+ * false, so the recording indicator does not linger.
+ */
+export default function useAudioLevels(active: boolean): number[] {
+ const [levels, setLevels] = useState<number[]>(SILENT);
+ const levelsRef = useRef<number[]>(SILENT);
+
+ useEffect(() => {
+ if (!active) {
+ levelsRef.current = SILENT;
+ setLevels(SILENT);
+ return;
+ }
+
+ let stream: MediaStream | undefined;
+ let context: AudioContext | undefined;
+ let timer: ReturnType<typeof setInterval> | undefined;
+ let cancelled = false;
+
+ const start = async () => {
+ try {
+ stream = await navigator.mediaDevices.getUserMedia({ audio: true });
+ } catch {
+ /* Permission denied or no device: the bar still works, just flat. */
+ return;
+ }
+ if (cancelled) {
+ stream.getTracks().forEach((track) => track.stop());
+ return;
+ }
+
+ context = new AudioContext();
+ const analyser = context.createAnalyser();
+ analyser.fftSize = 1024;
+ context.createMediaStreamSource(stream).connect(analyser);
+ const buffer = new Uint8Array(analyser.frequencyBinCount);
+
+ timer = setInterval(() => {
+ analyser.getByteTimeDomainData(buffer);
+ /* RMS around the 128 midpoint, scaled so ordinary speech lands near the
+ top of the range without clipping every bar to full height. */
+ let sum = 0;
+ for (let i = 0; i < buffer.length; i++) {
+ const deviation = (buffer[i] - 128) / 128;
+ sum += deviation * deviation;
+ }
+ const rms = Math.sqrt(sum / buffer.length);
+ const level = Math.min(1, rms * 3.2);
+ levelsRef.current = [...levelsRef.current.slice(1), level];
+ setLevels(levelsRef.current);
+ }, SAMPLE_MS);
+ };
+
+ void start();
+
+ return () => {
+ cancelled = true;
+ if (timer != null) {
+ clearInterval(timer);
+ }
+ stream?.getTracks().forEach((track) => track.stop());
+ void context?.close();
+ };
+ }, [active]);
+
+ return levels;
+}
+
+export { BAR_COUNT };
diff --git a/client/src/hooks/Input/useChipPacking.ts b/client/src/hooks/Input/useChipPacking.ts
new file mode 100644
index 0000000000..790b65bf89
--- /dev/null
+++ b/client/src/hooks/Input/useChipPacking.ts
@@ -0,0 +1,83 @@
+import { useRef, useMemo, useState, useLayoutEffect } from 'react';
+
+interface Keyed {
+ key: string;
+}
+
+/**
+ * Reorders wrapping chips so they fill each row instead of leaving ragged gaps.
+ *
+ * Chips arrive in catalog order, which for skills and MCP servers is close to
+ * alphabetical: a very long name landing mid-row pushes everything after it down
+ * and strands the remainder of that row. Ordering widest-first is the
+ * first-fit-decreasing heuristic, so the wide chips claim their rows early and
+ * the narrow ones backfill whatever is left.
+ *
+ * Widths are measured rather than estimated from label length, which is a poor
+ * proxy in a proportional font and worse across languages. They are keyed by
+ * chip id so a reorder reuses the previous measurements instead of triggering
+ * another pass, which is what keeps this from oscillating.
+ */
+export default function useChipPacking<T extends Keyed>(
+ items: T[],
+): {
+ ordered: T[];
+ /** Put this on whatever encloses the chips; they are found by role, so they
+ * may be split across several containers. */
+ rootRef: React.RefObject<HTMLDivElement>;
+ /** Measured chip widths by key, empty until every chip has been seen. */
+ widths: Record<string, number>;
+} {
+ const rootRef = useRef<HTMLDivElement>(null);
+ /* State, not a ref: the order below is render output, and deriving it from a
+ value React does not track let two passes of the same render disagree. */
+ const [widths, setWidths] = useState<Record<string, number>>({});
+
+ const ordered = useMemo(() => {
+ /* Until every chip has been measured, leave the order alone: a partial sort
+ would shuffle on each pass and never settle. */
+ if (items.some((item) => widths[item.key] == null)) {
+ return items;
+ }
+ return [...items].sort((a, b) => widths[b.key] - widths[a.key]);
+ }, [items, widths]);
+
+ useLayoutEffect(() => {
+ const root = rootRef.current;
+ if (!root) {
+ return;
+ }
+ const measured: Record<string, number> = {};
+ /* Queried by role rather than walked as children: the caller may split the
+ chips across rows. Document order still matches `ordered`. */
+ root.querySelectorAll<HTMLElement>('[role="listitem"]').forEach((node, index) => {
+ const key = ordered[index]?.key;
+ const width = node.offsetWidth;
+ if (key != null && width > 0) {
+ measured[key] = width;
+ }
+ });
+
+ setWidths((prev) => {
+ const next: Record<string, number> = {};
+ let changed = false;
+ /* Only live chips are carried over, so a width cannot outlive the chip it
+ belongs to and place it wrongly when it comes back. */
+ for (const item of items) {
+ const width = measured[item.key] ?? prev[item.key];
+ if (width != null) {
+ next[item.key] = width;
+ }
+ if (next[item.key] !== prev[item.key]) {
+ changed = true;
+ }
+ }
+ if (!changed && Object.keys(next).length === Object.keys(prev).length) {
+ return prev;
+ }
+ return next;
+ });
+ }, [items, ordered]);
+
+ return { ordered, rootRef, widths };
+}
diff --git a/client/src/hooks/Input/useComposerHint.ts b/client/src/hooks/Input/useComposerHint.ts
new file mode 100644
index 0000000000..12f0e882db
--- /dev/null
+++ b/client/src/hooks/Input/useComposerHint.ts
@@ -0,0 +1,245 @@
+import { useMemo } from 'react';
+import type { LocalizeFunction } from '~/common';
+import { isMacPlatform, bindingDisplayString, resolveComposerKeyDown } from '~/utils/shortcuts';
+import useComposerBindings from '~/hooks/Input/useComposerBindings';
+import { useShortcutDisplay } from '~/hooks/useKeyboardShortcuts';
+import useLocalize from '~/hooks/useLocalize';
+
+/** The effective `submitMessage` binding, reduced to what the hints need.
+ * `customized` false means the stock modifier chord applies; a customized
+ * binding replaces it, and a cleared one leaves no chord at all. */
+export interface SendBinding {
+ customized: boolean;
+ display: string;
+}
+
+const DEFAULT_SEND_BINDING: SendBinding = { customized: false, display: '' };
+
+export interface ComposerHintState {
+ hasText: boolean;
+ isSubmitting: boolean;
+ /** Enter steers or queues instead of starting a turn. */
+ duringRunActive: boolean;
+ /** Whether the run can be reached yet. `isSubmitting` flips as soon as the
+ * user sends, but the start POST installs the generation epoch a moment
+ * later, and until it lands every chord that touches the live run refuses.
+ * Queueing is local, so it works throughout. */
+ canControlGeneration: boolean;
+ /** Whether the stop control can act yet; the stop shortcut presses it, so
+ * the key is named only once it does something. Defaults to reachable. */
+ canStop?: boolean;
+ /** Which action Enter takes during a run, per the effective setting. */
+ duringRunAction: 'steer' | 'queue';
+ steerInterruptsByDefault?: boolean;
+ /** Whether the steer route can accept input right now. A paused tool
+ * approval forces the effective action to queue and refuses steers, so the
+ * live-send alternate must not be advertised through it. */
+ canSteer: boolean;
+ /** The composer is the answer box for a paused `ask_user_question`. */
+ answerModeActive: boolean;
+ uploadingCount: number;
+ /** Plain Enter submits. When off, Enter inserts a newline and the modifier
+ * chord is what submits, which inverts every shortcut named below. */
+ enterToSend: boolean;
+ /** Which idle affordances act right now: `/` opens prompts, `@` opens the
+ * model mention, `+` attaches. The host resolves them from the same settings,
+ * permissions and attach target the composer obeys. */
+ idleActions: { prompts: boolean; mentions: boolean; attach: boolean };
+}
+
+/**
+ * `tip` is ambient discovery copy, true of the composer at all times. `state`
+ * reports something happening right now. Only the first is worth permanent
+ * space, so the two are distinguished here rather than at the call site.
+ */
+export type ComposerHintKind = 'tip' | 'state';
+
+export interface ComposerHint {
+ text: string;
+ kind: ComposerHintKind;
+}
+
+const SEPARATOR = ' · ';
+
+/**
+ * Resolves the one line shown under the composer. Ordered most-specific first:
+ * a paused question owns the composer outright, an in-flight upload is the most
+ * urgent transient state, and the during-run modifiers only matter once there
+ * is text for them to act on.
+ *
+ * Exported separately from the hook so the state matrix is testable without
+ * rendering.
+ */
+export function composeHint(
+ state: ComposerHintState,
+ localize: LocalizeFunction,
+ isMac: boolean,
+ /** The live binding for `stopGenerating`, which the user can rebind or clear
+ * outright, so the stop line is built from it rather than naming a key. */
+ stopShortcut: string,
+ /** The live `submitMessage` binding, for the same reason: the send chords
+ * named below follow the customization instead of asserting the stock one. */
+ sendBinding: SendBinding = DEFAULT_SEND_BINDING,
+ /** Whether the keydown resolver still returns the interrupt action for the
+ * Alt+Enter chord; when a rebound submit or disabled shortcuts claim it,
+ * the hint must not name a key that does something else. */
+ altEnterInterrupt: boolean = true,
+): ComposerHint {
+ if (state.answerModeActive) {
+ return { text: localize('com_ui_composer_hint_answer'), kind: 'state' };
+ }
+
+ if (state.uploadingCount > 0) {
+ return {
+ text: localize(
+ state.uploadingCount === 1
+ ? 'com_ui_composer_hint_uploading_one'
+ : 'com_ui_composer_hint_uploading',
+ { count: state.uploadingCount },
+ ),
+ kind: 'state',
+ };
+ }
+
+ if (state.duringRunActive && state.hasText) {
+ const mod = isMac ? '⌘⏎' : 'Ctrl+⏎';
+ const alt = isMac ? '⌥⏎' : 'Alt+⏎';
+ /* A customized binding replaces the stock chord as what triggers the
+ default action; it also makes the modifier's alternate route unreachable
+ (`resolveComposerKeyDown` only maps it with the stock binding), so the
+ alternate is named only while the stock chord still works. */
+ const sendChord = sendBinding.customized ? sendBinding.display : mod;
+ const isSteer = state.duringRunAction === 'steer';
+ const interruptByDefault = isSteer && state.steerInterruptsByDefault === true;
+ /* The default action and the live submit route share this preference:
+ naming plain Enter as Steer while it preempts is materially misleading. */
+ let defaultAction: string;
+ if (interruptByDefault) {
+ defaultAction = localize('com_ui_interrupt_steer');
+ } else if (isSteer) {
+ defaultAction = localize('com_ui_composer_hint_steer');
+ } else {
+ defaultAction = localize('com_ui_composer_hint_queue_default');
+ }
+ const alternateAction = isSteer
+ ? `${mod} ${localize('com_ui_composer_hint_queue')}`
+ : `${mod} ${localize('com_ui_composer_hint_send_now')}`;
+ let chordVerb: Parameters<typeof localize>[0];
+ if (interruptByDefault) {
+ chordVerb = 'com_ui_interrupt_steer';
+ } else if (isSteer) {
+ chordVerb = 'com_ui_composer_hint_steer_verb';
+ } else {
+ chordVerb = 'com_ui_composer_hint_queue_verb';
+ }
+ const parts: string[] = [];
+ if (state.enterToSend) {
+ parts.push(defaultAction);
+ /* The queue alternate is local and always lands; the send-now alternate
+ rides the steer route, which a paused approval refuses. */
+ if (!sendBinding.customized && (isSteer || state.canSteer)) {
+ parts.push(alternateAction);
+ }
+ } else if (sendChord) {
+ parts.push(`${sendChord} ${localize(chordVerb)}`);
+ }
+ /* Until the start POST installs the generation epoch, every chord that
+ reaches the live run refuses; only the default action survives, because
+ queueing is local. Naming the others through that window advertises keys
+ that do nothing, the same failure as pointing at an unbound shortcut. */
+ if (!state.canControlGeneration) {
+ return {
+ text: parts[0] ?? localize('com_ui_composer_hint_running'),
+ kind: 'state',
+ };
+ }
+ /* The interrupt chord is named only while the keydown resolver still hands
+ it back: a `submitMessage` rebound to Alt+Enter, a chord yielded to a
+ global shortcut, or shortcuts disabled altogether each make the key do
+ something else, and advertising it is worse than omitting it. */
+ const text = altEnterInterrupt
+ ? [...parts, `${alt} ${localize('com_ui_composer_hint_interrupt')}`].join(SEPARATOR)
+ : parts.join(SEPARATOR);
+ return {
+ text: text || localize('com_ui_composer_hint_running'),
+ kind: 'state',
+ };
+ }
+
+ if (state.isSubmitting) {
+ /* Nothing to advertise when the binding has been cleared: the stop button
+ is right there, and naming a key that does nothing is worse than saying
+ only that a reply is running. */
+ return {
+ text:
+ stopShortcut && state.canStop !== false
+ ? `${stopShortcut} ${localize('com_ui_composer_hint_stop')}`
+ : localize('com_ui_composer_hint_running'),
+ kind: 'state',
+ };
+ }
+
+ if (state.hasText) {
+ if (!state.enterToSend) {
+ const mod = isMac ? '⌘⏎' : 'Ctrl+⏎';
+ const sendChord = sendBinding.customized ? sendBinding.display : mod;
+ /* A cleared binding leaves no key that sends: name only what Enter does
+ rather than a send key that does nothing. */
+ const newline = `⏎ ${localize('com_ui_composer_hint_newline')}`;
+ return {
+ text: sendChord
+ ? [`${sendChord} ${localize('com_ui_composer_hint_send')}`, newline].join(SEPARATOR)
+ : newline,
+ kind: 'tip',
+ };
+ }
+ return { text: localize('com_ui_composer_hint_typing'), kind: 'tip' };
+ }
+
+ const { prompts, mentions, attach } = state.idleActions;
+ const idle = [
+ prompts && localize('com_ui_composer_hint_prompts'),
+ mentions && localize('com_ui_composer_hint_mentions'),
+ attach && localize('com_ui_composer_hint_attach'),
+ ].filter((part): part is string => typeof part === 'string');
+ return { text: idle.join(SEPARATOR), kind: 'tip' };
+}
+
+export default function useComposerHint(state: ComposerHintState): ComposerHint {
+ const localize = useLocalize();
+ const stopShortcut = useShortcutDisplay('stopGenerating');
+ const { shortcutsEnabled, submitOverride, yieldedChords } = useComposerBindings();
+ const sendBinding = useMemo<SendBinding>(
+ () => ({
+ customized: submitOverride !== undefined,
+ display: submitOverride ? bindingDisplayString(submitOverride, isMacPlatform) : '',
+ }),
+ [submitOverride],
+ );
+ /* The same verdict the during-run send button reads, so the hint and the
+ button can never disagree about whether Alt+Enter still interrupts. */
+ const altEnterInterrupt = useMemo(
+ () =>
+ resolveComposerKeyDown(
+ {
+ key: 'Enter',
+ altKey: true,
+ ctrlKey: false,
+ metaKey: false,
+ shiftKey: false,
+ },
+ {
+ isComposing: false,
+ isSubmitting: true,
+ allowSubmitWhileGenerating: true,
+ hasDuringRunModifier: true,
+ shortcutsEnabled,
+ enterToSend: state.enterToSend,
+ submitOverride,
+ yieldedChords,
+ },
+ ) === 'interrupt',
+ [shortcutsEnabled, state.enterToSend, submitOverride, yieldedChords],
+ );
+ return composeHint(state, localize, isMacPlatform, stopShortcut, sendBinding, altEnterInterrupt);
+}
diff --git a/client/src/hooks/Input/useComposerItems.ts b/client/src/hooks/Input/useComposerItems.ts
new file mode 100644
index 0000000000..e7c595a0d3
--- /dev/null
+++ b/client/src/hooks/Input/useComposerItems.ts
@@ -0,0 +1,81 @@
+import { useMemo, useCallback } from 'react';
+import { useRecoilValue, useSetRecoilState } from 'recoil';
+import store from '~/store';
+
+export type ComposerItemKind = 'quote' | 'skill';
+
+/**
+ * One piece of context staged for the next submission.
+ *
+ * Files are deliberately not here: they carry upload progress, previews and
+ * their own delete-or-abort semantics, and `FileRow` already renders them as
+ * cards. This covers the sources whose whole content is a line of text.
+ */
+export interface ComposerItem {
+ id: string;
+ kind: ComposerItemKind;
+ label: string;
+ /** Full text for the tooltip when `label` is truncated in the chip. */
+ title: string;
+ remove: () => void;
+}
+
+/**
+ * Merges the staged-text sources into a single ordered list in one pass each,
+ * so the tray renders one homogeneous list instead of a row per source.
+ *
+ * `includeQuotes` is false on the endpoints whose client path cannot transmit
+ * an excerpt: showing a quote as staged there promises something the send
+ * would silently drop.
+ */
+export default function useComposerItems(
+ conversationId: string,
+ includeQuotes = true,
+): ComposerItem[] {
+ const quotes = useRecoilValue(store.pendingQuotesByConvoId(conversationId));
+ const skills = useRecoilValue(store.pendingManualSkillsByConvoId(conversationId));
+ const setQuotes = useSetRecoilState(store.pendingQuotesByConvoId(conversationId));
+ const setSkills = useSetRecoilState(store.pendingManualSkillsByConvoId(conversationId));
+
+ const removeQuoteAt = useCallback(
+ (index: number) => setQuotes((prev) => prev.filter((_, i) => i !== index)),
+ [setQuotes],
+ );
+ const removeSkill = useCallback(
+ (name: string) => setSkills((prev) => prev.filter((skill) => skill !== name)),
+ [setSkills],
+ );
+
+ return useMemo(() => {
+ const items: ComposerItem[] = [];
+
+ /* Keyed by content, with the index only breaking ties between two
+ identical excerpts: an index in every id rewrote the ids of everything
+ after a removal, remounting those chips and dropping focus. */
+ const seen = new Map<string, number>();
+ for (let i = 0; includeQuotes && i < quotes.length; i++) {
+ const text = quotes[i];
+ const repeat = seen.get(text) ?? 0;
+ seen.set(text, repeat + 1);
+ items.push({
+ id: `quote:${JSON.stringify([text, repeat])}`,
+ kind: 'quote',
+ label: text,
+ title: text,
+ remove: () => removeQuoteAt(i),
+ });
+ }
+
+ for (const name of skills) {
+ items.push({
+ id: `skill:${name}`,
+ kind: 'skill',
+ label: name,
+ title: name,
+ remove: () => removeSkill(name),
+ });
+ }
+
+ return items;
+ }, [quotes, skills, includeQuotes, removeQuoteAt, removeSkill]);
+}
diff --git a/client/src/hooks/Input/useComposerRestore.ts b/client/src/hooks/Input/useComposerRestore.ts
new file mode 100644
index 0000000000..b2464e6a1d
--- /dev/null
+++ b/client/src/hooks/Input/useComposerRestore.ts
@@ -0,0 +1,222 @@
+import { useRef, useEffect, useCallback } from 'react';
+import { useStore } from 'jotai';
+import { useRecoilCallback } from 'recoil';
+import type { TMessage } from 'librechat-data-provider';
+import type { QueuedMessageContext } from '~/hooks/Chat/useSteering';
+import type { ExtendedFile, FileSetter } from '~/common';
+import type { useChatFormContext } from '~/Providers';
+import {
+ getReasoningStateKey,
+ pendingReasoningOverrideFamily,
+} from '~/components/Chat/Input/Composer/state';
+import store from '~/store';
+
+export interface ComposerRestore {
+ /** Chip "Edit message": replaces the draft outright, since the caller has
+ * already decided that is wanted. Returns whether the composer took the
+ * words: only a paused question, which owns the box, refuses. */
+ editToComposer: (
+ text: string,
+ files?: TMessage['files'],
+ context?: QueuedMessageContext,
+ ) => boolean;
+ /** The same restore for a steer whose reclaim was a round-trip, guarded
+ * against everything that can change while it is in flight. Returns whether
+ * the words were taken, so a refusal can be re-homed rather than dropped. */
+ restoreReclaimedSteer: (
+ text: string,
+ files: TMessage['files'],
+ context: QueuedMessageContext,
+ originConversationId: string,
+ ) => boolean;
+ /** Whether `restoreReclaimedSteer` would take words for this conversation
+ * right now, without writing anything. A caller about to give up a durable
+ * copy checks this first, so a refusal cannot strand the words locally. */
+ canRestoreToComposer: (originConversationId: string) => boolean;
+}
+
+interface UseComposerRestoreParams {
+ index?: number;
+ conversationId: string;
+ methods: ReturnType<typeof useChatFormContext>;
+ files: Map<string, ExtendedFile>;
+ setFiles: FileSetter;
+ textAreaRef: React.RefObject<HTMLTextAreaElement>;
+ /** A paused `ask_user_question` owns the composer; see `restoreReclaimedSteer`. */
+ answerModeActive: boolean;
+}
+
+/**
+ * Putting a message back into the composer: the queue rail's "Edit message",
+ * and the guarded restore a reclaimed steer resolves into.
+ *
+ * Extracted from `ChatForm` because the guarded path is the only one in the
+ * composer that can destroy text outright, and every one of its conditions is
+ * about time passing between a click and its answer, which is exactly what a
+ * component holding half a dozen other concerns makes impossible to test.
+ */
+export default function useComposerRestore({
+ index = 0,
+ conversationId,
+ methods,
+ files,
+ setFiles,
+ textAreaRef,
+ answerModeActive,
+}: UseComposerRestoreParams): ComposerRestore {
+ const reasoningStore = useStore();
+ const reasoningStateKey = getReasoningStateKey(conversationId, index);
+ /** Chip "Edit message" restore: quote chips, skill picks, and the reasoning
+ * override merge back into their compose-time atoms. */
+ const restoreComposerContext = useRecoilCallback(
+ ({ set }) =>
+ (context?: QueuedMessageContext) => {
+ const { quotes, manualSkills, reasoningOverride } = context ?? {};
+ if (quotes != null && quotes.length > 0) {
+ set(store.pendingQuotesByConvoId(conversationId), (prev) => [
+ ...new Set([...prev, ...quotes]),
+ ]);
+ }
+ if (manualSkills != null && manualSkills.length > 0) {
+ set(store.pendingManualSkillsByConvoId(conversationId), (prev) => [
+ ...new Set([...prev, ...manualSkills]),
+ ]);
+ }
+ if (reasoningOverride != null) {
+ reasoningStore.set(pendingReasoningOverrideFamily(reasoningStateKey), reasoningOverride);
+ }
+ },
+ [conversationId, reasoningStateKey, reasoningStore],
+ );
+
+ /** Read at call time rather than captured, so both the synchronous edit below
+ * and the round-trip restore further down see the pause that started while
+ * they were in flight. */
+ const liveAnswerModeRef = useRef(answerModeActive);
+ liveAnswerModeRef.current = answerModeActive;
+
+ /** The text replaces the composer draft and the chip's attachments merge back
+ * into the composer file map (already uploaded, so they restore as completed
+ * entries, same shape as draft recovery).
+ *
+ * A paused `ask_user_question` is the one thing that refuses: `onSubmit`
+ * hands the composer's text to `answerMode.submitText` before any send
+ * routing, so a queued message dropped in here would leave the box on
+ * screen looking like a draft and answer the tool on the next Enter. */
+ const editToComposer = useCallback(
+ (text: string, chipFiles?: TMessage['files'], context?: QueuedMessageContext): boolean => {
+ if (liveAnswerModeRef.current) {
+ return false;
+ }
+ methods.setValue('text', text, { shouldDirty: true });
+ if (chipFiles != null && chipFiles.length > 0) {
+ setFiles((prev) => {
+ const next = new Map(prev);
+ for (const file of chipFiles) {
+ if (!file.file_id) {
+ continue;
+ }
+ next.set(file.file_id, {
+ file_id: file.file_id,
+ filename: file.filename,
+ filepath: file.filepath,
+ type: file.type ?? '',
+ height: file.height,
+ width: file.width,
+ size: file.bytes ?? 0,
+ progress: 1,
+ attached: true,
+ llmDeliveryPath: file.llmDeliveryPath,
+ });
+ }
+ return next;
+ });
+ }
+ restoreComposerContext(context);
+ textAreaRef.current?.focus();
+ return true;
+ },
+ [methods, setFiles, restoreComposerContext, textAreaRef],
+ );
+
+ /** Read at call time, not captured: a reclaim resolves into the callback from
+ * the render it was clicked in, so the closure's `conversationId` is the OLD
+ * chat: comparing it against itself would pass while `methods` (one form,
+ * reused across conversations) writes into the chat now on screen. */
+ const liveConversationIdRef = useRef(conversationId);
+ liveConversationIdRef.current = conversationId;
+ /** Same reason: attachments staged after the click must be seen. */
+ const liveFilesRef = useRef(files);
+ liveFilesRef.current = files;
+ /** A reclaim can resolve after the composer unmounts (left the route, closed
+ * the pane). Its refs still hold the origin chat, so the restore would pass
+ * its checks and write into a dead form, reporting success and making the
+ * caller drop the steer, losing the text. Track mount so the restore refuses
+ * and the caller queues it instead. */
+ const mountedRef = useRef(true);
+ useEffect(
+ () => () => {
+ mountedRef.current = false;
+ },
+ [],
+ );
+
+ /** A draft is anything the user has staged, not just typed: `editToComposer`
+ * MERGES the steer's attachments into the composer's file map and its quotes
+ * and skill picks into their atoms, so restoring over staged context would
+ * glue the two submissions together. */
+ const hasStagedContext = useRecoilCallback(
+ ({ snapshot }) =>
+ (convoId: string) =>
+ snapshot.getLoadable(store.pendingQuotesByConvoId(convoId)).getValue().length > 0 ||
+ snapshot.getLoadable(store.pendingManualSkillsByConvoId(convoId)).getValue().length > 0 ||
+ reasoningStore.get(pendingReasoningOverrideFamily(getReasoningStateKey(convoId, index))) !=
+ null,
+ [index, reasoningStore],
+ );
+
+ /**
+ * `editToComposer` for a steer whose reclaim was a round-trip: by the time it
+ * resolves the composer may have moved on. Refuses (returning false, so the
+ * caller re-homes the words instead of dropping them) rather than overwrite a
+ * draft the user has since staged, or drop a steer into whatever chat they
+ * navigated to.
+ */
+ const canRestoreToComposer = useCallback(
+ (originConversationId: string): boolean => {
+ if (!mountedRef.current || liveAnswerModeRef.current) {
+ return false;
+ }
+ const liveConversationId = liveConversationIdRef.current;
+ if (originConversationId !== liveConversationId) {
+ return false;
+ }
+ return (
+ (methods.getValues('text') ?? '').trim().length === 0 &&
+ (liveFilesRef.current?.size ?? 0) === 0 &&
+ !hasStagedContext(liveConversationId)
+ );
+ },
+ [methods, hasStagedContext],
+ );
+
+ const restoreReclaimedSteer = useCallback(
+ (
+ text: string,
+ steerFiles: TMessage['files'],
+ context: QueuedMessageContext,
+ originConversationId: string,
+ ): boolean => {
+ if (!canRestoreToComposer(originConversationId)) {
+ return false;
+ }
+ /** `editToComposer` repeats the answer-mode refusal: a question can pause
+ * the run mid-reclaim, and restoring into the answer box would turn the
+ * steer into the tool's answer on the next Enter. */
+ return editToComposer(text, steerFiles, context);
+ },
+ [canRestoreToComposer, editToComposer],
+ );
+
+ return { editToComposer, restoreReclaimedSteer, canRestoreToComposer };
+}
diff --git a/client/src/hooks/Input/useDictation.ts b/client/src/hooks/Input/useDictation.ts
new file mode 100644
index 0000000000..c5c1df0d8f
--- /dev/null
+++ b/client/src/hooks/Input/useDictation.ts
@@ -0,0 +1,349 @@
+import { useRef, useMemo, useState, useEffect, useCallback } from 'react';
+import { useToastContext } from '@librechat/client';
+import type { TAskFunction } from '~/common';
+import useGetAudioSettings from './useGetAudioSettings';
+import { useChatFormContext } from '~/Providers';
+import { isFocusedChatPane } from '~/utils/pane';
+import useSpeechToText from './useSpeechToText';
+import { globalAudioId } from '~/common';
+import useLocalize from '../useLocalize';
+
+const isExternalSTT = (speechToTextEndpoint: string) => speechToTextEndpoint === 'external';
+
+/** How the in-flight transcription should be spent once recording ends. */
+type StopMode = 'compose' | 'send' | 'cancel';
+
+export interface Dictation {
+ active: boolean;
+ transcribing: boolean;
+ /** The composer is free, but a discarded external request still owns STT. */
+ startDisabled: boolean;
+ elapsed: number;
+ start: () => void;
+ /** Drop the take and restore whatever draft was there before. */
+ cancel: () => void;
+ /** Transcribe into the composer and stop, leaving the turn unsent. */
+ stopToComposer: () => void;
+ /** Transcribe and send in one action. */
+ stopAndSend: () => void;
+}
+
+/**
+ * Speech capture for the composer, owning the whole recording lifecycle so the
+ * bar can hand its existing buttons over to it: `+` becomes cancel, the mic
+ * becomes stop, and send transcribes and sends in one action.
+ *
+ * Stopping and sending are deliberately separate. Previously the only control
+ * submitted whatever had been heard, with no way to review it first and no way
+ * to back out at all.
+ */
+export default function useDictation({
+ ask,
+ duringRunSubmit,
+ methods,
+ isSubmitting,
+ filesLoading = false,
+ deferComposerReset = false,
+ disabled = false,
+ autoSendText,
+ speechToText,
+ index = 0,
+}: {
+ ask: TAskFunction;
+ /** Optional host route for a take that completes while generation is active. */
+ duringRunSubmit?: (text: string) => boolean | void;
+ methods: ReturnType<typeof useChatFormContext>;
+ isSubmitting: boolean;
+ /** Attachments still uploading. Send and steer both refuse to submit while
+ * this is true, and a dictated turn must not be the one path that lets a
+ * half-uploaded file ride along. */
+ filesLoading?: boolean;
+ /** The accepted submission owns composer cleanup asynchronously. Keep this
+ * take spent while leaving its transcript until that owner confirms it. */
+ deferComposerReset?: boolean;
+ /** Host-owned speech and composer gates, including settings hydration. */
+ disabled?: boolean;
+ /** Host-owned Auto Send Text preference. */
+ autoSendText: number;
+ /** Host-owned Speech to Text preference. */
+ speechToText: boolean;
+ /** The chat pane this composer belongs to; only the focused pane answers the shortcut. */
+ index?: number;
+}): Dictation {
+ const { setValue, reset, getValues } = methods;
+ const localize = useLocalize();
+ const { showToast } = useToastContext();
+ const { speechToTextEndpoint } = useGetAudioSettings();
+ /** The Auto Send Text setting, which submits a plain recording once its
+ * transcript settles. A stop that was never asked to send still honours it. */
+ const autoSendEnabled = autoSendText > -1;
+
+ const existingTextRef = useRef<string>('');
+ const takeIdRef = useRef(0);
+ const isSubmittingRef = useRef(isSubmitting);
+ isSubmittingRef.current = isSubmitting;
+ const duringRunSubmitRef = useRef(duringRunSubmit);
+ duringRunSubmitRef.current = duringRunSubmit;
+ const filesLoadingRef = useRef(filesLoading);
+ filesLoadingRef.current = filesLoading;
+ const deferComposerResetRef = useRef(deferComposerReset);
+ deferComposerResetRef.current = deferComposerReset;
+ /** Read when the transcription lands, which is after the stop that set it.
+ * The speech hooks have no notion of cancelling or of deferring a send. */
+ const modeRef = useRef<StopMode>('compose');
+ /** One submission per take. Both the settle fallback below and a late
+ * auto-send callback can reach the same transcript, and whichever gets
+ * there first is the one that spends it. */
+ const spentRef = useRef(false);
+ /** Whether this take produced any words at all. A transcription that fails,
+ * or a take too short to reach the engine, reports nothing back and leaves
+ * the composer holding the draft that was there before recording, which an
+ * armed stop-and-send would then send as if it had been dictated. */
+ const heardRef = useRef(false);
+ const submit = useCallback(
+ (text: string) => {
+ if (spentRef.current || !text) {
+ return;
+ }
+ const runSubmit = duringRunSubmitRef.current;
+ if (isSubmittingRef.current && runSubmit == null) {
+ showToast({ message: localize('com_ui_speech_while_submitting'), status: 'error' });
+ return;
+ }
+ /* The transcript stays in the composer so the turn can be sent by hand
+ once the upload finishes, rather than going out without its file. */
+ if (filesLoadingRef.current) {
+ showToast({ message: localize('com_ui_speech_while_uploading'), status: 'error' });
+ return;
+ }
+ spentRef.current = true;
+ const globalAudio = document.getElementById(globalAudioId) as HTMLAudioElement | null;
+ if (globalAudio) {
+ globalAudio.muted = false;
+ }
+ const submitted = runSubmit?.(text) ?? ask({ text });
+ if (submitted === false) {
+ spentRef.current = false;
+ return;
+ }
+ if (deferComposerResetRef.current) {
+ return;
+ }
+ reset({ text: '' });
+ existingTextRef.current = '';
+ },
+ [ask, reset, showToast, localize],
+ );
+ const onTranscriptionComplete = useCallback(
+ (text: string, takeId?: number) => {
+ if (takeId != null && takeId !== takeIdRef.current) {
+ return;
+ }
+ const mode = modeRef.current;
+
+ if (text) {
+ heardRef.current = true;
+ }
+
+ if (mode === 'cancel') {
+ /* The draft stays on the ref until a take is actually spent: an
+ external transcription already in flight cannot be recalled, and
+ clearing it at cancel time left this reset wiping the very draft the
+ cancel had just put back. */
+ reset({ text: existingTextRef.current });
+ return;
+ }
+
+ /** For external STT, append existing text to the transcription */
+ const finalText =
+ isExternalSTT(speechToTextEndpoint) && existingTextRef.current
+ ? `${existingTextRef.current} ${text}`
+ : text;
+
+ if (mode === 'compose' && !autoSendEnabled) {
+ if (finalText) {
+ setValue('text', finalText, { shouldValidate: true });
+ }
+ existingTextRef.current = '';
+ return;
+ }
+
+ submit(finalText);
+ },
+ [autoSendEnabled, reset, setValue, submit, speechToTextEndpoint],
+ );
+
+ const setText = useCallback(
+ (text: string, takeId?: number) => {
+ if (takeId != null && takeId !== takeIdRef.current) {
+ return;
+ }
+ if (modeRef.current === 'cancel') {
+ return;
+ }
+ if (text) {
+ heardRef.current = true;
+ }
+ setValue('text', existingTextRef.current ? `${existingTextRef.current} ${text}` : text, {
+ shouldValidate: true,
+ });
+ },
+ [setValue],
+ );
+
+ const [settling, setSettling] = useState(false);
+ const onTranscriptionSettled = useCallback((takeId?: number) => {
+ if (takeId == null || takeId === takeIdRef.current) {
+ setSettling(false);
+ }
+ }, []);
+ const { isListening, isLoading, startRecording, stopRecording, abortRecording } = useSpeechToText(
+ setText,
+ onTranscriptionComplete,
+ onTranscriptionSettled,
+ autoSendText,
+ );
+
+ const active = isListening === true;
+
+ /* Bridges the gap between the recorder being told to stop and the upload
+ starting: `isListening` clears synchronously, while the recorder's own
+ `stop` event, which is what begins the transcription request, arrives a
+ tick later. Without this the composer reads as idle for that tick and every
+ control it had put away flashes back in and out again. */
+ const [elapsed, setElapsed] = useState(0);
+ useEffect(() => {
+ if (!active) {
+ setElapsed(0);
+ return;
+ }
+ const timer = setInterval(() => setElapsed((value) => value + 1), 1000);
+ return () => clearInterval(timer);
+ }, [active]);
+
+ /* The engines only report a completed transcription when Auto Send Text is
+ configured, so an explicit stop-and-send cannot wait for that callback:
+ with the default setting it never arrives. Instead the send is armed here
+ and spent once the take has fully settled, reading whatever the transcript
+ put in the composer. */
+ const [pendingSend, setPendingSend] = useState(false);
+ useEffect(() => {
+ if (!pendingSend || active || isLoading === true || settling) {
+ return;
+ }
+ setPendingSend(false);
+ /* Nothing was heard: the request failed, or the take never reached the
+ engine. The engines report that themselves, so the send simply stands
+ down rather than sending the pre-recording draft in its place. */
+ if (!heardRef.current) {
+ return;
+ }
+ submit(getValues('text') || '');
+ }, [pendingSend, active, isLoading, settling, submit, getValues]);
+ /* A discarded request can remain in React Query's loading state until the
+ network settles. It no longer owns the composer once cancel is pressed. */
+ const [discarded, setDiscarded] = useState(false);
+
+ const start = useCallback(() => {
+ if (disabled || isLoading === true || settling) {
+ /* Do not re-arm the canceled take before its late callback arrives. */
+ return;
+ }
+ const takeId = takeIdRef.current + 1;
+ takeIdRef.current = takeId;
+ modeRef.current = 'compose';
+ spentRef.current = false;
+ heardRef.current = false;
+ setDiscarded(false);
+ setPendingSend(false);
+ existingTextRef.current = getValues('text') || '';
+ startRecording(takeId);
+ }, [disabled, getValues, isLoading, settling, startRecording]);
+
+ /* Only a running take can be stopped. The bar disables stop and send once a
+ transcription is in flight, and this hook keeps the same boundary. */
+ const activeRef = useRef(active);
+ activeRef.current = active;
+ const stopWith = useCallback(
+ (mode: StopMode) => {
+ if (!activeRef.current) {
+ return;
+ }
+ modeRef.current = mode;
+ setSettling(true);
+ if (mode === 'send') {
+ setPendingSend(true);
+ }
+ stopRecording();
+ },
+ [stopRecording],
+ );
+
+ /* A real abort, not a stop that throws the result away. The token invalidates
+ callbacks from this take even if an external request settles later. */
+ const cancel = useCallback(() => {
+ takeIdRef.current += 1;
+ modeRef.current = 'cancel';
+ spentRef.current = true;
+ setDiscarded(true);
+ setSettling(false);
+ setPendingSend(false);
+ abortRecording();
+ reset({ text: existingTextRef.current });
+ }, [abortRecording, reset]);
+
+ const stopToComposer = useCallback(() => stopWith('compose'), [stopWith]);
+ const stopAndSend = useCallback(() => stopWith('send'), [stopWith]);
+
+ useEffect(() => {
+ const handleShortcut = (event: KeyboardEvent) => {
+ if (
+ disabled ||
+ speechToText !== true ||
+ !isFocusedChatPane(index) ||
+ event.code !== 'KeyL' ||
+ !event.shiftKey ||
+ !event.altKey ||
+ event.ctrlKey ||
+ event.metaKey
+ ) {
+ return;
+ }
+ event.preventDefault();
+ if (activeRef.current) {
+ stopToComposer();
+ } else {
+ start();
+ }
+ };
+ window.addEventListener('keydown', handleShortcut);
+ return () => window.removeEventListener('keydown', handleShortcut);
+ }, [disabled, index, speechToText, start, stopToComposer]);
+
+ /* Memoized so `memo(Bar)` has something that can compare equal: a fresh
+ object here re-rendered the whole bar on every keystroke in the composer. */
+ return useMemo(
+ () => ({
+ active,
+ transcribing: !discarded && (isLoading === true || settling),
+ startDisabled: disabled || isLoading === true || settling,
+ elapsed,
+ start,
+ cancel,
+ stopToComposer,
+ stopAndSend,
+ }),
+ [
+ active,
+ discarded,
+ disabled,
+ isLoading,
+ settling,
+ elapsed,
+ start,
+ cancel,
+ stopToComposer,
+ stopAndSend,
+ ],
+ );
+}
diff --git a/client/src/hooks/Input/usePaletteEntries.tsx b/client/src/hooks/Input/usePaletteEntries.tsx
new file mode 100644
index 0000000000..6ff787e833
--- /dev/null
+++ b/client/src/hooks/Input/usePaletteEntries.tsx
@@ -0,0 +1,595 @@
+import React, { useMemo, useEffect, useRef, useCallback } from 'react';
+import { MCPIcon } from '@librechat/client';
+import { useRecoilValue, useSetRecoilState } from 'recoil';
+import {
+ Brain,
+ Globe,
+ Layers,
+ Settings,
+ X,
+ FolderSearch,
+ WandSparkles,
+ SquareChevronRight,
+} from 'lucide-react';
+import {
+ AuthType,
+ Permissions,
+ ArtifactModes,
+ PermissionTypes,
+ SkillsScope,
+ isEphemeralAgentId,
+ defaultAgentCapabilities,
+ resolveAgentSkillsScope,
+} from 'librechat-data-provider';
+import type { TSkillSummary, TToolFavoriteType } from 'librechat-data-provider';
+import {
+ useHasAccess,
+ useAuthContext,
+ useHasMemoryAccess,
+ useAgentCapabilities,
+ useSkillActiveState,
+} from '~/hooks';
+import { filterSkillsForPopover } from '~/components/Chat/Input/SkillsCommand';
+import { useAgentsMapContext, useBadgeRowContext } from '~/Providers';
+import { useSkillsInfiniteQuery } from '~/data-provider';
+import store, { ephemeralAgentByConvoId } from '~/store';
+import { favoriteKey } from './useToolFavorites';
+import useLocalize from '~/hooks/useLocalize';
+
+export type PaletteSection = 'tool' | 'skill' | 'mcp';
+
+/**
+ * One selectable row in the composer palette. Tools, skills and MCP servers are
+ * normalized to the same shape so search, favouriting and rendering each run
+ * once over a single list rather than per source.
+ */
+export interface PaletteMode {
+ id: string;
+ label: string;
+ active: boolean;
+ onSelect: () => void;
+ /** When set, the palette row renders this instead of the text pill (e.g. a
+ * gear for Configure). Icon modes stay off the bar chip so they do not
+ * open a Configure/chevron menu. */
+ icon?: React.ReactNode;
+}
+
+export interface PaletteEntry {
+ key: string;
+ itemType: TToolFavoriteType;
+ itemId: string;
+ label: string;
+ description?: string;
+ icon: React.ReactNode;
+ section: PaletteSection;
+ active: boolean;
+ /** Keeps an inactive built-in available as a prompt-bar quick control. */
+ pinned: boolean;
+ /** Temporary catalog placeholders do not have a durable favorite identity. */
+ favoritable?: boolean;
+ onSelect: () => void;
+ /** Removes a persistent pin without changing the tool's active state. */
+ onUnpin?: () => void;
+ /** Refinements of this tool, rendered as inline pills on the row while it is
+ * on. Not separately favouritable: they only exist within the parent. */
+ modes?: PaletteMode[];
+}
+
+/** Accumulates skill pages so client-side search covers the full catalog. */
+function useAllSkills(enabled: boolean, openRevision: number): TSkillSummary[] {
+ const { data, isError, fetchNextPage, hasNextPage, isFetchingNextPage, refetch } =
+ useSkillsInfiniteQuery({ limit: 50 }, { enabled });
+
+ /* Circuit breaker: once any page request fails, stop auto-fetching so a
+ transient API error does not turn into an unbounded retry loop. A later
+ successful fetch (React Query refetching in the background, or the user
+ reopening the palette) re-arms pagination; a repeat failure re-trips it. */
+ const blockedRef = useRef(false);
+ const previousOpenRevisionRef = useRef(openRevision);
+ useEffect(() => {
+ if (isError) {
+ blockedRef.current = true;
+ } else if (data != null) {
+ blockedRef.current = false;
+ }
+ }, [isError, data]);
+
+ useEffect(() => {
+ if (previousOpenRevisionRef.current === openRevision) {
+ return;
+ }
+ previousOpenRevisionRef.current = openRevision;
+ if (enabled && isError) {
+ blockedRef.current = false;
+ void refetch();
+ }
+ }, [enabled, isError, openRevision, refetch]);
+
+ useEffect(() => {
+ if (blockedRef.current || isError || !enabled) {
+ return;
+ }
+ if (hasNextPage && !isFetchingNextPage) {
+ fetchNextPage();
+ }
+ }, [enabled, hasNextPage, isFetchingNextPage, isError, fetchNextPage]);
+
+ return useMemo(() => {
+ if (!data?.pages) {
+ return [];
+ }
+ const all: TSkillSummary[] = [];
+ for (const page of data.pages) {
+ for (const skill of page.skills) {
+ all.push(skill);
+ }
+ }
+ return all;
+ }, [data?.pages]);
+}
+
+export default function usePaletteEntries({
+ conversationId,
+ agentId,
+ enabled = true,
+ toolsEnabled = enabled,
+ catalogEnabled = true,
+ catalogOpenRevision = 0,
+ favoriteKeys,
+}: {
+ conversationId: string;
+ agentId?: string | null;
+ /** Endpoints without a tool row discard these, so there is nothing to fetch
+ * or build for them. */
+ enabled?: boolean;
+ /** Whether ephemeral built-ins and MCP servers belong to this endpoint. */
+ toolsEnabled?: boolean;
+ /** Whether to walk the full skills catalog. The bar keeps this off until the
+ * palette has actually been opened: following every cursor on mount pulled
+ * a deployment's whole catalog into every composer that was merely visited. */
+ catalogEnabled?: boolean;
+ /** Increments on each palette open so a failed catalog walk can retry. */
+ catalogOpenRevision?: number;
+ /** Favorited `${itemType}:${itemId}` keys, so a name shared by several skill
+ * records is represented by the one the user starred. */
+ favoriteKeys?: ReadonlySet<string>;
+}): PaletteEntry[] {
+ const localize = useLocalize();
+ const context = useBadgeRowContext();
+ const agentsMap = useAgentsMapContext();
+ const { isActive } = useSkillActiveState();
+ const setEphemeralAgent = useSetRecoilState(ephemeralAgentByConvoId(conversationId));
+ const pendingManualSkills = useRecoilValue(store.pendingManualSkillsByConvoId(conversationId));
+ const setPendingManualSkills = useSetRecoilState(
+ store.pendingManualSkillsByConvoId(conversationId),
+ );
+
+ const {
+ codeEnabled,
+ memoryEnabled,
+ webSearchEnabled,
+ artifactsEnabled,
+ fileSearchEnabled,
+ skillsEnabled,
+ } = useAgentCapabilities(context?.agentsConfig?.capabilities ?? defaultAgentCapabilities);
+
+ const canUseWebSearch = useHasAccess({
+ permissionType: PermissionTypes.WEB_SEARCH,
+ permission: Permissions.USE,
+ });
+ const canRunCode = useHasAccess({
+ permissionType: PermissionTypes.RUN_CODE,
+ permission: Permissions.USE,
+ });
+ const canUseFileSearch = useHasAccess({
+ permissionType: PermissionTypes.FILE_SEARCH,
+ permission: Permissions.USE,
+ });
+ const canUseMcp = useHasAccess({
+ permissionType: PermissionTypes.MCP_SERVERS,
+ permission: Permissions.USE,
+ });
+ const canUseSkills = useHasAccess({
+ permissionType: PermissionTypes.SKILLS,
+ permission: Permissions.USE,
+ });
+ const { user } = useAuthContext();
+ /* Personalization is the user's own opt-out and the backend refuses to
+ register the memory tools once it is off, so role access and the global
+ capability are not enough to offer the toggle. */
+ const canUseMemory = useHasMemoryAccess() && user?.personalization?.memories !== false;
+
+ /* Mirrors backend `resolveAgentScopedSkillIds`: ephemeral agents see the full
+ catalog; persisted agents gate on `skills_enabled` and the resolved scope,
+ and fail closed while `agentsMap` is hydrating or when the agent is missing
+ from it. */
+ const agentSkillIds = useMemo<string[] | null | undefined>(() => {
+ if (!agentId || isEphemeralAgentId(agentId)) {
+ return undefined;
+ }
+ if (!agentsMap) {
+ return [];
+ }
+ const agent = agentsMap[agentId];
+ if (!agent || agent.skills_enabled !== true) {
+ return [];
+ }
+ const scope = resolveAgentSkillsScope(agent.skills, agent.skills_enabled, agent.skills_scope);
+ if (scope === SkillsScope.none) {
+ return [];
+ }
+ if (scope === SkillsScope.all) {
+ return undefined;
+ }
+ return agent.skills ?? [];
+ }, [agentId, agentsMap]);
+
+ /* A saved agent whose scope admits no skill renders no skill rows, so the
+ catalog is not paged in for it. */
+ const skillsListable = enabled && canUseSkills && skillsEnabled;
+ const allSkills = useAllSkills(
+ skillsListable && catalogEnabled && agentSkillIds?.length !== 0,
+ catalogOpenRevision,
+ );
+
+ /* A toggle, like every other row: picking a skill used to be one-way, so the
+ only way to undo a mis-click was to find the chip in the tray. */
+ const toggleSkill = useCallback(
+ (name: string) => {
+ if (pendingManualSkills.includes(name)) {
+ setPendingManualSkills((prev) => prev.filter((staged) => staged !== name));
+ return;
+ }
+ setEphemeralAgent((agent) =>
+ agent?.skills === true ? agent : { ...(agent ?? {}), skills: true },
+ );
+ setPendingManualSkills((prev) => (prev.includes(name) ? prev : [...prev, name]));
+ },
+ [pendingManualSkills, setEphemeralAgent, setPendingManualSkills],
+ );
+
+ return useMemo(() => {
+ const entries: PaletteEntry[] = [];
+ if (!context || !enabled) {
+ return entries;
+ }
+
+ const {
+ webSearch,
+ codeInterpreter,
+ fileSearch,
+ skills,
+ memory,
+ artifacts,
+ mcpServerManager,
+ searchApiKeyForm,
+ } = context;
+
+ const pushTool = (
+ itemId: string,
+ label: string,
+ icon: React.ReactNode,
+ active: boolean,
+ pinned: boolean,
+ onSelect: () => void,
+ onUnpin: () => void,
+ modes?: PaletteMode[],
+ ) => {
+ entries.push({
+ key: `builtin:${itemId}`,
+ itemType: 'builtin',
+ itemId,
+ label,
+ icon,
+ section: 'tool',
+ active,
+ pinned,
+ onSelect,
+ onUnpin,
+ modes,
+ });
+ };
+
+ if (toolsEnabled && canUseWebSearch && webSearchEnabled) {
+ /* Same rule the old tools menu used for its gear: only credentials the
+ user can actually provide are editable. Toggling opens the key dialog
+ on its own while unauthenticated, so this pill is what keeps existing
+ credentials reachable: editing, switching provider or revoking. */
+ const authTypes = webSearch.authData?.authTypes ?? [];
+ const searchConfigurable =
+ authTypes.length === 0 ||
+ !authTypes.every(([, authType]) => authType === AuthType.SYSTEM_DEFINED);
+ pushTool(
+ 'web_search',
+ localize('com_ui_web_search'),
+ <Globe className="icon-md" aria-hidden="true" />,
+ webSearch.toggleState === true,
+ webSearch.isPinned === true,
+ () => webSearch.debouncedChange({ value: !webSearch.toggleState }),
+ () => webSearch.setIsPinned(false),
+ searchConfigurable && searchApiKeyForm != null
+ ? [
+ {
+ id: 'configure',
+ label: localize('com_ui_configure'),
+ active: false,
+ icon: <Settings className="h-4 w-4" aria-hidden="true" />,
+ onSelect: () => searchApiKeyForm.setIsDialogOpen(true),
+ },
+ ]
+ : undefined,
+ );
+ }
+
+ if (toolsEnabled && canRunCode && codeEnabled) {
+ pushTool(
+ 'execute_code',
+ localize('com_ui_run_code'),
+ <SquareChevronRight className="icon-md" aria-hidden="true" />,
+ codeInterpreter.toggleState === true,
+ codeInterpreter.isPinned === true,
+ () => codeInterpreter.debouncedChange({ value: !codeInterpreter.toggleState }),
+ () => codeInterpreter.setIsPinned(false),
+ );
+ }
+
+ if (toolsEnabled && canUseFileSearch && fileSearchEnabled) {
+ pushTool(
+ 'file_search',
+ localize('com_assistants_file_search'),
+ <FolderSearch className="icon-md" aria-hidden="true" />,
+ fileSearch.toggleState === true,
+ fileSearch.isPinned === true,
+ () => fileSearch.debouncedChange({ value: !fileSearch.toggleState }),
+ () => fileSearch.setIsPinned(false),
+ );
+ }
+
+ if (toolsEnabled && skillsListable) {
+ pushTool(
+ 'skills',
+ localize('com_ui_skills'),
+ <WandSparkles className="icon-md" aria-hidden="true" />,
+ skills.toggleState === true,
+ skills.isPinned === true,
+ () => skills.debouncedChange({ value: !skills.toggleState }),
+ () => skills.setIsPinned(false),
+ );
+ }
+
+ if (toolsEnabled && canUseMemory && memoryEnabled) {
+ pushTool(
+ 'memory',
+ localize('com_ui_memory'),
+ <Brain className="icon-md" aria-hidden="true" />,
+ memory.toggleState === true,
+ memory.isPinned === true,
+ () => memory.debouncedChange({ value: !memory.toggleState }),
+ () => memory.setIsPinned(false),
+ );
+ }
+
+ if (toolsEnabled && artifactsEnabled) {
+ const stored = artifacts.toggleState;
+ const mode = stored == null || stored === false ? '' : String(stored);
+ const artifactsOn = mode !== '';
+ /* Anything on that is not an explicit generation mode counts as Default:
+ the toggle has historically also held a bare `true`, which would
+ otherwise leave every mode unchecked. */
+ const isDefault =
+ artifactsOn && mode !== ArtifactModes.SHADCNUI && mode !== ArtifactModes.CUSTOM;
+ /* The two generation modes only mean anything once artifacts are on, and
+ each toggles back to DEFAULT rather than off; same semantics the old
+ `ArtifactsSubMenu` had, as inline pills instead of two long rows. */
+ const buildMode = (id: string, label: string, target: string): PaletteMode => ({
+ id,
+ label,
+ active: mode === target,
+ onSelect: () =>
+ artifacts.debouncedChange({ value: mode === target ? ArtifactModes.DEFAULT : target }),
+ });
+ pushTool(
+ 'artifacts',
+ localize('com_ui_artifacts'),
+ <Layers className="icon-md" aria-hidden="true" />,
+ artifactsOn,
+ artifacts.isPinned === true,
+ () => artifacts.debouncedChange({ value: artifactsOn ? '' : ArtifactModes.DEFAULT }),
+ () => artifacts.setIsPinned(false),
+ artifactsOn
+ ? [
+ {
+ id: 'default',
+ label: localize('com_ui_default'),
+ active: isDefault,
+ onSelect: () => artifacts.debouncedChange({ value: ArtifactModes.DEFAULT }),
+ },
+ buildMode('shadcn', localize('com_ui_shadcnui'), ArtifactModes.SHADCNUI),
+ buildMode('custom', localize('com_ui_custom_prompt'), ArtifactModes.CUSTOM),
+ ]
+ : undefined,
+ );
+ }
+
+ if (skillsListable) {
+ const staged = new Set(pendingManualSkills);
+ /* Manual skills are primed by name server-side (`resolveManualSkills`),
+ so records sharing a name are one selectable thing however many of them
+ the catalog holds. Listed once each: otherwise every copy lit up when
+ any was picked, while the tray (keyed by name) showed a single chip. */
+ const listed = new Map<string, TSkillSummary>();
+ const isFavorite = (skill: TSkillSummary) =>
+ favoriteKeys?.has(favoriteKey('skill', skill._id)) === true;
+ for (const skill of filterSkillsForPopover(allSkills, { agentSkillIds, isActive })) {
+ const held = listed.get(skill.name);
+ /* The favorite is keyed by id, so the copy the user starred represents
+ the name; keeping the first copy dropped the star and the favorite. */
+ if (held == null || (!isFavorite(held) && isFavorite(skill))) {
+ listed.set(skill.name, skill);
+ }
+ }
+ for (const skill of listed.values()) {
+ entries.push({
+ key: `skill:${skill._id}`,
+ itemType: 'skill',
+ itemId: skill._id,
+ label: skill.displayTitle ?? skill.name,
+ description: skill.description,
+ icon: <WandSparkles className="icon-md" aria-hidden="true" />,
+ section: 'skill',
+ active: staged.has(skill.name),
+ pinned: false,
+ onSelect: () => toggleSkill(skill.name),
+ });
+ }
+ /* Skills staged by name (the slash command, or a draft restored before
+ the catalog loads) still need an entry, or their chips in the bar
+ would vanish while the catalog is not held. */
+ for (const name of staged) {
+ if (listed.has(name)) {
+ continue;
+ }
+ entries.push({
+ key: `skill:staged:${name}`,
+ itemType: 'skill',
+ itemId: name,
+ label: name,
+ icon: <WandSparkles className="icon-md" aria-hidden="true" />,
+ section: 'skill',
+ active: true,
+ pinned: false,
+ favoritable: false,
+ onSelect: () => toggleSkill(name),
+ });
+ }
+ }
+
+ const {
+ selectableServers,
+ mcpValues,
+ toggleServerSelection,
+ connectionStatus,
+ initializeServer,
+ getServerStatusIconProps,
+ } = mcpServerManager ?? {};
+ if (toolsEnabled && canUseMcp && selectableServers) {
+ const selected = new Set(mcpValues ?? []);
+ const syntheticClick = {
+ stopPropagation: () => {},
+ preventDefault: () => {},
+ } as React.MouseEvent;
+ for (const server of selectableServers) {
+ const title = server.config?.title || server.serverName;
+ const statusProps = getServerStatusIconProps?.(server.serverName);
+ /* A row for a server that is not connected routes through the manager
+ instead of blindly selecting: credentials first when the server wants
+ custom variables, otherwise a reinitialize, which runs the OAuth
+ flow when needed and selects the server itself once it is ready.
+ Selecting an unusable server here used to be a dead end: every
+ connect, authenticate and retry control lived in the menu this
+ palette replaced. */
+ const selectServer = () => {
+ if (selected.has(server.serverName)) {
+ toggleServerSelection?.(server.serverName);
+ return;
+ }
+ /* An unknown status means the server has not reported a connection
+ yet, which is not the same as being connected: treat it like a
+ disconnected server so it initializes before it can be selected. */
+ if (connectionStatus?.[server.serverName]?.connectionState !== 'connected') {
+ if (statusProps?.isInitializing) {
+ return;
+ }
+ if (statusProps?.hasCustomUserVars) {
+ statusProps.onConfigClick(syntheticClick);
+ return;
+ }
+ void initializeServer?.(server.serverName);
+ return;
+ }
+ toggleServerSelection?.(server.serverName);
+ };
+ /* A connected server keeps its per-user variables editable: the
+ palette row carries the Configure action the replaced menu had. */
+ const getServerModes = (): PaletteMode[] | undefined => {
+ if (statusProps?.isInitializing === true && statusProps.canCancel === true) {
+ return [
+ {
+ id: 'cancel',
+ label: localize('com_ui_cancel'),
+ active: false,
+ icon: <X className="h-4 w-4" aria-hidden="true" />,
+ onSelect: () => statusProps.onCancel(syntheticClick),
+ },
+ ];
+ }
+ if (
+ statusProps?.hasCustomUserVars === true &&
+ connectionStatus?.[server.serverName]?.connectionState === 'connected'
+ ) {
+ return [
+ {
+ id: 'configure',
+ label: localize('com_ui_configure'),
+ active: false,
+ icon: <Settings className="h-4 w-4" aria-hidden="true" />,
+ onSelect: () => statusProps.onConfigClick(syntheticClick),
+ },
+ ];
+ }
+ return undefined;
+ };
+ entries.push({
+ key: `mcp:${server.serverName}`,
+ itemType: 'mcp',
+ itemId: server.serverName,
+ label: title,
+ description: server.config?.description,
+ /* Servers ship their own branding; fall back to the generic MCP mark
+ so a server without `iconPath` still reads as an MCP server rather
+ than borrowing an unrelated tool glyph. */
+ icon:
+ server.config?.iconPath != null && server.config.iconPath !== '' ? (
+ <img
+ src={server.config.iconPath}
+ alt=""
+ aria-hidden="true"
+ className="h-4 w-4 rounded-sm object-contain"
+ />
+ ) : (
+ <MCPIcon className="h-4 w-4" aria-hidden="true" />
+ ),
+ section: 'mcp',
+ active: selected.has(server.serverName),
+ pinned: false,
+ onSelect: selectServer,
+ modes: getServerModes(),
+ });
+ }
+ }
+
+ return entries;
+ }, [
+ context,
+ enabled,
+ toolsEnabled,
+ localize,
+ canUseMcp,
+ canRunCode,
+ codeEnabled,
+ allSkills,
+ isActive,
+ toggleSkill,
+ favoriteKeys,
+ pendingManualSkills,
+ canUseMemory,
+ memoryEnabled,
+ agentSkillIds,
+ skillsListable,
+ canUseWebSearch,
+ webSearchEnabled,
+ artifactsEnabled,
+ canUseFileSearch,
+ fileSearchEnabled,
+ ]);
+}
diff --git a/client/src/hooks/Input/useRecentFiles.ts b/client/src/hooks/Input/useRecentFiles.ts
new file mode 100644
index 0000000000..6a0cc8ce02
--- /dev/null
+++ b/client/src/hooks/Input/useRecentFiles.ts
@@ -0,0 +1,43 @@
+import { useMemo } from 'react';
+import { DEFAULT_COMPOSER_RECENT_FILES } from 'librechat-data-provider';
+import type { TFile } from 'librechat-data-provider';
+import type { AttachExistingContext } from '~/hooks/Files/useAttachExisting';
+import { useGetFiles, useGetRecentFiles, useGetStartupConfig } from '~/data-provider';
+import useAttachExisting from '~/hooks/Files/useAttachExisting';
+
+/**
+ * The user's files for the composer palette attach section.
+ *
+ * Unsearched: a short server-sorted page of the most recently touched files
+ * (opened only while the palette is open). Searching: the full list, filtered
+ * client-side by filename: the palette is a shortcut when idle, a finder
+ * once the user starts typing.
+ */
+export default function useRecentFiles(
+ enabled: boolean,
+ context: AttachExistingContext,
+ search = '',
+): {
+ files: TFile[];
+ attach: (file: TFile) => void;
+} {
+ const { data: startupConfig } = useGetStartupConfig();
+ const recentFileCount =
+ startupConfig?.interface?.composerRecentFiles ?? DEFAULT_COMPOSER_RECENT_FILES;
+ const query = search.trim().toLowerCase();
+ const searching = query.length > 0;
+ const { data: recent } = useGetRecentFiles(recentFileCount, {
+ enabled: enabled && !searching,
+ });
+ const { data: all } = useGetFiles<TFile[]>({ enabled: enabled && searching });
+ const attach = useAttachExisting(context);
+
+ const files = useMemo(() => {
+ if (searching) {
+ return (all ?? []).filter((file) => file.filename?.toLowerCase().includes(query));
+ }
+ return recent ?? [];
+ }, [searching, query, all, recent]);
+
+ return { files, attach };
+}
diff --git a/client/src/hooks/Input/useSpeechToText.spec.ts b/client/src/hooks/Input/useSpeechToText.spec.ts
index 34eb38f04a..4e099d231c 100644
--- a/client/src/hooks/Input/useSpeechToText.spec.ts
+++ b/client/src/hooks/Input/useSpeechToText.spec.ts
@@ -45,7 +45,9 @@ describe('useSpeechToText', () => {
it('selects the externally seeded engine after settings change', () => {
mockSpeechToTextEndpoint = 'browser';
- const { result, rerender } = renderHook(() => useSpeechToText(jest.fn(), jest.fn()));
+ const { result, rerender } = renderHook(() =>
+ useSpeechToText(jest.fn(), jest.fn(), jest.fn(), -1),
+ );
mockSpeechToTextEndpoint = 'external';
rerender();
@@ -58,7 +60,7 @@ describe('useSpeechToText', () => {
it('selects the browser engine', () => {
mockSpeechToTextEndpoint = 'browser';
- const { result } = renderHook(() => useSpeechToText(jest.fn(), jest.fn()));
+ const { result } = renderHook(() => useSpeechToText(jest.fn(), jest.fn(), jest.fn(), -1));
act(() => result.current.startRecording());
@@ -68,7 +70,7 @@ describe('useSpeechToText', () => {
it('selects the active engine stop handler', () => {
mockExternalIsListening = true;
- const { result } = renderHook(() => useSpeechToText(jest.fn(), jest.fn()));
+ const { result } = renderHook(() => useSpeechToText(jest.fn(), jest.fn(), jest.fn(), -1));
act(() => result.current.stopRecording());
diff --git a/client/src/hooks/Input/useSpeechToText.ts b/client/src/hooks/Input/useSpeechToText.ts
index f149b72af8..47a10f11ff 100644
--- a/client/src/hooks/Input/useSpeechToText.ts
+++ b/client/src/hooks/Input/useSpeechToText.ts
@@ -3,13 +3,18 @@ import useSpeechToTextBrowser from './useSpeechToTextBrowser';
import useGetAudioSettings from './useGetAudioSettings';
const useSpeechToText = (
- setText: (text: string) => void,
- onTranscriptionComplete: (text: string) => void,
+ setText: (text: string, takeId?: number) => void,
+ onTranscriptionComplete: (text: string, takeId?: number) => void,
+ onTranscriptionSettled: (takeId?: number) => void,
+ /** Host-owned Auto Send Text preference. */
+ autoSendText: number,
): {
isLoading?: boolean;
isListening?: boolean;
- stopRecording: () => void | (() => Promise<void>);
- startRecording: () => void | (() => Promise<void>);
+ stopRecording: () => void | Promise<void>;
+ startRecording: (takeId?: number) => void | Promise<void>;
+ /** Ends capture without producing a transcript. */
+ abortRecording: () => void;
} => {
const { speechToTextEndpoint } = useGetAudioSettings();
const externalSpeechToText = speechToTextEndpoint === 'external';
@@ -19,14 +24,26 @@ const useSpeechToText = (
isLoading: speechIsLoadingBrowser,
startRecording: startSpeechRecordingBrowser,
stopRecording: stopSpeechRecordingBrowser,
- } = useSpeechToTextBrowser(setText, onTranscriptionComplete);
+ abortRecording: abortSpeechRecordingBrowser,
+ } = useSpeechToTextBrowser(
+ setText,
+ onTranscriptionComplete,
+ onTranscriptionSettled,
+ autoSendText,
+ );
const {
isListening: speechIsListeningExternal,
isLoading: speechIsLoadingExternal,
externalStartRecording: startSpeechRecordingExternal,
externalStopRecording: stopSpeechRecordingExternal,
- } = useSpeechToTextExternal(setText, onTranscriptionComplete);
+ externalAbortRecording: abortSpeechRecordingExternal,
+ } = useSpeechToTextExternal(
+ setText,
+ onTranscriptionComplete,
+ onTranscriptionSettled,
+ autoSendText,
+ );
const isListening = externalSpeechToText ? speechIsListeningExternal : speechIsListeningBrowser;
const isLoading = externalSpeechToText ? speechIsLoadingExternal : speechIsLoadingBrowser;
@@ -38,11 +55,16 @@ const useSpeechToText = (
? stopSpeechRecordingExternal
: stopSpeechRecordingBrowser;
+ const abortRecording = externalSpeechToText
+ ? abortSpeechRecordingExternal
+ : abortSpeechRecordingBrowser;
+
return {
isLoading,
isListening,
stopRecording,
startRecording,
+ abortRecording,
};
};
diff --git a/client/src/hooks/Input/useSpeechToTextBrowser.ts b/client/src/hooks/Input/useSpeechToTextBrowser.ts
index a72403a239..c473b7765d 100644
--- a/client/src/hooks/Input/useSpeechToTextBrowser.ts
+++ b/client/src/hooks/Input/useSpeechToTextBrowser.ts
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useRef } from 'react';
+import { useState, useCallback, useEffect, useRef } from 'react';
import { useRecoilState } from 'recoil';
import { useToastContext } from '@librechat/client';
import { useGetCustomConfigSpeechQuery } from 'librechat-data-provider/react-query';
@@ -6,10 +6,13 @@ import SpeechRecognitionImport, { useSpeechRecognition } from 'react-speech-reco
import { useLocalize } from '~/hooks';
import store from '~/store';
+/** `abortListening` stays optional: it is not part of what makes a module a
+ * usable controller, so a build without it must still count as supported. */
type SpeechRecognitionController = Pick<
typeof SpeechRecognitionImport,
'startListening' | 'stopListening'
->;
+> &
+ Partial<Pick<typeof SpeechRecognitionImport, 'abortListening'>>;
type SpeechRecognitionModule = Partial<SpeechRecognitionController> & {
default?: Partial<SpeechRecognitionController>;
};
@@ -26,8 +29,10 @@ const SpeechRecognition = hasSpeechRecognitionController(speechRecognitionModule
: speechRecognitionModule.default;
const useSpeechToTextBrowser = (
- setText: (text: string) => void,
- onTranscriptionComplete: (text: string) => void,
+ setText: (text: string, takeId?: number) => void,
+ onTranscriptionComplete: (text: string, takeId?: number) => void,
+ onTranscriptionSettled: (takeId?: number) => void,
+ autoSendText: number,
) => {
const localize = useLocalize();
const { showToast } = useToastContext();
@@ -36,8 +41,8 @@ const useSpeechToTextBrowser = (
const lastTranscript = useRef<string | null>(null);
const lastInterim = useRef<string | null>(null);
+ const activeTakeIdRef = useRef<number | undefined>(undefined);
const timeoutRef = useRef<NodeJS.Timeout | null>();
- const [autoSendText] = useRecoilState(store.autoSendText);
const [languageSTT] = useRecoilState<string>(store.languageSTT);
const [autoTranscribeAudio] = useRecoilState<boolean>(store.autoTranscribeAudio);
@@ -60,7 +65,7 @@ const useSpeechToTextBrowser = (
return;
}
- setText(interimTranscript);
+ setText(interimTranscript, activeTakeIdRef.current);
lastInterim.current = interimTranscript;
}, [setText, interimTranscript]);
@@ -73,11 +78,12 @@ const useSpeechToTextBrowser = (
return;
}
- setText(finalTranscript);
+ const takeId = activeTakeIdRef.current;
+ setText(finalTranscript, takeId);
lastTranscript.current = finalTranscript;
if (autoSendText > -1 && finalTranscript.length > 0) {
timeoutRef.current = setTimeout(() => {
- onTranscriptionComplete(finalTranscript);
+ onTranscriptionComplete(finalTranscript, takeId);
resetTranscript();
}, autoSendText * 1000);
}
@@ -89,59 +95,107 @@ const useSpeechToTextBrowser = (
};
}, [setText, onTranscriptionComplete, resetTranscript, finalTranscript, autoSendText]);
- const toggleListening = useCallback(() => {
- if (!browserSupportsSpeechRecognition) {
- showToast({
- message: sttExternal
- ? localize('com_ui_speech_not_supported_use_external')
- : localize('com_ui_speech_not_supported'),
- status: 'error',
- });
+ /**
+ * The recognizer's final result lands in `useSpeechRecognition`'s reducer before
+ * `stopListening` resolves, but reaches `setText` only through the effect above.
+ * Settling from an effect declared after it, off a state update queued behind that
+ * result, keeps the take busy until the final transcript is in the composer.
+ */
+ const [stoppedTake, setStoppedTake] = useState<{ takeId?: number } | null>(null);
+ useEffect(() => {
+ if (stoppedTake == null) {
return;
}
+ setStoppedTake(null);
+ onTranscriptionSettled(stoppedTake.takeId);
+ }, [stoppedTake, onTranscriptionSettled]);
+
+ const startRecording = useCallback(
+ (takeId?: number) => {
+ activeTakeIdRef.current = takeId;
+ if (!browserSupportsSpeechRecognition) {
+ showToast({
+ message: sttExternal
+ ? localize('com_ui_speech_not_supported_use_external')
+ : localize('com_ui_speech_not_supported'),
+ status: 'error',
+ });
+ return;
+ }
- if (!isMicrophoneAvailable) {
- showToast({
- message: localize('com_ui_microphone_unavailable'),
- status: 'error',
- });
- return;
- }
+ if (!isMicrophoneAvailable) {
+ showToast({
+ message: localize('com_ui_microphone_unavailable'),
+ status: 'error',
+ });
+ return;
+ }
- if (!hasSpeechRecognitionController(SpeechRecognition)) {
- showToast({
- message: sttExternal
- ? localize('com_ui_speech_not_supported_use_external')
- : localize('com_ui_speech_not_supported'),
- status: 'error',
- });
- return;
- }
+ if (!hasSpeechRecognitionController(SpeechRecognition)) {
+ showToast({
+ message: sttExternal
+ ? localize('com_ui_speech_not_supported_use_external')
+ : localize('com_ui_speech_not_supported'),
+ status: 'error',
+ });
+ return;
+ }
- if (isListening === true) {
- SpeechRecognition.stopListening();
- } else {
SpeechRecognition.startListening({
language: languageSTT,
continuous: autoTranscribeAudio,
});
+ },
+ [
+ autoTranscribeAudio,
+ browserSupportsSpeechRecognition,
+ isMicrophoneAvailable,
+ languageSTT,
+ localize,
+ showToast,
+ sttExternal,
+ ],
+ );
+
+ const stopRecording = useCallback(async () => {
+ const takeId = activeTakeIdRef.current;
+ try {
+ if (hasSpeechRecognitionController(SpeechRecognition)) {
+ await SpeechRecognition.stopListening();
+ }
+ } finally {
+ setStoppedTake({ takeId });
}
- }, [
- autoTranscribeAudio,
- browserSupportsSpeechRecognition,
- isListening,
- isMicrophoneAvailable,
- languageSTT,
- localize,
- showToast,
- sttExternal,
- ]);
+ }, []);
+
+ /**
+ * Drops the take without emitting a transcript. `abortListening` discards the
+ * recogniser's buffered result, and the pending auto-send timer is cleared so
+ * a transcript that already landed cannot fire after the user cancelled.
+ */
+ const abortListening = useCallback(() => {
+ if (timeoutRef.current) {
+ clearTimeout(timeoutRef.current);
+ timeoutRef.current = null;
+ }
+ lastTranscript.current = null;
+ lastInterim.current = null;
+ if (hasSpeechRecognitionController(SpeechRecognition)) {
+ if (typeof SpeechRecognition.abortListening === 'function') {
+ SpeechRecognition.abortListening();
+ } else {
+ SpeechRecognition.stopListening();
+ }
+ }
+ resetTranscript();
+ }, [resetTranscript]);
return {
isListening,
isLoading: false,
- startRecording: toggleListening,
- stopRecording: toggleListening,
+ startRecording,
+ stopRecording,
+ abortRecording: abortListening,
};
};
diff --git a/client/src/hooks/Input/useSpeechToTextExternal.ts b/client/src/hooks/Input/useSpeechToTextExternal.ts
index 6dc698ceeb..33b38acc1d 100644
--- a/client/src/hooks/Input/useSpeechToTextExternal.ts
+++ b/client/src/hooks/Input/useSpeechToTextExternal.ts
@@ -1,4 +1,4 @@
-import { useState, useRef } from 'react';
+import { useState, useEffect, useRef } from 'react';
import { useRecoilState } from 'recoil';
import { useToastContext } from '@librechat/client';
import { useSpeechToTextMutation } from '~/data-provider';
@@ -35,8 +35,10 @@ export const getBestSupportedMimeType = (
};
const useSpeechToTextExternal = (
- setText: (text: string) => void,
- onTranscriptionComplete: (text: string) => void,
+ setText: (text: string, takeId?: number) => void,
+ onTranscriptionComplete: (text: string, takeId?: number) => void,
+ onTranscriptionSettled: (takeId?: number) => void,
+ autoSendText: number,
) => {
const { showToast } = useToastContext();
const audioStream = useRef<MediaStream | null>(null);
@@ -45,36 +47,28 @@ const useSpeechToTextExternal = (
const mediaRecorderRef = useRef<MediaRecorder | null>(null);
const audioChunksRef = useRef<Blob[]>([]);
+ /** Read by the recorder's `stop` handler, which fires a tick after the call
+ * that ended capture and cannot otherwise tell an abort from a stop. */
+ const abortedRef = useRef(false);
+ /** Cleared on unmount so a queued auto-send cannot fire into a gone composer. */
+ const autoSendTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ /** Guards the async permission request: a stream that resolves after unmount
+ * would otherwise hold the microphone open with nothing left to stop it. */
+ const isMountedRef = useRef(true);
+ /** The type the recorder was actually constructed with. `handleStop` runs
+ * from a listener registered at start, so state read there is a render
+ * behind and could pack the blob as a format the audio is not in. */
+ const audioMimeTypeRef = useRef<string>('');
+ const recordingTakeIdRef = useRef<number | undefined>(undefined);
const [isListening, setIsListening] = useState(false);
const [isRequestBeingMade, setIsRequestBeingMade] = useState(false);
- const [audioMimeType, setAudioMimeType] = useState<string>(() => getBestSupportedMimeType());
const [minDecibels] = useRecoilState(store.decibelValue);
- const [autoSendText] = useRecoilState(store.autoSendText);
const [languageSTT] = useRecoilState<string>(store.languageSTT);
const [speechToText] = useRecoilState<boolean>(store.speechToText);
const [autoTranscribeAudio] = useRecoilState<boolean>(store.autoTranscribeAudio);
- const { mutate: processAudio, isLoading: isProcessing } = useSpeechToTextMutation({
- onSuccess: (data) => {
- const extractedText = data.text;
- setText(extractedText);
- setIsRequestBeingMade(false);
-
- if (autoSendText > -1 && speechToText && extractedText.length > 0) {
- setTimeout(() => {
- onTranscriptionComplete(extractedText);
- }, autoSendText * 1000);
- }
- },
- onError: () => {
- showToast({
- message: 'An error occurred while processing the audio, maybe the audio was too short',
- status: 'error',
- });
- setIsRequestBeingMade(false);
- },
- });
+ const { mutate: processAudio, isLoading: isProcessing } = useSpeechToTextMutation();
const getFileExtension = (mimeType: string) => {
if (mimeType.includes('mp4')) {
@@ -100,6 +94,10 @@ const useSpeechToTextExternal = (
audio: true,
video: false,
});
+ if (!isMountedRef.current) {
+ streamData?.getTracks().forEach((track) => track.stop());
+ return;
+ }
audioStream.current = streamData ?? null;
} catch {
audioStream.current = null;
@@ -107,9 +105,16 @@ const useSpeechToTextExternal = (
};
const handleStop = () => {
+ if (abortedRef.current) {
+ abortedRef.current = false;
+ audioChunksRef.current = [];
+ cleanup();
+ return;
+ }
+
if (audioChunksRef.current.length > 0) {
- const audioBlob = new Blob(audioChunksRef.current, { type: audioMimeType });
- const fileExtension = getFileExtension(audioMimeType);
+ const audioBlob = new Blob(audioChunksRef.current, { type: audioMimeTypeRef.current });
+ const fileExtension = getFileExtension(audioMimeTypeRef.current);
audioChunksRef.current = [];
@@ -120,14 +125,48 @@ const useSpeechToTextExternal = (
}
setIsRequestBeingMade(true);
cleanup();
- processAudio(formData);
+ const takeId = recordingTakeIdRef.current;
+ processAudio(formData, {
+ onSuccess: (data) => {
+ if (!isMountedRef.current) {
+ return;
+ }
+ const extractedText = data.text;
+ setText(extractedText, takeId);
+ setIsRequestBeingMade(false);
+ onTranscriptionSettled(takeId);
+ if (autoSendText > -1 && speechToText && extractedText.length > 0) {
+ if (autoSendTimerRef.current != null) {
+ clearTimeout(autoSendTimerRef.current);
+ autoSendTimerRef.current = null;
+ }
+ autoSendTimerRef.current = setTimeout(() => {
+ autoSendTimerRef.current = null;
+ onTranscriptionComplete(extractedText, takeId);
+ }, autoSendText * 1000);
+ }
+ },
+ onError: () => {
+ showToast({
+ message: 'An error occurred while processing the audio, maybe the audio was too short',
+ status: 'error',
+ });
+ setIsRequestBeingMade(false);
+ onTranscriptionSettled(takeId);
+ },
+ });
} else {
showToast({ message: 'The audio was too short', status: 'warning' });
+ onTranscriptionSettled(recordingTakeIdRef.current);
}
};
const monitorSilence = (stream: MediaStream, stopRecording: () => void) => {
+ /* Held so it can be closed again: without this the ref below is never
+ assigned, its guard is always true, and every take leaves another audio
+ context open until the browser refuses to grant one. */
const audioContext = new AudioContext();
+ audioContextRef.current = audioContext;
const audioStreamSource = audioContext.createMediaStreamSource(stream);
const analyser = audioContext.createAnalyser();
analyser.minDecibels = minDecibels;
@@ -159,12 +198,31 @@ const useSpeechToTextExternal = (
animationFrameIdRef.current = window.requestAnimationFrame(detectSound);
};
- const startRecording = async () => {
+ /** Stops and drops the capture this hook owns; safe to call more than once. */
+ const releaseAudioStream = () => {
+ audioStream.current?.getTracks().forEach((track) => track.stop());
+ audioStream.current = null;
+ };
+
+ const startRecording = async (takeId?: number) => {
+ recordingTakeIdRef.current = takeId;
if (isRequestBeingMade) {
showToast({ message: 'A request is already being made. Please wait.', status: 'warning' });
return;
}
+ /* Checked before the microphone is requested, and here rather than in
+ `externalStartRecording`, so every caller — the mic button, the dictation
+ shortcut, an auto-start — is covered. A webview that exposes
+ `getUserMedia` without `MediaRecorder` would otherwise hold a live
+ capture that no Stop control can reach: construction throws after
+ permission is granted, `isListening` stays false, and the tracks run
+ until the composer unmounts. */
+ if (typeof MediaRecorder === 'undefined') {
+ showToast({ message: 'MediaRecorder is not supported in this browser', status: 'error' });
+ return;
+ }
+
if (!audioStream.current) {
await getMicrophonePermission();
}
@@ -172,11 +230,12 @@ const useSpeechToTextExternal = (
if (audioStream.current) {
try {
audioChunksRef.current = [];
+ abortedRef.current = false;
const bestMimeType = getBestSupportedMimeType();
- setAudioMimeType(bestMimeType);
+ audioMimeTypeRef.current = bestMimeType;
mediaRecorderRef.current = new MediaRecorder(audioStream.current, {
- mimeType: audioMimeType,
+ mimeType: bestMimeType,
});
mediaRecorderRef.current.addEventListener('dataavailable', (event: BlobEvent) => {
audioChunksRef.current.push(event.data);
@@ -188,6 +247,12 @@ const useSpeechToTextExternal = (
}
setIsListening(true);
} catch (error) {
+ /* The recorder never started, so nothing else will release the stream:
+ `stopRecording` returns early without a recorder and unmount cleanup
+ is the only other path. Leaving it open keeps the microphone light on
+ behind a UI that offers no way to stop it. */
+ releaseAudioStream();
+ cleanup();
showToast({ message: `Error starting recording: ${error}`, status: 'error' });
}
} else {
@@ -195,6 +260,15 @@ const useSpeechToTextExternal = (
}
};
+ /** Releases the silence monitor's audio graph; safe to call more than once. */
+ const closeAudioContext = () => {
+ const context = audioContextRef.current;
+ audioContextRef.current = null;
+ if (context != null && context.state !== 'closed') {
+ void context.close().catch(() => undefined);
+ }
+ };
+
const stopRecording = () => {
if (!mediaRecorderRef.current) {
return;
@@ -210,25 +284,20 @@ const useSpeechToTextExternal = (
window.cancelAnimationFrame(animationFrameIdRef.current);
animationFrameIdRef.current = null;
}
+ closeAudioContext();
setIsListening(false);
} else {
showToast({ message: 'MediaRecorder is not recording', status: 'error' });
}
};
-
- const externalStartRecording = () => {
- if (typeof MediaRecorder === 'undefined') {
- showToast({ message: 'MediaRecorder is not supported in this browser', status: 'error' });
- return;
- }
-
+ const externalStartRecording = (takeId?: number) => {
if (isListening) {
showToast({ message: 'Already listening. Please stop recording first.', status: 'warning' });
return;
}
- startRecording();
+ void startRecording(takeId);
};
const externalStopRecording = () => {
@@ -243,9 +312,75 @@ const useSpeechToTextExternal = (
stopRecording();
};
+ /**
+ * Drops the take without transcribing it. `handleStop` is where the audio is
+ * packed into a FormData and uploaded, so an abort has to reach it: the flag
+ * is what stops a discarded take from spending a transcription request.
+ */
+ const externalAbortRecording = () => {
+ abortedRef.current = true;
+ audioChunksRef.current = [];
+
+ const recorder = mediaRecorderRef.current;
+ if (recorder && recorder.state !== 'inactive') {
+ recorder.stop();
+ }
+
+ audioStream.current?.getTracks().forEach((track) => track.stop());
+ audioStream.current = null;
+
+ if (animationFrameIdRef.current !== null) {
+ window.cancelAnimationFrame(animationFrameIdRef.current);
+ animationFrameIdRef.current = null;
+ }
+ closeAudioContext();
+
+ setIsListening(false);
+ };
+
+ /* Navigating away mid-take ends neither path above: the recorder keeps
+ running, the microphone tracks stay live, the silence monitor keeps
+ scheduling frames, and the audio graph outlives the page that opened it.
+ Refs only, so the empty dependency list holds no stale closure. */
+ useEffect(() => {
+ isMountedRef.current = true;
+ return () => {
+ isMountedRef.current = false;
+
+ if (autoSendTimerRef.current) {
+ clearTimeout(autoSendTimerRef.current);
+ autoSendTimerRef.current = null;
+ }
+
+ abortedRef.current = true;
+ audioChunksRef.current = [];
+
+ const recorder = mediaRecorderRef.current;
+ if (recorder && recorder.state !== 'inactive') {
+ recorder.stop();
+ }
+ mediaRecorderRef.current = null;
+
+ audioStream.current?.getTracks().forEach((track) => track.stop());
+ audioStream.current = null;
+
+ if (animationFrameIdRef.current !== null) {
+ window.cancelAnimationFrame(animationFrameIdRef.current);
+ animationFrameIdRef.current = null;
+ }
+
+ const context = audioContextRef.current;
+ audioContextRef.current = null;
+ if (context != null && context.state !== 'closed') {
+ void context.close().catch(() => undefined);
+ }
+ };
+ }, []);
+
return {
isListening,
externalStopRecording,
+ externalAbortRecording,
externalStartRecording,
isLoading: isProcessing,
};
diff --git a/client/src/hooks/Input/useTextarea.spec.tsx b/client/src/hooks/Input/useTextarea.spec.tsx
index d5f2fee063..96848f255a 100644
--- a/client/src/hooks/Input/useTextarea.spec.tsx
+++ b/client/src/hooks/Input/useTextarea.spec.tsx
@@ -162,6 +162,7 @@ const renderTextareaHook = (initialAnswerModeActive = false) => {
submitButtonRef: { current: submitButton },
setIsScrollable,
answerModeActive,
+ enterToSend: true,
}),
);
const rerender = (nextAnswerModeActive = answerModeActive) => {
@@ -206,6 +207,7 @@ describe('useTextarea long-paste fallback', () => {
textAreaRef: { current: textArea },
submitButtonRef: { current: null },
setIsScrollable: jest.fn(),
+ enterToSend: true,
}),
);
@@ -234,6 +236,7 @@ describe('useTextarea long-paste fallback', () => {
textAreaRef: { current: textArea },
submitButtonRef: { current: null },
setIsScrollable: jest.fn(),
+ enterToSend: true,
}),
);
diff --git a/client/src/hooks/Input/useTextarea.ts b/client/src/hooks/Input/useTextarea.ts
index 73e960766d..c38c6503d6 100644
--- a/client/src/hooks/Input/useTextarea.ts
+++ b/client/src/hooks/Input/useTextarea.ts
@@ -51,6 +51,7 @@ export default function useTextarea({
allowSubmitWhileGenerating = false,
onDuringRunModifier,
answerModeActive = false,
+ enterToSend,
}: {
textAreaRef: React.RefObject<HTMLTextAreaElement>;
submitButtonRef: React.RefObject<HTMLButtonElement>;
@@ -64,6 +65,8 @@ export default function useTextarea({
onDuringRunModifier?: (kind: 'other' | 'interrupt' | 'preempt') => void;
/** Keeps pasted text inline while the composer is answering a paused question. */
answerModeActive?: boolean;
+ /** Host-owned: whether Enter sends. The hint advertises the same value. */
+ enterToSend: boolean;
}) {
const localize = useLocalize();
const getSender = useGetSender();
@@ -82,7 +85,6 @@ export default function useTextarea({
const { openModal } = useUploadModalContext();
const assistantMap = useAssistantsMapContext();
const checkHealth = useInteractionHealthCheck();
- const enterToSend = useRecoilValue(store.enterToSend);
const saveDrafts = useRecoilValue(store.saveDrafts);
const pasteLongTextAsFile = useRecoilValue(store.pasteLongTextAsFile);
const { shortcutsEnabled, submitOverride, yieldedChords } = useComposerBindings();
@@ -154,12 +156,20 @@ export default function useTextarea({
* navigation that resolves its record before moving the route. */
useEffect(() => {
const text = pendingComposerText ?? '';
- if (text === '' || !insertComposerText(text)) {
+ if (text === '') {
+ return;
+ }
+ /* A reclaimed steer must not overwrite a draft the user typed while the
+ * cancel request was in flight. Keep both messages distinct when the
+ * composer already owns text; an empty composer receives the exact steer. */
+ const currentText = textAreaRef.current?.value ?? '';
+ const handoffText = currentText.length > 0 ? `\n${text}` : text;
+ if (!insertComposerText(handoffText)) {
return;
}
setPendingComposerText(undefined);
- }, [insertComposerText, pendingComposerText, setPendingComposerText]);
+ }, [insertComposerText, pendingComposerText, setPendingComposerText, textAreaRef]);
useEffect(() => {
const currentValue = textAreaRef.current?.value ?? '';
diff --git a/client/src/hooks/Input/useToolFavorites.ts b/client/src/hooks/Input/useToolFavorites.ts
new file mode 100644
index 0000000000..839eb34dd2
--- /dev/null
+++ b/client/src/hooks/Input/useToolFavorites.ts
@@ -0,0 +1,45 @@
+import { useMemo, useCallback } from 'react';
+import type { TToolFavoriteType } from 'librechat-data-provider';
+import useMarketplaceFavorites from '~/hooks/useToolFavorites';
+
+export interface ToolFavorites {
+ /** `${itemType}:${itemId}` keys, for O(1) membership tests while building
+ * the palette instead of scanning the favourites array per row. */
+ keys: Set<string>;
+ isFavorite: (itemType: TToolFavoriteType, itemId: string) => boolean;
+ toggleFavorite: (itemType: TToolFavoriteType, itemId: string) => void;
+}
+
+export const favoriteKey = (itemType: TToolFavoriteType, itemId: string) => `${itemType}:${itemId}`;
+
+/**
+ * Server-persisted favourites for anything the composer palette can list:
+ * built-in tools, plugin tools, MCP servers and skills.
+ *
+ * A shape adapter over the marketplace's own hook rather than a second copy of
+ * it: the palette addresses items by type and id where the marketplace uses
+ * `{ kind, id }`, and that was the whole difference. Going through it also
+ * carries its error handling, so starring past the server's cap says so here
+ * too instead of failing silently with the star left where it was.
+ */
+export default function useToolFavorites(): ToolFavorites {
+ const { favoriteKeys, toggle } = useMarketplaceFavorites();
+
+ const isFavorite = useCallback(
+ (itemType: TToolFavoriteType, itemId: string) =>
+ favoriteKeys.has(favoriteKey(itemType, itemId)),
+ [favoriteKeys],
+ );
+
+ const toggleFavorite = useCallback(
+ (itemType: TToolFavoriteType, itemId: string) => {
+ void toggle({ kind: itemType, id: itemId });
+ },
+ [toggle],
+ );
+
+ return useMemo(
+ () => ({ keys: favoriteKeys, isFavorite, toggleFavorite }),
+ [favoriteKeys, isFavorite, toggleFavorite],
+ );
+}
diff --git a/client/src/hooks/MCP/__tests__/useAppBridge.spec.tsx b/client/src/hooks/MCP/__tests__/useAppBridge.spec.tsx
index 4d8130e993..93785848e0 100644
--- a/client/src/hooks/MCP/__tests__/useAppBridge.spec.tsx
+++ b/client/src/hooks/MCP/__tests__/useAppBridge.spec.tsx
@@ -1109,7 +1109,12 @@ describe('useAppBridge', () => {
expect(mockAsk).toHaveBeenCalledTimes(1);
expect(mockAsk).toHaveBeenCalledWith(
{ text: 'approved\nmessage' },
- { overrideFiles: [], overrideManualSkills: [], overrideQuotes: [] },
+ {
+ overrideFiles: [],
+ overrideManualSkills: [],
+ overrideQuotes: [],
+ overrideReasoning: null,
+ },
);
view.unmount();
});
diff --git a/client/src/hooks/MCP/__tests__/useMCPServerManager.spec.ts b/client/src/hooks/MCP/__tests__/useMCPServerManager.spec.ts
new file mode 100644
index 0000000000..ca0805f79b
--- /dev/null
+++ b/client/src/hooks/MCP/__tests__/useMCPServerManager.spec.ts
@@ -0,0 +1,23 @@
+import { selectInitializedMCPServer } from '../useMCPServerManager';
+
+describe('selectInitializedMCPServer', () => {
+ it('preserves selections from concurrent initialization completions', () => {
+ const valuesRef = { current: [] as string[] };
+ const setValues = jest.fn();
+
+ selectInitializedMCPServer(valuesRef, setValues, 'github');
+ selectInitializedMCPServer(valuesRef, setValues, 'spotify');
+
+ expect(valuesRef.current).toEqual(['github', 'spotify']);
+ expect(setValues).toHaveBeenLastCalledWith(['github', 'spotify']);
+ });
+
+ it('does not write a selection that is already present', () => {
+ const valuesRef = { current: ['github'] };
+ const setValues = jest.fn();
+
+ selectInitializedMCPServer(valuesRef, setValues, 'github');
+
+ expect(setValues).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/hooks/MCP/useAppBridge.ts b/client/src/hooks/MCP/useAppBridge.ts
index 7cf32cb866..0dc82a7225 100644
--- a/client/src/hooks/MCP/useAppBridge.ts
+++ b/client/src/hooks/MCP/useAppBridge.ts
@@ -365,10 +365,16 @@ export function useAppBridge({
);
if (!allowed || actionSignal.aborted || cancelled) return { isError: true };
// The selected agent and MCP servers belong to the conversation. Only the
- // next composer's staged files, manual skill picks and quotes are excluded.
+ // next composer's staged files, manual skill picks, quotes and reasoning
+ // level are excluded.
const accepted = askRef.current(
{ text },
- { overrideFiles: [], overrideManualSkills: [], overrideQuotes: [] },
+ {
+ overrideFiles: [],
+ overrideManualSkills: [],
+ overrideQuotes: [],
+ overrideReasoning: null,
+ },
);
if (accepted === false) {
return { isError: true };
diff --git a/client/src/hooks/MCP/useMCPServerManager.ts b/client/src/hooks/MCP/useMCPServerManager.ts
index 820dac1ef0..21b66f850d 100644
--- a/client/src/hooks/MCP/useMCPServerManager.ts
+++ b/client/src/hooks/MCP/useMCPServerManager.ts
@@ -62,6 +62,20 @@ export interface MCPServerDefinition {
// The init states (isInitializing, isCancellable, etc.) are stored in the global Jotai atom
type PollIntervals = Record<string, NodeJS.Timeout | null>;
+export function selectInitializedMCPServer(
+ valuesRef: { current: string[] },
+ setValues: (values: string[]) => void,
+ serverName: string,
+) {
+ const currentValues = valuesRef.current ?? [];
+ if (currentValues.includes(serverName)) {
+ return;
+ }
+ const nextValues = [...currentValues, serverName];
+ valuesRef.current = nextValues;
+ setValues(nextValues);
+}
+
export function useMCPServerManager({
conversationId,
storageContextKey,
@@ -168,10 +182,15 @@ export function useMCPServerManager({
[],
);
- const reinitializeMutation = useReinitializeMCPServerMutation();
- const cancelOAuthMutation = useCancelMCPOAuthMutation();
+ /* Destructured to the callables: react-query hands back a fresh result
+ object every render, and the callbacks below that depended on the whole
+ object were new identities each time, which is what kept this hook's
+ return, and `BadgeRowProvider`'s context value with it, changing on every
+ keystroke in the composer. */
+ const { mutateAsync: reinitializeServer } = useReinitializeMCPServerMutation();
+ const { mutate: cancelMCPOAuth } = useCancelMCPOAuthMutation();
- const updateUserPluginsMutation = useUpdateUserPluginsMutation({
+ const { mutate: updateUserPlugins, isLoading: isUpdatingPlugins } = useUpdateUserPluginsMutation({
onSuccess: async (_data, variables) => {
const isRevoke = variables.action === 'uninstall';
const message = isRevoke
@@ -340,7 +359,7 @@ export function useMCPServerManager({
/** Flow completion is durable credential readiness, not proof that tool discovery
* finished on this pod. Reinitialize once more through the normal API so the
* selected server and its tools are usable before the UI reports success. */
- const readiness = await reinitializeMutation.mutateAsync(serverName);
+ const readiness = await reinitializeServer(serverName);
if (!isMCPReadyAfterOAuth(readiness)) {
showToast({
message: getMCPReinitializeErrorMessage(readiness, localize),
@@ -392,10 +411,7 @@ export function useMCPServerManager({
status: 'success',
});
- const currentValues = mcpValuesRef.current ?? [];
- if (!currentValues.includes(serverName)) {
- setMCPValues([...currentValues, serverName]);
- }
+ selectInitializedMCPServer(mcpValuesRef, setMCPValues, serverName);
await Promise.all([
queryClient.invalidateQueries([QueryKeys.mcpServers]),
@@ -488,7 +504,7 @@ export function useMCPServerManager({
timeoutId = setTimeout(pollOnce, getPollInterval(0));
pollIntervalsRef.current[serverName] = timeoutId;
},
- [queryClient, showToast, localize, setMCPValues, cleanupServerState, reinitializeMutation],
+ [queryClient, showToast, localize, setMCPValues, cleanupServerState, reinitializeServer],
);
const initializeServer = useCallback(
@@ -497,10 +513,10 @@ export function useMCPServerManager({
* attempt can never be mistaken for this attempt's outcome. */
updateServerInitState(serverName, { isInitializing: true, connectionDeferred: false });
try {
- const response = await reinitializeMutation.mutateAsync(serverName);
+ const response = await reinitializeServer(serverName);
/** Record whether this attempt deferred to a chat turn (request-scoped
- * server) so consumers that didn't await this call — e.g. the agent
- * builder behind the customUserVars config dialog — can react to it. */
+ * server) so consumers that didn't await this call (e.g. the agent
+ * builder behind the customUserVars config dialog) can react to it. */
updateServerInitState(serverName, {
connectionDeferred: Boolean(response.connectionDeferred),
});
@@ -542,10 +558,7 @@ export function useMCPServerManager({
status: 'success',
});
- const currentValues = mcpValues ?? [];
- if (!currentValues.includes(serverName)) {
- setMCPValues([...currentValues, serverName]);
- }
+ selectInitializedMCPServer(mcpValuesRef, setMCPValues, serverName);
}
return response;
} catch (error) {
@@ -559,12 +572,11 @@ export function useMCPServerManager({
},
[
updateServerInitState,
- reinitializeMutation,
+ reinitializeServer,
startServerPolling,
queryClient,
showToast,
localize,
- mcpValues,
cleanupServerState,
setMCPValues,
],
@@ -572,7 +584,7 @@ export function useMCPServerManager({
const cancelOAuthFlow = useCallback(
(serverName: string) => {
- cancelOAuthMutation.mutate(serverName, {
+ cancelMCPOAuth(serverName, {
onSuccess: () => {
cleanupServerState(serverName);
Promise.all([
@@ -596,7 +608,7 @@ export function useMCPServerManager({
},
});
},
- [queryClient, cleanupServerState, showToast, localize, cancelOAuthMutation],
+ [queryClient, cleanupServerState, showToast, localize, cancelMCPOAuth],
);
const isInitializing = useCallback(
@@ -620,7 +632,7 @@ export function useMCPServerManager({
[serverInitStates],
);
- /** Clear a recorded deferred outcome without starting a new attempt — used
+ /** Clear a recorded deferred outcome without starting a new attempt: used
* before routing into the customUserVars config dialog so a stale flag from
* an earlier attempt can't trigger consumers while the dialog is open. */
const resetConnectionDeferred = useCallback(
@@ -669,10 +681,10 @@ export function useMCPServerManager({
action: 'install',
auth: authData,
};
- updateUserPluginsMutation.mutate(payload);
+ updateUserPlugins(payload);
}
},
- [selectedToolForConfig, updateUserPluginsMutation],
+ [selectedToolForConfig, updateUserPlugins],
);
const handleConfigRevoke = useCallback(
@@ -683,11 +695,11 @@ export function useMCPServerManager({
action: 'uninstall',
auth: {},
};
- updateUserPluginsMutation.mutate(payload);
- /** Deselection is now handled centrally in updateUserPluginsMutation.onSuccess */
+ updateUserPlugins(payload);
+ /** Deselection is now handled centrally in the mutation's onSuccess */
}
},
- [selectedToolForConfig, updateUserPluginsMutation],
+ [selectedToolForConfig, updateUserPlugins],
);
/** Standalone revoke function for OAuth servers - doesn't require selectedToolForConfig */
@@ -698,9 +710,9 @@ export function useMCPServerManager({
action: 'uninstall',
auth: {},
};
- updateUserPluginsMutation.mutate(payload);
+ updateUserPlugins(payload);
},
- [updateUserPluginsMutation],
+ [updateUserPlugins],
);
const handleSave = useCallback(
@@ -829,7 +841,7 @@ export function useMCPServerManager({
initialValues,
onSave: handleSave,
onRevoke: handleRevoke,
- isSubmitting: updateUserPluginsMutation.isLoading,
+ isSubmitting: isUpdatingPlugins,
};
}, [
selectedToolForConfig,
@@ -838,41 +850,77 @@ export function useMCPServerManager({
handleDialogOpenChange,
handleSave,
handleRevoke,
- updateUserPluginsMutation.isLoading,
+ isUpdatingPlugins,
]);
- return {
- availableMCPServers,
- /** MCP servers filtered for chat menu selection (chatMenu !== false && !consumeOnly) */
- selectableServers,
- availableMCPServersMap: loadedServers,
- isLoading,
- connectionStatus,
- initializeServer,
- cancelOAuthFlow,
- isInitializing,
- isCancellable,
- isConnectionDeferred,
- resetConnectionDeferred,
- getOAuthUrl,
- mcpValues,
- setMCPValues,
-
- isPinned,
- setIsPinned,
- placeholderText,
- toggleServerSelection,
- localize,
+ /* Memoized because `BadgeRowProvider` carries this straight into its context
+ value: a fresh object here changed that value on every keystroke in the
+ composer, rebuilding the palette's whole server catalog per character. */
+ return useMemo(
+ () => ({
+ availableMCPServers,
+ /** MCP servers filtered for chat menu selection (chatMenu !== false && !consumeOnly) */
+ selectableServers,
+ availableMCPServersMap: loadedServers,
+ isLoading,
+ connectionStatus,
+ initializeServer,
+ cancelOAuthFlow,
+ isInitializing,
+ isCancellable,
+ isConnectionDeferred,
+ resetConnectionDeferred,
+ getOAuthUrl,
+ mcpValues,
+ setMCPValues,
- isConfigModalOpen,
- handleDialogOpenChange,
- selectedToolForConfig,
- setSelectedToolForConfig,
- handleSave,
- handleRevoke,
- revokeOAuthForServer,
- getServerStatusIconProps,
- getConfigDialogProps,
- checkEffectivePermission,
- };
+ isPinned,
+ setIsPinned,
+ placeholderText,
+ toggleServerSelection,
+ localize,
+
+ isConfigModalOpen,
+ handleDialogOpenChange,
+ selectedToolForConfig,
+ setSelectedToolForConfig,
+ handleSave,
+ handleRevoke,
+ revokeOAuthForServer,
+ getServerStatusIconProps,
+ getConfigDialogProps,
+ checkEffectivePermission,
+ }),
+ [
+ availableMCPServers,
+ selectableServers,
+ loadedServers,
+ isLoading,
+ connectionStatus,
+ initializeServer,
+ cancelOAuthFlow,
+ isInitializing,
+ isCancellable,
+ isConnectionDeferred,
+ resetConnectionDeferred,
+ getOAuthUrl,
+ mcpValues,
+ setMCPValues,
+ isPinned,
+ setIsPinned,
+ placeholderText,
+ toggleServerSelection,
+ localize,
+ isConfigModalOpen,
+ handleDialogOpenChange,
+ selectedToolForConfig,
+ setSelectedToolForConfig,
+ handleSave,
+ handleRevoke,
+ revokeOAuthForServer,
+ getServerStatusIconProps,
+ getConfigDialogProps,
+ checkEffectivePermission,
+ ],
+ );
}
diff --git a/client/src/hooks/Messages/__tests__/useSubmitMessage.spec.ts b/client/src/hooks/Messages/__tests__/useSubmitMessage.spec.ts
index ee07598295..0cf87a6401 100644
--- a/client/src/hooks/Messages/__tests__/useSubmitMessage.spec.ts
+++ b/client/src/hooks/Messages/__tests__/useSubmitMessage.spec.ts
@@ -1,5 +1,6 @@
import { act, renderHook } from '@testing-library/react';
import { useRecoilValue, useSetRecoilState } from 'recoil';
+import type { TReasoningOverride } from 'librechat-data-provider';
import { useChatContext, useChatFormContext, useAddedChatContext } from '~/Providers';
import { useGetLatestMessage } from '~/hooks/Messages/useLatestMessage';
import { useAuthContext } from '~/hooks/AuthContext';
@@ -166,4 +167,20 @@ describe('useSubmitMessage', () => {
}),
);
});
+
+ it('forwards a queued reasoning override without resetting it on refusal', () => {
+ ask.mockReturnValue(false);
+ const { result } = renderHook(() => useSubmitMessage());
+ const override = { key: 'thinkingLevel', value: 'high' } as TReasoningOverride;
+
+ act(() => {
+ result.current.submitMessage({ text: 'queued thought', overrideReasoning: override });
+ });
+
+ expect(ask).toHaveBeenCalledWith(
+ { text: 'queued thought' },
+ expect.objectContaining({ overrideReasoning: override }),
+ );
+ expect(reset).not.toHaveBeenCalled();
+ });
});
diff --git a/client/src/hooks/Messages/useSubmitMessage.ts b/client/src/hooks/Messages/useSubmitMessage.ts
index a01d1ce1d4..3899bfc82a 100644
--- a/client/src/hooks/Messages/useSubmitMessage.ts
+++ b/client/src/hooks/Messages/useSubmitMessage.ts
@@ -1,7 +1,7 @@
import { useCallback } from 'react';
import { useRecoilValue, useSetRecoilState } from 'recoil';
import { replaceSpecialVars } from 'librechat-data-provider';
-import type { TMessage } from 'librechat-data-provider';
+import type { TMessage, TReasoningOverride } from 'librechat-data-provider';
import { useChatContext, useChatFormContext, useAddedChatContext } from '~/Providers';
import { useGetLatestMessage } from '~/hooks/Messages/useLatestMessage';
import { useAuthContext } from '~/hooks/AuthContext';
@@ -24,6 +24,7 @@ export default function useSubmitMessage() {
overrideFiles?: TMessage['files'];
overrideQuotes?: string[];
overrideManualSkills?: string[];
+ overrideReasoning?: TReasoningOverride | null;
overrideClientRequestId?: string;
overrideRecoverySteerId?: string;
overrideExpectedPredecessorCreatedAt?: number;
@@ -55,6 +56,7 @@ export default function useSubmitMessage() {
overrideFiles: data.overrideFiles,
overrideQuotes: data.overrideQuotes,
overrideManualSkills: data.overrideManualSkills,
+ overrideReasoning: data.overrideReasoning,
overrideClientRequestId: data.overrideClientRequestId,
overrideRecoverySteerId: data.overrideRecoverySteerId,
overrideExpectedPredecessorCreatedAt: data.overrideExpectedPredecessorCreatedAt,
diff --git a/client/src/hooks/Nav/useSideNavLinks.ts b/client/src/hooks/Nav/useSideNavLinks.ts
index 20ccf3c321..a4bc5319cd 100644
--- a/client/src/hooks/Nav/useSideNavLinks.ts
+++ b/client/src/hooks/Nav/useSideNavLinks.ts
@@ -1,5 +1,5 @@
import { useMemo } from 'react';
-import { MCPIcon, AttachmentIcon, OpenAIMinimalIcon } from '@librechat/client';
+import { MCPIcon, OpenAIMinimalIcon } from '@librechat/client';
import {
Bot,
Brain,
@@ -33,7 +33,6 @@ import PanelSwitch from '~/components/SidePanel/Builder/PanelSwitch';
import { SchedulePanel } from '~/components/SidePanel/Schedules';
import Parameters from '~/components/SidePanel/Parameters/Panel';
import { MemoryPanel } from '~/components/SidePanel/Memories';
-import FilesPanel from '~/components/SidePanel/Files/Panel';
import { PromptsAccordion } from '~/components/Prompts';
import { SkillsAccordion } from '~/components/Skills';
@@ -196,14 +195,6 @@ export default function useSideNavLinks({
});
}
- links.push({
- title: 'com_sidepanel_attach_files',
- label: '',
- icon: AttachmentIcon,
- id: 'files',
- Component: FilesPanel,
- });
-
if (
interfaceConfig.parameters === true &&
isParamEndpoint(endpoint ?? '', endpointType ?? '') === true &&
diff --git a/client/src/hooks/Plugins/useAuthSearchTool.ts b/client/src/hooks/Plugins/useAuthSearchTool.ts
index 1cb65ede0f..ffcb7f12cf 100644
--- a/client/src/hooks/Plugins/useAuthSearchTool.ts
+++ b/client/src/hooks/Plugins/useAuthSearchTool.ts
@@ -34,7 +34,11 @@ export type SearchApiKeyDirtyFields = Partial<Record<keyof SearchApiKeyFormData,
const useAuthSearchTool = (options?: { isEntityTool: boolean }) => {
const queryClient = useQueryClient();
const isEntityTool = options?.isEntityTool ?? true;
- const updateUserPlugins = useUpdateUserPluginsMutation({
+ /* `mutate` rather than the mutation object: react-query hands back a fresh
+ result object on every render, and depending on it made both callbacks
+ below new identities each time, which travelled up through
+ `useSearchApiKeyForm` into `BadgeRowProvider`'s context value. */
+ const { mutate: updateUserPlugins } = useUpdateUserPluginsMutation({
onMutate: (vars) => {
queryClient.setQueryData([QueryKeys.toolAuth, Tools.web_search], () => {
return {
@@ -90,7 +94,7 @@ const useAuthSearchTool = (options?: { isEntityTool: boolean }) => {
{} as Record<string, string>,
);
- updateUserPlugins.mutate({
+ updateUserPlugins({
pluginKey: Tools.web_search,
action: 'install',
auth,
@@ -101,7 +105,7 @@ const useAuthSearchTool = (options?: { isEntityTool: boolean }) => {
);
const removeTool = useCallback(() => {
- updateUserPlugins.mutate({
+ updateUserPlugins({
pluginKey: Tools.web_search,
action: 'uninstall',
auth: {},
diff --git a/client/src/hooks/Plugins/useSearchApiKeyForm.ts b/client/src/hooks/Plugins/useSearchApiKeyForm.ts
index a8744a798d..e71a6551c4 100644
--- a/client/src/hooks/Plugins/useSearchApiKeyForm.ts
+++ b/client/src/hooks/Plugins/useSearchApiKeyForm.ts
@@ -1,4 +1,4 @@
-import { useRef, useState, useCallback } from 'react';
+import { useRef, useMemo, useState, useCallback } from 'react';
import { useForm } from 'react-hook-form';
import type { SearchApiKeyFormData } from '~/hooks/Plugins/useAuthSearchTool';
import useAuthSearchTool from '~/hooks/Plugins/useAuthSearchTool';
@@ -36,13 +36,19 @@ export default function useSearchApiKeyForm({
onRevoke?.();
}, [reset, onRevoke, removeTool]);
- return {
- methods,
- isDialogOpen,
- setIsDialogOpen,
- handleRevokeApiKey,
- onSubmit: onSubmitHandler,
- badgeTriggerRef,
- menuTriggerRef,
- };
+ /* Memoized because `BadgeRowProvider` carries this straight into its context
+ value: a fresh object here changed that value on every keystroke in the
+ composer, which is the one thing the provider's own memo exists to stop. */
+ return useMemo(
+ () => ({
+ methods,
+ isDialogOpen,
+ setIsDialogOpen,
+ handleRevokeApiKey,
+ onSubmit: onSubmitHandler,
+ badgeTriggerRef,
+ menuTriggerRef,
+ }),
+ [methods, isDialogOpen, handleRevokeApiKey, onSubmitHandler],
+ );
}
diff --git a/client/src/hooks/Plugins/useToolToggle.ts b/client/src/hooks/Plugins/useToolToggle.ts
index 72f3674908..2b90675513 100644
--- a/client/src/hooks/Plugins/useToolToggle.ts
+++ b/client/src/hooks/Plugins/useToolToggle.ts
@@ -162,17 +162,37 @@ export function useToolToggle({
[handleChange],
);
- return {
- toggleState: toolValue, // Return the actual value from ephemeralAgent
- handleChange,
- isToolEnabled,
- toolValue,
- setToggleState: (value: ToolValue) => handleChange({ value }), // Adapter for direct setting
- ephemeralAgent,
- debouncedChange,
- setEphemeralAgent,
- authData: authQuery?.data,
- isPinned,
- setIsPinned,
- };
+ const setToggleState = useCallback((value: ToolValue) => handleChange({ value }), [handleChange]);
+
+ /* Memoized because `BadgeRowContext` puts six of these in a context value that
+ the composer palette derives its whole catalog from: a fresh object here on
+ every render made that value change on every keystroke, whatever the
+ provider did about it. */
+ return useMemo(
+ () => ({
+ toggleState: toolValue, // Return the actual value from ephemeralAgent
+ handleChange,
+ isToolEnabled,
+ toolValue,
+ setToggleState, // Adapter for direct setting
+ ephemeralAgent,
+ debouncedChange,
+ setEphemeralAgent,
+ authData: authQuery?.data,
+ isPinned,
+ setIsPinned,
+ }),
+ [
+ toolValue,
+ handleChange,
+ isToolEnabled,
+ setToggleState,
+ ephemeralAgent,
+ debouncedChange,
+ setEphemeralAgent,
+ authQuery?.data,
+ isPinned,
+ setIsPinned,
+ ],
+ );
}
diff --git a/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts b/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts
index 735cda82a3..dece3fe1cf 100644
--- a/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts
+++ b/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts
@@ -12,6 +12,7 @@ import {
} from 'librechat-data-provider';
import type { TMessage, TSubmission } from 'librechat-data-provider';
import type { Query, QueryKey } from '@tanstack/react-query';
+import type { PendingSteer } from '~/store/families';
import {
activeUsageResponseIdFamily,
liveTokensFamily,
@@ -301,7 +302,10 @@ jest.mock('librechat-data-provider', () => {
};
});
-import useResumableSSE from '~/hooks/SSE/useResumableSSE';
+import useResumableSSE, {
+ selectLocalSteersForQueue,
+ ABORT_SWEEP_STATUSES,
+} from '~/hooks/SSE/useResumableSSE';
import useSSE from '~/hooks/SSE/useSSE';
const CONV_ID = 'conv-abc-123';
@@ -970,7 +974,7 @@ describe('useResumableSSE', () => {
expect(mockConvertSteersToQueued).toHaveBeenCalledWith(CONV_ID, parked, {
generationProtocolVersion: 1,
});
- // The true outcome is unknown — the run-end signal must release parked
+ // The true outcome is unknown: the run-end signal must release parked
// interrupt flags WITHOUT auto-sending queued messages.
expect(mockSetRunEnd).toHaveBeenCalledWith(
expect.objectContaining({ conversationId: CONV_ID, outcome: 'aborted' }),
@@ -5503,3 +5507,131 @@ describe('useResumableSSE - sync response identity', () => {
unmount();
});
});
+
+/**
+ * `convertLocalSteersToQueued` (the `final` handler and the intentional-close
+ * `abort` listener both call it, alongside the two failure-terminal paths
+ * covered above) is a thin `useRecoilCallback` wrapper: read the conversation's
+ * chips, run them through this selection, hand the result to `useSteerConvert`.
+ * This file's `useRecoilCallback: () => jest.fn()` mock (see above, "the
+ * hook's steer-chip/queue callbacks need a RecoilRoot; these tests render
+ * bare") makes that wrapper, and every other recoil-callback in this hook
+ * (`resolveSteerChip`, `seedSteerChips` included; neither has a direct test
+ * in this file either), inert: calling it from the `final`/`abort` source
+ * lines is invisible to `mockConvertSteersToQueued` assertions here, since the
+ * mock discards the real closure before it can ever call through. Covering
+ * the selection logic directly (this is the exact piece of logic finding 3
+ * was about: which statuses survive a run end) rather than faking a
+ * RecoilRoot-backed integration around the rest of this large hook's mocks.
+ *
+ * The `statuses` parameter pins a second contract: the `final` handler and
+ * the two error/404 terminals call `convertLocalSteersToQueued` with no
+ * override (default `pending || failed`, the run is genuinely over), while
+ * the intentional-close `abort` listener passes `{ statuses: ['failed'] }`
+ * because that listener also fires on navigation away while the run
+ * CONTINUES server-side: a server-ACK'd `pending` chip must be left alone
+ * there, not swept into the queue as a duplicate of the server's own injection.
+ */
+describe('selectLocalSteersForQueue', () => {
+ const chip = (over: Partial<PendingSteer> = {}): PendingSteer => ({
+ steerId: 's1',
+ text: 'default text',
+ status: 'pending',
+ createdAt: 1,
+ ...over,
+ });
+
+ it('final/error-path selection (default statuses) includes pending and failed chips, excluding sending', () => {
+ const chips = [
+ chip({ steerId: 'p1', status: 'pending' }),
+ chip({ steerId: 'f1', status: 'failed' }),
+ chip({ steerId: 'sending-1', status: 'sending' }),
+ ];
+ expect(selectLocalSteersForQueue(chips).map((steer) => steer.steerId)).toEqual(['p1', 'f1']);
+ });
+
+ it('abort-path selection (statuses: ["failed"]) sweeps only failed chips, leaving pending alone', () => {
+ // The abort listener fires on navigation away while the run CONTINUES
+ // server-side: a `pending` chip already has a server id and will be
+ // injected by the server regardless, so sweeping it here too would make
+ // `useQueueDrain` resend the same words as a duplicate turn at run end.
+ const chips = [
+ chip({ steerId: 'p1', status: 'pending' }),
+ chip({ steerId: 'f1', status: 'failed' }),
+ chip({ steerId: 'sending-1', status: 'sending' }),
+ ];
+ expect(selectLocalSteersForQueue(chips, ['failed']).map((steer) => steer.steerId)).toEqual([
+ 'f1',
+ ]);
+ });
+
+ it('converts a failed local chip present at a run-end path into a queueable item', () => {
+ // The leak finding 3 was about: a `failed` chip carries a local-* id the
+ // server never reports, so `data.pendingSteers`/the abort response can
+ // never carry it: this selection is the ONLY place left that can catch
+ // it before the `final`/`abort` paths hand off to `useSteerConvert`.
+ const failed = chip({ steerId: 'local-failed', status: 'failed', text: 'redo this' });
+ expect(selectLocalSteersForQueue([failed])).toEqual([
+ expect.objectContaining({ steerId: 'local-failed', text: 'redo this', createdAt: 1 }),
+ ]);
+ });
+
+ it('does not sweep a sending chip: its own POST callback owns it', () => {
+ // Converting it here too would race that callback: a late ACK's re-add
+ // in `resolveAcknowledgedSteer` could then double-queue the same words.
+ const sending = chip({ steerId: 'in-flight', status: 'sending' });
+ expect(selectLocalSteersForQueue([sending])).toEqual([]);
+ });
+
+ it('preserves uncertain deliveries for explicit same-id recovery', () => {
+ const legacy = chip({
+ steerId: 'legacy-uncertain',
+ status: 'failed',
+ deliveryUncertain: true,
+ generationProtocolVersion: 1,
+ });
+ const modern = chip({
+ steerId: 'modern-uncertain',
+ status: 'failed',
+ deliveryUncertain: true,
+ generationProtocolVersion: 2,
+ });
+
+ expect(selectLocalSteersForQueue([legacy, modern])).toEqual([]);
+ expect(selectLocalSteersForQueue([legacy], ABORT_SWEEP_STATUSES)).toEqual([]);
+ });
+
+ it('carries files only when present', () => {
+ const withFiles = chip({
+ steerId: 'p2',
+ files: [{ file_id: 'f1', filename: 'a.png' }],
+ });
+ const withoutFiles = chip({ steerId: 'p3' });
+ const [withResult, withoutResult] = selectLocalSteersForQueue([withFiles, withoutFiles]);
+ expect(withResult.files).toEqual(withFiles.files);
+ expect(withoutResult.files).toBeUndefined();
+ });
+
+ describe('the abort sweep', () => {
+ /* The abort path is the one terminal where the run may still be live on the
+ server, so a chip it has already ACK'd must be left for it to inject. */
+ it('sweeps only what never reached the server', () => {
+ expect([...ABORT_SWEEP_STATUSES]).toEqual(['failed']);
+ });
+
+ it("leaves an ACK'd chip alone where the default sweep would take it", () => {
+ const chips = [
+ chip({ steerId: 'acked', status: 'pending' }),
+ chip({ steerId: 'never-sent', status: 'failed' }),
+ ];
+ expect(selectLocalSteersForQueue(chips, ABORT_SWEEP_STATUSES).map((s) => s.steerId)).toEqual([
+ 'never-sent',
+ ]);
+ /* Where the run has genuinely ended, both are swept. */
+ expect(selectLocalSteersForQueue(chips).map((s) => s.steerId)).toEqual([
+ 'acked',
+ 'never-sent',
+ ]);
+ });
+ });
+});
diff --git a/client/src/hooks/SSE/useAttachmentHandler.ts b/client/src/hooks/SSE/useAttachmentHandler.ts
index 5eb218d43c..ddbc5982da 100644
--- a/client/src/hooks/SSE/useAttachmentHandler.ts
+++ b/client/src/hooks/SSE/useAttachmentHandler.ts
@@ -7,6 +7,7 @@ import type {
TFile,
} from 'librechat-data-provider';
import type { QueryClient } from '@tanstack/react-query';
+import { invalidateRecentFiles } from '~/utils/files';
import { handleMemoryArtifact } from '~/utils/memory';
import store from '~/store';
@@ -55,6 +56,7 @@ export default function useAttachmentHandler(queryClient?: QueryClient) {
}
return [fileData, ...oldData];
});
+ invalidateRecentFiles(queryClient);
}
if (queryClient && data.type === Tools.memory && data[Tools.memory]) {
diff --git a/client/src/hooks/SSE/useEventHandlers.ts b/client/src/hooks/SSE/useEventHandlers.ts
index 45d2fd1282..3e1dfe6385 100644
--- a/client/src/hooks/SSE/useEventHandlers.ts
+++ b/client/src/hooks/SSE/useEventHandlers.ts
@@ -1,5 +1,6 @@
import { useCallback, useEffect, useRef } from 'react';
import { v4 } from 'uuid';
+import { useStore } from 'jotai';
import { useQueryClient } from '@tanstack/react-query';
import { useSetRecoilState, useRecoilCallback } from 'recoil';
import { useParams, useNavigate, useLocation } from 'react-router-dom';
@@ -46,6 +47,10 @@ import {
isEmptyContentPart,
getPartKeyIndex,
} from '~/utils';
+import {
+ getReasoningStateKey,
+ pendingReasoningOverrideFamily,
+} from '~/components/Chat/Input/Composer/state';
import {
startupConfigKey,
queueTitleGeneration,
@@ -570,6 +575,7 @@ export default function useEventHandlers({
setShowStopButton,
}: EventHandlerParams) {
const queryClient = useQueryClient();
+ const reasoningStore = useStore();
const { announcePolite } = useLiveAnnouncer();
const applyAgentTemplate = useApplyAgentTemplate();
const setAbortScroll = useSetRecoilState(store.abortScroll);
@@ -620,17 +626,23 @@ export default function useEventHandlers({
const navigate = useNavigate();
const location = useLocation();
- /** Re-queue the turn's quoted excerpts when an early abort restores the draft,
- * so retrying the restored message still sends the references; the pending
- * queue was already drained on submit. */
- const restorePendingQuotes = useRecoilCallback(
+ /** Re-stage request context when an early abort restores the draft, so a
+ * retry keeps the references and one-shot reasoning selection already
+ * drained from the composer on submit. */
+ const restorePendingContext = useRecoilCallback(
({ set }) =>
- (convoId: string, quotes?: string[]) => {
+ (convoId: string, quotes?: string[], reasoningOverride?: TMessage['reasoningOverride']) => {
if (Array.isArray(quotes) && quotes.length > 0) {
set(store.pendingQuotesByConvoId(convoId), quotes);
}
+ if (reasoningOverride != null) {
+ const reasoningAtom = pendingReasoningOverrideFamily(
+ getReasoningStateKey(convoId, runIndex),
+ );
+ reasoningStore.set(reasoningAtom, (current) => current ?? reasoningOverride);
+ }
},
- [],
+ [reasoningStore, runIndex],
);
const lastAnnouncementTimeRef = useRef(Date.now());
@@ -1050,7 +1062,11 @@ export default function useEventHandlers({
abortMessages,
);
setDraft({ id: currentConvoId, value: requestMessage?.text });
- restorePendingQuotes(currentConvoId, requestMessage?.quotes);
+ restorePendingContext(
+ currentConvoId,
+ requestMessage?.quotes,
+ requestMessage?.reasoningOverride,
+ );
return;
}
@@ -1065,7 +1081,11 @@ export default function useEventHandlers({
id: getConversationDraftId(runIndex, Constants.NEW_CONVO),
value: requestMessage?.text,
});
- restorePendingQuotes(String(Constants.NEW_CONVO), requestMessage?.quotes);
+ restorePendingContext(
+ String(Constants.NEW_CONVO),
+ requestMessage?.quotes,
+ requestMessage?.reasoningOverride,
+ );
if (location.pathname !== `/c/${Constants.NEW_CONVO}`) {
navigate(`/c/${Constants.NEW_CONVO}`, { replace: true });
}
@@ -1133,7 +1153,11 @@ export default function useEventHandlers({
id: getConversationDraftId(runIndex, currentConvoId),
value: requestMessage?.text,
});
- restorePendingQuotes(currentConvoId, requestMessage?.quotes);
+ restorePendingContext(
+ currentConvoId,
+ requestMessage?.quotes,
+ requestMessage?.reasoningOverride,
+ );
if (isNewChat) {
requestChatFocus();
navigate(`/c/${Constants.NEW_CONVO}`, { replace: true });
@@ -1296,8 +1320,7 @@ export default function useEventHandlers({
applyAgentTemplate,
attachmentHandler,
setSubmissionStart,
- restorePendingQuotes,
- reconcileFailedCodeDecision,
+ restorePendingContext,
],
);
diff --git a/client/src/hooks/SSE/useResumableSSE.ts b/client/src/hooks/SSE/useResumableSSE.ts
index 9f50726fc4..3cc3e3a02e 100644
--- a/client/src/hooks/SSE/useResumableSSE.ts
+++ b/client/src/hooks/SSE/useResumableSSE.ts
@@ -41,8 +41,8 @@ import type {
TContextUsageEvent,
ChatStreamConnection,
} from 'librechat-data-provider';
+import type { DrainAfterAbort, QueuedMessageOrigin, PendingSteer } from '~/store/families';
import type { ActiveJobsResponse, StreamStatusResponse } from '~/data-provider';
-import type { DrainAfterAbort, QueuedMessageOrigin } from '~/store/families';
import type { GenerationProtocolVersion } from '~/data-provider';
import type { EventHandlerParams } from './useEventHandlers';
import type { TResData, TFinalResData } from '~/common';
@@ -162,7 +162,7 @@ const getStartGenerationStreamId = (data: unknown): string | null => {
};
/** The server returns `status: 'resumed'` when a duplicate start request was deduped to an
- * already-running stream — the client must subscribe with resume=true to replay its state
+ * already-running stream: the client must subscribe with resume=true to replay its state
* (prior content and any pending-action) rather than only receiving live events. */
const isResumedStartResponse = (data: unknown): boolean =>
data != null && typeof data === 'object' && (data as { status?: unknown }).status === 'resumed';
@@ -821,6 +821,60 @@ const mergeResumeMessages = (
return [...nextMessages, userMessage, responseMessage];
};
+/** Default sweep for a run that has genuinely ended (final/error/404): a
+ * `pending` chip behind a server id that no `on_steer_applied` will ever
+ * confirm, or a `failed` chip that never reached the server at all. Either
+ * one left behind survives past this run end and renders under whatever
+ * comes next, since `PendingSteers` reads the same atom keyed only by
+ * conversation, not by run. */
+const RUN_ENDED_STATUSES: readonly PendingSteer['status'][] = ['pending', 'failed'];
+
+/** Sweep for an intentional abort, where the run may still be live
+ * server-side: a server-ACK'd `pending` chip is injected regardless, so
+ * sweeping it here would send the same words a second time as a queued turn. */
+export const ABORT_SWEEP_STATUSES: readonly PendingSteer['status'][] = ['failed'];
+
+/**
+ * Local chips with no injection-boundary event left to resolve them.
+ * `statuses` defaults to `RUN_ENDED_STATUSES` for terminals where the run is
+ * actually over; pass `['failed']` for a path (like intentional abort) where
+ * the run may still be live server-side and a server-ACK'd `pending` chip
+ * must be left alone: the server injects it regardless, and sweeping it here
+ * would resend the same words as a duplicate queued turn.
+ *
+ * `sending` chips are never included: they have their own in-flight POST
+ * whose `onSuccess`/`onError` will settle them, and sweeping them here too
+ * would race that callback, since a late ACK's re-add in
+ * `resolveAcknowledgedSteer` could then double-queue the same words.
+ * Uncertain failures are also excluded. Protocol v2 makes an explicit retry
+ * idempotent, but a local queue conversion would create a second submission.
+ */
+export function selectLocalSteersForQueue(
+ chips: PendingSteer[],
+ statuses: readonly PendingSteer['status'][] = RUN_ENDED_STATUSES,
+ /** Ids the caller has already routed elsewhere this run end; matched against
+ * both ids a chip can be known by, since either may be the one excluded. */
+ excluded: ReadonlySet<string> = new Set(),
+): TPendingSteer[] {
+ const allowed = new Set(statuses);
+ return chips
+ .filter(
+ (steer) =>
+ allowed.has(steer.status) &&
+ steer.deliveryUncertain !== true &&
+ !excluded.has(steer.steerId) &&
+ (steer.clientSteerId == null || !excluded.has(steer.clientSteerId)),
+ )
+ .map((steer) => ({
+ steerId: steer.steerId,
+ ...(steer.clientSteerId && { clientSteerId: steer.clientSteerId }),
+ text: steer.text,
+ createdAt: steer.createdAt,
+ ...(steer.files && steer.files.length > 0 && { files: steer.files }),
+ ...(steer.queuedOrigin && { queuedOrigin: steer.queuedOrigin }),
+ }));
+}
+
/**
* Hook for resumable SSE streams.
* Separates generation start (POST) from stream subscription (GET EventSource).
@@ -925,7 +979,7 @@ export default function useResumableSSE(
const replacementHandoffRef = useRef(false);
const optimisticStreamIdsRef = useRef(new Set<string>());
const createdStreamIdsRef = useRef(new Set<string>());
- /** Pending action whose tool-call content part hasn't rendered yet — retried
+ /** Pending action whose tool-call content part hasn't rendered yet, retried
* on the next frame so a fast pause-before-render race still attaches. */
const pendingActionRetryRef = useRef<number | null>(null);
/** EVERY steer retry frame, not only the newest one. Several steers can be
@@ -935,7 +989,7 @@ export default function useResumableSSE(
const steerRetryFramesRef = useRef<Set<number>>(new Set());
/** EVERY outstanding label-retry frame, not a single handle: labels fire
* two events per slot (reservation, then fill), so concurrent retry
- * chains are the norm — a single ref would let cleanup cancel only the
+ * chains are the norm: a single ref would let cleanup cancel only the
* newest chain while the others kept running for up to 120 frames and
* could apply a stale label to a replacement generation that reuses the
* same response id (edits do). */
@@ -944,13 +998,13 @@ export default function useResumableSSE(
* Set once a SYNC has replaced the response with the server's
* completion-local snapshot, which discards the prefix an edited
* resubmission retained. From that point incoming indices are absolute and
- * `editPrefixLength` must no longer be applied — by run steps or labels.
+ * `editPrefixLength` must no longer be applied, by run steps or labels.
*/
const editPrefixClearedRef = useRef(false);
const editPrefixFirstPartFoldedRef = useRef(false);
/** Generation the cleared-prefix state above belongs to, so it is dropped
* when a new generation starts rather than when a subscribe happens to be
- * live. Keyed by response message id — the stream id is the conversation
+ * live. Keyed by response message id: the stream id is the conversation
* id and is therefore shared by every generation within it. */
const prefixStateGenerationIdRef = useRef<string | null>(null);
@@ -1221,42 +1275,57 @@ export default function useResumableSSE(
* HTTP response consumes the same data as a fallback in useChatHelpers). */
const convertSteersToQueued = useSteerConvert();
- /** Error events carry no `pendingSteers` payload (the server drops its copy
- * on failure), but every acknowledged chip's text is local — convert them
- * to queued follow-ups so the user's words survive a failed run. `sending`
- * chips settle through their own POST callbacks (404 falls back to
- * queue/send) and `failed` chips keep their manual controls. */
+ /** Sweeps this conversation's local chips (see `selectLocalSteersForQueue`)
+ * into queued follow-ups. Error events carry no `pendingSteers` payload of
+ * their own (the server drops its copy on failure); this is the only
+ * source of truth for those runs; the `final` and error/404 terminals call
+ * it (default `statuses`, i.e. `pending || failed`) alongside their own
+ * server-reported list as a backstop for `failed` chips, which never rode
+ * that list at all. The intentional-abort path passes `statuses: ['failed']`
+ * since the run may still be live server-side there (see its call site). */
const convertLocalSteersToQueued = useRecoilCallback(
({ snapshot }) =>
(
conversationId: string,
options?: {
claimParked?: boolean;
+ statuses?: readonly PendingSteer['status'][];
excludeSteerIds?: Iterable<string>;
generationProtocolVersion?: GenerationProtocolVersion;
},
) => {
const chips = snapshot.getLoadable(store.pendingSteersByConvoId(conversationId)).getValue();
+ const generationProtocolVersion =
+ options?.generationProtocolVersion ??
+ snapshot
+ .getLoadable(store.activeGenerationProtocolVersionByConvoId(conversationId))
+ .getValue();
+ const activeStatuses = options?.statuses ?? RUN_ENDED_STATUSES;
const excluded = new Set(options?.excludeSteerIds ?? []);
- const settled = chips
- .filter(
- (steer) =>
- steer.status === 'pending' &&
- !excluded.has(steer.steerId) &&
- (steer.clientSteerId == null || !excluded.has(steer.clientSteerId)),
- )
- .map((steer) => ({
- steerId: steer.steerId,
- ...(steer.clientSteerId && { clientSteerId: steer.clientSteerId }),
- text: steer.text,
- createdAt: steer.createdAt,
- ...(steer.files && steer.files.length > 0 && { files: steer.files }),
- ...(steer.queuedOrigin && { queuedOrigin: steer.queuedOrigin }),
- }));
- if (settled.length > 0) {
- convertSteersToQueued(conversationId, settled, {
+ const accepted = selectLocalSteersForQueue(
+ chips,
+ activeStatuses.filter((status) => status === 'pending'),
+ excluded,
+ );
+ if (accepted.length > 0) {
+ convertSteersToQueued(conversationId, accepted, {
claimParked: options?.claimParked,
- generationProtocolVersion: options?.generationProtocolVersion,
+ generationProtocolVersion,
+ });
+ }
+ const failed = selectLocalSteersForQueue(
+ chips,
+ activeStatuses.filter((status) => status === 'failed'),
+ excluded,
+ );
+ if (failed.length > 0) {
+ convertSteersToQueued(conversationId, failed, {
+ generationProtocolVersion,
+ bindRecoverySource: false,
+ /** Swept out of the chip surface so it cannot render under the next
+ * reply, but the server refused these words: the rail holds the row
+ * for Retry or an explicit send instead of draining it automatically. */
+ needsExplicitSend: true,
});
}
},
@@ -1330,7 +1399,7 @@ export default function useResumableSSE(
/**
* Run steps and activity labels must resolve indices in ONE space, and the
- * resume SYNC boundary that invalidates the edit prefix is owned here — so
+ * resume SYNC boundary that invalidates the edit prefix is owned here, so
* this transport stamps its cleared state onto every dispatched
* submission. `useStepHandler` reads the flag (alongside the captured
* `editPrefixLength`) instead of measuring the live
@@ -1444,19 +1513,19 @@ export default function useResumableSSE(
}
/**
* A NEW generation starts with its retained prefix intact, so the
- * cleared-prefix state from a previous one must not carry over — the
+ * cleared-prefix state from a previous one must not carry over: the
* hook outlives any single submission, and a later edited resubmission
* would otherwise dispatch with no offset and overwrite the content it
* kept.
*
* Keyed on `clientRequestId`, the per-submission uuid. Each of the
* narrower keys tried before it crossed a real boundary:
- * - `isResume` — a submission whose POST succeeded but lost its
+ * - `isResume`: a submission whose POST succeeded but lost its
* response retries and returns `resumed: true`, so a NEW generation
* arrives in resume mode and skipped the reset.
- * - the stream id — `request.js` sets `streamId = conversationId`, so
+ * - the stream id: `request.js` sets `streamId = conversationId`, so
* every generation in a conversation shares it.
- * - the response message id — editing an assistant response reuses
+ * - the response message id: editing an assistant response reuses
* that same id (`editedMessageId`), so re-editing one response
* produced the same key twice.
* `clientRequestId` is minted per submission and forwarded unchanged on
@@ -1548,7 +1617,7 @@ export default function useResumableSSE(
* rather than clobbering it.
*
* If the mapping is a no-op (the paused tool-call content part hasn't
- * rendered yet — a pause-before-render race), retry on subsequent frames
+ * rendered yet, a pause-before-render race), retry on subsequent frames
* so the approval still attaches. `ask_user_question` always applies (it
* appends a synthetic part), so only `tool_approval` ever retries.
*/
@@ -1582,7 +1651,7 @@ export default function useResumableSSE(
}
};
/** The pause card must attach to the same message state the stream
- * produced — apply any queued delta before reading the cache, or the
+ * produced: apply any queued delta before reading the cache, or the
* later flush would clobber the card (and `syncStepMessage` below
* would sync a pre-delta copy). */
flushPendingDeltas();
@@ -1770,7 +1839,7 @@ export default function useResumableSSE(
return;
}
/** Edit-and-resubmit replays the kept prefix into the response before
- * the run starts, and the server indexes only the NEW content — so
+ * the run starts, and the server indexes only the NEW content, so
* run steps offset by that prefix (`useStepHandler`). The label index
* is claimed in the same server-side space and needs the identical
* shift, or it lands inside the prefix and overwrites kept content.
@@ -1780,7 +1849,7 @@ export default function useResumableSSE(
* `initialResponse.content` with the server's completion-local
* snapshot, so its length no longer describes the retained prefix.
* Tool cards and the label heading them must land in one index
- * space — a label shifting differently from its tools would overwrite
+ * space: a label shifting differently from its tools would overwrite
* another part, and a gap fill would miss its own reservation and
* leave the placeholder pending forever. */
const prefixLength = editPrefixLength();
@@ -2118,6 +2187,11 @@ export default function useResumableSSE(
generationProtocolVersion,
},
);
+ // A `failed` chip never reached the server, so it never rides
+ // `data.pendingSteers` above; without this it survives a NORMAL
+ // completion and renders (with a live Retry) under the NEXT run's
+ // reply. Idempotent alongside the call above: both dedupe by id.
+ convertLocalSteersToQueued(finalConvoId);
let finalHandled = false;
try {
finalHandler(data as TFinalResData, currentSubmission as EventSubmission);
@@ -2148,7 +2222,7 @@ export default function useResumableSSE(
conversationId: runEndTarget.conversationId,
// A Stop that lands before completion can arrive as a final with
// `unfinished: true` and no `aborted` flag (request.js's
- // wasAbortedBeforeComplete branch) — it must not auto-drain.
+ // wasAbortedBeforeComplete branch); it must not auto-drain.
outcome: finalOutcome,
startedAsNewConvo: runEndTarget.startedAsNewConvo,
endedAt: Date.now(),
@@ -2314,11 +2388,11 @@ export default function useResumableSSE(
if (data.resumeState?.contextUsage) {
/** Already reconciled to the call's real prompt tokens server-side
* (GenerationJobManager.persistTokenUsage) when the snapshot's call
- * completed, so install it as-is — no client backfill reconcile. */
+ * completed, so install it as-is: no client backfill reconcile. */
contextHandler(data.resumeState.contextUsage, resumeSubmission);
}
- /** Output streamed before this resume is not re-delivered as deltas
- * — estimate it from the trailing aggregated content. This is
+ /** Output streamed before this resume is not re-delivered as deltas;
+ * estimate it from the trailing aggregated content. This is
* needed even with a snapshot: the snapshot is pre-invoke, so the
* in-flight output it precedes rides on the live estimate.
* countTrailingOutputChars only counts output at the very end (0
@@ -2379,7 +2453,7 @@ export default function useResumableSSE(
* prefix an edited resubmission had retained: the snapshot is
* completion-local, indexed from zero. Every later event must
* therefore stop offsetting, or it writes past the end of the
- * shorter array — for an activity label that means the fill
+ * shorter array: for an activity label that means the fill
* misses its own reservation and the placeholder never
* resolves. Preserving `oldContent` keeps the prefix, and with
* it the offset. Run steps and labels both read this.
@@ -2615,7 +2689,7 @@ export default function useResumableSSE(
parentMessageId: data.parentMessageId,
messageId: data.messageId,
} as TMessage;
- /** Legacy non-agent streams send cumulative text here — feed the
+ /** Legacy non-agent streams send cumulative text here; feed the
* live estimate like the content path above */
const textSubmission = { ...currentSubmission, userMessage, initialResponse };
currentSubmission = textSubmission;
@@ -3324,35 +3398,17 @@ export default function useResumableSSE(
!createdStreamIdsRef.current.has(currentStreamId) &&
optimisticStreamIdsRef.current.has(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);
- }
+ 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);
}
// An inconclusive read must not turn a saved chat into a phantom.
invalidateConversationLists(queryClient);
@@ -3411,7 +3467,7 @@ export default function useResumableSSE(
cancelSteerRetryFrames();
closeStream();
/** FLUSH (not cancel): the error card below is built from the cache
- * tail, so queued tokens must land first — and a stale trailing
+ * tail, so queued tokens must land first, and a stale trailing
* frame must never overwrite the error write. */
flushPendingDeltas();
removeActiveJob(currentStreamId);
@@ -3817,6 +3873,18 @@ export default function useResumableSSE(
* merge into the next response in this conversation. On a resume the
* collected usage is re-folded via backfillUsage, so nothing is lost. */
resetLive({ ...currentSubmission, userMessage });
+ // No final/error event fires on this path, so it's the only place left
+ // to sweep a local `failed` chip; otherwise it survives this close and
+ // renders (with a live Retry) under whatever run starts next. `pending`
+ // chips are deliberately left alone here: this listener also fires on
+ // navigation away while the run CONTINUES server-side, so a
+ // server-ACK'd `pending` steer is not stranded: the server injects it
+ // regardless, and sweeping it into the queue too would resend the same
+ // words as a duplicate turn once `useQueueDrain` fires at run end.
+ convertLocalSteersToQueued(
+ currentSubmission.conversation?.conversationId ?? currentStreamId,
+ { statuses: ABORT_SWEEP_STATUSES },
+ );
};
connection = createSSETransport({ token }).reconnectToStream(
@@ -4656,7 +4724,7 @@ export default function useResumableSSE(
// Optimistically add to active jobs
addActiveJob(newStreamId);
// Queue title generation if this is a new conversation (first message).
- // Skip temporary conversations — the server never generates titles for
+ // Skip temporary conversations: the server never generates titles for
// them, so polling would 404 indefinitely.
const isNewConvo = isInitialNewConversation(submission);
if (isNewConvo && !submission.isTemporary) {
@@ -4684,7 +4752,15 @@ export default function useResumableSSE(
}
};
- initStream();
+ /* Fire-and-forget, but not silent: this sets the submitting flags before
+ it does any work, so a throw would leave the composer generating with no
+ stream, no final event and no way back but a reload. */
+ initStream().catch((error: unknown) => {
+ logger.error('[useResumableSSE] Failed to start the stream', error);
+ setIsSubmitting(false);
+ setShowStopButton(false);
+ setSubmission(null);
+ });
/** The Set object itself is never reassigned, so this alias reads the
* LIVE frame ids at cleanup time (satisfies react-hooks/exhaustive-deps
diff --git a/client/src/hooks/__tests__/useIsActiveItem.spec.tsx b/client/src/hooks/__tests__/useIsActiveItem.spec.tsx
index eba51d2617..5a068cb346 100644
--- a/client/src/hooks/__tests__/useIsActiveItem.spec.tsx
+++ b/client/src/hooks/__tests__/useIsActiveItem.spec.tsx
@@ -36,13 +36,13 @@ const nextActiveItemMutation = (element: HTMLElement): Promise<void> =>
* mutation; this unfiltered observer proves delivery happened before the test asserts
* that the hook did not react.
*/
-const nextAttributeMutation = (element: HTMLElement): Promise<void> =>
+const nextAttributeMutation = (element: HTMLElement, attributeName: string): Promise<void> =>
new Promise((resolve) => {
const observer = new MutationObserver(() => {
observer.disconnect();
resolve();
});
- observer.observe(element, { attributes: true });
+ observer.observe(element, { attributes: true, attributeFilter: [attributeName] });
});
describe('useIsActiveItem', () => {
@@ -87,7 +87,7 @@ describe('useIsActiveItem', () => {
const { container } = render(<Probe />);
const probe = getProbe(container);
- const delivered = nextAttributeMutation(probe);
+ const delivered = nextAttributeMutation(probe, 'data-something-else');
await act(async () => {
probe.setAttribute('data-something-else', 'x');
await delivered;
diff --git a/client/src/hooks/useKeyboardShortcuts.spec.tsx b/client/src/hooks/useKeyboardShortcuts.spec.tsx
index 4155e92dd1..a1299fb984 100644
--- a/client/src/hooks/useKeyboardShortcuts.spec.tsx
+++ b/client/src/hooks/useKeyboardShortcuts.spec.tsx
@@ -1,34 +1,70 @@
-import copy from 'copy-to-clipboard';
import { MemoryRouter } from 'react-router-dom';
import { RecoilRoot, useRecoilValue } from 'recoil';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
-import { render, act, cleanup, renderHook } from '@testing-library/react';
-import type { TConversation } from 'librechat-data-provider';
+import { render, act, cleanup, renderHook, fireEvent, screen } from '@testing-library/react';
+import type { SettingDefinition, TConversation } from 'librechat-data-provider';
import type { MutableSnapshot } from 'recoil';
import type { ReactNode } from 'react';
+import type * as ReasoningModule from '~/components/Chat/Input/Reasoning';
import useKeyboardShortcuts, {
isOverridden,
effectiveBinding,
useShortcutHint,
+ useShortcutActions,
getShortcutDisplay,
getShortcutAriaKey,
useShortcutDisplay,
useShortcutAriaKey,
} from './useKeyboardShortcuts';
+import { ReasoningControl } from '~/components/Chat/Input/Reasoning';
+import Thinking from '~/components/Chat/Input/Composer/Thinking';
import store from '~/store';
-jest.mock('copy-to-clipboard', () => ({
+/** `copy-to-clipboard` exports a single callable: `copy(text, options?)`. */
+const mockCopy = jest.fn((_text: string, _options?: { format?: string }) => true);
+
+jest.mock('~/components/Chat/Input/Reasoning', () => ({
+ __esModule: true,
+ ReasoningControl: jest.requireActual<typeof ReasoningModule>('~/components/Chat/Input/Reasoning')
+ .ReasoningControl,
+ useComposerReasoning: () => ({
+ setting: {
+ key: 'reasoning_effort',
+ type: 'enum',
+ default: 'low',
+ options: ['auto', 'low', 'high'],
+ } as SettingDefinition,
+ value: { key: 'reasoning_effort', value: 'low' },
+ setValue: jest.fn(),
+ }),
+}));
+
+jest.mock('~/data-provider/Endpoints/queries', () => ({
+ ...jest.requireActual('~/data-provider/Endpoints/queries'),
+ useGetStartupConfig: () => ({ data: { interface: { parameters: true } } }),
+}));
+
+jest.mock('~/Providers', () => ({
+ useChatContext: () => ({
+ conversation: { conversationId: 'test-convo', endpoint: 'openAI', model: 'gpt-4o' },
+ }),
+}));
+
+jest.mock('~/hooks/Generic/useReducedMotion', () => ({
__esModule: true,
- default: jest.fn(() => true),
+ default: () => true,
}));
+jest.mock('copy-to-clipboard', () => ({
+ __esModule: true,
+ default: (text: string, options?: { format?: string }) => mockCopy(text, options),
+}));
jest.mock('./useNewConvo', () => ({
__esModule: true,
default: () => ({ newConversation: jest.fn() }),
}));
const STORAGE_KEY = 'customKeyboardShortcuts';
-const copyMock = copy as jest.MockedFunction<typeof copy>;
let queryClient: QueryClient;
function buildConversation(conversationId: string, title: string): TConversation {
@@ -59,6 +95,7 @@ function renderHarness(
conversation?: TConversation,
route = '/c/test-convo',
initialize?: (snapshot: MutableSnapshot) => void,
+ children?: ReactNode,
) {
const initializeState = (snapshot: MutableSnapshot) => {
if (conversation) {
@@ -66,21 +103,27 @@ function renderHarness(
}
initialize?.(snapshot);
};
- return render(<Harness />, {
- wrapper: ({ children }: { children: ReactNode }) => (
- <QueryClientProvider client={queryClient}>
- <RecoilRoot initializeState={initializeState}>
- <MemoryRouter initialEntries={[route]}>{children}</MemoryRouter>
- </RecoilRoot>
- </QueryClientProvider>
- ),
- });
+ return render(
+ <>
+ <Harness />
+ {children}
+ </>,
+ {
+ wrapper: ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={queryClient}>
+ <RecoilRoot initializeState={initializeState}>
+ <MemoryRouter initialEntries={[route]}>{children}</MemoryRouter>
+ </RecoilRoot>
+ </QueryClientProvider>
+ ),
+ },
+ );
}
beforeEach(() => {
queryClient = new QueryClient();
window.localStorage.clear();
- copyMock.mockClear();
+ mockCopy.mockClear();
});
afterEach(() => {
@@ -107,7 +150,55 @@ function appendResponseCopyButton(onClick: () => void) {
document.body.appendChild(button);
}
-function appendEscalationButton(surface: 'bubble' | 'queued', active = false) {
+/** A composer form carrying the stop control the way `ChatForm` renders it:
+ * visible when it owns the action slot, hidden behind the during-run send
+ * button while the user types a steer. */
+function appendComposerForm({ hidden = false }: { hidden?: boolean } = {}) {
+ const onClick = jest.fn();
+ const pane = document.createElement('div');
+ pane.dataset.chatPane = String(document.querySelectorAll('[data-chat-pane]').length);
+ const form = document.createElement('form');
+ const textarea = document.createElement('textarea');
+ const button = document.createElement('button');
+ button.type = 'button';
+ button.dataset.testid = 'stop-generation-button';
+ if (hidden) {
+ button.style.display = 'none';
+ }
+ button.addEventListener('click', onClick);
+ form.append(textarea, button);
+ pane.appendChild(form);
+ document.body.appendChild(pane);
+ return { form: pane, textarea, onClick };
+}
+
+/** A composer form carrying the palette disclosure the upload shortcut clicks.
+ * Identified by test id rather than by `id`, which two mounted composers
+ * cannot share. */
+function appendPaletteForm({ uploadShortcut = true }: { uploadShortcut?: boolean } = {}) {
+ const onClick = jest.fn();
+ const pane = document.createElement('div');
+ pane.dataset.chatPane = String(document.querySelectorAll('[data-chat-pane]').length);
+ const form = document.createElement('form');
+ const textarea = document.createElement('textarea');
+ const anchor = document.createElement('button');
+ anchor.type = 'button';
+ const button = document.createElement('button');
+ button.type = 'button';
+ button.dataset.testid = 'composer-palette-button';
+ button.dataset.uploadShortcut = String(uploadShortcut);
+ button.addEventListener('click', onClick);
+ form.append(textarea, anchor, button);
+ pane.appendChild(form);
+ document.body.appendChild(pane);
+ return { form: pane, textarea, anchor, onClick };
+}
+
+function appendEscalationButton(
+ surface: 'bubble' | 'queued',
+ active = false,
+ parent: HTMLElement = document.body,
+) {
const onClick = jest.fn();
const button = document.createElement('button');
button.dataset.escalateSteer = surface;
@@ -115,10 +206,20 @@ function appendEscalationButton(surface: 'bubble' | 'queued', active = false) {
button.dataset.escalateSteerActive = 'true';
}
button.addEventListener('click', onClick);
- document.body.appendChild(button);
+ parent.appendChild(button);
return { button, onClick };
}
+function appendPortalFocus(paneIndex: number, tag: 'button' | 'input' = 'button') {
+ const portal = document.createElement('div');
+ portal.dataset.chatPanePortal = String(paneIndex);
+ const focusTarget = document.createElement(tag);
+ portal.appendChild(focusTarget);
+ document.body.appendChild(portal);
+ focusTarget.focus();
+ return focusTarget;
+}
+
describe('binding resolution helpers', () => {
it('falls back to the default binding when there is no override', () => {
const binding = effectiveBinding('newChat');
@@ -257,6 +358,24 @@ describe('global shortcut dispatch', () => {
expect(event.defaultPrevented).toBe(false);
});
+ it('ignores hidden dialog shells but suppresses shortcuts for visible dialogs', () => {
+ renderHarness();
+ const hiddenDialog = document.createElement('div');
+ hiddenDialog.setAttribute('role', 'dialog');
+ hiddenDialog.hidden = true;
+ document.body.appendChild(hiddenDialog);
+
+ const hiddenEvent = dispatchKey({ key: 's', ctrlKey: true, shiftKey: true });
+ expect(hiddenEvent.defaultPrevented).toBe(true);
+
+ hiddenDialog.remove();
+ const visibleDialog = document.createElement('div');
+ visibleDialog.setAttribute('role', 'dialog');
+ document.body.appendChild(visibleDialog);
+
+ const visibleEvent = dispatchKey({ key: 's', ctrlKey: true, shiftKey: true });
+ expect(visibleEvent.defaultPrevented).toBe(false);
+ });
it('ignores non-allowed shortcuts while typing in an input', () => {
renderHarness();
@@ -338,6 +457,44 @@ describe('global shortcut dispatch', () => {
expect(newest.onClick).toHaveBeenCalledTimes(1);
});
+ it('keeps escalation inside the pane containing keyboard focus', () => {
+ renderHarness();
+ const focusedPane = document.createElement('section');
+ const otherPane = document.createElement('section');
+ focusedPane.dataset.chatPane = '0';
+ otherPane.dataset.chatPane = '1';
+ const textarea = document.createElement('textarea');
+ const focused = appendEscalationButton('bubble', false, focusedPane);
+ const other = appendEscalationButton('bubble', true, otherPane);
+ focusedPane.appendChild(textarea);
+ document.body.append(focusedPane, otherPane);
+ textarea.focus();
+
+ const event = dispatchKey({ key: '.', ctrlKey: true, shiftKey: true }, textarea);
+
+ expect(focused.onClick).toHaveBeenCalledTimes(1);
+ expect(other.onClick).not.toHaveBeenCalled();
+ expect(event.defaultPrevented).toBe(true);
+ });
+
+ it('keeps escalation scoped while focus is inside a portaled palette', () => {
+ renderHarness();
+ const firstPane = document.createElement('section');
+ const secondPane = document.createElement('section');
+ firstPane.dataset.chatPane = '0';
+ secondPane.dataset.chatPane = '1';
+ const first = appendEscalationButton('bubble', true, firstPane);
+ const second = appendEscalationButton('bubble', false, secondPane);
+ document.body.append(firstPane, secondPane);
+ const focusTarget = appendPortalFocus(1, 'input');
+
+ const event = dispatchKey({ key: '.', ctrlKey: true, shiftKey: true }, focusTarget);
+
+ expect(second.onClick).toHaveBeenCalledTimes(1);
+ expect(first.onClick).not.toHaveBeenCalled();
+ expect(event.defaultPrevented).toBe(true);
+ });
+
it('dispatches the escalation shortcut by physical key on a non-US layout', () => {
renderHarness();
const escalation = appendEscalationButton('bubble');
@@ -419,7 +576,7 @@ describe('clipboard shortcuts', () => {
expect(firstCopy).not.toHaveBeenCalled();
expect(secondCopy).toHaveBeenCalledTimes(1);
- expect(copyMock).not.toHaveBeenCalled();
+ expect(mockCopy).not.toHaveBeenCalled();
expect(event.defaultPrevented).toBe(true);
});
@@ -429,7 +586,7 @@ describe('clipboard shortcuts', () => {
const event = dispatchKey({ key: 'k', ctrlKey: true, shiftKey: true });
- expect(copyMock).toHaveBeenCalledWith('const x = 1;', { format: 'text/plain' });
+ expect(mockCopy).toHaveBeenCalledWith('const x = 1;', { format: 'text/plain' });
expect(event.defaultPrevented).toBe(true);
});
@@ -438,7 +595,278 @@ describe('clipboard shortcuts', () => {
const event = dispatchKey({ key: 'k', ctrlKey: true, shiftKey: true });
- expect(copyMock).not.toHaveBeenCalled();
+ expect(mockCopy).not.toHaveBeenCalled();
+ expect(event.defaultPrevented).toBe(false);
+ });
+});
+
+describe('stop generating shortcut', () => {
+ it('stops the run of the pane the user is focused in', () => {
+ renderHarness();
+ const first = appendComposerForm();
+ const second = appendComposerForm();
+ second.textarea.focus();
+
+ const event = dispatchKey({ key: 'x', ctrlKey: true, shiftKey: true }, second.textarea);
+
+ expect(second.onClick).toHaveBeenCalledTimes(1);
+ expect(first.onClick).not.toHaveBeenCalled();
+ expect(event.defaultPrevented).toBe(true);
+ });
+ it('clicks the visible stop control when a hidden control is mounted first', () => {
+ renderHarness();
+ const hiddenClick = jest.fn();
+ const visibleClick = jest.fn();
+ const hidden = document.createElement('button');
+ hidden.dataset.testid = 'stop-generation-button';
+ hidden.style.display = 'none';
+ hidden.addEventListener('click', hiddenClick);
+ const visible = document.createElement('button');
+ visible.dataset.testid = 'stop-generation-button';
+ visible.addEventListener('click', visibleClick);
+ const focusTarget = document.createElement('input');
+ document.body.append(hidden, visible, focusTarget);
+ focusTarget.focus();
+
+ const event = dispatchKey({ key: 'x', ctrlKey: true, shiftKey: true }, focusTarget);
+
+ expect(hiddenClick).not.toHaveBeenCalled();
+ expect(visibleClick).toHaveBeenCalledTimes(1);
+ expect(event.defaultPrevented).toBe(true);
+ });
+
+ /* A drafted follow-up gives the send button the composer slot during a run,
+ leaving the stop control mounted but hidden; with focus in a dialog there
+ is no focused pane, and stop must still reach that control. */
+ it('clicks a hidden stop control when no visible one exists and no pane is focused', () => {
+ renderHarness();
+ const hiddenClick = jest.fn();
+ const hidden = document.createElement('button');
+ hidden.dataset.testid = 'stop-generation-button';
+ hidden.hidden = true;
+ hidden.addEventListener('click', hiddenClick);
+ const dialogInput = document.createElement('input');
+ document.body.append(hidden, dialogInput);
+ dialogInput.focus();
+
+ const event = dispatchKey({ key: 'x', ctrlKey: true, shiftKey: true }, dialogInput);
+
+ expect(hiddenClick).toHaveBeenCalledTimes(1);
+ expect(event.defaultPrevented).toBe(true);
+ });
+
+ it('uses the visible model selector when a hidden selector is mounted first', () => {
+ renderHarness();
+ const hiddenClick = jest.fn();
+ const visibleClick = jest.fn();
+ const hidden = document.createElement('button');
+ hidden.dataset.testid = 'model-selector-button';
+ hidden.style.display = 'none';
+ hidden.addEventListener('click', hiddenClick);
+ const visible = document.createElement('button');
+ visible.dataset.testid = 'model-selector-button';
+ visible.addEventListener('click', visibleClick);
+ document.body.append(hidden, visible);
+ visible.focus();
+
+ const event = dispatchKey({ key: 'm', ctrlKey: true, shiftKey: true }, visible);
+
+ expect(hiddenClick).not.toHaveBeenCalled();
+ expect(visibleClick).toHaveBeenCalledTimes(1);
+ expect(event.defaultPrevented).toBe(true);
+ });
+
+ it('stops through the hidden control while the during-run send button owns the slot', () => {
+ renderHarness();
+ const other = appendComposerForm();
+ const focused = appendComposerForm({ hidden: true });
+ focused.textarea.focus();
+
+ const event = dispatchKey({ key: 'x', ctrlKey: true, shiftKey: true }, focused.textarea);
+
+ expect(focused.onClick).toHaveBeenCalledTimes(1);
+ expect(other.onClick).not.toHaveBeenCalled();
+ expect(event.defaultPrevented).toBe(true);
+ });
+
+ it('stops the owning pane while focus is inside its portaled palette', () => {
+ renderHarness();
+ const first = appendComposerForm();
+ const second = appendComposerForm();
+ first.form.dataset.chatPane = '0';
+ second.form.dataset.chatPane = '1';
+ const focusTarget = appendPortalFocus(1, 'input');
+
+ const event = dispatchKey({ key: 'x', ctrlKey: true, shiftKey: true }, focusTarget);
+
+ expect(second.onClick).toHaveBeenCalledTimes(1);
+ expect(first.onClick).not.toHaveBeenCalled();
+ expect(event.defaultPrevented).toBe(true);
+ });
+
+ it('stops only the secondary pane from its numeric reasoning input and slider', () => {
+ const setting = {
+ key: 'thinkingBudget',
+ label: 'com_endpoint_thinking_budget',
+ type: 'number',
+ range: { min: -1, positiveMin: 128, max: 32768, step: 128 },
+ } as SettingDefinition;
+ let stop: (() => boolean | void) | undefined;
+ function NumericReasoning() {
+ stop = useShortcutActions().find((action) => action.id === 'stopGenerating')?.run;
+ return (
+ <ReasoningControl
+ index={1}
+ setting={setting}
+ value={{ key: 'thinkingBudget', value: 4096 }}
+ onChange={jest.fn()}
+ />
+ );
+ }
+ renderHarness(undefined, '/c/test-convo', undefined, <NumericReasoning />);
+ const first = appendComposerForm();
+ const second = appendComposerForm();
+ first.form.dataset.chatPane = '0';
+ second.form.dataset.chatPane = '1';
+ fireEvent.click(screen.getByRole('button', { name: /Reasoning for next message/ }));
+
+ for (const role of ['spinbutton', 'slider']) {
+ const control = screen.getByRole(role);
+ control.focus();
+ act(() => {
+ expect(stop?.()).toBe(true);
+ });
+ }
+
+ expect(second.onClick).toHaveBeenCalledTimes(2);
+ expect(first.onClick).not.toHaveBeenCalled();
+ });
+ it('stops only the secondary pane from its thinking effort radios', () => {
+ let stop: (() => boolean | void) | undefined;
+ function EnumThinking() {
+ stop = useShortcutActions().find((action) => action.id === 'stopGenerating')?.run;
+ return <Thinking index={1} disabled={false} hasAddedConversation={false} />;
+ }
+
+ renderHarness(undefined, '/c/test-convo', undefined, <EnumThinking />);
+ const first = appendComposerForm();
+ const second = appendComposerForm();
+ first.form.dataset.chatPane = '0';
+ second.form.dataset.chatPane = '1';
+
+ fireEvent.click(screen.getByRole('button', { name: /thinking/i }));
+ const effort = screen.getByRole('radio', { name: 'Low' });
+ effort.focus();
+
+ act(() => {
+ expect(stop?.()).toBe(true);
+ });
+
+ expect(second.onClick).toHaveBeenCalledTimes(1);
+ expect(first.onClick).not.toHaveBeenCalled();
+ });
+
+ it('stops the pane whose header controls hold focus', () => {
+ renderHarness();
+ const first = appendComposerForm();
+ const second = appendComposerForm();
+ const headerControl = appendPortalFocus(1);
+
+ const event = dispatchKey({ key: 'x', ctrlKey: true, shiftKey: true }, headerControl);
+
+ expect(second.onClick).toHaveBeenCalledTimes(1);
+ expect(first.onClick).not.toHaveBeenCalled();
+ expect(event.defaultPrevented).toBe(true);
+ });
+
+ it('does nothing when focus is in an idle pane while another pane is generating', () => {
+ renderHarness();
+ const generating = appendComposerForm();
+ const idle = appendComposerForm();
+ generating.form.dataset.chatPane = '0';
+ idle.form.dataset.chatPane = '1';
+ idle.form.querySelector('[data-testid="stop-generation-button"]')?.remove();
+ idle.textarea.focus();
+
+ const event = dispatchKey({ key: 'x', ctrlKey: true, shiftKey: true }, idle.textarea);
+
+ expect(generating.onClick).not.toHaveBeenCalled();
+ expect(event.defaultPrevented).toBe(false);
+ });
+
+ it('does not prevent the event when nothing is generating', () => {
+ renderHarness();
+
+ const event = dispatchKey({ key: 'x', ctrlKey: true, shiftKey: true });
+
+ expect(event.defaultPrevented).toBe(false);
+ });
+});
+
+describe('upload file shortcut', () => {
+ /* Focus sits on a button rather than the textarea: `uploadFile` is not in
+ EDITING_ALLOWED_SHORTCUTS, so the chord is filtered out entirely while the
+ caret is in a composer. Pane resolution matters for the focus that is left,
+ anywhere in a pane that is not an editing context. */
+ it('opens the palette of the pane the user is focused in', () => {
+ renderHarness();
+ const first = appendPaletteForm();
+ const second = appendPaletteForm();
+ second.anchor.focus();
+
+ const event = dispatchKey({ key: 'u', ctrlKey: true, shiftKey: true }, second.anchor);
+
+ expect(second.onClick).toHaveBeenCalledTimes(1);
+ expect(first.onClick).not.toHaveBeenCalled();
+ expect(event.defaultPrevented).toBe(true);
+ });
+
+ it('opens the owning palette while focus is inside its portal', () => {
+ renderHarness();
+ const first = appendPaletteForm();
+ const second = appendPaletteForm();
+ first.form.dataset.chatPane = '0';
+ second.form.dataset.chatPane = '1';
+ const focusTarget = appendPortalFocus(1);
+
+ const event = dispatchKey({ key: 'u', ctrlKey: true, shiftKey: true }, focusTarget);
+
+ expect(second.onClick).toHaveBeenCalledTimes(1);
+ expect(first.onClick).not.toHaveBeenCalled();
+ expect(event.defaultPrevented).toBe(true);
+ });
+
+ it('opens the palette while the caret is in a composer', () => {
+ renderHarness();
+ const only = appendPaletteForm();
+ only.textarea.focus();
+
+ const event = dispatchKey({ key: 'u', ctrlKey: true, shiftKey: true }, only.textarea);
+
+ expect(only.onClick).toHaveBeenCalledTimes(1);
+ expect(event.defaultPrevented).toBe(true);
+ });
+
+ it('falls back to the document when focus sits outside any composer', () => {
+ renderHarness();
+ const only = appendPaletteForm();
+
+ const event = dispatchKey({ key: 'u', ctrlKey: true, shiftKey: true });
+
+ expect(only.onClick).toHaveBeenCalledTimes(1);
+ expect(event.defaultPrevented).toBe(true);
+ });
+
+ it('does not cancel dictation or fall through to another pane', () => {
+ renderHarness();
+ const other = appendPaletteForm();
+ const dictating = appendPaletteForm({ uploadShortcut: false });
+ dictating.anchor.focus();
+
+ const event = dispatchKey({ key: 'u', ctrlKey: true, shiftKey: true }, dictating.anchor);
+
+ expect(dictating.onClick).not.toHaveBeenCalled();
+ expect(other.onClick).not.toHaveBeenCalled();
expect(event.defaultPrevented).toBe(false);
});
});
diff --git a/client/src/hooks/useKeyboardShortcuts.ts b/client/src/hooks/useKeyboardShortcuts.ts
index d63aeda894..4f837e155d 100644
--- a/client/src/hooks/useKeyboardShortcuts.ts
+++ b/client/src/hooks/useKeyboardShortcuts.ts
@@ -1,4 +1,5 @@
import { useCallback, useEffect, useMemo } from 'react';
+import { useSetAtom } from 'jotai';
import copy from 'copy-to-clipboard';
import { useToastContext } from '@librechat/client';
import { useMatch, useNavigate } from 'react-router-dom';
@@ -17,7 +18,9 @@ import {
import { mainTextareaId, NotificationSeverity } from '~/common';
import useSidebarToggle from '~/hooks/Nav/useSidebarToggle';
import { useArchiveConvoMutation } from '~/data-provider';
+import { showFilesDialogAtom } from '~/store/filesDialog';
import { useHasAccess, useLocalize } from '~/hooks';
+import { getFocusedChatPane } from '~/utils/pane';
import useNewChat from '~/hooks/Chat/useNewChat';
import store from '~/store';
@@ -299,6 +302,11 @@ export const EDITING_ALLOWED_SHORTCUTS: ReadonlySet<ShortcutActionId> = new Set(
'submitMessage',
'escalateSteer',
'uploadFile',
+ /* The composer keeps focus across a send, so this is where a user reads the
+ hint naming it and where they press it. Filtering it out as an editing
+ chord made the one shortcut the composer advertises the one that did
+ nothing; it is a no-op whenever no reply is running. */
+ 'stopGenerating',
]);
export type ShortcutAction = ShortcutDefinition & {
@@ -332,6 +340,17 @@ function anyModalOpen(): boolean {
if (dialog.getAttribute('data-state') === 'closed') {
continue;
}
+ if (dialog.hasAttribute('hidden')) {
+ continue;
+ }
+ const style = (dialog as HTMLElement).style;
+ if (style.display === 'none' || style.visibility === 'hidden') {
+ continue;
+ }
+ const computedStyle = typeof window !== 'undefined' ? window.getComputedStyle(dialog) : null;
+ if (computedStyle?.display === 'none' || computedStyle?.visibility === 'hidden') {
+ continue;
+ }
return true;
}
return false;
@@ -363,8 +382,34 @@ function clickTarget(el: HTMLElement | null | undefined): boolean {
return true;
}
+function isVisibleElement(el: HTMLElement): boolean {
+ for (let current: HTMLElement | null = el; current != null; current = current.parentElement) {
+ if (current.hidden) {
+ return false;
+ }
+ const style = current.style;
+ const computedStyle = typeof window !== 'undefined' ? window.getComputedStyle(current) : null;
+ if (
+ style.display === 'none' ||
+ style.visibility === 'hidden' ||
+ computedStyle?.display === 'none' ||
+ computedStyle?.visibility === 'hidden'
+ ) {
+ return false;
+ }
+ }
+ return true;
+}
+
function clickElement(selector: string): boolean {
- return clickTarget(document.querySelector<HTMLElement>(selector));
+ const elements = document.querySelectorAll<HTMLElement>(selector);
+ for (const element of elements) {
+ if (!isUnavailableElement(element) && isVisibleElement(element)) {
+ element.click();
+ return true;
+ }
+ }
+ return false;
}
function clickLastElement(selector: string): boolean {
@@ -504,6 +549,7 @@ export function useShortcutActions(): ShortcutAction[] {
const sidebarExpanded = useRecoilValue(store.sidebarExpanded);
const { setSidebarOpen, toggleSidebar } = useSidebarToggle();
const setShowShortcutsDialog = useSetRecoilState(store.showShortcutsDialog);
+ const setShowFilesDialog = useSetAtom(showFilesDialogAtom);
const setIsTemporary = useSetRecoilState(store.isTemporary);
const setDeleteTarget = useSetRecoilState(store.keyboardDeleteTarget);
const hasAccessToTemporaryChat = useHasAccess({
@@ -603,10 +649,23 @@ export function useShortcutActions(): ShortcutAction[] {
return copy(text.trim(), { format: 'text/plain' });
}, []);
- const handleStopGenerating = useCallback(
- () => clickElement('[data-testid="stop-generation-button"]'),
- [],
- );
+ const handleStopGenerating = useCallback(() => {
+ const focusedPane = getFocusedChatPane();
+ const scoped = focusedPane?.querySelector<HTMLElement>(
+ '[data-testid="stop-generation-button"]',
+ );
+ if (focusedPane == null) {
+ /** A run with a drafted follow-up keeps its stop control mounted but
+ * hidden behind the send button, and stop must still reach it. */
+ return (
+ clickElement('[data-testid="stop-generation-button"]') ||
+ Array.from(
+ document.querySelectorAll<HTMLElement>('[data-testid="stop-generation-button"]'),
+ ).some(clickTarget)
+ );
+ }
+ return scoped != null ? clickTarget(scoped) : false;
+ }, []);
const handleRegenerateResponse = useCallback(
() => clickElement('[data-testid="regenerate-generation-button"]'),
@@ -618,15 +677,15 @@ export function useShortcutActions(): ShortcutAction[] {
* button's semantics. A waiting steer bubble beats a queued follow-up (it
* is closer to the run); newest-last matches how both stacks append. */
const handleEscalateSteer = useCallback(() => {
- const active = document.querySelector<HTMLButtonElement>('[data-escalate-steer-active="true"]');
+ const focusedPane = getFocusedChatPane();
+ const scope: ParentNode = focusedPane ?? document;
+ const active = scope.querySelector<HTMLButtonElement>('[data-escalate-steer-active="true"]');
if (clickTarget(active)) {
return true;
}
const pick = (surface: string) => {
- const list = document.querySelectorAll<HTMLButtonElement>(
- `[data-escalate-steer="${surface}"]`,
- );
+ const list = scope.querySelectorAll<HTMLButtonElement>(`[data-escalate-steer="${surface}"]`);
for (let i = list.length - 1; i >= 0; i--) {
if (!isUnavailableElement(list[i])) {
return list[i];
@@ -710,7 +769,28 @@ export function useShortcutActions(): ShortcutAction[] {
]);
const handleUploadFile = useCallback(() => {
+ /* Same resolution as the stop shortcut, and for the same reason: both
+ split panes mount a composer advertising this shortcut, so attach to the
+ one the user is focused in rather than always the first in the document.
+ The document-wide lookups behind it cover focus sitting outside any
+ composer, and `#attach-file` is the single-instance legacy control. */
+ const focusedPane = getFocusedChatPane();
+ const scoped = focusedPane?.querySelector<HTMLElement>(
+ '[data-testid="composer-palette-button"]',
+ );
+ if (scoped != null) {
+ /* During dictation this disclosure becomes Cancel. The upload shortcut
+ must remain a no-op instead of discarding the focused pane's take, and
+ must not fall through to a different pane. */
+ if (scoped.dataset.uploadShortcut !== 'true') {
+ return false;
+ }
+ return clickTarget(scoped);
+ }
const btn =
+ document.querySelector<HTMLElement>(
+ '[data-testid="composer-palette-button"][data-upload-shortcut="true"]',
+ ) ??
document.querySelector<HTMLButtonElement>('#attach-file-menu-button') ??
document.querySelector<HTMLButtonElement>('#attach-file-button') ??
document.querySelector<HTMLButtonElement>('#attach-file');
@@ -825,7 +905,12 @@ export function useShortcutActions(): ShortcutAction[] {
const handleOpenPrompts = useCallback(() => handleOpenPanel('prompts'), [handleOpenPanel]);
const handleOpenMemories = useCallback(() => handleOpenPanel('memories'), [handleOpenPanel]);
const handleOpenParameters = useCallback(() => handleOpenPanel('parameters'), [handleOpenPanel]);
- const handleOpenFiles = useCallback(() => handleOpenPanel('files'), [handleOpenPanel]);
+ /* The file manager moved out of the side panel and into a dialog, so there is
+ no `nav-panel-files` button left for `handleOpenPanel` to find. */
+ const handleOpenFiles = useCallback(() => {
+ setShowFilesDialog(true);
+ return true;
+ }, [setShowFilesDialog]);
const handleOpenBookmarks = useCallback(() => handleOpenPanel('bookmarks'), [handleOpenPanel]);
const handleOpenMCP = useCallback(() => handleOpenPanel('mcp-builder'), [handleOpenPanel]);
@@ -1069,11 +1154,12 @@ export default function useKeyboardShortcuts() {
const target = e.target as HTMLElement | null;
+ const isStopGenerating = matchedId === 'stopGenerating';
if (shortcutsDialogOpen) {
- if (matchedId !== 'showShortcuts') {
+ if (matchedId !== 'showShortcuts' && !isStopGenerating) {
return;
}
- } else if (anyModalOpen() || isWithinOpenMenu(target)) {
+ } else if (!isStopGenerating && (anyModalOpen() || isWithinOpenMenu(target))) {
return;
}
@@ -1082,8 +1168,6 @@ export default function useKeyboardShortcuts() {
tagName === 'INPUT' || tagName === 'TEXTAREA' || target?.isContentEditable === true;
const isMainTextarea = target?.id === mainTextareaId;
- // The composer owns every Enter-based submit chord (native and custom), so defer all
- // Enter presses there; other editing contexts handle their own submit too.
if (
matchedId === 'submitMessage' &&
((isMainTextarea && e.key === 'Enter') || (isEditing && !isMainTextarea))
@@ -1091,7 +1175,7 @@ export default function useKeyboardShortcuts() {
return;
}
- if (isEditing && !EDITING_ALLOWED_SHORTCUTS.has(matchedId)) {
+ if (!isStopGenerating && isEditing && !EDITING_ALLOWED_SHORTCUTS.has(matchedId)) {
return;
}
diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json
index 05e6215641..0719b67c85 100644
--- a/client/src/locales/en/translation.json
+++ b/client/src/locales/en/translation.json
@@ -598,7 +598,6 @@
"com_files_result_found": "{{count}} result found",
"com_files_results_found": "{{count}} results found",
"com_files_sharepoint_picker_title": "Pick Files",
- "com_files_table": "Files Table",
"com_files_upload_local_machine": "From Local Computer",
"com_files_upload_sharepoint": "From SharePoint",
"com_generated_files": "Generated files:",
@@ -671,6 +670,7 @@
"com_nav_clock_format_system": "System",
"com_nav_collapse_user_messages": "Collapse long user messages",
"com_nav_close_sidebar": "Close sidebar",
+ "com_nav_composer_tips": "Show composer tips",
"com_nav_confirm_archive_all": "Confirm Archive",
"com_nav_confirm_clear": "Confirm Clear",
"com_nav_control_panel": "Control Panel",
@@ -1049,7 +1049,6 @@
"com_ui_all_projects": "All projects",
"com_ui_all_proper": "All",
"com_ui_all_turns": "All turns",
- "com_ui_always_interrupt": "Steer sooner by default",
"com_ui_analyzing": "Analyzing",
"com_ui_analyzing_finished": "Finished analyzing",
"com_ui_any": "Any",
@@ -1112,7 +1111,6 @@
"com_ui_artifacts_mode_default_info": "Standard artifact instructions: the agent renders React, HTML, SVG, Markdown, and Mermaid inline.",
"com_ui_artifacts_mode_shadcn": "shadcn/ui",
"com_ui_artifacts_mode_shadcn_info": "Adds shadcn/ui component-library instructions so the agent can build polished interfaces from prebuilt components.",
- "com_ui_artifacts_options": "Artifacts Options",
"com_ui_artifacts_subtext": "Lets the agent render React, HTML, SVG, Markdown, and Mermaid as interactive artifacts in a side panel instead of plain code blocks.",
"com_ui_ascending": "Asc",
"com_ui_ask_answer_error": "Your answer couldn't be sent. Try again.",
@@ -1135,8 +1133,9 @@
"com_ui_at_least_one_owner_required": "At least one owner is required",
"com_ui_attach_error": "Cannot attach file. Create or select a conversation, or try refreshing the page.",
"com_ui_attach_error_disabled": "File uploads are disabled for this endpoint",
+ "com_ui_attach_error_file_limit": "File limit reached: {{count}} files ({{0}})",
+ "com_ui_attach_error_file_limit_one": "File limit reached: {{count}} file ({{0}})",
"com_ui_attach_error_pending": "Still loading upload settings. Try attaching the file again in a moment.",
- "com_ui_attach_error_limit": "File limit reached:",
"com_ui_attach_error_openai": "Cannot attach Assistant files to other endpoints",
"com_ui_attach_error_size": "File size limit exceeded for endpoint:",
"com_ui_attach_error_total_size": "Total file size limit exceeded for endpoint:",
@@ -1146,6 +1145,8 @@
"com_ui_attach_warn_endpoint": "Non-Assistant files may be ignored without a compatible tool",
"com_ui_attached_image": "Attached image",
"com_ui_attachment": "Attachment",
+ "com_ui_attachment_count": "{{count}} attachments",
+ "com_ui_attachment_count_one": "{{count}} attachment",
"com_ui_auth_apikey_desc": "Send a key or token with each request",
"com_ui_auth_format_hint": "This usually starts with \"{{0}}\"",
"com_ui_auth_invalid_url": "Enter a valid URL, including http:// or https://",
@@ -1157,6 +1158,7 @@
"com_ui_authentication": "Authentication",
"com_ui_authentication_type": "Authentication Type",
"com_ui_auto": "Auto",
+ "com_ui_reasoning_for_next_message": "Reasoning for next message",
"com_ui_available_options": "Available options",
"com_ui_avatar": "Avatar",
"com_ui_avatar_drop_image": "Drop an image here to use as your profile picture",
@@ -1248,6 +1250,39 @@
"com_ui_command_usage_placeholder": "Select a Prompt by command or name",
"com_ui_complete": "Complete!",
"com_ui_complete_setup": "Complete Setup",
+ "com_ui_composer_attach": "Attach",
+ "com_ui_composer_attach_less": "Fewer upload options",
+ "com_ui_composer_attach_more": "More upload options",
+ "com_ui_composer_effort_faster": "Faster",
+ "com_ui_composer_effort_smarter": "Smarter",
+ "com_ui_composer_files": "Your files",
+ "com_ui_composer_hint_answer": "Answering. Esc to dismiss",
+ "com_ui_composer_hint_attach": "+ to attach",
+ "com_ui_composer_hint_interrupt": "interrupt & send",
+ "com_ui_composer_hint_mentions": "@ for models",
+ "com_ui_composer_hint_newline": "for newline",
+ "com_ui_composer_hint_prompts": "/ for prompts",
+ "com_ui_composer_hint_queue": "queue",
+ "com_ui_composer_hint_queue_default": "Enter queues",
+ "com_ui_composer_hint_queue_verb": "queues",
+ "com_ui_composer_hint_running": "Generating a reply…",
+ "com_ui_composer_hint_send": "to send",
+ "com_ui_composer_hint_send_now": "send now",
+ "com_ui_composer_hint_steer": "Enter steers",
+ "com_ui_composer_hint_steer_verb": "steers",
+ "com_ui_composer_hint_stop": "to stop",
+ "com_ui_composer_hint_typing": "Enter to send · Shift+Enter for newline",
+ "com_ui_composer_hint_uploading": "Uploading {{count}} files…",
+ "com_ui_composer_hint_uploading_one": "Uploading {{count}} file…",
+ "com_ui_composer_mcp": "MCP Servers",
+ "com_ui_composer_no_results": "No matches",
+ "com_ui_composer_palette": "Attach and tools",
+ "com_ui_composer_palette_help": "Use the arrow keys to browse, Enter to select, and {{0}}+D to favorite.",
+ "com_ui_composer_palette_search": "Search tools, skills and servers",
+ "com_ui_composer_staged_context": "Staged context",
+ "com_ui_composer_thinking": "Thinking",
+ "com_ui_composer_thinking_value": "Thinking: {{0}}",
+ "com_ui_composer_tools": "Tools",
"com_ui_concise": "Concise",
"com_ui_configure": "Configure",
"com_ui_configure_mcp_variables_for": "Configure Variables for {{0}}",
@@ -1355,7 +1390,7 @@
"com_ui_currently_production": "Currently in production",
"com_ui_custom": "Custom",
"com_ui_custom_header_name": "Custom Header Name",
- "com_ui_custom_prompt_mode": "Custom Prompt Mode",
+ "com_ui_custom_prompt": "Custom prompt",
"com_ui_dark_theme_enabled": "Dark theme enabled",
"com_ui_data_table": "Data table",
"com_ui_data_table_scroll_area": "Scrollable data table area",
@@ -1674,7 +1709,6 @@
"com_ui_import_conversation_success": "Conversations imported successfully",
"com_ui_import_conversation_upload_error": "Error uploading file. Please try again.",
"com_ui_importing": "Importing",
- "com_ui_include_shadcnui": "Include shadcn/ui components instructions",
"com_ui_input": "Input",
"com_ui_instructions": "Instructions",
"com_ui_interrupt_send": "Interrupt & send",
@@ -1733,6 +1767,7 @@
"com_ui_lines_count": "{0} lines",
"com_ui_link_copied": "Link copied",
"com_ui_link_refreshed": "Link updated",
+ "com_ui_listening": "Listening",
"com_ui_live": "live",
"com_ui_load_more": "Load more",
"com_ui_loading": "Loading...",
@@ -1883,6 +1918,8 @@
"com_ui_min_tags": "Cannot remove more values, a minimum of {{0}} are required.",
"com_ui_minimal": "Minimal",
"com_ui_misc": "Misc.",
+ "com_ui_mode": "Mode",
+ "com_ui_mode_value": "Mode: {{0}}",
"com_ui_model": "Model",
"com_ui_model_parameters": "Model Parameters",
"com_ui_model_parameters_reset": "Model Parameters have been reset.",
@@ -2109,6 +2146,13 @@
"com_ui_asking_questions": "Asking {{0}} questions",
"com_ui_question_unanswered": "No answer was given",
"com_ui_queue": "Queue",
+ "com_ui_convert_to_queue": "Queue for after the response",
+ "com_ui_queue_edit_blocked": "Clear the message box in this chat, or finish answering the question, to edit this message.",
+ "com_ui_queue_moved": "Moved to {{0}} of {{1}}",
+ "com_ui_queue_reorder_blocked": "Queued turns already acknowledged by the server cannot be reordered.",
+ "com_ui_queue_remove_blocked": "Clear the message box in this chat to take this message back.",
+ "com_ui_queue_reorder": "Reorder message, {{0}} of {{1}}",
+ "com_ui_queue_reorder_hint": "Use the up and down arrow keys to move this message in the queue.",
"com_ui_queue_send": "Queue message for after the response",
"com_ui_queued_attachment_count": "{{0}} attachments queued with this message",
"com_ui_queued_messages": "Queued messages",
@@ -2116,8 +2160,6 @@
"com_ui_queued_turn_failed": "Queued message failed",
"com_ui_queued_turn_reconciliation_required": "Awaiting reconciliation",
"com_ui_queued_turn_starting": "Starting as the next turn",
- "com_ui_quote_selections": "{{0}} selections",
- "com_ui_quotes_queued": "Quotes added for your next message",
"com_ui_ran_n_actions": "Ran {{0}} actions",
"com_ui_ran_n_agents": "Ran {{0}} agents",
"com_ui_read_aloud": "Read aloud",
@@ -2154,13 +2196,13 @@
"com_ui_remote_agents_allow_share_public": "Allow users to grant API access to agents to all users",
"com_ui_remote_agents_allow_use": "Allow users to create API keys and query agents remotely",
"com_ui_remove_agent_from_chain": "Remove {{0}} from chain",
- "com_ui_remove_all_quotes": "Remove all selections",
"com_ui_remove_from_project": "Remove from project",
"com_ui_remove_queued": "Remove message",
"com_ui_dismiss_unconfirmed_delivery": "Dismiss unconfirmed delivery",
"com_ui_remove_quote": "Remove quote",
- "com_ui_remove_skill_var": "Remove {{0}}",
+ "com_ui_remove_skill": "Remove skill",
"com_ui_remove_user": "Remove {{0}}",
+ "com_ui_remove_var": "Remove {{0}}",
"com_ui_rename": "Rename",
"com_ui_rename_conversation": "Rename Conversation",
"com_ui_rename_failed": "Failed to rename conversation",
@@ -2214,7 +2256,6 @@
"com_ui_running_n_agents": "Running {{0}} agents",
"com_ui_sandbox_starting": "Starting sandbox environment",
"com_ui_save": "Save",
- "com_ui_save_badge_changes": "Save badge changes?",
"com_ui_save_before_rerun": "Rerunning applies one edited section at a time. Save to keep all of these changes.",
"com_ui_save_key_error": "Failed to save API key. Please try again.",
"com_ui_save_key_success": "API key saved successfully",
@@ -2324,7 +2365,10 @@
"com_ui_select_search_region": "Search region by name",
"com_ui_select_var": "Select {{0}}",
"com_ui_selected_count": "{{count}} selected",
+ "com_ui_send_as_new": "Send as new message",
"com_ui_send_now": "Send now",
+ "com_ui_send_now_paused": "Available after you respond to the pending request",
+ "com_ui_sending": "Sending...",
"com_ui_set": "Set",
"com_ui_settings_label_2fa": "Two-factor authentication",
"com_ui_settings_label_agent_api_keys": "Agent API keys",
@@ -2394,6 +2438,7 @@
"com_ui_settings_section_tts": "Text to speech",
"com_ui_settings_tab_data": "Data & Privacy",
"com_ui_settings_tab_langfuse": "Langfuse",
+ "com_ui_shadcnui": "shadcn/ui",
"com_ui_share": "Share",
"com_ui_share_access_description": "Choose who can access this resource and what they can do.",
"com_ui_share_create_message": "Your name and any messages you add after sharing stay private.",
@@ -2537,7 +2582,6 @@
"com_ui_skills_mode_all": "All",
"com_ui_skills_mode_off": "Off",
"com_ui_skills_mode_selected": "Selected",
- "com_ui_skills_queued": "Skills queued for next submission",
"com_ui_skills_remove": "Remove {{name}}",
"com_ui_skip": "Skip",
"com_ui_something_else": "Something else...",
@@ -2566,6 +2610,7 @@
"com_ui_speech_not_supported": "Your browser does not support speech recognition",
"com_ui_speech_not_supported_use_external": "Your browser does not support speech recognition. Try switching to External STT in Settings > Speech.",
"com_ui_speech_while_submitting": "Can't submit speech while a response is being generated",
+ "com_ui_speech_while_uploading": "Can't submit speech while files are still uploading",
"com_ui_sr_global_prompt": "Global prompt group",
"com_ui_sr_public_skill": "Public skill",
"com_ui_stack_trace": "Stack Trace",
@@ -2627,20 +2672,18 @@
"com_ui_steer_delivered": "Delivered",
"com_ui_steer_delivered_info": "Delivered. Your message can join this response at the next tool step or, when possible, before it finishes.",
"com_ui_steer_delivery_unconfirmed": "Delivery unconfirmed",
- "com_ui_steer_edit_queued": "Your composer already has a draft, so that steering message was queued for after the response instead",
+ "com_ui_steer_delivery_uncertain": "Delivery status is unknown; this steering message may still reach the agent",
"com_ui_steer_failed": "Steering failed",
- "com_ui_steer_first_turn_stop": "Stop & send (first response)",
- "com_ui_steer_first_turn_stop_info": "Steering isn't available yet. Stops this response and sends your message as a new turn.",
+ "com_ui_steer_failed_inline": "Couldn't add to this reply",
"com_ui_steer_in_flight": "Steering",
- "com_ui_steer_in_flight_preempt": "Steer sooner requested",
- "com_ui_steer_interrupting_info": "Earlier steering requested. The agent may pause a text reply at a safe point or restart an attempt that has produced only reasoning. Running tools finish first. If it cannot pause, your message waits for the next tool step or an end-of-response opportunity.",
- "com_ui_steer_interrupts_default": "Steer sooner on Enter",
- "com_ui_steer_interrupts_default_info": "When steering is the default, Enter requests an earlier safe point instead of waiting for the next tool step. Running tools finish first; a thinking-only attempt may restart. Text already shown is kept.",
- "com_ui_steer_interrupts_enable_info": "Makes steering the Enter default and requests an earlier safe point. Running tools finish first; a thinking-only attempt may restart. Text already shown is kept.",
+ "com_ui_steer_in_flight_preempt": "Interrupting",
+ "com_ui_steer_interrupting_info": "Interrupt requested. The response will stop at the next safe point, then your message takes over. Reasoning and tool calls are not interrupted. To interrupt them, stop the response instead.",
+ "com_ui_steer_interrupts_default": "Steering interrupts generation",
+ "com_ui_steer_interrupts_default_info": "When on, Enter stops the response at the next safe point instead of waiting for the agent's next tool step. Either way the partial answer is kept and the response continues.",
+ "com_ui_steer_moved_to_queue": "Moved to the queue: it sends when this response finishes",
"com_ui_steer_paused_queued": "The agent is waiting for your review — your message was queued instead",
"com_ui_steer_preempt_unsupported": "This deployment can't steer mid-response. Your message waits for the next tool step or an end-of-response opportunity",
"com_ui_steer_queued_info": "Sends when this response finishes",
- "com_ui_steer_retry": "Retry steering",
"com_ui_steer_send": "Steer the current response",
"com_ui_steer_sending": "Sending…",
"com_ui_stop": "Stop",
@@ -2938,12 +2981,11 @@
"com_ui_trace_view": "View trace",
"com_ui_trace_view_conversation": "View as conversation",
"com_ui_trace_view_raw": "View raw",
+ "com_ui_transcribing": "Transcribing...",
"com_ui_transferred_to": "Transferred to",
"com_ui_travel": "Travel",
"com_ui_trust_app": "I trust this application",
"com_ui_try_adjusting_search": "Try adjusting your search terms",
- "com_ui_turn_on_queueing": "Turn on queueing",
- "com_ui_turn_on_steering": "Turn on steering",
"com_ui_ui_resource_error": "UI Resource Error ({{0}})",
"com_ui_ui_resource_not_found": "UI Resource not found (index: {{0}})",
"com_ui_unarchive": "Unarchive",
@@ -3015,7 +3057,6 @@
"com_ui_wakeup_task_finished": "Background task finished",
"com_ui_wakeup_tasks_finished": "{{0}} background tasks finished",
"com_ui_wakeup_view_activity": "View activity",
- "com_ui_wait_for_tool_steps": "Wait for the next step instead",
"com_ui_web_search": "Web Search",
"com_ui_web_search_cohere_key": "Enter Cohere API Key",
"com_ui_web_search_firecrawl_url": "Firecrawl API URL (optional)",
@@ -3061,7 +3102,6 @@
"com_ui_workspace_changes": "Workspace changes",
"com_ui_write": "Writing",
"com_ui_writing_command": "Writing command",
- "com_ui_x_selected": "{{0}} selected",
"com_ui_xhigh": "Extra High",
"com_ui_yes": "Yes",
"com_ui_you": "You",
diff --git a/client/src/store/composerTips.ts b/client/src/store/composerTips.ts
new file mode 100644
index 0000000000..a2f9f3a8a6
--- /dev/null
+++ b/client/src/store/composerTips.ts
@@ -0,0 +1,4 @@
+import { createStorageAtom } from './jotai-utils';
+
+/** Whether the composer displays its keyboard shortcut discovery hints. */
+export const showComposerTipsAtom = createStorageAtom<boolean>('showComposerTips', false);
diff --git a/client/src/store/families.ts b/client/src/store/families.ts
index b66a555291..ebf4745a9e 100644
--- a/client/src/store/families.ts
+++ b/client/src/store/families.ts
@@ -376,6 +376,8 @@ export type PendingSteer = {
/** Manual skill picks, carried for restoration only (a skill pick
* configures a NEW turn's run, so it never rides the steer POST). */
manualSkills?: string[];
+ /** Full-generation setting carried for restoration only; it cannot alter a live steer. */
+ reasoningOverride?: TMessage['reasoningOverride'];
/** Asked the run to seal generation at the next safe boundary rather than
* wait for a tool step. Labelling only — the server owns the behaviour and
* echoes what it actually armed. */
@@ -430,6 +432,11 @@ export type QueuedMessage = {
position?: number;
revision?: number;
};
+ /** A row the run-end drain must not submit on its own. Set when a steer the
+ * server REJECTED is swept into the queue so its words stay recoverable:
+ * the failure surface offers Retry and "Send as new", and auto-sending here
+ * would start a turn the user never asked for with text that was refused. */
+ needsExplicitSend?: boolean;
/** Stable identity for server enqueue/retry. Recovered steer rows also use
* it to dismiss their parked source; a later recovery attempt gets a fresh
* identity. */
@@ -449,6 +456,8 @@ export type QueuedMessage = {
/** Manual skill picks consumed from the composer at enqueue time; passed
* to `ask` as `overrideManualSkills` on drain. */
manualSkills?: string[];
+ /** Request-scoped reasoning setting captured when this item was queued. */
+ reasoningOverride?: TMessage['reasoningOverride'];
/** Front-inserted by "Interrupt & send": stays ahead of chronologically
* older items when leftover steers are merged back into the queue. */
priority?: boolean;
diff --git a/client/src/store/filesDialog.ts b/client/src/store/filesDialog.ts
new file mode 100644
index 0000000000..029cc5d6d9
--- /dev/null
+++ b/client/src/store/filesDialog.ts
@@ -0,0 +1,16 @@
+import { atom } from 'jotai';
+import type { RefObject } from 'react';
+
+/** Whether the shell-level file manager dialog is open. */
+export const showFilesDialogAtom = atom(false);
+
+/**
+ * The control that opened the file manager, for focus restoration on close.
+ *
+ * `MyFilesModal` rejects an active element inside a menu, because the menu is
+ * already unmounting by the time the dialog captures focus; an opener that
+ * lives in a menu has to publish itself here instead, or the dialog closes
+ * onto the document body. The shortcut path leaves this null on purpose: its
+ * active element is the composer, which restores on its own.
+ */
+export const filesDialogTriggerAtom = atom<RefObject<HTMLElement | null> | null>(null);
diff --git a/client/src/store/index.ts b/client/src/store/index.ts
index 75d4a0379c..f8d12e561f 100644
--- a/client/src/store/index.ts
+++ b/client/src/store/index.ts
@@ -18,7 +18,6 @@ export * from './favorites';
export * from './sandbox';
export * from './ptc';
export * from './usage';
-export * from './steer';
export default {
...artifacts,
diff --git a/client/src/store/settings.ts b/client/src/store/settings.ts
index 90f293b2f5..d693eaeb5c 100644
--- a/client/src/store/settings.ts
+++ b/client/src/store/settings.ts
@@ -62,7 +62,7 @@ const localStorageAtoms = {
// Chat settings
enterToSend: atomWithLocalStorage('enterToSend', true),
- /** What Enter does while a run is generating: steer (inject mid-run) or queue (send after). */
+ /** The action Enter uses while a reply is generating. */
duringRunDefaultAction: atomWithLocalStorage<'steer' | 'queue'>(
'duringRunDefaultAction',
'steer',
diff --git a/client/src/store/steer.ts b/client/src/store/steer.ts
index 87a1298949..b8c23633fe 100644
--- a/client/src/store/steer.ts
+++ b/client/src/store/steer.ts
@@ -2,17 +2,6 @@ import { atom } from 'jotai';
import { atomFamily } from 'jotai/utils';
import type { TMessage } from 'librechat-data-provider';
-/**
- * Measured pixel height of the in-flight steer overlay for a conversation.
- * The overlay floats above the composer over the bottom of the message scroll
- * area; the messages reserve an equal band of bottom padding (see
- * `MessagesView`) so the newest message clears it at rest and older messages
- * scroll behind it. `InFlightSteers` publishes its height here and resets it to
- * 0 on unmount, so the entry is never stale — the atomFamily is not GC'd, but
- * each holds a single number per visited conversation.
- */
-export const steerOverlayHeightFamily = atomFamily((_conversationId: string) => atom<number>(0));
-
/**
* Set synchronously before a bubble's arm request and cleared on settlement.
* Purely a UX gate: with the atomic in-place arm, a double-arm is harmless
@@ -44,3 +33,8 @@ export type RevealedQueuedTurn = {
export const revealedQueuedTurnFamily = atomFamily((_conversationId: string) =>
atom<RevealedQueuedTurn | null>(null),
);
+
+/** Client ids cancelled before the steer POST receives its authoritative id. */
+export const pendingSteerCancelClientIdsFamily = atomFamily((_conversationId: string) =>
+ atom<string[]>([]),
+);
diff --git a/client/src/style.css b/client/src/style.css
index e939a7ee24..8b1cc40e31 100644
--- a/client/src/style.css
+++ b/client/src/style.css
@@ -138,7 +138,7 @@
--markdown-font-size: 1rem;
}
-/* transitions-dev tokens — semantic names shared by every t-* class below. */
+/* transitions-dev tokens: semantic names shared by every t-* class below. */
:root {
--resize-dur: 300ms;
--resize-ease: cubic-bezier(0.22, 1, 0.36, 1);
@@ -154,7 +154,7 @@
--avatar-ease-out: cubic-bezier(0.34, 3.85, 0.64, 1);
}
-/* Icon swap — cross-fade two icons sharing a slot. */
+/* Icon swap: cross-fade two icons sharing a slot. */
.t-icon-swap {
position: relative;
display: inline-grid;
@@ -186,7 +186,7 @@
}
}
-/* Avatar group hover — distance-falloff lift on a horizontal row. */
+/* Avatar group hover: distance-falloff lift on a horizontal row. */
.t-avatar {
transform-origin: center;
transform: translateY(var(--shift, 0px)) scale(var(--scale-active, 1));
@@ -2606,6 +2606,124 @@ html[data-input-modality='keyboard']
transform: scale(1) translate(0, 0);
}
+/**
+ * Composer popovers. Its own curve rather than `animate-popover`'s: these are
+ * large surfaces, and the shared 150ms ease-in-out reads as a snap at that size.
+ * Decelerating hard from the first frame and then settling is what makes a panel
+ * feel placed rather than switched on. Leaving is quicker than entering, so
+ * dismissing never feels like waiting.
+ */
+.animate-composer-popover {
+ /* Ariakit resolves this to the edge nearest the trigger, so the panel grows
+ out of the button whether it opens below or flips above. `animate-popover`
+ pins the origin to the top and translates down, which is right one way
+ round and backwards the other. */
+ transform-origin: var(--popover-transform-origin, top center);
+ opacity: 0;
+ transform: scale(0.94);
+ transition:
+ opacity 190ms cubic-bezier(0.32, 0.72, 0, 1),
+ transform 260ms cubic-bezier(0.32, 0.72, 0, 1);
+ will-change: transform, opacity;
+}
+.animate-composer-popover[data-enter] {
+ opacity: 1;
+ transform: scale(1);
+}
+.animate-composer-popover[data-leave] {
+ transition-duration: 120ms, 140ms;
+}
+
+/* The Thinking pill's label slot resizes with the popover it opens: same
+ duration and curve as the opacity leg above. */
+.composer-slot-resize {
+ transition: width 190ms cubic-bezier(0.32, 0.72, 0, 1);
+}
+
+/**
+ * Palette list. `.scrollbar-hover` fades its thumb in on pointer-over, so on a
+ * list this dense the scrollbar reads as appearing out of nowhere, and where
+ * the platform draws classic rather than overlay scrollbars, a gutter that only
+ * exists while the thumb does shifts every row sideways under the cursor. The
+ * thumb stays drawn and the gutter stays reserved; the class is only applied
+ * when the list actually overflows, so a short list keeps its full width.
+ *
+ * Standard properties only, deliberately: styling `::-webkit-scrollbar` opts an
+ * element out of overlay scrollbars altogether, which would spend 8px of gutter
+ * on the platforms that never had the problem.
+ */
+.composer-palette-scroll {
+ scrollbar-width: thin;
+ scrollbar-color: rgb(var(--border-medium) / var(--border-medium-alpha, 1)) transparent;
+ scrollbar-gutter: stable;
+}
+/** Trigger glyphs that turn as their popover opens, on the same curve. */
+.animate-composer-icon {
+ transition: transform 260ms cubic-bezier(0.32, 0.72, 0, 1);
+}
+
+/**
+ * The palette growing or shrinking as its list rearranges. The rows themselves
+ * are moved from `Palette.tsx`, which plays each one back to where it was after
+ * the list has been redrawn; a re-inserted node drops any transition it was
+ * about to run, and starring an entry re-inserts every row it passed. The
+ * panel's own height has no such problem: the list box is never re-inserted.
+ */
+.composer-palette-rows .ReactVirtualized__Grid {
+ transition: height 260ms cubic-bezier(0.32, 0.72, 0, 1);
+}
+/* Held for the frame a search redraws in: the list is being replaced rather
+ than rearranged there, and growing into its new size reads as the panel
+ lagging behind the typing. */
+.composer-palette-instant .ReactVirtualized__Grid {
+ transition-duration: 0s;
+}
+@keyframes composer-palette-row {
+ from {
+ opacity: 0;
+ }
+ to {
+ opacity: 1;
+ }
+}
+.animate-composer-palette-row {
+ animation: composer-palette-row 200ms cubic-bezier(0.32, 0.72, 0, 1) both;
+}
+@keyframes composer-palette-row-out {
+ from {
+ opacity: 1;
+ }
+ to {
+ opacity: 0;
+ }
+}
+/* Accelerating away, unlike everything else here: the shared decelerating curve
+ spends this beat almost entirely at zero, leaving the rows gone well before
+ the list starts closing over them. */
+.animate-composer-palette-row-out {
+ animation: composer-palette-row-out 110ms cubic-bezier(0.4, 0, 1, 1) both;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .animate-composer-popover,
+ .animate-composer-popover[data-enter],
+ .animate-composer-popover[data-leave],
+ .animate-composer-icon,
+ .composer-slot-resize,
+ .composer-palette-rows .ReactVirtualized__Grid {
+ transition-duration: 1ms;
+ }
+ .animate-composer-palette-row,
+ .animate-composer-palette-row-out {
+ animation-duration: 1ms;
+ }
+ .animate-composer-popover,
+ .animate-composer-popover[data-enter],
+ .animate-composer-popover[data-leave] {
+ transform: none;
+ }
+}
+
/** Note: ensure KaTeX can spread across visible space */
.message-content pre:has(> span.katex) {
overflow: visible !important;
diff --git a/client/src/utils/__tests__/getViableUploadOptions.spec.ts b/client/src/utils/__tests__/getViableUploadOptions.spec.ts
index 6d2ea63580..d3525c215b 100644
--- a/client/src/utils/__tests__/getViableUploadOptions.spec.ts
+++ b/client/src/utils/__tests__/getViableUploadOptions.spec.ts
@@ -1,6 +1,10 @@
-import { EToolResources } from 'librechat-data-provider';
+import { Tools, EToolResources } from 'librechat-data-provider';
import type { FileConfig } from 'librechat-data-provider';
-import { getViableUploadOptions, type UploadOptionContext } from '../files';
+import {
+ getViableUploadOptions,
+ getUploadToolAllowances,
+ type UploadOptionContext,
+} from '../files';
const XLSX = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
const POTX = 'application/vnd.openxmlformats-officedocument.presentationml.template';
@@ -180,3 +184,72 @@ describe('getViableUploadOptions', () => {
]);
});
});
+
+describe('getUploadToolAllowances', () => {
+ const SAVED = 'agent_abc123';
+
+ it('offers both tool destinations in an ordinary chat, where no agent decides', () => {
+ expect(getUploadToolAllowances(null, undefined)).toEqual({
+ fileSearchAllowedByAgent: true,
+ codeAllowedByAgent: true,
+ });
+ expect(getUploadToolAllowances(undefined, undefined)).toEqual({
+ fileSearchAllowedByAgent: true,
+ codeAllowedByAgent: true,
+ });
+ expect(getUploadToolAllowances('', undefined)).toEqual({
+ fileSearchAllowedByAgent: true,
+ codeAllowedByAgent: true,
+ });
+ });
+
+ /* The regression this rule was extracted for: an ephemeral agent carries no
+ tool list, and reading one left both destinations hidden for good. */
+ it('offers both to an ephemeral agent, which has no tool list to consult', () => {
+ expect(getUploadToolAllowances('openAI__gpt-5___GPT-5', undefined)).toEqual({
+ fileSearchAllowedByAgent: true,
+ codeAllowedByAgent: true,
+ });
+ expect(getUploadToolAllowances('openAI__gpt-5___GPT-5', [])).toEqual({
+ fileSearchAllowedByAgent: true,
+ codeAllowedByAgent: true,
+ });
+ });
+
+ it('lets a saved agent offer only what it was built with', () => {
+ expect(getUploadToolAllowances(SAVED, [Tools.file_search])).toEqual({
+ fileSearchAllowedByAgent: true,
+ codeAllowedByAgent: false,
+ });
+ expect(getUploadToolAllowances(SAVED, [Tools.execute_code])).toEqual({
+ fileSearchAllowedByAgent: false,
+ codeAllowedByAgent: true,
+ });
+ expect(getUploadToolAllowances(SAVED, [Tools.file_search, Tools.execute_code])).toEqual({
+ fileSearchAllowedByAgent: true,
+ codeAllowedByAgent: true,
+ });
+ });
+
+ it('offers a saved agent nothing when its tools are absent or empty', () => {
+ expect(getUploadToolAllowances(SAVED, undefined)).toEqual({
+ fileSearchAllowedByAgent: false,
+ codeAllowedByAgent: false,
+ });
+ expect(getUploadToolAllowances(SAVED, [])).toEqual({
+ fileSearchAllowedByAgent: false,
+ codeAllowedByAgent: false,
+ });
+ expect(getUploadToolAllowances(SAVED, ['some_other_tool'])).toEqual({
+ fileSearchAllowedByAgent: false,
+ codeAllowedByAgent: false,
+ });
+ });
+
+ it('reads through an indexed agent id, which carries the suffix from a split view', () => {
+ expect(getUploadToolAllowances(`${SAVED}____1`, [Tools.execute_code])).toEqual({
+ fileSearchAllowedByAgent: false,
+ codeAllowedByAgent: true,
+ });
+ });
+});
diff --git a/client/src/utils/__tests__/queueIntent.spec.ts b/client/src/utils/__tests__/queueIntent.spec.ts
new file mode 100644
index 0000000000..b854015c08
--- /dev/null
+++ b/client/src/utils/__tests__/queueIntent.spec.ts
@@ -0,0 +1,39 @@
+import { DEFAULT_QUEUED_SEND_LOCK_TIMEOUT_MS } from 'librechat-data-provider';
+import { acquireQueueSendLock, releaseQueueSendLock } from '../queueIntent';
+
+describe('acquireQueueSendLock', () => {
+ let now = 1_000_000;
+
+ beforeEach(() => {
+ jest.spyOn(Date, 'now').mockImplementation(() => now);
+ });
+
+ afterEach(() => {
+ jest.restoreAllMocks();
+ });
+
+ it('refuses a second claim on a pane while the first is held', () => {
+ const lock = acquireQueueSendLock('pane-held');
+ expect(lock).not.toBeNull();
+ expect(acquireQueueSendLock('pane-held')).toBeNull();
+ releaseQueueSendLock(lock);
+ expect(acquireQueueSendLock('pane-held')).not.toBeNull();
+ });
+
+ it('treats a claim older than the default expiry as broken', () => {
+ acquireQueueSendLock('pane-default');
+ now += DEFAULT_QUEUED_SEND_LOCK_TIMEOUT_MS - 1;
+ expect(acquireQueueSendLock('pane-default')).toBeNull();
+ now += 1;
+ expect(acquireQueueSendLock('pane-default')).not.toBeNull();
+ });
+
+ /* `interface.queuedSendLockTimeoutMs` reaches here as the second argument. */
+ it('honours an operator-configured expiry', () => {
+ acquireQueueSendLock('pane-configured', 5_000);
+ now += 4_999;
+ expect(acquireQueueSendLock('pane-configured', 5_000)).toBeNull();
+ now += 1;
+ expect(acquireQueueSendLock('pane-configured', 5_000)).not.toBeNull();
+ });
+});
diff --git a/client/src/utils/__tests__/steer.spec.ts b/client/src/utils/__tests__/steer.spec.ts
index 2dba4a24a2..285aa26eee 100644
--- a/client/src/utils/__tests__/steer.spec.ts
+++ b/client/src/utils/__tests__/steer.spec.ts
@@ -1,4 +1,4 @@
-import { Constants, ContentTypes } from 'librechat-data-provider';
+import { Constants, ContentTypes, ReasoningEffort } from 'librechat-data-provider';
import type { TMessage, TSteerAppliedEvent } from 'librechat-data-provider';
import {
getSteerPart,
@@ -6,10 +6,12 @@ import {
resolveRunEndTarget,
findSteerMessageIndex,
appendAppliedSteerIds,
+ isLegacyDeliveryUncertain,
resolveAbortSteerTarget,
insertQueuedOrigin,
mergeRestagedQuotes,
collectDroppedSteerQuotes,
+ carriedSteerContext,
} from '../steer';
const buildEvent = (overrides: Partial<TSteerAppliedEvent> = {}): TSteerAppliedEvent => ({
@@ -36,6 +38,22 @@ const assistantMessage = (overrides: Partial<TMessage> = {}): TMessage =>
...overrides,
}) as TMessage;
+describe('carriedSteerContext', () => {
+ it('preserves request-scoped reasoning through restore and recovery paths', () => {
+ expect(
+ carriedSteerContext({
+ quotes: ['excerpt'],
+ manualSkills: ['writer'],
+ reasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.high },
+ }),
+ ).toEqual({
+ quotes: ['excerpt'],
+ manualSkills: ['writer'],
+ reasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.high },
+ });
+ });
+});
+
describe('applySteerPart', () => {
it('places the part at its absolute index on a new message object', () => {
const message = assistantMessage();
@@ -211,6 +229,19 @@ describe('appendAppliedSteerIds', () => {
});
});
+describe('isLegacyDeliveryUncertain', () => {
+ it('locks ambiguous v1 and unnegotiated deliveries, but not v2', () => {
+ expect(
+ isLegacyDeliveryUncertain({ deliveryUncertain: true, generationProtocolVersion: 1 }),
+ ).toBe(true);
+ expect(isLegacyDeliveryUncertain({ deliveryUncertain: true })).toBe(true);
+ expect(
+ isLegacyDeliveryUncertain({ deliveryUncertain: true, generationProtocolVersion: 2 }),
+ ).toBe(false);
+ expect(isLegacyDeliveryUncertain({ generationProtocolVersion: 1 })).toBe(false);
+ });
+});
+
describe('insertQueuedOrigin', () => {
const staleOrigin = {
item: {
diff --git a/client/src/utils/agents.tsx b/client/src/utils/agents.tsx
index d983452a89..d15ad1013e 100644
--- a/client/src/utils/agents.tsx
+++ b/client/src/utils/agents.tsx
@@ -1,6 +1,7 @@
import React, { useState } from 'react';
import { Feather } from 'lucide-react';
import { Skeleton } from '@librechat/client';
+import { isEphemeralAgentId, parseEphemeralAgentId } from 'librechat-data-provider';
import type t from 'librechat-data-provider';
/**
@@ -134,3 +135,22 @@ export const getContactDisplayName = (agent: t.Agent | null | undefined): string
};
// All hardcoded category constants removed - now using database-driven categories
+
+/**
+ * The provider and model an agents-endpoint conversation runs on: the saved
+ * agent's, or the target encoded in an ephemeral agent id. A saved agent that
+ * has not loaded yet resolves to nothing, so callers fail closed.
+ */
+export const resolveAgentTarget = (
+ agentId: string | null | undefined,
+ agent: Pick<t.Agent, 'provider' | 'model'> | null | undefined,
+): { provider: string; model: string } | undefined => {
+ if (agent != null) {
+ return { provider: agent.provider ?? '', model: agent.model ?? '' };
+ }
+ if (agentId == null || !isEphemeralAgentId(agentId)) {
+ return undefined;
+ }
+ const parsed = parseEphemeralAgentId(agentId);
+ return parsed == null ? undefined : { provider: parsed.endpoint, model: parsed.model };
+};
diff --git a/client/src/utils/composerFiles.ts b/client/src/utils/composerFiles.ts
new file mode 100644
index 0000000000..87f7867cc8
--- /dev/null
+++ b/client/src/utils/composerFiles.ts
@@ -0,0 +1,53 @@
+/**
+ * Composer attachments a during-run submit has already consumed.
+ *
+ * Taking files into a steer or a queued message clears them from the composer,
+ * but an upload for one of them can still have async callbacks in flight
+ * (`loadImage`'s `onload`, HEIC conversion progress, the resize pass). Those
+ * callbacks write the file back with a `set`, which resurrects an attachment
+ * the message already owns: it reappears in the composer and rides the user's
+ * NEXT message too.
+ *
+ * Held outside React state because the decision is synchronous and crosses two
+ * hooks that never share an instance: `useSteering` consumes, `useUpdateFiles`
+ * writes. Ids are per-upload UUIDs (or a library file's own id), so an upload
+ * the user starts AFTER the submit is never confused with a consumed one.
+ */
+
+/** Bounded so a long session cannot grow the set without limit; far beyond the
+ * handful of callbacks that can still be in flight for one submit. */
+const TAKEN_LIMIT = 200;
+
+const takenFileIds = new Set<string>();
+
+export function markComposerFilesTaken(fileIds: readonly string[]): void {
+ for (const id of fileIds) {
+ if (id.length === 0) {
+ continue;
+ }
+ takenFileIds.delete(id);
+ takenFileIds.add(id);
+ }
+ while (takenFileIds.size > TAKEN_LIMIT) {
+ const oldest = takenFileIds.values().next();
+ if (oldest.done === true) {
+ return;
+ }
+ takenFileIds.delete(oldest.value);
+ }
+}
+
+/** Whether a write for this id is a late callback for an already-consumed
+ * attachment, rather than part of an attachment the composer still holds. */
+export function isComposerFileTaken(id: string): boolean {
+ return takenFileIds.has(id);
+}
+
+/**
+ * Forgets a consumed id, so the SAME file can be attached again on purpose.
+ * Re-attaching a library file reuses its server id, and a permanent mark would
+ * make that attachment silently impossible for the rest of the session.
+ */
+export function releaseComposerFile(id: string): void {
+ takenFileIds.delete(id);
+}
diff --git a/client/src/utils/files.ts b/client/src/utils/files.ts
index 5692905d66..929617d126 100644
--- a/client/src/utils/files.ts
+++ b/client/src/utils/files.ts
@@ -7,6 +7,7 @@ import {
SheetPaths,
} from '@librechat/client';
import {
+ Tools,
megabyte,
Providers,
QueryKeys,
@@ -15,6 +16,7 @@ import {
EToolResources,
EModelEndpoint,
retrievalMimeTypes,
+ isEphemeralAgentId,
isBedrockDocumentType,
isExplicitMimeConfig,
codeInterpreterMimeTypes,
@@ -242,10 +244,32 @@ export function formatDate(dateString: string, isSmallScreen = false) {
return `${day} ${month} ${year}`;
}
+/**
+ * Matches every `[QueryKeys.files, 'recent', limit]` cache entry regardless of
+ * the requested limit, so any writer that patches the plain `[QueryKeys.files]`
+ * list can keep the composer palette's recent-files list in step with it.
+ */
+export const isRecentFilesQueryKey = (queryKey: readonly unknown[]): boolean =>
+ queryKey[0] === QueryKeys.files && queryKey[1] === 'recent';
+
+/**
+ * The recent-files query is server-sorted and mounted with refetching off, so a
+ * new file only reaches it when something invalidates it explicitly.
+ */
+export const invalidateRecentFiles = (queryClient: QueryClient): void => {
+ queryClient.invalidateQueries({
+ predicate: (query) => isRecentFilesQueryKey(query.queryKey),
+ });
+};
+
/**
* Adds a file to the query cache
*/
export function addFileToCache(queryClient: QueryClient, newfile: TFile) {
+ /* Ahead of the early returns below: the full list may not be cached at all
+ while the palette's recent list is, and that list still has to learn about
+ the new file. */
+ invalidateRecentFiles(queryClient);
const currentFiles = queryClient.getQueryData<TFile[]>([QueryKeys.files]);
if (!currentFiles) {
@@ -594,6 +618,34 @@ const isContextType = (type: string, fileConfig: FileConfig | null): boolean =>
...(fileConfig?.stt?.supportedMimeTypes || []),
]);
+/**
+ * Which tool destinations an upload may be routed to, before the files
+ * themselves are considered.
+ *
+ * A saved agent's tool list is the authority: it can only receive uploads for
+ * the tools it was built with. Everywhere else the destination is offered
+ * whether or not the tool is currently switched on, because choosing it is what
+ * switches it on.
+ *
+ * Shared by the `+` menu and the drag-and-drop router so a file has the same
+ * destinations however it arrives.
+ */
+export interface UploadToolAllowances {
+ fileSearchAllowedByAgent: boolean;
+ codeAllowedByAgent: boolean;
+}
+
+export const getUploadToolAllowances = (
+ agentId: string | null | undefined,
+ tools: string[] | undefined,
+): UploadToolAllowances => {
+ const isSavedAgent = agentId != null && agentId !== '' && !isEphemeralAgentId(agentId);
+ return {
+ fileSearchAllowedByAgent: !isSavedAgent || (tools?.includes(Tools.file_search) ?? false),
+ codeAllowedByAgent: !isSavedAgent || (tools?.includes(Tools.execute_code) ?? false),
+ };
+};
+
/**
* Upload destinations a file set can be routed to, given the active endpoint and agent
* capabilities. `undefined` is direct provider attachment; the rest are tool resources.
diff --git a/client/src/utils/index.ts b/client/src/utils/index.ts
index 2e0fe03aba..7d6a691185 100644
--- a/client/src/utils/index.ts
+++ b/client/src/utils/index.ts
@@ -50,6 +50,7 @@ export * from './toolLabels';
export * from './favoritesError';
export * from './approval';
export * from './steer';
+export * from './pane';
export * from './activityLabels';
export * from './agentModelSelection';
export * from './runStepDuration';
diff --git a/client/src/utils/pane.ts b/client/src/utils/pane.ts
new file mode 100644
index 0000000000..4b1cedef75
--- /dev/null
+++ b/client/src/utils/pane.ts
@@ -0,0 +1,27 @@
+/** Resolves the chat pane an element belongs to: its own `[data-chat-pane]`
+ * ancestor, or the pane named by a `[data-chat-pane-portal]` ancestor for
+ * surfaces rendered outside the pane's subtree (palettes, popovers, header). */
+export function getChatPane(element: Element | null): HTMLElement | null {
+ const directPane = element?.closest<HTMLElement>('[data-chat-pane]');
+ if (directPane != null) {
+ return directPane;
+ }
+ const paneIndex =
+ element?.closest<HTMLElement>('[data-chat-pane-portal]')?.dataset.chatPanePortal;
+ if (paneIndex != null && /^\d+$/.test(paneIndex)) {
+ return document.querySelector<HTMLElement>(`[data-chat-pane="${paneIndex}"]`);
+ }
+ return null;
+}
+
+/** The pane holding keyboard focus, or `null` when focus sits outside every pane. */
+export function getFocusedChatPane(): HTMLElement | null {
+ return getChatPane(document.activeElement);
+}
+
+/** Whether a pane-scoped keyboard action should act for this pane: the pane
+ * holding focus, or the first pane when focus sits outside every pane. */
+export function isFocusedChatPane(index: number): boolean {
+ const focused = getFocusedChatPane()?.dataset.chatPane;
+ return focused == null ? index === 0 : focused === String(index);
+}
diff --git a/client/src/utils/queue.ts b/client/src/utils/queue.ts
index 5bea8b01fc..82411cffa1 100644
--- a/client/src/utils/queue.ts
+++ b/client/src/utils/queue.ts
@@ -29,3 +29,44 @@ const releaseTail = (key: string, settled: Promise<unknown>): void => {
tails.delete(key);
}
};
+import type { QueuedMessage } from '~/store/families';
+
+export const compareQueuedMessages = (a: QueuedMessage, b: QueuedMessage): number =>
+ Number(b.priority ?? false) - Number(a.priority ?? false) || a.createdAt - b.createdAt;
+
+/** Places one new message without disturbing the order the user chose for
+ * rows already in the queue. */
+export function insertQueuedMessage(
+ queue: readonly QueuedMessage[],
+ item: QueuedMessage,
+): QueuedMessage[] {
+ const index = queue.findIndex((queued) => compareQueuedMessages(item, queued) < 0);
+ if (index < 0) {
+ return [...queue, item];
+ }
+ return [...queue.slice(0, index), item, ...queue.slice(index)];
+}
+
+/** Merges independently ordered queue keys while preserving the relative
+ * order within each key, including any manual reordering. */
+export function mergeQueuedMessages(
+ first: readonly QueuedMessage[],
+ second: readonly QueuedMessage[],
+): QueuedMessage[] {
+ const merged: QueuedMessage[] = [];
+ let firstIndex = 0;
+ let secondIndex = 0;
+
+ while (firstIndex < first.length && secondIndex < second.length) {
+ if (compareQueuedMessages(first[firstIndex], second[secondIndex]) <= 0) {
+ merged.push(first[firstIndex]);
+ firstIndex += 1;
+ } else {
+ merged.push(second[secondIndex]);
+ secondIndex += 1;
+ }
+ }
+
+ merged.push(...first.slice(firstIndex), ...second.slice(secondIndex));
+ return merged;
+}
diff --git a/client/src/utils/queueIntent.ts b/client/src/utils/queueIntent.ts
new file mode 100644
index 0000000000..ca7c672135
--- /dev/null
+++ b/client/src/utils/queueIntent.ts
@@ -0,0 +1,87 @@
+import { DEFAULT_QUEUED_SEND_LOCK_TIMEOUT_MS } from 'librechat-data-provider';
+
+/**
+ * Cross-hook arbitration for the client-side message queue, deliberately held
+ * OUTSIDE React state.
+ *
+ * Two independent surfaces decide whether to submit a queued message: the
+ * run-end drain (`useQueueDrain`) and the rail's own actions (`useSteering`).
+ * Both read `isSubmitting`, which Recoil only makes readable a render after
+ * `ask()` was called, so within one browser task each can observe an idle pane
+ * and submit the same slot. A ref belongs to a single hook instance and Recoil
+ * is asynchronous, so neither can arbitrate; a module-scoped registry read and
+ * written synchronously can.
+ */
+
+/** Opaque proof of ownership: a holder can only release the lock it took. */
+export type QueueSendLock = {
+ readonly pane: string;
+ readonly takenAt: number;
+};
+
+const sendLocks = new Map<string, QueueSendLock>();
+
+/**
+ * Claims a pane's submission slot for one queued send. Returns `null` when a
+ * send is already in flight there, in which case the caller must NOT submit.
+ *
+ * `staleAfterMs` is a last-resort expiry, never the normal release path. A
+ * claim is given up as soon as the pane's submission state moves, which for
+ * the ordinary agents start happens synchronously inside `ask`. A start that
+ * hard-fails without ever setting `isSubmitting` leaves nothing to observe, and
+ * without an expiry that claim would sit on the pane until the user navigated
+ * away. It is far longer than any healthy start takes to become observable, so
+ * it only fires on a claim that is already broken, and then the pane degrades
+ * to the unguarded behaviour rather than latching shut. Operators set it as
+ * `interface.queuedSendLockTimeoutMs`.
+ */
+export function acquireQueueSendLock(
+ pane: string,
+ staleAfterMs: number = DEFAULT_QUEUED_SEND_LOCK_TIMEOUT_MS,
+): QueueSendLock | null {
+ const held = sendLocks.get(pane);
+ if (held != null && Date.now() - held.takenAt < staleAfterMs) {
+ return null;
+ }
+ const lock: QueueSendLock = { pane, takenAt: Date.now() };
+ sendLocks.set(pane, lock);
+ return lock;
+}
+
+/**
+ * Releases a lock only while it is still the one held, so a late release
+ * cannot free a slot some other caller has since claimed.
+ */
+export function releaseQueueSendLock(lock: QueueSendLock | null | undefined): void {
+ if (lock != null && sendLocks.get(lock.pane) === lock) {
+ sendLocks.delete(lock.pane);
+ }
+}
+
+const queuedIntents = new Set<string>();
+
+/**
+ * Marks a queued row as spoken for while the user edits or removes it. The
+ * handoff spans an await (discarding the parked server copy, then handing the
+ * words to the composer) and the run-end drain can land inside that gap, which
+ * would send the very message being taken back.
+ *
+ * Returns `false` when another intent already holds the row, so a second
+ * click leaves it alone rather than racing the first.
+ */
+export function claimQueuedIntent(id: string): boolean {
+ if (queuedIntents.has(id)) {
+ return false;
+ }
+ queuedIntents.add(id);
+ return true;
+}
+
+export function releaseQueuedIntent(id: string): void {
+ queuedIntents.delete(id);
+}
+
+/** Whether a queued row is mid-edit or mid-remove; the drain skips those. */
+export function hasQueuedIntent(id: string): boolean {
+ return queuedIntents.has(id);
+}
diff --git a/client/src/utils/shortcuts.spec.ts b/client/src/utils/shortcuts.spec.ts
index bfb6588a9f..eff456ed6e 100644
--- a/client/src/utils/shortcuts.spec.ts
+++ b/client/src/utils/shortcuts.spec.ts
@@ -404,11 +404,43 @@ describe('resolveComposerKeyDown', () => {
it('keeps idle Enter semantics', () => {
expect(resolveComposerKeyDown(keydown(), idle)).toBe('submit');
expect(resolveComposerKeyDown(keydown(), { ...idle, enterToSend: false })).toBe('newline');
- expect(resolveComposerKeyDown(keydown({ ctrlKey: true }), idle)).toBe('submit');
expect(resolveComposerKeyDown(keydown({ shiftKey: true }), idle)).toBe('none');
expect(resolveComposerKeyDown(new KeyboardEvent('keydown', { key: 'a' }), idle)).toBe('none');
});
+ /* The modifier is the inverse of plain Enter, so whichever of the two sends,
+ the other writes a newline and neither preference leaves the user without
+ a way to break a line. */
+ it('inverts Ctrl/Cmd+Enter against the Enter-to-send preference while idle', () => {
+ expect(resolveComposerKeyDown(keydown({ ctrlKey: true }), idle)).toBe('newline');
+ expect(resolveComposerKeyDown(keydown({ metaKey: true }), idle)).toBe('newline');
+ expect(
+ resolveComposerKeyDown(keydown({ ctrlKey: true }), { ...idle, enterToSend: false }),
+ ).toBe('submit');
+ expect(
+ resolveComposerKeyDown(keydown({ metaKey: true }), { ...idle, enterToSend: false }),
+ ).toBe('submit');
+ });
+
+ it('leaves both newline chords available whichever way Enter is bound', () => {
+ expect(resolveComposerKeyDown(keydown({ ctrlKey: true }), idle)).toBe('newline');
+ expect(resolveComposerKeyDown(keydown({ shiftKey: true }), idle)).toBe('none');
+ const newlineOnEnter = { ...idle, enterToSend: false };
+ expect(resolveComposerKeyDown(keydown(), newlineOnEnter)).toBe('newline');
+ expect(resolveComposerKeyDown(keydown({ shiftKey: true }), newlineOnEnter)).toBe('newline');
+ });
+
+ /* The during-run table claims Ctrl/Cmd+Enter for the alternate send action,
+ and it resolves before the idle tail, so the newline chord must not reach
+ into a live run and swallow it. */
+ it('does not let the idle newline chord displace the during-run actions', () => {
+ expect(resolveComposerKeyDown(keydown({ ctrlKey: true }), duringRun)).toBe('other');
+ expect(resolveComposerKeyDown(keydown({ ctrlKey: true, shiftKey: true }), duringRun)).toBe(
+ 'preempt',
+ );
+ expect(resolveComposerKeyDown(keydown({ altKey: true }), duringRun)).toBe('interrupt');
+ });
+
it('resolves through the submit override while idle', () => {
const ctx = { ...idle, submitOverride: makeBinding({ alt: true, key: 'Enter' }) };
expect(resolveComposerKeyDown(keydown({ altKey: true }), ctx)).toBe('submit');
diff --git a/client/src/utils/shortcuts.ts b/client/src/utils/shortcuts.ts
index aae538bfdb..0da06e3547 100644
--- a/client/src/utils/shortcuts.ts
+++ b/client/src/utils/shortcuts.ts
@@ -300,11 +300,20 @@ export function resolveComposerKeyDown(
return resolveSubmitOverrideAction(binding, ctx.submitOverride, ctx.enterToSend);
}
const isCtrlEnter = e.ctrlKey || e.metaKey;
- if (!ctx.enterToSend && !isCtrlEnter && !ctx.isComposing) {
- return 'newline';
- }
- if ((!e.shiftKey || isCtrlEnter) && !ctx.isComposing) {
- return 'submit';
+ if (!ctx.isComposing) {
+ /** The modifier is always the inverse of plain Enter: it sends when Enter
+ * writes a newline, and writes one when Enter sends. The rebound path in
+ * `resolveSubmitOverrideAction` already reads it this way, so the default
+ * path only looked different because it had no newline branch. */
+ if (isCtrlEnter) {
+ return ctx.enterToSend ? 'newline' : 'submit';
+ }
+ if (!ctx.enterToSend) {
+ return 'newline';
+ }
+ if (!e.shiftKey) {
+ return 'submit';
+ }
}
if (!e.shiftKey) {
return 'block';
diff --git a/client/src/utils/steer.ts b/client/src/utils/steer.ts
index cf35ba84ab..2580d4bbae 100644
--- a/client/src/utils/steer.ts
+++ b/client/src/utils/steer.ts
@@ -5,10 +5,18 @@ import type {
TSteerAppliedEvent,
TMessageContentParts,
} from 'librechat-data-provider';
-import type { QueuedMessage, QueuedMessageOrigin } from '~/store/families';
+import type { PendingSteer, QueuedMessage, QueuedMessageOrigin } from '~/store/families';
type SteerPart = Extract<TMessageContentParts, { type: ContentTypes.STEER }>;
+/** Protocol v1 cannot correlate an ambiguous failed POST with server state.
+ * Retrying or rerouting it could duplicate words the server already accepted. */
+export function isLegacyDeliveryUncertain(
+ steer: Pick<PendingSteer, 'deliveryUncertain' | 'generationProtocolVersion'>,
+): boolean {
+ return steer.deliveryUncertain === true && steer.generationProtocolVersion !== 2;
+}
+
/** Returns the steer content part when `part` is one, else undefined. */
export function getSteerPart(part: TMessageContentParts | undefined): SteerPart | undefined {
return part?.type === ContentTypes.STEER ? (part as SteerPart) : undefined;
@@ -229,7 +237,11 @@ export function appendAppliedSteerIds(prev: string[], steerIds: string[]): strin
return [...prev, ...fresh].slice(-APPLIED_STEER_IDS_CAP);
}
-export type SteerCarriedContext = { quotes?: string[]; manualSkills?: string[] };
+export type SteerCarriedContext = {
+ quotes?: string[];
+ manualSkills?: string[];
+ reasoningOverride?: TMessage['reasoningOverride'];
+};
/** Quotes ride the steer POST (the server merges them into the injected
* turn) but chips, reseeds, and queued conversions still carry them locally
@@ -239,9 +251,11 @@ export type SteerCarriedContext = { quotes?: string[]; manualSkills?: string[] }
export function carriedSteerContext(source?: SteerCarriedContext): SteerCarriedContext {
const quotes = source?.quotes;
const manualSkills = source?.manualSkills;
+ const reasoningOverride = source?.reasoningOverride;
return {
...(quotes && quotes.length > 0 && { quotes }),
...(manualSkills && manualSkills.length > 0 && { manualSkills }),
+ ...(reasoningOverride != null && { reasoningOverride }),
};
}
diff --git a/config/create-user.js b/config/create-user.js
index 4d05211acc..32773e8c47 100644
--- a/config/create-user.js
+++ b/config/create-user.js
@@ -14,7 +14,9 @@ const connect = require('./connect');
console.purple('--------------------------');
if (process.argv.length < 5) {
- console.orange('Usage: npm run create-user -- <email> <name> <username> [--email-verified=false]');
+ console.orange(
+ 'Usage: npm run create-user -- <email> <name> <username> [--email-verified=false]',
+ );
console.orange('Note: if you do not pass in the arguments, you will be prompted for them.');
console.orange(
'If you really need to pass in the password, you can do so as the 4th argument (not recommended for security).',
@@ -88,9 +90,9 @@ If \`n\`, and email service is configured, the user will be sent a verification
If \`n\`, and email service is not configured, you must have the \`ALLOW_UNVERIFIED_EMAIL_LOGIN\` .env variable set to true,
or the user will need to attempt logging in to have a verification link sent to them.`);
- const normalizedEmailVerifiedInput = emailVerifiedInput.trim().toLowerCase()
+ const normalizedEmailVerifiedInput = emailVerifiedInput.trim().toLowerCase();
- emailVerified = true
+ emailVerified = true;
if (normalizedEmailVerifiedInput === 'n') {
emailVerified = false;
diff --git a/e2e/config/librechat.e2e.yaml b/e2e/config/librechat.e2e.yaml
index 42c95b746d..e78d0d9a67 100644
--- a/e2e/config/librechat.e2e.yaml
+++ b/e2e/config/librechat.e2e.yaml
@@ -8,6 +8,10 @@ interface:
# Exercises the cost row in the context usage gauge (off by default).
# Mock models price at the default rate, so synthetic usage yields a value.
contextCost: true
+ # Enables the model-parameter surface, including the per-turn reasoning
+ # control in the composer. Mock Provider A resolves Anthropic's adaptive
+ # `effort` setting through its custom endpoint configuration below.
+ parameters: true
# Grants MULTI_CONVO.USE so the composer's `+` command opens the added-model
# popover. agent-skills-added.spec.ts drives that flow; without an explicit
# value the permission falls through to the seeded role default and
@@ -166,7 +170,10 @@ endpoints:
modelDisplayLabel: 'Mock Provider A'
customParams:
defaultParamsEndpoint: anthropic
-
+ # Explicitly advertise the effort control for the mock custom endpoint.
+ # Generic fallback inference is intentionally disabled for custom targets.
+ paramDefinitions:
+ - key: effort
- name: 'Mock Provider B'
apiKey: 'e2e-mock-key-b'
baseURL: 'http://127.0.0.1:8889/v1'
diff --git a/e2e/specs/a11y.spec.ts b/e2e/specs/a11y.spec.ts
index f46fea238b..f803680519 100644
--- a/e2e/specs/a11y.spec.ts
+++ b/e2e/specs/a11y.spec.ts
@@ -94,11 +94,15 @@ test('Conversation list rows should be accessible with their controls revealed',
expect(accessibilityScanResults.violations).toEqual([]);
});
-test('Tools menu should be accessible when open', async ({ page }) => {
+test('Attach and tools palette should be accessible when open', async ({ page }) => {
await loadApp(page);
- await page.locator('#tools-dropdown-button').first().click();
- await expect(page.locator('#tools-dropdown-menu')).toBeVisible({ timeout: 10000 });
+ await page.getByRole('button', { name: 'Attach and tools' }).first().click();
+ const palette = page.getByRole('dialog', { name: 'Attach and tools' });
+ await expect(palette).toBeVisible({ timeout: 10000 });
+ await expect(
+ palette.getByRole('combobox', { name: 'Search tools, skills and servers', exact: true }),
+ ).toBeVisible();
const accessibilityScanResults = await new AxeBuilder({ page }).analyze();
diff --git a/e2e/specs/mock/activity-labels.spec.ts b/e2e/specs/mock/activity-labels.spec.ts
index b0096115ec..f7785c1520 100644
--- a/e2e/specs/mock/activity-labels.spec.ts
+++ b/e2e/specs/mock/activity-labels.spec.ts
@@ -54,13 +54,15 @@ async function getLabelRequestsFor(
/** Select the MCP server whose `remember_fact` tool creates the batch boundary. */
async function selectEphemeralMCP(page: Page) {
- await page.getByRole('button', { name: 'MCP Servers', exact: true }).click();
- const serverItem = page.getByRole('menuitemcheckbox', { name: new RegExp(MCP_SERVER_TITLE) });
+ await page.getByRole('button', { name: 'Attach and tools' }).click();
+ const serverItem = page
+ .getByRole('dialog', { name: 'Attach and tools' })
+ .getByRole('button', { name: new RegExp(`^${MCP_SERVER_TITLE}\\b`) });
await expect(serverItem).toBeVisible();
await serverItem.click();
- await expect(serverItem).toHaveAttribute('aria-checked', 'true');
+ await expect(serverItem).toHaveAttribute('aria-pressed', 'true');
await page.keyboard.press('Escape');
- await expect(page.getByRole('button', { name: new RegExp(MCP_SERVER_TITLE) })).toBeVisible();
+ await expect(page.getByRole('listitem', { name: MCP_SERVER_TITLE, exact: true })).toBeVisible();
}
/** Run one labeled turn: two parallel tool calls => exactly one PostToolBatch. */
diff --git a/e2e/specs/mock/activity-phases.spec.ts b/e2e/specs/mock/activity-phases.spec.ts
index 23b77f1e4d..a3fef0f44a 100644
--- a/e2e/specs/mock/activity-phases.spec.ts
+++ b/e2e/specs/mock/activity-phases.spec.ts
@@ -84,13 +84,15 @@ async function getLabelRequestsFor(
}
async function selectEphemeralMCP(page: Page) {
- await page.getByRole('button', { name: 'MCP Servers', exact: true }).click();
- const serverItem = page.getByRole('menuitemcheckbox', { name: new RegExp(MCP_SERVER_TITLE) });
+ await page.getByRole('button', { name: 'Attach and tools' }).click();
+ const serverItem = page
+ .getByRole('dialog', { name: 'Attach and tools' })
+ .getByRole('button', { name: new RegExp(`^${MCP_SERVER_TITLE}\\b`) });
await expect(serverItem).toBeVisible();
await serverItem.click();
- await expect(serverItem).toHaveAttribute('aria-checked', 'true');
+ await expect(serverItem).toHaveAttribute('aria-pressed', 'true');
await page.keyboard.press('Escape');
- await expect(page.getByRole('button', { name: new RegExp(MCP_SERVER_TITLE) })).toBeVisible();
+ await expect(page.getByRole('listitem', { name: MCP_SERVER_TITLE, exact: true })).toBeVisible();
}
function contentPartText(part: PersistedContentPart | null): string {
diff --git a/e2e/specs/mock/agent-skills.spec.ts b/e2e/specs/mock/agent-skills.spec.ts
index 2f9aa47a80..f5811b1c51 100644
--- a/e2e/specs/mock/agent-skills.spec.ts
+++ b/e2e/specs/mock/agent-skills.spec.ts
@@ -389,10 +389,12 @@ test.describe('Agent Builder skills', () => {
await expectSkillInPicker(page, manualPickerSearch, inlineSkillName);
await skillPickerOption(page, inlineSkillName).click();
await expect(manualPickerSearch).toBeHidden();
+ // Manual skill picks stage as tray chips (shared "Staged context" list).
await expect(
page
- .getByRole('list', { name: 'Skills queued for next submission' })
- .getByText(inlineSkillName, { exact: true }),
+ .getByTestId('composer-tray')
+ .getByTestId('composer-chip-skill')
+ .filter({ hasText: inlineSkillName }),
).toBeVisible();
const manualResponse = await sendMessage(
diff --git a/e2e/specs/mock/agents.helpers.ts b/e2e/specs/mock/agents.helpers.ts
index b5d11fdc09..8d36f49b1f 100644
--- a/e2e/specs/mock/agents.helpers.ts
+++ b/e2e/specs/mock/agents.helpers.ts
@@ -91,8 +91,13 @@ export async function waitForPersistedAgent(
return latestAgent!;
}
-export async function openAgentBuilder(page: Page) {
- await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
+export async function openAgentBuilder(
+ page: Page,
+ { navigate = true }: { navigate?: boolean } = {},
+) {
+ if (navigate) {
+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
+ }
const form = page.getByRole('form', { name: 'Agent configuration form' });
/** Which control exists is a layout decision, not a timing one: the rail is
diff --git a/e2e/specs/mock/chat.spec.ts b/e2e/specs/mock/chat.spec.ts
index 10ebb78754..4374d7005e 100644
--- a/e2e/specs/mock/chat.spec.ts
+++ b/e2e/specs/mock/chat.spec.ts
@@ -58,11 +58,13 @@ const imageFixture: UploadFixture = {
const composer = (page: Page) => page.locator('form');
async function openProviderFileChooser(page: Page) {
- await page.getByRole('button', { name: 'Attach File Options' }).click();
- await expect(page.getByText('Upload to Provider')).toBeVisible();
+ // Uploads live in the composer palette (the old AttachFileMenu is gone).
+ await page.getByRole('button', { name: 'Attach and tools' }).click();
+ const uploadOption = page.getByRole('button', { name: 'Upload to Provider', exact: true });
+ await expect(uploadOption).toBeVisible();
const fileChooserPromise = page.waitForEvent('filechooser');
- await page.getByText('Upload to Provider').click();
+ await uploadOption.click();
const fileChooser = await fileChooserPromise;
expect(await fileChooser.element().getAttribute('type')).toBe('file');
return fileChooser;
diff --git a/e2e/specs/mock/code-upload.spec.ts b/e2e/specs/mock/code-upload.spec.ts
index 8628c4aa05..a30c6e89b6 100644
--- a/e2e/specs/mock/code-upload.spec.ts
+++ b/e2e/specs/mock/code-upload.spec.ts
@@ -7,6 +7,7 @@ import {
messagesView,
requestJson,
sendMessageAndWaitForCompletion,
+ uploadViaLegacyOption,
} from './helpers';
/**
@@ -74,28 +75,14 @@ async function selectAgent(page: Page, agentName: string) {
await expect(modelTrigger(page)).toContainText(agentName);
}
-/** Attaches a CSV through the real attach menu → Code Environment target,
+/** Attaches a CSV through the palette's Code Environment destination row,
* which uploads it to the live Code API before the message is ever sent. */
async function attachCodeFile(page: Page) {
- const [chooser] = await Promise.all([
- page.waitForEvent('filechooser'),
- (async () => {
- await page.getByRole('button', { name: 'Attach File Options' }).click();
- await page.getByRole('menuitem', { name: 'Upload to Code Environment' }).click();
- })(),
- ]);
- const [upload] = await Promise.all([
- page.waitForResponse(
- (response) =>
- new URL(response.url()).pathname === '/api/files' && response.request().method() === 'POST',
- { timeout: 60_000 },
- ),
- chooser.setFiles({
- name: FILE_NAME,
- mimeType: 'text/csv',
- buffer: Buffer.from(FILE_CONTENT),
- }),
- ]);
+ const upload = await uploadViaLegacyOption(page, 'Upload to Code Environment', {
+ name: FILE_NAME,
+ mimeType: 'text/csv',
+ content: FILE_CONTENT,
+ });
expect(upload.ok(), `code file upload returned ${upload.status()}`).toBeTruthy();
await expect(page.getByText(FILE_NAME).first()).toBeVisible();
}
diff --git a/e2e/specs/mock/file-provisioning.spec.ts b/e2e/specs/mock/file-provisioning.spec.ts
index e099f2ce06..47950e4caa 100644
--- a/e2e/specs/mock/file-provisioning.spec.ts
+++ b/e2e/specs/mock/file-provisioning.spec.ts
@@ -23,10 +23,10 @@ import {
*
* Two trigger points are covered end to end (real backend + DB + provisioning HTTP):
*
- * - Immediate (legacy dropdown, Mock Provider A): choosing "Upload to Code
+ * - Immediate (legacy destination rows, Mock Provider A): choosing "Upload to Code
* Environment" / "Upload for File Search" provisions at upload time
* (`uploadCodeEnvFile` / `uploadVectors`).
- * - Lazy (unified button, Mock Provider B): a plain attachment routes to `none` and
+ * - Lazy (unified palette source row, Mock Provider B): a plain attachment routes to `none` and
* is NOT provisioned at upload; it is uploaded to the code env / embedded only
* when a tool that needs it runs (`provisionFiles` at ON_TOOL_EXECUTE). This is the
* headline behavior — "all uploaded files available to the tool at execute time".
@@ -35,14 +35,14 @@ import {
* actually reached the target env, independent of the deferred DB write.
*/
-test.describe('file provisioning — immediate (legacy dropdown)', () => {
+test.describe('file provisioning — immediate (legacy destination rows)', () => {
test('"Upload to Code Environment" provisions the file to the code env', async ({ page }) => {
test.setTimeout(120000);
await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
await resetProvisioning(page);
- // The legacy "Upload to Code Environment" option only appears once the
- // ephemeral execute_code capability is enabled.
+ // The Code Environment destination row appears once the ephemeral
+ // execute_code capability is enabled.
await enableCodeInterpreter(page);
const fileName = `${uniqueName('code')}.csv`;
@@ -66,7 +66,7 @@ test.describe('file provisioning — immediate (legacy dropdown)', () => {
await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
await resetProvisioning(page);
- // The legacy "Upload for File Search" option only appears once the ephemeral
+ // The File Search destination row appears once the ephemeral
// file_search capability is enabled.
await enableFileSearch(page);
@@ -106,7 +106,11 @@ test.describe('file provisioning — lazy (unified upload, at tool-execute)', ()
(await getCodeProvisionedUploads(page)).map((u) => u.filename),
'unified upload must not provision to the code env until a tool runs',
).not.toContain(fileName);
- await expect(page.getByRole('button', { name: fileName })).toBeVisible({ timeout: 15000 });
+ /* Scoped to the tray: the palette lists the same file under its recent
+ uploads, and it is still in the DOM while its close animation runs. */
+ await expect(
+ page.getByTestId('composer-tray').getByRole('button', { name: fileName }),
+ ).toBeVisible({ timeout: 15000 });
// A tool run triggers lazy provisioning: the fake model emits an execute_code call.
// Provisioning fires at ON_TOOL_EXECUTE, before the execute_code tool itself runs,
@@ -144,7 +148,11 @@ test.describe('file provisioning — lazy (unified upload, at tool-execute)', ()
(await getRagEmbedded(page)).map((e) => e.file_id),
'unified upload must not embed until file_search runs',
).not.toContain(fileId);
- await expect(page.getByRole('button', { name: fileName })).toBeVisible({ timeout: 15000 });
+ /* Scoped to the tray: the palette lists the same file under its recent
+ uploads, and it is still in the DOM while its close animation runs. */
+ await expect(
+ page.getByTestId('composer-tray').getByRole('button', { name: fileName }),
+ ).toBeVisible({ timeout: 15000 });
// The first tool call lazily embeds the attachment and searches it.
await sendMessageAndWaitForCompletion(page, `E2E_FILE_SEARCH:${uniqueName('first')}`);
diff --git a/e2e/specs/mock/helpers.ts b/e2e/specs/mock/helpers.ts
index 6f62b5ac10..fcd7cd4192 100644
--- a/e2e/specs/mock/helpers.ts
+++ b/e2e/specs/mock/helpers.ts
@@ -74,36 +74,44 @@ export async function selectModelSpec(page: Page, label: string) {
await expect(trigger).toContainText(label);
}
-/** Enable the ephemeral Skills capability from the composer tool menu. */
-export async function enableSkills(page: Page) {
- await page.getByRole('button', { name: 'Tools Options' }).click();
- await page.getByTestId('tools-menu-skills').click();
+/** Toggle a built-in tool row on from the composer palette and wait for its chip. */
+async function enableBuiltinTool(page: Page, label: string) {
+ await page.getByRole('button', { name: 'Attach and tools' }).click();
+ const row = page
+ .getByRole('dialog', { name: 'Attach and tools' })
+ .getByRole('button', { name: label, exact: true });
+ await expect(row).toBeVisible();
+ await row.click();
+ await expect(row).toHaveAttribute('aria-pressed', 'true');
await page.keyboard.press('Escape');
- await expect(page.getByRole('button', { name: 'Skills' })).toBeVisible();
+ await expect(
+ page.getByTestId('composer-active-builtin').filter({ hasText: label }),
+ ).toBeVisible();
+ /* Wait for the palette to finish closing. Reopening it during the leave
+ animation resumes the same popover rather than mounting a fresh one, so the
+ list keeps the scroll offset this click left it at, and the Attach rows at
+ the top sit outside the virtualized window a caller then queries. */
+ await expect(page.getByRole('dialog', { name: 'Attach and tools' })).toHaveCount(0);
}
-/** Enable the ephemeral Memory capability from the composer tool menu. */
+/** Enable the ephemeral Skills capability from the composer palette. */
+export async function enableSkills(page: Page) {
+ await enableBuiltinTool(page, 'Skills');
+}
+
+/** Enable the ephemeral Memory capability from the composer palette. */
export async function enableMemory(page: Page) {
- await page.getByRole('button', { name: 'Tools Options' }).click();
- await page.getByTestId('tools-menu-memory').click();
- await page.keyboard.press('Escape');
- await expect(page.getByRole('checkbox', { name: 'Memory' })).toBeVisible();
+ await enableBuiltinTool(page, 'Memory');
}
-/** Enable the ephemeral Code Interpreter (execute_code) capability from the tool menu. */
+/** Enable the ephemeral Code Interpreter (execute_code) capability from the palette. */
export async function enableCodeInterpreter(page: Page) {
- await page.getByRole('button', { name: 'Tools Options' }).click();
- await page.getByTestId('tools-menu-run-code').click();
- await page.keyboard.press('Escape');
- await expect(page.getByRole('checkbox', { name: 'Run Code' })).toBeVisible();
+ await enableBuiltinTool(page, 'Run Code');
}
-/** Enable the ephemeral File Search capability from the composer tool menu. */
+/** Enable the ephemeral File Search capability from the composer palette. */
export async function enableFileSearch(page: Page) {
- await page.getByRole('button', { name: 'Tools Options' }).click();
- await page.getByTestId('tools-menu-file-search').click();
- await page.keyboard.press('Escape');
- await expect(page.getByRole('checkbox', { name: 'File Search' })).toBeVisible();
+ await enableBuiltinTool(page, 'File Search');
}
/** The conversation messages container. */
@@ -461,13 +469,16 @@ export function waitForUpload(page: Page) {
});
}
-/** Attach a file via the unified single button (no tool resource). */
+/** Attach a file through the palette's implicit local/provider source row. */
export async function uploadViaUnifiedButton(page: Page, file: AttachFile) {
const uploadResponse = waitForUpload(page);
- const [fileChooser] = await Promise.all([
- page.waitForEvent('filechooser'),
- page.locator('#attach-file-button').click(),
- ]);
+ await page.getByRole('button', { name: 'Attach and tools', exact: true }).click();
+ const palette = page.getByRole('dialog', { name: 'Attach and tools', exact: true });
+ const sourceRow = palette.getByRole('button', {
+ name: /^(From Local Computer|Upload to Provider)$/,
+ });
+ await expect(sourceRow).toBeVisible();
+ const [fileChooser] = await Promise.all([page.waitForEvent('filechooser'), sourceRow.click()]);
await fileChooser.setFiles({
name: file.name,
mimeType: file.mimeType,
@@ -476,13 +487,40 @@ export async function uploadViaUnifiedButton(page: Page, file: AttachFile) {
return uploadResponse;
}
-/** Attach a file via a named option in the legacy 3-way dropdown. */
+const legacyDestinationRows: Record<string, { key: string; label: string }> = {
+ 'Upload to Code Environment': {
+ key: 'local:execute_code',
+ label: 'Upload to Code Environment',
+ },
+ 'Upload for File Search': {
+ key: 'local:file_search',
+ label: 'Upload for File Search',
+ },
+};
+
+/** Attach through a named legacy destination row in the composer palette. */
export async function uploadViaLegacyOption(page: Page, optionName: string, file: AttachFile) {
+ const destination = legacyDestinationRows[optionName];
+ if (destination == null) {
+ throw new Error(`Unsupported legacy upload destination: ${optionName}`);
+ }
+
const uploadResponse = waitForUpload(page);
- await page.locator('#attach-file-menu-button').click();
+ await page.getByRole('button', { name: 'Attach and tools', exact: true }).click();
+ const palette = page.getByRole('dialog', { name: 'Attach and tools', exact: true });
+ const moreOptions = palette.getByRole('button', { name: 'More upload options', exact: true });
+ await expect(moreOptions).toBeVisible();
+ await moreOptions.click();
+ const destinationRow = palette
+ .locator(`[data-row-key="${destination.key}"]`)
+ .getByRole('button', {
+ name: destination.label,
+ exact: true,
+ });
+ await expect(destinationRow).toBeVisible();
const [fileChooser] = await Promise.all([
page.waitForEvent('filechooser'),
- page.getByRole('menuitem', { name: optionName }).click(),
+ destinationRow.click(),
]);
await fileChooser.setFiles({
name: file.name,
diff --git a/e2e/specs/mock/mcp-apps.spec.ts b/e2e/specs/mock/mcp-apps.spec.ts
index 20cc990cdc..4837513b13 100644
--- a/e2e/specs/mock/mcp-apps.spec.ts
+++ b/e2e/specs/mock/mcp-apps.spec.ts
@@ -236,13 +236,24 @@ async function rawAuthenticatedRequest(
);
}
+/** The redesigned composer seats MCP servers in the attach-and-tools palette as
+ * toggleable rows, so enabling one for the run opens the palette, waits for the
+ * server wave of the catalog, and flips the row's pressed state. */
async function selectMcpAppServer(page: Page) {
- await page.getByRole('button', { name: 'MCP Servers', exact: true }).click();
- const server = page.getByRole('menuitemcheckbox', { name: new RegExp(MCP_SERVER_TITLE) });
+ const paletteButton = page.getByRole('button', { name: 'Attach and tools' });
+ await expect(paletteButton).toBeVisible();
+ await paletteButton.click();
+ const palette = page.getByRole('dialog', { name: 'Attach and tools' });
+ await expect(palette).toBeVisible();
+ await expect(palette.getByRole('columnheader', { name: 'MCP Servers', exact: true })).toBeVisible(
+ { timeout: 20000 },
+ );
+ const server = palette.locator('[data-row-key]').filter({ hasText: MCP_SERVER_TITLE });
await expect(server).toBeVisible();
await server.click();
- await expect(server).toHaveAttribute('aria-checked', 'true');
+ await expect(server.getByRole('button').first()).toHaveAttribute('aria-pressed', 'true');
await page.keyboard.press('Escape');
+ await expect(palette).toBeHidden();
}
function appFrame(page: Page, toolName = 'show_app', occurrence = 0): FrameLocator {
diff --git a/e2e/specs/mock/mcp-ephemeral.spec.ts b/e2e/specs/mock/mcp-ephemeral.spec.ts
index 93104f4a43..6b19adfa1b 100644
--- a/e2e/specs/mock/mcp-ephemeral.spec.ts
+++ b/e2e/specs/mock/mcp-ephemeral.spec.ts
@@ -19,15 +19,18 @@ const MCP_SERVER_TITLE = 'E2E Memory';
const uniqueText = (prefix: string) => `${prefix} ${Date.now()}-${Math.floor(Math.random() * 1e4)}`;
-const mcpBadge = (page: Page) => page.getByRole('button', { name: new RegExp(MCP_SERVER_TITLE) });
+const mcpBadge = (page: Page) =>
+ page.getByRole('listitem', { name: MCP_SERVER_TITLE, exact: true });
-/** Select the MCP server from the composer's ephemeral MCP dropdown. */
+/** Select the MCP server from the composer palette. */
async function selectEphemeralMCP(page: Page) {
- await page.getByRole('button', { name: 'MCP Servers', exact: true }).click();
- const serverItem = page.getByRole('menuitemcheckbox', { name: new RegExp(MCP_SERVER_TITLE) });
+ await page.getByRole('button', { name: 'Attach and tools' }).click();
+ const serverItem = page
+ .getByRole('dialog', { name: 'Attach and tools' })
+ .getByRole('button', { name: new RegExp(`^${MCP_SERVER_TITLE}\\b`) });
await expect(serverItem).toBeVisible();
await serverItem.click();
- await expect(serverItem).toHaveAttribute('aria-checked', 'true');
+ await expect(serverItem).toHaveAttribute('aria-pressed', 'true');
await page.keyboard.press('Escape');
await expect(mcpBadge(page)).toBeVisible();
}
diff --git a/e2e/specs/mock/mcp-oauth-readiness.spec.ts b/e2e/specs/mock/mcp-oauth-readiness.spec.ts
index 85cdf17b29..438579ae89 100644
--- a/e2e/specs/mock/mcp-oauth-readiness.spec.ts
+++ b/e2e/specs/mock/mcp-oauth-readiness.spec.ts
@@ -1,9 +1,49 @@
import { expect, test } from '@playwright/test';
+import type { Locator, Page } from '@playwright/test';
const SERVER_NAME = 'e2e-memory';
const SERVER_TITLE = 'E2E Memory';
const FLOW_ID = 'e2e-user:e2e-memory';
+/** The MCP Builder panel card for the mock server, which owns Connect/Cancel. */
+async function openMcpPanel(page: Page) {
+ const nav = page.getByRole('button', { name: 'MCP Settings' });
+ if ((await nav.getAttribute('aria-pressed')) !== 'true') {
+ await nav.click();
+ }
+}
+const serverCard = (page: Page) => page.getByLabel(new RegExp(`^${SERVER_TITLE} - `));
+/** Row actions reveal on hover on pointer devices, so reach Connect the way a
+ * pointer does: over the row first. */
+async function connectButton(card: Locator) {
+ await card.hover();
+ return card.getByRole('button', { name: 'Connect', exact: true });
+}
+
+/** Selection state lives in the composer palette; open it fresh per check and
+ * close with Escape so the panel underneath stays interactable. */
+const paletteOption = (page: Page) =>
+ page
+ .getByRole('dialog', { name: 'Attach and tools' })
+ .getByRole('button', { name: new RegExp(`^${SERVER_TITLE}\\b`) });
+/** Connect opens the OAuth dialog on top of the panel. It is a modal, so while
+ * it is open the rest of the document is marked `aria-hidden` and the card's
+ * own Cancel button is not in the accessibility tree at all. Dismiss it before
+ * asserting on anything underneath. */
+async function dismissOAuthDialog(page: Page) {
+ /* Titled with the server's name, not its display title. */
+ const dialog = page.getByRole('dialog', { name: `Connect ${SERVER_NAME}`, exact: true });
+ await expect(dialog).toBeVisible({ timeout: 10000 });
+ await page.keyboard.press('Escape');
+ await expect(dialog).toHaveCount(0);
+}
+
+async function expectSelected(page: Page, checked: 'true' | 'false') {
+ await page.getByRole('button', { name: 'Attach and tools' }).click();
+ await expect(paletteOption(page)).toHaveAttribute('aria-pressed', checked);
+ await page.keyboard.press('Escape');
+}
+
test.describe('MCP OAuth readiness', () => {
test('keeps the server unselected until post-OAuth tool readiness completes', async ({
page,
@@ -105,26 +145,21 @@ test.describe('MCP OAuth readiness', () => {
});
await page.goto('/c/new', { timeout: 10000 });
- await page.getByRole('button', { name: 'MCP Servers', exact: true }).click();
- const serverItem = page.getByRole('menuitemcheckbox', { name: new RegExp(SERVER_TITLE) });
- await expect(serverItem).toHaveAttribute('aria-checked', 'false');
- await serverItem.getByRole('button', { name: `Connect ${SERVER_NAME}` }).click();
+ await expectSelected(page, 'false');
- await page.getByRole('button', { name: 'Authenticate', exact: true }).click();
- await expect(page.getByRole('button', { name: 'Continue with OAuth' })).toBeVisible();
+ await openMcpPanel(page);
+ const card = serverCard(page);
+ await (await connectButton(card)).click();
await pendingPolled;
+ await dismissOAuthDialog(page);
- await page.keyboard.press('Escape');
- await page.getByRole('button', { name: 'MCP Servers', exact: true }).click();
- await expect(serverItem.getByRole('button', { name: 'Cancel' })).toBeVisible();
+ await expect(card.getByRole('button', { name: 'Cancel' })).toBeVisible();
await expect(page.getByText('Failed to initialize MCP server')).toHaveCount(0);
await readinessStarted;
- await page.keyboard.press('Escape');
- await page.getByRole('button', { name: 'MCP Servers', exact: true }).click();
- await expect(serverItem).toHaveAttribute('aria-checked', 'false');
- await expect(serverItem.getByRole('button', { name: 'Cancel' })).toBeVisible();
+ await expectSelected(page, 'false');
+ await expect(card.getByRole('button', { name: 'Cancel' })).toBeVisible();
await expect(
page.getByText(`MCP server '${SERVER_NAME}' authenticated successfully`),
).toHaveCount(0);
@@ -134,7 +169,7 @@ test.describe('MCP OAuth readiness', () => {
await expect(
page.getByText(`MCP server '${SERVER_NAME}' authenticated successfully`).first(),
).toBeVisible();
- await expect(serverItem).toHaveAttribute('aria-checked', 'true');
+ await expectSelected(page, 'true');
expect(reinitializeCalls).toBe(2);
});
@@ -184,19 +219,16 @@ test.describe('MCP OAuth readiness', () => {
});
await page.goto('/c/new', { timeout: 10000 });
- await page.getByRole('button', { name: 'MCP Servers', exact: true }).click();
- const serverItem = page.getByRole('menuitemcheckbox', { name: new RegExp(SERVER_TITLE) });
- await serverItem.getByRole('button', { name: `Connect ${SERVER_NAME}` }).click();
- await page.getByRole('button', { name: 'Authenticate', exact: true }).click();
+ await openMcpPanel(page);
+ const card = serverCard(page);
+ await (await connectButton(card)).click();
await expect(page.getByText(`OAuth login timed out for ${SERVER_NAME}`).first()).toBeVisible({
timeout: 15000,
});
expect(flowStatusCalls).toBe(2);
- await page.keyboard.press('Escape');
- await page.getByRole('button', { name: 'MCP Servers', exact: true }).click();
- await expect(serverItem.getByRole('button', { name: `Connect ${SERVER_NAME}` })).toBeVisible();
+ await expect(await connectButton(card)).toBeVisible();
});
test('accepts completion found by the final poll after the attempt deadline', async ({
@@ -259,21 +291,15 @@ test.describe('MCP OAuth readiness', () => {
});
await page.goto('/c/new', { timeout: 10000 });
- await page.getByRole('button', { name: 'MCP Servers', exact: true }).click();
- const serverItem = page.getByRole('menuitemcheckbox', { name: new RegExp(SERVER_TITLE) });
- await serverItem.getByRole('button', { name: `Connect ${SERVER_NAME}` }).click();
- await page.getByRole('button', { name: 'Authenticate', exact: true }).click();
+ await openMcpPanel(page);
+ const card = serverCard(page);
+ await (await connectButton(card)).click();
await expect(
page.getByText(`MCP server '${SERVER_NAME}' authenticated successfully`).first(),
).toBeVisible({ timeout: 15000 });
await expect(page.getByText(`OAuth login timed out for ${SERVER_NAME}`)).toHaveCount(0);
- await expect(
- page.getByRole('menuitemcheckbox', {
- name: new RegExp(SERVER_TITLE),
- includeHidden: true,
- }),
- ).toHaveAttribute('aria-checked', 'true');
+ await expectSelected(page, 'true');
expect(flowStatusCalls).toBe(1);
expect(reinitializeCalls).toBe(2);
});
@@ -326,10 +352,9 @@ test.describe('MCP OAuth readiness', () => {
});
await page.goto('/c/new', { timeout: 10000 });
- await page.getByRole('button', { name: 'MCP Servers', exact: true }).click();
- const serverItem = page.getByRole('menuitemcheckbox', { name: new RegExp(SERVER_TITLE) });
- await serverItem.getByRole('button', { name: `Connect ${SERVER_NAME}` }).click();
- await page.getByRole('button', { name: 'Authenticate', exact: true }).click();
+ await openMcpPanel(page);
+ const card = serverCard(page);
+ await (await connectButton(card)).click();
await expect(page.getByText(`OAuth login timed out for ${SERVER_NAME}`).first()).toBeVisible({
timeout: 15000,
@@ -397,21 +422,19 @@ test.describe('MCP OAuth readiness', () => {
});
await page.goto('/c/new', { timeout: 10000 });
- await page.getByRole('button', { name: 'MCP Servers', exact: true }).click();
- const serverItem = page.getByRole('menuitemcheckbox', { name: new RegExp(SERVER_TITLE) });
- await serverItem.getByRole('button', { name: `Connect ${SERVER_NAME}` }).click();
- await page.getByRole('button', { name: 'Authenticate', exact: true }).click();
-
- await page.keyboard.press('Escape');
- await page.getByRole('button', { name: 'MCP Servers', exact: true }).click();
- await expect(serverItem.getByRole('button', { name: 'Cancel' })).toBeVisible({
+ await openMcpPanel(page);
+ const card = serverCard(page);
+ await (await connectButton(card)).click();
+ await dismissOAuthDialog(page);
+
+ await expect(card.getByRole('button', { name: 'Cancel' })).toBeVisible({
timeout: 8000,
});
await expect(page.getByText('Failed to initialize MCP server')).toHaveCount(0);
await expect(
page.getByText(`MCP server '${SERVER_NAME}' authenticated successfully`).first(),
).toBeVisible({ timeout: 20000 });
- await expect(serverItem).toHaveAttribute('aria-checked', 'true');
+ await expectSelected(page, 'true');
expect(flowStatusCalls).toBeGreaterThanOrEqual(2);
});
});
diff --git a/e2e/specs/mock/memory.spec.ts b/e2e/specs/mock/memory.spec.ts
index 86c7328bb0..6dc724ccdf 100644
--- a/e2e/specs/mock/memory.spec.ts
+++ b/e2e/specs/mock/memory.spec.ts
@@ -23,7 +23,9 @@ test.describe('memory badge', () => {
await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
await enableMemory(page);
- await expect(page.getByRole('checkbox', { name: 'Memory' })).toBeChecked();
+ await expect(
+ page.getByTestId('composer-active-builtin').filter({ hasText: 'Memory' }),
+ ).toBeVisible();
const memoryRequest = page.waitForRequest(
(request) => request.url().includes('/api/agents/chat') && request.method() === 'POST',
diff --git a/e2e/specs/mock/message-visual.spec.ts b/e2e/specs/mock/message-visual.spec.ts
index afb30be0e9..3704bd7f90 100644
--- a/e2e/specs/mock/message-visual.spec.ts
+++ b/e2e/specs/mock/message-visual.spec.ts
@@ -78,13 +78,13 @@ async function expectMessageScreenshot(locator: Locator, name: string) {
}
async function selectEphemeralMCP(page: Page) {
- await page.getByRole('button', { name: 'MCP Servers', exact: true }).click();
- const serverItem = page.getByRole('menuitemcheckbox', {
- name: new RegExp(MCP_SERVER_TITLE),
- });
+ await page.getByRole('button', { name: 'Attach and tools' }).click();
+ const serverItem = page
+ .getByRole('dialog', { name: 'Attach and tools' })
+ .getByRole('button', { name: new RegExp(`^${MCP_SERVER_TITLE}\\b`) });
await expect(serverItem).toBeVisible();
await serverItem.click();
- await expect(serverItem).toHaveAttribute('aria-checked', 'true');
+ await expect(serverItem).toHaveAttribute('aria-pressed', 'true');
await page.keyboard.press('Escape');
}
@@ -162,6 +162,9 @@ for (const viewport of VIEWPORTS) {
test(`captures an applied steer message`, async ({ page }) => {
test.setTimeout(150000);
+ await page.addInitScript(() => {
+ localStorage.setItem('duringRunDefaultAction', JSON.stringify('steer'));
+ });
const setupLabel = `message-visual-steer-setup-${viewport.name}`;
const runLabel = `message-visual-steer-${viewport.name}`;
const steerText =
diff --git a/e2e/specs/mock/model-replay-tools.spec.ts b/e2e/specs/mock/model-replay-tools.spec.ts
index d290073cd1..bd8daa6b18 100644
--- a/e2e/specs/mock/model-replay-tools.spec.ts
+++ b/e2e/specs/mock/model-replay-tools.spec.ts
@@ -58,13 +58,15 @@ const TOOL_PROMPT =
/** Enable the ephemeral MCP server whose tools this turn calls. */
async function selectEphemeralMCP(page: Page) {
- await page.getByRole('button', { name: 'MCP Servers', exact: true }).click();
- const serverItem = page.getByRole('menuitemcheckbox', { name: new RegExp(MCP_SERVER_TITLE) });
+ await page.getByRole('button', { name: 'Attach and tools' }).click();
+ const serverItem = page
+ .getByRole('dialog', { name: 'Attach and tools' })
+ .getByRole('button', { name: new RegExp(`^${MCP_SERVER_TITLE}\\b`) });
await expect(serverItem).toBeVisible();
await serverItem.click();
- await expect(serverItem).toHaveAttribute('aria-checked', 'true');
+ await expect(serverItem).toHaveAttribute('aria-pressed', 'true');
await page.keyboard.press('Escape');
- await expect(page.getByRole('button', { name: new RegExp(MCP_SERVER_TITLE) })).toBeVisible();
+ await expect(page.getByRole('listitem', { name: MCP_SERVER_TITLE, exact: true })).toBeVisible();
}
test.describe('recorded tool-call fixture replay', () => {
diff --git a/e2e/specs/mock/quotes.spec.ts b/e2e/specs/mock/quotes.spec.ts
index f3b776d2c7..480b46e2a0 100644
--- a/e2e/specs/mock/quotes.spec.ts
+++ b/e2e/specs/mock/quotes.spec.ts
@@ -25,7 +25,7 @@ type SelectionTarget = {
* Resolve a needle — or a pair of them spanning two messages — to a DOM Range
* inside the most recent `.message-render` containing it, optionally placing it
* on the document selection, and return the viewport midpoint of its first
- * character.
+ * word.
*
* The lookup matches each message's *flattened* text rather than one text node,
* because a needle is routinely spread over several: while a reply streams, the
@@ -110,11 +110,15 @@ function resolveSelection(page: Page, target: SelectionTarget) {
}
}
- const afterFirst = boundaryAt(head.runs, head.index + 1);
- const firstCharacter = document.createRange();
- firstCharacter.setStart(start.node, start.offset);
- firstCharacter.setEnd(afterFirst.node, afterFirst.offset);
- const box = firstCharacter.getBoundingClientRect();
+ const firstWord = from.match(/^\S+/)?.[0] ?? from;
+ const afterFirst = boundaryAt(head.runs, head.index + firstWord.length);
+ const wordRange = document.createRange();
+ wordRange.setStart(start.node, start.offset);
+ wordRange.setEnd(afterFirst.node, afterFirst.offset);
+ const box = [...wordRange.getClientRects()].find((rect) => rect.width > 0 && rect.height > 0);
+ if (!box) {
+ throw new Error(`No visible text rect contains: ${from}`);
+ }
return { x: box.x + box.width / 2, y: box.y + box.height / 2 };
}, target);
}
@@ -135,11 +139,13 @@ async function selectMessageText(page: Page, needle: string, emitMouseUp = true)
}
/**
- * Viewport coordinates of the first character of `needle` inside the most
- * recent message containing it. Measuring the `needle` text itself (not the
- * first text node in `.message-render`, which may be a `select-none`
+ * Viewport coordinates of the first word of `needle` inside the most
+ * recent message containing it. Measuring the `needle` text node itself (not
+ * the first text node in `.message-render`, which may be a `select-none`
* screen-reader/model-label header) keeps the gesture on the actual reply word,
- * not metadata or whitespace.
+ * not metadata or whitespace. The first whole word (not a one-character
+ * caret-edge range) keeps the click inside a glyph across font and layout
+ * differences.
*/
function measureNeedle(page: Page, needle: string) {
return resolveSelection(page, { from: needle });
@@ -285,7 +291,7 @@ function scrollSelectionTo(page: Page, needle: string, fraction: number) {
}
const addToChat = (page: Page) => page.getByTestId('add-to-chat-button');
-const pendingChips = (page: Page) => page.getByTestId('pending-quote-chips');
+const pendingChips = (page: Page) => page.getByTestId('composer-chip-quote');
const messageQuotes = (page: Page) => messagesView(page).getByTestId('message-quotes');
/** A phone's context options, minus `defaultBrowserType` — Playwright refuses
@@ -334,7 +340,7 @@ async function addQuote(page: Page, needle: string, expectedCount: number) {
const button = addToChat(page);
await expect(button).toBeVisible({ timeout: 3000 });
await button.click();
- await expect(pendingChips(page)).toHaveAttribute('data-quote-count', String(expectedCount));
+ await expect(pendingChips(page)).toHaveCount(expectedCount);
}).toPass({ timeout: 30000 });
}
@@ -395,7 +401,7 @@ test.describe('quote references', () => {
const button = addToChat(page);
await expect(button).toBeVisible({ timeout: 3000 });
await button.click();
- await expect(pendingChips(page)).toHaveAttribute('data-quote-count', '1');
+ await expect(pendingChips(page)).toHaveCount(1);
}).toPass({ timeout: 30000 });
// The quoted excerpt is a word from the reply, not empty.
@@ -419,7 +425,7 @@ test.describe('quote references', () => {
const button = addToChat(page);
await expect(button).toBeVisible({ timeout: 3000 });
await button.click();
- await expect(pendingChips(page)).toHaveAttribute('data-quote-count', '1');
+ await expect(pendingChips(page)).toHaveCount(1);
}).toPass({ timeout: 30000 });
// The excerpt is the closing paragraph itself, not the overhang.
@@ -573,12 +579,9 @@ test.describe('quote references', () => {
await expect(addToChat(page)).toBeHidden({ timeout: 5000 });
});
- test('collapses multiple selections into one chip with a hover popup, and removes one', async ({
- page,
- }) => {
+ test('stages each selection as its own chip in the tray, and removes one', async ({ page }) => {
test.setTimeout(120000);
const firstMessage = 'quote target alpha';
- const popup = page.getByTestId('quote-selections-popup');
await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
@@ -591,37 +594,31 @@ test.describe('quote references', () => {
await addQuote(page, MOCK_REPLY_TEXT, 1);
await addQuote(page, firstMessage, 2);
- // Composer shows a single collapsed "2 selections" chip, not a row of two.
- await expect(pendingChips(page)).toContainText('2 selections');
+ // The tray holds one chip per excerpt, each carrying its own text.
+ await expect(
+ pendingChips(page).filter({ hasText: new RegExp(MOCK_REPLY_TEXT, 'i') }),
+ ).toHaveCount(1);
+ await expect(pendingChips(page).filter({ hasText: firstMessage })).toHaveCount(1);
- // Hovering the collapsed chip reveals a popup listing every excerpt.
- await pendingChips(page).getByRole('listitem').hover();
- await expect(popup).toBeVisible({ timeout: 5000 });
- await expect(popup).toContainText(MOCK_REPLY_TEXT);
- await expect(popup).toContainText(firstMessage);
-
- // Remove the reply from the popup; one selection remains and collapses back
- // to its excerpt text.
- await popup
- .getByRole('listitem')
- .filter({ hasText: MOCK_REPLY_TEXT })
+ // Remove the reply's chip; the other excerpt stays staged.
+ await pendingChips(page)
+ .filter({ hasText: new RegExp(MOCK_REPLY_TEXT, 'i') })
.getByRole('button', { name: /remove quote/i })
.click();
- await expect(pendingChips(page)).toHaveAttribute('data-quote-count', '1');
+ await expect(pendingChips(page)).toHaveCount(1);
await expect(pendingChips(page)).toContainText(firstMessage);
- await expect(pendingChips(page)).not.toContainText(MOCK_REPLY_TEXT);
+ await expect(pendingChips(page)).not.toContainText(new RegExp(MOCK_REPLY_TEXT, 'i'));
// Send; only the remaining quote pins to the new user message.
const followUp = await sendMessage(page, 'expand on this');
expect(followUp.ok()).toBeTruthy();
await expect(messageQuotes(page)).toContainText(firstMessage);
- await expect(messageQuotes(page)).not.toContainText(MOCK_REPLY_TEXT);
+ await expect(messageQuotes(page)).not.toContainText(new RegExp(MOCK_REPLY_TEXT, 'i'));
});
- test('opens the selections popup via keyboard and closes on Escape', async ({ page }) => {
+ test('removes a staged quote via keyboard', async ({ page }) => {
test.setTimeout(120000);
const firstMessage = 'quote target beta';
- const popup = page.getByTestId('quote-selections-popup');
await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
@@ -632,26 +629,16 @@ test.describe('quote references', () => {
await addQuote(page, MOCK_REPLY_TEXT, 1);
await addQuote(page, firstMessage, 2);
- // The collapsed pill is a focusable disclosure: focus + Enter opens it.
- const trigger = pendingChips(page).getByRole('button', { name: '2 selections' });
- await trigger.focus();
- await expect(trigger).toBeFocused();
+ // Each chip's remove control is a real focusable button: focus + Enter
+ // removes just that excerpt without touching the pointer.
+ const removeButton = pendingChips(page)
+ .filter({ hasText: new RegExp(MOCK_REPLY_TEXT, 'i') })
+ .getByRole('button', { name: /remove quote/i });
+ await removeButton.focus();
+ await expect(removeButton).toBeFocused();
await page.keyboard.press('Enter');
- await expect(popup).toBeVisible({ timeout: 5000 });
- await expect(popup).toContainText(MOCK_REPLY_TEXT);
- await expect(popup).toContainText(firstMessage);
-
- // Opening via keyboard moves focus into the popup (first excerpt's remove ×).
- await expect(popup.getByRole('button').first()).toBeFocused();
-
- // Escape closes it and returns focus to the pill that opened it (NOT the
- // page top, the bug this guards against). `document.activeElement` must be
- // a real control.
- await page.keyboard.press('Escape');
- await expect(popup).toBeHidden();
- await expect(trigger).toBeFocused();
- const focusTag = await page.evaluate(() => document.activeElement?.tagName ?? 'NONE');
- expect(focusTag).not.toBe('BODY');
+ await expect(pendingChips(page)).toHaveCount(1);
+ await expect(pendingChips(page)).toContainText(firstMessage);
});
test('re-merges a persisted quote into later-turn history (durable)', async ({ page }) => {
@@ -701,7 +688,11 @@ test.describe('quote references on touch devices', () => {
/** Long-press equivalent: touch the text, then select it without any mouse event. */
async function touchSelect(page: Page, needle: string) {
- await messagesView(page).getByText(needle).scrollIntoViewIfNeeded();
+ await messagesView(page)
+ .locator('.message-render')
+ .filter({ hasText: needle })
+ .last()
+ .scrollIntoViewIfNeeded();
const point = await measureNeedle(page, needle);
/** Drop any earlier selection *before* the press. Chromium answers a
* synthetic tap with compatibility mouse events, and a leftover selection
@@ -737,9 +728,9 @@ test.describe('quote references on touch devices', () => {
expect(popup!.height).toBeGreaterThanOrEqual(44);
// Tapping has to commit before the tap dismisses the selection out from
- // under the click — the second reason this was unusable on a phone.
+ // under the click, the second reason this was unusable on a phone.
await addToChat(page).tap();
- await expect(pendingChips(page)).toHaveAttribute('data-quote-count', '1');
+ await expect(pendingChips(page)).toHaveCount(1);
await expect(pendingChips(page)).toContainText(CLOSING_PARAGRAPH);
});
@@ -757,7 +748,7 @@ test.describe('quote references on touch devices', () => {
const button = addToChat(page);
await expect(button).toBeVisible({ timeout: 5000 });
await button.tap();
- await expect(pendingChips(page)).toHaveAttribute('data-quote-count', '1');
+ await expect(pendingChips(page)).toHaveCount(1);
}).toPass({ timeout: 30000 });
// End to end from a finger: the mock model confirms the blockquote arrived.
diff --git a/e2e/specs/mock/run-files.spec.ts b/e2e/specs/mock/run-files.spec.ts
index c3a47fa0dd..1746580f0d 100644
--- a/e2e/specs/mock/run-files.spec.ts
+++ b/e2e/specs/mock/run-files.spec.ts
@@ -176,12 +176,16 @@ test.describe('run-scoped subagent files', () => {
expect(download.suggestedFilename()).toBe(outputName);
expect(await download.failure()).toBeNull();
- await page.getByTestId('nav-panel-files').click();
- const filesPanel = page.getByRole('region', { name: 'Files Table' });
- await filesPanel.locator('#filename-filter').fill(outputName);
- const reuse = filesPanel.locator('td[role="button"]').filter({ hasText: outputName });
+ /* Reuse goes through the composer palette, which searches every file the
+ user owns and attaches the chosen one to the draft. */
+ await page.getByRole('button', { name: 'Attach and tools' }).click();
+ const palette = page.getByRole('dialog', { name: 'Attach and tools' });
+ await palette
+ .getByRole('combobox', { name: 'Search tools, skills and servers', exact: true })
+ .fill(outputName);
+ const reuse = palette.locator(`[data-row-key="file:${published.file_id}"]`);
await expect(reuse).toHaveCount(1);
- await reuse.press('Enter');
+ await reuse.click();
await expect(
page.getByTestId('composer-surface').getByRole('button', { name: outputName, exact: true }),
).toBeVisible();
diff --git a/e2e/specs/mock/scenarios/composer-context.spec.ts b/e2e/specs/mock/scenarios/composer-context.spec.ts
new file mode 100644
index 0000000000..241618484e
--- /dev/null
+++ b/e2e/specs/mock/scenarios/composer-context.spec.ts
@@ -0,0 +1,194 @@
+import { expect, test } from '@playwright/test';
+import type { Page } from '@playwright/test';
+import type { TMessage } from 'librechat-data-provider';
+import {
+ MOCK_ENDPOINTS,
+ NEW_CHAT_PATH,
+ getAccessToken,
+ messagesView,
+ requestJson,
+ selectMockEndpoint,
+ sendMessageAndWaitForCompletion,
+ uniqueName,
+} from '../helpers';
+import { deleteConversations, deleteMessagesByConversation } from '../db';
+
+async function cleanupConversation(page: Page) {
+ const conversationId = /\/c\/([^/?]+)/.exec(page.url())?.[1];
+ if (conversationId == null || conversationId === 'new') {
+ return;
+ }
+ await deleteMessagesByConversation([conversationId]);
+ await deleteConversations([conversationId]);
+}
+
+async function uploadViaComposerPalette(
+ page: Page,
+ file: { name: string; mimeType: string; content: string },
+) {
+ await page.getByRole('button', { name: 'Attach and tools' }).click();
+ const palette = page.getByRole('dialog', { name: 'Attach and tools' });
+ const localUpload = palette.getByRole('button', {
+ name: /^(From Local Computer|Upload to Provider)$/,
+ });
+ await expect(localUpload).toBeVisible();
+
+ const [fileChooser] = await Promise.all([page.waitForEvent('filechooser'), localUpload.click()]);
+ const uploadResponse = page.waitForResponse(
+ (response) =>
+ new URL(response.url()).pathname === '/api/files' && response.request().method() === 'POST',
+ { timeout: 30000 },
+ );
+ await fileChooser.setFiles({
+ name: file.name,
+ mimeType: file.mimeType,
+ buffer: Buffer.from(file.content, 'utf8'),
+ });
+ return uploadResponse;
+}
+
+test.describe('composer context', () => {
+ test('selecting a built-in tool leaves a removable active chip @scenario:selected-tool-shows-as-an-active-composer-chip', async ({
+ page,
+ }) => {
+ test.setTimeout(90000);
+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
+
+ const palette = page.getByRole('button', { name: 'Attach and tools' });
+ await palette.click();
+ const dialog = page.getByRole('dialog', { name: 'Attach and tools' });
+ const memoryRow = dialog.getByRole('button', { name: 'Memory', exact: true });
+ await expect(memoryRow).toBeVisible();
+ await memoryRow.click();
+ await expect(memoryRow).toHaveAttribute('aria-pressed', 'true');
+
+ const activeChip = page.getByTestId('composer-active-builtin').filter({ hasText: 'Memory' });
+ await expect(activeChip).toBeVisible();
+ await page.keyboard.press('Escape');
+ await expect(dialog).toBeHidden();
+ await expect(activeChip).toContainText('Memory');
+
+ await activeChip.getByRole('button', { name: 'Remove Memory', exact: true }).click();
+ await expect(activeChip).toBeHidden();
+
+ await palette.click();
+ const reopenedDialog = page.getByRole('dialog', { name: 'Attach and tools' });
+ await expect(
+ reopenedDialog.getByRole('button', { name: 'Memory', exact: true }),
+ ).toHaveAttribute('aria-pressed', 'false');
+ });
+
+ test('attached files stage in the tray and only retained files ride with the message @scenario:attached-file-stages-in-the-tray-and-rides-with-the-message', async ({
+ page,
+ }) => {
+ test.setTimeout(120000);
+ try {
+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
+ await selectMockEndpoint(page, MOCK_ENDPOINTS[1]);
+
+ const retainedName = `${uniqueName('retained')}.md`;
+ const removedName = `${uniqueName('removed')}.md`;
+ const tray = page.getByTestId('composer-tray');
+
+ const retainedUpload = await uploadViaComposerPalette(page, {
+ name: retainedName,
+ mimeType: 'text/markdown',
+ content: '# retained staged file\n',
+ });
+ expect(retainedUpload.ok()).toBeTruthy();
+ await expect(tray).toBeVisible();
+ await expect(tray.getByRole('button', { name: retainedName, exact: true })).toBeVisible();
+
+ const removedUpload = await uploadViaComposerPalette(page, {
+ name: removedName,
+ mimeType: 'text/markdown',
+ content: '# removed before send\n',
+ });
+ expect(removedUpload.ok()).toBeTruthy();
+ await expect(tray.getByRole('button', { name: removedName, exact: true })).toBeVisible();
+
+ const removedCard = tray
+ .getByRole('button', { name: removedName, exact: true })
+ .locator('..');
+ await removedCard.getByRole('button', { name: 'Remove file', exact: true }).click();
+ await expect(tray.getByRole('button', { name: removedName, exact: true })).toBeHidden();
+ await expect(tray.getByRole('button', { name: retainedName, exact: true })).toBeVisible();
+
+ await sendMessageAndWaitForCompletion(page, 'E2E retained staged attachment');
+ await expect(
+ messagesView(page).getByRole('button', { name: retainedName, exact: true }),
+ ).toBeVisible();
+ await expect(
+ messagesView(page).getByRole('button', { name: removedName, exact: true }),
+ ).toHaveCount(0);
+
+ const conversationId = /\/c\/([^/?]+)/.exec(page.url())?.[1];
+ expect(conversationId, 'sent attachment conversation should have an id').toBeTruthy();
+ const messages = await requestJson<TMessage[]>(page, {
+ path: `/api/messages/${encodeURIComponent(conversationId as string)}`,
+ token: await getAccessToken(page),
+ });
+ const sentUserMessages = messages.filter((message) => message.isCreatedByUser === true);
+ const sentMessage = sentUserMessages[sentUserMessages.length - 1];
+ expect(sentMessage, 'the sent user message should persist').toBeDefined();
+ const sentFiles = [
+ ...(sentMessage?.files ?? []),
+ ...(sentMessage?.attachments ?? []),
+ ] as Array<{ filename?: string }>;
+ expect(sentFiles.map((file) => file.filename)).toContain(retainedName);
+ expect(sentFiles.map((file) => file.filename)).not.toContain(removedName);
+ } finally {
+ await cleanupConversation(page);
+ }
+ });
+
+ test('thinking selection applies to one turn and then resolves back to default @scenario:per-turn-thinking-level-applies-to-the-next-turn-only', async ({
+ page,
+ }) => {
+ test.setTimeout(120000);
+ try {
+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
+ // Mock Provider A resolves the custom endpoint to Anthropic's adaptive
+ // `effort` setting, so the composer renders the compact effort slider.
+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
+
+ const thinkingButton = page.getByRole('button', { name: /^Thinking: / });
+ await expect(thinkingButton).toBeVisible();
+ const resolvedDefaultLabel = await thinkingButton.getAttribute('aria-label');
+ expect(resolvedDefaultLabel).toBeTruthy();
+
+ await thinkingButton.click();
+ const thinkingDialog = page.getByRole('dialog', { name: /^Thinking: / });
+ await expect(thinkingDialog).toBeVisible();
+ const thinkingMax = thinkingDialog.getByRole('radio', { name: 'Max', exact: true });
+ await thinkingMax.click();
+ await expect(thinkingButton).not.toHaveAttribute('aria-label', resolvedDefaultLabel!);
+ await page.keyboard.press('Escape');
+
+ const firstRequestPromise = page.waitForRequest(
+ (request) => request.url().includes('/api/agents/chat') && request.method() === 'POST',
+ );
+ await sendMessageAndWaitForCompletion(page, 'E2E first scoped thinking turn');
+ const firstBody = (await firstRequestPromise).postDataJSON() as {
+ reasoningOverride?: { key?: string; value?: string };
+ };
+ expect(firstBody.reasoningOverride).toEqual(
+ expect.objectContaining({ key: 'effort', value: 'max' }),
+ );
+ await expect(thinkingButton).toHaveAttribute('aria-label', resolvedDefaultLabel!);
+
+ const secondRequestPromise = page.waitForRequest(
+ (request) => request.url().includes('/api/agents/chat') && request.method() === 'POST',
+ );
+ await sendMessageAndWaitForCompletion(page, 'E2E second default thinking turn');
+ const secondBody = (await secondRequestPromise).postDataJSON() as {
+ reasoningOverride?: unknown;
+ };
+ expect(secondBody.reasoningOverride).toBeUndefined();
+ await expect(thinkingButton).toHaveAttribute('aria-label', resolvedDefaultLabel!);
+ } finally {
+ await cleanupConversation(page);
+ }
+ });
+});
diff --git a/e2e/specs/mock/scenarios/composer-defaults.spec.ts b/e2e/specs/mock/scenarios/composer-defaults.spec.ts
new file mode 100644
index 0000000000..80f26031fe
--- /dev/null
+++ b/e2e/specs/mock/scenarios/composer-defaults.spec.ts
@@ -0,0 +1,171 @@
+import { expect, test } from '@playwright/test';
+import type { Page, Response } from '@playwright/test';
+import {
+ NEW_CHAT_PATH,
+ messagesView,
+ replyPrompt,
+ replyText,
+ selectMockEndpoint,
+ sendMessage,
+} from '../helpers';
+
+const MCP_SERVER_TITLE = 'E2E Memory';
+const PROVIDER_C = { label: 'Mock Provider C', model: 'mock-model-c' };
+
+const messageInput = (page: Page) => page.getByRole('textbox', { name: 'Message input' });
+const duringRunSendButton = (page: Page) => page.getByTestId('during-run-send-button');
+const uniqueLabel = (prefix: string) =>
+ `${prefix}-${Date.now()}-${Math.floor(Math.random() * 1e4)}`;
+
+function isSteerRequest(response: Response) {
+ return (
+ response.request().method() === 'POST' &&
+ new URL(response.url()).pathname === '/api/agents/chat/steer'
+ );
+}
+
+async function selectEphemeralMCP(page: Page) {
+ await page.getByRole('button', { name: 'Attach and tools' }).click();
+ const serverItem = page
+ .getByRole('dialog', { name: 'Attach and tools' })
+ .getByRole('button', { name: new RegExp(`^${MCP_SERVER_TITLE}\\b`) });
+ await expect(serverItem).toBeVisible();
+ await serverItem.click();
+ await expect(serverItem).toHaveAttribute('aria-pressed', 'true');
+ await page.keyboard.press('Escape');
+ await expect(page.getByRole('listitem', { name: MCP_SERVER_TITLE, exact: true })).toBeVisible();
+}
+
+async function establishConversation(page: Page, label: string) {
+ const setup = await sendMessage(page, replyPrompt(label));
+ expect(setup.ok()).toBeTruthy();
+ await expect(messagesView(page).getByText(replyText(label))).toBeVisible({ timeout: 30000 });
+ await expect(page).toHaveURL(/\/c\/[0-9a-fA-F-]{36}$/, { timeout: 15000 });
+}
+
+/**
+ * These tests need one thing from the sidebar: the account menu. On a narrow
+ * viewport that lives inside the mobile drawer, which stays mounted and keeps
+ * its layout box when closed, so `inert` is the only signal that tells the two
+ * states apart. Desktop renders no drawer and its panel is always there.
+ *
+ * The layout is read from the viewport, not from whether the drawer exists:
+ * the first render runs before the app's media query resolves, so an early
+ * probe finds no drawer and would take the desktop branch on a phone.
+ *
+ * Deliberately not `ensureSidebarOnScreen`: that helper also settles the Pinned
+ * section's placement for the pinned specs, and a run where an earlier test
+ * left a pinned conversation made these two wait 15s on a region they never
+ * touch.
+ */
+async function openAccountMenuHost(page: Page) {
+ if ((page.viewportSize()?.width ?? 1280) > 768) {
+ return;
+ }
+ const drawer = page.locator('#mobile-drawer');
+ await expect(drawer).toBeAttached();
+ /* While open the opener is labelled "Close sidebar", so a retried click can
+ never toggle the drawer back shut. */
+ await expect(async () => {
+ if (await drawer.evaluate((element) => element.hasAttribute('inert'))) {
+ await page.getByRole('button', { name: 'Open sidebar' }).click({ timeout: 2_000 });
+ }
+ await expect(drawer).not.toHaveAttribute('inert', /.*/, { timeout: 2_000 });
+ }).toPass({ timeout: 15_000 });
+}
+
+test.describe('composer defaults', () => {
+ test('file manager opens from the account menu @scenario:file-manager-opens-from-the-account-menu', async ({
+ page,
+ }) => {
+ test.setTimeout(60000);
+
+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
+ await openAccountMenuHost(page);
+ const accountMenuButton =
+ (page.viewportSize()?.width ?? 1280) <= 768
+ ? page.locator('#mobile-drawer').getByTestId('nav-user')
+ : page.getByTestId('nav-user');
+ await expect(accountMenuButton).toBeVisible();
+ await accountMenuButton.click();
+
+ const accountMenu = page.getByRole('menu');
+ const filesItem = accountMenu.getByRole('menuitem', { name: 'My Files', exact: true });
+ await expect(filesItem).toBeVisible();
+ await filesItem.click();
+ await expect(page.getByRole('dialog', { name: 'My Files' })).toHaveCount(1);
+ });
+
+ test('closing the file manager returns focus to its opener @scenario:closing-the-file-manager-returns-focus-to-its-opener', async ({
+ page,
+ }) => {
+ test.setTimeout(60000);
+
+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
+ await openAccountMenuHost(page);
+ const accountMenuButton =
+ (page.viewportSize()?.width ?? 1280) <= 768
+ ? page.locator('#mobile-drawer').getByTestId('nav-user')
+ : page.getByTestId('nav-user');
+ await expect(accountMenuButton).toBeVisible();
+ await accountMenuButton.click();
+
+ const filesItem = page
+ .getByRole('menu')
+ .getByRole('menuitem', { name: 'My Files', exact: true });
+ await expect(filesItem).toBeVisible();
+ await filesItem.click();
+
+ const dialog = page.getByRole('dialog', { name: 'My Files' });
+ await expect(dialog).toHaveCount(1);
+
+ /** The menu that held the opener is gone by the time the dialog captures
+ * focus, so without an explicit opener the close lands on the body and a
+ * keyboard user loses their place in the sidebar. */
+ await page.keyboard.press('Escape');
+ await expect(dialog).toHaveCount(0);
+ await expect(accountMenuButton).toBeFocused();
+ });
+
+ test('Enter during a run steers the current reply by default @scenario:enter-during-a-run-steers-the-current-reply-by-default', async ({
+ page,
+ }) => {
+ test.setTimeout(150000);
+ const label = uniqueLabel('default-steer');
+ const steerText = `Default steer ${label}`;
+
+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
+ await selectMockEndpoint(page, PROVIDER_C);
+ await selectEphemeralMCP(page);
+ await establishConversation(page, `default-steer-setup-${label}`);
+
+ const run = await sendMessage(page, `E2E_STEER_TOOL_REPLY:${label}`);
+ expect(run.ok()).toBeTruthy();
+ const input = messageInput(page);
+ await input.fill(steerText);
+ await expect(duringRunSendButton(page)).toBeVisible({ timeout: 5000 });
+ await expect(duringRunSendButton(page)).toHaveAttribute('data-during-run-action', 'steer');
+
+ const [steerResponse] = await Promise.all([
+ page.waitForResponse(isSteerRequest, { timeout: 15000 }),
+ input.press('Enter'),
+ ]);
+ expect(steerResponse.status()).toBe(202);
+ await expect(page.getByTestId('pending-steers').filter({ hasText: steerText })).toHaveCount(1, {
+ timeout: 10000,
+ });
+ await expect(
+ messagesView(page)
+ .locator('[data-testid="steer-part"]:not([data-testid="pending-steers"] *)')
+ .filter({
+ hasText: steerText,
+ }),
+ ).toHaveCount(1, { timeout: 60000 });
+ await expect(messagesView(page).getByText(`E2E steer tool reply done ${label}`)).toBeVisible({
+ timeout: 60000,
+ });
+ await expect(messagesView(page).getByText(`[steers-seen=1] ${steerText}`)).toBeVisible({
+ timeout: 30000,
+ });
+ });
+});
diff --git a/e2e/specs/mock/scenarios/composer-numeric-reasoning.spec.ts b/e2e/specs/mock/scenarios/composer-numeric-reasoning.spec.ts
new file mode 100644
index 0000000000..f39dd8470c
--- /dev/null
+++ b/e2e/specs/mock/scenarios/composer-numeric-reasoning.spec.ts
@@ -0,0 +1,71 @@
+import { expect, test } from '@playwright/test';
+import {
+ messagesView,
+ MOCK_ENDPOINTS,
+ NEW_CHAT_PATH,
+ selectMockEndpoint,
+ sendMessage,
+} from '../helpers';
+
+test('Inspecting numeric reasoning preserves Auto and steering @scenario:inspecting-numeric-reasoning-preserves-auto-and-steering', async ({
+ page,
+}) => {
+ await page.route('**/api/endpoints', async (route) => {
+ const response = await route.fetch();
+ const endpoints = await response.json();
+ endpoints['Mock Provider A'].customParams = {
+ defaultParamsEndpoint: 'google',
+ paramDefinitions: [
+ {
+ key: 'thinkingBudget',
+ type: 'number',
+ default: -1,
+ range: { min: -1, positiveMin: 128, max: 32768, step: 128 },
+ },
+ ],
+ };
+ await route.fulfill({ response, json: endpoints });
+ });
+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
+ const response = await sendMessage(page, `E2E_SLOW_REPLY:numeric-reasoning-${Date.now()}`);
+ expect(response.ok()).toBeTruthy();
+ await expect(messagesView(page).getByText('chunk-010')).toBeVisible({ timeout: 15000 });
+
+ const input = page.getByRole('textbox', { name: 'Message input' });
+ await input.fill('Keep steering after inspecting Auto');
+ const send = page.getByTestId('during-run-send-button');
+ await expect(send).toHaveAttribute('data-during-run-action', 'steer');
+ const reasoning = page.getByRole('button', { name: /Reasoning for next message.*Auto/i });
+ await reasoning.click();
+ const budget = page.getByRole('spinbutton');
+ await expect(budget).toHaveValue('');
+ await budget.focus();
+ await page.keyboard.press('Tab');
+ await expect(page.getByRole('button', { name: 'Auto', exact: true })).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ );
+ await page.keyboard.press('Escape');
+ await expect(reasoning).toBeFocused();
+ await expect(send).toHaveAttribute('data-during-run-action', 'steer');
+ await expect(input).toHaveValue('Keep steering after inspecting Auto');
+
+ await reasoning.click();
+ await budget.fill('4096');
+ await page.keyboard.press('Tab');
+ await expect(page.getByRole('button', { name: 'Auto', exact: true })).toHaveAttribute(
+ 'aria-pressed',
+ 'false',
+ );
+ await budget.fill('');
+ await page.keyboard.press('Tab');
+ await expect(page.getByRole('button', { name: 'Auto', exact: true })).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ );
+ await expect(budget).toHaveValue('');
+ await page.keyboard.press('Escape');
+ await input.clear();
+ await page.getByRole('button', { name: 'Stop generating' }).click();
+});
diff --git a/e2e/specs/mock/scenarios/composer-palette.spec.ts b/e2e/specs/mock/scenarios/composer-palette.spec.ts
new file mode 100644
index 0000000000..8ac80237a3
--- /dev/null
+++ b/e2e/specs/mock/scenarios/composer-palette.spec.ts
@@ -0,0 +1,250 @@
+import { expect, test } from '@playwright/test';
+import type { Page } from '@playwright/test';
+import AxeBuilder from '@axe-core/playwright';
+import {
+ MOCK_ENDPOINTS,
+ NEW_CHAT_PATH,
+ getAccessToken,
+ requestJson,
+ selectMockEndpoint,
+} from '../helpers';
+
+const PALETTE_NAME = 'Attach and tools';
+const SEARCH_NAME = 'Search tools, skills and servers';
+const FAVORITE_SECTION = 'Favorites';
+const TOOL_FAVORITE_PATH = '/api/user/settings/favorites/tools/builtin/execute_code';
+
+const paletteButton = (page: Page) => page.getByRole('button', { name: PALETTE_NAME });
+const palette = (page: Page) => page.getByRole('dialog', { name: PALETTE_NAME });
+const paletteRows = (page: Page) => palette(page).locator('[data-row-key]');
+const paletteSearch = (page: Page) =>
+ palette(page).getByRole('combobox', { name: SEARCH_NAME, exact: true });
+
+async function openPalette(page: Page) {
+ await expect(paletteButton(page)).toBeVisible();
+ await paletteButton(page).click();
+ await expect(palette(page)).toBeVisible();
+ await expect(paletteSearch(page)).toBeVisible();
+}
+
+/**
+ * The catalog arrives in waves: built-in tools paint with the dialog, the MCP
+ * server list is released by the app-wide warmup timer, and the skills catalog
+ * only starts fetching once the dialog's open effect has run. Counting rows the
+ * moment the dialog appears therefore snapshots a partial catalog, and the row
+ * count keeps climbing underneath the test.
+ *
+ * Wait for the last wave to land, then for the count to hold still across
+ * consecutive reads, and return that settled total.
+ */
+async function settledRowCount(page: Page): Promise<number> {
+ const mcpSection = palette(page).getByRole('columnheader', {
+ name: 'MCP Servers',
+ exact: true,
+ });
+ await expect(mcpSection).toBeVisible({ timeout: 20000 });
+ const rows = paletteRows(page);
+ let previous = -1;
+ let stableReads = 0;
+ await expect
+ .poll(
+ async () => {
+ const current = await rows.count();
+ stableReads = current === previous ? stableReads + 1 : 0;
+ previous = current;
+ return stableReads;
+ },
+ { timeout: 20000, intervals: [300] },
+ )
+ .toBeGreaterThanOrEqual(3);
+ return previous;
+}
+
+async function selectMockChat(page: Page) {
+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
+ await expect(page.getByRole('textbox', { name: 'Message input' })).toBeVisible();
+}
+
+test.describe('composer palette', () => {
+ test('opens one searchable catalog with attach and tool sections @scenario:palette-opens-one-searchable-catalog', async ({
+ page,
+ }) => {
+ test.setTimeout(60000);
+ await selectMockChat(page);
+ await openPalette(page);
+
+ await expect(page.getByRole('dialog')).toHaveCount(1);
+ await expect(
+ palette(page).getByRole('columnheader', { name: 'Attach', exact: true }),
+ ).toBeVisible();
+ await expect(
+ palette(page).getByRole('columnheader', { name: 'Tools', exact: true }),
+ ).toBeVisible();
+ await expect(
+ palette(page).getByRole('button', { name: 'Upload to Provider', exact: true }),
+ ).toBeVisible();
+ await expect(
+ palette(page).getByRole('button', { name: 'Run Code', exact: true }),
+ ).toBeVisible();
+ await expect(
+ palette(page).getByRole('button', { name: 'File Search', exact: true }),
+ ).toBeVisible();
+
+ /* Skills and MCP sections depend on the permissions and catalog state supplied
+ by the deployment. When present, they are rows in this same dialog rather
+ than separate surfaces. */
+ const skillsSection = palette(page).getByRole('columnheader', { name: 'Skills', exact: true });
+ if ((await skillsSection.count()) > 0) {
+ await expect(skillsSection).toBeVisible();
+ }
+ const mcpSection = palette(page).getByRole('columnheader', {
+ name: 'MCP Servers',
+ exact: true,
+ });
+ if ((await mcpSection.count()) > 0) {
+ await expect(mcpSection).toBeVisible();
+ }
+
+ /* Removed redesign surfaces must be absent from the active palette, not merely
+ absent under a legacy test id. */
+ await expect(
+ palette(page).getByRole('button', { name: 'Tools Options', exact: true }),
+ ).toHaveCount(0);
+ await expect(page.getByRole('dialog', { name: 'Select Upload Type', exact: true })).toHaveCount(
+ 0,
+ );
+ await expect(page.getByRole('menu')).toHaveCount(0);
+ });
+
+ test('search narrows the visible rows and clearing restores the catalog @scenario:palette-search-narrows-to-matching-rows', async ({
+ page,
+ }) => {
+ test.setTimeout(60000);
+ await selectMockChat(page);
+ await openPalette(page);
+
+ const rows = paletteRows(page);
+ const fullCatalogCount = await settledRowCount(page);
+ expect(fullCatalogCount).toBeGreaterThan(3);
+
+ await paletteSearch(page).fill('Run Code');
+ await expect(
+ palette(page).getByRole('button', { name: 'Run Code', exact: true }),
+ ).toBeVisible();
+ await expect(
+ palette(page).getByRole('button', { name: 'File Search', exact: true }),
+ ).toHaveCount(0);
+ await expect.poll(() => rows.count()).toBeLessThan(fullCatalogCount);
+
+ await paletteSearch(page).fill('');
+ await expect.poll(() => rows.count()).toBe(fullCatalogCount);
+ await expect(
+ palette(page).getByRole('button', { name: 'File Search', exact: true }),
+ ).toBeVisible();
+ });
+
+ test('favourited palette row moves to favourites and persists after reload @scenario:favourited-palette-row-moves-to-favourites-and-persists', async ({
+ page,
+ }) => {
+ test.setTimeout(60000);
+ await selectMockChat(page);
+ const token = await getAccessToken(page);
+
+ /* The shared e2e user may retain state from a prior interrupted run. Remove
+ this one known row first, then prove the UI's own write survives reload. */
+ await requestJson(page, { path: TOOL_FAVORITE_PATH, token, method: 'DELETE' });
+
+ try {
+ await page.reload({ timeout: 10000 });
+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
+ await openPalette(page);
+ await paletteSearch(page).fill('Run Code');
+
+ const runCode = palette(page).getByRole('button', { name: 'Run Code', exact: true });
+ await expect(runCode).toBeVisible();
+ await page.keyboard.press('Control+d');
+
+ await expect(
+ palette(page).getByRole('button', { name: 'Remove from favorites', exact: true }),
+ ).toBeVisible();
+ await expect(
+ palette(page).getByRole('button', { name: 'Run Code, Favorites', exact: true }),
+ ).toBeVisible();
+ await paletteSearch(page).fill('');
+ await expect(
+ palette(page).getByRole('columnheader', { name: FAVORITE_SECTION, exact: true }),
+ ).toBeVisible();
+ await expect(
+ palette(page).getByRole('button', { name: 'Run Code, Favorites', exact: true }),
+ ).toBeVisible();
+
+ await page.reload({ timeout: 10000 });
+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
+ await openPalette(page);
+ await expect(
+ palette(page).getByRole('columnheader', { name: FAVORITE_SECTION, exact: true }),
+ ).toBeVisible();
+ await expect(
+ palette(page).getByRole('button', { name: 'Run Code, Favorites', exact: true }),
+ ).toBeVisible();
+ } finally {
+ await requestJson(page, { path: TOOL_FAVORITE_PATH, token, method: 'DELETE' });
+ }
+ });
+
+ test('open palette has no detectable accessibility violations @scenario:open-palette-has-no-accessibility-violations', async ({
+ page,
+ }) => {
+ test.setTimeout(60000);
+ await selectMockChat(page);
+ await openPalette(page);
+ await settledRowCount(page);
+
+ const results = await new AxeBuilder({ page })
+ .include('[role="dialog"][aria-label="Attach and tools"]')
+ .analyze();
+
+ expect(results.violations).toEqual([]);
+ });
+
+ test('palette is operable from the keyboard alone @scenario:palette-is-operable-from-the-keyboard-alone', async ({
+ page,
+ }) => {
+ test.setTimeout(60000);
+ await selectMockChat(page);
+
+ const messageInput = page.getByRole('textbox', { name: 'Message input' });
+ await messageInput.focus();
+ await expect(messageInput).toBeFocused();
+ await page.keyboard.press('Tab');
+ await expect(paletteButton(page)).toBeFocused();
+ await page.keyboard.press('Enter');
+
+ await expect(palette(page)).toBeVisible();
+ await expect(paletteSearch(page)).toBeFocused();
+ // Search for the code capability: this lab exposes Run Code (the passing
+ // catalog scenarios use the same row), while "search" initially selected
+ // Web Search and opened its provider configuration dialog.
+ await page.keyboard.type('code');
+ const runCode = palette(page).getByRole('button', { name: 'Run Code', exact: true });
+ await expect(runCode).toBeVisible();
+ const initialActive = await paletteSearch(page).getAttribute('aria-activedescendant');
+ await page.keyboard.press('ArrowDown');
+ const movedActive = await paletteSearch(page).getAttribute('aria-activedescendant');
+ expect(movedActive).not.toBe(initialActive);
+ await page.keyboard.press('Enter');
+
+ await expect(runCode).toHaveAttribute('aria-pressed', 'true');
+ await expect(
+ page.getByTestId('composer-active-builtin').filter({ hasText: 'Run Code' }),
+ ).toBeVisible();
+
+ await page.keyboard.press('Escape');
+ await expect(palette(page)).toBeHidden();
+ /* The close was a key press, so focus returns to the message field on every
+ * project, a touch-primary one included: only a touch or pen close leaves
+ * it alone, to keep the on-screen keyboard from rising again. */
+ await expect(messageInput).toBeFocused();
+ });
+});
diff --git a/e2e/specs/mock/scenarios/composer-pane-controls.spec.ts b/e2e/specs/mock/scenarios/composer-pane-controls.spec.ts
new file mode 100644
index 0000000000..b3b7206d29
--- /dev/null
+++ b/e2e/specs/mock/scenarios/composer-pane-controls.spec.ts
@@ -0,0 +1,240 @@
+import { expect, test } from '@playwright/test';
+import type { Page } from '@playwright/test';
+import { cleanupAgent, openAgentBuilder, uniqueAgentName } from '../agents.helpers';
+import {
+ MOCK_ENDPOINTS,
+ NEW_CHAT_PATH,
+ fetchJson,
+ getAccessToken,
+ requestJson,
+ selectMockEndpoint,
+ sendMessage,
+} from '../helpers';
+
+type AgentResponse = { id: string };
+
+/**
+ * The app currently mounts one ChatView/ChatForm (`ChatRoute.tsx:64`,
+ * `ChatRoute.tsx:356-357`). The runtime contract therefore exercises the
+ * pane-scoped shortcut through the one real pane's portaled palette rather than
+ * pretending that the added-conversation response columns are independent
+ * composers.
+ */
+test('stops a run from a portaled composer control @scenario:stop-from-a-portaled-composer-control-aborts-the-run', async ({
+ page,
+}) => {
+ test.setTimeout(120000);
+
+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
+
+ const label = `portaled-stop-${Date.now()}-${Math.floor(Math.random() * 1e4)}`;
+ const messages = page.getByTestId('messages-view');
+ const partialReply = messages
+ .locator('.message-render')
+ .filter({ hasText: `E2E slow reply ${label}` })
+ .first();
+ const run = await sendMessage(page, `E2E_SLOW_REPLY:${label}`);
+ expect(run.ok()).toBeTruthy();
+ // Match the queue scenarios' stable mid-stream barrier before inspecting the
+ // assistant turn: the fake model's marker is emitted before the full reply.
+ await expect(messages.getByText('chunk-010')).toBeVisible({ timeout: 15000 });
+
+ /*
+ The effort popover is portaled out of the composer pane. Keep focus on one
+ of its radios, then use the pane's own Stop control: the global shortcut
+ dispatcher intentionally suppresses all role="dialog" surfaces.
+ */
+ const thinkingButton = page.getByRole('button', { name: /^Thinking: / });
+ await thinkingButton.click();
+ const thinkingPopover = page.getByRole('dialog', { name: /^Thinking: / });
+ await expect(thinkingPopover).toBeVisible();
+ const thinkingRadio = thinkingPopover.getByRole('radio', { name: 'Medium', exact: true });
+ await thinkingRadio.focus();
+ await expect(thinkingRadio).toBeFocused();
+
+ const stopButton = page.getByTestId('stop-generation-button');
+ await expect(stopButton).toBeVisible();
+ const [abortResponse] = await Promise.all([
+ page.waitForResponse(
+ (response) =>
+ response.request().method() === 'POST' &&
+ new URL(response.url()).pathname.endsWith('/api/agents/chat/abort'),
+ { timeout: 30000 },
+ ),
+ stopButton.click(),
+ ]);
+ expect(abortResponse.ok()).toBeTruthy();
+
+ await expect(page.getByTestId('stop-generation-button')).toBeHidden({ timeout: 30000 });
+ /* Idle means Stop is gone and Send is restored; an empty composer keeps Send disabled. */
+ await expect(page.getByTestId('send-button')).toBeVisible({ timeout: 30000 });
+
+ /* Wait for the stream to become stable, then prove no later chunk is appended. */
+ let stableText = '';
+ await expect
+ .poll(
+ async () => {
+ const first = await partialReply.textContent();
+ await page.waitForTimeout(750);
+ const second = await partialReply.textContent();
+ if (first === second) {
+ stableText = second ?? '';
+ return true;
+ }
+ return false;
+ },
+ { timeout: 30000, intervals: [250, 500, 1000] },
+ )
+ .toBe(true);
+ expect(stableText).toContain(`E2E slow reply ${label}`);
+});
+
+const MCP_SERVER_NAME = 'e2e-memory';
+const APPROVAL_TOOL_ID = `approval_probe_mcp_${MCP_SERVER_NAME}`;
+
+type MCPToolsResponse = {
+ servers?: Record<string, { tools?: Array<{ pluginKey: string }> }>;
+};
+
+async function waitForApprovalTool(page: Page) {
+ const token = await getAccessToken(page);
+ let latestTools: MCPToolsResponse | null = null;
+ for (let attempt = 0; attempt < 20; attempt++) {
+ latestTools = await fetchJson<MCPToolsResponse>(page, '/api/mcp/tools', token);
+ const tools = latestTools.servers?.[MCP_SERVER_NAME]?.tools ?? [];
+ if (tools.some((tool) => tool.pluginKey === APPROVAL_TOOL_ID)) {
+ return;
+ }
+ await page.waitForTimeout(500);
+ }
+ expect(latestTools?.servers?.[MCP_SERVER_NAME]?.tools).toEqual(
+ expect.arrayContaining([expect.objectContaining({ pluginKey: APPROVAL_TOOL_ID })]),
+ );
+}
+
+async function createApprovalAgent(page: Page, name: string): Promise<AgentResponse> {
+ const token = await getAccessToken(page);
+ return requestJson<AgentResponse>(page, {
+ path: '/api/agents',
+ token,
+ method: 'POST',
+ body: {
+ name,
+ description: 'Exercises the composer-bar approval control in mock e2e.',
+ instructions: 'Use the approval probe when asked.',
+ provider: MOCK_ENDPOINTS[0].label,
+ model: MOCK_ENDPOINTS[0].model,
+ tools: [`sys__server__sys_mcp_${MCP_SERVER_NAME}`, APPROVAL_TOOL_ID],
+ },
+ });
+}
+
+async function selectAgent(page: Page, agentName: string) {
+ const form = await openAgentBuilder(page);
+ await form.getByRole('combobox', { name: 'Agent', exact: true }).click();
+ await page.getByRole('option', { name: agentName }).click();
+ await expect(form.getByLabel('Agent name')).toHaveValue(agentName);
+ await form.getByRole('button', { name: 'Select Agent' }).click();
+ await expect(page.getByRole('textbox', { name: 'Message input' })).toBeVisible();
+}
+
+/**
+ * The composer-hosted Review panel/chip is intentionally not asserted here.
+ * On the first turn, the pending-approval atom is keyed by the run's durable
+ * conversation id while the composer remains bound to the new-chat sentinel
+ * through the pause, in code identical to origin/dev. Mirroring the write onto
+ * the sentinel did not surface that panel either, so the timeline approval
+ * card is the reliable approval surface for this scenario.
+ */
+test('resumes a pending tool approval with the composer usable @scenario:pending-tool-approval-resumes-the-run-with-the-composer-usable', async ({
+ page,
+}) => {
+ test.setTimeout(120000);
+ const agentName = uniqueAgentName('E2E composer approval');
+ let agentId: string | undefined;
+ const label = `composer-approval-${Date.now()}-${Math.floor(Math.random() * 1e4)}`;
+
+ try {
+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
+ await waitForApprovalTool(page);
+ const agent = await createApprovalAgent(page, agentName);
+ agentId = agent.id;
+ await selectAgent(page, agentName);
+ if ((page.viewportSize()?.width ?? 0) <= 768) {
+ /* Agent Builder lives in the mobile drawer; close it before returning to
+ * the full-bleed composer so the drawer cannot intercept composer input. */
+ await page.getByRole('button', { name: 'Close sidebar', exact: true }).click();
+ await expect(page.locator('#mobile-drawer')).toHaveAttribute('inert', /.*/);
+ }
+ const response = await sendMessage(page, `E2E_TOOL_APPROVAL:${label}`);
+ expect(response.ok()).toBeTruthy();
+ await expect(page).toHaveURL(/\/c\/(?!new)/, { timeout: 15000 });
+
+ const messages = page.getByTestId('messages-view');
+ const approval = messages.getByTestId('tool-approval').first();
+ await expect(approval).toBeVisible({ timeout: 30000 });
+ await expect(approval).toContainText(
+ `E2E approval required before running ${APPROVAL_TOOL_ID}.`,
+ );
+
+ /* The paused run must not disable the composer's searchable palette. */
+ const paletteButton = page.getByRole('button', { name: 'Attach and tools', exact: true });
+ await expect(paletteButton).toBeVisible();
+ await paletteButton.click();
+ const palette = page.getByRole('dialog', { name: 'Attach and tools', exact: true });
+ await expect(palette).toBeVisible();
+ await expect(palette.locator('[data-row-key]').first()).toBeVisible();
+ await page.keyboard.press('Escape');
+ await expect(palette).toHaveCount(0);
+
+ /* Thinking remains interactive while the approval request is paused. */
+ const thinkingButton = page.getByRole('button', { name: /^Thinking: / });
+ await expect(thinkingButton).toBeVisible();
+ await thinkingButton.click();
+ await expect(page.getByRole('dialog', { name: /^Thinking: / })).toBeVisible();
+ await page.keyboard.press('Escape');
+ await expect(page.getByRole('dialog', { name: /^Thinking: / })).toHaveCount(0);
+ await expect(page.getByTestId('stop-generation-button')).toBeVisible();
+
+ /* The composer's review panel owns the batch submit and floats over the
+ tail of the thread, so the thread's own copy of the card sits behind it
+ and cannot be clicked. Drive the surface the user is actually looking
+ at; the timeline card is asserted above as the record of the request. */
+ const reviewPanel = page.locator('#pending-tool-approval-panel');
+ await expect(reviewPanel).toBeVisible();
+ const submit = reviewPanel.getByRole('button', { name: 'Continue', exact: true });
+ await expect(submit).toBeDisabled();
+ await reviewPanel.getByRole('button', { name: 'Approve', exact: true }).click();
+ await expect(submit).toBeEnabled();
+
+ const [resumeRequest, resumeResponse] = await Promise.all([
+ page.waitForRequest(
+ (request) =>
+ request.method() === 'POST' &&
+ new URL(request.url()).pathname === '/api/agents/chat/resume',
+ ),
+ page.waitForResponse(
+ (candidate) =>
+ candidate.request().method() === 'POST' &&
+ new URL(candidate.url()).pathname === '/api/agents/chat/resume' &&
+ candidate.status() === 200,
+ ),
+ submit.click(),
+ ]);
+ expect(resumeResponse.ok()).toBeTruthy();
+ expect(resumeRequest.postDataJSON()).toMatchObject({
+ decisions: [expect.objectContaining({ decision: 'approve' })],
+ });
+
+ await expect(
+ messages.getByText(`E2E approval outcomes: E2E approval probe executed: original-${label}`, {
+ exact: true,
+ }),
+ ).toBeVisible({ timeout: 30000 });
+ await expect(page.getByTestId('stop-generation-button')).toBeHidden({ timeout: 30000 });
+ await expect(page.getByTestId('send-button')).toBeVisible({ timeout: 30000 });
+ } finally {
+ await cleanupAgent(page, agentId);
+ }
+});
diff --git a/e2e/specs/mock/scenarios/composer-queue.spec.ts b/e2e/specs/mock/scenarios/composer-queue.spec.ts
new file mode 100644
index 0000000000..e52878a519
--- /dev/null
+++ b/e2e/specs/mock/scenarios/composer-queue.spec.ts
@@ -0,0 +1,193 @@
+import { expect, test } from '@playwright/test';
+import type { Page } from '@playwright/test';
+import {
+ MOCK_ENDPOINTS,
+ MOCK_REPLY_TEXT,
+ NEW_CHAT_PATH,
+ messagesView,
+ replyPrompt,
+ replyText,
+ selectMockEndpoint,
+ sendMessage,
+} from '../helpers';
+
+/** `E2E_SLOW_REPLY` emits 160 chunks with a 35ms delay between chunks. */
+const SLOW_REPLY_LAST_CHUNK = 'chunk-159';
+
+const messageInput = (page: Page) => page.getByRole('textbox', { name: 'Message input' });
+const duringRunSendButton = (page: Page) => page.getByTestId('during-run-send-button');
+const queuedRows = (page: Page) => page.getByTestId('queued-message-row');
+const messageTurns = (page: Page) => messagesView(page).locator('.message-render');
+
+const uniqueLabel = (prefix: string) =>
+ `${prefix}-${Date.now()}-${Math.floor(Math.random() * 1e4)}`;
+
+/** Establish a persisted conversation before starting a run whose queue is
+ * observed. This keeps the run and its follow-up turns in one thread. */
+async function establishConversation(page: Page, label: string) {
+ const setup = await sendMessage(page, replyPrompt(label));
+ expect(setup.ok()).toBeTruthy();
+ await expect(messagesView(page).getByText(replyText(label))).toBeVisible({ timeout: 30000 });
+ await expect(page).toHaveURL(/\/c\/[0-9a-fA-F-]{36}$/, { timeout: 15000 });
+}
+
+/** Fill while generation is active and wait for the dedicated submit control;
+ * its primary action reflects the preference installed in beforeEach. */
+async function typeDuringRun(page: Page, text: string) {
+ const input = messageInput(page);
+ await input.click();
+ await input.fill(text);
+ await expect(duringRunSendButton(page)).toBeVisible({ timeout: 5000 });
+}
+
+async function startSlowRun(page: Page, label: string) {
+ const run = await sendMessage(page, `E2E_SLOW_REPLY:${label}`);
+ expect(run.ok()).toBeTruthy();
+ await expect(messagesView(page).getByText('chunk-010')).toBeVisible({ timeout: 15000 });
+}
+
+test.describe('composer queue rail', () => {
+ test.beforeEach(async ({ page }) => {
+ // Enter uses the queue route during a run; the modifier route remains the
+ // alternate action, matching the user preference this contract exercises.
+ await page.addInitScript(() => {
+ localStorage.setItem('duringRunDefaultAction', JSON.stringify('queue'));
+ });
+ });
+
+ test('Enter during a run queues the message and sends it when the run ends @scenario:enter-during-a-run-queues-the-message-and-sends-it-when-the-run-ends', async ({
+ page,
+ }) => {
+ test.setTimeout(120000);
+ const label = uniqueLabel('queue-enter');
+ const queueText = `Queued with Enter ${label}`;
+
+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
+ await establishConversation(page, `queue-enter-setup-${label}`);
+
+ await startSlowRun(page, label);
+ await typeDuringRun(page, queueText);
+ await messageInput(page).press('Enter');
+
+ const row = queuedRows(page).filter({ hasText: queueText });
+ await expect(row).toBeVisible({ timeout: 10000 });
+ // Submitting consumes the composer text, so the run-action control returns
+ // to the ordinary Stop button while the queued row is the durable signal
+ // that Enter selected the queue action.
+
+ // Clean completion drains the queued row as a new user turn, then its
+ // ordinary fake-model answer completes in the same conversation.
+ await expect(messagesView(page).getByText(SLOW_REPLY_LAST_CHUNK)).toBeVisible({
+ timeout: 15000,
+ });
+ await expect(row).toHaveCount(0, { timeout: 60000 });
+ await expect(messageTurns(page)).toHaveCount(6, { timeout: 30000 });
+ await expect(messageTurns(page).nth(4)).toContainText(queueText);
+ await expect(messageTurns(page).nth(4).locator('.user-turn')).toBeVisible();
+ await expect(messageTurns(page).nth(5)).toContainText(MOCK_REPLY_TEXT, { timeout: 30000 });
+ await expect(messageTurns(page).nth(5).locator('.agent-turn')).toBeVisible();
+ });
+
+ test('Queued rows reorder with the keyboard @scenario:queued-rows-reorder-with-the-keyboard', async ({
+ page,
+ }) => {
+ test.setTimeout(120000);
+ const label = uniqueLabel('queue-reorder');
+ const firstText = `First queued message ${label}`;
+ const secondText = `Second queued message ${label}`;
+
+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
+ await establishConversation(page, `queue-reorder-setup-${label}`);
+
+ await startSlowRun(page, label);
+ await typeDuringRun(page, firstText);
+ await messageInput(page).press('Enter');
+ await expect(queuedRows(page).filter({ hasText: firstText })).toBeVisible({ timeout: 10000 });
+
+ await typeDuringRun(page, secondText);
+ await messageInput(page).press('Enter');
+ await expect(queuedRows(page)).toHaveCount(2, { timeout: 10000 });
+
+ // The first row's handle owns ArrowDown; after the move, the second row is
+ // the head that queue drain will send first.
+ await queuedRows(page).first().getByTestId('queued-message-grip').press('ArrowDown');
+ await expect(queuedRows(page).first()).toContainText(secondText);
+
+ await expect(messagesView(page).getByText(SLOW_REPLY_LAST_CHUNK)).toBeVisible({
+ timeout: 15000,
+ });
+ await expect(queuedRows(page)).toHaveCount(0, { timeout: 60000 });
+ await expect(messageTurns(page)).toHaveCount(8, { timeout: 45000 });
+
+ // Verify the externally visible conversation order, including each answer,
+ // rather than relying only on the transient rail order.
+ await expect(messageTurns(page).nth(4)).toContainText(secondText);
+ await expect(messageTurns(page).nth(5)).toContainText(MOCK_REPLY_TEXT, { timeout: 30000 });
+ await expect(messageTurns(page).nth(6)).toContainText(firstText);
+ await expect(messageTurns(page).nth(7)).toContainText(MOCK_REPLY_TEXT, { timeout: 30000 });
+ });
+
+ test('Pointer reordering commits the new queue order @scenario:pointer-reordering-commits-the-new-queue-order', async ({
+ page,
+ }) => {
+ test.setTimeout(120000);
+ test.skip(
+ (page.viewportSize()?.width ?? 1280) <= 768,
+ 'HTML5 pointer drag requires hover support',
+ );
+ const label = uniqueLabel('queue-pointer-reorder');
+ const firstText = `First pointer message ${label}`;
+ const secondText = `Second pointer message ${label}`;
+
+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
+ await establishConversation(page, `queue-pointer-setup-${label}`);
+
+ await startSlowRun(page, label);
+ await typeDuringRun(page, firstText);
+ await messageInput(page).press('Enter');
+ await expect(queuedRows(page).filter({ hasText: firstText })).toBeVisible({ timeout: 10000 });
+
+ await typeDuringRun(page, secondText);
+ await messageInput(page).press('Enter');
+ await expect(queuedRows(page)).toHaveCount(2, { timeout: 10000 });
+
+ const firstGrip = queuedRows(page).first().getByTestId('queued-message-grip');
+ const secondRow = queuedRows(page).nth(1);
+ await firstGrip.dragTo(secondRow);
+ await expect(queuedRows(page).first()).toContainText(secondText);
+
+ await expect(messagesView(page).getByText(SLOW_REPLY_LAST_CHUNK)).toBeVisible({
+ timeout: 15000,
+ });
+ await expect(queuedRows(page)).toHaveCount(0, { timeout: 60000 });
+ await expect(messageTurns(page)).toHaveCount(8, { timeout: 45000 });
+ await expect(messageTurns(page).nth(4)).toContainText(secondText);
+ await expect(messageTurns(page).nth(6)).toContainText(firstText);
+ });
+
+ test('Composer keeps typed text when the run finishes @scenario:composer-keeps-typed-text-when-the-run-finishes', async ({
+ page,
+ }) => {
+ test.setTimeout(120000);
+ const label = uniqueLabel('queue-draft');
+ const draftText = `Draft retained after run ${label}`;
+
+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
+ await establishConversation(page, `queue-draft-setup-${label}`);
+
+ await startSlowRun(page, label);
+ await typeDuringRun(page, draftText);
+
+ // The text was never submitted, so run completion must not replace the
+ // composer's own draft with an empty value.
+ await expect(messagesView(page).getByText(SLOW_REPLY_LAST_CHUNK)).toBeVisible({
+ timeout: 15000,
+ });
+ await expect(messageInput(page)).toHaveValue(draftText);
+ await expect(queuedRows(page)).toHaveCount(0);
+ });
+});
diff --git a/e2e/specs/mock/scenarios/composer-redesign.spec.ts b/e2e/specs/mock/scenarios/composer-redesign.spec.ts
new file mode 100644
index 0000000000..4e2880dee9
--- /dev/null
+++ b/e2e/specs/mock/scenarios/composer-redesign.spec.ts
@@ -0,0 +1,262 @@
+import { expect, test } from '@playwright/test';
+import type { Page } from '@playwright/test';
+import { openAgentBuilder } from '../agents.helpers';
+import {
+ messagesView,
+ MOCK_ENDPOINTS,
+ NEW_CHAT_PATH,
+ selectMockEndpoint,
+ selectModelSpec,
+ sendMessage,
+} from '../helpers';
+
+const messageInput = (page: Page) => page.getByRole('textbox', { name: 'Message input' });
+const slowRun = (label: string) => `E2E_SLOW_REPLY:${label}`;
+
+async function startRun(page: Page, label: string) {
+ const response = await sendMessage(page, slowRun(label));
+ expect(response.ok()).toBeTruthy();
+ await expect(messagesView(page).getByText('chunk-010')).toBeVisible({ timeout: 15000 });
+}
+
+async function startRunThroughComposer(page: Page, label: string) {
+ await messageInput(page).fill(slowRun(label));
+ await messageInput(page).press('Enter');
+ await expect(messagesView(page).getByText('chunk-010')).toBeVisible({ timeout: 15000 });
+}
+
+async function openComposer(page: Page) {
+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
+}
+
+test.describe('composer redesign contracts', () => {
+ test('Composer hint names the interrupt default @scenario:composer-hint-names-the-interrupt-default', async ({
+ page,
+ }) => {
+ await page.addInitScript(() =>
+ localStorage.setItem('steerInterruptsByDefault', JSON.stringify(true)),
+ );
+ await openComposer(page);
+ await startRun(page, `interrupt-hint-${Date.now()}`);
+ await messageInput(page).fill('interrupt hint');
+ await expect(page.getByTestId('composer-hints')).toContainText(/interrupt/i);
+ });
+
+ test('Staged reasoning relabels steer as a new turn @scenario:staged-reasoning-relabels-steer-as-a-new-turn', async ({
+ page,
+ }) => {
+ await openComposer(page);
+ await startRun(page, `staged-reasoning-${Date.now()}`);
+ const thinking = page.getByRole('button', { name: /^Thinking: / });
+ await thinking.click();
+ await page
+ .getByRole('dialog', { name: /^Thinking: / })
+ .getByRole('radio', { name: 'Max', exact: true })
+ .click();
+ await page.keyboard.press('Escape');
+ await expect(thinking).toHaveAccessibleName(/Max/i);
+ await messageInput(page).fill('new turn after reasoning');
+ await expect(page.getByTestId('during-run-send-button')).toBeVisible();
+ await expect(page.getByTestId('during-run-send-button')).toHaveAttribute(
+ 'data-during-run-action',
+ 'queue',
+ );
+ /* The send-now chord would queue as well, so the hint names only the queue. */
+ await expect(messageInput(page)).toHaveAccessibleDescription(/Enter queues/);
+ await expect(messageInput(page)).not.toHaveAccessibleDescription(/send now/i);
+ await page.getByTestId('during-run-send-button').click();
+ await expect(
+ page.getByTestId('queued-message-row').filter({ hasText: 'new turn after reasoning' }),
+ ).toBeVisible();
+ });
+
+ test('Model-spec locked reasoning control is hidden @scenario:model-spec-locked-reasoning-control-is-hidden', async ({
+ page,
+ }) => {
+ let interceptedConfig:
+ | {
+ modelSpecs?: {
+ enforce?: boolean;
+ list?: Array<{ name?: string; preset?: Record<string, unknown> }>;
+ };
+ }
+ | undefined;
+ await page.route('**/api/config', async (route) => {
+ const response = await route.fetch();
+ const config = await response.json();
+ const list = Array.isArray(config.modelSpecs?.list) ? config.modelSpecs.list : [];
+ const lockedList = list.map((spec: Record<string, unknown>) => ({
+ ...spec,
+ preset: {
+ ...((spec.preset as Record<string, unknown>) ?? {}),
+ effort: 'max',
+ reasoning_effort: 'max',
+ thinkingLevel: 'high',
+ thinkingBudget: 1024,
+ },
+ }));
+ interceptedConfig = {
+ ...config,
+ modelSpecs: { ...(config.modelSpecs ?? {}), enforce: true, list: lockedList },
+ };
+ await route.fulfill({
+ response,
+ json: interceptedConfig,
+ });
+ });
+ await openComposer(page);
+ await selectModelSpec(page, 'E2E Skill Scope');
+ await expect(page).toHaveURL(/spec=e2e-skill-scope/);
+ expect(interceptedConfig?.modelSpecs?.enforce).toBe(true);
+ expect(
+ interceptedConfig?.modelSpecs?.list?.find(
+ (spec: Record<string, unknown>) => spec.name === 'e2e-skill-scope',
+ )?.preset,
+ ).toEqual(
+ expect.objectContaining({
+ effort: 'max',
+ reasoning_effort: 'max',
+ thinkingLevel: 'high',
+ thinkingBudget: 1024,
+ }),
+ );
+ await expect(page.getByTestId('composer-thinking-button')).toHaveCount(0);
+ });
+
+ test('Stop shortcut ignores focus in a non-chat form @scenario:stop-shortcut-ignores-focus-in-a-non-chat-form', async ({
+ page,
+ }) => {
+ const narrow = (page.viewportSize()?.width ?? 1280) <= 768;
+ let form;
+ if (narrow) {
+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
+ await startRunThroughComposer(page, `shortcut-form-${Date.now()}`);
+ form = await openAgentBuilder(page, { navigate: false });
+ } else {
+ form = await openAgentBuilder(page);
+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
+ await startRunThroughComposer(page, `shortcut-form-${Date.now()}`);
+ }
+ /* Clears whatever the desktop setup left open. On a phone the builder sits
+ in the drawer, and Escape there dismisses the drawer itself, taking the
+ form this test needs behind `inert`. */
+ if (!narrow) {
+ await page.keyboard.press('Escape');
+ await page.keyboard.press('Escape');
+ }
+ const dialogs = await page.evaluate(
+ () =>
+ Array.from(
+ document.querySelectorAll('[role="dialog"]:not([inert]):not([data-state="closed"])'),
+ ).filter((el) => {
+ const style = (el as HTMLElement).style;
+ const computedStyle = window.getComputedStyle(el);
+ return (
+ !el.hasAttribute('hidden') &&
+ style.display !== 'none' &&
+ style.visibility !== 'hidden' &&
+ computedStyle.display !== 'none' &&
+ computedStyle.visibility !== 'hidden'
+ );
+ }).length,
+ );
+ expect(dialogs).toBe(0);
+ const nameInput = form.getByLabel('Agent name');
+ await nameInput.click();
+ await expect(nameInput).toBeFocused();
+ const abort = page.waitForResponse(
+ (response) =>
+ response.request().method() === 'POST' &&
+ new URL(response.url()).pathname.endsWith('/api/agents/chat/abort'),
+ );
+ const modifier = await page.evaluate(() =>
+ navigator.platform.includes('Mac') ? 'Meta' : 'Control',
+ );
+ await page.keyboard.press(`${modifier}+Shift+X`);
+ const abortResponse = await abort;
+ expect(abortResponse.ok()).toBeTruthy();
+ });
+
+ test('Canceled pending steer disappears before application @scenario:canceled-pending-steer-disappears-before-application', async ({
+ page,
+ }) => {
+ await openComposer(page);
+ await startRun(page, `cancel-steer-${Date.now()}`);
+ await messageInput(page).fill('pending steer');
+ await page.getByTestId('during-run-send-button').click();
+ const bubble = page
+ .getByTestId('pending-steers')
+ .getByRole('listitem')
+ .filter({ hasText: 'pending steer' });
+ await expect(bubble).toContainText('Sending');
+ await bubble.getByRole('button', { name: 'Cancel', exact: true }).click();
+ await expect(bubble).toHaveCount(0);
+ await expect(messagesView(page).getByText('pending steer', { exact: true })).toHaveCount(0);
+ });
+
+ test('Canceled steer returns its text to the composer @scenario:canceled-steer-returns-its-text-to-the-composer', async ({
+ page,
+ }) => {
+ await openComposer(page);
+ await startRun(page, `reclaim-steer-${Date.now()}`);
+ await messageInput(page).fill('pending steer');
+ await page.getByTestId('during-run-send-button').click();
+ const bubble = page
+ .getByTestId('pending-steers')
+ .getByRole('listitem')
+ .filter({ hasText: 'pending steer' });
+ await expect(bubble).toContainText('Sending');
+ await bubble.getByRole('button', { name: 'Cancel', exact: true }).click();
+ await expect(bubble).toHaveCount(0);
+ await expect(messageInput(page)).toHaveValue('pending steer');
+ });
+
+ test('Canceled steer keeps a typed draft and queues the message @scenario:canceled-steer-keeps-a-typed-draft-and-queues-the-message', async ({
+ page,
+ }) => {
+ await openComposer(page);
+ await startRun(page, `reclaim-draft-${Date.now()}`);
+ await messageInput(page).fill('pending steer');
+ await page.getByTestId('during-run-send-button').click();
+ const bubble = page
+ .getByTestId('pending-steers')
+ .getByRole('listitem')
+ .filter({ hasText: 'pending steer' });
+ await expect(bubble).toContainText('Sending');
+ /** A draft staged while the cancel is in flight owns the composer. The
+ * reclaimed steer is a different message: gluing the two together would
+ * send one submission the user never wrote, so it becomes a queued
+ * follow-up instead, and the draft is left exactly as typed. */
+ await messageInput(page).fill('draft remains');
+ await bubble.getByRole('button', { name: 'Cancel', exact: true }).click();
+ await expect(bubble).toHaveCount(0);
+ await expect(messageInput(page)).toHaveValue('draft remains');
+ const queuedRow = page.getByTestId('queued-message-row').filter({ hasText: 'pending steer' });
+ await expect(queuedRow).toBeVisible();
+ /** Editing the queued row while that draft is still typed would merge the
+ * two the same way, so Edit refuses and says what to do instead. */
+ await queuedRow.getByRole('button', { name: 'Edit message' }).click();
+ await expect(
+ page.getByLabel('Notifications (F8)').getByText(/Clear the message box in this chat/),
+ ).toBeVisible();
+ await expect(queuedRow).toBeVisible();
+ await expect(messageInput(page)).toHaveValue('draft remains');
+ });
+
+ test('Pending steer status does not claim application before delivery @scenario:pending-steer-status-does-not-claim-application-before-delivery', async ({
+ page,
+ }) => {
+ await openComposer(page);
+ await startRun(page, `pending-status-${Date.now()}`);
+ await messageInput(page).fill('pending status');
+ await page.getByTestId('during-run-send-button').click();
+ const bubble = page
+ .getByTestId('pending-steers')
+ .getByRole('listitem')
+ .filter({ hasText: 'pending status' });
+ await expect(bubble).toBeVisible();
+ await expect(bubble).toContainText('Sending');
+ });
+});
diff --git a/e2e/specs/mock/scenarios/files-tree-removal.spec.ts b/e2e/specs/mock/scenarios/files-tree-removal.spec.ts
index 481e527895..e2bca7eed7 100644
--- a/e2e/specs/mock/scenarios/files-tree-removal.spec.ts
+++ b/e2e/specs/mock/scenarios/files-tree-removal.spec.ts
@@ -2,30 +2,34 @@ import { expect, test } from '@playwright/test';
/**
* The unmounted Files component tree this change deleted was never reachable,
- * which is exactly why its removal needs a scenario: the surfaces that LOOK
- * like it, the chat input's file manager and the files side panel, are the ones
- * a bad deletion would take with them. The panel nav sits behind the mobile
- * drawer on a phone-width viewport, so the scenario states the desktop viewport
- * it means rather than depending on which project runs it.
+ * so this scenario exercises the live file manager in the account menu and the
+ * composer attachment entry. The account menu sits behind the mobile drawer on
+ * a phone-width viewport, so this scenario explicitly uses a desktop viewport.
*/
test.use({ viewport: { width: 1280, height: 800 } });
test.describe('files surfaces after the tree removal', () => {
- test('the files panel and the composer attachment entry still work @scenario:files-tree-removal-leaves-live-surfaces-working', async ({
+ test('the file manager and the composer attachment entry still work @scenario:files-tree-removal-leaves-live-surfaces-working', async ({
page,
}) => {
test.setTimeout(60000);
await page.goto('/c/new', { timeout: 15000 });
- await page.getByTestId('nav-panel-files').click();
- const panel = page.getByRole('region', { name: 'Files Table' });
- await expect(panel).toBeVisible({ timeout: 15000 });
- /** The panel's own filter field is part of the live tree that had to
- * survive the deletion of the unreachable one beside it. */
- await expect(panel.locator('#filename-filter')).toBeVisible();
+ await page.getByTestId('nav-user').click();
+ await page.getByRole('menu').getByRole('menuitem', { name: 'My Files', exact: true }).click();
+ const fileManager = page.getByRole('dialog', { name: 'My Files', exact: true });
+ await expect(fileManager).toBeVisible({ timeout: 15000 });
+ const filter = fileManager.locator('#files-filter');
+ await expect(filter).toBeVisible();
+ await filter.fill('file-surface-regression');
+ await expect(filter).toHaveValue('file-surface-regression');
await page.keyboard.press('Escape');
+ await expect(fileManager).not.toBeVisible();
await expect(page.getByTestId('composer-surface')).toBeVisible();
+ await page.getByRole('button', { name: 'Attach and tools', exact: true }).click();
+ await expect(page.getByRole('dialog', { name: 'Attach and tools' })).toBeVisible();
+ await page.keyboard.press('Escape');
});
});
diff --git a/e2e/specs/mock/scenarios/highlight-throttle.spec.ts b/e2e/specs/mock/scenarios/highlight-throttle.spec.ts
index f8e6219c34..848d3d1c86 100644
--- a/e2e/specs/mock/scenarios/highlight-throttle.spec.ts
+++ b/e2e/specs/mock/scenarios/highlight-throttle.spec.ts
@@ -50,10 +50,14 @@ async function openCodePane(page: Parameters<typeof sendMessage>[0]) {
* test, because that is the only time the input keeps changing.
*/
async function expectHighlightedCode(page: Parameters<typeof sendMessage>[0]) {
- await openCodePane(page);
const code = highlightedCode(page);
- await expect(code).toBeVisible({ timeout: 30000 });
- await expect.poll(() => code.locator('span').count(), { timeout: 30000 }).toBeGreaterThan(0);
+ /** The saved card can replace the live card after opening it. Reopen that
+ * replacement before checking tokens; collapsed cards deliberately stay raw. */
+ await expect(async () => {
+ await openCodePane(page);
+ await expect(code).toBeVisible();
+ expect(await code.locator('span').count()).toBeGreaterThan(0);
+ }).toPass({ timeout: 30000 });
return code;
}
diff --git a/e2e/specs/mock/scenarios/parts.spec.ts b/e2e/specs/mock/scenarios/parts.spec.ts
index 9a9f379e6c..f6da16160f 100644
--- a/e2e/specs/mock/scenarios/parts.spec.ts
+++ b/e2e/specs/mock/scenarios/parts.spec.ts
@@ -40,12 +40,15 @@ function viewAndRestore(messages: TMessage[]): UIMessage[] {
}
async function selectMemoryServer(page: Page) {
- await page.getByRole('button', { name: 'MCP Servers', exact: true }).click();
- const serverItem = page.getByRole('menuitemcheckbox', { name: new RegExp(MCP_SERVER_TITLE) });
+ await page.getByRole('button', { name: 'Attach and tools' }).click();
+ const serverItem = page
+ .getByRole('dialog', { name: 'Attach and tools' })
+ .getByRole('button', { name: new RegExp(`^${MCP_SERVER_TITLE}\\b`) });
await expect(serverItem).toBeVisible();
await serverItem.click();
- await expect(serverItem).toHaveAttribute('aria-checked', 'true');
+ await expect(serverItem).toHaveAttribute('aria-pressed', 'true');
await page.keyboard.press('Escape');
+ await expect(page.getByRole('listitem', { name: MCP_SERVER_TITLE, exact: true })).toBeVisible();
}
test.describe('UI parts view of persisted messages', () => {
diff --git a/e2e/specs/mock/scenarios/pinned.helpers.ts b/e2e/specs/mock/scenarios/pinned.helpers.ts
index 9b00a4bd59..252e66b0d4 100644
--- a/e2e/specs/mock/scenarios/pinned.helpers.ts
+++ b/e2e/specs/mock/scenarios/pinned.helpers.ts
@@ -191,6 +191,36 @@ const sidebarPlacement = async (page: Page): Promise<SidebarPlacement> => {
* than answered with a click that would never resolve.
*/
export async function ensureSidebarOnScreen(page: Page): Promise<void> {
+ const drawer = page.locator('#mobile-drawer');
+ /* A closed drawer stays mounted and keeps its layout box, so geometry cannot
+ tell it from an open one; `inert` is the state the component actually sets
+ and the reason every control inside answers a query while none of them can
+ be tapped. Open it before anything below measures. */
+ if ((await drawer.count()) > 0 && (await drawer.getAttribute('inert')) != null) {
+ const opener = page.getByRole('button', { name: 'Open sidebar' });
+ if ((await opener.count()) > 0) {
+ await opener.first().click();
+ await expect.poll(() => drawer.getAttribute('inert'), { timeout: 15_000 }).toBeNull();
+ /* `inert` clears on the state commit, a few frames ahead of the slide
+ settling. Wait for the drawer to actually be in the viewport before
+ letting a caller query the controls inside it. */
+ await expect
+ .poll(async () => (await drawer.boundingBox())?.x ?? Number.NEGATIVE_INFINITY, {
+ timeout: 15_000,
+ })
+ .toBeGreaterThanOrEqual(0);
+ }
+ }
+ if ((await pinnedSection(page).count()) === 0) {
+ /* Empty sidebars have no Pinned region to measure, and there is nothing
+ left to do: the drawer above is already open, and desktop renders no
+ drawer at all. Measuring the drawer again here and opening it a second
+ time is what used to close it: the slide is animated imperatively and
+ its state commit is deferred by several frames, so a bounding box read
+ mid-flight still reads as off-screen and the extra click lands on the
+ machine that is already opening it. */
+ return;
+ }
await expect.poll(() => sidebarPlacement(page), { timeout: 15_000 }).not.toBe('unlaid');
if ((await sidebarPlacement(page)) === 'on-screen') {
return;
diff --git a/e2e/specs/mock/scenarios/quieter-panels.spec.ts b/e2e/specs/mock/scenarios/quieter-panels.spec.ts
index 7c3c13e537..25d7141cd9 100644
--- a/e2e/specs/mock/scenarios/quieter-panels.spec.ts
+++ b/e2e/specs/mock/scenarios/quieter-panels.spec.ts
@@ -352,8 +352,8 @@ test.describe('quieter management panels', () => {
}));
await page.route('**/api/files', (route) => route.fulfill({ json: files }));
await page.goto('/c/new');
- await openPanel(page, 'files', 'Attach Files');
- await page.getByRole('button', { name: 'Manage Files', exact: true }).click();
+ await page.getByTestId('nav-user').click();
+ await page.getByRole('menu').getByRole('menuitem', { name: 'My Files', exact: true }).click();
const dialog = page.getByRole('dialog', { name: 'My Files' });
const header = dialog.locator('thead');
await expect(header).toBeVisible();
diff --git a/e2e/specs/mock/scenarios/tool-context-split.spec.ts b/e2e/specs/mock/scenarios/tool-context-split.spec.ts
index 6264aceba1..67d887ddca 100644
--- a/e2e/specs/mock/scenarios/tool-context-split.spec.ts
+++ b/e2e/specs/mock/scenarios/tool-context-split.spec.ts
@@ -26,13 +26,15 @@ async function expectGaugeAboveZero(page: Page) {
/** Select the ephemeral MCP server whose real remember_fact tool creates the
* tool boundary and causes the fake model to take its tool-response path. */
async function selectEphemeralMCP(page: Page) {
- await page.getByRole('button', { name: 'MCP Servers', exact: true }).click();
- const serverItem = page.getByRole('menuitemcheckbox', { name: new RegExp(MCP_SERVER_TITLE) });
+ await page.getByRole('button', { name: 'Attach and tools' }).click();
+ const serverItem = page
+ .getByRole('dialog', { name: 'Attach and tools' })
+ .getByRole('button', { name: new RegExp(`^${MCP_SERVER_TITLE}\\b`) });
await expect(serverItem).toBeVisible();
await serverItem.click();
- await expect(serverItem).toHaveAttribute('aria-checked', 'true');
+ await expect(serverItem).toHaveAttribute('aria-pressed', 'true');
await page.keyboard.press('Escape');
- await expect(page.getByRole('button', { name: new RegExp(MCP_SERVER_TITLE) })).toBeVisible();
+ await expect(page.getByRole('listitem', { name: MCP_SERVER_TITLE, exact: true })).toBeVisible();
}
/** The popover opens with only the meter visible; its detail is a remembered
diff --git a/e2e/specs/mock/scenarios/unseen-replies.spec.ts b/e2e/specs/mock/scenarios/unseen-replies.spec.ts
index 33bb19ef0c..eed4179a68 100644
--- a/e2e/specs/mock/scenarios/unseen-replies.spec.ts
+++ b/e2e/specs/mock/scenarios/unseen-replies.spec.ts
@@ -138,6 +138,14 @@ async function seedReplyMessage(id: string, label: string) {
}
test.describe('unseen replies', () => {
+ /* The tab title counts every unseen conversation, and a shared verification run leaves
+ * legitimately-unseen conversations from earlier scenarios behind, so these tests assert
+ * the count they add and clear rather than a pristine zero baseline. */
+ async function titleCount(page: Page): Promise<number> {
+ const match = (await page.title()).match(/^\((\d+)\)/);
+ return match ? Number(match[1]) : 0;
+ }
+
test('opening a conversation clears its dot and the title count @scenario:open-conversation-clears-dot-and-title-count', async ({
page,
}) => {
@@ -161,7 +169,17 @@ test.describe('unseen replies', () => {
.filter({ hasText: firstTitle })
.locator('span[aria-hidden="true"].bg-status-info'),
).toBeVisible();
- await expect.poll(() => page.title()).toMatch(/^\(2\)/);
+ await expect(
+ page
+ .getByTestId('convo-item')
+ .filter({ hasText: secondTitle })
+ .locator('span[aria-hidden="true"].bg-status-info'),
+ ).toBeVisible();
+ /* Both seeded dots are on screen, so the count read here already includes
+ * them; the away poll can still discover older conversations the client
+ * had not counted yet (a shared run leaves many), so what opening has to
+ * do is clear THIS conversation's contribution, not land on a fixed sum. */
+ const settled = await titleCount(page);
await page
.getByTestId('convo-item')
.filter({ hasText: firstTitle })
@@ -177,7 +195,7 @@ test.describe('unseen replies', () => {
.filter({ hasText: firstTitle })
.locator('span[aria-hidden="true"].bg-status-info'),
).toHaveCount(0);
- await expect.poll(() => page.title()).toMatch(/^\(1\)/);
+ await expect.poll(() => titleCount(page)).toBeLessThanOrEqual(settled - 1);
} finally {
await cleanup(first);
await cleanup(second);
@@ -231,12 +249,15 @@ test.describe('unseen replies', () => {
await openSidebar(page);
const row = page.getByTestId('convo-item').filter({ hasText: title });
await expect(row.locator('span[aria-hidden="true"].bg-status-info')).toHaveCount(0);
+ const baseline = await titleCount(page);
await openConversationMenu(row);
/* Dispatched rather than clicked, like the row controls around it: the menu is portaled,
and on the mobile project the drawer's scrim sits over it and intercepts the pointer. */
await page.getByRole('menuitem', { name: 'Mark as unread' }).dispatchEvent('click');
await expect(row.locator('span[aria-hidden="true"].bg-status-info')).toBeVisible();
- await expect.poll(() => page.title()).toMatch(/^\(1\)/);
+ /* At least one more, not exactly one: the other projects share this user
+ * and seed unseen conversations of their own while this one runs. */
+ await expect.poll(() => titleCount(page)).toBeGreaterThanOrEqual(baseline + 1);
const token = await getAccessToken(page);
const neverReplied = conversationId();
@@ -309,6 +330,7 @@ test.describe('unseen replies', () => {
await openSidebar(page);
const row = page.getByTestId('convo-item').filter({ hasText: title });
await expect(row.locator('span[aria-hidden="true"].bg-status-info')).toHaveCount(0);
+ const baseline = await titleCount(page);
await unfocus(page);
const second = await context.newPage();
@@ -341,7 +363,10 @@ test.describe('unseen replies', () => {
await expect(row.locator('span[aria-hidden="true"].bg-status-info')).toBeVisible({
timeout: 75_000,
});
- await expect.poll(() => page.title()).toMatch(/^\(1\)/);
+ /* The away poll that lights the dot also discovers conversations the
+ * client had not counted yet, so the count must rise past the baseline
+ * rather than land on an exact sum over state this tab never owned. */
+ await expect.poll(() => titleCount(page)).toBeGreaterThan(baseline);
} finally {
await second.close();
}
diff --git a/e2e/specs/mock/scenarios/v4-focus.spec.ts b/e2e/specs/mock/scenarios/v4-focus.spec.ts
index 8e7de6ef41..b9a63f3da6 100644
--- a/e2e/specs/mock/scenarios/v4-focus.spec.ts
+++ b/e2e/specs/mock/scenarios/v4-focus.spec.ts
@@ -1,10 +1,6 @@
import { expect, test } from '@playwright/test';
-import { randomUUID } from 'node:crypto';
-import { ObjectId } from 'mongodb';
import type { Page } from '@playwright/test';
import { computedStyles, normalizeColor, themeValue, useStoredTheme } from './style.helpers';
-import { getAccessToken } from '../helpers';
-import { withMongo } from '../db';
/**
* Two of the upgrade's renamings are about focus, and both are invisible until
@@ -16,26 +12,36 @@ import { withMongo } from '../db';
* when the platform forces its own colours — while v4's means `outline: none`.
*/
-/** The attach-file menu trigger: one Tab from the composer on the new-chat
- * screen with no seeding, and it carries both classes under test
- * (`focus-visible:ring-text-primary/50` and `focus-visible:outline-hidden`,
- * client/src/components/Chat/Input/Files/AttachFileMenu.tsx). */
-const ATTACH_TRIGGER = '#attach-file-menu-button';
+/** The composer's palette trigger: reachable by Tab from the composer on the
+ * new-chat screen with no seeding, and it carries the outline half of the pair
+ * under test (`focus-visible:outline-hidden` beside its ring, from IconButton). */
+const PALETTE_TRIGGER = '[data-testid="composer-palette-button"]';
-/** Focus it by keyboard, because both classes are behind `focus-visible:`. */
-async function tabToAttachTrigger(page: Page): Promise<void> {
+/** The composer control that halves its own ring
+ * (`focus-visible:ring-text-primary/50`, Chat/Input/CollapseChat.tsx). It only
+ * renders once the draft outgrows three rows. */
+const HALVED_RING_CONTROL = 'button[aria-label="Collapse Chat"]';
+const TALL_DRAFT = ['one', 'two', 'three', 'four', 'five'].join('\n');
+
+/** Focus a composer control by keyboard, because both classes are behind
+ * `focus-visible:`. */
+async function tabToComposerControl(page: Page, selector: string, draft?: string): Promise<void> {
const composer = page.getByRole('textbox', { name: 'Message input' });
await expect(composer).toBeVisible({ timeout: 30000 });
await composer.click();
+ if (draft != null) {
+ await composer.fill(draft);
+ await expect(page.locator(selector)).toHaveCount(1, { timeout: 10000 });
+ }
for (let press = 0; press < 15; press++) {
await page.keyboard.press('Tab');
const focused = await page.evaluate(
- (selector) => document.activeElement?.matches(selector) ?? false,
- ATTACH_TRIGGER,
+ (target) => document.activeElement?.matches(target) ?? false,
+ selector,
);
if (focused) return;
}
- throw new Error('the attach-file trigger was never reached by Tab');
+ throw new Error(`${selector} was never reached by Tab`);
}
test.describe('Tailwind v4 focus treatment', () => {
@@ -50,28 +56,28 @@ test.describe('Tailwind v4 focus treatment', () => {
test.setTimeout(120_000);
await page.goto('/c/new', { timeout: 30000 });
- await tabToAttachTrigger(page);
+ await tabToComposerControl(page, HALVED_RING_CONTROL, TALL_DRAFT);
/** Without the mode, the control's own halved ring is what shows. */
- const halved = await computedStyles(page.locator(ATTACH_TRIGGER), ['--tw-ring-color']);
+ const halved = await computedStyles(page.locator(HALVED_RING_CONTROL), ['--tw-ring-color']);
expect(halved['--tw-ring-color']).toContain('color-mix');
await page.emulateMedia({ contrast: 'more' });
await expect(page.locator('html.high-contrast')).toHaveCount(1, { timeout: 30000 });
- await tabToAttachTrigger(page);
+ await tabToComposerControl(page, HALVED_RING_CONTROL, TALL_DRAFT);
/** With it, the ring is restored to the ink token at full strength: the
* stylesheet re-declares the colour, because v4 has no ring-opacity. */
- const restored = await computedStyles(page.locator(ATTACH_TRIGGER), ['--tw-ring-color']);
+ const restored = await computedStyles(page.locator(HALVED_RING_CONTROL), ['--tw-ring-color']);
const opaque = await normalizeColor(page, `rgb(${await themeValue(page, '--text-primary')})`);
expect(await normalizeColor(page, restored['--tw-ring-color'])).toBe(opaque);
expect(restored['--tw-ring-color']).not.toContain('color-mix');
/** The restoring rule is `html.high-contrast *`, so it has to hold for every
* control that halves its own ring rather than only the one focused above:
- * the attach-file button, the composer's collapse and its tools menu all
- * write the same class. */
- for (const selector of ['#attach-file', '#collapse-chat-button', '#tools-menu-button']) {
+ * the assistants attach button and the composer's collapse both write the
+ * same class. */
+ for (const selector of ['#attach-file', HALVED_RING_CONTROL]) {
const control = page.locator(selector);
if ((await control.count()) === 0) continue;
const ring = await computedStyles(control, ['--tw-ring-color']);
@@ -88,13 +94,13 @@ test.describe('Tailwind v4 focus treatment', () => {
await page.emulateMedia({ forcedColors: 'active' });
await page.goto('/c/new', { timeout: 30000 });
- await tabToAttachTrigger(page);
+ await tabToComposerControl(page, PALETTE_TRIGGER);
/** `outline-hidden` keeps v3's transparent outline, which the platform
* repaints in forced colours; `outline-none` would remove the outline box
* and leave the keyboard user with the ring alone, which forced colours
* flattens. */
- const outline = await computedStyles(page.locator(ATTACH_TRIGGER), [
+ const outline = await computedStyles(page.locator(PALETTE_TRIGGER), [
'outlineStyle',
'outlineWidth',
]);
@@ -108,10 +114,13 @@ test.describe('Tailwind v4 focus treatment', () => {
}) => {
test.setTimeout(120_000);
await useStoredTheme(page, 'light');
+ /* Pin the scheme with the stored theme: a dark system scheme still brings in
+ the dark theme's own `:focus-visible` outline, which is not under test. */
+ await page.emulateMedia({ colorScheme: 'light' });
await page.goto('/c/new', { timeout: 30000 });
- await tabToAttachTrigger(page);
+ await tabToComposerControl(page, PALETTE_TRIGGER);
- const focused = await computedStyles(page.locator(ATTACH_TRIGGER), [
+ const focused = await computedStyles(page.locator(PALETTE_TRIGGER), [
'outlineStyle',
'boxShadow',
]);
@@ -120,71 +129,9 @@ test.describe('Tailwind v4 focus treatment', () => {
});
});
-/** The signed-in user's id, read from the access token's payload. */
-async function currentUserId(page: Page): Promise<string> {
- const token = await getAccessToken(page);
- const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString('utf8'));
- return String(payload.id);
-}
-
test.describe('Tailwind v4 focus ownership', () => {
test.use({ viewport: { width: 1280, height: 900 } });
- /** The files table marks a file's name cell as a button and draws its keyboard
- * indicator as a 2px outline. v4's `outline-hidden` sets `--tw-outline-style:
- * none`, and `outline-2` reads that variable, so the cell's own
- * `focus:outline-hidden` beside `focus-visible:outline-2` erased the outline it
- * was meant to draw and left the cell with no indicator at all. */
- test('a keyboard-focused file name shows its outline @scenario:a-keyboard-focused-file-name-shows-its-outline', async ({
- page,
- }) => {
- test.setTimeout(120_000);
- await page.goto('/c/new', { timeout: 30000 });
-
- const fileId = randomUUID();
- const filename = `outline-${fileId.slice(0, 8)}.txt`;
- const user = new ObjectId(await currentUserId(page));
- await withMongo((db) =>
- db.collection('files').insertOne({
- user,
- file_id: fileId,
- filename,
- filepath: `/uploads/${user.toHexString()}/${fileId}__${filename}`,
- bytes: 12,
- type: 'text/plain',
- object: 'file',
- usage: 0,
- source: 'local',
- createdAt: new Date(),
- updatedAt: new Date(),
- }),
- );
-
- try {
- await page.reload();
- await page.getByTestId('nav-panel-files').click();
- const table = page.getByRole('region', { name: 'Files Table' });
- const filter = table.locator('#filename-filter');
- await filter.fill(filename);
- const cell = table.locator('td[role="button"]').filter({ hasText: filename });
- await expect(cell).toHaveCount(1, { timeout: 30000 });
-
- /** Reach it by keyboard, because the outline is behind `focus-visible:`. */
- await filter.focus();
- for (let press = 0; press < 10; press++) {
- await page.keyboard.press('Tab');
- if (await cell.evaluate((node) => node === document.activeElement)) break;
- }
- await expect(cell).toBeFocused();
-
- const focused = await computedStyles(cell, ['outlineStyle', 'outlineWidth']);
- expect(focused.outlineStyle).toBe('solid');
- expect(focused.outlineWidth).toBe('2px');
- } finally {
- await withMongo((db) => db.collection('files').deleteOne({ file_id: fileId }));
- }
- });
-
/** A primitive that owns no focus treatment of its own, such as the keyboard
* shortcuts dialog's close control, takes `focusOutline="hidden"` from a caller
* that draws its own ring. It has to drop the browser's outline beside that
diff --git a/e2e/specs/mock/shared-links.spec.ts b/e2e/specs/mock/shared-links.spec.ts
index 380112651b..dea7695841 100644
--- a/e2e/specs/mock/shared-links.spec.ts
+++ b/e2e/specs/mock/shared-links.spec.ts
@@ -57,8 +57,8 @@ type PublicSharedPayload = {
const randomSuffix = () => `${Date.now()}-${Math.floor(Math.random() * 10000)}`;
async function uploadProviderFile(page: Page, fixture: UploadFixture) {
- await page.getByRole('button', { name: 'Attach File Options' }).click();
- const uploadOption = page.getByText('Upload to Provider', { exact: true });
+ await page.getByRole('button', { name: 'Attach and tools' }).click();
+ const uploadOption = page.getByRole('button', { name: 'Upload to Provider', exact: true });
await expect(uploadOption).toBeVisible();
const fileChooserPromise = page.waitForEvent('filechooser');
diff --git a/e2e/specs/mock/steering-escalation.spec.ts b/e2e/specs/mock/steering-escalation.spec.ts
index dfb1b9f1eb..f5f3c1707e 100644
--- a/e2e/specs/mock/steering-escalation.spec.ts
+++ b/e2e/specs/mock/steering-escalation.spec.ts
@@ -21,8 +21,11 @@ const messageInput = (page: Page) => page.getByRole('textbox', { name: 'Message
const duringRunSendButton = (page: Page) => page.getByTestId('during-run-send-button');
const queuedRows = (page: Page) => page.getByTestId('queued-message-row');
const messageTurns = (page: Page) => messagesView(page).locator('.message-render');
-const inFlightSteers = (page: Page) => page.getByTestId('in-flight-steer');
-const appliedSteerParts = (page: Page) => messagesView(page).getByTestId('steer-part');
+const inFlightSteers = (page: Page) => page.getByTestId('pending-steers').getByRole('listitem');
+/** Applied (persisted) steer parts only: pending steers render their own
+ * SteerPart inside the reply now, so exclude anything under `pending-steers`. */
+const appliedSteerParts = (page: Page) =>
+ messagesView(page).locator('[data-testid="steer-part"]:not([data-testid="pending-steers"] *)');
function isSteerRequest(response: Response) {
return (
@@ -74,6 +77,14 @@ async function expectModelContinuation(page: Page, label: string, steerText: str
* a real interrupt rather than relabelling a chip.
*/
test.describe('escalating waiting messages to an interrupt', () => {
+ /* The composer ships with Enter queueing during a run; escalation rides the
+ steer route, so pin the during-run default to steering. */
+ test.beforeEach(async ({ page }) => {
+ await page.addInitScript(() => {
+ localStorage.setItem('duringRunDefaultAction', JSON.stringify('steer'));
+ });
+ });
+
/** `steerInterruptsByDefault` is a localStorage preference; the toggle test
* flips it, and a mid-test failure must not leak preempt-by-default into
* the rest of the serial suite. */
@@ -197,24 +208,23 @@ test.describe('escalating waiting messages to an interrupt', () => {
expect(run.ok()).toBeTruthy();
await expect(messagesView(page).getByText('chunk-010')).toBeVisible({ timeout: 15000 });
- // A queued row hosts the overflow menu carrying the preference toggle.
+ // Park a queued row so the run is visibly still going while the
+ // preference flips.
await typeDuringRun(page, queueText);
await messageInput(page).press('ControlOrMeta+Enter');
const row = queuedRows(page).filter({ hasText: queueText });
await expect(row).toBeVisible({ timeout: 10000 });
- // The toggle lives in the row menu's separated Preferences section.
- await row.getByRole('button', { name: 'More options' }).click();
- await expect(page.getByText('Preferences', { exact: true })).toBeVisible({ timeout: 5000 });
- await page.getByRole('menuitem', { name: 'Steer sooner by default', exact: true }).click();
-
- // Verify the preference flips while this row is guaranteed to remain
- // parked. After the interrupt is submitted the run may seal and auto-drain
- // the row before another locator action can observe it.
- await row.getByRole('button', { name: 'More options' }).click();
- await expect(
- page.getByRole('menuitem', { name: 'Wait for the next step instead', exact: true }),
- ).toBeVisible({ timeout: 5000 });
+ // The during-run default lives in Settings > Chat as an ordinary switch.
+ await page.getByTestId('nav-user').click();
+ await page.getByRole('menuitem', { name: 'Settings' }).click();
+ await page.getByRole('tab', { name: 'Chat' }).click();
+ const interruptToggle = page.getByRole('switch', {
+ name: 'Steering interrupts generation',
+ });
+ await expect(interruptToggle).toBeVisible({ timeout: 5000 });
+ await interruptToggle.click();
+ await expect(interruptToggle).toHaveAttribute('aria-checked', 'true');
await page.keyboard.press('Escape');
// The toggle is live for the SAME run: plain Enter now routes the default
diff --git a/e2e/specs/mock/steering.spec.ts b/e2e/specs/mock/steering.spec.ts
index c0e163083c..2605fcf97b 100644
--- a/e2e/specs/mock/steering.spec.ts
+++ b/e2e/specs/mock/steering.spec.ts
@@ -34,9 +34,12 @@ const messageInput = (page: Page) => page.getByRole('textbox', { name: 'Message
const duringRunSendButton = (page: Page) => page.getByTestId('during-run-send-button');
const queuedRows = (page: Page) => page.getByTestId('queued-message-row');
const messageTurns = (page: Page) => messagesView(page).locator('.message-render');
-/** In-flight steers are anchored above the composer, not in the thread. */
-const inFlightSteers = (page: Page) => page.getByTestId('in-flight-steer');
-const appliedSteerParts = (page: Page) => messagesView(page).getByTestId('steer-part');
+/** In-flight steers render at the tail of the streaming reply. */
+const inFlightSteers = (page: Page) => page.getByTestId('pending-steers').getByRole('listitem');
+/** Applied (persisted) steer parts only: pending steers render their own
+ * SteerPart inside the reply now, so exclude anything under `pending-steers`. */
+const appliedSteerParts = (page: Page) =>
+ messagesView(page).locator('[data-testid="steer-part"]:not([data-testid="pending-steers"] *)');
type PersistedMessage = {
messageId: string;
@@ -58,15 +61,17 @@ function isSteerRequest(response: Response) {
);
}
-/** Select the MCP server from the composer's ephemeral MCP dropdown. */
+/** Select the MCP server from the composer palette. */
async function selectEphemeralMCP(page: Page) {
- await page.getByRole('button', { name: 'MCP Servers', exact: true }).click();
- const serverItem = page.getByRole('menuitemcheckbox', { name: new RegExp(MCP_SERVER_TITLE) });
+ await page.getByRole('button', { name: 'Attach and tools' }).click();
+ const serverItem = page
+ .getByRole('dialog', { name: 'Attach and tools' })
+ .getByRole('button', { name: new RegExp(`^${MCP_SERVER_TITLE}\\b`) });
await expect(serverItem).toBeVisible();
await serverItem.click();
- await expect(serverItem).toHaveAttribute('aria-checked', 'true');
+ await expect(serverItem).toHaveAttribute('aria-pressed', 'true');
await page.keyboard.press('Escape');
- await expect(page.getByRole('button', { name: new RegExp(MCP_SERVER_TITLE) })).toBeVisible();
+ await expect(page.getByRole('listitem', { name: MCP_SERVER_TITLE, exact: true })).toBeVisible();
}
/** Establish a real conversation with a fast first turn so during-run actions
@@ -88,6 +93,15 @@ async function typeDuringRun(page: Page, text: string) {
}
test.describe('mid-run steering and queuing', () => {
+ /* The composer ships with Enter queueing during a run; these tests exercise
+ the steer route, so pin the during-run default to steering. Cmd/Ctrl+Enter
+ then carries the queue path, which the queue tests below rely on. */
+ test.beforeEach(async ({ page }) => {
+ await page.addInitScript(() => {
+ localStorage.setItem('duringRunDefaultAction', JSON.stringify('steer'));
+ });
+ });
+
/**
* The applied-steer contract (requires @librechat/agents ≥ 3.2.63, where
* top-level `PostToolBatch` hook inputs carry no subagent-scope `agentId`):
@@ -591,8 +605,7 @@ test.describe('mid-run steering and queuing', () => {
await expect(row).toBeVisible({ timeout: 15000 });
await expect(row.getByRole('button', { name: 'Remove message', exact: true })).toBeVisible();
- await row.getByRole('button', { name: 'More options', exact: true }).click();
- const edit = page.getByRole('menuitem', { name: 'Edit message', exact: true });
+ const edit = row.getByRole('button', { name: 'Edit message', exact: true });
await expect(edit).toBeVisible();
await edit.click();
diff --git a/e2e/specs/mock/thread-fold.spec.ts b/e2e/specs/mock/thread-fold.spec.ts
index 83ba3c5e9a..49cbf8d248 100644
--- a/e2e/specs/mock/thread-fold.spec.ts
+++ b/e2e/specs/mock/thread-fold.spec.ts
@@ -92,7 +92,9 @@ test.describe('thread fold regressions', () => {
/** Queue mid-run, then escalate to an interrupt: the closest scripted
* reproduction of the incident's preempt churn (mid-stream seal, new
- * generation, resume-path cache writes). */
+ * generation, resume-path cache writes). Enter takes the default
+ * during-run action, which is steer; Ctrl/Cmd+Enter takes the other one,
+ * which is what queues the message this test needs. */
const input = messageInput(page);
await input.click();
await input.fill(interruptText);
diff --git a/e2e/specs/mock/thread-renderers.spec.ts b/e2e/specs/mock/thread-renderers.spec.ts
index bad842d4f5..c9df48fdf1 100644
--- a/e2e/specs/mock/thread-renderers.spec.ts
+++ b/e2e/specs/mock/thread-renderers.spec.ts
@@ -114,10 +114,12 @@ async function sendAndExpectReply(page: Page, prompt: string, expectedReply: str
}
async function uploadProviderFile(page: Page) {
- await page.getByRole('button', { name: 'Attach File Options' }).click();
- await expect(page.getByText('Upload to Provider')).toBeVisible();
+ await page.getByRole('button', { name: 'Attach and tools', exact: true }).click();
+ const palette = page.getByRole('dialog', { name: 'Attach and tools', exact: true });
+ const uploadOption = palette.getByRole('button', { name: 'Upload to Provider', exact: true });
+ await expect(uploadOption).toBeVisible();
const fileChooserPromise = page.waitForEvent('filechooser');
- await page.getByText('Upload to Provider').click();
+ await uploadOption.click();
const fileChooser = await fileChooserPromise;
const uploadResponse = page.waitForResponse(
(response) =>
diff --git a/e2e/specs/mock/unified-upload.spec.ts b/e2e/specs/mock/unified-upload.spec.ts
index b064001338..e36eea60d8 100644
--- a/e2e/specs/mock/unified-upload.spec.ts
+++ b/e2e/specs/mock/unified-upload.spec.ts
@@ -15,12 +15,12 @@ import {
* Unified file upload — per-mime-type delivery routing (PR #12626).
*
* Runs against Mock Provider B, configured for unified mode in
- * e2e/config/librechat.e2e.yaml (Mock Provider A stays on the legacy dropdown
+ * e2e/config/librechat.e2e.yaml (Mock Provider A retains legacy routing
* for chat.spec.ts's upload-to-provider test).
*
* What this proves end-to-end (real backend + DB), and what it deliberately can't:
- * - The composer renders ONE attach button (unified mode), not the legacy 3-way
- * dropdown.
+ * - The composer opens one palette entry point in unified mode, with no separate
+ * legacy upload menu.
* - A `none`-routed upload (csv) persists `llmDeliveryPath: 'none'` and is kept
* out of LLM delivery — reachable only by tools.
* - A `provider`-routed upload (markdown) is STILL delivered to the model AND
@@ -42,10 +42,10 @@ test.describe('unified file upload', () => {
// Default model needs a real key; Mock Provider B is the unified-mode endpoint.
await selectMockEndpoint(page, MOCK_ENDPOINTS[1]);
- // Unified mode: one attach button, and the legacy multi-option dropdown trigger
- // is not rendered at all.
- await expect(page.locator('#attach-file-button')).toBeVisible({ timeout: 15000 });
- await expect(page.locator('#attach-file-menu-button')).toHaveCount(0);
+ // Unified mode: the palette entry point is visible.
+ await expect(page.getByRole('button', { name: 'Attach and tools', exact: true })).toBeVisible({
+ timeout: 15000,
+ });
// Upload-time routing: the configured override (csv -> none) must persist, so
// the file is kept out of LLM delivery and left for tools (code interpreter).
@@ -76,9 +76,10 @@ test.describe('unified file upload', () => {
await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
await selectMockEndpoint(page, MOCK_ENDPOINTS[1]);
- // Same single unified button — no legacy dropdown.
- await expect(page.locator('#attach-file-button')).toBeVisible({ timeout: 15000 });
- await expect(page.locator('#attach-file-menu-button')).toHaveCount(0);
+ // Same palette entry point — no separate legacy upload menu.
+ await expect(page.getByRole('button', { name: 'Attach and tools', exact: true })).toBeVisible({
+ timeout: 15000,
+ });
// markdown is overridden to `provider` for Mock Provider B: it should be
// delivered to the model (unlike `none`) while still attaching to the chat.
@@ -122,7 +123,9 @@ test.describe('unified file upload', () => {
await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
await selectMockEndpoint(page, MOCK_ENDPOINTS[1]);
- await expect(page.locator('#attach-file-button')).toBeVisible({ timeout: 15000 });
+ await expect(page.getByRole('button', { name: 'Attach and tools', exact: true })).toBeVisible({
+ timeout: 15000,
+ });
// application/json is neither overridden nor image/pdf, so it falls through to the
// system fallback ('text'): extracted and delivered as text context, not a provider file.
@@ -141,22 +144,22 @@ test.describe('unified file upload', () => {
expect(persisted?.llmDeliveryPath).toBe('text');
});
- test('legacy endpoint renders the 3-way upload dropdown, not the single button', async ({
- page,
- }) => {
+ test('legacy endpoint uses the palette provider source', async ({ page }) => {
test.setTimeout(120000);
await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
- // Mock Provider A opts into legacyFileUploadUX.
+ // Mock Provider A retains legacy destination routing behind the shared palette.
await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
- // Legacy: the menu-button trigger is present; the unified single button is not.
- await expect(page.locator('#attach-file-menu-button')).toBeVisible({ timeout: 15000 });
- await expect(page.locator('#attach-file-button')).toHaveCount(0);
+ await expect(page.getByRole('button', { name: 'Attach and tools', exact: true })).toBeVisible({
+ timeout: 15000,
+ });
+ await expect(page.getByRole('menu')).toHaveCount(0);
- // Opening it reveals the classic multi-option menu (its always-present entry is
- // the provider upload; the code/file_search options are gated on those ephemeral
- // capabilities being enabled first).
- await page.locator('#attach-file-menu-button').click();
- await expect(page.getByText('Upload to Provider')).toBeVisible();
+ // Opening the palette exposes the provider source row.
+ await page.getByRole('button', { name: 'Attach and tools', exact: true }).click();
+ const palette = page.getByRole('dialog', { name: 'Attach and tools', exact: true });
+ await expect(
+ palette.getByRole('button', { name: 'Upload to Provider', exact: true }),
+ ).toBeVisible();
});
});
diff --git a/eslint-suppressions.json b/eslint-suppressions.json
index 748b965d7b..6005c9c819 100644
--- a/eslint-suppressions.json
+++ b/eslint-suppressions.json
@@ -179,29 +179,11 @@
"count": 1
}
},
- "client/src/components/Chat/Input/Artifacts.tsx": {
- "shadcn/no-restyle": {
- "count": 2
- },
- "shadcn/require-static-classes": {
- "count": 1
- }
- },
"client/src/components/Chat/Input/AskUserQuestionPopover.tsx": {
"shadcn/no-restyle": {
"count": 13
}
},
- "client/src/components/Chat/Input/AudioRecorder.tsx": {
- "shadcn/no-restyle": {
- "count": 4
- }
- },
- "client/src/components/Chat/Input/BadgeRow.tsx": {
- "shadcn/no-inline-styles": {
- "count": 2
- }
- },
"client/src/components/Chat/Input/ChatForm.tsx": {
"shadcn/no-arbitrary-values": {
"count": 4
@@ -221,11 +203,6 @@
"count": 1
}
},
- "client/src/components/Chat/Input/CodeInterpreter.tsx": {
- "shadcn/require-static-classes": {
- "count": 1
- }
- },
"client/src/components/Chat/Input/CodeWorkspaceMenu.tsx": {
"shadcn/no-arbitrary-values": {
"count": 1
@@ -236,21 +213,6 @@
"count": 2
}
},
- "client/src/components/Chat/Input/EditBadges.tsx": {
- "shadcn/no-restyle": {
- "count": 2
- }
- },
- "client/src/components/Chat/Input/FileSearch.tsx": {
- "shadcn/require-static-classes": {
- "count": 1
- }
- },
- "client/src/components/Chat/Input/Files/AttachFileMenu.tsx": {
- "shadcn/no-restyle": {
- "count": 2
- }
- },
"client/src/components/Chat/Input/Files/DragDropOverlay.tsx": {
"shadcn/no-inline-styles": {
"count": 4
@@ -261,7 +223,7 @@
},
"client/src/components/Chat/Input/Files/FileRow.tsx": {
"shadcn/no-inline-styles": {
- "count": 10
+ "count": 7
}
},
"client/src/components/Chat/Input/Files/FileUpload.tsx": {
@@ -321,34 +283,11 @@
"count": 9
}
},
- "client/src/components/Chat/Input/InFlightSteers.tsx": {
- "shadcn/no-unknown-classes": {
- "count": 1
- },
- "shadcn/require-static-classes": {
- "count": 1
- }
- },
"client/src/components/Chat/Input/MCPConfigDialog.tsx": {
"shadcn/no-restyle": {
"count": 17
}
},
- "client/src/components/Chat/Input/MCPSelect.tsx": {
- "shadcn/no-arbitrary-values": {
- "count": 1
- }
- },
- "client/src/components/Chat/Input/MCPSubMenu.tsx": {
- "shadcn/no-restyle": {
- "count": 1
- }
- },
- "client/src/components/Chat/Input/Memory.tsx": {
- "shadcn/require-static-classes": {
- "count": 1
- }
- },
"client/src/components/Chat/Input/Mention.tsx": {
"shadcn/no-restyle": {
"count": 6
@@ -362,11 +301,6 @@
"count": 5
}
},
- "client/src/components/Chat/Input/PendingSteerChips.tsx": {
- "shadcn/no-restyle": {
- "count": 3
- }
- },
"client/src/components/Chat/Input/PopoverButtons.tsx": {
"shadcn/no-restyle": {
"count": 22
@@ -385,24 +319,11 @@
"count": 1
}
},
- "client/src/components/Chat/Input/Skills.tsx": {
- "shadcn/require-static-classes": {
- "count": 1
- }
- },
"client/src/components/Chat/Input/SkillsCommand.tsx": {
"shadcn/no-restyle": {
"count": 6
}
},
- "client/src/components/Chat/Input/SteerMenu.tsx": {
- "shadcn/no-arbitrary-values": {
- "count": 1
- },
- "shadcn/require-static-classes": {
- "count": 3
- }
- },
"client/src/components/Chat/Input/StreamAudio.tsx": {
"shadcn/no-inline-styles": {
"count": 3
@@ -426,16 +347,6 @@
"count": 1
}
},
- "client/src/components/Chat/Input/ToolsDropdown.tsx": {
- "shadcn/no-restyle": {
- "count": 3
- }
- },
- "client/src/components/Chat/Input/WebSearch.tsx": {
- "shadcn/require-static-classes": {
- "count": 1
- }
- },
"client/src/components/Chat/Landing.tsx": {
"shadcn/no-raw-colors": {
"count": 1
@@ -918,7 +829,7 @@
},
"client/src/components/Chat/Messages/MessagesView.tsx": {
"shadcn/no-inline-styles": {
- "count": 3
+ "count": 2
}
},
"client/src/components/Chat/Messages/MinimalHoverButtons.tsx": {
@@ -2024,22 +1935,6 @@
"count": 1
}
},
- "client/src/components/SidePanel/Files/PanelColumns.tsx": {
- "shadcn/no-restyle": {
- "count": 4
- }
- },
- "client/src/components/SidePanel/Files/PanelTable.tsx": {
- "shadcn/no-arbitrary-values": {
- "count": 1
- },
- "shadcn/no-inline-styles": {
- "count": 3
- },
- "shadcn/no-restyle": {
- "count": 6
- }
- },
"client/src/components/SidePanel/MCPBuilder/MCPBuilderPanel.tsx": {
"shadcn/no-restyle": {
"count": 2
diff --git a/eslint.config.mjs b/eslint.config.mjs
index fdc76ee151..b1d1034481 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -57,7 +57,6 @@ export default [
'packages/data-provider/dist/**/*',
'packages/data-provider/test_bundle/**/*',
'packages/data-schemas/dist/**/*',
- 'packages/data-schemas/misc/**/*',
'data-node/**/*',
'meili_data/**/*',
'**/node_modules/**/*',
@@ -347,6 +346,14 @@ export default [
'**/*.spec.tsx',
'**/setupTests.js',
],
+ settings: {
+ jest: {
+ globalAliases: {
+ describe: ['describeIfFerretDB', 'describeLive'],
+ it: ['itIfFerretDB'],
+ },
+ },
+ },
languageOptions: {
globals: {
...globals.jest,
@@ -355,6 +362,7 @@ export default [
},
rules: {
// TEST
+ 'jest/no-standalone-expect': ['error', { additionalTestBlockFunctions: ['itIfFerretDB'] }],
'react/display-name': 'off',
'react/prop-types': 'off',
'jest/no-commented-out-tests': 'off',
@@ -382,8 +390,9 @@ export default [
})),
{
files: ['**/*.ts', '**/*.tsx'],
- // e2e specs keep only the non-type-checked recommended rules from the block above.
- ignores: ['packages/**/*', 'client/vite.config.ts', 'e2e/**/*'],
+ // Package, E2E, and root integration tests are not part of the client
+ // TypeScript project. They still get the recommended rules above.
+ ignores: ['packages/**/*', 'client/vite.config.ts', 'e2e/**/*', 'src/tests/**/*'],
plugins: {
'@typescript-eslint': typescriptEslintEslintPlugin,
jest: fixupPluginRules(jest),
@@ -496,6 +505,13 @@ export default [
parser: tsParser,
ecmaVersion: 'latest',
sourceType: 'module',
+ parserOptions: {
+ project: [
+ './packages/data-schemas/tsconfig.json',
+ './packages/data-schemas/misc/ferretdb/tsconfig.json',
+ './packages/data-schemas/misc/documentdb/tsconfig.json',
+ ],
+ },
},
rules: {
'@typescript-eslint/no-unused-vars': [
diff --git a/librechat.example.yaml b/librechat.example.yaml
index 741fe622b3..3911861392 100644
--- a/librechat.example.yaml
+++ b/librechat.example.yaml
@@ -58,6 +58,8 @@ cache: true
# File storage configuration
# Single strategy for all file types (legacy format, still supported)
# fileStrategy: "s3"
+# Maximum rows returned when GET /files receives an explicit `limit` query parameter.
+# fileListLimit: 100
# Granular file storage strategies (new format - recommended)
# Allows different storage strategies for different file types
diff --git a/packages/api/src/agents/client.spec.ts b/packages/api/src/agents/client.spec.ts
index f3a5b56e9d..a1b27779d1 100644
--- a/packages/api/src/agents/client.spec.ts
+++ b/packages/api/src/agents/client.spec.ts
@@ -3,13 +3,12 @@ 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,
countRetainedToolTokens,
createCachedTokenCounter,
+ payloadParser,
prependQuotes,
prependFileContext,
applyAttachmentOnlyText,
@@ -308,6 +307,68 @@ describe('collectToolCallIds', () => {
expect(collectToolCallIds(undefined)).toEqual(new Set());
});
});
+describe('payloadParser reasoning override persistence', () => {
+ it('returns the base value while the runtime endpoint option uses the override', () => {
+ const req = {
+ body: {
+ endpointOption: {
+ model_parameters: { model: 'gpt-5.1', reasoning_effort: 'high' },
+ },
+ },
+ reasoningOverrideBase: {
+ key: 'reasoning_effort',
+ hadValue: true,
+ value: 'low',
+ },
+ } as unknown as ServerRequest;
+
+ expect(payloadParser({ req, endpoint: 'openAI' })).toEqual({
+ model: 'gpt-5.1',
+ reasoning_effort: 'low',
+ });
+ expect(req.body.endpointOption?.model_parameters?.reasoning_effort).toBe('high');
+ });
+
+ it('omits a transient override when no base value existed', () => {
+ const req = {
+ body: {
+ endpointOption: {
+ model_parameters: { model: 'gpt-5.1', reasoning_effort: 'high' },
+ },
+ },
+ reasoningOverrideBase: {
+ key: 'reasoning_effort',
+ hadValue: false,
+ },
+ } as unknown as ServerRequest;
+
+ expect(payloadParser({ req, endpoint: 'openAI' })).toEqual({ model: 'gpt-5.1' });
+ expect(req.body.endpointOption?.model_parameters?.reasoning_effort).toBe('high');
+ });
+
+ it('restores the conversation thinking switch after a coupled Claude override', () => {
+ const req = {
+ body: {
+ endpointOption: {
+ model_parameters: { model: 'claude-sonnet-4-6', effort: 'max', thinking: true },
+ },
+ },
+ reasoningOverrideBase: {
+ key: 'effort',
+ hadValue: true,
+ value: 'low',
+ thinkingHadValue: true,
+ thinkingValue: false,
+ },
+ } as unknown as ServerRequest;
+
+ expect(payloadParser({ req, endpoint: 'anthropic' })).toEqual({
+ model: 'claude-sonnet-4-6',
+ effort: 'low',
+ thinking: false,
+ });
+ });
+});
describe('prependFileContext', () => {
it('prepends file context to string content', () => {
diff --git a/packages/api/src/agents/client.ts b/packages/api/src/agents/client.ts
index 4b05d2b8e7..16e3e7fa38 100644
--- a/packages/api/src/agents/client.ts
+++ b/packages/api/src/agents/client.ts
@@ -42,7 +42,24 @@ export function payloadParser({
if (isAgentsEndpoint(endpoint)) {
return;
}
- return req.body?.endpointOption?.model_parameters;
+ const modelParameters = req.body?.endpointOption?.model_parameters;
+ if (modelParameters == null || req.reasoningOverrideBase == null) {
+ return modelParameters;
+ }
+
+ const { key, hadValue, value } = req.reasoningOverrideBase;
+ const persistedParameters = { ...modelParameters };
+ if (hadValue) {
+ persistedParameters[key] = value;
+ } else {
+ delete persistedParameters[key];
+ }
+ if (req.reasoningOverrideBase.thinkingHadValue === true) {
+ persistedParameters.thinking = req.reasoningOverrideBase.thinkingValue;
+ } else if (req.reasoningOverrideBase.thinkingHadValue === false) {
+ delete persistedParameters.thinking;
+ }
+ return persistedParameters;
}
/**
diff --git a/packages/api/src/agents/hitl/policy.spec.ts b/packages/api/src/agents/hitl/policy.spec.ts
index 72722060cd..7d4b913b42 100644
--- a/packages/api/src/agents/hitl/policy.spec.ts
+++ b/packages/api/src/agents/hitl/policy.spec.ts
@@ -1,3 +1,4 @@
+import { ReasoningEffort } from 'librechat-data-provider';
import type { Agents, TToolApprovalPolicy } from 'librechat-data-provider';
import {
resolveToolApprovalPolicy,
@@ -17,6 +18,7 @@ import {
sanitizeResumeModelParameters,
pickResumeContext,
applyResumeContext,
+ applyResumeRequest,
applyResumeModelParameters,
exemptAskUserQuestionFromApproval,
isToolApprovalPauseCapable,
@@ -626,6 +628,19 @@ describe('captureResumeModelParameters', () => {
).toEqual({ thinking: false, effort: 'low' });
});
+ test('the validated one-shot reasoning selection wins on resume and re-enables thinking', () => {
+ expect(
+ captureResumeModelParameters(
+ {
+ thinking: false,
+ effort: 'low',
+ reasoningOverride: { key: 'effort', value: 'max' },
+ },
+ { thinking: { type: 'adaptive' }, invocationKwargs: { output_config: { effort: 'max' } } },
+ ),
+ ).toEqual({ thinking: true, effort: 'max' });
+ });
+
test('resolved params still fill gaps the body lacks (normalized to UI form)', () => {
expect(
captureResumeModelParameters(
@@ -793,6 +808,14 @@ describe('computeAgentRequestFingerprint', () => {
});
describe('pickResumeContext / applyResumeContext', () => {
+ it('captures the trusted reasoning snapshot alongside the body fields', () => {
+ const base = { key: 'reasoning_effort' as const, hadValue: true, value: 'low' };
+ const ctx = pickResumeContext({ endpoint: 'agents' }, base);
+ expect(ctx).toEqual({ endpoint: 'agents', reasoningOverrideBase: base });
+ expect(ctx.reasoningOverrideBase).not.toBe(base);
+ expect(pickResumeContext({ endpoint: 'agents' }, null)).toEqual({ endpoint: 'agents' });
+ });
+
it('picks only the graph-determining fields (incl. addedConvo + timezone), dropping unrelated keys', () => {
const ctx = pickResumeContext({
endpoint: 'agents',
@@ -805,6 +828,7 @@ describe('pickResumeContext / applyResumeContext', () => {
timezone: 'America/New_York',
// Graph-determining: skill allowed-tools union into the tool set.
manualSkills: ['code-reviewer'],
+ reasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.high },
// Graph-determining: feeds the ephemeral agent id / checkpoint namespace (#14253).
modelLabel: 'My Opus',
codeApprovalMode: 'acceptEdits',
@@ -823,6 +847,7 @@ describe('pickResumeContext / applyResumeContext', () => {
addedConvo: { agent_id: 'secondary' },
timezone: 'America/New_York',
manualSkills: ['code-reviewer'],
+ reasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.high },
modelLabel: 'My Opus',
codeApprovalMode: 'acceptEdits',
codeEnvironmentMode: 'attached',
@@ -979,6 +1004,42 @@ describe('pickResumeContext / applyResumeContext', () => {
});
});
+describe('applyResumeRequest', () => {
+ it('restores the body, the reasoning snapshot and the generation params together', () => {
+ const reasoningOverrideBase = { key: 'reasoning_effort' as const, hadValue: false };
+ const req: {
+ body: Record<string, unknown>;
+ reasoningOverrideBase?: typeof reasoningOverrideBase;
+ resumeReplayed?: boolean;
+ } = { body: { conversationId: 'c', addedConvo: { endpoint: 'x' } } };
+ applyResumeRequest(req, {
+ endpoint: 'agents',
+ reasoningOverrideBase,
+ model_parameters: { temperature: 0.3, conversationId: 'forged' },
+ });
+ expect(req.body).toEqual({ conversationId: 'c', endpoint: 'agents', temperature: 0.3 });
+ expect(req.reasoningOverrideBase).toEqual(reasoningOverrideBase);
+ expect(req.reasoningOverrideBase).not.toBe(reasoningOverrideBase);
+ /* Marks the request as carrying trusted replayed state, so a replayed
+ override that no longer validates degrades instead of refusing. */
+ expect(req.resumeReplayed).toBe(true);
+ });
+
+ it('leaves the reasoning snapshot unset when the paused turn had none', () => {
+ const req: { body: Record<string, unknown>; reasoningOverrideBase?: undefined } = {
+ body: {},
+ };
+ applyResumeRequest(req, { endpoint: 'agents' });
+ expect(req).not.toHaveProperty('reasoningOverrideBase');
+ });
+
+ it('is a no-op without a persisted context', () => {
+ const req = { body: { ephemeralAgent: null } };
+ applyResumeRequest(req, undefined);
+ expect(req).toEqual({ body: { ephemeralAgent: null } });
+ });
+});
+
describe('applyResumeModelParameters', () => {
it('replays generation params without replacing routing or resume identity fields (#14946)', () => {
const body: Record<string, unknown> = {
diff --git a/packages/api/src/agents/hitl/policy.ts b/packages/api/src/agents/hitl/policy.ts
index 2f832334a6..092d6e2b23 100644
--- a/packages/api/src/agents/hitl/policy.ts
+++ b/packages/api/src/agents/hitl/policy.ts
@@ -1,6 +1,11 @@
import { randomUUID, createHash } from 'crypto';
-import { openAIBaseSchema, googleBaseSchema, anthropicBaseSchema } from 'librechat-data-provider';
-import type { Agents, TToolApprovalPolicy } from 'librechat-data-provider';
+import {
+ openAIBaseSchema,
+ googleBaseSchema,
+ anthropicBaseSchema,
+ reasoningOverrideSchema,
+} from 'librechat-data-provider';
+import type { Agents, TReasoningOverride, TToolApprovalPolicy } from 'librechat-data-provider';
import type { ToolPolicyConfig } from '@librechat/agents';
import type { MCPToolAlias } from '~/tools/classification';
@@ -458,6 +463,9 @@ export const RESUME_CONTEXT_KEYS = [
// different skill's tools (manualSkills isn't covered by the fingerprint). Replay-only.
// (alwaysAppliedSkills is NOT here — it's resolved server-side from the DB, not req.body.)
'manualSkills',
+ // The one-shot reasoning selection is generation-determining and must
+ // survive a HITL continuation across reloads/replicas.
+ 'reasoningOverride',
// Graph-determining for ephemeral agents: `loadEphemeralAgent` encodes the agent id
// (and thus the LangGraph node name / HITL checkpoint namespace) from
// `sender = modelLabel ?? modelSpec.label ?? …`. `modelLabel` is stripped from the
@@ -473,6 +481,14 @@ export const RESUME_CONTEXT_KEYS = [
export type ResumeContext = Partial<Record<(typeof RESUME_CONTEXT_KEYS)[number], unknown>> & {
/** Resolved model params captured at pause (sanitized); replayed by the resume route. */
model_parameters?: Record<string, unknown>;
+ /** Original conversation values hidden from the provider runtime override. */
+ reasoningOverrideBase?: {
+ key: TReasoningOverride['key'];
+ hadValue: boolean;
+ value?: unknown;
+ thinkingHadValue?: boolean;
+ thinkingValue?: unknown;
+ };
};
/** Exact (lowercased) parameter keys that carry credentials or server transport config. */
@@ -694,13 +710,29 @@ export function captureResumeModelParameters(
captured[key] = sanitizeParamValue(body[key], 1);
}
}
+ const reasoningOverride = reasoningOverrideSchema.safeParse(body.reasoningOverride);
+ if (reasoningOverride.success) {
+ captured[reasoningOverride.data.key] = reasoningOverride.data.value;
+ if (
+ reasoningOverride.data.key === 'effort' ||
+ reasoningOverride.data.key === 'thinkingLevel' ||
+ reasoningOverride.data.key === 'thinkingBudget'
+ ) {
+ captured.thinking = true;
+ }
+ }
}
return Object.keys(captured).length > 0 ? captured : undefined;
}
-/** Extract the graph-determining fields from a request body for durable replay. */
-export function pickResumeContext(body: Record<string, unknown> | undefined | null): ResumeContext {
- const ctx: ResumeContext = {};
+/** Extract the graph-determining fields from a request body, and the trusted reasoning
+ * snapshot when the request resolved one, for durable replay. */
+export function pickResumeContext(
+ body: Record<string, unknown> | undefined | null,
+ reasoningOverrideBase?: ResumeContext['reasoningOverrideBase'] | null,
+): ResumeContext {
+ const ctx: ResumeContext =
+ reasoningOverrideBase != null ? { reasoningOverrideBase: { ...reasoningOverrideBase } } : {};
if (body == null) {
return ctx;
}
@@ -737,6 +769,33 @@ export function applyResumeContext(
}
}
+/**
+ * Restore a paused turn onto its resume request: the graph-determining body fields, the
+ * trusted reasoning-override snapshot that keeps a request-scoped override out of saved
+ * conversation defaults, and the resolved generation parameters.
+ */
+export function applyResumeRequest(
+ req: {
+ body?: Record<string, unknown> | null;
+ reasoningOverrideBase?: ResumeContext['reasoningOverrideBase'];
+ resumeReplayed?: boolean;
+ },
+ ctx: ResumeContext | undefined | null,
+): void {
+ applyResumeContext(req.body, ctx);
+ if (ctx != null) {
+ /* Marks the request as carrying trusted server state rather than fresh
+ * client input: a replayed `reasoningOverride` that no longer validates
+ * (the endpoint's reasoning config changed between pause and resume) is
+ * degraded rather than rejected, because a 400 would brick the checkpoint. */
+ req.resumeReplayed = true;
+ }
+ if (ctx?.reasoningOverrideBase != null) {
+ req.reasoningOverrideBase = { ...ctx.reasoningOverrideBase };
+ }
+ applyResumeModelParameters(req.body, ctx?.model_parameters);
+}
+
/** Request-envelope fields that resolved provider params must never replace. */
const RESUME_REQUEST_CONTROL_KEYS = new Set<string>([
...RESUME_CONTEXT_KEYS,
diff --git a/packages/api/src/agents/queuedTurnHttp.spec.ts b/packages/api/src/agents/queuedTurnHttp.spec.ts
index c3627d5f6c..f2afbffb8f 100644
--- a/packages/api/src/agents/queuedTurnHttp.spec.ts
+++ b/packages/api/src/agents/queuedTurnHttp.spec.ts
@@ -1,4 +1,5 @@
import { Types } from 'mongoose';
+import { ReasoningEffort } from 'librechat-data-provider';
import { AgentQueuedTurnLaneRetiredError } from '@librechat/data-schemas';
import type { AgentQueuedTurnMethods, AgentQueuedTurnRecord } from '@librechat/data-schemas';
import type { Request, Response } from 'express';
@@ -25,6 +26,7 @@ function turn(status: AgentQueuedTurnRecord['status']): AgentQueuedTurnRecord {
status,
priority: false,
text: 'follow up',
+ reasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.high },
attempts: status === 'admitted' ? 1 : 0,
availableAt: new Date('2026-08-30T12:00:00Z'),
createdAt: new Date('2026-08-30T12:00:00Z'),
@@ -37,6 +39,7 @@ function requestBody() {
parentMessageId: 'assistant-1',
clientRequestId: 'client-request-1',
text: 'follow up',
+ reasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.high },
};
}
@@ -209,10 +212,46 @@ describe('Agent queued-turn HTTP admission receipts', () => {
getAgentQueuedTurnByClientRequestId.mock.calls[0][0],
);
expect(enqueueAgentQueuedTurn).toHaveBeenCalledTimes(1);
+ expect(enqueueAgentQueuedTurn).toHaveBeenCalledWith(
+ expect.objectContaining({
+ reasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.high },
+ }),
+ );
expect(methods.getConvo).toHaveBeenCalledTimes(1);
expect(schedule).toHaveBeenCalledTimes(1);
});
+ it('rejects an idempotent replay when only the reasoning override changes', async () => {
+ const existing = turn('queued');
+ const methods = {
+ getConvo: jest.fn(),
+ getAgentQueuedTurnByClientRequestId: jest.fn(async () => existing),
+ enqueueAgentQueuedTurn: jest.fn(),
+ };
+ const deps = {
+ methods: methods as unknown as AgentQueuedTurnMethods & {
+ getConvo: typeof methods.getConvo;
+ },
+ lifecycle: { schedule: jest.fn(), cancel: jest.fn() },
+ } satisfies AgentQueuedTurnHttpDeps;
+
+ await expect(
+ handleAgentQueuedTurnEnqueue(
+ { id: USER_ID },
+ {
+ ...requestBody(),
+ reasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.low },
+ },
+ deps,
+ ),
+ ).resolves.toEqual({
+ status: 409,
+ body: { code: 'QUEUED_TURN_IDEMPOTENCY_CONFLICT' },
+ });
+ expect(methods.getConvo).not.toHaveBeenCalled();
+ expect(methods.enqueueAgentQueuedTurn).not.toHaveBeenCalled();
+ });
+
it('surfaces a dead receipt and lets the user dismiss its delivery', async () => {
const dead = {
...turn('dead'),
diff --git a/packages/api/src/agents/queuedTurnHttp.ts b/packages/api/src/agents/queuedTurnHttp.ts
index 97440344a7..1b0743f5d0 100644
--- a/packages/api/src/agents/queuedTurnHttp.ts
+++ b/packages/api/src/agents/queuedTurnHttp.ts
@@ -21,6 +21,7 @@ import type {
TAgentQueuedTurnFileRef,
TAgentQueuedTurnReceipt,
TFile,
+ TReasoningOverride,
} from 'librechat-data-provider';
import type { Request, RequestHandler } from 'express';
import type { AgentQueuedTurnLifecycle } from './queuedTurns';
@@ -91,7 +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 && {
expectedPredecessorCreatedAt: turn.expectedPredecessorCreatedAt,
@@ -138,6 +139,13 @@ function uniqueStrings(values: readonly string[] | undefined): string[] | undefi
return values == null ? undefined : [...new Set(values)];
}
+function sameReasoningOverride(
+ left: TReasoningOverride | undefined,
+ right: TReasoningOverride | undefined,
+): boolean {
+ return left?.key === right?.key && left?.value === right?.value;
+}
+
function matchesReplayIntent(
turn: AgentQueuedTurnRecord,
input: {
@@ -145,7 +153,7 @@ function matchesReplayIntent(
clientRequestId: string;
files?: readonly TAgentQueuedTurnFileRef[];
manualSkills?: readonly string[];
- codeApprovalMode?: CodeApprovalMode;
+ reasoningOverride?: TReasoningOverride;
expectedPredecessorCreatedAt?: number;
},
text: string,
@@ -161,7 +169,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
);
}
@@ -349,7 +357,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 && {
expectedPredecessorCreatedAt: input.expectedPredecessorCreatedAt,
diff --git a/packages/api/src/agents/queuedTurns.spec.ts b/packages/api/src/agents/queuedTurns.spec.ts
index 61e8bc390d..6c204e52a0 100644
--- a/packages/api/src/agents/queuedTurns.spec.ts
+++ b/packages/api/src/agents/queuedTurns.spec.ts
@@ -1,4 +1,5 @@
import { Types } from 'mongoose';
+import { ReasoningEffort } from 'librechat-data-provider';
import type {
AgentQueuedTurnClaim,
AgentQueuedTurnMethods,
@@ -62,6 +63,7 @@ function claim(): AgentQueuedTurnClaim {
files: [{ file_id: 'file-1' }],
quotes: ['quote'],
manualSkills: ['skill-1'],
+ reasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.high },
attempts: 1,
availableAt: new Date(NOW),
claimId: 'trigger-1',
@@ -280,6 +282,7 @@ describe('Agent queued-turn continuation', () => {
files: [{ file_id: 'file-1' }],
quotes: ['quote'],
manualSkills: ['skill-1'],
+ reasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.high },
admissionSource: {
source: AGENT_QUEUED_TURN_SOURCE,
sourceId: 'queued-turn-1',
diff --git a/packages/api/src/agents/queuedTurns.ts b/packages/api/src/agents/queuedTurns.ts
index 693bc54acf..6230b84041 100644
--- a/packages/api/src/agents/queuedTurns.ts
+++ b/packages/api/src/agents/queuedTurns.ts
@@ -647,7 +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,
sourceId: claim.queuedTurnId,
diff --git a/packages/api/src/agents/triggers/host.spec.ts b/packages/api/src/agents/triggers/host.spec.ts
index 45c4b5fd0c..b86de1484a 100644
--- a/packages/api/src/agents/triggers/host.spec.ts
+++ b/packages/api/src/agents/triggers/host.spec.ts
@@ -1,5 +1,5 @@
-import { Constants, EModelEndpoint } from 'librechat-data-provider';
import { getRequestId, getTenantId, getUserId } from '@librechat/data-schemas';
+import { Constants, EModelEndpoint, ReasoningEffort } from 'librechat-data-provider';
import type { AgentTriggerExecutionHostDeps, AgentTriggerFetch } from './host';
import {
EVENT_ACTOR_DETACHED_COMPLETION_SOURCE,
@@ -645,7 +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,7 +667,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,
});
expect(getBaseUrl).toHaveBeenCalledWith({ localOnly: true });
diff --git a/packages/api/src/agents/triggers/host.ts b/packages/api/src/agents/triggers/host.ts
index 4dad9baf8b..93e32d0467 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 { CodeApprovalMode, TFile } from 'librechat-data-provider';
+import type { TFile, TReasoningOverride } from 'librechat-data-provider';
import type {
AgentContinueTriggerEnvelope,
AgentFireTriggerEnvelope,
@@ -58,9 +58,7 @@ 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. */
admissionSource?: AgentContinuationAdmissionSource;
@@ -677,6 +675,9 @@ async function startRun(
...(readyPreparation?.manualSkills != null && {
manualSkills: readyPreparation.manualSkills,
}),
+ ...(readyPreparation?.reasoningOverride != null && {
+ reasoningOverride: readyPreparation.reasoningOverride,
+ }),
isContinued: false,
isRegenerate: false,
clientRequestId: context.idempotencyKey,
diff --git a/packages/api/src/cache/__tests__/cacheFactory/limiterCache.cache_integration.spec.ts b/packages/api/src/cache/__tests__/cacheFactory/limiterCache.cache_integration.spec.ts
index 9ccc830a7b..444c8f3a7d 100644
--- a/packages/api/src/cache/__tests__/cacheFactory/limiterCache.cache_integration.spec.ts
+++ b/packages/api/src/cache/__tests__/cacheFactory/limiterCache.cache_integration.spec.ts
@@ -56,9 +56,23 @@ describe('limiterCache', () => {
// Verify it returns a RedisStore instance
expect(testStore).toBeDefined();
expect(testStore!.constructor.name).toBe('RedisStore');
- expect(testStore!.prefix).toBe('test-limiter:');
+ expect(testStore!.prefix).toBe('Cache-Integration-Test::test-limiter:');
expect(typeof testStore!.sendCommand).toBe('function');
+ // rate-limit-redis sends uppercase dynamic commands. The pinned ioredis
+ // key lookup is case-sensitive, so these raw calls bypass keyPrefix and
+ // RedisStore must carry the deployment prefix itself.
+ const limiterKey = 'rate-limit-user:123';
+ testStore!.init({ windowMs: 60_000 } as Parameters<RedisStore['init']>[0]);
+ await expect(testStore!.increment(limiterKey)).resolves.toMatchObject({ totalHits: 1 });
+ expect(await ioredisClient!.call('GET', `${testStore!.prefix}${limiterKey}`)).toBe('1');
+ expect(await ioredisClient!.call('GET', `test-limiter:${limiterKey}`)).toBeNull();
+ expect(
+ await ioredisClient!.call('GET', `Cache-Integration-Test::${testStore!.prefix}${limiterKey}`),
+ ).toBeNull();
+ await testStore!.resetKey(limiterKey);
+ expect(await ioredisClient!.call('GET', `${testStore!.prefix}${limiterKey}`)).toBeNull();
+
const testKey = 'user:123';
// SET operation
diff --git a/packages/api/src/cache/__tests__/limiterSendCommand.spec.ts b/packages/api/src/cache/__tests__/limiterSendCommand.spec.ts
new file mode 100644
index 0000000000..b1d9850a38
--- /dev/null
+++ b/packages/api/src/cache/__tests__/limiterSendCommand.spec.ts
@@ -0,0 +1,22 @@
+import type { SendCommandFn } from 'rate-limit-redis';
+import { createClusterSafeSendCommand } from '../limiterSendCommand';
+
+describe('createClusterSafeSendCommand', () => {
+ it('falls back to EVAL with the cached script when a cluster node returns NOSCRIPT', async () => {
+ const execute = jest.fn<ReturnType<SendCommandFn>, Parameters<SendCommandFn>>();
+ execute
+ .mockResolvedValueOnce('script-sha')
+ .mockRejectedValueOnce(new Error('NOSCRIPT No matching script. Please use EVAL.'))
+ .mockResolvedValueOnce([1, 60_000]);
+ const sendCommand = createClusterSafeSendCommand(execute);
+ const script = 'return redis.call("INCR", KEYS[1])';
+
+ await expect(sendCommand('SCRIPT', 'LOAD', script)).resolves.toBe('script-sha');
+ await expect(sendCommand('EVALSHA', 'script-sha', '1', 'limiter:key')).resolves.toEqual([
+ 1, 60_000,
+ ]);
+
+ expect(execute).toHaveBeenNthCalledWith(2, 'EVALSHA', 'script-sha', '1', 'limiter:key');
+ expect(execute).toHaveBeenNthCalledWith(3, 'EVAL', script, '1', 'limiter:key');
+ });
+});
diff --git a/packages/api/src/cache/cacheFactory.ts b/packages/api/src/cache/cacheFactory.ts
index e41d665fbc..07e443cac8 100644
--- a/packages/api/src/cache/cacheFactory.ts
+++ b/packages/api/src/cache/cacheFactory.ts
@@ -15,6 +15,7 @@ import { Time, CacheKeys } from 'librechat-data-provider';
import { RedisStore as ConnectRedis } from 'connect-redis';
import type { SendCommandFn } from 'rate-limit-redis';
import { keyvRedisClient, ioredisClient, handleKeyvRedisError } from './redisClients';
+import { createClusterSafeSendCommand } from './limiterSendCommand';
import { batchDeleteKeys, scanKeys } from './redisUtils';
import {
instrumentIORedisClient,
@@ -191,27 +192,36 @@ export const limiterCache = (prefix: string): RedisStore | undefined => {
if (!cacheConfig.USE_REDIS) {
return undefined;
}
- // Note: The `prefix` is applied by RedisStore internally to its key operations.
- // The global REDIS_KEY_PREFIX is applied by ioredisClient's keyPrefix setting.
- // Combined key format: `{REDIS_KEY_PREFIX}::{prefix}{identifier}`
+ // rate-limit-redis supplies uppercase command names to `call()`. In the
+ // pinned ioredis version, dynamic-command key metadata is case-sensitive,
+ // so those calls bypass the configured keyPrefix, including EVALSHA keys.
+ // Include the deployment prefix here exactly once.
prefix = prefix.endsWith(':') ? prefix : `${prefix}:`;
+ const deploymentPrefix = cacheConfig.REDIS_KEY_PREFIX
+ ? `${cacheConfig.REDIS_KEY_PREFIX}${cacheConfig.GLOBAL_PREFIX_SEPARATOR}`
+ : '';
+ const limiterPrefix = `${deploymentPrefix}${prefix}`;
try {
- const sendCommand: SendCommandFn = (async (...args: string[]) => {
+ const executeCommand = (async (...args: string[]) => {
const redisClient = ioredisClient;
if (redisClient == null) {
throw new Error('Redis client not available');
}
+ return await observeRedisOperation('ioredis', RedisUseCases.RATE_LIMIT, args[0], () =>
+ redisClient.call(args[0], ...args.slice(1)),
+ );
+ }) as SendCommandFn;
+ const clusterSafeCommand = createClusterSafeSendCommand(executeCommand);
+ const sendCommand: SendCommandFn = async (...args: string[]) => {
try {
- return await observeRedisOperation('ioredis', RedisUseCases.RATE_LIMIT, args[0], () =>
- redisClient.call(args[0], ...args.slice(1)),
- );
+ return await clusterSafeCommand(...args);
} catch (err) {
logger.error('Redis command execution failed:', err);
throw err;
}
- }) as SendCommandFn;
- return new RedisStore({ sendCommand, prefix });
+ };
+ return new RedisStore({ sendCommand, prefix: limiterPrefix });
} catch (err) {
logger.error(`Failed to create Redis rate limiter for prefix ${prefix}:`, err);
return undefined;
diff --git a/packages/api/src/cache/limiterSendCommand.ts b/packages/api/src/cache/limiterSendCommand.ts
new file mode 100644
index 0000000000..35fb538c61
--- /dev/null
+++ b/packages/api/src/cache/limiterSendCommand.ts
@@ -0,0 +1,41 @@
+import type { SendCommandFn } from 'rate-limit-redis';
+
+const isNoScriptError = (error: unknown): boolean => {
+ const code = (error as { code?: unknown } | null)?.code;
+ if (typeof code === 'string' && code.toUpperCase() === 'NOSCRIPT') {
+ return true;
+ }
+ const message = error instanceof Error ? error.message : String(error);
+ return message.startsWith('NOSCRIPT ');
+};
+
+/**
+ * Redis Cluster loads a script on one node, while EVALSHA routes to the node
+ * that owns the command's key. Cache each loaded script so a NOSCRIPT reply can
+ * fall back to EVAL on the correctly routed node.
+ */
+export const createClusterSafeSendCommand = (execute: SendCommandFn): SendCommandFn => {
+ const scriptsBySha = new Map<string, string>();
+
+ return async (...args: string[]) => {
+ const command = args[0]?.toUpperCase();
+ try {
+ const result = await execute(...args);
+ if (
+ command === 'SCRIPT' &&
+ args[1]?.toUpperCase() === 'LOAD' &&
+ typeof args[2] === 'string' &&
+ typeof result === 'string'
+ ) {
+ scriptsBySha.set(result, args[2]);
+ }
+ return result;
+ } catch (error) {
+ const script = command === 'EVALSHA' ? scriptsBySha.get(args[1]) : undefined;
+ if (script == null || !isNoScriptError(error)) {
+ throw error;
+ }
+ return execute('EVAL', script, ...args.slice(2));
+ }
+ };
+};
diff --git a/packages/api/src/files/index.ts b/packages/api/src/files/index.ts
index 0d5a83dde5..fb20a690ed 100644
--- a/packages/api/src/files/index.ts
+++ b/packages/api/src/files/index.ts
@@ -27,3 +27,4 @@ export * from './sweep';
export * from './usage';
export * from './validation';
export * from './text';
+export * from './list';
diff --git a/packages/api/src/files/list.spec.ts b/packages/api/src/files/list.spec.ts
new file mode 100644
index 0000000000..1aef721e7f
--- /dev/null
+++ b/packages/api/src/files/list.spec.ts
@@ -0,0 +1,162 @@
+import { FileSources } from 'librechat-data-provider';
+import { DEFAULT_FILE_LIST_LIMIT, handleFileListRequest, type FileListDependencies } from './list';
+
+const staleFile = {
+ file_id: 'f1',
+ user: 'user-123',
+ source: FileSources.s3,
+ filepath: 'https://bucket.s3.amazonaws.com/key?X-Amz-Expires=1',
+};
+const freshFile = { ...staleFile, filepath: 'https://bucket.s3.amazonaws.com/key?X-Amz-Expires=2' };
+
+function createDependencies(files = [staleFile]) {
+ const cache = {
+ get: jest.fn().mockResolvedValue(null),
+ set: jest.fn().mockResolvedValue(undefined),
+ };
+ const dependencies: FileListDependencies = {
+ getFiles: jest.fn().mockResolvedValue(files),
+ batchUpdateFiles: jest.fn().mockResolvedValue(undefined),
+ refreshS3FileUrls: jest.fn().mockResolvedValue(files),
+ getLogStores: jest.fn().mockReturnValue(cache),
+ logger: { warn: jest.fn() },
+ };
+ return { dependencies, cache };
+}
+
+describe('handleFileListRequest', () => {
+ it('passes a positive query limit through to the owner-scoped query', async () => {
+ const { dependencies } = createDependencies([]);
+
+ await handleFileListRequest({
+ userId: 'user-123',
+ rawLimit: '5',
+ fileStrategy: FileSources.local,
+ dependencies,
+ });
+
+ expect(dependencies.getFiles).toHaveBeenCalledWith({ user: 'user-123' }, null, null, 5);
+ });
+
+ it('caps an explicit query limit at the default deployment limit', async () => {
+ const { dependencies } = createDependencies([]);
+
+ await handleFileListRequest({
+ userId: 'user-123',
+ rawLimit: '100000',
+ fileStrategy: FileSources.local,
+ dependencies,
+ });
+
+ expect(dependencies.getFiles).toHaveBeenCalledWith(
+ { user: 'user-123' },
+ null,
+ null,
+ DEFAULT_FILE_LIST_LIMIT,
+ );
+ });
+
+ it('uses the configured maximum instead of the default cap', async () => {
+ const { dependencies } = createDependencies([]);
+
+ await handleFileListRequest({
+ userId: 'user-123',
+ rawLimit: '100000',
+ maxLimit: 250,
+ fileStrategy: FileSources.local,
+ dependencies,
+ });
+
+ expect(dependencies.getFiles).toHaveBeenCalledWith({ user: 'user-123' }, null, null, 250);
+ });
+
+ it.each([undefined, 'abc', '0', '-1'])('leaves %p as an unlimited query', async (rawLimit) => {
+ const { dependencies } = createDependencies([]);
+
+ await handleFileListRequest({
+ userId: 'user-123',
+ rawLimit,
+ fileStrategy: FileSources.local,
+ dependencies,
+ });
+
+ expect(dependencies.getFiles).toHaveBeenCalledWith({ user: 'user-123' }, null, null, undefined);
+ });
+
+ it('returns refreshed S3 rows and avoids marking a limited request as a full-list check', async () => {
+ const { dependencies, cache } = createDependencies([staleFile]);
+ dependencies.refreshS3FileUrls = jest.fn().mockResolvedValue([freshFile]);
+
+ const result = await handleFileListRequest({
+ userId: 'user-123',
+ rawLimit: '5',
+ fileStrategy: FileSources.s3,
+ dependencies,
+ });
+
+ expect(result).toEqual([freshFile]);
+ expect(dependencies.refreshS3FileUrls).toHaveBeenCalledWith(
+ [staleFile],
+ dependencies.batchUpdateFiles,
+ );
+ expect(cache.set).not.toHaveBeenCalled();
+ });
+
+ it('marks the cache after refreshing an unlimited S3 request', async () => {
+ const { dependencies, cache } = createDependencies([staleFile]);
+ dependencies.refreshS3FileUrls = jest.fn().mockResolvedValue([freshFile]);
+
+ const result = await handleFileListRequest({
+ userId: 'user-123',
+ fileStrategy: FileSources.s3,
+ dependencies,
+ });
+
+ expect(result).toEqual([freshFile]);
+ expect(cache.set).toHaveBeenCalledWith('user-123', true, expect.any(Number));
+ });
+
+ it('skips S3 refresh when the user interval is already marked', async () => {
+ const { dependencies, cache } = createDependencies([staleFile]);
+ cache.get.mockResolvedValue(true);
+
+ const result = await handleFileListRequest({
+ userId: 'user-123',
+ fileStrategy: FileSources.s3,
+ dependencies,
+ });
+
+ expect(dependencies.refreshS3FileUrls).not.toHaveBeenCalled();
+ expect(result).toEqual([staleFile]);
+ });
+
+ it('keeps original rows when S3 refresh fails and reports the warning', async () => {
+ const { dependencies } = createDependencies([staleFile]);
+ dependencies.refreshS3FileUrls = jest.fn().mockRejectedValue(new Error('s3 down'));
+
+ const result = await handleFileListRequest({
+ userId: 'user-123',
+ fileStrategy: FileSources.s3,
+ dependencies,
+ });
+
+ expect(result).toEqual([staleFile]);
+ expect(dependencies.logger.warn).toHaveBeenCalledWith(
+ '[/files] Error refreshing S3 file URLs:',
+ expect.any(Error),
+ );
+ });
+
+ it('does not access S3 for local deployments', async () => {
+ const { dependencies } = createDependencies([staleFile]);
+
+ await handleFileListRequest({
+ userId: 'user-123',
+ fileStrategy: FileSources.local,
+ dependencies,
+ });
+
+ expect(dependencies.refreshS3FileUrls).not.toHaveBeenCalled();
+ expect(dependencies.getLogStores).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/api/src/files/list.ts b/packages/api/src/files/list.ts
new file mode 100644
index 0000000000..ff4cd2da57
--- /dev/null
+++ b/packages/api/src/files/list.ts
@@ -0,0 +1,87 @@
+import { CacheKeys, FileSources, Time } from 'librechat-data-provider';
+import type { TFile } from 'librechat-data-provider';
+
+/** Default maximum number of files returned for an explicitly limited list request. */
+export const DEFAULT_FILE_LIST_LIMIT = 100;
+
+export type FileListCache = {
+ get: (key: string) => Promise<unknown>;
+ set: (key: string, value: boolean, ttl: number) => Promise<unknown>;
+};
+
+export type FileListLogger = {
+ warn: (message: string, error?: unknown) => void;
+};
+
+export type FileListDependencies = {
+ getFiles: (
+ filter: { user: string },
+ projection: null,
+ options: null,
+ limit?: number,
+ ) => Promise<TFile[] | null | undefined>;
+ batchUpdateFiles: (...args: unknown[]) => Promise<unknown>;
+ refreshS3FileUrls: (
+ files: TFile[] | null | undefined,
+ batchUpdateFiles: FileListDependencies['batchUpdateFiles'],
+ ) => Promise<TFile[]>;
+ getLogStores: (key: string) => FileListCache;
+ logger: FileListLogger;
+};
+
+export type FileListRequest = {
+ userId: string;
+ rawLimit?: unknown;
+ fileStrategy?: string;
+ maxLimit?: number;
+ dependencies: FileListDependencies;
+};
+
+const resolveMaxLimit = (maxLimit: number | undefined): number => {
+ if (Number.isFinite(maxLimit) && maxLimit != null && maxLimit > 0) {
+ return Math.floor(maxLimit);
+ }
+ return DEFAULT_FILE_LIST_LIMIT;
+};
+
+const parseLimit = (rawLimit: unknown, maxLimit: number): number | undefined => {
+ const numericLimit = Number(rawLimit);
+ return Number.isFinite(numericLimit) && numericLimit > 0
+ ? Math.min(Math.floor(numericLimit), maxLimit)
+ : undefined;
+};
+
+/**
+ * Loads one user's files and applies the list endpoint's query and S3 refresh policy.
+ * An omitted or invalid query limit remains an unlimited request, while an explicit
+ * positive limit is bounded by the deployment's configured `maxLimit`.
+ */
+export async function handleFileListRequest({
+ userId,
+ rawLimit,
+ fileStrategy,
+ maxLimit,
+ dependencies,
+}: FileListRequest): Promise<TFile[] | null | undefined> {
+ const limit = parseLimit(rawLimit, resolveMaxLimit(maxLimit));
+ const files = await dependencies.getFiles({ user: userId }, null, null, limit);
+
+ let responseFiles = files;
+ if (fileStrategy === FileSources.s3) {
+ try {
+ const cache = dependencies.getLogStores(CacheKeys.S3_EXPIRY_INTERVAL);
+ const alreadyChecked = await cache.get(userId);
+ if (!alreadyChecked) {
+ responseFiles = await dependencies.refreshS3FileUrls(files, dependencies.batchUpdateFiles);
+ /** A limited palette refresh must not mark the user's full list as checked. */
+ if (limit == null) {
+ await cache.set(userId, true, Time.THIRTY_MINUTES);
+ }
+ }
+ } catch (error) {
+ dependencies.logger.warn('[/files] Error refreshing S3 file URLs:', error);
+ }
+ }
+
+ return responseFiles;
+}
diff --git a/packages/api/src/modelSpecs/index.ts b/packages/api/src/modelSpecs/index.ts
index 72c4f28ef8..167ed801a6 100644
--- a/packages/api/src/modelSpecs/index.ts
+++ b/packages/api/src/modelSpecs/index.ts
@@ -47,6 +47,10 @@ export type ApplyModelSpecPresetParams = {
export type ApplyModelSpecPresetResult = {
parsedBody: ModelSpecParsedBody;
appliedPrivateFields: Set<PrivateModelSpecPresetField>;
+ /** The keys an enforced spec locks: exactly the fields its preset defines.
+ * Refusal rules downstream (reasoning-override validation) key off this set,
+ * so its derivation lives with the facade rather than in route wiring. */
+ enforcedFields: Set<string>;
};
function hasModelSpecValue(field: PrivateModelSpecPresetField, value: unknown): boolean {
@@ -85,7 +89,7 @@ function mergeModelSpecPreset(
modelSpec: TModelSpec,
parsedBody: ModelSpecParsedBody,
{ includePresetDefaults = false }: Pick<ApplyModelSpecPresetParams, 'includePresetDefaults'> = {},
-): ApplyModelSpecPresetResult {
+): Pick<ApplyModelSpecPresetResult, 'parsedBody' | 'appliedPrivateFields'> {
const preset = modelSpec.preset;
const requestFields = includePresetDefaults
? pickEnforcedModelSpecRequestFields(parsedBody)
@@ -195,7 +199,11 @@ export function applyModelSpecPreset({
modelSpecParsedBody.iconURL = modelSpec.iconURL;
}
- return { parsedBody: modelSpecParsedBody, appliedPrivateFields };
+ return {
+ parsedBody: modelSpecParsedBody,
+ appliedPrivateFields,
+ enforcedFields: new Set(Object.keys(modelSpec.preset)),
+ };
}
export function resolveModelSpecPromptPrefixVariables<T extends { promptPrefix?: string | null }>(
@@ -284,3 +292,5 @@ export function sanitizeModelSpecs<T extends Partial<TSpecsConfig> | null | unde
}),
} as T;
}
+export * from './reasoningOverride';
+export * from './persistedReasoningOverride';
diff --git a/packages/api/src/modelSpecs/modelSpecs.test.ts b/packages/api/src/modelSpecs/modelSpecs.test.ts
index 359ff23b8a..d544669f62 100644
--- a/packages/api/src/modelSpecs/modelSpecs.test.ts
+++ b/packages/api/src/modelSpecs/modelSpecs.test.ts
@@ -90,7 +90,7 @@ describe('modelSpecs helpers', () => {
},
};
- const { parsedBody, appliedPrivateFields } = applyModelSpecPreset({
+ const { parsedBody, appliedPrivateFields, enforcedFields } = applyModelSpecPreset({
modelSpec,
parsedBody: {
endpoint: EModelEndpoint.openAI,
@@ -108,6 +108,9 @@ describe('modelSpecs helpers', () => {
expect(parsedBody.maxContextTokens).toBeUndefined();
expect(parsedBody.iconURL).toBe(EModelEndpoint.openAI);
expect(appliedPrivateFields.has('promptPrefix')).toBe(true);
+ /* The keys an enforced spec locks are exactly its preset's fields: the
+ reasoning-override refusal rule keys off this set. */
+ expect([...enforcedFields].sort()).toEqual([...Object.keys(modelSpec.preset)].sort());
});
it('should restore preset defaults when model specs are enforced', () => {
diff --git a/packages/api/src/modelSpecs/persistedReasoningOverride.spec.ts b/packages/api/src/modelSpecs/persistedReasoningOverride.spec.ts
new file mode 100644
index 0000000000..3ece40c109
--- /dev/null
+++ b/packages/api/src/modelSpecs/persistedReasoningOverride.spec.ts
@@ -0,0 +1,56 @@
+import { ReasoningEffort } from 'librechat-data-provider';
+import {
+ persistedReasoningOverrideFields,
+ resolvePersistedReasoningOverride,
+ type PersistedReasoningOverride,
+ type PersistedReasoningOverrideInput,
+} from './persistedReasoningOverride';
+
+const resolve = (
+ overrides: Partial<PersistedReasoningOverrideInput> = {},
+): PersistedReasoningOverride =>
+ resolvePersistedReasoningOverride({
+ rawReasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.high },
+ ...overrides,
+ });
+
+describe('resolvePersistedReasoningOverride', () => {
+ it('returns the schema-normalized override for a fresh turn', () => {
+ expect(resolve()).toEqual({ key: 'reasoning_effort', value: ReasoningEffort.high });
+ });
+
+ it.each([
+ undefined,
+ null,
+ { key: 'model', value: 'secret-model' },
+ { key: 'thinkingBudget', value: -2 },
+ ])('omits an invalid request override: %o', (rawReasoningOverride) => {
+ expect(resolve({ rawReasoningOverride })).toBeUndefined();
+ });
+
+ it.each([
+ ['edited', { isEdited: true }],
+ ['compaction', { isCompaction: true }],
+ ])('omits the override on a %s turn', (_name, flags) => {
+ expect(resolve(flags)).toBeUndefined();
+ });
+});
+
+describe('persistedReasoningOverrideFields', () => {
+ it('carries a fresh turn override as a message field', () => {
+ expect(
+ persistedReasoningOverrideFields({
+ rawReasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.high },
+ }),
+ ).toEqual({ reasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.high } });
+ });
+
+ it('adds no field for an edit, a compaction or an invalid payload', () => {
+ const rawReasoningOverride = { key: 'reasoning_effort', value: ReasoningEffort.high };
+ expect(persistedReasoningOverrideFields({ rawReasoningOverride, isEdited: true })).toEqual({});
+ expect(persistedReasoningOverrideFields({ rawReasoningOverride, isCompaction: true })).toEqual(
+ {},
+ );
+ expect(persistedReasoningOverrideFields({ rawReasoningOverride: { key: 'x' } })).toEqual({});
+ });
+});
diff --git a/packages/api/src/modelSpecs/persistedReasoningOverride.ts b/packages/api/src/modelSpecs/persistedReasoningOverride.ts
new file mode 100644
index 0000000000..6d8a0579a0
--- /dev/null
+++ b/packages/api/src/modelSpecs/persistedReasoningOverride.ts
@@ -0,0 +1,38 @@
+import { reasoningOverrideSchema, type TReasoningOverride } from 'librechat-data-provider';
+
+export type PersistedReasoningOverrideInput = {
+ rawReasoningOverride: unknown;
+ isEdited?: boolean;
+ isCompaction?: boolean;
+};
+
+export type PersistedReasoningOverride = TReasoningOverride | undefined;
+
+/**
+ * Resolves the validated request-scoped reasoning metadata for a user turn.
+ * Existing messages and compaction anchors already represent persisted turns,
+ * so only a fresh, non-compaction turn may carry the request override.
+ */
+export function resolvePersistedReasoningOverride({
+ rawReasoningOverride,
+ isEdited,
+ isCompaction,
+}: PersistedReasoningOverrideInput): PersistedReasoningOverride {
+ if (isEdited || isCompaction) {
+ return undefined;
+ }
+
+ const parsed = reasoningOverrideSchema.safeParse(rawReasoningOverride);
+ return parsed.success ? parsed.data : undefined;
+}
+
+/**
+ * The same resolution shaped as message fields, so a caller spreads or assigns
+ * the result instead of branching on whether the turn carries an override.
+ */
+export function persistedReasoningOverrideFields(input: PersistedReasoningOverrideInput): {
+ reasoningOverride?: TReasoningOverride;
+} {
+ const reasoningOverride = resolvePersistedReasoningOverride(input);
+ return reasoningOverride === undefined ? {} : { reasoningOverride };
+}
diff --git a/packages/api/src/modelSpecs/reasoningOverride.spec.ts b/packages/api/src/modelSpecs/reasoningOverride.spec.ts
new file mode 100644
index 0000000000..78bb7197a7
--- /dev/null
+++ b/packages/api/src/modelSpecs/reasoningOverride.spec.ts
@@ -0,0 +1,527 @@
+import {
+ AnthropicEffort,
+ EModelEndpoint,
+ ReasoningEffort,
+ ReasoningParameterFormat,
+ ThinkingLevel,
+ type TReasoningOverride,
+} from 'librechat-data-provider';
+import {
+ parseReasoningOverrideRequest,
+ resolveReasoningOverride,
+ applyRequestReasoningOverride,
+ type ReasoningOverrideBase,
+ type ReasoningOverrideInput,
+ type ReasoningOverrideResult,
+} from './reasoningOverride';
+
+const baseInput: ReasoningOverrideInput = {
+ reasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.high },
+ endpointOption: {
+ model_parameters: { model: 'gpt-5.1', reasoning_effort: 'low' },
+ agent: Promise.resolve({ provider: EModelEndpoint.openAI, model: 'gpt-5.1' }),
+ },
+ endpoint: EModelEndpoint.openAI,
+ isAgent: true,
+ endpointsConfig: {},
+};
+
+const resolve = async (
+ overrides: Partial<ReasoningOverrideInput> = {},
+): Promise<ReasoningOverrideResult> =>
+ resolveReasoningOverride({
+ ...baseInput,
+ ...overrides,
+ endpointOption: {
+ ...baseInput.endpointOption,
+ ...overrides.endpointOption,
+ },
+ });
+
+describe('parseReasoningOverrideRequest', () => {
+ it('accepts a request that carries no reasoning override', () => {
+ expect(parseReasoningOverrideRequest(undefined)).toEqual({ ok: true });
+ expect(parseReasoningOverrideRequest(null)).toEqual({ ok: true });
+ });
+
+ it('returns the parsed override for a well-formed payload', () => {
+ const result = parseReasoningOverrideRequest({
+ key: 'reasoning_effort',
+ value: ReasoningEffort.high,
+ });
+
+ expect(result.ok).toBe(true);
+ expect(result.ok && result.reasoningOverride).toEqual({
+ key: 'reasoning_effort',
+ value: ReasoningEffort.high,
+ });
+ });
+
+ it('rejects an unknown key rather than passing it to the resolver', () => {
+ expect(
+ parseReasoningOverrideRequest({ key: 'not_a_reasoning_field', value: ReasoningEffort.high }),
+ ).toEqual({
+ ok: false,
+ reason: 'invalid-reasoning-override',
+ });
+ });
+
+ it('rejects a payload that is not an object', () => {
+ expect(parseReasoningOverrideRequest('reasoning_effort')).toEqual({
+ ok: false,
+ reason: 'invalid-reasoning-override',
+ });
+ });
+});
+
+describe('resolveReasoningOverride', () => {
+ it('applies a supported override and records the existing value', async () => {
+ const result = await resolve();
+
+ expect(result).toEqual({
+ ok: true,
+ modelParameters: {
+ model: 'gpt-5.1',
+ reasoning_effort: 'high',
+ },
+ reasoningOverrideBase: {
+ key: 'reasoning_effort',
+ hadValue: true,
+ value: 'low',
+ },
+ });
+ });
+
+ it('rejects an override whose field does not belong to the effective provider', async () => {
+ const result = await resolve({
+ reasoningOverride: { key: 'effort', value: AnthropicEffort.high },
+ });
+
+ expect(result).toEqual({ ok: false, reason: 'invalid-reasoning-override' });
+ });
+
+ it.each([
+ [EModelEndpoint.anthropic, 'claude-sonnet-4-6', { key: 'effort', value: 'max' }],
+ [EModelEndpoint.google, 'gemini-3-pro', { key: 'thinkingLevel', value: ThinkingLevel.high }],
+ [EModelEndpoint.google, 'gemini-2.5-pro', { key: 'thinkingBudget', value: 32768 }],
+ ])('applies the supported %s reasoning field', async (endpoint, model, reasoningOverride) => {
+ const result = await resolve({
+ endpoint,
+ reasoningOverride: reasoningOverride as TReasoningOverride,
+ endpointOption: {
+ model_parameters: { model },
+ agent: Promise.resolve({ provider: endpoint, model }),
+ },
+ });
+
+ expect(result).toMatchObject({
+ ok: true,
+ modelParameters: {
+ model,
+ [reasoningOverride.key]: reasoningOverride.value,
+ thinking: true,
+ },
+ });
+ });
+
+ it('rejects the wrong Google reasoning field for Gemini 2.5', async () => {
+ const result = await resolve({
+ endpoint: EModelEndpoint.google,
+ reasoningOverride: { key: 'thinkingLevel', value: ThinkingLevel.high },
+ endpointOption: {
+ model_parameters: { model: 'gemini-2.5-pro' },
+ agent: Promise.resolve({ provider: EModelEndpoint.google, model: 'gemini-2.5-pro' }),
+ },
+ });
+
+ expect(result).toEqual({ ok: false, reason: 'invalid-reasoning-override' });
+ });
+
+ it('rejects overrides for custom endpoints that disable reasoning parameters', async () => {
+ const result = await resolve({
+ endpoint: 'QwenCompatible',
+ isAgent: true,
+ reasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.high },
+ endpointOption: {
+ model_parameters: { model: 'qwen3-max' },
+ agent: Promise.resolve({ provider: 'QwenCompatible', model: 'qwen3-max' }),
+ },
+ endpointsConfig: {
+ QwenCompatible: {
+ order: 0,
+ type: EModelEndpoint.custom,
+ customParams: { reasoningFormat: ReasoningParameterFormat.disabled },
+ },
+ },
+ });
+
+ expect(result).toEqual({ ok: false, reason: 'invalid-reasoning-override' });
+ });
+
+ it.each([
+ ['anthropic.claude-sonnet-4-6-v1:0', 'effort', 'high'],
+ ['moonshot.kimi-k2.5', 'reasoning_effort', 'high'],
+ ['zai.glm-4.7', 'reasoning_effort', 'high'],
+ ])('applies the Bedrock model-family reasoning field for %s', async (model, key, value) => {
+ const result = await resolve({
+ endpoint: EModelEndpoint.bedrock,
+ reasoningOverride: { key, value } as TReasoningOverride,
+ endpointOption: {
+ model_parameters: { model },
+ agent: Promise.resolve({ provider: EModelEndpoint.bedrock, model }),
+ },
+ });
+
+ expect(result).toMatchObject({
+ ok: true,
+ modelParameters: { model, [key]: value },
+ });
+ });
+
+ it('preserves the saved base value for a repeated override key', async () => {
+ const existingBase = {
+ key: 'reasoning_effort' as const,
+ hadValue: true,
+ value: 'medium',
+ };
+ const result = await resolve({ reasoningOverrideBase: existingBase });
+
+ expect(result).toMatchObject({ ok: true, reasoningOverrideBase: existingBase });
+ });
+
+ it('uses a custom-backed agent provider default when validating its override', async () => {
+ const result = await resolve({
+ endpoint: EModelEndpoint.agents,
+ reasoningOverride: { key: 'effort', value: AnthropicEffort.high },
+ endpointOption: {
+ model_parameters: { model: 'claude-sonnet-4-6', effort: 'low' },
+ agent: Promise.resolve({ provider: 'ClaudeProxy', model: 'claude-sonnet-4-6' }),
+ },
+ endpointsConfig: {
+ ClaudeProxy: {
+ order: 0,
+ type: EModelEndpoint.custom,
+ customParams: { defaultParamsEndpoint: EModelEndpoint.anthropic },
+ },
+ },
+ });
+
+ expect(result).toMatchObject({
+ ok: true,
+ modelParameters: { effort: 'high' },
+ });
+ });
+ it('accepts the effort level advertised by a non-agent custom endpoint', async () => {
+ const result = await resolve({
+ endpoint: 'Mock Provider A',
+ endpointType: EModelEndpoint.custom,
+ parsedModel: 'mock-model-a',
+ isAgent: false,
+ reasoningOverride: { key: 'effort', value: AnthropicEffort.high },
+ endpointOption: {
+ endpointType: EModelEndpoint.custom,
+ model_parameters: { model: 'mock-model-a' },
+ },
+ endpointsConfig: {
+ 'Mock Provider A': {
+ order: 0,
+ type: EModelEndpoint.custom,
+ customParams: {
+ defaultParamsEndpoint: EModelEndpoint.anthropic,
+ paramDefinitions: [{ key: 'effort' }],
+ },
+ },
+ },
+ });
+
+ expect(result).toMatchObject({
+ ok: true,
+ modelParameters: { model: 'mock-model-a', effort: AnthropicEffort.high, thinking: true },
+ });
+ });
+
+ describe('a thinking budget range the operator widened past the built-in maximum', () => {
+ const wideBudget = (value: number) =>
+ resolve({
+ endpoint: 'Mock Provider A',
+ endpointType: EModelEndpoint.custom,
+ parsedModel: 'mock-model-a',
+ isAgent: false,
+ reasoningOverride: { key: 'thinkingBudget', value },
+ endpointOption: {
+ endpointType: EModelEndpoint.custom,
+ model_parameters: { model: 'mock-model-a' },
+ },
+ endpointsConfig: {
+ 'Mock Provider A': {
+ order: 0,
+ type: EModelEndpoint.custom,
+ customParams: {
+ defaultParamsEndpoint: EModelEndpoint.anthropic,
+ paramDefinitions: [
+ { key: 'thinkingBudget', range: { min: 1024, max: 500000, step: 1024 } },
+ ],
+ },
+ },
+ },
+ });
+
+ it('parses and applies a budget inside the configured range', async () => {
+ expect(parseReasoningOverrideRequest({ key: 'thinkingBudget', value: 300032 })).toEqual({
+ ok: true,
+ reasoningOverride: { key: 'thinkingBudget', value: 300032 },
+ });
+ await expect(wideBudget(300032)).resolves.toMatchObject({
+ ok: true,
+ modelParameters: { thinkingBudget: 300032 },
+ });
+ });
+
+ it('still rejects a budget above the configured range', async () => {
+ await expect(wideBudget(600064)).resolves.toEqual({
+ ok: false,
+ reason: 'invalid-reasoning-override',
+ });
+ });
+ });
+
+ it('rejects an override for a field owned by an enforced model spec', async () => {
+ const result = await resolve({
+ enforcedModelSpecFields: new Set(['reasoning_effort']),
+ });
+
+ expect(result).toEqual({ ok: false, reason: 'invalid-reasoning-override' });
+ });
+});
+
+describe('applyRequestReasoningOverride', () => {
+ const { reasoningOverride, endpointOption, ...input } = baseInput;
+ const request = () => ({
+ body: {
+ endpointOption: {
+ ...endpointOption,
+ model_parameters: { ...endpointOption.model_parameters },
+ endpoint: EModelEndpoint.agents,
+ },
+ },
+ });
+
+ it('leaves a request without an override untouched', async () => {
+ const req = request();
+ const before = req.body.endpointOption;
+ const parameters = { ...before.model_parameters };
+
+ await expect(applyRequestReasoningOverride(req, input)).resolves.toBe(true);
+
+ expect(req.body.endpointOption).toBe(before);
+ expect(req.body.endpointOption.model_parameters).toEqual(parameters);
+ expect(req).not.toHaveProperty('reasoningOverrideBase');
+ });
+
+ it('applies the override and records the base snapshot on the request', async () => {
+ const req: ReturnType<typeof request> & { reasoningOverrideBase?: ReasoningOverrideBase } =
+ request();
+
+ await expect(applyRequestReasoningOverride(req, { ...input, reasoningOverride })).resolves.toBe(
+ true,
+ );
+
+ expect(req.body.endpointOption).toMatchObject({
+ endpoint: EModelEndpoint.agents,
+ model_parameters: { model: 'gpt-5.1', reasoning_effort: 'high' },
+ });
+ expect(req.reasoningOverrideBase).toEqual({
+ key: 'reasoning_effort',
+ hadValue: true,
+ value: 'low',
+ });
+ });
+
+ it('refuses a malformed override without touching the request', async () => {
+ const req = request();
+ const before = req.body.endpointOption;
+
+ await expect(
+ applyRequestReasoningOverride(req, {
+ ...input,
+ reasoningOverride: { key: 'not_a_reasoning_field', value: 'high' },
+ }),
+ ).resolves.toBe(false);
+
+ expect(req.body.endpointOption).toBe(before);
+ expect(req).not.toHaveProperty('reasoningOverrideBase');
+ });
+
+ it('refuses an unsupported override without touching the request', async () => {
+ const req = request();
+ const before = req.body.endpointOption;
+ const parameters = { ...before.model_parameters };
+
+ await expect(
+ applyRequestReasoningOverride(req, {
+ ...input,
+ reasoningOverride: { key: 'effort', value: AnthropicEffort.high },
+ }),
+ ).resolves.toBe(false);
+
+ expect(req.body.endpointOption).toBe(before);
+ expect(req.body.endpointOption.model_parameters).toEqual(parameters);
+ expect(req).not.toHaveProperty('reasoningOverrideBase');
+ });
+
+ /* A replayed resume override is trusted server state captured when it was
+ valid; the endpoint's config may have moved on since the pause. Refusing
+ would brick the checkpoint, so the stale override is stripped and the
+ resume proceeds on defaults. */
+ it('strips a malformed replayed override instead of refusing the resume', async () => {
+ const base = request();
+ const req = {
+ resumeReplayed: true,
+ ...base,
+ body: {
+ ...base.body,
+ reasoningOverride: { key: 'not_a_reasoning_field', value: 'high' },
+ },
+ };
+ const before = req.body.endpointOption;
+
+ await expect(
+ applyRequestReasoningOverride(req, {
+ ...input,
+ reasoningOverride: req.body.reasoningOverride,
+ }),
+ ).resolves.toBe(true);
+
+ expect(req.body.reasoningOverride).toBeUndefined();
+ expect(req.body.endpointOption).toBe(before);
+ expect(req).not.toHaveProperty('reasoningOverrideBase');
+ });
+
+ it('strips a replayed override the endpoint no longer accepts instead of refusing the resume', async () => {
+ const base = request();
+ const req = {
+ resumeReplayed: true,
+ ...base,
+ body: {
+ ...base.body,
+ reasoningOverride: { key: 'effort', value: AnthropicEffort.high },
+ },
+ };
+ const before = req.body.endpointOption;
+ const parameters = { ...before.model_parameters };
+
+ await expect(
+ applyRequestReasoningOverride(req, {
+ ...input,
+ reasoningOverride: req.body.reasoningOverride,
+ }),
+ ).resolves.toBe(true);
+
+ expect(req.body.reasoningOverride).toBeUndefined();
+ expect(req.body.endpointOption).toBe(before);
+ expect(req.body.endpointOption.model_parameters).toEqual(parameters);
+ expect(req).not.toHaveProperty('reasoningOverrideBase');
+ });
+
+ /* A durable queued turn carries the override it was validated with at
+ enqueue time; the agent may have changed while it waited. Refusing would
+ dead-letter the turn, so its admission degrades to defaults like a resume. */
+ it('strips an override a queued turn admission no longer supports instead of refusing it', async () => {
+ const base = request();
+ const req = {
+ _isAgentTrigger: true,
+ ...base,
+ body: {
+ ...base.body,
+ reasoningOverride: { key: 'effort', value: AnthropicEffort.high },
+ agentContinuationAdmission: {
+ source: 'agent-queued-turn',
+ sourceId: 'queued-turn-1',
+ claimId: 'claim-1',
+ claimBy: 'worker-1',
+ },
+ },
+ };
+ const before = req.body.endpointOption;
+ const parameters = { ...before.model_parameters };
+
+ await expect(
+ applyRequestReasoningOverride(req, {
+ ...input,
+ reasoningOverride: req.body.reasoningOverride,
+ }),
+ ).resolves.toBe(true);
+
+ expect(req.body.reasoningOverride).toBeUndefined();
+ expect(req.body.endpointOption.model_parameters).toEqual(parameters);
+ });
+
+ it('still refuses an unsupported override on a trigger request that is not a queued turn admission', async () => {
+ const base = request();
+ const req = {
+ _isAgentTrigger: true,
+ ...base,
+ body: {
+ ...base.body,
+ reasoningOverride: { key: 'effort', value: AnthropicEffort.high },
+ },
+ };
+
+ await expect(
+ applyRequestReasoningOverride(req, {
+ ...input,
+ reasoningOverride: req.body.reasoningOverride,
+ }),
+ ).resolves.toBe(false);
+ });
+
+ /* The resume replays the paused turn's parameters with the override already
+ applied, so degrading has to invert that application from the replayed
+ base: the pre-override value returns and the thinking flag the override
+ forced on comes off, or the provider still receives what was refused. */
+ it('restores the pre-override parameters from the replayed base when degrading', async () => {
+ const base = request();
+ const req = {
+ resumeReplayed: true,
+ reasoningOverrideBase: {
+ key: 'reasoning_effort' as const,
+ hadValue: true,
+ value: 'low',
+ thinkingHadValue: false,
+ },
+ ...base,
+ body: {
+ ...base.body,
+ reasoningOverride: { key: 'effort', value: 'high' },
+ endpointOption: {
+ ...base.body.endpointOption,
+ model_parameters: {
+ ...base.body.endpointOption.model_parameters,
+ reasoning_effort: 'high',
+ thinking: true,
+ },
+ },
+ },
+ };
+
+ await expect(
+ applyRequestReasoningOverride(req, {
+ ...input,
+ reasoningOverride: { key: 'effort', value: 'high' },
+ }),
+ ).resolves.toBe(true);
+
+ expect(req.body.reasoningOverride).toBeUndefined();
+ expect(req.body.endpointOption.model_parameters).toMatchObject({
+ model: 'gpt-5.1',
+ reasoning_effort: 'low',
+ });
+ expect(req.body.endpointOption.model_parameters).not.toHaveProperty('thinking');
+ expect(req.reasoningOverrideBase).toEqual({
+ key: 'reasoning_effort',
+ hadValue: true,
+ value: 'low',
+ thinkingHadValue: false,
+ });
+ });
+});
diff --git a/packages/api/src/modelSpecs/reasoningOverride.ts b/packages/api/src/modelSpecs/reasoningOverride.ts
new file mode 100644
index 0000000000..49a75606e0
--- /dev/null
+++ b/packages/api/src/modelSpecs/reasoningOverride.ts
@@ -0,0 +1,247 @@
+import {
+ isReasoningOverrideSupported,
+ reasoningOverrideSchema,
+ ReasoningParameterFormat,
+ resolveReasoningSettingForTarget,
+ type TEndpointsConfig,
+ type TReasoningOverride,
+} from 'librechat-data-provider';
+import type { AgentContinuationAdmissionSource } from '~/agents/triggers/host';
+
+export type ReasoningOverrideRequest =
+ | { ok: true; reasoningOverride?: TReasoningOverride }
+ | { ok: false; reason: 'invalid-reasoning-override' };
+
+/**
+ * Validates the reasoning override a request carries, before the conversation
+ * is parsed or an endpoint option is built. An absent override is valid and
+ * yields no target, so the caller only has to map `ok: false` onto its own
+ * error response instead of knowing the payload's shape.
+ */
+export function parseReasoningOverrideRequest(raw: unknown): ReasoningOverrideRequest {
+ if (raw == null) {
+ return { ok: true };
+ }
+ const parsed = reasoningOverrideSchema.safeParse(raw);
+ if (!parsed.success) {
+ return { ok: false, reason: 'invalid-reasoning-override' };
+ }
+ return { ok: true, reasoningOverride: parsed.data };
+}
+
+export type ReasoningOverrideBase = {
+ key: TReasoningOverride['key'];
+ hadValue: boolean;
+ value: unknown;
+ thinkingHadValue?: boolean;
+ thinkingValue?: unknown;
+};
+
+type LoadedAgent = {
+ provider?: string | null;
+ model?: string | null;
+};
+
+type EndpointOption = {
+ endpointType?: string | null;
+ model_parameters?: (Record<string, unknown> & { model?: string | null }) | null;
+ agent?: LoadedAgent | Promise<LoadedAgent | null | undefined> | null;
+};
+
+export type ReasoningOverrideInput = {
+ reasoningOverride: TReasoningOverride;
+ endpointOption: EndpointOption;
+ endpoint: string;
+ endpointType?: string | null;
+ parsedModel?: string | null;
+ isAgent: boolean;
+ endpointsConfig?: TEndpointsConfig;
+ defaultParamsEndpoint?: string | null;
+ appliedModelSpecPrivateFields?: ReadonlySet<string>;
+ enforcedModelSpecFields?: ReadonlySet<string>;
+ reasoningOverrideBase?: ReasoningOverrideBase;
+};
+
+export type ReasoningOverrideResult =
+ | {
+ ok: true;
+ modelParameters: Record<string, unknown>;
+ reasoningOverrideBase: ReasoningOverrideBase;
+ }
+ | {
+ ok: false;
+ reason: 'invalid-reasoning-override';
+ };
+
+/**
+ * Resolves and applies a request-scoped reasoning override without mutating
+ * the endpoint option or the saved reasoning value. The middleware owns only
+ * request/response wiring; all endpoint capability and model-parameter policy
+ * lives behind this interface.
+ */
+export async function resolveReasoningOverride({
+ reasoningOverride,
+ endpointOption,
+ endpoint,
+ endpointType,
+ parsedModel,
+ isAgent,
+ endpointsConfig,
+ defaultParamsEndpoint,
+ appliedModelSpecPrivateFields = new Set(),
+ enforcedModelSpecFields = new Set(),
+ reasoningOverrideBase: existingBase,
+}: ReasoningOverrideInput): Promise<ReasoningOverrideResult> {
+ if (
+ appliedModelSpecPrivateFields.has(reasoningOverride.key) ||
+ enforcedModelSpecFields.has(reasoningOverride.key)
+ ) {
+ return { ok: false, reason: 'invalid-reasoning-override' };
+ }
+
+ const loadedAgent = await endpointOption.agent;
+ const effectiveEndpoint =
+ loadedAgent?.provider ?? endpointOption.endpointType ?? endpointType ?? endpoint;
+ const modelParameters = endpointOption.model_parameters ?? {};
+ const effectiveModel = loadedAgent?.model ?? modelParameters.model ?? parsedModel;
+ const customEndpointKey = isAgent ? effectiveEndpoint : endpoint;
+ const customParams = endpointsConfig?.[customEndpointKey]?.customParams;
+
+ if (customParams?.reasoningFormat === ReasoningParameterFormat.disabled) {
+ return { ok: false, reason: 'invalid-reasoning-override' };
+ }
+
+ const supportedSetting = resolveReasoningSettingForTarget({
+ endpoint: effectiveEndpoint,
+ model: effectiveModel,
+ isAgent,
+ defaultParamsEndpoint: customParams?.defaultParamsEndpoint ?? defaultParamsEndpoint,
+ paramDefinitions: customParams?.paramDefinitions,
+ reasoningFormat: customParams?.reasoningFormat,
+ blockedReasoningKeys: new Set([...appliedModelSpecPrivateFields, ...enforcedModelSpecFields]),
+ });
+
+ if (!isReasoningOverrideSupported(reasoningOverride, supportedSetting)) {
+ return { ok: false, reason: 'invalid-reasoning-override' };
+ }
+
+ const enablesThinking =
+ reasoningOverride.key === 'effort' ||
+ reasoningOverride.key === 'thinkingLevel' ||
+ reasoningOverride.key === 'thinkingBudget';
+ const nextBase =
+ existingBase?.key === reasoningOverride.key
+ ? existingBase
+ : {
+ key: reasoningOverride.key,
+ hadValue: Object.prototype.hasOwnProperty.call(modelParameters, reasoningOverride.key),
+ value: modelParameters[reasoningOverride.key],
+ ...(enablesThinking && {
+ thinkingHadValue: Object.prototype.hasOwnProperty.call(modelParameters, 'thinking'),
+ thinkingValue: modelParameters.thinking,
+ }),
+ };
+
+ return {
+ ok: true,
+ reasoningOverrideBase: nextBase,
+ modelParameters: {
+ ...modelParameters,
+ [reasoningOverride.key]: reasoningOverride.value,
+ ...(enablesThinking && { thinking: true }),
+ },
+ };
+}
+
+export type RequestReasoningOverrideInput = Omit<
+ ReasoningOverrideInput,
+ 'reasoningOverride' | 'endpointOption' | 'reasoningOverrideBase'
+> & {
+ /** The raw request field; validated here, so the caller passes it unparsed. */
+ reasoningOverride?: unknown;
+};
+
+/**
+ * Validates a request's reasoning override, applies it to the built endpoint
+ * option and records the trusted base snapshot on the request. A request without
+ * an override is left untouched; `false` means the override was malformed or
+ * refused and the caller must reject the request.
+ *
+ * A replayed resume override is trusted server state, not fresh client input:
+ * when it no longer validates (the endpoint's reasoning config changed between
+ * pause and resume) it is stripped and the resume proceeds on defaults, because
+ * rejecting would make the paused checkpoint permanently unresumable. A durable
+ * queued turn's admission is the same: the override was validated when it was
+ * queued, and rejecting it after the agent changed would dead-letter the turn.
+ */
+export async function applyRequestReasoningOverride<T extends EndpointOption>(
+ req: {
+ reasoningOverrideBase?: ReasoningOverrideBase;
+ resumeReplayed?: boolean;
+ _isAgentTrigger?: boolean;
+ body: {
+ endpointOption: T;
+ reasoningOverride?: unknown;
+ agentContinuationAdmission?: AgentContinuationAdmissionSource;
+ };
+ },
+ { reasoningOverride: raw, ...input }: RequestReasoningOverrideInput,
+): Promise<boolean> {
+ const stripReplayedOverride = (): boolean => {
+ delete req.body.reasoningOverride;
+ /* The resume already replayed the paused turn's model parameters, override
+ * applied, into the endpoint option; dropping only the metadata field would
+ * still send the now-unsupported override to the provider. The base the
+ * resume replayed alongside it holds the pre-override values, so the strip
+ * inverts the application it was captured from. */
+ const base = req.reasoningOverrideBase;
+ if (base == null) {
+ return true;
+ }
+ const parameters: Record<string, unknown> = {
+ ...req.body.endpointOption.model_parameters,
+ };
+ if (base.hadValue) {
+ parameters[base.key] = base.value;
+ } else {
+ delete parameters[base.key];
+ }
+ if (base.thinkingHadValue != null) {
+ if (base.thinkingHadValue) {
+ parameters.thinking = base.thinkingValue;
+ } else {
+ delete parameters.thinking;
+ }
+ }
+ req.body.endpointOption = {
+ ...req.body.endpointOption,
+ model_parameters: parameters,
+ };
+ return true;
+ };
+ const replayed =
+ req.resumeReplayed === true ||
+ (req._isAgentTrigger === true && req.body.agentContinuationAdmission != null);
+ const request = parseReasoningOverrideRequest(raw);
+ if (!request.ok) {
+ return replayed ? stripReplayedOverride() : false;
+ }
+ if (request.reasoningOverride == null) {
+ return true;
+ }
+ const resolution = await resolveReasoningOverride({
+ ...input,
+ reasoningOverride: request.reasoningOverride,
+ endpointOption: req.body.endpointOption,
+ reasoningOverrideBase: req.reasoningOverrideBase,
+ });
+ if (!resolution.ok) {
+ return replayed ? stripReplayedOverride() : false;
+ }
+ req.reasoningOverrideBase = resolution.reasoningOverrideBase;
+ req.body.endpointOption = {
+ ...req.body.endpointOption,
+ model_parameters: resolution.modelParameters,
+ };
+ return true;
+}
diff --git a/packages/api/src/types/http.ts b/packages/api/src/types/http.ts
index 2ead23ff08..80fec4a6da 100644
--- a/packages/api/src/types/http.ts
+++ b/packages/api/src/types/http.ts
@@ -3,6 +3,7 @@ import type {
CodeEnvironmentMode,
CodeWorkspaceSelection,
TEndpointOption,
+ TReasoningOverride,
Agents,
} from 'librechat-data-provider';
import type { IUser, AppConfig, IConversation } from '@librechat/data-schemas';
@@ -23,6 +24,7 @@ export type RequestBody = {
imageDetail?: Agents.ImageDetail;
key?: string;
endpointOption?: Partial<TEndpointOption>;
+ reasoningOverride?: TReasoningOverride;
/** Browser IANA timezone used to resolve local-time prompt variables (e.g. `{{current_datetime}}`). */
timezone?: string;
codeApprovalMode?: CodeApprovalMode;
@@ -42,4 +44,12 @@ export type ServerRequest = Request<unknown, unknown, RequestBody> & {
resolvedConversation?: Partial<IConversation> | null;
/** Passport strategy that populated req.user for this request. */
authStrategy?: string;
+ /** Trusted snapshot used to keep a request-scoped override out of saved conversation defaults. */
+ reasoningOverrideBase?: {
+ key: TReasoningOverride['key'];
+ hadValue: boolean;
+ value?: unknown;
+ thinkingHadValue?: boolean;
+ thinkingValue?: unknown;
+ };
};
diff --git a/packages/client/src/components/Chip.spec.tsx b/packages/client/src/components/Chip.spec.tsx
index a6dba04f36..ab331d19b2 100644
--- a/packages/client/src/components/Chip.spec.tsx
+++ b/packages/client/src/components/Chip.spec.tsx
@@ -3,6 +3,16 @@ import { fireEvent, render, screen } from '@testing-library/react';
import { Chip } from './Chip';
describe('Chip', () => {
+ it('renders a theme-aware surface tone for non-status context', () => {
+ render(<Chip tone="surface">Context</Chip>);
+
+ expect(screen.getByText('Context').parentElement).toHaveClass(
+ 'border-border-light',
+ 'bg-surface-secondary',
+ 'text-text-secondary',
+ );
+ });
+
it('renders semantic tone classes', () => {
render(<Chip tone="info">Search result</Chip>);
diff --git a/packages/client/src/components/Chip.tsx b/packages/client/src/components/Chip.tsx
index e158e8db0a..2f7c3436bf 100644
--- a/packages/client/src/components/Chip.tsx
+++ b/packages/client/src/components/Chip.tsx
@@ -6,7 +6,7 @@ import { IconButton } from './IconButton';
import { cn } from '~/utils';
type ChipVariantProps = {
- tone?: 'neutral' | 'info' | 'success' | 'warning' | 'error' | null;
+ tone?: 'surface' | 'neutral' | 'info' | 'success' | 'warning' | 'error' | null;
size?: 'sm' | 'md' | 'theme' | null;
shape?: 'round' | 'theme' | null;
};
@@ -16,6 +16,7 @@ const chipVariants: (props?: ChipVariantProps & ClassProp) => string = cva(
{
variants: {
tone: {
+ surface: 'border-border-light bg-surface-secondary text-text-secondary',
neutral: 'border-status-neutral-border bg-status-neutral-subtle text-status-neutral',
info: 'border-status-info-border bg-status-info-subtle text-status-info',
success: 'border-status-success-border bg-status-success-subtle text-status-success',
diff --git a/packages/client/src/components/IconButton.spec.tsx b/packages/client/src/components/IconButton.spec.tsx
index 866785a168..e333b61a00 100644
--- a/packages/client/src/components/IconButton.spec.tsx
+++ b/packages/client/src/components/IconButton.spec.tsx
@@ -32,4 +32,18 @@ describe('IconButton', () => {
'rounded-theme-control-round',
);
});
+
+ it('provides a theme-aware primary action', () => {
+ render(
+ <IconButton label="Send" variant="primary">
+ send
+ </IconButton>,
+ );
+
+ expect(screen.getByRole('button', { name: 'Send' })).toHaveClass(
+ 'bg-surface-inverted',
+ 'text-text-inverted',
+ 'hover:bg-surface-inverted-hover',
+ );
+ });
});
diff --git a/packages/client/src/components/IconButton.tsx b/packages/client/src/components/IconButton.tsx
index b731a62276..68a3140d90 100644
--- a/packages/client/src/components/IconButton.tsx
+++ b/packages/client/src/components/IconButton.tsx
@@ -1,10 +1,11 @@
import * as React from 'react';
import { cva } from 'class-variance-authority';
import type { ClassProp } from 'class-variance-authority/types';
+import { composerSubmitClasses } from '~/utils/composer';
import { cn } from '~/utils';
type IconButtonVariantProps = {
- variant?: 'default' | 'secondary' | 'ghost' | 'destructive' | null;
+ variant?: 'default' | 'primary' | 'secondary' | 'ghost' | 'destructive' | 'submit' | null;
size?: 'xs' | 'sm' | 'md' | 'lg' | 'theme' | null;
shape?: 'round' | 'square' | 'theme' | null;
};
@@ -15,10 +16,13 @@ const iconButtonVariants: (props?: IconButtonVariantProps & ClassProp) => string
variants: {
variant: {
default: 'bg-surface-secondary hover:bg-surface-hover',
+ primary: 'bg-surface-inverted text-text-inverted hover:bg-surface-inverted-hover',
secondary: 'border border-border-light bg-surface-secondary hover:bg-surface-hover',
ghost: 'bg-transparent hover:bg-surface-hover',
destructive:
'bg-surface-destructive text-text-on-status hover:bg-surface-destructive-hover',
+ /** The composer's submit slot: send, stop and the during-run send share it. */
+ submit: cn('hover:bg-surface-inverted-hover', composerSubmitClasses()),
},
size: {
xs: 'size-6',
diff --git a/packages/client/src/components/OriginalDialog.tsx b/packages/client/src/components/OriginalDialog.tsx
index e808ba3880..f8080df1c2 100644
--- a/packages/client/src/components/OriginalDialog.tsx
+++ b/packages/client/src/components/OriginalDialog.tsx
@@ -76,8 +76,8 @@ const escapeBelongsToPopup = (ownerDocument: Document): boolean => {
};
interface OGDialogProps extends DialogPrimitive.DialogProps {
- triggerRef?: React.RefObject<HTMLButtonElement | HTMLInputElement | HTMLDivElement | null>;
- triggerRefs?: React.RefObject<HTMLButtonElement | HTMLInputElement | HTMLDivElement | null>[];
+ triggerRef?: React.RefObject<HTMLElement | null>;
+ triggerRefs?: React.RefObject<HTMLElement | null>[];
}
const Dialog: React.ForwardRefExoticComponent<OGDialogProps & React.RefAttributes<HTMLDivElement>> =
diff --git a/packages/client/src/components/Slider.tsx b/packages/client/src/components/Slider.tsx
index 7a78fd156e..dbdf2fe97b 100644
--- a/packages/client/src/components/Slider.tsx
+++ b/packages/client/src/components/Slider.tsx
@@ -6,6 +6,7 @@ type SliderProps = React.ComponentPropsWithoutRef<typeof SliderPrimitive.Root> &
className?: string;
onDoubleClick?: () => void;
'aria-describedby'?: string;
+ 'aria-valuetext'?: string;
} & (
| { 'aria-label': string; 'aria-labelledby'?: never }
| { 'aria-labelledby': string; 'aria-label'?: never }
@@ -21,6 +22,7 @@ const Slider: React.ForwardRefExoticComponent<SliderProps & React.RefAttributes<
'aria-labelledby': ariaLabelledBy,
'aria-label': ariaLabel,
'aria-describedby': ariaDescribedBy,
+ 'aria-valuetext': ariaValueText,
...props
},
ref,
@@ -50,6 +52,7 @@ const Slider: React.ForwardRefExoticComponent<SliderProps & React.RefAttributes<
'aria-labelledby': ariaLabelledBy,
'aria-label': ariaLabel,
'aria-describedby': ariaDescribedBy,
+ 'aria-valuetext': ariaValueText,
}}
/>
</SliderPrimitive.Root>
diff --git a/packages/client/src/theme/semanticTokens.spec.ts b/packages/client/src/theme/semanticTokens.spec.ts
index 311e962f87..c2ede2be94 100644
--- a/packages/client/src/theme/semanticTokens.spec.ts
+++ b/packages/client/src/theme/semanticTokens.spec.ts
@@ -30,9 +30,13 @@ const sharedDialogComponents = [
];
describe('shared component color guardrail', () => {
- it('keeps shared primitives free of direct palette utilities and hex colors', () => {
+ it('keeps shared primitives free of direct palette utilities and raw colors', () => {
const directPalette =
- /(?:bg|text|border|ring|from|via|to)-(?:gray|red|green|blue|purple|amber|yellow|orange|pink|indigo|violet|teal|cyan|slate|zinc|neutral|stone)-\d/;
+ /(?:bg|text|border|ring|from|via|to|fill|stroke)-(?:(?:slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d|white\b|black\b)/;
+ /** Literal colors only: `rgb(var(--token))` reads the theme at paint time,
+ * which is exactly what a shared primitive is supposed to do. */
+ const rawColor =
+ /#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{4}|[0-9a-f]{3})\b|(?:rgb|hsl)a?\((?!\s*var\()/i;
/** Only CSS-legal hex lengths (3, 4, 6, 8). `{3,8}` also matched a five-
* digit issue reference in a comment — see the PR number in
* `OriginalDialog.tsx` — which reads as a color to a regex and to nobody
@@ -43,7 +47,7 @@ describe('shared component color guardrail', () => {
const source = readFileSync(join(__dirname, '..', 'components', component), 'utf8');
expect(source).not.toMatch(directPalette);
- expect(source).not.toMatch(hexColor);
+ expect(source).not.toMatch(rawColor);
});
/** The guardrail still has to catch what it exists for. */
diff --git a/packages/data-provider/specs/config-schemas.spec.ts b/packages/data-provider/specs/config-schemas.spec.ts
index 26671c9a2f..75b059dfea 100644
--- a/packages/data-provider/specs/config-schemas.spec.ts
+++ b/packages/data-provider/specs/config-schemas.spec.ts
@@ -1127,6 +1127,25 @@ describe('configSchema fileStrategy', () => {
});
});
+describe('configSchema fileListLimit', () => {
+ it('defaults fileListLimit to 100 for existing configurations', () => {
+ const result = configSchema.parse({ version: '1.3.7' });
+ expect(result.fileListLimit).toBe(100);
+ });
+
+ it('accepts a positive integer override', () => {
+ const result = configSchema.safeParse({ version: '1.3.7', fileListLimit: 250 });
+ expect(result.success).toBe(true);
+ if (result.success) {
+ expect(result.data.fileListLimit).toBe(250);
+ }
+ });
+
+ it.each([0, -1, 1.5])('rejects invalid fileListLimit %p', (fileListLimit) => {
+ expect(configSchema.safeParse({ version: '1.3.7', fileListLimit }).success).toBe(false);
+ });
+});
+
describe('configSchema skillSync', () => {
it('accepts a GitHub skill sync source with explicit paths and credential key', () => {
const result = configSchema.safeParse({
diff --git a/packages/data-provider/src/config.spec.ts b/packages/data-provider/src/config.spec.ts
index acb55cec5a..fa1083d00b 100644
--- a/packages/data-provider/src/config.spec.ts
+++ b/packages/data-provider/src/config.spec.ts
@@ -6,8 +6,9 @@ import {
DEFAULT_MAX_RETAINED_TOOL_COUNT_CHARS,
bedrockModels,
configSchema,
+ DEFAULT_STEER_ARM_CONFIRMATION_TIMEOUT_MS,
codeEnvironmentUserConfigSchema,
- CODE_ENVIRONMENT_ADMISSION_MAX_MS,
+ interfaceSchema,
excludedKeys,
DEFAULT_MCP_APP_ADMISSION_REQUESTS_PER_MINUTE,
DEFAULT_MCP_APP_PERSISTED_BYTES,
@@ -154,6 +155,35 @@ describe('repository instruction configuration', () => {
});
});
+describe('steer escalation confirmation timeout', () => {
+ it('defaults to the existing ten-second confirmation window', () => {
+ expect(interfaceSchema.parse({}).steerArmConfirmationTimeoutMs).toBe(
+ DEFAULT_STEER_ARM_CONFIRMATION_TIMEOUT_MS,
+ );
+ expect(configSchema.parse({ version: '1.0' }).interface?.steerArmConfirmationTimeoutMs).toBe(
+ DEFAULT_STEER_ARM_CONFIRMATION_TIMEOUT_MS,
+ );
+ });
+
+ it('accepts a configured confirmation window', () => {
+ expect(
+ configSchema.parse({
+ version: '1.0',
+ interface: { steerArmConfirmationTimeoutMs: 30_000 },
+ }).interface?.steerArmConfirmationTimeoutMs,
+ ).toBe(30_000);
+ });
+
+ it.each([0, -1, 1.5, 2_147_483_648, '30s'])('rejects invalid confirmation window %p', (value) => {
+ expect(
+ configSchema.safeParse({
+ version: '1.0',
+ interface: { steerArmConfirmationTimeoutMs: value },
+ }).success,
+ ).toBe(false);
+ });
+});
+
describe('ask user retained answers', () => {
it('leaves the block unconfigured by default and accepts an operator budget', () => {
expect(agentsEndpointSchema.parse({}).askUserQuestion).toBeUndefined();
diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.ts
index a1ba5fc018..6b43805364 100644
--- a/packages/data-provider/src/config.ts
+++ b/packages/data-provider/src/config.ts
@@ -2175,12 +2175,19 @@ export type TTermsOfService = z.infer<typeof termsOfServiceSchema>;
// Schema for localized string (either simple string or language-keyed object)
const localizedStringSchema = z.union([z.string(), z.record(z.string())]);
export type LocalizedString = z.infer<typeof localizedStringSchema>;
-
export const mcpRefreshDefaults = {
toolsRefreshInterval: 5 * 60 * 1000,
statusRefreshInterval: 30 * 1000,
};
+/** Default confirmation window for a client-side steer escalation arm. */
+export const DEFAULT_STEER_ARM_CONFIRMATION_TIMEOUT_MS = 10_000;
+export const DEFAULT_QUEUED_TURN_RECONCILIATION_TIMEOUT_MS = 60_000;
+/** Last-resort expiry of the client's per-pane queued-send lock. */
+export const DEFAULT_QUEUED_SEND_LOCK_TIMEOUT_MS = 60_000;
+/** How many recently touched files the composer palette offers to reuse. */
+export const DEFAULT_COMPOSER_RECENT_FILES = 5;
+
const mcpServersSchema = z
.object({
/** Foreground polling intervals in milliseconds; 0 disables polling. */
@@ -2502,12 +2509,44 @@ export const interfaceSchema = z
requireProject: z.boolean().optional(),
/** Pins every scheduled run to ONE chat project, ignoring any client
* choice. Implies `requireProject`. The project must belong to the
- * schedule's owner, so a deployment-wide value only makes sense with a
- * per-user/per-role config override. */
+ * schedule's owner, so a deployment-wide value only makes sense with
+ * a per-user/per-role config override. */
projectId: z.string().trim().min(1).optional(),
}),
])
.optional(),
+ /** Client confirmation window for a steer escalation arm, in milliseconds. */
+ steerArmConfirmationTimeoutMs: z
+ .number()
+ .int()
+ .positive()
+ .max(2_147_483_647)
+ .default(DEFAULT_STEER_ARM_CONFIRMATION_TIMEOUT_MS),
+ /** How long the client keeps reconciling a transport-ambiguous queued turn
+ * before it stops polling, in milliseconds. A slow proxy or a delayed
+ * read replica needs a longer window than the default. */
+ queuedTurnReconciliationTimeoutMs: z
+ .number()
+ .int()
+ .positive()
+ .max(2_147_483_647)
+ .default(DEFAULT_QUEUED_TURN_RECONCILIATION_TIMEOUT_MS),
+ /** How long a queued send may hold its pane before the claim is treated as
+ * broken and released, in milliseconds. A healthy start releases it at once;
+ * this only bounds a start that failed without ever reporting progress. */
+ queuedSendLockTimeoutMs: z
+ .number()
+ .int()
+ .positive()
+ .max(2_147_483_647)
+ .default(DEFAULT_QUEUED_SEND_LOCK_TIMEOUT_MS),
+ /** How many recently touched files the composer palette requests and shows
+ * while idle; 0 turns that idle list off. Searching the palette still
+ * finds any of the user's files, since it is the composer's only way to
+ * reuse one. Capped at the file list endpoint's
+ * own default maximum (`fileListLimit`) so the palette can never ask for
+ * more than a typical deployment will return. */
+ composerRecentFiles: z.number().int().min(0).max(100).default(DEFAULT_COMPOSER_RECENT_FILES),
})
.default({
modelSelect: true,
@@ -2586,6 +2625,10 @@ export const interfaceSchema = z
// from librechat.yaml — including it would silently enable the feature (and permit
// billable scheduled runs) on every deployment that never opted in. The PERMISSION
// defaults live in updateInterfacePermissions, which is a separate concern.
+ steerArmConfirmationTimeoutMs: DEFAULT_STEER_ARM_CONFIRMATION_TIMEOUT_MS,
+ queuedTurnReconciliationTimeoutMs: DEFAULT_QUEUED_TURN_RECONCILIATION_TIMEOUT_MS,
+ queuedSendLockTimeoutMs: DEFAULT_QUEUED_SEND_LOCK_TIMEOUT_MS,
+ composerRecentFiles: DEFAULT_COMPOSER_RECENT_FILES,
});
export type TInterfaceConfig = z.infer<typeof interfaceSchema>;
@@ -3516,6 +3559,8 @@ export const configSchema = z.object({
.optional(),
interface: interfaceSchema,
turnstile: turnstileSchema.optional(),
+ /** Maximum rows an explicitly limited GET /files request may return. */
+ fileListLimit: z.number().int().positive().default(100),
fileStrategy: fileStorageSchema.default(FileSources.local),
fileStrategies: fileStrategiesSchema,
cloudfront: cloudfrontConfigSchema,
diff --git a/packages/data-provider/src/data-service.ts b/packages/data-provider/src/data-service.ts
index ca58b92621..07505efdbe 100644
--- a/packages/data-provider/src/data-service.ts
+++ b/packages/data-provider/src/data-service.ts
@@ -574,8 +574,11 @@ export const getToolCalls = (params: q.GetToolCallParams): Promise<q.ToolCallRes
/* Files */
-export const getFiles = (): Promise<f.TFile[]> => {
- return request.get(endpoints.files());
+export const getFiles = (params?: { limit?: number }): Promise<f.TFile[]> => {
+ return request.get(
+ endpoints.files(),
+ params?.limit != null ? { params: { limit: params.limit } } : undefined,
+ );
};
/**
diff --git a/packages/data-provider/src/parameterSettings.spec.ts b/packages/data-provider/src/parameterSettings.spec.ts
index f6ac41507a..6fdfe84779 100644
--- a/packages/data-provider/src/parameterSettings.spec.ts
+++ b/packages/data-provider/src/parameterSettings.spec.ts
@@ -1,10 +1,14 @@
import type { SettingDefinition } from './generate';
import {
+ paramSettings,
+ resolveReasoningSetting,
+ resolveReasoningSettingForTarget,
+ isReasoningOverrideSupported,
applyModelAwareDefaults,
resolveDropParamsUIKeys,
- paramSettings,
} from './parameterSettings';
-import { EModelEndpoint, Providers } from './types';
+import { BedrockProviders, EModelEndpoint, Providers } from './types';
+import { ReasoningEffort, ReasoningParameterFormat } from './schemas';
const googleParams = paramSettings[EModelEndpoint.google] as SettingDefinition[];
const anthropicParams = paramSettings[EModelEndpoint.anthropic] as SettingDefinition[];
@@ -151,6 +155,296 @@ describe('applyModelAwareDefaults', () => {
});
});
+describe('resolveReasoningSetting', () => {
+ it('selects qualitative reasoning effort for OpenAI reasoning models', () => {
+ expect(
+ resolveReasoningSetting({
+ endpoint: EModelEndpoint.openAI,
+ model: 'gpt-5.6',
+ settings: paramSettings[EModelEndpoint.openAI] ?? [],
+ })?.key,
+ ).toBe('reasoning_effort');
+ });
+
+ it('hides the control for known non-reasoning OpenAI models', () => {
+ expect(
+ resolveReasoningSetting({
+ endpoint: EModelEndpoint.openAI,
+ model: 'gpt-4o',
+ settings: paramSettings[EModelEndpoint.openAI] ?? [],
+ }),
+ ).toBeUndefined();
+ });
+
+ it('uses the configured Azure capability for administrator-defined deployment names', () => {
+ expect(
+ resolveReasoningSetting({
+ endpoint: EModelEndpoint.azureOpenAI,
+ model: 'production-reasoning-west',
+ settings: paramSettings[EModelEndpoint.azureOpenAI] ?? [],
+ })?.key,
+ ).toBe('reasoning_effort');
+ });
+
+ it('keeps custom OpenAI-compatible models capability-driven', () => {
+ expect(
+ resolveReasoningSetting({
+ endpoint: EModelEndpoint.custom,
+ model: 'qwen3.8-max',
+ settings: paramSettings[EModelEndpoint.custom] ?? [],
+ })?.key,
+ ).toBe('reasoning_effort');
+ });
+
+ it('uses effort for adaptive Claude and a token budget for manual-thinking Claude', () => {
+ expect(
+ resolveReasoningSetting({
+ endpoint: EModelEndpoint.anthropic,
+ model: 'claude-sonnet-4.6',
+ settings: paramSettings[EModelEndpoint.anthropic] ?? [],
+ })?.key,
+ ).toBe('effort');
+ expect(
+ resolveReasoningSetting({
+ endpoint: EModelEndpoint.anthropic,
+ model: 'claude-3-7-sonnet-latest',
+ settings: paramSettings[EModelEndpoint.anthropic] ?? [],
+ })?.key,
+ ).toBe('thinkingBudget');
+ });
+
+ it('uses thinking level for Gemini 3 and a token budget for Gemini 2.5', () => {
+ expect(
+ resolveReasoningSetting({
+ endpoint: EModelEndpoint.google,
+ model: 'gemini-3.5-flash',
+ settings: paramSettings[EModelEndpoint.google] ?? [],
+ })?.key,
+ ).toBe('thinkingLevel');
+ expect(
+ resolveReasoningSetting({
+ endpoint: EModelEndpoint.google,
+ model: 'gemini-2.5-pro',
+ settings: paramSettings[EModelEndpoint.google] ?? [],
+ })?.key,
+ ).toBe('thinkingBudget');
+ expect(
+ resolveReasoningSetting({
+ endpoint: EModelEndpoint.google,
+ model: 'gemini-1.5-pro',
+ settings: paramSettings[EModelEndpoint.google] ?? [],
+ }),
+ ).toBeUndefined();
+ });
+
+ it('uses the Bedrock provider-specific settings surface', () => {
+ const endpoint = `${EModelEndpoint.bedrock}-${BedrockProviders.Moonshot}`;
+ expect(
+ resolveReasoningSetting({
+ endpoint,
+ model: 'moonshot.kimi-k2.5',
+ settings: paramSettings[endpoint] ?? [],
+ })?.key,
+ ).toBe('reasoning_effort');
+ });
+
+ it('supports Bedrock Claude but hides non-reasoning Bedrock families', () => {
+ const anthropicEndpoint = `${EModelEndpoint.bedrock}-${BedrockProviders.Anthropic}`;
+ expect(
+ resolveReasoningSetting({
+ endpoint: anthropicEndpoint,
+ model: 'anthropic.claude-sonnet-4-6-v1:0',
+ settings: paramSettings[anthropicEndpoint] ?? [],
+ })?.key,
+ ).toBe('effort');
+
+ const metaEndpoint = `${EModelEndpoint.bedrock}-${BedrockProviders.Meta}`;
+ expect(
+ resolveReasoningSetting({
+ endpoint: metaEndpoint,
+ model: 'meta.llama4-maverick-instruct-v1:0',
+ settings: paramSettings[metaEndpoint] ?? [],
+ }),
+ ).toBeUndefined();
+ });
+
+ it('normalizes the production-shaped bare Bedrock endpoint before selecting Claude reasoning', () => {
+ const settings = paramSettings[`${EModelEndpoint.bedrock}-${BedrockProviders.Anthropic}`] ?? [];
+ expect(
+ resolveReasoningSetting({
+ endpoint: EModelEndpoint.bedrock,
+ model: 'anthropic.claude-3-7-sonnet-20250219-v1:0',
+ settings,
+ })?.key,
+ ).toBe('thinkingBudget');
+ });
+});
+
+describe('resolveReasoningSettingForTarget', () => {
+ it('uses a custom-backed agent default parameter surface', () => {
+ expect(
+ resolveReasoningSettingForTarget({
+ endpoint: 'ClaudeProxy',
+ model: 'claude-sonnet-4-6',
+ isAgent: true,
+ defaultParamsEndpoint: EModelEndpoint.anthropic,
+ })?.key,
+ ).toBe('effort');
+ });
+
+ it('prefers a custom endpoint default over the generic custom surface', () => {
+ expect(
+ resolveReasoningSettingForTarget({
+ endpoint: EModelEndpoint.custom,
+ model: 'claude-sonnet-4-6',
+ defaultParamsEndpoint: EModelEndpoint.anthropic,
+ })?.key,
+ ).toBe('effort');
+ });
+ it.each([EModelEndpoint.custom, Providers.OPENROUTER])(
+ 'does not infer reasoning for an undeclared %s deployment',
+ (endpoint) => {
+ expect(
+ resolveReasoningSettingForTarget({
+ endpoint,
+ model: 'deployment-model',
+ }),
+ ).toBeUndefined();
+ },
+ );
+ it('requires an explicit reasoning definition for Azure deployments', () => {
+ expect(
+ resolveReasoningSettingForTarget({
+ endpoint: EModelEndpoint.azureOpenAI,
+ model: 'administrator-named-deployment',
+ }),
+ ).toBeUndefined();
+ expect(
+ resolveReasoningSettingForTarget({
+ endpoint: EModelEndpoint.azureOpenAI,
+ model: 'administrator-named-deployment',
+ paramDefinitions: [{ key: 'reasoning_effort' }],
+ })?.key,
+ ).toBe('reasoning_effort');
+ });
+ it('honors an explicit reasoning format on a custom deployment', () => {
+ expect(
+ resolveReasoningSettingForTarget({
+ endpoint: EModelEndpoint.custom,
+ model: 'deployment-model',
+ reasoningFormat: ReasoningParameterFormat.reasoningObject,
+ })?.key,
+ ).toBe('reasoning_effort');
+ });
+ it('hides a custom deployment when its reasoning format is disabled', () => {
+ expect(
+ resolveReasoningSettingForTarget({
+ endpoint: EModelEndpoint.custom,
+ model: 'deployment-model',
+ reasoningFormat: ReasoningParameterFormat.disabled,
+ }),
+ ).toBeUndefined();
+ });
+
+ it('offers only the declared options a request override can carry', () => {
+ const declared = (options: string[]) =>
+ resolveReasoningSettingForTarget({
+ endpoint: EModelEndpoint.custom,
+ model: 'deployment-model',
+ paramDefinitions: [{ key: 'thinkingLevel', type: 'enum', options }],
+ });
+ expect(declared(['', 'low', 'ultra', 'high'])?.options).toEqual(['', 'low', 'high']);
+ expect(declared(['ultra', 'turbo'])).toBeUndefined();
+ });
+
+ it('merges a deployment-owned reasoning definition into provider defaults', () => {
+ expect(
+ resolveReasoningSettingForTarget({
+ endpoint: EModelEndpoint.custom,
+ model: 'deployment-model',
+ paramDefinitions: [
+ {
+ key: 'reasoning_effort',
+ type: 'enum',
+ options: ['low', 'high'],
+ } as SettingDefinition,
+ ],
+ })?.options,
+ ).toEqual(['low', 'high']);
+ });
+
+ it('resolves the declared effort control for a custom endpoint using Anthropic defaults', () => {
+ const setting = resolveReasoningSettingForTarget({
+ endpoint: EModelEndpoint.custom,
+ model: 'mock-model-a',
+ defaultParamsEndpoint: EModelEndpoint.anthropic,
+ paramDefinitions: [{ key: 'effort' }],
+ });
+
+ expect(setting).toMatchObject({
+ key: 'effort',
+ options: expect.arrayContaining(['low', 'high']),
+ });
+ });
+ it.each([
+ [
+ 'effort',
+ { key: 'effort', type: 'enum', options: ['low', 'high'] } as Partial<SettingDefinition>,
+ ],
+ [
+ 'thinkingLevel',
+ {
+ key: 'thinkingLevel',
+ type: 'enum',
+ options: ['low', 'high'],
+ } as Partial<SettingDefinition>,
+ ],
+ [
+ 'thinkingBudget',
+ {
+ key: 'thinkingBudget',
+ type: 'number',
+ range: { min: 256, max: 32768, step: 128 },
+ } as Partial<SettingDefinition>,
+ ],
+ ])(
+ 'appends the declared %s reasoning definition without a default parameter endpoint',
+ (key, definition) => {
+ const setting = resolveReasoningSettingForTarget({
+ endpoint: EModelEndpoint.custom,
+ model: 'deployment-model',
+ paramDefinitions: [definition],
+ });
+
+ expect(setting?.key).toBe(key);
+ expect(setting).toMatchObject(definition);
+ },
+ );
+});
+
+describe('isReasoningOverrideSupported', () => {
+ it('rejects a stale key and a model-specific value outside its range', () => {
+ const setting = {
+ key: 'thinkingBudget',
+ type: 'number',
+ range: { min: -1, positiveMin: 128, max: 32768, step: 128 },
+ } as SettingDefinition;
+
+ expect(
+ isReasoningOverrideSupported(
+ { key: 'reasoning_effort', value: ReasoningEffort.high },
+ setting,
+ ),
+ ).toBe(false);
+ expect(isReasoningOverrideSupported({ key: 'thinkingBudget', value: 64000 }, setting)).toBe(
+ false,
+ );
+ expect(isReasoningOverrideSupported({ key: 'thinkingBudget', value: 32768 }, setting)).toBe(
+ true,
+ );
+ });
+});
+
/**
* The field is rendered by every endpoint, so bounds written for Gemini would
* silently clamp a context window another provider accepts.
diff --git a/packages/data-provider/src/parameterSettings.ts b/packages/data-provider/src/parameterSettings.ts
index 8dbc93c9a2..d8a0c3ec74 100644
--- a/packages/data-provider/src/parameterSettings.ts
+++ b/packages/data-provider/src/parameterSettings.ts
@@ -1,3 +1,5 @@
+import type { SettingDefinition, SettingsConfiguration } from './generate';
+import type { TReasoningOverride } from './schemas';
import type { ResponsesApiRouting } from './types';
import {
Verbosity,
@@ -17,10 +19,15 @@ import {
BedrockProviders,
anthropicSettings,
} from './types';
-import { hasAlwaysOnThinking, hasBetweenToolsThinkingFloor, supportsPromptCache } from './bedrock';
-import { SettingDefinition, SettingsConfiguration } from './generate';
+import {
+ getModelKey,
+ getSettingsKeys,
+ reasoningOverrideSchema,
+ ReasoningParameterFormat,
+} from './schemas';
+import { isOpus55Model, supportsPromptCache, supportsAdaptiveThinking } from './bedrock';
import { resolveEffectiveUseResponsesApi } from './file-config';
-import { gpt6Tier } from './families';
+import { clampSettingRange } from './generate';
// Base definitions
const baseDefinitions: Record<string, SettingDefinition> = {
@@ -1309,6 +1316,241 @@ export const agentParamSettings: Record<string, SettingsConfiguration | undefine
return acc;
}, {});
+const reasoningSettingKeys = [
+ 'reasoning_effort',
+ 'effort',
+ 'thinkingLevel',
+ 'thinkingBudget',
+] as const;
+
+export type ReasoningSettingKey = (typeof reasoningSettingKeys)[number];
+
+const findReasoningSetting = (
+ settings: SettingsConfiguration,
+ key: ReasoningSettingKey,
+): SettingDefinition | undefined => settings.find((setting) => setting.key === key);
+
+const knownReasoningProviderEndpoints: Record<string, true> = {
+ [EModelEndpoint.openAI]: true,
+ [EModelEndpoint.azureOpenAI]: true,
+ [EModelEndpoint.anthropic]: true,
+ [EModelEndpoint.bedrock]: true,
+ [`${EModelEndpoint.bedrock}-${BedrockProviders.Anthropic}`]: true,
+ [`${EModelEndpoint.bedrock}-${BedrockProviders.Moonshot}`]: true,
+ [`${EModelEndpoint.bedrock}-${BedrockProviders.MoonshotAI}`]: true,
+ [`${EModelEndpoint.bedrock}-${BedrockProviders.ZAI}`]: true,
+};
+
+const isKnownReasoningProvider = (endpoint?: string | null): boolean =>
+ endpoint != null && knownReasoningProviderEndpoints[endpoint] === true;
+
+const isKnownOpenAIReasoningModel = (model: string): boolean =>
+ /(?:^|[/._-])(?:o[134](?:[-.]|$)|gpt[-.]?(?:[5-9]|\d{2,})(?:[-.]|$)|gpt[-.]?oss(?:[-.]|$))/i.test(
+ model,
+ );
+
+const isManualClaudeThinkingModel = (model: string): boolean =>
+ /claude-3[-.]7|claude-(?:sonnet|opus|haiku)-[4-9]|claude-[4-9](?:[-.][0-9]+)?-(?:sonnet|opus|haiku)/i.test(
+ model,
+ );
+
+/**
+ * Selects the request-scoped reasoning control supported by the active model.
+ * Custom and OpenRouter endpoints remain definition-driven because their model
+ * catalogs are deployment-owned and cannot be inferred safely from a name.
+ */
+export function resolveReasoningSetting({
+ endpoint,
+ model,
+ settings,
+}: {
+ endpoint: string;
+ model?: string | null;
+ settings: SettingsConfiguration;
+}): SettingDefinition | undefined {
+ if (!model) {
+ return undefined;
+ }
+
+ if (endpoint === EModelEndpoint.google) {
+ if (getGoogleThinkingBudgetBounds(model) != null) {
+ return findReasoningSetting(settings, 'thinkingBudget');
+ }
+ if (/gemini-(?:[3-9]|\d{2,})|gemma-(?:[4-9]|\d{2,})/i.test(model)) {
+ return findReasoningSetting(settings, 'thinkingLevel');
+ }
+ return undefined;
+ }
+
+ const isAnthropicEndpoint =
+ endpoint === EModelEndpoint.anthropic ||
+ endpoint === `${EModelEndpoint.bedrock}-${BedrockProviders.Anthropic}` ||
+ (endpoint === EModelEndpoint.bedrock &&
+ getModelKey(endpoint, model) === BedrockProviders.Anthropic);
+ if (isAnthropicEndpoint) {
+ if (supportsAdaptiveThinking(model)) {
+ return findReasoningSetting(settings, 'effort');
+ }
+ if (isManualClaudeThinkingModel(model)) {
+ return findReasoningSetting(settings, 'thinkingBudget');
+ }
+ return undefined;
+ }
+
+ if (endpoint === EModelEndpoint.azureOpenAI) {
+ /* Azure deployment names are administrator-defined and often contain no
+ * model-family signal. An explicit resolved parameter definition is the
+ * capability evidence available to this layer. */
+ return findReasoningSetting(settings, 'reasoning_effort');
+ }
+
+ if (endpoint === EModelEndpoint.openAI) {
+ return isKnownOpenAIReasoningModel(model)
+ ? findReasoningSetting(settings, 'reasoning_effort')
+ : undefined;
+ }
+
+ return reasoningSettingKeys.reduce<SettingDefinition | undefined>(
+ (resolved, key) => resolved ?? findReasoningSetting(settings, key),
+ undefined,
+ );
+}
+
+/** Narrows an enum reasoning setting to the options a request-scoped override
+ * can carry. A deployment may declare provider values the override schema does
+ * not accept; offering them rendered a choice that could never be submitted. */
+const toSubmittableReasoningSetting = (
+ setting: SettingDefinition | undefined,
+): SettingDefinition | undefined => {
+ if (setting?.options == null) {
+ return setting;
+ }
+ const options = setting.options.filter(
+ (option) => reasoningOverrideSchema.safeParse({ key: setting.key, value: option }).success,
+ );
+ if (options.length === setting.options.length) {
+ return setting;
+ }
+ return options.length === 0 ? undefined : { ...setting, options };
+};
+
+/** Builds the effective reasoning definition shared by the composer and the server.
+ * A model-spec lock is part of capability resolution, not a caller-only UI check:
+ * both surfaces must see the same unavailable result before an override is staged. */
+export function resolveReasoningSettingForTarget({
+ endpoint,
+ model,
+ isAgent = false,
+ defaultParamsEndpoint,
+ reasoningFormat,
+ paramDefinitions,
+ blockedReasoningKeys,
+}: {
+ endpoint: string;
+ model?: string | null;
+ isAgent?: boolean;
+ defaultParamsEndpoint?: string | null;
+ reasoningFormat?: ReasoningParameterFormat | null;
+ paramDefinitions?: Partial<SettingDefinition>[] | null;
+ blockedReasoningKeys?: ReadonlySet<string>;
+}): SettingDefinition | undefined {
+ if (!model || reasoningFormat === ReasoningParameterFormat.disabled) {
+ return undefined;
+ }
+ const [combinedSettingsKey, endpointSettingsKey] = getSettingsKeys(endpoint, model);
+ const effectiveDefaultParamsEndpoint = defaultParamsEndpoint ?? endpointSettingsKey;
+
+ const hasExplicitCapability =
+ (paramDefinitions?.some((setting) =>
+ reasoningSettingKeys.includes(setting.key as ReasoningSettingKey),
+ ) ??
+ false) ||
+ reasoningFormat != null ||
+ isKnownReasoningProvider(effectiveDefaultParamsEndpoint);
+ const usesGenericSettings =
+ endpoint === EModelEndpoint.custom ||
+ endpoint === Providers.OPENROUTER ||
+ paramSettings[endpoint] == null;
+ if (usesGenericSettings && !hasExplicitCapability) {
+ return undefined;
+ }
+ const baseSettings = isAgent
+ ? (agentParamSettings[combinedSettingsKey] ??
+ agentParamSettings[effectiveDefaultParamsEndpoint] ??
+ agentParamSettings[endpointSettingsKey] ??
+ paramSettings[combinedSettingsKey] ??
+ paramSettings[effectiveDefaultParamsEndpoint] ??
+ paramSettings[endpointSettingsKey] ??
+ [])
+ : (paramSettings[combinedSettingsKey] ??
+ paramSettings[effectiveDefaultParamsEndpoint] ??
+ paramSettings[endpointSettingsKey] ??
+ []);
+
+ const customSettingsByKey = new Map(
+ (paramDefinitions ?? []).flatMap((setting) =>
+ setting.key == null ? [] : ([[setting.key, setting]] as const),
+ ),
+ );
+ const settings = applyModelAwareDefaults(baseSettings, effectiveDefaultParamsEndpoint, model).map(
+ (setting) => {
+ const override = customSettingsByKey.get(setting.key);
+ return override == null ? setting : { ...setting, ...override };
+ },
+ );
+ const declaredReasoningSettings = (paramDefinitions ?? [])
+ .filter((setting) => reasoningSettingKeys.includes(setting.key as ReasoningSettingKey))
+ .filter((setting) => !settings.some((baseSetting) => baseSetting.key === setting.key))
+ .map((setting) => setting as SettingDefinition);
+ const effectiveSettings = [...settings, ...declaredReasoningSettings];
+ const explicitReasoningKey = paramDefinitions?.find((setting) =>
+ reasoningSettingKeys.includes(setting.key as ReasoningSettingKey),
+ )?.key as ReasoningSettingKey | undefined;
+ if (explicitReasoningKey != null) {
+ const explicitSetting = findReasoningSetting(effectiveSettings, explicitReasoningKey);
+ return explicitSetting != null && blockedReasoningKeys?.has(explicitSetting.key)
+ ? undefined
+ : toSubmittableReasoningSetting(explicitSetting);
+ }
+ const resolutionEndpoint = isKnownReasoningProvider(effectiveDefaultParamsEndpoint)
+ ? effectiveDefaultParamsEndpoint
+ : endpoint;
+ if (
+ resolutionEndpoint === EModelEndpoint.azureOpenAI &&
+ !paramDefinitions?.some((setting) =>
+ reasoningSettingKeys.includes(setting.key as ReasoningSettingKey),
+ )
+ ) {
+ return undefined;
+ }
+ const resolvedSetting = resolveReasoningSetting({
+ endpoint: resolutionEndpoint,
+ model,
+ settings: effectiveSettings,
+ });
+ return resolvedSetting != null && blockedReasoningKeys?.has(resolvedSetting.key)
+ ? undefined
+ : toSubmittableReasoningSetting(resolvedSetting);
+}
+
+/** Confirms that a stored one-shot override still belongs to the selected
+ * model and remains inside its advertised enum or numeric range. */
+export function isReasoningOverrideSupported(
+ reasoningOverride: TReasoningOverride,
+ setting: SettingDefinition | undefined,
+): boolean {
+ if (setting?.key !== reasoningOverride.key) {
+ return false;
+ }
+ if (typeof reasoningOverride.value === 'number') {
+ return (
+ setting.range == null ||
+ clampSettingRange(reasoningOverride.value, setting.range) === reasoningOverride.value
+ );
+ }
+ return setting.options == null || setting.options.includes(reasoningOverride.value);
+}
+
/**
* Resolves model-aware defaults for a settings configuration before rendering.
* Google's `maxOutputTokens` default depends on the selected Gemini model so that
diff --git a/packages/data-provider/src/schemas.spec.ts b/packages/data-provider/src/schemas.spec.ts
index 0acd30f303..7ec806e2ff 100644
--- a/packages/data-provider/src/schemas.spec.ts
+++ b/packages/data-provider/src/schemas.spec.ts
@@ -11,11 +11,37 @@ import {
eReasoningEffortSchema,
eReasoningModeSchema,
eReasoningContextSchema,
+ reasoningOverrideSchema,
subagentThreadLineageSchema,
getGoogleThinkingBudgetBounds,
tPresetSchema,
} from './schemas';
+describe('reasoningOverrideSchema', () => {
+ it.each([
+ { key: 'reasoning_effort', value: ReasoningEffort.high },
+ { key: 'effort', value: AnthropicEffort.medium },
+ { key: 'thinkingLevel', value: 'low' },
+ { key: 'thinkingBudget', value: -1 },
+ { key: 'thinkingBudget', value: 32768 },
+ { key: 'thinkingBudget', value: 500000 },
+ ])('accepts a supported request-scoped override: %o', (override) => {
+ expect(reasoningOverrideSchema.parse(override)).toEqual(override);
+ });
+
+ it.each([
+ { key: 'temperature', value: 1 },
+ { key: 'reasoning_effort', value: 'turbo' },
+ { key: 'effort', value: 'none' },
+ { key: 'thinkingLevel', value: 'max' },
+ { key: 'thinkingBudget', value: 1.5 },
+ { key: 'thinkingBudget', value: -2 },
+ { key: 'thinkingBudget', value: 1000, extra: true },
+ ])('rejects an invalid request-scoped override: %o', (override) => {
+ expect(reasoningOverrideSchema.safeParse(override).success).toBe(false);
+ });
+});
+
describe('anthropicSettings', () => {
describe('maxOutputTokens.reset()', () => {
const { reset } = anthropicSettings.maxOutputTokens;
diff --git a/packages/data-provider/src/schemas.ts b/packages/data-provider/src/schemas.ts
index 9e692a7621..7916b0c75f 100644
--- a/packages/data-provider/src/schemas.ts
+++ b/packages/data-provider/src/schemas.ts
@@ -357,6 +357,37 @@ export const eThinkingLevelSchema = z.nativeEnum(ThinkingLevel);
export const eReasoningModeSchema = z.nativeEnum(ReasoningMode);
export const eReasoningContextSchema = z.nativeEnum(ReasoningContext);
+export const reasoningOverrideSchema = z.discriminatedUnion('key', [
+ z
+ .object({
+ key: z.literal('reasoning_effort'),
+ value: eReasoningEffortSchema,
+ })
+ .strict(),
+ z
+ .object({
+ key: z.literal('effort'),
+ value: eAnthropicEffortSchema,
+ })
+ .strict(),
+ z
+ .object({
+ key: z.literal('thinkingLevel'),
+ value: eThinkingLevelSchema,
+ })
+ .strict(),
+ z
+ .object({
+ key: z.literal('thinkingBudget'),
+ /* No fixed ceiling: an operator's paramDefinitions may widen the range,
+ and the request is checked against the resolved range server-side. */
+ value: z.number().int().min(-1).max(Number.MAX_SAFE_INTEGER),
+ })
+ .strict(),
+]);
+
+export type TReasoningOverride = z.infer<typeof reasoningOverrideSchema>;
+
export const defaultAssistantFormValues = {
assistant: '',
id: '',
@@ -988,6 +1019,8 @@ export const tMessageSchema = z.object({
* request time and counted in the user message token count.
*/
quotes: z.array(z.string()).optional(),
+ /** Request-scoped reasoning selection that produced this user turn. */
+ reasoningOverride: reasoningOverrideSchema.optional(),
});
/**
diff --git a/packages/data-provider/src/types/queuedTurns.spec.ts b/packages/data-provider/src/types/queuedTurns.spec.ts
index 2233694ef2..efc5875bf8 100644
--- a/packages/data-provider/src/types/queuedTurns.spec.ts
+++ b/packages/data-provider/src/types/queuedTurns.spec.ts
@@ -5,6 +5,7 @@ import {
enqueueAgentQueuedTurnSchema,
listAgentQueuedTurnsSchema,
} from './queuedTurns';
+import { ReasoningEffort } from '../schemas';
const request = {
conversationId: 'conversation-1',
@@ -14,6 +15,7 @@ const request = {
files: [{ file_id: 'file-1', filename: 'context.txt', llmDeliveryPath: 'text' }],
quotes: ['quoted context'],
manualSkills: ['research'],
+ reasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.high },
expectedPredecessorCreatedAt: 42,
};
@@ -61,6 +63,15 @@ describe('agent queued turn schemas', () => {
).toThrow();
});
+ it('rejects an invalid reasoning override', () => {
+ expect(() =>
+ enqueueAgentQueuedTurnSchema.parse({
+ ...request,
+ reasoningOverride: { key: 'temperature', value: 0.5 },
+ }),
+ ).toThrow();
+ });
+
it('validates list and cancel identities', () => {
expect(
listAgentQueuedTurnsSchema.parse({
diff --git a/packages/data-provider/src/types/queuedTurns.ts b/packages/data-provider/src/types/queuedTurns.ts
index aacfe4ae60..5baa3ae250 100644
--- a/packages/data-provider/src/types/queuedTurns.ts
+++ b/packages/data-provider/src/types/queuedTurns.ts
@@ -1,5 +1,5 @@
import { z } from 'zod';
-import { CODE_APPROVAL_MODES } from '../code/approval';
+import { reasoningOverrideSchema } from '../schemas';
export const agentQueuedTurnStatuses = [
'queued',
@@ -31,8 +31,7 @@ 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/misc/documentdb/audit.documentdb.spec.ts b/packages/data-schemas/misc/documentdb/audit.documentdb.spec.ts
index 93f57ae569..8b9bd373df 100644
--- a/packages/data-schemas/misc/documentdb/audit.documentdb.spec.ts
+++ b/packages/data-schemas/misc/documentdb/audit.documentdb.spec.ts
@@ -274,6 +274,7 @@ describeLive('Amazon DocumentDB - 2026-08-30 audit surface', () => {
});
it('probes the classic-operator replacements the fix would use', async () => {
+ expect.hasAssertions();
await probe('$max update operator', () =>
getDb()
.collection(probeCollection)
@@ -291,6 +292,7 @@ describeLive('Amazon DocumentDB - 2026-08-30 audit surface', () => {
describe('production shapes (drives the real methods)', () => {
it('site 1 - claimNextAgentTriggerDelivery', async () => {
+ expect.hasAssertions();
await probe('enqueueAgentTriggerDelivery', () =>
triggerMethods.enqueueAgentTriggerDelivery({
deliveryKey,
@@ -314,6 +316,7 @@ describeLive('Amazon DocumentDB - 2026-08-30 audit surface', () => {
});
it('site 2 - renewAgentTriggerDeliveryProducerLease', async () => {
+ expect.hasAssertions();
await probe('renewAgentTriggerDeliveryProducerLease', () =>
triggerMethods.renewAgentTriggerDeliveryProducerLease({
deliveryKey,
@@ -325,6 +328,7 @@ describeLive('Amazon DocumentDB - 2026-08-30 audit surface', () => {
});
it('site 3 - claimBackgroundToolResults', async () => {
+ expect.hasAssertions();
/** This method returns `not_found`/`not_ready` before it ever builds the
* update, so an unseeded probe would report a false `accepted`. Seed a
* terminal, wakeup-eligible, unclaimed task so the claim path is reached. */
@@ -360,6 +364,7 @@ describeLive('Amazon DocumentDB - 2026-08-30 audit surface', () => {
});
it('site 4 - releaseBackgroundToolResultClaims', async () => {
+ expect.hasAssertions();
await probe('releaseBackgroundToolResultClaims', () =>
messageMethods.releaseBackgroundToolResultClaims({
userId: String(userId),
@@ -374,6 +379,7 @@ describeLive('Amazon DocumentDB - 2026-08-30 audit surface', () => {
});
it('site 5 - getMessagesForSubagentThreadView ($$REMOVE path)', async () => {
+ expect.hasAssertions();
await probe('getMessagesForSubagentThreadView (list)', () =>
messageMethods.getMessagesForSubagentThreadView({
user: String(userId),
@@ -386,6 +392,7 @@ describeLive('Amazon DocumentDB - 2026-08-30 audit surface', () => {
});
it('site 6 - getMessagesForSubagentThreadView ($facet path)', async () => {
+ expect.hasAssertions();
await probe('getMessagesForSubagentThreadView (selected)', () =>
messageMethods.getMessagesForSubagentThreadView({
user: String(userId),
@@ -399,6 +406,7 @@ describeLive('Amazon DocumentDB - 2026-08-30 audit surface', () => {
});
it('listSubagentTasksForThreads ($regexMatch path)', async () => {
+ expect.hasAssertions();
await probe('listSubagentTasksForThreads', () =>
messageMethods.listSubagentTasksForThreads({
user: String(userId),
@@ -418,6 +426,7 @@ describeLive('Amazon DocumentDB - 2026-08-30 audit surface', () => {
});
it('site 7 - updateToolCallResult', async () => {
+ expect.hasAssertions();
const settleMessageId = `audit-settle-${runId}`;
await mongoose.models.Message.create({
messageId: settleMessageId,
diff --git a/packages/data-schemas/misc/documentdb/sweep.documentdb.spec.ts b/packages/data-schemas/misc/documentdb/sweep.documentdb.spec.ts
index 9e5eae1cfb..08f01dc3c0 100644
--- a/packages/data-schemas/misc/documentdb/sweep.documentdb.spec.ts
+++ b/packages/data-schemas/misc/documentdb/sweep.documentdb.spec.ts
@@ -299,7 +299,7 @@ function replaceValue(node: unknown, target: string, replacement: unknown): unkn
/** Repairs synthesized arguments from a validation error's own message, so the
* retry reaches the database instead of being reported `not-driven`. Returns
* the repaired arguments, or null when the error is not machine-repairable. */
-function adaptArgs(args: unknown[], error: unknown, paramNames: string[] = []): unknown[] | null {
+function adaptArgs(args: unknown[], error: unknown): unknown[] | null {
const message = String((error as { message?: string })?.message ?? '');
let match = /Cast to (?:\[)?ObjectId(?:\])? failed for value "+?\[?'?"?([^"'\]]+)/.exec(message);
if (match != null) {
@@ -642,10 +642,13 @@ describeSweep(`data-schemas method sweep (${BASELINE ? 'MongoDB baseline' : 'Doc
);
}
if (STRICT) {
- /** Enforced against the FINALIZED rows: the per-test assertion has
+ /** Enforced against the FINALIZED rows: the per-test check has
* already passed for a row that timed out and only later recorded its
* engine rejection. */
- expect(rejected.map((row) => `${row.name}: ${row.engineError}`)).toEqual([]);
+ const rejectionDetails = rejected.map((row) => `${row.name}: ${row.engineError}`);
+ if (rejectionDetails.length > 0) {
+ throw new Error(`DocumentDB method sweep rejected:\n${rejectionDetails.join('\n')}`);
+ }
}
}, 120_000);
diff --git a/packages/data-schemas/misc/ferretdb/multiTenancy.ferretdb.spec.ts b/packages/data-schemas/misc/ferretdb/multiTenancy.ferretdb.spec.ts
index 1ff69a6f08..753718b68e 100644
--- a/packages/data-schemas/misc/ferretdb/multiTenancy.ferretdb.spec.ts
+++ b/packages/data-schemas/misc/ferretdb/multiTenancy.ferretdb.spec.ts
@@ -9,22 +9,22 @@ import { getModelSchemas } from './schemas';
* at scale using database-per-org isolation via Mongoose useDb().
*
* Phases:
- * 1. useDb schema mapping — verifies per-org PostgreSQL schema creation and data isolation
- * 2. Index initialization — validates every current org-local collection + its
+ * 1. useDb schema mapping: verifies per-org PostgreSQL schema creation and data isolation
+ * 2. Index initialization: validates every current org-local collection + its
* indexes, tests for deadlocks
- * 3. Scaling curve — measures catalog growth, init time, and query latency at 10/50/100 orgs
- * 4. Write amplification — compares update cost on high-index vs zero-index collections
- * 5. Shared-collection alternative — benchmarks orgId-discriminated shared collections
+ * 3. Scaling curve: measures catalog growth, init time, and query latency at 10/50/100 orgs
+ * 4. Write amplification: compares update cost on high-index vs zero-index collections
+ * 5. Shared-collection alternative: benchmarks orgId-discriminated shared collections
*
* Run:
* FERRETDB_URI="mongodb://ferretdb:[email protected]:27020/mt_bench" \
* npx jest multiTenancy.ferretdb --testTimeout=600000
*
* Env vars:
- * FERRETDB_URI — Required. FerretDB connection string.
- * PG_CONTAINER — Docker container name for psql (default: librechat-ferretdb-postgres-1)
- * SCALE_TIERS — Comma-separated org counts (default: 10,50,100)
- * WRITE_AMP_DOCS — Number of docs for write amp test (default: 200)
+ * FERRETDB_URI : Required. FerretDB connection string.
+ * PG_CONTAINER : Docker container name for psql (default: librechat-ferretdb-postgres-1)
+ * SCALE_TIERS : Comma-separated org counts (default: 10,50,100)
+ * WRITE_AMP_DOCS : Number of docs for write amp test (default: 200)
*/
const FERRETDB_URI = process.env.FERRETDB_URI;
@@ -273,14 +273,17 @@ describeIfFerretDB('FerretDB Multi-Tenancy Benchmark', () => {
}
const t0 = Date.now();
+ let failure: Error | undefined;
try {
await Promise.all(Object.values(models).map((m) => m.createIndexes()));
- console.log(`[Phase 2] Concurrent: ${Date.now() - t0}ms — no deadlock`);
+ console.log(`[Phase 2] Concurrent: ${Date.now() - t0}ms, no deadlock`);
} catch (err) {
+ failure = err instanceof Error ? err : new Error(String(err));
console.warn(
- `[Phase 2] Concurrent: DEADLOCKED after ${Date.now() - t0}ms — ${(err as Error).message}`,
+ `[Phase 2] Concurrent: DEADLOCKED after ${Date.now() - t0}ms: ${failure.message}`,
);
}
+ expect(failure).toBeUndefined();
}, 120_000);
it('verifies sparse, partial, and TTL index types on FerretDB', async () => {
@@ -340,7 +343,7 @@ describeIfFerretDB('FerretDB Multi-Tenancy Benchmark', () => {
beforeAll(() => {
const baseline = catalogMetrics();
console.log(
- `[Phase 3] Baseline — collections: ${baseline.collections}, ` +
+ `[Phase 3] Baseline, collections: ${baseline.collections}, ` +
`databases: ${baseline.databases}, catalog indexes: ${baseline.catalogIndexes}, ` +
`data tables: ${baseline.dataTables}, pg_class: ${baseline.pgClassTotal}`,
);
diff --git a/packages/data-schemas/misc/ferretdb/orgOperations.ferretdb.spec.ts b/packages/data-schemas/misc/ferretdb/orgOperations.ferretdb.spec.ts
index 2db44d62bf..b115e0f0cb 100644
--- a/packages/data-schemas/misc/ferretdb/orgOperations.ferretdb.spec.ts
+++ b/packages/data-schemas/misc/ferretdb/orgOperations.ferretdb.spec.ts
@@ -30,9 +30,12 @@ const MODEL_COUNT = Object.keys(MODEL_SCHEMAS).length;
const NEW_MODEL = 'OrgEvent';
const NEW_COLLECTION = 'orgevents';
-function registerModels(conn: Connection): Record<string, Model<unknown>> {
+function registerModels(
+ conn: Connection,
+ schemas: Record<string, Schema> = MODEL_SCHEMAS,
+): Record<string, Model<unknown>> {
const models: Record<string, Model<unknown>> = {};
- for (const [name, schema] of Object.entries(MODEL_SCHEMAS)) {
+ for (const [name, schema] of Object.entries(schemas)) {
models[name] = conn.models[name] || conn.model(name, schema);
}
return models;
@@ -97,7 +100,7 @@ async function migrateOrg(
schemas: Record<string, Schema>,
): Promise<MigrationResult> {
const t0 = Date.now();
- const models = registerModels(conn);
+ const models = registerModels(conn, schemas);
const existingCollections = new Set(
(await conn.db!.listCollections().toArray()).map((c) => c.name),
);
diff --git a/packages/data-schemas/misc/ferretdb/sharding.ferretdb.spec.ts b/packages/data-schemas/misc/ferretdb/sharding.ferretdb.spec.ts
index 42c4d12285..5412c7faed 100644
--- a/packages/data-schemas/misc/ferretdb/sharding.ferretdb.spec.ts
+++ b/packages/data-schemas/misc/ferretdb/sharding.ferretdb.spec.ts
@@ -111,8 +111,7 @@ class TenantRouter {
}
/** Convenience: get a single model for an org */
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- async getModel(orgId: string, modelName: string): Promise<Model<any>> {
+ async getModel(orgId: string, modelName: string): Promise<Model<unknown>> {
const models = await this.getOrgModels(orgId);
const model = models[modelName];
if (!model) {
@@ -441,10 +440,9 @@ describeIfFerretDB('Sharding PoC', () => {
describe('simulated Express middleware pattern', () => {
it('demonstrates the request-scoped getModel pattern', async () => {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
const fakeReq = { orgId: 'org_1' } as {
orgId: string;
- getModel?: (name: string) => Promise<Model<any>>;
+ getModel?: (name: string) => Promise<Model<unknown>>;
};
fakeReq.getModel = (modelName: string) => router.getModel(fakeReq.orgId, modelName);
diff --git a/packages/data-schemas/src/app/interface.spec.ts b/packages/data-schemas/src/app/interface.spec.ts
index 74f56519a4..f8c519869d 100644
--- a/packages/data-schemas/src/app/interface.spec.ts
+++ b/packages/data-schemas/src/app/interface.spec.ts
@@ -36,28 +36,69 @@ 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({
+ it('uses and preserves the schema default for queued-turn reconciliation', async () => {
+ const configDefaults = getConfigDefaults();
+ const defaultInterface = await loadDefaultInterface({
config: {},
- configDefaults: getConfigDefaults(),
+ configDefaults,
});
+ expect(defaultInterface?.queuedTurnReconciliationTimeoutMs).toBe(60_000);
- expect(interfaceConfig?.agentSelectorLimit).toBe(10);
+ const configuredInterface = await loadDefaultInterface({
+ config: { interface: { queuedTurnReconciliationTimeoutMs: 180_000 } },
+ configDefaults,
+ });
+ expect(configuredInterface?.queuedTurnReconciliationTimeoutMs).toBe(180_000);
});
- it('forwards a configured agent selector list cap to the served interface', async () => {
- const config: Partial<TCustomConfig> = {
- interface: {
- agentSelectorLimit: 4,
- },
- };
+ it('uses and preserves the schema default for the queued-send lock expiry', async () => {
+ const configDefaults = getConfigDefaults();
+ const defaultInterface = await loadDefaultInterface({
+ config: {},
+ configDefaults,
+ });
+ expect(defaultInterface?.queuedSendLockTimeoutMs).toBe(60_000);
- const interfaceConfig = await loadDefaultInterface({
- config,
- configDefaults: getConfigDefaults(),
+ const configuredInterface = await loadDefaultInterface({
+ config: { interface: { queuedSendLockTimeoutMs: 15_000 } },
+ configDefaults,
});
+ expect(configuredInterface?.queuedSendLockTimeoutMs).toBe(15_000);
+ });
+
+ it('uses and preserves the schema default for the composer recent-files limit', async () => {
+ const configDefaults = getConfigDefaults();
+ const defaultInterface = await loadDefaultInterface({
+ config: {},
+ configDefaults,
+ });
+ expect(defaultInterface?.composerRecentFiles).toBe(5);
+
+ const configuredInterface = await loadDefaultInterface({
+ config: { interface: { composerRecentFiles: 10 } },
+ configDefaults,
+ });
+ expect(configuredInterface?.composerRecentFiles).toBe(10);
+ });
+
+ it('uses and preserves the schema default for steer arm confirmation', async () => {
+ const configDefaults = getConfigDefaults();
+ const interfaceDefaults = {
+ ...configDefaults.interface,
+ steerArmConfirmationTimeoutMs: 10_000,
+ };
+ const defaults = { ...configDefaults, interface: interfaceDefaults };
+ const defaultInterface = await loadDefaultInterface({
+ config: {},
+ configDefaults: defaults,
+ });
+ expect(defaultInterface?.steerArmConfirmationTimeoutMs).toBe(10_000);
- expect(interfaceConfig?.agentSelectorLimit).toBe(4);
+ const configuredInterface = await loadDefaultInterface({
+ config: { interface: { steerArmConfirmationTimeoutMs: 30_000 } },
+ configDefaults: defaults,
+ });
+ expect(configuredInterface?.steerArmConfirmationTimeoutMs).toBe(30_000);
});
it('preserves disabled URL auto-submit config', async () => {
diff --git a/packages/data-schemas/src/app/interface.ts b/packages/data-schemas/src/app/interface.ts
index de9bce7783..fb14fe7f8a 100644
--- a/packages/data-schemas/src/app/interface.ts
+++ b/packages/data-schemas/src/app/interface.ts
@@ -48,6 +48,14 @@ export async function loadDefaultInterface({
feedback: interfaceConfig?.feedback ?? defaults.feedback,
currency: interfaceConfig?.currency ?? defaults.currency,
theme: interfaceConfig?.theme,
+ steerArmConfirmationTimeoutMs:
+ interfaceConfig?.steerArmConfirmationTimeoutMs ?? defaults.steerArmConfirmationTimeoutMs,
+ queuedTurnReconciliationTimeoutMs:
+ interfaceConfig?.queuedTurnReconciliationTimeoutMs ??
+ defaults.queuedTurnReconciliationTimeoutMs,
+ queuedSendLockTimeoutMs:
+ interfaceConfig?.queuedSendLockTimeoutMs ?? defaults.queuedSendLockTimeoutMs,
+ composerRecentFiles: interfaceConfig?.composerRecentFiles ?? defaults.composerRecentFiles,
// Permissions and related settings - only include if explicitly configured
bookmarks: interfaceConfig?.bookmarks,
diff --git a/packages/data-schemas/src/methods/file.ts b/packages/data-schemas/src/methods/file.ts
index 7e0993bc13..156fd477ea 100644
--- a/packages/data-schemas/src/methods/file.ts
+++ b/packages/data-schemas/src/methods/file.ts
@@ -134,6 +134,7 @@ export function createFileMethods(mongoose: typeof import('mongoose')): {
filter: FilterQuery<IMongoFile>,
_sortOptions?: Record<string, SortOrder> | null,
selectFields?: Record<string, 0 | 1> | string | null,
+ limit?: number | null,
) => Promise<IMongoFile[] | null>;
getExpiredFiles: (limit?: number, options?: ExpiredFileQueryOptions) => Promise<IMongoFile[]>;
incrementFileDeletionAttempts: (file_id: string) => Promise<number>;
@@ -363,13 +364,14 @@ export function createFileMethods(mongoose: typeof import('mongoose')): {
* @param filter - The filter criteria to apply
* @param _sortOptions - Optional sort parameters
* @param selectFields - Fields to include/exclude in the query results. Default excludes the 'text' field
- * @param options - Additional query options (userId, agentId for ACL)
+ * @param limit - Optional max number of documents to return (newest first)
* @returns A promise that resolves to an array of file documents
*/
async function getFiles(
filter: FilterQuery<IMongoFile>,
_sortOptions?: Record<string, SortOrder> | null,
selectFields?: string | Record<string, 0 | 1> | null | undefined,
+ limit?: number | null,
): Promise<IMongoFile[] | null> {
const File = mongoose.models.File as Model<IMongoFile>;
const sortOptions = { updatedAt: -1 as SortOrder, ..._sortOptions };
@@ -379,6 +381,9 @@ export function createFileMethods(mongoose: typeof import('mongoose')): {
} else {
query.select({ text: 0 });
}
+ if (limit != null && limit > 0) {
+ query.limit(limit);
+ }
return await query.sort(sortOptions).lean<IMongoFile[]>();
}
diff --git a/packages/data-schemas/src/methods/queuedTurn.spec.ts b/packages/data-schemas/src/methods/queuedTurn.spec.ts
index 0e8b5207af..4a9e8cb2b2 100644
--- a/packages/data-schemas/src/methods/queuedTurn.spec.ts
+++ b/packages/data-schemas/src/methods/queuedTurn.spec.ts
@@ -1,6 +1,7 @@
import mongoose from 'mongoose';
import { createHash } from 'node:crypto';
import { MongoMemoryServer } from 'mongodb-memory-server';
+import { ReasoningEffort } from 'librechat-data-provider';
import type { Model } from 'mongoose';
import type {
IAgentQueuedTurnDocument,
@@ -95,6 +96,7 @@ describe('agent queued turn methods', () => {
],
quotes: [' quote ', '', 'second'],
manualSkills: [' skill-a ', 'skill-a'],
+ reasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.high },
expectedPredecessorCreatedAt: 42,
});
@@ -107,6 +109,7 @@ describe('agent queued turn methods', () => {
files: [{ file_id: 'file-1', filename: 'report.pdf' }],
quotes: ['quote', 'second'],
manualSkills: ['skill-a'],
+ reasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.high },
});
expect(first.replayed).toBe(false);
@@ -120,11 +123,27 @@ describe('agent queued turn methods', () => {
files: [{ file_id: 'file-1', filename: 'report.pdf', llmDeliveryPath: 'text' }],
quotes: ['quote', 'second'],
manualSkills: ['skill-a'],
+ reasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.high },
expectedPredecessorCreatedAt: 42,
});
expect(replay).toMatchObject({
replayed: true,
- turn: { queuedTurnId: first.turn.queuedTurnId },
+ turn: {
+ queuedTurnId: first.turn.queuedTurnId,
+ reasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.high },
+ },
+ });
+ await expect(methods.listActiveAgentQueuedTurns(input)).resolves.toEqual([
+ expect.objectContaining({
+ queuedTurnId: first.turn.queuedTurnId,
+ reasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.high },
+ }),
+ ]);
+ await expect(
+ methods.claimNextAgentQueuedTurn(claimInput(first.turn.queuedTurnId)),
+ ).resolves.toMatchObject({
+ outcome: 'acquired',
+ claim: { reasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.high } },
});
await expect(
methods.enqueueAgentQueuedTurn({ ...input, agentId: 'agent-2' }),
@@ -135,6 +154,12 @@ describe('agent queued turn methods', () => {
parentMessageId: 'different-parent',
}),
).rejects.toBeInstanceOf(AgentQueuedTurnConflictError);
+ await expect(
+ methods.enqueueAgentQueuedTurn({
+ ...input,
+ reasoningOverride: { key: 'reasoning_effort', value: ReasoningEffort.low },
+ }),
+ ).rejects.toBeInstanceOf(AgentQueuedTurnConflictError);
expect(await Turn.countDocuments()).toBe(1);
});
diff --git a/packages/data-schemas/src/methods/queuedTurn.ts b/packages/data-schemas/src/methods/queuedTurn.ts
index ad61076152..17ddf42730 100644
--- a/packages/data-schemas/src/methods/queuedTurn.ts
+++ b/packages/data-schemas/src/methods/queuedTurn.ts
@@ -1,6 +1,6 @@
import { createHash, randomUUID } from 'node:crypto';
-import { CODE_APPROVAL_MODES } from 'librechat-data-provider';
-import type { CodeApprovalMode } from 'librechat-data-provider';
+import { reasoningOverrideSchema } from 'librechat-data-provider';
+import type { TReasoningOverride } from 'librechat-data-provider';
import type { FilterQuery, Model, Types } from 'mongoose';
import type {
AgentQueuedTurnActiveRecord,
@@ -110,9 +110,7 @@ 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;
availableAt?: Date;
@@ -521,6 +519,15 @@ function normalizeText(text: string): string {
return normalized;
}
+function normalizeReasoningOverride(
+ reasoningOverride: TReasoningOverride | undefined,
+): TReasoningOverride | undefined {
+ if (reasoningOverride == null) {
+ return undefined;
+ }
+ return reasoningOverrideSchema.parse(reasoningOverride);
+}
+
function normalizePredecessor(value: number | undefined): number | undefined {
if (value == null) {
return undefined;
@@ -547,9 +554,7 @@ 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,
};
@@ -622,7 +627,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,
}),
@@ -684,7 +689,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/methods/share.ts b/packages/data-schemas/src/methods/share.ts
index 216c7daadd..1849be8f13 100644
--- a/packages/data-schemas/src/methods/share.ts
+++ b/packages/data-schemas/src/methods/share.ts
@@ -698,6 +698,7 @@ function anonymizeMessages(
...(message.manualSkills && { manualSkills: message.manualSkills }),
...(message.alwaysAppliedSkills && { alwaysAppliedSkills: message.alwaysAppliedSkills }),
...(message.quotes && { quotes: message.quotes }),
+ ...(message.reasoningOverride && { reasoningOverride: message.reasoningOverride }),
...(files && { files }),
...(attachments && { attachments }),
};
diff --git a/packages/data-schemas/src/schema/message.ts b/packages/data-schemas/src/schema/message.ts
index cb88fc01b5..6ca371ed4b 100644
--- a/packages/data-schemas/src/schema/message.ts
+++ b/packages/data-schemas/src/schema/message.ts
@@ -270,6 +270,19 @@ const messageSchema: Schema<IMessage> = new Schema(
* count), so they are not duplicated into the stored `text`.
*/
quotes: { type: [String], default: undefined },
+ /** Request-scoped reasoning selection used for this user turn. */
+ reasoningOverride: {
+ type: {
+ key: {
+ type: String,
+ enum: ['reasoning_effort', 'effort', 'thinkingLevel', 'thinkingBudget'],
+ required: true,
+ },
+ value: { type: mongoose.Schema.Types.Mixed, required: true },
+ },
+ _id: false,
+ default: undefined,
+ },
/*
attachments: {
type: [
diff --git a/packages/data-schemas/src/schema/queuedTurn.ts b/packages/data-schemas/src/schema/queuedTurn.ts
index ba508d3c9d..0fd6f32f51 100644
--- a/packages/data-schemas/src/schema/queuedTurn.ts
+++ b/packages/data-schemas/src/schema/queuedTurn.ts
@@ -24,6 +24,18 @@ const failureSchema = new Schema(
{ _id: false },
);
+const reasoningOverrideSchema = new Schema(
+ {
+ key: {
+ type: String,
+ enum: ['reasoning_effort', 'effort', 'thinkingLevel', 'thinkingBudget'],
+ required: true,
+ },
+ value: { type: Schema.Types.Mixed, required: true },
+ },
+ { _id: false },
+);
+
const terminalReceiptSchema = new Schema(
{
outcome: {
@@ -74,7 +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 },
availableAt: { type: Date, required: true },
diff --git a/packages/data-schemas/src/types/message.ts b/packages/data-schemas/src/types/message.ts
index d2628b6110..679f9e9b80 100644
--- a/packages/data-schemas/src/types/message.ts
+++ b/packages/data-schemas/src/types/message.ts
@@ -1,6 +1,7 @@
import type {
TFeedbackRating,
TFeedbackTag,
+ TReasoningOverride,
UserSubmittedMessageFieldPath,
} from 'librechat-data-provider';
import type { Document } from 'mongoose';
@@ -135,6 +136,8 @@ export interface IMessage extends Document {
alwaysAppliedSkills?: string[];
/** Verbatim excerpts the user quoted to reference on this turn. UI-only metadata for `MessageQuotes`. */
quotes?: string[];
+ /** Request-scoped reasoning selection that produced this user turn. */
+ reasoningOverride?: TReasoningOverride;
expiredAt?: Date | null;
createdAt?: Date;
updatedAt?: Date;
diff --git a/packages/data-schemas/src/types/queuedTurn.ts b/packages/data-schemas/src/types/queuedTurn.ts
index bb45d6c082..75a418e63f 100644
--- a/packages/data-schemas/src/types/queuedTurn.ts
+++ b/packages/data-schemas/src/types/queuedTurn.ts
@@ -1,4 +1,4 @@
-import type { CodeApprovalMode } from 'librechat-data-provider';
+import type { TReasoningOverride } from 'librechat-data-provider';
import type { Document, Types } from 'mongoose';
export type AgentQueuedTurnStatus =
@@ -73,8 +73,7 @@ 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;
availableAt: Date;
@@ -151,7 +150,7 @@ export type AgentQueuedTurnActiveRecord = Pick<
| 'files'
| 'quotes'
| 'manualSkills'
- | 'codeApprovalMode'
+ | 'reasoningOverride'
| 'expectedPredecessorCreatedAt'
| 'attempts'
| 'availableAt'
diff --git a/packages/data-schemas/src/types/share.ts b/packages/data-schemas/src/types/share.ts
index c0bfc4e532..cb64247db3 100644
--- a/packages/data-schemas/src/types/share.ts
+++ b/packages/data-schemas/src/types/share.ts
@@ -96,6 +96,7 @@ export type SharedMessage = Pick<
| 'manualSkills'
| 'alwaysAppliedSkills'
| 'quotes'
+ | 'reasoningOverride'
> & {
model?: string;
files?: SharedFile[];
diff --git a/src/tests/oidc-integration.test.ts b/src/tests/oidc-integration.test.ts
index 2bbff4fd37..654f0e7df8 100644
--- a/src/tests/oidc-integration.test.ts
+++ b/src/tests/oidc-integration.test.ts
@@ -30,7 +30,8 @@ describe('OpenID Connect Federated Provider Token Integration', () => {
openidId: 'cognito-user-123',
federatedTokens: {
access_token: 'cognito-access-token-123',
- id_token: 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJjb2duaXRvLXVzZXItMTIzIiwiZW1haWwiOiJ0ZXN0QGV4YW1wbGUuY29tIiwibmFtZSI6IlRlc3QgVXNlciIsImV4cCI6MTcwMDAwMDAwMH0.fake-signature',
+ id_token:
+ 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJjb2duaXRvLXVzZXItMTIzIiwiZW1haWwiOiJ0ZXN0QGV4YW1wbGUuY29tIiwibmFtZSI6IlRlc3QgVXNlciIsImV4cCI6MTcwMDAwMDAwMH0.fake-signature',
expires_at: Math.floor(Date.now() / 1000) + 3600, // Expires in 1 hour
},
};
@@ -272,7 +273,7 @@ describe('OpenID Connect Federated Provider Token Integration', () => {
describe('Integration with resolveHeaders', () => {
it('should resolve OpenID Connect placeholders in headers for Cognito', () => {
const headers = {
- 'Authorization': '{{LIBRECHAT_OPENID_TOKEN}}',
+ Authorization: '{{LIBRECHAT_OPENID_TOKEN}}',
'X-User-ID': '{{LIBRECHAT_OPENID_USER_ID}}',
'X-User-Email': '{{LIBRECHAT_OPENID_USER_EMAIL}}',
};
@@ -289,7 +290,7 @@ describe('OpenID Connect Federated Provider Token Integration', () => {
it('should work with Bearer token format for Cognito', () => {
const headers = {
- 'Authorization': 'Bearer {{LIBRECHAT_OPENID_TOKEN}}',
+ Authorization: 'Bearer {{LIBRECHAT_OPENID_TOKEN}}',
};
const resolvedHeaders = resolveHeaders({
@@ -302,7 +303,7 @@ describe('OpenID Connect Federated Provider Token Integration', () => {
it('should work with specific access token placeholder', () => {
const headers = {
- 'Authorization': 'Bearer {{LIBRECHAT_OPENID_ACCESS_TOKEN}}',
+ Authorization: 'Bearer {{LIBRECHAT_OPENID_ACCESS_TOKEN}}',
'X-Cognito-ID-Token': '{{LIBRECHAT_OPENID_ID_TOKEN}}',
};
@@ -312,7 +313,9 @@ describe('OpenID Connect Federated Provider Token Integration', () => {
});
expect(resolvedHeaders['Authorization']).toBe('Bearer cognito-access-token-123');
- expect(resolvedHeaders['X-Cognito-ID-Token']).toContain('eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9');
+ expect(resolvedHeaders['X-Cognito-ID-Token']).toContain(
+ 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9',
+ );
});
});
@@ -322,9 +325,9 @@ describe('OpenID Connect Federated Provider Token Integration', () => {
command: 'node',
args: ['server.js'],
env: {
- 'COGNITO_ACCESS_TOKEN': '{{LIBRECHAT_OPENID_TOKEN}}',
- 'USER_ID': '{{LIBRECHAT_OPENID_USER_ID}}',
- 'USER_EMAIL': '{{LIBRECHAT_OPENID_USER_EMAIL}}',
+ COGNITO_ACCESS_TOKEN: '{{LIBRECHAT_OPENID_TOKEN}}',
+ USER_ID: '{{LIBRECHAT_OPENID_USER_ID}}',
+ USER_EMAIL: '{{LIBRECHAT_OPENID_USER_EMAIL}}',
},
};
@@ -343,7 +346,7 @@ describe('OpenID Connect Federated Provider Token Integration', () => {
type: 'sse' as const,
url: 'https://api.example.com/mcp',
headers: {
- 'Authorization': 'Bearer {{LIBRECHAT_OPENID_ACCESS_TOKEN}}',
+ Authorization: 'Bearer {{LIBRECHAT_OPENID_ACCESS_TOKEN}}',
'X-Cognito-User-Info': '{{LIBRECHAT_OPENID_USER_EMAIL}}',
'X-Cognito-ID-Token': '{{LIBRECHAT_OPENID_ID_TOKEN}}',
},
@@ -356,7 +359,9 @@ describe('OpenID Connect Federated Provider Token Integration', () => {
expect(processedOptions.headers?.['Authorization']).toBe('Bearer cognito-access-token-123');
expect(processedOptions.headers?.['X-Cognito-User-Info']).toBe('[email protected]');
- expect(processedOptions.headers?.['X-Cognito-ID-Token']).toContain('eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9');
+ expect(processedOptions.headers?.['X-Cognito-ID-Token']).toContain(
+ 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9',
+ );
});
it('should handle AWS-specific MCP server configuration', () => {
@@ -364,9 +369,9 @@ describe('OpenID Connect Federated Provider Token Integration', () => {
command: 'node',
args: ['aws-mcp-server.js'],
env: {
- 'AWS_COGNITO_TOKEN': '{{LIBRECHAT_OPENID_ACCESS_TOKEN}}',
- 'AWS_COGNITO_ID_TOKEN': '{{LIBRECHAT_OPENID_ID_TOKEN}}',
- 'COGNITO_USER_SUB': '{{LIBRECHAT_OPENID_USER_ID}}',
+ AWS_COGNITO_TOKEN: '{{LIBRECHAT_OPENID_ACCESS_TOKEN}}',
+ AWS_COGNITO_ID_TOKEN: '{{LIBRECHAT_OPENID_ID_TOKEN}}',
+ COGNITO_USER_SUB: '{{LIBRECHAT_OPENID_USER_ID}}',
},
};
@@ -376,7 +381,9 @@ describe('OpenID Connect Federated Provider Token Integration', () => {
});
expect(processedOptions.env?.['AWS_COGNITO_TOKEN']).toBe('cognito-access-token-123');
- expect(processedOptions.env?.['AWS_COGNITO_ID_TOKEN']).toContain('eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9');
+ expect(processedOptions.env?.['AWS_COGNITO_ID_TOKEN']).toContain(
+ 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9',
+ );
expect(processedOptions.env?.['COGNITO_USER_SUB']).toBe('cognito-user-123');
});
});
@@ -384,7 +391,7 @@ describe('OpenID Connect Federated Provider Token Integration', () => {
describe('Security and Edge Cases', () => {
it('should not process OpenID Connect placeholders for expired tokens', () => {
const headers = {
- 'Authorization': 'Bearer {{LIBRECHAT_OPENID_TOKEN}}',
+ Authorization: 'Bearer {{LIBRECHAT_OPENID_TOKEN}}',
};
const resolvedHeaders = resolveHeaders({
@@ -405,7 +412,7 @@ describe('OpenID Connect Federated Provider Token Integration', () => {
};
const headers = {
- 'Authorization': 'Bearer {{LIBRECHAT_OPENID_TOKEN}}',
+ Authorization: 'Bearer {{LIBRECHAT_OPENID_TOKEN}}',
};
const resolvedHeaders = resolveHeaders({
@@ -418,7 +425,8 @@ describe('OpenID Connect Federated Provider Token Integration', () => {
});
it('should handle multiple placeholder instances in same string', () => {
- const template = '{{LIBRECHAT_OPENID_TOKEN}}-{{LIBRECHAT_OPENID_TOKEN}}-{{LIBRECHAT_OPENID_USER_ID}}';
+ const template =
+ '{{LIBRECHAT_OPENID_TOKEN}}-{{LIBRECHAT_OPENID_TOKEN}}-{{LIBRECHAT_OPENID_USER_ID}}';
const tokenInfo: OpenIDTokenInfo = {
accessToken: 'cognito-token123',
@@ -439,7 +447,7 @@ describe('OpenID Connect Federated Provider Token Integration', () => {
};
const headers = {
- 'Authorization': 'Bearer {{LIBRECHAT_OPENID_TOKEN}}',
+ Authorization: 'Bearer {{LIBRECHAT_OPENID_TOKEN}}',
};
const resolvedHeaders = resolveHeaders({
@@ -470,4 +478,4 @@ describe('OpenID Connect Federated Provider Token Integration', () => {
expect(tokenInfo?.accessToken).toBe('federated-priority-token');
});
});
-});
\ No newline at end of file
+});