const { Readable } = require('stream');
// Configurable file size limit for tests - use a getter so it can be changed per test
const fileSizeLimitConfig = { value: 20 * 1024 * 1024 }; // Default 20MB
// Mock librechat-data-provider with configurable file size limit
jest.mock('librechat-data-provider', () => {
const actual = jest.requireActual('librechat-data-provider');
return {
...actual,
mergeFileConfig: jest.fn((config) => {
const merged = actual.mergeFileConfig(config);
// Override the serverFileSizeLimit with our test value
return {
...merged,
get serverFileSizeLimit() {
return fileSizeLimitConfig.value;
},
};
}),
getEndpointFileConfig: jest.fn((options) => {
const config = actual.getEndpointFileConfig(options);
// Override fileSizeLimit with our test value
return {
...config,
get fileSizeLimit() {
return fileSizeLimitConfig.value;
},
};
}),
};
});
const { ErrorTypes, FileContext, ResourceType } = require('librechat-data-provider');
// Mock uuid
jest.mock('uuid', () => ({
v4: jest.fn(() => 'mock-uuid-1234'),
}));
// Mock axios — process.js now uses createAxiosInstance() from @librechat/api
const mockAxios = jest.fn();
mockAxios.post = jest.fn();
mockAxios.isAxiosError = jest.fn(() => false);
const mockClassifyCodeArtifact = jest.fn(() => 'other');
const mockExtractCodeArtifactRawText = jest.fn(() => null);
const mockExtractCodeArtifactInspectionText = jest.fn(async () => ({
text: null,
complete: false,
}));
const mockExtractCodeArtifactText = jest.fn(async () => null);
const mockExecuteWorkspaceTool = jest.fn();
const mockGetExtractedTextFormat = jest.fn((_name, _mime, text) => (text == null ? null : 'text'));
/* `hasOfficeHtmlPath` gates the persist-then-render split: when true, processCodeOutput
* returns `{ file, finalize }` with the file persisted at `status: 'pending'`
* and `finalize` runs the background extraction. Default false here so the
* legacy single-phase tests below (txt/png/etc) exercise the inline path
* unchanged. The dedicated office/finalize describe block toggles it on. */
const mockHasOfficeHtmlPath = jest.fn(() => false);
/* Stands in for the real chunk parser so a transport test can decide what
* one `/exec` response means without reaching into `packages/api`. */
const mockParseSandboxImageChunk = jest.fn((response) => response);
/* Pass-through `withTimeout`: tests don't drive timeouts here (those live
* in promise.spec.ts and the finalizePreview unit tests below). */
const passthroughWithTimeout = async (promise) => promise;
jest.mock('@librechat/api', () => {
return {
withFileProvisioning: jest.requireActual('@librechat/api').withFileProvisioning,
confirmFileProvision: jest.requireActual('@librechat/api').confirmFileProvision,
processCodeOutput: jest.requireActual('@librechat/api').processCodeOutput,
createSandboxTextReader: jest.requireActual('@librechat/api').createSandboxTextReader,
prepareCodeOutputBufferForInspection:
jest.requireActual('@librechat/api').prepareCodeOutputBufferForInspection,
getCodeFileContextLine: jest.requireActual('@librechat/api').getCodeFileContextLine,
appendCodeFileContextLine: jest.requireActual('@librechat/api').appendCodeFileContextLine,
createCodeReuploadFailures: jest.requireActual('@librechat/api').createCodeReuploadFailures,
openCodeFileSource: jest.requireActual('@librechat/api').openCodeFileSource,
resolveDownloadPath: (file) => file.storageKey || file.filepath,
logAxiosError: jest.fn(),
/* Behaviourally identical to the real predicate in
* `packages/api/src/files/code/errors.ts`, which owns the contract and
* its own spec. Inlined because this factory replaces the whole module
* and `requireActual` here would load the entire package. */
isMissingSandboxPathError: (reason) =>
/no such file or directory|cannot access|cannot find the path|enoent/i.test(reason),
getBasePath: jest.fn(() => ''),
sanitizeArtifactPath: jest.fn((name) => name),
flattenArtifactPath: jest.fn((name) => name.replace(/\//g, '__')),
createAxiosInstance: jest.fn(() => mockAxios),
normalizeArtifactDeliveryFailure: (value) =>
value?.code === 'artifact_delivery_failed'
? {
code: value.code,
status: value.status,
attempted: value.attempted,
delivered: value.delivered,
failed: value.failed,
}
: undefined,
executeWorkspaceTool: (...args) => mockExecuteWorkspaceTool(...args),
getCodeApiAuthHeaders: jest.fn(async () => ({})),
isAbortError: (error) =>
error?.name === 'AbortError' || error?.code === 'ABORT_ERR' || error?.code === 'ERR_CANCELED',
/* Windowing, sizing and rate-limit policy are real code in
* `packages/api` with their own tests (`files/code/image.spec.ts`,
* `utils/code.spec.ts`). These stand-ins are deliberately inert
* passthroughs — they assert nothing about that behavior, so the
* transport tests below cover only what this file still owns. */
createCodeApiRateLimitBudget: jest.fn(() => ({
limitMs: 20_000,
waitedMs: 0,
activeWaitEnds: new Set(),
})),
getCodeApiUploadOptions: jest.fn(() => ({
scope: 'default:user-123',
concurrency: 3,
retryWaitMs: 20_000,
})),
withCodeApiRateLimit: jest.fn(async ({ attempt }) => {
try {
return await attempt();
} catch (error) {
if (error?.response?.status !== 429) {
throw error;
}
return attempt();
}
}),
withCodeApiUploadRecovery: jest.fn(async ({ openSource, upload }) => {
try {
return await upload(await openSource());
} catch (error) {
if (error?.response?.status !== 429) {
throw error;
}
return upload(await openSource());
}
}),
buildSandboxImageReaderCode: jest.fn(
({ filePath, limit, offset, chunkBytes }) =>
`read ${filePath} ${limit} ${offset} ${chunkBytes}`,
),
parseSandboxImageChunk: jest.fn((response) => mockParseSandboxImageChunk(response)),
readWindowedSandboxImage: jest.fn(({ readChunk }) => readChunk({ code: 'read-one-window' })),
getCodeExecutionBaseUrl: jest.fn((profile) =>
profile === 'stateful' ? 'https://code-stateful.example.com' : 'https://code-api.example.com',
),
CODE_API_EXPECTED_PROFILE_HEADER: 'X-CodeAPI-Expected-Profile',
codeExecutionHeaders: ({ executionProfile, bridgeWorkerId }) => ({
'X-CodeAPI-Expected-Profile': executionProfile,
...(bridgeWorkerId ? { 'X-LibreChat-Code-Worker-ID': bridgeWorkerId } : {}),
}),
withTimeout: (...args) => passthroughWithTimeout(...args),
hasOfficeHtmlPath: (...args) => mockHasOfficeHtmlPath(...args),
/**
* Arrow-function indirection (vs. a direct `jest.fn()` reference) so
* tests can per-case `mockReturnValueOnce` / `mockImplementationOnce`
* on `mockClassifyCodeArtifact` / `mockExtractCodeArtifactText`.
* `jest.mock(...)` is hoisted above the outer `const` declarations
* at parse time, so a direct reference here would capture
* `undefined`; the arrow defers the binding to call time. The
* direct-`jest.fn()` mocks below stay constant per file.
*/
classifyCodeArtifact: (...args) => mockClassifyCodeArtifact(...args),
extractCodeArtifactRawText: (...args) => mockExtractCodeArtifactRawText(...args),
extractCodeArtifactInspectionText: (...args) => mockExtractCodeArtifactInspectionText(...args),
extractCodeArtifactText: (...args) => mockExtractCodeArtifactText(...args),
getBoundedCodeOutputByteLimit: (configured) =>
typeof configured === 'number' && Number.isFinite(configured) && configured > 0
? Math.min(configured, 64 * 1024 * 1024)
: 64 * 1024 * 1024,
CODE_OUTPUT_PREFLIGHT_MAX_BYTES: 64 * 1024 * 1024,
CODE_OUTPUT_PREFLIGHT_MAX_COUNT: 10,
/* `processCodeOutput` derives the `textFormat` trust flag for
* `IMongoFile` from this helper — Codex P1 review on PR #12934.
* The mock returns 'text' for non-null extractor output and null
* otherwise so the downstream `file.textFormat` field is set to
* a believable shape without modeling the office-HTML branch
* (the dispatcher under test isn't exercising that path). Per-
* test overrides via `mockGetExtractedTextFormat.mockReturnValue`
* if a case needs to assert the 'html' value. */
getExtractedTextFormat: (...args) => mockGetExtractedTextFormat(...args),
getStorageMetadata: jest.fn(() => ({})),
/* Identity helpers mirror codeapi's validator. The real impl
* lives in `packages/api/src/files/code/identity.ts` with its
* own dedicated `identity.spec.ts`; here we just stub the
* download-query builder since `processCodeOutput` calls it on
* every output download. */
buildCodeEnvDownloadQuery: jest.fn(({ kind, id, version }) => {
const params = new URLSearchParams({ kind, id });
if (version != null) params.set('version', String(version));
return `?${params.toString()}`;
}),
codeServerHttpAgent: jest.requireActual('@librechat/api').codeServerHttpAgent,
codeServerHttpsAgent: jest.requireActual('@librechat/api').codeServerHttpsAgent,
selectCodeFiles: jest.requireActual('@librechat/api').selectCodeFiles,
getCodeFileInfo: jest.requireActual('@librechat/api').getCodeFileInfo,
getUploadedCodeEnvFilename: jest.requireActual('@librechat/api').getUploadedCodeEnvFilename,
checkCodeFileActive: jest.requireActual('@librechat/api').checkCodeFileActive,
};
});
jest.mock('@librechat/data-schemas', () => ({
logger: {
warn: jest.fn(),
debug: jest.fn(),
error: jest.fn(),
},
}));
jest.mock('@librechat/agents', () => ({
...jest.requireActual('@librechat/agents'),
getCodeBaseURL: jest.fn(() => 'https://code-api.example.com'),
}));
// Mock models
const mockClaimCodeFile = jest.fn();
const mockCommitCodeFile = jest.fn();
const mockUpdateFile = jest.fn();
const mockAcquireFileProvision = jest.fn(async () => true);
const mockReleaseFileProvision = jest.fn(async () => true);
const mockCommitFileProvision = jest.fn();
let mockProvisionRecovery;
jest.mock('~/server/services/Files/operations', () => ({
getFileStorage: () => ({
recovery: mockProvisionRecovery,
acquireFileProvision: (...args) => mockAcquireFileProvision(...args),
releaseFileProvision: (...args) => mockReleaseFileProvision(...args),
commitFileProvision: (...args) => mockCommitFileProvision(...args),
}),
}));
jest.mock('~/models', () => ({
createFile: jest.fn().mockResolvedValue({}),
getFiles: jest.fn(),
updateFile: mockUpdateFile,
acquireFileProvision: (...args) => mockAcquireFileProvision(...args),
releaseFileProvision: (...args) => mockReleaseFileProvision(...args),
commitFileProvision: (...args) => mockCommitFileProvision(...args),
claimCodeFile: (...args) => mockClaimCodeFile(...args),
commitCodeFile: mockCommitCodeFile,
}));
// Mock permissions (must be before process.js import)
jest.mock('~/server/services/Files/permissions', () => ({
filterFilesByAgentAccess: jest.fn((options) => Promise.resolve(options.files)),
}));
// Mock strategy functions
jest.mock('~/server/services/Files/strategies', () => ({
getStrategyFunctions: jest.fn(),
}));
// Mock convertImage
jest.mock('~/server/services/Files/images/convert', () => ({
convertImage: jest.fn(),
}));
jest.mock('~/server/services/Files/retention', () => ({
getRetentionExpiry: jest.fn(() => ({})),
}));
// Mock determineFileType
jest.mock('~/server/utils', () => ({
determineFileType: jest.fn(),
}));
const http = require('http');
const https = require('https');
const { createFile, getFiles } = require('~/models');
const { getRetentionExpiry } = require('~/server/services/Files/retention');
const { getStrategyFunctions } = require('~/server/services/Files/strategies');
const { convertImage } = require('~/server/services/Files/images/convert');
const { determineFileType } = require('~/server/utils');
const { logger } = require('@librechat/data-schemas');
const {
codeServerHttpAgent,
codeServerHttpsAgent,
getCodeApiAuthHeaders,
getStorageMetadata,
} = require('@librechat/api');
const {
processCodeOutput,
prepareCodeOutputForInspection,
getSessionInfo,
readSandboxFile,
readWorkspaceFile,
searchWorkspace,
listWorkspaceFiles,
writeWorkspaceFile,
previewWorkspaceEdit,
editWorkspaceFile,
readSandboxImage,
writeSandboxFile,
primeFiles,
} = require('./process');
describe('Code Process', () => {
const mockReq = {
user: { id: 'user-123' },
config: {
fileConfig: {},
fileStrategy: 'local',
imageOutputType: 'webp',
},
};
const baseParams = {
req: mockReq,
id: 'file-id-123',
name: 'test-file.txt',
apiKey: 'test-api-key',
toolCallId: 'tool-call-123',
conversationId: 'conv-123',
messageId: 'msg-123',
session_id: 'session-123',
};
beforeEach(() => {
jest.clearAllMocks();
mockProvisionRecovery = jest.requireActual('@librechat/api').createFileProvisionRecovery();
mockAcquireFileProvision.mockReset().mockResolvedValue(true);
mockReleaseFileProvision.mockReset().mockResolvedValue(true);
mockCommitFileProvision
.mockReset()
.mockImplementation(async ({ claim, code, output, releaseOnly }) => {
if (releaseOnly) return true;
if (output) return mockCommitCodeFile(output.file, output.sourceDispatchedAt);
const result = await mockUpdateFile({
file_id: claim.file_id,
'metadata.codeEnvRef': code.legacyRef ?? code.ref,
[`metadata.codeEnvRefs.${code.routeKey}`]: code.ref,
});
return result !== null && result !== false;
});
fileSizeLimitConfig.value = 20 * 1024 * 1024;
// Default mock: atomic claim returns a new file record (no existing file)
mockClaimCodeFile.mockResolvedValue({
file_id: 'mock-uuid-1234',
user: 'user-123',
});
getFiles.mockResolvedValue(null);
createFile.mockResolvedValue({});
mockCommitCodeFile.mockReset();
mockCommitCodeFile.mockResolvedValue(true);
getStrategyFunctions.mockReturnValue({
saveBuffer: jest.fn().mockResolvedValue('/uploads/mock-file-path.txt'),
});
determineFileType.mockResolvedValue({ mime: 'text/plain' });
});
describe('code output inspection preflight', () => {
it('derives file content from downloaded bytes without persisting anything', async () => {
const buffer = Buffer.from('safe raw content');
mockAxios.mockResolvedValue({ data: buffer });
mockClassifyCodeArtifact.mockReturnValueOnce('utf8-text');
mockExtractCodeArtifactRawText.mockReturnValueOnce('safe raw content');
mockExtractCodeArtifactInspectionText.mockResolvedValueOnce({
text: 'safe extracted content',
complete: true,
});
const prepared = await prepareCodeOutputForInspection(baseParams);
expect(prepared).toEqual({
buffer,
extractedTextComplete: true,
file: {
name: 'test-file.txt',
filename: 'test-file.txt',
type: 'text/plain',
content: 'safe raw content',
extractedText: 'safe extracted content',
},
});
expect(mockClaimCodeFile).not.toHaveBeenCalled();
expect(mockCommitCodeFile).not.toHaveBeenCalled();
expect(getStrategyFunctions).not.toHaveBeenCalled();
});
it('persists the exact preflight buffer without downloading it again', async () => {
const preparedBuffer = Buffer.from('already inspected');
await processCodeOutput({ ...baseParams, preparedBuffer });
expect(mockAxios).not.toHaveBeenCalled();
expect(mockClaimCodeFile).toHaveBeenCalledTimes(1);
expect(mockCommitCodeFile).toHaveBeenCalledTimes(1);
});
it('does not overwrite a reused output when its storage claim is denied', async () => {
mockClaimCodeFile.mockResolvedValue({ file_id: 'existing-output', user: 'user-123' });
mockAcquireFileProvision.mockResolvedValueOnce(false);
const saveBuffer = jest.fn();
getStrategyFunctions.mockReturnValue({ saveBuffer });
await processCodeOutput({ ...baseParams, preparedBuffer: Buffer.from('new output') });
expect(saveBuffer).not.toHaveBeenCalled();
expect(mockCommitCodeFile).not.toHaveBeenCalled();
expect(mockReleaseFileProvision).not.toHaveBeenCalled();
});
it('holds regenerated output storage through primary write and full record commit', async () => {
mockClaimCodeFile.mockResolvedValue({
file_id: 'existing-output',
user: 'user-123',
messageId: 'original-message',
});
let finishWrite;
const writing = new Promise((resolve) => {
finishWrite = resolve;
});
const saveBuffer = jest.fn(async () => {
expect(mockAcquireFileProvision).toHaveBeenCalledTimes(1);
await writing;
return '/uploads/existing-output.txt';
});
getStrategyFunctions.mockReturnValue({ saveBuffer });
const pending = processCodeOutput({
...baseParams,
preparedBuffer: Buffer.from('new output'),
});
await new Promise((resolve) => setImmediate(resolve));
expect(saveBuffer).toHaveBeenCalledTimes(1);
expect(mockReleaseFileProvision).not.toHaveBeenCalled();
finishWrite();
const result = await pending;
expect(result.file.file_id).toBe('existing-output');
expect(result.file.messageId).toBe(baseParams.messageId);
expect(mockCommitCodeFile).toHaveBeenCalledWith(
expect.objectContaining({ messageId: baseParams.messageId }),
undefined,
);
expect(mockCommitFileProvision).toHaveBeenCalledWith(
expect.objectContaining({
output: expect.objectContaining({
file: expect.objectContaining({ file_id: 'existing-output' }),
}),
}),
);
expect(mockReleaseFileProvision).toHaveBeenCalledWith(
mockAcquireFileProvision.mock.calls[0][0],
);
});
it('enforces a caller-provided aggregate inspection budget while downloading', async () => {
mockAxios.mockResolvedValue({ data: Buffer.from('too large') });
await expect(
prepareCodeOutputForInspection({
...baseParams,
maxBytes: 4,
}),
).rejects.toThrow('Generated file exceeds the 4-byte transport limit');
expect(mockAxios).toHaveBeenCalledWith(
expect.objectContaining({
maxContentLength: 4,
maxBodyLength: 4,
}),
);
expect(mockClaimCodeFile).not.toHaveBeenCalled();
expect(mockCommitCodeFile).not.toHaveBeenCalled();
});
it('extracts text bytes even when the generated filename spoofs an image extension', async () => {
const buffer = Buffer.from('PRIVATE-SECRET');
mockAxios.mockResolvedValue({ data: buffer });
determineFileType.mockResolvedValueOnce(undefined);
mockClassifyCodeArtifact.mockReturnValueOnce('utf8-text');
mockExtractCodeArtifactRawText.mockReturnValueOnce('PRIVATE-SECRET');
mockExtractCodeArtifactInspectionText.mockResolvedValueOnce({
text: 'PRIVATE-SECRET',
complete: true,
});
const prepared = await prepareCodeOutputForInspection({
...baseParams,
name: 'secret.png',
});
expect(mockExtractCodeArtifactRawText).toHaveBeenCalledWith(buffer, 'utf8-text');
expect(prepared.file).toMatchObject({
name: 'secret.png',
type: 'text/plain',
content: 'PRIVATE-SECRET',
extractedText: 'PRIVATE-SECRET',
});
});
it('returns the explicit bounded fallback without a second download or persistence', async () => {
const result = await processCodeOutput({
...baseParams,
downloadFallback: true,
});
expect(result.file).toMatchObject({
filename: 'test-file.txt',
filepath: '/api/files/code/download/session-123/file-id-123',
});
expect(mockAxios).not.toHaveBeenCalled();
expect(mockClaimCodeFile).not.toHaveBeenCalled();
expect(mockCommitCodeFile).not.toHaveBeenCalled();
});
});
describe('published run artifacts', () => {
const scope = {
userId: 'user-123',
conversationId: 'conv-123',
runId: 'parent-run',
executionId: 'child-run',
agentId: 'child-agent',
sourceFileId: 'file-id-123',
};
const provenance = {
runId: scope.runId,
executionId: scope.executionId,
agentId: scope.agentId,
sourceFileId: scope.sourceFileId,
parentExecutionId: 'parent-execution',
publishedAt: '2026-09-11T16:00:00.000Z',
inputFileIds: ['input-pdf'],
};
it('stores the existing output pipeline result through the publication boundary', async () => {
const publish = jest.fn(async ({ file }) => ({
...file,
file_id: 'published-id',
user: scope.userId,
conversationId: scope.conversationId,
context: FileContext.run_artifact,
metadata: { ...file.metadata, runFile: provenance },
}));
const discard = jest.fn();
const result = await processCodeOutput({
...baseParams,
preparedBuffer: Buffer.from('report data'),
publication: { scope, provenance, publish, find: jest.fn(), discard },
});
expect(result.file).toMatchObject({
file_id: 'published-id',
filename: baseParams.name,
context: FileContext.run_artifact,
metadata: { runFile: provenance },
});
expect(publish).toHaveBeenCalledWith(expect.objectContaining({ scope, provenance }));
expect(mockClaimCodeFile).not.toHaveBeenCalled();
expect(mockCommitCodeFile).not.toHaveBeenCalled();
expect(discard).not.toHaveBeenCalled();
});
it('finalizes office previews against the canonical published file identity', async () => {
mockHasOfficeHtmlPath.mockReturnValueOnce(true);
const publish = jest.fn(async ({ file }) => ({
...file,
file_id: 'published-office-id',
user: scope.userId,
conversationId: scope.conversationId,
context: FileContext.run_artifact,
metadata: { ...file.metadata, runFile: provenance },
}));
const result = await processCodeOutput({
...baseParams,
name: 'report.csv',
preparedBuffer: Buffer.from('a,b\n1,2'),
publication: { scope, provenance, publish, find: jest.fn(), discard: jest.fn() },
});
expect(result.file.file_id).toBe('published-office-id');
expect(result.file.status).toBe('pending');
await result.finalize();
expect(require('~/models').updateFile).toHaveBeenCalledWith(
expect.objectContaining({ file_id: 'published-office-id' }),
{ previewRevision: result.previewRevision },
);
});
it('cleans a stored publication attempt when classification fails before metadata commit', async () => {
const { createRunArtifactPublisher } = jest.requireActual('@librechat/api');
const discard = jest.fn(async () => undefined);
const publishRunArtifactFile = jest.fn();
mockClassifyCodeArtifact.mockImplementationOnce(() => {
throw new Error('Classification failed after storage');
});
const publish = createRunArtifactPublisher({
claimRunArtifactFile: async () => ({ file_id: 'published-id' }),
publishRunArtifactFile,
findRunArtifactFile: async () => null,
processCodeOutput: (input) => processCodeOutput({ ...input, req: mockReq }),
prepare: async () => Buffer.from('report data'),
discard,
finalize: jest.fn(),
});
await expect(
publish({
scope,
provenance,
artifact: { id: baseParams.id, name: baseParams.name, sessionId: baseParams.session_id },
}),
).rejects.toThrow('durable storage');
expect(publishRunArtifactFile).not.toHaveBeenCalled();
expect(discard).toHaveBeenCalledWith(
expect.objectContaining({
file_id: 'mock-uuid-1234',
filepath: '/uploads/mock-file-path.txt',
metadata: undefined,
}),
);
expect(discard).toHaveBeenCalledTimes(1);
});
it('cleans a generated image cancelled after conversion without publishing it', async () => {
const { createRunArtifactPublisher } = jest.requireActual('@librechat/api');
const controller = new AbortController();
const discard = jest.fn(async () => undefined);
const publishRunArtifactFile = jest.fn();
convertImage.mockImplementationOnce(async () => {
controller.abort(new Error('Publication generation expired'));
return { filepath: '/uploads/generated.webp', bytes: 12, width: 2, height: 2 };
});
const publish = createRunArtifactPublisher({
claimRunArtifactFile: async () => ({ file_id: 'published-id' }),
publishRunArtifactFile,
findRunArtifactFile: async () => null,
processCodeOutput: (input) => processCodeOutput({ ...input, req: mockReq }),
prepare: async () => Buffer.from('image data'),
discard,
finalize: jest.fn(),
});
await expect(
publish({
scope,
provenance,
artifact: { id: baseParams.id, name: 'generated.png', sessionId: baseParams.session_id },
signal: controller.signal,
}),
).rejects.toThrow('generation expired');
expect(publishRunArtifactFile).not.toHaveBeenCalled();
expect(discard).toHaveBeenCalledWith(
expect.objectContaining({
filepath: '/uploads/generated.webp',
file_id: 'mock-uuid-1234',
metadata: undefined,
}),
);
expect(discard).toHaveBeenCalledTimes(1);
});
});
describe('snapshot reservation', () => {
it('reserves a fresh capture rather than claiming the mutable filename slot', async () => {
mockAxios.mockResolvedValue({ data: Buffer.alloc(100) });
const { file } = await processCodeOutput(baseParams);
expect(mockClaimCodeFile).toHaveBeenCalledWith(
expect.objectContaining({
filename: 'test-file.txt',
conversationId: 'conv-123',
file_id: 'mock-uuid-1234',
user: 'user-123',
snapshot: true,
}),
);
expect(file.usage).toBe(1);
expect(getRetentionExpiry).toHaveBeenCalledWith(baseParams.req);
});
it('keeps an older background capture instead of discarding its history', async () => {
mockAxios.mockResolvedValue({ data: Buffer.alloc(100) });
const { file } = await processCodeOutput({ ...baseParams, freshClaimAfter: 100 });
expect(file.metadata.sourceDispatchedAt).toBe(100);
expect(mockCommitCodeFile).toHaveBeenCalledWith(
expect.objectContaining({ file_id: file.file_id }),
100,
);
});
it('omits output when the storage commit is not confirmed', async () => {
mockCommitCodeFile.mockResolvedValue(false);
mockAxios.mockResolvedValue({ data: Buffer.alloc(100) });
expect(await processCodeOutput({ ...baseParams, freshClaimAfter: 100 })).toBeNull();
});
});
describe('processCodeOutput', () => {
it('forwards Code API auth headers when downloading generated output', async () => {
getCodeApiAuthHeaders.mockResolvedValueOnce({ Authorization: 'Bearer codeapi-token' });
mockAxios.mockResolvedValue({ data: Buffer.alloc(100) });
await processCodeOutput(baseParams);
expect(getCodeApiAuthHeaders).toHaveBeenCalledWith(mockReq, undefined);
expect(mockAxios).toHaveBeenCalledWith(
expect.objectContaining({
method: 'get',
headers: expect.objectContaining({
Authorization: 'Bearer codeapi-token',
'User-Agent': 'LibreChat/1.0',
}),
}),
);
});
describe('image file processing', () => {
it('should process image files using convertImage', async () => {
const imageParams = { ...baseParams, name: 'chart.png' };
const imageBuffer = Buffer.alloc(500);
mockAxios.mockResolvedValue({ data: imageBuffer });
const convertedFile = {
filepath: '/uploads/converted-image.webp',
bytes: 400,
};
convertImage.mockResolvedValue(convertedFile);
const { file: result } = await processCodeOutput(imageParams);
expect(convertImage).toHaveBeenCalledWith(
mockReq,
imageBuffer,
'high',
'mock-uuid-1234.png',
);
expect(result.type).toBe('image/webp');
expect(result.context).toBe(FileContext.execute_code_snapshot);
expect(result.filename).toBe('chart.png');
});
it('persists tenantId on image code output records when present', async () => {
const tenantReq = { ...mockReq, user: { ...mockReq.user, tenantId: 'tenantA' } };
const imageBuffer = Buffer.alloc(500);
mockAxios.mockResolvedValue({ data: imageBuffer });
convertImage.mockResolvedValue({
filepath: '/t/tenantA/images/user-123/mock-uuid-1234.webp',
});
await processCodeOutput({
...baseParams,
req: tenantReq,
name: 'chart.png',
});
expect(mockClaimCodeFile).toHaveBeenCalledWith(
expect.objectContaining({ tenantId: 'tenantA' }),
);
expect(mockCommitCodeFile).toHaveBeenCalledWith(
expect.objectContaining({ tenantId: 'tenantA' }),
undefined,
);
});
it('uses the snapshot object URL without mutable cache busting', async () => {
mockAxios.mockResolvedValue({ data: Buffer.alloc(500) });
convertImage.mockResolvedValue({ filepath: '/images/user-123/mock-uuid-1234.webp' });
const { file } = await processCodeOutput({ ...baseParams, name: 'chart.png' });
expect(file.filepath).toBe('/images/user-123/mock-uuid-1234.webp');
expect(file.usage).toBe(1);
});
});
describe('non-image file processing', () => {
it('should process non-image files using saveBuffer', async () => {
const smallBuffer = Buffer.alloc(100);
mockAxios.mockResolvedValue({ data: smallBuffer });
const mockSaveBuffer = jest.fn().mockResolvedValue('/uploads/saved-file.txt');
getStrategyFunctions.mockReturnValue({ saveBuffer: mockSaveBuffer });
determineFileType.mockResolvedValue({ mime: 'text/plain' });
const { file: result } = await processCodeOutput(baseParams);
expect(mockSaveBuffer).toHaveBeenCalledWith({
userId: 'user-123',
buffer: smallBuffer,
fileName: 'mock-uuid-1234__test-file.txt',
basePath: 'uploads',
});
expect(result.type).toBe('text/plain');
expect(result.filepath).toBe('/uploads/saved-file.txt');
expect(result.bytes).toBe(100);
});
it.each([
[
'slides.pptx',
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
],
['sheet.xlsx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'],
[
'document.docx',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
],
])('preserves stored metadata for code-generated office file %s', async (name, mime) => {
const cloudfrontReq = {
...mockReq,
user: { ...mockReq.user, tenantId: 'tenantA' },
config: { ...mockReq.config, fileStrategy: 'cloudfront' },
};
const smallBuffer = Buffer.alloc(100);
const filepath = `https://cdn.example.com/r/us-east-2/t/tenantA/uploads/user-123/mock-uuid-1234__${name}`;
const storageKey = `r/us-east-2/t/tenantA/uploads/user-123/mock-uuid-1234__${name}`;
mockAxios.mockResolvedValue({ data: smallBuffer });
determineFileType.mockResolvedValue({ mime });
mockHasOfficeHtmlPath.mockReturnValueOnce(true);
getStorageMetadata.mockReturnValueOnce({ storageKey, storageRegion: 'us-east-2' });
const mockSaveBuffer = jest.fn().mockResolvedValue(filepath);
getStrategyFunctions.mockReturnValue({ saveBuffer: mockSaveBuffer });
const { file: result, finalize } = await processCodeOutput({
...baseParams,
req: cloudfrontReq,
name,
});
expect(mockSaveBuffer).toHaveBeenCalledWith(
expect.objectContaining({
userId: 'user-123',
basePath: 'uploads',
tenantId: 'tenantA',
}),
);
expect(result).toMatchObject({
file_id: 'mock-uuid-1234',
user: 'user-123',
tenantId: 'tenantA',
source: 'cloudfront',
filename: name,
filepath,
storageKey,
storageRegion: 'us-east-2',
status: 'pending',
});
expect(mockCommitCodeFile).toHaveBeenCalledWith(
expect.objectContaining({
file_id: 'mock-uuid-1234',
user: 'user-123',
tenantId: 'tenantA',
source: 'cloudfront',
storageKey,
storageRegion: 'us-east-2',
}),
undefined,
);
expect(typeof finalize).toBe('function');
});
it('passes and persists tenantId for non-image code output records', async () => {
const tenantReq = { ...mockReq, user: { ...mockReq.user, tenantId: 'tenantA' } };
const smallBuffer = Buffer.alloc(100);
mockAxios.mockResolvedValue({ data: smallBuffer });
const mockSaveBuffer = jest
.fn()
.mockResolvedValue('/t/tenantA/uploads/user-123/mock-file-path.txt');
getStrategyFunctions.mockReturnValue({ saveBuffer: mockSaveBuffer });
await processCodeOutput({
...baseParams,
req: tenantReq,
});
expect(mockClaimCodeFile).toHaveBeenCalledWith(
expect.objectContaining({ tenantId: 'tenantA' }),
);
expect(mockSaveBuffer).toHaveBeenCalledWith(
expect.objectContaining({ tenantId: 'tenantA' }),
);
expect(mockCommitCodeFile).toHaveBeenCalledWith(
expect.objectContaining({ tenantId: 'tenantA' }),
undefined,
);
});
it('preserves nested directory paths in the DB record while flattening the storage key', async () => {
/* Regression test for the silent-data-loss path: when codeapi reports a
* file with a nested name like "test_folder/test_file.txt", LibreChat
* used to feed it through `sanitizeFilename` (basename-only), which
* persisted "test_file.txt" to the DB and made the file un-locatable on
* the next prime() (cat /mnt/data/test_folder/test_file.txt would
* 404). The fix: keep the path on the DB record (so primeFiles can
* place it back at the same nested location), but flatten it for the
* storage key (saveBuffer strategies key by single component). */
const smallBuffer = Buffer.alloc(100);
mockAxios.mockResolvedValue({ data: smallBuffer });
const mockSaveBuffer = jest.fn().mockResolvedValue('/uploads/saved.txt');
getStrategyFunctions.mockReturnValue({ saveBuffer: mockSaveBuffer });
const { file: result } = await processCodeOutput({
...baseParams,
name: 'test_folder/test_file.txt',
});
// Storage key flattens `/` to `__` so on-disk strategies don't
// accidentally create real subdirectories under uploads/.
expect(mockSaveBuffer).toHaveBeenCalledWith(
expect.objectContaining({
fileName: 'mock-uuid-1234__test_folder__test_file.txt',
}),
);
// DB row keeps the nested path verbatim — that's what primeFiles
// ships back to the sandbox on the next turn.
expect(result.filename).toBe('test_folder/test_file.txt');
// Claim is also keyed by the path-preserving name so the
// (filename, conversationId) compound key stays consistent.
expect(mockClaimCodeFile).toHaveBeenCalledWith(
expect.objectContaining({ filename: 'test_folder/test_file.txt' }),
);
});
it('passes a NAME_MAX-aware budget to flattenArtifactPath when composing the storage key', async () => {
/* Codex review P1: per-segment caps on the path-preserving form
* aren't enough — once the segments are joined with `__` for the
* storage key, deeply-nested or moderately long paths can still
* exceed filesystem NAME_MAX (255) and cause `ENAMETOOLONG` in
* saveBuffer. processCodeOutput must pass a file_id-aware budget
* to flattenArtifactPath so the cap holds end-to-end. The unit
* tests in `packages/api/src/utils/files.spec.ts` cover the
* truncation logic itself; this test covers the integration. */
const smallBuffer = Buffer.alloc(100);
mockAxios.mockResolvedValue({ data: smallBuffer });
const mockSaveBuffer = jest.fn().mockResolvedValue('/uploads/saved.bin');
getStrategyFunctions.mockReturnValue({ saveBuffer: mockSaveBuffer });
const flattenSpy = require('@librechat/api').flattenArtifactPath;
flattenSpy.mockClear();
await processCodeOutput({ ...baseParams, name: 'a/b/c.csv' });
// The handler should call flattenArtifactPath with both the
// safeName AND a budget = NAME_MAX (255) minus the prefix
// (`${file_id}__`). file_id mock is `mock-uuid-1234` (14 chars),
// so the budget should be 255 - 14 - 2 = 239.
expect(flattenSpy).toHaveBeenCalledWith(expect.any(String), 239);
});
it('passes the basename (not the full nested path) to classifyCodeArtifact and extractCodeArtifactText', async () => {
/* Codex review P2: with the path-preserving sanitizer, `safeName`
* can be a nested string like `reports.v1/Makefile`. The
* classifier reads `extensionOf` against the full string, which
* sees `.v1/Makefile` after the dotted-dir's first dot and
* misclassifies the file as `other` (so text extraction is
* skipped). Pass `path.basename(safeName)` instead. */
const smallBuffer = Buffer.alloc(100);
mockAxios.mockResolvedValue({ data: smallBuffer });
const mockSaveBuffer = jest.fn().mockResolvedValue('/uploads/saved.txt');
getStrategyFunctions.mockReturnValue({ saveBuffer: mockSaveBuffer });
await processCodeOutput({
...baseParams,
name: 'reports.v1/Makefile',
});
expect(mockClassifyCodeArtifact).toHaveBeenCalledWith('Makefile', expect.any(String));
expect(mockExtractCodeArtifactText).toHaveBeenCalledWith(
expect.any(Buffer),
'Makefile',
expect.any(String),
expect.any(String),
);
});
it('should detect MIME type from buffer', async () => {
const smallBuffer = Buffer.alloc(100);
mockAxios.mockResolvedValue({ data: smallBuffer });
determineFileType.mockResolvedValue({ mime: 'application/pdf' });
const { file: result } = await processCodeOutput({ ...baseParams, name: 'document.pdf' });
expect(determineFileType).toHaveBeenCalledWith(smallBuffer, true);
expect(result.type).toBe('application/pdf');
});
it('should fallback to application/octet-stream for unknown types', async () => {
const smallBuffer = Buffer.alloc(100);
mockAxios.mockResolvedValue({ data: smallBuffer });
determineFileType.mockResolvedValue(null);
const { file: result } = await processCodeOutput({ ...baseParams, name: 'unknown.xyz' });
expect(result.type).toBe('application/octet-stream');
});
});
describe('inline text extraction', () => {
it('should populate text on the file when extractor returns content', async () => {
const buffer = Buffer.from('hello world\n', 'utf-8');
mockAxios.mockResolvedValue({ data: buffer });
determineFileType.mockResolvedValue({ mime: 'text/plain' });
mockClassifyCodeArtifact.mockReturnValueOnce('utf8-text');
mockExtractCodeArtifactText.mockResolvedValueOnce('hello world\n');
const { file: result } = await processCodeOutput({ ...baseParams, name: 'note.txt' });
expect(mockClassifyCodeArtifact).toHaveBeenCalledWith('note.txt', 'text/plain');
expect(mockExtractCodeArtifactText).toHaveBeenCalledWith(
buffer,
'note.txt',
'text/plain',
'utf8-text',
);
expect(result.text).toBe('hello world\n');
expect(mockCommitCodeFile).toHaveBeenCalledWith(
expect.objectContaining({ text: 'hello world\n' }),
undefined,
);
});
it('should set text to null when extractor returns null so updates clear stale values', async () => {
const buffer = Buffer.alloc(100);
mockAxios.mockResolvedValue({ data: buffer });
determineFileType.mockResolvedValue({ mime: 'application/octet-stream' });
mockClassifyCodeArtifact.mockReturnValueOnce('other');
mockExtractCodeArtifactText.mockResolvedValueOnce(null);
const { file: result } = await processCodeOutput({ ...baseParams, name: 'archive.zip' });
expect(result.text).toBeNull();
const createCall = mockCommitCodeFile.mock.calls[0][0];
expect(createCall.text).toBeNull();
});
it('should overwrite a previously-stored text value when re-emitting a now-binary file', async () => {
// Same filename + conversationId already has a stored text value;
// claimCodeFile returns the existing record (isUpdate path).
mockClaimCodeFile.mockResolvedValueOnce({
file_id: 'existing-id',
filename: 'output.bin',
usage: 1,
createdAt: '2024-01-01T00:00:00.000Z',
});
const binaryBuffer = Buffer.from([0x00, 0xff, 0x00, 0xff]);
mockAxios.mockResolvedValue({ data: binaryBuffer });
determineFileType.mockResolvedValue({ mime: 'application/octet-stream' });
mockClassifyCodeArtifact.mockReturnValueOnce('other');
mockExtractCodeArtifactText.mockResolvedValueOnce(null);
await processCodeOutput({ ...baseParams, name: 'output.bin' });
// null (not omitted) so $set clears any prior `text` value.
const createCall = mockCommitCodeFile.mock.calls[0][0];
expect(createCall).toHaveProperty('text', null);
});
it('should not invoke text extraction for image files', async () => {
const imageBuffer = Buffer.alloc(500);
mockAxios.mockResolvedValue({ data: imageBuffer });
convertImage.mockResolvedValue({ filepath: '/uploads/x.webp', bytes: 400 });
await processCodeOutput({ ...baseParams, name: 'chart.png' });
expect(mockClassifyCodeArtifact).not.toHaveBeenCalled();
expect(mockExtractCodeArtifactText).not.toHaveBeenCalled();
});
it('clears deferred-preview lifecycle fields so a prior office record at this file_id stops looking pending', async () => {
/* Codex P2: same (filename, conversationId) was previously an
* office artifact, leaving status/previewError/previewRevision
* populated. The non-office update must reset them or the
* client renders the wrong state for the now non-office file. */
mockClaimCodeFile.mockResolvedValueOnce({
file_id: 'reused-id',
filename: 'output.txt',
usage: 1,
createdAt: '2024-01-01T00:00:00.000Z',
});
mockAxios.mockResolvedValue({ data: Buffer.from('hello') });
determineFileType.mockResolvedValue({ mime: 'text/plain' });
mockClassifyCodeArtifact.mockReturnValueOnce('text');
mockHasOfficeHtmlPath.mockReturnValueOnce(false);
mockExtractCodeArtifactText.mockResolvedValueOnce('hello');
await processCodeOutput({ ...baseParams, name: 'output.txt' });
const createCall = mockCommitCodeFile.mock.calls[0][0];
expect(createCall).toHaveProperty('status', null);
expect(createCall).toHaveProperty('previewError', null);
expect(createCall).toHaveProperty('previewRevision', null);
});
});
describe('file size limit enforcement', () => {
it('treats a zero configured limit as unlimited within the hard transport ceiling', async () => {
fileSizeLimitConfig.value = 0;
mockAxios.mockResolvedValue({ data: Buffer.alloc(100) });
await processCodeOutput(baseParams);
expect(mockAxios).toHaveBeenCalledWith(
expect.objectContaining({
maxContentLength: 64 * 1024 * 1024,
maxBodyLength: 64 * 1024 * 1024,
}),
);
expect(mockClaimCodeFile).toHaveBeenCalledTimes(1);
expect(mockCommitCodeFile).toHaveBeenCalledTimes(1);
});
it('should fallback to download URL when file exceeds size limit', async () => {
// Set a small file size limit for this test
fileSizeLimitConfig.value = 1000; // 1KB limit
const largeBuffer = Buffer.alloc(5000); // 5KB - exceeds 1KB limit
mockAxios.mockResolvedValue({ data: largeBuffer });
const { file: result } = await processCodeOutput(baseParams);
expect(mockAxios).toHaveBeenCalledWith(
expect.objectContaining({
maxContentLength: 1000,
maxBodyLength: 1000,
}),
);
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('exceeds size limit'));
expect(result.filepath).toContain('/api/files/code/download/session-123/file-id-123');
expect(result.expiresAt).toBeDefined();
// Oversized files use the download fallback without committing metadata.
expect(mockCommitCodeFile).not.toHaveBeenCalled();
// Reset to default for other tests
fileSizeLimitConfig.value = 20 * 1024 * 1024;
});
it('uses the existing download fallback when Axios stops an oversized response', async () => {
fileSizeLimitConfig.value = 1000;
mockAxios.mockRejectedValue(new Error('maxContentLength size of 1000 exceeded'));
const { file: result } = await processCodeOutput(baseParams);
expect(result.filepath).toContain('/api/files/code/download/session-123/file-id-123');
expect(logger.warn).toHaveBeenCalledWith(
expect.stringContaining('Generated file exceeds size limit'),
);
expect(mockClaimCodeFile).not.toHaveBeenCalled();
expect(mockCommitCodeFile).not.toHaveBeenCalled();
fileSizeLimitConfig.value = 20 * 1024 * 1024;
});
});
describe('fallback behavior', () => {
it('preserves the stateful route in generated downloads and fallbacks', async () => {
mockAxios.mockRejectedValue(new Error('Network error'));
const executionRouteKey = `stateful:${'a'.repeat(32)}`;
const { file: result } = await processCodeOutput({
...baseParams,
codeApiBaseUrl: 'https://code-stateful.example.com',
executionProfile: 'stateful',
bridgeWorkerId: 'personal-worker-1',
executionRouteKey,
});
expect(mockAxios).toHaveBeenCalledWith(
expect.objectContaining({
url: expect.stringContaining('https://code-stateful.example.com/download/'),
headers: expect.objectContaining({
'X-CodeAPI-Expected-Profile': 'stateful',
'X-LibreChat-Code-Worker-ID': 'personal-worker-1',
}),
}),
);
expect(result.filepath).toContain('execution_profile=stateful');
expect(result.filepath).toContain(
`execution_route_key=${encodeURIComponent(executionRouteKey)}`,
);
});
it('should fallback to download URL when saveBuffer is not available', async () => {
const smallBuffer = Buffer.alloc(100);
mockAxios.mockResolvedValue({ data: smallBuffer });
getStrategyFunctions.mockReturnValue({ saveBuffer: null });
const { file: result } = await processCodeOutput(baseParams);
expect(logger.warn).toHaveBeenCalledWith(
expect.stringContaining('saveBuffer not available'),
);
expect(result.filepath).toContain('/api/files/code/download/');
expect(result.filename).toBe('test-file.txt');
});
it('should fallback to download URL on axios error', async () => {
mockAxios.mockRejectedValue(new Error('Network error'));
const { file: result } = await processCodeOutput(baseParams);
expect(logger.warn).toHaveBeenCalledWith(
expect.stringContaining('Falling back to Code API download URL for strategy local'),
);
expect(result.filepath).toContain('/api/files/code/download/session-123/file-id-123');
expect(result.conversationId).toBe('conv-123');
expect(result.messageId).toBe('msg-123');
expect(result.toolCallId).toBe('tool-call-123');
});
});
describe('metadata and file properties', () => {
it('should include codeEnvSource in metadata with kind: user', async () => {
const smallBuffer = Buffer.alloc(100);
mockAxios.mockResolvedValue({ data: smallBuffer });
const { file: result } = await processCodeOutput(baseParams);
expect(result.metadata).toEqual({
codeEnvSource: {
kind: 'user',
id: 'user-123',
storage_session_id: 'session-123',
file_id: 'file-id-123',
executionProfile: 'default',
},
codeDestination: true,
sourceDispatchedAt: expect.any(Number),
});
});
it('persists the originating profile on a stateful artifact ref', async () => {
mockAxios.mockResolvedValue({ data: Buffer.alloc(100) });
const executionRouteKey = `stateful:${'a'.repeat(32)}`;
const { file: result } = await processCodeOutput({
...baseParams,
codeApiBaseUrl: 'https://code-stateful.example.com',
executionProfile: 'stateful',
executionRouteKey,
});
expect(result.metadata.codeEnvSource).toEqual(
expect.objectContaining({ executionProfile: 'stateful', executionRouteKey }),
);
expect(result.metadata.codeEnvRefs).toBeUndefined();
});
/* Phase C lock-in: outputs are ALWAYS user-scoped, never skill-scoped.
* Even when an execution turn invoked a skill (so input files were
* `kind: 'skill'` shared cross-user), the resulting output bucket
* tags `kind: 'user'` with the requesting user's id. This prevents
* cross-user leakage of artifacts a skill may have generated for
* one user — each user gets their own output sessionKey on codeapi.
*
* Drift hazard: someone reading the simple user-derivation may
* later think "we should respect input kind for outputs too" and
* widen output scope to match input scope. This test pins the
* intentional asymmetry so that change requires updating the test
* (and re-reading the rationale). */
it('outputs are user-scoped regardless of which skill the execution invoked', async () => {
const smallBuffer = Buffer.alloc(100);
mockAxios.mockResolvedValue({ data: smallBuffer });
const userA = { ...mockReq, user: { id: 'user-A' } };
const userB = { ...mockReq, user: { id: 'user-B' } };
const { file: outputA } = await processCodeOutput({ ...baseParams, req: userA });
const { file: outputB } = await processCodeOutput({ ...baseParams, req: userB });
// Each user's output ref is keyed by their own user id. The
// `id` field tracks the requesting user, never the skill.
expect(outputA.metadata.codeEnvSource).toEqual({
kind: 'user',
id: 'user-A',
storage_session_id: 'session-123',
file_id: 'file-id-123',
executionProfile: 'default',
});
expect(outputB.metadata.codeEnvSource).toEqual({
kind: 'user',
id: 'user-B',
storage_session_id: 'session-123',
file_id: 'file-id-123',
executionProfile: 'default',
});
// No skill identity leaks into the output ref under any property.
const refA = outputA.metadata.codeEnvSource;
const refB = outputB.metadata.codeEnvSource;
expect(refA.kind).not.toBe('skill');
expect(refB.kind).not.toBe('skill');
expect(refA).not.toHaveProperty('version');
expect(refB).not.toHaveProperty('version');
});
it('should set correct context for code-generated files', async () => {
const smallBuffer = Buffer.alloc(100);
mockAxios.mockResolvedValue({ data: smallBuffer });
const { file: result } = await processCodeOutput(baseParams);
expect(result.context).toBe(FileContext.execute_code_snapshot);
});
it('should include toolCallId and messageId in result', async () => {
const smallBuffer = Buffer.alloc(100);
mockAxios.mockResolvedValue({ data: smallBuffer });
const { file: result } = await processCodeOutput(baseParams);
expect(result.toolCallId).toBe('tool-call-123');
expect(result.messageId).toBe('msg-123');
});
it('commits foreground output without a background dispatch constraint', async () => {
const smallBuffer = Buffer.alloc(100);
mockAxios.mockResolvedValue({ data: smallBuffer });
await processCodeOutput(baseParams);
expect(mockCommitCodeFile).toHaveBeenCalledWith(
expect.objectContaining({
file_id: 'mock-uuid-1234',
context: FileContext.execute_code_snapshot,
}),
undefined,
);
});
});
describe('socket pool isolation', () => {
it('should pass dedicated keepAlive:false agents to axios for processCodeOutput', async () => {
const smallBuffer = Buffer.alloc(100);
mockAxios.mockResolvedValue({ data: smallBuffer });
await processCodeOutput(baseParams);
const callConfig = mockAxios.mock.calls[0][0];
expect(callConfig.httpAgent).toBe(codeServerHttpAgent);
expect(callConfig.httpsAgent).toBe(codeServerHttpsAgent);
expect(callConfig.httpAgent).toBeInstanceOf(http.Agent);
expect(callConfig.httpsAgent).toBeInstanceOf(https.Agent);
expect(callConfig.httpAgent.keepAlive).toBe(false);
expect(callConfig.httpsAgent.keepAlive).toBe(false);
});
it('should pass dedicated keepAlive:false agents to axios for getSessionInfo', async () => {
mockAxios.mockResolvedValue({
data: [{ name: 'sess/fid', lastModified: new Date().toISOString() }],
});
await getSessionInfo({
kind: 'user',
id: 'user-1',
storage_session_id: 'sess',
file_id: 'fid',
});
const callConfig = mockAxios.mock.calls[0][0];
expect(callConfig.httpAgent).toBe(codeServerHttpAgent);
expect(callConfig.httpsAgent).toBe(codeServerHttpsAgent);
expect(callConfig.httpAgent.keepAlive).toBe(false);
expect(callConfig.httpsAgent.keepAlive).toBe(false);
});
it('forwards cancellation to the freshness request and preserves its error', async () => {
const controller = new AbortController();
const canceled = Object.assign(new Error('canceled'), {
name: 'CanceledError',
code: 'ERR_CANCELED',
});
mockAxios.mockImplementationOnce(async (config) => {
expect(config.signal).toBe(controller.signal);
controller.abort();
throw canceled;
});
await expect(
getSessionInfo(
{
kind: 'user',
id: 'user-1',
storage_session_id: 'sess',
file_id: 'fid',
},
mockReq,
{},
controller.signal,
),
).rejects.toBe(canceled);
});
it('forwards Code API auth headers when checking session object freshness', async () => {
getCodeApiAuthHeaders.mockResolvedValueOnce({ Authorization: 'Bearer freshness-token' });
mockAxios.mockResolvedValue({
data: { lastModified: '2024-01-01T00:00:00Z' },
});
await getSessionInfo(
{
kind: 'user',
id: 'user-123',
storage_session_id: 'session-123',
file_id: 'file-123',
},
mockReq,
);
expect(getCodeApiAuthHeaders).toHaveBeenCalledWith(mockReq, undefined);
expect(mockAxios).toHaveBeenCalledWith(
expect.objectContaining({
method: 'get',
headers: expect.objectContaining({
Authorization: 'Bearer freshness-token',
'User-Agent': 'LibreChat/1.0',
}),
}),
);
});
it('checks freshness against the trusted stateful endpoint and profile', async () => {
mockAxios.mockResolvedValue({
data: { lastModified: '2026-08-15T00:00:00Z' },
});
await getSessionInfo(
{
kind: 'user',
id: 'user-123',
storage_session_id: 'session-123',
file_id: 'file-123',
},
mockReq,
{
baseUrl: 'https://stateful-code.example.com',
executionProfile: 'stateful',
},
);
expect(mockAxios).toHaveBeenCalledWith(
expect.objectContaining({
url: expect.stringMatching(/^https:\/\/stateful-code\.example\.com\/sessions\//),
headers: expect.objectContaining({
'X-CodeAPI-Expected-Profile': 'stateful',
}),
}),
);
});
});
describe('deferred-preview flow (office-bucket files)', () => {
/* Office-bucket files (DOCX/XLSX/etc.) split into:
* the initial emit (await): persist `text: null, status: 'pending'`,
* return `{ file, finalize }` so the caller can ship the
* attachment to the client immediately;
* the deferred render (background): finalize() invokes the extractor and
* transitions the record to 'ready' (with text/textFormat) or
* 'failed' (with previewError). The agent's final response
* never blocks on the deferred render.
*
* The `hasOfficeHtmlPath` mock is the gate. Other tests keep it
* at `false` (legacy single-phase path); we flip it on here. */
const { updateFile } = require('~/models');
beforeEach(() => {
mockHasOfficeHtmlPath.mockReturnValue(true);
updateFile.mockResolvedValue({ file_id: 'mock-uuid-1234', status: 'ready' });
});
afterEach(() => {
mockHasOfficeHtmlPath.mockReturnValue(false);
});
it('persists the initial emit with status:pending and text:null, deferring extraction', async () => {
mockAxios.mockResolvedValue({ data: Buffer.alloc(100) });
determineFileType.mockResolvedValue({
mime: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
});
const result = await processCodeOutput({ ...baseParams, name: 'data.xlsx' });
expect(result.file).toMatchObject({
file_id: 'mock-uuid-1234',
filename: 'data.xlsx',
status: 'pending',
text: null,
textFormat: null,
});
expect(typeof result.finalize).toBe('function');
// Extractor MUST NOT have been called yet — that's deferred preview work.
expect(mockExtractCodeArtifactText).not.toHaveBeenCalled();
// Persisted record with the pending status.
expect(mockCommitCodeFile).toHaveBeenCalledWith(
expect.objectContaining({ status: 'pending', text: null, textFormat: null }),
undefined,
);
});
it('finalize() runs the extractor, transitions to ready with text+textFormat on success', async () => {
mockAxios.mockResolvedValue({ data: Buffer.alloc(100) });
determineFileType.mockResolvedValue({
mime: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
});
mockExtractCodeArtifactText.mockResolvedValueOnce('
');
mockGetExtractedTextFormat.mockReturnValueOnce('html');
const { finalize } = await processCodeOutput({ ...baseParams, name: 'data.xlsx' });
await finalize();
expect(mockExtractCodeArtifactText).toHaveBeenCalledTimes(1);
/* Update is conditional on `previewRevision` so an older render
* can't overwrite a newer turn's record on cross-turn filename
* reuse. The uuid mock returns the same value for every v4()
* call, so file_id and previewRevision happen to coincide here
* — what matters is the second arg carries the revision filter. */
expect(updateFile).toHaveBeenCalledWith(
{
file_id: 'mock-uuid-1234',
text: '',
textFormat: 'html',
status: 'ready',
previewError: null,
},
{ previewRevision: 'mock-uuid-1234' },
);
});
it('finalize() transitions to failed with previewError when extractor returns null (HTML-or-null contract)', async () => {
mockAxios.mockResolvedValue({ data: Buffer.alloc(100) });
determineFileType.mockResolvedValue({
mime: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
});
mockExtractCodeArtifactText.mockResolvedValueOnce(null);
// Office bucket + null text → must be 'failed', NEVER raw text fallback
// (PR #12934 SEC fix: prevents