Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Add Delete with confirmation to skill bundle files (PRD-7791) (#3202)
tim-inkeepddc7a791f6b2
diff --git a/.changeset/skill-file-delete-action.md b/.changeset/skill-file-delete-action.mdnew file mode 100644index 000000000..1058632f0--- /dev/null+++ b/.changeset/skill-file-delete-action.md@@ -0,0 +1,9 @@+---+'@inkeep/open-knowledge': patch+---++Add a Delete action, with a confirmation dialog, to skill bundle files. It shows up wherever a skill file's actions do: the Skills sidebar row and the file's editor tab. Deleting closes the file's open tab and reports a miss instead of a silent success when the file is already gone.++Editable `.md` reference tabs previously carried no skill-file actions at all; they now offer the same Rename, Reveal in Finder, Copy Path and Delete set as the sidebar row for that file.++Also fixes a pre-existing hazard in `DELETE /api/skill-file`: the live-doc teardown for a project `.md` reference ran before the file's existence was known. Because bundle doc names are extension-less, deleting a path that was not on disk tore down the live doc of a same-stem sibling (`references/x.md` vs `references/x.mdx`) that survived the no-op unlink.diff --git a/packages/app/src/components/EditorTabs.dom.test.tsx b/packages/app/src/components/EditorTabs.dom.test.tsxindex 636d6d772..097976024 100644--- a/packages/app/src/components/EditorTabs.dom.test.tsx+++ b/packages/app/src/components/EditorTabs.dom.test.tsx@@ -621,6 +621,36 @@ describe('EditorTabs runtime behavior', () => {expect(requestSkillFileRename).toHaveBeenCalledWith(skill, filePath);});+ test('reuses the sidebar file actions for an editable reference DOC tab', async () => {+ // A `.md` reference opens as an ordinary doc tab, not a `skill-file` one —+ // it carried no skill actions at all until its bundle path was resolved+ // back from the doc name.+ const skill = {+ scope: 'project',+ name: 'ask-matt',+ path: '.agents/skills/ask-matt/SKILL.md',+ hosts: ['agents'],+ managed: false,+ };+ const docName = '.agents/skills/ask-matt/references/notes';+ activeDocName = docName;+ activeTabId = docName;+ openTabs = [docName];+ visibleTabIds = [docName];+ newTabIds = [];+ skillsState = { status: 'ready', data: [skill] };++ await renderEditorTabs();++ const renameItem = screen.getByRole('menuitem', {+ name: 'Rename skill file references/notes.md',+ });+ expect(renameItem.getAttribute('data-menu-kind')).toBe('context');++ fireEvent.click(renameItem);+ expect(requestSkillFileRename).toHaveBeenCalledWith(skill, 'references/notes.md');+ });+test('uses the host-qualified owner for an editable skill-file tab', async () => {const agentsSkill = {scope: 'global',diff --git a/packages/app/src/components/EditorTabs.tsx b/packages/app/src/components/EditorTabs.tsxindex 11a91cae9..a7b8ce712 100644--- a/packages/app/src/components/EditorTabs.tsx+++ b/packages/app/src/components/EditorTabs.tsx@@ -53,6 +53,7 @@ import {tabParts,} from '@/editor/editor-tabs';import { useLifecycleStatus } from '@/hooks/use-lifecycle-status';+import { skillFileForDocName } from '@/hooks/use-reconcile-skill-tabs';import { useSkills } from '@/hooks/use-skills';import { emitFileTreeMenuActionRename } from '@/lib/file-tree-menu-action-events';import { matchesKeyboardShortcut } from '@/lib/keyboard-shortcuts';@@ -1275,6 +1276,13 @@ export function EditorTabs({const docName = tab.docName;const skill = editableSkillsByTabId.get(docName);const docExt = pageMeta.get(docName)?.docExt ?? '.md';+ // An editable `.md`/`.mdx` reference opens as an ordinary doc+ // tab, not a `skill-file` one, so its bundle-file actions have+ // to be resolved back from the doc name to reach parity with+ // the same file's row in the Skills sidebar.+ const bundleFile = skill+ ? null+ : skillFileForDocName(docName, editableSkills, docExt);const { baseName, extension, label, prefix } = tabParts(docName, docExt);const accessibleLabel = `${prefix}${label}`;const hideDocExtension = docExt === '.md' || docExt === '.mdx';@@ -1314,6 +1322,13 @@ export function EditorTabs({menuKind="context"skill={skill}/>+ ) : bundleFile ? (+ <SkillFileContextMenuItems+ actions={skillActions}+ filePath={bundleFile.filePath}+ menuKind="context"+ skill={bundleFile.skill}+ />) : undefined}unpinTab={unpinTab}diff --git a/packages/app/src/components/SkillFileDeleteDialog.dom.test.tsx b/packages/app/src/components/SkillFileDeleteDialog.dom.test.tsxnew file mode 100644index 000000000..28747c930--- /dev/null+++ b/packages/app/src/components/SkillFileDeleteDialog.dom.test.tsx@@ -0,0 +1,108 @@+/**+ * The three outcomes of a bundle-file delete differ in their SIDE EFFECTS, not+ * just their toast: only a real delete may evict the file's tabs. Swapping the+ * `existed: false` branch with the success branch would either strand tabs on a+ * deleted file or close tabs on a delete that never happened — neither shows up+ * in the helper unit tests, which cover tab SELECTION rather than whether+ * eviction is called at all.+ */++import { render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { beforeEach, describe, expect, test, vi } from 'vitest';+import { skillFileTabId } from '@/editor/editor-tabs';+import * as linguiShim from '../../tests/lingui-macro-shim';++vi.doMock('@lingui/react/macro', () => linguiShim);++const deleteSkillFile = vi.fn();+const closeTabs = vi.fn();+const setSkillsSidebar = vi.fn();+const onOpenChange = vi.fn();+const toastError = vi.fn();+const toastSuccess = vi.fn();++vi.doMock('@/lib/skills-api', () => ({ deleteSkillFile }));+vi.doMock('sonner', () => ({ toast: { error: toastError, success: toastSuccess } }));+vi.doMock('@/editor/DocumentContext', () => ({+ useDocumentContext: () => ({+ setSkillsSidebar,+ closeTabs,+ // The script tab for the file under test, plus an unrelated tab that must+ // survive every branch. Built through the real id helper — the literal form+ // carries a NUL byte, which turns a source file binary to git and grep.+ openTabs: [scriptTabId, 'notes/standup'],+ }),+}));++const scriptTabId = skillFileTabId({+ scope: 'project',+ name: 'demo',+ path: 'scripts/run.sh',+});++const skill = {+ scope: 'project' as const,+ name: 'demo',+ path: '.agents/skills/demo/SKILL.md',+ installed: true,+ hosts: [],+};++async function renderDialog() {+ const { SkillFileDeleteDialog } = await import('./SkillFileDeleteDialog');+ render(+ <SkillFileDeleteDialog+ target={{ skill, filePath: 'scripts/run.sh' }}+ onOpenChange={onOpenChange}+ />,+ );+ return screen.getByRole('button', { name: /^Delete$/ });+}++describe('SkillFileDeleteDialog outcome branches', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ test('a real delete evicts the file tab and closes the dialog', async () => {+ deleteSkillFile.mockResolvedValue({ ok: true, existed: true });+ const confirm = await renderDialog();++ await userEvent.click(confirm);++ expect(deleteSkillFile).toHaveBeenCalledWith({+ scope: 'project',+ name: 'demo',+ path: 'scripts/run.sh',+ });+ expect(closeTabs).toHaveBeenCalledWith([scriptTabId], { force: true });+ expect(setSkillsSidebar).toHaveBeenCalledWith(true);+ expect(toastSuccess).toHaveBeenCalled();+ expect(onOpenChange).toHaveBeenCalledWith(false);+ });++ test('a miss reports failure, closes the dialog, and evicts NOTHING', async () => {+ deleteSkillFile.mockResolvedValue({ ok: true, existed: false });+ const confirm = await renderDialog();++ await userEvent.click(confirm);++ expect(closeTabs).not.toHaveBeenCalled();+ expect(toastSuccess).not.toHaveBeenCalled();+ expect(toastError).toHaveBeenCalled();+ expect(onOpenChange).toHaveBeenCalledWith(false);+ });++ test('a failed request keeps the dialog open and evicts NOTHING', async () => {+ deleteSkillFile.mockResolvedValue({ ok: false, error: 'boom' });+ const confirm = await renderDialog();++ await userEvent.click(confirm);++ expect(closeTabs).not.toHaveBeenCalled();+ expect(toastSuccess).not.toHaveBeenCalled();+ expect(toastError).toHaveBeenCalled();+ expect(onOpenChange).not.toHaveBeenCalled();+ });+});diff --git a/packages/app/src/components/SkillFileDeleteDialog.tsx b/packages/app/src/components/SkillFileDeleteDialog.tsxnew file mode 100644index 000000000..1776836b3--- /dev/null+++ b/packages/app/src/components/SkillFileDeleteDialog.tsx@@ -0,0 +1,81 @@+import type { SkillsListEntry } from '@inkeep/open-knowledge-core';+import { useLingui } from '@lingui/react/macro';+import { useState } from 'react';+import { toast } from 'sonner';+import { DeleteConfirmationDialog } from '@/components/DeleteConfirmationDialog';+import { Dialog } from '@/components/ui/dialog';+import { useDocumentContext } from '@/editor/DocumentContext';+import { tabIdsForSkillFile } from '@/hooks/use-reconcile-skill-tabs';+import { skillDir } from '@/lib/skill-scope';+import { deleteSkillFile } from '@/lib/skills-api';++export interface SkillFileDeleteTarget {+ skill: SkillsListEntry;+ filePath: string;+}++/**+ * Confirm and delete ONE bundle file inside a skill (`references/**`,+ * `scripts/**`, …). The skill itself survives; only the named file goes, so the+ * confirmation names the file rather than the skill. Deleting an editable `.md`+ * reference also tears down its live doc server-side, so the open tab is evicted+ * here rather than left pointing at a doc that no longer exists.+ */+export function SkillFileDeleteDialog({+ target,+ onOpenChange,+}: {+ target: SkillFileDeleteTarget | null;+ onOpenChange: (open: boolean) => void;+}) {+ const { t } = useLingui();+ const { setSkillsSidebar, closeTabs, openTabs } = useDocumentContext();+ const [deleting, setDeleting] = useState(false);++ async function handleDelete({ skill, filePath }: SkillFileDeleteTarget) {+ // Pin the Skills surface before the tab eviction, for the same reason the+ // skill-level delete does: closing the active tab can otherwise let+ // autofollow drop the sidebar back to Files.+ setSkillsSidebar(true);+ setDeleting(true);+ const result = await deleteSkillFile({+ scope: skill.scope,+ name: skill.name,+ path: filePath,+ });+ setDeleting(false);+ if (!result.ok) {+ toast.error(t`Couldn't delete file: ${result.error}`);+ return;+ }+ // The endpoint reports a miss rather than failing, so a path that addressed+ // nothing would otherwise read as a successful delete while the file is+ // still on disk. Say so instead, and leave the tab alone.+ if (!result.existed) {+ toast.error(t`${filePath} is no longer in this skill`);+ onOpenChange(false);+ return;+ }+ toast.success(t`Deleted ${filePath}`);+ closeTabs(tabIdsForSkillFile(openTabs, skill, filePath), { force: true });+ onOpenChange(false);+ }++ return (+ <Dialog+ open={target !== null}+ onOpenChange={(open) => {+ if (!open && !deleting) onOpenChange(false);+ }}+ >+ {target ? (+ <DeleteConfirmationDialog+ itemName={t`"${target.filePath}"`}+ isSubmitting={deleting}+ onDelete={() => handleDelete(target)}+ customDescription={t`This permanently removes ${skillDir(target.skill.path)}/${target.filePath} from the "${target.skill.name}" skill. Anything in SKILL.md that points at it will break until it's recreated.`}+ />+ ) : null}+ </Dialog>+ );+}diff --git a/packages/app/src/components/skill-actions.tsx b/packages/app/src/components/skill-actions.tsxindex 3aa327736..aa234d757 100644--- a/packages/app/src/components/skill-actions.tsx+++ b/packages/app/src/components/skill-actions.tsx@@ -29,6 +29,10 @@ import {SkillFileCreateDialog,type SkillFileCreateTarget,} from '@/components/SkillFileCreateDialog';+import {+ SkillFileDeleteDialog,+ type SkillFileDeleteTarget,+} from '@/components/SkillFileDeleteDialog';import {SkillFileRenameDialog,type SkillFileRenameTarget,@@ -112,6 +116,8 @@ export interface SkillActions {requestScopeMove: (skill: SkillsListEntry, toScope: SkillScope) => void;/** Open the bundle-FILE rename/move dialog (§8.9). */requestFileRename: (skill: SkillsListEntry, filePath: string) => void;+ /** Open the delete-confirm dialog for ONE bundle file. */+ requestFileDelete: (skill: SkillsListEntry, filePath: string) => void;/** Open the new-bundle-file dialog (optionally seeded with a dir prefix). */requestFileCreate: (skill: SkillsListEntry, prefix?: string) => void;/** Open the fork-resolution dialog for a conflicted editor copy. */@@ -130,6 +136,7 @@ export function useSkillActions(): SkillActions {} | null>(null);const [scopeMoveTarget, setScopeMoveTarget] = useState<SkillScopeMoveTarget | null>(null);const [fileRenameTarget, setFileRenameTarget] = useState<SkillFileRenameTarget | null>(null);+ const [fileDeleteTarget, setFileDeleteTarget] = useState<SkillFileDeleteTarget | null>(null);const [fileCreateTarget, setFileCreateTarget] = useState<SkillFileCreateTarget | null>(null);const [forkTarget, setForkTarget] = useState<SkillForkTarget | null>(null);const [installingName, setInstallingName] = useState<string | null>(null);@@ -290,6 +297,12 @@ export function useSkillActions(): SkillActions {if (!open) setFileRenameTarget(null);}}/>+ <SkillFileDeleteDialog+ target={fileDeleteTarget}+ onOpenChange={(open) => {+ if (!open) setFileDeleteTarget(null);+ }}+ /><SkillFileCreateDialogtarget={fileCreateTarget}onOpenChange={(open) => {@@ -316,6 +329,7 @@ export function useSkillActions(): SkillActions {requestScopeMove: (skill, toScope) =>setScopeMoveTarget({ scope: skill.scope, name: skill.name, toScope }),requestFileRename: (skill, filePath) => setFileRenameTarget({ skill, filePath }),+ requestFileDelete: (skill, filePath) => setFileDeleteTarget({ skill, filePath }),requestFileCreate: (skill, prefix) =>setFileCreateTarget(prefix !== undefined ? { skill, prefix } : { skill }),requestForkResolve: (skill, editor) => setForkTarget({ skill, editor }),@@ -357,42 +371,55 @@ export function SkillFileContextMenuItems({}return (- <SkillMenuGroup menuKind={menuKind}>- <SkillMenuItem- menuKind={menuKind}- onSelect={() => actions.requestFileRename(skill, filePath)}- >- <PencilLine aria-hidden />- <Trans>Rename</Trans>- </SkillMenuItem>- {bridge && absoluteFile ? (+ <>+ <SkillMenuGroup menuKind={menuKind}><SkillMenuItemmenuKind={menuKind}- onSelect={() => void bridge.shell.showItemInFolder(absoluteFile)}+ onSelect={() => actions.requestFileRename(skill, filePath)}>- <FolderOpen aria-hidden />- <Trans>Reveal in Finder</Trans>+ <PencilLine aria-hidden />+ <Trans>Rename</Trans></SkillMenuItem>- ) : null}- <SkillMenuSub menuKind={menuKind}>- <SkillMenuSubTrigger menuKind={menuKind}>- <Copy aria-hidden />- <Trans>Copy Path</Trans>- </SkillMenuSubTrigger>- <SkillMenuSubContent menuKind={menuKind}>- <SkillMenuGroup menuKind={menuKind}>- {absoluteFile ? (- <SkillMenuItem menuKind={menuKind} onSelect={() => void copy(absoluteFile)}>- <Trans>Full Path</Trans>+ {bridge && absoluteFile ? (+ <SkillMenuItem+ menuKind={menuKind}+ onSelect={() => void bridge.shell.showItemInFolder(absoluteFile)}+ >+ <FolderOpen aria-hidden />+ <Trans>Reveal in Finder</Trans>+ </SkillMenuItem>+ ) : null}+ <SkillMenuSub menuKind={menuKind}>+ <SkillMenuSubTrigger menuKind={menuKind}>+ <Copy aria-hidden />+ <Trans>Copy Path</Trans>+ </SkillMenuSubTrigger>+ <SkillMenuSubContent menuKind={menuKind}>+ <SkillMenuGroup menuKind={menuKind}>+ {absoluteFile ? (+ <SkillMenuItem menuKind={menuKind} onSelect={() => void copy(absoluteFile)}>+ <Trans>Full Path</Trans>+ </SkillMenuItem>+ ) : null}+ <SkillMenuItem menuKind={menuKind} onSelect={() => void copy(relativeFile)}>+ <Trans>Relative Path</Trans></SkillMenuItem>- ) : null}- <SkillMenuItem menuKind={menuKind} onSelect={() => void copy(relativeFile)}>- <Trans>Relative Path</Trans>- </SkillMenuItem>- </SkillMenuGroup>- </SkillMenuSubContent>- </SkillMenuSub>- </SkillMenuGroup>+ </SkillMenuGroup>+ </SkillMenuSubContent>+ </SkillMenuSub>+ </SkillMenuGroup>+ <SkillMenuSeparator menuKind={menuKind} />+ <SkillMenuGroup menuKind={menuKind}>+ <SkillMenuItem+ menuKind={menuKind}+ variant="destructive"+ onSelect={() => actions.requestFileDelete(skill, filePath)}+ >+ <Trash2 aria-hidden />+ <Trans>Delete</Trans>+ </SkillMenuItem>+ </SkillMenuGroup>+ </>);}diff --git a/packages/app/src/hooks/use-reconcile-skill-tabs.test.ts b/packages/app/src/hooks/use-reconcile-skill-tabs.test.tsindex 75c61be6b..091f73b07 100644--- a/packages/app/src/hooks/use-reconcile-skill-tabs.test.ts+++ b/packages/app/src/hooks/use-reconcile-skill-tabs.test.ts@@ -1,10 +1,16 @@-import { skillFileLiveDocName, skillLiveDocName } from '@inkeep/open-knowledge-core';+import {+ type SkillsListEntry,+ skillFileLiveDocName,+ skillLiveDocName,+} from '@inkeep/open-knowledge-core';import { describe, expect, test } from 'vitest';import { skillFileTabId, skillPreviewTabId } from '@/editor/editor-tabs';import {computeSkillTabReconcile,parseSkillTabDocName,+ skillFileForDocName,tabIdsForSkill,+ tabIdsForSkillFile,} from './use-reconcile-skill-tabs';/**@@ -75,6 +81,81 @@ describe('tabIdsForSkill', () => {});});+describe('tabIdsForSkillFile', () => {+ test('selects both tab shapes for the deleted file, and only that file', () => {+ const skill = { scope: 'project', name: 'demo', path: '.agents/skills/demo/SKILL.md' } as const;+ // A script opens as a dedicated skill-file tab; an editable `.md` reference+ // opens as an ordinary doc tab at its ext-less live doc name.+ const scriptTab = skillFileTabId({+ scope: 'project',+ name: 'demo',+ path: 'scripts/run.sh',+ });+ const refDocTab = '.agents/skills/demo/references/notes';+ const siblingRefTab = '.agents/skills/demo/references/other';+ const skillTab = '.agents/skills/demo/SKILL';++ expect(+ tabIdsForSkillFile([scriptTab, refDocTab, siblingRefTab, skillTab], skill, 'scripts/run.sh'),+ ).toEqual([scriptTab]);+ expect(+ tabIdsForSkillFile(+ [scriptTab, refDocTab, siblingRefTab, skillTab],+ skill,+ 'references/notes.md',+ ),+ ).toEqual([refDocTab]);+ });+});++describe('skillFileForDocName', () => {+ const demo: SkillsListEntry = {+ scope: 'project',+ name: 'demo',+ path: '.agents/skills/demo/SKILL.md',+ installed: true,+ hosts: [],+ };++ test('resolves an editable reference doc tab back to its skill and bundle path', () => {+ expect(skillFileForDocName('.agents/skills/demo/references/notes', [demo], '.md')).toEqual({+ skill: demo,+ filePath: 'references/notes.md',+ });+ });++ test('carries a .mdx extension through, from the SAME doc name', () => {+ // Both extensions strip to this one doc name, so the round-trip guard cannot+ // separate them — whichever extension the caller supplies is the one acted+ // on. Pinned because it is the whole reason a delete miss has to report+ // failure rather than success.+ expect(skillFileForDocName('.agents/skills/demo/references/notes', [demo], '.mdx')).toEqual({+ skill: demo,+ filePath: 'references/notes.mdx',+ });+ });++ test('declines the SKILL doc, an unknown skill, and a plain page', () => {+ expect(skillFileForDocName('.agents/skills/demo/SKILL', [demo], '.md')).toBeNull();+ expect(skillFileForDocName('.agents/skills/other/references/notes', [demo], '.md')).toBeNull();+ expect(skillFileForDocName('notes/standup', [demo], '.md')).toBeNull();+ });++ test('declines a managed built-in (read-only, no mutate menu)', () => {+ const builtin: SkillsListEntry = { ...demo, managed: true };+ expect(+ skillFileForDocName('.agents/skills/demo/references/notes', [builtin], '.md'),+ ).toBeNull();+ });++ test('declines when the skill dir does not round-trip to the doc name', () => {+ // Same skill NAME, different on-disk dir — reconstructing against it would+ // address a file in the wrong folder.+ const moved: SkillsListEntry = { ...demo, path: '.claude/skills/demo/SKILL.md' };+ expect(skillFileForDocName('.agents/skills/demo/references/notes', [moved], '.md')).toBeNull();+ });+});+describe('computeSkillTabReconcile', () => {test('leaves a tab whose skill still exists at its scope untouched', () => {const actions = computeSkillTabReconcile(diff --git a/packages/app/src/hooks/use-reconcile-skill-tabs.ts b/packages/app/src/hooks/use-reconcile-skill-tabs.tsindex 15f2c369a..725f5da3d 100644--- a/packages/app/src/hooks/use-reconcile-skill-tabs.ts+++ b/packages/app/src/hooks/use-reconcile-skill-tabs.ts@@ -8,7 +8,7 @@ import { useEffect, useRef } from 'react';import { useManagedArtifactRetarget } from '@/components/ManagedArtifactProperties';import { useDocumentContext } from '@/editor/DocumentContext';import { parseEditorTabId } from '@/editor/editor-tabs';-import { skillEntryLiveDocName } from '@/lib/managed-artifact-doc-name';+import { skillEntryFileLiveDocName, skillEntryLiveDocName } from '@/lib/managed-artifact-doc-name';import { useSkills } from './use-skills';/**@@ -43,6 +43,58 @@ export function tabIdsForSkill(});}+/**+ * Return every open tab backed by ONE bundle file. A file opens either as a+ * dedicated `skill-file` tab (scripts, binaries, built-ins) or — for an+ * editable `.md`/`.mdx` reference — as an ordinary doc tab at its live doc+ * name, so a delete has to evict both shapes.+ */+export function tabIdsForSkillFile(+ openTabIds: ReadonlyArray<string>,+ skill: Pick<SkillsListEntry, 'scope' | 'name' | 'path'>,+ filePath: string,+): string[] {+ const liveDocName = skillEntryFileLiveDocName(skill, filePath);+ return openTabIds.filter((tabId) => {+ const tab = parseEditorTabId(tabId);+ if (tab.kind === 'skill-file')+ return tab.scope === skill.scope && tab.name === skill.name && tab.path === filePath;+ return tab.kind === 'doc' && tab.docName === liveDocName;+ });+}++/**+ * Resolve an editable bundle-FILE doc tab back to its owning skill and its+ * on-disk bundle path — the inverse of `skillEntryFileLiveDocName`, which is+ * what the Skills sidebar calls to open one. Without this a `references/*.md`+ * tab carried NO skill actions at all (the skill-level map is keyed by the+ * SKILL doc), so the same file offered Rename/Delete in the sidebar and nothing+ * on its own tab.+ *+ * Live doc names are ext-less by design, so the caller supplies the extension+ * (the page index's `docExt`, `.md` when unknown). `.md` and `.mdx` strip to the+ * SAME doc name, so the round-trip below cannot tell them apart — an `.mdx`+ * reference whose extension the page index doesn't carry resolves to a path+ * that isn't on disk. Every writer reports that as a miss rather than a silent+ * success, so it surfaces as "no longer in this skill" instead of deleting the+ * wrong file.+ */+export function skillFileForDocName(+ docName: string,+ skills: ReadonlyArray<SkillsListEntry>,+ docExt: string,+): { skill: SkillsListEntry; filePath: string } | null {+ const parsed = parseSkillTabDocName(docName);+ if (!parsed || parsed.rel === null) return null;+ const skill = skills.find((s) => s.scope === parsed.scope && s.name === parsed.name);+ if (!skill || skill.managed) return null;+ const filePath = `references/${parsed.rel}${docExt}`;+ // Only trust the reconstruction when it round-trips to the doc name we were+ // handed — a skill whose entry sits under a different dir than the tab's+ // would otherwise address a file in the wrong folder.+ return skillEntryFileLiveDocName(skill, filePath) === docName ? { skill, filePath } : null;+}+export type SkillTabReconcileAction =| { kind: 'retarget'; fromDocName: string; toDocName: string }| { kind: 'close'; docName: string };diff --git a/packages/app/src/lib/skills-api.ts b/packages/app/src/lib/skills-api.tsindex a76dceed3..4bf7b622f 100644--- a/packages/app/src/lib/skills-api.ts+++ b/packages/app/src/lib/skills-api.ts@@ -647,6 +647,30 @@ export async function renameSkillFile(input: {}}+/** DELETE `/api/skill-file` — remove ONE bundle file inside a skill. The server+ * closes a project `.md` reference's live doc before unlinking, so the caller+ * only has to evict the tab. */+export async function deleteSkillFile(input: {+ scope: SkillScope;+ name: string;+ path: string;+}): Promise<WriteResult<{ existed: boolean }>> {+ try {+ const params = new URLSearchParams({+ scope: input.scope,+ name: input.name,+ path: input.path,+ });+ const res = await fetch(`/api/skill-file?${params.toString()}`, { method: 'DELETE' });+ if (!res.ok) return { ok: false, error: await readErrorBody(res) };+ const payload = (await res.json().catch(() => null)) as { existed?: boolean } | null;+ emitSkillsChanged();+ return { ok: true, existed: payload?.existed ?? false };+ } catch (err) {+ return { ok: false, error: err instanceof Error ? err.message : String(err) };+ }+}+/** One bundled file beside a skill's `SKILL.md`, with inline read-only text. */export interface SkillBundledFile {path: string;diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex 31cc61ad6..f6b49dfcb 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -782,6 +782,7 @@"C62P6b": ["Editor selection"],"C9TBvF": ["No Outgoing"],"CB7c0Z": ["Save queued message"],+ "CBT70t": ["Couldn't delete file: ", ["0"]],"CBsdhe": ["The agent isn't stopping. Force stop closes this thread and quits the agent."],"CCTop_": ["Recent"],"CD8lBW": ["Tidying up…"],@@ -2630,6 +2631,7 @@"gL_sdV": ["Popular"],"gN3JX8": ["skills.sh"],"gOD68k": ["Open a single markdown file — no project setup."],+ "gOmloS": ["Deleted ", ["filePath"]],"gQV-9w": ["Branch switched but the ",["targetNoun"],@@ -3276,6 +3278,15 @@"pkAft1": ["Search failed."],"pmUArF": ["Workspace"],"ppDgFi": ["Restart with this app's version"],+ "ppzof_": [+ "This permanently removes ",+ ["0"],+ "/",+ ["1"],+ " from the \"",+ ["2"],+ "\" skill. Anything in SKILL.md that points at it will break until it's recreated."+ ],"psfGPX": ["MCP connections"],"psl2Sj": ["Your change is still being saved — run the test again in a moment."],"ptQ3_N": ["unlink"],@@ -3285,6 +3296,7 @@"q3TWG7": ["Move to Trash"],"q3W2nd": ["Couldn't add that comment: ", ["0"]],"q4YJl_": ["The terminal session ended (exit code ", ["0"], ")."],+ "q4efaG": [["filePath"], " is no longer in this skill"],"q6-JVU": ["Loading pages"],"q7F5am": ["title"],"q8aCbb": ["Two versions of \"", ["0"], "\" — source vs ", ["editor"]],@@ -3672,6 +3684,7 @@["projectName"],"\" from recent projects. Its folder no longer exists."],+ "wZPUJx": ["\"", ["0"], "\""],"w_Sphq": ["Attachments"],"wbv9xO": ["Create new project"],"wc54KE": ["Trying it out…"],diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex 4c1c8911c..81e128f96 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -49,6 +49,11 @@ msgstr ".ok/skills is back to Only me."msgid ".ok/skills is committable so your team gets your skills; the rest of .ok/ stays on this computer."msgstr ".ok/skills is committable so your team gets your skills; the rest of .ok/ stays on this computer."+#. placeholder {0}: target.filePath+#: src/components/SkillFileDeleteDialog.tsx+msgid "\"{0}\""+msgstr "\"{0}\""+#. placeholder {0}: skill.name#. placeholder {1}: label(result.hosts)#: src/components/skill-actions.tsx@@ -536,6 +541,10 @@ msgstr "{fileCount, plural, one {# file} other {# files}}"msgid "{fileCount, plural, one {file} other {files}}"msgstr "{fileCount, plural, one {file} other {files}}"+#: src/components/SkillFileDeleteDialog.tsx+msgid "{filePath} is no longer in this skill"+msgstr "{filePath} is no longer in this skill"+#: src/components/CreatedItemsList.tsxmsgid "{folderCount, plural, one {folder} other {folders}}"msgstr "{folderCount, plural, one {folder} other {folders}}"@@ -2983,6 +2992,11 @@ msgstr "Couldn't create the report"msgid "Couldn't create the worktree. Try a different name."msgstr "Couldn't create the worktree. Try a different name."+#. placeholder {0}: result.error+#: src/components/SkillFileDeleteDialog.tsx+msgid "Couldn't delete file: {0}"+msgstr "Couldn't delete file: {0}"+#: src/components/SkillDeleteDialog.tsxmsgid "Couldn't delete skill: {error}"msgstr "Couldn't delete skill: {error}"@@ -3639,6 +3653,10 @@ msgstr "Delete this conversation?"msgid "Deleted {file}"msgstr "Deleted {file}"+#: src/components/SkillFileDeleteDialog.tsx+msgid "Deleted {filePath}"+msgstr "Deleted {filePath}"+#: src/components/FolderTimelineCard.tsxmsgid "deleted template"msgstr "deleted template"@@ -11114,6 +11132,13 @@ msgstr "This permanently removes {0}. Agents that invoke this skill by name willmsgid "This permanently removes {0}. The plugin it was copied from is untouched — its read-only version will show up as detected again."msgstr "This permanently removes {0}. The plugin it was copied from is untouched — its read-only version will show up as detected again."+#. placeholder {0}: skillDir(target.skill.path)+#. placeholder {1}: target.filePath+#. placeholder {2}: target.skill.name+#: src/components/SkillFileDeleteDialog.tsx+msgid "This permanently removes {0}/{1} from the \"{2}\" skill. Anything in SKILL.md that points at it will break until it's recreated."+msgstr "This permanently removes {0}/{1} from the \"{2}\" skill. Anything in SKILL.md that points at it will break until it's recreated."+#: src/components/TemplateDeleteDialog.tsxmsgid "This permanently removes {path}. Agents that reference this template by name will fail until it's recreated or replaced by one in a parent folder."msgstr "This permanently removes {path}. Agents that reference this template by name will fail until it's recreated or replaced by one in a parent folder."diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.jsonindex e3a731c9f..6fd4c2fce 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -782,6 +782,7 @@"C62P6b": ["Ēďĩţōŕ śēĺēćţĩōń"],"C9TBvF": ["Ńō Ōũţĝōĩńĝ"],"CB7c0Z": ["Śàvē ǫũēũēď ḿēśśàĝē"],+ "CBT70t": ["Ćōũĺďń'ţ ďēĺēţē ƒĩĺē: ", ["0"]],"CBsdhe": ["Ţĥē àĝēńţ ĩśń'ţ śţōƥƥĩńĝ. Ƒōŕćē śţōƥ ćĺōśēś ţĥĩś ţĥŕēàď àńď ǫũĩţś ţĥē àĝēńţ."],"CCTop_": ["Ŕēćēńţ"],"CD8lBW": ["Ţĩďŷĩńĝ ũƥ…"],@@ -2630,6 +2631,7 @@"gL_sdV": ["Ƥōƥũĺàŕ"],"gN3JX8": ["śķĩĺĺś.śĥ"],"gOD68k": ["Ōƥēń à śĩńĝĺē ḿàŕķďōŵń ƒĩĺē — ńō ƥŕōĴēćţ śēţũƥ."],+ "gOmloS": ["Ďēĺēţēď ", ["filePath"]],"gQV-9w": ["ßŕàńćĥ śŵĩţćĥēď ƀũţ ţĥē ",["targetNoun"],@@ -3276,6 +3278,15 @@"pkAft1": ["Śēàŕćĥ ƒàĩĺēď."],"pmUArF": ["Ŵōŕķśƥàćē"],"ppDgFi": ["Ŕēśţàŕţ ŵĩţĥ ţĥĩś àƥƥ'ś vēŕśĩōń"],+ "ppzof_": [+ "Ţĥĩś ƥēŕḿàńēńţĺŷ ŕēḿōvēś ",+ ["0"],+ "/",+ ["1"],+ " ƒŕōḿ ţĥē \"",+ ["2"],+ "\" śķĩĺĺ. Àńŷţĥĩńĝ ĩń ŚĶĨĹĹ.ḿď ţĥàţ ƥōĩńţś àţ ĩţ ŵĩĺĺ ƀŕēàķ ũńţĩĺ ĩţ'ś ŕēćŕēàţēď."+ ],"psfGPX": ["ḾĆƤ ćōńńēćţĩōńś"],"psl2Sj": ["Ŷōũŕ ćĥàńĝē ĩś śţĩĺĺ ƀēĩńĝ śàvēď — ŕũń ţĥē ţēśţ àĝàĩń ĩń à ḿōḿēńţ."],"ptQ3_N": ["ũńĺĩńķ"],@@ -3285,6 +3296,7 @@"q3TWG7": ["Ḿōvē ţō Ţŕàśĥ"],"q3W2nd": ["Ćōũĺďń'ţ àďď ţĥàţ ćōḿḿēńţ: ", ["0"]],"q4YJl_": ["Ţĥē ţēŕḿĩńàĺ śēśśĩōń ēńďēď (ēxĩţ ćōďē ", ["0"], ")."],+ "q4efaG": [["filePath"], " ĩś ńō ĺōńĝēŕ ĩń ţĥĩś śķĩĺĺ"],"q6-JVU": ["Ĺōàďĩńĝ ƥàĝēś"],"q7F5am": ["ţĩţĺē"],"q8aCbb": ["Ţŵō vēŕśĩōńś ōƒ \"", ["0"], "\" — śōũŕćē vś ", ["editor"]],@@ -3672,6 +3684,7 @@["projectName"],"\" ƒŕōḿ ŕēćēńţ ƥŕōĴēćţś. Ĩţś ƒōĺďēŕ ńō ĺōńĝēŕ ēxĩśţś."],+ "wZPUJx": ["\"", ["0"], "\""],"w_Sphq": ["Àţţàćĥḿēńţś"],"wbv9xO": ["Ćŕēàţē ńēŵ ƥŕōĴēćţ"],"wc54KE": ["Ţŕŷĩńĝ ĩţ ōũţ…"],diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex 453c6130d..f08bce771 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -49,6 +49,11 @@ msgstr ""msgid ".ok/skills is committable so your team gets your skills; the rest of .ok/ stays on this computer."msgstr ""+#. placeholder {0}: target.filePath+#: src/components/SkillFileDeleteDialog.tsx+msgid "\"{0}\""+msgstr ""+#. placeholder {0}: skill.name#. placeholder {1}: label(result.hosts)#: src/components/skill-actions.tsx@@ -536,6 +541,10 @@ msgstr ""msgid "{fileCount, plural, one {file} other {files}}"msgstr ""+#: src/components/SkillFileDeleteDialog.tsx+msgid "{filePath} is no longer in this skill"+msgstr ""+#: src/components/CreatedItemsList.tsxmsgid "{folderCount, plural, one {folder} other {folders}}"msgstr ""@@ -2979,6 +2988,11 @@ msgstr ""msgid "Couldn't create the worktree. Try a different name."msgstr ""+#. placeholder {0}: result.error+#: src/components/SkillFileDeleteDialog.tsx+msgid "Couldn't delete file: {0}"+msgstr ""+#: src/components/SkillDeleteDialog.tsxmsgid "Couldn't delete skill: {error}"msgstr ""@@ -3635,6 +3649,10 @@ msgstr ""msgid "Deleted {file}"msgstr ""+#: src/components/SkillFileDeleteDialog.tsx+msgid "Deleted {filePath}"+msgstr ""+#: src/components/FolderTimelineCard.tsxmsgid "deleted template"msgstr ""@@ -11110,6 +11128,13 @@ msgstr ""msgid "This permanently removes {0}. The plugin it was copied from is untouched — its read-only version will show up as detected again."msgstr ""+#. placeholder {0}: skillDir(target.skill.path)+#. placeholder {1}: target.filePath+#. placeholder {2}: target.skill.name+#: src/components/SkillFileDeleteDialog.tsx+msgid "This permanently removes {0}/{1} from the \"{2}\" skill. Anything in SKILL.md that points at it will break until it's recreated."+msgstr ""+#: src/components/TemplateDeleteDialog.tsxmsgid "This permanently removes {path}. Agents that reference this template by name will fail until it's recreated or replaced by one in a parent folder."msgstr ""diff --git a/packages/app/tests/integration/skill-bundle-files.test.ts b/packages/app/tests/integration/skill-bundle-files.test.tsindex 8010cc386..7c7548617 100644--- a/packages/app/tests/integration/skill-bundle-files.test.ts+++ b/packages/app/tests/integration/skill-bundle-files.test.ts@@ -1,7 +1,13 @@import { existsSync, readFileSync, writeFileSync } from 'node:fs';import { resolve } from 'node:path';import { afterEach, beforeEach, describe, expect, test } from 'vitest';-import { createTestServer, pollUntil, type TestServer } from './test-harness.ts';+import {+ createTestClient,+ createTestServer,+ getServerState,+ pollUntil,+ type TestServer,+} from './test-harness.ts';/*** End-to-end proof through the real server that the skill BUNDLE-FILE surface@@ -292,6 +298,48 @@ ${String(err)}`,expect(existsSync(abs)).toBe(false);});+ /**+ * A DELETE for a path that is not on disk must not tear anything down. Bundle+ * doc names are ext-less, so `references/x.md` and `references/x.mdx` name the+ * SAME live doc: deleting the absent one used to close connections, mark the+ * doc `deleted-upstream` and unload it, killing the surviving sibling's live+ * doc while the unlink itself no-opped.+ */+ test('DELETE of an absent path leaves a same-stem sibling doc intact', async () => {+ const dirRel = await putSkill('stem-clash', 'stem pin', '# Body\n');+ expect((await putSkillFile('stem-clash', 'references/notes.mdx', '# Notes\n')).status).toBe(+ 200,+ );+ const survivor = resolve(server.contentDir, dirRel, 'references', 'notes.mdx');+ expect(existsSync(survivor)).toBe(true);++ // Open the survivor so there IS a live doc to tear down — the bug is+ // invisible against an unloaded doc. Its name is ext-less, so the absent+ // `.md` sibling below addresses this exact doc.+ const docName = `${dirRel}/references/notes`;+ const client = await createTestClient(server.port, docName);+ await pollUntil(() => getServerState(server, docName) !== null);++ const del = await fetch(+ `${base()}/api/skill-file?name=stem-clash&scope=project&path=${encodeURIComponent('references/notes.md')}`,+ { method: 'DELETE' },+ );+ expect(del.status).toBe(200);+ expect(((await del.json()) as { existed: boolean }).existed).toBe(false);++ // The no-op delete must not have unloaded the doc, marked it+ // deleted-upstream, or dropped the client's connection.+ const state = getServerState(server, docName);+ expect(state).not.toBeNull();+ expect(state?.connectionCount).toBeGreaterThan(0);+ expect(+ server.instance.hocuspocus.documents.get(docName)?.getMap('lifecycle').get('status'),+ ).toBeUndefined();+ expect(existsSync(survivor)).toBe(true);++ await client.cleanup();+ });+/*** §8.9: rename moves the file on disk, moves the live content-doc identity,* and refuses to overwrite an existing destination.diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.tsindex 88da07583..cbc848739 100644--- a/packages/server/src/api-extension.ts+++ b/packages/server/src/api-extension.ts@@ -18797,7 +18797,15 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {// removing the file so its persistence branch can't resurrect it. The// doc name derives from the REAL dir (a minted store shape closed// nothing for an in-place skill).- if (isProjectMdReference(scope, kind, rel)) {+ //+ // Gated on the file actually being there: the teardown closes+ // connections, marks the doc `deleted-upstream` and unloads it, and the+ // doc name is ext-less — so `references/x.md` and `references/x.mdx`+ // name the SAME doc. Deleting a path that isn't on disk would otherwise+ // tear down the live doc of a same-stem sibling that survives the+ // no-op unlink below.+ const bundleAbs = resolve(realDir ?? join(skillsRoot, name), rel);+ if (existsSync(bundleAbs) && isProjectMdReference(scope, kind, rel)) {const extLess = rel.replace(/\.md$/i, '');const refDoc =realDir !== null