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
🖊️ fix: Persist Skill Subfile Edits (#16362)
lia-by-librechat[bot]7caa98ff15a2
diff --git a/api/server/routes/agents/__tests__/openapi.contract.spec.js b/api/server/routes/agents/__tests__/openapi.contract.spec.jsindex bbd76e2756..6a97570165 100644--- a/api/server/routes/agents/__tests__/openapi.contract.spec.js+++ b/api/server/routes/agents/__tests__/openapi.contract.spec.js@@ -239,14 +239,14 @@ describe('Agents OpenAPI actual HTTP contract', () => {uniqueTempPath: true,});- const { getSkillToolDeps } = require('~/server/services/Endpoints/agents/skillDeps');+ const { getSkillManagementFileSaver } = require('~/server/services/Endpoints/agents/skillDeps');const skillHandlers = createSkillManagementHandlers({handlers: {},getSkillById: db.getSkillById,getRoleByName,checkPermission: async () => true,hasCapability: async () => true,- saveFile: getSkillToolDeps().saveSkillFileContent,+ saveFile: getSkillManagementFileSaver(),});app = express();diff --git a/api/server/routes/agents/__tests__/skills.spec.js b/api/server/routes/agents/__tests__/skills.spec.jsindex 6cca03c759..7bace5539d 100644--- a/api/server/routes/agents/__tests__/skills.spec.js+++ b/api/server/routes/agents/__tests__/skills.spec.js@@ -4,6 +4,7 @@ const request = require('supertest');const mockList = jest.fn((_req, res) => res.json({ object: 'list' }));const mockWrite = jest.fn((_req, res) => res.json({ saved: true }));const mockSync = jest.fn();+const mockManagementSaveFile = jest.fn();const mockIp = jest.fn((_req, _res, next) => next());const mockUser = jest.fn((_req, _res, next) => next());const mockAuth = jest.fn((_req, _res, next) => next());@@ -38,7 +39,7 @@ jest.mock('~/server/services/Skills/sync', () => ({}));jest.mock('~/server/services/Endpoints/agents/skillDeps', () => ({getSkillDbMethods: () => ({}),- getSkillToolDeps: () => ({}),+ getSkillManagementFileSaver: () => mockManagementSaveFile,}));jest.mock('~/models', () => ({}));jest.mock('~/server/middleware/limiters/uploadLimiters', () => ({@@ -55,6 +56,7 @@ it('wires sync and both upload limiters into the authorized management handlers'await mockDeps.beforeList({ config: { tenantConfig: true } });expect(mockSync).toHaveBeenCalledWith({ config: { tenantConfig: true } });expect(mockDeps.fileWriteLimiters).toHaveLength(2);+ expect(mockDeps.saveFile).toBe(mockManagementSaveFile);const next = jest.fn();for (const limiter of mockDeps.fileWriteLimiters) limiter({}, {}, next);expect(mockIp).toHaveBeenCalledTimes(1);diff --git a/api/server/routes/agents/skills.js b/api/server/routes/agents/skills.jsindex ccace9bf8b..6431da12f1 100644--- a/api/server/routes/agents/skills.js+++ b/api/server/routes/agents/skills.js@@ -8,7 +8,7 @@ const { checkPermission } = require('~/server/services/PermissionService');const { getSkillsHandlers } = require('~/server/services/Skills/handlers');const {getSkillDbMethods,- getSkillToolDeps,+ getSkillManagementFileSaver,} = require('~/server/services/Endpoints/agents/skillDeps');const { getRoleByName } = require('~/models');const { requireAgentManagementAuth } = require('./middleware');@@ -23,7 +23,7 @@ const handlers = createSkillManagementHandlers({getRoleByName,checkPermission,hasCapability,- saveFile: getSkillToolDeps().saveSkillFileContent,+ saveFile: getSkillManagementFileSaver(),});router.use(requireAgentManagementAuth, checkBan, configMiddleware);router.get('/', handlers.list);diff --git a/api/server/routes/skills.js b/api/server/routes/skills.jsindex dd40662750..321d17d00c 100644--- a/api/server/routes/skills.js+++ b/api/server/routes/skills.js@@ -1,10 +1,9 @@const path = require('path');-const crypto = require('crypto');const multer = require('multer');const express = require('express');const {createImportHandler,- blockFilteredSkillFile,+ createSkillUploadHandler,generateCheckAccess,getStorageMetadata,resolveRequestTenantId,@@ -149,110 +148,13 @@ const importHandler = createImportHandler({// ---------------------------------------------------------------------------// Per-file upload handler (add a single file to an existing skill)// ----------------------------------------------------------------------------async function uploadFileHandler(req, res) {- try {- const { file } = req;- if (!file) {- return res.status(400).json({ error: 'No file provided' });- }-- const skillId = req.params.id;- const relativePath = req.body.relativePath;- if (!relativePath) {- return res.status(400).json({ error: 'relativePath is required in form body' });- }- if (relativePath.toUpperCase() === 'SKILL.MD') {- return res.status(400).json({ error: 'SKILL.md is reserved; update the skill body instead' });- }- // Reject traversal, absolute paths, empty/dot segments — matches model-layer validator- // so storage writes don't happen before DB rejects the path.- if (- !/^[a-zA-Z0-9._\-/]+$/.test(relativePath) ||- /^\//.test(relativePath) ||- relativePath.split('/').some((s) => s === '' || s === '.' || s === '..')- ) {- return res.status(400).json({ error: 'Invalid file path' });- }- if (- blockFilteredSkillFile(req.config?.filters, res, {- buffer: file.buffer,- originalName: file.originalname,- relativePath,- })- ) {- return res;- }-- const tenantId = resolveRequestTenantId(req);-- // Look up existing file before saving — needed to clean up old blob on replace- const existingFile = await getSkillFileByPath(skillId, relativePath);-- const fileId = crypto.randomUUID();- const filename = file.originalname;- const storageFileName = `${fileId}__${filename}`;-- const isImage = (file.mimetype || '').startsWith('image/');- const storage = resolveSkillStorage(req, { isImage });- const filepath = await storage.saveBuffer({- userId: req.user.id,- buffer: file.buffer,- fileName: storageFileName,- basePath: 'uploads',- tenantId,- });- const storageMetadata = getStorageMetadata({ filepath, source: storage.source });-- let result;- try {- result = await upsertSkillFile({- skillId,- relativePath,- file_id: fileId,- filename,- filepath,- ...storageMetadata,- source: storage.source,- mimeType: file.mimetype || 'application/octet-stream',- bytes: file.size,- isExecutable: false,- author: req.user._id,- tenantId,- });- } catch (dbError) {- // Clean up the stored blob so it doesn't leak on DB failure- try {- const { deleteFile } = getStrategyFunctions(storage.source);- if (deleteFile) {- await deleteFile(req, { filepath, user: req.user.id, tenantId });- }- } catch (cleanupErr) {- logger.error('[uploadFile] Failed to clean up orphaned blob:', cleanupErr);- }- throw dbError;- }-- // Clean up old blob if this was a replace (different filepath means new storage object)- if (existingFile && existingFile.filepath !== filepath) {- const { deleteFile: delOld } = getStrategyFunctions(existingFile.source);- if (delOld) {- delOld(req, {- filepath: existingFile.filepath,- user: existingFile.author ?? req.user.id,- tenantId: existingFile.tenantId ?? tenantId,- }).catch((e) => logger.error('[uploadFile] Old blob cleanup failed:', e));- }- }-- return res.status(200).json(result);- } catch (error) {- if (error.code === 'SKILL_FILE_VALIDATION_FAILED') {- return res.status(400).json({ error: error.message });- }- logger.error('[uploadFile] Error:', error);- return res.status(500).json({ error: 'Failed to upload file' });- }-}+const uploadFileHandler = createSkillUploadHandler({+ getSkillById,+ getSkillFileByPath,+ upsertSkillFile,+ resolveStorage: resolveSkillStorage,+ getStrategyFunctions,+});// ---------------------------------------------------------------------------// Routes@@ -306,9 +208,9 @@ router.get(handlers.listFiles,);-// Per-file upload (live — replaces 501 stub)+// Legacy upload and revision-checked editing. Older servers have no POST wildcard route.router.post(- '/:id/files',+ ['/:id/files', '/:id/files/*relativePath'],canAccessSkillResource({ requiredPermission: PermissionBits.EDIT }),fileUploadIpLimiter,fileUploadUserLimiter,diff --git a/api/server/routes/skills.test.js b/api/server/routes/skills.test.jsindex 992cb2d849..92272ae899 100644--- a/api/server/routes/skills.test.js+++ b/api/server/routes/skills.test.js@@ -791,6 +791,450 @@ describe('Skill routes', () => {});describe('POST /api/skills/:id/files (live)', () => {+ it('replaces a nested text file and clears the old cached content', async () => {+ const { Readable } = require('stream');+ const { getStrategyFunctions } = require('~/server/services/Files/strategies');+ const { updateSkillFileContent } = require('~/models');+ const originalStrategy = getStrategyFunctions.getMockImplementation();+ const stored = new Map();+ const saveBuffer = jest.fn(async ({ buffer, fileName }) => {+ const filepath = `/uploads/${fileName}`;+ stored.set(filepath, Buffer.from(buffer));+ return filepath;+ });+ const getDownloadStream = jest.fn(async (_req, filepath) => {+ const buffer = stored.get(filepath);+ if (!buffer) {+ throw new Error('File not found in test storage');+ }+ return Readable.from([buffer]);+ });+ getStrategyFunctions.mockReturnValue({ saveBuffer, getDownloadStream });++ try {+ const created = await createSkillAsOwner();+ const skillId = created.body._id;+ const relativePath = 'references/queries.md';+ const url = `/api/skills/${skillId}/files`;+ const readUrl = `${url}/${encodeURIComponent(relativePath)}`;+ const upload = (content) =>+ request(app)+ .post(url)+ .field('relativePath', relativePath)+ .attach('file', Buffer.from(content), {+ filename: 'queries.md',+ contentType: 'text/markdown',+ });++ const original = await upload('first revision');+ expect(original.status).toBe(200);+ await updateSkillFileContent(skillId, relativePath, {+ content: 'first revision',+ isBinary: false,+ });+ const cached = await request(app).get(readUrl);+ expect(cached.status).toBe(200);+ expect(cached.body.content).toBe('first revision');++ const replacement = await upload('saved revision');+ expect(replacement.status).toBe(200);+ expect(replacement.body.relativePath).toBe(relativePath);+ const persisted = await request(app).get(readUrl);+ expect(persisted.status).toBe(200);+ expect(persisted.body.content).toBe('saved revision');+ expect(getDownloadStream).toHaveBeenCalledTimes(1);+ expect(saveBuffer).toHaveBeenCalledTimes(2);+ } finally {+ getStrategyFunctions.mockImplementation(originalStrategy);+ }+ });++ it('rejects an editor revision after a newer write and never recreates a deleted file', async () => {+ const created = await createSkillAsOwner();+ const url = `/api/skills/${created.body._id}/files`;+ const upload = (text, expectedFileId) => {+ const req = request(app)+ .post(expectedFileId ? `${url}/references/revision.md` : url)+ .field('relativePath', 'references/revision.md');+ if (expectedFileId) req.field('expectedFileId', expectedFileId);+ return req.attach('file', Buffer.from(text), {+ filename: 'revision.md',+ contentType: 'text/markdown',+ });+ };+ const initial = await upload('first');+ expect(initial.status).toBe(200);+ const read = await request(app).get(`${url}/references/revision.md`);+ expect(read.body.fileId).toBe(initial.body.file_id);+ const replaced = await upload('newer', initial.body.file_id);+ expect(replaced.status).toBe(200);+ expect((await upload('stale', initial.body.file_id)).status).toBe(409);+ const stored = await SkillFile.findOne({ skillId: created.body._id });+ expect(stored.file_id).toBe(replaced.body.file_id);+ await request(app).delete(`${url}/references/revision.md`);+ expect((await upload('resurrect', replaced.body.file_id)).status).toBe(409);+ expect(await SkillFile.countDocuments({ skillId: created.body._id })).toBe(0);+ });++ it.each(['github', 'notion'])(+ 'rejects uploads to %s-managed skills before storing bytes',+ async (source) => {+ const created = await createSkillAsOwner();+ await Skill.updateOne({ _id: created.body._id }, { $set: { source } });+ const { getStrategyFunctions } = require('~/server/services/Files/strategies');+ const saveBuffer = getStrategyFunctions('local').saveBuffer;+ saveBuffer.mockClear();+ const response = await request(app)+ .post(`/api/skills/${created.body._id}/files`)+ .field('relativePath', 'references/managed.md')+ .attach('file', Buffer.from('local draft'), {+ filename: 'managed.md',+ contentType: 'text/markdown',+ });+ expect(response.status).toBe(403);+ expect(saveBuffer).not.toHaveBeenCalled();+ expect(await SkillFile.countDocuments()).toBe(0);+ },+ );++ it('treats legacy skills without a stored source as inline for reads and file edits', async () => {+ const created = await createSkillAsOwner();+ const skillId = created.body._id;+ const id = new mongoose.Types.ObjectId(skillId);+ await Skill.collection.updateOne({ _id: id }, { $unset: { source: '' } });+ expect(await Skill.collection.findOne({ _id: id })).not.toHaveProperty('source');++ const detail = await request(app).get(`/api/skills/${skillId}`);+ expect(detail.status).toBe(200);+ expect(detail.body.source).toBe('inline');+ const list = await request(app).get('/api/skills');+ expect(list.status).toBe(200);+ expect(list.body.skills.find((entry) => entry._id === skillId).source).toBe('inline');++ const url = `/api/skills/${skillId}/files`;+ const first = await request(app)+ .post(url)+ .field('relativePath', 'references/legacy.md')+ .attach('file', Buffer.from('first'), {+ filename: 'legacy.md',+ contentType: 'text/markdown',+ });+ expect(first.status).toBe(200);+ const edited = await request(app)+ .post(`${url}/references/legacy.md`)+ .field('relativePath', 'references/legacy.md')+ .field('expectedFileId', first.body.file_id)+ .attach('file', Buffer.from('edited'), {+ filename: 'legacy.md',+ contentType: 'text/markdown',+ });+ expect(edited.status).toBe(200);+ expect(await SkillFile.findOne({ skillId }).lean()).toMatchObject({+ file_id: edited.body.file_id,+ });+ });++ it('rejects an agent replacement captured before a newer browser edit', async () => {+ const { getSkillToolDeps } = require('~/server/services/Endpoints/agents/skillDeps');+ const { getStrategyFunctions } = require('~/server/services/Files/strategies');+ const originalStrategy = getStrategyFunctions.getMockImplementation();+ const created = await createSkillAsOwner();+ const skillId = created.body._id;+ const relativePath = 'references/shared.md';+ const url = `/api/skills/${skillId}/files`;+ const initial = await request(app)+ .post(url)+ .field('relativePath', relativePath)+ .attach('file', Buffer.from('original'), {+ filename: 'shared.md',+ contentType: 'text/markdown',+ });+ expect(initial.status).toBe(200);+ const agentRead = await getSkillToolDeps().getSkillFileByPath(skillId, relativePath);+ const capturedVersion = (await Skill.findById(skillId).lean()).version;+ expect(agentRead.file_id).toBe(initial.body.file_id);++ const browser = await request(app)+ .post(`${url}/references/shared.md`)+ .field('relativePath', relativePath)+ .field('expectedFileId', agentRead.file_id)+ .attach('file', Buffer.from('browser winner'), {+ filename: 'shared.md',+ contentType: 'text/markdown',+ });+ expect(browser.status).toBe(200);+ expect((await Skill.findById(skillId).lean()).version).toBe(capturedVersion + 1);+ const winner = await SkillFile.findOne({ skillId, relativePath }).lean();++ const saveBuffer = jest.fn(async ({ fileName }) => `/uploads/${fileName}`);+ const deleteFile = jest.fn(async () => undefined);+ getStrategyFunctions.mockReturnValue({ saveBuffer, deleteFile });+ try {+ await expect(+ getSkillToolDeps().saveSkillFileContent({+ req: {+ user: { id: testUsers.owner._id.toString(), _id: testUsers.owner._id },+ config: { fileStrategy: 'local' },+ },+ skillId,+ relativePath,+ content: 'stale agent edit',+ mimeType: 'text/markdown',+ expectedFileId: agentRead.file_id,+ }),+ ).rejects.toMatchObject({ code: 'SKILL_FILE_CONFLICT' });+ expect(saveBuffer).not.toHaveBeenCalled();+ expect(deleteFile).not.toHaveBeenCalled();+ expect(await SkillFile.findOne({ skillId, relativePath }).lean()).toMatchObject({+ file_id: browser.body.file_id,+ filepath: winner.filepath,+ });+ expect((await Skill.findById(skillId).lean()).version).toBe(capturedVersion + 1);+ } finally {+ getStrategyFunctions.mockImplementation(originalStrategy);+ }+ });++ it('rejects and cleans an agent upload when a browser edit lands during storage', async () => {+ const { getSkillToolDeps } = require('~/server/services/Endpoints/agents/skillDeps');+ const { getStrategyFunctions } = require('~/server/services/Files/strategies');+ const originalStrategy = getStrategyFunctions.getMockImplementation();+ const created = await createSkillAsOwner();+ const skillId = created.body._id;+ const relativePath = 'references/overlap.md';+ const url = `/api/skills/${skillId}/files`;+ const initial = await request(app)+ .post(url)+ .field('relativePath', relativePath)+ .attach('file', Buffer.from('initial'), {+ filename: 'overlap.md',+ contentType: 'text/markdown',+ });+ expect(initial.status).toBe(200);+ const agentRead = await getSkillToolDeps().getSkillFileByPath(skillId, relativePath);+ const agentReq = {+ user: { id: testUsers.owner._id.toString(), _id: testUsers.owner._id },+ config: { fileStrategy: 'local' },+ };+ let browserRevision;+ const deleteFile = jest.fn(async () => undefined);+ const saveBuffer = jest.fn(async ({ fileName }) => {+ if (saveBuffer.mock.calls.length === 1) {+ const browser = await request(app)+ .post(`${url}/references/overlap.md`)+ .field('relativePath', relativePath)+ .field('expectedFileId', agentRead.file_id)+ .attach('file', Buffer.from('browser wins'), {+ filename: 'overlap.md',+ contentType: 'text/markdown',+ });+ expect(browser.status).toBe(200);+ browserRevision = browser.body.file_id;+ }+ return `/uploads/${fileName}`;+ });+ getStrategyFunctions.mockReturnValue({ saveBuffer, deleteFile });+ try {+ await expect(+ getSkillToolDeps().saveSkillFileContent({+ req: agentReq,+ skillId,+ relativePath,+ content: 'agent stale edit',+ mimeType: 'text/markdown',+ expectedFileId: agentRead.file_id,+ createOnly: false,+ }),+ ).rejects.toMatchObject({ code: 'SKILL_FILE_CONFLICT' });+ expect(saveBuffer).toHaveBeenCalledTimes(2);+ const agentPath = `/uploads/${saveBuffer.mock.calls[0][0].fileName}`;+ const browserPath = `/uploads/${saveBuffer.mock.calls[1][0].fileName}`;+ expect(await SkillFile.findOne({ skillId, relativePath }).lean()).toMatchObject({+ file_id: browserRevision,+ filepath: browserPath,+ });+ expect(deleteFile).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ filepath: agentPath }),+ );+ expect(deleteFile).not.toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ filepath: browserPath }),+ );+ } finally {+ getStrategyFunctions.mockImplementation(originalStrategy);+ }+ });++ it('atomically rejects a race after storing bytes and cleans up only the losing upload', async () => {+ const { getStrategyFunctions } = require('~/server/services/Files/strategies');+ const originalStrategy = getStrategyFunctions.getMockImplementation();+ const { upsertSkillFile } = require('~/models');+ const created = await createSkillAsOwner();+ const skillId = created.body._id;+ const input = {+ skillId,+ relativePath: 'references/race.md',+ file_id: 'initial',+ filename: 'race.md',+ filepath: '/uploads/initial',+ source: 'local',+ mimeType: 'text/markdown',+ bytes: 4,+ author: testUsers.owner._id,+ };+ await upsertSkillFile(input);+ const deleteFile = jest.fn(async () => undefined);+ const saveBuffer = jest.fn(async ({ fileName }) => {+ // Another writer commits after the handler's preflight but before its atomic update.+ await upsertSkillFile({ ...input, file_id: 'winner', filepath: '/uploads/winner' });+ return `/uploads/${fileName}`;+ });+ getStrategyFunctions.mockReturnValue({ saveBuffer, deleteFile });+ try {+ const res = await request(app)+ .post(`/api/skills/${skillId}/files/references/race.md`)+ .field('relativePath', input.relativePath)+ .field('expectedFileId', 'initial')+ .attach('file', Buffer.from('losing draft'), {+ filename: 'race.md',+ contentType: 'text/markdown',+ });+ expect(res.status).toBe(409);+ expect(await SkillFile.findOne({ skillId }).lean()).toMatchObject({+ file_id: 'winner',+ filepath: '/uploads/winner',+ });+ expect(deleteFile).toHaveBeenCalledTimes(1);+ expect(deleteFile.mock.calls[0][1].filepath).toBe(+ `/uploads/${saveBuffer.mock.calls[0][0].fileName}`,+ );+ } finally {+ getStrategyFunctions.mockImplementation(originalStrategy);+ }+ });++ it('does not delete committed file bytes if the parent version bump fails', async () => {+ const created = await createSkillAsOwner();+ const { getStrategyFunctions } = require('~/server/services/Files/strategies');+ const originalStrategy = getStrategyFunctions.getMockImplementation();+ const deleteFile = jest.fn(async () => undefined);+ getStrategyFunctions.mockReturnValue({+ saveBuffer: jest.fn(async () => '/uploads/committed'),+ deleteFile,+ });+ const bump = jest+ .spyOn(Skill, 'findByIdAndUpdate')+ .mockRejectedValueOnce(new Error('parent update failed'));+ try {+ const response = await request(app)+ .post(`/api/skills/${created.body._id}/files`)+ .field('relativePath', 'references/committed.md')+ .attach('file', Buffer.from('committed text'), {+ filename: 'committed.md',+ contentType: 'text/markdown',+ });+ expect(response.status).toBe(500);+ expect(await SkillFile.findOne({ skillId: created.body._id }).lean()).toMatchObject({+ filepath: '/uploads/committed',+ });+ expect(deleteFile).not.toHaveBeenCalled();+ } finally {+ bump.mockRestore();+ getStrategyFunctions.mockImplementation(originalStrategy);+ }+ });++ it('cleans up the superseded blob when a replacement commits but the parent bump fails', async () => {+ const { getStrategyFunctions } = require('~/server/services/Files/strategies');+ const { upsertSkillFile } = require('~/models');+ const originalStrategy = getStrategyFunctions.getMockImplementation();+ const created = await createSkillAsOwner();+ const skillId = created.body._id;+ const oldPath = '/uploads/previous';+ const newPath = '/uploads/replacement';+ const stored = new Set([oldPath]);+ await upsertSkillFile({+ skillId,+ relativePath: 'references/committed.md',+ file_id: 'original',+ filename: 'committed.md',+ filepath: oldPath,+ source: 'local',+ mimeType: 'text/markdown',+ bytes: 8,+ author: testUsers.editor._id,+ });+ const deleteFile = jest.fn(async (_req, { filepath }) => {+ stored.delete(filepath);+ });+ const saveBuffer = jest.fn(async () => {+ stored.add(newPath);+ return newPath;+ });+ getStrategyFunctions.mockReturnValue({ saveBuffer, deleteFile });+ const bump = jest+ .spyOn(Skill, 'findByIdAndUpdate')+ .mockRejectedValueOnce(new Error('parent update failed'));+ try {+ const response = await request(app)+ .post(`/api/skills/${skillId}/files/references/committed.md`)+ .field('relativePath', 'references/committed.md')+ .field('expectedFileId', 'original')+ .attach('file', Buffer.from('new text'), {+ filename: 'committed.md',+ contentType: 'text/markdown',+ });+ expect(response.status).toBe(500);+ expect(await SkillFile.findOne({ skillId }).lean()).toMatchObject({+ filepath: newPath,+ file_id: expect.not.stringMatching('original'),+ });+ expect(saveBuffer).toHaveBeenCalledTimes(1);+ expect(deleteFile).toHaveBeenCalledTimes(1);+ expect(deleteFile.mock.calls[0][1]).toMatchObject({+ filepath: oldPath,+ user: testUsers.editor._id.toString(),+ });+ expect(stored.has(oldPath)).toBe(false);+ expect(stored.has(newPath)).toBe(true);+ } finally {+ bump.mockRestore();+ getStrategyFunctions.mockImplementation(originalStrategy);+ }+ });++ it('rejects a file save without EDIT access', async () => {+ const created = await createSkillAsOwner();+ setTestUser(testUsers.noAccess);+ const response = await request(app)+ .post(`/api/skills/${created.body._id}/files`)+ .field('relativePath', 'references/denied.md')+ .attach('file', Buffer.from('denied'), {+ filename: 'denied.md',+ contentType: 'text/markdown',+ });+ expect(response.status).toBe(403);+ expect(await SkillFile.countDocuments()).toBe(0);+ });++ it('requires both a revision and a matching body path on the conditional route', async () => {+ const created = await createSkillAsOwner();+ const url = `/api/skills/${created.body._id}/files/references/file.md`;+ const missing = await request(app)+ .post(url)+ .field('relativePath', 'references/file.md')+ .attach('file', Buffer.from('text'), { filename: 'file.md', contentType: 'text/markdown' });+ expect(missing.status).toBe(400);+ const mismatch = await request(app)+ .post(url)+ .field('relativePath', 'references/other.md')+ .field('expectedFileId', 'some-revision')+ .attach('file', Buffer.from('text'), { filename: 'file.md', contentType: 'text/markdown' });+ expect(mismatch.status).toBe(400);+ expect(await SkillFile.countDocuments()).toBe(0);+ });+it('returns 400 when no file is provided', async () => {const created = await createSkillAsOwner();const res = await request(app).post(`/api/skills/${created.body._id}/files`);diff --git a/api/server/services/Endpoints/agents/skillDeps.js b/api/server/services/Endpoints/agents/skillDeps.jsindex 7f695bbfea..52d251a57d 100644--- a/api/server/services/Endpoints/agents/skillDeps.js+++ b/api/server/services/Endpoints/agents/skillDeps.js@@ -1,4 +1,3 @@-const crypto = require('crypto');const { getStrategyFunctions } = require('~/server/services/Files/strategies');const { batchUploadCodeEnvFiles } = require('~/server/services/Files/Code/crud');const {@@ -17,11 +16,12 @@ const {const {checkAccess,isMemoryEnabled,- getStorageMetadata,resolveRequestTenantId,enrichWithSkillConfigurable,mergeDeploymentSkillIds,createDeploymentSkillMethods,+ createSkillFileSaver,+ createSkillManagementFileSaver,isDeploymentSkillFileSource,getDeploymentSkillDownloadStream,} = require('@librechat/api');@@ -77,71 +77,17 @@ function resolveSkillStorage(req, { isImage = false } = {}) {return { saveBuffer: strategy.saveBuffer, source };}-function basename(relativePath) {- const slash = relativePath.lastIndexOf('/');- return slash === -1 ? relativePath : relativePath.slice(slash + 1);-}--async function saveSkillFileContent({ req, skillId, relativePath, content, mimeType }) {- const existingFile = await db.getSkillFileByPath(skillId, relativePath);- const tenantId = resolveRequestTenantId(req);- const fileId = crypto.randomUUID();- const filename = basename(relativePath);- const storageFileName = `${fileId}__${filename}`;- const buffer = Buffer.from(content, 'utf8');- const storage = resolveSkillStorage(req, { isImage: mimeType.startsWith('image/') });- const filepath = await storage.saveBuffer({- userId: req.user.id,- buffer,- fileName: storageFileName,- basePath: 'uploads',- tenantId,- });- const storageMetadata = getStorageMetadata({ filepath, source: storage.source });-- let result;- try {- result = await db.upsertSkillFile({- skillId,- relativePath,- file_id: fileId,- filename,- filepath,- ...storageMetadata,- source: storage.source,- mimeType,- bytes: buffer.length,- isExecutable: false,- author: req.user._id ?? req.user.id,- tenantId,- });- if (!result) {- const error = new Error('Skill file save failed to persist metadata');- error.code = 'SKILL_FILE_UPSERT_NOT_FOUND';- throw error;- }- } catch (error) {- const { deleteFile } = getStrategyFunctions(storage.source);- if (deleteFile) {- await deleteFile(req, { filepath, user: req.user.id, tenantId }).catch(() => undefined);- }- throw error;- }-- if (existingFile && existingFile.filepath !== filepath) {- const { deleteFile } = getStrategyFunctions(existingFile.source);- if (deleteFile) {- deleteFile(req, {- filepath: existingFile.filepath,- storageKey: existingFile.storageKey,- storageRegion: existingFile.storageRegion,- user: existingFile.author ?? req.user.id,- tenantId: existingFile.tenantId ?? tenantId,- }).catch(() => undefined);- }- }+const skillFileSaveDeps = {+ getSkillFileByPath: db.getSkillFileByPath,+ upsertSkillFile: db.upsertSkillFile,+ resolveStorage: resolveSkillStorage,+ getStrategyFunctions,+};+const saveSkillFileContent = createSkillFileSaver(skillFileSaveDeps);+const saveSkillManagementFileContent = createSkillManagementFileSaver(skillFileSaveDeps);- return { bytes: result.bytes, relativePath: result.relativePath };+function getSkillManagementFileSaver() {+ return saveSkillManagementFileContent;}function canCreateSkill({ req }) {@@ -425,6 +371,7 @@ function getSkillToolDeps() {module.exports = {getSkillToolDeps,+ getSkillManagementFileSaver,canAuthorSkillFiles,isAgentSkillAuthoringEnabledForRun,getSkillDbMethods,diff --git a/api/server/services/Endpoints/agents/skillDeps.spec.js b/api/server/services/Endpoints/agents/skillDeps.spec.jsindex bf848b7045..c107a52d75 100644--- a/api/server/services/Endpoints/agents/skillDeps.spec.js+++ b/api/server/services/Endpoints/agents/skillDeps.spec.js@@ -5,6 +5,18 @@ const mockGetFileStrategy = jest.fn();const mockGetStorageMetadata = jest.fn();const mockResolveRequestTenantId = jest.fn();const mockCreateDeploymentSkillMethods = jest.fn((methods) => methods);+const mockSaveSkillFileContent = jest.fn();+const mockSaveSkillManagementFileContent = jest.fn();+let mockSaverDeps;+let mockManagementSaverDeps;+const mockCreateSkillFileSaver = jest.fn((deps) => {+ mockSaverDeps = deps;+ return mockSaveSkillFileContent;+});+const mockCreateSkillManagementFileSaver = jest.fn((deps) => {+ mockManagementSaverDeps = deps;+ return mockSaveSkillManagementFileContent;+});const mockReadWorkspaceFile = jest.fn();const mockSearchWorkspace = jest.fn();const mockListWorkspaceFiles = jest.fn();@@ -36,6 +48,8 @@ jest.mock('~/server/services/Files/Code/process', () => ({jest.mock('@librechat/api', () => ({checkAccess: jest.fn(),createDeploymentSkillMethods: (...args) => mockCreateDeploymentSkillMethods(...args),+ createSkillFileSaver: (...args) => mockCreateSkillFileSaver(...args),+ createSkillManagementFileSaver: (...args) => mockCreateSkillManagementFileSaver(...args),enrichWithSkillConfigurable: jest.fn(),getDeploymentSkillDownloadStream: jest.fn(),getStorageMetadata: (...args) => mockGetStorageMetadata(...args),@@ -71,7 +85,7 @@ const mockDb = {jest.mock('~/models', () => mockDb);-const { getSkillToolDeps } = require('./skillDeps');+const { getSkillToolDeps, getSkillManagementFileSaver } = require('./skillDeps');describe('skillDeps saveSkillFileContent', () => {beforeEach(() => {@@ -118,29 +132,53 @@ describe('skillDeps saveSkillFileContent', () => {expect(mockEditWorkspaceFile).toHaveBeenCalledWith({ path: 'src/app.ts' });});- it('cleans up the uploaded object when metadata upsert returns no row', async () => {- mockDb.upsertSkillFile.mockResolvedValue(null);-- await expect(- getSkillToolDeps().saveSkillFileContent({- req: {- user: { id: 'user-1', _id: 'user-1' },- config: {},- },- skillId: 'skill-1',- relativePath: 'references/template.html',- content: '<html></html>',- mimeType: 'text/html',- }),- ).rejects.toMatchObject({ code: 'SKILL_FILE_UPSERT_NOT_FOUND' });-- expect(mockDeleteFile).toHaveBeenCalledWith(- expect.objectContaining({ user: expect.objectContaining({ id: 'user-1' }) }),- {- filepath: 'https://files.example.test/uploads/file.txt',- user: 'user-1',- tenantId: 'tenant-1',- },- );+ it('wires the typed saver to the existing database and storage strategies', async () => {+ expect(mockSaverDeps.getSkillFileByPath).toBe(mockDb.getSkillFileByPath);+ expect(mockSaverDeps.upsertSkillFile).toBe(mockDb.upsertSkillFile);+ expect(mockSaverDeps.getStrategyFunctions).toBeDefined();+ expect(mockManagementSaverDeps).toBe(mockSaverDeps);+ const req = { user: { id: 'user-1' }, config: {} };+ const storage = mockSaverDeps.resolveStorage(req, { isImage: false });+ expect(storage).toEqual({ source: 's3', saveBuffer: mockSaveBuffer });+ expect(mockGetFileStrategy).toHaveBeenCalledWith(req.config, {+ context: 'skill_file',+ isImage: false,+ });++ const params = {+ req,+ skillId: 'skill-1',+ relativePath: 'references/template.html',+ content: '<html></html>',+ mimeType: 'text/html',+ expectedFileId: 'revision-1',+ createOnly: false,+ };+ mockSaveSkillFileContent.mockResolvedValue({ bytes: 13, relativePath: params.relativePath });+ await expect(getSkillToolDeps().saveSkillFileContent(params)).resolves.toEqual({+ bytes: 13,+ relativePath: params.relativePath,+ });+ expect(mockSaveSkillFileContent).toHaveBeenCalledWith(params);+ });++ it('uses an independent management saver for existing content-only PUT requests', async () => {+ const params = {+ req: { user: { id: 'user-1' } },+ skillId: 'skill-1',+ relativePath: 'references/template.html',+ content: '<html></html>',+ mimeType: 'text/plain',+ };+ mockSaveSkillManagementFileContent.mockResolvedValue({+ bytes: 13,+ relativePath: params.relativePath,+ });+ await expect(getSkillManagementFileSaver()(params)).resolves.toEqual({+ bytes: 13,+ relativePath: params.relativePath,+ });+ expect(mockSaveSkillManagementFileContent).toHaveBeenCalledWith(params);+ expect(mockSaveSkillFileContent).not.toHaveBeenCalled();});});diff --git a/client/src/components/Skills/display/SkillFileViewer.tsx b/client/src/components/Skills/display/SkillFileViewer.tsxindex ebac6b94ce..b753816d00 100644--- a/client/src/components/Skills/display/SkillFileViewer.tsx+++ b/client/src/components/Skills/display/SkillFileViewer.tsx@@ -2,26 +2,36 @@ import React, { memo, useMemo, useState, useCallback, useRef } from 'react';import { Copy, Check } from 'lucide';import { useNavigate } from 'react-router-dom';import { apiBaseUrl } from 'librechat-data-provider';-import { ArrowLeft, FileText, FileQuestion } from 'lucide-react';-import { Spinner, MorphIcon, TooltipAnchor, useToastContext } from '@librechat/client';+import { ArrowLeft, FileText, FileQuestion, Pencil } from 'lucide-react';+import { Button, Spinner, MorphIcon, TooltipAnchor, useToastContext } from '@librechat/client';+import type { TSkill, TSkillFileContentResponse } from 'librechat-data-provider';import { useGetSkillFileContentQuery } from '~/data-provider';import SkillMarkdownRenderer from './SkillMarkdownRenderer';+import { useLocalize, useSkillPermissions } from '~/hooks';+import SkillTextEditor from './SkillTextEditor';import { parseFrontmatter } from '../utils';import ViewToggle from './ViewToggle';-import { useLocalize } from '~/hooks';interface SkillFileViewerProps {skillId: string;relativePath: string;+ skill: TSkill | undefined;}const SKILL_MD_SKIP_KEYS = new Set(['name', 'description']);-function SkillFileViewer({ skillId, relativePath }: SkillFileViewerProps) {+function SkillFileViewer({ skillId, relativePath, skill }: SkillFileViewerProps) {const navigate = useNavigate();const localize = useLocalize();const { showToast } = useToastContext();- const { data, isLoading, isError } = useGetSkillFileContentQuery(skillId, relativePath);+ const { data, isLoading, isError, isFetching, refetch } = useGetSkillFileContentQuery(+ skillId,+ relativePath,+ );+ const permissions = useSkillPermissions(skill);+ const [editingFile, setEditingFile] = useState<+ (TSkillFileContentResponse & { content: string }) | null+ >(null);const [viewMode, setViewMode] = useState<'rendered' | 'source'>('rendered');const [isCopied, setIsCopied] = useState(false);const copyTimeout = useRef<NodeJS.Timeout | null>(null);@@ -30,6 +40,10 @@ function SkillFileViewer({ skillId, relativePath }: SkillFileViewerProps) {const isImage = data?.mimeType?.startsWith('image/') ?? false;const isSkillMd = relativePath === 'SKILL.md';const isText = data != null && !data.isBinary && data.content != null;+ const isEditing = editingFile != null;+ const canEdit = skill?.source === 'inline' && !permissions.isLoading && permissions.canEdit;+ // Older servers do not support conditional writes. Keep their sub-files read-only.+ const canEditFile = canEdit && data != null && (isSkillMd || !!data.fileId);const rawUrl = useMemo(() =>@@ -80,8 +94,29 @@ function SkillFileViewer({ skillId, relativePath }: SkillFileViewerProps) {{/* Actions — right side */}<div className="flex shrink-0 items-center gap-1">+ {canEditFile && !isEditing && !isLoading && (isSkillMd || isText) && (+ <TooltipAnchor+ description={localize('com_ui_edit')}+ render={+ <button+ type="button"+ onClick={() => {+ if (isSkillMd) {+ navigate(`/skills/${skillId}/edit`);+ } else if (data?.content != null) {+ setEditingFile({ ...data, content: data.content });+ }+ }}+ className="rounded-md p-1 text-text-secondary transition-colors hover:bg-surface-hover hover:text-text-primary"+ aria-label={localize('com_ui_edit')}+ >+ <Pencil className="size-4" />+ </button>+ }+ />+ )}{/* Copy (text files only) */}- {isText && (+ {!isEditing && isText && (<TooltipAnchordescription={isCopied ? localize('com_ui_copied') : localize('com_ui_copy')}render={@@ -98,96 +133,118 @@ function SkillFileViewer({ skillId, relativePath }: SkillFileViewerProps) {)}{/* View toggle (markdown only) */}- {isMarkdown && isText && <ViewToggle viewMode={viewMode} setViewMode={setViewMode} />}+ {!isEditing && isMarkdown && isText && (+ <ViewToggle viewMode={viewMode} setViewMode={setViewMode} />+ )}</div></div>{/* Content — fills remaining space */}- <div className="flex-1 overflow-y-auto px-5 py-4">- {isLoading && (- <div className="flex items-center justify-center py-12">- <Spinner className="size-6 text-text-secondary" />- </div>- )}-- {isError && (- <div className="flex flex-col items-center justify-center gap-2 py-12 text-text-secondary">- <FileQuestion className="size-8" />- <p className="text-sm">{localize('com_ui_skill_file_load_error')}</p>- </div>- )}-- {data && !isLoading && !isError && (+ <div className="min-h-0 flex-1 overflow-y-auto px-5 py-4">+ {editingFile ? (+ <SkillTextEditor+ skillId={skillId}+ relativePath={relativePath}+ file={editingFile}+ canEdit={canEditFile}+ onClose={() => setEditingFile(null)}+ />+ ) : (<>- {data.isBinary && isImage && (- <img- src={rawUrl}- alt={data.filename}- className="max-h-[600px] max-w-full rounded-lg object-contain"- />+ {isLoading && (+ <div className="flex items-center justify-center py-12">+ <Spinner className="size-6 text-text-secondary" />+ </div>)}- {data.isBinary && !isImage && (+ {(isError || data === null) && !data && (<div className="flex flex-col items-center justify-center gap-2 py-12 text-text-secondary"><FileQuestion className="size-8" />- <p className="text-sm">{localize('com_ui_skill_file_binary')}</p>- <a- href={rawUrl}- download- className="text-sm text-text-primary underline hover:no-underline"+ <p className="text-sm">{localize('com_ui_skill_file_load_error')}</p>+ <Button+ type="button"+ variant="outline"+ onClick={() => void refetch()}+ disabled={isFetching}>- {localize('com_ui_skill_file_download')}- </a>+ {localize('com_ui_retry')}+ </Button></div>)}- {/* Markdown — frontmatter grid + rendered/source body */}- {isText && isMarkdown && parsed && (+ {data && !isLoading && (<>- {viewMode === 'rendered' && parsed.fields.length > 0 && (- <div className="mb-3 grid grid-cols-[max-content_1fr] items-baseline gap-x-8 gap-y-2">- {parsed.fields.map(({ key, value }) => (- <React.Fragment key={key}>- <span className="text-xs capitalize text-text-secondary">{key}</span>- <span className="text-sm text-text-primary">{value}</span>- </React.Fragment>- ))}+ {data.isBinary && isImage && (+ <img+ src={rawUrl}+ alt={data.filename}+ className="max-h-[600px] max-w-full rounded-lg object-contain"+ />+ )}++ {data.isBinary && !isImage && (+ <div className="flex flex-col items-center justify-center gap-2 py-12 text-text-secondary">+ <FileQuestion className="size-8" />+ <p className="text-sm">{localize('com_ui_skill_file_binary')}</p>+ <a+ href={rawUrl}+ download+ className="text-sm text-text-primary underline hover:no-underline"+ >+ {localize('com_ui_skill_file_download')}+ </a></div>)}- {viewMode === 'rendered' ? (- <SkillMarkdownRenderer- content={parsed.body}- skillId={skillId}- currentFilePath={relativePath}- />- ) : (++ {/* Markdown — frontmatter grid + rendered/source body */}+ {isText && isMarkdown && parsed && (+ <>+ {viewMode === 'rendered' && parsed.fields.length > 0 && (+ <div className="mb-3 grid grid-cols-[max-content_1fr] items-baseline gap-x-8 gap-y-2">+ {parsed.fields.map(({ key, value }) => (+ <React.Fragment key={key}>+ <span className="text-xs capitalize text-text-secondary">{key}</span>+ <span className="text-sm text-text-primary">{value}</span>+ </React.Fragment>+ ))}+ </div>+ )}+ {viewMode === 'rendered' ? (+ <SkillMarkdownRenderer+ content={parsed.body}+ skillId={skillId}+ currentFilePath={relativePath}+ />+ ) : (+ <pre className="whitespace-pre-wrap font-mono text-sm leading-relaxed text-text-primary">+ {data.content}+ </pre>+ )}+ </>+ )}++ {/* Non-markdown text */}+ {isText && !isMarkdown && (<pre className="whitespace-pre-wrap font-mono text-sm leading-relaxed text-text-primary">{data.content}</pre>)}- </>- )}- {/* Non-markdown text */}- {isText && !isMarkdown && (- <pre className="whitespace-pre-wrap font-mono text-sm leading-relaxed text-text-primary">- {data.content}- </pre>- )}-- {/* Text file too large for JSON response — offer download */}- {!data.isBinary && data.content == null && (- <div className="flex flex-col items-center justify-center gap-2 py-12 text-text-secondary">- <FileText className="size-8" />- <p className="text-sm">{localize('com_ui_skill_file_download')}</p>- <a- href={rawUrl}- download- className="text-sm text-text-primary underline hover:no-underline"- >- {localize('com_ui_skill_file_download')}- </a>- </div>+ {/* Text file too large for JSON response — offer download */}+ {!data.isBinary && data.content == null && (+ <div className="flex flex-col items-center justify-center gap-2 py-12 text-text-secondary">+ <FileText className="size-8" />+ <p className="text-sm">{localize('com_ui_skill_file_download')}</p>+ <a+ href={rawUrl}+ download+ className="text-sm text-text-primary underline hover:no-underline"+ >+ {localize('com_ui_skill_file_download')}+ </a>+ </div>+ )}+ </>)}</>)}diff --git a/client/src/components/Skills/display/SkillTextEditor.tsx b/client/src/components/Skills/display/SkillTextEditor.tsxnew file mode 100644index 0000000000..860cb6f788--- /dev/null+++ b/client/src/components/Skills/display/SkillTextEditor.tsx@@ -0,0 +1,118 @@+import { useState } from 'react';+import { QueryKeys } from 'librechat-data-provider';+import { useQueryClient } from '@tanstack/react-query';+import { Button, Textarea, useToastContext } from '@librechat/client';+import type { TSkillFileContentResponse } from 'librechat-data-provider';+import { useUploadSkillFileMutation } from '~/data-provider';+import { useLocalize } from '~/hooks';++interface SkillTextEditorProps {+ skillId: string;+ relativePath: string;+ file: TSkillFileContentResponse & { content: string };+ canEdit: boolean;+ onClose: () => void;+}++export default function SkillTextEditor({+ skillId,+ relativePath,+ file,+ canEdit,+ onClose,+}: SkillTextEditorProps) {+ const localize = useLocalize();+ const { showToast } = useToastContext();+ const queryClient = useQueryClient();+ const [content, setContent] = useState(file.content);+ const [conflict, setConflict] = useState(false);++ const upload = useUploadSkillFileMutation({+ onSuccess: (saved) => {+ queryClient.setQueryData<TSkillFileContentResponse | null>(+ [QueryKeys.skillFileContent, skillId, relativePath],+ {+ ...file,+ content,+ fileId: saved.file_id,+ bytes: new Blob([content]).size,+ filename: saved.filename,+ mimeType: saved.mimeType,+ isBinary: false,+ },+ );+ showToast({+ status: 'success',+ message: localize('com_ui_edited_file', { 0: file.filename }),+ });+ onClose();+ },+ onError: (error: unknown) => {+ const isConflict = (error as { response?: { status?: number } })?.response?.status === 409;+ setConflict(isConflict);+ if (isConflict) {+ queryClient.invalidateQueries([QueryKeys.skillFileContent, skillId, relativePath]);+ }+ showToast({+ status: 'error',+ message: localize(+ isConflict ? 'com_ui_skill_file_conflict' : 'com_ui_skill_file_save_error',+ ),+ });+ },+ });++ const save = () => {+ if (!canEdit || !file.fileId || conflict || upload.isLoading || content === file.content) {+ return;+ }+ const formData = new FormData();+ formData.append('relativePath', relativePath);+ formData.append('expectedFileId', file.fileId);+ formData.append('file', new File([content], file.filename, { type: file.mimeType }));+ upload.mutate({ skillId, formData });+ };++ return (+ <div className="flex h-full min-h-0 flex-col gap-3">+ <Textarea+ value={content}+ onChange={(event) => setContent(event.target.value)}+ onKeyDown={(event) => {+ if ((event.ctrlKey || event.metaKey) && event.key === 's') {+ event.preventDefault();+ save();+ }+ }}+ disabled={upload.isLoading}+ spellCheck={false}+ aria-label={`${localize('com_ui_edit')} ${file.filename}`}+ className="min-h-0 flex-1 resize-none font-mono text-sm text-text-primary"+ />+ {upload.isError && (+ <p role="alert" className="text-sm text-text-destructive">+ {localize(conflict ? 'com_ui_skill_file_conflict' : 'com_ui_skill_file_save_error')}+ </p>+ )}+ {!canEdit && (+ <p role="note" className="text-sm text-text-secondary">+ {localize('com_ui_skill_no_edit_permission')}+ </p>+ )}+ <div className="flex justify-end gap-2">+ <Button type="button" variant="outline" onClick={onClose} disabled={upload.isLoading}>+ {localize('com_ui_cancel')}+ </Button>+ <Button+ type="button"+ onClick={save}+ disabled={+ !canEdit || !file.fileId || conflict || upload.isLoading || content === file.content+ }+ >+ {upload.isLoading ? localize('com_ui_saving') : localize('com_ui_save')}+ </Button>+ </div>+ </div>+ );+}diff --git a/client/src/components/Skills/display/__tests__/SkillFileViewer.spec.tsx b/client/src/components/Skills/display/__tests__/SkillFileViewer.spec.tsxnew file mode 100644index 0000000000..3be38151a1--- /dev/null+++ b/client/src/components/Skills/display/__tests__/SkillFileViewer.spec.tsx@@ -0,0 +1,699 @@+import React from 'react';+import axios from 'axios';+import { QueryKeys } from 'librechat-data-provider';+import { MemoryRouter, useLocation } from 'react-router-dom';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';+import type { TSkill } from 'librechat-data-provider';+import type { AxiosResponse } from 'axios';+import SkillFileViewer from '../SkillFileViewer';++const mockShowToast = jest.fn();+let mockCanEdit = true;++jest.mock('~/data-provider', () => ({+ useGetSkillFileContentQuery: jest.requireActual('~/data-provider/Skills/queries')+ .useGetSkillFileContentQuery,+ useUploadSkillFileMutation: jest.requireActual('~/data-provider/Skills/mutations')+ .useUploadSkillFileMutation,+}));++jest.mock('~/hooks', () => ({+ useLocalize: () => (key: string, values?: Record<number, string>) =>+ key === 'com_ui_edited_file' ? `Edited ${values?.[0]}` : key,+ useSkillPermissions: () => ({ isLoading: false, canEdit: mockCanEdit }),+}));++jest.mock('@librechat/client', () => ({+ Button: ({+ children,+ variant: _variant,+ ...props+ }: React.ButtonHTMLAttributes<HTMLButtonElement> & { variant?: string }) => (+ <button {...props}>{children}</button>+ ),+ Textarea: (props: React.TextareaHTMLAttributes<HTMLTextAreaElement>) => <textarea {...props} />,+ Spinner: () => <span data-testid="spinner" />,+ MorphIcon: () => <span />,+ TooltipAnchor: ({ render: content }: { render: React.ReactNode }) => content,+ useToastContext: () => ({ showToast: mockShowToast }),+}));++jest.mock('../SkillMarkdownRenderer', () => ({+ __esModule: true,+ default: ({ content }: { content: string }) => <pre>{content}</pre>,+}));++jest.mock('../ViewToggle', () => ({+ __esModule: true,+ default: () => <span />,+}));++const skill = { _id: 'skill-id', name: 'example', author: 'user-id', source: 'inline' } as TSkill;+const filePath = 'references/queries.md';++function Location() {+ const location = useLocation();+ return <output data-testid="location">{location.pathname}</output>;+}++function renderViewer(+ path = filePath,+ selectedSkill = skill,+ queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ }),+) {+ const view = render(+ <QueryClientProvider client={queryClient}>+ <MemoryRouter initialEntries={['/skills/skill-id']}>+ <SkillFileViewer skill={selectedSkill} skillId={skill._id} relativePath={path} />+ <Location />+ </MemoryRouter>+ </QueryClientProvider>,+ );+ return { ...view, queryClient };+}++function readFile(file: File): Promise<string> {+ return new Promise((resolve, reject) => {+ const reader = new FileReader();+ reader.onload = () => resolve(String(reader.result));+ reader.onerror = () => reject(reader.error);+ reader.readAsText(file);+ });+}++describe('skill file editing', () => {+ beforeEach(() => {+ mockCanEdit = true;+ mockShowToast.mockClear();+ });++ it('round-trips a nested text file via the existing read and multipart replacement endpoints', async () => {+ let persisted = 'original text';+ const get = jest.spyOn(axios, 'get').mockImplementation(async (url) => {+ expect(url).toBe(`/api/skills/skill-id/files/${encodeURIComponent(filePath)}`);+ return {+ data: {+ content: persisted,+ fileId: 'revision-1',+ file_id: 'revision-2',+ filename: 'queries.md',+ relativePath: filePath,+ mimeType: 'text/markdown',+ isBinary: false,+ bytes: persisted.length,+ },+ } as AxiosResponse;+ });+ const post = jest.spyOn(axios, 'post').mockImplementation(async (url, body) => {+ expect(url).toBe(`/api/skills/skill-id/files/${encodeURIComponent(filePath)}`);+ expect(body).toBeInstanceOf(FormData);+ const formData = body as FormData;+ expect(formData.get('relativePath')).toBe(filePath);+ expect(formData.get('expectedFileId')).toBe('revision-1');+ const file = formData.get('file');+ expect(file).toBeInstanceOf(File);+ if (!(file instanceof File)) {+ throw new Error('Expected an uploaded file');+ }+ expect(file.name).toBe('queries.md');+ expect(file.type).toBe('text/markdown');+ persisted = await readFile(file);+ return {+ data: {+ relativePath: filePath,+ fileId: 'revision-1',+ file_id: 'revision-2',+ filename: file.name,+ mimeType: file.type,+ },+ } as AxiosResponse;+ });+ const first = renderViewer();++ await screen.findByText('original text');+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_edit' }));+ const textarea = screen.getByRole('textbox', { name: 'com_ui_edit queries.md' });+ expect(textarea).toHaveValue('original text');+ fireEvent.change(textarea, { target: { value: 'persisted text' } });+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_save' }));++ await waitFor(() => expect(persisted).toBe('persisted text'));+ await screen.findByText('persisted text');+ expect(mockShowToast).toHaveBeenCalledWith({ status: 'success', message: 'Edited queries.md' });+ first.unmount();+ first.queryClient.clear();++ const readsBeforeReload = get.mock.calls.length;+ const second = renderViewer();+ await screen.findByText('persisted text');+ expect(get).toHaveBeenCalledTimes(readsBeforeReload + 1);+ expect(post).toHaveBeenCalledTimes(1);+ second.queryClient.clear();+ });++ it('keeps the draft and shows an error when upload fails, then allows retry and cancel', async () => {+ let persisted = 'before';+ jest.spyOn(axios, 'get').mockImplementation(+ async () =>+ ({+ data: {+ content: persisted,+ fileId: 'revision-1',+ file_id: 'revision-2',+ filename: 'queries.md',+ relativePath: filePath,+ mimeType: 'text/markdown',+ isBinary: false,+ bytes: persisted.length,+ },+ }) as AxiosResponse,+ );+ const post = jest+ .spyOn(axios, 'post')+ .mockRejectedValueOnce(new Error('connection lost'))+ .mockImplementationOnce(async (_url, body) => {+ const file = (body as FormData).get('file');+ if (!(file instanceof File)) {+ throw new Error('Expected an uploaded file');+ }+ persisted = await readFile(file);+ return {+ data: {+ relativePath: filePath,+ fileId: 'revision-1',+ file_id: 'revision-2',+ filename: file.name,+ mimeType: file.type,+ },+ } as AxiosResponse;+ });+ const view = renderViewer();+ await screen.findByText('before');+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_edit' }));+ fireEvent.change(screen.getByRole('textbox'), { target: { value: 'after' } });+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_save' }));++ expect(await screen.findByRole('alert')).toHaveTextContent('com_ui_skill_file_save_error');+ expect(screen.getByRole('textbox')).toHaveValue('after');+ expect(screen.getByRole('button', { name: 'com_ui_save' })).toBeEnabled();+ expect(persisted).toBe('before');+ expect(mockShowToast).toHaveBeenCalledWith({+ status: 'error',+ message: 'com_ui_skill_file_save_error',+ });++ fireEvent.click(screen.getByRole('button', { name: 'com_ui_save' }));+ await waitFor(() => expect(persisted).toBe('after'));+ await screen.findByText('after');+ expect(post).toHaveBeenCalledTimes(2);++ fireEvent.click(screen.getByRole('button', { name: 'com_ui_edit' }));+ fireEvent.change(screen.getByRole('textbox'), { target: { value: 'unsaved' } });+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_cancel' }));+ expect(screen.queryByRole('textbox')).not.toBeInTheDocument();+ expect(persisted).toBe('after');+ expect(post).toHaveBeenCalledTimes(2);+ view.queryClient.clear();+ });++ it.each([+ ['read-only permissions', false, 'text/markdown', false, 'visible'],+ ['binary content', true, 'image/png', true, undefined],+ ['oversized text without JSON content', true, 'text/plain', false, undefined],+ ])('hides editing for %s', async (_case, allowed, mimeType, isBinary, content) => {+ mockCanEdit = allowed;+ jest.spyOn(axios, 'get').mockResolvedValue({+ data: {+ content,+ fileId: 'revision-1',+ file_id: 'revision-2',+ filename: 'queries.md',+ relativePath: filePath,+ mimeType,+ isBinary,+ bytes: 12,+ },+ });+ const view = renderViewer();+ await screen.findByText('queries.md');+ await waitFor(() => expect(screen.queryByTestId('spinner')).not.toBeInTheDocument());+ expect(screen.queryByRole('button', { name: 'com_ui_edit' })).not.toBeInTheDocument();+ view.queryClient.clear();+ });++ it('can edit an empty text file using the keyboard shortcut', async () => {+ jest.spyOn(axios, 'get').mockResolvedValue({+ data: {+ content: '',+ fileId: 'revision-1',+ file_id: 'revision-2',+ filename: 'empty.sh',+ relativePath: 'scripts/empty.sh',+ mimeType: 'text/plain',+ isBinary: false,+ bytes: 0,+ },+ });+ const post = jest.spyOn(axios, 'post').mockResolvedValue({+ data: {+ relativePath: 'scripts/empty.sh',+ fileId: 'revision-1',+ file_id: 'revision-2',+ filename: 'empty.sh',+ mimeType: 'text/plain',+ },+ });+ const view = renderViewer('scripts/empty.sh');+ fireEvent.click(await screen.findByRole('button', { name: 'com_ui_edit' }));+ const textarea = screen.getByRole('textbox', { name: 'com_ui_edit empty.sh' });+ expect(textarea).toHaveValue('');+ fireEvent.change(textarea, { target: { value: 'echo ready' } });+ fireEvent.keyDown(textarea, { key: 's', ctrlKey: true });+ await waitFor(() => expect(post).toHaveBeenCalledTimes(1));+ expect((post.mock.calls[0][1] as FormData).get('relativePath')).toBe('scripts/empty.sh');+ view.queryClient.clear();+ });++ it('keeps an in-progress draft but disables Save when edit access is lost', async () => {+ jest.spyOn(axios, 'get').mockResolvedValue({+ data: {+ content: 'old content',+ fileId: 'revision-1',+ file_id: 'revision-2',+ filename: 'queries.md',+ relativePath: filePath,+ mimeType: 'text/markdown',+ isBinary: false,+ bytes: 11,+ },+ });+ const post = jest.spyOn(axios, 'post');+ const view = renderViewer();+ await screen.findByText('old content');+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_edit' }));+ fireEvent.change(screen.getByRole('textbox'), { target: { value: 'unsaved draft' } });+ mockCanEdit = false;+ view.queryClient.setQueryData([QueryKeys.skillFileContent, skill._id, filePath], {+ content: 'remote revision',+ fileId: 'revision-1',+ file_id: 'revision-2',+ filename: 'queries.md',+ relativePath: filePath,+ mimeType: 'text/markdown',+ isBinary: false,+ bytes: 15,+ });++ await screen.findByRole('note');+ expect(screen.getByRole('textbox')).toHaveValue('unsaved draft');+ expect(screen.getByRole('button', { name: 'com_ui_save' })).toBeDisabled();+ fireEvent.keyDown(screen.getByRole('textbox'), { key: 's', ctrlKey: true });+ expect(post).not.toHaveBeenCalled();+ view.queryClient.clear();+ });++ it.each([undefined, 500, 503])(+ 'keeps confirmed content visible if verification fails transiently (%s)',+ async (status) => {+ jest+ .spyOn(axios, 'get')+ .mockResolvedValueOnce({+ data: {+ fileId: 'revision-1',+ content: 'original',+ filename: 'queries.md',+ relativePath: filePath,+ mimeType: 'text/markdown',+ isBinary: false,+ bytes: 8,+ },+ })+ .mockRejectedValue(status ? { response: { status } } : new Error('verification offline'));+ jest.spyOn(axios, 'post').mockResolvedValue({+ data: {+ file_id: 'revision-2',+ filename: 'queries.md',+ relativePath: filePath,+ mimeType: 'text/markdown',+ },+ });+ const view = renderViewer();+ fireEvent.click(await screen.findByRole('button', { name: 'com_ui_edit' }));+ fireEvent.change(screen.getByRole('textbox'), { target: { value: 'confirmed save' } });+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_save' }));+ await waitFor(() =>+ expect(+ view.queryClient.getQueryState([QueryKeys.skillFileContent, skill._id, filePath])?.status,+ ).toBe('error'),+ );+ expect(screen.getByText('confirmed save')).toBeVisible();+ expect(screen.queryByText('com_ui_skill_file_load_error')).not.toBeInTheDocument();+ view.queryClient.clear();+ },+ );++ it('publishes a confirmed save even if an earlier reread cleared the cached content while saving', async () => {+ jest+ .spyOn(axios, 'get')+ .mockResolvedValueOnce({+ data: {+ fileId: 'revision-1',+ content: 'before',+ filename: 'queries.md',+ relativePath: filePath,+ mimeType: 'text/markdown',+ isBinary: false,+ bytes: 6,+ },+ })+ .mockRejectedValue({ response: { status: 503 } });+ let acknowledge!: (response: AxiosResponse) => void;+ const post = jest.spyOn(axios, 'post').mockImplementation(+ () =>+ new Promise((resolve) => {+ acknowledge = resolve;+ }),+ );+ const view = renderViewer();+ fireEvent.click(await screen.findByRole('button', { name: 'com_ui_edit' }));+ fireEvent.change(screen.getByRole('textbox'), { target: { value: 'confirmed content' } });+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_save' }));+ await waitFor(() => expect(post).toHaveBeenCalledTimes(1));+ act(() => {+ view.queryClient.setQueryData([QueryKeys.skillFileContent, skill._id, filePath], null);+ });+ await act(async () => {+ acknowledge({+ data: {+ file_id: 'revision-2',+ filename: 'queries.md',+ mimeType: 'text/markdown',+ relativePath: filePath,+ },+ } as AxiosResponse);+ });+ await screen.findByText('confirmed content');+ await waitFor(() =>+ expect(+ view.queryClient.getQueryState([QueryKeys.skillFileContent, skill._id, filePath])?.status,+ ).toBe('error'),+ );+ expect(+ view.queryClient.getQueryData([QueryKeys.skillFileContent, skill._id, filePath]),+ ).toMatchObject({ fileId: 'revision-2', content: 'confirmed content' });+ view.unmount();+ view.queryClient.clear();+ });++ it('ignores a delayed terminal reread that began before a confirmed save', async () => {+ let rejectOldRead!: (error: unknown) => void;+ const get = jest+ .spyOn(axios, 'get')+ .mockResolvedValueOnce({+ data: {+ fileId: 'revision-1',+ content: 'before',+ filename: 'queries.md',+ relativePath: filePath,+ mimeType: 'text/markdown',+ isBinary: false,+ bytes: 6,+ },+ })+ .mockImplementationOnce(+ () =>+ new Promise((_resolve, reject) => {+ rejectOldRead = reject;+ }),+ )+ .mockRejectedValue({ response: { status: 503 } });+ jest.spyOn(axios, 'post').mockResolvedValue({+ data: {+ file_id: 'revision-2',+ filename: 'queries.md',+ mimeType: 'text/markdown',+ relativePath: filePath,+ },+ });+ const view = renderViewer();+ fireEvent.click(await screen.findByRole('button', { name: 'com_ui_edit' }));+ act(() => {+ void view.queryClient.invalidateQueries([QueryKeys.skillFileContent, skill._id, filePath]);+ });+ await waitFor(() => expect(get).toHaveBeenCalledTimes(2));+ fireEvent.change(screen.getByRole('textbox'), { target: { value: 'confirmed content' } });+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_save' }));+ await screen.findByText('confirmed content');+ await waitFor(() => expect(view.queryClient.isFetching()).toBe(0));+ await act(async () => {+ rejectOldRead({ response: { status: 404 } });+ });+ expect(screen.getByText('confirmed content')).toBeVisible();+ expect(+ view.queryClient.getQueryData([QueryKeys.skillFileContent, skill._id, filePath]),+ ).toMatchObject({ fileId: 'revision-2', content: 'confirmed content' });+ view.unmount();+ view.queryClient.clear();+ });++ it('preserves a conflicting draft and does not allow a blind retry', async () => {+ jest.spyOn(axios, 'get').mockResolvedValue({+ data: {+ fileId: 'revision-1',+ content: 'before',+ filename: 'queries.md',+ relativePath: filePath,+ mimeType: 'text/markdown',+ isBinary: false,+ bytes: 6,+ },+ });+ const post = jest.spyOn(axios, 'post').mockRejectedValue({ response: { status: 409 } });+ const view = renderViewer();+ fireEvent.click(await screen.findByRole('button', { name: 'com_ui_edit' }));+ fireEvent.change(screen.getByRole('textbox'), { target: { value: 'stale draft' } });+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_save' }));+ expect(await screen.findByRole('alert')).toHaveTextContent('com_ui_skill_file_conflict');+ expect(screen.getByRole('textbox')).toHaveValue('stale draft');+ expect(screen.getByRole('button', { name: 'com_ui_save' })).toBeDisabled();+ fireEvent.keyDown(screen.getByRole('textbox'), { key: 's', ctrlKey: true });+ expect(post).toHaveBeenCalledTimes(1);+ view.queryClient.clear();+ });++ it.each([404, 410, 403])(+ 'discards cached content after a conflict reread returns %s without losing the draft',+ async (status) => {+ const get = jest+ .spyOn(axios, 'get')+ .mockResolvedValueOnce({+ data: {+ fileId: 'revision-1',+ content: 'deleted content',+ filename: 'queries.md',+ relativePath: filePath,+ mimeType: 'text/markdown',+ isBinary: false,+ bytes: 15,+ },+ })+ .mockRejectedValue({ response: { status } });+ const post = jest.spyOn(axios, 'post').mockRejectedValue({ response: { status: 409 } });+ const view = renderViewer();+ fireEvent.click(await screen.findByRole('button', { name: 'com_ui_edit' }));+ fireEvent.change(screen.getByRole('textbox'), { target: { value: 'keep this draft' } });+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_save' }));+ expect(await screen.findByRole('alert')).toHaveTextContent('com_ui_skill_file_conflict');+ await waitFor(() => expect(get).toHaveBeenCalledTimes(2));+ await waitFor(() => expect(view.queryClient.isFetching()).toBe(0));+ expect(screen.getByRole('textbox')).toHaveValue('keep this draft');+ expect(screen.getByRole('button', { name: 'com_ui_save' })).toBeDisabled();+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_cancel' }));++ expect(screen.queryByText('deleted content')).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'com_ui_edit' })).not.toBeInTheDocument();+ expect(screen.getByText('com_ui_skill_file_load_error')).toBeVisible();+ expect(+ view.queryClient.getQueryData([QueryKeys.skillFileContent, skill._id, filePath]),+ ).toBeNull();+ view.unmount();+ const reopened = renderViewer(filePath, skill, view.queryClient);+ await waitFor(() => expect(get).toHaveBeenCalledTimes(3));+ await waitFor(() => expect(view.queryClient.isFetching()).toBe(0));+ expect(screen.queryByText('deleted content')).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'com_ui_edit' })).not.toBeInTheDocument();+ expect(post).toHaveBeenCalledTimes(1);+ reopened.unmount();++ get.mockResolvedValue({+ data: {+ fileId: 'restored-revision',+ content: 'restored content',+ filename: 'queries.md',+ relativePath: filePath,+ mimeType: 'text/markdown',+ isBinary: false,+ bytes: 16,+ },+ });+ const restored = renderViewer(filePath, skill, view.queryClient);+ expect(await screen.findByText('restored content')).toBeVisible();+ expect(screen.getByRole('button', { name: 'com_ui_edit' })).toBeEnabled();+ expect(get).toHaveBeenCalledTimes(4);+ restored.unmount();+ view.queryClient.clear();+ },+ );++ it.each([403, 404, 410])(+ 'refetches a previously unavailable file on revisit after %s',+ async (status) => {+ const get = jest+ .spyOn(axios, 'get')+ .mockRejectedValueOnce({ response: { status } })+ .mockResolvedValue({+ data: {+ fileId: 'restored-revision',+ content: 'restored after revisit',+ filename: 'queries.md',+ relativePath: filePath,+ mimeType: 'text/markdown',+ isBinary: false,+ bytes: 22,+ },+ });+ const first = renderViewer();+ expect(await screen.findByText('com_ui_skill_file_load_error')).toBeVisible();+ expect(get).toHaveBeenCalledTimes(1);+ first.unmount();++ const second = renderViewer(filePath, skill, first.queryClient);+ expect(await screen.findByText('restored after revisit')).toBeVisible();+ expect(screen.getByRole('button', { name: 'com_ui_edit' })).toBeEnabled();+ expect(get).toHaveBeenCalledTimes(2);+ second.unmount();+ first.queryClient.clear();+ },+ );++ it('can retry a temporarily unavailable file without leaving the viewer', async () => {+ const get = jest+ .spyOn(axios, 'get')+ .mockRejectedValueOnce({ response: { status: 403 } })+ .mockRejectedValueOnce({ response: { status: 403 } })+ .mockResolvedValue({+ data: {+ fileId: 'restored-revision',+ content: 'access restored in place',+ filename: 'queries.md',+ relativePath: filePath,+ mimeType: 'text/markdown',+ isBinary: false,+ bytes: 24,+ },+ });+ const view = renderViewer();+ expect(await screen.findByText('com_ui_skill_file_load_error')).toBeVisible();+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_retry' }));+ await waitFor(() => expect(get).toHaveBeenCalledTimes(2));+ await waitFor(() => expect(screen.getByRole('button', { name: 'com_ui_retry' })).toBeEnabled());+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_retry' }));+ expect(await screen.findByText('access restored in place')).toBeVisible();+ expect(get).toHaveBeenCalledTimes(3);+ view.unmount();+ view.queryClient.clear();+ });++ it('keeps confirmed file content fresh across revisits', async () => {+ const get = jest.spyOn(axios, 'get').mockResolvedValue({+ data: {+ fileId: 'revision-1',+ content: 'confirmed text',+ filename: 'queries.md',+ relativePath: filePath,+ mimeType: 'text/markdown',+ isBinary: false,+ bytes: 14,+ },+ });+ const first = renderViewer();+ expect(await screen.findByText('confirmed text')).toBeVisible();+ first.unmount();+ const second = renderViewer(filePath, skill, first.queryClient);+ expect(screen.getByText('confirmed text')).toBeVisible();+ expect(get).toHaveBeenCalledTimes(1);+ second.unmount();+ first.queryClient.clear();+ });++ it.each(['github', 'notion'] as const)(+ 'keeps %s-managed skill files read-only even with edit permission',+ async (source) => {+ jest.spyOn(axios, 'get').mockResolvedValue({+ data: {+ fileId: 'revision-1',+ content: 'upstream text',+ filename: 'queries.md',+ relativePath: filePath,+ mimeType: 'text/markdown',+ isBinary: false,+ bytes: 13,+ },+ });+ const view = renderViewer(filePath, { ...skill, source });+ await screen.findByText('upstream text');+ expect(screen.queryByRole('button', { name: 'com_ui_edit' })).not.toBeInTheDocument();+ view.queryClient.clear();+ },+ );++ it('does not offer unprotected edits for an older server response without a revision', async () => {+ jest.spyOn(axios, 'get').mockResolvedValue({+ data: {+ content: 'legacy text',+ filename: 'queries.md',+ relativePath: filePath,+ mimeType: 'text/markdown',+ isBinary: false,+ bytes: 11,+ },+ });+ const view = renderViewer();+ await screen.findByText('legacy text');+ expect(screen.queryByRole('button', { name: 'com_ui_edit' })).not.toBeInTheDocument();+ view.queryClient.clear();+ });++ it('does not offer editing when loading a file fails', async () => {+ jest.spyOn(axios, 'get').mockRejectedValue(new Error('file read failed'));+ const view = renderViewer();+ await screen.findByText('com_ui_skill_file_load_error');+ expect(screen.queryByRole('button', { name: 'com_ui_edit' })).not.toBeInTheDocument();+ view.queryClient.clear();+ });++ it('routes SKILL.md edits to the existing skill form, never the multipart file endpoint', async () => {+ jest.spyOn(axios, 'get').mockResolvedValue({+ data: {+ content: '# Skill',+ fileId: 'revision-1',+ file_id: 'revision-2',+ filename: 'SKILL.md',+ relativePath: 'SKILL.md',+ mimeType: 'text/markdown',+ isBinary: false,+ bytes: 7,+ },+ });+ const post = jest.spyOn(axios, 'post');+ const view = renderViewer('SKILL.md');+ await screen.findByText('# Skill');+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_edit' }));+ expect(screen.getByTestId('location')).toHaveTextContent('/skills/skill-id/edit');+ expect(post).not.toHaveBeenCalled();+ view.queryClient.clear();+ });+});diff --git a/client/src/components/Skills/layouts/SkillsView.tsx b/client/src/components/Skills/layouts/SkillsView.tsxindex 405953eac8..1a838f114d 100644--- a/client/src/components/Skills/layouts/SkillsView.tsx+++ b/client/src/components/Skills/layouts/SkillsView.tsx@@ -96,7 +96,12 @@ function DetailView({ skillId }: { skillId: string }) {return (<div className="flex h-full w-full flex-col bg-presentation"><MobileSidebarToggle />- <SkillFileViewer skillId={skillId} relativePath={activeFile} />+ <SkillFileViewer+ key={`${skillId}:${activeFile}`}+ skillId={skillId}+ relativePath={activeFile}+ skill={skillQuery.data}+ /></div>);}diff --git a/client/src/components/Skills/layouts/__tests__/SkillsView.spec.tsx b/client/src/components/Skills/layouts/__tests__/SkillsView.spec.tsxindex 015ecad264..077e13c9e6 100644--- a/client/src/components/Skills/layouts/__tests__/SkillsView.spec.tsx+++ b/client/src/components/Skills/layouts/__tests__/SkillsView.spec.tsx@@ -5,6 +5,11 @@ import SkillsView from '../SkillsView';const mockUseHasAccess = jest.fn((..._args: unknown[]) => true);const mockUseMediaQuery = jest.fn((_query: string) => false);+const mockGetSkillByIdQuery = jest.fn(() => ({+ isLoading: false,+ isError: false,+ data: null as { _id: string; name: string } | null,+}));jest.mock('librechat-data-provider', () => ({PermissionTypes: { SKILLS: 'skills' },@@ -31,11 +36,7 @@ jest.mock('~/hooks', () => ({}));jest.mock('~/data-provider', () => ({- useGetSkillByIdQuery: jest.fn(() => ({- isLoading: false,- isError: false,- data: null,- })),+ useGetSkillByIdQuery: () => mockGetSkillByIdQuery(),}));jest.mock('~/components/Skills/forms', () => ({@@ -43,9 +44,13 @@ jest.mock('~/components/Skills/forms', () => ({SkillForm: () => <div data-testid="skill-form" />,}));-jest.mock('~/components/Skills/display/SkillFileViewer', () => () => (- <div data-testid="skill-file-viewer" />-));+jest.mock(+ '~/components/Skills/display/SkillFileViewer',+ () =>+ ({ skill, relativePath }: { skill?: { name: string }; relativePath: string }) => (+ <div data-testid="skill-file-viewer">{`${skill?.name}:${relativePath}`}</div>+ ),+);jest.mock('~/components/Skills/display/SkillDetail', () => () => (<div data-testid="skill-detail" />));@@ -59,6 +64,8 @@ describe('SkillsView', () => {mockUseHasAccess.mockReturnValue(true);mockUseMediaQuery.mockReset();mockUseMediaQuery.mockReturnValue(false);+ mockGetSkillByIdQuery.mockReset();+ mockGetSkillByIdQuery.mockReturnValue({ isLoading: false, isError: false, data: null });});it('renders the create skill form for /skills/new', () => {@@ -71,6 +78,23 @@ describe('SkillsView', () => {expect(screen.getByTestId('create-skill-form')).toBeInTheDocument();});+ it('passes the loaded skill and selected nested file to the live viewer', () => {+ mockGetSkillByIdQuery.mockReturnValue({+ isLoading: false,+ isError: false,+ data: { _id: 'skill-id', name: 'stored skill' },+ });+ const router = createMemoryRouter([{ path: '/skills/:skillId', element: <SkillsView /> }], {+ initialEntries: ['/skills/skill-id?file=references%2Fqueries.md'],+ });++ render(<RouterProvider router={router} />);++ expect(screen.getByTestId('skill-file-viewer')).toHaveTextContent(+ 'stored skill:references/queries.md',+ );+ });+it('renders the sidebar toggle on small screens', () => {mockUseMediaQuery.mockReturnValue(true);const router = createMemoryRouter([{ path: '/skills', element: <SkillsView /> }], {diff --git a/client/src/data-provider/Skills/__tests__/mutations.spec.tsx b/client/src/data-provider/Skills/__tests__/mutations.spec.tsxindex f75e17e6d9..92866cd5cd 100644--- a/client/src/data-provider/Skills/__tests__/mutations.spec.tsx+++ b/client/src/data-provider/Skills/__tests__/mutations.spec.tsx@@ -8,13 +8,16 @@ import {useCreateSkillMutation,useDeleteSkillMutation,useImportSkillMutation,+ useUploadSkillFileMutation,} from '../mutations';-import { useSkillsInfiniteQuery } from '../queries';+import { useSkillsInfiniteQuery, useListSkillFilesQuery } from '../queries';const mockCreateSkill = jest.fn();const mockDeleteSkill = jest.fn();const mockImportSkill = jest.fn();const mockListSkills = jest.fn();+const mockUploadSkillFile = jest.fn();+const mockListSkillFiles = jest.fn();jest.mock('librechat-data-provider', () => {const actual = jest.requireActual('librechat-data-provider');@@ -26,6 +29,8 @@ jest.mock('librechat-data-provider', () => {deleteSkill: (...args: unknown[]) => mockDeleteSkill(...args),importSkill: (...args: unknown[]) => mockImportSkill(...args),listSkills: (...args: unknown[]) => mockListSkills(...args),+ uploadSkillFile: (...args: unknown[]) => mockUploadSkillFile(...args),+ listSkillFiles: (...args: unknown[]) => mockListSkillFiles(...args),},};});@@ -225,3 +230,66 @@ describe('skill creation cache updates', () => {queryClient.clear();});});++describe('skill file replacement cache', () => {+ it('fetches the complete list when a direct-file save had no list cache', async () => {+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ const wrapper = ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ );+ const saved = { relativePath: 'references/edited.md' };+ const sibling = { relativePath: 'scripts/run.sh' };+ mockUploadSkillFile.mockResolvedValue(saved);+ mockListSkillFiles.mockResolvedValue({ files: [saved, sibling] });+ const { result, rerender } = renderHook(+ ({ enabled }) => ({+ upload: useUploadSkillFileMutation(),+ files: useListSkillFilesQuery('skill-id', { enabled }),+ }),+ { wrapper, initialProps: { enabled: false } },+ );+ await act(async () => {+ await result.current.upload.mutateAsync({ skillId: 'skill-id', formData: new FormData() });+ });+ expect(queryClient.getQueryData([QueryKeys.skillFiles, 'skill-id'])).toBeUndefined();+ rerender({ enabled: true });+ await waitFor(() => expect(result.current.files.data?.files).toEqual([saved, sibling]));+ queryClient.clear();+ });++ it('cancels stale in-flight list reads and refreshes a complete list after replacement', async () => {+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ const wrapper = ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ );+ const key = [QueryKeys.skillFiles, 'skill-id'];+ const original = { relativePath: 'references/edited.md', file_id: 'old' };+ const saved = { ...original, file_id: 'saved' };+ const sibling = { relativePath: 'scripts/run.sh' };+ queryClient.setQueryData(key, { files: [original, sibling] });+ const stale = deferred<{ files: (typeof original)[] }>();+ mockListSkillFiles+ .mockReturnValueOnce(stale.promise)+ .mockResolvedValue({ files: [saved, sibling] });+ mockUploadSkillFile.mockResolvedValue(saved);+ const { result } = renderHook(+ () => ({+ upload: useUploadSkillFileMutation(),+ files: useListSkillFilesQuery('skill-id'),+ }),+ { wrapper },+ );+ act(() => {+ void result.current.files.refetch();+ });+ await act(async () => {+ await result.current.upload.mutateAsync({ skillId: 'skill-id', formData: new FormData() });+ });+ await waitFor(() => expect(result.current.files.data?.files).toEqual([saved, sibling]));+ await act(async () => {+ stale.resolve({ files: [original] });+ });+ expect(result.current.files.data?.files).toEqual([saved, sibling]);+ queryClient.clear();+ });+});diff --git a/client/src/data-provider/Skills/mutations.ts b/client/src/data-provider/Skills/mutations.tsindex d97b54bd41..5a55ad4f05 100644--- a/client/src/data-provider/Skills/mutations.ts+++ b/client/src/data-provider/Skills/mutations.ts@@ -258,10 +258,7 @@ export const useDeleteSkillMutation = (});};-/**- * Upload a file into a skill. Stubbed in phase 1 — the backend responds 501.- * The hook is wired now so the frontend can call it once the backend is ready.- */+/** Upload or replace a file in a skill and refresh its cached contents. */export const useUploadSkillFileMutation = (options?: UploadSkillFileOptions,): UseMutationResult<TSkillFile, unknown, TUploadSkillFileVariables> => {@@ -271,17 +268,31 @@ export const useUploadSkillFileMutation = (mutationFn: ({ skillId, formData }: TUploadSkillFileVariables) =>dataService.uploadSkillFile(skillId, formData),...rest,- onSuccess: (skillFile, variables, context) => {+ onSuccess: async (skillFile, variables, context) => {+ await Promise.all([+ queryClient.cancelQueries([QueryKeys.skillFiles, variables.skillId]),+ queryClient.cancelQueries([+ QueryKeys.skillFileContent,+ variables.skillId,+ skillFile.relativePath,+ ]),+ ]);queryClient.setQueryData<TListSkillFilesResponse>([QueryKeys.skillFiles, variables.skillId],(prev) => {- if (!prev) return { files: [skillFile] };+ if (!prev) return prev;const filtered = prev.files.filter((f) => f.relativePath !== skillFile.relativePath);return { files: [...filtered, skillFile] };},);queryClient.invalidateQueries([QueryKeys.skill, variables.skillId]);if (onSuccess) onSuccess(skillFile, variables, context);+ queryClient.invalidateQueries([QueryKeys.skillFiles, variables.skillId]);+ queryClient.invalidateQueries([+ QueryKeys.skillFileContent,+ variables.skillId,+ skillFile.relativePath,+ ]);},});};diff --git a/client/src/data-provider/Skills/queries.ts b/client/src/data-provider/Skills/queries.tsindex 6046780d06..c66fa15166 100644--- a/client/src/data-provider/Skills/queries.ts+++ b/client/src/data-provider/Skills/queries.ts@@ -1,10 +1,5 @@-import { useQuery, useMutation, useInfiniteQuery, useQueryClient } from '@tanstack/react-query';import { QueryKeys, dataService } from 'librechat-data-provider';-import type {- QueryObserverResult,- UseQueryOptions,- UseInfiniteQueryOptions,-} from '@tanstack/react-query';+import { useQuery, useMutation, useInfiniteQuery, useQueryClient } from '@tanstack/react-query';import type {TSkill,TSkillListRequest,@@ -13,6 +8,11 @@ import type {TListSkillFilesResponse,TSkillFileContentResponse,} from 'librechat-data-provider';+import type {+ QueryObserverResult,+ UseQueryOptions,+ UseInfiniteQueryOptions,+} from '@tanstack/react-query';/*** Paginated skill list (single page) — use this for small lists or when you want to@@ -128,21 +128,33 @@ export const useListSkillFilesQuery = (/*** Fetch a single skill file's content. Returns cached text from the DB when* available; otherwise the backend reads from storage, caches, and returns it.- * Uses `staleTime: Infinity` because file content is cached server-side.+ * Confirmed content stays fresh until invalidated; unavailable results refetch on revisit.*/export const useGetSkillFileContentQuery = (skillId: string | null | undefined,relativePath: string | null | undefined,- config?: UseQueryOptions<TSkillFileContentResponse>,-): QueryObserverResult<TSkillFileContentResponse> => {+ config?: UseQueryOptions<TSkillFileContentResponse | null>,+): QueryObserverResult<TSkillFileContentResponse | null> => {const enabled = !!skillId && !!relativePath;- return useQuery<TSkillFileContentResponse>(+ return useQuery<TSkillFileContentResponse | null>([QueryKeys.skillFileContent, skillId, relativePath],- () => dataService.getSkillFileContent(skillId as string, relativePath as string),+ async () => {+ try {+ return await dataService.getSkillFileContent(skillId as string, relativePath as string);+ } catch (error) {+ const status = (error as { response?: { status?: number } })?.response?.status;+ // A terminal response replaces cached bytes, including on background reads.+ // Throw transient failures so React Query retains the last confirmed content.+ if (status === 404 || status === 410 || status === 403) {+ return null;+ }+ throw error;+ }+ },{refetchOnWindowFocus: false,refetchOnReconnect: false,- refetchOnMount: false,+ refetchOnMount: (query) => (query.state.data === null ? 'always' : false),retry: false,staleTime: Infinity,...config,diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.jsonindex 67b09ec258..2e17759197 100644--- a/client/src/locales/en/translation.json+++ b/client/src/locales/en/translation.json@@ -2346,6 +2346,8 @@"com_ui_skill_file_binary": "Binary file — cannot preview inline","com_ui_skill_file_download": "Download","com_ui_skill_file_load_error": "Failed to load file content",+ "com_ui_skill_file_conflict": "This file changed or was deleted since you opened it. Copy your draft, cancel, and reopen the file before editing again.",+ "com_ui_skill_file_save_error": "Could not save the file. Your changes are still in the editor.","com_ui_skill_finished": "Loaded {{0}}","com_ui_skill_instructions": "Instructions","com_ui_skill_instructions_too_long": "Instructions must be {{0}} characters or fewer",diff --git a/packages/api/src/agents/handlers.spec.ts b/packages/api/src/agents/handlers.spec.tsindex b25a137ea5..c79e694fd6 100644--- a/packages/api/src/agents/handlers.spec.ts+++ b/packages/api/src/agents/handlers.spec.ts@@ -4264,6 +4264,7 @@ describe('createToolExecuteHandler', () => {mimeType: 'text/markdown',bytes: 10,filepath: '/tmp/a.md',+ file_id: 'revision-1',source: 'local',relativePath: 'references/a.md',})),@@ -4300,6 +4301,286 @@ describe('createToolExecuteHandler', () => {);});+ it.each([+ ['edit_file', { old_text: 'hello old', new_text: 'hello new' }, 'hello new\n'],+ ['create_file', { content: 'replacement', overwrite: true }, 'replacement'],+ ] as const)(+ 'passes the revision read with the bytes to %s for an existing subfile',+ async (toolName, args, expectedContent) => {+ const saveSkillFileContent = jest.fn(async () => ({+ bytes: 11,+ relativePath: 'references/a.md',+ }));+ const handler = makeAuthoringHandler({+ getSkillByName: jest.fn(async () => ({+ _id: SKILL_ID,+ name: 'edit-skill',+ body: '# Existing',+ fileCount: 1,+ version: 1,+ })),+ getSkillFileByPath: jest.fn(async () => ({+ file_id: 'revision-1',+ content: 'hello old\n',+ isBinary: false,+ mimeType: 'text/markdown',+ bytes: 10,+ filepath: '/tmp/a.md',+ source: 'local',+ relativePath: 'references/a.md',+ })),+ saveSkillFileContent,+ });+ const [result] = await invokeHandler(handler, [+ {+ id: 'call_revision',+ name: toolName,+ args: { path: 'skills/edit-skill/references/a.md', ...args },+ },+ ]);+ expect(result.status).toBe('success');+ expect(saveSkillFileContent).toHaveBeenCalledWith(+ expect.objectContaining({+ relativePath: 'references/a.md',+ content: expectedContent,+ expectedFileId: 'revision-1',+ createOnly: false,+ }),+ );+ },+ );++ it('requires a revision before replacing an existing skill subfile', async () => {+ const saveSkillFileContent = jest.fn();+ const handler = makeAuthoringHandler({+ getSkillByName: jest.fn(async () => ({+ _id: SKILL_ID,+ name: 'edit-skill',+ body: '# Existing',+ fileCount: 1,+ version: 1,+ })),+ getSkillFileByPath: jest.fn(async () => ({+ content: 'hello old\n',+ isBinary: false,+ mimeType: 'text/markdown',+ bytes: 10,+ filepath: '/tmp/a.md',+ source: 'local',+ relativePath: 'references/a.md',+ })),+ saveSkillFileContent,+ });+ const [result] = await invokeHandler(handler, [+ {+ id: 'call_missing_revision',+ name: 'edit_file',+ args: {+ path: 'skills/edit-skill/references/a.md',+ old_text: 'hello old',+ new_text: 'hello new',+ },+ },+ ]);+ expect(result.status).toBe('error');+ expect(result.errorMessage).toContain('revision');+ expect(saveSkillFileContent).not.toHaveBeenCalled();+ });++ it('requires an absent file when create_file sees no subfile', async () => {+ const saveSkillFileContent = jest.fn(async () => ({+ bytes: 11,+ relativePath: 'references/new.md',+ }));+ const handler = makeAuthoringHandler({+ getSkillByName: jest.fn(async () => ({+ _id: SKILL_ID,+ name: 'edit-skill',+ body: '# Existing',+ fileCount: 0,+ version: 1,+ })),+ getSkillFileByPath: jest.fn(async () => null),+ saveSkillFileContent,+ });+ const [result] = await invokeHandler(handler, [+ {+ id: 'call_create_only',+ name: 'create_file',+ args: { path: 'skills/edit-skill/references/new.md', content: 'new subfile' },+ },+ ]);+ expect(result.status).toBe('success');+ expect(saveSkillFileContent).toHaveBeenCalledWith(+ expect.objectContaining({ relativePath: 'references/new.md', createOnly: true }),+ );+ });++ it('keeps the streamed file revision paired with the text before saving an edit', async () => {+ const saveSkillFileContent = jest.fn(async () => ({+ bytes: 10,+ relativePath: 'references/a.md',+ }));+ const handler = makeAuthoringHandler({+ getSkillByName: jest.fn(async () => ({+ _id: SKILL_ID,+ name: 'stream-skill',+ body: '# Existing',+ fileCount: 1,+ version: 1,+ })),+ getSkillFileByPath: jest.fn(async () => ({+ file_id: 'streamed-revision',+ isBinary: false,+ mimeType: 'text/markdown',+ bytes: 10,+ filepath: '/tmp/a.md',+ source: 'local',+ relativePath: 'references/a.md',+ })),+ getStrategyFunctions: jest.fn(() => ({+ getDownloadStream: jest.fn(async () => Readable.from([Buffer.from('hello old\n')])),+ })),+ saveSkillFileContent,+ });+ const [result] = await invokeHandler(handler, [+ {+ id: 'call_streamed_edit',+ name: 'edit_file',+ args: {+ path: 'skills/stream-skill/references/a.md',+ old_text: 'hello old',+ new_text: 'hello new',+ },+ },+ ]);+ expect(result.status).toBe('success');+ expect(saveSkillFileContent).toHaveBeenCalledWith(+ expect.objectContaining({+ content: 'hello new\n',+ expectedFileId: 'streamed-revision',+ createOnly: false,+ }),+ );+ });++ it('reports a safe conflict when Mongo rejects a revision after the agent read', async () => {+ const saveSkillFileContent = jest.fn(async () => {+ throw Object.assign(new Error('stale revision'), { code: 'SKILL_FILE_CONFLICT' });+ });+ const handler = makeAuthoringHandler({+ getSkillByName: jest.fn(async () => ({+ _id: SKILL_ID,+ name: 'edit-skill',+ body: '# Existing',+ fileCount: 1,+ version: 1,+ })),+ getSkillFileByPath: jest.fn(async () => ({+ file_id: 'revision-1',+ content: 'hello old\n',+ isBinary: false,+ mimeType: 'text/markdown',+ bytes: 10,+ filepath: '/tmp/a.md',+ source: 'local',+ relativePath: 'references/a.md',+ })),+ saveSkillFileContent,+ });+ const [result] = await invokeHandler(handler, [+ {+ id: 'call_conflict',+ name: 'edit_file',+ args: {+ path: 'skills/edit-skill/references/a.md',+ old_text: 'hello old',+ new_text: 'hello new',+ },+ },+ ]);+ expect(result.status).toBe('error');+ expect(result.errorMessage).toContain('Re-read skills/edit-skill/references/a.md and retry');+ expect(result.content).not.toContain('Updated');+ expect(saveSkillFileContent).toHaveBeenCalledWith(+ expect.objectContaining({ expectedFileId: 'revision-1', createOnly: false }),+ );+ });++ it.each(['github', 'notion'] as const)(+ 'does not allow an agent to modify a %s-managed skill file',+ async (source) => {+ const saveSkillFileContent = jest.fn();+ const handler = makeAuthoringHandler({+ getSkillByName: jest.fn(async () => ({+ _id: SKILL_ID,+ name: 'managed-skill',+ source,+ body: '# Managed',+ fileCount: 1,+ version: 1,+ })),+ getSkillFileByPath: jest.fn(async () => ({+ file_id: 'revision-1',+ content: 'upstream text\n',+ isBinary: false,+ mimeType: 'text/markdown',+ bytes: 14,+ filepath: '/tmp/managed.md',+ source: 'local',+ relativePath: 'references/a.md',+ })),+ saveSkillFileContent,+ });+ const [result] = await invokeHandler(handler, [+ {+ id: 'call_managed_edit',+ name: 'edit_file',+ args: {+ path: 'skills/managed-skill/references/a.md',+ old_text: 'upstream text',+ new_text: 'agent text',+ },+ },+ ]);+ expect(result.status).toBe('error');+ expect(result.errorMessage).toContain('Externally managed skill files are read-only');+ expect(saveSkillFileContent).not.toHaveBeenCalled();+ },+ );++ it('reports a newly created competing file without claiming the agent created it', async () => {+ const saveSkillFileContent = jest.fn(async () => {+ throw Object.assign(new Error('another writer created the path'), {+ code: 'SKILL_FILE_CONFLICT',+ });+ });+ const handler = makeAuthoringHandler({+ getSkillByName: jest.fn(async () => ({+ _id: SKILL_ID,+ name: 'edit-skill',+ body: '# Existing',+ fileCount: 0,+ version: 1,+ })),+ getSkillFileByPath: jest.fn(async () => null),+ saveSkillFileContent,+ });+ const [result] = await invokeHandler(handler, [+ {+ id: 'call_competing_create',+ name: 'create_file',+ args: { path: 'skills/edit-skill/references/new.md', content: 'new file' },+ },+ ]);+ expect(result.status).toBe('error');+ expect(result.errorMessage).toContain('File already exists');+ expect(result.errorMessage).toContain('overwrite: true');+ expect(saveSkillFileContent).toHaveBeenCalledWith(+ expect.objectContaining({ createOnly: true, expectedFileId: undefined }),+ );+ });+it('repairs protected bundled file text without echoing removed lines in the diff', async () => {const protectedValue = 'PROTECTED-BUNDLED-DIFF';const saveSkillFileContent = jest.fn(async () => ({@@ -4346,6 +4627,7 @@ describe('createToolExecuteHandler', () => {mimeType: 'text/markdown',bytes: protectedValue.length + 11,filepath: '/tmp/private.md',+ file_id: 'revision-1',source: 'local',relativePath: 'references/private.md',})),@@ -4390,6 +4672,7 @@ describe('createToolExecuteHandler', () => {mimeType: 'text/markdown',bytes: 10,filepath: '/tmp/a.md',+ file_id: 'revision-1',source: 'local',relativePath: 'references/a.md',})),@@ -4434,6 +4717,7 @@ describe('createToolExecuteHandler', () => {mimeType: 'text/markdown',bytes: 10,filepath: '/tmp/a.md',+ file_id: 'revision-1',source: 'local',relativePath: 'references/a.md',})),@@ -4521,6 +4805,7 @@ describe('createToolExecuteHandler', () => {mimeType: 'text/markdown',bytes: 10,filepath: '/tmp/a.md',+ file_id: 'revision-1',source: 'local',relativePath: 'references/a.md',})),@@ -4951,6 +5236,7 @@ describe('createToolExecuteHandler', () => {mimeType: 'text/markdown',bytes: 600 * 1024,filepath: '/tmp/large.md',+ file_id: 'revision-1',source: 'local',relativePath: 'references/large.md',})),@@ -5004,6 +5290,7 @@ describe('createToolExecuteHandler', () => {mimeType: 'text/markdown',bytes: Buffer.byteLength(storedContent, 'utf8'),filepath: '/tmp/a.md',+ file_id: 'revision-1',source: 'local',relativePath: 'references/a.md',})),diff --git a/packages/api/src/agents/handlers.ts b/packages/api/src/agents/handlers.tsindex 9303dfaf94..4438b0d0c4 100644--- a/packages/api/src/agents/handlers.ts+++ b/packages/api/src/agents/handlers.ts@@ -386,6 +386,7 @@ export interface ToolExecuteOptions {* prior cache entry. */version: number;fileCount: number;+ source?: 'inline' | 'github' | 'notion' | 'deployment';/** True for deployment-directory skills that are loaded in memory. */deployment?: boolean;/**@@ -420,6 +421,7 @@ export interface ToolExecuteOptions {_id: Types.ObjectId;version: number;fileCount: number;+ source?: 'inline' | 'github' | 'notion' | 'deployment';disableModelInvocation?: boolean;} | null>;/** Creates a skill from a tool-authored SKILL.md body. */@@ -481,6 +483,8 @@ export interface ToolExecuteOptions {relativePath: string;content: string;mimeType: string;+ expectedFileId?: string;+ createOnly: boolean;}) => Promise<{bytes: number;relativePath: string;@@ -535,6 +539,7 @@ export interface ToolExecuteOptions {skillId: Types.ObjectId | string,relativePath: string,) => Promise<{+ file_id?: string;content?: string;isBinary?: boolean;mimeType: string;@@ -548,6 +553,7 @@ export interface ToolExecuteOptions {skillId: Types.ObjectId | string,relativePath: string,update: { content?: string; isBinary?: boolean },+ expectedFileId?: string,) => Promise<void>;/** Reads a bounded text range from an attached worker's logical workspace. */readWorkspaceFile?: (params: {@@ -1025,12 +1031,12 @@ type MatchStatus =| { status: 'ambiguous'; strategy: string; count: number };type LoadedSkillText =- | { status: 'loaded'; content: string; bytes: number }+ | { status: 'loaded'; content: string; bytes: number; fileId?: string }| { status: 'missing' }| { status: 'error'; message: string };type ExistingSkillFile =- | { status: 'present'; oldContent?: string }+ | { status: 'present'; oldContent?: string; fileId?: string }| { status: 'missing' }| { status: 'error'; message: string };@@ -3462,6 +3468,7 @@ async function loadSkillFileTextForAuthoring({status: 'loaded',content: file.content,bytes: Buffer.byteLength(file.content, 'utf8'),+ fileId: file.file_id,};}if (file.bytes > MAX_CACHE_BYTES) {@@ -3504,7 +3511,7 @@ async function loadSkillFileTextForAuthoring({for (let i = 0; i < checkLen; i++) {if (buffer[i] === 0) {if (updateSkillFileContent) {- updateSkillFileContent(skill._id, relativePath, { isBinary: true }).catch(+ updateSkillFileContent(skill._id, relativePath, { isBinary: true }, file.file_id).catch((err: unknown) => {logAxiosError({message: '[loadSkillFileTextForAuthoring] cache write failed',@@ -3519,16 +3526,19 @@ async function loadSkillFileTextForAuthoring({const text = buffer.toString('utf-8');if (updateSkillFileContent) {- updateSkillFileContent(skill._id, relativePath, { content: text, isBinary: false }).catch(- (err: unknown) => {- logAxiosError({- message: '[loadSkillFileTextForAuthoring] cache write failed',- error: err,- });- },- );+ updateSkillFileContent(+ skill._id,+ relativePath,+ { content: text, isBinary: false },+ file.file_id,+ ).catch((err: unknown) => {+ logAxiosError({+ message: '[loadSkillFileTextForAuthoring] cache write failed',+ error: err,+ });+ });}- return { status: 'loaded', content: text, bytes: buffer.length };+ return { status: 'loaded', content: text, bytes: buffer.length, fileId: file.file_id };}async function inspectBundledSkillFileForCreate({@@ -3552,13 +3562,13 @@ async function inspectBundledSkillFileForCreate({return { status: 'missing' };}if (file.isBinary === true || file.bytes > MAX_CACHE_BYTES) {- return { status: 'present' };+ return { status: 'present', fileId: file.file_id };}if (file.content != null && file.content !== '') {- return { status: 'present', oldContent: file.content };+ return { status: 'present', oldContent: file.content, fileId: file.file_id };}if (!options.getStrategyFunctions || !req) {- return { status: 'present' };+ return { status: 'present', fileId: file.file_id };}const loaded = await loadSkillFileTextForAuthoring({@@ -3571,9 +3581,9 @@ async function inspectBundledSkillFileForCreate({return { status: 'missing' };}if (loaded.status === 'error') {- return { status: 'present' };+ return { status: 'present', fileId: file.file_id };}- return { status: 'present', oldContent: loaded.content };+ return { status: 'present', oldContent: loaded.content, fileId: loaded.fileId };}async function ensureBundledSkillVersionCurrent({@@ -3791,6 +3801,7 @@ async function writeBundledSkillFile({displayPath,content,oldContent,+ fileId,created,}: {tc: ToolCallRequest;@@ -3801,6 +3812,7 @@ async function writeBundledSkillFile({displayPath: string;content: string;oldContent?: string;+ fileId?: string;created: boolean;}): AuthoringResult {const editDenied = await ensureCanEditSkill(tc, options, req, skill._id);@@ -3810,6 +3822,15 @@ async function writeBundledSkillFile({if (!req || !options.saveSkillFileContent) {return errorResult(tc, 'Skill file writing is not configured.');}+ if (skill.source != null && skill.source !== 'inline') {+ return errorResult(tc, 'Externally managed skill files are read-only.');+ }+ if (!created && !fileId) {+ return errorResult(+ tc,+ `File revision unavailable for ${displayPath}. Re-read the file and retry.`,+ );+ }const staleDenied = await ensureBundledSkillVersionCurrent({tc,options,@@ -3846,13 +3867,27 @@ async function writeBundledSkillFile({diff = undefined;}- await options.saveSkillFileContent({- req,- skillId: skill._id,- relativePath,- content,- mimeType: guessMimeType(relativePath),- });+ try {+ await options.saveSkillFileContent({+ req,+ skillId: skill._id,+ relativePath,+ content,+ mimeType: guessMimeType(relativePath),+ expectedFileId: fileId,+ createOnly: created,+ });+ } catch (error) {+ if (error instanceof Error && 'code' in error && error.code === 'SKILL_FILE_CONFLICT') {+ return errorResult(+ tc,+ created+ ? `File already exists: ${displayPath}. Re-read it and pass overwrite: true to replace.`+ : `Skill file changed while editing. Re-read ${displayPath} and retry.`,+ );+ }+ throw error;+ }const action = created ? 'Created' : 'Updated';const summary = `${action} ${displayPath} (${content.length} chars).`;return successResult(tc, diff ? `${summary}\n\n${diff}` : summary, {@@ -4355,6 +4390,7 @@ async function handleCreateFileCall(displayPath: parsed.displayPath,content: args.content,oldContent: current.status === 'present' ? current.oldContent : undefined,+ fileId: current.status === 'present' ? current.fileId : undefined,created: current.status === 'missing',});}@@ -4482,6 +4518,7 @@ async function handleEditFileCall(displayPath: parsed.displayPath,content: edited.content,oldContent: current.content,+ fileId: current.fileId,created: false,});if (result.status === 'success') {@@ -4975,7 +5012,7 @@ async function handleReadFileCall(if (isBinary) {// Cache the binary flag (first read only)if (file.isBinary == null && updateSkillFileContent) {- updateSkillFileContent(skill._id, relativePath, { isBinary: true }).catch(+ updateSkillFileContent(skill._id, relativePath, { isBinary: true }, file.file_id).catch((err: unknown) => {logAxiosError({message: '[handleReadFileCall] cache write failed',@@ -5021,14 +5058,17 @@ async function handleReadFileCall(// Cache text on first read (skill files are immutable)if (file.content == null && updateSkillFileContent && buffer.length <= MAX_CACHE_BYTES) {- updateSkillFileContent(skill._id, relativePath, { content: text, isBinary: false }).catch(- (err: unknown) => {- logAxiosError({- message: '[handleReadFileCall] cache write failed',- error: err,- });- },- );+ updateSkillFileContent(+ skill._id,+ relativePath,+ { content: text, isBinary: false },+ file.file_id,+ ).catch((err: unknown) => {+ logAxiosError({+ message: '[handleReadFileCall] cache write failed',+ error: err,+ });+ });}if (buffer.length > MAX_READABLE_BYTES) {diff --git a/packages/api/src/skills/__tests__/deployment.test.ts b/packages/api/src/skills/__tests__/deployment.test.tsindex baf93dbcf9..10eef4cb00 100644--- a/packages/api/src/skills/__tests__/deployment.test.ts+++ b/packages/api/src/skills/__tests__/deployment.test.ts@@ -394,6 +394,18 @@ describe('createDeploymentSkillMethods', () => {const updatedFile = await methods.getSkillFileByPath?.(deploymentId, 'references/guide.txt');expect(updatedFile?.content).toBe('updated content');expect(base.updateSkillFileContent).not.toHaveBeenCalled();+ await methods.updateSkillFileContent?.(+ dbId,+ 'references/db.txt',+ { content: 'db text' },+ 'db-revision',+ );+ expect(base.updateSkillFileContent).toHaveBeenCalledWith(+ dbId,+ 'references/db.txt',+ { content: 'db text' },+ 'db-revision',+ );const codeEnvRef: CodeEnvRef = {kind: 'skill',diff --git a/packages/api/src/skills/deployment.ts b/packages/api/src/skills/deployment.tsindex 1cf18e0efc..ceee9d94bc 100644--- a/packages/api/src/skills/deployment.ts+++ b/packages/api/src/skills/deployment.ts@@ -188,6 +188,7 @@ export type DeploymentSkillBaseMethods = {skillId: SkillId,relativePath: string,update: { content?: string; isBinary?: boolean },+ expectedFileId?: string,) => Promise<void>;updateSkillFileCodeEnvIds?: (updates: Array<{ skillId: SkillId; relativePath: string; codeEnvRef: CodeEnvRef }>,@@ -604,6 +605,7 @@ export function createDeploymentSkillMethods<T extends DeploymentSkillBaseMethodskillId: SkillId,relativePath: string,update: { content?: string; isBinary?: boolean },+ expectedFileId?: string,): Promise<void> => {const deploymentFile = registry.getFileByPath(skillId, relativePath);if (deploymentFile) {@@ -616,7 +618,7 @@ export function createDeploymentSkillMethods<T extends DeploymentSkillBaseMethodreturn;}if (base.updateSkillFileContent) {- await base.updateSkillFileContent(skillId, relativePath, update);+ await base.updateSkillFileContent(skillId, relativePath, update, expectedFileId);}},updateSkillFileCodeEnvIds: async (diff --git a/packages/api/src/skills/handlers.ts b/packages/api/src/skills/handlers.tsindex 7c53c67493..c22d384c55 100644--- a/packages/api/src/skills/handlers.ts+++ b/packages/api/src/skills/handlers.ts@@ -107,6 +107,7 @@ export interface SkillsHandlersDeps {skillId: string | Types.ObjectId,relativePath: string,update: { content?: string; isBinary?: boolean },+ expectedFileId?: string,) => Promise<void>;/** Storage strategy resolver — returns stream/URL helpers keyed by source. */@@ -159,7 +160,7 @@ function serializeSkill(author: skill.author.toString(),authorName: skill.authorName,version: skill.version,- source: skill.source,+ source: skill.source ?? 'inline',sourceMetadata: serializeSourceMetadata(skill.sourceMetadata),fileCount: skill.fileCount,alwaysApply: skill.alwaysApply,@@ -187,7 +188,7 @@ function serializeSkillSummary(author: skill.author.toString(),authorName: skill.authorName,version: skill.version,- source: skill.source,+ source: skill.source ?? 'inline',sourceMetadata: serializeSourceMetadata(skill.sourceMetadata),fileCount: skill.fileCount,alwaysApply: skill.alwaysApply,@@ -756,6 +757,7 @@ export function createSkillsHandlers(deps: SkillsHandlersDeps): {}const base: Omit<TSkillFileContentResponse, 'content' | 'isBinary'> = {+ fileId: file.file_id,mimeType: file.mimeType,relativePath: file.relativePath,filename: file.filename,@@ -789,7 +791,7 @@ export function createSkillsHandlers(deps: SkillsHandlersDeps): {if (!binaryChecked && totalBytes >= 8192) {binaryChecked = true;if (isBinaryBuffer(Buffer.concat(chunks))) {- updateSkillFileContent(id, decodedPath, { isBinary: true }).catch((e) =>+ updateSkillFileContent(id, decodedPath, { isBinary: true }, file.file_id).catch((e) =>logger.error('[downloadFile] Cache write failed:', e),);if ('destroy' in stream && typeof stream.destroy === 'function') {@@ -812,7 +814,7 @@ export function createSkillsHandlers(deps: SkillsHandlersDeps): {const buffer = Buffer.concat(chunks);if (isBinaryBuffer(buffer)) {- updateSkillFileContent(id, decodedPath, { isBinary: true }).catch((e) =>+ updateSkillFileContent(id, decodedPath, { isBinary: true }, file.file_id).catch((e) =>logger.error('[downloadFile] Cache write failed:', e),);return res.status(200).json({ ...base, isBinary: true });@@ -820,9 +822,12 @@ export function createSkillsHandlers(deps: SkillsHandlersDeps): {const text = buffer.toString('utf-8');if (buffer.length <= MAX_TEXT_CACHE_BYTES) {- updateSkillFileContent(id, decodedPath, { content: text, isBinary: false }).catch((e) =>- logger.error('[downloadFile] Cache write failed:', e),- );+ updateSkillFileContent(+ id,+ decodedPath,+ { content: text, isBinary: false },+ file.file_id,+ ).catch((e) => logger.error('[downloadFile] Cache write failed:', e));}return res.status(200).json({ ...base, isBinary: false, content: text });} catch (error) {diff --git a/packages/api/src/skills/index.ts b/packages/api/src/skills/index.tsindex 706126377b..4de0b7c6ab 100644--- a/packages/api/src/skills/index.ts+++ b/packages/api/src/skills/index.ts@@ -9,3 +9,5 @@ export * from './skillStates';export * from './deployment';export * from './sync';export * from './management';+export * from './upload';+export * from './save';diff --git a/packages/api/src/skills/management.spec.ts b/packages/api/src/skills/management.spec.tsindex 685647122a..18478404a4 100644--- a/packages/api/src/skills/management.spec.ts+++ b/packages/api/src/skills/management.spec.ts@@ -342,6 +342,17 @@ it('classifies content-policy blocks as invalid input and never writes the file'expect(result.body).toMatchObject({ error: { code: 'invalid_request' } });expect(saveFile).not.toHaveBeenCalled();});+it('returns a documented 409 when another writer changes the skill file during the save', async () => {+ saveFile.mockRejectedValueOnce(+ Object.assign(new Error('private file storage revision'), { code: 'SKILL_FILE_CONFLICT' }),+ );+ const result = await request(app)+ .put(`/skills/${skillId}/files/notes.md`)+ .send({ content: 'Notes' })+ .expect(409);+ expect(result.body).toEqual({ error: { code: 'conflict', message: 'Resource conflict' } });+});+it('returns safe errors for storage failures', async () => {saveFile.mockRejectedValueOnce(new Error('secret-storage-path'));const result = await request(app)diff --git a/packages/api/src/skills/management.ts b/packages/api/src/skills/management.tsindex bbc68657b4..b209f92d44 100644--- a/packages/api/src/skills/management.ts+++ b/packages/api/src/skills/management.ts@@ -362,14 +362,21 @@ export function createSkillManagementHandlers(return sendError(res, 'invalid_request');}if (!(await admitFileWrite(req, res, deps.fileWriteLimiters ?? []))) return res;- const result = await deps.saveFile({- req: req as ServerRequest,- skillId: req.params.id,- relativePath,- content: parsed.data.content,- mimeType: 'text/plain',- });- return res.status(200).json({ relativePath: result.relativePath, bytes: result.bytes });+ try {+ const result = await deps.saveFile({+ req: req as ServerRequest,+ skillId: req.params.id,+ relativePath,+ content: parsed.data.content,+ mimeType: 'text/plain',+ });+ return res.status(200).json({ relativePath: result.relativePath, bytes: result.bytes });+ } catch (error) {+ if (error instanceof Error && 'code' in error && error.code === 'SKILL_FILE_CONFLICT') {+ return sendError(res, 'conflict');+ }+ throw error;+ }}),};}diff --git a/packages/api/src/skills/save.spec.ts b/packages/api/src/skills/save.spec.tsnew file mode 100644index 0000000000..49200d1cda--- /dev/null+++ b/packages/api/src/skills/save.spec.ts@@ -0,0 +1,230 @@+import { FileSources } from 'librechat-data-provider';+import type { SaveBufferParams } from '~/storage/types';+import { createSkillFileSaver, createSkillManagementFileSaver } from './save';++type SaverDeps = Parameters<typeof createSkillFileSaver>[0];++const existing = {+ file_id: 'initial',+ filepath: '/uploads/initial',+ source: 'local',+ author: { toString: () => 'original-owner' },+ tenantId: 'original-tenant',+ isExecutable: true,+ bytes: 8,+ relativePath: 'references/a.md',+};++function harness() {+ const saveBuffer = jest.fn(async (_input: SaveBufferParams) => '/uploads/new');+ const deleteFile = jest.fn(async () => undefined);+ const getSkillFileByPath = jest.fn(+ async (): ReturnType<SaverDeps['getSkillFileByPath']> => existing,+ );+ const upsertSkillFile = jest.fn(+ async (+ row: Parameters<SaverDeps['upsertSkillFile']>[0],+ ): ReturnType<SaverDeps['upsertSkillFile']> => ({+ ...existing,+ file_id: row.file_id,+ filepath: '/uploads/new',+ bytes: 9,+ }),+ );+ const deps = {+ getSkillFileByPath,+ upsertSkillFile,+ resolveStorage: jest.fn(() => ({ source: FileSources.local, saveBuffer })),+ getStrategyFunctions: jest.fn(() => ({ deleteFile })),+ } satisfies SaverDeps;+ const req = { user: { id: 'editor', _id: 'editor' }, config: {} } as never;+ const params = {+ req,+ skillId: 'skill-id',+ relativePath: 'references/a.md',+ content: 'new text\n',+ mimeType: 'text/markdown',+ expectedFileId: 'initial',+ createOnly: false,+ };+ const { req: request, skillId, relativePath, content, mimeType } = params;+ return {+ deps,+ params,+ managementParams: { req: request, skillId, relativePath, content, mimeType },+ saveBuffer,+ deleteFile,+ getSkillFileByPath,+ upsertSkillFile,+ save: createSkillFileSaver(deps),+ saveManagement: createSkillManagementFileSaver(deps),+ };+}++describe('management skill file saver', () => {+ it('creates a missing path with an insert-only write and no second lookup', async () => {+ const h = harness();+ h.getSkillFileByPath.mockResolvedValueOnce(null);+ await expect(h.saveManagement(h.managementParams)).resolves.toEqual({+ bytes: 9,+ relativePath: 'references/a.md',+ });+ expect(h.getSkillFileByPath).toHaveBeenCalledTimes(1);+ expect(h.upsertSkillFile).toHaveBeenCalledWith(+ expect.objectContaining({ createOnly: true, expectedFileId: undefined }),+ );+ expect(h.deleteFile).not.toHaveBeenCalled();+ });++ it('matches the current stored revision when replacing a file with complete content', async () => {+ const h = harness();+ await expect(h.saveManagement(h.managementParams)).resolves.toEqual({+ bytes: 9,+ relativePath: 'references/a.md',+ });+ expect(h.getSkillFileByPath).toHaveBeenCalledTimes(1);+ expect(h.upsertSkillFile).toHaveBeenCalledWith(+ expect.objectContaining({ createOnly: false, expectedFileId: 'initial' }),+ );+ expect(h.deleteFile).toHaveBeenCalledWith(+ h.params.req,+ expect.objectContaining({ filepath: '/uploads/initial', user: 'original-owner' }),+ );+ });++ it('rejects and removes only its upload if a concurrent browser edit wins', async () => {+ const h = harness();+ h.upsertSkillFile.mockRejectedValueOnce(+ Object.assign(new Error('browser won the write'), { code: 'SKILL_FILE_CONFLICT' }),+ );+ h.getSkillFileByPath+ .mockResolvedValueOnce(existing)+ .mockResolvedValueOnce({ ...existing, file_id: 'browser', filepath: '/uploads/browser' });+ await expect(h.saveManagement(h.managementParams)).rejects.toMatchObject({+ code: 'SKILL_FILE_CONFLICT',+ });+ expect(h.upsertSkillFile).toHaveBeenCalledWith(+ expect.objectContaining({ createOnly: false, expectedFileId: 'initial' }),+ );+ expect(h.deleteFile).toHaveBeenCalledTimes(1);+ expect(h.deleteFile).toHaveBeenCalledWith(+ h.params.req,+ expect.objectContaining({ filepath: '/uploads/new', user: 'editor' }),+ );+ });+});++describe('agent skill file saver', () => {+ it('rejects an obsolete or absent revision before writing bytes', async () => {+ const h = harness();+ await expect(h.save({ ...h.params, expectedFileId: 'stale' })).rejects.toMatchObject({+ code: 'SKILL_FILE_CONFLICT',+ });+ await expect(h.save({ ...h.params, expectedFileId: undefined })).rejects.toMatchObject({+ code: 'SKILL_FILE_CONFLICT',+ });+ expect(h.saveBuffer).not.toHaveBeenCalled();+ expect(h.upsertSkillFile).not.toHaveBeenCalled();+ });++ it('inserts only when absent and forwards creation-only intent to Mongo', async () => {+ const h = harness();+ await expect(+ h.save({ ...h.params, expectedFileId: undefined, createOnly: true }),+ ).rejects.toMatchObject({+ code: 'SKILL_FILE_CONFLICT',+ });+ h.getSkillFileByPath.mockResolvedValueOnce(null);+ await expect(+ h.save({ ...h.params, expectedFileId: undefined, createOnly: true }),+ ).resolves.toEqual({+ bytes: 9,+ relativePath: 'references/a.md',+ });+ expect(h.upsertSkillFile).toHaveBeenCalledWith(+ expect.objectContaining({ createOnly: true, expectedFileId: undefined }),+ );+ });++ it('preserves executable metadata and deletes the original blob under its owner on replacement', async () => {+ const h = harness();+ await expect(h.save(h.params)).resolves.toEqual({+ bytes: 9,+ relativePath: 'references/a.md',+ });+ expect(h.upsertSkillFile).toHaveBeenCalledWith(+ expect.objectContaining({ expectedFileId: 'initial', createOnly: false, isExecutable: true }),+ );+ expect(h.deleteFile).toHaveBeenCalledWith(h.params.req, {+ filepath: '/uploads/initial',+ storageKey: undefined,+ storageRegion: undefined,+ user: 'original-owner',+ tenantId: 'original-tenant',+ });+ expect(h.deleteFile).not.toHaveBeenCalledWith(+ h.params.req,+ expect.objectContaining({ filepath: '/uploads/new' }),+ );+ });++ it('deletes only the losing upload when the browser wins after storage starts', async () => {+ const h = harness();+ h.upsertSkillFile.mockRejectedValueOnce(+ Object.assign(new Error('browser won the race'), { code: 'SKILL_FILE_CONFLICT' }),+ );+ h.getSkillFileByPath.mockResolvedValueOnce(existing).mockResolvedValueOnce({+ ...existing,+ file_id: 'browser-winner',+ filepath: '/uploads/browser',+ });+ await expect(h.save(h.params)).rejects.toMatchObject({ code: 'SKILL_FILE_CONFLICT' });+ expect(h.deleteFile).toHaveBeenCalledWith(+ h.params.req,+ expect.objectContaining({ filepath: '/uploads/new', user: 'editor' }),+ );+ expect(h.deleteFile).not.toHaveBeenCalledWith(+ h.params.req,+ expect.objectContaining({ filepath: '/uploads/browser' }),+ );+ });++ it('retains committed bytes and cleans up the superseded blob if the parent bump fails', async () => {+ const h = harness();+ let committedRevision = '';+ h.upsertSkillFile.mockImplementationOnce(async (row) => {+ committedRevision = row.file_id;+ throw new Error('parent update failed');+ });+ h.getSkillFileByPath.mockResolvedValueOnce(existing).mockImplementationOnce(async () => ({+ ...existing,+ file_id: committedRevision,+ filepath: '/uploads/new',+ }));+ await expect(h.save(h.params)).rejects.toThrow('parent update failed');+ expect(committedRevision).not.toBe('');+ expect(h.deleteFile).toHaveBeenCalledWith(+ h.params.req,+ expect.objectContaining({ filepath: '/uploads/initial', user: 'original-owner' }),+ );+ expect(h.deleteFile).not.toHaveBeenCalledWith(+ h.params.req,+ expect.objectContaining({ filepath: '/uploads/new' }),+ );+ });++ it('deletes an unreferenced upload when Mongo does not return a saved row', async () => {+ const h = harness();+ h.getSkillFileByPath.mockResolvedValueOnce(null).mockResolvedValueOnce(null);+ h.upsertSkillFile.mockResolvedValueOnce(null);+ await expect(+ h.save({ ...h.params, expectedFileId: undefined, createOnly: true }),+ ).rejects.toMatchObject({+ code: 'SKILL_FILE_UPSERT_NOT_FOUND',+ });+ expect(h.deleteFile).toHaveBeenCalledWith(+ h.params.req,+ expect.objectContaining({ filepath: '/uploads/new', user: 'editor' }),+ );+ });+});diff --git a/packages/api/src/skills/save.ts b/packages/api/src/skills/save.tsnew file mode 100644index 0000000000..66b434e7e1--- /dev/null+++ b/packages/api/src/skills/save.ts@@ -0,0 +1,157 @@+import { randomUUID } from 'node:crypto';+import { logger } from '@librechat/data-schemas';+import type { UpsertSkillFileInput } from '@librechat/data-schemas';+import type { TSkillFile } from 'librechat-data-provider';+import type { ServerRequest, StrategyFunctions } from '~/types';+import type { SaveBufferParams } from '~/storage/types';+import type { StoredSkillFile } from './upload';+import { resolveRequestTenantId } from '~/middleware/tenant';+import { getStorageMetadata } from '~/storage/metadata';++interface SkillFileSaveDeps {+ getSkillFileByPath: (skillId: string, relativePath: string) => Promise<StoredSkillFile | null>;+ upsertSkillFile: (+ row: Omit<UpsertSkillFileInput, 'skillId' | 'author'> & { skillId: string; author: string },+ ) => Promise<(StoredSkillFile & { bytes: number; relativePath: string }) | null>;+ resolveStorage: (+ req: ServerRequest,+ options: { isImage: boolean },+ ) => { source: TSkillFile['source']; saveBuffer: (params: SaveBufferParams) => Promise<string> };+ getStrategyFunctions: (source: string) => Partial<StrategyFunctions>;+}++interface SaveSkillFileParams {+ req: ServerRequest;+ skillId: { toString(): string };+ relativePath: string;+ content: string;+ mimeType: string;+ expectedFileId?: string;+ createOnly: boolean;+}++type ManagementFileSaveParams = Omit<SaveSkillFileParams, 'expectedFileId' | 'createOnly'>;+type SavedSkillFile = { bytes: number; relativePath: string };++/** Agent edits must carry the file revision captured alongside their original content. */+export function createSkillFileSaver(+ deps: SkillFileSaveDeps,+): (params: SaveSkillFileParams) => Promise<SavedSkillFile> {+ return (params) => saveSkillFile(deps, params, 'captured');+}++/** Management PUT sends complete content, so it matches the revision current at request time. */+export function createSkillManagementFileSaver(+ deps: SkillFileSaveDeps,+): (params: ManagementFileSaveParams) => Promise<SavedSkillFile> {+ return (params) => saveSkillFile(deps, { ...params, createOnly: false }, 'current');+}++async function saveSkillFile(+ deps: SkillFileSaveDeps,+ {+ req,+ skillId: skillIdValue,+ relativePath,+ content,+ mimeType,+ expectedFileId,+ createOnly,+ }: SaveSkillFileParams,+ revisionMode: 'captured' | 'current',+): Promise<SavedSkillFile> {+ const user = req.user;+ if (!user?.id) {+ throw new Error('Authentication required to save a skill file');+ }+ const userId = user.id;+ const skillId = skillIdValue.toString();+ const existingFile = await deps.getSkillFileByPath(skillId, relativePath);+ const insertOnly = revisionMode === 'current' ? existingFile == null : createOnly;+ const revision = revisionMode === 'current' ? existingFile?.file_id : expectedFileId;+ if (+ (insertOnly && (existingFile != null || revision !== undefined)) ||+ (!insertOnly && (!revision || existingFile?.file_id !== revision))+ ) {+ throw Object.assign(new Error('Skill file changed since it was read'), {+ code: 'SKILL_FILE_CONFLICT',+ });+ }++ const tenantId = resolveRequestTenantId(req);+ const fileId = randomUUID();+ const filename = relativePath.slice(relativePath.lastIndexOf('/') + 1);+ const buffer = Buffer.from(content, 'utf8');+ const storage = deps.resolveStorage(req, { isImage: mimeType.startsWith('image/') });+ const filepath = await storage.saveBuffer({+ userId,+ buffer,+ fileName: `${fileId}__${filename}`,+ basePath: 'uploads',+ tenantId,+ });+ const storageMetadata = getStorageMetadata({ filepath, source: storage.source });+ const cleanupPreviousBlob = (): void => {+ if (!existingFile || existingFile.filepath === filepath) {+ return;+ }+ const deleteFile = deps.getStrategyFunctions(existingFile.source).deleteFile;+ if (deleteFile) {+ deleteFile(req, {+ filepath: existingFile.filepath,+ storageKey: existingFile.storageKey,+ storageRegion: existingFile.storageRegion,+ user: existingFile.author?.toString() ?? userId,+ tenantId: existingFile.tenantId ?? tenantId,+ }).catch((error: Error) =>+ logger.error('[saveSkillFileContent] Old blob cleanup failed:', error),+ );+ }+ };++ let result: StoredSkillFile & { bytes: number; relativePath: string };+ try {+ const saved = await deps.upsertSkillFile({+ skillId,+ relativePath,+ expectedFileId: revision,+ createOnly: insertOnly,+ file_id: fileId,+ filename,+ filepath,+ ...storageMetadata,+ source: storage.source,+ mimeType,+ bytes: buffer.length,+ isExecutable: existingFile?.isExecutable ?? false,+ author: user._id?.toString() ?? userId,+ tenantId,+ });+ if (!saved) {+ throw Object.assign(new Error('Skill file save failed to persist metadata'), {+ code: 'SKILL_FILE_UPSERT_NOT_FOUND',+ });+ }+ result = saved;+ } catch (error) {+ try {+ const persisted = await deps.getSkillFileByPath(skillId, relativePath);+ if (persisted?.file_id === fileId) {+ cleanupPreviousBlob();+ } else {+ await deps.getStrategyFunctions(storage.source).deleteFile?.(req, {+ filepath,+ ...storageMetadata,+ user: userId,+ tenantId,+ });+ }+ } catch (cleanupError) {+ logger.error('[saveSkillFileContent] Failed to clean up uploaded blob:', cleanupError);+ }+ throw error;+ }++ cleanupPreviousBlob();+ return { bytes: result.bytes, relativePath: result.relativePath };+}diff --git a/packages/api/src/skills/sync/github.spec.ts b/packages/api/src/skills/sync/github.spec.tsindex f7b2e62ede..52ab43e93a 100644--- a/packages/api/src/skills/sync/github.spec.ts+++ b/packages/api/src/skills/sync/github.spec.ts@@ -2993,7 +2993,7 @@ describe('createGitHubSkillSyncRunner', () => {bytes: row.bytes,category: 'script' as const,isExecutable: row.isExecutable ?? false,- author: row.author,+ author: new Types.ObjectId(row.author),tenantId: row.tenantId,};files.set(row.relativePath, next);@@ -3071,6 +3071,7 @@ describe('createGitHubSkillSyncRunner', () => {...row,_id: oldFile._id,skillId: row.skillId as Types.ObjectId,+ author: new Types.ObjectId(row.author),})),saveBuffer: jest.fn(async () => ({filepath: '/uploads/new-file-id__run.sh',diff --git a/packages/api/src/skills/upload.spec.ts b/packages/api/src/skills/upload.spec.tsnew file mode 100644index 0000000000..9d5f0b2e86--- /dev/null+++ b/packages/api/src/skills/upload.spec.ts@@ -0,0 +1,115 @@+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 () => '/uploads/replacement');+ const deps = {+ getSkillById: jest.fn(() => skill.promise),+ getSkillFileByPath: jest.fn(() => file.promise),+ upsertSkillFile: jest.fn(async () => ({ ...originalFile, file_id: 'saved' })),+ resolveStorage: jest.fn(() => ({ source: FileSources.local, saveBuffer })),+ getStrategyFunctions: jest.fn(() => ({})),+ } 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, req, res, handler: createSkillUploadHandler(deps) };+}++describe('skill upload lookup ordering', () => {+ 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(['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();+ },+ );+});diff --git a/packages/api/src/skills/upload.ts b/packages/api/src/skills/upload.tsnew file mode 100644index 0000000000..7b15ac40cd--- /dev/null+++ b/packages/api/src/skills/upload.ts@@ -0,0 +1,181 @@+import { randomUUID } from 'crypto';+import { logger, validateRelativePath } from '@librechat/data-schemas';+import type { UpsertSkillFileInput } from '@librechat/data-schemas';+import type { TSkillFile, TSkill } from 'librechat-data-provider';+import type { Response } from 'express';+import type { StrategyFunctions, ServerRequest } from '~/types';+import type { SaveBufferParams } from '~/storage/types';+import { resolveRequestTenantId } from '~/middleware/tenant';+import { getStorageMetadata } from '~/storage/metadata';+import { blockFilteredSkillFile } from './protection';+import { resolveSkillFilePathParam } from './path';++/** Metadata required for replacement and cleanup, independent of a database document. */+export interface StoredSkillFile {+ file_id: string;+ filepath: string;+ source: string;+ storageKey?: string;+ storageRegion?: string;+ tenantId?: string;+ author?: { toString(): string };+ isExecutable?: boolean;+}++interface SkillUploadDeps {+ getSkillFileByPath: (skillId: string, relativePath: string) => Promise<StoredSkillFile | null>;+ getSkillById: (id: string) => Promise<Pick<TSkill, 'source'> | null>;+ upsertSkillFile: (+ row: Omit<UpsertSkillFileInput, 'skillId' | 'author'> & { skillId: string; author: string },+ ) => Promise<StoredSkillFile>;+ resolveStorage: (+ req: ServerRequest,+ options: { isImage: boolean },+ ) => { source: TSkillFile['source']; saveBuffer: (params: SaveBufferParams) => Promise<string> };+ getStrategyFunctions: (source: string) => Partial<StrategyFunctions>;+}++type UploadRequest = ServerRequest & {+ body: { relativePath?: string; expectedFileId?: string };+ resourceAccess?: { resourceInfo?: Pick<TSkill, 'source'> };+};++/** A conditional replacement never creates a missing file or overwrites another revision. */+export function createSkillUploadHandler(+ deps: SkillUploadDeps,+): (req: UploadRequest, res: Response) => Promise<Response> {+ return async function uploadFileHandler(req: UploadRequest, res: Response): Promise<Response> {+ try {+ const { file } = req;+ if (!file) {+ return res.status(400).json({ error: 'No file provided' });+ }+ if (!req.user?.id) {+ return res.status(401).json({ error: 'Unauthorized' });+ }+ const userId = req.user.id;+ const skillId = String((req.params as { id: string }).id);+ const { relativePath, expectedFileId } = req.body;+ if (typeof relativePath !== 'string' || !relativePath) {+ return res.status(400).json({ error: 'relativePath is required in form body' });+ }+ if (relativePath.toUpperCase() === 'SKILL.MD') {+ return res+ .status(400)+ .json({ error: 'SKILL.md is reserved; update the skill body instead' });+ }+ if (validateRelativePath(relativePath).length > 0) {+ return res.status(400).json({ error: 'Invalid file path' });+ }+ if (expectedFileId !== undefined && (typeof expectedFileId !== 'string' || !expectedFileId)) {+ return res.status(400).json({ error: 'Invalid file revision' });+ }+ const pathParam = (req.params as { relativePath?: string | string[] }).relativePath;+ if (+ pathParam !== undefined &&+ (!expectedFileId || resolveSkillFilePathParam(pathParam) !== relativePath)+ ) {+ return res.status(400).json({ error: 'A matching path and file revision are required' });+ }+ // Privileged access can bypass the ACL resolver. Start both scoped reads+ // together, but do not write bytes until the source and revision are checked.+ const [skill, existingFile] = await Promise.all([+ req.resourceAccess?.resourceInfo ?? deps.getSkillById(skillId),+ deps.getSkillFileByPath(skillId, relativePath),+ ]);+ if (!skill) {+ return res.status(404).json({ error: 'Skill not found' });+ }+ if ((skill.source ?? 'inline') !== 'inline') {+ return res.status(403).json({ error: 'Externally managed skill files are read-only' });+ }+ if (+ blockFilteredSkillFile(req.config?.filters, res, {+ buffer: file.buffer,+ originalName: file.originalname,+ relativePath,+ })+ ) {+ return res;+ }+ if (expectedFileId != null && existingFile?.file_id !== expectedFileId) {+ return res.status(409).json({ error: 'SKILL_FILE_CONFLICT' });+ }+ const tenantId = resolveRequestTenantId(req);+ const storage = deps.resolveStorage(req, { isImage: file.mimetype.startsWith('image/') });+ const fileId = randomUUID();+ const filepath = await storage.saveBuffer({+ userId,+ buffer: file.buffer,+ fileName: `${fileId}__${file.originalname}`,+ basePath: 'uploads',+ tenantId,+ });+ const cleanupReplacedBlob = (): void => {+ if (!existingFile || existingFile.filepath === filepath) {+ return;+ }+ const deleteFile = deps.getStrategyFunctions(existingFile.source).deleteFile;+ if (deleteFile) {+ deleteFile(req, {+ filepath: existingFile.filepath,+ storageKey: existingFile.storageKey,+ storageRegion: existingFile.storageRegion,+ user: existingFile.author?.toString() ?? userId,+ tenantId: existingFile.tenantId ?? tenantId,+ }).catch((error: Error) => logger.error('[uploadFile] Old blob cleanup failed:', error));+ }+ };+ let result: StoredSkillFile;+ try {+ result = await deps.upsertSkillFile({+ skillId,+ relativePath,+ expectedFileId,+ file_id: fileId,+ filename: file.originalname,+ filepath,+ ...getStorageMetadata({ filepath, source: storage.source }),+ source: storage.source,+ mimeType: file.mimetype || 'application/octet-stream',+ bytes: file.size,+ isExecutable: existingFile?.isExecutable ?? false,+ author: userId,+ tenantId,+ });+ } catch (error) {+ try {+ // A parent-version update can fail after the file row committed. Never+ // delete its live blob on that ambiguous failure; retain it for reread.+ const persisted = await deps.getSkillFileByPath(skillId, relativePath);+ if (persisted?.file_id === fileId) {+ cleanupReplacedBlob();+ } else {+ await deps.getStrategyFunctions(storage.source).deleteFile?.(req, {+ filepath,+ ...getStorageMetadata({ filepath, source: storage.source }),+ user: userId,+ tenantId,+ });+ }+ } catch (cleanupError) {+ logger.error('[uploadFile] Failed to clean up orphaned blob:', cleanupError);+ }+ throw error;+ }+ cleanupReplacedBlob();+ return res.status(200).json(result);+ } catch (error) {+ if (error instanceof Error && 'code' in error) {+ if (error.code === 'SKILL_FILE_CONFLICT') {+ return res.status(409).json({ error: 'SKILL_FILE_CONFLICT' });+ }+ if (error.code === 'SKILL_FILE_VALIDATION_FAILED') {+ return res.status(400).json({ error: error.message });+ }+ }+ logger.error('[uploadFile] Error:', error);+ return res.status(500).json({ error: 'Failed to upload file' });+ }+ };+}diff --git a/packages/data-provider/src/data-service.ts b/packages/data-provider/src/data-service.tsindex 47108dce2b..bfc7bea792 100644--- a/packages/data-provider/src/data-service.ts+++ b/packages/data-provider/src/data-service.ts@@ -1304,6 +1304,12 @@ export function listSkillFiles(skillId: string): Promise<sk.TListSkillFilesRespo}export function uploadSkillFile(skillId: string, formData: FormData): Promise<sk.TSkillFile> {+ const relativePath = formData.get('relativePath');+ // Conditional edits use a new route: older servers must reject the request,+ // not silently ignore expectedFileId and perform an unconditional replacement.+ if (formData.has('expectedFileId') && typeof relativePath === 'string') {+ return request.postMultiPart(endpoints.skillFile(skillId, relativePath), formData);+ }return request.postMultiPart(endpoints.skillFiles(skillId), formData);}diff --git a/packages/data-provider/src/types/skills.ts b/packages/data-provider/src/types/skills.tsindex a01fe79a1e..0a71fde2aa 100644--- a/packages/data-provider/src/types/skills.ts+++ b/packages/data-provider/src/types/skills.ts@@ -426,6 +426,8 @@ export type TDeleteSkillFileResponse = {/** Response from GET `/api/skills/:id/files/:relativePath` (JSON mode). */export type TSkillFileContentResponse = {+ /** Opaque storage revision for conditional sub-file replacement. Absent on older servers. */+ fileId?: string;content?: string;mimeType: string;isBinary: boolean;diff --git a/packages/data-schemas/src/methods/skill.spec.ts b/packages/data-schemas/src/methods/skill.spec.tsindex c7145e2cd4..5e81e6531a 100644--- a/packages/data-schemas/src/methods/skill.spec.ts+++ b/packages/data-schemas/src/methods/skill.spec.ts@@ -1861,6 +1861,141 @@ describe('Skill CRUD methods', () => {});describe('SkillFile methods', () => {+ it('allows exactly one conditional writer and rejects a stale or deleted revision', async () => {+ const { skill } = await methods.createSkill(makeSkillInput());+ const input = {+ skillId: skill._id,+ relativePath: 'references/race.md',+ file_id: 'original',+ filename: 'race.md',+ filepath: '/tmp/original',+ source: 'local',+ mimeType: 'text/markdown',+ bytes: 10,+ author: owner._id,+ };+ await methods.upsertSkillFile(input);+ const results = await Promise.allSettled(+ ['a', 'b'].map((revision) =>+ methods.upsertSkillFile({ ...input, expectedFileId: 'original', file_id: revision }),+ ),+ );+ expect(results.filter((result) => result.status === 'fulfilled')).toHaveLength(1);+ expect(results.find((result) => result.status === 'rejected')).toMatchObject({+ reason: { code: 'SKILL_FILE_CONFLICT' },+ });+ const current = await methods.getSkillFileByPath(skill._id, input.relativePath);+ expect(['a', 'b']).toContain(current?.file_id);+ expect(await methods.getSkillById(skill._id)).toMatchObject({ version: 3, fileCount: 1 });++ // An unconditional authoring/agent write also invalidates a captured editor revision.+ await methods.upsertSkillFile({ ...input, file_id: 'agent' });+ await expect(+ methods.upsertSkillFile({+ ...input,+ expectedFileId: current!.file_id,+ file_id: 'stale-editor',+ }),+ ).rejects.toMatchObject({ code: 'SKILL_FILE_CONFLICT' });+ await methods.deleteSkillFile(skill._id, input.relativePath);+ await expect(+ methods.upsertSkillFile({+ ...input,+ expectedFileId: 'agent',+ file_id: 'resurrected',+ }),+ ).rejects.toMatchObject({ code: 'SKILL_FILE_CONFLICT' });+ expect(await methods.getSkillFileByPath(skill._id, input.relativePath)).toBeNull();+ });++ it('creates only absent skill files and leaves the winner intact when creation races', async () => {+ await SkillFile.init();+ const { skill } = await methods.createSkill(makeSkillInput());+ const original = {+ skillId: skill._id,+ relativePath: 'references/new.md',+ file_id: 'browser',+ filename: 'new.md',+ filepath: '/tmp/browser',+ source: 'local',+ mimeType: 'text/markdown',+ bytes: 7,+ author: owner._id,+ };+ await methods.upsertSkillFile(original);+ await expect(+ methods.upsertSkillFile({ ...original, createOnly: true, file_id: 'late-agent' }),+ ).rejects.toMatchObject({ code: 'SKILL_FILE_CONFLICT' });+ expect(await methods.getSkillFileByPath(skill._id, original.relativePath)).toMatchObject({+ file_id: 'browser',+ filepath: '/tmp/browser',+ });+ expect(await methods.getSkillById(skill._id)).toMatchObject({ version: 2, fileCount: 1 });++ const results = await Promise.allSettled(+ ['first', 'second'].map((id) =>+ methods.upsertSkillFile({+ ...original,+ relativePath: 'references/concurrent.md',+ filename: 'concurrent.md',+ filepath: `/tmp/${id}`,+ file_id: id,+ createOnly: true,+ }),+ ),+ );+ expect(results.filter((result) => result.status === 'fulfilled')).toHaveLength(1);+ expect(results.find((result) => result.status === 'rejected')).toMatchObject({+ reason: { code: 'SKILL_FILE_CONFLICT' },+ });+ expect(['first', 'second']).toContain(+ (await methods.getSkillFileByPath(skill._id, 'references/concurrent.md'))?.file_id,+ );+ expect(await methods.getSkillById(skill._id)).toMatchObject({ version: 3, fileCount: 2 });+ });++ it('does not let a delayed read cache old bytes on a replaced file', async () => {+ const { skill } = await methods.createSkill(makeSkillInput());+ const input = {+ skillId: skill._id,+ relativePath: 'references/cache.md',+ file_id: 'before',+ filename: 'cache.md',+ filepath: '/tmp/before',+ source: 'local',+ mimeType: 'text/markdown',+ bytes: 10,+ author: owner._id,+ };+ await methods.upsertSkillFile(input);+ await methods.upsertSkillFile({ ...input, expectedFileId: 'before', file_id: 'after' });+ await methods.updateSkillFileContent(+ skill._id,+ input.relativePath,+ {+ content: 'stale read',+ isBinary: false,+ },+ 'before',+ );+ expect(await methods.getSkillFileByPath(skill._id, input.relativePath)).not.toHaveProperty(+ 'content',+ );+ await methods.updateSkillFileContent(+ skill._id,+ input.relativePath,+ {+ content: 'new bytes',+ isBinary: false,+ },+ 'after',+ );+ expect(await methods.getSkillFileByPath(skill._id, input.relativePath)).toMatchObject({+ file_id: 'after',+ content: 'new bytes',+ });+ });+it('upsertSkillFile bumps parent skill version and updates fileCount', async () => {const { skill } = await methods.createSkill(makeSkillInput());expect(skill.version).toBe(1);diff --git a/packages/data-schemas/src/methods/skill.ts b/packages/data-schemas/src/methods/skill.tsindex e807be080d..30b046e02e 100644--- a/packages/data-schemas/src/methods/skill.ts+++ b/packages/data-schemas/src/methods/skill.ts@@ -746,6 +746,10 @@ function getAlwaysApplyFrontmatterValue(}export type UpsertSkillFileInput = {+ /** When supplied, replace only this stored revision; never recreate a deleted file. */+ expectedFileId?: string;+ /** Insert only when the path is absent, even if another writer creates it first. */+ createOnly?: boolean;skillId: Types.ObjectId | string;relativePath: string;file_id: string;@@ -758,7 +762,7 @@ export type UpsertSkillFileInput = {mimeType: string;bytes: number;isExecutable?: boolean;- author: Types.ObjectId;+ author: Types.ObjectId | string;tenantId?: string;};@@ -1095,6 +1099,7 @@ export function createSkillMethods(skillId: Types.ObjectId | string,relativePath: string,update: { content?: string; isBinary?: boolean },+ expectedFileId?: string,) => Promise<void>;updateSkillFileCodeEnvIds: (updates: Array<{@@ -1867,32 +1872,59 @@ export function createSkillMethods(throw error;}const SkillFile = mongoose.models.SkillFile as Model<ISkillFileDocument>;- const category = inferSkillFileCategory(row.relativePath);+ const fields = {+ skillId: row.skillId,+ relativePath: row.relativePath,+ file_id: row.file_id,+ filename: row.filename,+ filepath: row.filepath,+ storageKey: row.storageKey,+ storageRegion: row.storageRegion,+ source: row.source,+ sourceMetadata: row.sourceMetadata,+ mimeType: row.mimeType,+ bytes: row.bytes,+ category: inferSkillFileCategory(row.relativePath),+ isExecutable: row.isExecutable ?? false,+ author: row.author,+ tenantId: row.tenantId,+ };+ if (row.createOnly) {+ if (row.expectedFileId != null) {+ throw new Error('A file cannot require both an absent path and an existing revision');+ }+ let created: ISkillFileDocument;+ try {+ created = await SkillFile.create(fields);+ } catch (error) {+ if (error instanceof Error && 'code' in error && error.code === 11000) {+ throw Object.assign(new Error('Skill file was created by another writer'), {+ code: 'SKILL_FILE_CONFLICT',+ });+ }+ throw error;+ }+ await bumpSkillVersionAndAdjustFileCount(row.skillId, 1);+ return created.toObject() as unknown as ISkillFile & { _id: Types.ObjectId };+ }const result = (await SkillFile.findOneAndUpdate(- { skillId: row.skillId, relativePath: row.relativePath },{- $set: {- skillId: row.skillId,- relativePath: row.relativePath,- file_id: row.file_id,- filename: row.filename,- filepath: row.filepath,- storageKey: row.storageKey,- storageRegion: row.storageRegion,- source: row.source,- sourceMetadata: row.sourceMetadata,- mimeType: row.mimeType,- bytes: row.bytes,- category,- isExecutable: row.isExecutable ?? false,- author: row.author,- tenantId: row.tenantId,- },+ skillId: row.skillId,+ relativePath: row.relativePath,+ ...(row.expectedFileId != null ? { file_id: row.expectedFileId } : {}),+ },+ {+ $set: fields,$unset: { content: '', isBinary: '', codeEnvRef: '', codeEnvRefs: '' },},- { new: true, upsert: true, includeResultMetadata: true },+ { new: true, upsert: row.expectedFileId == null, includeResultMetadata: true },).lean()) as unknown as SkillFileUpsertResult;const current = result.value;+ if (!current && row.expectedFileId != null) {+ throw Object.assign(new Error('Skill file changed since it was read'), {+ code: 'SKILL_FILE_CONFLICT',+ });+ }if (!current) {const error = new Error('Skill file upsert failed to read the saved file row');(error as Error & { code?: string }).code = 'SKILL_FILE_UPSERT_NOT_FOUND';@@ -1930,9 +1962,13 @@ export function createSkillMethods(skillId: Types.ObjectId | string,relativePath: string,update: { content?: string; isBinary?: boolean },+ expectedFileId?: string,): Promise<void> {const SkillFile = mongoose.models.SkillFile as Model<ISkillFileDocument>;- await SkillFile.updateOne({ skillId, relativePath }, { $set: update });+ await SkillFile.updateOne(+ { skillId, relativePath, ...(expectedFileId != null ? { file_id: expectedFileId } : {}) },+ { $set: update },+ );}async function updateSkillFileCodeEnvIds(