Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Handle extensionless file tree renames (#1972)

Dimitri POSTOLOVe40efb947ebc
diff --git a/packages/app/src/components/FileTree.tsx b/packages/app/src/components/FileTree.tsx
index fe5f9595d..ffe616f83 100644
--- a/packages/app/src/components/FileTree.tsx
+++ b/packages/app/src/components/FileTree.tsx
@@ -106,13 +106,18 @@ import {
type FileTreeTarget,
planRenameCleanupCalls,
type RenamedAssetMapping,
+ type RenamedDocExtensionMapping,
type RenamedDocMapping,
type RenamedFolderMapping,
remapActiveDocName,
} from '@/components/file-tree-operations';
-import { applyRenameChip, FILE_TREE_RENAME_CHIP_CSS } from '@/components/file-tree-rename-chip';
+import {
+ applyRenameInputAffordance,
+ FILE_TREE_RENAME_INPUT_CSS,
+} from '@/components/file-tree-rename-chip';
import {
getFileExtension,
+ hasSupportedDocumentExtension,
validateAndCoerceRenameDestination,
} from '@/components/file-tree-rename-validation';
import { revealActiveRow } from '@/components/file-tree-reveal';
@@ -371,7 +376,7 @@ const FILE_TREE_CREATION_CLEARED_CSS = `
}
`;
-const FILE_TREE_UNSAFE_CSS = `${FILE_TREE_EXT_BADGE_CSS}\n${FILE_TREE_RENAME_CHIP_CSS}\n${FILE_TREE_ROOT_DROP_CSS}\n${FILE_TREE_EXTERNAL_FILE_DROP_CSS}\n${FILE_TREE_CREATION_CLEARED_CSS}\n${FILE_TREE_INDENT_GUIDE_CSS}\n${FILE_TREE_STICKY_HEADER_CSS}`;
+const FILE_TREE_UNSAFE_CSS = `${FILE_TREE_EXT_BADGE_CSS}\n${FILE_TREE_RENAME_INPUT_CSS}\n${FILE_TREE_ROOT_DROP_CSS}\n${FILE_TREE_EXTERNAL_FILE_DROP_CSS}\n${FILE_TREE_CREATION_CLEARED_CSS}\n${FILE_TREE_INDENT_GUIDE_CSS}\n${FILE_TREE_STICKY_HEADER_CSS}`;
function isAgentTreePath(treePath: string): boolean {
const name = treePath.split('/').pop()?.replace(/\.md$/i, '').toLowerCase();
@@ -498,7 +503,7 @@ interface FileTreeMenuProps {
folderTreePaths: readonly string[];
isAsset: boolean;
/** Authoritative document list — sourced for `docExt` when Pierre's tree
- * path has lost its extension (post-rename-strip). See `treeItemToTarget`. */
+ * path has lost its extension after a basename-only commit. See `treeItemToTarget`. */
documents: readonly FileEntry[];
}
@@ -1156,8 +1161,9 @@ export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {
);
navigateToWithPulse(action.path, docEntry?.size);
}
- function navigateToAssetWithPulse(assetPath: string) {
- const entry = documentsRef.current.find(
+ function navigateToAssetWithPulse(assetPath: string, entries?: readonly FileEntry[]) {
+ const currentEntries = entries ?? documentsRef.current;
+ const entry = currentEntries.find(
(item): item is Extract<FileEntry, { kind: 'asset' }> =>
isAssetEntry(item) && item.path === assetPath,
);
@@ -1572,7 +1578,7 @@ export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {
}
};
- const reconcileModelAfterChipRename = (
+ const reconcileModelAfterExtensionlessRename = (
current: readonly FileEntry[],
next: readonly FileEntry[],
renamed: readonly RenamedDocMapping[],
@@ -1586,7 +1592,10 @@ export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {
);
if (source == null) continue;
if (model.getItem(toDocName) == null) continue;
- const canonicalTreePath = docNameToTreePath(toDocName, source.docExt);
+ const destination = next.find(
+ (entry): entry is DocumentEntry => isDocumentEntry(entry) && entry.docName === toDocName,
+ );
+ const canonicalTreePath = docNameToTreePath(toDocName, destination?.docExt ?? source.docExt);
model.move(toDocName, canonicalTreePath);
lastCanonical = canonicalTreePath;
reconciledCount += 1;
@@ -2041,9 +2050,32 @@ export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {
folderPath: string | null;
assetPath: string | null;
},
+ renamedDocExtensions: RenamedDocExtensionMapping[] = [],
) => {
const currentActiveDocName = activeBeforeRename?.docName ?? activeDocNameRef.current;
- const nextActiveDocName = remapActiveDocName(currentActiveDocName, renamed);
+ const docToAssetRenames = new Map<string, string>();
+ const assetToDocRenames = new Map<string, string>();
+ for (const entry of documentsRef.current) {
+ if (isDocumentEntry(entry)) {
+ const assetPath = renamedAssets.find(
+ (renamedAsset) =>
+ renamedAsset.fromPath === docNameToTreePath(entry.docName, entry.docExt),
+ )?.toPath;
+ if (assetPath) docToAssetRenames.set(entry.docName, assetPath);
+ continue;
+ }
+ if (isAssetEntry(entry)) {
+ const docPath = renamedAssets.find(
+ (renamedAsset) => renamedAsset.fromPath === entry.path,
+ )?.toPath;
+ if (docPath && hasSupportedDocumentExtension(docPath)) {
+ assetToDocRenames.set(entry.path, treeFilePathToDocName(docPath));
+ }
+ }
+ }
+ const activeDocToAssetPath = currentActiveDocName
+ ? (docToAssetRenames.get(currentActiveDocName) ?? null)
+ : null;
const currentActiveFolderPath =
activeBeforeRename?.folderPath ??
(activeTargetRef.current?.kind === 'folder' ? activeTargetRef.current.folderPath : null);
@@ -2053,22 +2085,46 @@ export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {
const currentActiveAssetPath =
activeBeforeRename?.assetPath ??
(activeTargetRef.current?.kind === 'asset' ? activeTargetRef.current.assetPath : null);
- const nextActiveAssetPath = currentActiveAssetPath
- ? (renamedAssets.find((entry) => entry.fromPath === currentActiveAssetPath)?.toPath ??
- remapPathForFolderRenames(currentActiveAssetPath, renamedFolders))
+ const activeAssetToDoc = currentActiveAssetPath
+ ? (assetToDocRenames.get(currentActiveAssetPath) ?? null)
: null;
+ const nextActiveDocName = activeDocToAssetPath
+ ? null
+ : (activeAssetToDoc ?? remapActiveDocName(currentActiveDocName, renamed));
+ const nextActiveAssetPath =
+ activeDocToAssetPath ??
+ (currentActiveAssetPath
+ ? activeAssetToDoc
+ ? null
+ : (renamedAssets.find((entry) => entry.fromPath === currentActiveAssetPath)?.toPath ??
+ remapPathForFolderRenames(currentActiveAssetPath, renamedFolders))
+ : null);
captureRenameSnapshots(renamed);
- const cleanupDocNames = planRenameCleanupCalls(renamed, getPoolActiveDocName(), poolHas);
+ const cleanupDocNames = [
+ ...planRenameCleanupCalls(renamed, getPoolActiveDocName(), poolHas),
+ ...docToAssetRenames.keys(),
+ ];
await Promise.all(cleanupDocNames.map((docName) => closeAndClearForRename(docName)));
for (const entry of renamed) {
addPage(entry.toDocName);
}
+ for (const entry of assetToDocRenames.values()) {
+ addPage(entry);
+ }
remapTabsForRename(renamed, renamedFolders, renamedAssets);
+ let nextDocumentsForRename: FileEntry[] | null = null;
setDocuments((current) => {
- const next = applyRenameToDocuments(current, renamed, renamedFolders, renamedAssets);
- reconcileModelAfterChipRename(current, next, renamed, renamedAssets);
+ const next = applyRenameToDocuments(
+ current,
+ renamed,
+ renamedFolders,
+ renamedAssets,
+ renamedDocExtensions,
+ );
+ nextDocumentsForRename = next;
+ reconcileModelAfterExtensionlessRename(current, next, renamed, renamedAssets);
markNextDocumentsAsApplied(next);
return next;
});
@@ -2083,11 +2139,10 @@ export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {
navigateToWithPulse(nextActiveDocName);
focusEditorAfterRename(nextActiveDocName);
} else if (
- currentActiveAssetPath &&
nextActiveAssetPath &&
- nextActiveAssetPath !== currentActiveAssetPath
+ (activeDocToAssetPath || nextActiveAssetPath !== currentActiveAssetPath)
) {
- navigateToAssetWithPulse(nextActiveAssetPath);
+ navigateToAssetWithPulse(nextActiveAssetPath, nextDocumentsForRename ?? documentsRef.current);
}
emitDocumentsChanged(['files', 'backlinks', 'graph']);
};
@@ -2106,22 +2161,15 @@ export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {
event.sourcePath,
event.destinationPath,
event.isFolder,
- sourceIsAsset,
);
- if (validation.kind === 'block') {
- toast.error(
- t`File extensions are managed automatically - please rename without changing the extension`,
- );
- queueMicrotask(() => {
- resetModelToDocuments();
- });
- clearPendingCreate();
- setBusyPath(null);
- return;
- }
- const destinationTreePath = sourceIsAsset
- ? validation.destinationPath
- : normalizeTreePathForKind(validation.destinationPath, event.isFolder);
+ const documentBecomesFile =
+ !event.isFolder &&
+ !sourceIsAsset &&
+ !hasSupportedDocumentExtension(validation.destinationPath);
+ const destinationTreePath =
+ sourceIsAsset || documentBecomesFile
+ ? validation.destinationPath
+ : normalizeTreePathForKind(validation.destinationPath, event.isFolder);
const payload = event.isFolder
? {
@@ -2129,7 +2177,7 @@ export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {
fromPath: treeDirectoryPathToFolderPath(sourceTreePath),
toPath: treeDirectoryPathToFolderPath(destinationTreePath),
}
- : sourceIsAsset
+ : sourceIsAsset || documentBecomesFile
? {
kind: 'asset' as const,
fromPath: sourceTreePath,
@@ -2138,7 +2186,7 @@ export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {
: {
kind: 'file' as const,
fromPath: treeFilePathToDocName(sourceTreePath),
- toPath: treeFilePathToDocName(destinationTreePath),
+ toPath: destinationTreePath,
};
const activeBeforeRename = {
docName: activeDocNameRef.current,
@@ -2185,6 +2233,12 @@ export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {
: [],
success.renamedAssets,
activeBeforeRename,
+ !event.isFolder && !sourceIsAsset && !documentBecomesFile
+ ? success.renamed.flatMap((entry): RenamedDocExtensionMapping[] => {
+ const docExt = getFileExtension(destinationTreePath);
+ return docExt ? [{ toDocName: entry.toDocName, docExt }] : [];
+ })
+ : [],
);
} catch (reconcileErr) {
console.warn('[FileTree] post-rename reconciliation failed', {
@@ -2753,7 +2807,7 @@ export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {
if (loading || documents.length === 0) return;
const shadow = fileTreeHostRef.current?.querySelector(FILE_TREE_TAG_NAME)?.shadowRoot;
if (!shadow) return;
- const apply = () => applyRenameChip(shadow);
+ const apply = () => applyRenameInputAffordance(shadow);
apply();
const observer = new MutationObserver(apply);
observer.observe(shadow, {
diff --git a/packages/app/src/components/file-tree-operations.test.ts b/packages/app/src/components/file-tree-operations.test.ts
index 71810caff..a2d0eac49 100644
--- a/packages/app/src/components/file-tree-operations.test.ts
+++ b/packages/app/src/components/file-tree-operations.test.ts
@@ -87,6 +87,22 @@ describe('file-tree-operations', () => {
).toEqual(['docs/renamed', 'guides/nested/page', 'docs/empty', 'docs/image.png', 'README']);
});
+ test('applyRenameToDocuments updates docExt for explicit extension-change rename', () => {
+ const [renamed] = applyRenameToDocuments(
+ [{ kind: 'document', docName: 'docs/notes', docExt: '.md', size: 10, modified: '' }],
+ [{ fromDocName: 'docs/notes', toDocName: 'docs/notes' }],
+ [],
+ [],
+ [{ toDocName: 'docs/notes', docExt: '.mdx' }],
+ );
+
+ expect(renamed).toMatchObject({
+ kind: 'document',
+ docName: 'docs/notes',
+ docExt: '.mdx',
+ });
+ });
+
test('applyRenameToDocuments remaps explicit folder and asset paths', () => {
expect(
applyRenameToDocuments(documents, [], [{ fromPath: 'docs', toPath: 'guides' }]).map(
@@ -106,6 +122,51 @@ describe('file-tree-operations', () => {
).toEqual(['docs/notes', 'docs/nested/page', 'docs/empty', 'docs/hero.png', 'README']);
});
+ test('applyRenameToDocuments converts a markdown document renamed to a non-document file', () => {
+ const [renamed] = applyRenameToDocuments(
+ [{ kind: 'document', docName: 'docs/notes', docExt: '.md', size: 10, modified: 'now' }],
+ [],
+ [],
+ [{ fromPath: 'docs/notes.md', toPath: 'docs/notes.txt' }],
+ );
+
+ expect(renamed).toEqual({
+ kind: 'asset',
+ path: 'docs/notes.txt',
+ assetExt: 'txt',
+ mediaKind: null,
+ size: 10,
+ modified: 'now',
+ referencedBy: [],
+ });
+ });
+
+ test('applyRenameToDocuments converts a non-document file renamed to markdown', () => {
+ const [renamed] = applyRenameToDocuments(
+ [
+ {
+ kind: 'asset',
+ path: 'docs/notes.txt',
+ assetExt: 'txt',
+ mediaKind: null,
+ size: 10,
+ modified: 'now',
+ },
+ ],
+ [],
+ [],
+ [{ fromPath: 'docs/notes.txt', toPath: 'docs/notes.md' }],
+ );
+
+ expect(renamed).toEqual({
+ kind: 'document',
+ docName: 'docs/notes',
+ docExt: '.md',
+ size: 10,
+ modified: 'now',
+ });
+ });
+
test('applyDeleteToDocuments removes all deleted doc names', () => {
expect(
applyDeleteToDocuments(documents, ['docs/notes', 'docs/nested/page']).map((entry) =>
diff --git a/packages/app/src/components/file-tree-operations.ts b/packages/app/src/components/file-tree-operations.ts
index e9196f9a7..57fe28594 100644
--- a/packages/app/src/components/file-tree-operations.ts
+++ b/packages/app/src/components/file-tree-operations.ts
@@ -3,12 +3,22 @@ import type {
RenamedAssetMapping,
RenamedDocMapping,
} from '@inkeep/open-knowledge-core';
-import { docNameToTreePath, resolveExtensionlessAssetPath } from '@/components/file-tree-adapter';
+import { mediaKindForSidebarAssetExtension } from '@inkeep/open-knowledge-core';
+import {
+ docNameToTreePath,
+ resolveExtensionlessAssetPath,
+ treeFilePathToDocName,
+} from '@/components/file-tree-adapter';
+import {
+ getFileExtension,
+ hasSupportedDocumentExtension,
+} from '@/components/file-tree-rename-validation';
import {
type FileEntry,
isAssetEntry,
isDocumentEntry,
isFolderEntry,
+ synthesizeFileAssetExt,
} from '@/components/file-tree-utils';
import { joinWorkspacePath, type Workspace } from '@/lib/workspace-paths';
@@ -19,6 +29,11 @@ export interface RenamedFolderMapping {
toPath: string;
}
+export interface RenamedDocExtensionMapping {
+ toDocName: string;
+ docExt: string;
+}
+
interface FileTreeTargetBase {
path: string;
name: string;
@@ -57,17 +72,41 @@ export function applyRenameToDocuments(
renamed: RenamedDocMapping[],
renamedFolders: RenamedFolderMapping[] = [],
renamedAssets: RenamedAssetMapping[] = [],
+ renamedDocExtensions: RenamedDocExtensionMapping[] = [],
): FileEntry[] {
- if (renamed.length === 0 && renamedFolders.length === 0 && renamedAssets.length === 0) {
+ if (
+ renamed.length === 0 &&
+ renamedFolders.length === 0 &&
+ renamedAssets.length === 0 &&
+ renamedDocExtensions.length === 0
+ ) {
return documents;
}
const renamedMap = new Map(renamed.map((entry) => [entry.fromDocName, entry.toDocName]));
+ const renamedDocExtMap = new Map(
+ renamedDocExtensions.map((entry) => [entry.toDocName, entry.docExt]),
+ );
const renamedAssetMap = new Map(renamedAssets.map((entry) => [entry.fromPath, entry.toPath]));
return documents.map((entry) => {
if (isDocumentEntry(entry)) {
+ const assetPath = renamedAssetMap.get(docNameToTreePath(entry.docName, entry.docExt));
+ if (assetPath) {
+ const assetExt = synthesizeFileAssetExt(assetPath);
+ return {
+ kind: 'asset',
+ path: assetPath,
+ assetExt,
+ mediaKind: mediaKindForSidebarAssetExtension(assetExt),
+ size: entry.size,
+ modified: entry.modified,
+ referencedBy: [],
+ };
+ }
+ const docName = renamedMap.get(entry.docName) ?? entry.docName;
return {
...entry,
- docName: renamedMap.get(entry.docName) ?? entry.docName,
+ docName,
+ docExt: renamedDocExtMap.get(docName) ?? entry.docExt,
};
}
if (isFolderEntry(entry)) {
@@ -77,10 +116,19 @@ export function applyRenameToDocuments(
};
}
if (isAssetEntry(entry)) {
+ const renamedAssetPath = renamedAssetMap.get(entry.path);
+ if (renamedAssetPath && hasSupportedDocumentExtension(renamedAssetPath)) {
+ return {
+ kind: 'document',
+ docName: treeFilePathToDocName(renamedAssetPath),
+ docExt: getFileExtension(renamedAssetPath),
+ size: entry.size,
+ modified: entry.modified,
+ };
+ }
return {
...entry,
- path:
- renamedAssetMap.get(entry.path) ?? remapPathForFolderRenames(entry.path, renamedFolders),
+ path: renamedAssetPath ?? remapPathForFolderRenames(entry.path, renamedFolders),
};
}
return entry;
diff --git a/packages/app/src/components/file-tree-rename-chip.dom.test.tsx b/packages/app/src/components/file-tree-rename-chip.dom.test.tsx
index 9f60eacd8..3dbb04ed1 100644
--- a/packages/app/src/components/file-tree-rename-chip.dom.test.tsx
+++ b/packages/app/src/components/file-tree-rename-chip.dom.test.tsx
@@ -1,9 +1,8 @@
import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { cleanup } from '@testing-library/react';
import {
- __resetRenameChipForTesting,
- applyRenameChip,
- OK_RENAME_CHIP_ATTR,
+ __resetRenameInputAffordanceForTesting,
+ applyRenameInputAffordance,
OK_RENAMING_ATTR,
} from './file-tree-rename-chip';
@@ -56,111 +55,113 @@ function buildPierreShadowRoot(): ShadowRoot {
return shadow;
}
-describe('applyRenameChip — strip extension + inject chip + select basename', () => {
+describe('applyRenameInputAffordance — keep extension editable + select filename stem', () => {
afterEach(() => {
cleanup();
document.body.innerHTML = '';
});
- test('strips `.md` from input value and injects a `.md` chip sibling', () => {
- const { input, content } = buildPierreRenameRow({
+ test('keeps `.md` in the input value and selects only the filename stem', () => {
+ const { input } = buildPierreRenameRow({
path: 'AGENTS.md',
initialValue: 'AGENTS.md',
});
- applyRenameChip(document);
+ applyRenameInputAffordance(document);
- expect(input.value).toBe('AGENTS');
- const chip = content.querySelector(`[${OK_RENAME_CHIP_ATTR}]`);
- expect(chip).not.toBeNull();
- expect(chip?.textContent).toBe('.md');
- expect(chip?.getAttribute('aria-hidden')).toBe('true');
+ expect(input.value).toBe('AGENTS.md');
+ expect(input.selectionStart).toBe(0);
+ expect(input.selectionEnd).toBe('AGENTS'.length);
});
- test('strips `.mdx` from input value and injects a `.mdx` chip sibling', () => {
- const { input, content } = buildPierreRenameRow({
+ test('keeps `.mdx` editable and selects only the filename stem', () => {
+ const { input } = buildPierreRenameRow({
path: 'notes/ideas.mdx',
initialValue: 'ideas.mdx',
});
- applyRenameChip(document);
+ applyRenameInputAffordance(document);
- expect(input.value).toBe('ideas');
- expect(content.querySelector(`[${OK_RENAME_CHIP_ATTR}]`)?.textContent).toBe('.mdx');
+ expect(input.value).toBe('ideas.mdx');
+ expect(input.selectionStart).toBe(0);
+ expect(input.selectionEnd).toBe('ideas'.length);
});
- test('strips non-markdown extensions (jpg, pdf, etc.) with the same lowercase chip', () => {
- const { input, content } = buildPierreRenameRow({
- path: 'images/cat.jpg',
- initialValue: 'cat.jpg',
+ test('keeps asset extensions editable and selects only the stem', () => {
+ const { input } = buildPierreRenameRow({
+ path: '.mcp.json',
+ initialValue: '.mcp.json',
});
- applyRenameChip(document);
+ applyRenameInputAffordance(document);
- expect(input.value).toBe('cat');
- expect(content.querySelector(`[${OK_RENAME_CHIP_ATTR}]`)?.textContent).toBe('.jpg');
+ expect(input.value).toBe('.mcp.json');
+ expect(input.selectionStart).toBe(0);
+ expect(input.selectionEnd).toBe('.mcp'.length);
});
- test('selects the basename after stripping (selectionStart=0, selectionEnd=basename length)', () => {
+ test('new file placeholder shows `Untitled.md` and selects `Untitled`', () => {
const { input } = buildPierreRenameRow({
- path: 'README.md',
- initialValue: 'README.md',
+ path: 'Untitled.md',
+ initialValue: 'Untitled.md',
});
- applyRenameChip(document);
+ applyRenameInputAffordance(document);
- expect(input.value).toBe('README');
+ expect(input.value).toBe('Untitled.md');
expect(input.selectionStart).toBe(0);
- expect(input.selectionEnd).toBe('README'.length);
+ expect(input.selectionEnd).toBe('Untitled'.length);
});
- test('folder rows (path ends with `/`) are ignored — no chip, no strip', () => {
- const { input, content } = buildPierreRenameRow({
+ test('folder rows (path ends with `/`) are ignored', () => {
+ const { input } = buildPierreRenameRow({
path: 'docs/',
initialValue: 'docs',
});
- applyRenameChip(document);
+ applyRenameInputAffordance(document);
expect(input.value).toBe('docs');
- expect(content.querySelector(`[${OK_RENAME_CHIP_ATTR}]`)).toBeNull();
});
- test('extension-less files are ignored — no chip, no strip', () => {
- const { input, content } = buildPierreRenameRow({
+ test('extension-less files keep their value and select the full filename', () => {
+ const { input } = buildPierreRenameRow({
path: 'Makefile',
initialValue: 'Makefile',
});
- applyRenameChip(document);
+ applyRenameInputAffordance(document);
expect(input.value).toBe('Makefile');
- expect(content.querySelector(`[${OK_RENAME_CHIP_ATTR}]`)).toBeNull();
+ expect(input.selectionStart).toBe(0);
+ expect(input.selectionEnd).toBe('Makefile'.length);
});
- test('idempotent — repeated calls during the same rename session do not re-strip or re-select', () => {
- const { input, content } = buildPierreRenameRow({
+ test('idempotent — repeated calls during the same rename session do not re-select', () => {
+ const { input } = buildPierreRenameRow({
path: 'AGENTS.md',
initialValue: 'AGENTS.md',
});
- applyRenameChip(document);
- expect(input.value).toBe('AGENTS');
+ applyRenameInputAffordance(document);
+ expect(input.value).toBe('AGENTS.md');
- input.value = 'AGENTS-edited';
+ input.value = 'AGENTS-edited.md';
input.setSelectionRange(10, 13); // caret somewhere inside the typed text
- applyRenameChip(document);
- expect(input.value).toBe('AGENTS-edited');
+ applyRenameInputAffordance(document);
+ expect(input.value).toBe('AGENTS-edited.md');
expect(input.selectionStart).toBe(10);
expect(input.selectionEnd).toBe(13);
- expect(content.querySelectorAll(`[${OK_RENAME_CHIP_ATTR}]`).length).toBe(1);
});
- test('idempotent across user typing the extension back in (no double-strip)', () => {
+ test('idempotent across user editing the extension', () => {
const { input } = buildPierreRenameRow({
path: 'AGENTS.md',
initialValue: 'AGENTS.md',
});
- applyRenameChip(document);
- expect(input.value).toBe('AGENTS');
-
- input.value = 'AGENTS.md.bak';
- applyRenameChip(document);
- expect(input.value).toBe('AGENTS.md.bak');
+ applyRenameInputAffordance(document);
+ expect(input.value).toBe('AGENTS.md');
+
+ input.value = 'AGENTS.mdx';
+ input.setSelectionRange('AGENTS.'.length, 'AGENTS.mdx'.length);
+ applyRenameInputAffordance(document);
+ expect(input.value).toBe('AGENTS.mdx');
+ expect(input.selectionStart).toBe('AGENTS.'.length);
+ expect(input.selectionEnd).toBe('AGENTS.mdx'.length);
});
test('survives ShadowRoot context — find works through the open shadow root', () => {
@@ -177,10 +178,11 @@ describe('applyRenameChip — strip extension + inject chip + select basename',
content.appendChild(input);
shadow.appendChild(row);
- applyRenameChip(shadow);
+ applyRenameInputAffordance(shadow);
- expect(input.value).toBe('AGENTS');
- expect(content.querySelector(`[${OK_RENAME_CHIP_ATTR}]`)?.textContent).toBe('.md');
+ expect(input.value).toBe('AGENTS.md');
+ expect(input.selectionStart).toBe(0);
+ expect(input.selectionEnd).toBe('AGENTS'.length);
});
test('no rename input present — no-op', () => {
@@ -192,29 +194,44 @@ describe('applyRenameChip — strip extension + inject chip + select basename',
row.appendChild(content);
document.body.appendChild(row);
- expect(() => applyRenameChip(document)).not.toThrow();
- expect(content.querySelector(`[${OK_RENAME_CHIP_ATTR}]`)).toBeNull();
+ expect(() => applyRenameInputAffordance(document)).not.toThrow();
});
});
-describe('applyRenameChip — overlay marker for symptom 2 (icon-flash bridge)', () => {
+describe('applyRenameInputAffordance — overlay marker for symptom 2 (icon-flash bridge)', () => {
beforeEach(() => {
- __resetRenameChipForTesting();
+ __resetRenameInputAffordanceForTesting();
});
afterEach(() => {
cleanup();
document.body.innerHTML = '';
- __resetRenameChipForTesting();
+ __resetRenameInputAffordanceForTesting();
});
- test('chip-activate stamps the row with data-ok-renaming=<extension>', () => {
+ test('rename-input mount does not stamp the row, avoiding a duplicate markdown icon', () => {
const { row } = buildPierreRenameRow({
path: 'AGENTS.md',
initialValue: 'AGENTS.md',
});
- applyRenameChip(document);
+ applyRenameInputAffordance(document);
- expect(row.getAttribute(OK_RENAMING_ATTR)).toBe('.md');
+ expect(row.getAttribute(OK_RENAMING_ATTR)).toBeNull();
+ });
+
+ test('non-markdown asset renames never stamp the overlay marker', () => {
+ const { row, input } = buildPierreRenameRow({
+ path: '.mcp.json',
+ initialValue: '.mcp.json',
+ });
+ applyRenameInputAffordance(document);
+ expect(row.getAttribute(OK_RENAMING_ATTR)).toBeNull();
+
+ input.remove();
+ row.setAttribute('data-item-path', '.mcp');
+ row.setAttribute('data-item-selected', 'true');
+ applyRenameInputAffordance(document);
+
+ expect(row.getAttribute(OK_RENAMING_ATTR)).toBeNull();
});
test('after Pierre commits — selected extensionless row gets the marker reapplied', () => {
@@ -222,15 +239,15 @@ describe('applyRenameChip — overlay marker for symptom 2 (icon-flash bridge)',
path: 'AGENTS.md',
initialValue: 'AGENTS.md',
});
- applyRenameChip(document);
- expect(row.getAttribute(OK_RENAMING_ATTR)).toBe('.md');
+ applyRenameInputAffordance(document);
+ expect(row.getAttribute(OK_RENAMING_ATTR)).toBeNull();
input.remove();
row.setAttribute('data-item-path', 'AGENTS-RENAMED');
row.setAttribute('data-item-selected', 'true');
row.removeAttribute(OK_RENAMING_ATTR);
- applyRenameChip(document);
+ applyRenameInputAffordance(document);
expect(row.getAttribute(OK_RENAMING_ATTR)).toBe('.md');
});
@@ -244,11 +261,11 @@ describe('applyRenameChip — overlay marker for symptom 2 (icon-flash bridge)',
path: 'docs/photo.md',
initialValue: 'docs/photo.md',
});
- applyRenameChip(document);
+ applyRenameInputAffordance(document);
input.remove();
- applyRenameChip(document);
+ applyRenameInputAffordance(document);
expect(makefileRow.getAttribute(OK_RENAMING_ATTR)).toBeNull();
const renamedRow = document.body.querySelector(
@@ -260,7 +277,7 @@ describe('applyRenameChip — overlay marker for symptom 2 (icon-flash bridge)',
renamedRow.setAttribute('data-item-selected', 'true');
renamedRow.removeAttribute(OK_RENAMING_ATTR);
- applyRenameChip(document);
+ applyRenameInputAffordance(document);
expect(renamedRow.getAttribute(OK_RENAMING_ATTR)).toBe('.md');
expect(makefileRow.getAttribute(OK_RENAMING_ATTR)).toBeNull();
@@ -271,18 +288,18 @@ describe('applyRenameChip — overlay marker for symptom 2 (icon-flash bridge)',
path: 'AGENTS.md',
initialValue: 'AGENTS.md',
});
- applyRenameChip(document);
- expect(row.getAttribute(OK_RENAMING_ATTR)).toBe('.md');
+ applyRenameInputAffordance(document);
+ expect(row.getAttribute(OK_RENAMING_ATTR)).toBeNull();
input.remove();
row.setAttribute('data-item-path', 'AGENTS-RENAMED');
row.setAttribute('data-item-selected', 'true');
row.removeAttribute(OK_RENAMING_ATTR);
- applyRenameChip(document);
+ applyRenameInputAffordance(document);
expect(row.getAttribute(OK_RENAMING_ATTR)).toBe('.md');
row.setAttribute('data-item-path', 'AGENTS-RENAMED.md');
- applyRenameChip(document);
+ applyRenameInputAffordance(document);
expect(row.getAttribute(OK_RENAMING_ATTR)).toBeNull();
});
@@ -291,12 +308,12 @@ describe('applyRenameChip — overlay marker for symptom 2 (icon-flash bridge)',
path: 'AGENTS.md',
initialValue: 'AGENTS.md',
});
- applyRenameChip(document);
- expect(row.getAttribute(OK_RENAMING_ATTR)).toBe('.md');
+ applyRenameInputAffordance(document);
+ expect(row.getAttribute(OK_RENAMING_ATTR)).toBeNull();
input.remove();
row.setAttribute('data-item-path', 'images/cat.jpg');
- applyRenameChip(document);
+ applyRenameInputAffordance(document);
expect(row.getAttribute(OK_RENAMING_ATTR)).toBeNull();
});
@@ -305,12 +322,12 @@ describe('applyRenameChip — overlay marker for symptom 2 (icon-flash bridge)',
path: 'AGENTS.md',
initialValue: 'AGENTS.md',
});
- applyRenameChip(document);
- expect(row.getAttribute(OK_RENAMING_ATTR)).toBe('.md');
+ applyRenameInputAffordance(document);
+ expect(row.getAttribute(OK_RENAMING_ATTR)).toBeNull();
input.remove();
row.setAttribute('data-item-path', 'AGENTS-RENAMED.md'); // disk-truth refresh
- applyRenameChip(document);
+ applyRenameInputAffordance(document);
expect(row.getAttribute(OK_RENAMING_ATTR)).toBeNull();
const makefileRow = document.createElement('div');
@@ -319,7 +336,7 @@ describe('applyRenameChip — overlay marker for symptom 2 (icon-flash bridge)',
makefileRow.setAttribute('data-item-selected', 'true');
document.body.appendChild(makefileRow);
- applyRenameChip(document);
+ applyRenameInputAffordance(document);
expect(makefileRow.getAttribute(OK_RENAMING_ATTR)).toBeNull();
});
});
diff --git a/packages/app/src/components/file-tree-rename-chip.ts b/packages/app/src/components/file-tree-rename-chip.ts
index 4fcbdd6fd..80acf6ec5 100644
--- a/packages/app/src/components/file-tree-rename-chip.ts
+++ b/packages/app/src/components/file-tree-rename-chip.ts
@@ -1,47 +1,32 @@
-import { getFileExtension } from '@/components/file-tree-rename-validation';
+import {
+ getFileExtension,
+ hasSupportedDocumentExtension,
+} from '@/components/file-tree-rename-validation';
-export const OK_RENAME_CHIP_ATTR = 'data-ok-rename-extension-chip';
export const OK_RENAMING_ATTR = 'data-ok-renaming';
-const RENAME_STRIPPED_MARKER = 'data-ok-rename-stripped';
+const RENAME_SELECTION_MARKER = 'data-ok-rename-selection-applied';
let activeRenameExt: string | null = null;
let activeRenameTimer: ReturnType<typeof setTimeout> | null = null;
const ACTIVE_RENAME_TIMEOUT_MS = 5_000;
-export const FILE_TREE_RENAME_CHIP_CSS = `
- [data-item-section="content"]:has([data-item-rename-input]) {
- position: relative;
- }
- [data-item-section="content"]:has([${OK_RENAME_CHIP_ATTR}]) [data-item-rename-input] {
- padding-inline-end: 36px;
- }
- [${OK_RENAME_CHIP_ATTR}] {
- position: absolute;
- top: 50%;
- right: 6px;
- transform: translateY(-50%);
- font-size: 0.6875rem;
- line-height: 1;
- letter-spacing: 0.02em;
- color: color-mix(in oklab, var(--muted-foreground) 60%, transparent);
- background: transparent;
- padding: 2px 4px;
- border-radius: 3px;
- pointer-events: none;
- user-select: none;
- }
- /* Pierre's icon decoration keys off the row's data-item-path. The chip's
- value-strip plus Pierre's optimistic commit make the path temporarily
- extensionless, so Pierre swaps the row's [data-icon-token] from
- 'markdown' to 'default' until the disk-truth refresh restores .md.
+export const FILE_TREE_RENAME_INPUT_CSS = `
+ /* Pierre's icon decoration keys off the row's data-item-path. If the user
+ deletes the extension before commit, Pierre can temporarily key the row
+ by an extensionless path and swap [data-icon-token] from 'markdown' to
+ 'default' until the disk-truth refresh restores .md.
Cover the wrong icon with a CSS-rendered markdown glyph for the duration.
- applyRenameChip sets the marker on the row when the rename input mounts;
- the sweep in applyRenameChip clears it when the path next includes the
- saved extension (settle / cancel / row recycle to a settled file). */
- [${OK_RENAMING_ATTR}] [data-item-section="icon"] {
+ applyRenameInputAffordance records the in-flight markdown extension when
+ the input mounts; the sweep stamps the marker only if Pierre later moves
+ the row to an extensionless path, then clears it when the path next
+ includes the saved extension (settle / cancel / row recycle to a settled
+ file). */
+ [${OK_RENAMING_ATTR}='.md'] [data-item-section="icon"],
+ [${OK_RENAMING_ATTR}='.mdx'] [data-item-section="icon"] {
position: relative;
}
- [${OK_RENAMING_ATTR}] [data-item-section="icon"] [data-icon-token]:not([data-icon-token='markdown']) {
+ [${OK_RENAMING_ATTR}='.md'] [data-item-section="icon"] [data-icon-token]:not([data-icon-token='markdown']),
+ [${OK_RENAMING_ATTR}='.mdx'] [data-item-section="icon"] [data-icon-token]:not([data-icon-token='markdown']) {
visibility: hidden;
}
[${OK_RENAMING_ATTR}='.md'] [data-item-section="icon"]::before,
@@ -59,29 +44,22 @@ export const FILE_TREE_RENAME_CHIP_CSS = `
}
`;
-export function applyRenameChip(root: ParentNode): void {
+export function applyRenameInputAffordance(root: ParentNode): void {
syncRenameOverlay(root);
const input = root.querySelector<HTMLInputElement>('[data-item-rename-input]');
if (!input) return;
- const content = input.closest<HTMLElement>('[data-item-section="content"]');
const row = input.closest<HTMLElement>('[data-type="item"]');
- if (!content || !row) return;
+ if (!row) return;
const treePath = row.dataset.itemPath ?? '';
if (treePath.endsWith('/')) return;
const extension = getFileExtension(treePath);
- if (!extension) return;
+ if (hasSupportedDocumentExtension(treePath)) setActiveRenameExt(extension);
- upsertChip(content, extension);
- if (row.getAttribute(OK_RENAMING_ATTR) !== extension) {
- row.setAttribute(OK_RENAMING_ATTR, extension);
- }
- setActiveRenameExt(extension);
-
- if (input.hasAttribute(RENAME_STRIPPED_MARKER)) return;
- stripExtensionFromValue(input, extension);
- input.setAttribute(RENAME_STRIPPED_MARKER, '');
+ if (input.hasAttribute(RENAME_SELECTION_MARKER)) return;
+ selectFilenameStem(input);
+ input.setAttribute(RENAME_SELECTION_MARKER, '');
}
function setActiveRenameExt(ext: string): void {
@@ -100,7 +78,7 @@ function clearActiveRenameExt(): void {
/** Test-only — reset the module's in-flight rename state so a fresh test
* starts from a known baseline. Not used at runtime. */
-export function __resetRenameChipForTesting(): void {
+export function __resetRenameInputAffordanceForTesting(): void {
clearActiveRenameExt();
}
@@ -149,29 +127,8 @@ function syncRenameOverlay(root: ParentNode): void {
}
}
-function upsertChip(content: HTMLElement, label: string): void {
- let chip = content.querySelector<HTMLSpanElement>(`[${OK_RENAME_CHIP_ATTR}]`);
- if (!chip) {
- chip = content.ownerDocument.createElement('span');
- chip.setAttribute(OK_RENAME_CHIP_ATTR, '');
- chip.setAttribute('aria-hidden', 'true');
- content.appendChild(chip);
- }
- if (chip.textContent !== label) chip.textContent = label;
-}
-
-function stripExtensionFromValue(input: HTMLInputElement, extension: string): void {
- const currentValue = input.value;
- if (!currentValue.toLowerCase().endsWith(extension.toLowerCase())) return;
-
- const nativeSetter = Object.getOwnPropertyDescriptor(
- window.HTMLInputElement.prototype,
- 'value',
- )?.set;
- if (!nativeSetter) return;
-
- const stripped = currentValue.slice(0, -extension.length);
- nativeSetter.call(input, stripped);
- input.dispatchEvent(new Event('input', { bubbles: true }));
- input.setSelectionRange(0, stripped.length);
+function selectFilenameStem(input: HTMLInputElement): void {
+ const extension = getFileExtension(input.value);
+ const selectionEnd = extension ? input.value.length - extension.length : input.value.length;
+ input.setSelectionRange(0, selectionEnd);
}
diff --git a/packages/app/src/components/file-tree-rename-focus-reconciliation.dom.test.tsx b/packages/app/src/components/file-tree-rename-focus-reconciliation.dom.test.tsx
index 8be79dfa8..16075a06c 100644
--- a/packages/app/src/components/file-tree-rename-focus-reconciliation.dom.test.tsx
+++ b/packages/app/src/components/file-tree-rename-focus-reconciliation.dom.test.tsx
@@ -390,7 +390,7 @@ interface RenameEvent {
function simulatePierreCommitRename(
source: string,
- chipStrippedDest: string,
+ extensionlessDest: string,
isFolder: boolean,
): void {
const options = capturedOptions as { renaming?: { onRename?: (e: RenameEvent) => void } } | null;
@@ -398,8 +398,8 @@ function simulatePierreCommitRename(
if (!onRename) {
throw new Error('onRename callback missing from captured Pierre options');
}
- onRename({ sourcePath: source, destinationPath: chipStrippedDest, isFolder });
- model.move(source, chipStrippedDest);
+ onRename({ sourcePath: source, destinationPath: extensionlessDest, isFolder });
+ model.move(source, extensionlessDest);
}
describe('FileTree post-rename Pierre/React store reconciliation', () => {
diff --git a/packages/app/src/components/file-tree-rename-validation.test.ts b/packages/app/src/components/file-tree-rename-validation.test.ts
index 5c878759d..7c0542ecc 100644
--- a/packages/app/src/components/file-tree-rename-validation.test.ts
+++ b/packages/app/src/components/file-tree-rename-validation.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, test } from 'bun:test';
import {
getFileExtension,
+ hasSupportedDocumentExtension,
replaceFileExtension,
validateAndCoerceRenameDestination,
} from './file-tree-rename-validation';
@@ -94,7 +95,7 @@ describe('replaceFileExtension', () => {
});
describe('validateAndCoerceRenameDestination — allow paths', () => {
- test('matching extension allows the rename and coerces casing to source', () => {
+ test('matching extension allows the rename', () => {
expect(validateAndCoerceRenameDestination('foo.md', 'bar.md', false)).toEqual({
kind: 'allow',
destinationPath: 'bar.md',
@@ -108,9 +109,9 @@ describe('validateAndCoerceRenameDestination — allow paths', () => {
});
});
- test('chip-stripped destination preserves source extension on commit (chip↔validator contract)', () => {
+ test('basename-only destination preserves source extension on commit', () => {
const source = 'specs/RELEASES.md';
- const userTypedBasename = 'specs/RELEASES-v2'; // user typed in chip-mode
+ const userTypedBasename = 'specs/RELEASES-v2';
const result = validateAndCoerceRenameDestination(source, userTypedBasename, false);
expect(result).toEqual({
kind: 'allow',
@@ -118,10 +119,10 @@ describe('validateAndCoerceRenameDestination — allow paths', () => {
});
});
- test('user used a different casing of the same extension → coerce to source casing', () => {
+ test('user used a different casing of the same supported extension → preserve typed casing', () => {
expect(validateAndCoerceRenameDestination('foo.md', 'bar.MD', false)).toEqual({
kind: 'allow',
- destinationPath: 'bar.md',
+ destinationPath: 'bar.MD',
});
});
@@ -168,40 +169,64 @@ describe('validateAndCoerceRenameDestination — allow paths', () => {
destinationPath: 'bar.mdx',
});
});
-});
-describe('validateAndCoerceRenameDestination — block paths', () => {
- test('user types a different extension (.md → .tx) → block', () => {
- expect(validateAndCoerceRenameDestination('foo.md', 'bar.tx', false)).toEqual({
- kind: 'block',
+ test('user changes document extension .md → .mdx explicitly', () => {
+ expect(validateAndCoerceRenameDestination('foo.md', 'bar.mdx', false)).toEqual({
+ kind: 'allow',
+ destinationPath: 'bar.mdx',
});
});
- test('user changes type .md → .mdx → block (different doc type, explicit change)', () => {
- expect(validateAndCoerceRenameDestination('foo.md', 'bar.mdx', false)).toEqual({
- kind: 'block',
+ test('user changes document extension .mdx → .md explicitly', () => {
+ expect(validateAndCoerceRenameDestination('foo.mdx', 'bar.md', false)).toEqual({
+ kind: 'allow',
+ destinationPath: 'bar.md',
});
});
- test('block is independent of directory depth', () => {
+ test('user types an arbitrary document extension (.md → .tx) → allow as-is', () => {
+ expect(validateAndCoerceRenameDestination('foo.md', 'bar.tx', false)).toEqual({
+ kind: 'allow',
+ destinationPath: 'bar.tx',
+ });
+ });
+
+ test('arbitrary extension allowance is independent of directory depth', () => {
expect(
validateAndCoerceRenameDestination('meetings/2026/foo.md', 'meetings/2026/foo.notes', false),
- ).toEqual({ kind: 'block' });
+ ).toEqual({
+ kind: 'allow',
+ destinationPath: 'meetings/2026/foo.notes',
+ });
});
- test('user adds a multi-dot suffix that looks like a different extension → block', () => {
+ test('user adds a multi-dot suffix that looks like a different extension → allow as-is', () => {
expect(validateAndCoerceRenameDestination('foo.md', 'report.2026', false)).toEqual({
- kind: 'block',
+ kind: 'allow',
+ destinationPath: 'report.2026',
});
});
- test('block is case-insensitive on comparison (.MD == .md, but .TX != .md)', () => {
+ test('arbitrary extension allowance preserves typed casing', () => {
expect(validateAndCoerceRenameDestination('foo.md', 'bar.TX', false)).toEqual({
- kind: 'block',
+ kind: 'allow',
+ destinationPath: 'bar.TX',
});
});
});
+describe('hasSupportedDocumentExtension', () => {
+ test('recognizes managed markdown extensions case-insensitively', () => {
+ expect(hasSupportedDocumentExtension('foo.md')).toBe(true);
+ expect(hasSupportedDocumentExtension('foo.MDX')).toBe(true);
+ });
+
+ test('returns false for arbitrary file extensions', () => {
+ expect(hasSupportedDocumentExtension('foo.txt')).toBe(false);
+ expect(hasSupportedDocumentExtension('foo')).toBe(false);
+ });
+});
+
describe('validateAndCoerceRenameDestination — folder short-circuit', () => {
test('folder rename always allows the destination as-is (no extension to preserve)', () => {
expect(validateAndCoerceRenameDestination('meetings', 'archived-meetings', true)).toEqual({
@@ -227,18 +252,16 @@ describe('validateAndCoerceRenameDestination — folder short-circuit', () => {
describe('validateAndCoerceRenameDestination — asset paths', () => {
test('asset rename allows extension changes as-is', () => {
- expect(
- validateAndCoerceRenameDestination('media/image.png', 'media/image.jpg', false, true),
- ).toEqual({
- kind: 'allow',
- destinationPath: 'media/image.jpg',
- });
+ expect(validateAndCoerceRenameDestination('media/image.png', 'media/image.jpg', false)).toEqual(
+ {
+ kind: 'allow',
+ destinationPath: 'media/image.jpg',
+ },
+ );
});
test('asset rename preserves the source extension when omitted', () => {
- expect(
- validateAndCoerceRenameDestination('media/image.png', 'media/image', false, true),
- ).toEqual({
+ expect(validateAndCoerceRenameDestination('media/image.png', 'media/image', false)).toEqual({
kind: 'allow',
destinationPath: 'media/image.png',
});
diff --git a/packages/app/src/components/file-tree-rename-validation.ts b/packages/app/src/components/file-tree-rename-validation.ts
index c036aa5df..c6be16e43 100644
--- a/packages/app/src/components/file-tree-rename-validation.ts
+++ b/packages/app/src/components/file-tree-rename-validation.ts
@@ -1,4 +1,5 @@
-type RenameDestinationValidation = { kind: 'allow'; destinationPath: string } | { kind: 'block' };
+type RenameDestinationValidation = { kind: 'allow'; destinationPath: string };
+const SUPPORTED_DOCUMENT_EXTENSIONS = new Set(['.md', '.mdx']);
export function getFileExtension(path: string): string {
const lastSlash = path.lastIndexOf('/');
@@ -17,27 +18,21 @@ export function replaceFileExtension(path: string, newExt: string): string {
return `${dir}${basenameNoExt}${newExt}`;
}
+export function hasSupportedDocumentExtension(path: string): boolean {
+ return SUPPORTED_DOCUMENT_EXTENSIONS.has(getFileExtension(path).toLowerCase());
+}
+
export function validateAndCoerceRenameDestination(
sourcePath: string,
destinationPath: string,
isFolder: boolean,
- isAsset = false,
): RenameDestinationValidation {
if (isFolder) return { kind: 'allow', destinationPath };
const sourceExt = getFileExtension(sourcePath);
if (sourceExt === '') return { kind: 'allow', destinationPath };
const destExt = getFileExtension(destinationPath);
- if (isAsset) {
- return {
- kind: 'allow',
- destinationPath: destExt ? destinationPath : replaceFileExtension(destinationPath, sourceExt),
- };
- }
- if (destExt && destExt.toLowerCase() !== sourceExt.toLowerCase()) {
- return { kind: 'block' };
- }
return {
kind: 'allow',
- destinationPath: replaceFileExtension(destinationPath, sourceExt),
+ destinationPath: destExt ? destinationPath : replaceFileExtension(destinationPath, sourceExt),
};
}
diff --git a/packages/app/src/components/file-tree-utils.ts b/packages/app/src/components/file-tree-utils.ts
index 74c916334..e19ae1ef2 100644
--- a/packages/app/src/components/file-tree-utils.ts
+++ b/packages/app/src/components/file-tree-utils.ts
@@ -127,7 +127,7 @@ export function toFileEntries(entries: readonly DocumentListEntry[]): FileEntry[
return mapped;
}
-function synthesizeFileAssetExt(path: string): string {
+export function synthesizeFileAssetExt(path: string): string {
const basename = path.includes('/') ? (path.split('/').pop() ?? path) : path;
const dotIndex = basename.lastIndexOf('.');
if (dotIndex > 0 && dotIndex < basename.length - 1) {
diff --git a/packages/app/src/editor/editor-tabs.test.ts b/packages/app/src/editor/editor-tabs.test.ts
index ce0ab4a72..323d40a5f 100644
--- a/packages/app/src/editor/editor-tabs.test.ts
+++ b/packages/app/src/editor/editor-tabs.test.ts
@@ -446,6 +446,32 @@ describe('editor tab state', () => {
]);
});
+ test('remapOpenTabs converts document tabs after document-to-file rename', () => {
+ expect(
+ remapOpenTabs(
+ ['docs/a', `${docTabId('docs/a')}\u0000doc-tab:1`, 'docs/b'],
+ [],
+ 10,
+ [],
+ [],
+ [{ fromPath: 'docs/a.md', toPath: 'docs/a.txt' }],
+ ),
+ ).toEqual([assetTabId('docs/a.txt'), `${assetTabId('docs/a.txt')}\u0000doc-tab:1`, 'docs/b']);
+ });
+
+ test('remapOpenTabs converts asset tabs after file-to-document rename', () => {
+ expect(
+ remapOpenTabs(
+ [assetTabId('docs/a.txt'), `${assetTabId('docs/a.txt')}\u0000doc-tab:1`, 'docs/b'],
+ [],
+ 10,
+ [],
+ [],
+ [{ fromPath: 'docs/a.txt', toPath: 'docs/a.md' }],
+ ),
+ ).toEqual(['docs/a', `docs/a\u0000doc-tab:1`, 'docs/b']);
+ });
+
test('remapOpenTabs preserves pinned tabs while capping unpinned tabs', () => {
expect(
remapOpenTabs(
diff --git a/packages/app/src/editor/editor-tabs.ts b/packages/app/src/editor/editor-tabs.ts
index 7696258be..3d2940a37 100644
--- a/packages/app/src/editor/editor-tabs.ts
+++ b/packages/app/src/editor/editor-tabs.ts
@@ -25,6 +25,7 @@ const LOCAL_TAB_SESSION_PREFIX = 'ok-editor-tabs-v1:';
const FOLDER_TAB_PREFIX = '\u0000folder:';
const ASSET_TAB_PREFIX = '\u0000asset:';
const TAB_INSTANCE_SEPARATOR = '\u0000doc-tab:';
+const MARKDOWN_TAB_EXTENSION_PATTERN = /\.(md|mdx)$/i;
interface OpenTabOptions {
behavior: 'append' | 'replace-active';
@@ -46,6 +47,12 @@ function baseTabId(tabId: string): string {
return splitTabInstance(tabId).baseTabId;
}
+function stripMarkdownTabExtension(path: string): string | null {
+ return MARKDOWN_TAB_EXTENSION_PATTERN.test(path)
+ ? path.replace(MARKDOWN_TAB_EXTENSION_PATTERN, '')
+ : null;
+}
+
function isValidTabId(value: unknown): value is string {
if (typeof value !== 'string' || value.length === 0) return false;
const base = baseTabId(value);
@@ -373,8 +380,30 @@ export function remapOpenTabs(
return normalizeOpenTabs(tabs, limit);
}
const bySource = new Map(mappings.map((entry) => [entry.fromDocName, entry.toDocName]));
+ const docToAssetBySource = new Map(
+ assetMappings.flatMap((entry) => {
+ const sourceDocName = stripMarkdownTabExtension(entry.fromPath);
+ return sourceDocName ? [[sourceDocName, entry.toPath] as const] : [];
+ }),
+ );
+ const assetToDocBySource = new Map(
+ assetMappings.flatMap((entry) => {
+ const targetDocName = stripMarkdownTabExtension(entry.toPath);
+ return targetDocName ? [[entry.fromPath, targetDocName] as const] : [];
+ }),
+ );
const remapAssetPath = (assetPath: string) =>
remapPathForAssetRenames(remapPathForFolderRenames(assetPath, folderMappings), assetMappings);
+ const remapDocTabBase = (docName: string, fallbackTabId: string): string => {
+ const renamedDocName = bySource.get(docName);
+ if (renamedDocName) return renamedDocName;
+ const assetPath = docToAssetBySource.get(docName);
+ return assetPath ? assetTabId(assetPath) : fallbackTabId;
+ };
+ const remapAssetTabBase = (assetPath: string): string => {
+ const docName = assetToDocBySource.get(assetPath);
+ return docName ? docTabId(docName) : assetTabId(remapAssetPath(assetPath));
+ };
const next: string[] = [];
const seen = new Set<string>();
for (const tab of tabs) {
@@ -382,10 +411,10 @@ export function remapOpenTabs(
const parsed = parseEditorTabId(tab);
const mappedBase =
parsed.kind === 'doc'
- ? (bySource.get(parsed.docName) ?? baseTabId(tab))
+ ? remapDocTabBase(parsed.docName, baseTabId(tab))
: parsed.kind === 'folder'
? folderTabId(remapPathForFolderRenames(parsed.folderPath, folderMappings))
- : assetTabId(remapAssetPath(parsed.assetPath));
+ : remapAssetTabBase(parsed.assetPath);
const mapped = `${mappedBase}${instanceSuffix}`;
if (seen.has(mapped)) continue;
seen.add(mapped);
@@ -396,10 +425,10 @@ export function remapOpenTabs(
const remappedPinnedTabIds = pinnedTabIds.map((tabId) => {
const parsed = parseEditorTabId(tabId);
return parsed.kind === 'doc'
- ? (bySource.get(parsed.docName) ?? tabId)
+ ? remapDocTabBase(parsed.docName, tabId)
: parsed.kind === 'folder'
? folderTabId(remapPathForFolderRenames(parsed.folderPath, folderMappings))
- : assetTabId(remapAssetPath(parsed.assetPath));
+ : remapAssetTabBase(parsed.assetPath);
});
return capOpenTabsPreservingPinned(next, limit, remappedPinnedTabIds);
}
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index 7191fe22a..b26514506 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -544,9 +544,6 @@
"FRYB1Q": ["/api/config returned a malformed body"],
"FTUGgh": ["Enter a repository URL or owner/repo"],
"FUMerq": ["Could not enable sync: ", ["detail"]],
- "FaBZwp": [
- "File extensions are managed automatically - please rename without changing the extension"
- ],
"FjkaiT": ["Zoom out"],
"FnMkli": ["Sync disabled — you don't have permission to push"],
"FqTpiN": ["Bird wiki"],
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index 89c4fc1f7..d215e1fcf 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -2475,10 +2475,6 @@ msgstr "File drop zone"
msgid "File duplicated"
msgstr "File duplicated"
-#: src/components/FileTree.tsx
-msgid "File extensions are managed automatically - please rename without changing the extension"
-msgstr "File extensions are managed automatically - please rename without changing the extension"
-
#: src/components/NewItemDialog.tsx
msgid "File name"
msgstr "File name"
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index d61c9ca25..baaede039 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -544,9 +544,6 @@
"FRYB1Q": ["/àƥĩ/ćōńƒĩĝ ŕēţũŕńēď à ḿàĺƒōŕḿēď ƀōďŷ"],
"FTUGgh": ["Ēńţēŕ à ŕēƥōśĩţōŕŷ ŨŔĹ ōŕ ōŵńēŕ/ŕēƥō"],
"FUMerq": ["Ćōũĺď ńōţ ēńàƀĺē śŷńć: ", ["detail"]],
- "FaBZwp": [
- "Ƒĩĺē ēxţēńśĩōńś àŕē ḿàńàĝēď àũţōḿàţĩćàĺĺŷ - ƥĺēàśē ŕēńàḿē ŵĩţĥōũţ ćĥàńĝĩńĝ ţĥē ēxţēńśĩōń"
- ],
"FjkaiT": ["Źōōḿ ōũţ"],
"FnMkli": ["Śŷńć ďĩśàƀĺēď — ŷōũ ďōń'ţ ĥàvē ƥēŕḿĩśśĩōń ţō ƥũśĥ"],
"FqTpiN": ["ßĩŕď ŵĩķĩ"],
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index 650600e9f..52a4f2e71 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -2470,10 +2470,6 @@ msgstr ""
msgid "File duplicated"
msgstr ""
-#: src/components/FileTree.tsx
-msgid "File extensions are managed automatically - please rename without changing the extension"
-msgstr ""
-
#: src/components/NewItemDialog.tsx
msgid "File name"
msgstr ""
diff --git a/packages/app/tests/stress/file-tree-decoration-chip-strip-repro.e2e.ts b/packages/app/tests/stress/file-tree-decoration-chip-strip-repro.e2e.ts
index ba50d8876..9f4d01d9f 100644
--- a/packages/app/tests/stress/file-tree-decoration-chip-strip-repro.e2e.ts
+++ b/packages/app/tests/stress/file-tree-decoration-chip-strip-repro.e2e.ts
@@ -3,7 +3,7 @@ import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
import { expect, test } from './_helpers';
-test.describe('CHECK: renderRowDecoration is robust through chip-strip rename', () => {
+test.describe('CHECK: renderRowDecoration is robust through inline rename', () => {
test('symlink badge stays present at every step of inline rename', async ({
page,
api,
@@ -33,10 +33,7 @@ test.describe('CHECK: renderRowDecoration is robust through chip-strip rename',
const renameInput = sidebar.getByRole('textbox', { name: /rename foo\.md/i });
await expect(renameInput).toBeVisible({ timeout: 5_000 });
- await expect(renameInput).toHaveAttribute('data-ok-rename-stripped', '', {
- timeout: 5_000,
- });
- await expect(renameInput).toHaveValue('foo');
+ await expect(renameInput).toHaveValue('foo.md');
await expect(fooRow).toBeVisible(); // still queryable by data-item-path="foo.md"
const extensionlessRow = sidebar.locator('[data-type="item"][data-item-path="foo"]');
@@ -44,7 +41,7 @@ test.describe('CHECK: renderRowDecoration is robust through chip-strip rename',
await expect(decorationIcon).toHaveCount(1);
- await renameInput.fill('bar');
+ await renameInput.fill('bar.md');
await wait(150); // settle
await expect(fooRow).toBeVisible();
diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.ts
index 88e627be2..bd3cae826 100644
--- a/packages/server/src/api-extension.ts
+++ b/packages/server/src/api-extension.ts
@@ -1505,6 +1505,17 @@ function collectFolderPaths(contentDir: string, folderPath: string): string[] {
function probeAndRegisterSourceFileExtension(contentDir: string, fromPath: string): void {
if (!isValidRelativeContentPath(fromPath)) return;
const resolvedContentDir = resolve(contentDir);
+ if (isSupportedDocFile(fromPath)) {
+ const candidate = resolve(resolvedContentDir, fromPath);
+ if (
+ candidate !== resolvedContentDir &&
+ candidate.startsWith(`${resolvedContentDir}${sep}`) &&
+ existsSync(candidate)
+ ) {
+ registerDocExtension(stripDocExtension(fromPath), extname(fromPath));
+ }
+ return;
+ }
for (const ext of SUPPORTED_DOC_EXTENSIONS) {
const candidate = resolve(resolvedContentDir, `${fromPath}${ext}`);
if (candidate !== resolvedContentDir && !candidate.startsWith(`${resolvedContentDir}${sep}`)) {
@@ -2505,19 +2516,6 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
throw new BacklinkIndexRequiredError();
}
const destinationAssetPath = extname(toPath) ? toPath : `${toPath}${extname(fromPath)}`;
- if (isSupportedDocFile(fromPath) || isSupportedDocFile(destinationAssetPath)) {
- throw new ManagedRenameInvalidRequestError(
- 'Asset operations do not support markdown documents.',
- );
- }
- if (
- !isSupportedAssetFile(fromPath, LINKABLE_ASSET_EXTENSIONS) ||
- !isSupportedAssetFile(destinationAssetPath, LINKABLE_ASSET_EXTENSIONS)
- ) {
- throw new ManagedRenameInvalidRequestError(
- 'Asset operations require supported asset extensions.',
- );
- }
if (
isReservedProjectStatePath(fromPath) ||
isReservedProjectStatePath(destinationAssetPath)
@@ -2596,6 +2594,147 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
);
}
+ async function _performDocumentToFileRename(
+ fromPath: string,
+ toPath: string,
+ ): Promise<{ renamedAssets: RenamedAssetMapping[]; rewrittenDocs: ManagedRenameRewrittenDoc[] }> {
+ return runSerialized(async () =>
+ withSpan(
+ 'rename.executeDocumentToFileRewrites',
+ {
+ attributes: {
+ 'rename.kind': 'asset',
+ 'rename.transition': 'document-to-file',
+ },
+ },
+ async (span) => {
+ if (!backlinkIndex) {
+ throw new BacklinkIndexRequiredError();
+ }
+ if (!isSupportedDocFile(fromPath) || isSupportedDocFile(toPath)) {
+ throw new ManagedRenameInvalidRequestError(
+ 'Document-to-file rename requires a markdown source and non-markdown destination.',
+ );
+ }
+ const sourceDocName = stripDocExtension(fromPath);
+ if (isSystemDoc(sourceDocName) || isConfigDoc(sourceDocName)) {
+ throw new ManagedRenameReservedPathError('Reserved document names cannot be renamed.');
+ }
+ if (isReservedProjectStatePath(fromPath) || isReservedProjectStatePath(toPath)) {
+ throw new ManagedRenameReservedPathError('.ok and .git are reserved directories.');
+ }
+ if (contentFilter?.isPathIgnored(toPath)) {
+ throw new ManagedRenameInvalidRequestError(
+ 'Destination file is excluded by the project content config.',
+ );
+ }
+
+ const sourcePath = resolveContentEntryPath(contentDir, 'folder', fromPath);
+ const destinationPath = resolveContentEntryPath(contentDir, 'folder', toPath);
+ if (sourcePath === destinationPath) {
+ return { renamedAssets: [], rewrittenDocs: [] };
+ }
+ if (stringsDifferOnlyByCase(fromPath, toPath)) {
+ throw new ManagedRenameInvalidRequestError('Case-only renames are not supported.');
+ }
+ if (!existsSync(sourcePath)) {
+ throw new ManagedRenameSourceNotFoundError('file');
+ }
+ if (existsSync(destinationPath)) {
+ throw new ManagedRenameDestinationExistsError();
+ }
+ const sourceStat = statSync(sourcePath);
+ if (!sourceStat.isFile()) {
+ throw new ManagedRenameSourceTypeMismatchError(
+ 'file',
+ 'Source path is not a document file.',
+ );
+ }
+
+ const renameEngine = getSyncEngine?.();
+ const trackedFiles = new Set(
+ renameEngine ? renameEngine.getConflicts().map((c) => c.file) : [],
+ );
+ const sourceDoc = hocuspocus.documents.get(sourceDocName);
+ if (
+ (sourceDoc !== undefined && isDocInConflict(sourceDoc)) ||
+ trackedFiles.has(fromPath)
+ ) {
+ throw new DocInConflictError({ file: fromPath });
+ }
+
+ const renamedAssets = [{ fromPath, toPath }];
+ const pendingRewrites = collectAssetReferenceRewritesForMappings(renamedAssets).filter(
+ (entry) => entry.docName !== sourceDocName,
+ );
+ span.setAttribute('rename.rewrite_candidates', pendingRewrites.length);
+ assertRewriteTargetsNotConflicted(pendingRewrites.map((entry) => entry.docName));
+
+ reconcileDiskBeforeAgentWrite(hocuspocus, sourceDocName, contentDir);
+ if (recentlyRemovedDocs && !isSystemDoc(sourceDocName) && !isConfigDoc(sourceDocName)) {
+ recentlyRemovedDocs.setDeleted(sourceDocName);
+ }
+ const liveContents = await captureAndCloseDocuments([sourceDocName]);
+ const liveContent = liveContents.get(sourceDocName);
+ const sourceContent =
+ typeof liveContent === 'string' ? liveContent : readFileSync(sourcePath, 'utf-8');
+ const recoveryJournal = createManagedRenameRecoveryJournal({
+ fromPath,
+ toPath,
+ affectedDocs: [{ from: sourceDocName, to: sourceDocName }],
+ snapshots: [{ docName: sourceDocName, content: sourceContent }],
+ cleanupPaths: [toPath],
+ });
+ let rewrittenDocs: ManagedRenameRewrittenDoc[] = [];
+ await withManagedRenameRecovery(projectDir ?? contentDir, recoveryJournal, async () => {
+ tracedWriteFileSync(sourcePath, sourceContent, 'utf-8');
+ registerWrite(sourcePath, contentHash(sourceContent));
+
+ const renamedWithGit = await renameTrackedPathInGit(
+ projectDir,
+ sourcePath,
+ destinationPath,
+ );
+ if (!renamedWithGit) {
+ renamePathOnDisk(sourcePath, destinationPath);
+ }
+
+ backlinkIndex.deleteDocument(sourceDocName);
+ forgetDocExtension(sourceDocName);
+ mutateFileIndex?.({ kind: 'delete', path: sourcePath, docName: sourceDocName });
+ const destinationStat = statSync(destinationPath);
+ mutateFileIndex?.({
+ kind: 'file-create',
+ path: destinationPath,
+ relativePath: toPath,
+ size: destinationStat.size,
+ modifiedTs: destinationStat.mtimeMs,
+ inode: destinationStat.ino,
+ });
+
+ rewrittenDocs = applyPendingAssetReferenceRewrites(pendingRewrites, renamedAssets);
+
+ void backlinkIndex.saveToDisk().catch((err) => {
+ console.warn(
+ `[backlinks] Failed to persist document-to-file rename cache for ${fromPath} -> ${toPath}:`,
+ err,
+ );
+ });
+ signalChannel?.('files');
+ if (rewrittenDocs.length > 0) {
+ signalChannel?.('backlinks');
+ signalChannel?.('graph');
+ }
+ });
+
+ rewrittenDocs.sort((a, b) => a.docName.localeCompare(b.docName));
+ span.setAttribute('rename.rewrite_count', rewrittenDocs.length);
+ return { renamedAssets, rewrittenDocs };
+ },
+ ),
+ );
+ }
+
async function _performManagedRenameForDocs(
fromPath: string,
toPath: string,
@@ -2857,58 +2996,65 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
if (shadowRef?.current) {
const shadow = shadowRef.current;
- withSpanSync('rename.appendLog', { attributes: { 'rename.kind': kind } }, (span) => {
- const groupId = randomUUID();
- const at = new Date().toISOString();
- const branch = getCurrentBranch?.() ?? 'main';
- const renameLogIndex = getOrLoadRenameLogIndex(shadow.gitDir);
- const actorWriter = options?.actor
- ? {
- writerId: options.actor.writerId,
- displayName: options.actor.displayName,
+ const loggableAffectedDocs = affectedDocs.filter(({ from, to }) => from !== to);
+ if (loggableAffectedDocs.length > 0) {
+ withSpanSync(
+ 'rename.appendLog',
+ { attributes: { 'rename.kind': kind } },
+ (span) => {
+ const groupId = randomUUID();
+ const at = new Date().toISOString();
+ const branch = getCurrentBranch?.() ?? 'main';
+ const renameLogIndex = getOrLoadRenameLogIndex(shadow.gitDir);
+ const actorWriter = options?.actor
+ ? {
+ writerId: options.actor.writerId,
+ displayName: options.actor.displayName,
+ }
+ : { writerId: SERVICE_WRITER.id, displayName: SERVICE_WRITER.name };
+ let entriesAppended = 0;
+ for (const { from, to } of loggableAffectedDocs) {
+ const logEntry: RenameLogEntry = {
+ v: 1,
+ from,
+ to,
+ at,
+ commitSha: '',
+ branch,
+ groupId,
+ kind,
+ actor: actorWriter,
+ };
+ appendRenameLogEntry(shadow.gitDir, logEntry, renameLogIndex, shadow);
+ entriesAppended += 1;
+ if (options?.actor) {
+ recordContributor(
+ to,
+ options.actor.writerId,
+ options.actor.displayName,
+ options.actor.colorSeed,
+ formatRenameSubject(from, to),
+ options.actor.actorMetadata,
+ undefined,
+ [{ from, to }],
+ );
+ } else {
+ recordContributor(
+ to,
+ SERVICE_WRITER.id,
+ SERVICE_WRITER.name,
+ SERVICE_WRITER.id,
+ formatRenameSubject(from, to),
+ undefined,
+ undefined,
+ [{ from, to }],
+ );
+ }
}
- : { writerId: SERVICE_WRITER.id, displayName: SERVICE_WRITER.name };
- let entriesAppended = 0;
- for (const { from, to } of affectedDocs) {
- const logEntry: RenameLogEntry = {
- v: 1,
- from,
- to,
- at,
- commitSha: '',
- branch,
- groupId,
- kind,
- actor: actorWriter,
- };
- appendRenameLogEntry(shadow.gitDir, logEntry, renameLogIndex, shadow);
- entriesAppended += 1;
- if (options?.actor) {
- recordContributor(
- to,
- options.actor.writerId,
- options.actor.displayName,
- options.actor.colorSeed,
- formatRenameSubject(from, to),
- options.actor.actorMetadata,
- undefined,
- [{ from, to }],
- );
- } else {
- recordContributor(
- to,
- SERVICE_WRITER.id,
- SERVICE_WRITER.name,
- SERVICE_WRITER.id,
- formatRenameSubject(from, to),
- undefined,
- undefined,
- [{ from, to }],
- );
- }
- }
- span.setAttribute('rename.entries_appended', entriesAppended);
- });
+ span.setAttribute('rename.entries_appended', entriesAppended);
+ },
+ );
+ }
}
const explicitDestExt: string | null =
@@ -7151,13 +7297,20 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
);
return;
}
- if (kind === 'asset') {
+ const operationKind =
+ kind === 'asset' && isSupportedDocFile(fromPath) && isSupportedDocFile(toPath)
+ ? 'file'
+ : kind;
+ if (operationKind === 'asset') {
let result: {
renamedAssets: RenamedAssetMapping[];
rewrittenDocs: ManagedRenameRewrittenDoc[];
};
try {
- result = await _performAssetRename(fromPath, toPath);
+ result =
+ isSupportedDocFile(fromPath) && !isSupportedDocFile(toPath)
+ ? await _performDocumentToFileRename(fromPath, toPath)
+ : await _performAssetRename(fromPath, toPath);
} catch (err) {
if (err instanceof DocInConflictError) {
respondDocInConflict(res, err, 'rename-path');
@@ -7171,6 +7324,10 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
return;
}
+ if (result.renamedAssets.length > 0) {
+ invalidateReferencedAssetsCache();
+ }
+
let summaryResponse: SummaryResponse | undefined;
if (result.renamedAssets.length > 0 && result.rewrittenDocs.length > 0) {
const subject = `Renamed asset ${fromPath} → ${toPath}`;
@@ -7226,7 +7383,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
return;
}
const renameAffectedDocNames =
- kind === 'file'
+ operationKind === 'file'
? [stripDocExtension(fromPath)]
: listManagedDocNamesUnderFolderFromDisk(
resolveContentEntryPath(contentDir, 'folder', fromPath),
@@ -7239,7 +7396,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
const affectedDocName = stripDocExtension(affected);
const doc = hocuspocus.documents.get(affectedDocName);
const filePath =
- kind === 'file' ? fromPath : `${affectedDocName}${getDocExtension(affected)}`;
+ operationKind === 'file' ? fromPath : `${affectedDocName}${getDocExtension(affected)}`;
const conflictedByLifecycle = doc !== undefined && isDocInConflict(doc);
const conflictedByStore = renameTrackedFiles.has(filePath);
if (conflictedByLifecycle || conflictedByStore) {
@@ -7247,13 +7404,13 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
return;
}
}
- if (kind === 'file') {
+ if (operationKind === 'file') {
probeAndRegisterSourceFileExtension(contentDir, fromPath);
}
if (contentFilter) {
const excluded =
- kind === 'file'
+ operationKind === 'file'
? contentFilter.isExcluded(
isSupportedDocFile(toPath) ? toPath : `${toPath}${getDocExtension(fromPath)}`,
)
@@ -7263,7 +7420,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
res,
400,
'urn:ok:error:invalid-request',
- `Destination ${kind === 'file' ? 'document' : 'folder'} is excluded by the project content config.`,
+ `Destination ${operationKind === 'file' ? 'document' : 'folder'} is excluded by the project content config.`,
{ handler: 'rename-path' },
);
return;
@@ -7289,7 +7446,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
result = await _performManagedRenameForDocs(
fromPath,
toPath,
- kind,
+ operationKind,
renameActor ? { actor: renameActor } : {},
);
} catch (err) {
@@ -7320,11 +7477,14 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
}
let summaryResponse: SummaryResponse | undefined;
- if (result.renamed.length > 0) {
+ const logicalRenames = result.renamed.filter(
+ ({ fromDocName, toDocName }) => fromDocName !== toDocName,
+ );
+ if (logicalRenames.length > 0) {
summaryResponse = attributeRenameWriteToActor(
actor,
`Renamed ${fromPath} → ${toPath}`,
- result.renamed.map(({ fromDocName, toDocName }) => ({
+ logicalRenames.map(({ fromDocName, toDocName }) => ({
docName: toDocName,
subject: formatRenameSubject(fromDocName, toDocName),
})),
@@ -7339,7 +7499,10 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
},
);
}
- renameAttributionCounter().add(1, { kind: `rename-${kind}`, attribution_kind: actor.kind });
+ renameAttributionCounter().add(1, {
+ kind: `rename-${operationKind}`,
+ attribution_kind: actor.kind,
+ });
if (flushContributors) {
try {
@@ -7404,54 +7567,61 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
return;
}
const operationPath = assetResolution.path;
- if (
- kind === 'asset' &&
- (isSupportedDocFile(operationPath) || isReservedProjectStatePath(operationPath))
- ) {
+ const operationKind = kind === 'asset' && isSupportedDocFile(operationPath) ? 'file' : kind;
+ if (operationKind === 'file') {
+ probeAndRegisterSourceFileExtension(contentDir, operationPath);
+ }
+ if (operationKind === 'asset' && isReservedProjectStatePath(operationPath)) {
errorResponse(
res,
400,
- isReservedProjectStatePath(operationPath)
- ? 'urn:ok:error:reserved-doc-name'
- : 'urn:ok:error:invalid-request',
- isReservedProjectStatePath(operationPath)
- ? '.ok and .git are reserved directories.'
- : 'Asset operations do not support markdown documents.',
+ 'urn:ok:error:reserved-doc-name',
+ '.ok and .git are reserved directories.',
{ handler: 'delete-path' },
);
return;
}
const targetPath =
- kind === 'asset'
+ operationKind === 'asset'
? resolveContentEntryPath(contentDir, 'folder', operationPath)
- : resolveContentEntryPath(contentDir, kind, operationPath);
+ : resolveContentEntryPath(contentDir, operationKind, operationPath);
if (!existsSync(targetPath)) {
- errorResponse(res, 404, 'urn:ok:error:doc-not-found', `${kind} does not exist.`, {
- handler: 'delete-path',
- });
+ errorResponse(
+ res,
+ 404,
+ 'urn:ok:error:doc-not-found',
+ `${operationKind} does not exist.`,
+ {
+ handler: 'delete-path',
+ },
+ );
return;
}
const targetStat = statSync(targetPath);
if (
- (kind === 'file' && !targetStat.isFile()) ||
- (kind === 'asset' && !targetStat.isFile()) ||
- (kind === 'folder' && !targetStat.isDirectory())
+ (operationKind === 'file' && !targetStat.isFile()) ||
+ (operationKind === 'asset' && !targetStat.isFile()) ||
+ (operationKind === 'folder' && !targetStat.isDirectory())
) {
- errorResponse(res, 400, 'urn:ok:error:invalid-request', `Target path is not a ${kind}.`, {
- handler: 'delete-path',
- });
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ `Target path is not a ${operationKind}.`,
+ { handler: 'delete-path' },
+ );
return;
}
const deletedDocNames =
- kind === 'asset'
+ operationKind === 'asset'
? []
- : kind === 'file'
- ? [path]
+ : operationKind === 'file'
+ ? [stripDocExtension(operationPath)]
: listManagedDocNamesUnderFolderFromDisk(
- resolveContentEntryPath(contentDir, 'folder', path),
+ resolveContentEntryPath(contentDir, 'folder', operationPath),
);
const deleteEngine = getSyncEngine?.();
@@ -7462,7 +7632,11 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
const affectedDocName = stripDocExtension(affected);
const doc = hocuspocus.documents.get(affectedDocName);
const filePath =
- kind === 'file' ? affected : `${affectedDocName}${getDocExtension(affectedDocName)}`;
+ operationKind === 'file'
+ ? isSupportedDocFile(operationPath)
+ ? operationPath
+ : `${affectedDocName}${getDocExtension(affectedDocName)}`
+ : `${affectedDocName}${getDocExtension(affectedDocName)}`;
const conflictedByLifecycle = doc !== undefined && isDocInConflict(doc);
const conflictedByStore = deleteTrackedFiles.has(filePath);
if (conflictedByLifecycle || conflictedByStore) {
@@ -7488,11 +7662,11 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
}
}
- if (kind === 'file' || kind === 'asset') {
+ if (operationKind === 'file' || operationKind === 'asset') {
tracedUnlinkSync(targetPath);
} else {
tracedRmSync(targetPath, { recursive: true, force: false });
- removeFolderIndexEntries(path);
+ removeFolderIndexEntries(operationPath);
}
invalidateReferencedAssetsCache();
@@ -7555,27 +7729,30 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
);
return;
}
- const isReservedFolder = kind === 'folder' && isReservedSyntheticFolderPath(path);
- const isReservedAsset = kind === 'asset' && isReservedProjectStatePath(path);
- const isInvalidAsset = kind === 'asset' && isSupportedDocFile(path);
+ const operationKind = kind === 'asset' && isSupportedDocFile(path) ? 'file' : kind;
+ const operationDocName = stripDocExtension(path);
+ if (operationKind === 'file') {
+ probeAndRegisterSourceFileExtension(contentDir, path);
+ }
+ const isReservedFolder =
+ operationKind === 'folder' && isReservedSyntheticFolderPath(path);
+ const isReservedAsset = operationKind === 'asset' && isReservedProjectStatePath(path);
if (
- (kind === 'file' && (isSystemDoc(path) || isConfigDoc(path))) ||
+ (operationKind === 'file' &&
+ (isSystemDoc(operationDocName) || isConfigDoc(operationDocName))) ||
isReservedFolder ||
- isReservedAsset ||
- isInvalidAsset
+ isReservedAsset
) {
errorResponse(
res,
400,
- isInvalidAsset ? 'urn:ok:error:invalid-request' : 'urn:ok:error:reserved-doc-name',
- isInvalidAsset
- ? 'Asset operations do not support markdown documents.'
- : `'${path}' is a reserved document name.`,
+ 'urn:ok:error:reserved-doc-name',
+ `'${path}' is a reserved document name.`,
{ handler: 'trash-cleanup' },
);
return;
}
- if (kind === 'asset') {
+ if (operationKind === 'asset') {
invalidateReferencedAssetsCache();
signalChannel?.('files');
successResponse(
@@ -7590,11 +7767,11 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
const initialIndex = getFileIndex();
const deletedDocNames =
- kind === 'file'
- ? initialIndex.has(path)
- ? [path]
+ operationKind === 'file'
+ ? initialIndex.has(operationDocName)
+ ? [operationDocName]
: []
- : listAffectedDocNames(initialIndex, kind, path);
+ : listAffectedDocNames(initialIndex, operationKind, path);
invalidateReferencedAssetsCache();
@@ -7633,7 +7810,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
docName,
});
}
- if (kind === 'folder') {
+ if (operationKind === 'folder') {
removeFolderIndexEntries(path);
}
diff --git a/packages/server/src/api-file-ops.test.ts b/packages/server/src/api-file-ops.test.ts
index 6e4bb8bb5..796121c07 100644
--- a/packages/server/src/api-file-ops.test.ts
+++ b/packages/server/src/api-file-ops.test.ts
@@ -728,6 +728,25 @@ describe('file operation API routes', () => {
expect(String(notFoundBody.title).toLowerCase()).toContain('does not exist');
});
+ test('managed rename does not register explicit missing source extensions', async () => {
+ const dir = setupTmpDir();
+
+ const result = await callApi(
+ dir,
+ '/api/rename-path',
+ 'POST',
+ {
+ kind: 'file',
+ fromPath: 'missing.mdx',
+ toPath: 'renamed.mdx',
+ },
+ { backlinkIndex: buildBacklinkIndex(dir) },
+ );
+
+ expect(result.status).toBe(404);
+ expect(getDocExtension('missing')).toBe('.md');
+ });
+
test.skipIf(process.platform === 'win32')(
'managed rename surfaces actionable symlink escape errors',
async () => {
@@ -1089,6 +1108,21 @@ describe('file operation API routes', () => {
expect(body.deletedDocNames).toEqual(['trash-me']);
});
+ test('delete accepts asset-shaped markdown paths as document deletes', async () => {
+ const dir = setupTmpDir();
+ writeFileSync(join(dir, 'trash-me.md'), '# Delete me\n', 'utf-8');
+
+ const result = await callApi(dir, '/api/delete-path', 'POST', {
+ kind: 'asset',
+ path: 'trash-me.md',
+ });
+
+ expect(result.status).toBe(200);
+ expect(existsSync(join(dir, 'trash-me.md'))).toBe(false);
+ const body = JSON.parse(result.body) as { deletedDocNames: string[] };
+ expect(body.deletedDocNames).toEqual(['trash-me']);
+ });
+
test('renames an asset and rewrites markdown references', async () => {
const dir = setupTmpDir();
mkdirSync(join(dir, 'docs/media'), { recursive: true });
@@ -1229,7 +1263,7 @@ describe('file operation API routes', () => {
expect(body.rewrittenDocs).toEqual([{ docName: 'docs/guide', rewrites: 1 }]);
});
- test('asset rename rejects unsupported source extensions', async () => {
+ test('asset rename allows arbitrary source extensions', async () => {
const dir = setupTmpDir();
mkdirSync(join(dir, 'docs/media'), { recursive: true });
writeFileSync(join(dir, 'docs/media/archive.xyz'), 'fake bytes', 'utf-8');
@@ -1240,17 +1274,12 @@ describe('file operation API routes', () => {
toPath: 'docs/media/archive.png',
});
- expect(result.status).toBe(400);
- expect(existsSync(join(dir, 'docs/media/archive.xyz'))).toBe(true);
- expect(existsSync(join(dir, 'docs/media/archive.png'))).toBe(false);
- expect(JSON.parse(result.body)).toMatchObject({
- type: 'urn:ok:error:invalid-request',
- title: 'Asset operations require supported asset extensions.',
- status: 400,
- });
+ expect(result.status).toBe(200);
+ expect(existsSync(join(dir, 'docs/media/archive.xyz'))).toBe(false);
+ expect(readFileSync(join(dir, 'docs/media/archive.png'), 'utf-8')).toBe('fake bytes');
});
- test('asset rename rejects unsupported destination extensions', async () => {
+ test('asset rename allows arbitrary destination extensions', async () => {
const dir = setupTmpDir();
mkdirSync(join(dir, 'docs/media'), { recursive: true });
writeFileSync(join(dir, 'docs/media/diagram.png'), 'fake image bytes', 'utf-8');
@@ -1258,38 +1287,306 @@ describe('file operation API routes', () => {
const result = await callApi(dir, '/api/rename-path', 'POST', {
kind: 'asset',
fromPath: 'docs/media/diagram.png',
- toPath: 'docs/media/output.xyz',
+ toPath: 'docs/media/diagram.pngg',
});
- expect(result.status).toBe(400);
- expect(existsSync(join(dir, 'docs/media/diagram.png'))).toBe(true);
- expect(existsSync(join(dir, 'docs/media/output.xyz'))).toBe(false);
+ expect(result.status).toBe(200);
+ expect(existsSync(join(dir, 'docs/media/diagram.png'))).toBe(false);
+ expect(readFileSync(join(dir, 'docs/media/diagram.pngg'), 'utf-8')).toBe('fake image bytes');
+ });
+
+ test('asset rename allows markdown documents to become arbitrary files', async () => {
+ const dir = setupTmpDir();
+ mkdirSync(join(dir, 'docs/media'), { recursive: true });
+ writeFileSync(join(dir, 'docs/guide.md'), '# Guide\n', 'utf-8');
+ writeFileSync(join(dir, 'docs/index.md'), '[Guide](./guide.md)\n', 'utf-8');
+
+ const result = await callApi(
+ dir,
+ '/api/rename-path',
+ 'POST',
+ {
+ kind: 'asset',
+ fromPath: 'docs/guide.md',
+ toPath: 'docs/media/guide.custom',
+ },
+ { backlinkIndex: buildBacklinkIndex(dir) },
+ );
+
+ expect(result.status).toBe(200);
+ expect(existsSync(join(dir, 'docs/guide.md'))).toBe(false);
+ expect(readFileSync(join(dir, 'docs/media/guide.custom'), 'utf-8')).toBe('# Guide\n');
+ expect(readFileSync(join(dir, 'docs/index.md'), 'utf-8')).toBe(
+ '[Guide](./media/guide.custom)\n',
+ );
+ const body = JSON.parse(result.body) as {
+ renamed: Array<{ fromDocName: string; toDocName: string }>;
+ renamedAssets: Array<{ fromPath: string; toPath: string }>;
+ rewrittenDocs: Array<{ docName: string; rewrites: number }>;
+ };
+ expect(body.renamed).toEqual([]);
+ expect(body.renamedAssets).toEqual([
+ {
+ fromPath: 'docs/guide.md',
+ toPath: 'docs/media/guide.custom',
+ },
+ ]);
+ expect(body.rewrittenDocs).toEqual([{ docName: 'docs/index', rewrites: 1 }]);
+ });
+
+ test('document-to-file rename carries live Y.Doc content to the destination file', async () => {
+ const dir = setupTmpDir();
+ writeFileSync(join(dir, 'live.md'), '# Stale\n', 'utf-8');
+
+ const hocuspocus = new Hocuspocus({ quiet: true });
+ const conn = await hocuspocus.openDirectConnection('live');
+ const document = (conn as unknown as { document: Y.Doc }).document;
+ const ytext = document.getText('source');
+ document.transact(() => {
+ ytext.insert(0, '# Live\n');
+ });
+
+ try {
+ const result = await callApi(
+ dir,
+ '/api/rename-path',
+ 'POST',
+ {
+ kind: 'asset',
+ fromPath: 'live.md',
+ toPath: 'live.txt',
+ },
+ {
+ backlinkIndex: buildBacklinkIndex(dir),
+ hocuspocus,
+ },
+ );
+
+ expect(result.status).toBe(200);
+ expect(existsSync(join(dir, 'live.md'))).toBe(false);
+ expect(readFileSync(join(dir, 'live.txt'), 'utf-8')).toBe('# Live\n');
+ } finally {
+ await conn.disconnect().catch(() => {});
+ }
+ });
+
+ test('document-to-file rename returns 404 when the source document is missing', async () => {
+ const dir = setupTmpDir();
+
+ const result = await callApi(
+ dir,
+ '/api/rename-path',
+ 'POST',
+ {
+ kind: 'asset',
+ fromPath: 'missing.md',
+ toPath: 'missing.txt',
+ },
+ { backlinkIndex: buildBacklinkIndex(dir) },
+ );
+
+ expect(result.status).toBe(404);
+ expect(existsSync(join(dir, 'missing.txt'))).toBe(false);
expect(JSON.parse(result.body)).toMatchObject({
- type: 'urn:ok:error:invalid-request',
- title: 'Asset operations require supported asset extensions.',
- status: 400,
+ type: 'urn:ok:error:doc-not-found',
+ status: 404,
});
});
- test('asset rename rejects markdown documents as asset operands', async () => {
+ test('document-to-file rename returns 409 when the destination file exists', async () => {
+ const dir = setupTmpDir();
+ writeFileSync(join(dir, 'guide.md'), '# Guide\n', 'utf-8');
+ writeFileSync(join(dir, 'guide.txt'), 'existing\n', 'utf-8');
+
+ const result = await callApi(
+ dir,
+ '/api/rename-path',
+ 'POST',
+ {
+ kind: 'asset',
+ fromPath: 'guide.md',
+ toPath: 'guide.txt',
+ },
+ { backlinkIndex: buildBacklinkIndex(dir) },
+ );
+
+ expect(result.status).toBe(409);
+ expect(readFileSync(join(dir, 'guide.md'), 'utf-8')).toBe('# Guide\n');
+ expect(readFileSync(join(dir, 'guide.txt'), 'utf-8')).toBe('existing\n');
+ });
+
+ test('document-to-file rename requires a backlink index', async () => {
+ const dir = setupTmpDir();
+ writeFileSync(join(dir, 'guide.md'), '# Guide\n', 'utf-8');
+
+ const result = await callApi(
+ dir,
+ '/api/rename-path',
+ 'POST',
+ {
+ kind: 'asset',
+ fromPath: 'guide.md',
+ toPath: 'guide.txt',
+ },
+ { backlinkIndex: null },
+ );
+
+ expect(result.status).toBe(503);
+ expect(JSON.parse(result.body)).toMatchObject({
+ type: 'urn:ok:error:backlink-index-not-configured',
+ status: 503,
+ });
+ expect(readFileSync(join(dir, 'guide.md'), 'utf-8')).toBe('# Guide\n');
+ });
+
+ test('asset rename allows arbitrary files to use markdown extensions', async () => {
const dir = setupTmpDir();
mkdirSync(join(dir, 'docs/media'), { recursive: true });
- writeFileSync(join(dir, 'docs/guide.md'), '# Guide\n', 'utf-8');
+ writeFileSync(join(dir, 'docs/media/guide.custom'), '# Guide\n', 'utf-8');
+ writeFileSync(join(dir, 'docs/index.md'), '[Guide](./media/guide.custom)\n', 'utf-8');
- const result = await callApi(dir, '/api/rename-path', 'POST', {
- kind: 'asset',
- fromPath: 'docs/guide.md',
- toPath: 'docs/media/guide.png',
+ const result = await callApi(
+ dir,
+ '/api/rename-path',
+ 'POST',
+ {
+ kind: 'asset',
+ fromPath: 'docs/media/guide.custom',
+ toPath: 'docs/guide.md',
+ },
+ { backlinkIndex: buildBacklinkIndex(dir) },
+ );
+
+ expect(result.status).toBe(200);
+ expect(existsSync(join(dir, 'docs/media/guide.custom'))).toBe(false);
+ expect(readFileSync(join(dir, 'docs/guide.md'), 'utf-8')).toBe('# Guide\n');
+ expect(readFileSync(join(dir, 'docs/index.md'), 'utf-8')).toBe('[Guide](./guide.md)\n');
+ const body = JSON.parse(result.body) as {
+ renamed: Array<{ fromDocName: string; toDocName: string }>;
+ renamedAssets: Array<{ fromPath: string; toPath: string }>;
+ rewrittenDocs: Array<{ docName: string; rewrites: number }>;
+ };
+ expect(body.renamed).toEqual([]);
+ expect(body.renamedAssets).toEqual([
+ {
+ fromPath: 'docs/media/guide.custom',
+ toPath: 'docs/guide.md',
+ },
+ ]);
+ expect(body.rewrittenDocs).toEqual([{ docName: 'docs/index', rewrites: 1 }]);
+ });
+
+ test('asset rename to markdown extension returns 404 when the source file is missing', async () => {
+ const dir = setupTmpDir();
+
+ const result = await callApi(
+ dir,
+ '/api/rename-path',
+ 'POST',
+ {
+ kind: 'asset',
+ fromPath: 'missing.txt',
+ toPath: 'missing.md',
+ },
+ { backlinkIndex: buildBacklinkIndex(dir) },
+ );
+
+ expect(result.status).toBe(404);
+ expect(existsSync(join(dir, 'missing.md'))).toBe(false);
+ expect(JSON.parse(result.body)).toMatchObject({
+ type: 'urn:ok:error:doc-not-found',
+ title: 'Asset does not exist.',
+ status: 404,
});
+ });
- expect(result.status).toBe(400);
- expect(existsSync(join(dir, 'docs/guide.md'))).toBe(true);
- expect(existsSync(join(dir, 'docs/media/guide.png'))).toBe(false);
+ test('asset rename to markdown extension returns 409 when the destination exists', async () => {
+ const dir = setupTmpDir();
+ writeFileSync(join(dir, 'guide.txt'), '# Guide\n', 'utf-8');
+ writeFileSync(join(dir, 'guide.md'), '# Existing\n', 'utf-8');
+
+ const result = await callApi(
+ dir,
+ '/api/rename-path',
+ 'POST',
+ {
+ kind: 'asset',
+ fromPath: 'guide.txt',
+ toPath: 'guide.md',
+ },
+ { backlinkIndex: buildBacklinkIndex(dir) },
+ );
+
+ expect(result.status).toBe(409);
+ expect(readFileSync(join(dir, 'guide.txt'), 'utf-8')).toBe('# Guide\n');
+ expect(readFileSync(join(dir, 'guide.md'), 'utf-8')).toBe('# Existing\n');
+ });
+
+ test('asset rename to markdown extension requires a backlink index', async () => {
+ const dir = setupTmpDir();
+ writeFileSync(join(dir, 'guide.txt'), '# Guide\n', 'utf-8');
+
+ const result = await callApi(
+ dir,
+ '/api/rename-path',
+ 'POST',
+ {
+ kind: 'asset',
+ fromPath: 'guide.txt',
+ toPath: 'guide.md',
+ },
+ { backlinkIndex: null },
+ );
+
+ expect(result.status).toBe(503);
expect(JSON.parse(result.body)).toMatchObject({
- type: 'urn:ok:error:invalid-request',
- title: 'Asset operations do not support markdown documents.',
- status: 400,
+ type: 'urn:ok:error:backlink-index-not-configured',
+ status: 503,
});
+ expect(readFileSync(join(dir, 'guide.txt'), 'utf-8')).toBe('# Guide\n');
+ });
+
+ test('asset rename allows binary input to use a markdown extension', async () => {
+ const dir = setupTmpDir();
+ writeFileSync(join(dir, 'binary.bin'), Buffer.from([0x23, 0x00, 0xff]));
+
+ const result = await callApi(
+ dir,
+ '/api/rename-path',
+ 'POST',
+ {
+ kind: 'asset',
+ fromPath: 'binary.bin',
+ toPath: 'binary.md',
+ },
+ { backlinkIndex: buildBacklinkIndex(dir) },
+ );
+
+ expect(result.status).toBe(200);
+ expect(existsSync(join(dir, 'binary.bin'))).toBe(false);
+ expect(readFileSync(join(dir, 'binary.md'))).toEqual(Buffer.from([0x23, 0x00, 0xff]));
+ });
+
+ test('asset-shaped markdown rename uses the document rename path', async () => {
+ const dir = setupTmpDir();
+ mkdirSync(join(dir, 'docs'), { recursive: true });
+ writeFileSync(join(dir, 'docs/guide.md'), '# Guide\n', 'utf-8');
+
+ const result = await callApi(
+ dir,
+ '/api/rename-path',
+ 'POST',
+ {
+ kind: 'asset',
+ fromPath: 'docs/guide.md',
+ toPath: 'docs/guide.mdx',
+ },
+ { backlinkIndex: buildBacklinkIndex(dir) },
+ );
+
+ expect(result.status).toBe(200);
+ expect(existsSync(join(dir, 'docs/guide.md'))).toBe(false);
+ expect(readFileSync(join(dir, 'docs/guide.mdx'), 'utf-8')).toBe('# Guide\n');
});
test('asset rename returns 404 when the source asset is missing', async () => {
@@ -1626,6 +1923,28 @@ describe('file operation API routes', () => {
expect(assetPathsFromDocumentList(after)).not.toContain('docs/foo.png');
});
+ test('trash cleanup accepts asset-shaped markdown paths as document cleanup', async () => {
+ const dir = setupTmpDir();
+ mkdirSync(join(dir, 'docs'), { recursive: true });
+ writeFileSync(join(dir, 'docs/guide.md'), '# Guide\n', 'utf-8');
+
+ const fileIndex = new Map(buildFileIndex(dir));
+ const api = await createTestApiExtension(dir, {
+ getFileIndex: () => fileIndex,
+ });
+
+ rmSync(join(dir, 'docs/guide.md'));
+ const result = await callApiExtension(api, '/api/trash/cleanup', 'POST', {
+ kind: 'asset',
+ path: 'docs/guide.md',
+ });
+
+ expect(result.status).toBe(200);
+ const body = JSON.parse(result.body) as { deletedDocNames: string[] };
+ expect(body.deletedDocNames).toEqual(['docs/guide']);
+ expect(fileIndex.has('docs/guide')).toBe(false);
+ });
+
test('asset-only folder trash cleanup invalidates the cached document list asset row', async () => {
const dir = setupTmpDir();
mkdirSync(join(dir, 'docs/media'), { recursive: true });
diff --git a/packages/server/src/api-rename-log-emission.test.ts b/packages/server/src/api-rename-log-emission.test.ts
index a02a43025..c1395555f 100644
--- a/packages/server/src/api-rename-log-emission.test.ts
+++ b/packages/server/src/api-rename-log-emission.test.ts
@@ -8,6 +8,7 @@ import simpleGit from 'simple-git';
import { createApiExtension } from './api-extension.ts';
import { BacklinkIndex } from './backlink-index.ts';
import { recordContributor, swapContributors } from './contributor-tracker.ts';
+import { _resetDocExtensionsForTests } from './doc-extensions.ts';
import type { FileIndexEntry } from './file-watcher.ts';
import { loadRenameLogIndex, type RenameLogEntry, resetRenameLogIndexCache } from './rename-log.ts';
import { initShadowRepo, type ShadowRef } from './shadow-repo.ts';
@@ -84,6 +85,7 @@ beforeEach(async () => {
shadowRef = { current: shadow };
swapContributors();
+ _resetDocExtensionsForTests();
resetRenameLogIndexCache();
});
@@ -158,6 +160,23 @@ describe('rename log emission inside withManagedRenameRecovery (US-006)', () =>
expect(e.at).toMatch(/^\d{4}-\d{2}-\d{2}T/);
});
+ test('same-base extension change succeeds without a self-rename log entry', async () => {
+ writeFileSync(resolve(contentDir, 'a.md'), '# A\n');
+
+ const response = await callRename({
+ kind: 'file',
+ fromPath: 'a',
+ toPath: 'a.mdx',
+ agentId: 'claude-1',
+ agentName: 'Claude',
+ });
+ expect(response.status).toBe(200);
+
+ expect(existsSync(resolve(contentDir, 'a.mdx'))).toBe(true);
+ expect(existsSync(resolve(contentDir, 'a.md'))).toBe(false);
+ expect(loadEntries()).toHaveLength(0);
+ });
+
test('anonymous rename produces a service-writer log entry (FR13)', async () => {
writeFileSync(resolve(contentDir, 'a.md'), '# A\n');
diff --git a/packages/server/src/managed-rename-journal.test.ts b/packages/server/src/managed-rename-journal.test.ts
index 7cd76c3cd..28d5fd605 100644
--- a/packages/server/src/managed-rename-journal.test.ts
+++ b/packages/server/src/managed-rename-journal.test.ts
@@ -255,6 +255,55 @@ describe('managed rename recovery journal — v2 multi-doc recovery', () => {
expect(existsSync(join(dir, 'essays', 'unrelated.md'))).toBe(true);
expect(existsSync(join(dir, 'essays'))).toBe(true);
});
+
+ test('replays path snapshots and removes path-level cleanup targets', () => {
+ const dir = setupTmpDir();
+ mkdirSync(join(dir, 'docs'), { recursive: true });
+ writeFileSync(join(dir, 'docs', 'guide.md'), '# Guide\n', 'utf-8');
+ writeFileSync(join(dir, 'docs', 'guide.txt'), '# Guide\n', 'utf-8');
+
+ writeManagedRenameJournal(
+ dir,
+ createManagedRenameRecoveryJournal({
+ fromPath: 'docs/guide.txt',
+ toPath: 'docs/guide.md',
+ affectedDocs: [],
+ snapshots: [],
+ pathSnapshots: [{ path: 'docs/guide.txt', content: '# Guide\n' }],
+ cleanupPaths: ['docs/guide.md'],
+ }),
+ );
+
+ const recovery = recoverPendingManagedRename(dir);
+ expect(recovery.recovered).toBe(true);
+ expect(recovery.restoredDocNames).toEqual([]);
+ expect(readFileSync(join(dir, 'docs', 'guide.txt'), 'utf-8')).toBe('# Guide\n');
+ expect(existsSync(join(dir, 'docs', 'guide.md'))).toBe(false);
+ expect(existsSync(managedRenameJournalPath(dir))).toBe(false);
+ });
+
+ test('keeps the journal when a path-level cleanup target is invalid', () => {
+ const dir = setupTmpDir();
+ mkdirSync(join(dir, 'docs'), { recursive: true });
+
+ writeManagedRenameJournal(
+ dir,
+ createManagedRenameRecoveryJournal({
+ fromPath: 'docs/guide.txt',
+ toPath: 'docs/guide.md',
+ affectedDocs: [],
+ snapshots: [],
+ pathSnapshots: [{ path: 'docs/guide.txt', content: '# Guide\n' }],
+ cleanupPaths: ['../escape.md'],
+ }),
+ );
+
+ expect(() => recoverPendingManagedRename(dir)).toThrow(
+ 'Managed rename recovery incomplete; failed to clean destinations: ../escape.md',
+ );
+ expect(readFileSync(join(dir, 'docs', 'guide.txt'), 'utf-8')).toBe('# Guide\n');
+ expect(existsSync(managedRenameJournalPath(dir))).toBe(true);
+ });
});
describe('managed rename recovery journal — failure cause propagation', () => {
@@ -417,4 +466,25 @@ describe('managed rename recovery journal — v2 parser validation', () => {
'Managed rename journal v2 has invalid snapshots',
);
});
+
+ test('accepts v2 path-only journals for cross-type file recovery', () => {
+ const dir = setupTmpDir();
+ writeRawJournal(dir, {
+ version: 2,
+ fromPath: 'docs/guide.txt',
+ toPath: 'docs/guide.md',
+ createdAt: '2026-04-30T00:00:00.000Z',
+ affectedDocs: [],
+ snapshots: [],
+ pathSnapshots: [{ path: 'docs/guide.txt', content: '# Guide\n' }],
+ cleanupPaths: ['docs/guide.md'],
+ });
+
+ const parsed = readManagedRenameJournal(dir);
+ expect(parsed?.version).toBe(2);
+ if (parsed?.version === 2) {
+ expect(parsed.pathSnapshots).toEqual([{ path: 'docs/guide.txt', content: '# Guide\n' }]);
+ expect(parsed.cleanupPaths).toEqual(['docs/guide.md']);
+ }
+ });
});
diff --git a/packages/server/src/managed-rename-journal.ts b/packages/server/src/managed-rename-journal.ts
index 8a6af80b1..1ed97ddcf 100644
--- a/packages/server/src/managed-rename-journal.ts
+++ b/packages/server/src/managed-rename-journal.ts
@@ -17,6 +17,11 @@ export interface ManagedRenameSnapshot {
content: string;
}
+export interface ManagedRenamePathSnapshot {
+ path: string;
+ content: string;
+}
+
interface ManagedRenameAffectedDoc {
from: string;
to: string;
@@ -37,6 +42,8 @@ interface ManagedRenameRecoveryJournalV2 {
affectedDocs: ManagedRenameAffectedDoc[];
createdAt: string;
snapshots: ManagedRenameSnapshot[];
+ pathSnapshots?: ManagedRenamePathSnapshot[];
+ cleanupPaths?: string[];
}
type ManagedRenameRecoveryJournal = ManagedRenameRecoveryJournalV1 | ManagedRenameRecoveryJournalV2;
@@ -62,9 +69,11 @@ export function createManagedRenameRecoveryJournal(args: {
toPath: string;
affectedDocs: ManagedRenameAffectedDoc[];
snapshots: ManagedRenameSnapshot[];
+ pathSnapshots?: ManagedRenamePathSnapshot[];
+ cleanupPaths?: string[];
createdAt?: string;
}): ManagedRenameRecoveryJournalV2 {
- return {
+ const journal: ManagedRenameRecoveryJournalV2 = {
version: 2,
fromPath: args.fromPath,
toPath: args.toPath,
@@ -72,6 +81,13 @@ export function createManagedRenameRecoveryJournal(args: {
createdAt: args.createdAt ?? new Date().toISOString(),
snapshots: args.snapshots,
};
+ if (args.pathSnapshots && args.pathSnapshots.length > 0) {
+ journal.pathSnapshots = args.pathSnapshots;
+ }
+ if (args.cleanupPaths && args.cleanupPaths.length > 0) {
+ journal.cleanupPaths = args.cleanupPaths;
+ }
+ return journal;
}
function isManagedRenameSnapshot(value: unknown): value is ManagedRenameSnapshot {
@@ -80,6 +96,16 @@ function isManagedRenameSnapshot(value: unknown): value is ManagedRenameSnapshot
return typeof snapshot.docName === 'string' && typeof snapshot.content === 'string';
}
+function isManagedRenamePathSnapshot(value: unknown): value is ManagedRenamePathSnapshot {
+ if (!value || typeof value !== 'object') return false;
+ const snapshot = value as Partial<ManagedRenamePathSnapshot>;
+ return typeof snapshot.path === 'string' && typeof snapshot.content === 'string';
+}
+
+function isManagedRenameCleanupPath(value: unknown): value is string {
+ return typeof value === 'string' && value.length > 0;
+}
+
function isManagedRenameAffectedDoc(value: unknown): value is ManagedRenameAffectedDoc {
if (!value || typeof value !== 'object') return false;
const entry = value as Partial<ManagedRenameAffectedDoc>;
@@ -96,21 +122,35 @@ function parseV2(value: Record<string, unknown>): ManagedRenameRecoveryJournalV2
if (typeof value.createdAt !== 'string' || value.createdAt.length === 0) {
throw new Error('Managed rename journal v2 is missing createdAt');
}
- if (
- !Array.isArray(value.affectedDocs) ||
- value.affectedDocs.length === 0 ||
- !value.affectedDocs.every(isManagedRenameAffectedDoc)
- ) {
+ const affectedDocs = value.affectedDocs;
+ const rawPathSnapshots = value.pathSnapshots;
+ const rawCleanupPaths = value.cleanupPaths;
+ const hasPathSnapshots = Array.isArray(rawPathSnapshots) && rawPathSnapshots.length > 0;
+ const hasCleanupPaths = Array.isArray(rawCleanupPaths) && rawCleanupPaths.length > 0;
+ if (!Array.isArray(affectedDocs) || !affectedDocs.every(isManagedRenameAffectedDoc)) {
+ throw new Error('Managed rename journal v2 has invalid affectedDocs');
+ }
+ if (affectedDocs.length === 0 && !hasPathSnapshots && !hasCleanupPaths) {
throw new Error('Managed rename journal v2 has invalid affectedDocs');
}
if (
!Array.isArray(value.snapshots) ||
- value.snapshots.length === 0 ||
+ (affectedDocs.length > 0 && value.snapshots.length === 0) ||
!value.snapshots.every(isManagedRenameSnapshot)
) {
throw new Error('Managed rename journal v2 has invalid snapshots');
}
- for (const entry of value.affectedDocs as ManagedRenameAffectedDoc[]) {
+ if (rawPathSnapshots !== undefined) {
+ if (!Array.isArray(rawPathSnapshots) || !rawPathSnapshots.every(isManagedRenamePathSnapshot)) {
+ throw new Error('Managed rename journal v2 has invalid pathSnapshots');
+ }
+ }
+ if (rawCleanupPaths !== undefined) {
+ if (!Array.isArray(rawCleanupPaths) || !rawCleanupPaths.every(isManagedRenameCleanupPath)) {
+ throw new Error('Managed rename journal v2 has invalid cleanupPaths');
+ }
+ }
+ for (const entry of affectedDocs as ManagedRenameAffectedDoc[]) {
if (
!(value.snapshots as ManagedRenameSnapshot[]).some(
(snapshot) => snapshot.docName === entry.from,
@@ -125,9 +165,11 @@ function parseV2(value: Record<string, unknown>): ManagedRenameRecoveryJournalV2
version: 2,
fromPath: value.fromPath,
toPath: value.toPath,
- affectedDocs: value.affectedDocs as ManagedRenameAffectedDoc[],
+ affectedDocs: affectedDocs as ManagedRenameAffectedDoc[],
createdAt: value.createdAt,
snapshots: value.snapshots as ManagedRenameSnapshot[],
+ ...(hasPathSnapshots ? { pathSnapshots: rawPathSnapshots as ManagedRenamePathSnapshot[] } : {}),
+ ...(hasCleanupPaths ? { cleanupPaths: rawCleanupPaths as string[] } : {}),
};
}
@@ -221,6 +263,15 @@ function destinationsToCleanV2(journal: ManagedRenameRecoveryJournalV2): string[
return journal.affectedDocs.map((entry) => entry.to);
}
+function resolveRecoveryPath(contentDir: string, relativePath: string): string {
+ const root = resolve(contentDir);
+ const filePath = resolve(root, relativePath);
+ if (relativePath.includes('\x00') || filePath === root || !filePath.startsWith(`${root}${sep}`)) {
+ throw new Error(`Invalid recovery path: ${relativePath}`);
+ }
+ return filePath;
+}
+
function pruneEmptyAncestors(filePath: string, contentDir: string): void {
const root = resolve(contentDir);
const boundary = `${root}${sep}`;
@@ -254,6 +305,7 @@ export function recoverPendingManagedRename(
}
const restoredDocNames = new Set<string>();
+ const restoredPaths = new Set<string>();
const restoreFailures: Array<{ docName: string; cause: unknown }> = [];
for (const snapshot of journal.snapshots) {
try {
@@ -281,6 +333,35 @@ export function recoverPendingManagedRename(
);
}
+ if (journal.version === 2) {
+ const pathRestoreFailures: Array<{ path: string; cause: unknown }> = [];
+ for (const snapshot of journal.pathSnapshots ?? []) {
+ try {
+ const filePath = resolveRecoveryPath(contentDir, snapshot.path);
+ tracedMkdirSync(dirname(filePath), { recursive: true });
+ tracedWriteFileSync(filePath, snapshot.content, 'utf-8');
+ restoredPaths.add(snapshot.path);
+ } catch (err) {
+ pathRestoreFailures.push({ path: snapshot.path, cause: err });
+ console.warn(`[managed-rename] Failed to restore path ${snapshot.path}:`, err);
+ }
+ }
+
+ if (pathRestoreFailures.length > 0) {
+ const failedPaths = pathRestoreFailures.map((f) => f.path).join(', ');
+ console.warn(
+ `[managed-rename] Recovery incomplete; keeping journal for retry (${failedPaths})`,
+ );
+ const causes = pathRestoreFailures.map((f) =>
+ f.cause instanceof Error ? f.cause : new Error(String(f.cause)),
+ );
+ throw new AggregateError(
+ causes,
+ `Managed rename recovery incomplete; failed to restore paths: ${failedPaths}`,
+ );
+ }
+ }
+
const destinationsToClean =
journal.version === 2 ? destinationsToCleanV2(journal) : destinationsToCleanV1(journal);
const cleanupFailures: Array<{ destination: string; cause: unknown }> = [];
@@ -304,6 +385,29 @@ export function recoverPendingManagedRename(
}
}
+ if (journal.version === 2) {
+ for (const destination of journal.cleanupPaths ?? []) {
+ if (restoredPaths.has(destination)) continue;
+ let destinationPath: string | null = null;
+ try {
+ destinationPath = resolveRecoveryPath(contentDir, destination);
+ tracedRmSync(destinationPath, { force: true });
+ pruneEmptyAncestors(destinationPath, contentDir);
+ } catch (err) {
+ if (destinationPath && existsSync(destinationPath)) {
+ console.warn(
+ `[managed-rename] Both source and destination paths exist after partial recovery for ${destination}`,
+ );
+ }
+ console.warn(
+ `[managed-rename] Recovery incomplete; failed to clean destination path ${destination}:`,
+ err,
+ );
+ cleanupFailures.push({ destination, cause: err });
+ }
+ }
+ }
+
if (cleanupFailures.length > 0) {
const failedNames = cleanupFailures.map((f) => f.destination).join(', ');
const causes = cleanupFailures.map((f) =>