Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(ok): stop back/forward nav appending a tab per step (PRD-8000) (#3472)

Andrew Mikofalvy25b56891b155
diff --git a/.changeset/history-traversal-preview-slot.md b/.changeset/history-traversal-preview-slot.md
new file mode 100644
index 000000000..df94bb5f9
--- /dev/null
+++ b/.changeset/history-traversal-preview-slot.md
@@ -0,0 +1,5 @@
+---
+'@inkeep/open-knowledge': patch
+---
+
+Back and Forward no longer pile up tabs. With preview tabs on, single-clicking through several files in the sidebar keeps the strip at one tab, but pressing Back then added a permanent tab for each earlier file, so a few presses turned one tab into a strip you had to close by hand. History navigation now reuses the same preview slot the sidebar click used, so going back through a run of previews leaves you with one tab, italic, on whichever file you landed on. With preview tabs turned off, Back and Forward behave exactly as before and open permanent tabs.
diff --git a/knip.config.ts b/knip.config.ts
index f9179f2d4..78162ec09 100644
--- a/knip.config.ts
+++ b/knip.config.ts
@@ -123,9 +123,7 @@ export default {
'packages/server': {
entry: ['src/**/*.test.ts', 'src/parse-worker.ts'],
project: 'src/**',
- ignoreDependencies: [
- '@types/shell-quote',
- ],
+ ignoreDependencies: ['@types/shell-quote'],
},
'packages/cli': {
entry: ['src/**/*.test.ts', 'scripts/*.ts', 'tests/**/*.ts', 'src/parse-worker.ts'],
diff --git a/packages/app/package.json b/packages/app/package.json
index 52b1e0a14..89f41fa1b 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-collapse-spaced-folder.e2e.ts tests/stress/sidebar-file-list-fills.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/frontmatter-glob-picker.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/image-invalid-placeholder.e2e.ts tests/stress/local-target-audit.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 tests/stress/cv-paint-lock-click.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-collapse-spaced-folder.e2e.ts tests/stress/sidebar-file-list-fills.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/frontmatter-glob-picker.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/image-invalid-placeholder.e2e.ts tests/stress/local-target-audit.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 tests/stress/cv-paint-lock-click.e2e.ts tests/stress/history-traversal-preview-tab.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/App.dom.test.tsx b/packages/app/src/App.dom.test.tsx
index 99817ada5..734c15acb 100644
--- a/packages/app/src/App.dom.test.tsx
+++ b/packages/app/src/App.dom.test.tsx
@@ -582,7 +582,14 @@ describe('App runtime wiring', () => {
expect(forward).toHaveBeenCalledOnce();
});
- test('history traversal opens permanent canonical tabs', async () => {
+ test('history traversal reuses the preview slot instead of opening a permanent tab', async () => {
+ // A replay must not raise the disposition a target held when its history
+ // entry was recorded: a doc the sidebar opened as a provisional preview has
+ // to come back from Back as a preview, not as a durable tab. The option bag
+ // is read through `objectContaining` so a field added later does not break
+ // this, with both fields the handler promises today spelled out. What the
+ // disposition then does to the tab strip is pinned against the real reducer
+ // in App.history-traversal.dom.test.tsx.
setHash('#/page-a');
renderApp();
@@ -616,7 +623,7 @@ describe('App runtime wiring', () => {
target: 'page-b',
docName: 'page-b',
},
- { disposition: 'permanent', consumeActiveNewTab: true },
+ expect.objectContaining({ disposition: 'preview', consumeActiveNewTab: true }),
);
});
@@ -631,7 +638,7 @@ describe('App runtime wiring', () => {
target: 'page-a',
docName: 'page-a',
},
- { disposition: 'permanent', consumeActiveNewTab: true },
+ expect.objectContaining({ disposition: 'preview', consumeActiveNewTab: true }),
);
});
@@ -646,7 +653,7 @@ describe('App runtime wiring', () => {
target: 'page-b',
docName: 'page-b',
},
- { disposition: 'permanent', consumeActiveNewTab: true },
+ expect.objectContaining({ disposition: 'preview', consumeActiveNewTab: true }),
);
});
});
diff --git a/packages/app/src/App.history-traversal.dom.test.tsx b/packages/app/src/App.history-traversal.dom.test.tsx
new file mode 100644
index 000000000..83ba5f124
--- /dev/null
+++ b/packages/app/src/App.history-traversal.dom.test.tsx
@@ -0,0 +1,468 @@
+/**
+ * History traversal must not upgrade a previewed tab into a permanent one.
+ *
+ * The sibling `App.dom.test.tsx` mocks the document context wholesale, so it can
+ * only observe the disposition ARGUMENT the hash handler passes. That is blind
+ * to what actually goes wrong here: the argument is one input to the tab
+ * reducer, and what the user sees is the tab SET the reducer produces. So the
+ * handler runs here against the real reducer, the real tab-id derivation, the
+ * real hash writer, and jsdom's real History — and every assertion reads the
+ * state the editor renders from: the tab list, and the pane's active target.
+ *
+ * One step is modeled: the document context's forwarding of (target, options)
+ * into the reducer command, transcribed from `openTargetWithOptions` including
+ * its disposition default. The real one needs a live collab provider pool,
+ * which cannot exist in jsdom. That transcription is this file's only drift
+ * risk, and the pair that closes it is
+ * `tests/stress/history-traversal-preview-tab.e2e.ts`, which runs the same
+ * journey in a real browser with nothing modeled.
+ *
+ * Fidelity limit worth knowing before reading a failure here: jsdom implements
+ * `popstate`/`event.state` but not the Navigation API, so this tier can only
+ * exercise a traversal classifier built on the former. The real-browser pair
+ * above is the one that is agnostic to which signal the handler reads.
+ */
+
+import { cleanup, render, waitFor } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import type { ResolvedNavigationTarget } from '@/components/navigation-targets';
+import {
+ createEmptyEditorWorkspace,
+ type EditorWorkspaceState,
+ type TabOpenDisposition,
+ transitionEditorWorkspace,
+} from '@/editor/editor-panes';
+import { tabIdForNavigationTarget } from '@/editor/editor-tabs';
+import {
+ hashFromDocName,
+ hashFromSkillPreview,
+ pushHashWithoutNavigation,
+ type SkillPreviewHashTarget,
+} from '@/lib/doc-hash';
+import { __resetLocalMenuActionBusForTests } from '@/lib/local-menu-action-bus';
+
+interface OpenOptions {
+ disposition?: TabOpenDisposition;
+ tabBehavior?: 'append' | 'replace-active';
+ consumeActiveNewTab?: boolean;
+}
+
+const SKILL_PREVIEW: SkillPreviewHashTarget = {
+ flavor: 'builtin',
+ source: 'bundled/skills/project',
+ name: 'project',
+ subtitle: '',
+ level: 'project',
+};
+
+/** The target the hash handler builds for a preview hash. Its `target` string is
+ * the identity coordinates only — no selected file, same as the tab id. */
+function previewTarget(preview: SkillPreviewHashTarget): ResolvedNavigationTarget {
+ return {
+ kind: 'skill-preview',
+ target: `${preview.flavor}/${preview.source}/${preview.name}`,
+ ...preview,
+ };
+}
+
+const SKILL_PREVIEW_TARGET = previewTarget(SKILL_PREVIEW);
+
+// An un-imported skill: its bundle-file chips select in place on the preview
+// rather than opening a skill-file tab, so they are the surface that moves a
+// preview's selection without changing its tab.
+const EXPLORE_PREVIEW: SkillPreviewHashTarget = {
+ flavor: 'explore',
+ source: 'inkeep/open-knowledge-skills',
+ name: 'trip-log',
+ subtitle: 'inkeep/open-knowledge-skills',
+ level: 'project',
+};
+
+// Derived, never spelled out: a skill-preview tab id is NUL-prefixed and its
+// segments are percent-encoded.
+const SKILL_PREVIEW_TAB_ID = tabIdForNavigationTarget(SKILL_PREVIEW_TARGET);
+const EXPLORE_PREVIEW_TAB_ID = tabIdForNavigationTarget(previewTarget(EXPLORE_PREVIEW));
+
+// ----------------------------------------------------------------- real state
+
+let workspace: EditorWorkspaceState = createEmptyEditorWorkspace();
+
+function focusedPane() {
+ const found = workspace.panes.find((candidate) => candidate.id === workspace.focusedPaneId);
+ if (!found) throw new Error('no focused pane');
+ return found;
+}
+
+function openTabIds(): string[] {
+ return [...focusedPane().openTabs];
+}
+
+function previewTabId(): string | null {
+ return focusedPane().previewTabId;
+}
+
+/** The bundle file the active preview shows — what `EditorArea` hands
+ * `SkillPreviewTab` as its `path`. */
+function activePreviewPath(): string | undefined {
+ const target = focusedPane().activeTarget;
+ if (target?.kind !== 'skill-preview') throw new Error('no skill preview is active');
+ return target.path;
+}
+
+/**
+ * Transcription of `DocumentContext.openTargetWithOptions`' command
+ * construction, down to the disposition default and the `activate-owner`
+ * default for an already-open tab. Everything it calls is the real thing.
+ */
+function applyOpen(target: ResolvedNavigationTarget, options: OpenOptions = {}) {
+ const tabId = tabIdForNavigationTarget(target);
+ if (!tabId) throw new Error(`no tab id for ${target.target}`);
+ const transition = transitionEditorWorkspace(workspace, {
+ type: 'open-target',
+ paneId: workspace.focusedPaneId,
+ tabId,
+ target,
+ disposition:
+ options.disposition ?? (options.tabBehavior === 'replace-active' ? 'preview' : 'permanent'),
+ consumeActiveNewTab: options.consumeActiveNewTab ?? true,
+ existingTabBehavior: 'activate-owner',
+ });
+ workspace = transition.workspace;
+}
+
+/** What the Files tree does for a document row: open, then record the hash. */
+function clickDocRow(docName: string, previewTabsEnabled: boolean) {
+ applyOpen(
+ { kind: 'doc', target: docName, docName },
+ {
+ disposition: previewTabsEnabled ? 'preview' : 'permanent',
+ consumeActiveNewTab: true,
+ },
+ );
+ pushHashWithoutNavigation(hashFromDocName(docName));
+}
+
+/** What the Skills tree does for a read-only preview row. */
+function clickSkillPreviewRow(preview: SkillPreviewHashTarget, previewTabsEnabled: boolean) {
+ applyOpen(previewTarget(preview), {
+ tabBehavior: previewTabsEnabled ? 'replace-active' : 'append',
+ });
+ pushHashWithoutNavigation(hashFromSkillPreview(preview));
+}
+
+// ---------------------------------------------------------------------- mocks
+
+let pages = new Set<string>();
+let mergedConfig: { editor: { previewTabs: boolean } } | null = null;
+
+vi.doMock('@/lib/perf', () => ({
+ mark: () => {},
+ ProfilerBoundary: ({ children }: { children: ReactNode }) => children,
+}));
+
+vi.doMock('@/editor/DocumentContext', () => ({
+ DocumentProvider: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+ useDocumentContext: () => ({
+ activeDocName:
+ focusedPane().activeTarget?.kind === 'doc' ? focusedPane().activeTarget?.target : null,
+ activeTabId: focusedPane().activeTabId,
+ activeTarget: focusedPane().activeTarget,
+ clearTarget: () => {},
+ promoteAllPreviewTabs: () => {},
+ syncOpenTabsWithKnownTargets: () => {},
+ tabSessionLoaded: true,
+ openTabs: openTabIds(),
+ closeDocument: () => {},
+ }),
+ useDocumentTransition: () => ({
+ openTargetTransition: (target: ResolvedNavigationTarget, options?: OpenOptions) =>
+ applyOpen(target, options),
+ }),
+}));
+
+vi.doMock('@/components/PageListContext', () => {
+ const list = () => ({
+ assetPaths: new Set<string>(),
+ filePaths: new Set<string>(),
+ folderPaths: new Set<string>(),
+ loading: false,
+ pageMeta: new Map<string, unknown>(),
+ pages,
+ pagesBySlug: new Map<string, unknown>(),
+ pagesByBasename: new Map<string, unknown>(),
+ });
+ return {
+ PageListProvider: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+ usePageList: list,
+ useOptionalPageList: list,
+ };
+});
+
+vi.doMock('@/components/navigation-targets', () => ({
+ resolveNavigationTarget: (docName: string) => ({
+ kind: 'doc' as const,
+ target: docName,
+ docName,
+ }),
+ downgradeFolderIndexForHashNav: (target: ResolvedNavigationTarget) => target,
+ withLargeFileOpenGuard: (target: ResolvedNavigationTarget) => target,
+}));
+
+vi.doMock('@/lib/config-provider', () => ({
+ ConfigProvider: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+ useConfigContext: () => ({ merged: mergedConfig }),
+}));
+vi.doMock('@/lib/config-context', () => ({
+ useConfigContext: () => ({ merged: mergedConfig }),
+}));
+vi.doMock('@/lib/api-config', () => ({
+ fetchApiConfig: () =>
+ Promise.resolve({
+ status: 'ok' as const,
+ config: { collabUrl: null, previewUrl: null, port: 0, singleFile: false },
+ }),
+}));
+vi.doMock('@/lib/use-server-keepalive', () => ({ useServerKeepalive: () => {} }));
+vi.doMock('@/lib/single-file-mode', () => ({
+ SingleFileModeProvider: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+ useSingleFileMode: () => false,
+}));
+vi.doMock('@/components/ConnectingBanner', () => ({ ConnectingBanner: () => null }));
+vi.doMock('@/components/SystemDocSubscriber', () => ({ SystemDocSubscriber: () => null }));
+vi.doMock('@/editor/EditorLifecycleFlush', () => ({ EditorLifecycleFlush: () => null }));
+vi.doMock('@/editor/BackgroundThrottleReporter', () => ({
+ BackgroundThrottleReporter: () => null,
+}));
+vi.doMock('@/components/McpConsentDialog', () => ({ McpConsentDialog: () => null }));
+vi.doMock('@/components/CommandPalette', () => ({ CommandPalette: () => null }));
+vi.doMock('@/components/AuthModal', () => ({ AuthModal: () => null }));
+vi.doMock('@/components/InstallInClaudeDesktopDialog', () => ({
+ InstallInClaudeDesktopDialog: () => null,
+}));
+vi.doMock('@/components/CreateProjectMenuTrigger', () => ({
+ CreateProjectMenuTrigger: () => null,
+}));
+vi.doMock('@/components/ReportBugMenuTrigger', () => ({ ReportBugMenuTrigger: () => null }));
+vi.doMock('@/components/FeedbackMenuTrigger', () => ({ FeedbackMenuTrigger: () => null }));
+vi.doMock('@/components/ShareBranchSwitchDialog', () => ({ ShareBranchSwitchDialog: () => null }));
+vi.doMock('@/components/ShareReceiveMissDialog', () => ({ ShareReceiveMissDialog: () => null }));
+vi.doMock('@/components/NewItemDialog', () => ({
+ isNewItemShortcut: () => false,
+ NewItemDialog: () => null,
+}));
+vi.doMock('@/components/FileSidebar', () => ({ FileSidebar: () => null }));
+vi.doMock('@/components/EditorPane', () => ({ EditorPane: () => <main /> }));
+vi.doMock('@/components/ui/sidebar', () => ({
+ SidebarProvider: ({ children }: { children: ReactNode }) => <section>{children}</section>,
+ SidebarInset: ({ children }: { children: ReactNode }) => <section>{children}</section>,
+}));
+vi.doMock('@/components/ShareReceiveDialog', () => ({ ShareReceiveDialog: () => null }));
+vi.doMock('@/lib/share/clone-controller', () => ({ createCloneController: () => ({}) }));
+vi.doMock('@/lib/transports/auth-query-transport', () => ({ httpAuthQueryTransport: () => ({}) }));
+vi.doMock('@/lib/transports/clone-transport', () => ({ httpCloneTransport: () => ({}) }));
+
+const { App } = await import('./App');
+
+describe('history traversal and the preview tab slot', () => {
+ beforeEach(() => {
+ workspace = createEmptyEditorWorkspace();
+ pages = new Set(['page-a', 'page-b', 'page-c']);
+ mergedConfig = { editor: { previewTabs: true } };
+ window.history.replaceState(null, '', window.location.pathname);
+ globalThis.fetch = vi.fn(() => Promise.resolve(new Response(null, { status: 204 }))) as never;
+ });
+
+ afterEach(() => {
+ cleanup();
+ __resetLocalMenuActionBusForTests();
+ vi.restoreAllMocks();
+ });
+
+ test('three sidebar preview clicks keep the strip at one tab', async () => {
+ // The control, and the guard on the handler's forward-path re-entry: the
+ // effect re-runs on every tab-state change and re-enters the hash handler
+ // with the hash the click just pushed. That self-echo must stay a no-op.
+ const view = render(<App />);
+ for (const doc of ['page-a', 'page-b', 'page-c']) {
+ clickDocRow(doc, true);
+ view.rerender(<App />);
+ }
+ await waitFor(() => expect(window.location.hash).toBe('#/page-c'));
+
+ expect(openTabIds()).toEqual(['page-c']);
+ expect(previewTabId()).toBe('page-c');
+ });
+
+ test('back to a doc opened as a preview reuses the preview slot instead of appending', async () => {
+ const view = render(<App />);
+ for (const doc of ['page-a', 'page-b', 'page-c']) {
+ clickDocRow(doc, true);
+ view.rerender(<App />);
+ }
+ expect(openTabIds()).toEqual(['page-c']);
+
+ window.history.back();
+ await waitFor(() => expect(window.location.hash).toBe('#/page-b'));
+ view.rerender(<App />);
+
+ // `page-b` was provisional when its history entry was recorded — the click
+ // after it took the slot back. Replaying that entry must not durably grow
+ // the strip.
+ await waitFor(() => expect(openTabIds()).toEqual(['page-b']));
+ expect(previewTabId()).toBe('page-b');
+
+ window.history.back();
+ await waitFor(() => expect(window.location.hash).toBe('#/page-a'));
+ view.rerender(<App />);
+
+ await waitFor(() => expect(openTabIds()).toEqual(['page-a']));
+ expect(previewTabId()).toBe('page-a');
+ });
+
+ test('a re-render between a traversal popstate and its hashchange reuses the preview slot', async () => {
+ // Engines dispatch popstate inside the traversal itself and queue
+ // hashchange as a later task, so whatever else is already queued runs
+ // between them — including React flushing a pending render, which
+ // re-subscribes this effect and re-enters the hash sync while the traversal
+ // is still in flight. That re-entry reads the same replay the hashchange is
+ // about to read, and if it retires the signal that marks it a replay, the
+ // hashchange behind it sees a fresh navigation and promotes the tab.
+ //
+ // jsdom fires the pair back to back, so the gap is opened here by a
+ // popstate listener registered after the handler's own. Everything it
+ // triggers is the real thing; only its timing is arranged.
+ const view = render(<App />);
+ for (const doc of ['page-a', 'page-b', 'page-c']) {
+ clickDocRow(doc, true);
+ view.rerender(<App />);
+ }
+ expect(openTabIds()).toEqual(['page-c']);
+
+ const rerenderMidTraversal = () => {
+ window.removeEventListener('popstate', rerenderMidTraversal);
+ view.rerender(<App />);
+ };
+ window.addEventListener('popstate', rerenderMidTraversal);
+
+ window.history.back();
+ await waitFor(() => expect(window.location.hash).toBe('#/page-b'));
+ view.rerender(<App />);
+
+ await waitFor(() => expect(openTabIds()).toEqual(['page-b']));
+ expect(previewTabId()).toBe('page-b');
+
+ // What losing the slot costs the user: the next sidebar click appends
+ // beside `page-b` instead of taking its place.
+ clickDocRow('page-c', true);
+ view.rerender(<App />);
+ await waitFor(() => expect(openTabIds()).toEqual(['page-c']));
+ });
+
+ test('a skill preview stays one reusable tab across a click away and back', async () => {
+ // The hash handler's second open site. It routes through the same
+ // `openHashTarget` the document path uses, so it inherits both the identity
+ // guard that absorbs the forward re-entry and the disposition a replay
+ // re-derives. This journey is what holds those consistent across the two
+ // branches: a skill preview has to come back from Back into the slot it
+ // left, exactly as a document does.
+ const view = render(<App />);
+
+ clickSkillPreviewRow(SKILL_PREVIEW, true);
+ view.rerender(<App />);
+ await waitFor(() => expect(openTabIds()).toEqual([SKILL_PREVIEW_TAB_ID]));
+
+ clickDocRow('page-a', true);
+ view.rerender(<App />);
+ await waitFor(() => expect(openTabIds()).toEqual(['page-a']));
+
+ window.history.back();
+ await waitFor(() => expect(window.location.hash).toBe(hashFromSkillPreview(SKILL_PREVIEW)));
+ view.rerender(<App />);
+
+ await waitFor(() => expect(openTabIds()).toEqual([SKILL_PREVIEW_TAB_ID]));
+ expect(previewTabId()).toBe(SKILL_PREVIEW_TAB_ID);
+ });
+
+ test('a bundle file clicked inside a preview moves the selection on the same tab', async () => {
+ // A preview tab is deliberately one tab for the whole bundle: its id and its
+ // target string both drop the selected file so the tab is reused as the
+ // selection moves. That makes the selection invisible to a same-tab check,
+ // and the hash handler runs one — so the hash a chip click writes has to
+ // reach the pane anyway, or the preview keeps rendering the file the user
+ // just navigated away from while the URL says otherwise.
+ const view = render(<App />);
+
+ clickSkillPreviewRow(EXPLORE_PREVIEW, true);
+ view.rerender(<App />);
+ await waitFor(() => expect(openTabIds()).toEqual([EXPLORE_PREVIEW_TAB_ID]));
+ expect(activePreviewPath()).toBeUndefined();
+
+ // What a FILES chip does on an un-imported skill: rewrite the hash with the
+ // clicked file, changing nothing else about the target.
+ window.location.hash = hashFromSkillPreview({
+ ...EXPLORE_PREVIEW,
+ path: 'references/gear.md',
+ });
+
+ await waitFor(() => expect(activePreviewPath()).toBe('references/gear.md'));
+ view.rerender(<App />);
+ // Still the one tab it started as — the selection moved, the tab did not.
+ expect(openTabIds()).toEqual([EXPLORE_PREVIEW_TAB_ID]);
+ });
+
+ test('back to a doc whose tab is still open activates it without appending', async () => {
+ // With preview tabs off every click keeps its own tab, so the doc a replay
+ // lands on is already open and takes the activate-existing branch. Nothing
+ // about restoring traversal semantics may change that.
+ mergedConfig = { editor: { previewTabs: false } };
+ const view = render(<App />);
+
+ clickDocRow('page-a', false);
+ view.rerender(<App />);
+ clickDocRow('page-b', false);
+ view.rerender(<App />);
+ expect(openTabIds()).toEqual(['page-a', 'page-b']);
+
+ window.history.back();
+ await waitFor(() => expect(window.location.hash).toBe('#/page-a'));
+ view.rerender(<App />);
+
+ expect(openTabIds()).toEqual(['page-a', 'page-b']);
+ });
+
+ test('with preview tabs off, back to a closed doc appends instead of taking a slot', async () => {
+ // The disposition-sensitive half of the preview-tabs-off contract. The
+ // sibling above lands on a doc whose tab is still open, where the reducer
+ // ignores the disposition outright — so it reads the same whether a replay
+ // asks for a preview or a permanent tab. A closed target is the only shape
+ // where those two answers diverge.
+ //
+ // Appending is the answer that has to hold: nothing promotes a preview tab
+ // back once the setting is already off, so a replay that claimed the
+ // preview slot would strand an evictable tab in a configuration that is
+ // supposed to have none.
+ //
+ // Evicting `page-a` takes preview clicks, hence the flip between the clicks
+ // and the traversal rather than a `previewTabs: false` run throughout.
+ const view = render(<App />);
+
+ clickDocRow('page-a', true);
+ view.rerender(<App />);
+ clickDocRow('page-b', true);
+ view.rerender(<App />);
+ expect(openTabIds()).toEqual(['page-b']);
+
+ mergedConfig = { editor: { previewTabs: false } };
+ view.rerender(<App />);
+
+ window.history.back();
+ await waitFor(() => expect(window.location.hash).toBe('#/page-a'));
+ view.rerender(<App />);
+
+ await waitFor(() => expect(openTabIds()).toEqual(['page-b', 'page-a']));
+ // The slot `page-b` still holds is left alone; the replay claims no slot of
+ // its own.
+ expect(previewTabId()).toBe('page-b');
+ });
+});
diff --git a/packages/app/src/App.tsx b/packages/app/src/App.tsx
index 1977b3fa3..2deff8701 100644
--- a/packages/app/src/App.tsx
+++ b/packages/app/src/App.tsx
@@ -38,6 +38,7 @@ import {
} from '@/editor/DocumentContext';
import { EditorLifecycleFlush } from '@/editor/EditorLifecycleFlush';
import { parseEditorTabId, tabIdForNavigationTarget } from '@/editor/editor-tabs';
+import { previewOpenDisposition } from '@/editor/preview-open-disposition';
import { useInstalledClis } from '@/hooks/use-installed-clis';
import { useReconcileSkillTabs } from '@/hooks/use-reconcile-skill-tabs';
import { ConfigProvider, useConfigContext } from '@/lib/config-provider';
@@ -45,6 +46,7 @@ import {
assetPathFromHash,
docNameFromHash,
isContentRootHash,
+ isManagedHashHistoryState,
markCurrentHashHistoryEntry,
replaceHashWithoutNavigation,
skillFileFromHash,
@@ -111,6 +113,30 @@ function exactOpenMarkdownTabTarget(
return null;
}
+/**
+ * The bundle file a target selects, for the kinds that carry one. A
+ * skill-preview tab's identity is deliberately path-independent so one preview
+ * tab is reused as the selection moves across bundle files, which means two
+ * navigations that differ only in the selected file share both a tab id and a
+ * `target` string. Reading the selection separately is what lets a same-tab
+ * comparison still tell those two navigations apart.
+ */
+function selectedPathForNavigationTarget(target: ResolvedNavigationTarget): string | null {
+ switch (target.kind) {
+ case 'skill-file':
+ case 'skill-preview':
+ return target.path ?? null;
+ case 'doc':
+ case 'folder-index':
+ case 'folder':
+ case 'asset':
+ case 'skills':
+ case 'large-file':
+ case 'missing':
+ return null;
+ }
+}
+
function knownTargetsSignature(
pages: ReadonlySet<string>,
folderPaths: ReadonlySet<string>,
@@ -156,7 +182,16 @@ function NavigationHandler() {
pagesBySlug,
pagesByBasename,
} = usePageList();
+ const { merged } = useConfigContext();
+ const previewTabsEnabled = merged?.editor?.previewTabs ?? true;
const lastSyncedTargetsSignatureRef = useRef<string | null>(null);
+ // Same-tab navigation records hashes with pushState, which stays silent
+ // until history traversal. Pair popstate with its following hashchange so a
+ // replay reuses the preview slot instead of taking the hash handler's append
+ // path. Keyed on the URL rather than a boolean because popstate is dispatched
+ // inside the traversal while hashchange is queued as a later task, so a flag
+ // set by one navigation could be read by another.
+ const historyTraversalUrlRef = useRef<string | null>(null);
const targetsSignature = knownTargetsSignature(pages, folderPaths, assetPaths, filePaths);
useEffect(
@@ -191,20 +226,59 @@ function NavigationHandler() {
useEffect(() => {
if (!tabSessionLoaded && window.okDesktop?.config.mode === 'editor') return;
- onHashChange();
+ // Re-entry from a re-subscribe re-syncs the current URL rather than
+ // announcing a navigation, so it reads the marker and leaves it standing.
+ syncTargetFromHash(historyTraversalUrlRef.current);
+
+ function onPopState(event: PopStateEvent) {
+ // Only an entry we stamped can be a replay of one of our own opens. A
+ // direct `location.hash = …` also emits popstate in Chromium, but it
+ // creates a fresh entry whose state is null, so it stays classified as a
+ // fresh navigation and keeps the append path.
+ historyTraversalUrlRef.current = isManagedHashHistoryState(event.state)
+ ? window.location.href
+ : null;
+ }
function onHashChange() {
+ // The hashchange that closes a traversal is the one event that retires
+ // the marker. This effect re-subscribes on every tab-state change and
+ // re-enters the sync below, and that re-entry can land in the gap between
+ // a traversal's popstate and its hashchange; retiring the marker there
+ // would leave this handler reading the same replay as a fresh navigation
+ // and promoting the tab the replay was meant to reuse.
+ const traversedUrl = historyTraversalUrlRef.current;
+ historyTraversalUrlRef.current = null;
+ syncTargetFromHash(traversedUrl);
+ }
+
+ function syncTargetFromHash(traversedUrl: string | null) {
+ const isHistoryTraversal = traversedUrl === window.location.href;
+ // Marking has to follow the classification, or it would stamp the very
+ // entry being classified.
markCurrentHashHistoryEntry();
const openHashTarget = (target: ResolvedNavigationTarget) => {
+ // Absorbs this effect's own re-entry on the hash a forward open just
+ // wrote. The test is "the same navigation", not "the same tab": a skill
+ // preview keeps one tab across its bundle files, so a hash that moved
+ // only the selection matches on both the tab id and the target string,
+ // and returning there would leave the pane rendering the file the user
+ // navigated away from.
if (
tabIdForNavigationTarget(target) === activeTabId &&
activeTarget?.kind === target.kind &&
- activeTarget.target === target.target
+ activeTarget.target === target.target &&
+ selectedPathForNavigationTarget(activeTarget) === selectedPathForNavigationTarget(target)
) {
return;
}
openTargetTransition(target, {
- disposition: 'permanent',
+ // A replay must not raise a target above the disposition it held
+ // when its entry was created, so it re-derives from the same rule
+ // the sidebar used to open it.
+ disposition: isHistoryTraversal
+ ? previewOpenDisposition(previewTabsEnabled)
+ : 'permanent',
consumeActiveNewTab: true,
});
};
@@ -254,7 +328,7 @@ function NavigationHandler() {
const skillPreview = skillPreviewFromHash(window.location.hash);
if (skillPreview) {
mark('ok/nav/hash-change', { docName: null, kind: 'skill-preview' });
- openTargetTransition({
+ openHashTarget({
kind: 'skill-preview',
target: `${skillPreview.flavor}/${skillPreview.source}/${skillPreview.name}`,
flavor: skillPreview.flavor,
@@ -303,8 +377,10 @@ function NavigationHandler() {
mark('ok/nav/hash-change', { docName, kind: target.kind });
openHashTarget(target);
}
+ window.addEventListener('popstate', onPopState);
window.addEventListener('hashchange', onHashChange);
return () => {
+ window.removeEventListener('popstate', onPopState);
window.removeEventListener('hashchange', onHashChange);
};
}, [
@@ -319,6 +395,7 @@ function NavigationHandler() {
pages,
pagesBySlug,
pagesByBasename,
+ previewTabsEnabled,
tabSessionLoaded,
]);
diff --git a/packages/app/src/components/FileTree.tsx b/packages/app/src/components/FileTree.tsx
index ce7604c4c..32bf820ae 100644
--- a/packages/app/src/components/FileTree.tsx
+++ b/packages/app/src/components/FileTree.tsx
@@ -187,6 +187,7 @@ import { asDirectoryHandle, useSelectionMirror } from '@/components/use-selectio
import { getEditorForDoc } from '@/editor/active-editor';
import { type OpenTargetOptions, useDocumentContext } from '@/editor/DocumentContext';
import { assetTabId, docTabId, folderTabId, remapPathForFolderRenames } from '@/editor/editor-tabs';
+import { previewOpenDisposition } from '@/editor/preview-open-disposition';
import { requestPreviewTabPromotionForTab } from '@/editor/preview-tab-promotion';
import { useConflicts } from '@/hooks/use-conflicts';
import { useFolderConfig } from '@/hooks/use-folder-config';
@@ -867,7 +868,7 @@ export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {
const showOkFolders = merged?.appearance?.sidebar?.showOkFolders ?? false;
const previewTabsEnabled = merged?.editor?.previewTabs ?? true;
const previewOpenOptions = {
- disposition: previewTabsEnabled ? 'preview' : 'permanent',
+ disposition: previewOpenDisposition(previewTabsEnabled),
consumeActiveNewTab: true,
} satisfies OpenTargetOptions;
const {
diff --git a/packages/app/src/editor/preview-open-disposition.ts b/packages/app/src/editor/preview-open-disposition.ts
new file mode 100644
index 000000000..ed007a7a1
--- /dev/null
+++ b/packages/app/src/editor/preview-open-disposition.ts
@@ -0,0 +1,14 @@
+import type { TabOpenDisposition } from '@/editor/editor-panes';
+
+/**
+ * The single rule for what disposition a preview-eligible open gets.
+ *
+ * Two surfaces need it and must not drift: the Files tree, which opens a target
+ * and records a history entry for it, and the hash handler, which re-opens
+ * that target when the entry is replayed by Back/Forward. If the two derived
+ * the disposition independently, a replay could silently promote a
+ * provisional open into a durable tab.
+ */
+export function previewOpenDisposition(previewTabsEnabled: boolean): TabOpenDisposition {
+ return previewTabsEnabled ? 'preview' : 'permanent';
+}
diff --git a/packages/app/tests/stress/history-traversal-preview-tab.e2e.ts b/packages/app/tests/stress/history-traversal-preview-tab.e2e.ts
new file mode 100644
index 000000000..5d3e6e857
--- /dev/null
+++ b/packages/app/tests/stress/history-traversal-preview-tab.e2e.ts
@@ -0,0 +1,132 @@
+/**
+ * History traversal must not upgrade a previewed tab into a permanent one.
+ *
+ * A preview tab (single sidebar click, italic label) is provisional: the next
+ * click reuses its slot. Pressing Back replays a hash the sidebar already
+ * recorded, so the doc it lands on was provisional when its history entry was
+ * created. Replaying it must not durably grow the strip.
+ *
+ * Why this belongs in a real browser rather than beside the jsdom sibling:
+ *
+ * - The signal that distinguishes a replay from a fresh hash assignment can
+ * come from `popstate`/`event.state` or from the Navigation API's
+ * `navigationType`. jsdom implements the first and not the second, so a
+ * jsdom-only pin would silently decide which mechanism is allowed. Real
+ * Chromium exposes both, so the contract pinned here is about the outcome
+ * the user sees — the tab strip — not about how the handler classifies.
+ * - It is the composition of the hash handler, the document context, and the
+ * tab reducer against a real session-persistence write that grows; each
+ * part is individually correct.
+ *
+ * The two neighbouring suites are each blind to this on their own:
+ * navigation-history.e2e.ts traverses every target kind but never reads the tab
+ * strip, and preview-tab-promotion.e2e.ts reads the strip thoroughly but never
+ * traverses history.
+ */
+
+import { randomUUID } from 'node:crypto';
+import type { Locator, Page } from '@playwright/test';
+import { type ApiHelpers, expect, test } 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);
+}
+
+async function expectHash(page: Page, expected: string) {
+ await expect
+ .poll(async () => decodeURIComponent(await page.evaluate(() => window.location.hash)), {
+ timeout: 15_000,
+ })
+ .toBe(expected);
+}
+
+/**
+ * Preview state is carried by the `italic` class on the tab's title button —
+ * the same signal the user reads.
+ */
+async function expectPreviewTab(tab: Locator, isPreview: boolean) {
+ if (isPreview) {
+ await expect(tab).toHaveClass(/italic/);
+ } else {
+ await expect(tab).not.toHaveClass(/italic/);
+ }
+}
+
+/** Three fresh docs, unique per test so parallel workers never share a docName. */
+async function seedThreeDocs(api: ApiHelpers, page: Page): Promise<[string, string, string]> {
+ const id = randomUUID().slice(0, 8);
+ const names: [string, string, string] = [`hist-a-${id}`, `hist-b-${id}`, `hist-c-${id}`];
+ for (const name of names) {
+ await api.createPage(`${name}.md`);
+ await api.replaceDoc(name, `# ${name}\n\nSeed body.\n`);
+ }
+ await page.goto('/');
+ await expect(sidebarTreeItem(page, `${names[0]}.md`)).toBeVisible();
+ return names;
+}
+
+test.describe('history traversal and the preview tab slot', () => {
+ test('back to a previewed doc reuses the preview slot instead of appending a tab', async ({
+ page,
+ api,
+ }) => {
+ const [a, b, c] = await seedThreeDocs(api, page);
+
+ // Forward: three single clicks. Each reuses the preview slot, so the strip
+ // stays at one tab. The sidebar records each hash with pushState, which is
+ // silent — the hash handler only hears about these again on traversal.
+ await sidebarTreeItem(page, `${a}.md`).click();
+ await expectOpenTabs(page, [a]);
+ await sidebarTreeItem(page, `${b}.md`).click();
+ await expectOpenTabs(page, [b]);
+ await sidebarTreeItem(page, `${c}.md`).click();
+ await expectOpenTabs(page, [c]);
+ await expectPreviewTab(editorTab(page, `${c}.md`), true);
+
+ // The in-app Back button is Electron-only; it emits `navigate-back` ->
+ // `window.history.back()`, which is exactly what `goBack()` performs.
+ await page.goBack();
+ await expectHash(page, `#/${b}`);
+ await expectOpenTabs(page, [b]);
+ await expectPreviewTab(editorTab(page, `${b}.md`), true);
+ await expect(editorTab(page, `${c}.md`)).toHaveCount(0);
+
+ await page.goBack();
+ await expectHash(page, `#/${a}`);
+ await expectOpenTabs(page, [a]);
+ await expectPreviewTab(editorTab(page, `${a}.md`), true);
+ await expect(editorTab(page, `${b}.md`)).toHaveCount(0);
+
+ // Forward is the same replay in the other direction and carries the same
+ // contract; it is only harder to notice because a Back sequence usually
+ // leaves the forward targets already open.
+ await page.goForward();
+ await expectHash(page, `#/${b}`);
+ await expectOpenTabs(page, [b]);
+ await expectPreviewTab(editorTab(page, `${b}.md`), true);
+ });
+});
diff --git a/packages/core/src/bridge/bind-frontmatter-doc.ts b/packages/core/src/bridge/bind-frontmatter-doc.ts
index dfd95ef49..d7a845280 100644
--- a/packages/core/src/bridge/bind-frontmatter-doc.ts
+++ b/packages/core/src/bridge/bind-frontmatter-doc.ts
@@ -1,4 +1,3 @@
-
import type * as Y from 'yjs';
import type { Err, Ok, Result } from '../config/result.ts';
import { type FrontmatterValidationError, toFrontmatterIssue } from '../frontmatter/errors.ts';
diff --git a/packages/core/src/bridge/bridge-invariant.ts b/packages/core/src/bridge/bridge-invariant.ts
index 8bfdb40cd..005627195 100644
--- a/packages/core/src/bridge/bridge-invariant.ts
+++ b/packages/core/src/bridge/bridge-invariant.ts
@@ -1,4 +1,3 @@
-
import { fnv1aDigest } from './hash-util.ts';
export type BridgeInvariantSite = 'observer-b' | 'persistence' | 'test-harness';
diff --git a/packages/core/src/bridge/compose.ts b/packages/core/src/bridge/compose.ts
index 2a597ec3d..f4cc8a286 100644
--- a/packages/core/src/bridge/compose.ts
+++ b/packages/core/src/bridge/compose.ts
@@ -1,4 +1,3 @@
-
import { prependFrontmatter, stripFrontmatter } from '../extensions/frontmatter.ts';
export type ComposeAdjustment = 'none' | 'body' | 'frontmatter' | 'unresolved';
diff --git a/packages/core/src/bridge/divergence-locate.ts b/packages/core/src/bridge/divergence-locate.ts
index d979f4b39..6b505314d 100644
--- a/packages/core/src/bridge/divergence-locate.ts
+++ b/packages/core/src/bridge/divergence-locate.ts
@@ -1,4 +1,3 @@
-
import { findFirstDivergenceIndex } from './tolerance-telemetry.ts';
export const BRIDGE_LINE_KINDS = [
diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.ts
index 01ef76a9f..8fb428b90 100644
--- a/packages/core/src/bridge/doc-boundary-space.ts
+++ b/packages/core/src/bridge/doc-boundary-space.ts
@@ -1,4 +1,3 @@
-
import { FRONTMATTER_RE, stripFrontmatter } from '../extensions/frontmatter.ts';
import { carriedEdgeEmpties, type DocEdgeEmpties } from '../markdown/doc-edge-blank-runs.ts';
diff --git a/packages/core/src/bridge/growth-detect.ts b/packages/core/src/bridge/growth-detect.ts
index 463e89595..9d9c244b0 100644
--- a/packages/core/src/bridge/growth-detect.ts
+++ b/packages/core/src/bridge/growth-detect.ts
@@ -1,4 +1,3 @@
-
const DEFAULT_MIN_SUBSTANTIVE_LINE_LENGTH = 16;
export const DUPLICATION_GATE_MIN_LINE_LENGTH = 8;
diff --git a/packages/core/src/bridge/intraline-predicate.ts b/packages/core/src/bridge/intraline-predicate.ts
index 0939885bb..c43fdd7e7 100644
--- a/packages/core/src/bridge/intraline-predicate.ts
+++ b/packages/core/src/bridge/intraline-predicate.ts
@@ -1,4 +1,3 @@
-
export function rawLineCounts(doc: string): Map<string, number> {
const counts = new Map<string, number>();
for (const line of doc.split('\n')) {
diff --git a/packages/core/src/bridge/merge-three-way.ts b/packages/core/src/bridge/merge-three-way.ts
index c0dc65705..251560a35 100644
--- a/packages/core/src/bridge/merge-three-way.ts
+++ b/packages/core/src/bridge/merge-three-way.ts
@@ -65,7 +65,6 @@ export function tryLineLevelCombine(
return { clean: true, merged };
}
-
export type BridgeMergeContentLossSide = 'user' | 'agent';
export type BridgeMergeContentLossWhich = 'substring' | 'order' | 'growth';
diff --git a/packages/core/src/bridge/normalize.ts b/packages/core/src/bridge/normalize.ts
index dcc5b0690..01ac80099 100644
--- a/packages/core/src/bridge/normalize.ts
+++ b/packages/core/src/bridge/normalize.ts
@@ -1,4 +1,3 @@
-
import { stripFrontmatter } from '../extensions/frontmatter.ts';
import { bodyEdgeEmpties } from './doc-boundary-space.ts';
diff --git a/packages/core/src/bridge/pm-structural-equivalence.ts b/packages/core/src/bridge/pm-structural-equivalence.ts
index 0be5203e4..754dc5cc2 100644
--- a/packages/core/src/bridge/pm-structural-equivalence.ts
+++ b/packages/core/src/bridge/pm-structural-equivalence.ts
@@ -32,7 +32,6 @@ const BR_SENTINEL: PmStructuralNode = { type: '__br__' };
const BR_LITERAL_RE = /^<br\s*\/?>$/i;
-
interface DegradeEntry {
readonly label: string;
readonly severity: ToleranceClassSeverity;
@@ -128,7 +127,6 @@ export interface ComparePmStructuralOptions {
ignoreAttrs?: (attrKey: string) => boolean;
}
-
/** Rebuild a node with `fn` applied to each child; identity when childless.
* Shared by the degrade canonicalizers so none re-implements the walk. */
function mapChildren(
@@ -250,7 +248,6 @@ function applyDegrades(tree: PmStructuralNode): {
return { normalized: current, fired };
}
-
export function comparePmStructural(
expected: PmStructuralNode,
actual: PmStructuralNode,
diff --git a/packages/core/src/bridge/subsequence.ts b/packages/core/src/bridge/subsequence.ts
index dca644141..af20de1e2 100644
--- a/packages/core/src/bridge/subsequence.ts
+++ b/packages/core/src/bridge/subsequence.ts
@@ -1,4 +1,3 @@
-
/** True when `needle` is a subsequence of `haystack` (two-pointer, O(n+m)):
* insertions in `haystack` are free; any dropped or substituted `needle` byte
* fails. */
diff --git a/packages/core/src/markdown/callout-transformer.ts b/packages/core/src/markdown/callout-transformer.ts
index a363dfd54..83d47404a 100644
--- a/packages/core/src/markdown/callout-transformer.ts
+++ b/packages/core/src/markdown/callout-transformer.ts
@@ -1,4 +1,3 @@
-
import type { Blockquote, Paragraph, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/code-fence.ts b/packages/core/src/markdown/code-fence.ts
index 4499dbc92..9807a7e82 100644
--- a/packages/core/src/markdown/code-fence.ts
+++ b/packages/core/src/markdown/code-fence.ts
@@ -1,4 +1,3 @@
-
export function selectFenceChar(info: string): '`' | '~' {
return info.includes('`') ? '~' : '`';
}
diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.ts
index 34704165b..7415c474a 100644
--- a/packages/core/src/markdown/comment-promoter.ts
+++ b/packages/core/src/markdown/comment-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Paragraph, PhrasingContent, Root, RootContent, Text } from 'mdast';
import { SKIP, visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/dedent-block-jsx-close.ts b/packages/core/src/markdown/dedent-block-jsx-close.ts
index b6299a948..ece5c02a1 100644
--- a/packages/core/src/markdown/dedent-block-jsx-close.ts
+++ b/packages/core/src/markdown/dedent-block-jsx-close.ts
@@ -1,4 +1,3 @@
-
import { findFencedRegions, isInsideFence } from './fence-regions.ts';
const INDENTED_BLOCK_JSX_CLOSE_RE = /^([ ]{1,3})(<\/[A-Z][A-Za-z0-9_]*\s*>)([ \t]*)$/gm;
diff --git a/packages/core/src/markdown/details-accordion-promoter.ts b/packages/core/src/markdown/details-accordion-promoter.ts
index acd398aa6..54774764a 100644
--- a/packages/core/src/markdown/details-accordion-promoter.ts
+++ b/packages/core/src/markdown/details-accordion-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/div-align-promoter.ts b/packages/core/src/markdown/div-align-promoter.ts
index ba9b56384..43ecdc709 100644
--- a/packages/core/src/markdown/div-align-promoter.ts
+++ b/packages/core/src/markdown/div-align-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';
import type { MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/fence-regions.ts b/packages/core/src/markdown/fence-regions.ts
index 4513da9bb..6d3f3643e 100644
--- a/packages/core/src/markdown/fence-regions.ts
+++ b/packages/core/src/markdown/fence-regions.ts
@@ -1,4 +1,3 @@
-
const FENCE_RE = /^(`{3,}|~{3,})/gm;
export function findFencedRegions(src: string): Array<[number, number]> {
diff --git a/packages/core/src/markdown/fixtures/index.ts b/packages/core/src/markdown/fixtures/index.ts
index 6931623c7..00f5771ee 100644
--- a/packages/core/src/markdown/fixtures/index.ts
+++ b/packages/core/src/markdown/fixtures/index.ts
@@ -1,4 +1,3 @@
-
import { readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -9,7 +8,6 @@ function fixturePath(...segments: string[]): string {
return resolve(FIXTURES_DIR, ...segments);
}
-
interface GfmExample {
section: string;
markdown: string;
@@ -19,7 +17,6 @@ export function loadGfmExamples(): GfmExample[] {
return JSON.parse(readFileSync(fixturePath('gfm', 'examples.json'), 'utf8')) as GfmExample[];
}
-
interface MdxCrashEntry {
id: string;
input: string;
@@ -71,7 +68,6 @@ export function loadLargeEmbedFixtures(): LargeEmbedFixture[] {
) as LargeEmbedFixture[];
}
-
export function loadPrd6955Before(): string {
return readFileSync(fixturePath('regression', 'prd-6955-before.md'), 'utf8');
}
@@ -80,7 +76,6 @@ export function loadPrd6955CorruptedTriplicated(): string {
return readFileSync(fixturePath('regression', 'prd-6955-corrupted-triplicated.md'), 'utf8');
}
-
export interface NgPinnedCase {
id: string;
name: string;
@@ -97,7 +92,6 @@ export function loadNgPinnedCases(): NgPinnedCase[] {
) as NgPinnedCase[];
}
-
export function loadLargeRealistic(): string {
return readFileSync(fixturePath('perf', 'large-realistic.md'), 'utf8');
}
diff --git a/packages/core/src/markdown/fixtures/perf/generate.ts b/packages/core/src/markdown/fixtures/perf/generate.ts
index daa3ef82b..8b1eb8519 100644
--- a/packages/core/src/markdown/fixtures/perf/generate.ts
+++ b/packages/core/src/markdown/fixtures/perf/generate.ts
@@ -1,4 +1,3 @@
-
import { writeFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -11,7 +10,6 @@ const BASELINE_ONLY_COUNTS = [500, 2500] as const;
const SEED = 0xf1de1117;
-
function mulberry32(seed: number): () => number {
let a = seed >>> 0;
return () => {
@@ -38,7 +36,6 @@ function pickWeighted<T>(rand: () => number, items: readonly [T, number][]): T {
return items[items.length - 1][0];
}
-
const WORDS = [
'lorem',
'ipsum',
@@ -156,7 +153,6 @@ function mdxBlock(rand: () => number): string {
return `<${name}>\n\n${sentence(rand)}\n\n</${name}>`;
}
-
type BlockKind = 'paragraph' | 'heading' | 'list' | 'code' | 'table' | 'mdx';
const MIX: readonly [BlockKind, number][] = [
@@ -195,7 +191,6 @@ function generateDocument(blockCount: number, seed: number): string {
return `${blocks.join('\n\n')}\n`;
}
-
function main(): void {
for (const count of [...BLOCK_COUNTS, ...BASELINE_ONLY_COUNTS]) {
const doc = generateDocument(count, SEED);
diff --git a/packages/core/src/markdown/guard-flanking-matrix.ts b/packages/core/src/markdown/guard-flanking-matrix.ts
index 32c055c5b..420dc0fe5 100644
--- a/packages/core/src/markdown/guard-flanking-matrix.ts
+++ b/packages/core/src/markdown/guard-flanking-matrix.ts
@@ -7,7 +7,6 @@ import {
import { BACKSLASH_GUARD_SUBSTITUTIONS, encodeBackslashEscapes } from './backslash-escape-guard.ts';
import { ENTITY_REF_GUARD_SUBSTITUTIONS, encodeEntityRefs } from './entity-ref-guard.ts';
-
export const ATTENTION_DELIMITERS = ['*', '_', '**', '~~', '=='] as const;
export type FlankClass = 'whitespace' | 'punctuation' | 'other';
diff --git a/packages/core/src/markdown/handler-shadow-audit.ts b/packages/core/src/markdown/handler-shadow-audit.ts
index 283913255..2653473da 100644
--- a/packages/core/src/markdown/handler-shadow-audit.ts
+++ b/packages/core/src/markdown/handler-shadow-audit.ts
@@ -1,4 +1,3 @@
-
export interface HandlerShadowWitness {
input: string;
expect: 'byte' | 'byte-and-reparse-type';
diff --git a/packages/core/src/markdown/highlight-promoter.ts b/packages/core/src/markdown/highlight-promoter.ts
index 5d1000cc4..da0a81d23 100644
--- a/packages/core/src/markdown/highlight-promoter.ts
+++ b/packages/core/src/markdown/highlight-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Parent, PhrasingContent, Root, Text } from 'mdast';
import type { MdxJsxTextElement } from 'mdast-util-mdx';
import { SKIP, visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/html-to-mdast.ts b/packages/core/src/markdown/html-to-mdast.ts
index 9681c0056..787315157 100644
--- a/packages/core/src/markdown/html-to-mdast.ts
+++ b/packages/core/src/markdown/html-to-mdast.ts
@@ -1,4 +1,3 @@
-
import type { Element as HastElement, Root as HastRoot } from 'hast';
import type { List, Nodes as MdastNodes, Root as MdastRoot } from 'mdast';
import rehypeParse from 'rehype-parse';
@@ -129,8 +128,7 @@ export function htmlToMdast(html: string, options?: HtmlToMdastOptions): MdastRo
throw new HtmlPayloadTooLargeError(html.length, maxBytes);
}
- const processor = unified()
- .use(rehypeParse, { fragment: true });
+ const processor = unified().use(rehypeParse, { fragment: true });
for (const plugin of cleanupPlugins) {
processor.use(plugin);
diff --git a/packages/core/src/markdown/image-promoter.ts b/packages/core/src/markdown/image-promoter.ts
index 994eb6917..706fa9afb 100644
--- a/packages/core/src/markdown/image-promoter.ts
+++ b/packages/core/src/markdown/image-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Image, Paragraph, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/index.ts b/packages/core/src/markdown/index.ts
index ec1ac1b7e..779e27500 100644
--- a/packages/core/src/markdown/index.ts
+++ b/packages/core/src/markdown/index.ts
@@ -1,4 +1,3 @@
-
import {
type FromProseMirrorOptions,
fromPmMark,
@@ -207,7 +206,6 @@ export class MarkdownManager {
}
}
-
const registry = createRegistry();
function destructureAttrs(
@@ -256,7 +254,6 @@ function destructureAttrs(
return result;
}
-
function hasDirtyDescendant(node: PmNode): boolean {
let found = false;
node.descendants((child) => {
@@ -279,7 +276,6 @@ function effectiveDirty(node: PmNode, freshnessChecker?: StructuralFreshnessChec
return freshnessChecker ? freshnessChecker.isDiverged(node.toJSON()) : false;
}
-
function isEmptyMdastParagraph(node: MdastNodes): boolean {
if (node.type !== 'paragraph') return false;
const children = node.children ?? [];
@@ -348,7 +344,6 @@ function extractTextFromMdastNodes(nodes: MdastNodes[]): string {
return out;
}
-
import {
AUDIO_EXTENSIONS,
FILE_ATTACHMENT_EXTENSIONS,
@@ -601,7 +596,6 @@ function buildMdastToPmHandlers(
}));
}
-
if (m.emphasis) {
handlers.emphasis = toPmMark(m.emphasis, (node: Emphasis) => ({
sourceDelimiter: node.data?.sourceDelimiter ?? '*',
@@ -682,7 +676,6 @@ function buildMdastToPmHandlers(
}));
}
-
if (m.link) {
const sourceLiteralMark = m.sourceLiteral;
handlers.link = (node: Link, _parent: MdastParent, state: MdastToPmState) => {
@@ -980,7 +973,6 @@ function buildMdastToPmHandlers(
};
}
-
const blockUnknownHandler = (node: {
type: string;
position?: { start: { offset: number }; end: { offset: number } };
@@ -1106,7 +1098,6 @@ function buildMdastToPmHandlers(
return handlers as RemarkProseMirrorOptions['handlers'];
}
-
function buildPmToMdastHandlers(
schema: Schema,
freshness: FreshnessCheckerHolder,
diff --git a/packages/core/src/markdown/lint/applies-to.ts b/packages/core/src/markdown/lint/applies-to.ts
index b79e9aef7..fa0be9e86 100644
--- a/packages/core/src/markdown/lint/applies-to.ts
+++ b/packages/core/src/markdown/lint/applies-to.ts
@@ -1,4 +1,3 @@
-
import picomatch from 'picomatch';
import { SUPPORTED_DOC_EXTENSIONS } from '../../constants/doc-extensions.ts';
diff --git a/packages/core/src/markdown/lint/config-files.ts b/packages/core/src/markdown/lint/config-files.ts
index 94b34dee1..312c9c74b 100644
--- a/packages/core/src/markdown/lint/config-files.ts
+++ b/packages/core/src/markdown/lint/config-files.ts
@@ -1,4 +1,3 @@
-
const MARKDOWNLINT_JSON_CONFIG_FILES: ReadonlySet<string> = new Set([
'.markdownlint.json',
'.markdownlint.jsonc',
diff --git a/packages/core/src/markdown/lint/config-schemas.ts b/packages/core/src/markdown/lint/config-schemas.ts
index 1e3ad29c6..c400441b2 100644
--- a/packages/core/src/markdown/lint/config-schemas.ts
+++ b/packages/core/src/markdown/lint/config-schemas.ts
@@ -39,7 +39,6 @@ const fullPluginShape = Object.fromEntries(
LINT_PLUGINS.map((plugin) => [plugin.id, plugin.sliceSchema]),
) as z.ZodRawShape;
-
export const LinterConfigSchema = z.object({
enabled: z.boolean(),
plugins: z.object(fullPluginShape),
diff --git a/packages/core/src/markdown/lint/default-config.ts b/packages/core/src/markdown/lint/default-config.ts
index a51f2ffb0..d48eea5e4 100644
--- a/packages/core/src/markdown/lint/default-config.ts
+++ b/packages/core/src/markdown/lint/default-config.ts
@@ -6,7 +6,6 @@ export const DEFAULT_MARKDOWNLINT_CONFIG: Record<string, MarkdownlintRuleSetting
MD013: false,
};
-
export function resolveMarkdownlintConfig(
rules: Record<string, MarkdownlintRuleSetting> | undefined,
): Configuration {
diff --git a/packages/core/src/markdown/lint/frontmatter-schema-edit.ts b/packages/core/src/markdown/lint/frontmatter-schema-edit.ts
index 9c9542661..ef478e268 100644
--- a/packages/core/src/markdown/lint/frontmatter-schema-edit.ts
+++ b/packages/core/src/markdown/lint/frontmatter-schema-edit.ts
@@ -1,4 +1,3 @@
-
import { CANONICAL_SCHEMA_DIALECT_URIS, DEFAULT_SCHEMA_DIALECT } from './frontmatter-validate.ts';
export interface FrontmatterFieldConstraint {
diff --git a/packages/core/src/markdown/lint/frontmatter-validate.ts b/packages/core/src/markdown/lint/frontmatter-validate.ts
index b96d19182..0d4c9a0df 100644
--- a/packages/core/src/markdown/lint/frontmatter-validate.ts
+++ b/packages/core/src/markdown/lint/frontmatter-validate.ts
@@ -1,4 +1,3 @@
-
import Ajv, { type ValidateFunction } from 'ajv';
import Ajv2019 from 'ajv/dist/2019.js';
import Ajv2020 from 'ajv/dist/2020.js';
diff --git a/packages/core/src/markdown/lint/index.ts b/packages/core/src/markdown/lint/index.ts
index 1ca263610..af38c2ae2 100644
--- a/packages/core/src/markdown/lint/index.ts
+++ b/packages/core/src/markdown/lint/index.ts
@@ -1,4 +1,3 @@
-
import { LINT_PLUGINS, type LinterConfig } from './plugins.ts';
import type { LintDiagnostic } from './types.ts';
diff --git a/packages/core/src/markdown/lint/plugins.ts b/packages/core/src/markdown/lint/plugins.ts
index be5871ed9..5e832aa19 100644
--- a/packages/core/src/markdown/lint/plugins.ts
+++ b/packages/core/src/markdown/lint/plugins.ts
@@ -1,4 +1,3 @@
-
import { z } from 'zod';
import { DEFAULT_MARKDOWNLINT_CONFIG, resolveMarkdownlintConfig } from './default-config.ts';
import {
@@ -14,7 +13,6 @@ import {
type MarkdownlintSlice,
} from './types.ts';
-
const MarkdownlintRuleSettingSchema = z.union([
z.boolean(),
z.enum(MARKDOWNLINT_RULE_SEVERITIES),
diff --git a/packages/core/src/markdown/lint/types.ts b/packages/core/src/markdown/lint/types.ts
index 3dae5c031..01ce4a5af 100644
--- a/packages/core/src/markdown/lint/types.ts
+++ b/packages/core/src/markdown/lint/types.ts
@@ -1,4 +1,3 @@
-
import type { BrokenLinkReason } from '../../schemas/api/agent-write.ts';
export const LINT_PLUGIN_IDS = ['markdownlint', 'frontmatter'] as const;
@@ -99,7 +98,6 @@ export interface FrontmatterSlice {
schemas: ResolvedFrontmatterSchemaEntry[];
}
-
interface RuleOptionSpecBase {
key: string;
description: string;
diff --git a/packages/core/src/markdown/lint/validation-counts.ts b/packages/core/src/markdown/lint/validation-counts.ts
index 437cc539a..98238656e 100644
--- a/packages/core/src/markdown/lint/validation-counts.ts
+++ b/packages/core/src/markdown/lint/validation-counts.ts
@@ -1,4 +1,3 @@
-
export interface ValidationSourceCounts {
errorCount: number;
warningCount: number;
diff --git a/packages/core/src/markdown/math-promoter.ts b/packages/core/src/markdown/math-promoter.ts
index bd79424c7..a5b511f25 100644
--- a/packages/core/src/markdown/math-promoter.ts
+++ b/packages/core/src/markdown/math-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Code, Root } from 'mdast';
import type { Math as MdastMath } from 'mdast-util-math';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
diff --git a/packages/core/src/markdown/mdast-to-hast-handlers.ts b/packages/core/src/markdown/mdast-to-hast-handlers.ts
index 00fbc0035..ed89371d0 100644
--- a/packages/core/src/markdown/mdast-to-hast-handlers.ts
+++ b/packages/core/src/markdown/mdast-to-hast-handlers.ts
@@ -1,4 +1,3 @@
-
import type { Comment, Element, ElementContent, Properties } from 'hast';
import type { FootnoteDefinition, FootnoteReference } from 'mdast';
import type { MdxJsxFlowElement, MdxJsxTextElement } from 'mdast-util-mdx';
diff --git a/packages/core/src/markdown/mdast-to-html.ts b/packages/core/src/markdown/mdast-to-html.ts
index df788a80d..8ce2b2492 100644
--- a/packages/core/src/markdown/mdast-to-html.ts
+++ b/packages/core/src/markdown/mdast-to-html.ts
@@ -1,4 +1,3 @@
-
import type { Element, Root as HastRoot, Text as HastText } from 'hast';
import type { Root as MdastRoot, Text as MdastText } from 'mdast';
import type { Handler } from 'mdast-util-to-hast';
diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.ts
index fa3cfcd86..bfd7e3109 100644
--- a/packages/core/src/markdown/merged-walker.ts
+++ b/packages/core/src/markdown/merged-walker.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Parent, Root } from 'mdast';
import { SKIP, visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/mermaid-promoter.ts b/packages/core/src/markdown/mermaid-promoter.ts
index 17ed2b829..1a897fca8 100644
--- a/packages/core/src/markdown/mermaid-promoter.ts
+++ b/packages/core/src/markdown/mermaid-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Code, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/parse-with-fallback.ts b/packages/core/src/markdown/parse-with-fallback.ts
index 4aa0490c4..d988f4b8b 100644
--- a/packages/core/src/markdown/parse-with-fallback.ts
+++ b/packages/core/src/markdown/parse-with-fallback.ts
@@ -168,7 +168,6 @@ export function parseRecursive(
}
}
-
interface VFilePlace {
offset?: number;
start?: { offset?: number };
@@ -187,7 +186,6 @@ function extractErrorOffset(err: unknown): number | undefined {
return undefined;
}
-
interface Region {
start: number;
end: number;
@@ -211,7 +209,6 @@ function nearestBlankLineAfter(src: string, offset: number): number | null {
return null;
}
-
export interface TagEvent {
kind: 'open' | 'close' | 'self-close';
name: string;
@@ -358,7 +355,6 @@ function findFallbackRegion(src: string, errorOffset: number): Region {
return { start: blockStart, end: blockEnd };
}
-
interface SourceBlock {
src: string;
start: number;
@@ -456,7 +452,6 @@ function tryPerBlockFallback(
};
}
-
function wholeDocRawText(source: string): JSONContent {
return {
type: 'doc',
diff --git a/packages/core/src/markdown/parser-drop-closure.ts b/packages/core/src/markdown/parser-drop-closure.ts
index 43d420187..e6ab4fd57 100644
--- a/packages/core/src/markdown/parser-drop-closure.ts
+++ b/packages/core/src/markdown/parser-drop-closure.ts
@@ -1,4 +1,3 @@
-
export type DroppedTokenAdjudication =
| {
kind: 'format-dof-axis';
diff --git a/packages/core/src/markdown/pipeline.ts b/packages/core/src/markdown/pipeline.ts
index 55736041c..0e3224206 100644
--- a/packages/core/src/markdown/pipeline.ts
+++ b/packages/core/src/markdown/pipeline.ts
@@ -1,4 +1,3 @@
-
import {
type FromProseMirrorOptions,
fromProseMirror,
diff --git a/packages/core/src/markdown/position-aware-join.ts b/packages/core/src/markdown/position-aware-join.ts
index ccf06e94d..91cdf658f 100644
--- a/packages/core/src/markdown/position-aware-join.ts
+++ b/packages/core/src/markdown/position-aware-join.ts
@@ -1,4 +1,3 @@
-
import type { Join } from 'mdast-util-to-markdown';
import type { Position } from 'unist';
import { isBlankLineParagraph } from './zero-emission-blocks.ts';
diff --git a/packages/core/src/markdown/position-slice.ts b/packages/core/src/markdown/position-slice.ts
index e5b4c9eba..0f399d34c 100644
--- a/packages/core/src/markdown/position-slice.ts
+++ b/packages/core/src/markdown/position-slice.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Root } from 'mdast';
import { visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
@@ -477,8 +476,7 @@ export function applyPositionSliceToNode(
const first = source[startOff];
if (first !== '[' && first !== '<' && !node.title) {
node.data.sourceStyle = 'gfm-autolink';
- }
- else if (first === '[') {
+ } else if (first === '[') {
const slice = source.slice(startOff, endOff);
const closeBracketIdx = slice.lastIndexOf('](');
if (closeBracketIdx !== -1) {
diff --git a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
index ca225ce9b..db10fa54b 100644
--- a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
+++ b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
@@ -1,4 +1,3 @@
-
import type { Comment, Element, Root, Text } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
index 3a2524a9a..34068d103 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
@@ -1,4 +1,3 @@
-
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
index 2279a0189..93151d43b 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
@@ -1,4 +1,3 @@
-
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
index a0f467c42..188f02d83 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
@@ -1,4 +1,3 @@
-
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
index 4e8542a21..4ba2c3418 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
@@ -1,4 +1,3 @@
-
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
index a3c96b24a..1a74b1272 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
@@ -1,4 +1,3 @@
-
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
index e95cf43d6..de35e7b79 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
@@ -1,4 +1,3 @@
-
import type { Comment, Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
index ffdb4d5b5..b4be1b2ea 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
@@ -1,4 +1,3 @@
-
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
index e2a96d1a7..3c8d88b7c 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
@@ -1,4 +1,3 @@
-
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/resolve-image-url.ts b/packages/core/src/markdown/resolve-image-url.ts
index 0389575ac..cf2c9da8e 100644
--- a/packages/core/src/markdown/resolve-image-url.ts
+++ b/packages/core/src/markdown/resolve-image-url.ts
@@ -1,4 +1,3 @@
-
import { isRelativeUrl } from './safe-url.ts';
function isDevDiagnosticContext(): boolean {
diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.ts
index 8be632ba4..4d3250d3a 100644
--- a/packages/core/src/markdown/safe-url.ts
+++ b/packages/core/src/markdown/safe-url.ts
@@ -1,4 +1,3 @@
-
export const SAFE_URL_SCHEMES = ['https', 'http', 'mailto', 'tel', 'ftp', 'sms'] as const;
const SCHEME_ALT = SAFE_URL_SCHEMES.map((s) => `${s}:`).join('|');
diff --git a/packages/core/src/markdown/serialize-fidelity.test-helper.ts b/packages/core/src/markdown/serialize-fidelity.test-helper.ts
index 96304e7a5..0dd54070e 100644
--- a/packages/core/src/markdown/serialize-fidelity.test-helper.ts
+++ b/packages/core/src/markdown/serialize-fidelity.test-helper.ts
@@ -1,4 +1,3 @@
-
import type { JSONContent } from '@tiptap/core';
import type { Nodes } from 'mdast';
import { expect } from 'vitest';
diff --git a/packages/core/src/markdown/serialize-helpers.ts b/packages/core/src/markdown/serialize-helpers.ts
index 93798cf83..7cac5b042 100644
--- a/packages/core/src/markdown/serialize-helpers.ts
+++ b/packages/core/src/markdown/serialize-helpers.ts
@@ -1,4 +1,3 @@
-
import type { Node as PmNode } from '@tiptap/pm/model';
import type {
MdxJsxAttribute,
diff --git a/packages/core/src/markdown/single-dollar-math-promoter.ts b/packages/core/src/markdown/single-dollar-math-promoter.ts
index 8c08b7a04..b012a5aff 100644
--- a/packages/core/src/markdown/single-dollar-math-promoter.ts
+++ b/packages/core/src/markdown/single-dollar-math-promoter.ts
@@ -1,4 +1,3 @@
-
import type { PhrasingContent, Root, Text } from 'mdast';
import type { InlineMath } from 'mdast-util-math';
import { SKIP, visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/to-markdown-handlers.ts b/packages/core/src/markdown/to-markdown-handlers.ts
index 959cc0bd2..3e79f8cb6 100644
--- a/packages/core/src/markdown/to-markdown-handlers.ts
+++ b/packages/core/src/markdown/to-markdown-handlers.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Parents } from 'mdast';
import type { MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import type { Handle, Info, State } from 'mdast-util-to-markdown';
diff --git a/packages/core/src/markdown/underline-promoter.ts b/packages/core/src/markdown/underline-promoter.ts
index 6e6d73400..0f1b0f27d 100644
--- a/packages/core/src/markdown/underline-promoter.ts
+++ b/packages/core/src/markdown/underline-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Parent, Root } from 'mdast';
import type { MdxJsxTextElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/unknown-mdast-guard.ts b/packages/core/src/markdown/unknown-mdast-guard.ts
index 932d7d2a8..1a082bda7 100644
--- a/packages/core/src/markdown/unknown-mdast-guard.ts
+++ b/packages/core/src/markdown/unknown-mdast-guard.ts
@@ -1,4 +1,3 @@
-
import type { Root as MdastRoot } from 'mdast';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/whitespace-char-ref.ts b/packages/core/src/markdown/whitespace-char-ref.ts
index ac9f5239b..d578476a7 100644
--- a/packages/core/src/markdown/whitespace-char-ref.ts
+++ b/packages/core/src/markdown/whitespace-char-ref.ts
@@ -1,4 +1,3 @@
-
const INLINE_WHITESPACE_BY_CODE: ReadonlyMap<number, string> = new Map([
[0x20, ' '],
[0x09, '\t'],
diff --git a/packages/core/src/markdown/wiki-link-micromark.ts b/packages/core/src/markdown/wiki-link-micromark.ts
index afd9936fe..6dad26200 100644
--- a/packages/core/src/markdown/wiki-link-micromark.ts
+++ b/packages/core/src/markdown/wiki-link-micromark.ts
@@ -17,7 +17,6 @@ declare module 'micromark-util-types' {
}
}
-
const CODE_BANG = 33; // !
const CODE_LBRACKET = 91; // [
const CODE_RBRACKET = 93; // ]
@@ -261,7 +260,6 @@ export function wikiLinkSyntax(): Extension {
};
}
-
function enterWikiLink(this: CompileContext, token: Token) {
this.enter(
{
@@ -387,7 +385,6 @@ export const wikiLinkToMarkdown: {
unsafe: [{ character: '[', inConstruct: ['phrasing'] }],
};
-
const MICROMARK_EXT = wikiLinkSyntax();
export function remarkWikiLink(this: Processor) {