Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Preserve exact markdown document identities in file tree (#2343)
Dimitri POSTOLOVe6b13d150a12
diff --git a/.changeset/markdown-sibling-docnames.md b/.changeset/markdown-sibling-docnames.mdnew file mode 100644index 000000000..5e53e5ac4--- /dev/null+++ b/.changeset/markdown-sibling-docnames.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Opening a workspace that contains same-stem `.md` and `.mdx` files, such as `foo.md` and `foo.mdx`, no longer blanks or wedges the app. Show All now lists both files, URLs keep the extension when needed, both siblings open and edit independently, and sidebar actions like share, handoff, rename, delete, and duplicate target the selected sibling instead of collapsing to the extensionless stem.diff --git a/packages/app/src/App.dom.test.tsx b/packages/app/src/App.dom.test.tsxindex 3a6ba9783..79f66121c 100644--- a/packages/app/src/App.dom.test.tsx+++ b/packages/app/src/App.dom.test.tsx@@ -17,6 +17,8 @@ let pagesBySlug = new Map<string, unknown>();let pagesByBasename = new Map<string, unknown>();let folderPaths = new Set<string>();let assetPaths = new Set<string>();+let filePaths = new Set<string>();+let openTabs: string[] = [];let loading = false;let singleFileMode = false;let tabSessionLoaded = true;@@ -58,7 +60,7 @@ mock.module('@/editor/DocumentContext', () => ({tabSessionLoaded,// The skill-tab reconciler reads these at render (no open skill tab here,// so it issues no `/api/skills` fetch); the real context always supplies them.- openTabs: [],+ openTabs,closeDocument: () => {},}),useDocumentTransition: () => ({@@ -72,6 +74,7 @@ mock.module('@/components/PageListContext', () => ({),usePageList: () => ({assetPaths,+ filePaths,folderPaths,loading,pageMeta,@@ -246,6 +249,8 @@ describe('App runtime wiring', () => {pagesByBasename = new Map();folderPaths = new Set(['reports']);assetPaths = new Set();+ filePaths = new Set();+ openTabs = [];loading = false;singleFileMode = false;tabSessionLoaded = true;@@ -287,6 +292,21 @@ describe('App runtime wiring', () => {expect(screen.getByTestId('editor-pane')).not.toBeNull();});+ test('passes tracked non-markdown files to tab reconciliation', async () => {+ filePaths = new Set(['LICENSE', 'pnpm-workspace.yaml']);++ renderApp();++ await waitFor(() => {+ expect(syncOpenTabsWithKnownTargetsMock).toHaveBeenCalledWith({+ pages,+ folderPaths,+ assetPaths,+ filePaths,+ });+ });+ });+test('Cmd/Ctrl-comma opens settings via the canonical hash and ignores text inputs', () => {renderApp();@@ -324,6 +344,27 @@ describe('App runtime wiring', () => {expect(openTargetTransitionMock).not.toHaveBeenCalledWith(resolved);});+ test('hash navigation keeps an open extension-qualified markdown tab exact', async () => {+ openTabs = ['docs/guide.mdx'];+ resolveNavigationTargetMock = mock(() => ({+ kind: 'doc',+ target: 'docs/guide',+ docName: 'docs/guide',+ }));+ setHash('#/docs/guide.mdx');++ renderApp();++ await waitFor(() => {+ expect(openTargetTransitionMock).toHaveBeenCalledWith({+ kind: 'doc',+ target: 'docs/guide.mdx',+ docName: 'docs/guide.mdx',+ });+ });+ expect(resolveNavigationTargetMock).not.toHaveBeenCalled();+ });+test('base-open pane target applies a well-formed config route once and consumes it', async () => {fetchApiConfigMock = mock(() =>Promise.resolve({diff --git a/packages/app/src/App.tsx b/packages/app/src/App.tsxindex 7a363463c..654ff07bc 100644--- a/packages/app/src/App.tsx+++ b/packages/app/src/App.tsx@@ -17,6 +17,7 @@ import { McpConsentDialog } from '@/components/McpConsentDialog';import { isNewItemShortcut, NewItemDialog } from '@/components/NewItemDialog';import {downgradeFolderIndexForHashNav,+ type ResolvedNavigationTarget,resolveNavigationTarget,withLargeFileOpenGuard,} from '@/components/navigation-targets';@@ -28,6 +29,7 @@ import {useDocumentContext,useDocumentTransition,} from '@/editor/DocumentContext';+import { parseEditorTabId } from '@/editor/editor-tabs';import { useReconcileSkillTabs } from '@/hooks/use-reconcile-skill-tabs';import { fetchApiConfig } from '@/lib/api-config';import { ConfigProvider } from '@/lib/config-provider';@@ -72,16 +74,32 @@ const ShareReceiveMissDialog = lazy(() =>* trigger component to keep that locality.*/const INSTALL_DIALOG_HASH = '#install-claude-desktop';+const MARKDOWN_EXTENSION_QUALIFIED_DOC_PATTERN = /\.(md|mdx)$/i;function isAuxiliaryDialogHash(hash: string): boolean {return hash === SETTINGS_OPEN_HASH || hash === INSTALL_DIALOG_HASH;}+function exactOpenMarkdownTabTarget(+ docName: string,+ openTabs: ReadonlyArray<string>,+): ResolvedNavigationTarget | null {+ if (!MARKDOWN_EXTENSION_QUALIFIED_DOC_PATTERN.test(docName)) return null;+ for (const tabId of openTabs) {+ const tab = parseEditorTabId(tabId);+ if (tab.kind === 'doc' && tab.docName === docName) {+ return { kind: 'doc', target: docName, docName };+ }+ }+ return null;+}+function knownTargetsSignature(pages: ReadonlySet<string>,folderPaths: ReadonlySet<string>,assetPaths: ReadonlySet<string>,+ filePaths: ReadonlySet<string>,): string {- return [pages, folderPaths, assetPaths]+ return [pages, folderPaths, assetPaths, filePaths].map((values) => [...values].sort().join('\u0000')).join('\u0001');}@@ -97,16 +115,25 @@ function knownTargetsSignature(* path. Target resolution (asset / doc / folder-index / folder / missing)* lives here plus resolveNavigationTarget. */function NavigationHandler() {- const { clearTarget, syncOpenTabsWithKnownTargets, tabSessionLoaded } = useDocumentContext();+ const { clearTarget, openTabs, syncOpenTabsWithKnownTargets, tabSessionLoaded } =+ useDocumentContext();const { openTargetTransition } = useDocumentTransition();// Reconcile open skill tabs against the live skills list: an agent/MCP/server-// side scope move only broadcasts `files` (never retargets the client tab),// leaving an open skill tab pointing at a doc that no longer exists.useReconcileSkillTabs();- const { assetPaths, folderPaths, loading, pageMeta, pages, pagesBySlug, pagesByBasename } =- usePageList();+ const {+ assetPaths,+ filePaths,+ folderPaths,+ loading,+ pageMeta,+ pages,+ pagesBySlug,+ pagesByBasename,+ } = usePageList();const lastSyncedTargetsSignatureRef = useRef<string | null>(null);- const targetsSignature = knownTargetsSignature(pages, folderPaths, assetPaths);+ const targetsSignature = knownTargetsSignature(pages, folderPaths, assetPaths, filePaths);useEffect(() => {if (@@ -117,9 +144,10 @@ function NavigationHandler() {return;}lastSyncedTargetsSignatureRef.current = targetsSignature;- syncOpenTabsWithKnownTargets({ pages, folderPaths, assetPaths });+ syncOpenTabsWithKnownTargets({ pages, folderPaths, assetPaths, filePaths });}, [assetPaths,+ filePaths,folderPaths,loading,pages,@@ -187,12 +215,14 @@ function NavigationHandler() {mark('ok/nav/hash-change', { docName, kind: 'deferred-loading' });return;}- const resolved = resolveNavigationTarget(docName, {- pages,- folderPaths,- pagesBySlug,- pagesByBasename,- });+ const resolved =+ exactOpenMarkdownTabTarget(docName, openTabs) ??+ resolveNavigationTarget(docName, {+ pages,+ folderPaths,+ pagesBySlug,+ pagesByBasename,+ });if (resolved.kind === 'missing' && /\/+$/.test(docName.trim())) {mark('ok/nav/hash-change', { docName, kind: 'deferred-missing-folder' });return;@@ -208,6 +238,7 @@ function NavigationHandler() {folderPaths,loading,openTargetTransition,+ openTabs,pageMeta,pages,pagesBySlug,diff --git a/packages/app/src/components/BottomComposer.dom.test.tsx b/packages/app/src/components/BottomComposer.dom.test.tsxindex 9c69c1c46..7d7f2b878 100644--- a/packages/app/src/components/BottomComposer.dom.test.tsx+++ b/packages/app/src/components/BottomComposer.dom.test.tsx@@ -156,12 +156,17 @@ mock.module('@/lib/use-workspace', () => ({// is a no-op here (the publishing path is covered in use-selection-context tests).let liveSelection: unknown = null;let liveFrontmatterSelection: unknown = null;+let pageMeta: ReadonlyMap<string, { docExt?: string }> = new Map();mock.module('@/hooks/use-selection-context', () => ({useSelectionContext: (_docName: string | null, surface: string) =>surface === 'frontmatter' ? liveFrontmatterSelection : liveSelection,usePublishFrontmatterSelection: () => {},}));+mock.module('@/components/PageListContext', () => ({+ usePageList: () => ({ pageMeta }),+}));+const recordAskedAiSpy = mock(() => {});mock.module('@/lib/onboarding-signals', () => ({ recordOnboardingAskedAi: recordAskedAiSpy }));@@ -188,6 +193,7 @@ mock.module('@/components/handoff/useHandoffDispatch', () => ({}),buildComposerHandoffInput: (args: {docName: string | null;+ docRelativePath?: string;folderRelativePath?: string;workspace: unknown;instruction: string;@@ -337,6 +343,7 @@ beforeEach(() => {builderReturnsNull = false;liveSelection = null;liveFrontmatterSelection = null;+ pageMeta = new Map();mockInlineMentions = [];emitMentions = null;dispatchCalls.length = 0;@@ -912,6 +919,40 @@ describe('BottomComposer (top-row file-context chips lifecycle)', () => {expect(screen.getByRole('button', { name: /Remove SPEC\.md from context/i })).toBeTruthy();});+ test('the first keystroke uses docExt metadata for an active .mdx document', async () => {+ pageMeta = new Map([['foo', { docExt: '.mdx' }]]);+ await renderComposer('foo');+ fireEvent.change(getInput(), { target: { value: 'do a thing' } });++ expect(await screen.findByTestId('composer-context-chip-file-foo.mdx')).toBeTruthy();+ expect(screen.queryByTestId('composer-context-chip-file-foo.md')).toBeNull();+ });++ test('extension-qualified and extensionless routes for the same .mdx doc do not duplicate chips', async () => {+ pageMeta = new Map([['foo', { docExt: '.mdx' }]]);+ const { rerender } = await renderComposer('foo.mdx');+ fireEvent.change(getInput(), { target: { value: 'drafting' } });+ await screen.findByTestId('composer-context-chip-file-foo.mdx');++ const { BottomComposer } = await import('./BottomComposer');+ rerender(<BottomComposer docName="foo" surface="wysiwyg" />);++ expect(screen.getByTestId('composer-context-chip-file-foo.mdx')).toBeTruthy();+ expect(screen.queryByTestId('composer-context-chip-file-foo.md')).toBeNull();+ });++ test('switching same-stem md/mdx documents replaces the prior file chip', async () => {+ const { rerender } = await renderComposer('foo.md');+ fireEvent.change(getInput(), { target: { value: 'drafting' } });+ await screen.findByTestId('composer-context-chip-file-foo.md');++ const { BottomComposer } = await import('./BottomComposer');+ rerender(<BottomComposer docName="foo.mdx" surface="wysiwyg" />);++ await screen.findByTestId('composer-context-chip-file-foo.mdx');+ expect(screen.queryByTestId('composer-context-chip-file-foo.md')).toBeNull();+ });+test('switching files while drafting accumulates a chip for each touched file', async () => {const { rerender } = await renderComposer('fileA');fireEvent.change(getInput(), { target: { value: 'drafting' } });@@ -977,6 +1018,20 @@ describe('BottomComposer (top-row file-context chips lifecycle)', () => {expect(buildArgs[0]?.mentions).not.toContain('fileB.md');});+ test('dispatch carries the .mdx relative path for an active .mdx lead', async () => {+ pageMeta = new Map([['fileA', { docExt: '.mdx' }]]);+ await renderComposer('fileA');+ fireEvent.change(getInput(), { target: { value: 'drafting' } });+ await screen.findByTestId('composer-context-chip-file-fileA.mdx');++ fireEvent.click(screen.getByTestId('ask-ai-send'));+ await waitFor(() => expect(dispatchCalls).toHaveLength(1));++ expect(buildArgs[0]?.docName).toBe('fileA');+ expect(buildArgs[0]?.docRelativePath).toBe('fileA.mdx');+ expect(buildArgs[0]?.mentions).not.toContain('fileA.mdx');+ });+test('dismissing all file chips with no inline mentions falls back to project scope', async () => {await renderComposer('fileA');fireEvent.change(getInput(), { target: { value: 'drafting' } });diff --git a/packages/app/src/components/BottomComposer.tsx b/packages/app/src/components/BottomComposer.tsxindex 06f4e99ff..e31f5134a 100644--- a/packages/app/src/components/BottomComposer.tsx+++ b/packages/app/src/components/BottomComposer.tsx@@ -76,10 +76,23 @@ import { cn } from '@/lib/utils';import { docNameToRelativePath } from '@/lib/workspace-paths';import { emitOpenAskAiComposer, subscribeToOpenAskAiComposer } from './ask-ai-composer-events';import { clearComposerDraft, getComposerDraft, setComposerDraftDoc } from './composer-draft-store';+import { usePageList } from './PageListContext';// Each suggestion holds long enough to read, then cross-fades to the next.const SUGGESTION_HOLD_MS = 5200; // fully-visible dwell per suggestionconst SUGGESTION_FADE_MS = 500; // cross-fade duration (matches the CSS duration)+const MARKDOWN_RELATIVE_PATH_EXTENSION = /\.(md|mdx)$/i;++function docNameToComposerRelativePath(docName: string, docExt?: string): string {+ if (MARKDOWN_RELATIVE_PATH_EXTENSION.test(docName)) return docName;+ return docExt ? `${docName}${docExt}` : docNameToRelativePath(docName);+}++function markdownRelativePathStem(path: string): string | null {+ return MARKDOWN_RELATIVE_PATH_EXTENSION.test(path)+ ? path.replace(MARKDOWN_RELATIVE_PATH_EXTENSION, '')+ : null;+}/*** Whether a keydown originated inside a native form field. ⌘L should still fire@@ -191,6 +204,7 @@ export function BottomComposer({const effectiveSurface: EditorSurface = surface ?? 'wysiwyg';const reduced = useReducedMotion();const workspace = useWorkspace();+ const { pageMeta } = usePageList();const { states } = useInstalledAgents();const { dispatch } = useHandoffDispatch();// Desktop-only docked-terminal launcher (null on web). Its presence is what@@ -397,14 +411,25 @@ export function BottomComposer({// and again whenever the active doc changes while still drafting (accumulate on// switch). Sticky-dismissed paths are never re-added. Keyed on `isEmpty` +// `docName` so a file-switch mid-draft fires it.- const activeFilePath = folderMode || docName == null ? '' : docNameToRelativePath(docName);+ const activeFilePath =+ folderMode || docName == null+ ? ''+ : docNameToComposerRelativePath(docName, pageMeta.get(docName)?.docExt);useEffect(() => {// Folder mode has no active doc to "touch" — its single top-row chip is the// folder itself, derived below, not the touched-file set.if (folderMode || isEmpty) return;setTouchedFiles((prev) => {- if (prev.includes(activeFilePath) || dismissedFiles.has(activeFilePath)) return prev;- return [...prev, activeFilePath];+ if (dismissedFiles.has(activeFilePath)) return prev;+ const activeStem = markdownRelativePathStem(activeFilePath);+ const next =+ activeStem === null+ ? prev+ : prev.filter(+ (path) => path === activeFilePath || markdownRelativePathStem(path) !== activeStem,+ );+ if (next.includes(activeFilePath)) return next.length === prev.length ? prev : next;+ return [...next, activeFilePath];});}, [folderMode, isEmpty, activeFilePath, dismissedFiles]);@@ -628,13 +653,17 @@ export function BottomComposer({: fileChips.includes(activeFilePath)? (docName ?? null): null;- const leadPath = leadDocName !== null ? docNameToRelativePath(leadDocName) : null;+ const leadPath =+ leadDocName !== null+ ? docNameToComposerRelativePath(leadDocName, pageMeta.get(leadDocName)?.docExt)+ : null;const dispatchMentions = [...new Set([...fileChips, ...mentions])].filter((path) => path !== leadPath,);dispatchComposed(buildComposerHandoffInput({docName: leadDocName,+ ...(leadPath !== null ? { docRelativePath: leadPath } : {}),workspace,instruction,mentions: dispatchMentions,@@ -656,7 +685,13 @@ export function BottomComposer({let pinnedLabel = '';let pinnedPreview = '';if (pinnedSelection) {- const basename = docNameToRelativePath(pinnedSelection.docName).split('/').pop() ?? '';+ const basename =+ docNameToComposerRelativePath(+ pinnedSelection.docName,+ pageMeta.get(pinnedSelection.docName)?.docExt,+ )+ .split('/')+ .pop() ?? '';pinnedLabel = selectionChipLabel(pinnedSelection, basename);pinnedPreview = lightRenderMarkdownPreview(pinnedSelection.markdown);}diff --git a/packages/app/src/components/ComposerContextChips.dom.test.tsx b/packages/app/src/components/ComposerContextChips.dom.test.tsxindex 7ea608e73..e7ee863a3 100644--- a/packages/app/src/components/ComposerContextChips.dom.test.tsx+++ b/packages/app/src/components/ComposerContextChips.dom.test.tsx@@ -84,6 +84,15 @@ describe('ComposerContextChips', () => {expect(new Set([folderIcon, pageIcon, videoIcon, audioIcon]).size).toBe(4);});+ test('keeps extension badges out of the compact leading icon cell', async () => {+ await renderChips(['foo.mdx']);+ const chip = screen.getByTestId('composer-context-chip-file-foo.mdx');++ expect(chip.textContent).toContain('foo.mdx');+ expect(chip.querySelector('[data-testid="file-entry-icon-markdown"]')).not.toBeNull();+ expect(chip.querySelector('[data-testid="file-entry-extension-badge"]')).toBeNull();+ });+test('renders nothing when the file set is empty', async () => {const { container } = await renderChips([]);expect(container.querySelector('[data-testid="composer-context-chips"]')).toBeNull();diff --git a/packages/app/src/components/ComposerContextChips.tsx b/packages/app/src/components/ComposerContextChips.tsxindex 1af3c44af..ee9033a87 100644--- a/packages/app/src/components/ComposerContextChips.tsx+++ b/packages/app/src/components/ComposerContextChips.tsx@@ -70,7 +70,7 @@ function FileChip({ path, onRemove }: { path: string; onRemove: () => void }) {className="group/remove relative size-3.5 shrink-0 rounded-sm text-muted-foreground/80 hover:text-foreground"><span className="absolute top-1/2 left-1/2 inline-flex size-3 -translate-x-1/2 -translate-y-1/2 opacity-100 transition-opacity duration-150 ease-out group-hover/chip:opacity-0 group-focus-within/chip:opacity-0 motion-reduce:transition-none">- <FileEntryPathIcon path={path} className="size-3" />+ <FileEntryPathIcon path={path} className="size-3" showExtensionBadge={false} /></span><XclassName="absolute top-1/2 left-1/2 size-3 -translate-x-1/2 -translate-y-1/2 opacity-0 transition-opacity duration-150 ease-out group-hover/chip:opacity-100 group-focus-within/chip:opacity-100 motion-reduce:transition-none"diff --git a/packages/app/src/components/FileSidebar.tsx b/packages/app/src/components/FileSidebar.tsxindex ad4e06fff..35b2e1447 100644--- a/packages/app/src/components/FileSidebar.tsx+++ b/packages/app/src/components/FileSidebar.tsx@@ -146,6 +146,21 @@ const ToolbarButton: FC<ToolbarButtonProps> = ({ icon: Icon, label, ...props }));};+const ToolbarDropdownTrigger: FC<ToolbarButtonProps> = ({ icon: Icon, label, ...props }) => {+ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <DropdownMenuTrigger asChild>+ <Button variant="ghost" size="icon-sm" aria-label={label} {...props}>+ <Icon aria-hidden="true" />+ </Button>+ </DropdownMenuTrigger>+ </TooltipTrigger>+ <TooltipContent>{label}</TooltipContent>+ </Tooltip>+ );+};+function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {const { t } = useLingui();// Imperative handle to the FileTree — header buttons (Expand-All / Collapse-@@ -240,6 +255,7 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {// cycle: cleanup unsubscribes the old listener, then the body re-subscribes// through the new handle. No race, no stale closure.const [folderState, setFolderState] = useState(EMPTY_FOLDER_STATE);+useEffect(() => {if (tree === null) return;const sync = () => {@@ -504,7 +520,7 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {}case 'reveal-in-finder': {if (!bridge || !workspace) return;- const absPath = resolveActiveTargetAbsPath(activeTarget, activeDocName, workspace);+ const absPath = resolveActiveTargetAbsPath(activeTarget, workspace);void bridge.shell.showItemInFolder(absPath);return;}@@ -534,7 +550,7 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {toast.error(t`No AI agents installed`);return;}- const input = buildSendToAiInputForActiveTarget(activeTarget, activeDocName, workspace);+ const input = buildSendToAiInputForActiveTarget(activeTarget, workspace);if (!input) return;const [defaultTarget] = installedTargets;if (!defaultTarget) return;@@ -543,7 +559,7 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {}case 'copy-full-path': {if (!workspace) return;- const absPath = resolveActiveTargetAbsPath(activeTarget, activeDocName, workspace);+ const absPath = resolveActiveTargetAbsPath(activeTarget, workspace);void navigator.clipboard.writeText(absPath).then(() => toast.success(t`Copied full path`, { description: absPath }))@@ -554,7 +570,7 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {return;}case 'copy-relative-path': {- const relPath = resolveActiveTargetRelativePath(activeTarget, activeDocName);+ const relPath = resolveActiveTargetRelativePath(activeTarget);// `resolveActiveTargetRelativePath` returns `''` for null / missing// scopes (the project root has no project-relative path).// Don't pollute the clipboard with an empty string + a misleading@@ -624,7 +640,6 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {tree,workspace,activeTarget,- activeDocName,initialCreateDir,projectLocalBinding,showHiddenFiles,@@ -793,9 +808,7 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {*/}{hasFolders ? (<DropdownMenu>- <DropdownMenuTrigger asChild>- <ToolbarButton icon={ListCollapse} label={t`Tree view options`} />- </DropdownMenuTrigger>+ <ToolbarDropdownTrigger icon={ListCollapse} label={t`Tree view options`} /><DropdownMenuContent align="end" className="min-w-52">{!allExpanded ? (<DropdownMenuItem onSelect={() => tree?.expandAll()}>@@ -823,9 +836,7 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {// Mirrors the Tree view options dropdown above. Picking a// template runs the same inline-rename create flow as New file.<DropdownMenu>- <DropdownMenuTrigger asChild>- <ToolbarButton icon={FilePlus} label={t`New from template`} />- </DropdownMenuTrigger>+ <ToolbarDropdownTrigger icon={FilePlus} label={t`New from template`} /><DropdownMenuContent align="end" className="min-w-52"><TemplateMenuRowsparentDir={initialCreateDir}diff --git a/packages/app/src/components/FileTree.showall-lazy.dom.test.tsx b/packages/app/src/components/FileTree.showall-lazy.dom.test.tsxindex 87aeba0bc..7771fdbb3 100644--- a/packages/app/src/components/FileTree.showall-lazy.dom.test.tsx+++ b/packages/app/src/components/FileTree.showall-lazy.dom.test.tsx@@ -20,8 +20,8 @@*/import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from 'bun:test';import { i18n } from '@lingui/core';-import { cleanup, render, screen, waitFor } from '@testing-library/react';-import type { ReactNode } from 'react';+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';+import type { MouseEventHandler, ReactNode } from 'react';import { emitDocumentsChanged } from '@/lib/documents-events';// Deterministic `Intl.NumberFormat` output for the truncation-notice smoke@@ -70,6 +70,18 @@ function docEntry(docName: string) {};}+function assetEntry(path: string) {+ return {+ kind: 'asset',+ path,+ assetExt: path.split('.').pop() ?? 'file',+ mediaKind: null,+ size: 1,+ modified: '2026-06-12T00:00:00.000Z',+ referencedBy: [],+ };+}+function folderEntry(path: string, hasChildren: boolean) {return {kind: 'folder',@@ -193,6 +205,7 @@ class StubModel {}const model = new StubModel();+const openTargetMock = mock(() => {});mock.module('sonner', () => ({ toast: { success: mock(() => {}), error: mock(() => {}) } }));mock.module('next-themes', () => ({ useTheme: () => ({ resolvedTheme: 'light' }) }));@@ -208,7 +221,7 @@ mock.module('@/editor/DocumentContext', () => ({getPoolActiveDocName: () => null,poolHas: () => false,isNewTabActive: false,- openTarget: mock(() => {}),+ openTarget: openTargetMock,prewarm: () => {},remapTabsForRename: mock(() => {}),}),@@ -279,11 +292,31 @@ mock.module('@pierre/trees', () => ({}));mock.module('@pierre/trees/react', () => ({useFileTree: () => ({ model }),- FileTree: ({ header }: { header?: ReactNode }) => (- <div data-testid="fake-pierre-tree" role="tree">- {header}- </div>- ),+ FileTree: ({+ header,+ onClickCapture,+ }: {+ header?: ReactNode;+ onClickCapture?: MouseEventHandler<HTMLDivElement>;+ }) => {+ return (+ <div data-testid="fake-pierre-tree" role="tree" onClickCapture={onClickCapture}>+ {header}+ {[...model.items.values()].map((item) => (+ <div+ key={item.path}+ role="treeitem"+ data-item-path={item.path}+ data-item-type={item.isDirectory() ? 'folder' : 'file'}+ aria-selected={model.selectedPaths.includes(item.path) ? 'true' : 'false'}+ tabIndex={-1}+ >+ {item.path}+ </div>+ ))}+ </div>+ );+ },}));const { FileTree } = await import('./FileTree');@@ -306,6 +339,8 @@ describe('FileTree showAll lazy root seed', () => {model.listeners.clear();model.focusedPath = null;model.selectedPaths = [];+ openTargetMock.mockClear();+ window.location.hash = '';globalThis.fetch = makeFetchMock() as unknown as typeof fetch;consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});});@@ -406,6 +441,93 @@ describe('FileTree showAll lazy root seed', () => {expect(model.getItem('README.md')?.isDirectory()).toBe(false);});+ test('first click on non-document file rows opens the asset tab', async () => {+ showAllResponseFactory = () =>+ jsonResponse({+ documents: [assetEntry('LICENSE'), assetEntry('package.json')],+ truncated: false,+ });+ const view = render(<FileTree />);++ await waitFor(() => expect(model.items.has('package.json')).toBe(true));+ view.rerender(<FileTree />);+ for (const path of ['LICENSE', 'package.json']) {+ const row = screen.getByRole('treeitem', { name: path });+ fireEvent.click(row);++ await waitFor(() =>+ expect(openTargetMock).toHaveBeenCalledWith(+ {+ kind: 'asset',+ target: path,+ assetPath: path,+ mediaKind: null,+ },+ { tabBehavior: 'replace-active' },+ ),+ );+ expect(window.location.hash).toBe(`#/__asset__/${path}`);+ openTargetMock.mockClear();+ window.location.hash = '';+ }+ });++ test('first click from one document row to README opens README', async () => {+ showAllResponseFactory = () =>+ jsonResponse({+ documents: [docEntry('foo'), docEntry('README')],+ truncated: false,+ });+ const view = render(<FileTree />);++ await waitFor(() => expect(model.items.has('README.md')).toBe(true));+ model.selectedPaths = ['foo.md'];+ view.rerender(<FileTree />);+ const row = screen.getByRole('treeitem', { name: 'README.md' });+ fireEvent.click(row);++ await waitFor(() =>+ expect(openTargetMock).toHaveBeenCalledWith(+ {+ kind: 'doc',+ target: 'README',+ docName: 'README',+ },+ { tabBehavior: 'replace-active' },+ ),+ );+ expect(window.location.hash).toBe('#/README');+ });++ test('first click from a document row to a folder opens the folder', async () => {+ showAllResponseFactory = () =>+ jsonResponse({+ documents: [docEntry('foo'), folderEntry('docs', true), docEntry('docs/nested')],+ truncated: false,+ });+ const view = render(<FileTree />);++ await waitFor(() => expect(model.items.has('docs/')).toBe(true));+ model.selectedPaths = ['foo.md'];+ view.rerender(<FileTree />);+ expect(model.getItem('docs/')?.isExpanded()).toBe(false);+ const row = screen.getByRole('treeitem', { name: 'docs/' });+ fireEvent.click(row);++ await waitFor(() =>+ expect(openTargetMock).toHaveBeenCalledWith(+ {+ kind: 'folder',+ target: 'docs',+ folderPath: 'docs',+ },+ { tabBehavior: 'replace-active' },+ ),+ );+ expect(window.location.hash).toBe('#/docs/');+ expect(model.getItem('docs/')?.isExpanded()).toBe(true);+ });+test('a truncated depth-1 level still drives the truncation notice (QA-002 wiring)', async () => {showAllResponseFactory = () =>jsonResponse({diff --git a/packages/app/src/components/FileTree.tsx b/packages/app/src/components/FileTree.tsxindex e59789d9c..b14d4700c 100644--- a/packages/app/src/components/FileTree.tsx+++ b/packages/app/src/components/FileTree.tsx@@ -86,6 +86,7 @@ import {relativePathForTreeItem,treeDirectoryPathToFolderPath,treeFilePathToDocName,+ treeFilePathToDocumentDocName,treeItemToTarget,treePathSignature,treePathToAppPath,@@ -606,6 +607,23 @@ function treePathToTarget(treePath: string, documents: readonly FileEntry[]): Fi);}+function alternateMarkdownTreePath(treePath: string): string | null {+ const match = treePath.match(/\.(md|mdx)$/i);+ if (!match) return null;+ const ext = match[0].toLowerCase();+ const alternateExt = ext === '.md' ? '.mdx' : '.md';+ return `${treePath.slice(0, -match[0].length)}${alternateExt}`;+}++function hasSameStemMarkdownSiblingTreePath(+ treePath: string,+ treePaths: readonly string[],+): boolean {+ const alternate = alternateMarkdownTreePath(treePath);+ if (!alternate) return false;+ return treePaths.includes(alternate);+}+function isTreePathInsideFolder(treePath: string, folderTreePath: string): boolean {return treePath !== folderTreePath && treePath.startsWith(folderTreePath);}@@ -751,7 +769,7 @@ function FileTreeMenu({workspace,}): buildHandoffInput({- docName: treeFilePathToDocName(item.path),+ docName: treeFilePathToDocumentDocName(item.path, documents),workspace,});@@ -767,7 +785,7 @@ function FileTreeMenu({? null: isFolder? buildFolderShareInput(treeDirectoryPathToFolderPath(item.path))- : buildDocShareInput(treeFilePathToDocName(item.path));+ : buildDocShareInput(treeFilePathToDocumentDocName(item.path, documents));const canShare = hasRemote && shareInput !== null;const handleShare = () => {if (!shareInput) return;@@ -1299,7 +1317,12 @@ export function FileTree({});}- function navigateToWithPulse(targetPath: string, size?: number) {+ function navigateToWithPulse(+ targetPath: string,+ size?: number,+ options?: { registerPage?: boolean },+ ) {+ if (options?.registerPage) addPage(targetPath);openTarget(navigationTargetForDocument(targetPath, size), { tabBehavior: 'replace-active' });replaceHashWithoutNavigation(hashFromDocName(targetPath));notifySidebarFileSelected();@@ -1368,6 +1391,7 @@ export function FileTree({const documentsRef = useRef(documents);const pageMetaRef = useRef(pageMeta);+ const pendingExactFileSelectionRef = useRef<string | null>(null);function activateTreePath(treePath: string, entries: readonly FileEntry[] = documents) {const action = resolveFileTreeSelectionAction(treePath, entries);if (action.kind === 'none') {@@ -1398,7 +1422,9 @@ export function FileTree({const docEntry = entries.find((item): item is DocumentEntry => isDocumentEntry(item) && item.docName === action.path,);- navigateToWithPulse(action.path, docEntry?.size);+ navigateToWithPulse(action.path, docEntry?.size, {+ registerPage: hasSupportedDocumentExtension(action.path),+ });}function navigateToAssetWithPulse(assetPath: string, entries?: readonly FileEntry[]) {const currentEntries = entries ?? documentsRef.current;@@ -2689,7 +2715,7 @@ export function FileTree({}: {kind: 'file' as const,- fromPath: treeFilePathToDocName(sourceTreePath),+ fromPath: treeFilePathToDocumentDocName(sourceTreePath, documentsRef.current),toPath: destinationTreePath,};const activeBeforeRename = {@@ -2806,6 +2832,9 @@ export function FileTree({for (const operation of operations) {const isFolder = operation.sourcePath.endsWith('/');const sourceIsAsset = !isFolder && isAssetTreePath(operation.sourcePath);+ const sourceDocName = sourceIsAsset+ ? null+ : treeFilePathToDocumentDocName(operation.sourcePath, documentsRef.current);const payload = isFolder? {kind: 'folder' as const,@@ -2820,8 +2849,11 @@ export function FileTree({}: {kind: 'file' as const,- fromPath: treeFilePathToDocName(operation.sourcePath),- toPath: treeFilePathToDocName(operation.destinationTreePath),+ fromPath: sourceDocName ?? treeFilePathToDocName(operation.sourcePath),+ toPath:+ sourceDocName && hasSupportedDocumentExtension(sourceDocName)+ ? operation.destinationTreePath+ : treeFilePathToDocName(operation.destinationTreePath),};const res = await fetch('/api/rename-path', {@@ -3191,6 +3223,14 @@ export function FileTree({});}+ function selectedRenderedTreePath(): string | null {+ const shadow = fileTreeHostRef.current?.querySelector(FILE_TREE_TAG_NAME)?.shadowRoot;+ const selectedRow = shadow?.querySelector<HTMLElement>(+ '[aria-selected="true"][data-item-path]',+ );+ return selectedRow?.dataset.itemPath ?? null;+ }+useLayoutEffect(() => {documentsRef.current = documents;pageMetaRef.current = pageMeta;@@ -3217,7 +3257,25 @@ export function FileTree({// effect also catches this once activeTarget commits, but clearing// eagerly avoids a one-frame deselected flash on the clicked row).setCreationDirCleared(false);- activateTreePath(normalizeSelectionPath(selected), documents);+ const selectedTreePath = normalizeSelectionPath(selected);+ const pendingExactFileSelection = pendingExactFileSelectionRef.current;+ // The click handler sets this ref and schedules hash navigation with+ // setTimeout(0); this microtask consumes the exact row first.+ const hasPendingExactFileSelection =+ pendingExactFileSelection !== null &&+ treeFilePathToDocName(pendingExactFileSelection) ===+ treeFilePathToDocName(selectedTreePath);+ const targetTreePath = hasPendingExactFileSelection+ ? pendingExactFileSelection+ : selectedTreePath;+ pendingExactFileSelectionRef.current = null;+ queueMicrotask(() => {+ const renderedTreePath = hasPendingExactFileSelection ? null : selectedRenderedTreePath();+ activateTreePath(+ normalizeSelectionPath(renderedTreePath ?? targetTreePath),+ documentsRef.current,+ );+ });}};handleRenameErrorRef.current = (message) => {@@ -4012,18 +4070,32 @@ export function FileTree({hoveredPrewarmDocRef.current = null;}+ function hasSameStemMarkdownSiblingRendered(treePath: string): boolean {+ const alternate = alternateMarkdownTreePath(treePath);+ if (!alternate) return false;+ const shadow = fileTreeHostRef.current?.querySelector(FILE_TREE_TAG_NAME)?.shadowRoot;+ if (!shadow) return false;+ for (const row of shadow.querySelectorAll<HTMLElement>('[data-item-path]')) {+ if (row.dataset.itemPath === alternate) return true;+ }+ return false;+ }+function handleTreeMouseMove(event: ReactMouseEvent<HTMLElement>) {const path = findTreeItemPath(event.nativeEvent);if (!path || path.endsWith('/')) {cancelCurrentHoverPrewarm();return;}- const docName = treeFilePathToDocName(path);const entry = documentsRef.current.find((item) => fileEntryToTreePath(item) === path);if (entry && isAssetEntry(entry)) {cancelCurrentHoverPrewarm();return;}+ const docName =+ entry && isDocumentEntry(entry)+ ? entry.docName+ : treeFilePathToDocumentDocName(path, documentsRef.current);if (entry && isDocumentEntry(entry) && isDocumentOverOpenByteLimit(entry.size)) {cancelCurrentHoverPrewarm();return;@@ -4052,23 +4124,51 @@ export function FileTree({}return;}- if (item.getAttribute('aria-selected') !== 'true') return;+ const wasSelected = item.getAttribute('aria-selected') === 'true';const rawPath = item.dataset.itemPath;if (!rawPath) return;const path =item.dataset.itemType === 'folder' ? folderPathToTreeDirectoryPath(rawPath) : rawPath;- if (model.getSelectedPaths().length !== 1) return;if (item.dataset.itemType === 'folder') {const folderPath = treeDirectoryPathToFolderPath(path);+ const folderItem = asDirectoryHandle(model.getItem(path));+ if (!wasSelected) {+ event.preventDefault();+ event.stopPropagation();+ if (folderItem && !folderItem.isExpanded()) folderItem.expand();+ queueMicrotask(() => navigateToFolderWithPulse(folderPath));+ return;+ }+ if (model.getSelectedPaths().length !== 1) return;if (window.location.hash === hashFromFolderPath(folderPath)) return;+ event.preventDefault();+ event.stopPropagation();+ if (folderItem && !folderItem.isExpanded()) folderItem.expand();queueMicrotask(() => navigateToFolderWithPulse(folderPath));return;}- const docName = treeFilePathToDocName(path);+ if (!wasSelected) {+ // Lazy/show-all model state can lag rows that already rendered, so the+ // DOM query is the fallback for same-stem markdown sibling detection.+ if (+ hasSameStemMarkdownSiblingTreePath(path, treePathsRef.current) ||+ hasSameStemMarkdownSiblingRendered(path)+ ) {+ pendingExactFileSelectionRef.current = path;+ // Let handleSelectionChange's microtask consume the exact file selection+ // before navigation commits the extension-qualified URL.+ setTimeout(() => navigateToWithPulse(path, undefined, { registerPage: true }), 0);+ return;+ }+ queueMicrotask(() => activateTreePath(path));+ return;+ }+ const docName = treeFilePathToDocumentDocName(path, documentsRef.current);+ if (model.getSelectedPaths().length !== 1) return;if (window.location.hash === hashFromDocName(docName)) return;queueMicrotask(() => activateTreePath(path));}diff --git a/packages/app/src/components/composer-shared-draft.dom.test.tsx b/packages/app/src/components/composer-shared-draft.dom.test.tsxindex 42bb27d9d..21d03af0b 100644--- a/packages/app/src/components/composer-shared-draft.dom.test.tsx+++ b/packages/app/src/components/composer-shared-draft.dom.test.tsx@@ -37,6 +37,10 @@ mock.module('@/lib/config-context', () => ({useConfigContext: () => ({ merged: { appearance: { preview: { autoOpen: true } } } }),}));+mock.module('@/components/PageListContext', () => ({+ usePageList: () => ({ pageMeta: new Map() }),+}));+mock.module('@/components/handoff/OpenInAgentMenuItem', () => ({TargetIcon: ({ id }: { id: string }) => <span data-testid={`target-icon-${id}`} />,}));diff --git a/packages/app/src/components/file-entry-icon.tsx b/packages/app/src/components/file-entry-icon.tsxindex 095a7f45d..6129c5e11 100644--- a/packages/app/src/components/file-entry-icon.tsx+++ b/packages/app/src/components/file-entry-icon.tsx@@ -51,8 +51,22 @@ function fileEntryIconFieldsForPath(path: string): {return { kind: 'file', path, bodyIndexed: false };}-export function FileEntryPathIcon({ path, className }: { path: string; className?: string }) {- return <FileEntryIcon {...fileEntryIconFieldsForPath(path)} className={className} />;+export function FileEntryPathIcon({+ path,+ className,+ showExtensionBadge,+}: {+ path: string;+ className?: string;+ showExtensionBadge?: boolean;+}) {+ return (+ <FileEntryIcon+ {...fileEntryIconFieldsForPath(path)}+ className={className}+ showExtensionBadge={showExtensionBadge}+ />+ );}export function fileEntryPathIconToSvgString(path: string): string {@@ -77,12 +91,14 @@ export function FileEntryIcon({docExt,bodyIndexed,className,+ showExtensionBadge = true,}: {kind: 'file' | 'folder';path: string;docExt?: string;bodyIndexed?: boolean;className?: string;+ showExtensionBadge?: boolean;}) {if (kind === 'folder') {return (@@ -98,7 +114,8 @@ export function FileEntryIcon({bodyIndexed === false ? getFileExtension(path) : (docExt ?? (getFileExtension(path) || '.md'));const normalizedExt = ext.toLowerCase();const mediaKind = mediaKindForSidebarAssetExtension(normalizedExt);- const badge = ext && normalizedExt !== '.md' ? ext.slice(1).toUpperCase() : null;+ const badge =+ showExtensionBadge && ext && normalizedExt !== '.md' ? ext.slice(1).toUpperCase() : null;const iconClassName = cn(className, mediaKind === 'image' && 'text-rose-500');return (diff --git a/packages/app/src/components/file-tree-adapter.test.ts b/packages/app/src/components/file-tree-adapter.test.tsindex 8425606f9..d66664588 100644--- a/packages/app/src/components/file-tree-adapter.test.ts+++ b/packages/app/src/components/file-tree-adapter.test.ts@@ -19,6 +19,7 @@ import {relativePathForTreeItem,treeDirectoryPathToFolderPath,treeFilePathToDocName,+ treeFilePathToDocumentDocName,treeItemToTarget,treePathToAppPath,uploadedPathForSidebarDrop,@@ -261,6 +262,7 @@ describe('file-tree-adapter', () => {expect(docNameToTreePath('README')).toBe('README.md');expect(docNameToTreePath('README', '.md')).toBe('README.md');expect(docNameToTreePath('docs/guide', '.mdx')).toBe('docs/guide.mdx');+ expect(docNameToTreePath('docs/guide.mdx', '.mdx')).toBe('docs/guide.mdx');});test('treeFilePathToDocName strips both .md and .mdx suffixes', () => {@@ -268,6 +270,87 @@ describe('file-tree-adapter', () => {expect(treeFilePathToDocName('docs/guide.mdx')).toBe('docs/guide');});+ test('treeFilePathToDocumentDocName preserves exact document identities', () => {+ const documents: FileEntry[] = [+ {+ kind: 'document',+ docName: 'docs/guide.mdx',+ docExt: '.mdx',+ size: 0,+ modified: '',+ },+ ];++ expect(treeFilePathToDocumentDocName('docs/guide.mdx', documents)).toBe('docs/guide.mdx');+ expect(treeFilePathToDocumentDocName('docs/missing.mdx', documents)).toBe('docs/missing');+ });++ test('treeFilePathToDocumentDocName preserves an extension row beside the opposite document extension', () => {+ const documents: FileEntry[] = [+ {+ kind: 'document',+ docName: 'docs/guide',+ docExt: '.mdx',+ size: 0,+ modified: '',+ },+ {+ kind: 'asset',+ path: 'docs/guide.md',+ assetExt: 'md',+ mediaKind: null,+ size: 0,+ modified: '',+ },+ ];++ expect(treeFilePathToDocumentDocName('docs/guide.md', documents)).toBe('docs/guide.md');+ });++ test('treeFilePathToDocumentDocName preserves extension rows when both variants are generic entries', () => {+ const documents: FileEntry[] = [+ {+ kind: 'asset',+ path: 'docs/guide.md',+ assetExt: 'md',+ mediaKind: null,+ size: 0,+ modified: '',+ },+ {+ kind: 'asset',+ path: 'docs/guide.mdx',+ assetExt: 'mdx',+ mediaKind: null,+ size: 0,+ modified: '',+ },+ ];++ expect(treeFilePathToDocumentDocName('docs/guide.md', documents)).toBe('docs/guide.md');+ });++ test('treeItemToTarget preserves exact document identities when present', () => {+ const mdxFile = menuItem('docs/guide.mdx', 'file');+ const documents: FileEntry[] = [+ {+ kind: 'document',+ docName: 'docs/guide.mdx',+ docExt: '.mdx',+ size: 0,+ modified: '',+ },+ ];++ expect(treeItemToTarget(mdxFile, documents)).toEqual({+ kind: 'file',+ name: 'guide',+ path: 'docs/guide.mdx',+ treePath: 'docs/guide.mdx',+ docExt: '.mdx',+ });+ });+test('documentsToTreePaths uses each doc.docExt; absent docExt defaults to .md', () => {expect(documentsToTreePaths([diff --git a/packages/app/src/components/file-tree-adapter.ts b/packages/app/src/components/file-tree-adapter.tsindex 054c56f20..2a25f2a2a 100644--- a/packages/app/src/components/file-tree-adapter.ts+++ b/packages/app/src/components/file-tree-adapter.ts@@ -27,6 +27,7 @@ export function docNameToTreePath(docName: string,docExt: string = DEFAULT_TREE_EXTENSION,): string {+ if (TREE_EXTENSION_PATTERN.test(docName)) return docName;return `${docName}${docExt}`;}@@ -34,6 +35,28 @@ export function treeFilePathToDocName(treePath: string): string {return stripTrailingSlash(treePath).replace(TREE_EXTENSION_PATTERN, '');}+export function treeFilePathToDocumentDocName(+ treePath: string,+ documents: readonly FileEntry[],+): string {+ const normalized = stripTrailingSlash(treePath);+ const exact = documents.find(+ (entry): entry is DocumentEntry =>+ isDocumentEntry(entry) && fileEntryToTreePath(entry) === normalized,+ );+ if (exact) return exact.docName;+ const extensionless = treeFilePathToDocName(normalized);+ const collidingEntry = documents.find((entry) => {+ const entryTreePath = fileEntryToTreePath(entry);+ return (+ entryTreePath !== normalized &&+ TREE_EXTENSION_PATTERN.test(entryTreePath) &&+ treeFilePathToDocName(entryTreePath) === extensionless+ );+ });+ return collidingEntry && TREE_EXTENSION_PATTERN.test(normalized) ? normalized : extensionless;+}+export function fileEntryToTreePath(entry: FileEntry): string {if (isFolderEntry(entry)) return folderPathToTreeDirectoryPath(entry.path);return isAssetEntry(entry) ? entry.path : docNameToTreePath(entry.docName, entry.docExt);@@ -191,7 +214,7 @@ export function treeItemToTarget(const isFolder = item.kind === 'directory';const appPath = isFolder? treeDirectoryPathToFolderPath(item.path)- : treeFilePathToDocName(item.path);+ : treeFilePathToDocumentDocName(item.path, documents);if (isFolder) {return {kind: 'folder',diff --git a/packages/app/src/components/file-tree-selection.test.ts b/packages/app/src/components/file-tree-selection.test.tsindex 22b05931b..eba531f87 100644--- a/packages/app/src/components/file-tree-selection.test.ts+++ b/packages/app/src/components/file-tree-selection.test.ts@@ -164,6 +164,74 @@ describe('resolveFileTreeSelectionAction', () => {});});+ test('routes extension-qualified document rows to their exact document identity', () => {+ expect(+ resolveFileTreeSelectionAction('docs/guide.mdx', [+ {+ kind: 'document',+ docName: 'docs/guide.mdx',+ docExt: '.mdx',+ size: 0,+ modified: '',+ },+ ]),+ ).toEqual({+ kind: 'document',+ path: 'docs/guide.mdx',+ });+ });++ test('routes an extension row beside the opposite document extension as an exact document', () => {+ expect(+ resolveFileTreeSelectionAction('docs/guide.md', [+ {+ kind: 'document',+ docName: 'docs/guide',+ docExt: '.mdx',+ size: 0,+ modified: '',+ },+ {+ kind: 'asset',+ path: 'docs/guide.md',+ assetExt: 'md',+ mediaKind: null,+ size: 0,+ modified: '',+ },+ ]),+ ).toEqual({+ kind: 'document',+ path: 'docs/guide.md',+ });+ });++ test('routes same-stem markdown generic rows as exact document identities', () => {+ expect(+ resolveFileTreeSelectionAction('docs/guide.md', [+ {+ kind: 'asset',+ path: 'docs/guide.md',+ assetExt: 'md',+ mediaKind: null,+ size: 0,+ modified: '',+ },+ {+ kind: 'asset',+ path: 'docs/guide.mdx',+ assetExt: 'mdx',+ mediaKind: null,+ size: 0,+ modified: '',+ },+ ]),+ ).toEqual({+ kind: 'document',+ path: 'docs/guide.md',+ });+ });+test('drops transient unknown document and folder selections', () => {expect(resolveFileTreeSelectionAction('docs/missing.md', [])).toEqual({ kind: 'none' });expect(resolveFileTreeSelectionAction('docs/', [])).toEqual({ kind: 'none' });diff --git a/packages/app/src/components/file-tree-selection.ts b/packages/app/src/components/file-tree-selection.tsindex b088c60af..1a1567e5f 100644--- a/packages/app/src/components/file-tree-selection.ts+++ b/packages/app/src/components/file-tree-selection.ts@@ -1,6 +1,10 @@import type { InlineAssetMediaKind } from '@inkeep/open-knowledge-core';import { hashFromAssetPath } from '@/lib/doc-hash';-import { fileEntryToTreePath, treePathToAppPath } from './file-tree-adapter';+import {+ fileEntryToTreePath,+ treeFilePathToDocumentDocName,+ treePathToAppPath,+} from './file-tree-adapter';import type { FileEntry } from './file-tree-utils';import { isAssetEntry, isDocumentEntry, isFolderEntry } from './file-tree-utils';import { docNameForNavigationTarget, type ResolvedNavigationTarget } from './navigation-targets';@@ -83,6 +87,13 @@ export function resolveFileTreeSelectionAction(if (!selectedPath) return { kind: 'none' };const entry = entries.find((item) => fileEntryToTreePath(item) === selectedPath);+ const appPath = treePathToAppPath(selectedPath);+ const documentDocName = selectedPath.endsWith('/')+ ? appPath+ : treeFilePathToDocumentDocName(selectedPath, entries);+ if (documentDocName !== appPath) {+ return { kind: 'document', path: documentDocName };+ }if (entry && isAssetEntry(entry)) {return {kind: 'asset',@@ -91,8 +102,10 @@ export function resolveFileTreeSelectionAction(mediaKind: entry.mediaKind,};}+ if (entry && isDocumentEntry(entry)) {+ return { kind: 'document', path: entry.docName };+ }- const appPath = treePathToAppPath(selectedPath);if (selectedPath.endsWith('/')) {const hasFolderEntry = entries.some((item) => {if (isFolderEntry(item)) return item.path === appPath || item.path.startsWith(`${appPath}/`);diff --git a/packages/app/src/components/handoff/useHandoffDispatch.test.ts b/packages/app/src/components/handoff/useHandoffDispatch.test.tsindex af589af91..aae04257e 100644--- a/packages/app/src/components/handoff/useHandoffDispatch.test.ts+++ b/packages/app/src/components/handoff/useHandoffDispatch.test.ts@@ -676,6 +676,19 @@ describe('buildHandoffInput — shared surface helper (US-011)', () => {});});+ test('POSIX: preserves extension-qualified mdx relativePath + docPath', async () => {+ const { buildHandoffInput } = await import('./useHandoffDispatch');+ const input = buildHandoffInput({+ docName: 'specs/foo/SPEC.mdx',+ workspace: { contentDir: '/Users/andrew/repo', pathSeparator: '/' },+ });+ expect(input).toEqual({+ docContext: { relativePath: 'specs/foo/SPEC.mdx' },+ projectDir: '/Users/andrew/repo',+ docPath: '/Users/andrew/repo/specs/foo/SPEC.mdx',+ });+ });+test('Windows: rewrites relativePath slashes to backslash for docPath', async () => {const { buildHandoffInput } = await import('./useHandoffDispatch');const input = buildHandoffInput({@@ -2164,6 +2177,24 @@ describe('buildComposerHandoffInput — compose-scoped helper (US-002)', () => {expect(input?.docPath).toBe('/repo/specs/foo/SPEC.md');});+ test('docRelativePath overrides the fallback docName extension for compose input', async () => {+ const { buildComposerHandoffInput } = await import('./useHandoffDispatch');+ const input = buildComposerHandoffInput({+ docName: 'specs/foo/SPEC',+ docRelativePath: 'specs/foo/SPEC.mdx',+ workspace: { contentDir: '/repo', pathSeparator: '/' },+ instruction: 'tighten the intro',+ mentions: [],+ });+ expect(input?.compose).toEqual({+ scope: 'doc',+ docRelativePath: 'specs/foo/SPEC.mdx',+ instruction: 'tighten the intro',+ mentions: [],+ });+ expect(input?.docPath).toBe('/repo/specs/foo/SPEC.mdx');+ });+test('folderRelativePath with null docName builds a folder-scope compose input (folder lead, empty docPath)', async () => {const { buildComposerHandoffInput } = await import('./useHandoffDispatch');const input = buildComposerHandoffInput({diff --git a/packages/app/src/components/handoff/useHandoffDispatch.ts b/packages/app/src/components/handoff/useHandoffDispatch.tsindex c80c052ee..5820e3cb2 100644--- a/packages/app/src/components/handoff/useHandoffDispatch.ts+++ b/packages/app/src/components/handoff/useHandoffDispatch.ts@@ -256,15 +256,15 @@ export interface HandoffDispatchInput {/*** Shared helper for the three surfaces (EditorHeader, CommandPalette, FileTree)- * that all construct a `HandoffDispatchInput` the same way: from an extension-- * less doc path (`activeDocName` or a right-clicked tree-node's `path`) plus- * the workspace root / OS separator.+ * that all construct a `HandoffDispatchInput` the same way: from a document+ * identifier (`activeDocName` or a right-clicked tree-node's `path`) plus the+ * workspace root / OS separator.** Returns `null` when either input is missing — mirrors the* `OpenInAgentMenu.input` contract ("disabled trigger when nothing to dispatch").** Centralizing the construction here guarantees that every surface:- * - Uses the same `.md`-suffix convention (via `docNameToRelativePath`).+ * - Uses the same markdown path convention (via `docNameToRelativePath`).* - Joins with the advertised separator (via `joinWorkspacePath`).* - Sets `docContext.relativePath` to the exact same POSIX form that the* prompt composer and MCP server consume.@@ -400,7 +400,7 @@ export function buildFolderHandoffInput(args: {/*** Selection-scoped variant — for the editor "Edit with AI" affordance (the* WYSIWYG bubble-menu button). Builds the input from the active doc's- * extension-less name, the user's instruction, and the passage the user+ * document identifier, the user's instruction, and the passage the user* selected, already serialized to markdown.** `relativePath` and `docPath` are derived exactly as `buildHandoffInput`@@ -465,8 +465,8 @@ export function buildSkillHandoffInput(args: {/*** Ask-scoped variant — for the persistent bottom "Ask AI" composer. Builds the- * input from the active doc's extension-less name, the loaded workspace, and- * the user's typed instruction. `relativePath` and `docPath` are derived+ * input from the active doc's identifier, the loaded workspace, and the user's+ * typed instruction. `relativePath` and `docPath` are derived* exactly as `buildHandoffInput` / `buildSelectionHandoffInput` do; ask scope* names a real doc, so `docPath` carries the doc's absolute path (informational* only — no URL builder threads `docPath`).@@ -525,6 +525,7 @@ export function buildAskHandoffInput(args: {*/export function buildComposerHandoffInput(args: {readonly docName: string | null;+ readonly docRelativePath?: string;/** Workspace-relative folder path, forward-slash normalized, no trailing* slash. When set and `docName` is null, selects folder scope. */readonly folderRelativePath?: string;@@ -536,7 +537,7 @@ export function buildComposerHandoffInput(args: {if (!args.workspace?.contentDir) return null;const { contentDir, pathSeparator } = args.workspace;if (args.docName) {- const relativePath = docNameToRelativePath(args.docName);+ const relativePath = args.docRelativePath ?? docNameToRelativePath(args.docName);const base = {scope: 'doc' as const,docRelativePath: relativePath,diff --git a/packages/app/src/components/navigation-targets.test.ts b/packages/app/src/components/navigation-targets.test.tsindex e2073a9c8..9910bb6c0 100644--- a/packages/app/src/components/navigation-targets.test.ts+++ b/packages/app/src/components/navigation-targets.test.ts@@ -107,6 +107,32 @@ describe('resolveNavigationTarget', () => {});});+ test('preserves extension-qualified document targets when the exact page exists', () => {+ const resolved = resolveNavigationTarget('docs/guide.md', {+ pages: new Set(['docs/guide.md', 'docs/guide.mdx', 'docs/guide']),+ folderPaths: new Set(['docs']),+ });++ expect(resolved).toEqual({+ kind: 'doc',+ target: 'docs/guide.md',+ docName: 'docs/guide.md',+ });+ });++ test('falls back to extensionless document targets when no exact extension page exists', () => {+ const resolved = resolveNavigationTarget('docs/guide.md', {+ pages: new Set(['docs/guide']),+ folderPaths: new Set(['docs']),+ });++ expect(resolved).toEqual({+ kind: 'doc',+ target: 'docs/guide',+ docName: 'docs/guide',+ });+ });+test('prefers an exact document over a folder with the same basename', () => {const resolved = resolveNavigationTarget('hello', {pages: new Set(['hello']),diff --git a/packages/app/src/components/navigation-targets.ts b/packages/app/src/components/navigation-targets.tsindex 1cb76aa48..e87656b41 100644--- a/packages/app/src/components/navigation-targets.ts+++ b/packages/app/src/components/navigation-targets.ts@@ -71,11 +71,18 @@ export function normalizeTargetPath(target: string): {} {const trimmed = target.trim();return {- normalizedTarget: normalizeDocNameInput(trimmed).replace(/\/+$/g, ''),+ normalizedTarget: trimmed+ .replace(/^\.\/+/, '')+ .replace(/^\/+/, '')+ .replace(/\/+$/g, ''),expectsFolder: /\/+$/.test(trimmed),};}+function extensionlessTargetPath(target: string): string {+ return normalizeDocNameInput(target).replace(/\/+$/g, '');+}+export function deriveKnownFolderPaths(docNames: Iterable<string>): Set<string> {const folderPaths = new Set<string>();for (const docName of docNames) {@@ -184,6 +191,7 @@ export function resolveNavigationTarget(if (!normalizedTarget) {return { kind: 'missing', target: normalizedTarget };}+ const extensionlessTarget = extensionlessTargetPath(target);if (!expectsFolder && options.pages.has(normalizedTarget)) {return {@@ -193,8 +201,20 @@ export function resolveNavigationTarget(};}+ if (+ !expectsFolder &&+ extensionlessTarget !== normalizedTarget &&+ options.pages.has(extensionlessTarget)+ ) {+ return {+ kind: 'doc',+ target: extensionlessTarget,+ docName: extensionlessTarget,+ };+ }+if (!expectsFolder) {- const slugMatchDocName = slugResolve(normalizedTarget, options.pagesBySlug);+ const slugMatchDocName = slugResolve(extensionlessTarget, options.pagesBySlug);if (slugMatchDocName) {return {kind: 'doc',@@ -204,31 +224,31 @@ export function resolveNavigationTarget(}}- const canonicalIndexDocName = `${normalizedTarget}/index`;+ const canonicalIndexDocName = `${extensionlessTarget}/index`;if (options.pages.has(canonicalIndexDocName)) {return {kind: 'folder-index',- target: normalizedTarget,- folderPath: normalizedTarget,+ target: extensionlessTarget,+ folderPath: extensionlessTarget,docName: canonicalIndexDocName,noteKind: 'canonical-index',};}- const leaf = normalizedTarget.split('/').pop();- const legacyFolderNoteDocName = leaf ? `${normalizedTarget}/${leaf}` : null;+ const leaf = extensionlessTarget.split('/').pop();+ const legacyFolderNoteDocName = leaf ? `${extensionlessTarget}/${leaf}` : null;if (legacyFolderNoteDocName && options.pages.has(legacyFolderNoteDocName)) {return {kind: 'folder-index',- target: normalizedTarget,- folderPath: normalizedTarget,+ target: extensionlessTarget,+ folderPath: extensionlessTarget,docName: legacyFolderNoteDocName,noteKind: 'legacy-folder-note',};}if (!expectsFolder) {- const basenameMatchDocName = basenameResolve(normalizedTarget, options.pagesByBasename);+ const basenameMatchDocName = basenameResolve(extensionlessTarget, options.pagesByBasename);if (basenameMatchDocName) {return {kind: 'doc',@@ -239,17 +259,17 @@ export function resolveNavigationTarget(}const knownFolderPaths = options.folderPaths ?? deriveKnownFolderPaths(options.pages);- if (knownFolderPaths.has(normalizedTarget)) {+ if (knownFolderPaths.has(extensionlessTarget)) {return {kind: 'folder',- target: normalizedTarget,- folderPath: normalizedTarget,+ target: extensionlessTarget,+ folderPath: extensionlessTarget,};}return {kind: 'missing',- target: normalizedTarget,+ target: extensionlessTarget || normalizedTarget,};}diff --git a/packages/app/src/components/ui/sidebar.partition.dom.test.tsx b/packages/app/src/components/ui/sidebar.partition.dom.test.tsxindex 5ba6135c0..f503568c1 100644--- a/packages/app/src/components/ui/sidebar.partition.dom.test.tsx+++ b/packages/app/src/components/ui/sidebar.partition.dom.test.tsx@@ -105,11 +105,8 @@ beforeEach(() => {originalInnerWidth = window.innerWidth;originalMatchMedia = window.matchMedia;originalUserAgent = window.navigator.userAgent;- // jsdom-preload exposes window.localStorage but does not also install the- // bare globalThis.localStorage that production source paths use directly.- // Install it for the duration of the test so the SidebarProvider's- // readPins()/applyToggle() (no-arg storage default) exercise the real- // jsdom storage instead of falling through readPins's try/catch.+ // Keep the production global and window storage references aligned so the+ // no-arg storage default exercises the real jsdom storage.(globalThis as { localStorage?: Storage }).localStorage = window.localStorage;window.localStorage.clear();});diff --git a/packages/app/src/components/ui/sidebar.web-shortcut-gate.dom.test.tsx b/packages/app/src/components/ui/sidebar.web-shortcut-gate.dom.test.tsxindex 4df30ea14..ae53fd883 100644--- a/packages/app/src/components/ui/sidebar.web-shortcut-gate.dom.test.tsx+++ b/packages/app/src/components/ui/sidebar.web-shortcut-gate.dom.test.tsx@@ -17,6 +17,7 @@*/import { afterEach, beforeEach, describe, expect, test } from 'bun:test';import { act, cleanup, render, screen } from '@testing-library/react';+import { SIDEBAR_PINS_KEY } from '@/lib/sidebar-pin-store';import { SidebarProvider, useSidebar } from './sidebar';function StateProbe() {@@ -40,11 +41,13 @@ describe('SidebarProvider web-mode ⌥⌘S shortcut — Electron gate', () => {beforeEach(() => {window.innerWidth = 1400;setOkDesktop(undefined);+ window.localStorage.removeItem(SIDEBAR_PINS_KEY);});afterEach(() => {cleanup();setOkDesktop(undefined);+ window.localStorage.removeItem(SIDEBAR_PINS_KEY);});test('web host (no window.okDesktop): ⌥⌘S toggles the sidebar', () => {diff --git a/packages/app/src/editor/DocumentContext.dom.test.tsx b/packages/app/src/editor/DocumentContext.dom.test.tsxindex 89e09ec25..4ad7de58d 100644--- a/packages/app/src/editor/DocumentContext.dom.test.tsx+++ b/packages/app/src/editor/DocumentContext.dom.test.tsx@@ -1,9 +1,10 @@import { afterEach, describe, expect, mock, spyOn, test } from 'bun:test';-import { act, cleanup, render, screen } from '@testing-library/react';+import { act, cleanup, render, screen, waitFor } from '@testing-library/react';import userEvent from '@testing-library/user-event';import { type ReactNode, useLayoutEffect, useState } from 'react';import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';-import { docTabId, localTabSessionStorageKey } from './editor-tabs';+import { hashFromAssetPath } from '@/lib/doc-hash';+import { assetTabId, docTabId, localTabSessionStorageKey } from './editor-tabs';let mockCollabUrl: string | null = null;@@ -22,6 +23,7 @@ const { DocumentProvider, useDocumentContext } = await import('./DocumentContextconst PINNED_TAB_ID = docTabId('Pinned.md');const OTHER_TAB_ID = docTabId('Other.md');const THIRD_TAB_ID = docTabId('Third.md');+const LICENSE_TAB_ID = assetTabId('LICENSE');const originalFetch = globalThis.fetch;function seedTabSession() {@@ -83,6 +85,11 @@ interface EditorBridgeStub {fire(action: MenuActionLike): void;}+interface DeferredSessionBridgeStub {+ bridge: OkDesktopBridge;+ resolveSession(): void;+}+function makeEditorBridgeStub(): EditorBridgeStub {let captured: ((action: MenuActionLike) => void) | null = null;const bridge = {@@ -119,6 +126,40 @@ function makeEditorBridgeStub(): EditorBridgeStub {};}+function makeDeferredSessionBridgeStub(state: {+ openTabs: string[];+ pinnedTabIds: string[];+ activeDocName: string | null;+ activeTabId: string | null;+ updatedAt: string | null;+}): DeferredSessionBridgeStub {+ let resolveSession: (() => void) | null = null;+ const sessionLoaded = new Promise<typeof state>((resolve) => {+ resolveSession = () => resolve(state);+ });+ const bridge = {+ config: {+ mode: 'editor',+ collabUrl: '',+ apiOrigin: '',+ projectPath: '',+ projectName: 'Test Project',+ },+ onMenuAction: () => () => {},+ project: {+ getSessionState: async () => sessionLoaded,+ setSessionState: async () => undefined,+ },+ } as unknown as OkDesktopBridge;++ return {+ bridge,+ resolveSession: () => {+ resolveSession?.();+ },+ };+}+function Harness() {const ctx = useDocumentContext();return (@@ -177,6 +218,30 @@ function BridgeCloseActiveHarness({ bridge }: { bridge: OkDesktopBridge }) {return <CloseActiveHarness />;}+function OpenLicenseDuringRestoreHarness() {+ const ctx = useDocumentContext();+ return (+ <>+ <span data-testid="open-tabs">{ctx.openTabs.join('|')}</span>+ <span data-testid="visible-tabs">{ctx.visibleTabIds.join('|')}</span>+ <span data-testid="active-tab">{ctx.activeTabId ?? ''}</span>+ <button+ type="button"+ onClick={() =>+ ctx.openTarget({+ kind: 'asset',+ target: 'LICENSE',+ assetPath: 'LICENSE',+ mediaKind: null,+ })+ }+ >+ Open license+ </button>+ </>+ );+}+function ProviderHarness({ children }: { children: ReactNode }) {return <DocumentProvider>{children}</DocumentProvider>;}@@ -546,6 +611,8 @@ describe('DocumentContext reorderTabs — order + drag-mutable pin', () => {});const COLD_START_DOC = docTabId('event_watcher');+const SAME_STEM_MD_TAB = docTabId('foo.md');+const SAME_STEM_MDX_TAB = docTabId('foo.mdx');function seedColdStartSession() {// The state a cold single-file window reaches mid-startup: the seeded doc tab@@ -562,6 +629,19 @@ function seedColdStartSession() {);}+function seedSameStemActiveMdxSession() {+ window.localStorage.setItem(+ localTabSessionStorageKey(window.location.origin),+ JSON.stringify({+ openTabs: [SAME_STEM_MD_TAB, SAME_STEM_MDX_TAB],+ pinnedTabIds: [],+ activeDocName: 'foo.mdx',+ activeTabId: SAME_STEM_MDX_TAB,+ updatedAt: new Date('2026-06-07T00:00:00.000Z').toISOString(),+ }),+ );+}+function ColdStartSyncHarness() {const ctx = useDocumentContext();return (@@ -585,9 +665,33 @@ function ColdStartSyncHarness() {);}+function SameStemSyncHarness() {+ const ctx = useDocumentContext();+ return (+ <>+ <span data-testid="open-tabs">{ctx.openTabs.join('|')}</span>+ <span data-testid="active-tab">{ctx.activeTabId ?? ''}</span>+ <button+ type="button"+ onClick={() =>+ ctx.syncOpenTabsWithKnownTargets({+ pages: new Set(['foo']),+ folderPaths: new Set(),+ assetPaths: new Set(),+ })+ }+ >+ Sync canonical page+ </button>+ </>+ );+}+describe('DocumentContext syncOpenTabsWithKnownTargets — cold-start hash preservation', () => {afterEach(() => {cleanup();+ mockCollabUrl = null;+ globalThis.fetch = originalFetch;window.localStorage.clear();window.location.hash = '';});@@ -612,6 +716,89 @@ describe('DocumentContext syncOpenTabsWithKnownTargets — cold-start hash preseexpect(screen.getByTestId('open-tabs').textContent).toBe(COLD_START_DOC);expect(window.location.hash).toBe('#/event_watcher');});++ test('same-stem md and mdx tabs survive canonical extensionless page sync', async () => {+ mockCollabUrl = 'ws://localhost:1/collab';+ globalThis.fetch = mock(() => Promise.reject(new Error('unexpected fetch'))) as never;+ seedSameStemActiveMdxSession();+ window.location.hash = '#/foo.mdx';+ render(<SameStemSyncHarness />, { wrapper: ProviderHarness });++ expect(screen.getByTestId('open-tabs').textContent).toBe(+ `${SAME_STEM_MD_TAB}|${SAME_STEM_MDX_TAB}`,+ );+ await waitFor(() => {+ expect(screen.getByTestId('active-tab').textContent).toBe(SAME_STEM_MDX_TAB);+ });++ const user = userEvent.setup();+ await user.click(screen.getByRole('button', { name: 'Sync canonical page' }));++ expect(screen.getByTestId('open-tabs').textContent).toBe(+ `${SAME_STEM_MD_TAB}|${SAME_STEM_MDX_TAB}`,+ );+ expect(screen.getByTestId('active-tab').textContent).toBe(SAME_STEM_MDX_TAB);+ expect(window.location.hash).toBe('#/foo.mdx');+ });+});++describe('DocumentContext tab restore', () => {+ afterEach(() => {+ cleanup();+ delete window.okDesktop;+ mockCollabUrl = null;+ globalThis.fetch = originalFetch;+ window.localStorage.clear();+ window.location.hash = '';+ });++ test('restores an extension-qualified mdx tab over an ambiguous extensionless hash', async () => {+ mockCollabUrl = 'ws://localhost:1/collab';+ globalThis.fetch = mock(() => Promise.reject(new Error('unexpected fetch'))) as never;+ seedSameStemActiveMdxSession();+ window.location.hash = '#/foo';++ render(<CloseActiveHarness />, { wrapper: ProviderHarness });++ await waitFor(() => {+ expect(screen.getByTestId('active-tab').textContent).toBe(SAME_STEM_MDX_TAB);+ });+ expect(window.location.hash).toBe('#/foo.mdx');+ });++ test('keeps saved tab order when an active asset hash opens before session restore resolves', async () => {+ mockCollabUrl = 'ws://localhost:1/collab';+ globalThis.fetch = mock(() => Promise.reject(new Error('unexpected fetch'))) as never;+ const stub = makeDeferredSessionBridgeStub({+ openTabs: [OTHER_TAB_ID, LICENSE_TAB_ID],+ pinnedTabIds: [],+ activeDocName: null,+ activeTabId: LICENSE_TAB_ID,+ updatedAt: new Date('2026-06-07T00:00:00.000Z').toISOString(),+ });+ window.okDesktop = stub.bridge;+ window.location.hash = hashFromAssetPath('LICENSE');++ render(<OpenLicenseDuringRestoreHarness />, { wrapper: ProviderHarness });++ const user = userEvent.setup();+ await user.click(screen.getByRole('button', { name: 'Open license' }));++ expect(screen.getByTestId('visible-tabs').textContent).toBe(LICENSE_TAB_ID);++ act(() => {+ stub.resolveSession();+ });++ await waitFor(() => {+ expect(screen.getByTestId('open-tabs').textContent).toBe(`${OTHER_TAB_ID}|${LICENSE_TAB_ID}`);+ expect(screen.getByTestId('visible-tabs').textContent).toBe(+ `${OTHER_TAB_ID}|${LICENSE_TAB_ID}`,+ );+ expect(screen.getByTestId('active-tab').textContent).toBe(LICENSE_TAB_ID);+ });+ expect(window.location.hash).toBe(hashFromAssetPath('LICENSE'));+ });});const RENAME_FOO = docTabId('foo.md');diff --git a/packages/app/src/editor/DocumentContext.tsx b/packages/app/src/editor/DocumentContext.tsxindex 220ca3821..2cb27d53c 100644--- a/packages/app/src/editor/DocumentContext.tsx+++ b/packages/app/src/editor/DocumentContext.tsx@@ -193,6 +193,7 @@ interface DocumentContextValue {pages: ReadonlySet<string>;folderPaths: ReadonlySet<string>;assetPaths: ReadonlySet<string>;+ filePaths?: ReadonlySet<string>;}) => void;/** Rename visible tabs after a file/folder/asset rename without changing their order. */remapTabsForRename: (@@ -400,6 +401,7 @@ function warnPrincipalFetchOnce(err: unknown): void {}const DocumentContext = createContext<DocumentContextValue | null>(null);+const MARKDOWN_EXTENSION_QUALIFIED_DOC_PATTERN = /\.(md|mdx)$/i;// Module-level singleton — survives React re-renders and StrictMode double-mount.// Same pattern the old singleton HocuspocusProvider used. Instantiated lazily@@ -514,6 +516,18 @@ function tabIdFromHash(hash: string): string | null {return docTabId(docName);}+function isBareHashForExtensionQualifiedActiveDoc(+ hashDocName: string | null,+ hash: string,+ activeDocName: string | null,+): boolean {+ if (!hashDocName || !activeDocName) return false;+ if (hash !== hashFromDocName(hashDocName)) return false;+ if (MARKDOWN_EXTENSION_QUALIFIED_DOC_PATTERN.test(hashDocName)) return false;+ if (!MARKDOWN_EXTENSION_QUALIFIED_DOC_PATTERN.test(activeDocName)) return false;+ return activeDocName.replace(MARKDOWN_EXTENSION_QUALIFIED_DOC_PATTERN, '') === hashDocName;+}+function assetTargetForPath(assetPath: string,): Extract<ResolvedNavigationTarget, { kind: 'asset' }> {@@ -781,8 +795,12 @@ export function DocumentProvider({ children }: { children: ReactNode }) {setPinnedTabIds((current) =>sameTabIds(current, normalizedPinnedTabIds) ? current : normalizedPinnedTabIds,);+ // A hash target can open before async session restore resolves. When a+ // saved session exists, keep the restored tab order authoritative so the+ // hash-opened tab does not jump to the front of the strip on reload.+ const visibleOrderSeed = state.openTabs.length > 0 ? nextTabs : visibleTabIdsRef.current;const nextVisibleTabIds = reconcileVisibleTabOrder(- visibleTabIdsRef.current,+ visibleOrderSeed,nextTabs,newTabIdsRef.current,);@@ -797,9 +815,15 @@ export function DocumentProvider({ children }: { children: ReactNode }) {state.openTabs[0] ??null;const restoredActiveHash = restoredActive ? hashFromTabId(restoredActive) : null;+ const restoredActiveDocName = restoredActive ? docNameForTabId(restoredActive) : null;const shouldRestoreActive =(currentHashDoc === null && window.location.hash.length === 0) ||- (restoredActiveHash !== null && restoredActiveHash === window.location.hash);+ (restoredActiveHash !== null && restoredActiveHash === window.location.hash) ||+ isBareHashForExtensionQualifiedActiveDoc(+ currentHashDoc,+ window.location.hash,+ restoredActiveDocName,+ );if (shouldRestoreActive && restoredActive) {activeTabIdRef.current = restoredActive;setActiveTabId(restoredActive);@@ -1648,7 +1672,7 @@ export function DocumentProvider({ children }: { children: ReactNode }) {commitActiveTabId(null);window.location.hash = '';},- syncOpenTabsWithKnownTargets: ({ pages, folderPaths, assetPaths }) => {+ syncOpenTabsWithKnownTargets: ({ pages, folderPaths, assetPaths, filePaths }) => {const keepMissingDocName = activeTarget?.kind === 'missing' ? activeTarget.target : null;// Never evict the doc the hash currently points at: on cold start the page// list arrives empty-then-populated, and a sync firing in that window would@@ -1662,6 +1686,7 @@ export function DocumentProvider({ children }: { children: ReactNode }) {pages,folderPaths,assetPaths,+ filePaths,keepMissingDocName,keepHashDocName,});diff --git a/packages/app/src/editor/editor-tabs.test.ts b/packages/app/src/editor/editor-tabs.test.tsindex 7ec611fbd..0a8e33a5c 100644Binary files a/packages/app/src/editor/editor-tabs.test.ts and b/packages/app/src/editor/editor-tabs.test.ts differdiff --git a/packages/app/src/editor/editor-tabs.ts b/packages/app/src/editor/editor-tabs.tsindex f9c43a671..5a39ae751 100644--- a/packages/app/src/editor/editor-tabs.ts+++ b/packages/app/src/editor/editor-tabs.ts@@ -29,6 +29,7 @@ interface KnownTabTargets {pages: ReadonlySet<string>;folderPaths: ReadonlySet<string>;assetPaths: ReadonlySet<string>;+ filePaths?: ReadonlySet<string>;keepMissingDocName?: string | null;/*** Doc the location hash currently points at — kept even when absent from@@ -142,11 +143,15 @@ export function tabParts(}const slash = docName.lastIndexOf('/');const baseName = slash < 0 ? docName : docName.slice(slash + 1);- const label = `${baseName}${docExt}`;- if (slash < 0) return { baseName, extension: docExt, label, prefix: '' };+ const extension =+ MARKDOWN_TAB_EXTENSION_PATTERN.test(docExt) && MARKDOWN_TAB_EXTENSION_PATTERN.test(baseName)+ ? ''+ : docExt;+ const label = `${baseName}${extension}`;+ if (slash < 0) return { baseName, extension, label, prefix: '' };return {baseName,- extension: docExt,+ extension,label,prefix: `${docName.slice(0, slash)}/`,};@@ -429,6 +434,7 @@ export function filterOpenTabsForKnownTargets(pages,folderPaths,assetPaths,+ filePaths,keepMissingDocName = null,keepHashDocName = null,}: KnownTabTargets,@@ -436,13 +442,17 @@ export function filterOpenTabsForKnownTargets(return normalizeOpenTabs(tabs, Number.MAX_SAFE_INTEGER).filter((tabId) => {const tab = parseEditorTabId(tabId);if (tab.kind === 'folder') return folderPaths.has(tab.folderPath);- if (tab.kind === 'asset') return assetPaths.has(tab.assetPath);+ if (tab.kind === 'asset') {+ return assetPaths.has(tab.assetPath) || filePaths?.has(tab.assetPath) === true;+ }// Skill bundle files are addressed outside the content tree (scope/name/// path), so they never appear in `pages`/`assetPaths` — keep their tabs so// a page-list sync doesn't prune the open viewer.if (tab.kind === 'skill-file') return true;+ const markdownStem = stripMarkdownTabExtension(tab.docName);return (pages.has(tab.docName) ||+ (markdownStem !== null && pages.has(markdownStem)) ||// Managed-artifact docs (skills/templates) are tree-excluded by design, so// they never appear in `pages` — keep their tabs regardless, otherwise the// page-list sync would prune the active skill/template tab the moment adiff --git a/packages/app/src/lib/doc-paths.test.ts b/packages/app/src/lib/doc-paths.test.tsindex c20a59385..6e2eac4b1 100644--- a/packages/app/src/lib/doc-paths.test.ts+++ b/packages/app/src/lib/doc-paths.test.ts@@ -10,7 +10,12 @@ describe('normalizeDocNameInput', () => {describe('docNameToMarkdownPath', () => {test('appends .md to normalized doc names', () => {- expect(docNameToMarkdownPath('./guides/install.mdx')).toBe('guides/install.md');+ expect(docNameToMarkdownPath('guides/install')).toBe('guides/install.md');+ });++ test('preserves extension-qualified markdown paths', () => {+ expect(docNameToMarkdownPath('./guides/install.md')).toBe('guides/install.md');+ expect(docNameToMarkdownPath('./guides/install.mdx')).toBe('guides/install.mdx');});test('falls back to untitled.md for empty input', () => {diff --git a/packages/app/src/lib/doc-paths.ts b/packages/app/src/lib/doc-paths.tsindex cd962adbd..b366240bc 100644--- a/packages/app/src/lib/doc-paths.ts+++ b/packages/app/src/lib/doc-paths.ts@@ -1,14 +1,20 @@-export function normalizeDocNameInput(value: string): string {+const MARKDOWN_EXTENSION = /\.(md|mdx)$/i;++function normalizeDocPathInput(value: string): string {return value.trim().replace(/^\.\/+/, '')- .replace(/^\/+/, '')- .replace(/\.mdx?$/i, '');+ .replace(/^\/+/, '');+}++export function normalizeDocNameInput(value: string): string {+ return normalizeDocPathInput(value).replace(MARKDOWN_EXTENSION, '');}export function docNameToMarkdownPath(docName: string): string {- const normalized = normalizeDocNameInput(docName);- return normalized ? `${normalized}.md` : 'untitled.md';+ const normalized = normalizeDocPathInput(docName);+ if (!normalized) return 'untitled.md';+ return MARKDOWN_EXTENSION.test(normalized) ? normalized : `${normalized}.md`;}export function docNameToDialogSeed(docName: string): {diff --git a/packages/app/src/lib/file-menu-target-resolvers.test.ts b/packages/app/src/lib/file-menu-target-resolvers.test.tsindex 687426267..123c80944 100644--- a/packages/app/src/lib/file-menu-target-resolvers.test.ts+++ b/packages/app/src/lib/file-menu-target-resolvers.test.ts@@ -24,11 +24,10 @@ const WORKSPACE: Workspace = {};describe('resolveActiveTargetAbsPath', () => {- test('doc scope joins contentDir + .md-suffixed docName', () => {+ test('doc scope joins contentDir + markdown relative path', () => {expect(resolveActiveTargetAbsPath({ kind: 'doc', target: 'specs/foo', docName: 'specs/foo' },- 'specs/foo',WORKSPACE,),).toBe('/Users/test/project/specs/foo.md');@@ -44,95 +43,104 @@ describe('resolveActiveTargetAbsPath', () => {docName: 'specs/index',noteKind: 'canonical-index',},- 'specs/index',WORKSPACE,),).toBe('/Users/test/project/specs/index.md');});+ test('extension-qualified doc scope uses active target docName', () => {+ expect(+ resolveActiveTargetAbsPath(+ { kind: 'doc', target: 'specs/foo.mdx', docName: 'specs/foo.mdx' },+ WORKSPACE,+ ),+ ).toBe('/Users/test/project/specs/foo.mdx');+ });+test('folder scope joins contentDir + folderPath (no trailing slash)', () => {expect(resolveActiveTargetAbsPath({ kind: 'folder', target: 'reports', folderPath: 'reports' },- null,WORKSPACE,),).toBe('/Users/test/project/reports');});test('null scope (project) returns contentDir verbatim', () => {- expect(resolveActiveTargetAbsPath(null, null, WORKSPACE)).toBe('/Users/test/project');+ expect(resolveActiveTargetAbsPath(null, WORKSPACE)).toBe('/Users/test/project');});test('asset scope joins contentDir + assetPath', () => {expect(resolveActiveTargetAbsPath({ kind: 'asset', target: 'media/foo.png', assetPath: 'media/foo.png', mediaKind: null },- null,WORKSPACE,),).toBe('/Users/test/project/media/foo.png');});test('missing scope falls back to contentDir', () => {- expect(resolveActiveTargetAbsPath({ kind: 'missing', target: 'gone' }, null, WORKSPACE)).toBe(+ expect(resolveActiveTargetAbsPath({ kind: 'missing', target: 'gone' }, WORKSPACE)).toBe('/Users/test/project',);});});describe('resolveActiveTargetRelativePath', () => {- test('doc scope returns .md-suffixed relative path', () => {+ test('doc scope returns markdown relative path', () => {expect(- resolveActiveTargetRelativePath(- { kind: 'doc', target: 'specs/foo', docName: 'specs/foo' },- 'specs/foo',- ),+ resolveActiveTargetRelativePath({ kind: 'doc', target: 'specs/foo', docName: 'specs/foo' }),).toBe('specs/foo.md');});test('folder-index scope returns the doc-relative path', () => {expect(- resolveActiveTargetRelativePath(- {- kind: 'folder-index',- target: 'specs',- folderPath: 'specs',- docName: 'specs/index',- noteKind: 'canonical-index',- },- 'specs/index',- ),+ resolveActiveTargetRelativePath({+ kind: 'folder-index',+ target: 'specs',+ folderPath: 'specs',+ docName: 'specs/index',+ noteKind: 'canonical-index',+ }),).toBe('specs/index.md');});+ test('extension-qualified doc scope returns active target relative path', () => {+ expect(+ resolveActiveTargetRelativePath({+ kind: 'doc',+ target: 'specs/foo.mdx',+ docName: 'specs/foo.mdx',+ }),+ ).toBe('specs/foo.mdx');+ });+test('folder scope returns the folder path with no trailing slash', () => {expect(- resolveActiveTargetRelativePath(- { kind: 'folder', target: 'reports', folderPath: 'reports' },- null,- ),+ resolveActiveTargetRelativePath({ kind: 'folder', target: 'reports', folderPath: 'reports' }),).toBe('reports');});test('asset scope returns the asset-relative path', () => {expect(- resolveActiveTargetRelativePath(- { kind: 'asset', target: 'x.png', assetPath: 'x.png', mediaKind: null },- null,- ),+ resolveActiveTargetRelativePath({+ kind: 'asset',+ target: 'x.png',+ assetPath: 'x.png',+ mediaKind: null,+ }),).toBe('x.png');});test('null / missing scopes return empty string (contentDir convention)', () => {- expect(resolveActiveTargetRelativePath(null, null)).toBe('');- expect(resolveActiveTargetRelativePath({ kind: 'missing', target: 'gone' }, null)).toBe('');+ expect(resolveActiveTargetRelativePath(null)).toBe('');+ expect(resolveActiveTargetRelativePath({ kind: 'missing', target: 'gone' })).toBe('');});});describe('buildSendToAiInputForActiveTarget', () => {test('null scope (project) returns project-scoped handoff input', () => {- const input = buildSendToAiInputForActiveTarget(null, null, WORKSPACE);+ const input = buildSendToAiInputForActiveTarget(null, WORKSPACE);expect(input).not.toBeNull();expect(input?.docContext).toBeNull();expect(input?.projectDir).toBe('/Users/test/project');@@ -142,7 +150,6 @@ describe('buildSendToAiInputForActiveTarget', () => {test('folder scope returns folder-scoped handoff input with contentDir projectDir + relative path', () => {const input = buildSendToAiInputForActiveTarget({ kind: 'folder', target: 'reports', folderPath: 'reports' },- null,WORKSPACE,);expect(input).not.toBeNull();@@ -157,7 +164,6 @@ describe('buildSendToAiInputForActiveTarget', () => {test('doc + folder-index scopes return file-scoped handoff input', () => {const docInput = buildSendToAiInputForActiveTarget({ kind: 'doc', target: 'specs/foo', docName: 'specs/foo' },- 'specs/foo',WORKSPACE,);expect(docInput?.docContext?.relativePath).toBe('specs/foo.md');@@ -171,39 +177,38 @@ describe('buildSendToAiInputForActiveTarget', () => {docName: 'specs/index',noteKind: 'canonical-index',},- 'specs/index',WORKSPACE,);expect(folderIndexInput?.docContext?.relativePath).toBe('specs/index.md');});+ test('extension-qualified doc scope keeps the selected file extension', () => {+ const docInput = buildSendToAiInputForActiveTarget(+ { kind: 'doc', target: 'specs/foo.mdx', docName: 'specs/foo.mdx' },+ WORKSPACE,+ );+ expect(docInput?.docContext?.relativePath).toBe('specs/foo.mdx');+ expect(docInput?.docPath).toBe('/Users/test/project/specs/foo.mdx');+ });+test('asset / missing scopes return null (no meaningful dispatch)', () => {expect(buildSendToAiInputForActiveTarget({ kind: 'asset', target: 'x.png', assetPath: 'x.png', mediaKind: null },- null,WORKSPACE,),).toBeNull();expect(- buildSendToAiInputForActiveTarget({ kind: 'missing', target: 'gone' }, null, WORKSPACE),+ buildSendToAiInputForActiveTarget({ kind: 'missing', target: 'gone' }, WORKSPACE),).toBeNull();});test('returns null when workspace is unresolved on doc / folder scopes', () => {expect(- buildSendToAiInputForActiveTarget(- { kind: 'doc', target: 'foo', docName: 'foo' },- 'foo',- null,- ),+ buildSendToAiInputForActiveTarget({ kind: 'doc', target: 'foo', docName: 'foo' }, null),).toBeNull();expect(- buildSendToAiInputForActiveTarget(- { kind: 'folder', target: 'foo', folderPath: 'foo' },- null,- null,- ),+ buildSendToAiInputForActiveTarget({ kind: 'folder', target: 'foo', folderPath: 'foo' }, null),).toBeNull();});});diff --git a/packages/app/src/lib/file-menu-target-resolvers.ts b/packages/app/src/lib/file-menu-target-resolvers.tsindex fe4f95c86..d14a34b38 100644--- a/packages/app/src/lib/file-menu-target-resolvers.ts+++ b/packages/app/src/lib/file-menu-target-resolvers.ts@@ -42,20 +42,19 @@ import { docNameToRelativePath, joinWorkspacePath, type Workspace } from './work*/export function resolveActiveTargetAbsPath(activeTarget: ResolvedNavigationTarget | null,- activeDocName: string | null,workspace: Workspace,): string {- if (activeTarget?.kind === 'doc' && activeDocName) {+ if (activeTarget?.kind === 'doc') {return joinWorkspacePath(workspace.contentDir,- docNameToRelativePath(activeDocName),+ docNameToRelativePath(activeTarget.docName),workspace.pathSeparator,);}- if (activeTarget?.kind === 'folder-index' && activeDocName) {+ if (activeTarget?.kind === 'folder-index') {return joinWorkspacePath(workspace.contentDir,- docNameToRelativePath(activeDocName),+ docNameToRelativePath(activeTarget.docName),workspace.pathSeparator,);}@@ -74,17 +73,15 @@ export function resolveActiveTargetAbsPath(/*** Project-relative path string for Copy Relative Path. Doc / folder-index- * scopes return the `.md`-suffixed relative path; folder scope returns the- * folder path with no trailing slash; asset scope returns the asset path;- * everything else (null / missing) returns `''` matching the contentDir-- * itself convention.+ * scopes return the markdown relative path; folder scope returns the folder+ * path with no trailing slash; asset scope returns the asset path; everything+ * else (null / missing) returns `''` matching the contentDir-itself convention.*/export function resolveActiveTargetRelativePath(activeTarget: ResolvedNavigationTarget | null,- activeDocName: string | null,): string {- if ((activeTarget?.kind === 'doc' || activeTarget?.kind === 'folder-index') && activeDocName) {- return docNameToRelativePath(activeDocName);+ if (activeTarget?.kind === 'doc' || activeTarget?.kind === 'folder-index') {+ return docNameToRelativePath(activeTarget.docName);}if (activeTarget?.kind === 'folder') {return activeTarget.folderPath;@@ -103,7 +100,6 @@ export function resolveActiveTargetRelativePath(*/export function buildSendToAiInputForActiveTarget(activeTarget: ResolvedNavigationTarget | null,- activeDocName: string | null,workspace: Workspace | null,): HandoffDispatchInput | null {if (activeTarget === null) {@@ -117,7 +113,7 @@ export function buildSendToAiInputForActiveTarget(});}if (activeTarget.kind === 'doc' || activeTarget.kind === 'folder-index') {- return buildHandoffInput({ docName: activeDocName, workspace });+ return buildHandoffInput({ docName: activeTarget.docName, workspace });}return null;}diff --git a/packages/app/src/lib/share/run-share-action.test.ts b/packages/app/src/lib/share/run-share-action.test.tsindex fd877dae7..f41de9f56 100644--- a/packages/app/src/lib/share/run-share-action.test.ts+++ b/packages/app/src/lib/share/run-share-action.test.ts@@ -291,6 +291,23 @@ describe('runShareAction — happy path', () => {expect(deps.fetchCalls[0].body).toEqual({ kind: 'doc', docPath: 'docs/sub/page.md' });});+ test('extension-qualified mdx docName maps to matching docPath', async () => {+ const okResponse: ShareConstructUrlResponse = {+ ok: true,+ shareUrl: 'https://openknowledge.ai/d/Aaa',+ sharedUrl: 'https://github.com/o/r/blob/main/docs/page.mdx',+ branch: 'main',+ };+ const deps = makeDeps({ fetchResponse: okResponse });++ await runShareAction(+ { kind: 'doc', docName: 'docs/page.mdx', hasRemote: true, onClickWhenNoRemote: () => {} },+ deps,+ );++ expect(deps.fetchCalls[0].body).toEqual({ kind: 'doc', docPath: 'docs/page.mdx' });+ });+test('folder input POSTs {kind:folder, folderPath} verbatim + folder-specific success toast', async () => {const okResponse: ShareConstructUrlResponse = {ok: true,diff --git a/packages/app/src/lib/share/run-share-action.ts b/packages/app/src/lib/share/run-share-action.tsindex 076821118..14a5b174d 100644--- a/packages/app/src/lib/share/run-share-action.ts+++ b/packages/app/src/lib/share/run-share-action.ts@@ -11,7 +11,7 @@ const SHARE_CONSTRUCT_URL_PATH = '/api/share/construct-url';/*** Discriminated share target the button dispatches. `doc` carries the- * extension-less `activeDocName` (transformed to a `.md` content-relative+ * document identifier (transformed to a `.md` / `.mdx` content-relative* `docPath` here, mirroring the editor's `docNameToMarkdownPath` convention);* `folder` carries the content-relative `folderRelativePath` verbatim (it is* already the wire's `folderPath` — the empty string is the content-root@@ -23,7 +23,7 @@ export type ShareTargetInput =| { kind: 'doc'; docName: string }| { kind: 'folder'; folderRelativePath: string };-/** File-scope share input from an extension-less doc name. */+/** File-scope share input from a document identifier. */export function buildDocShareInput(docName: string): ShareTargetInput {return { kind: 'doc', docName };}@@ -116,9 +116,9 @@ export async function runShareAction(return { kind: 'opened-wizard' };}- // `docPath` is the `.md` content-relative path (extension-less docName →- // `foo.md`); `folderPath` is the content-relative folder path passed- // through unchanged (the empty string is the content-root sentinel).+ // `docPath` is the `.md` / `.mdx` content-relative path; `folderPath` is the+ // content-relative folder path passed through unchanged (the empty string is+ // the content-root sentinel).const body: ShareConstructUrlRequest =input.kind === 'folder'? { kind: 'folder', folderPath: input.folderRelativePath }diff --git a/packages/app/src/lib/workspace-paths.test.ts b/packages/app/src/lib/workspace-paths.test.tsindex 0ead91229..a93f3176d 100644--- a/packages/app/src/lib/workspace-paths.test.ts+++ b/packages/app/src/lib/workspace-paths.test.ts@@ -44,4 +44,9 @@ describe('docNameToRelativePath', () => {test('preserves nested forward slashes', () => {expect(docNameToRelativePath('a/b/c/d')).toBe('a/b/c/d.md');});++ test('preserves extension-qualified markdown paths', () => {+ expect(docNameToRelativePath('specs/foo/SPEC.md')).toBe('specs/foo/SPEC.md');+ expect(docNameToRelativePath('specs/foo/SPEC.mdx')).toBe('specs/foo/SPEC.mdx');+ });});diff --git a/packages/app/src/lib/workspace-paths.ts b/packages/app/src/lib/workspace-paths.tsindex 72a94a530..74301e81a 100644--- a/packages/app/src/lib/workspace-paths.ts+++ b/packages/app/src/lib/workspace-paths.ts@@ -36,15 +36,13 @@ export function joinWorkspacePath(contentDir: string, relative: string, sep: '/'return `${trimmedDir}${sep}${normalizedRelative}`;}+const MARKDOWN_EXTENSION = /\.(md|mdx)$/i;+/**- * Convert an extension-less docName (e.g. `specs/foo/SPEC`) to its `.md`-- * suffixed relative-path form (e.g. `specs/foo/SPEC.md`).- *- * Assumes all docs use the `.md` extension. An `.mdx` document present in- * the content directory would still report its docName without the extension;- * callers that need true-extension resolution would need a new `/api/documents`- * field.+ * Convert a document identifier to its workspace-relative file path. Most+ * docNames are extension-less, but Show All can pass extension-qualified names+ * for same-stem `.md` / `.mdx` siblings.*/export function docNameToRelativePath(docName: string): string {- return `${docName}.md`;+ return MARKDOWN_EXTENSION.test(docName) ? docName : `${docName}.md`;}diff --git a/packages/app/tests/dom/jsdom-preload.ts b/packages/app/tests/dom/jsdom-preload.tsindex 5a8646805..7ed75a9ae 100644--- a/packages/app/tests/dom/jsdom-preload.ts+++ b/packages/app/tests/dom/jsdom-preload.ts@@ -29,6 +29,8 @@ Object.assign(globalThis, {navigator: win.navigator,location: win.location,history: win.history,+ localStorage: win.localStorage,+ sessionStorage: win.sessionStorage,HTMLElement: win.HTMLElement,HTMLDivElement: win.HTMLDivElement,HTMLSpanElement: win.HTMLSpanElement,diff --git a/packages/app/tests/stress/showall-lazy-tree.e2e.ts b/packages/app/tests/stress/showall-lazy-tree.e2e.tsindex cb72af90b..244b30155 100644--- a/packages/app/tests/stress/showall-lazy-tree.e2e.ts+++ b/packages/app/tests/stress/showall-lazy-tree.e2e.ts@@ -18,7 +18,7 @@* top level.*/-import { mkdirSync, writeFileSync } from 'node:fs';+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';import { join } from 'node:path';import type { Page } from '@playwright/test';import { expect, test } from './_helpers';@@ -39,15 +39,15 @@ function uniqueStamp(): string {}function fileRow(page: Page, filename: string) {- return page- .locator('[data-slot="sidebar-container"]')- .getByRole('treeitem', { name: filename, exact: true });+ return page.getByRole('treeitem', {+ name: new RegExp(`^${escapeRegExp(filename)}(?:\\s|$)`),+ });}function folderRow(page: Page, folderName: string) {- return page- .locator('[data-slot="sidebar-container"]')- .getByRole('treeitem', { name: new RegExp(`^${escapeRegExp(folderName)}/?$`) });+ return page.getByRole('treeitem', {+ name: new RegExp(`^${escapeRegExp(folderName)}/?(?:\\s|$)`),+ });}/**@@ -153,6 +153,73 @@ test('Show All seeds the root lazily and loads folder children on expand', async}});+test('folder containing same-name .md and .mdx shows and opens both files', async ({+ page,+ workerServer,+}) => {+ const stamp = uniqueStamp();+ const folder = `showall-dupe-${stamp}`;+ const stem = `foo-${stamp}`;+ const mdSentinel = `edited-md-${stamp}`;+ const mdxSentinel = `edited-mdx-${stamp}`;+ const mdPath = join(workerServer.contentDir, folder, `${stem}.md`);+ const mdxPath = join(workerServer.contentDir, folder, `${stem}.mdx`);++ mkdirSync(join(workerServer.contentDir, folder), { recursive: true });+ writeFileSync(mdPath, '# Markdown shadow\n', 'utf-8');+ writeFileSync(mdxPath, '# MDX winner\n', 'utf-8');++ await page.goto('/');+ await page.waitForLoadState('domcontentloaded');++ await expect(folderRow(page, folder)).toBeVisible({ timeout: 15_000 });+ await expandFolder(page, folder);++ const mdRow = fileRow(page, `${stem}.md`);+ const mdxRow = fileRow(page, `${stem}.mdx`);+ await expect(mdRow).toHaveCount(1);+ await expect(mdRow).toBeVisible();+ await expect(mdxRow).toHaveCount(1);+ await expect(mdxRow).toBeVisible();++ await mdRow.click();+ await expect+ .poll(() => page.evaluate(() => window.__activeProvider?.configuration.name ?? null))+ .toBe(`${folder}/${stem}.md`);+ await expect(page.locator('.ProseMirror', { hasText: 'Markdown shadow' })).toBeVisible({+ timeout: 30_000,+ });+ await expect+ .poll(() => decodeURIComponent(new URL(page.url()).hash))+ .toBe(`#/${folder}/${stem}.md`);+ const editor = page.locator('.ProseMirror').first();+ await editor.click();+ await page.keyboard.insertText(`\n${mdSentinel}`);+ await expect(editor).toContainText(mdSentinel);+ await expect.poll(() => readFileSync(mdPath, 'utf-8'), { timeout: 15_000 }).toContain(mdSentinel);+ expect(readFileSync(mdxPath, 'utf-8')).not.toContain(mdSentinel);+ await expect(page.locator('[data-slot="sidebar-container"]')).toBeVisible();++ await mdxRow.click();+ await expect+ .poll(() => page.evaluate(() => window.__activeProvider?.configuration.name ?? null))+ .toBe(`${folder}/${stem}.mdx`);+ await expect(page.locator('.ProseMirror', { hasText: 'MDX winner' })).toBeVisible({+ timeout: 30_000,+ });+ await expect+ .poll(() => decodeURIComponent(new URL(page.url()).hash))+ .toBe(`#/${folder}/${stem}.mdx`);+ await editor.click();+ await page.keyboard.insertText(`\n${mdxSentinel}`);+ await expect(editor).toContainText(mdxSentinel);+ await expect+ .poll(() => readFileSync(mdxPath, 'utf-8'), { timeout: 15_000 })+ .toContain(mdxSentinel);+ expect(readFileSync(mdPath, 'utf-8')).not.toContain(mdxSentinel);+ await expect(page.locator('[data-slot="sidebar-container"]')).toBeVisible();+});+test('truncation banner appears for an overflowing level while every root entry stays visible', async ({page,api,diff --git a/packages/app/tests/stress/ux-interactions.e2e.ts b/packages/app/tests/stress/ux-interactions.e2e.tsindex ad6fb091b..8aac8865a 100644--- a/packages/app/tests/stress/ux-interactions.e2e.ts+++ b/packages/app/tests/stress/ux-interactions.e2e.ts@@ -415,8 +415,10 @@ test('sidebar folder: row click navigates to folder overview; treeitem toggles eawait expect(folderRow).toHaveAttribute('aria-expanded', 'false');await expect(nestedFile).toHaveCount(0);- // Re-expand so we can navigate to the nested doc.- await folderRow.press('ArrowRight');+ // Row click opens the folder too: it navigates to the folder's resolved+ // target and expands the row so the child is visible.+ await folderRow.click();+ await expect(page).toHaveURL(/#\/sidebar-folder\/$/);await expect(folderRow).toHaveAttribute('aria-expanded', 'true');await expect(nestedFile).toBeVisible();@@ -432,10 +434,13 @@ test('sidebar folder: row click navigates to folder overview; treeitem toggles eawait expect(folderRow).toHaveAttribute('aria-expanded', 'true');await expect(nestedFile).toBeVisible();- // Row click navigates to the folder's resolved target. Folder routes keep a- // trailing slash so a folder and same-basename document remain distinct.+ // Row click navigates back to the folder target. Folder routes keep a+ // trailing slash so a folder and same-basename document remain distinct, and+ // the navigation click must not also collapse the already-open folder.await folderRow.click();await expect(page).toHaveURL(/#\/sidebar-folder\/$/);+ await expect(folderRow).toHaveAttribute('aria-expanded', 'true');+ await expect(nestedFile).toBeVisible();});test('markdown link edit dialog preserves page mode while clearing and updates the href target', async ({diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.tsindex 8dc135b65..8a1f10183 100644--- a/packages/server/src/api-extension.ts+++ b/packages/server/src/api-extension.ts@@ -426,6 +426,7 @@ import { isConfigDoc, isSystemDoc } from './cc1-broadcast.ts';import type { ResolveStrategy } from './conflict-storage.ts';import type { ContentFilter } from './content-filter.ts';import {+ docNameToRelativePath,forgetDocExtension,getDocExtension,isSupportedAssetFile,@@ -1351,8 +1352,6 @@ export interface StreamShowAllOpts {contentFilter: ContentFilter;/** Optional dir filter (contentDir-relative subtree to walk; null = whole tree). */dirFilter: string | null;- /** Pulls the registered on-disk extension for a markdown docName (or `.md` default). */- getDocExtension: (docName: string) => string;/** Hard ceiling on emitted entries; the walk stops once reached. */maxEntries: number;/**@@ -1415,7 +1414,7 @@ export interface WalkShowAllOpts extends StreamShowAllOpts {export async function* streamShowAllEntries(opts: StreamShowAllOpts,): AsyncGenerator<DocumentListEntry, { truncated: boolean }, void> {- const { contentDir, contentFilter, dirFilter, getDocExtension, maxEntries, signal } = opts;+ const { contentDir, contentFilter, dirFilter, maxEntries, signal } = opts;const maxDepth = opts.maxDepth ?? Number.POSITIVE_INFINITY;showAllWalkInvocations += 1;// Running count of yielded entries — the streaming analogue of the buffered@@ -1448,6 +1447,71 @@ export async function* streamShowAllEntries(const isInsideContentDir = (resolved: string): boolean =>isWithinDir(resolved, contentDirCanonical);+ const docVariantCounts = async (+ entries: readonly import('node:fs').Dirent[],+ absDir: string,+ relDir: string,+ ): Promise<ReadonlyMap<string, number>> => {+ const candidateCounts = new Map<string, number>();+ for (const entry of entries) {+ if (!entry.isFile() && !entry.isSymbolicLink()) continue;+ if (!isSupportedDocFile(entry.name)) continue;+ const relPath = relDir ? `${relDir}/${entry.name}` : entry.name;+ const docName = stripDocExtension(relPath);+ candidateCounts.set(docName, (candidateCounts.get(docName) ?? 0) + 1);+ }+ const collidingDocNames = new Set(+ [...candidateCounts].filter(([, count]) => count > 1).map(([docName]) => docName),+ );+ if (collidingDocNames.size === 0) return new Map();++ const counts = new Map<string, number>();+ for (const entry of entries) {+ if (!entry.isFile() && !entry.isSymbolicLink()) continue;+ if (!isSupportedDocFile(entry.name)) continue;+ const relPath = relDir ? `${relDir}/${entry.name}` : entry.name;+ const docName = stripDocExtension(relPath);+ if (!collidingDocNames.has(docName)) continue;+ if (contentFilter.isExcluded(relPath, { bypassFilters: true })) continue;+ if (!passesDirFilter(relPath)) continue;++ if (entry.isSymbolicLink()) {+ const linkAbs = join(absDir, entry.name);+ let canonical: string;+ try {+ canonical = await realpath(linkAbs);+ } catch {+ continue;+ }+ if (!isInsideContentDir(canonical)) continue;+ let canonStat: import('node:fs').Stats;+ try {+ canonStat = await stat(canonical);+ } catch {+ continue;+ }+ if (!canonStat.isFile()) continue;+ } else {+ try {+ await stat(join(absDir, entry.name));+ } catch {+ continue;+ }+ }++ counts.set(docName, (counts.get(docName) ?? 0) + 1);+ }+ return counts;+ };++ const showAllDocName = (+ relPath: string,+ countsByExtensionlessDocName: ReadonlyMap<string, number>,+ ): string => {+ const extensionless = stripDocExtension(relPath);+ return (countsByExtensionlessDocName.get(extensionless) ?? 0) > 1 ? relPath : extensionless;+ };+// Cheap bounded probe for `hasChildren` on a leaf-depth folder (depth-1// contract): readdir the folder and stop at the first admitted child, so the// client can render an expand affordance without the server walking the@@ -1532,6 +1596,7 @@ export async function* streamShowAllEntries(console.warn(`[document-list][showAll] readdir failed for ${absDir}:`, err);continue;}+ const variantCountsByDocName = await docVariantCounts(entries, absDir, relDir);for (const entry of entries) {// Abort-on-disconnect: stop walking once the request's last waiter has@@ -1680,11 +1745,11 @@ export async function* streamShowAllEntries(if (!passesDirFilter(relPath)) continue;emitted += 1;if (isSupportedDocFile(entry.name)) {- const docName = relPath.replace(/\.(md|mdx)$/i, '');+ const docName = showAllDocName(relPath, variantCountsByDocName);yield {kind: 'document',docName,- docExt: getDocExtension(docName),+ docExt: extname(entry.name),size: canonStat.size,modified: canonStat.mtime.toISOString(),isSymlink: true,@@ -1728,11 +1793,10 @@ export async function* streamShowAllEntries(}if (isSupportedDocFile(entry.name)) {- // Markdown — classify as 'document'. `getDocExtension` reads the- // registered on-disk extension if the docName has been seen by the- // watcher; for files surfaced only via showAll it falls back to .md.- const docName = relPath.replace(/\.(md|mdx)$/i, '');- const docExt = getDocExtension(docName);+ // Markdown — classify as 'document'. The directory entry is the+ // show-all source of truth for the file extension.+ const docName = showAllDocName(relPath, variantCountsByDocName);+ const docExt = extname(entry.name);emitted += 1;yield {kind: 'document',@@ -1978,10 +2042,9 @@ function resolveContentEntryPath(contentDir: string, kind: ContentEntryKind, pat// When kind is 'file': if the caller passed an explicit supported extension,// use the path verbatim — this is how rename callers signal an extension// change (toPath: "foo.mdx" renames foo.md → foo.mdx). Extension-less paths- // fall through to getDocExtension() + the registered extension map so legacy- // callers keep the source's existing extension.- const relativePath =- kind === 'file' ? (isSupportedDocFile(path) ? path : `${path}${getDocExtension(path)}`) : path;+ // route through `docNameToRelativePath`, which consults the registered+ // extension map so legacy callers keep the source's existing extension.+ const relativePath = kind === 'file' ? docNameToRelativePath(path) : path;const fullPath = resolve(resolvedContentDir, relativePath);if (fullPath !== resolvedContentDir && !fullPath.startsWith(`${resolvedContentDir}${sep}`)) {@@ -2050,11 +2113,31 @@ function classifyDuplicatePathFilesystemProblem(}function docNameExistsWithAnySupportedExtension(contentDir: string, docName: string): boolean {+ if (isSupportedDocFile(docName)) {+ return existsSync(resolve(contentDir, docName));+ }return SUPPORTED_DOC_EXTENSIONS.some((ext) =>existsSync(resolve(contentDir, `${docName}${ext}`)),);}+function hasSameStemDocumentSibling(contentDir: string, relPath: string): boolean {+ if (!isSupportedDocFile(relPath)) return false;+ const extensionless = stripDocExtension(relPath);+ const currentExt = extname(relPath).toLowerCase();+ return SUPPORTED_DOC_EXTENSIONS.some((ext) => {+ if (ext.toLowerCase() === currentExt) return false;+ return existsSync(resolve(contentDir, `${extensionless}${ext}`));+ });+}++function docNameForFileOperationPath(contentDir: string, relPath: string): string {+ const extensionless = stripDocExtension(relPath);+ return isSupportedDocFile(relPath) && hasSameStemDocumentSibling(contentDir, relPath)+ ? relPath+ : extensionless;+}+function resolveDuplicateDocPath(contentDir: string, docName: string, extension: string): string {if (!isValidRelativeContentPath(docName)) {throw new Error('path must be a relative content path');@@ -2112,7 +2195,7 @@ function collectMarkdownCopies(}if (!entry.isFile() || !isSupportedDocFile(childRel)) continue;docs.push({- docName: stripDocExtension(childRel),+ docName: docNameForFileOperationPath(contentDir, childRel),fullPath: childAbs,content: readFileSync(childAbs, 'utf-8'),});@@ -2158,13 +2241,26 @@ function probeAndRegisterSourceFileExtension(contentDir: string, fromPath: strinif (!isValidRelativeContentPath(fromPath)) return;const resolvedContentDir = resolve(contentDir);if (isSupportedDocFile(fromPath)) {- const candidate = resolve(resolvedContentDir, fromPath);+ const extensionless = stripDocExtension(fromPath);+ for (const ext of SUPPORTED_DOC_EXTENSIONS) {+ const candidate = resolve(resolvedContentDir, `${extensionless}${ext}`);+ if (+ candidate !== resolvedContentDir &&+ !candidate.startsWith(`${resolvedContentDir}${sep}`)+ ) {+ continue;+ }+ if (existsSync(candidate)) {+ registerDocExtension(extensionless, ext);+ }+ }+ const explicitCandidate = resolve(resolvedContentDir, fromPath);if (- candidate !== resolvedContentDir &&- candidate.startsWith(`${resolvedContentDir}${sep}`) &&- existsSync(candidate)+ explicitCandidate !== resolvedContentDir &&+ explicitCandidate.startsWith(`${resolvedContentDir}${sep}`) &&+ existsSync(explicitCandidate)) {- registerDocExtension(stripDocExtension(fromPath), extname(fromPath));+ registerDocExtension(extensionless, extname(fromPath));}return;}@@ -2865,7 +2961,8 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {}if (!isSafeDocName(docName)) return null;const resolvedContentDir = resolve(contentDir);- const filePath = resolve(resolvedContentDir, `${docName}${getDocExtension(docName)}`);+ const relPath = docNameToRelativePath(docName);+ const filePath = resolve(resolvedContentDir, relPath);if (!isWithinDir(filePath, resolvedContentDir)) {return null;}@@ -3174,12 +3271,13 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {// the admitted set by another door, or its on-disk title/frontmatter leaks// through the link/title endpoints. String-only (no realpath/symlink syscalls// — this runs per forward-key on a hot path); the extension mirrors- // `resolveContentEntryPath`'s `getDocExtension` default so `.md`/`.mdx` ignore- // patterns match. A managed-artifact docName lives outside contentDir and is- // admitted separately, so a wrong relPath here only ever fails open (admit).+ // `resolveContentEntryPath`'s `docNameToRelativePath` default so `.md`/`.mdx`+ // ignore patterns match. A managed-artifact docName lives outside contentDir+ // and is admitted separately, so a wrong relPath here only ever fails open+ // (admit).function isDocNameContentExcluded(docName: string): boolean {if (!contentFilter) return false;- const relPath = isSupportedDocFile(docName) ? docName : `${docName}${getDocExtension(docName)}`;+ const relPath = docNameToRelativePath(docName);return contentFilter.isExcluded(relPath);}@@ -3572,7 +3670,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {);for (const docName of docNames) {const doc = hocuspocus.documents.get(docName);- const filePath = `${docName}${getDocExtension(docName)}`;+ const filePath = docNameToRelativePath(docName);const conflictedByLifecycle = doc !== undefined && isDocInConflict(doc);const conflictedByStore = renameTrackedFiles.has(filePath);if (conflictedByLifecycle || conflictedByStore) {@@ -3680,8 +3778,8 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {if (!entry.isFile() || !isSupportedDocFile(relPath) || contentFilter?.isExcluded(relPath)) {continue;}- const docName = stripDocExtension(relPath);- registerDocExtension(docName, extname(relPath));+ const docName = docNameForFileOperationPath(contentDir, relPath);+ registerDocExtension(stripDocExtension(relPath), extname(relPath));docNames.push(docName);}}@@ -4040,25 +4138,25 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {: [];span.setAttribute('rename.affected_assets', renamedAssets.length);- // Downstream code (safeContentPath, setReconciledBase,- // backlinkIndex, file index, applyRenameMap) keys on extension-less- // docNames; file rename receives `fromPath`/`toPath` with the- // user-supplied extension, so strip here. Folder rename enumerates- // descendant docs from DISK rather than the in-memory file index:+ // Downstream code keys on extension-less docNames for ordinary+ // files, but same-stem `.md` / `.mdx` siblings stay+ // extension-qualified so the operation targets the selected file.+ // Folder rename enumerates descendant docs from DISK rather than+ // the in-memory file index:// the index lags on-disk truth after a fresh `write`, which// made folder rename report `renamed: []` and skip link rewriting// while still moving the directory. Disk is the authoritative set of// what the move carries.const affectedDocNames =kind === 'file'- ? [stripDocExtension(fromPath)]+ ? [docNameForFileOperationPath(contentDir, fromPath)]: listManagedDocNamesUnderFolderFromDisk(sourcePathRoot);const affectedDocs: Array<{ from: string; to: string }> = affectedDocNames.map((docName) => ({from: docName,to:kind === 'file'- ? stripDocExtension(toPath)+ ? docNameForFileOperationPath(contentDir, toPath): remapDocNameForRename(docName, kind, fromPath, toPath),}),);@@ -4427,7 +4525,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {const explicitDestExt: string | null =kind === 'file' && isSupportedDocFile(toPath) ? extname(toPath) : null;for (const { from, to } of affectedDocs) {- const sourceExt = getDocExtension(from);+ const sourceExt = isSupportedDocFile(from) ? extname(from) : getDocExtension(from);forgetDocExtension(from);registerDocExtension(to, explicitDestExt ?? sourceExt);}@@ -5771,7 +5869,6 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {contentDir,contentFilter,dirFilter: dir,- getDocExtension,maxEntries,maxDepth: showAllMaxDepth,signal: controller.signal,@@ -5849,7 +5946,6 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {contentFilter,dirFilter: dir,documents,- getDocExtension,maxEntries,maxDepth: showAllMaxDepth,signal: controller.signal,@@ -7999,7 +8095,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {if (targetDoc && isDocInConflict(targetDoc)) {respondDocInConflict(res,- new DocInConflictError({ file: `${body.docName}${getDocExtension(body.docName)}` }),+ new DocInConflictError({ file: docNameToRelativePath(body.docName) }),'rollback',);return;@@ -9308,7 +9404,8 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {}const { kind } = body;- const requestedPath = kind === 'file' ? stripDocExtension(body.path) : body.path;+ const requestedPath = body.path;+ const requestedDocName = kind === 'file' ? stripDocExtension(requestedPath) : requestedPath;if (!isValidRelativeContentPath(requestedPath)) {errorResponse(res,@@ -9322,7 +9419,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {if (requestedPath === '.ok' ||requestedPath.startsWith('.ok/') ||- (kind === 'file' && (isSystemDoc(requestedPath) || isConfigDoc(requestedPath))) ||+ (kind === 'file' && (isSystemDoc(requestedDocName) || isConfigDoc(requestedDocName))) ||(kind === 'folder' && isReservedSyntheticFolderPath(requestedPath))) {errorResponse(@@ -9382,10 +9479,10 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {// `write` create the index lags and a conflicted child would// be silently skipped, copying its marker bytes intact. Same root// cause and fix as handleRenamePath's pre-check. Also registers- // each child's on-disk extension, which `getDocExtension` relies on.+ // each child's on-disk extension for extension-less legacy docNames.const duplicateSourceDocNames =kind === 'file'- ? [requestedPath]+ ? [docNameForFileOperationPath(contentDir, requestedPath)]: listManagedDocNamesUnderFolderFromDisk(resolveContentEntryPath(contentDir, 'folder', requestedPath),);@@ -9394,9 +9491,9 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {duplicateEngine ? duplicateEngine.getConflicts().map((c) => c.file) : [],);for (const affected of duplicateSourceDocNames) {- const affectedDocName = stripDocExtension(affected);+ const affectedDocName = affected;const doc = hocuspocus.documents.get(affectedDocName);- const filePath = `${affectedDocName}${getDocExtension(affectedDocName)}`;+ const filePath = docNameToRelativePath(affectedDocName);const conflictedByLifecycle = doc !== undefined && isDocInConflict(doc);const conflictedByStore = duplicateTrackedFiles.has(filePath);if (conflictedByLifecycle || conflictedByStore) {@@ -9410,7 +9507,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {if (kind === 'file') {const sourceExtension = extname(sourcePath);- const next = nextAvailableDuplicateDocName(contentDir, requestedPath);+ const next = nextAvailableDuplicateDocName(contentDir, requestedDocName);duplicatedPath = next.docName;if (isSystemDoc(duplicatedPath) ||@@ -9541,7 +9638,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {duplicatedDocNames = copiedDocs.map((doc) => doc.docName);for (const doc of copiedDocs) {const sourceExtension = extname(doc.fullPath);- registerDocExtension(doc.docName, sourceExtension);+ registerDocExtension(stripDocExtension(doc.docName), sourceExtension);recentlyRemovedDocs?.delete(doc.docName);if (contentFilter) {contentFilter.incrementMdDir(dirname(doc.docName));@@ -9849,6 +9946,13 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {);return;}+ // Register the source's actual on-disk extension before downstream+ // checks so admission, conflict checks, and existsSync probes all see+ // the right value when the file watcher hasn't yet observed the source+ // (boot race).+ if (operationKind === 'file') {+ probeAndRegisterSourceFileExtension(contentDir, fromPath);+ }// Conflict-aware refusal. Renaming a conflicted source doc would// shift the file path while the merge stages still live at the// old path — the disk-watcher → reconcile loop would then see two@@ -9867,11 +9971,10 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {// 404 gate.// Enumerate from disk (not the lagging file index) so the conflict// pre-check sees every on-disk child of the folder — same root cause- // as the spine's `affectedDocNames`. Also registers each child's- // on-disk extension, which `getDocExtension(affected)` relies on.+ // as the spine's `affectedDocNames`.const renameAffectedDocNames =operationKind === 'file'- ? [stripDocExtension(fromPath)]+ ? [docNameForFileOperationPath(contentDir, fromPath)]: listManagedDocNamesUnderFolderFromDisk(resolveContentEntryPath(contentDir, 'folder', fromPath),);@@ -9880,10 +9983,9 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {renameEngine ? renameEngine.getConflicts().map((c) => c.file) : [],);for (const affected of renameAffectedDocNames) {- const affectedDocName = stripDocExtension(affected);+ const affectedDocName = affected;const doc = hocuspocus.documents.get(affectedDocName);- const filePath =- operationKind === 'file' ? fromPath : `${affectedDocName}${getDocExtension(affected)}`;+ const filePath = docNameToRelativePath(affectedDocName);const conflictedByLifecycle = doc !== undefined && isDocInConflict(doc);const conflictedByStore = renameTrackedFiles.has(filePath);if (conflictedByLifecycle || conflictedByStore) {@@ -9891,21 +9993,18 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {return;}}- // Register the source's actual on-disk extension before downstream- // checks so admission and existsSync probes both see the right value- // when the file watcher hasn't yet observed the source (boot race).- if (operationKind === 'file') {- probeAndRegisterSourceFileExtension(contentDir, fromPath);- }if (contentFilter) {// Mirror `resolveContentEntryPath`'s explicit-extension detection so// a destination like `bar.mdx` is checked verbatim instead of as// `bar.mdx.md` (which would miss `*.mdx` exclusion patterns).+ const sourceExt = isSupportedDocFile(fromPath)+ ? extname(fromPath)+ : getDocExtension(fromPath);const excluded =operationKind === 'file'? contentFilter.isExcluded(- isSupportedDocFile(toPath) ? toPath : `${toPath}${getDocExtension(fromPath)}`,+ isSupportedDocFile(toPath) ? toPath : `${toPath}${sourceExt}`,): contentFilter.isDirExcluded(toPath);if (excluded) {@@ -10128,12 +10227,12 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {// Y.Docs (silent data loss). Same root cause and fix as// handleRenamePath's affected-docs scan. The walk runs before the disk// delete, so disk is authoritative here; it also registers each- // child's on-disk extension, which `getDocExtension` relies on below.+ // child's on-disk extension for extension-less legacy docNames.const deletedDocNames =operationKind === 'asset'? []: operationKind === 'file'- ? [stripDocExtension(operationPath)]+ ? [docNameForFileOperationPath(contentDir, operationPath)]: listManagedDocNamesUnderFolderFromDisk(resolveContentEntryPath(contentDir, 'folder', operationPath),);@@ -10152,24 +10251,9 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {deleteEngine ? deleteEngine.getConflicts().map((c) => c.file) : [],);for (const affected of deletedDocNames) {- const affectedDocName = stripDocExtension(affected);+ const affectedDocName = affected;const doc = hocuspocus.documents.get(affectedDocName);- // For `kind === 'file'` `affected` already carries the extension- // (= the request body's `path`); for `kind === 'folder'` the disk- // walk returns extension-LESS docNames, so reconstruct the extension- // for the ConflictStore has-check (its entries are extension-ful- // `git ls-files`-style paths). The walk's `registerDocExtension`- // side effect is what makes `getDocExtension` resolve a `.mdx` child- // correctly here rather than falling back to the `.md` default — a- // mismatch would silently let a conflicted `.mdx` child through.- // Without this the folder branch silently falls through whenever the- // conflicted doc's Y.Doc has been evicted from memory.- const filePath =- operationKind === 'file'- ? isSupportedDocFile(operationPath)- ? operationPath- : `${affectedDocName}${getDocExtension(affectedDocName)}`- : `${affectedDocName}${getDocExtension(affectedDocName)}`;+ const filePath = docNameToRelativePath(affectedDocName);const conflictedByLifecycle = doc !== undefined && isDocInConflict(doc);const conflictedByStore = deleteTrackedFiles.has(filePath);if (conflictedByLifecycle || conflictedByStore) {@@ -10219,7 +10303,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {for (const docName of deletedDocNames) {mutateFileIndex?.({kind: 'delete',- path: resolve(contentDir, `${docName}${getDocExtension(docName)}`),+ path: resolve(contentDir, docNameToRelativePath(docName)),docName,});}@@ -10385,7 +10469,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {for (const docName of deletedDocNames) {mutateFileIndex?.({kind: 'delete',- path: resolve(contentDir, `${docName}${getDocExtension(docName)}`),+ path: resolve(contentDir, docNameToRelativePath(docName)),docName,});}diff --git a/packages/server/src/api-file-ops.test.ts b/packages/server/src/api-file-ops.test.tsindex 30ddb1c7e..c679d0c29 100644--- a/packages/server/src/api-file-ops.test.ts+++ b/packages/server/src/api-file-ops.test.ts@@ -118,6 +118,7 @@ type CallApiOptions = {sessionManager?: Parameters<typeof createApiExtension>[0]['sessionManager'];getFileIndex?: () => ReadonlyMap<string, FileIndexEntry>;getFolderIndex?: () => ReadonlyMap<string, FolderIndexEntry>;+ mutateFileIndex?: Parameters<typeof createApiExtension>[0]['mutateFileIndex'];onReferencedAssetsCacheInvalidator?: Parameters<typeof createApiExtension>[0]['onReferencedAssetsCacheInvalidator'];@@ -148,6 +149,7 @@ async function createTestApiExtension(contentDir: string, options?: CallApiOptiocontentDir,getFileIndex: options?.getFileIndex ?? (() => buildFileIndex(contentDir)),getFolderIndex: options?.getFolderIndex ?? (() => buildFolderIndex(contentDir)),+ mutateFileIndex: options?.mutateFileIndex,onReferencedAssetsCacheInvalidator: options?.onReferencedAssetsCacheInvalidator,backlinkIndex: resolvedBacklinkIndex,signalChannel: options?.signalChannel,@@ -258,6 +260,124 @@ describe('file operation API routes', () => {]);});+ test('renames the selected .md sibling when .md and .mdx share a stem', async () => {+ const dir = setupTmpDir();+ writeFileSync(join(dir, 'foo.md'), '# Markdown sibling\n', 'utf-8');+ writeFileSync(join(dir, 'foo.mdx'), '# MDX sibling\n', 'utf-8');++ const result = await callApi(+ dir,+ '/api/rename-path',+ 'POST',+ {+ kind: 'file',+ fromPath: 'foo.md',+ toPath: 'renamed.md',+ },+ { backlinkIndex: buildBacklinkIndex(dir) },+ );++ expect(result.status).toBe(200);+ expect(existsSync(join(dir, 'foo.md'))).toBe(false);+ expect(readFileSync(join(dir, 'renamed.md'), 'utf-8')).toBe('# Markdown sibling\n');+ expect(readFileSync(join(dir, 'foo.mdx'), 'utf-8')).toBe('# MDX sibling\n');+ const body = JSON.parse(result.body) as {+ renamed: Array<{ fromDocName: string; toDocName: string }>;+ };+ expect(body.renamed).toEqual([{ fromDocName: 'foo.md', toDocName: 'renamed' }]);+ });++ test('renames a folder containing same-stem .md and .mdx siblings', async () => {+ const dir = setupTmpDir();+ mkdirSync(join(dir, 'docs'), { recursive: true });+ writeFileSync(join(dir, 'docs/foo.md'), '# Markdown sibling\n', 'utf-8');+ writeFileSync(join(dir, 'docs/foo.mdx'), '# MDX sibling\n', 'utf-8');++ const result = await callApi(+ dir,+ '/api/rename-path',+ 'POST',+ {+ kind: 'folder',+ fromPath: 'docs',+ toPath: 'archive',+ },+ { backlinkIndex: buildBacklinkIndex(dir) },+ );++ expect(result.status).toBe(200);+ expect(existsSync(join(dir, 'docs'))).toBe(false);+ expect(readFileSync(join(dir, 'archive/foo.md'), 'utf-8')).toBe('# Markdown sibling\n');+ expect(readFileSync(join(dir, 'archive/foo.mdx'), 'utf-8')).toBe('# MDX sibling\n');+ const body = JSON.parse(result.body) as {+ renamed: Array<{ fromDocName: string; toDocName: string }>;+ };+ expect(body.renamed).toEqual([+ { fromDocName: 'docs/foo.md', toDocName: 'archive/foo.md' },+ { fromDocName: 'docs/foo.mdx', toDocName: 'archive/foo.mdx' },+ ]);+ });++ test('renames into an explicit destination sibling stem without collapsing identity', async () => {+ const dir = setupTmpDir();+ writeFileSync(join(dir, 'foo.md'), '# Source\n', 'utf-8');+ writeFileSync(join(dir, 'bar.mdx'), '# Existing MDX sibling\n', 'utf-8');++ const result = await callApi(+ dir,+ '/api/rename-path',+ 'POST',+ {+ kind: 'file',+ fromPath: 'foo.md',+ toPath: 'bar.md',+ },+ { backlinkIndex: buildBacklinkIndex(dir) },+ );++ expect(result.status).toBe(200);+ expect(existsSync(join(dir, 'foo.md'))).toBe(false);+ expect(readFileSync(join(dir, 'bar.md'), 'utf-8')).toBe('# Source\n');+ expect(readFileSync(join(dir, 'bar.mdx'), 'utf-8')).toBe('# Existing MDX sibling\n');+ const body = JSON.parse(result.body) as {+ renamed: Array<{ fromDocName: string; toDocName: string }>;+ };+ expect(body.renamed).toEqual([{ fromDocName: 'foo', toDocName: 'bar.md' }]);+ });++ test('deletes the selected .md sibling without purging the .mdx sibling identity', async () => {+ const dir = setupTmpDir();+ writeFileSync(join(dir, 'foo.md'), '# Markdown sibling\n', 'utf-8');+ writeFileSync(join(dir, 'foo.mdx'), '# MDX sibling\n', 'utf-8');+ const indexEvents: Array<{ kind: string; path?: string; docName?: string }> = [];++ const result = await callApi(+ dir,+ '/api/delete-path',+ 'POST',+ {+ kind: 'file',+ path: 'foo.md',+ },+ {+ mutateFileIndex: (event) => {+ indexEvents.push(event as (typeof indexEvents)[number]);+ },+ },+ );++ expect(result.status).toBe(200);+ expect(existsSync(join(dir, 'foo.md'))).toBe(false);+ expect(readFileSync(join(dir, 'foo.mdx'), 'utf-8')).toBe('# MDX sibling\n');+ const body = JSON.parse(result.body) as { deletedDocNames: string[] };+ expect(body.deletedDocNames).toEqual(['foo.md']);+ expect(indexEvents).toContainEqual({+ kind: 'delete',+ path: join(dir, 'foo.md'),+ docName: 'foo.md',+ });+ });+test('managed rename updates an already-loaded referring document', async () => {const dir = setupTmpDir();writeFileSync(join(dir, 'notes.md'), '# Notes\n', 'utf-8');@@ -2161,6 +2281,57 @@ describe('file operation API routes', () => {});});+ test('duplicates the selected .md sibling when .md and .mdx share a stem', async () => {+ const dir = setupTmpDir();+ writeFileSync(join(dir, 'foo.md'), '# Markdown sibling\n', 'utf-8');+ writeFileSync(join(dir, 'foo.mdx'), '# MDX sibling\n', 'utf-8');++ const result = await callApi(dir, '/api/duplicate-path', 'POST', {+ kind: 'file',+ path: 'foo.md',+ });++ expect(result.status).toBe(200);+ expect(readFileSync(join(dir, 'foo copy.md'), 'utf-8')).toBe('# Markdown sibling\n');+ expect(readFileSync(join(dir, 'foo.mdx'), 'utf-8')).toBe('# MDX sibling\n');+ const body = JSON.parse(result.body) as {+ kind: string;+ path: string;+ duplicatedDocNames: string[];+ };+ expect(body).toMatchObject({+ kind: 'file',+ path: 'foo copy',+ duplicatedDocNames: ['foo copy'],+ });+ });++ test('duplicates a folder containing same-stem .md and .mdx siblings', async () => {+ const dir = setupTmpDir();+ mkdirSync(join(dir, 'docs'), { recursive: true });+ writeFileSync(join(dir, 'docs/foo.md'), '# Markdown sibling\n', 'utf-8');+ writeFileSync(join(dir, 'docs/foo.mdx'), '# MDX sibling\n', 'utf-8');++ const result = await callApi(dir, '/api/duplicate-path', 'POST', {+ kind: 'folder',+ path: 'docs',+ });++ expect(result.status).toBe(200);+ expect(readFileSync(join(dir, 'docs copy/foo.md'), 'utf-8')).toBe('# Markdown sibling\n');+ expect(readFileSync(join(dir, 'docs copy/foo.mdx'), 'utf-8')).toBe('# MDX sibling\n');+ const body = JSON.parse(result.body) as {+ kind: string;+ path: string;+ duplicatedDocNames: string[];+ };+ expect(body).toMatchObject({+ kind: 'folder',+ path: 'docs copy',+ duplicatedDocNames: ['docs copy/foo.md', 'docs copy/foo.mdx'],+ });+ });+test('duplicates a folder recursively and reports copied markdown docs', async () => {const dir = setupTmpDir();mkdirSync(join(dir, 'archive/old'), { recursive: true });diff --git a/packages/server/src/doc-extensions.test.ts b/packages/server/src/doc-extensions.test.tsindex a09201c1b..9a97558a4 100644--- a/packages/server/src/doc-extensions.test.ts+++ b/packages/server/src/doc-extensions.test.ts@@ -1,6 +1,7 @@import { beforeEach, describe, expect, test } from 'bun:test';import {_resetDocExtensionsForTests,+ docNameToRelativePath,forgetDocExtension,getDocExtension,isSupportedDocFile,@@ -63,6 +64,23 @@ describe('stripDocExtension', () => {});});+describe('docNameToRelativePath', () => {+ test('passes through extension-qualified docNames unchanged', () => {+ registerDocExtension('docs/guide', '.MDX');+ expect(docNameToRelativePath('docs/guide.mdx')).toBe('docs/guide.mdx');+ expect(docNameToRelativePath('docs/guide.md')).toBe('docs/guide.md');+ });++ test('appends the registered extension for extension-less docNames', () => {+ registerDocExtension('docs/guide', '.MDX');+ expect(docNameToRelativePath('docs/guide')).toBe('docs/guide.MDX');+ });++ test('defaults extension-less docNames to .md', () => {+ expect(docNameToRelativePath('docs/new')).toBe('docs/new.md');+ });+});+describe('registerDocExtension / getDocExtension', () => {test('defaults to .md when no file observed', () => {expect(getDocExtension('foo')).toBe('.md');diff --git a/packages/server/src/doc-extensions.ts b/packages/server/src/doc-extensions.tsindex 65e84c2b2..6552c6b0d 100644--- a/packages/server/src/doc-extensions.ts+++ b/packages/server/src/doc-extensions.ts@@ -6,9 +6,13 @@* (Next.js, Astro, Fumadocs): `.mdx` is a strict superset of `.md`, so a* co-located `.mdx` is presumed to intentionally override the `.md`.*- * The extension-less docName is what flows through the CRDT layer, MCP tools,- * wiki-link resolution, and the backlink index. Persistence uses- * `getDocExtension()` to decide which file extension to write to.+ * The extension-less docName is what normally flows through the CRDT layer,+ * MCP tools, wiki-link resolution, and the backlink index. When a Show All+ * disk walk sees same-stem `.md` and `.mdx` files, it can surface an+ * extension-qualified docName for those ambiguous rows so both files remain+ * independently addressable. Persistence writes extension-qualified docNames+ * to that exact file; otherwise it uses `getDocExtension()` to decide which+ * file extension to write to.** Casing preservation: extensions are matched case-insensitively (`.MD` and* `.md` both qualify), but the actual on-disk casing observed at registration@@ -158,6 +162,14 @@ export function getDocExtension(docName: string): string {return docExtensionByName.get(docName) ?? DEFAULT_EXTENSION;}+/**+ * Materialize the content-tree relative path for a docName. Callers still own+ * traversal validation against their target root after resolving the result.+ */+export function docNameToRelativePath(docName: string): string {+ return isSupportedDocFile(docName) ? docName : `${docName}${getDocExtension(docName)}`;+}+/** Clear the recorded extension for a docName (e.g. on file delete). */export function forgetDocExtension(docName: string): void {docExtensionByName.delete(docName);diff --git a/packages/server/src/persistence.test.ts b/packages/server/src/persistence.test.tsindex 0dc74b4a4..0abbcf5c5 100644--- a/packages/server/src/persistence.test.ts+++ b/packages/server/src/persistence.test.ts@@ -49,6 +49,13 @@ describe('safeContentPath', () => {const result = safeContentPath('sub/nested', contentDir);expect(result).toBe(resolve(contentDir, 'sub/nested.md'));});++ test('preserves document names that already include a supported extension', () => {+ expect(safeContentPath('sub/nested.md', contentDir)).toBe(resolve(contentDir, 'sub/nested.md'));+ expect(safeContentPath('sub/nested.mdx', contentDir)).toBe(+ resolve(contentDir, 'sub/nested.mdx'),+ );+ });});describe('isWithinContentDir', () => {diff --git a/packages/server/src/persistence.ts b/packages/server/src/persistence.tsindex e41281a56..cd16b1ede 100644--- a/packages/server/src/persistence.ts+++ b/packages/server/src/persistence.ts@@ -56,7 +56,7 @@ import {restoreContributors,swapContributors,} from './contributor-tracker.ts';-import { getDocExtension } from './doc-extensions.ts';+import { docNameToRelativePath } from './doc-extensions.ts';import { applyDiskContentToDoc, FILE_WATCHER_ORIGIN } from './external-change.ts';import { contentHash, registerWrite } from './file-watcher.ts';import { tracedMkdir, tracedRename, tracedUnlinkSync, tracedWriteFile } from './fs-traced.ts';@@ -420,8 +420,8 @@ export function safeContentPath(documentName: string, contentDir: string): strinif (documentName.includes('\x00')) {throw new Error(`Invalid document name: ${documentName}`);}- const ext = getDocExtension(documentName);- const filePath = resolve(contentDir, `${documentName}${ext}`);+ const relativePath = docNameToRelativePath(documentName);+ const filePath = resolve(contentDir, relativePath);if (!isWithinDir(filePath, contentDir)) {throw new Error(`Invalid document name: ${documentName}`);}diff --git a/packages/server/src/server-factory.ts b/packages/server/src/server-factory.tsindex da9984b23..c85c4df6a 100644--- a/packages/server/src/server-factory.ts+++ b/packages/server/src/server-factory.ts@@ -61,7 +61,7 @@ import { createConflictLifecycleSeedExtension } from './conflict-lifecycle-seed.import { resolveProjectTemplates } from './content/templates-resolver.ts';import { type ContentFilter, createContentFilter } from './content-filter.ts';import { dropPendingDocs, recordContributor } from './contributor-tracker.ts';-import { getDocExtension, stripDocExtension } from './doc-extensions.ts';+import { docNameToRelativePath, stripDocExtension } from './doc-extensions.ts';import { runDocLineageGuard } from './doc-lineage-guard.ts';import {DEFAULT_EMBEDDINGS_DIMENSIONS,@@ -1376,7 +1376,8 @@ export function createServer(options: ServerOptions): ServerInstance {// The traversal-character set lives in `isSafeDocName` (api-extension.ts)// so the security-relevant validation only exists in one place.if (!isSafeDocName(docName)) return null;- const filePath = resolve(resolvedContentDir, `${docName}${getDocExtension(docName)}`);+ const relativePath = docNameToRelativePath(docName);+ const filePath = resolve(resolvedContentDir, relativePath);if (!isWithinDir(filePath, resolvedContentDir)) {return null;}@@ -1576,7 +1577,8 @@ export function createServer(options: ServerOptions): ServerInstance {/** Resolve a safe rescue buffer path, returning null if traversal is detected. */function safeRescuePath(shadowGitDir: string, docName: string): string | null {const rescueBase = resolve(shadowGitDir, 'rescue');- const filePath = resolve(rescueBase, `${docName}${getDocExtension(docName)}`);+ const relativePath = docNameToRelativePath(docName);+ const filePath = resolve(rescueBase, relativePath);if (!isWithinDir(filePath, rescueBase)) return null;return filePath;}diff --git a/packages/server/src/showall-cap.test.ts b/packages/server/src/showall-cap.test.tsindex e7766b4b3..2c1a48595 100644--- a/packages/server/src/showall-cap.test.ts+++ b/packages/server/src/showall-cap.test.ts@@ -17,6 +17,7 @@ import {__resetShowAllWalkStatsForTesting,DEFAULT_SHOWALL_MAX_ENTRIES,getShowAllMaxEntries,+ streamShowAllEntries,walkContentDirForShowAll,} from './api-extension.ts';import { createContentFilter } from './content-filter.ts';@@ -39,7 +40,6 @@ async function walkFixture(dir: string, maxEntries: number) {contentFilter: createContentFilter({ projectDir: dir, contentDir: dir }),dirFilter: null,documents,- getDocExtension: () => '.md',maxEntries,});return { documents, truncated };@@ -148,18 +148,13 @@ describe('walkContentDirForShowAll — entry-cap boundary honesty', () => {});describe('walkContentDirForShowAll — abort-on-disconnect (PRD-6854)', () => {- async function walkWithSignal(- dir: string,- signal: AbortSignal,- getDocExtension: (docName: string) => string = () => '.md',- ) {+ async function walkWithSignal(dir: string, signal: AbortSignal) {const documents: DocumentListEntry[] = [];const { truncated } = await walkContentDirForShowAll({contentDir: dir,contentFilter: createContentFilter({ projectDir: dir, contentDir: dir }),dirFilter: null,documents,- getDocExtension,maxEntries: DEFAULT_SHOWALL_MAX_ENTRIES,signal,});@@ -182,13 +177,20 @@ describe('walkContentDirForShowAll — abort-on-disconnect (PRD-6854)', () => {__resetShowAllWalkStatsForTesting();const TOTAL = 20;const controller = new AbortController();- // Fire the abort from inside the per-file getDocExtension callback after the- // first push; the next per-entry boundary check then bails. Proves the- // loop-boundary guard halts an in-progress walk, not only a pre-aborted one.- const { documents } = await walkWithSignal(makeFlatFixture(TOTAL), controller.signal, () => {- controller.abort();- return '.md';+ const dir = makeFlatFixture(TOTAL);+ const documents: DocumentListEntry[] = [];+ const generator = streamShowAllEntries({+ contentDir: dir,+ contentFilter: createContentFilter({ projectDir: dir, contentDir: dir }),+ dirFilter: null,+ maxEntries: DEFAULT_SHOWALL_MAX_ENTRIES,+ signal: controller.signal,});+ const first = await generator.next();+ if (!first.done) documents.push(first.value);+ controller.abort();+ const final = await generator.next();+ expect(final.done).toBe(true);expect(documents.length).toBeGreaterThan(0);expect(documents.length).toBeLessThan(TOTAL);const stats = __getShowAllWalkStatsForTesting();diff --git a/packages/server/src/showall-stream.test.ts b/packages/server/src/showall-stream.test.tsindex 9e71d3d2b..79ba8b138 100644--- a/packages/server/src/showall-stream.test.ts+++ b/packages/server/src/showall-stream.test.ts@@ -51,7 +51,6 @@ function streamOptsFor(dir: string, maxEntries: number): StreamShowAllOpts {contentDir: dir,contentFilter: createContentFilter({ projectDir: dir, contentDir: dir }),dirFilter: null,- getDocExtension: () => '.md',maxEntries,};}@@ -272,6 +271,57 @@ describe('streamShowAllEntries — level-order emission (PRD-6858)', () => {expect(full?.kind === 'folder' && full.hasChildren).toBe(true);expect(hollow?.kind === 'folder' && hollow.hasChildren).toBe(false);});++ test('co-located .md and .mdx emit separate extension-qualified document rows', async () => {+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-showall-doc-ext-collision-')));+ writeFileSync(join(dir, 'foo.md'), '# Markdown\n');+ writeFileSync(join(dir, 'foo.mdx'), '# MDX\n');+ writeFileSync(join(dir, 'bar.mdx'), '# Bar\n');+ mkdirSync(join(dir, 'folder.mdx'));++ const { entries, truncated } = await drain(+ streamShowAllEntries({+ ...streamOptsFor(dir, 50_000),+ maxDepth: 1,+ }),+ );+ expect(truncated).toBe(false);++ const docs = entries.filter((e) => e.kind === 'document');+ expect(+ docs+ .map((doc) => ({ docName: doc.docName, docExt: doc.docExt, size: doc.size }))+ .toSorted((a, b) => a.docName.localeCompare(b.docName)),+ ).toEqual([+ { docName: 'bar', docExt: '.mdx', size: Buffer.byteLength('# Bar\n') },+ { docName: 'foo.md', docExt: '.md', size: Buffer.byteLength('# Markdown\n') },+ { docName: 'foo.mdx', docExt: '.mdx', size: Buffer.byteLength('# MDX\n') },+ ]);+ expect(entries.some((entry) => entry.kind === 'folder' && entry.path === 'folder.mdx')).toBe(+ true,+ );+ });++ test('escaping same-stem symlink does not force admitted document to extension-qualified row', async () => {+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-showall-doc-ext-symesc-')));+ const outside = realpathSync(mkdtempSync(join(tmpdir(), 'ok-showall-doc-ext-outside-')));+ writeFileSync(join(dir, 'foo.md'), '# Markdown\n');+ writeFileSync(join(outside, 'foo.mdx'), '# Escaped MDX\n');+ symlinkSync(join(outside, 'foo.mdx'), join(dir, 'foo.mdx'));++ const { entries, truncated } = await drain(+ streamShowAllEntries({+ ...streamOptsFor(dir, 50_000),+ maxDepth: 1,+ }),+ );+ expect(truncated).toBe(false);++ const docs = entries.filter((e) => e.kind === 'document');+ expect(docs.map((doc) => ({ docName: doc.docName, docExt: doc.docExt }))).toEqual([+ { docName: 'foo', docExt: '.md' },+ ]);+ });});describe('streamShowAllEntries — cap accounting boundary quirks', () => {diff --git a/packages/server/src/sync-engine.test.ts b/packages/server/src/sync-engine.test.tsindex 1e04f5ffc..5e44a7c40 100644--- a/packages/server/src/sync-engine.test.ts+++ b/packages/server/src/sync-engine.test.ts@@ -551,6 +551,7 @@ describe('SyncEngine ConflictStore admission (content-only)', () => {await sister.commit('base');await sister.addRemote('origin', bareDir);await sister.push('origin', 'main');+ await simpleGit(bareDir).raw('symbolic-ref', 'HEAD', 'refs/heads/main');// beforeEach pre-creates projectDir + .ok/local/. `git clone` refuses// a non-empty destination, so wipe and let clone recreate it, then