Skip to content

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

🫗 fix: Roll Back Incomplete Skill Archive Imports (#16052)

lia-by-librechat[bot]9acf9f0ac852
diff --git a/api/server/routes/skills.test.js b/api/server/routes/skills.test.js
index 3508cb512d..992cb2d849 100644
--- a/api/server/routes/skills.test.js
+++ b/api/server/routes/skills.test.js
@@ -553,6 +553,54 @@ describe('Skill routes', () => {
);
});
+ it('rolls back the skill, files, ACL, and stored blob when a bundled file fails', async () => {
+ const saveBuffer = jest.fn().mockResolvedValue('/uploads/test/queries.sql');
+ const deleteFile = jest.fn().mockResolvedValue(undefined);
+ const { getStrategyFunctions } = require('~/server/services/Files/strategies');
+ /** Both the write and the rollback delete resolve a strategy, so the
+ * override outlives a single call and is restored below. */
+ const defaultStrategies = getStrategyFunctions();
+ getStrategyFunctions.mockReturnValue({ saveBuffer, deleteFile });
+
+ const zip = new JSZip();
+ zip.file(
+ 'SKILL.md',
+ [
+ '---',
+ 'name: partial-import',
+ 'description: Imported skill that loses one bundled file.',
+ '---',
+ '# Partial Import',
+ ].join('\n'),
+ );
+ zip.file('queries.sql', 'select 1;');
+ /** A space is outside the stored path charset, so this entry can never
+ * persist — the import must fail instead of dropping it silently. */
+ zip.file('references/region mapping.md', '# regions');
+ const buffer = await zip.generateAsync({ type: 'nodebuffer' });
+
+ const res = await request(app).post('/api/skills/import').attach('file', buffer, {
+ filename: 'partial-import.skill',
+ contentType: 'application/zip',
+ });
+ getStrategyFunctions.mockReturnValue(defaultStrategies);
+
+ expect(res.status).toBe(422);
+ expect(res.body).toEqual(
+ expect.objectContaining({
+ error: 'skill_import_incomplete',
+ failedFiles: [{ path: 'references/region mapping.md', reason: 'invalid_path' }],
+ }),
+ );
+ expect(await Skill.countDocuments({ name: 'partial-import' })).toBe(0);
+ expect(await SkillFile.countDocuments()).toBe(0);
+ expect(await AclEntry.countDocuments({ resourceType: ResourceType.SKILL })).toBe(0);
+ expect(deleteFile).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ filepath: '/uploads/test/queries.sql' }),
+ );
+ });
+
it('blocks filtered Markdown before creating the imported skill', async () => {
mockFilters = {
files: {
diff --git a/client/src/components/Skills/dialogs/DeleteSkill.tsx b/client/src/components/Skills/dialogs/DeleteSkill.tsx
index 85a6ece659..075875f870 100644
--- a/client/src/components/Skills/dialogs/DeleteSkill.tsx
+++ b/client/src/components/Skills/dialogs/DeleteSkill.tsx
@@ -26,8 +26,12 @@ function DeleteSkill({ skillId, skillName, disabled, onDelete }: DeleteSkillProp
const localize = useLocalize();
const { showToast } = useToastContext();
const deleteSkill = useDeleteSkillMutation({
- onSuccess: () => {
- showToast({ status: 'success', message: localize('com_ui_skill_deleted') });
+ onSuccess: (response) => {
+ const cleanupComplete = response.cleanupComplete !== false;
+ showToast({
+ status: cleanupComplete ? 'success' : 'error',
+ message: localize(cleanupComplete ? 'com_ui_skill_deleted' : 'com_ui_skill_delete_partial'),
+ });
onDelete?.();
},
onError: () => {
diff --git a/client/src/components/Skills/dialogs/UploadSkillDialog.tsx b/client/src/components/Skills/dialogs/UploadSkillDialog.tsx
index 6ae501c83b..d5f97dccf3 100644
--- a/client/src/components/Skills/dialogs/UploadSkillDialog.tsx
+++ b/client/src/components/Skills/dialogs/UploadSkillDialog.tsx
@@ -7,6 +7,12 @@ import {
mergeFileConfig,
fileConfig as defaultFileConfig,
} from 'librechat-data-provider';
+import type {
+ SkillImportFailureReason,
+ TSkillImportFailedFile,
+ TSkillImportFailedResponse,
+} from 'librechat-data-provider';
+import type { TranslationKeys } from '~/hooks';
import { useGetFileConfig, useImportSkillMutation } from '~/data-provider';
import { useLocalize } from '~/hooks';
import { cn } from '~/utils';
@@ -21,12 +27,79 @@ function formatMegabytes(bytes: number): string {
return Number.isInteger(value) ? `${value}` : value.toFixed(1);
}
+/** Localization key per failure reason; `limitMb` fills `{{0}}` where present. */
+const FAILURE_REASON_KEYS: Record<SkillImportFailureReason, TranslationKeys> = {
+ invalid_path: 'com_ui_skill_upload_reason_invalid_path',
+ file_too_large: 'com_ui_skill_upload_reason_file_too_large',
+ archive_too_large: 'com_ui_skill_upload_reason_archive_too_large',
+ archive_entry_changed: 'com_ui_skill_upload_reason_archive_entry_changed',
+ persistence_failed: 'com_ui_skill_upload_reason_persistence_failed',
+};
+
+type ImportFailure = {
+ /** `skill_import_rollback_failed` also means the leftover skill needs deleting. */
+ code: TSkillImportFailedResponse['error'];
+ files: TSkillImportFailedFile[];
+};
+
+/**
+ * An import that could not persist every bundled file is rolled back whole and
+ * answered with `failedFiles`. Those paths are the only place the user learns
+ * which resources their archive lost, so they are rendered in the dialog
+ * instead of being flattened into a toast that disappears.
+ */
+function getImportFailure(error: unknown): ImportFailure | null {
+ const data = (error as { response?: { data?: unknown } })?.response?.data;
+ if (data == null || typeof data !== 'object') {
+ return null;
+ }
+ const body = data as Partial<TSkillImportFailedResponse>;
+ if (
+ (body.error !== 'skill_import_incomplete' &&
+ body.error !== 'skill_import_rollback_failed' &&
+ body.error !== 'skill_import_cleanup_incomplete') ||
+ !Array.isArray(body.failedFiles)
+ ) {
+ return null;
+ }
+ return { code: body.error, files: body.failedFiles };
+}
+
+function failureMessageKey(code: ImportFailure['code']): TranslationKeys {
+ if (code === 'skill_import_rollback_failed') {
+ return 'com_ui_skill_upload_rollback_failed';
+ }
+ if (code === 'skill_import_cleanup_incomplete') {
+ return 'com_ui_skill_upload_cleanup_incomplete';
+ }
+ return 'com_ui_skill_upload_incomplete';
+}
+
+function failureHeadingKey(code: ImportFailure['code']): TranslationKeys {
+ if (code === 'skill_import_rollback_failed') {
+ return 'com_ui_skill_upload_rollback_failed_files';
+ }
+ if (code === 'skill_import_cleanup_incomplete') {
+ return 'com_ui_skill_upload_cleanup_incomplete_files';
+ }
+ return 'com_ui_skill_upload_failed_files';
+}
+
export default function UploadSkillDialog({ isOpen, setIsOpen }: UploadSkillDialogProps) {
const localize = useLocalize();
const navigate = useNavigate();
const { showToast } = useToastContext();
const fileInputRef = useRef<HTMLInputElement>(null);
const [isDragging, setIsDragging] = useState(false);
+ const [failure, setFailure] = useState<ImportFailure | null>(null);
+ /**
+ * The dialog outlives any single upload: `CreateSkillMenu` keeps it mounted
+ * and only toggles `isOpen`. Closing it mid-import cannot cancel the request,
+ * so each session is numbered and a response that resolves after its own
+ * session ended is dropped rather than repopulating a dismissed panel.
+ */
+ const dialogSessionRef = useRef(0);
+ const requestSessionRef = useRef(0);
const {
data: skillFileConfig = { configuredSizeLimitMb: undefined, fileConfig: defaultFileConfig },
} = useGetFileConfig({
@@ -45,15 +118,36 @@ export default function UploadSkillDialog({ isOpen, setIsOpen }: UploadSkillDial
const importMutation = useImportSkillMutation({
onSuccess: (skill) => {
+ if (requestSessionRef.current !== dialogSessionRef.current) {
+ return;
+ }
+ setFailure(null);
showToast({ status: 'success', message: localize('com_ui_skill_created') });
setIsOpen(false);
navigate(`/skills/${skill._id}`);
},
onError: (error: unknown) => {
+ if (requestSessionRef.current !== dialogSessionRef.current) {
+ return;
+ }
+ const importFailure = getImportFailure(error);
+ if (importFailure != null) {
+ /** Keep the dialog open: the archive has to be fixed before a retry can
+ * succeed, and the failed paths are only listed here. */
+ setFailure(importFailure);
+ showToast({
+ status: 'error',
+ message: localize(failureMessageKey(importFailure.code), {
+ 0: `${importFailure.files.length}`,
+ }),
+ });
+ return;
+ }
const errData = (error as { response?: { data?: { error?: string; message?: string } } })
?.response?.data;
const message =
errData?.message ?? errData?.error ?? localize('com_ui_create_skill_upload_error');
+ setFailure(null);
showToast({ status: 'error', message });
},
});
@@ -63,6 +157,7 @@ export default function UploadSkillDialog({ isOpen, setIsOpen }: UploadSkillDial
if (importMutation.isLoading) {
return;
}
+ setFailure(null);
if (file.size > skillImportSizeLimit) {
showToast({
status: 'error',
@@ -72,6 +167,7 @@ export default function UploadSkillDialog({ isOpen, setIsOpen }: UploadSkillDial
}
const formData = new FormData();
formData.append('file', file, file.name);
+ requestSessionRef.current = dialogSessionRef.current;
importMutation.mutate(formData);
},
[displayedSizeLimit, importMutation, localize, showToast, skillImportSizeLimit],
@@ -101,7 +197,16 @@ export default function UploadSkillDialog({ isOpen, setIsOpen }: UploadSkillDial
);
return (
- <OGDialog open={isOpen} onOpenChange={setIsOpen}>
+ <OGDialog
+ open={isOpen}
+ onOpenChange={(open) => {
+ if (!open) {
+ dialogSessionRef.current += 1;
+ setFailure(null);
+ }
+ setIsOpen(open);
+ }}
+ >
<OGDialogContent className="w-11/12 max-w-lg overflow-hidden">
<div className="flex flex-col gap-6 p-1 sm:p-2">
<h2 className="text-lg font-bold text-text-primary">
@@ -135,6 +240,33 @@ export default function UploadSkillDialog({ isOpen, setIsOpen }: UploadSkillDial
{localize('com_ui_skill_upload_drag')}
</button>
+ {failure != null && failure.files.length > 0 && (
+ <div
+ role="alert"
+ className="flex flex-col gap-1 rounded-lg border border-border-medium bg-surface-secondary p-3 text-xs"
+ >
+ <p className="font-medium text-text-destructive">
+ {localize(failureHeadingKey(failure.code))}
+ </p>
+ {/* An archive may hold up to 500 entries, and the dialog's own
+ overflow-hidden would clip a long list past the viewport. */}
+ <ul className="max-h-40 list-inside list-disc overflow-y-auto text-text-secondary">
+ {failure.files.map((failedFile) => (
+ <li key={failedFile.path}>
+ <span className="break-all font-medium text-text-primary">
+ {failedFile.path}
+ </span>
+ {FAILURE_REASON_KEYS[failedFile.reason] != null
+ ? ` — ${localize(FAILURE_REASON_KEYS[failedFile.reason], {
+ 0: `${failedFile.limitMb ?? ''}`,
+ })}`
+ : ''}
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+
<div className="flex flex-col gap-3 text-xs text-text-secondary">
<div>
<p className="font-medium">{localize('com_ui_skill_upload_requirements')}</p>
diff --git a/client/src/components/Skills/dialogs/__tests__/UploadSkillDialog.spec.tsx b/client/src/components/Skills/dialogs/__tests__/UploadSkillDialog.spec.tsx
index 5e20ca4f56..f4fe40cf11 100644
--- a/client/src/components/Skills/dialogs/__tests__/UploadSkillDialog.spec.tsx
+++ b/client/src/components/Skills/dialogs/__tests__/UploadSkillDialog.spec.tsx
@@ -1,4 +1,4 @@
-import { fireEvent, render, screen } from '@testing-library/react';
+import { act, fireEvent, render, screen } from '@testing-library/react';
import type { FileConfigInput } from 'librechat-data-provider';
import type { ReactNode } from 'react';
import UploadSkillDialog from '../UploadSkillDialog';
@@ -7,6 +7,13 @@ const mockMutate = jest.fn();
const mockNavigate = jest.fn();
const mockSetIsOpen = jest.fn();
const mockShowToast = jest.fn();
+interface ImportMutationOptions {
+ onSuccess?: (skill: { _id: string }) => void;
+ onError?: (error: unknown) => void;
+}
+let mockImportOptions: ImportMutationOptions | undefined;
+/** Captured from OGDialog so a test can dismiss the dialog the way Escape does. */
+let mockOnOpenChange: ((open: boolean) => void) | undefined;
let mockFileConfigInput: FileConfigInput | undefined = {
skills: {
fileSizeLimit: 1,
@@ -22,13 +29,23 @@ jest.mock('@librechat/client', () => {
const React = jest.requireActual<typeof import('react')>('react');
const ReactDOM = jest.requireActual<typeof import('react-dom')>('react-dom');
return {
- OGDialog: ({ open, children }: { open: boolean; children: ReactNode }) =>
- open
+ OGDialog: ({
+ open,
+ onOpenChange,
+ children,
+ }: {
+ open: boolean;
+ onOpenChange?: (next: boolean) => void;
+ children: ReactNode;
+ }) => {
+ mockOnOpenChange = onOpenChange;
+ return open
? ReactDOM.createPortal(
React.createElement('div', null, children),
globalThis.document.body,
)
- : null,
+ : null;
+ },
OGDialogContent: ({ children }: { children: ReactNode }) =>
React.createElement('div', { role: 'dialog', 'data-state': 'open' }, children),
Spinner: () => React.createElement('div', { 'data-testid': 'spinner' }),
@@ -42,10 +59,13 @@ jest.mock('~/data-provider', () => ({
useGetFileConfig: ({ select }: { select?: (data: FileConfigInput | undefined) => unknown }) => ({
data: select != null ? select(mockFileConfigInput) : mockFileConfigInput,
}),
- useImportSkillMutation: () => ({
- mutate: mockMutate,
- isLoading: false,
- }),
+ useImportSkillMutation: (options?: ImportMutationOptions) => {
+ mockImportOptions = options;
+ return {
+ mutate: mockMutate,
+ isLoading: false,
+ };
+ },
}));
jest.mock('~/hooks', () => ({
@@ -63,6 +83,20 @@ jest.mock('~/hooks', () => ({
com_ui_skill_upload_size_error: `Skill import must not exceed ${params?.[0]} MB`,
com_ui_skill_created: 'Skill created',
com_ui_create_skill_upload_error: 'Failed to read the uploaded file',
+ com_ui_skill_upload_failed_files: 'These files could not be imported:',
+ com_ui_skill_upload_cleanup_incomplete: `Import failed for ${params?.[0]} file(s). The incomplete skill was removed, but automatic cleanup did not finish.`,
+ com_ui_skill_upload_cleanup_incomplete_files:
+ 'Import failed for these files; automatic cleanup did not finish:',
+ com_ui_skill_upload_incomplete: `Import canceled: ${params?.[0]} file(s) in the archive could not be imported. Fix the archive and upload it again.`,
+ com_ui_skill_upload_reason_invalid_path: 'Unsupported file path',
+ com_ui_skill_upload_reason_file_too_large: `Exceeds the ${params?.[0]} MB file size limit`,
+ com_ui_skill_upload_reason_archive_too_large: `Not imported: the archive exceeds the ${params?.[0]} MB total size limit`,
+ com_ui_skill_upload_reason_archive_entry_changed:
+ 'Changed while the archive was being read',
+ com_ui_skill_upload_reason_persistence_failed: 'Could not be saved',
+ com_ui_skill_upload_rollback_failed: `Import failed for ${params?.[0]} file(s), and the incomplete skill could not be removed automatically. Delete it before trying again.`,
+ com_ui_skill_upload_rollback_failed_files:
+ 'Import failed for these files, and the incomplete skill was left behind:',
};
return translations[key] ?? key;
},
@@ -86,9 +120,33 @@ function getFileInput(container: HTMLElement): HTMLInputElement {
return input;
}
+type FailedFile = { path: string; reason: string; limitMb?: number };
+
+function incompleteImportError(failedFiles: FailedFile[], code = 'skill_import_incomplete') {
+ return {
+ response: {
+ data: {
+ error: code,
+ message: `Import canceled: ${failedFiles.length} of 3 files in the archive could not be imported.`,
+ failedFiles,
+ },
+ },
+ };
+}
+
+function uploadArchive(container: HTMLElement, name = 'retry.skill') {
+ fireEvent.change(getFileInput(container), {
+ target: {
+ files: [new File([new Uint8Array(1024)], name, { type: 'application/zip' })],
+ },
+ });
+}
+
describe('UploadSkillDialog', () => {
beforeEach(() => {
jest.clearAllMocks();
+ mockImportOptions = undefined;
+ mockOnOpenChange = undefined;
mockFileConfigInput = {
skills: {
fileSizeLimit: 1,
@@ -164,6 +222,165 @@ describe('UploadSkillDialog', () => {
appendSpy.mockRestore();
});
+ it('lists the files a rolled-back import could not persist, localized, and keeps the dialog open', () => {
+ render(<UploadSkillDialog isOpen={true} setIsOpen={mockSetIsOpen} />);
+
+ act(() => {
+ mockImportOptions?.onError?.(
+ incompleteImportError([
+ { path: 'queries.sql', reason: 'file_too_large', limitMb: 10 },
+ { path: 'references/region_mapping.md', reason: 'invalid_path' },
+ ]),
+ );
+ });
+
+ expect(mockShowToast).toHaveBeenCalledWith({
+ status: 'error',
+ message:
+ 'Import canceled: 2 file(s) in the archive could not be imported. Fix the archive and upload it again.',
+ });
+ const alert = screen.getByRole('alert');
+ expect(alert).toHaveTextContent('These files could not be imported:');
+ expect(screen.getByText('queries.sql')).toBeInTheDocument();
+ expect(screen.getByText('references/region_mapping.md')).toBeInTheDocument();
+ /** Localized from the reason code, with the limit interpolated — never the
+ * server's own English text. */
+ expect(alert).toHaveTextContent('Exceeds the 10 MB file size limit');
+ expect(alert).toHaveTextContent('Unsupported file path');
+ expect(mockSetIsOpen).not.toHaveBeenCalled();
+ expect(mockNavigate).not.toHaveBeenCalled();
+ });
+
+ it('keeps a long failure list scrollable inside the dialog', () => {
+ render(<UploadSkillDialog isOpen={true} setIsOpen={mockSetIsOpen} />);
+ const manyFiles = Array.from({ length: 60 }, (_, index) => ({
+ path: `files/entry-${index}.txt`,
+ reason: 'invalid_path',
+ }));
+
+ act(() => {
+ mockImportOptions?.onError?.(incompleteImportError(manyFiles));
+ });
+
+ const list = screen.getByRole('alert').querySelector('ul');
+ expect(list).not.toBeNull();
+ expect(list?.className).toContain('overflow-y-auto');
+ expect(list?.className).toMatch(/max-h-/);
+ expect(list?.querySelectorAll('li')).toHaveLength(60);
+ });
+
+ it('tells the user to delete the leftover skill when rollback failed', () => {
+ render(<UploadSkillDialog isOpen={true} setIsOpen={mockSetIsOpen} />);
+
+ act(() => {
+ mockImportOptions?.onError?.(
+ incompleteImportError(
+ [{ path: 'queries.sql', reason: 'persistence_failed' }],
+ 'skill_import_rollback_failed',
+ ),
+ );
+ });
+
+ expect(mockShowToast).toHaveBeenCalledWith({
+ status: 'error',
+ message:
+ 'Import failed for 1 file(s), and the incomplete skill could not be removed automatically. Delete it before trying again.',
+ });
+ expect(screen.getByRole('alert')).toHaveTextContent(
+ 'Import failed for these files, and the incomplete skill was left behind:',
+ );
+ });
+
+ it('distinguishes incomplete cleanup from a skill that still needs deletion', () => {
+ render(<UploadSkillDialog isOpen={true} setIsOpen={mockSetIsOpen} />);
+
+ act(() => {
+ mockImportOptions?.onError?.(
+ incompleteImportError(
+ [{ path: 'queries.sql', reason: 'persistence_failed' }],
+ 'skill_import_cleanup_incomplete',
+ ),
+ );
+ });
+
+ expect(mockShowToast).toHaveBeenCalledWith({
+ status: 'error',
+ message:
+ 'Import failed for 1 file(s). The incomplete skill was removed, but automatic cleanup did not finish.',
+ });
+ expect(screen.getByRole('alert')).toHaveTextContent(
+ 'Import failed for these files; automatic cleanup did not finish:',
+ );
+ });
+
+ it('clears a previous import failure when a new file is selected', () => {
+ const { container } = render(<UploadSkillDialog isOpen={true} setIsOpen={mockSetIsOpen} />);
+
+ act(() => {
+ mockImportOptions?.onError?.(
+ incompleteImportError([{ path: 'queries.sql', reason: 'persistence_failed' }]),
+ );
+ });
+ expect(screen.getByRole('alert')).toBeInTheDocument();
+
+ uploadArchive(container);
+
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();
+ expect(mockMutate).toHaveBeenCalledWith(expect.any(FormData));
+ });
+
+ it('ignores a failure that resolves after the dialog was dismissed', () => {
+ /** The dialog is permanently mounted by CreateSkillMenu, so a 422 can land
+ * after the user closed it; reopening must not show the stale archive. */
+ const { container, rerender } = render(
+ <UploadSkillDialog isOpen={true} setIsOpen={mockSetIsOpen} />,
+ );
+ uploadArchive(container, 'abandoned.skill');
+
+ act(() => {
+ mockOnOpenChange?.(false);
+ });
+ rerender(<UploadSkillDialog isOpen={false} setIsOpen={mockSetIsOpen} />);
+ act(() => {
+ mockImportOptions?.onError?.(
+ incompleteImportError([{ path: 'queries.sql', reason: 'persistence_failed' }]),
+ );
+ });
+ rerender(<UploadSkillDialog isOpen={true} setIsOpen={mockSetIsOpen} />);
+
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();
+ expect(mockShowToast).not.toHaveBeenCalled();
+ });
+
+ it('ignores a success that resolves after the dialog was dismissed', () => {
+ const { container } = render(<UploadSkillDialog isOpen={true} setIsOpen={mockSetIsOpen} />);
+ uploadArchive(container, 'abandoned.skill');
+
+ act(() => {
+ mockOnOpenChange?.(false);
+ mockImportOptions?.onSuccess?.({ _id: 'late-skill' });
+ });
+
+ expect(mockShowToast).not.toHaveBeenCalled();
+ expect(mockNavigate).not.toHaveBeenCalled();
+ });
+
+ it('falls back to the server message for import errors without failed files', () => {
+ render(<UploadSkillDialog isOpen={true} setIsOpen={mockSetIsOpen} />);
+
+ act(() => {
+ mockImportOptions?.onError?.({
+ response: { data: { error: 'Archive must contain a SKILL.md file' } },
+ });
+ });
+
+ expect(mockShowToast).toHaveBeenCalledWith({
+ status: 'error',
+ message: 'Archive must contain a SKILL.md file',
+ });
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();
+ });
+
it('uploads files under the configured skill import limit', () => {
const appendSpy = jest.spyOn(FormData.prototype, 'append');
const { container } = render(<UploadSkillDialog isOpen={true} setIsOpen={mockSetIsOpen} />);
diff --git a/client/src/data-provider/Skills/__tests__/mutations.spec.tsx b/client/src/data-provider/Skills/__tests__/mutations.spec.tsx
index 4bd782ba3d..f75e17e6d9 100644
--- a/client/src/data-provider/Skills/__tests__/mutations.spec.tsx
+++ b/client/src/data-provider/Skills/__tests__/mutations.spec.tsx
@@ -4,10 +4,16 @@ import { act, renderHook, waitFor } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import type { TSkill, TSkillListResponse } from 'librechat-data-provider';
import type { ReactNode } from 'react';
-import { useCreateSkillMutation } from '../mutations';
+import {
+ useCreateSkillMutation,
+ useDeleteSkillMutation,
+ useImportSkillMutation,
+} from '../mutations';
import { useSkillsInfiniteQuery } from '../queries';
const mockCreateSkill = jest.fn();
+const mockDeleteSkill = jest.fn();
+const mockImportSkill = jest.fn();
const mockListSkills = jest.fn();
jest.mock('librechat-data-provider', () => {
@@ -17,6 +23,8 @@ jest.mock('librechat-data-provider', () => {
dataService: {
...actual.dataService,
createSkill: (...args: unknown[]) => mockCreateSkill(...args),
+ deleteSkill: (...args: unknown[]) => mockDeleteSkill(...args),
+ importSkill: (...args: unknown[]) => mockImportSkill(...args),
listSkills: (...args: unknown[]) => mockListSkills(...args),
},
};
@@ -139,4 +147,81 @@ describe('skill creation cache updates', () => {
queryClient.clear();
});
+
+ it.each([
+ 'skill_import_incomplete',
+ 'skill_import_rollback_failed',
+ 'skill_import_cleanup_incomplete',
+ ])('invalidates skill lists after %s', async (errorCode) => {
+ const queryClient = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false },
+ mutations: { retry: false },
+ },
+ });
+ const invalidateQueries = jest.spyOn(queryClient, 'invalidateQueries');
+ const staleListKey = [QueryKeys.skills, 'infinite', '', '', 100];
+ queryClient.setQueryData(staleListKey, {
+ pages: [{ skills: [makeSkill('leftover-skill', 'leftover')], has_more: false, after: null }],
+ pageParams: [undefined],
+ });
+ mockImportSkill.mockRejectedValue({
+ response: {
+ data: {
+ error: errorCode,
+ skillId: 'leftover-skill',
+ failedFiles: [{ path: 'queries.sql', reason: 'persistence_failed' }],
+ },
+ },
+ });
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ );
+ const { result } = renderHook(() => useImportSkillMutation(), { wrapper });
+
+ await act(async () => {
+ await expect(result.current.mutateAsync(new FormData())).rejects.toBeDefined();
+ });
+
+ expect(invalidateQueries).toHaveBeenCalledWith([QueryKeys.skills]);
+ expect(queryClient.getQueryData(staleListKey)).toBeUndefined();
+ queryClient.clear();
+ });
+
+ it('evicts a deleted skill when dependent server cleanup is incomplete', async () => {
+ const queryClient = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false },
+ mutations: { retry: false },
+ },
+ });
+ const skill = makeSkill('deleted-id', 'deleted-skill');
+ const queryKey = [QueryKeys.skills, 'infinite', '', '', 100];
+ queryClient.setQueryData([QueryKeys.skill, skill._id], skill);
+ queryClient.setQueryData(queryKey, {
+ pages: [{ skills: [skill], has_more: false, after: null }],
+ pageParams: [undefined],
+ });
+ mockDeleteSkill.mockResolvedValue({
+ id: skill._id,
+ deleted: true,
+ cleanupComplete: false,
+ });
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ );
+ const { result } = renderHook(() => useDeleteSkillMutation(), { wrapper });
+
+ await act(async () => {
+ await result.current.mutateAsync({ id: skill._id });
+ });
+
+ expect(queryClient.getQueryData([QueryKeys.skill, skill._id])).toBeUndefined();
+ expect(
+ queryClient
+ .getQueryData<{ pages: TSkillListResponse[] }>(queryKey)
+ ?.pages.flatMap((page) => page.skills),
+ ).toEqual([]);
+ queryClient.clear();
+ });
});
diff --git a/client/src/data-provider/Skills/mutations.ts b/client/src/data-provider/Skills/mutations.ts
index 5d84e9438c..d97b54bd41 100644
--- a/client/src/data-provider/Skills/mutations.ts
+++ b/client/src/data-provider/Skills/mutations.ts
@@ -3,6 +3,7 @@ import { useMutation, useQueryClient } from '@tanstack/react-query';
import type {
TSkill,
TSkillFile,
+ TSkillImportFailedResponse,
TCreateSkill,
TUpdateSkillVariables,
TUpdateSkillResponse,
@@ -149,7 +150,7 @@ export const useImportSkillMutation = (
options?: ImportSkillOptions,
): UseMutationResult<TSkill, unknown, FormData> => {
const queryClient = useQueryClient();
- const { onSuccess, ...rest } = options ?? {};
+ const { onError, onSuccess, ...rest } = options ?? {};
return useMutation({
mutationFn: (formData: FormData) => dataService.importSkill(formData),
...rest,
@@ -160,6 +161,19 @@ export const useImportSkillMutation = (
void queryClient.invalidateQueries([QueryKeys.skills]);
if (onSuccess) onSuccess(skill, variables, context);
},
+ onError: (error, variables, context) => {
+ const body = (error as { response?: { data?: Partial<TSkillImportFailedResponse> } })
+ ?.response?.data;
+ if (
+ body?.error === 'skill_import_incomplete' ||
+ body?.error === 'skill_import_rollback_failed' ||
+ body?.error === 'skill_import_cleanup_incomplete'
+ ) {
+ queryClient.removeQueries([QueryKeys.skills], { type: 'inactive' });
+ void queryClient.invalidateQueries([QueryKeys.skills]);
+ }
+ if (onError) onError(error, variables, context);
+ },
});
};
diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json
index 416763b458..c13e2bca02 100644
--- a/client/src/locales/en/translation.json
+++ b/client/src/locales/en/translation.json
@@ -2301,6 +2301,7 @@
"com_ui_skill_created": "Skill created",
"com_ui_skill_delete_confirm": "Are you sure you want to delete \"{{0}}\"? This action cannot be undone.",
"com_ui_skill_delete_error": "Failed to delete skill",
+ "com_ui_skill_delete_partial": "Skill deleted, but some related cleanup did not finish",
"com_ui_skill_deleted": "Skill deleted",
"com_ui_skill_description_field_hint": "Be specific about when this skill should apply.",
"com_ui_skill_description_placeholder": "Apply Acme Corp brand guidelines to presentations and documents...",
@@ -2344,12 +2345,23 @@
"com_ui_skill_validation_error": "Check the skill fields and try again",
"com_ui_skill_updated": "Skill saved",
"com_ui_skill_upload": "Upload a skill",
+ "com_ui_skill_upload_cleanup_incomplete": "Import failed for {{0}} file(s). The incomplete skill was removed, but automatic cleanup did not finish.",
+ "com_ui_skill_upload_cleanup_incomplete_files": "Import failed for these files; automatic cleanup did not finish:",
"com_ui_skill_upload_drag": "Drag and drop or click to upload",
+ "com_ui_skill_upload_failed_files": "These files could not be imported:",
"com_ui_skill_upload_file": "Upload File",
+ "com_ui_skill_upload_incomplete": "Import canceled: {{0}} file(s) in the archive could not be imported. Fix the archive and upload it again.",
+ "com_ui_skill_upload_reason_archive_entry_changed": "Changed while the archive was being read",
+ "com_ui_skill_upload_reason_archive_too_large": "Not imported: the archive exceeds the {{0}} MB total size limit",
+ "com_ui_skill_upload_reason_file_too_large": "Exceeds the {{0}} MB file size limit",
+ "com_ui_skill_upload_reason_invalid_path": "Unsupported file path",
+ "com_ui_skill_upload_reason_persistence_failed": "Could not be saved",
"com_ui_skill_upload_req_md": ".md file must contain skill name and description formatted in YAML",
"com_ui_skill_upload_req_size": "File size must not exceed {{0}} MB",
"com_ui_skill_upload_req_zip": ".zip or .skill file must include a SKILL.md file",
"com_ui_skill_upload_requirements": "File requirements",
+ "com_ui_skill_upload_rollback_failed": "Import failed for {{0}} file(s), and the incomplete skill could not be removed automatically. Delete it before trying again.",
+ "com_ui_skill_upload_rollback_failed_files": "Import failed for these files, and the incomplete skill was left behind:",
"com_ui_skill_upload_size_error": "Skill import must not exceed {{0}} MB",
"com_ui_skill_upload_title": "Upload skill",
"com_ui_skill_version": "v{{0}}",
diff --git a/librechat.example.yaml b/librechat.example.yaml
index c4289f737a..3a7ca6470e 100644
--- a/librechat.example.yaml
+++ b/librechat.example.yaml
@@ -1111,6 +1111,10 @@ endpoints:
# tokens: 2000 # Also preserve up to this many recent tokens
# fileConfig:
+# skills:
+# # Bound parallel storage deletes after a failed archive import (default: 8).
+# # Set to 1 for serial cleanup on storage backends that require it.
+# importCleanupConcurrency: 8
# # Store best-effort text for inferred tool-routed message attachments. On each turn,
# # deliver it only if no available tool can read the type. Off by default; also configurable
# # under endpoints.default or a provider/custom endpoint name. Explicit destinations stand.
diff --git a/packages/api/src/agents/handlers.spec.ts b/packages/api/src/agents/handlers.spec.ts
index d67cdb0402..acbae9698d 100644
--- a/packages/api/src/agents/handlers.spec.ts
+++ b/packages/api/src/agents/handlers.spec.ts
@@ -2913,6 +2913,49 @@ describe('createToolExecuteHandler', () => {
expect(grantSkillOwner).toHaveBeenCalledWith({ req, skillId: SKILL_ID });
});
+ it('retries dependent cleanup when create_file cannot grant ownership', async () => {
+ const createSkill = jest.fn(async () => ({
+ skill: { _id: SKILL_ID, name: 'permission-failure', body: '# Test', version: 1 },
+ }));
+ const deleteSkill = jest
+ .fn()
+ .mockResolvedValueOnce({
+ deleted: true,
+ skillAbsent: true,
+ cleanupComplete: false,
+ failedCleanupSteps: ['permissions'],
+ })
+ .mockResolvedValueOnce({
+ deleted: false,
+ skillAbsent: true,
+ cleanupComplete: true,
+ failedCleanupSteps: [],
+ });
+ const handler = makeAuthoringHandler({
+ getSkillByName: jest.fn(async () => null),
+ createSkill: createSkill as unknown as ToolExecuteOptions['createSkill'],
+ grantSkillOwner: jest.fn(async () => {
+ throw new Error('permission unavailable');
+ }),
+ deleteSkill,
+ });
+
+ const [result] = await invokeHandler(handler, [
+ {
+ id: 'call_permission_failure',
+ name: 'create_file',
+ args: {
+ path: 'skills/permission-failure/SKILL.md',
+ content:
+ '---\nname: permission-failure\ndescription: Permission rollback test\n---\n# Test\n',
+ },
+ },
+ ]);
+
+ expect(result.status).toBe('error');
+ expect(deleteSkill).toHaveBeenCalledTimes(2);
+ });
+
it('rejects case-colliding recognized frontmatter keys in create_file', async () => {
const createSkill = jest.fn();
const handler = makeAuthoringHandler({
diff --git a/packages/api/src/agents/handlers.ts b/packages/api/src/agents/handlers.ts
index 82816ac709..2e5982bc2d 100644
--- a/packages/api/src/agents/handlers.ts
+++ b/packages/api/src/agents/handlers.ts
@@ -22,8 +22,12 @@ import type {
StreamEventData,
ToolEndCallback as SdkToolEndCallback,
} from '@librechat/agents';
+import type {
+ BackgroundToolResultClaim,
+ DeleteSkillResult,
+ ValidationIssue,
+} from '@librechat/data-schemas';
import type { CodeEnvRef, CodeWorkspaceOperation, PtcToolCallEvent } from 'librechat-data-provider';
-import type { BackgroundToolResultClaim, ValidationIssue } from '@librechat/data-schemas';
import type { StructuredToolInterface } from '@librechat/agents/langchain/tools';
import type { CodeEnvFile, CodeSessionContext } from '@librechat/agents';
import type {
@@ -121,6 +125,7 @@ import { mergeCodeFilesIntoContext } from './codeFilesSession';
import { toolValidationFeedback } from './validationFeedback';
import { createSkillContentDigest } from './compatibility';
import { isMissingSandboxPathError } from '~/files/code';
+import { deleteSkillWithRetry } from '~/skills/cleanup';
import { resolveDownloadPath } from '~/storage/path';
import { parseFrontmatter } from '../skills/import';
import { cleanCodeToolOutput } from './cleanup';
@@ -454,7 +459,7 @@ export interface ToolExecuteOptions {
skillId: Types.ObjectId | string;
}) => Promise<void>;
/** Deletes a freshly-created skill if owner-permission setup fails. */
- deleteSkill?: (id: string) => Promise<{ deleted: boolean }>;
+ deleteSkill?: (id: string) => Promise<DeleteSkillResult>;
/** Saves or replaces a bundled skill file in configured storage and metadata. */
saveSkillFileContent?: (params: {
req: ServerRequest;
@@ -3587,11 +3592,20 @@ async function writeSkillMd({
await options.grantSkillOwner({ req, skillId: result.skill._id });
} catch (error) {
if (options.deleteSkill) {
- await options.deleteSkill(result.skill._id.toString()).catch((rollbackError: unknown) => {
- logger.error('[create_file] Failed to roll back skill after permission error', {
- rollbackError,
+ await deleteSkillWithRetry(options.deleteSkill, result.skill._id.toString())
+ .then((deletion) => {
+ if (!deletion.cleanupComplete) {
+ logger.error('[create_file] Skill rollback left dependent cleanup incomplete', {
+ skillId: result.skill._id.toString(),
+ failedCleanupSteps: deletion.failedCleanupSteps,
+ });
+ }
+ })
+ .catch((rollbackError: unknown) => {
+ logger.error('[create_file] Failed to roll back skill after permission error', {
+ rollbackError,
+ });
});
- });
}
throw error;
}
diff --git a/packages/api/src/skills/__tests__/import.test.ts b/packages/api/src/skills/__tests__/import.test.ts
index 54de9be397..33eeb7b6c1 100644
--- a/packages/api/src/skills/__tests__/import.test.ts
+++ b/packages/api/src/skills/__tests__/import.test.ts
@@ -22,6 +22,13 @@ interface ImportSummary {
errors: Array<{ path: string; status: 'ok' | 'error'; error?: string }>;
}
+interface ImportFailure {
+ error: string;
+ message: string;
+ failedFiles: Array<{ path: string; reason: string; limitMb?: number }>;
+ skillId?: string;
+}
+
function mockAppConfig(filters: FiltersConfig): NonNullable<ImportRequest['config']> {
return {
config: {},
@@ -57,9 +64,15 @@ function mockImportDeps(limits?: ImportSkillDeps['limits']): ImportSkillDeps {
limits,
createSkill: jest.fn(async () => ({ skill }) as unknown as CreateSkillResult),
getSkillById: jest.fn(async () => skill),
- deleteSkill: jest.fn(async () => ({ deleted: true })),
+ deleteSkill: jest.fn(async () => ({
+ deleted: true,
+ skillAbsent: true,
+ cleanupComplete: true,
+ failedCleanupSteps: [],
+ })),
upsertSkillFile: jest.fn(async () => skillFile),
saveBuffer: jest.fn(async () => ({ filepath: '/tmp/imported-file', source: 'local' })),
+ deleteFile: jest.fn(async () => undefined),
grantPermission: jest.fn(async () => undefined),
};
}
@@ -119,6 +132,10 @@ function importSummary(body: unknown): ImportSummary {
return (body as { _importSummary: ImportSummary })._importSummary;
}
+function importFailure(body: unknown): ImportFailure {
+ return body as ImportFailure;
+}
+
async function zipWithAdditionalFiles(fileCount: number, fileBytes: number): Promise<Buffer> {
const zip = new JSZip();
zip.file(
@@ -459,6 +476,23 @@ describe('createImportHandler', () => {
);
});
+ it('reports zero failed files when every archive entry persists', async () => {
+ const deps = mockImportDeps();
+ const handler = createImportHandler(deps);
+ const buffer = await zipWithAdditionalFiles(2, 128);
+ const res = mockResponse();
+
+ await handler(mockZipRequest(buffer), res);
+
+ expect(res.status).toHaveBeenCalledWith(201);
+ const summary = importSummary(res.body);
+ expect(summary.filesProcessed).toBe(2);
+ expect(summary.filesSucceeded).toBe(2);
+ expect(summary.filesFailed).toBe(0);
+ expect(summary.errors).toEqual([]);
+ expect(deps.deleteSkill).not.toHaveBeenCalled();
+ });
+
it('counts rejected oversized zip entries toward the cumulative decompressed limit', async () => {
const kib = 1024;
const deps = mockImportDeps({
@@ -473,14 +507,443 @@ describe('createImportHandler', () => {
await handler(mockZipRequest(buffer), res);
- expect(res.status).toHaveBeenCalledWith(201);
- const summary = importSummary(res.body);
- expect(summary.filesProcessed).toBe(3);
- expect(summary.filesSucceeded).toBe(0);
- expect(summary.filesFailed).toBe(3);
- expect(summary.errors).toHaveLength(3);
+ expect(res.status).toHaveBeenCalledWith(422);
+ const failure = importFailure(res.body);
+ expect(failure.error).toBe('skill_import_incomplete');
+ /** All four bundled files are reported, including the one the scan never
+ * reached once the cumulative budget was exhausted. */
+ expect(failure.failedFiles).toHaveLength(4);
+ expect(failure.failedFiles.map((entry) => entry.path)).toEqual([
+ 'files/0.txt',
+ 'files/1.txt',
+ 'files/2.txt',
+ 'files/3.txt',
+ ]);
+ expect(failure.message).toContain('4 of 4');
+ expect(deps.deleteSkill).toHaveBeenCalledTimes(1);
+ });
+
+ it('reports unprocessed archive entries once the decompression budget is exhausted', async () => {
+ const kib = 1024;
+ const deps = mockImportDeps({
+ maxZipBytes: 1024 * kib,
+ maxEntries: 10,
+ maxSingleFileBytes: 8 * kib,
+ maxDecompressedBytes: 12 * kib,
+ });
+ const handler = createImportHandler(deps);
+ /** The first entry fits the per-file limit and consumes most of the budget,
+ * so the second exhausts it and the third is never attempted. */
+ const buffer = await zipWithAdditionalFiles(3, 7 * kib);
+ const res = mockResponse();
+
+ await handler(mockZipRequest(buffer), res);
+
+ expect(res.status).toHaveBeenCalledWith(422);
+ const failure = importFailure(res.body);
+ expect(failure.failedFiles).toEqual([
+ { path: 'files/1.txt', reason: 'archive_too_large', limitMb: 0.01 },
+ { path: 'files/2.txt', reason: 'archive_too_large', limitMb: 0.01 },
+ ]);
+ expect(deps.deleteSkill).toHaveBeenCalledTimes(1);
});
+ it('reports a size-limit rejection as a code with the limit, not a server message', async () => {
+ const kib = 1024;
+ const deps = mockImportDeps({
+ maxZipBytes: 1024 * kib,
+ maxEntries: 10,
+ maxSingleFileBytes: 1024 * kib,
+ maxDecompressedBytes: 4096 * kib,
+ });
+ const handler = createImportHandler(deps);
+ const buffer = await zipWithAdditionalFiles(1, 1025 * kib);
+ const res = mockResponse();
+
+ await handler(mockZipRequest(buffer), res);
+
+ expect(res.status).toHaveBeenCalledWith(422);
+ const failure = importFailure(res.body);
+ expect(failure.failedFiles).toEqual([
+ { path: 'files/0.txt', reason: 'file_too_large', limitMb: 1 },
+ ]);
+ });
+
+ it('leaves stored blobs in place and reports 500 when the skill cannot be deleted', async () => {
+ const deps = mockImportDeps();
+ deps.deleteSkill = jest.fn(async () => {
+ throw new Error('replica set stepped down');
+ }) as ImportSkillDeps['deleteSkill'];
+ deps.deleteFile = jest.fn(async () => undefined);
+ const upsert = jest
+ .fn()
+ .mockResolvedValueOnce({ _id: new Types.ObjectId() })
+ .mockRejectedValueOnce(new Error('write conflict'));
+ deps.upsertSkillFile = upsert as unknown as ImportSkillDeps['upsertSkillFile'];
+ const handler = createImportHandler(deps);
+ const buffer = await zipWithAdditionalFiles(2, 64);
+ const res = mockResponse();
+
+ await handler(mockZipRequest(buffer), res);
+
+ expect(res.status).toHaveBeenCalledWith(500);
+ const failure = importFailure(res.body);
+ expect(failure.error).toBe('skill_import_rollback_failed');
+ expect(failure.skillId).toBeDefined();
+ expect(failure.failedFiles).toEqual([{ path: 'files/1.txt', reason: 'persistence_failed' }]);
+ /** Only the inline cleanup for the row that failed runs. The blob whose row
+ * survived stays, because SkillFile rows may still reference it and a
+ * visible skill with missing files is worse than unreferenced storage. */
+ expect(deps.deleteFile).toHaveBeenCalledTimes(1);
+ expect(deps.deleteFile).not.toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ filepath: '/tmp/imported-0' }),
+ );
+ });
+
+ it('retries an orphan blob after SkillFile cleanup remains incomplete', async () => {
+ const deps = mockImportDeps();
+ deps.deleteSkill = jest.fn(async () => ({
+ deleted: true,
+ skillAbsent: true,
+ cleanupComplete: false,
+ failedCleanupSteps: ['skill_files'],
+ })) as ImportSkillDeps['deleteSkill'];
+ deps.deleteFile = jest
+ .fn()
+ .mockRejectedValueOnce(new Error('storage unavailable'))
+ .mockResolvedValueOnce(undefined) as ImportSkillDeps['deleteFile'];
+ deps.upsertSkillFile = jest
+ .fn()
+ .mockRejectedValueOnce(
+ new Error('write conflict'),
+ ) as unknown as ImportSkillDeps['upsertSkillFile'];
+ const handler = createImportHandler(deps);
+ const res = mockResponse();
+
+ await handler(mockZipRequest(await zipWithAdditionalFiles(1, 64)), res);
+
+ expect(deps.deleteSkill).toHaveBeenCalledTimes(2);
+ expect(deps.deleteFile).toHaveBeenCalledTimes(2);
+ expect(res.status).toHaveBeenCalledWith(500);
+ expect(importFailure(res.body).error).toBe('skill_import_cleanup_incomplete');
+ });
+
+ it('retries dependent cleanup after owner permission setup fails', async () => {
+ const deps = mockImportDeps();
+ deps.grantPermission = jest.fn(async () => {
+ throw new Error('permission unavailable');
+ });
+ deps.deleteSkill = jest
+ .fn()
+ .mockResolvedValueOnce({
+ deleted: true,
+ skillAbsent: true,
+ cleanupComplete: false,
+ failedCleanupSteps: ['permissions'],
+ })
+ .mockResolvedValueOnce({
+ deleted: false,
+ skillAbsent: true,
+ cleanupComplete: true,
+ failedCleanupSteps: [],
+ }) as ImportSkillDeps['deleteSkill'];
+ const handler = createImportHandler(deps);
+ const res = mockResponse();
+
+ await handler(
+ mockMarkdownRequest(
+ '---\nname: permission-failure\ndescription: Permission rollback test\n---\n# Test',
+ ),
+ res,
+ );
+
+ expect(deps.deleteSkill).toHaveBeenCalledTimes(2);
+ expect(res.status).toHaveBeenCalledWith(500);
+ });
+
+ it('retries idempotent database cleanup before deleting stored blobs', async () => {
+ const deps = mockImportDeps();
+ deps.deleteSkill = jest
+ .fn()
+ .mockResolvedValueOnce({
+ deleted: true,
+ skillAbsent: true,
+ cleanupComplete: false,
+ failedCleanupSteps: ['skill_files'],
+ })
+ .mockResolvedValueOnce({
+ deleted: false,
+ skillAbsent: true,
+ cleanupComplete: true,
+ failedCleanupSteps: [],
+ }) as ImportSkillDeps['deleteSkill'];
+ deps.deleteFile = jest.fn(async () => undefined);
+ deps.upsertSkillFile = jest
+ .fn()
+ .mockResolvedValueOnce({ _id: new Types.ObjectId() })
+ .mockRejectedValueOnce(
+ new Error('write conflict'),
+ ) as unknown as ImportSkillDeps['upsertSkillFile'];
+ const handler = createImportHandler(deps);
+ const res = mockResponse();
+
+ await handler(mockZipRequest(await zipWithAdditionalFiles(2, 64)), res);
+
+ expect(deps.deleteSkill).toHaveBeenCalledTimes(2);
+ expect(res.status).toHaveBeenCalledWith(422);
+ expect(importFailure(res.body).error).toBe('skill_import_incomplete');
+ });
+
+ it('reports incomplete cleanup when a persisted blob cannot be deleted', async () => {
+ const deps = mockImportDeps();
+ deps.deleteFile = jest.fn(async (_req, file) => {
+ if (file.filepath === '/tmp/imported-file') {
+ throw new Error('storage unavailable');
+ }
+ });
+ deps.upsertSkillFile = jest
+ .fn()
+ .mockResolvedValueOnce({ _id: new Types.ObjectId() })
+ .mockRejectedValueOnce(
+ new Error('write conflict'),
+ ) as unknown as ImportSkillDeps['upsertSkillFile'];
+ const handler = createImportHandler(deps);
+ const res = mockResponse();
+
+ await handler(mockZipRequest(await zipWithAdditionalFiles(2, 64)), res);
+
+ expect(res.status).toHaveBeenCalledWith(500);
+ expect(importFailure(res.body).error).toBe('skill_import_cleanup_incomplete');
+ });
+
+ it('deletes unreferenced blobs while reporting incomplete non-file cleanup', async () => {
+ const deps = mockImportDeps();
+ deps.deleteSkill = jest.fn(async () => ({
+ deleted: true,
+ skillAbsent: true,
+ cleanupComplete: false,
+ failedCleanupSteps: ['permissions'],
+ })) as ImportSkillDeps['deleteSkill'];
+ deps.deleteFile = jest.fn(async () => undefined);
+ deps.upsertSkillFile = jest
+ .fn()
+ .mockResolvedValueOnce({ _id: new Types.ObjectId() })
+ .mockRejectedValueOnce(
+ new Error('write conflict'),
+ ) as unknown as ImportSkillDeps['upsertSkillFile'];
+ const handler = createImportHandler(deps);
+ const res = mockResponse();
+
+ await handler(mockZipRequest(await zipWithAdditionalFiles(2, 64)), res);
+
+ expect(deps.deleteSkill).toHaveBeenCalledTimes(2);
+ expect(deps.deleteFile).toHaveBeenCalledTimes(2);
+ expect(res.status).toHaveBeenCalledWith(500);
+ expect(importFailure(res.body).error).toBe('skill_import_cleanup_incomplete');
+ });
+
+ it('preserves successful cleanup steps across alternating rollback failures', async () => {
+ const deps = mockImportDeps();
+ deps.deleteSkill = jest
+ .fn()
+ .mockResolvedValueOnce({
+ deleted: true,
+ skillAbsent: true,
+ cleanupComplete: false,
+ failedCleanupSteps: ['permissions'],
+ })
+ .mockResolvedValueOnce({
+ deleted: false,
+ skillAbsent: true,
+ cleanupComplete: false,
+ failedCleanupSteps: ['skill_files'],
+ }) as ImportSkillDeps['deleteSkill'];
+ deps.deleteFile = jest.fn(async () => undefined);
+ deps.upsertSkillFile = jest
+ .fn()
+ .mockResolvedValueOnce({ _id: new Types.ObjectId() })
+ .mockRejectedValueOnce(
+ new Error('write conflict'),
+ ) as unknown as ImportSkillDeps['upsertSkillFile'];
+ const handler = createImportHandler(deps);
+ const res = mockResponse();
+
+ await handler(mockZipRequest(await zipWithAdditionalFiles(2, 64)), res);
+
+ expect(deps.deleteFile).toHaveBeenCalledTimes(2);
+ expect(res.status).toHaveBeenCalledWith(422);
+ expect(importFailure(res.body).error).toBe('skill_import_incomplete');
+ });
+
+ it('rolls back the skill and its stored blobs when one archive file fails', async () => {
+ const deps = mockImportDeps();
+ let savedFiles = 0;
+ deps.saveBuffer = jest.fn(async () => ({
+ filepath: `/tmp/imported-${savedFiles++}`,
+ source: 'local',
+ storageKey: `key-${savedFiles}`,
+ storageRegion: 'us-east-1',
+ })) as ImportSkillDeps['saveBuffer'];
+ deps.deleteFile = jest.fn(async () => undefined);
+ const upsert = jest
+ .fn()
+ .mockResolvedValueOnce({ _id: new Types.ObjectId() })
+ .mockRejectedValueOnce(new Error('write conflict'));
+ deps.upsertSkillFile = upsert as unknown as ImportSkillDeps['upsertSkillFile'];
+ const handler = createImportHandler(deps);
+ const buffer = await zipWithAdditionalFiles(2, 64);
+ const res = mockResponse();
+
+ await handler(mockZipRequest(buffer), res);
+
+ expect(res.status).toHaveBeenCalledWith(422);
+ const failure = importFailure(res.body);
+ expect(failure.error).toBe('skill_import_incomplete');
+ expect(failure.failedFiles).toEqual([{ path: 'files/1.txt', reason: 'persistence_failed' }]);
+ expect(deps.deleteSkill).toHaveBeenCalledTimes(1);
+ /** The blob whose row failed is cleaned up inline; the rollback removes the
+ * one that did persist, so both writes are undone. */
+ expect(deps.deleteFile).toHaveBeenCalledTimes(2);
+ expect(deps.deleteFile).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ filepath: '/tmp/imported-0' }),
+ );
+ expect(res.body).not.toHaveProperty('_importSummary');
+ });
+
+ it('rolls back an archive whose entry path is unsafe instead of importing it partially', async () => {
+ const deps = mockImportDeps();
+ deps.deleteFile = jest.fn(async () => undefined);
+ const handler = createImportHandler(deps);
+ const zip = new JSZip();
+ zip.file(
+ 'SKILL.md',
+ [
+ '---',
+ 'name: tiny-limit-skill',
+ 'description: A skill used by import handler tests.',
+ '---',
+ '# Test skill',
+ ].join('\n'),
+ );
+ zip.file('queries.sql', 'select 1;');
+ zip.file('references/region mapping.md', '# regions');
+ const buffer = await zip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' });
+ const res = mockResponse();
+
+ await handler(mockZipRequest(buffer), res);
+
+ expect(res.status).toHaveBeenCalledWith(422);
+ const failure = importFailure(res.body);
+ expect(failure.failedFiles).toEqual([
+ { path: 'references/region mapping.md', reason: 'invalid_path' },
+ ]);
+ expect(deps.deleteSkill).toHaveBeenCalledTimes(1);
+ expect(deps.deleteFile).toHaveBeenCalledTimes(1);
+ });
+
+ describe.each([false, true])('persisted path validation with preflight=%s', (preflight) => {
+ const config = preflight
+ ? mockAppConfig({
+ files: {
+ pii: {
+ fields: ['content'],
+ starterPatterns: [],
+ customPatterns: [{ id: 'private_token', label: 'private token', regex: 'PRIVATE' }],
+ },
+ },
+ })
+ : undefined;
+
+ it.each(['references/' + 'a'.repeat(486) + '.txt', 'SKILL.md/resource.txt'])(
+ 'rejects %s before writing storage',
+ async (relativePath) => {
+ const deps = mockImportDeps();
+ const zip = await JSZip.loadAsync(await zipWithAdditionalFiles(0, 0));
+ zip.file(`bundle/${relativePath}`, 'safe content');
+ const markdown = await zip.file('SKILL.md')!.async('string');
+ zip.remove('SKILL.md');
+ zip.file('bundle/SKILL.md', markdown);
+ const res = mockResponse();
+
+ await createImportHandler(deps)(
+ mockZipRequest(await zip.generateAsync({ type: 'nodebuffer' }), config),
+ res,
+ );
+
+ expect(res.statusCode).toBe(422);
+ expect(importFailure(res.body).failedFiles).toEqual([
+ { path: relativePath, reason: 'invalid_path' },
+ ]);
+ expect(deps.saveBuffer).not.toHaveBeenCalled();
+ expect(deps.upsertSkillFile).not.toHaveBeenCalled();
+ },
+ );
+
+ it('accepts a persisted path at the 500-character boundary', async () => {
+ const deps = mockImportDeps();
+ const zip = await JSZip.loadAsync(await zipWithAdditionalFiles(0, 0));
+ const relativePath = 'references/' + 'a'.repeat(485) + '.txt';
+ zip.file(relativePath, 'safe content');
+ const res = mockResponse();
+
+ await createImportHandler(deps)(
+ mockZipRequest(await zip.generateAsync({ type: 'nodebuffer' }), config),
+ res,
+ );
+
+ expect(relativePath).toHaveLength(500);
+ expect(res.statusCode).toBe(201);
+ expect(deps.upsertSkillFile).toHaveBeenCalledWith(expect.objectContaining({ relativePath }));
+ });
+ });
+
+ it.each([1, 3, undefined])(
+ 'awaits every blob cleanup with concurrency=%s even when deletions fail',
+ async (concurrency) => {
+ const deps = mockImportDeps();
+ const zip = await JSZip.loadAsync(await zipWithAdditionalFiles(20, 64));
+ zip.file('invalid path.txt', 'trigger rollback after the successful writes');
+ let active = 0;
+ let peak = 0;
+ let started = 0;
+ let finished = 0;
+ const failures: number[] = [];
+ deps.deleteFile = jest.fn(async () => {
+ const index = started++;
+ active++;
+ peak = Math.max(peak, active);
+ try {
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ if (index === 0 || index === 19) {
+ failures.push(index);
+ throw new Error('storage unavailable');
+ }
+ } finally {
+ active--;
+ finished++;
+ }
+ });
+ const config = mockAppConfig({});
+ config.fileConfig = { skills: { importCleanupConcurrency: concurrency } };
+ const res = mockResponse();
+
+ await createImportHandler(deps)(
+ mockZipRequest(await zip.generateAsync({ type: 'nodebuffer' }), config),
+ res,
+ );
+
+ expect(peak).toBe(concurrency ?? 8);
+ expect(finished).toBe(20);
+ expect(active).toBe(0);
+ expect(failures).toEqual([0, 19]);
+ expect(deps.deleteFile).toHaveBeenCalledTimes(20);
+ expect(res.statusCode).toBe(500);
+ expect(importFailure(res.body).error).toBe('skill_import_cleanup_incomplete');
+ },
+ );
+
it('bounds SKILL.md inflation even when archive headers understate its size', async () => {
const kib = 1024;
const deps = mockImportDeps({
diff --git a/packages/api/src/skills/cleanup.spec.ts b/packages/api/src/skills/cleanup.spec.ts
new file mode 100644
index 0000000000..b974a241d7
--- /dev/null
+++ b/packages/api/src/skills/cleanup.spec.ts
@@ -0,0 +1,48 @@
+import type { DeleteSkillResult } from '@librechat/data-schemas';
+import { deleteSkillWithRetry, mergeDeleteSkillResults } from './cleanup';
+
+function incomplete(...failedCleanupSteps: DeleteSkillResult['failedCleanupSteps']) {
+ return {
+ deleted: true,
+ skillAbsent: true,
+ cleanupComplete: false,
+ failedCleanupSteps,
+ } satisfies DeleteSkillResult;
+}
+
+describe('mergeDeleteSkillResults', () => {
+ it('keeps steps settled when alternating retries fail independently', () => {
+ expect(mergeDeleteSkillResults(incomplete('permissions'), incomplete('skill_files'))).toEqual({
+ deleted: true,
+ skillAbsent: true,
+ cleanupComplete: true,
+ failedCleanupSteps: [],
+ });
+ });
+
+ it('retains a step that failed in every attempt', () => {
+ expect(
+ mergeDeleteSkillResults(incomplete('permissions', 'skill_files'), incomplete('permissions')),
+ ).toEqual({
+ deleted: true,
+ skillAbsent: true,
+ cleanupComplete: false,
+ failedCleanupSteps: ['permissions'],
+ });
+ });
+});
+
+describe('deleteSkillWithRetry', () => {
+ it('retries and preserves settled cleanup steps', async () => {
+ const deleteSkill = jest
+ .fn()
+ .mockResolvedValueOnce(incomplete('permissions'))
+ .mockResolvedValueOnce(incomplete('skill_files'));
+
+ await expect(deleteSkillWithRetry(deleteSkill, 'skill-id')).resolves.toMatchObject({
+ cleanupComplete: true,
+ failedCleanupSteps: [],
+ });
+ expect(deleteSkill).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/packages/api/src/skills/cleanup.ts b/packages/api/src/skills/cleanup.ts
new file mode 100644
index 0000000000..d0b6a35d33
--- /dev/null
+++ b/packages/api/src/skills/cleanup.ts
@@ -0,0 +1,39 @@
+import type { DeleteSkillCleanupStep, DeleteSkillResult } from '@librechat/data-schemas';
+
+const CLEANUP_STEPS: DeleteSkillCleanupStep[] = ['agent_allowlists', 'skill_files', 'permissions'];
+
+/**
+ * Cleanup is monotonic across idempotent deletion attempts. Once any attempt
+ * confirms a step succeeded, a later transient failure cannot make that work
+ * incomplete again. Only steps that failed in every confirming attempt remain
+ * unsettled.
+ */
+export function mergeDeleteSkillResults(
+ current: DeleteSkillResult,
+ next: DeleteSkillResult,
+): DeleteSkillResult {
+ const confirmingAttempts = [current, next].filter((result) => result.skillAbsent);
+ const failedCleanupSteps = CLEANUP_STEPS.filter((step) =>
+ confirmingAttempts.every((result) => result.failedCleanupSteps.includes(step)),
+ );
+ const skillAbsent = confirmingAttempts.length > 0;
+
+ return {
+ deleted: current.deleted || next.deleted,
+ skillAbsent,
+ cleanupComplete: skillAbsent && failedCleanupSteps.length === 0,
+ failedCleanupSteps,
+ };
+}
+
+/** Retry an idempotent cascade once when the skill row is already gone. */
+export async function deleteSkillWithRetry(
+ deleteSkill: (id: string) => Promise<DeleteSkillResult>,
+ id: string,
+): Promise<DeleteSkillResult> {
+ const result = await deleteSkill(id);
+ if (!result.skillAbsent || result.cleanupComplete) {
+ return result;
+ }
+ return mergeDeleteSkillResults(result, await deleteSkill(id));
+}
diff --git a/packages/api/src/skills/handlers.spec.ts b/packages/api/src/skills/handlers.spec.ts
new file mode 100644
index 0000000000..ab991206fd
--- /dev/null
+++ b/packages/api/src/skills/handlers.spec.ts
@@ -0,0 +1,150 @@
+import { Types } from 'mongoose';
+import type { DeleteSkillResult, ISkillFile } from '@librechat/data-schemas';
+import type { Response } from 'express';
+import type { SkillsHandlersDeps } from './handlers';
+import type { ServerRequest } from '~/types';
+import { createSkillsHandlers } from './handlers';
+
+function mockResponse(): Response {
+ const res = {} as Response;
+ res.status = jest.fn(() => res) as Response['status'];
+ res.json = jest.fn(() => res) as Response['json'];
+ return res;
+}
+
+describe('skill delete handler', () => {
+ it('retries dependent cleanup before the deleted skill becomes unreachable', async () => {
+ const id = new Types.ObjectId().toString();
+ const deleteBlob = jest.fn(async () => undefined);
+ const incomplete: DeleteSkillResult = {
+ deleted: true,
+ skillAbsent: true,
+ cleanupComplete: false,
+ failedCleanupSteps: ['skill_files'],
+ };
+ const complete: DeleteSkillResult = {
+ deleted: false,
+ skillAbsent: true,
+ cleanupComplete: true,
+ failedCleanupSteps: [],
+ };
+ const deleteSkill = jest.fn().mockResolvedValueOnce(incomplete).mockResolvedValueOnce(complete);
+ const file = {
+ relativePath: 'references/query.sql',
+ filepath: '/uploads/query.sql',
+ source: 'local',
+ } as ISkillFile & { _id: Types.ObjectId };
+ const handlers = createSkillsHandlers({
+ deleteSkill,
+ listSkillFiles: jest.fn(async () => [file]),
+ getStrategyFunctions: jest.fn(() => ({ deleteFile: deleteBlob })),
+ isValidObjectIdString: jest.fn(() => true),
+ } as unknown as SkillsHandlersDeps);
+ const req = { params: { id } } as unknown as ServerRequest;
+ const res = mockResponse();
+
+ await handlers.delete(req, res);
+
+ expect(deleteSkill).toHaveBeenCalledTimes(2);
+ expect(deleteBlob).toHaveBeenCalledTimes(1);
+ expect(res.status).toHaveBeenCalledWith(200);
+ expect(res.json).toHaveBeenCalledWith({ id, deleted: true, cleanupComplete: true });
+ });
+
+ it('returns an evictable response when only non-file cleanup remains incomplete', async () => {
+ const id = new Types.ObjectId().toString();
+ const incomplete: DeleteSkillResult = {
+ deleted: true,
+ skillAbsent: true,
+ cleanupComplete: false,
+ failedCleanupSteps: ['permissions'],
+ };
+ const deleteSkill = jest.fn(async () => incomplete);
+ const handlers = createSkillsHandlers({
+ deleteSkill,
+ listSkillFiles: jest.fn(async () => []),
+ getStrategyFunctions: jest.fn(),
+ isValidObjectIdString: jest.fn(() => true),
+ } as unknown as SkillsHandlersDeps);
+ const req = { params: { id } } as unknown as ServerRequest;
+ const res = mockResponse();
+
+ await handlers.delete(req, res);
+
+ expect(deleteSkill).toHaveBeenCalledTimes(2);
+ expect(res.status).toHaveBeenCalledWith(200);
+ expect(res.json).toHaveBeenCalledWith({ id, deleted: true, cleanupComplete: false });
+ });
+
+ it('awaits blob cleanup and reports a partial deletion when storage rejects it', async () => {
+ const id = new Types.ObjectId().toString();
+ const deleteBlob = jest.fn(async () => {
+ throw new Error('storage unavailable');
+ });
+ const handlers = createSkillsHandlers({
+ deleteSkill: jest.fn(async () => ({
+ deleted: true,
+ skillAbsent: true,
+ cleanupComplete: true,
+ failedCleanupSteps: [],
+ })),
+ listSkillFiles: jest.fn(async () => [
+ {
+ relativePath: 'references/query.sql',
+ filepath: '/uploads/query.sql',
+ source: 'local',
+ } as ISkillFile & { _id: Types.ObjectId },
+ ]),
+ getStrategyFunctions: jest.fn(() => ({ deleteFile: deleteBlob })),
+ isValidObjectIdString: jest.fn(() => true),
+ } as unknown as SkillsHandlersDeps);
+ const req = { params: { id } } as unknown as ServerRequest;
+ const res = mockResponse();
+
+ await handlers.delete(req, res);
+
+ expect(deleteBlob).toHaveBeenCalledTimes(1);
+ expect(res.status).toHaveBeenCalledWith(200);
+ expect(res.json).toHaveBeenCalledWith({ id, deleted: true, cleanupComplete: false });
+ });
+});
+
+describe('skill create handler', () => {
+ it('retries dependent cleanup after owner permission setup fails', async () => {
+ const skillId = new Types.ObjectId();
+ const deleteSkill = jest
+ .fn()
+ .mockResolvedValueOnce({
+ deleted: true,
+ skillAbsent: true,
+ cleanupComplete: false,
+ failedCleanupSteps: ['permissions'],
+ })
+ .mockResolvedValueOnce({
+ deleted: false,
+ skillAbsent: true,
+ cleanupComplete: true,
+ failedCleanupSteps: [],
+ });
+ const handlers = createSkillsHandlers({
+ createSkill: jest.fn(async () => ({
+ skill: { _id: skillId, name: 'permission-failure' },
+ warnings: [],
+ })),
+ grantPermission: jest.fn(async () => {
+ throw new Error('permission unavailable');
+ }),
+ deleteSkill,
+ } as unknown as SkillsHandlersDeps);
+ const req = {
+ body: { name: 'permission-failure', description: 'Rollback test', body: '# Test' },
+ user: { id: 'user-1', _id: new Types.ObjectId(), name: 'Test User' },
+ } as unknown as ServerRequest;
+ const res = mockResponse();
+
+ await handlers.create(req, res);
+
+ expect(deleteSkill).toHaveBeenCalledTimes(2);
+ expect(res.status).toHaveBeenCalledWith(500);
+ });
+});
diff --git a/packages/api/src/skills/handlers.ts b/packages/api/src/skills/handlers.ts
index 7a75d0d199..7c53c67493 100644
--- a/packages/api/src/skills/handlers.ts
+++ b/packages/api/src/skills/handlers.ts
@@ -29,11 +29,13 @@ import type {
ListSkillsByAccessParams,
UpdateSkillResult,
ValidationIssue,
+ DeleteSkillResult,
} from '@librechat/data-schemas';
import type { Response } from 'express';
import type { Types } from 'mongoose';
import type { ServerRequest, StrategyFunctions } from '~/types';
import { extractSkillContent, inspectContentWithTraversal } from '~/protection';
+import { deleteSkillWithRetry, mergeDeleteSkillResults } from './cleanup';
import { contentFilterBlockResponse } from '~/middleware/contentFilter';
import { getDeploymentSkillIds } from './deployment';
import { resolveDownloadPath } from '~/storage/path';
@@ -62,7 +64,7 @@ export interface SkillsHandlersDeps {
expectedVersion: number;
update: UpdateSkillInput;
}) => Promise<UpdateSkillResult>;
- deleteSkill: (id: string) => Promise<{ deleted: boolean }>;
+ deleteSkill: (id: string) => Promise<DeleteSkillResult>;
listSkillFiles: (
skillId: string | Types.ObjectId,
) => Promise<Array<ISkillFile & { _id: Types.ObjectId }>>;
@@ -471,7 +473,12 @@ export function createSkillsHandlers(deps: SkillsHandlersDeps): {
permissionError,
);
try {
- await deleteSkill(skill._id.toString());
+ const deletion = await deleteSkillWithRetry(deleteSkill, skill._id.toString());
+ if (!deletion.cleanupComplete) {
+ logger.error(
+ `[POST /skills] Compensating delete incomplete for orphaned skill ${skill._id.toString()}: ${deletion.failedCleanupSteps.join(', ')}`,
+ );
+ }
} catch (rollbackError) {
logger.error(
`[POST /skills] Compensating delete failed for orphaned skill ${skill._id.toString()}:`,
@@ -596,28 +603,60 @@ export function createSkillsHandlers(deps: SkillsHandlersDeps): {
// Collect file records before deletion so we can clean up storage blobs
const files = await listSkillFiles(id);
- const result = await deleteSkill(id);
- if (!result.deleted) {
- return res.status(404).json({ error: 'Skill not found' });
+ let result = await deleteSkill(id);
+ if (result.skillAbsent && !result.cleanupComplete) {
+ try {
+ result = mergeDeleteSkillResults(result, await deleteSkill(id));
+ } catch (error) {
+ logger.error(`[deleteSkill] Cleanup retry failed for ${id}:`, error);
+ }
}
-
- // Fire-and-forget blob cleanup for each file
- for (const file of files) {
- const { deleteFile: deleteBlob } = getStrategyFunctions(file.source);
- if (deleteBlob) {
- deleteBlob(req, {
+ /** Once SkillFile cleanup succeeds, the records loaded above are the
+ * only remaining references to their blobs. Use them even if an
+ * independent allowlist or permission cleanup step needs a retry. */
+ let blobCleanupComplete = true;
+ if (!result.failedCleanupSteps.includes('skill_files')) {
+ const blobDeletions = files.map(async (file) => {
+ const { deleteFile: deleteBlob } = getStrategyFunctions(file.source);
+ if (!deleteBlob) {
+ throw new Error(`No delete strategy for ${file.source}`);
+ }
+ await deleteBlob(req, {
filepath: file.filepath,
storageKey: file.storageKey,
storageRegion: file.storageRegion,
user: file.author?.toString?.(),
tenantId: file.tenantId?.toString?.(),
- }).catch((e) =>
- logger.error(`[deleteSkill] Blob cleanup failed for ${file.relativePath}:`, e),
- );
+ });
+ });
+ const blobResults = await Promise.allSettled(blobDeletions);
+ for (const [index, blobResult] of blobResults.entries()) {
+ if (blobResult.status === 'rejected') {
+ blobCleanupComplete = false;
+ logger.error(
+ `[deleteSkill] Blob cleanup failed for ${files[index].relativePath}:`,
+ blobResult.reason,
+ );
+ }
+ }
+ }
+
+ const cleanupComplete = result.cleanupComplete && blobCleanupComplete;
+ if (!cleanupComplete) {
+ if (result.skillAbsent) {
+ /** The client must evict the now-missing skill even though dependent
+ * cleanup still needs repair. A 2xx response reaches the mutation's
+ * cache reconciliation path; the flag preserves the warning. */
+ const response: TDeleteSkillResponse = { id, deleted: true, cleanupComplete: false };
+ return res.status(200).json(response);
}
+ return res.status(500).json({ error: 'Skill deletion cleanup did not finish' });
+ }
+ if (!result.deleted && files.length === 0) {
+ return res.status(404).json({ error: 'Skill not found' });
}
- const response: TDeleteSkillResponse = { id, deleted: true };
+ const response: TDeleteSkillResponse = { id, deleted: true, cleanupComplete };
return res.status(200).json(response);
} catch (error) {
logger.error('[DELETE /skills/:id] Error deleting skill', error);
diff --git a/packages/api/src/skills/import.ts b/packages/api/src/skills/import.ts
index 480b7d9539..8d454b4fef 100644
--- a/packages/api/src/skills/import.ts
+++ b/packages/api/src/skills/import.ts
@@ -1,9 +1,10 @@
import path from 'path';
import JSZip from 'jszip';
import crypto from 'crypto';
-import { logger } from '@librechat/data-schemas';
+import { logger, validateRelativePath } from '@librechat/data-schemas';
import {
ResourceType,
+ DEFAULT_SKILL_IMPORT_CLEANUP_CONCURRENCY,
AccessRoleIds,
PrincipalType,
hasActivePiiFields,
@@ -15,8 +16,10 @@ import type {
ISkillFile,
CreateSkillInput,
CreateSkillResult,
+ DeleteSkillResult,
UpsertSkillFileInput,
} from '@librechat/data-schemas';
+import type { SkillImportFailureReason, TSkillImportFailedResponse } from 'librechat-data-provider';
import type { Request, Response } from 'express';
import type { Types } from 'mongoose';
import type {
@@ -37,10 +40,11 @@ import {
contentFilterUninspectableResponse,
getBlockedUninspectableSkillFileField,
} from '~/protection';
+import { deleteSkillWithRetry, mergeDeleteSkillResults } from './cleanup';
import { contentFilterBlockResponse } from '~/middleware/contentFilter';
import { resolveRequestTenantId } from '~/middleware/tenant';
+import { createConcurrencyLimiter } from '~/utils/promise';
import { DEFAULT_SKILL_IMPORT_LIMITS } from './limits';
-import { isSafeSkillFilePath } from './path';
import { parseSkillMarkdown } from './parse';
import { isBinaryBuffer } from './binary';
@@ -130,7 +134,7 @@ export interface ImportSkillDeps {
limits?: Partial<ImportLimits> | ((req: ServerRequest) => Partial<ImportLimits> | undefined);
createSkill: (data: CreateSkillInput) => Promise<CreateSkillResult>;
getSkillById: (id: string | Types.ObjectId) => Promise<(ISkill & { _id: Types.ObjectId }) | null>;
- deleteSkill: (id: string) => Promise<{ deleted: boolean }>;
+ deleteSkill: (id: string) => Promise<DeleteSkillResult>;
upsertSkillFile: (row: UpsertSkillFileInput) => Promise<ISkillFile & { _id: Types.ObjectId }>;
saveBuffer: (
req: Request,
@@ -365,7 +369,12 @@ async function grantOwnership(
} catch (error) {
logger.error(`[importSkill] Failed to grant SKILL_OWNER for ${skillId}, rolling back:`, error);
try {
- await deps.deleteSkill(skillId.toString());
+ const deletion = await deleteSkillWithRetry(deps.deleteSkill, skillId.toString());
+ if (!deletion.cleanupComplete) {
+ logger.error(
+ `[importSkill] Compensating delete incomplete for ${skillId}: ${deletion.failedCleanupSteps.join(', ')}`,
+ );
+ }
} catch (rollbackError) {
logger.error(`[importSkill] Compensating delete failed for ${skillId}:`, rollbackError);
}
@@ -468,9 +477,30 @@ async function handleMarkdown(
type ImportFileResult = {
path: string;
status: 'ok' | 'error';
+ /** Stable code the client localizes; set on every failure. */
+ reason?: SkillImportFailureReason;
+ /** Limit in MB, when `reason` names a size limit. */
+ limitMb?: number;
+ /**
+ * Human-readable detail for the server log only. Storage and database
+ * messages can name buckets, hosts and driver internals, so this never
+ * reaches the client — `reason` does.
+ */
error?: string;
};
+/**
+ * Limits are reported to the user in MB. Two decimals, and never 0 for a
+ * positive limit: a deployment configured in kilobytes would otherwise render
+ * as "exceeds the 0 MB limit".
+ */
+function bytesToMb(bytes: number): number {
+ if (bytes <= 0) {
+ return 0;
+ }
+ return Math.max(0.01, Math.round((bytes / (1024 * 1024)) * 100) / 100);
+}
+
interface ArchiveFileDescriptor {
readonly entryPath: string;
readonly relativePath: string;
@@ -526,6 +556,42 @@ async function readZipEntry(
};
}
+/**
+ * Record every archive entry the scan never reached.
+ *
+ * The decompression budget stops the loop mid-archive, and an import that
+ * reported only the entries it happened to read would tell the user they had
+ * seen the whole failure set: they would fix those paths, retry, and meet the
+ * next batch. `startIndex` is the entry the loop stopped on, inclusive.
+ */
+function pushUnprocessedEntries(
+ results: ImportFileResult[],
+ entries: readonly [string, JSZip.JSZipObject][],
+ startIndex: number,
+ prefix: string,
+ limitMb: number,
+): void {
+ for (let index = startIndex; index < entries.length; index++) {
+ const [entryPath, zipEntry] = entries[index];
+ if (zipEntry.dir) {
+ continue;
+ }
+ const normalized = entryPath.replace(/\\/g, '/');
+ const relativePath =
+ prefix && normalized.startsWith(prefix) ? normalized.slice(prefix.length) : normalized;
+ if (relativePath.toUpperCase() === SKILL_MD.toUpperCase()) {
+ continue;
+ }
+ results.push({
+ path: relativePath || normalized,
+ status: 'error',
+ reason: 'archive_too_large',
+ limitMb,
+ error: 'Not processed: cumulative decompressed size exceeded limit',
+ });
+ }
+}
+
async function scanArchiveFiles(
zip: JSZip,
prefix: string,
@@ -539,7 +605,11 @@ async function scanArchiveFiles(
let totalDecompressed = initialDecompressedBytes;
let cumulativeLimitExceeded = false;
- for (const [entryPath, zipEntry] of Object.entries(zip.files)) {
+ const entries = Object.entries(zip.files);
+ const budgetMb = bytesToMb(maxDecompressedBytes);
+
+ for (let index = 0; index < entries.length; index++) {
+ const [entryPath, zipEntry] = entries[index];
if (zipEntry.dir) {
continue;
}
@@ -552,8 +622,13 @@ async function scanArchiveFiles(
if (callbacks.onName?.(relativePath || normalized) === true) {
return { files, results, blocked: true, cumulativeLimitExceeded };
}
- if (!relativePath || !isSafeSkillFilePath(relativePath)) {
- results.push({ path: normalized, status: 'error', error: 'Invalid path' });
+ if (validateRelativePath(relativePath).length > 0) {
+ results.push({
+ path: relativePath,
+ status: 'error',
+ reason: 'invalid_path',
+ error: 'Invalid path',
+ });
continue;
}
@@ -562,26 +637,25 @@ async function scanArchiveFiles(
const effectiveLimit = Math.min(limits.maxSingleFileBytes, cumulativeLimit);
if (effectiveLimit <= 0) {
cumulativeLimitExceeded = true;
- results.push({
- path: relativePath,
- status: 'error',
- error: 'Cumulative decompressed size exceeds limit',
- });
+ pushUnprocessedEntries(results, entries, index, prefix, budgetMb);
break;
}
const { buffer, bytesRead } = await readZipEntry(zipEntry, effectiveLimit);
totalDecompressed += bytesRead;
if (buffer == null) {
- const reason =
- bytesRead > limits.maxSingleFileBytes
- ? `File too large (max ${limits.maxSingleFileBytes / 1024 / 1024}MB)`
- : 'Cumulative decompressed size exceeds limit';
- results.push({ path: relativePath, status: 'error', error: reason });
if (bytesRead > cumulativeLimit) {
cumulativeLimitExceeded = true;
+ pushUnprocessedEntries(results, entries, index, prefix, budgetMb);
break;
}
+ results.push({
+ path: relativePath,
+ status: 'error',
+ reason: 'file_too_large',
+ limitMb: bytesToMb(limits.maxSingleFileBytes),
+ error: `File too large (max ${limits.maxSingleFileBytes / 1024 / 1024}MB)`,
+ });
continue;
}
@@ -603,6 +677,7 @@ async function scanArchiveFiles(
results.push({
path: relativePath,
status: 'error',
+ reason: 'persistence_failed',
error: (error as Error).message,
});
}
@@ -633,11 +708,28 @@ function preflightArchiveNames(
return false;
}
+/** A blob that reached storage, kept so a failed import can delete it again. */
+interface PersistedArchiveBlob {
+ readonly relativePath: string;
+ readonly filepath: string;
+ readonly source: string;
+ readonly storageKey?: string;
+ readonly storageRegion?: string;
+ /** Whether a SkillFile row can still reference this blob. */
+ readonly rowPersisted: boolean;
+}
+
interface ArchivePersistenceContext {
readonly userId: string;
readonly skillId: Types.ObjectId;
readonly authorId: Types.ObjectId;
readonly tenantId?: string;
+ /**
+ * Blobs written so far, in archive order. An import that loses any bundled
+ * file is rolled back whole (`rollbackArchiveImport`), and the storage writes
+ * are the only part of that no database cascade can undo.
+ */
+ readonly persisted: PersistedArchiveBlob[];
}
async function persistArchiveFile(
@@ -657,6 +749,14 @@ async function persistArchiveFile(
isImage: file.mimeType.startsWith('image/'),
tenantId: context.tenantId,
});
+ const persistedBlob: PersistedArchiveBlob = {
+ relativePath: file.relativePath,
+ filepath,
+ source,
+ storageKey,
+ storageRegion,
+ rowPersisted: false,
+ };
try {
await deps.upsertSkillFile({
@@ -675,6 +775,7 @@ async function persistArchiveFile(
tenantId: context.tenantId,
});
} catch (dbError) {
+ let blobRemoved = false;
if (deps.deleteFile) {
await deps
.deleteFile(req, {
@@ -685,12 +786,143 @@ async function persistArchiveFile(
user: context.authorId,
tenantId: context.tenantId,
})
+ .then(() => {
+ blobRemoved = true;
+ })
.catch((error) =>
logger.error(`[importSkill] Orphan cleanup failed for ${file.relativePath}:`, error),
);
}
+ if (!blobRemoved) {
+ context.persisted.push(persistedBlob);
+ }
throw dbError;
}
+
+ context.persisted.push({ ...persistedBlob, rowPersisted: true });
+}
+
+async function cleanupArchiveBlobs(
+ req: ServerRequest,
+ deps: ImportSkillDeps,
+ context: ArchivePersistenceContext,
+ blobs: PersistedArchiveBlob[],
+): Promise<boolean> {
+ const { deleteFile } = deps;
+ if (blobs.length === 0) {
+ return true;
+ }
+ if (deleteFile == null) {
+ return false;
+ }
+
+ const limit = createConcurrencyLimiter(
+ req.config?.fileConfig?.skills?.importCleanupConcurrency ??
+ DEFAULT_SKILL_IMPORT_CLEANUP_CONCURRENCY,
+ );
+ const results = await Promise.allSettled(
+ blobs.map((blob) =>
+ limit(() =>
+ deleteFile(req, {
+ filepath: blob.filepath,
+ storageKey: blob.storageKey,
+ storageRegion: blob.storageRegion,
+ source: blob.source,
+ user: context.authorId,
+ tenantId: context.tenantId,
+ }),
+ ),
+ ),
+ );
+ let complete = true;
+ for (const [index, result] of results.entries()) {
+ if (result.status === 'rejected') {
+ complete = false;
+ logger.error(
+ `[importSkill] Rollback blob cleanup failed for ${blobs[index].relativePath}:`,
+ result.reason,
+ );
+ }
+ }
+ return complete;
+}
+
+/**
+ * Undo an archive import that could not persist every bundled file.
+ *
+ * `deleteSkill` cascades to the SkillFile rows, the agent allowlists and the
+ * ACL grant, so only the storage blobs written by `persistArchiveFile` need
+ * explicit cleanup.
+ *
+ * Order matters: the blobs are deleted only once the cascade has confirmed the
+ * skill is gone. If the delete throws or finds nothing, the SkillFile rows may
+ * still reference those blobs, and deleting them anyway would leave a visible,
+ * shareable skill whose files 404 — a worse version of the bug this rollback
+ * exists to prevent. Unreferenced storage is reclaimable; a broken skill is
+ * not, so the blobs stay and the caller reports the rollback as incomplete.
+ */
+async function rollbackArchiveImport(
+ req: ServerRequest,
+ deps: ImportSkillDeps,
+ context: ArchivePersistenceContext,
+): Promise<{ skillRemoved: boolean; cleanupComplete: boolean }> {
+ const skillId = context.skillId.toString();
+ let deletion: DeleteSkillResult;
+ try {
+ deletion = await deps.deleteSkill(skillId);
+ } catch (error) {
+ logger.error(`[importSkill] Rollback delete failed for skill ${skillId}:`, error);
+ logger.error(
+ `[importSkill] Rollback incomplete for skill ${skillId}: retaining row-backed files because the skill row was not removed`,
+ );
+ await cleanupArchiveBlobs(
+ req,
+ deps,
+ context,
+ context.persisted.filter((blob) => !blob.rowPersisted),
+ );
+ return { skillRemoved: false, cleanupComplete: false };
+ }
+
+ if (deletion.skillAbsent && !deletion.cleanupComplete) {
+ try {
+ deletion = mergeDeleteSkillResults(deletion, await deps.deleteSkill(skillId));
+ } catch (error) {
+ logger.error(`[importSkill] Rollback cleanup retry failed for skill ${skillId}:`, error);
+ }
+ }
+
+ if (!deletion.skillAbsent) {
+ logger.error(`[importSkill] Rollback could not confirm removal of skill ${skillId}`);
+ await cleanupArchiveBlobs(
+ req,
+ deps,
+ context,
+ context.persisted.filter((blob) => !blob.rowPersisted),
+ );
+ return { skillRemoved: false, cleanupComplete: false };
+ }
+ const databaseCleanupComplete = deletion.cleanupComplete;
+ if (!deletion.cleanupComplete) {
+ logger.error(
+ `[importSkill] Rollback database cleanup incomplete for skill ${skillId}: ${deletion.failedCleanupSteps.join(', ')}`,
+ );
+ /** If SkillFile cleanup failed, those rows can still reference the stored
+ * blobs, so retain them for the idempotent database retry. When only an
+ * independent cleanup step failed, the captured records are now the last
+ * blob references and must be consumed before returning the 500. */
+ }
+
+ const skillFileCleanupIncomplete = deletion.failedCleanupSteps.includes('skill_files');
+ const blobsToDelete = skillFileCleanupIncomplete
+ ? context.persisted.filter((blob) => !blob.rowPersisted)
+ : context.persisted;
+
+ const blobCleanupComplete = await cleanupArchiveBlobs(req, deps, context, blobsToDelete);
+ return {
+ skillRemoved: true,
+ cleanupComplete: databaseCleanupComplete && blobCleanupComplete,
+ };
}
async function persistPreflightedArchiveFiles(
@@ -704,8 +936,10 @@ async function persistPreflightedArchiveFiles(
): Promise<ImportFileResult[]> {
const results: ImportFileResult[] = [];
let totalDecompressed = initialDecompressedBytes;
+ const budgetMb = bytesToMb(limits.maxDecompressedBytes);
- for (const file of files) {
+ for (let index = 0; index < files.length; index++) {
+ const file = files[index];
try {
const zipEntry = zip.file(file.entryPath);
if (zipEntry == null) {
@@ -714,11 +948,18 @@ async function persistPreflightedArchiveFiles(
const cumulativeLimit = limits.maxDecompressedBytes - totalDecompressed;
const effectiveLimit = Math.min(limits.maxSingleFileBytes, cumulativeLimit);
if (effectiveLimit <= 0) {
- results.push({
- path: file.relativePath,
- status: 'error',
- error: 'Cumulative decompressed size exceeds limit',
- });
+ /** Same reasoning as `pushUnprocessedEntries`: the remaining files were
+ * never attempted, and omitting them would understate the failure set
+ * the user has to fix before a retry can succeed. */
+ for (const skipped of files.slice(index)) {
+ results.push({
+ path: skipped.relativePath,
+ status: 'error',
+ reason: 'archive_too_large',
+ limitMb: budgetMb,
+ error: 'Not processed: cumulative decompressed size exceeded limit',
+ });
+ }
break;
}
const { buffer, bytesRead } = await readZipEntry(zipEntry, effectiveLimit);
@@ -727,6 +968,7 @@ async function persistPreflightedArchiveFiles(
results.push({
path: file.relativePath,
status: 'error',
+ reason: 'archive_entry_changed',
error: 'Archive entry changed after content inspection',
});
continue;
@@ -741,6 +983,7 @@ async function persistPreflightedArchiveFiles(
results.push({
path: file.relativePath,
status: 'error',
+ reason: 'persistence_failed',
error: (error as Error).message,
});
}
@@ -782,6 +1025,9 @@ async function handleZip(
let skillMdPath: string | null = null;
let prefix = '';
for (const p of entries) {
+ if (zip.files[p].dir) {
+ continue;
+ }
const normalized = p.replace(/\\/g, '/');
const segments = normalized.split('/').filter(Boolean);
const basename = segments[segments.length - 1];
@@ -955,6 +1201,7 @@ async function handleZip(
skillId: skill._id,
authorId,
tenantId,
+ persisted: [],
};
let fileResults: ImportFileResult[];
if (preflight == null) {
@@ -995,9 +1242,56 @@ async function handleZip(
}
}
- logger.info(
- `[importSkill] Imported skill "${inferredName}" with ${successCount} files (${errors.length} errors)`,
- );
+ /**
+ * A skill whose bundled files did not all persist is broken in a way the
+ * uploader cannot see: it lists, shares and attaches normally while an agent
+ * that follows `SKILL.md` cannot find the resources it names. Import is
+ * therefore atomic — any failed file rolls the whole skill back and the
+ * response says which paths failed and why.
+ */
+ if (errors.length > 0) {
+ logger.warn(
+ `[importSkill] Rolling back skill "${inferredName}" (${skill._id.toString()}): ${errors.length} of ${fileResults.length} files failed`,
+ );
+ const { skillRemoved, cleanupComplete } = await rollbackArchiveImport(
+ req,
+ deps,
+ persistenceContext,
+ );
+ /** Reasons are codes, not prose: the client localizes them, and the
+ * underlying storage and database messages stay in the server log where
+ * they cannot leak infrastructure detail to the uploader. */
+ const failedFiles = errors.map((entry) => ({
+ path: entry.path,
+ reason: entry.reason ?? 'persistence_failed',
+ ...(entry.limitMb == null ? {} : { limitMb: entry.limitMb }),
+ }));
+ if (!skillRemoved) {
+ const rollbackFailure: TSkillImportFailedResponse = {
+ error: 'skill_import_rollback_failed',
+ message: `Import failed for ${errors.length} of ${fileResults.length} files and the partially created skill could not be removed automatically.`,
+ failedFiles,
+ skillId: skill._id.toString(),
+ };
+ return res.status(500).json(rollbackFailure);
+ }
+ if (!cleanupComplete) {
+ const cleanupFailure: TSkillImportFailedResponse = {
+ error: 'skill_import_cleanup_incomplete',
+ message: `Import failed for ${errors.length} of ${fileResults.length} files. The skill was removed, but automatic cleanup did not finish.`,
+ failedFiles,
+ };
+ return res.status(500).json(cleanupFailure);
+ }
+ const failure: TSkillImportFailedResponse = {
+ error: 'skill_import_incomplete',
+ message: `Import canceled: ${errors.length} of ${fileResults.length} files in the archive could not be imported.`,
+ failedFiles,
+ };
+ return res.status(422).json(failure);
+ }
+
+ logger.info(`[importSkill] Imported skill "${inferredName}" with ${successCount} files`);
// Re-read the skill to get the current version/fileCount (bumped by each upsertSkillFile)
const refreshed = (await deps.getSkillById(skill._id)) ?? skill;
@@ -1007,7 +1301,7 @@ async function handleZip(
_importSummary: {
filesProcessed: fileResults.length,
filesSucceeded: successCount,
- filesFailed: errors.length,
+ filesFailed: 0,
errors,
},
});
diff --git a/packages/api/src/skills/sync/github.spec.ts b/packages/api/src/skills/sync/github.spec.ts
index fc6b5951eb..f7b2e62ede 100644
--- a/packages/api/src/skills/sync/github.spec.ts
+++ b/packages/api/src/skills/sync/github.spec.ts
@@ -11,6 +11,7 @@ import type {
UpdateSkillInput,
UpdateSkillResult,
UpsertSkillFileInput,
+ DeleteSkillResult,
} from '@librechat/data-schemas';
import type { RepoTreeEntry, GitRepoAdapter } from './adapters/types';
import type { GitHubSkillSyncDeps } from './github';
@@ -40,6 +41,26 @@ function blob(content: string) {
};
}
+function completeSkillDeletion(deleted: boolean): DeleteSkillResult {
+ return {
+ deleted,
+ skillAbsent: true,
+ cleanupComplete: true,
+ failedCleanupSteps: [],
+ };
+}
+
+function incompleteSkillDeletion(
+ failedCleanupSteps: DeleteSkillResult['failedCleanupSteps'],
+): DeleteSkillResult {
+ return {
+ deleted: true,
+ skillAbsent: true,
+ cleanupComplete: false,
+ failedCleanupSteps,
+ };
+}
+
function githubFetch(
skillMarkdown = '---\nname: research\ndescription: Research things\nalways-apply: true\n---\nBody',
): typeof fetch {
@@ -306,7 +327,7 @@ function createDeps(
} as ISkillFile & { _id: Types.ObjectId };
}),
deleteSkillFile: jest.fn(async () => ({ deleted: true })),
- deleteSkill: jest.fn(async () => ({ deleted: true })),
+ deleteSkill: jest.fn(async () => completeSkillDeletion(true)),
saveBuffer: jest.fn(async () => ({ filepath: '/uploads/file-id__run.sh', source: 'local' })),
deleteFile: jest.fn(async () => undefined),
grantPermission: jest.fn(async () => undefined),
@@ -1599,7 +1620,7 @@ describe('createGitHubSkillSyncRunner', () => {
);
const deleteSkill = jest.fn(async (id: string) => {
deletedIds.add(id);
- return { deleted: true };
+ return completeSkillDeletion(true);
});
const updateSkill = jest.fn(
async ({
@@ -1751,7 +1772,9 @@ describe('createGitHubSkillSyncRunner', () => {
const staleSkill = makeExisting('librechat-skills:skills/removed', staleId, 'renamed');
const syncedSkill = makeExisting('librechat-skills:skills/research', existingId, 'research');
const createdIds: string[] = [];
- const deleteSkill = jest.fn(async (id: string) => ({ deleted: createdIds.includes(id) }));
+ const deleteSkill = jest.fn(async (id: string) =>
+ completeSkillDeletion(createdIds.includes(id)),
+ );
const deps = createDeps({
fetchFn,
findSkillBySourceIdentity: jest.fn(async ({ upstreamId }) =>
@@ -1824,7 +1847,7 @@ describe('createGitHubSkillSyncRunner', () => {
return { skill: restoredSkill, warnings: [] };
});
const deleteSkill = jest.fn(async (id: string) => {
- return { deleted: persistedSkills.delete(id) };
+ return completeSkillDeletion(persistedSkills.delete(id));
});
const deps = createDeps({
fetchFn: githubFetch('---\nname: renamed\ndescription: Renamed skill\n---\nBody'),
@@ -1868,60 +1891,85 @@ describe('createGitHubSkillSyncRunner', () => {
);
});
- it('fails the source when stale mirror deletion can leave partial persisted state', async () => {
- const staleId = new Types.ObjectId();
- const existingId = new Types.ObjectId();
- const author = makeSourceAuthorId();
- const makeExisting = (
- upstreamId: string,
- _id: Types.ObjectId,
- name: string,
- ): ISkill & { _id: Types.ObjectId } => {
- const skill = makeSkill({
- name,
- description: `${name} skill`,
+ it.each([
+ { failedStep: 'skill_files' as const, expectedBlobDeletes: 0 },
+ { failedStep: 'permissions' as const, expectedBlobDeletes: 1 },
+ ])(
+ 'fails the source and safely handles blobs when stale deletion leaves $failedStep incomplete',
+ async ({ failedStep, expectedBlobDeletes }) => {
+ const staleId = new Types.ObjectId();
+ const existingId = new Types.ObjectId();
+ const author = makeSourceAuthorId();
+ const makeExisting = (
+ upstreamId: string,
+ _id: Types.ObjectId,
+ name: string,
+ ): ISkill & { _id: Types.ObjectId } => {
+ const skill = makeSkill({
+ name,
+ description: `${name} skill`,
+ author,
+ authorName: 'GitHub Sync',
+ source: 'github',
+ sourceMetadata: { provider: 'github', sourceId: 'librechat-skills', upstreamId },
+ });
+ skill._id = _id;
+ return skill;
+ };
+ const staleSkill = makeExisting('librechat-skills:skills/removed', staleId, 'renamed');
+ const syncedSkill = makeExisting('librechat-skills:skills/research', existingId, 'research');
+ const deleteSkill = jest.fn(async (id: string) => {
+ if (id === staleId.toString()) {
+ return incompleteSkillDeletion([failedStep]);
+ }
+ return completeSkillDeletion(true);
+ });
+ const staleFile = {
+ _id: new Types.ObjectId(),
+ skillId: staleId,
+ relativePath: 'references/stale.md',
+ filepath: '/uploads/stale.md',
+ source: 'local',
author,
- authorName: 'GitHub Sync',
- source: 'github',
- sourceMetadata: { provider: 'github', sourceId: 'librechat-skills', upstreamId },
+ } as ISkillFile & { _id: Types.ObjectId };
+ const deleteFile = jest.fn(
+ async (_file: Parameters<NonNullable<GitHubSkillSyncDeps['deleteFile']>>[0]) => undefined,
+ );
+ const deps = createDeps({
+ fetchFn: githubFetch('---\nname: renamed\ndescription: Renamed skill\n---\nBody'),
+ findSkillBySourceIdentity: jest.fn(async ({ upstreamId }) =>
+ upstreamId === 'librechat-skills:skills/research' ? syncedSkill : null,
+ ),
+ getSkillById: jest.fn(async (id) =>
+ id.toString() === existingId.toString() ? syncedSkill : null,
+ ),
+ listSkillsBySource: jest.fn(async () => [staleSkill, syncedSkill]),
+ listSkillFiles: jest.fn(async (id) =>
+ id.toString() === staleId.toString() ? [staleFile] : [],
+ ),
+ deleteFile,
+ deleteSkill,
+ updateSkill: jest.fn(),
});
- skill._id = _id;
- return skill;
- };
- const staleSkill = makeExisting('librechat-skills:skills/removed', staleId, 'renamed');
- const syncedSkill = makeExisting('librechat-skills:skills/research', existingId, 'research');
- const deleteSkill = jest.fn(async (id: string) => {
- if (id === staleId.toString()) {
- throw new Error('skill file deletion unavailable');
- }
- return { deleted: true };
- });
- const deps = createDeps({
- fetchFn: githubFetch('---\nname: renamed\ndescription: Renamed skill\n---\nBody'),
- findSkillBySourceIdentity: jest.fn(async ({ upstreamId }) =>
- upstreamId === 'librechat-skills:skills/research' ? syncedSkill : null,
- ),
- getSkillById: jest.fn(async (id) =>
- id.toString() === existingId.toString() ? syncedSkill : null,
- ),
- listSkillsBySource: jest.fn(async () => [staleSkill, syncedSkill]),
- deleteSkill,
- updateSkill: jest.fn(),
- });
- const runner = createGitHubSkillSyncRunner(deps);
- const result = await runner.runOnce();
+ const runner = createGitHubSkillSyncRunner(deps);
+ const result = await runner.runOnce();
- expect(result.status).toBe('failed');
- expect(deleteSkill).toHaveBeenCalledWith(staleId.toString());
- expect(deps.updateSkill).not.toHaveBeenCalled();
- expect(deps.upsertStatus).toHaveBeenLastCalledWith(
- expect.objectContaining({
- status: 'failed',
- errorCode: 'SYNC_ROLLBACK_FAILED',
- errorMessage: 'Stale mirror deletion failed: skill file deletion unavailable',
- }),
- );
- });
+ expect(result.status).toBe('failed');
+ expect(deleteSkill).toHaveBeenCalledWith(staleId.toString());
+ const staleBlobCalls = deleteFile.mock.calls.filter(
+ ([file]) => file.filepath === staleFile.filepath,
+ );
+ expect(staleBlobCalls).toHaveLength(expectedBlobDeletes);
+ expect(deps.updateSkill).not.toHaveBeenCalled();
+ expect(deps.upsertStatus).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ status: 'failed',
+ errorCode: 'SYNC_ROLLBACK_FAILED',
+ errorMessage: `Stale mirror deletion failed: Skill cleanup did not finish: ${failedStep}`,
+ }),
+ );
+ },
+ );
it("does not mirror-delete another tenant's skills from an ambient source run", async () => {
const ambientStaleId = new Types.ObjectId();
@@ -2476,7 +2524,7 @@ describe('createGitHubSkillSyncRunner', () => {
expect(deps.deleteSkill).not.toHaveBeenCalled();
});
- it('fails the source when a skill rollback leaves a half-written mirror', async () => {
+ it('fails the source when skill rollback reports incomplete cleanup', async () => {
/* A clean rollback is just a skipped skill. A failed one leaves the mirror
inconsistent, which must not be reported as a partial success next to
the skills that did publish. */
@@ -2484,9 +2532,7 @@ describe('createGitHubSkillSyncRunner', () => {
saveBuffer: jest.fn(async () => {
throw new Error('storage unavailable');
}),
- deleteSkill: jest.fn(async () => {
- throw new Error('rollback unavailable');
- }),
+ deleteSkill: jest.fn(async () => incompleteSkillDeletion(['permissions'])),
});
const runner = createGitHubSkillSyncRunner(deps);
const result = await runner.runOnce();
@@ -2506,7 +2552,7 @@ describe('createGitHubSkillSyncRunner', () => {
const deleteFile = jest.fn(async () => {
throw new Error('storage cleanup unavailable');
});
- const deleteSkill = jest.fn(async () => ({ deleted: true }));
+ const deleteSkill = jest.fn(async () => completeSkillDeletion(true));
const deps = createDeps({
listSkillFiles: jest.fn(async () => storedFiles),
upsertSkillFile: jest.fn(async (input: UpsertSkillFileInput) => {
@@ -2700,7 +2746,7 @@ describe('createGitHubSkillSyncRunner', () => {
},
}) as ISkill & { _id: Types.ObjectId };
let createdSkill: (ISkill & { _id: Types.ObjectId }) | undefined;
- const deleteSkill = jest.fn(async () => ({ deleted: true }));
+ const deleteSkill = jest.fn(async () => completeSkillDeletion(true));
const deps = createDeps({
fetchFn: githubFetch(
'---\nname: renamed-research\ndescription: Renamed research skill\n---\nBody',
diff --git a/packages/api/src/skills/sync/github.ts b/packages/api/src/skills/sync/github.ts
index e48ad2f30e..aadc502f38 100644
--- a/packages/api/src/skills/sync/github.ts
+++ b/packages/api/src/skills/sync/github.ts
@@ -23,6 +23,7 @@ import type {
SkillSyncProvider,
SkillSyncCredentialSummary,
SkillSyncStatusInput,
+ DeleteSkillResult,
} from '@librechat/data-schemas';
import type { SkillSyncConfig, SkillSyncGitHubSourceConfig } from 'librechat-data-provider';
import type {
@@ -206,7 +207,7 @@ export type GitHubSkillSyncDeps = {
skillId: string | Types.ObjectId,
relativePath: string,
) => Promise<{ deleted: boolean }>;
- deleteSkill: (id: string) => Promise<{ deleted: boolean }>;
+ deleteSkill: (id: string) => Promise<DeleteSkillResult>;
saveBuffer: (params: {
userId: string;
buffer: Buffer;
@@ -1072,7 +1073,20 @@ async function deleteSyncedSkillForRestore(
skill: ISkill & { _id: Types.ObjectId },
): Promise<{ deletedFileCount: number; deletedSkill: DeletedSyncedSkillJournal }> {
const files = await deps.listSkillFiles(skill._id);
- await deps.deleteSkill(skill._id.toString());
+ const deletion = await deps.deleteSkill(skill._id.toString());
+ if (!deletion.cleanupComplete) {
+ if (!deletion.failedCleanupSteps.includes('skill_files')) {
+ await cleanupStoredFiles({
+ deps,
+ files: files.map(toStoredFileRefFromSkillFile),
+ logMessage: '[GitHubSkillSync] Failed to clean up partially deleted stale skill file:',
+ throwOnError: true,
+ });
+ }
+ throw new Error(
+ `Skill cleanup did not finish: ${deletion.failedCleanupSteps.join(', ') || 'unknown step'}`,
+ );
+ }
return {
deletedFileCount: files.length,
deletedSkill: { skill, files },
@@ -1396,16 +1410,23 @@ async function deleteSyncedSkill(
skill: ISkill & { _id: Types.ObjectId },
): Promise<number> {
const files = await deps.listSkillFiles(skill._id);
+ const deletion = await deps.deleteSkill(skill._id.toString());
let deletedFiles = 0;
const cleanupErrors: unknown[] = [];
- for (const file of files) {
- await cleanupFile(deps, file).catch((cleanupError) => {
- cleanupErrors.push(cleanupError);
- logger.error('[GitHubSkillSync] Failed to clean up mirrored skill file:', cleanupError);
- });
- deletedFiles++;
+ if (!deletion.failedCleanupSteps.includes('skill_files')) {
+ for (const file of files) {
+ await cleanupFile(deps, file).catch((cleanupError) => {
+ cleanupErrors.push(cleanupError);
+ logger.error('[GitHubSkillSync] Failed to clean up mirrored skill file:', cleanupError);
+ });
+ deletedFiles++;
+ }
+ }
+ if (!deletion.cleanupComplete) {
+ throw new Error(
+ `Skill cleanup did not finish: ${deletion.failedCleanupSteps.join(', ') || 'unknown step'}`,
+ );
}
- await deps.deleteSkill(skill._id.toString());
if (cleanupErrors.length > 0) {
throw cleanupErrors[0];
}
diff --git a/packages/data-provider/src/file-config.spec.ts b/packages/data-provider/src/file-config.spec.ts
index 908117c913..cecd38bfc8 100644
--- a/packages/data-provider/src/file-config.spec.ts
+++ b/packages/data-provider/src/file-config.spec.ts
@@ -968,6 +968,20 @@ describe('getEndpointFileConfig', () => {
expect(merged.skills?.fileSizeLimit).toBe(15 * 1024 * 1024);
});
+ it('defaults skill rollback concurrency and preserves configured overrides', () => {
+ expect(mergeFileConfig(undefined).skills?.importCleanupConcurrency).toBe(8);
+ const parsed = fileConfigSchema.parse({ skills: { importCleanupConcurrency: 3 } });
+ const merged = mergeFileConfig(parsed);
+ expect(merged.skills?.importCleanupConcurrency).toBe(3);
+ expect(merged.skills?.fileSizeLimit).toBe(50 * 1024 * 1024);
+ });
+
+ it.each([0, -1, 1.5])('rejects invalid rollback concurrency %s', (concurrency) => {
+ expect(
+ fileConfigSchema.safeParse({ skills: { importCleanupConcurrency: concurrency } }).success,
+ ).toBe(false);
+ });
+
it('should default skills fileSizeLimit to 50 MB', () => {
const merged = mergeFileConfig(undefined);
diff --git a/packages/data-provider/src/file-config.ts b/packages/data-provider/src/file-config.ts
index 0123c2b6a6..e4541c9cac 100644
--- a/packages/data-provider/src/file-config.ts
+++ b/packages/data-provider/src/file-config.ts
@@ -3,6 +3,9 @@ import type { EndpointFileConfig, FileConfig, RegexLike } from './types/files';
import { EModelEndpoint, isAgentsEndpoint, isDocumentSupportedProvider } from './schemas';
import { normalizeEndpointName } from './utils';
+/** Parallel storage deletions during rollback of a failed skill archive import. */
+export const DEFAULT_SKILL_IMPORT_CLEANUP_CONCURRENCY = 8;
+
export const supportsFiles = {
[EModelEndpoint.openAI]: true,
[EModelEndpoint.google]: true,
@@ -536,6 +539,7 @@ export const fileConfig = {
},
skills: {
fileSizeLimit: defaultSkillImportSizeLimit,
+ importCleanupConcurrency: DEFAULT_SKILL_IMPORT_CLEANUP_CONCURRENCY,
},
serverFileSizeLimit: defaultSizeLimit,
avatarSizeLimit: mbToBytes(2),
@@ -588,6 +592,7 @@ export const endpointFileConfigSchema = z.object({
const skillFileConfigSchema = z.object({
fileSizeLimit: z.number().min(0).optional(),
+ importCleanupConcurrency: z.number().int().positive().optional(),
});
export const fileConfigSchema = z.object({
@@ -1214,6 +1219,13 @@ export function mergeFileConfig(dynamic: z.infer<typeof fileConfigSchema> | unde
mergedConfig.fileContextCharLimit = dynamic.fileContextCharLimit;
}
+ if (dynamic.skills?.importCleanupConcurrency !== undefined) {
+ mergedConfig.skills = {
+ ...mergedConfig.skills,
+ importCleanupConcurrency: dynamic.skills.importCleanupConcurrency,
+ };
+ }
+
if (dynamic.skills?.fileSizeLimit !== undefined) {
mergedConfig.skills = {
...mergedConfig.skills,
diff --git a/packages/data-provider/src/types/files.ts b/packages/data-provider/src/types/files.ts
index 2651cc6ddb..5a415af39b 100644
--- a/packages/data-provider/src/types/files.ts
+++ b/packages/data-provider/src/types/files.ts
@@ -62,6 +62,8 @@ export type FileConfig = {
[key: string]: EndpointFileConfig;
};
skills?: {
+ /** Maximum concurrent blob deletions during failed archive import cleanup. */
+ importCleanupConcurrency?: number;
fileSizeLimit?: number;
};
fileTokenLimit?: number;
@@ -101,6 +103,8 @@ export type FileConfigInput = {
[key: string]: EndpointFileConfig;
};
skills?: {
+ /** Maximum concurrent blob deletions during failed archive import cleanup. */
+ importCleanupConcurrency?: number;
fileSizeLimit?: number;
};
serverFileSizeLimit?: number;
diff --git a/packages/data-provider/src/types/skills.ts b/packages/data-provider/src/types/skills.ts
index c0bd89198e..a01fe79a1e 100644
--- a/packages/data-provider/src/types/skills.ts
+++ b/packages/data-provider/src/types/skills.ts
@@ -348,10 +348,59 @@ export type TSkillListResponse = {
after: string | null;
};
+/**
+ * Why one archive entry could not be imported. A stable code rather than a
+ * message, so the client localizes the reason and server-side storage and
+ * database text never reaches the uploader.
+ */
+export type SkillImportFailureReason =
+ /** Path is absolute, traverses, or uses characters skills cannot store. */
+ | 'invalid_path'
+ /** Entry alone exceeds the per-file decompression limit. */
+ | 'file_too_large'
+ /** Archive exhausted the cumulative decompression budget at or before this entry. */
+ | 'archive_too_large'
+ /** Entry no longer matches what content inspection read. */
+ | 'archive_entry_changed'
+ /** Storage write or database row failed. */
+ | 'persistence_failed';
+
+/** One archive entry POST `/api/skills/import` could not persist. */
+export type TSkillImportFailedFile = {
+ /** Path inside the archive, relative to `SKILL.md`. */
+ path: string;
+ reason: SkillImportFailureReason;
+ /** Limit in MB, when `reason` names a size limit. */
+ limitMb?: number;
+};
+
+/**
+ * Response from a failed `POST /api/skills/import` of an archive.
+ *
+ * `skill_import_incomplete` (422) means at least one bundled file failed and
+ * everything the import created was rolled back. `skill_import_rollback_failed`
+ * (500) means the same failure occurred but the partially created skill could
+ * not be removed, so it may still be listed and needs deleting by hand.
+ * `skill_import_cleanup_incomplete` (500) means the Skill row was removed but
+ * dependent database or blob cleanup did not finish.
+ */
+export type TSkillImportFailedResponse = {
+ error:
+ | 'skill_import_incomplete'
+ | 'skill_import_rollback_failed'
+ | 'skill_import_cleanup_incomplete';
+ message: string;
+ failedFiles: TSkillImportFailedFile[];
+ /** Present when the Skill row may remain and should be surfaced for deletion. */
+ skillId?: string;
+};
+
/** Response from DELETE `/api/skills/:id`. */
export type TDeleteSkillResponse = {
id: string;
deleted: true;
+ /** False when the Skill row is gone but a dependent cleanup step needs repair. */
+ cleanupComplete?: boolean;
};
/** Response from GET `/api/skills/:id/files`. */
diff --git a/packages/data-schemas/src/methods/index.ts b/packages/data-schemas/src/methods/index.ts
index 1c7f4563ef..f84fd5f1e2 100644
--- a/packages/data-schemas/src/methods/index.ts
+++ b/packages/data-schemas/src/methods/index.ts
@@ -128,6 +128,8 @@ import {
type ListSkillsByAccessResult,
type UpdateSkillResult,
type ValidationIssue,
+ type DeleteSkillCleanupStep,
+ type DeleteSkillResult,
} from './skill';
import { createScheduleMethods, type ScheduleMethods } from './schedule';
import {
@@ -553,6 +555,8 @@ export type {
ListSkillsByAccessResult,
UpdateSkillResult,
ValidationIssue,
+ DeleteSkillCleanupStep,
+ DeleteSkillResult,
SkillSyncStatusInput,
SkillSyncCredentialSummary,
UpsertSkillSyncCredentialInput,
diff --git a/packages/data-schemas/src/methods/skill.spec.ts b/packages/data-schemas/src/methods/skill.spec.ts
index 387ee66885..c7145e2cd4 100644
--- a/packages/data-schemas/src/methods/skill.spec.ts
+++ b/packages/data-schemas/src/methods/skill.spec.ts
@@ -807,7 +807,7 @@ describe('Skill CRUD methods', () => {
expect(filtered).toEqual([canonical]);
});
- it('deleteSkill prunes agent allowlists even when skill file cleanup fails', async () => {
+ it('deleteSkill remains retryable after skill file cleanup fails', async () => {
const { skill } = await methods.createSkill(makeSkillInput({ name: 'flaky-files' }));
const Agent = mongoose.models.Agent;
const agent = await Agent.create(makeAgentDoc([skill._id.toString()]));
@@ -816,9 +816,21 @@ describe('Skill CRUD methods', () => {
.spyOn(SkillFile, 'deleteMany')
.mockRejectedValueOnce(new Error('transient storage failure'));
try {
- await expect(methods.deleteSkill(skill._id.toString())).rejects.toThrow(
- 'transient storage failure',
- );
+ const first = await methods.deleteSkill(skill._id.toString());
+ expect(first).toEqual({
+ deleted: true,
+ skillAbsent: true,
+ cleanupComplete: false,
+ failedCleanupSteps: ['skill_files'],
+ });
+
+ const retry = await methods.deleteSkill(skill._id.toString());
+ expect(retry).toEqual({
+ deleted: false,
+ skillAbsent: true,
+ cleanupComplete: true,
+ failedCleanupSteps: [],
+ });
} finally {
deleteManySpy.mockRestore();
}
diff --git a/packages/data-schemas/src/methods/skill.ts b/packages/data-schemas/src/methods/skill.ts
index a38afdc576..e807be080d 100644
--- a/packages/data-schemas/src/methods/skill.ts
+++ b/packages/data-schemas/src/methods/skill.ts
@@ -44,6 +44,18 @@ export type ValidationIssue = {
severity?: 'error' | 'warning';
};
+export type DeleteSkillCleanupStep = 'agent_allowlists' | 'skill_files' | 'permissions';
+
+export type DeleteSkillResult = {
+ /** Whether this call removed the Skill row. */
+ deleted: boolean;
+ /** Whether the Skill row is absent after this call, including an idempotent retry. */
+ skillAbsent: boolean;
+ /** Whether every dependent database cleanup step completed. */
+ cleanupComplete: boolean;
+ failedCleanupSteps: DeleteSkillCleanupStep[];
+};
+
type SkillFileUpsertResult = {
value: (ISkillFile & { _id: Types.ObjectId }) | null;
lastErrorObject?: {
@@ -1056,7 +1068,7 @@ export function createSkillMethods(
expectedVersion: number;
update: UpdateSkillInput;
}) => Promise<UpdateSkillResult>;
- deleteSkill: (id: string) => Promise<{ deleted: boolean }>;
+ deleteSkill: (id: string) => Promise<DeleteSkillResult>;
deleteUserSkills: (userId: Types.ObjectId | string) => Promise<number>;
findSkillBySourceIdentity: (params: {
source: 'github' | 'notion';
@@ -1669,9 +1681,9 @@ export function createSkillMethods(
* full catalog on purpose -- so disabling them would turn skills off behind
* the author's back.
*/
- async function removeSkillsFromAgentAllowlists(skillIds: string[]): Promise<void> {
+ async function removeSkillsFromAgentAllowlists(skillIds: string[]): Promise<boolean> {
if (skillIds.length === 0) {
- return;
+ return true;
}
const ids = skillIds.map((id) => id.toLowerCase());
const Agent = mongoose.models.Agent as Model<IAgent>;
@@ -1695,36 +1707,54 @@ export function createSkillMethods(
{ $pull: { skills: { $in: ids } } },
{ timestamps: false },
);
+ return true;
} catch (error) {
logger.error(
'[removeSkillsFromAgentAllowlists] Error pruning agent skill allowlists:',
error,
);
+ return false;
}
}
- async function deleteSkill(id: string): Promise<{ deleted: boolean }> {
+ async function deleteSkill(id: string): Promise<DeleteSkillResult> {
if (!isValidObjectIdString(id)) {
- return { deleted: false };
+ return {
+ deleted: false,
+ skillAbsent: false,
+ cleanupComplete: false,
+ failedCleanupSteps: [],
+ };
}
const Skill = mongoose.models.Skill as Model<ISkillDocument>;
const SkillFile = mongoose.models.SkillFile as Model<ISkillFileDocument>;
const objectId = new ObjectId(id);
const res = await Skill.deleteOne({ _id: objectId });
- if (!res.deletedCount) {
- return { deleted: false };
+ const failedCleanupSteps: DeleteSkillCleanupStep[] = [];
+ const allowlistsRemoved = await removeSkillsFromAgentAllowlists([id]);
+ if (!allowlistsRemoved) {
+ failedCleanupSteps.push('agent_allowlists');
}
- /** Prune allowlists immediately after the Skill row is gone: if the
- * SkillFile cleanup below throws, a retry exits early on
- * `deletedCount === 0` and would never reach a later prune. */
- await removeSkillsFromAgentAllowlists([id]);
- await SkillFile.deleteMany({ skillId: objectId });
- try {
- await deps.removeAllPermissions({ resourceType: ResourceType.SKILL, resourceId: id });
- } catch (error) {
- logger.error(`[deleteSkill] Error removing permissions for ${id}:`, error);
+
+ const [filesResult, permissionsResult] = await Promise.allSettled([
+ SkillFile.deleteMany({ skillId: objectId }),
+ deps.removeAllPermissions({ resourceType: ResourceType.SKILL, resourceId: id }),
+ ]);
+ if (filesResult.status === 'rejected') {
+ failedCleanupSteps.push('skill_files');
+ logger.error(`[deleteSkill] Error removing files for ${id}:`, filesResult.reason);
}
- return { deleted: true };
+ if (permissionsResult.status === 'rejected') {
+ failedCleanupSteps.push('permissions');
+ logger.error(`[deleteSkill] Error removing permissions for ${id}:`, permissionsResult.reason);
+ }
+
+ return {
+ deleted: Boolean(res.deletedCount),
+ skillAbsent: true,
+ cleanupComplete: failedCleanupSteps.length === 0,
+ failedCleanupSteps,
+ };
}
async function deleteUserSkills(userId: Types.ObjectId | string): Promise<number> {