Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
import { Types } from 'mongoose';
import { FileSources } from 'librechat-data-provider';
import type { Response } from 'express';
import { createSkillUploadHandler } from './upload';
type UploadDeps = Parameters<typeof createSkillUploadHandler>[0];
type UploadRequest = Parameters<ReturnType<typeof createSkillUploadHandler>>[0];
function deferred<T>() {
let resolve!: (value: T) => void;
let reject!: (reason: Error) => void;
const promise = new Promise<T>((resolvePromise, rejectPromise) => {
resolve = resolvePromise;
reject = rejectPromise;
});
return { promise, resolve, reject };
}
const originalFile = {
file_id: 'original',
filepath: '/uploads/original',
source: 'local',
isExecutable: true,
};
function harness() {
const skill = deferred<Awaited<ReturnType<UploadDeps['getSkillById']>>>();
const file = deferred<Awaited<ReturnType<UploadDeps['getSkillFileByPath']>>>();
const saveBuffer = jest.fn(async ({ userId, fileName }) => `/uploads/${userId}/${fileName}`);
const deleteFile = jest.fn(async () => undefined);
const deps = {
getSkillById: jest.fn(() => skill.promise),
getSkillFileByPath: jest.fn(() => file.promise),
upsertSkillFile: jest.fn(async (row) => ({
...originalFile,
file_id: row.file_id,
filepath: row.filepath,
})),
resolveStorage: jest.fn(() => ({ source: FileSources.local, saveBuffer })),
getStrategyFunctions: jest.fn(() => ({ deleteFile })),
reserveSkillUploadIntent: jest.fn(async (input) => ({
...input,
skillId: new Types.ObjectId(),
author: new Types.ObjectId(),
state: 'uploading' as const,
})),
transitionSkillUploadIntent: jest.fn(async () => true),
} satisfies UploadDeps;
const req = {
params: { id: 'skill-id', relativePath: ['references', 'guide.md'] },
body: { relativePath: 'references/guide.md', expectedFileId: 'original' },
user: { id: 'user-id', tenantId: 'tenant-id' },
file: {
originalname: 'guide.md',
mimetype: 'text/markdown',
buffer: Buffer.from('saved text'),
size: 10,
},
} as unknown as UploadRequest;
const res = {} as Response;
res.status = jest.fn(() => res);
res.json = jest.fn(() => res);
return {
skill,
file,
deps,
saveBuffer,
deleteFile,
req,
res,
handler: createSkillUploadHandler(deps),
};
}
describe('skill upload lookup ordering', () => {
it('leaves old-blob cleanup to the durable persistence queue after browser replacement', async () => {
const h = harness();
const pending = h.handler(h.req, h.res);
h.skill.resolve({ source: 'inline' });
h.file.resolve(originalFile);
await pending;
expect(h.res.status).toHaveBeenCalledWith(200);
expect(h.deps.upsertSkillFile).toHaveBeenCalledWith(
expect.objectContaining({ expectedFileId: 'original' }),
);
expect(h.deleteFile).not.toHaveBeenCalled();
});
it.each(['skill', 'file'] as const)(
'starts both privileged lookups before either resolves (%s first)',
async (first) => {
const h = harness();
const pending = h.handler(h.req, h.res);
expect(h.deps.getSkillById).toHaveBeenCalledWith('skill-id');
expect(h.deps.getSkillFileByPath).toHaveBeenCalledWith('skill-id', 'references/guide.md');
expect(h.saveBuffer).not.toHaveBeenCalled();
if (first === 'skill') h.skill.resolve({ source: 'inline' });
else h.file.resolve(originalFile);
await Promise.resolve();
expect(h.saveBuffer).not.toHaveBeenCalled();
h.skill.resolve({ source: 'inline' });
h.file.resolve(originalFile);
await pending;
expect(h.res.status).toHaveBeenCalledWith(200);
expect(h.saveBuffer).toHaveBeenCalledWith(expect.objectContaining({ tenantId: 'tenant-id' }));
expect(h.deps.upsertSkillFile).toHaveBeenCalledWith(
expect.objectContaining({
expectedFileId: 'original',
isExecutable: true,
tenantId: 'tenant-id',
}),
);
},
);
it('reuses the skill already resolved by ACL middleware', async () => {
const h = harness();
h.req.resourceAccess = { resourceInfo: { source: 'inline' } };
const pending = h.handler(h.req, h.res);
expect(h.deps.getSkillById).not.toHaveBeenCalled();
expect(h.deps.getSkillFileByPath).toHaveBeenCalledTimes(1);
h.file.resolve(originalFile);
await pending;
expect(h.res.status).toHaveBeenCalledWith(200);
});
it.each(['reservation', 'persistence'] as const)(
'reports a deletion race during %s as a conflict',
async (stage) => {
const h = harness();
const error = Object.assign(new Error('Internal deletion state'), { code: 'SKILL_DELETING' });
if (stage === 'reservation') h.deps.reserveSkillUploadIntent.mockRejectedValueOnce(error);
else h.deps.upsertSkillFile.mockRejectedValueOnce(error);
const pending = h.handler(h.req, h.res);
h.skill.resolve({ source: 'inline' });
h.file.resolve(originalFile);
await pending;
expect(h.res.status).toHaveBeenCalledWith(409);
expect(h.res.json).toHaveBeenCalledWith({ error: 'SKILL_DELETING' });
if (stage === 'reservation') expect(h.saveBuffer).not.toHaveBeenCalled();
},
);
it.each(['missing', 'managed', 'conflict', 'lookup failure'] as const)(
'does not store bytes for %s',
async (scenario) => {
const h = harness();
const pending = h.handler(h.req, h.res);
h.file.resolve(scenario === 'conflict' ? null : originalFile);
if (scenario === 'lookup failure') h.skill.reject(new Error('database unavailable'));
else
h.skill.resolve(
scenario === 'missing' ? null : { source: scenario === 'managed' ? 'github' : 'inline' },
);
await pending;
expect(h.res.status).toHaveBeenCalledWith(
{ missing: 404, managed: 403, conflict: 409, 'lookup failure': 500 }[scenario],
);
expect(h.deps.resolveStorage).not.toHaveBeenCalled();
expect(h.saveBuffer).not.toHaveBeenCalled();
expect(h.deps.upsertSkillFile).not.toHaveBeenCalled();
},
);
});