Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): keep an edited file open when you click the next one (PRD-7835) (#3274)
sarah103e961036fc
diff --git a/.changeset/preview-tab-promotion.md b/.changeset/preview-tab-promotion.mdnew file mode 100644index 000000000..d8ff7f452--- /dev/null+++ b/.changeset/preview-tab-promotion.md@@ -0,0 +1,9 @@+---+"@inkeep/open-knowledge": patch+---++A file you edit now stays open when you click the next one in the sidebar. Single-clicking a file opens it in a preview tab (italic label) that the next click reuses — but editing it left the tab provisional, so a document you had just typed into disappeared as soon as you opened something else. The edit itself was never lost, since it lands in the CRDT the moment you make it, but the tab vanishing read as lost work.++Editing a document now makes its tab permanent: typing in the visual editor or in source mode, cutting or pasting in source mode, applying a lint fix from the Problems panel or either editor, and editing frontmatter through the property panel — including nested fields, renames, and drag-reordering. Switching a document between source and visual mode promotes it too, as does double-clicking its row in the sidebar, matching double-click on the tab itself. Agent and remote-peer writes deliberately do not: a tab you are only reading stays provisional even while something else writes to the document.++Preview tabs are otherwise unchanged — clicking a file you never touch still gives up its slot to the next one.diff --git a/packages/app/package.json b/packages/app/package.jsonindex d36a49a26..98192a15d 100644--- a/packages/app/package.json+++ b/packages/app/package.json@@ -27,7 +27,7 @@"measure:stress": "bash scripts/measure-stress.sh","measure:sweep": "bash scripts/measure-sweep.sh","perf:compare": "bash scripts/perf-compare.sh",- "test:e2e": "playwright test tests/stress/ux-interactions.e2e.ts tests/stress/file-tree-create.e2e.ts tests/stress/file-tree-drag-to-root.e2e.ts tests/stress/file-tree-deselect-to-root.e2e.ts tests/stress/file-tree-sticky-collapse.e2e.ts tests/stress/create-then-rename-editable.e2e.ts tests/stress/find-replace.e2e.ts tests/stress/editor-tabs.e2e.ts tests/stress/crdt-stress.e2e.ts tests/stress/slash-command.e2e.ts tests/stress/paste-fidelity.e2e.ts tests/stress/fr-7a-disconnect-source-mode.e2e.ts tests/stress/docs-open.e2e.ts tests/stress/frozen-table-headers.e2e.ts tests/stress/asset-embed.e2e.ts tests/stress/asset-embed-advanced.e2e.ts tests/stress/asset-click-dispatch.e2e.ts tests/stress/handoff.e2e.ts tests/stress/multi-agent-presence.e2e.ts tests/stress/editor-mode-persistence.e2e.ts tests/stress/lint-config-toggle.e2e.ts tests/stress/plugin-enable-notice.e2e.ts tests/stress/schema-edit-fields-view.e2e.ts tests/stress/sidebar-search-pill.e2e.ts tests/stress/navigation-history.e2e.ts tests/stress/command-palette-semantic.e2e.ts tests/stress/agent-activity-panel.e2e.ts tests/stress/drop-pipeline-auto-open.e2e.ts tests/stress/command-palette-flicker.e2e.ts tests/stress/cm6-list-hanging-indent.e2e.ts tests/stress/ng7-rapid-nav-coherence.e2e.ts tests/stress/reveal-on-activate.e2e.ts tests/stress/selection-indicator.e2e.ts tests/stress/new-file-cross-doc-bleed.e2e.ts tests/stress/editor-mode-flip-cross-doc-bleed.e2e.ts tests/stress/editor-area-viewport-resize.e2e.ts tests/stress/qa-sidebar-responsive.e2e.ts tests/stress/prd-6955-reassertion-repro.e2e.ts tests/stress/prd-6955-reassertion-wedge.e2e.ts tests/stress/prd-6914-repro.e2e.ts tests/stress/showall-lazy-tree.e2e.ts tests/stress/tabs-component-strip.e2e.ts tests/stress/source-find-scroll.e2e.ts tests/stress/harness-app-warmth.e2e.ts tests/stress/qa-canary-authoring-both-modes.e2e.ts tests/stress/qa-canary-live-typing.e2e.ts tests/stress/keystroke-cadence-danger-space.e2e.ts tests/stress/jsx-unregistered-backspace-delete.e2e.ts tests/stress/jsx-unregistered-ime-concurrent.e2e.ts tests/stress/jsx-backspace-delete.e2e.ts tests/stress/link-authoring-bytes.e2e.ts tests/stress/link-authoring-apex.e2e.ts tests/stress/command-palette-parity.e2e.ts tests/stress/settings-search.e2e.ts tests/stress/chip-popover-positioning.e2e.ts tests/stress/docs-open-scroll-restore.e2e.ts tests/stress/file-tree-decoration-chip-strip-repro.e2e.ts tests/stress/grip-click-nodeselect.e2e.ts tests/stress/jsx-halo-semantics.e2e.ts tests/stress/jsx-image-body-click.e2e.ts tests/stress/jsx-prop-panel-placeholder.e2e.ts tests/stress/jsx-range-encompass-halo.e2e.ts tests/stress/jsx-wildcard-convert.e2e.ts tests/stress/markdown-lint.e2e.ts tests/stress/frontmatter-schema-badge.e2e.ts tests/stress/unified-problems.e2e.ts tests/stress/mid-type-recovery.e2e.ts tests/stress/observer-a-multi-client.e2e.ts tests/stress/outline-toolbar-occlusion.e2e.ts tests/stress/quiet-tree-hidden-doc.e2e.ts tests/stress/raw-mdx-fallback-onblur-upgrade.e2e.ts tests/stress/rename-noext-probe.e2e.ts tests/stress/show-ok-folders.e2e.ts tests/stress/source-polish.e2e.ts tests/stress/warm-skeleton-scroll-restore.e2e.ts tests/stress/props-toggle-scroll-preserve.e2e.ts tests/stress/yjs-no-dual-import.e2e.ts tests/stress/graph-panel-surfaces.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/rename-content-preservation.e2e.ts tests/stress/rename-consolidation.e2e.ts tests/stress/outline-active-heading.e2e.ts tests/stress/outline-navigation.e2e.ts tests/stress/prd-7627-default-swatch.e2e.ts tests/stress/clipboard-dollar-math-source-fallback.e2e.ts tests/stress/source-mode-undo-keymap.e2e.ts tests/stress/timeline-recovered-restore.e2e.ts tests/stress/blank-line-preservation.e2e.ts tests/stress/landing-helpers.e2e.ts tests/stress/mode-switch-landing.e2e.ts tests/stress/mode-switch-ordinal-divergence.e2e.ts tests/stress/comment-annotation-visibility.e2e.ts tests/stress/qa-miles-edge-blanks.e2e.ts tests/stress/prop-upload.e2e.ts tests/stress/slash-command-auto-open.e2e.ts tests/stress/clipboard-relative-url-source-fallback.e2e.ts tests/stress/editor-split-view.e2e.ts tests/stress/language-load-failure.e2e.ts tests/stress/language-first-paint.e2e.ts tests/stress/user-text-direction.e2e.ts tests/stress/pseudolocale.e2e.ts tests/stress/language-picker.e2e.ts tests/stress/zh-hans-coverage-sweep.e2e.ts",+ "test:e2e": "playwright test tests/stress/ux-interactions.e2e.ts tests/stress/file-tree-create.e2e.ts tests/stress/file-tree-drag-to-root.e2e.ts tests/stress/file-tree-deselect-to-root.e2e.ts tests/stress/file-tree-sticky-collapse.e2e.ts tests/stress/create-then-rename-editable.e2e.ts tests/stress/find-replace.e2e.ts tests/stress/editor-tabs.e2e.ts tests/stress/crdt-stress.e2e.ts tests/stress/slash-command.e2e.ts tests/stress/paste-fidelity.e2e.ts tests/stress/fr-7a-disconnect-source-mode.e2e.ts tests/stress/docs-open.e2e.ts tests/stress/frozen-table-headers.e2e.ts tests/stress/asset-embed.e2e.ts tests/stress/asset-embed-advanced.e2e.ts tests/stress/asset-click-dispatch.e2e.ts tests/stress/handoff.e2e.ts tests/stress/multi-agent-presence.e2e.ts tests/stress/editor-mode-persistence.e2e.ts tests/stress/lint-config-toggle.e2e.ts tests/stress/plugin-enable-notice.e2e.ts tests/stress/schema-edit-fields-view.e2e.ts tests/stress/sidebar-search-pill.e2e.ts tests/stress/navigation-history.e2e.ts tests/stress/command-palette-semantic.e2e.ts tests/stress/agent-activity-panel.e2e.ts tests/stress/drop-pipeline-auto-open.e2e.ts tests/stress/command-palette-flicker.e2e.ts tests/stress/cm6-list-hanging-indent.e2e.ts tests/stress/ng7-rapid-nav-coherence.e2e.ts tests/stress/reveal-on-activate.e2e.ts tests/stress/selection-indicator.e2e.ts tests/stress/new-file-cross-doc-bleed.e2e.ts tests/stress/editor-mode-flip-cross-doc-bleed.e2e.ts tests/stress/editor-area-viewport-resize.e2e.ts tests/stress/qa-sidebar-responsive.e2e.ts tests/stress/prd-6955-reassertion-repro.e2e.ts tests/stress/prd-6955-reassertion-wedge.e2e.ts tests/stress/prd-6914-repro.e2e.ts tests/stress/showall-lazy-tree.e2e.ts tests/stress/tabs-component-strip.e2e.ts tests/stress/source-find-scroll.e2e.ts tests/stress/harness-app-warmth.e2e.ts tests/stress/qa-canary-authoring-both-modes.e2e.ts tests/stress/qa-canary-live-typing.e2e.ts tests/stress/keystroke-cadence-danger-space.e2e.ts tests/stress/jsx-unregistered-backspace-delete.e2e.ts tests/stress/jsx-unregistered-ime-concurrent.e2e.ts tests/stress/jsx-backspace-delete.e2e.ts tests/stress/link-authoring-bytes.e2e.ts tests/stress/link-authoring-apex.e2e.ts tests/stress/command-palette-parity.e2e.ts tests/stress/settings-search.e2e.ts tests/stress/chip-popover-positioning.e2e.ts tests/stress/docs-open-scroll-restore.e2e.ts tests/stress/file-tree-decoration-chip-strip-repro.e2e.ts tests/stress/grip-click-nodeselect.e2e.ts tests/stress/jsx-halo-semantics.e2e.ts tests/stress/jsx-image-body-click.e2e.ts tests/stress/jsx-prop-panel-placeholder.e2e.ts tests/stress/jsx-range-encompass-halo.e2e.ts tests/stress/jsx-wildcard-convert.e2e.ts tests/stress/markdown-lint.e2e.ts tests/stress/frontmatter-schema-badge.e2e.ts tests/stress/unified-problems.e2e.ts tests/stress/mid-type-recovery.e2e.ts tests/stress/observer-a-multi-client.e2e.ts tests/stress/outline-toolbar-occlusion.e2e.ts tests/stress/quiet-tree-hidden-doc.e2e.ts tests/stress/raw-mdx-fallback-onblur-upgrade.e2e.ts tests/stress/rename-noext-probe.e2e.ts tests/stress/show-ok-folders.e2e.ts tests/stress/source-polish.e2e.ts tests/stress/warm-skeleton-scroll-restore.e2e.ts tests/stress/props-toggle-scroll-preserve.e2e.ts tests/stress/yjs-no-dual-import.e2e.ts tests/stress/graph-panel-surfaces.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/rename-content-preservation.e2e.ts tests/stress/rename-consolidation.e2e.ts tests/stress/outline-active-heading.e2e.ts tests/stress/outline-navigation.e2e.ts tests/stress/prd-7627-default-swatch.e2e.ts tests/stress/clipboard-dollar-math-source-fallback.e2e.ts tests/stress/source-mode-undo-keymap.e2e.ts tests/stress/timeline-recovered-restore.e2e.ts tests/stress/blank-line-preservation.e2e.ts tests/stress/landing-helpers.e2e.ts tests/stress/mode-switch-landing.e2e.ts tests/stress/mode-switch-ordinal-divergence.e2e.ts tests/stress/comment-annotation-visibility.e2e.ts tests/stress/qa-miles-edge-blanks.e2e.ts tests/stress/prop-upload.e2e.ts tests/stress/slash-command-auto-open.e2e.ts tests/stress/clipboard-relative-url-source-fallback.e2e.ts tests/stress/editor-split-view.e2e.ts tests/stress/language-load-failure.e2e.ts tests/stress/language-first-paint.e2e.ts tests/stress/user-text-direction.e2e.ts tests/stress/pseudolocale.e2e.ts tests/stress/language-picker.e2e.ts tests/stress/zh-hans-coverage-sweep.e2e.ts tests/stress/preview-tab-promotion.e2e.ts","test:e2e:install-browsers": "playwright install chromium webkit firefox","test:visual": "playwright test --config playwright.visual.config.ts","test:visual:update": "playwright test --config playwright.visual.config.ts --update-snapshots",diff --git a/packages/app/src/components/DocPanel.tsx b/packages/app/src/components/DocPanel.tsxindex ca307acc0..b2ccaa5a8 100644--- a/packages/app/src/components/DocPanel.tsx+++ b/packages/app/src/components/DocPanel.tsx@@ -136,14 +136,14 @@ export function DocPanel({// document the user is viewing.const handleFix = (diagnostic: DiagnosticLike) => {if (lintProvider !== null && diagnostic.fixes && diagnostic.fixes.length > 0) {- applyLintFixes(lintProvider, diagnostic.fixes);+ applyLintFixes(lintProvider, diagnostic.fixes, docName);}};// Auto-fix stays lint-only by construction: only the live lint diagnostics// carry deterministic fixes (broken links need content edits).const handleAutoFix = () => {if (lintProvider !== null) {- applyLintFixes(lintProvider, collectFixes(lintDiagnostics));+ applyLintFixes(lintProvider, collectFixes(lintDiagnostics), docName);}};// Hand one diagnostic to the user's preferred AI as a grounded fix prompt (thediff --git a/packages/app/src/components/EditorPane.dom.test.tsx b/packages/app/src/components/EditorPane.dom.test.tsxindex 47c037106..c9210ef29 100644--- a/packages/app/src/components/EditorPane.dom.test.tsx+++ b/packages/app/src/components/EditorPane.dom.test.tsx@@ -152,6 +152,11 @@ vi.doMock('@/editor/DocumentContext', () => ({isSkillsNewTabId: () => false,}));+const promotePreviewTabMock = vi.fn(() => {});+vi.doMock('@/editor/preview-tab-promotion', () => ({+ requestPreviewTabPromotion: promotePreviewTabMock,+}));+vi.doMock('@/editor/use-editor-mode', () => ({useEditorMode: () => ['wysiwyg', () => {}],}));@@ -1088,3 +1093,51 @@ describe('EditorPane session-panel wiring', () => {expect(input.texts).toEqual([]);});});++describe('EditorPane mode switch promotes the preview tab', () => {+ afterEach(() => {+ cleanup();+ delete (window as { okDesktop?: unknown }).okDesktop;+ promotePreviewTabMock.mockClear();+ activeProvider = undefined;+ clearPendingSourceNavigationsForTest();+ });++ /** The ⌥⌘M / Ctrl-Alt-M binding for `toggle-editor-mode`. */+ function pressModeToggle() {+ act(() => {+ window.dispatchEvent(+ new KeyboardEvent('keydown', {+ code: 'KeyM',+ key: 'm',+ altKey: true,+ metaKey: true,+ ctrlKey: true,+ bubbles: true,+ }),+ );+ });+ }++ test('flipping a doc between source and WYSIWYG promotes its tab', async () => {+ // Switching modes changes no bytes, so no editor origin guard can see it —+ // the promotion has to come from the mode-change handler itself.+ activeProvider = { document: new Y.Doc() };+ await renderEditorPane();++ pressModeToggle();++ expect(promotePreviewTabMock).toHaveBeenCalledWith('docs/notes');+ });++ test('a flip with no provider yet promotes nothing', async () => {+ // Same guard the anchor capture uses: before the provider resolves there is+ // no document to have committed to.+ activeProvider = undefined;+ await renderEditorPane();++ pressModeToggle();++ expect(promotePreviewTabMock).not.toHaveBeenCalled();+ });+});diff --git a/packages/app/src/components/EditorPane.tsx b/packages/app/src/components/EditorPane.tsxindex b68dceb60..107709496 100644--- a/packages/app/src/components/EditorPane.tsx+++ b/packages/app/src/components/EditorPane.tsx@@ -14,6 +14,7 @@ import { TagDialog } from '@/editor/components/TagDialog';import { useDocumentContext } from '@/editor/DocumentContext';import { RAW_MDX_NAV_EVENT, type RawMdxNavDetail } from '@/editor/extensions/raw-mdx-nav-event';import { captureModeSwitchAnchor, requestViewInSource } from '@/editor/mode-switch-landing';+import { requestPreviewTabPromotion } from '@/editor/preview-tab-promotion';import { getSelectionContext } from '@/editor/selection-context';import { rememberPendingSourceNavigation } from '@/editor/source-editor-navigation';import { type EditorModeValue, useEditorMode } from '@/editor/use-editor-mode';@@ -560,6 +561,11 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {docName: activeDocName,ytext: activeProvider.document.getText('source'),});+ // Flipping a doc's mode is committing to it, so a previewed doc stops+ // being provisional. Only this path promotes: the tool-driven flips+ // (raw-MDX nav, view-in-source) call `setEditorMode` directly and stay a+ // peek, exactly as they stay session-only for the persisted preference.+ requestPreviewTabPromotion(activeDocName);}setEditorMode(mode);// User-initiated change — persist globally. Tool-driven flips (e.g.diff --git a/packages/app/src/components/FileTree.preview-tabs.dom.test.tsx b/packages/app/src/components/FileTree.preview-tabs.dom.test.tsxindex 0d29c32b7..949594da8 100644--- a/packages/app/src/components/FileTree.preview-tabs.dom.test.tsx+++ b/packages/app/src/components/FileTree.preview-tabs.dom.test.tsx@@ -249,16 +249,33 @@ vi.doMock('@pierre/trees', () => ({}));vi.doMock('@pierre/trees/react', () => ({useFileTree: () => ({ model }),- FileTree: ({ onClickCapture }: { onClickCapture?: MouseEventHandler<HTMLDivElement> }) => (- <div data-testid="fake-pierre-tree" role="tree" onClickCapture={onClickCapture}>+ FileTree: ({+ onClickCapture,+ onDoubleClickCapture,+ }: {+ onClickCapture?: MouseEventHandler<HTMLDivElement>;+ onDoubleClickCapture?: MouseEventHandler<HTMLDivElement>;+ }) => (+ <div+ data-testid="fake-pierre-tree"+ role="tree"+ onClickCapture={onClickCapture}+ onDoubleClickCapture={onDoubleClickCapture}+ >+ {/* `aria-label` pins the row's accessible name so the nested rename+ field's value can't change how the tests address it. */}<divrole="treeitem"+ aria-label="note.md"data-item-path="note.md"data-item-type="file"aria-selected="false"tabIndex={-1}>note.md+ {/* Pierre renders the inline rename field inside the row, so it+ inherits the row's `data-item-path`. */}+ <input data-testid="rename-input" defaultValue="note.md" /></div><divrole="treeitem"@@ -284,6 +301,11 @@ vi.doMock('@pierre/trees/react', () => ({),}));+const promoteTabMock = vi.fn(() => {});+vi.doMock('@/editor/preview-tab-promotion', () => ({+ requestPreviewTabPromotionForTab: promoteTabMock,+}));+const { FileTree } = await import('./FileTree');describe('FileTree preview-tab activation', () => {@@ -356,3 +378,96 @@ describe('FileTree preview-tab activation', () => {expect(window.location.hash).toBe('');});});++describe('FileTree double-click promotes the previewed row', () => {+ let consoleWarnSpy: ReturnType<typeof vi.spyOn>;++ beforeEach(() => {+ previewTabsEnabled = true;+ model.items.clear();+ model.selectedPaths = [];+ openTargetMock.mockClear();+ promoteTabMock.mockClear();+ notifySidebarFileSelectedMock.mockClear();+ window.location.hash = '';+ globalThis.fetch = makeFetchMock() as unknown as typeof fetch;+ consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});+ });++ afterEach(() => {+ cleanup();+ consoleWarnSpy.mockRestore();+ });++ async function renderTree() {+ render(<FileTree />);+ await screen.findByTestId('fake-pierre-tree');+ await waitFor(() => expect(model.getItem('docs/')).not.toBeNull());+ }++ test('double-clicking a file row promotes its tab, addressed by tab id not row path', async () => {+ await renderTree();++ fireEvent.doubleClick(screen.getByRole('treeitem', { name: 'note.md' }));++ // The row is `note.md`; the tab is the extension-less `note`.+ await waitFor(() => expect(promoteTabMock).toHaveBeenCalledWith('note'));+ });++ test('a single click does not promote — that is what keeps preview provisional', async () => {+ await renderTree();++ fireEvent.click(screen.getByRole('treeitem', { name: 'note.md' }));++ await waitFor(() => expect(openTargetMock).toHaveBeenCalled());+ expect(promoteTabMock).not.toHaveBeenCalled();+ });++ test('double-clicking a folder row promotes nothing', async () => {+ // Two clicks on a folder are two expand toggles — a gesture about the tree,+ // not a commitment to the folder overview.+ await renderTree();++ fireEvent.doubleClick(screen.getByRole('treeitem', { name: 'docs/' }));++ expect(promoteTabMock).not.toHaveBeenCalled();+ });++ test('double-clicking the pinned folder header promotes nothing', async () => {+ await renderTree();++ fireEvent.doubleClick(screen.getByTestId('sticky-docs'));++ expect(promoteTabMock).not.toHaveBeenCalled();+ });++ test('a modified-key double-click promotes nothing', async () => {+ // Cmd/Ctrl/Shift-click are selection and open-elsewhere gestures; they must+ // not be read as a commitment to the row.+ await renderTree();++ fireEvent.doubleClick(screen.getByRole('treeitem', { name: 'note.md' }), { metaKey: true });+ fireEvent.doubleClick(screen.getByRole('treeitem', { name: 'note.md' }), { shiftKey: true });++ expect(promoteTabMock).not.toHaveBeenCalled();+ });++ test('a non-primary-button double-click promotes nothing', async () => {+ await renderTree();++ fireEvent.doubleClick(screen.getByRole('treeitem', { name: 'note.md' }), { button: 2 });++ expect(promoteTabMock).not.toHaveBeenCalled();+ });++ test('double-clicking inside the inline rename field promotes nothing', async () => {+ // The field is a descendant of the row and inherits its `data-item-path`,+ // so double-clicking to select a word while renaming would otherwise read+ // as a commit to the row.+ await renderTree();++ fireEvent.doubleClick(screen.getByTestId('rename-input'));++ expect(promoteTabMock).not.toHaveBeenCalled();+ });+});diff --git a/packages/app/src/components/FileTree.tsx b/packages/app/src/components/FileTree.tsxindex 7e4d8b485..89bb83ad0 100644--- a/packages/app/src/components/FileTree.tsx+++ b/packages/app/src/components/FileTree.tsx@@ -135,6 +135,7 @@ import {} from '@/components/file-tree-rename-validation';import { revealActiveRow } from '@/components/file-tree-reveal';import {+ previewTabIdForTreePath,resolveFileTreeSelection,resolveFileTreeSelectionAction,} from '@/components/file-tree-selection';@@ -185,6 +186,7 @@ import { asDirectoryHandle, useSelectionMirror } from '@/components/use-selectioimport { getEditorForDoc } from '@/editor/active-editor';import { type OpenTargetOptions, useDocumentContext } from '@/editor/DocumentContext';import { assetTabId, docTabId, folderTabId, remapPathForFolderRenames } from '@/editor/editor-tabs';+import { requestPreviewTabPromotionForTab } from '@/editor/preview-tab-promotion';import { useConflicts } from '@/hooks/use-conflicts';import { useFolderConfig } from '@/hooks/use-folder-config';import { useGitSyncStatusDetailed } from '@/hooks/use-git-sync-status';@@ -3480,6 +3482,33 @@ export function FileTree({queueMicrotask(() => activateTreePath(path));}+ /**+ * Double-clicking a row commits to that file, so its preview tab stops being+ * provisional — matching double-click on the tab itself.+ *+ * Deliberately additive: the row was already opened by the first click of the+ * pair, so this only flips the tab's preview state and never navigates. That+ * keeps it clear of the click-capture handler's folder-expand and+ * same-stem-sibling paths, which is why it doesn't preventDefault.+ *+ * Folders are skipped. A double-click on one is two toggles of its expand+ * state — a gesture about the tree, not a commitment to the folder overview.+ */+ function handleTreeDoubleClickCapture(event: ReactMouseEvent<HTMLElement>) {+ if (event.defaultPrevented || event.button !== 0) return;+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;+ // The inline rename input is a descendant of the row and inherits its+ // `data-item-path`, so a double-click to select a word while renaming would+ // otherwise read as a commit to the row. Same helper the tree's keydown+ // handler uses for the same reason.+ if (isEditableKeyboardTarget(event.target)) return;+ const item = findTreeItemElement(event.nativeEvent);+ if (!item || item.dataset.fileTreeStickyRow === 'true') return;+ if (item.dataset.itemType === 'folder') return;+ const tabId = previewTabIdForTreePath(item.dataset.itemPath, documentsRef.current, pages);+ if (tabId) requestPreviewTabPromotionForTab(tabId);+ }+function handleEmptyExternalFileDragOver(event: ReactDragEvent<HTMLDivElement>) {if (!isExternalFileDrag(event.nativeEvent)) return;event.preventDefault();@@ -3615,6 +3644,7 @@ export function FileTree({// focus-ring suppression in FILE_TREE_CREATION_CLEARED_CSS.{...{ [FILE_TREE_CREATION_CLEARED_ATTR]: creationDirCleared ? '' : undefined }}onClickCapture={handleTreeClickCapture}+ onDoubleClickCapture={handleTreeDoubleClickCapture}onMouseMove={handleTreeMouseMove}onMouseLeave={cancelCurrentHoverPrewarm}renderContextMenu={(item, context) => (diff --git a/packages/app/src/components/PageHeader.preview-promotion.dom.test.tsx b/packages/app/src/components/PageHeader.preview-promotion.dom.test.tsxnew file mode 100644index 000000000..939d12608--- /dev/null+++ b/packages/app/src/components/PageHeader.preview-promotion.dom.test.tsx@@ -0,0 +1,88 @@+/**+ * The page header's frontmatter binding is promotion-wrapped.+ *+ * `PageHeader` builds its own `bindFrontmatterDoc` binding, separately from+ * `PropertyPanel`'s. The wrapper unit tests prove the wrapper announces when+ * it is called; only this proves `PageHeader` calls it — so a refactor that+ * dropped the wrap would silently stop promoting on a cover reframe with every+ * other test still green.+ *+ * Drives the keyboard path (`role="slider"`, commit-on-keypress) rather than a+ * pointer drag: same `binding.patch` commit, no synthetic pointer-capture+ * choreography.+ */++import { HocuspocusProvider } from '@hocuspocus/provider';+import { cleanup, render, screen, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { afterEach, describe, expect, test, vi } from 'vitest';+import { subscribePreviewTabPromotion } from '@/editor/preview-tab-promotion';+import { PageHeader } from './PageHeader';++const DUMMY_WS = 'ws://localhost:1/collab';++const providers: HocuspocusProvider[] = [];+let unsubscribePromotion: (() => void) | undefined;++function makeProvider(docName: string, fenced: string): HocuspocusProvider {+ const p = new HocuspocusProvider({ url: DUMMY_WS, name: docName });+ providers.push(p);+ const ytext = p.document.getText('source');+ p.document.transact(() => {+ ytext.delete(0, ytext.length);+ ytext.insert(0, fenced);+ });+ return p;+}++afterEach(() => {+ cleanup();+ unsubscribePromotion?.();+ unsubscribePromotion = undefined;+ for (const p of providers.splice(0)) {+ try {+ p.destroy();+ } catch {+ // ignore+ }+ }+});++describe('PageHeader — preview-tab promotion', () => {+ test('committing a cover focal change announces the doc', async () => {+ const promoted = vi.fn();+ unsubscribePromotion = subscribePreviewTabPromotion(promoted);+ const provider = makeProvider(+ 'promotion-cover-doc',+ '---\ncover: https://example.com/a.png\ncover_y: 0.5\n---\n',+ );++ render(<PageHeader provider={provider} />);+ const slider = await screen.findByRole('slider');++ // Focused directly rather than clicked: a click would run the drag's+ // `setPointerCapture`, which jsdom does not implement, and the keyboard+ // path is the same `binding.patch` commit.+ const user = userEvent.setup();+ slider.focus();+ await user.keyboard('{ArrowUp}');++ await waitFor(() => expect(promoted).toHaveBeenCalledWith('promotion-cover-doc'));+ });++ test('merely rendering the header announces nothing', async () => {+ // Binding setup reads and subscribes; a cover you only looked at must not+ // promote the tab.+ const promoted = vi.fn();+ unsubscribePromotion = subscribePreviewTabPromotion(promoted);+ const provider = makeProvider(+ 'promotion-cover-render-only',+ '---\ncover: https://example.com/a.png\ncover_y: 0.5\n---\n',+ );++ render(<PageHeader provider={provider} />);+ await screen.findByRole('slider');++ expect(promoted).not.toHaveBeenCalled();+ });+});diff --git a/packages/app/src/components/PageHeader.tsx b/packages/app/src/components/PageHeader.tsxindex 52f7fda14..33c064644 100644--- a/packages/app/src/components/PageHeader.tsx+++ b/packages/app/src/components/PageHeader.tsx@@ -54,6 +54,7 @@ import {resolvePageCover,resolvePageIcon,} from '@/components/page-header-utils';+import { withPreviewTabPromotion } from '@/editor/preview-tab-promotion';interface PageHeaderProps {provider: HocuspocusProvider;@@ -82,7 +83,12 @@ export function PageHeader({ provider }: PageHeaderProps) {const bindingRef = useRef<FrontmatterBinding | null>(null);useEffect(() => {- const next = bindFrontmatterDoc(provider);+ // Wrapped like PropertyPanel's: a cover reframe is a user edit, and it+ // reaches the editors as a sync-origin Y.Text change they can't attribute.+ const next = withPreviewTabPromotion(+ bindFrontmatterDoc(provider),+ provider.configuration.name ?? '',+ );bindingRef.current = next;setSnapshot(next.current());const unsub = next.subscribe((s) => {diff --git a/packages/app/src/components/PropertyPanel.preview-promotion.dom.test.tsx b/packages/app/src/components/PropertyPanel.preview-promotion.dom.test.tsxnew file mode 100644index 000000000..348d8816a--- /dev/null+++ b/packages/app/src/components/PropertyPanel.preview-promotion.dom.test.tsx@@ -0,0 +1,126 @@+/**+ * Frontmatter edits promote the document's preview tab.+ *+ * Property-panel writes land in the YAML region of `Y.Text('source')`, so they+ * reach both editors as sync-origin changes and neither editor's origin guard+ * classifies them as user input. The panel therefore announces the promotion+ * itself, and this pins that wiring — including the part that is easy to get+ * wrong, that a REJECTED patch announces nothing.+ */++import { HocuspocusProvider } from '@hocuspocus/provider';+import { cleanup, render, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { afterEach, describe, expect, test, vi } from 'vitest';+import { TooltipProvider } from '@/components/ui/tooltip';+import { subscribePreviewTabPromotion } from '@/editor/preview-tab-promotion';+import { PropertyProvider } from './PropertyContext';+import { PropertyPanel } from './PropertyPanel';++let unsubscribePromotion: (() => void) | undefined;++const DUMMY_WS = 'ws://localhost:1/collab';++const providers: HocuspocusProvider[] = [];++function makeProvider(docName: string): HocuspocusProvider {+ const p = new HocuspocusProvider({ url: DUMMY_WS, name: docName });+ providers.push(p);+ return p;+}++function seedYTextFm(provider: HocuspocusProvider, fenced: string): void {+ const ytext = provider.document.getText('source');+ provider.document.transact(() => {+ ytext.delete(0, ytext.length);+ ytext.insert(0, fenced);+ });+}++function renderPanel(provider: HocuspocusProvider) {+ return render(+ <TooltipProvider>+ <PropertyProvider>+ <PropertyPanel provider={provider} />+ </PropertyProvider>+ </TooltipProvider>,+ );+}++function findInputByKey(testid: string, key: string): Promise<HTMLElement> {+ return waitFor(() => {+ const el = document.querySelector(+ `[data-testid="${testid}"][data-key="${key}"]`,+ ) as HTMLElement | null;+ if (!el) throw new Error(`element not found: [data-testid="${testid}"][data-key="${key}"]`);+ return el;+ });+}++afterEach(() => {+ cleanup();+ unsubscribePromotion?.();+ for (const p of providers.splice(0)) {+ try {+ p.destroy();+ } catch {+ // ignore+ }+ }+});++describe('PropertyPanel — preview-tab promotion', () => {+ test('committing a property edit announces the doc as user-edited', async () => {+ const onUserEdit = vi.fn();+ unsubscribePromotion = subscribePreviewTabPromotion(onUserEdit);++ const provider = makeProvider('promotion-commit-doc');+ seedYTextFm(provider, '---\ntitle: Draft\n---\n');+ renderPanel(provider);++ const titleInput = (await findInputByKey('text-widget', 'title')) as HTMLTextAreaElement | null;+ expect(titleInput).not.toBeNull();+ if (!titleInput) return;++ const user = userEvent.setup();+ await user.click(titleInput);+ await user.clear(titleInput);+ await user.type(titleInput, 'Published');+ await user.tab(); // blur — commits the draft through the binding.++ expect(onUserEdit).toHaveBeenCalledWith('promotion-commit-doc');+ });++ test('merely rendering the panel announces nothing', async () => {+ // Binding setup reads and subscribes; a doc the user only previewed must+ // not be promoted by the panel mounting against it.+ const onUserEdit = vi.fn();+ unsubscribePromotion = subscribePreviewTabPromotion(onUserEdit);++ const provider = makeProvider('promotion-render-only-doc');+ seedYTextFm(provider, '---\ntitle: Draft\n---\n');+ renderPanel(provider);++ await findInputByKey('text-widget', 'title');++ expect(onUserEdit).not.toHaveBeenCalled();+ });++ test('focusing and blurring without changing anything announces nothing', async () => {+ const onUserEdit = vi.fn();+ unsubscribePromotion = subscribePreviewTabPromotion(onUserEdit);++ const provider = makeProvider('promotion-no-change-doc');+ seedYTextFm(provider, '---\ntitle: Draft\n---\n');+ renderPanel(provider);++ const titleInput = (await findInputByKey('text-widget', 'title')) as HTMLTextAreaElement | null;+ if (!titleInput) return;++ const user = userEvent.setup();+ await user.click(titleInput);+ await user.tab();++ expect(onUserEdit).not.toHaveBeenCalled();+ });+});diff --git a/packages/app/src/components/PropertyPanel.tsx b/packages/app/src/components/PropertyPanel.tsxindex 649791f36..cc69c0a44 100644--- a/packages/app/src/components/PropertyPanel.tsx+++ b/packages/app/src/components/PropertyPanel.tsx@@ -46,6 +46,7 @@ import { coerceValue, DEFAULT_VALUE_FOR_TYPE } from '@/components/PropertyWidgetimport { usePropertiesCollapsed } from '@/components/properties-collapsed-store';import { Button } from '@/components/ui/button';import { useDocLintConfig } from '@/editor/lint-config-client';+import { withPreviewTabPromotion } from '@/editor/preview-tab-promotion';import {partitionFrontmatterProblems,useFrontmatterDiagnostics,@@ -109,7 +110,13 @@ export function PropertyPanel({ provider, reservedKeys, identitySlot }: Property);useEffect(() => {- const next = bindFrontmatterDoc(provider);+ // Wrapped so every mutating route — this panel's own patch/rename/reorder+ // AND the path-addressed edits nested widgets issue through+ // `FrontmatterBindingContext` — promotes the doc's preview tab.+ const next = withPreviewTabPromotion(+ bindFrontmatterDoc(provider),+ provider.configuration.name ?? '',+ );setBinding(next);setSnapshot(next.current());const unsub = next.subscribe((s) => {diff --git a/packages/app/src/components/file-tree-selection.test.ts b/packages/app/src/components/file-tree-selection.test.tsindex 33d9f807a..542ef5c60 100644--- a/packages/app/src/components/file-tree-selection.test.ts+++ b/packages/app/src/components/file-tree-selection.test.ts@@ -1,5 +1,10 @@import { describe, expect, test } from 'vitest';-import { resolveFileTreeSelection, resolveFileTreeSelectionAction } from './file-tree-selection';+import { assetTabId, docTabId } from '@/editor/editor-tabs';+import {+ previewTabIdForTreePath,+ resolveFileTreeSelection,+ resolveFileTreeSelectionAction,+} from './file-tree-selection';describe('resolveFileTreeSelection', () => {test('keeps a document row active for doc targets', () => {@@ -356,3 +361,146 @@ describe('resolveFileTreeSelectionAction — editable text assets', () => {).toMatchObject({ kind: 'asset', path: 'big/data.json' });});});++describe('previewTabIdForTreePath', () => {+ test('a markdown row resolves to its extension-less document tab', () => {+ // The row is `docs/guide.md`; the tab is `docs/guide`. Recomputing the tab+ // id from the row path instead of the resolved action would target a tab+ // that does not exist, and the double-click would silently do nothing.+ expect(+ previewTabIdForTreePath(+ 'docs/guide.md',+ [{ kind: 'document', docName: 'docs/guide', size: 0, modified: '' }],+ new Set<string>(),+ ),+ ).toBe(docTabId('docs/guide'));+ });++ test('an image row resolves to its asset tab', () => {+ expect(+ previewTabIdForTreePath(+ 'docs/photo.png',+ [+ {+ kind: 'asset',+ path: 'docs/photo.png',+ assetExt: '.png',+ mediaKind: 'image',+ size: 0,+ modified: '',+ },+ ],+ new Set<string>(),+ ),+ ).toBe(assetTabId('docs/photo.png'));+ });++ test('a mermaid row resolves to a DOCUMENT tab despite being an asset entry', () => {+ // The case that makes sharing `resolveFileTreeSelectionAction` load-bearing:+ // `.mmd` is an asset entry that opens as an editable doc, so keying the tab+ // id off the entry kind would promote the wrong tab.+ expect(+ previewTabIdForTreePath(+ 'assets/flow.mmd',+ [+ {+ kind: 'asset',+ path: 'assets/flow.mmd',+ assetExt: '.mmd',+ mediaKind: 'mermaid',+ size: 0,+ modified: '',+ },+ ],+ new Set<string>(),+ ),+ ).toBe(docTabId('assets/flow.mmd'));+ });++ test('an oversized text row resolves to its asset tab, matching where it opens', () => {+ expect(+ previewTabIdForTreePath(+ 'big/data.json',+ [+ {+ kind: 'asset',+ path: 'big/data.json',+ assetExt: '.json',+ mediaKind: 'text',+ size: 20 * 1024 * 1024,+ modified: '',+ },+ ],+ new Set<string>(),+ ),+ ).toBe(assetTabId('big/data.json'));+ });++ test('a folder row resolves to nothing', () => {+ expect(+ previewTabIdForTreePath(+ 'docs/',+ [{ kind: 'folder', path: 'docs', modified: '' }],+ new Set<string>(),+ ),+ ).toBeNull();+ });++ test('an unknown row resolves to nothing', () => {+ expect(previewTabIdForTreePath('ghost.md', [], new Set<string>())).toBeNull();+ expect(previewTabIdForTreePath(undefined, [], new Set<string>())).toBeNull();+ });+});++describe('previewTabIdForTreePath — revealed .ok rows', () => {+ // These rows are rerouted a second time by `okContentNavigationTarget`, AFTER+ // the selection action resolves. Deriving the tab id from the action alone+ // yields an id no pane owns, so the double-click is a silent no-op on exactly+ // these rows whenever "Show .ok folders" is on.+ test('a template row resolves to its managed-artifact doc tab', () => {+ expect(+ previewTabIdForTreePath(+ '.ok/templates/meeting.md',+ [+ {+ kind: 'document',+ docName: '.ok/templates/meeting',+ docExt: '.md',+ size: 0,+ modified: '',+ },+ ],+ new Set<string>(),+ ),+ ).toBe(docTabId('__template__/meeting'));+ });++ test('a non-page .ok doc row resolves to the read-only asset tab', () => {+ expect(+ previewTabIdForTreePath(+ '.ok/notes/scratch.md',+ [{ kind: 'document', docName: '.ok/notes/scratch', docExt: '.md', size: 0, modified: '' }],+ new Set<string>(),+ ),+ ).toBe(assetTabId('.ok/notes/scratch.md'));+ });++ test('an indexed .ok page keeps the ordinary doc tab', () => {+ // `pages` membership means the normal doc flow owns it — no reroute.+ expect(+ previewTabIdForTreePath(+ '.ok/skills/thing/SKILL.md',+ [+ {+ kind: 'document',+ docName: '.ok/skills/thing/SKILL',+ docExt: '.md',+ size: 0,+ modified: '',+ },+ ],+ new Set<string>(['.ok/skills/thing/SKILL']),+ ),+ ).toBe(docTabId('.ok/skills/thing/SKILL'));+ });+});diff --git a/packages/app/src/components/file-tree-selection.ts b/packages/app/src/components/file-tree-selection.tsindex 2bbbf336e..953ed5276 100644--- a/packages/app/src/components/file-tree-selection.ts+++ b/packages/app/src/components/file-tree-selection.ts@@ -4,15 +4,20 @@ import {isEditableTextDocFile,TEXT_DOC_OPEN_BYTE_LIMIT,} from '@inkeep/open-knowledge-core';+import { assetTabId, docTabId } from '@/editor/editor-tabs';import { hashFromAssetPath } from '@/lib/doc-hash';import {findEntryByTreePath,treeFilePathToDocumentDocName,treePathToAppPath,} from './file-tree-adapter';-import type { FileEntry } from './file-tree-utils';+import type { DocumentEntry, FileEntry } from './file-tree-utils';import { isAssetEntry, isDocumentEntry, isFolderEntry } from './file-tree-utils';-import { docNameForNavigationTarget, type ResolvedNavigationTarget } from './navigation-targets';+import {+ docNameForNavigationTarget,+ okContentNavigationTarget,+ type ResolvedNavigationTarget,+} from './navigation-targets';interface FileTreeSelection {selectedFilePath: string | null;@@ -146,3 +151,39 @@ export function resolveFileTreeSelectionAction(return { kind: 'document', path: appPath };}++/**+ * The editor tab id a tree row opens into, or null when the row opens no tab.+ *+ * Replays the click path's resolution rather than deriving from the row path,+ * so a double-click promotion targets exactly the tab the click created. Both+ * steps matter, because neither mapping is the obvious one:+ *+ * 1. `resolveFileTreeSelectionAction` — a `.mmd` or editable text file is an+ * asset ENTRY that opens as a DOCUMENT tab, and a markdown row's tab drops+ * the extension.+ * 2. `okContentNavigationTarget` — a revealed `.ok/**` row is rerouted again:+ * a template opens `__template__/<name>`, and any other non-page `.ok` doc+ * opens a read-only asset tab. Skipping this step yields a tab id no pane+ * owns, making the double-click a silent no-op on exactly those rows+ * whenever "Show .ok folders" is on.+ *+ * Folders return null. Their overview is reached by a gesture (expand /+ * collapse) that a double-click just performs twice.+ */+export function previewTabIdForTreePath(+ treePath: string | undefined,+ entries: readonly FileEntry[],+ pages: ReadonlySet<string>,+): string | null {+ const action = resolveFileTreeSelectionAction(treePath, entries);+ if (action.kind === 'asset') return assetTabId(action.path);+ if (action.kind !== 'document') return null;+ const docEntry = entries.find(+ (item): item is DocumentEntry => isDocumentEntry(item) && item.docName === action.path,+ );+ const okTarget = okContentNavigationTarget(action.path, { pages, docExt: docEntry?.docExt });+ if (okTarget?.kind === 'asset') return assetTabId(okTarget.assetPath);+ if (okTarget?.kind === 'doc') return docTabId(okTarget.docName);+ return docTabId(action.path);+}diff --git a/packages/app/src/editor/DocumentContext.dom.test.tsx b/packages/app/src/editor/DocumentContext.dom.test.tsxindex 971393cc6..1dc5941db 100644--- a/packages/app/src/editor/DocumentContext.dom.test.tsx+++ b/packages/app/src/editor/DocumentContext.dom.test.tsx@@ -6,6 +6,10 @@ import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';import { hashFromAssetPath } from '@/lib/doc-hash';import { emitLocalMenuAction } from '@/lib/local-menu-action-bus';import { assetTabId, docTabId, localTabSessionStorageKey, skillFileTabId } from './editor-tabs';+import {+ requestPreviewTabPromotion,+ requestPreviewTabPromotionForTab,+} from './preview-tab-promotion';let mockCollabUrl: string | null = null;@@ -496,6 +500,138 @@ function ProviderHarness({ children }: { children: ReactNode }) {return <DocumentProvider>{children}</DocumentProvider>;}+function PreviewEditHarness() {+ const ctx = useDocumentContext();+ const openPreview = (docName: string) =>+ ctx.openTarget(+ { kind: 'doc', target: docName, docName },+ { disposition: 'preview', consumeActiveNewTab: false },+ );+ return (+ <>+ <span data-testid="open-tabs">{ctx.openTabs.join('|')}</span>+ <span data-testid="preview-tab">+ {[...ctx.previewTabIdsByPane.values()].map((tabId) => tabId ?? '').join('|')}+ </span>+ <span data-testid="session-loaded">{String(ctx.tabSessionLoaded)}</span>+ <button type="button" onClick={() => openPreview('First.md')}>+ Preview first+ </button>+ <button type="button" onClick={() => openPreview('Second.md')}>+ Preview second+ </button>+ <button+ type="button"+ onClick={() =>+ ctx.openTarget(+ { kind: 'asset', target: 'LICENSE', assetPath: 'LICENSE', mediaKind: null },+ { disposition: 'preview', consumeActiveNewTab: false },+ )+ }+ >+ Preview asset+ </button>+ </>+ );+}++describe('DocumentContext preview-tab promotion on user edit', () => {+ afterEach(() => {+ cleanup();+ mockCollabUrl = null;+ globalThis.fetch = originalFetch;+ window.localStorage.clear();+ window.location.hash = '';+ });++ /** Opens bail during the restore window, so settle it before driving tabs. */+ async function renderSettled() {+ // Restore is gated on a resolved collab URL; without one `tabSessionLoaded`+ // never flips and every open stays in the restore window.+ mockCollabUrl = 'ws://localhost:1/collab';+ globalThis.fetch = vi.fn(() => Promise.reject(new Error('unexpected fetch'))) as never;+ window.localStorage.setItem(+ localTabSessionStorageKey(window.location.origin),+ JSON.stringify(+ persistedTabSession([], [], null, new Date('2026-05-13T00:00:00.000Z').toISOString()),+ ),+ );+ render(<PreviewEditHarness />, { wrapper: ProviderHarness });+ await waitFor(() => {+ expect(screen.getByTestId('session-loaded').textContent).toBe('true');+ });+ return userEvent.setup();+ }++ test('an edit promotes the preview tab, so the next sidebar click opens beside it', async () => {+ const user = await renderSettled();++ await user.click(screen.getByRole('button', { name: 'Preview first' }));+ expect(screen.getByTestId('preview-tab').textContent).toBe(docTabId('First.md'));++ // The notification the editors emit on a user-intent content change.+ act(() => {+ requestPreviewTabPromotion('First.md');+ });+ expect(screen.getByTestId('preview-tab').textContent).toBe('');++ await user.click(screen.getByRole('button', { name: 'Preview second' }));+ expect(screen.getByTestId('open-tabs').textContent).toBe(+ `${docTabId('First.md')}|${docTabId('Second.md')}`,+ );+ });++ test('without an edit the preview tab is still replaced', async () => {+ // The control. Preview replacement is correct behavior, not collateral of+ // the bug — this pins that the fix did not turn every click permanent.+ const user = await renderSettled();++ await user.click(screen.getByRole('button', { name: 'Preview first' }));+ await user.click(screen.getByRole('button', { name: 'Preview second' }));++ expect(screen.getByTestId('open-tabs').textContent).toBe(docTabId('Second.md'));+ });++ test('an edit to a document with no open tab changes nothing', async () => {+ const user = await renderSettled();++ await user.click(screen.getByRole('button', { name: 'Preview first' }));+ act(() => {+ requestPreviewTabPromotion('Unopened.md');+ });++ expect(screen.getByTestId('preview-tab').textContent).toBe(docTabId('First.md'));+ expect(screen.getByTestId('open-tabs').textContent).toBe(docTabId('First.md'));+ });++ test('the listener is torn down with the provider', () => {+ const { unmount } = render(<PreviewEditHarness />, { wrapper: ProviderHarness });+ unmount();+ // A notification arriving after teardown must not reach a disposed context.+ expect(() => requestPreviewTabPromotion('First.md')).not.toThrow();+ });++ test('a non-document preview tab promotes too, via its tab id', async () => {+ // The sidebar can preview an asset, whose tab id is NOT its document name.+ // Promotion is keyed by tab id precisely so this tab is reachable; the+ // earlier docName-only API could not address it at all.+ const user = await renderSettled();++ await user.click(screen.getByRole('button', { name: 'Preview asset' }));+ expect(screen.getByTestId('preview-tab').textContent).toBe(LICENSE_TAB_ID);++ act(() => {+ requestPreviewTabPromotionForTab(LICENSE_TAB_ID);+ });+ expect(screen.getByTestId('preview-tab').textContent).toBe('');++ await user.click(screen.getByRole('button', { name: 'Preview first' }));+ expect(screen.getByTestId('open-tabs').textContent).toBe(+ `${LICENSE_TAB_ID}|${docTabId('First.md')}`,+ );+ });+});+describe('DocumentContext tab close force contract', () => {afterEach(() => {cleanup();diff --git a/packages/app/src/editor/DocumentContext.tsx b/packages/app/src/editor/DocumentContext.tsxindex a732a3e33..78a7c3174 100644--- a/packages/app/src/editor/DocumentContext.tsx+++ b/packages/app/src/editor/DocumentContext.tsx@@ -77,6 +77,7 @@ import {tabIdForNavigationTarget,writeLocalTabSessionState,} from './editor-tabs';+import { subscribePreviewTabPromotion } from './preview-tab-promotion';import {MAX_POOL,ProviderPool,@@ -1988,6 +1989,29 @@ export function DocumentProvider({ children }: { children: ReactNode }) {);}+ /**+ * Make a tab permanent once the user commits to it, so the next sidebar click+ * opens beside it instead of replacing it.+ *+ * Guarded on the pane's current `previewTabId` before committing, because the+ * edit path calls this on every user keystroke: only the FIRST request for a+ * given preview tab reaches `commitWorkspace`, and every later one returns+ * without touching workspace state, persistence, or React.+ */+ function promotePreviewTab(tabId: string) {+ const owner = findPaneOwningTab(workspaceRef.current, tabId);+ if (!owner || owner.previewTabId !== tabId) return;+ promoteTabInPaneById(owner.id, tabId);+ }++ useEffect(+ () => subscribePreviewTabPromotion(promotePreviewTab),+ [+ // biome-ignore lint/correctness/useExhaustiveDependencies: promotePreviewTab is render-bound (React Compiler is on, so useCallback is not an option here); re-subscribing keeps the listener reading current workspace state, and the unsubscribe is identity-checked so the churn can't drop a live registration.+ promotePreviewTab,+ ],+ );+useEffect(() => {return subscribeLocalMenuAction((action) => {if (action !== 'close-active-tab-or-window') return;diff --git a/packages/app/src/editor/SourceEditor.tsx b/packages/app/src/editor/SourceEditor.tsxindex 6ffafcd4a..5cc85641d 100644--- a/packages/app/src/editor/SourceEditor.tsx+++ b/packages/app/src/editor/SourceEditor.tsx@@ -32,6 +32,7 @@ import { startSourceLanding } from './mode-switch-landing';import { getMountId } from './mount-id-registry';import { markUserTyping } from './observers';import { landingFlashSource } from './plugins/landing-flash-source';+import { isUserIntentCmUpdate, requestPreviewTabPromotion } from './preview-tab-promotion';import { claimScrollerForNavigation, runScrollNavigation } from './scroll-restore-coordination';import { publishSelectionContext, selectionSnapshotFromSource } from './selection-context';import {@@ -247,6 +248,7 @@ export function SourceEditor({const sourceClipboard = createSourceClipboardExtension({ydoc: provider.document,ytext,+ docName: resolvedDocName,});// Created here (not as component refs) so they live with the cached// view — see the compartment note above and `CmCacheEntry`.@@ -311,6 +313,15 @@ export function SourceEditor({landingFlashSource(),lintCompartment.of(createMarkdownLintExtension(linterConfig, docName)),sourceClipboard,+ // A user edit promotes this doc's preview tab to permanent. Safe to+ // capture `resolvedDocName` in the closure even though the view+ // outlives this component: the view is bound to one doc's Y.Text+ // for its whole lifetime, and the promotion itself is dispatched+ // through a module-level listener rather than a captured callback.+ EditorView.updateListener.of((update) => {+ if (!isUserIntentCmUpdate(update)) return;+ requestPreviewTabPromotion(resolvedDocName);+ }),EditorView.updateListener.of((update) => {if (!update.selectionSet && !update.docChanged) return;if (selectionStatsTimer !== null) clearTimeout(selectionStatsTimer);diff --git a/packages/app/src/editor/TiptapEditor.tsx b/packages/app/src/editor/TiptapEditor.tsxindex 0edab664a..52c92fbc2 100644--- a/packages/app/src/editor/TiptapEditor.tsx+++ b/packages/app/src/editor/TiptapEditor.tsx@@ -75,6 +75,7 @@ import {computeChangedRange,createAgentInsertFlashPlugin,} from './plugins/agent-insert-flash';+import { isUserIntentPmTransaction, requestPreviewTabPromotion } from './preview-tab-promotion';import { isScrollRestoreSuppressed, runScrollNavigation } from './scroll-restore-coordination';import { publishSelectionContext, selectionSnapshotFromWysiwyg } from './selection-context';import {@@ -459,7 +460,7 @@ export function buildExtensionList(args: BuildEditorOptionsArgs): AnyExtension[]MarkdownLintDecorations.configure({docName: provider.configuration.name ?? '',getSource: () => provider.document.getText('source').toString(),- applyFix: (fixes) => applyLintFixes(provider, fixes),+ applyFix: (fixes) => applyLintFixes(provider, fixes, provider.configuration.name ?? ''),}),];}@@ -1023,6 +1024,23 @@ const TiptapEditorChrome: FC<TiptapEditorChromeProps> = ({};}, [editor]);+ // A user edit promotes this doc's preview tab to permanent. Listens for the+ // content change rather than the keystroke: arrow keys, Escape and Cmd+C all+ // reach the DOM handlers above but leave the document untouched, and a tab+ // the user only navigated around is still provisional.+ useEffect(() => {+ const docName = provider.configuration.name;+ if (!docName) return;+ const onTransaction = ({ transaction }: { transaction: PMTransaction }) => {+ if (!isUserIntentPmTransaction(transaction)) return;+ requestPreviewTabPromotion(docName);+ };+ editor.on('transaction', onTransaction);+ return () => {+ editor.off('transaction', onTransaction);+ };+ }, [editor, provider]);+// Rename-snapshot consumption — one-shot, on the editor's first `'create'`.// The rename snapshot (HTML + scrollTop + selection, see editor-cache.ts)// is keyed by docName; this effect consumes it in two steps:diff --git a/packages/app/src/editor/apply-lint-fix.test.ts b/packages/app/src/editor/apply-lint-fix.test.tsindex e8bb33ff3..dd4b0d961 100644--- a/packages/app/src/editor/apply-lint-fix.test.ts+++ b/packages/app/src/editor/apply-lint-fix.test.ts@@ -1,7 +1,8 @@import type { LintDiagnostic, LintTextEdit } from '@inkeep/open-knowledge-core';-import { describe, expect, test } from 'vitest';+import { afterEach, describe, expect, test, vi } from 'vitest';import * as Y from 'yjs';import { applyLintFixes, collectFixes, LINT_SOURCE_FIXED_EVENT } from './apply-lint-fix.ts';+import { subscribePreviewTabPromotion } from './preview-tab-promotion';function docWith(source: string): Y.Doc {const doc = new Y.Doc();@@ -35,19 +36,19 @@ describe('applyLintFixes', () => {test('removes a trailing-space run (MD009-style, single-line delete)', () => {const doc = docWith('# Title\n\nParagraph here. \n');// line 2 (0-based), delete the 3 trailing spaces at chars 15..18.- applyLintFixes({ document: doc }, [edit(2, 15, 2, 18, '')]);+ applyLintFixes({ document: doc }, [edit(2, 15, 2, 18, '')], 'doc');expect(doc.getText('source').toString()).toBe('# Title\n\nParagraph here.\n');});test('replaces a hard tab (MD010-style, insert replaces range)', () => {const doc = docWith('a\tb\n');- applyLintFixes({ document: doc }, [edit(0, 1, 0, 2, ' ')]);+ applyLintFixes({ document: doc }, [edit(0, 1, 0, 2, ' ')], 'doc');expect(doc.getText('source').toString()).toBe('a b\n');});test('applies multiple edits high→low without offset drift', () => {const doc = docWith('x \ny \n'); // trailing spaces on two lines- applyLintFixes({ document: doc }, [edit(0, 1, 0, 4, ''), edit(1, 1, 1, 4, '')]);+ applyLintFixes({ document: doc }, [edit(0, 1, 0, 4, ''), edit(1, 1, 1, 4, '')], 'doc');expect(doc.getText('source').toString()).toBe('x\ny\n');});@@ -60,14 +61,14 @@ describe('applyLintFixes', () => {doc.on('update', () => {updates += 1;});- applyLintFixes({ document: doc }, [edit(0, 1, 0, 4, ''), edit(1, 1, 1, 4, '')]);+ applyLintFixes({ document: doc }, [edit(0, 1, 0, 4, ''), edit(1, 1, 1, 4, '')], 'doc');expect(updates).toBe(1);expect(doc.getText('source').toString()).toBe('x\ny\n');});test('empty fix list is a no-op returning false', () => {const doc = docWith('unchanged\n');- expect(applyLintFixes({ document: doc }, [])).toBe(false);+ expect(applyLintFixes({ document: doc }, [], 'doc')).toBe(false);expect(doc.getText('source').toString()).toBe('unchanged\n');});@@ -75,7 +76,7 @@ describe('applyLintFixes', () => {// MD047 (missing trailing newline) produces a pure-insertion fix: an edit// whose range is empty (start === end) with non-empty newText.const doc = docWith('# Heading');- applyLintFixes({ document: doc }, [edit(0, 9, 0, 9, '\n')]);+ applyLintFixes({ document: doc }, [edit(0, 9, 0, 9, '\n')], 'doc');expect(doc.getText('source').toString()).toBe('# Heading\n');});@@ -85,7 +86,7 @@ describe('applyLintFixes', () => {// N + 1, character: 0 } }. Exercises offsetOf's newline arithmetic across// a line boundary — a wrong byte count here would corrupt the shared Y.Text.const doc = docWith('# Title\n\npara\n\n\nextra blank\n');- applyLintFixes({ document: doc }, [edit(3, 0, 4, 0, '')]);+ applyLintFixes({ document: doc }, [edit(3, 0, 4, 0, '')], 'doc');expect(doc.getText('source').toString()).toBe('# Title\n\npara\n\nextra blank\n');});@@ -93,7 +94,7 @@ describe('applyLintFixes', () => {// Two diagnostics (e.g. two rules flagging the same run) can carry// byte-identical fixes; compounding them would delete twice.const doc = docWith('a\tb\n');- applyLintFixes({ document: doc }, [edit(0, 1, 0, 2, ' '), edit(0, 1, 0, 2, ' ')]);+ applyLintFixes({ document: doc }, [edit(0, 1, 0, 2, ' '), edit(0, 1, 0, 2, ' ')], 'doc');expect(doc.getText('source').toString()).toBe('a b\n');});@@ -103,28 +104,36 @@ describe('applyLintFixes', () => {// applyFixes skips the overlapped fix; the skipped issue re-surfaces on// the post-fix re-lint.const doc = docWith('keep\nx\ty\nkeep\n');- applyLintFixes({ document: doc }, [- edit(1, 0, 2, 0, ''), // delete line 1 entirely- edit(1, 1, 1, 2, ' '), // replace the tab inside line 1- ]);+ applyLintFixes(+ { document: doc },+ [+ edit(1, 0, 2, 0, ''), // delete line 1 entirely+ edit(1, 1, 1, 2, ' '), // replace the tab inside line 1+ ],+ 'doc',+ );expect(doc.getText('source').toString()).toBe('keep\nkeep\n');});test('applies touching (end-exclusive adjacent) edits from different diagnostics', () => {// [2,3) and [1,2) touch at offset 2 but do not overlap — both must land.const doc = docWith('a\t\tb\n');- applyLintFixes({ document: doc }, [edit(0, 1, 0, 2, ' '), edit(0, 2, 0, 3, ' ')]);+ applyLintFixes({ document: doc }, [edit(0, 1, 0, 2, ' '), edit(0, 2, 0, 3, ' ')], 'doc');expect(doc.getText('source').toString()).toBe('a b\n');});test('multi-diagnostic combination applies all non-conflicting fixes', () => {const doc = docWith('a\tb \n\n\npara');- applyLintFixes({ document: doc }, [- edit(0, 1, 0, 2, ' '), // MD010 hard tab- edit(0, 3, 0, 6, ''), // MD009 trailing spaces- edit(2, 0, 3, 0, ''), // MD012 extra blank line- edit(3, 4, 3, 4, '\n'), // MD047 trailing newline- ]);+ applyLintFixes(+ { document: doc },+ [+ edit(0, 1, 0, 2, ' '), // MD010 hard tab+ edit(0, 3, 0, 6, ''), // MD009 trailing spaces+ edit(2, 0, 3, 0, ''), // MD012 extra blank line+ edit(3, 4, 3, 4, '\n'), // MD047 trailing newline+ ],+ 'doc',+ );expect(doc.getText('source').toString()).toBe('a b\n\npara\n');});@@ -134,7 +143,7 @@ describe('applyLintFixes', () => {win.addEventListener(LINT_SOURCE_FIXED_EVENT, () => {fired += 1;});- applyLintFixes({ document: docWith('a\tb\n') }, [edit(0, 1, 0, 2, ' ')]);+ applyLintFixes({ document: docWith('a\tb\n') }, [edit(0, 1, 0, 2, ' ')], 'doc');});expect(fired).toBe(1);});@@ -145,7 +154,7 @@ describe('applyLintFixes', () => {win.addEventListener(LINT_SOURCE_FIXED_EVENT, () => {fired += 1;});- applyLintFixes({ document: docWith('unchanged\n') }, []);+ applyLintFixes({ document: docWith('unchanged\n') }, [], 'doc');});expect(fired).toBe(0);});@@ -165,3 +174,51 @@ describe('collectFixes', () => {expect(collectFixes([fixable, plain])).toHaveLength(1);});});++describe('applyLintFixes — preview-tab promotion', () => {+ // The write lands straight in Y.Text under LINT_FIX_ORIGIN: the WYSIWYG+ // editor sees it carrying sync meta, the source editor with no `userEvent`,+ // so both origin guards reject it. Announcing from the write side is the only+ // way clicking Fix promotes the tab.+ let unsubscribe: (() => void) | undefined;++ afterEach(() => {+ unsubscribe?.();+ unsubscribe = undefined;+ });++ test('a fix that lands announces the doc', () => {+ const promoted = vi.fn();+ unsubscribe = subscribePreviewTabPromotion(promoted);+ const doc = docWith('a\t\tb\n');++ applyLintFixes({ document: doc }, [edit(0, 1, 0, 2, ' ')], 'notes/thing');++ expect(promoted).toHaveBeenCalledWith('notes/thing');+ });++ test('an empty fix list announces nothing', () => {+ const promoted = vi.fn();+ unsubscribe = subscribePreviewTabPromotion(promoted);+ const doc = docWith('unchanged\n');++ applyLintFixes({ document: doc }, [], 'notes/thing');++ expect(promoted).not.toHaveBeenCalled();+ });++ test('a no-op edit still counts as applied, matching the return value', () => {+ // An out-of-range edit clamps to a zero-width no-op. It is still counted,+ // so the announce and the `true` return agree — a user who clicked Fix on a+ // stale diagnostic gets a promoted tab rather than a silent divergence+ // between what the function reports and what it announces.+ const promoted = vi.fn();+ unsubscribe = subscribePreviewTabPromotion(promoted);+ const doc = docWith('keep\n');++ const applied = applyLintFixes({ document: doc }, [edit(9, 0, 9, 0, '')], 'notes/thing');++ expect(applied).toBe(true);+ expect(promoted).toHaveBeenCalledWith('notes/thing');+ });+});diff --git a/packages/app/src/editor/apply-lint-fix.ts b/packages/app/src/editor/apply-lint-fix.tsindex 5baa3cea1..58025b9dc 100644--- a/packages/app/src/editor/apply-lint-fix.ts+++ b/packages/app/src/editor/apply-lint-fix.ts@@ -9,6 +9,7 @@import type { LintDiagnostic, LintPosition, LintTextEdit } from '@inkeep/open-knowledge-core';import type * as Y from 'yjs';+import { requestPreviewTabPromotion } from './preview-tab-promotion';/** Minimal provider shape — just the Y.Doc, so this stays test-friendly. */export interface SourceWriteProvider {@@ -65,6 +66,7 @@ export function collectFixes(diagnostics: readonly LintDiagnostic[]): LintTextEdexport function applyLintFixes(provider: SourceWriteProvider,fixes: readonly LintTextEdit[],+ docName: string,): boolean {if (fixes.length === 0) return false;const ytext = provider.document.getText('source');@@ -79,6 +81,7 @@ export function applyLintFixes(// inside it — the container applies, the swallowed edit skips. For// non-overlapping edits this is the same high→low order as from-desc..sort((a, b) => b.to - a.to || b.from - a.from || a.insert.localeCompare(b.insert));+ let appliedCount = 0;provider.document.transact(() => {let lowestAppliedFrom = Number.POSITIVE_INFINITY;let previous: (typeof edits)[number] | undefined;@@ -93,8 +96,15 @@ export function applyLintFixes(if (edit.to > edit.from) ytext.delete(edit.from, edit.to - edit.from);if (edit.insert.length > 0) ytext.insert(edit.from, edit.insert);lowestAppliedFrom = edit.from;+ appliedCount += 1;}}, LINT_FIX_ORIGIN);+ // Clicking Fix is the user committing to this document, but the write goes+ // straight to Y.Text — it reaches the WYSIWYG editor carrying sync meta and+ // the source editor with no `userEvent`, so both origin guards correctly+ // reject it and no editor can attribute it. Announce from the write side,+ // like the frontmatter binding wrapper, and only for a write that landed.+ if (appliedCount > 0) requestPreviewTabPromotion(docName);// Nudge any mounted WYSIWYG lint decoration to re-lint — a source-only fix// leaves the PM doc unchanged, so its PM-driven recompute never fires.if (typeof window !== 'undefined') {diff --git a/packages/app/src/editor/clipboard/source-clipboard.test.ts b/packages/app/src/editor/clipboard/source-clipboard.test.tsindex dbbd5d7b8..4735cd6e5 100644--- a/packages/app/src/editor/clipboard/source-clipboard.test.ts+++ b/packages/app/src/editor/clipboard/source-clipboard.test.ts@@ -287,6 +287,11 @@ describe('handleCopyOrCut — empty-selection no-op + wrapper integration', () =expect(view.dispatchCalls).toHaveLength(1);expect(view.dispatchCalls[0]).toEqual({changes: { from: 3, to: 3 + markdown.length, insert: '' },+ // `userEvent` is load-bearing beyond CodeMirror's undo grouping: the+ // preview-tab origin guard admits only annotated dispatches, so dropping+ // it makes a source-mode cut read as CRDT sync and the edited tab stays+ // provisional — losing it on the next sidebar click.+ userEvent: 'delete.cut',});// Clipboard payloads still written, same as copy.expect(dt.data['text/plain']).toBe(markdown);@@ -383,6 +388,11 @@ describe('handlePaste — source mode paste dispatch', () => {expect(handled).toBe(true);expect(event.prevented).toBe(true);expect(view.dispatchCalls).toHaveLength(1);+ // Pinned for the same reason the cut test pins `delete.cut`: the annotation+ // is the only signal that makes the preview-tab origin guard admit this as+ // a user edit, so dropping it would break paste promotion while leaving+ // every other assertion here green.+ expect(view.dispatchCalls[0]).toMatchObject({ userEvent: 'input.paste' });});test('source-mode wrapper with no text/plain routes through Branch D', () => {diff --git a/packages/app/src/editor/clipboard/source-clipboard.ts b/packages/app/src/editor/clipboard/source-clipboard.tsindex 3697fad38..487ae097c 100644--- a/packages/app/src/editor/clipboard/source-clipboard.ts+++ b/packages/app/src/editor/clipboard/source-clipboard.ts@@ -47,6 +47,7 @@ import {import { t } from '@lingui/core/macro';import { toast } from 'sonner';import * as Y from 'yjs';+import { requestPreviewTabPromotion } from '../preview-tab-promotion.ts';import { type ClipboardSource, detectSource } from './detect-source.ts';import {classifyError,@@ -75,6 +76,13 @@ const SOURCE_PASTE_ORIGIN = Object.freeze({export interface SourceClipboardDeps {ydoc: Y.Doc;ytext: Y.Text;+ /**+ * The document this view edits. Needed because the chunked large-paste path+ * writes Y.Text directly rather than dispatching to the view, so no editor+ * origin guard can attribute the write and the preview tab has to be+ * promoted from here.+ */+ docName: string;}/**@@ -174,7 +182,11 @@ export function handleCopyOrCut(}event.preventDefault();if (kind === 'cut') {- view.dispatch({ changes: { from, to, insert: '' } });+ // `userEvent` is CodeMirror-canonical for a cut, and load-bearing beyond+ // undo grouping: the preview-tab origin guard admits only annotated+ // dispatches, so an unstamped cut reads as CRDT sync and leaves the tab+ // provisional — losing it on the next sidebar click.+ view.dispatch({ changes: { from, to, insert: '' }, userEvent: 'delete.cut' });}logIfSlow(start, { op: kind, view: 'source', branch: 'serialize', source: 'local' });return true;@@ -339,6 +351,9 @@ function tryBranchDHtml(view.dispatch({changes: { from, to, insert: markdown },selection: { anchor: from + markdown.length },+ // See the cut above: without the annotation this reads as sync to the+ // preview-tab origin guard and the pasted-into tab stays provisional.+ userEvent: 'input.paste',});return true;}@@ -357,8 +372,13 @@ function tryBranchDHtml(// behind — see `handleChunkedInsertFailure` below.const restoreText = from === to ? '' : view.state.sliceDoc(from, to);if (from !== to) {- view.dispatch({ changes: { from, to, insert: '' } });+ view.dispatch({ changes: { from, to, insert: '' }, userEvent: 'input.paste' });}+ // The chunks below land in Y.Text without passing through the view, so the+ // source editor's origin guard never sees them — and with no selection to+ // delete, the dispatch above doesn't run either. Announce the commit here so+ // a large paste promotes the tab like every smaller one.+ requestPreviewTabPromotion(deps.docName);const anchorIndex = from;// `assoc = 0` (default) is left-binding: concurrent inserts AT anchorIndex// leave our anchor at the original spot, so their content lands AFTER ourdiff --git a/packages/app/src/editor/editor-panes.test.ts b/packages/app/src/editor/editor-panes.test.tsindex b3cf06c19..556e4d409 100644--- a/packages/app/src/editor/editor-panes.test.ts+++ b/packages/app/src/editor/editor-panes.test.ts@@ -536,6 +536,75 @@ describe('editor pane workspace', () => {});});+ test('an edited preview tab survives opening the next file; an untouched one is replaced', () => {+ // The two halves of the sidebar contract. Click a file, click another: the+ // first is provisional and gives up its slot. Click a file, EDIT it, click+ // another: the edit promoted it, so it stays open. The edited bytes were+ // never at risk (they live in the CRDT), but the tab vanishing read as+ // lost work.+ const opened: EditorWorkspaceState = transitionEditorWorkspace(+ { panes: [pane('pane-a', [], null)], focusedPaneId: 'pane-a' },+ {+ type: 'open-target',+ paneId: 'pane-a',+ tabId: 'first',+ target: docTarget('first'),+ disposition: 'preview',+ consumeActiveNewTab: false,+ },+ ).workspace;+ expect(opened.panes[0]?.previewTabId).toBe('first');++ const openSecond = (workspace: EditorWorkspaceState) =>+ transitionEditorWorkspace(workspace, {+ type: 'open-target',+ paneId: 'pane-a',+ tabId: 'second',+ target: docTarget('second'),+ disposition: 'preview',+ consumeActiveNewTab: false,+ }).workspace;++ // Untouched: the preview slot is reused, so `first` is gone.+ expect(openSecond(opened).panes[0]?.openTabs).toEqual(['second']);++ // Edited: `promote-preview` is what the user-edit listener dispatches.+ const edited = transitionEditorWorkspace(opened, {+ type: 'promote-preview',+ paneId: 'pane-a',+ tabId: 'first',+ }).workspace;+ expect(edited.panes[0]?.previewTabId).toBeNull();++ const afterSecond = openSecond(edited).panes[0];+ expect(afterSecond?.openTabs).toEqual(['first', 'second']);+ expect(afterSecond?.activeTabId).toBe('second');+ // `second` takes the slot `first` vacated, so it stays provisional itself.+ expect(afterSecond?.previewTabId).toBe('second');+ });++ test('promoting a tab that is not the pane preview leaves the preview alone', () => {+ // The listener fires on every user keystroke, so the no-match path is the+ // common one — it must not clear a different tab's preview state.+ const workspace: EditorWorkspaceState = {+ panes: [+ {+ ...pane('pane-a', ['permanent', 'preview'], 'permanent'),+ previewTabId: 'preview',+ },+ ],+ focusedPaneId: 'pane-a',+ };++ const after = transitionEditorWorkspace(workspace, {+ type: 'promote-preview',+ paneId: 'pane-a',+ tabId: 'permanent',+ }).workspace;++ expect(after.panes[0]?.previewTabId).toBe('preview');+ });+test('promotes an existing preview for permanent intent and never demotes a permanent tab', () => {const workspace: EditorWorkspaceState = {panes: [diff --git a/packages/app/src/editor/frontmatter-binding-promotion.test.ts b/packages/app/src/editor/frontmatter-binding-promotion.test.tsnew file mode 100644index 000000000..cb6cd5821--- /dev/null+++ b/packages/app/src/editor/frontmatter-binding-promotion.test.ts@@ -0,0 +1,135 @@+/**+ * The frontmatter-binding wrapper's coverage contract.+ *+ * The panel mutates frontmatter through eight methods reached from three+ * different trees, so the promotion is wired by wrapping the binding once+ * rather than by notifying at each call site. That only stays true if the+ * wrapper keeps up with the binding — hence the exhaustiveness test below,+ * which fails when `FrontmatterBinding` grows a method the wrapper doesn't+ * know about, instead of letting a new mutator silently stop promoting.+ */++import { bindFrontmatterDoc, type FrontmatterBinding } from '@inkeep/open-knowledge-core';+import { afterEach, describe, expect, test, vi } from 'vitest';+import * as Y from 'yjs';+import {+ MUTATING_BINDING_METHODS,+ READ_ONLY_BINDING_METHODS,+ subscribePreviewTabPromotion,+ withPreviewTabPromotion,+} from './preview-tab-promotion';++let unsubscribePromotion: (() => void) | undefined;++/**+ * `bindFrontmatterDoc` reaches only `document` plus the `synced` event hooks,+ * so a Y.Doc with no-op emitters stands in — a real HocuspocusProvider would+ * open a socket.+ */+function makeBinding(seed: string): FrontmatterBinding {+ const doc = new Y.Doc();+ const ytext = doc.getText('source');+ doc.transact(() => ytext.insert(0, seed));+ return bindFrontmatterDoc({ document: doc, on: () => {}, off: () => {} } as never);+}++afterEach(() => {+ unsubscribePromotion?.();+});++describe('withPreviewTabPromotion — coverage', () => {+ test('every method on the binding is either wrapped as mutating or listed read-only', () => {+ const binding = makeBinding('---\ntitle: Draft\n---\n');+ const methods = Object.entries(binding)+ .filter(([, value]) => typeof value === 'function')+ .map(([key]) => key)+ .sort();++ const accounted = [...MUTATING_BINDING_METHODS, ...READ_ONLY_BINDING_METHODS].sort();++ // If this fails, `FrontmatterBinding` gained a method. Decide whether it+ // mutates: add it to MUTATING_BINDING_METHODS and to the wrapper, or to+ // READ_ONLY_BINDING_METHODS.+ expect(methods).toEqual(accounted);+ binding.dispose();+ });++ test('the wrapper exposes every method the raw binding does', () => {+ const binding = makeBinding('---\ntitle: Draft\n---\n');+ const wrapped = withPreviewTabPromotion(binding, 'doc');++ for (const key of Object.keys(binding)) {+ expect(wrapped).toHaveProperty(key);+ }+ binding.dispose();+ });+});++describe('withPreviewTabPromotion — announcement', () => {+ test('a successful mutation announces exactly once', () => {+ const onUserEdit = vi.fn();+ unsubscribePromotion = subscribePreviewTabPromotion(onUserEdit);+ const binding = makeBinding('---\ntitle: Draft\n---\n');+ const wrapped = withPreviewTabPromotion(binding, 'notes/thing');++ const result = wrapped.patch({ title: 'Published' });++ expect(result.ok).toBe(true);+ expect(onUserEdit).toHaveBeenCalledExactlyOnceWith('notes/thing');+ binding.dispose();+ });++ test('a nested path edit announces — this is the route that bypassed the panel', () => {+ const onUserEdit = vi.fn();+ unsubscribePromotion = subscribePreviewTabPromotion(onUserEdit);+ const binding = makeBinding('---\nmetadata:\n version: "1.0.0"\n---\n');+ const wrapped = withPreviewTabPromotion(binding, 'notes/thing');++ const result = wrapped.patchPath(['metadata', 'version'], '2.0.0');++ expect(result.ok).toBe(true);+ expect(onUserEdit).toHaveBeenCalledWith('notes/thing');+ binding.dispose();+ });++ test('a rejected mutation announces nothing', () => {+ const onUserEdit = vi.fn();+ unsubscribePromotion = subscribePreviewTabPromotion(onUserEdit);+ const binding = makeBinding('---\ntitle: Draft\n---\n');+ const wrapped = withPreviewTabPromotion(binding, 'notes/thing');++ // `frontmatter` is the reserved key the binding rejects with SCHEMA_INVALID.+ const result = wrapped.patch({ frontmatter: 'nope' });++ expect(result.ok).toBe(false);+ expect(onUserEdit).not.toHaveBeenCalled();+ binding.dispose();+ });++ test('reads announce nothing', () => {+ const onUserEdit = vi.fn();+ unsubscribePromotion = subscribePreviewTabPromotion(onUserEdit);+ const binding = makeBinding('---\ntitle: Draft\n---\n');+ const wrapped = withPreviewTabPromotion(binding, 'notes/thing');++ wrapped.current();+ const unsub = wrapped.subscribe(() => {});+ unsub();++ expect(onUserEdit).not.toHaveBeenCalled();+ binding.dispose();+ });++ test('the wrapped binding still returns the raw result to its caller', () => {+ const binding = makeBinding('---\ntitle: Draft\n---\n');+ const wrapped = withPreviewTabPromotion(binding, 'notes/thing');++ const result = wrapped.patch({ title: 'Published' });++ // The panel branches on `appliedKeys` / `error`, so the wrapper must be+ // transparent, not merely truthy.+ expect(result).toMatchObject({ ok: true, appliedKeys: ['title'] });+ expect(wrapped.current().map.title).toBe('Published');+ binding.dispose();+ });+});diff --git a/packages/app/src/editor/preview-tab-promotion.test.ts b/packages/app/src/editor/preview-tab-promotion.test.tsnew file mode 100644index 000000000..5ab1e4ca8--- /dev/null+++ b/packages/app/src/editor/preview-tab-promotion.test.ts@@ -0,0 +1,146 @@+import { Annotation, Transaction as CMTransaction, EditorState } from '@codemirror/state';+import type { ViewUpdate } from '@codemirror/view';+import { ySyncPluginKey } from '@tiptap/y-tiptap';+import { afterEach, describe, expect, test, vi } from 'vitest';+import {+ isUserIntentCmUpdate,+ isUserIntentPmTransaction,+ requestPreviewTabPromotion,+ subscribePreviewTabPromotion,+} from './preview-tab-promotion';++let unsubscribePromotion: (() => void) | undefined;++/**+ * Minimal PM-transaction stand-in. The predicate reads exactly two properties,+ * and a real ProseMirror transaction needs a schema + doc that add nothing to+ * what is under test.+ */+function pmTransaction(docChanged: boolean, syncMeta?: unknown) {+ return {+ docChanged,+ getMeta: (key: unknown) => (key === ySyncPluginKey ? syncMeta : undefined),+ } as unknown as Parameters<typeof isUserIntentPmTransaction>[0];+}++/** A ViewUpdate stand-in carrying just the fields the predicate reads. */+function cmUpdate(docChanged: boolean, userEvents: (string | undefined)[]): ViewUpdate {+ return {+ docChanged,+ transactions: userEvents.map((userEvent) => ({+ annotation: (type: unknown) => (type === CMTransaction.userEvent ? userEvent : undefined),+ })),+ } as unknown as ViewUpdate;+}++afterEach(() => {+ unsubscribePromotion?.();+});++describe('isUserIntentPmTransaction', () => {+ test('a local content change with no sync meta is a user edit', () => {+ expect(isUserIntentPmTransaction(pmTransaction(true))).toBe(true);+ });++ test('a CRDT-origin change is not — this is what keeps agent writes from promoting', () => {+ expect(isUserIntentPmTransaction(pmTransaction(true, { isChangeOrigin: true }))).toBe(false);+ });++ test('selection-only transactions are not edits', () => {+ // Arrow keys and clicks produce these constantly; promoting on them would+ // make every previewed doc permanent the moment it took focus.+ expect(isUserIntentPmTransaction(pmTransaction(false))).toBe(false);+ });++ test('any present sync meta counts as sync, whatever its shape', () => {+ // The guard tests for the meta's presence, not for `isChangeOrigin`. That+ // is deliberate: it fails closed, so a y-prosemirror change to the meta+ // payload costs a missed promotion rather than a tab promoted by an agent.+ expect(isUserIntentPmTransaction(pmTransaction(true, {}))).toBe(false);+ expect(isUserIntentPmTransaction(pmTransaction(true, { isChangeOrigin: false }))).toBe(false);+ });+});++describe('isUserIntentCmUpdate', () => {+ test('a typed character is a user edit', () => {+ expect(isUserIntentCmUpdate(cmUpdate(true, ['input.type']))).toBe(true);+ });++ test('paste and delete are user edits', () => {+ expect(isUserIntentCmUpdate(cmUpdate(true, ['input.paste']))).toBe(true);+ expect(isUserIntentCmUpdate(cmUpdate(true, ['delete.backward']))).toBe(true);+ });++ test('a y-codemirror sync dispatch carries no userEvent, so it is not', () => {+ expect(isUserIntentCmUpdate(cmUpdate(true, [undefined]))).toBe(false);+ });++ test('selection-only updates are not edits', () => {+ expect(isUserIntentCmUpdate(cmUpdate(false, ['select.pointer']))).toBe(false);+ });++ test('a mixed update promotes when any transaction is user-driven', () => {+ expect(isUserIntentCmUpdate(cmUpdate(true, [undefined, 'input.type']))).toBe(true);+ });+});++describe('isUserIntentCmUpdate against real CodeMirror transactions', () => {+ // Pins the predicate to CodeMirror's actual annotation plumbing rather than+ // the hand-rolled stand-in above, so an upstream change to how userEvent is+ // carried fails here instead of silently disabling promotion.+ const state = EditorState.create({ doc: 'hello' });++ test('a userEvent-annotated change is detected', () => {+ const transaction = state.update({+ changes: { from: 5, insert: '!' },+ userEvent: 'input.type',+ });+ expect(isUserIntentCmUpdate(cmUpdateFrom(transaction))).toBe(true);+ });++ test('a programmatic change with a foreign annotation is not', () => {+ const foreign = Annotation.define<string>();+ const transaction = state.update({+ changes: { from: 5, insert: '!' },+ annotations: foreign.of('sync'),+ });+ expect(isUserIntentCmUpdate(cmUpdateFrom(transaction))).toBe(false);+ });++ function cmUpdateFrom(transaction: ReturnType<typeof state.update>): ViewUpdate {+ return {+ docChanged: transaction.docChanged,+ transactions: [transaction],+ } as unknown as ViewUpdate;+ }+});++describe('the user-edit listener', () => {+ test('notifications reach the registered listener', () => {+ const listener = vi.fn();+ unsubscribePromotion = subscribePreviewTabPromotion(listener);+ requestPreviewTabPromotion('docs/notes');+ expect(listener).toHaveBeenCalledWith('docs/notes');+ });++ test('unregistering stops delivery', () => {+ const listener = vi.fn();+ unsubscribePromotion = subscribePreviewTabPromotion(listener);+ unsubscribePromotion?.();+ requestPreviewTabPromotion('docs/notes');+ expect(listener).not.toHaveBeenCalled();+ });++ test('an empty docName is dropped rather than forwarded', () => {+ // A provider mid-teardown reports an empty name; forwarding it would make+ // the consumer resolve a tab id of "".+ const listener = vi.fn();+ unsubscribePromotion = subscribePreviewTabPromotion(listener);+ requestPreviewTabPromotion('');+ expect(listener).not.toHaveBeenCalled();+ });++ test('notifying with no listener registered is a no-op', () => {+ expect(() => requestPreviewTabPromotion('docs/notes')).not.toThrow();+ });+});diff --git a/packages/app/src/editor/preview-tab-promotion.ts b/packages/app/src/editor/preview-tab-promotion.tsnew file mode 100644index 000000000..1956bc070--- /dev/null+++ b/packages/app/src/editor/preview-tab-promotion.ts@@ -0,0 +1,190 @@+/**+ * Preview-tab promotion.+ *+ * A preview tab (single-click from the sidebar, italic label) is provisional:+ * opening another target reuses its slot. Committing to the document makes the+ * tab permanent. Without that the bytes survive — they are CRDT state,+ * persisted independently of the tab — but the tab vanishes on the next sidebar+ * click, which reads as lost work.+ *+ * What counts as committing:+ *+ * - editing the body, in WYSIWYG or source mode+ * - editing frontmatter through the property panel (see+ * {@link withPreviewTabPromotion})+ * - switching the doc between source and WYSIWYG+ * - double-clicking its row in the sidebar, or its tab+ *+ * The last two change no bytes, which is why this is named for its EFFECT+ * rather than for an edit — callers request a promotion, they don't report a+ * mutation. Anything the user does that says "I mean to keep working here"+ * belongs on that list; anything else does not.+ *+ * Agent and remote-peer writes deliberately do NOT promote. A tab you are only+ * reading must not become permanent because something else wrote to the+ * document.+ *+ * The listener indirection exists because both editor views outlive the React+ * components that mount them — the editor cache reparents a cached view across+ * Activity flips rather than destroying it, so a closure over a context method+ * captured at construction goes stale. Module-level state that survives React+ * remounts is the shared shape with `active-editor.ts` and the other+ * `subscribe*` registries; the slot here is single-consumer rather than a+ * listener set (see `subscribePreviewTabPromotion`).+ */++import { Transaction as CMTransaction } from '@codemirror/state';+import type { ViewUpdate } from '@codemirror/view';+import type { FrontmatterBinding } from '@inkeep/open-knowledge-core';+import type { Transaction as PMTransaction } from '@tiptap/pm/state';+// Sourced from `@tiptap/y-tiptap`, never `y-prosemirror` directly: the origin+// guard below compares against the PluginKey identity the y-prosemirror sync+// plugin used when it stamped the meta. A second PluginKey instance silently+// matches nothing, which would classify every CRDT-origin transaction as a user+// edit and promote tabs on agent writes. Aligns with source-dirty-observer.ts,+// bridge-id-plugin.ts, and editor-cache.ts.+import { ySyncPluginKey } from '@tiptap/y-tiptap';+import { docTabId } from './editor-tabs';++type PreviewTabPromotionListener = (tabId: string) => void;++let listener: PreviewTabPromotionListener | null = null;++/**+ * Register the single consumer of promotion requests (DocumentContext); the+ * returned function unregisters it, so a React caller can return it straight+ * from `useEffect`.+ *+ * Single-slot rather than a listener set: there is one DocumentContext per+ * window and one workspace for it to mutate, so a second consumer would mean+ * two writers racing on the same pane state. Unsubscribing only clears the slot+ * when it still holds THIS listener, which keeps a late cleanup from a+ * StrictMode double-mount from tearing down the live registration.+ */+export function subscribePreviewTabPromotion(next: PreviewTabPromotionListener): () => void {+ listener = next;+ return () => {+ if (listener === next) listener = null;+ };+}++/**+ * Ask for a tab to become permanent, by tab id. A no-op unless that tab is+ * currently its pane's preview, so callers don't have to know the tab state —+ * only that the user committed to what the tab holds.+ *+ * Keyed by tab id rather than document name because not every promotable tab+ * IS a document: the sidebar can preview an asset, whose tab id is its path+ * under a distinct prefix.+ */+export function requestPreviewTabPromotionForTab(tabId: string): void {+ if (!tabId) return;+ listener?.(tabId);+}++/**+ * Promote a document's tab. The form the editors use — an editor only ever+ * hosts a document, so it has a docName and no reason to know about tab ids.+ */+export function requestPreviewTabPromotion(docName: string): void {+ if (!docName) return;+ requestPreviewTabPromotionForTab(docTabId(docName));+}++/**+ * The binding methods that only read. Everything else on a+ * {@link FrontmatterBinding} mutates the YAML region and so must announce.+ * Named as the complement of the mutating set because that is the safe+ * direction to be wrong in: a method missing from the wrapper below is caught+ * by the coverage test, whereas a method wrongly listed here is not.+ */+export const READ_ONLY_BINDING_METHODS = ['current', 'subscribe', 'dispose'] as const;++/** The mutating surface, wrapped one-for-one below. */+export const MUTATING_BINDING_METHODS = [+ 'patch',+ 'rename',+ 'reorder',+ 'patchPath',+ 'deletePath',+ 'renamePath',+ 'reorderPath',+ 'reorderSeqPath',+] as const;++/**+ * Wrap a frontmatter binding so every successful mutation promotes the+ * document's preview tab.+ *+ * Property-panel writes edit the YAML region of `Y.Text('source')`, which+ * reaches both editors as a sync-origin change — neither editor's origin guard+ * sees them as user input, so the promotion has to come from the write side.+ *+ * Wrapping the binding rather than each call site is what makes this hold: the+ * panel mutates through eight methods reached from three trees (the panel+ * itself, and nested object/array widgets via `FrontmatterBindingContext`), and+ * a per-call-site notification would have covered only the routes someone+ * remembered. `frontmatter-binding-promotion.test.ts` fails if the binding+ * grows a mutator this misses.+ *+ * Failed patches announce nothing — a rejected write is not an edit.+ */+export function withPreviewTabPromotion(+ binding: FrontmatterBinding,+ docName: string,+): FrontmatterBinding {+ const announceOnSuccess = <R extends { ok: boolean }>(result: R): R => {+ if (result.ok) requestPreviewTabPromotion(docName);+ return result;+ };+ return {+ ...binding,+ current: () => binding.current(),+ subscribe: (fn) => binding.subscribe(fn),+ dispose: () => binding.dispose(),+ patch: (patch) => announceOnSuccess(binding.patch(patch)),+ rename: (oldKey, newKey, options) => announceOnSuccess(binding.rename(oldKey, newKey, options)),+ reorder: (orderedKeys) => announceOnSuccess(binding.reorder(orderedKeys)),+ patchPath: (path, value) => announceOnSuccess(binding.patchPath(path, value)),+ deletePath: (path) => announceOnSuccess(binding.deletePath(path)),+ renamePath: (path, newKey, options) =>+ announceOnSuccess(binding.renamePath(path, newKey, options)),+ reorderPath: (path, orderedKeys) => announceOnSuccess(binding.reorderPath(path, orderedKeys)),+ reorderSeqPath: (path, oldIndicesInNewOrder) =>+ announceOnSuccess(binding.reorderSeqPath(path, oldIndicesInNewOrder)),+ };+}++/**+ * Whether a ProseMirror transaction is a content change the user made.+ *+ * y-prosemirror stamps `ySyncPluginKey` meta on every transaction it injects+ * from the CRDT — remote peers, agent writes, rollback-apply, and both server+ * observer directions. Only local user intent (typing, paste, drag-drop,+ * node-view commits) arrives without it. Mirrors source-dirty-observer.ts,+ * which uses this same discipline to decide what counts as a user edit.+ */+export function isUserIntentPmTransaction(transaction: PMTransaction): boolean {+ if (!transaction.docChanged) return false;+ return !transaction.getMeta(ySyncPluginKey);+}++/**+ * Whether a CodeMirror update carries a content change the user made.+ *+ * y-codemirror.next dispatches CRDT-origin changes with no `userEvent`+ * annotation, so requiring one admits typing / paste / delete / drop and+ * excludes sync. `ySyncAnnotation` would be the more direct test but the+ * package's exports map does not expose it.+ *+ * Undo/redo in source mode is routed to the Y.UndoManager, whose changes come+ * back through the sync path and so do not promote. Harmless: an undo on a tab+ * the user never edited is a no-op, and once they have edited it the tab is+ * already permanent.+ */+export function isUserIntentCmUpdate(update: ViewUpdate): boolean {+ if (!update.docChanged) return false;+ return update.transactions.some(+ (transaction) => transaction.annotation(CMTransaction.userEvent) !== undefined,+ );+}diff --git a/packages/app/src/editor/source-lint/markdown-lint-source.ts b/packages/app/src/editor/source-lint/markdown-lint-source.tsindex cde8e41e2..e594d8069 100644--- a/packages/app/src/editor/source-lint/markdown-lint-source.ts+++ b/packages/app/src/editor/source-lint/markdown-lint-source.ts@@ -84,6 +84,10 @@ function fixAction(result: LintDiagnostic): Action | null {to: offsetOf(doc, fix.range.end),insert: fix.newText,})),+ // `@codemirror/lint` annotates none of its own dispatches. Without one+ // the preview-tab origin guard reads this as CRDT sync, so applying a+ // fix from the source gutter would leave the tab provisional.+ userEvent: 'input.complete',});},};diff --git a/packages/app/src/lib/use-frontmatter-field.ts b/packages/app/src/lib/use-frontmatter-field.tsindex fd7f9b0eb..9b53aec00 100644--- a/packages/app/src/lib/use-frontmatter-field.ts+++ b/packages/app/src/lib/use-frontmatter-field.ts@@ -13,6 +13,7 @@import type { HocuspocusProvider } from '@hocuspocus/provider';import { bindFrontmatterDoc } from '@inkeep/open-knowledge-core';import { useEffect, useRef, useState } from 'react';+import { withPreviewTabPromotion } from '@/editor/preview-tab-promotion';export interface FrontmatterFieldBinding {value: string;@@ -42,7 +43,13 @@ export function useFrontmatterField(const focusedRef = useRef(false);useEffect(() => {- const b = bindFrontmatterDoc(provider);+ // Wrapped so an on-blur commit promotes the doc's preview tab — same+ // reason as PropertyPanel: the write lands as a sync-origin Y.Text change+ // that no editor origin guard reads as user input.+ const b = withPreviewTabPromotion(+ bindFrontmatterDoc(provider),+ provider.configuration.name ?? '',+ );setBinding(b);setValue(readField(b, key));const unsub = b.subscribe(() => {diff --git a/packages/app/tests/stress/preview-tab-promotion.e2e.ts b/packages/app/tests/stress/preview-tab-promotion.e2e.tsnew file mode 100644index 000000000..cba6b5f62--- /dev/null+++ b/packages/app/tests/stress/preview-tab-promotion.e2e.ts@@ -0,0 +1,181 @@+/**+ * Preview-tab promotion, in a real browser.+ *+ * A preview tab (single sidebar click, italic label) is provisional — the next+ * click reuses its slot. Committing to the document makes it permanent. These+ * flows need a real browser for reasons the jsdom tests cannot reach:+ *+ * - A real double-click is `click → click → dblclick`, and click 2 lands on+ * an already-selected row, which re-runs the sidebar's open path. If that+ * re-open settled AFTER the promotion, the tab would silently go+ * provisional again. The dom test fires a synthetic `doubleClick` with no+ * preceding clicks, so only this layer proves the ordering.+ * - Promotion-on-edit runs off real ProseMirror/CodeMirror transactions+ * carrying real y-prosemirror sync metadata, which is what the origin+ * guards actually read.+ * - An agent write arrives over the wire as a remote CRDT update, the exact+ * shape that must NOT promote.+ */++import { randomUUID } from 'node:crypto';+import type { Locator, Page } from '@playwright/test';+import {+ type ApiHelpers,+ expect,+ test,+ waitForActiveProviderSynced as waitForProvider,+} from './_helpers';++function sidebarTreeItem(page: Page, accessibleLabel: string): Locator {+ return page+ .locator('[data-slot="sidebar-container"]')+ .getByRole('treeitem', { name: accessibleLabel, exact: true });+}++/** The tab strip's primary button for a tab, by its filename aria-label. */+function editorTab(page: Page, label: string): Locator {+ return page+ .locator('[data-editor-pane-focused] [data-editor-pane-tabs] [data-editor-tab-sortable]')+ .locator(`button[aria-label="${label}"]`);+}++/** Open tab ids from the persisted session — the durable record of what survived. */+async function openTabIds(page: Page): Promise<string[] | null> {+ return page.evaluate(() => {+ const raw = window.localStorage.getItem(`ok-editor-tabs-v1:${window.location.origin}`);+ if (!raw) return null;+ const parsed = JSON.parse(raw) as { panes?: Array<{ openTabs?: unknown }> };+ const openTabs = parsed.panes?.[0]?.openTabs;+ return Array.isArray(openTabs) ? (openTabs as string[]) : null;+ });+}++async function expectOpenTabs(page: Page, expected: string[]) {+ await expect.poll(() => openTabIds(page)).toEqual(expected);+}++/**+ * Preview state is carried by the `italic` class on the tab's title button —+ * the same signal the user reads. No data attribute mirrors it, so this+ * doubles as the assertion that the visual cue clears.+ */+async function expectPreviewTab(tab: Locator, isPreview: boolean) {+ if (isPreview) {+ await expect(tab).toHaveClass(/italic/);+ } else {+ await expect(tab).not.toHaveClass(/italic/);+ }+}++const sourceToggle = (page: Page) => page.getByRole('radio', { name: 'Markdown source' });++interface Fixture {+ first: string;+ second: string;+}++/**+ * Two fresh docs, sidebar visible, nothing open. Unique per test so parallel+ * workers never share a docName (shared names corrupt CRDT state across+ * workers).+ */+async function seedTwoDocs(api: ApiHelpers, page: Page): Promise<Fixture> {+ const id = randomUUID().slice(0, 8);+ const first = `promo-a-${id}`;+ const second = `promo-b-${id}`;+ for (const name of [first, second]) {+ await api.createPage(`${name}.md`);+ await api.replaceDoc(name, `# ${name}\n\nSeed body.\n`);+ }+ await page.goto('/');+ await expect(sidebarTreeItem(page, `${first}.md`)).toBeVisible();+ return { first, second };+}++test.describe('preview-tab promotion', () => {+ test('an untouched preview tab is replaced by the next sidebar click', async ({ page, api }) => {+ // The control. Preview replacement is correct behavior, and the promotion+ // work must not turn every click permanent.+ const { first, second } = await seedTwoDocs(api, page);++ await sidebarTreeItem(page, `${first}.md`).click();+ await expectOpenTabs(page, [first]);+ await expectPreviewTab(editorTab(page, `${first}.md`), true);++ await sidebarTreeItem(page, `${second}.md`).click();+ await expectOpenTabs(page, [second]);+ });++ test('editing keeps the file open when the next one is clicked', async ({ page, api }) => {+ // The reported bug: the edited file vanished from the tab strip as soon as+ // the next one was opened.+ const { first, second } = await seedTwoDocs(api, page);++ await sidebarTreeItem(page, `${first}.md`).click();+ // Wait on the seeded text rather than provider sync: the typing needs the+ // document's content actually rendered into ProseMirror, and a keystroke+ // that lands before then is applied to an empty doc and then overwritten.+ const body = page.locator('.ProseMirror:not(.composer-prosemirror)');+ await expect(body).toContainText('Seed body.');+ await body.click();+ await page.keyboard.type('EDITED');+ await expect(body).toContainText('EDITED');++ // The italic cue clears the moment the edit lands, before any navigation.+ await expectPreviewTab(editorTab(page, `${first}.md`), false);++ await sidebarTreeItem(page, `${second}.md`).click();+ await expectOpenTabs(page, [first, second]);+ });++ test('a real double-click on the sidebar row promotes, click-pair and all', async ({+ page,+ api,+ }) => {+ // The ordering risk: click 2 of the pair re-runs the sidebar open path for+ // an already-selected row. Promotion must survive that re-open.+ const { first, second } = await seedTwoDocs(api, page);++ await sidebarTreeItem(page, `${first}.md`).dblclick();+ await expectOpenTabs(page, [first]);+ await expectPreviewTab(editorTab(page, `${first}.md`), false);++ await sidebarTreeItem(page, `${second}.md`).click();+ await expectOpenTabs(page, [first, second]);+ });++ test('switching between source and visual mode promotes', async ({ page, api }) => {+ // A mode flip changes no bytes, so no editor origin guard can see it.+ const { first, second } = await seedTwoDocs(api, page);++ await sidebarTreeItem(page, `${first}.md`).click();+ await waitForProvider(page);+ await expectPreviewTab(editorTab(page, `${first}.md`), true);++ await sourceToggle(page).click();+ await expectPreviewTab(editorTab(page, `${first}.md`), false);++ await sidebarTreeItem(page, `${second}.md`).click();+ await expectOpenTabs(page, [first, second]);+ });++ test('an agent write does NOT promote a tab you are only reading', async ({ page, api }) => {+ // Arrives as a remote CRDT update — the shape the origin guards exist to+ // reject. A tab must not become permanent because something else wrote.+ const { first, second } = await seedTwoDocs(api, page);++ await sidebarTreeItem(page, `${first}.md`).click();+ await waitForProvider(page);+ await expectPreviewTab(editorTab(page, `${first}.md`), true);++ await api.replaceDoc(first, `# ${first}\n\nRewritten by an agent.\n`);+ await expect(page.locator('.ProseMirror:not(.composer-prosemirror)')).toContainText(+ 'Rewritten by an agent.',+ );++ await expectPreviewTab(editorTab(page, `${first}.md`), true);++ await sidebarTreeItem(page, `${second}.md`).click();+ await expectOpenTabs(page, [second]);+ });+});