Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Add vertical editor split workspace (#2873)

Dimitri POSTOLOVc8f8d193dfef
diff --git a/.changeset/editor-tab-path-tooltip.md b/.changeset/editor-tab-path-tooltip.md
index 734a3daf3..84c7ac419 100644
--- a/.changeset/editor-tab-path-tooltip.md
+++ b/.changeset/editor-tab-path-tooltip.md
@@ -2,4 +2,4 @@
"@inkeep/open-knowledge": patch
---
-Hovering an editor tab now shows the file's full path in a tooltip, so two tabs with the same file name — `SPEC.md` from two different folders, say — are no longer indistinguishable. The path was previously only available through the browser's native `title` tooltip, which is unstyled and takes about a second to appear; it now uses the app's own tooltip and appears immediately. Asset and skill-bundle-file tabs, which had no hover path at all, now show one too, and the tooltip stays out of the way while you drag a tab to reorder it.
+Hovering an editor tab now shows the file's full path immediately in an app-styled tooltip, so two tabs with the same file name — `SPEC.md` from two different folders, say — are no longer indistinguishable. Asset and skill-bundle-file tabs now disclose their paths too, and the tooltip stays out of the way while you drag a tab to reorder it.
diff --git a/.changeset/vertical-editor-splits.md b/.changeset/vertical-editor-splits.md
new file mode 100644
index 000000000..042f254df
--- /dev/null
+++ b/.changeset/vertical-editor-splits.md
@@ -0,0 +1,15 @@
+---
+"@inkeep/open-knowledge": minor
+---
+
+Add a resizable vertical split workspace with one shared header for tabs and
+workspace actions. Drag tabs or sidebar files into pane edges, or use tab
+actions, to create and populate panes. Pane sizes, open tabs, and focus restore
+with the project session, while editor actions and the right document and agent
+panels follow the focused pane below the header.
+
+Polish tabs across single and split panes with stable sizing, horizontal
+overflow scrolling, edge fades, clearer drag feedback, and shared actions for
+documents, folders, and assets. Existing preview tabs keep their replaceable
+and pinned behavior while supporting the same drag, split, and overflow
+interactions as regular tabs.
diff --git a/docs/content/features/editor.mdx b/docs/content/features/editor.mdx
index bb445c2b2..814a3fd08 100644
--- a/docs/content/features/editor.mdx
+++ b/docs/content/features/editor.mdx
@@ -202,6 +202,14 @@ Five tools stay gated: `delete` and `move` (knowledge-base-wide blast radius), `
Turn it off in **Settings → Terminal → “Let agents use OpenKnowledge without asking”** ([`agents.autoApproveOkTools`](../reference/configuration.mdx)). It applies to every project on this machine and defaults on.
+## Tabs and split panes
+
+Tabs share the main editor header and shrink as the row fills, keeping every open target visible without a horizontal scrollbar. Drag a tab to reorder it. Opening a file from the sidebar uses a lightweight preview tab by default: the next single-clicked file replaces it, while double-clicking the tab title, pinning, or choosing **Keep open** from its context menu keeps it open. Turn previews off with **Settings → Preferences → Preview tabs** ([`editor.previewTabs`](/docs/reference/configuration)).
+
+To work side by side, drag any document, folder, or **New tab** to the left or right edge of the editor. The blue drop indicator shows where the new vertical pane will open. You can also right-click a tab and choose **Move to new pane left** or **Move to new pane right**; from the keyboard, focus the tab, press `Shift+F10` (or the Menu key), then choose the same command. Drag the divider to resize panes. Each pane keeps its own active tab, while the document panel follows the pane you most recently focused. Moving or closing a pane's last tab removes the pane automatically.
+
+Open tabs, pane order, sizes, and the focused pane are restored with the project after a clean restart.
+
## Command palette
`Cmd+K` opens the command palette in both the desktop app and the browser. Type to jump to any file or folder, run create commands, open the graph or settings, or dispatch to an agent; recently opened entries surface first. In the desktop app it also switches projects and worktrees.
@@ -311,4 +319,3 @@ For recovery + history, see [Timeline and recovery](./timeline-and-recovery.mdx)
- [Configuration reference](../reference/configuration.mdx): `.ok/config.yml` schema including `appearance.sidebar.*`
- [Agent activity](./agent-activity.mdx): review and undo per-session agent edits
- [Timeline and recovery](./timeline-and-recovery.mdx): version history and restore
-
diff --git a/docs/content/reference/configuration.mdx b/docs/content/reference/configuration.mdx
index 2107a2261..f8f94ab9a 100644
--- a/docs/content/reference/configuration.mdx
+++ b/docs/content/reference/configuration.mdx
@@ -49,7 +49,7 @@ A key set in a file more specific than its scope (a user-scope key in `.ok/confi
| `remote.url` | string | (unset) | project | Public tunnel URL remote clients connect to (e.g. `https://myproject.ngrok.app`); its host is admitted through the Host-header allowlist. Used only when the server is started with `ok start --remote` (config alone never enables remote access, and there is no server-side auth). See [Remote access](/docs/deploy/remote-access). |
| `remote.port` | number | `24550` | project | Fixed TCP port the server binds when remote access is enabled, so the tunnel's port mapping survives restarts. See [Remote access](/docs/deploy/remote-access). |
| `editor.wordWrap` | boolean | `true` | user | Soft-wrap long lines in the source-mode CodeMirror editor. A personal preference, not project-shared. Toggle from the Settings pane. |
-| `editor.previewTabs` | boolean | `true` | user | Reuse one "preview" tab for single clicks in the Files tree and Skills sidebar, so browsing does not accumulate tabs. Set `false` to open every click in its own tab. A personal preference, not project-shared. Back/forward navigation and rename transitions always reuse the current tab regardless. Toggle from the Settings pane. |
+| `editor.previewTabs` | boolean | `true` | user | Reuse one replaceable preview tab for single clicks in the Files tree and Skills sidebar, so browsing does not accumulate tabs. Double-click the tab title, pin it, or choose **Keep open** from its context menu to make it permanent. Set `false` to open every click in its own tab. Rename transitions still reuse the current tab; back/forward navigation focuses the target's existing tab, or opens a permanent one when it is no longer open. A personal preference; toggle it from **Settings → Preferences → Preview tabs**. |
| `appearance.preview.autoOpen` | boolean | `true` | user | Whether the agent should open or refresh the OpenKnowledge preview when it edits a doc through the MCP. Default `true` lets the agent route the preview by host capability: the host's in-app browser (Cursor preview pane, Codex's built-in browser, Claude Code Desktop) when one exists, the system browser otherwise. Set `false` to keep the agent's hands off your preview window. This is useful when you're already viewing the doc in OK Desktop, a browser tab on a second display, a non-default browser, or any flow where your extensions / accessibility tooling only work in your own browser. The agent then surfaces the URL on request but does not navigate. The change takes effect on the next preview-related tool call. Toggle from **Settings → Preferences → "Open preview when agent edits"**. |
| `terminal.enabled` | `boolean \| null` | `null` | project-local | Opt-out for the in-app terminal (a real OS shell at full user privilege). On by default; set `false` to disable it for this project on this machine. |
| `agents.autoApproveOkTools` | boolean | `true` | user | Auto-approve OpenKnowledge's own MCP tools (and the `ok open` command on Claude) for agents launched from the built-in [docked terminal](/docs/features/editor#terminal), so reading and writing the knowledge base runs without a per-call approval prompt. Destructive tools (`delete`, `move`, `share_link`, `install`) still prompt; other shell commands and non-OpenKnowledge file edits are untouched. Per-machine preference; toggle from **Settings → Terminal**. Best-effort per agent — Claude uses an allow/deny list, Codex uses its per-server `approve` mode (and only when its OpenKnowledge entry is already configured). |
diff --git a/packages/app/package.json b/packages/app/package.json
index d54c73780..5269472de 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/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/slash-command-auto-open.e2e.ts tests/stress/graph-panel-surfaces.e2e.ts tests/stress/clipboard-relative-url-source-fallback.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/prop-upload.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",
+ "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/create-then-rename-editable.e2e.ts tests/stress/find-replace.e2e.ts tests/stress/editor-tabs.e2e.ts tests/stress/editor-split-view.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/slash-command-auto-open.e2e.ts tests/stress/graph-panel-surfaces.e2e.ts tests/stress/clipboard-relative-url-source-fallback.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/prop-upload.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",
"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",
@@ -46,7 +46,7 @@
{
"name": "main app bundle (gzipped)",
"path": "dist/assets/index-*.js",
- "limit": "485 kB",
+ "limit": "487 kB",
"gzip": true,
"running": false
},
diff --git a/packages/app/src/App.dom.test.tsx b/packages/app/src/App.dom.test.tsx
index a2d96e98d..99817ada5 100644
--- a/packages/app/src/App.dom.test.tsx
+++ b/packages/app/src/App.dom.test.tsx
@@ -28,6 +28,7 @@ let openTabs: string[] = [];
let loading = false;
let singleFileMode = false;
let tabSessionLoaded = true;
+let mergedConfig: { editor: { previewTabs: boolean } } | null = null;
let fetchApiConfigMock = vi.fn(() =>
Promise.resolve({
status: 'ok' as const,
@@ -41,8 +42,12 @@ let fetchApiConfigMock = vi.fn(() =>
);
let clearTargetMock = vi.fn(() => {});
let syncOpenTabsWithKnownTargetsMock = vi.fn(() => {});
+let promoteAllPreviewTabsMock = vi.fn(() => {});
let openTargetTransitionMock = vi.fn(
- (_: NavigationTarget, _options?: { tabBehavior?: 'append' | 'replace-active' }) => {},
+ (
+ _: NavigationTarget,
+ _options: { disposition: 'preview' | 'permanent'; consumeActiveNewTab: boolean },
+ ) => {},
);
let resolveNavigationTargetMock = vi.fn(
(docName: string): NavigationTarget => ({ kind: 'doc', target: docName, docName }),
@@ -61,8 +66,15 @@ vi.doMock('@/editor/DocumentContext', () => ({
),
useDocumentContext: () => ({
activeDocName: activeTarget?.kind === 'doc' ? activeTarget.docName : null,
+ activeTabId:
+ activeTarget?.kind === 'doc'
+ ? activeTarget.docName
+ : activeTarget?.kind === 'missing'
+ ? activeTarget.target
+ : null,
activeTarget,
clearTarget: clearTargetMock,
+ promoteAllPreviewTabs: promoteAllPreviewTabsMock,
syncOpenTabsWithKnownTargets: syncOpenTabsWithKnownTargetsMock,
tabSessionLoaded,
// The skill-tab reconciler reads these at render (no open skill tab here,
@@ -117,14 +129,14 @@ vi.doMock('@/lib/config-provider', () => ({
),
// ValidationFreshness (mounted in the App body) gates on the merged config;
// null merged reads as every default (indicators on).
- useConfigContext: () => ({ merged: null }),
+ useConfigContext: () => ({ merged: mergedConfig }),
}));
// AppBody reads `merged.appearance.preview.autoOpen` to compose the
// "Open in terminal" launch prompt; the ConfigProvider above is a passthrough
// so the real context is never set. Stub the hook to the cold-start shape.
vi.doMock('@/lib/config-context', () => ({
- useConfigContext: () => ({ merged: null }),
+ useConfigContext: () => ({ merged: mergedConfig }),
}));
vi.doMock('@/lib/api-config', () => ({
@@ -267,6 +279,7 @@ function createBridge() {
// to gate the terminal-launch provider (mac-only PTY). Mirror that shape so
// the gate resolves instead of dereferencing undefined.
config: {
+ mode: 'editor' as const,
ptyAvailable: true,
},
};
@@ -304,6 +317,7 @@ describe('App runtime wiring', () => {
loading = false;
singleFileMode = false;
tabSessionLoaded = true;
+ mergedConfig = null;
fetchApiConfigMock = vi.fn(() =>
Promise.resolve({
status: 'ok' as const,
@@ -318,8 +332,12 @@ describe('App runtime wiring', () => {
globalThis.fetch = vi.fn(() => Promise.resolve(new Response(null, { status: 204 }))) as never;
clearTargetMock = vi.fn(() => {});
syncOpenTabsWithKnownTargetsMock = vi.fn(() => {});
+ promoteAllPreviewTabsMock = vi.fn(() => {});
openTargetTransitionMock = vi.fn(
- (_: NavigationTarget, _options?: { tabBehavior?: 'append' | 'replace-active' }) => {},
+ (
+ _: NavigationTarget,
+ _options: { disposition: 'preview' | 'permanent'; consumeActiveNewTab: boolean },
+ ) => {},
);
resolveNavigationTargetMock = vi.fn(
(docName: string): NavigationTarget => ({ kind: 'doc', target: docName, docName }),
@@ -345,6 +363,23 @@ describe('App runtime wiring', () => {
expect(screen.getByTestId('editor-pane')).not.toBeNull();
});
+ test('promotes preview tabs when the setting changes from enabled to disabled', async () => {
+ mergedConfig = { editor: { previewTabs: true } };
+ const view = renderApp();
+
+ expect(promoteAllPreviewTabsMock).not.toHaveBeenCalled();
+
+ mergedConfig = { editor: { previewTabs: false } };
+ view.rerender(<App />);
+
+ await waitFor(() => {
+ expect(promoteAllPreviewTabsMock).toHaveBeenCalledTimes(1);
+ });
+
+ view.rerender(<App />);
+ expect(promoteAllPreviewTabsMock).toHaveBeenCalledTimes(1);
+ });
+
test('passes tracked non-markdown files to tab reconciliation', async () => {
filePaths = new Set(['LICENSE', 'pnpm-workspace.yaml']);
@@ -408,7 +443,10 @@ describe('App runtime wiring', () => {
await waitFor(() => {
expect(downgradeFolderIndexForHashNavMock).toHaveBeenCalledWith(resolved);
- expect(openTargetTransitionMock).toHaveBeenCalledWith(downgraded);
+ expect(openTargetTransitionMock).toHaveBeenCalledWith(downgraded, {
+ disposition: 'permanent',
+ consumeActiveNewTab: true,
+ });
});
expect(openTargetTransitionMock).not.toHaveBeenCalledWith(resolved);
});
@@ -440,7 +478,10 @@ describe('App runtime wiring', () => {
renderApp();
await waitFor(() => {
- expect(openTargetTransitionMock).toHaveBeenCalledWith(missing);
+ expect(openTargetTransitionMock).toHaveBeenCalledWith(missing, {
+ disposition: 'permanent',
+ consumeActiveNewTab: true,
+ });
});
});
@@ -456,15 +497,75 @@ describe('App runtime wiring', () => {
renderApp();
await waitFor(() => {
- expect(openTargetTransitionMock).toHaveBeenCalledWith({
- kind: 'doc',
- target: 'docs/guide.mdx',
- docName: 'docs/guide.mdx',
- });
+ expect(openTargetTransitionMock).toHaveBeenCalledWith(
+ {
+ kind: 'doc',
+ target: 'docs/guide.mdx',
+ docName: 'docs/guide.mdx',
+ },
+ {
+ disposition: 'permanent',
+ consumeActiveNewTab: true,
+ },
+ );
});
expect(resolveNavigationTargetMock).not.toHaveBeenCalled();
});
+ test('does not reopen an already-active hash target after tab state changes', async () => {
+ activeTarget = { kind: 'doc', target: 'page-a', docName: 'page-a' };
+ setHash('#/page-a');
+
+ renderApp();
+
+ await Promise.resolve();
+ expect(openTargetTransitionMock).not.toHaveBeenCalled();
+ });
+
+ test('refreshes an active missing target after the page list resolves it', async () => {
+ activeTarget = { kind: 'missing', target: 'page-a' };
+ setHash('#/page-a');
+
+ renderApp();
+
+ await waitFor(() => {
+ expect(openTargetTransitionMock).toHaveBeenCalledWith(
+ { kind: 'doc', target: 'page-a', docName: 'page-a' },
+ {
+ disposition: 'permanent',
+ consumeActiveNewTab: true,
+ },
+ );
+ });
+ });
+
+ test('defers hash navigation until the persisted tab session has restored', async () => {
+ tabSessionLoaded = false;
+ setHash('#/.editorconfig');
+ const view = renderApp({ bridge: createBridge() });
+
+ await Promise.resolve();
+ expect(resolveNavigationTargetMock).not.toHaveBeenCalled();
+ expect(openTargetTransitionMock).not.toHaveBeenCalled();
+
+ tabSessionLoaded = true;
+ view.rerender(<App />);
+
+ await waitFor(() => {
+ expect(openTargetTransitionMock).toHaveBeenCalledWith(
+ {
+ kind: 'doc',
+ target: '.editorconfig',
+ docName: '.editorconfig',
+ },
+ {
+ disposition: 'permanent',
+ consumeActiveNewTab: true,
+ },
+ );
+ });
+ });
+
test('navigation-history subscription cleans up before remount and invokes each action once', () => {
const back = vi.spyOn(window.history, 'back').mockImplementation(() => {});
const forward = vi.spyOn(window.history, 'forward').mockImplementation(() => {});
@@ -481,16 +582,22 @@ describe('App runtime wiring', () => {
expect(forward).toHaveBeenCalledOnce();
});
- test('history traversal reuses the active tab across same-tab page navigation', async () => {
+ test('history traversal opens permanent canonical tabs', async () => {
setHash('#/page-a');
renderApp();
await waitFor(() => {
- expect(openTargetTransitionMock).toHaveBeenCalledWith({
- kind: 'doc',
- target: 'page-a',
- docName: 'page-a',
- });
+ expect(openTargetTransitionMock).toHaveBeenCalledWith(
+ {
+ kind: 'doc',
+ target: 'page-a',
+ docName: 'page-a',
+ },
+ {
+ disposition: 'permanent',
+ consumeActiveNewTab: true,
+ },
+ );
});
// File-tree navigation opens in the active tab and records the URL with
@@ -509,7 +616,7 @@ describe('App runtime wiring', () => {
target: 'page-b',
docName: 'page-b',
},
- { tabBehavior: 'replace-active' },
+ { disposition: 'permanent', consumeActiveNewTab: true },
);
});
@@ -524,7 +631,7 @@ describe('App runtime wiring', () => {
target: 'page-a',
docName: 'page-a',
},
- { tabBehavior: 'replace-active' },
+ { disposition: 'permanent', consumeActiveNewTab: true },
);
});
@@ -539,7 +646,7 @@ describe('App runtime wiring', () => {
target: 'page-b',
docName: 'page-b',
},
- { tabBehavior: 'replace-active' },
+ { disposition: 'permanent', consumeActiveNewTab: true },
);
});
});
@@ -549,11 +656,17 @@ describe('App runtime wiring', () => {
renderApp();
await waitFor(() => {
- expect(openTargetTransitionMock).toHaveBeenCalledWith({
- kind: 'doc',
- target: 'page-a',
- docName: 'page-a',
- });
+ expect(openTargetTransitionMock).toHaveBeenCalledWith(
+ {
+ kind: 'doc',
+ target: 'page-a',
+ docName: 'page-a',
+ },
+ {
+ disposition: 'permanent',
+ consumeActiveNewTab: true,
+ },
+ );
});
openTargetTransitionMock.mockClear();
@@ -562,20 +675,18 @@ describe('App runtime wiring', () => {
window.dispatchEvent(new HashChangeEvent('hashchange'));
await waitFor(() => {
- expect(openTargetTransitionMock).toHaveBeenCalledWith({
- kind: 'doc',
- target: 'page-b',
- docName: 'page-b',
- });
+ expect(openTargetTransitionMock).toHaveBeenCalledWith(
+ {
+ kind: 'doc',
+ target: 'page-b',
+ docName: 'page-b',
+ },
+ {
+ disposition: 'permanent',
+ consumeActiveNewTab: true,
+ },
+ );
});
- expect(openTargetTransitionMock).not.toHaveBeenCalledWith(
- {
- kind: 'doc',
- target: 'page-b',
- docName: 'page-b',
- },
- { tabBehavior: 'replace-active' },
- );
});
test('active doc and folder targets are pushed to the desktop bridge', async () => {
diff --git a/packages/app/src/App.tsx b/packages/app/src/App.tsx
index 6a25f3b35..7ff992a52 100644
--- a/packages/app/src/App.tsx
+++ b/packages/app/src/App.tsx
@@ -35,15 +35,14 @@ import {
useDocumentTransition,
} from '@/editor/DocumentContext';
import { EditorLifecycleFlush } from '@/editor/EditorLifecycleFlush';
-import { parseEditorTabId } from '@/editor/editor-tabs';
+import { parseEditorTabId, tabIdForNavigationTarget } from '@/editor/editor-tabs';
import { useInstalledClis } from '@/hooks/use-installed-clis';
import { useReconcileSkillTabs } from '@/hooks/use-reconcile-skill-tabs';
-import { ConfigProvider } from '@/lib/config-provider';
+import { ConfigProvider, useConfigContext } from '@/lib/config-provider';
import {
assetPathFromHash,
docNameFromHash,
isContentRootHash,
- isManagedHashHistoryState,
markCurrentHashHistoryEntry,
replaceHashWithoutNavigation,
skillFileFromHash,
@@ -132,8 +131,14 @@ function knownTargetsSignature(
* path. Target resolution (asset / doc / folder-index / folder / missing)
* lives here plus resolveNavigationTarget. */
function NavigationHandler() {
- const { clearTarget, openTabs, syncOpenTabsWithKnownTargets, tabSessionLoaded } =
- useDocumentContext();
+ const {
+ activeTabId,
+ activeTarget,
+ clearTarget,
+ openTabs,
+ syncOpenTabsWithKnownTargets,
+ tabSessionLoaded,
+ } = useDocumentContext();
const { openTargetTransition } = useDocumentTransition();
// Reconcile open skill tabs against the live skills list: an agent/MCP/server-
// side scope move only broadcasts `files` (never retargets the client tab),
@@ -150,10 +155,6 @@ function NavigationHandler() {
pagesByBasename,
} = usePageList();
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 replay
- // replaces the active tab instead of taking the hash handler's append path.
- const historyTraversalUrlRef = useRef<string | null>(null);
const targetsSignature = knownTargetsSignature(pages, folderPaths, assetPaths, filePaths);
useEffect(
@@ -187,26 +188,23 @@ function NavigationHandler() {
]);
useEffect(() => {
+ if (!tabSessionLoaded && window.okDesktop?.config.mode === 'editor') return;
onHashChange();
- function onPopState(event: PopStateEvent) {
- historyTraversalUrlRef.current = isManagedHashHistoryState(event.state)
- ? window.location.href
- : null;
- }
-
function onHashChange() {
- const isHistoryTraversal = historyTraversalUrlRef.current === window.location.href;
- historyTraversalUrlRef.current = null;
- // Chromium also emits popstate before hashchange for direct hash assignments.
- // Mark entries after classifying them so only actual history traversal reuses the active tab.
markCurrentHashHistoryEntry();
const openHashTarget = (target: ResolvedNavigationTarget) => {
- if (isHistoryTraversal) {
- openTargetTransition(target, { tabBehavior: 'replace-active' });
+ if (
+ tabIdForNavigationTarget(target) === activeTabId &&
+ activeTarget?.kind === target.kind &&
+ activeTarget.target === target.target
+ ) {
return;
}
- openTargetTransition(target);
+ openTargetTransition(target, {
+ disposition: 'permanent',
+ consumeActiveNewTab: true,
+ });
};
// Overlay-dialog hashes (settings, install) don't replace the
@@ -303,13 +301,13 @@ 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);
};
}, [
+ activeTabId,
+ activeTarget,
clearTarget,
folderPaths,
loading,
@@ -319,6 +317,7 @@ function NavigationHandler() {
pages,
pagesBySlug,
pagesByBasename,
+ tabSessionLoaded,
]);
return null;
@@ -519,14 +518,27 @@ function ConfigProviderHost({ children }: { children: ReactNode }) {
);
}
+function PreviewTabsSettingsBridge({ children }: { children: ReactNode }) {
+ const { merged } = useConfigContext();
+ const { promoteAllPreviewTabs } = useDocumentContext();
+
+ useEffect(() => {
+ if (merged?.editor?.previewTabs === false) promoteAllPreviewTabs();
+ }, [merged?.editor?.previewTabs, promoteAllPreviewTabs]);
+
+ return children;
+}
+
export function App() {
return (
<ProfilerBoundary name="app">
<DocumentProvider>
<ConfigProviderHost>
- <SingleFileModeProvider>
- <AppBody />
- </SingleFileModeProvider>
+ <PreviewTabsSettingsBridge>
+ <SingleFileModeProvider>
+ <AppBody />
+ </SingleFileModeProvider>
+ </PreviewTabsSettingsBridge>
</ConfigProviderHost>
</DocumentProvider>
</ProfilerBoundary>
diff --git a/packages/app/src/components/ActivityModeContent.tsx b/packages/app/src/components/ActivityModeContent.tsx
index d758138af..ab67e3db1 100644
--- a/packages/app/src/components/ActivityModeContent.tsx
+++ b/packages/app/src/components/ActivityModeContent.tsx
@@ -390,6 +390,7 @@ export function ActivityModeContent({
const onNavigate = (docName: string): void => {
openTargetTransition(
withLargeFileOpenGuard({ kind: 'doc', target: docName, docName }, pageMeta),
+ { disposition: 'permanent', consumeActiveNewTab: true },
);
navigateToDoc(docName);
};
diff --git a/packages/app/src/components/AssetPreview.dom.test.tsx b/packages/app/src/components/AssetPreview.dom.test.tsx
index 78f800b69..e8518a4f4 100644
--- a/packages/app/src/components/AssetPreview.dom.test.tsx
+++ b/packages/app/src/components/AssetPreview.dom.test.tsx
@@ -40,6 +40,7 @@ let mergedConfig: { appearance?: { sidebar?: { showOnlyMarkdownFiles?: boolean }
vi.doMock('@/lib/config-provider', () => ({
useConfigContext: () => ({
merged: mergedConfig,
+ projectLocalSynced: true,
projectLocalBinding: null,
}),
}));
@@ -190,7 +191,7 @@ describe('AssetPreview — image loading-state placeholder (PRD-6638)', () => {
describe('AssetPreview — not-in-sidebar indicator', () => {
beforeEach(() => {
- mergedConfig = null;
+ mergedConfig = {};
});
afterEach(() => cleanup());
diff --git a/packages/app/src/components/EditorActivityPool.mount-gate.dom.test.tsx b/packages/app/src/components/EditorActivityPool.mount-gate.dom.test.tsx
index 59f796184..0e4b4175a 100644
--- a/packages/app/src/components/EditorActivityPool.mount-gate.dom.test.tsx
+++ b/packages/app/src/components/EditorActivityPool.mount-gate.dom.test.tsx
@@ -141,4 +141,26 @@ describe('ActivityEntry — mount gate reads the effective mode', () => {
rerender(<Pool isSourceMode activeDocName="doc-hidden" />);
expect(deferMountMark('doc-hidden')?.renderSource).toBe(true);
});
+
+ test('renders document toolbar chrome in every visible split-pane host', () => {
+ poolEntries.push(makeEntry('doc-third', 0));
+ const activityHosts = new Map(
+ poolEntries.map(({ docName }) => [docName, document.createElement('div')]),
+ );
+
+ render(
+ <EditorActivityPool
+ activeDocName="doc-active"
+ visibleDocNames={new Set(['doc-active', 'doc-hidden', 'doc-third'])}
+ activityHosts={activityHosts}
+ isSourceMode={false}
+ onRecycle={() => {}}
+ renderToolbar={(docName) => <div data-testid={`toolbar-${docName}`} />}
+ />,
+ );
+
+ for (const [docName, host] of activityHosts) {
+ expect(host.querySelector(`[data-testid="toolbar-${docName}"]`)).not.toBeNull();
+ }
+ });
});
diff --git a/packages/app/src/components/EditorActivityPool.test.ts b/packages/app/src/components/EditorActivityPool.test.ts
index 0442b8aa9..091791c48 100644
--- a/packages/app/src/components/EditorActivityPool.test.ts
+++ b/packages/app/src/components/EditorActivityPool.test.ts
@@ -237,6 +237,24 @@ describe('computeActivityMountList — active-doc force-inclusion (invariant #2)
});
});
+describe('computeActivityMountList — visible pane protection', () => {
+ test('keeps every visible document in pane order even above the warm floor', () => {
+ const entries = [entry('a', 100), entry('b', 400), entry('c', 300), entry('d', 200)];
+
+ const result = computeActivityMountList(entries, new Set(['d', 'a', 'c', 'b']), 3);
+
+ expect(result.map((item) => item.docName)).toEqual(['d', 'a', 'c', 'b']);
+ });
+
+ test('fills a partially visible workspace with hidden MRU entries', () => {
+ const entries = [entry('a', 100), entry('b', 400), entry('c', 300), entry('d', 200)];
+
+ const result = computeActivityMountList(entries, new Set(['a']), 3);
+
+ expect(result.map((item) => item.docName)).toEqual(['a', 'b', 'c']);
+ });
+});
+
describe('LARGE_DOC_CHAR_THRESHOLD', () => {
test('is 500_000 — matches SPEC D12 DIRECTED + evidence/s1-diagnosis.md', () => {
// The threshold is a tuning knob, not a contract. Lowering below the
diff --git a/packages/app/src/components/EditorActivityPool.tsx b/packages/app/src/components/EditorActivityPool.tsx
index 7ad8a4d73..f8ffcc43f 100644
--- a/packages/app/src/components/EditorActivityPool.tsx
+++ b/packages/app/src/components/EditorActivityPool.tsx
@@ -52,6 +52,7 @@ import {
useRef,
useState,
} from 'react';
+import { createPortal } from 'react-dom';
import { type PoolEntrySnapshot, useDocumentContext } from '@/editor/DocumentContext';
import { peekRenameSnapshot, setActivityMountList } from '@/editor/editor-cache';
import { isSystemDoc } from '@/editor/is-system-doc';
@@ -224,13 +225,14 @@ export function computeEffectiveSourceMode(
}
/**
- * Maximum number of editors mounted concurrently inside `<Activity>` boundaries.
- * Decoupled from `MAX_POOL` (exported from `provider-pool.ts`, default 10) per
- * precedent #18(c) — pool-resident-but-not-Activity-mounted docs keep their
- * warm provider (so revisiting is fast via Suspense-gated remount with
- * `syncPromise` resolving immediately from `hasSynced=true`) but skip the
- * per-editor memory + observer-CPU cost of keeping the TipTap + CodeMirror
- * instances alive.
+ * Minimum number of editors mounted concurrently inside `<Activity>`
+ * boundaries. Decoupled from `MAX_POOL` (exported from `provider-pool.ts`,
+ * default 10) per precedent #18(c): every visible split-pane document is
+ * mandatory, then MRU hidden documents fill this warm floor. Pool-resident
+ * docs outside that list keep their warm provider (so revisiting is fast via
+ * Suspense-gated remount with `syncPromise` resolving immediately from
+ * `hasSynced=true`) but skip the per-editor memory + observer-CPU cost of
+ * keeping the TipTap + CodeMirror instances alive.
*
* 3 covers the "alt-tab between recent docs" pattern dominant for the
* primary personas.
@@ -279,6 +281,18 @@ const LazySourceEditor = lazy(async () => {
interface EditorActivityPoolProps {
activeDocName: string;
+ /**
+ * Every document rendered in a visible editor pane, in pane order. Omitted
+ * callers retain the legacy single-focused-document behavior while the
+ * workspace is being introduced.
+ */
+ visibleDocNames?: ReadonlySet<string>;
+ /** Stable pane-owned DOM mounts for Activity hosts, keyed by docName. */
+ activityHosts?: ReadonlyMap<string, HTMLElement>;
+ /** Stable hidden mount for MRU warm Activity entries with no visible pane. */
+ parkingHost?: HTMLElement | null;
+ /** Pane-local chrome rendered for each visible document Activity. */
+ renderToolbar?: (docName: string, provider: PoolEntrySnapshot['provider']) => ReactNode;
isSourceMode: boolean;
editorPlaceholder?: string;
/**
@@ -308,14 +322,13 @@ interface EditorActivityPoolProps {
* Invariants:
* 1. System docs (`__system__`) are filtered out — defense-in-depth even though
* `ProviderPool.open` rejects them at admission.
- * 2. The active doc is always present in the result if it exists in `entries` —
- * even if its `lastAccessedAt` would put it outside the top `limit` (this can
- * happen transiently between `pool.open` and `pool.setActive`, or in tests).
- * 3. Otherwise: top `limit` entries by `lastAccessedAt` descending (MRU first).
+ * 2. Every existing visible document is present in the result, in pane order.
+ * 3. MRU hidden entries fill the remainder up to `limit`; when more than
+ * `limit` documents are visible, all visible documents remain mounted.
*/
export function computeActivityMountList<T extends { docName: string; lastAccessedAt: number }>(
entries: ReadonlyArray<T>,
- activeDocName: string | null,
+ visibleDocNames: ReadonlySet<string> | string | null,
limit: number,
): ReadonlyArray<T> {
if (limit <= 0) return [];
@@ -324,17 +337,35 @@ export function computeActivityMountList<T extends { docName: string; lastAccess
// the helper is correct for any input order — keeps test scenarios independent
// of upstream snapshot ordering decisions.
const sorted = [...filtered].sort((a, b) => b.lastAccessedAt - a.lastAccessedAt);
- const top = sorted.slice(0, limit);
- if (activeDocName === null) return top;
- if (top.some((e) => e.docName === activeDocName)) return top;
+ // Preserve the old focused-document helper contract for callers that have
+ // not yet adopted pane visibility. Split-aware callers always pass a Set.
+ if (typeof visibleDocNames === 'string' || visibleDocNames === null) {
+ const top = sorted.slice(0, limit);
+ if (visibleDocNames === null || top.some((entry) => entry.docName === visibleDocNames)) {
+ return top;
+ }
+ const active = filtered.find((entry) => entry.docName === visibleDocNames);
+ return active === undefined ? top : [...top.slice(0, limit - 1), active];
+ }
+
+ const visibleNames = visibleDocNames;
+ const entriesByDocName = new Map(filtered.map((entry) => [entry.docName, entry]));
+ const visible = [...visibleNames]
+ .filter((docName) => !isSystemDoc(docName))
+ .map((docName) => entriesByDocName.get(docName))
+ .filter((entry): entry is T => entry !== undefined);
+ const mountedDocNames = new Set(visible.map((entry) => entry.docName));
+ const targetSize = Math.max(limit, visible.length);
+
+ for (const entry of sorted) {
+ if (mountedDocNames.size >= targetSize) break;
+ if (mountedDocNames.has(entry.docName)) continue;
+ visible.push(entry);
+ mountedDocNames.add(entry.docName);
+ }
- // Active doc exists but didn't make the top-N by lastAccessedAt — force-include it
- // by displacing the LRU member of `top`. Preserves invariant #2 without growing
- // beyond `limit`.
- const active = filtered.find((e) => e.docName === activeDocName);
- if (!active) return top;
- return [...top.slice(0, limit - 1), active];
+ return visible;
}
type ServerRestartRecoveryView =
@@ -392,6 +423,10 @@ export function EditorActivityPool(props: EditorActivityPoolProps) {
function EditorActivityPoolInner({
activeDocName,
+ visibleDocNames,
+ activityHosts,
+ parkingHost,
+ renderToolbar,
isSourceMode,
editorPlaceholder,
previousDocName,
@@ -400,8 +435,12 @@ function EditorActivityPoolInner({
}: EditorActivityPoolProps) {
const { poolEntries, serverRestartRecovery } = useDocumentContext();
const { pages, loading } = usePageList();
-
- const mountList = computeActivityMountList(poolEntries, activeDocName, ACTIVITY_MOUNT_LIMIT);
+ const effectiveVisibleDocNames = visibleDocNames ?? new Set([activeDocName]);
+ const mountList = computeActivityMountList(
+ poolEntries,
+ effectiveVisibleDocNames,
+ ACTIVITY_MOUNT_LIMIT,
+ );
// Track prior mount list by a stringified doc-name key so we emit
// `ok/activity/mount-list-change` once per real change (not once per render).
@@ -473,24 +512,34 @@ function EditorActivityPoolInner({
return (
<>
{mountList.map((entry) => (
- <ActivityEntry
+ <ActivityEntryHost
key={entry.docName}
- entry={entry}
- isActive={entry.docName === activeDocName}
- isSourceMode={isSourceMode}
- editorPlaceholder={editorPlaceholder}
- isNewDoc={
- !loading &&
- !pages.has(entry.docName) &&
- !isManagedArtifactDocName(entry.docName) &&
- !isMermaidDocFile(entry.docName) &&
- !isEditableTextDocFile(entry.docName)
- }
- previousDocName={previousDocName}
- onNavigateBack={onNavigateBack}
- onRecycle={onRecycle}
- serverRestartRecovery={serverRestartRecovery}
- />
+ docName={entry.docName}
+ hostMount={activityHosts?.get(entry.docName) ?? parkingHost ?? null}
+ >
+ <ActivityEntry
+ entry={entry}
+ isVisible={effectiveVisibleDocNames.has(entry.docName)}
+ toolbar={
+ effectiveVisibleDocNames.has(entry.docName)
+ ? renderToolbar?.(entry.docName, entry.provider)
+ : null
+ }
+ isSourceMode={isSourceMode}
+ editorPlaceholder={editorPlaceholder}
+ isNewDoc={
+ !loading &&
+ !pages.has(entry.docName) &&
+ !isManagedArtifactDocName(entry.docName) &&
+ !isMermaidDocFile(entry.docName) &&
+ !isEditableTextDocFile(entry.docName)
+ }
+ previousDocName={previousDocName}
+ onNavigateBack={onNavigateBack}
+ onRecycle={onRecycle}
+ serverRestartRecovery={serverRestartRecovery}
+ />
+ </ActivityEntryHost>
))}
</>
);
@@ -498,7 +547,8 @@ function EditorActivityPoolInner({
interface ActivityEntryProps {
entry: PoolEntrySnapshot;
- isActive: boolean;
+ isVisible: boolean;
+ toolbar?: ReactNode;
isSourceMode: boolean;
editorPlaceholder?: string;
isNewDoc: boolean;
@@ -508,6 +558,39 @@ interface ActivityEntryProps {
serverRestartRecovery: ServerRestartRecoveryState;
}
+/**
+ * Owns one imperative host for a document Activity. Moving that host between
+ * pane mounts reparents DOM without changing the ActivityEntry's React key,
+ * preserving its scroll state and exclusive TipTap portal target.
+ */
+function ActivityEntryHost({
+ docName,
+ hostMount,
+ children,
+}: {
+ docName: string;
+ hostMount: HTMLElement | null;
+ children: ReactNode;
+}) {
+ const [host] = useState<HTMLDivElement>(() => {
+ const element = document.createElement('div');
+ element.setAttribute('data-ok-activity-host', docName);
+ element.className = 'relative h-full min-h-0';
+ return element;
+ });
+
+ useLayoutEffect(() => {
+ if (hostMount === null) return;
+ hostMount.append(host);
+ return () => host.remove();
+ }, [host, hostMount]);
+
+ // Legacy callers render the tree in place until the split workspace supplies
+ // stable pane and parking mounts. Once supplied, the portal container stays
+ // stable while the effect above moves only its host element.
+ return hostMount === null ? children : createPortal(children, host);
+}
+
/**
* Per-Activity scroll container that (a) owns its own scroller so scrollTop
* is DOM-local to this doc's subtree and (b) saves/restores scrollTop across
@@ -1024,7 +1107,8 @@ function WarmContentFallback({ html }: { html: string }) {
function ActivityEntry({
entry,
- isActive,
+ isVisible,
+ toolbar,
isSourceMode,
editorPlaceholder,
isNewDoc,
@@ -1049,7 +1133,6 @@ function ActivityEntry({
// Editable text docs (`.ts` / `.json` / `.txt` / …) — verbatim Y.Text docs
// rendered by a dedicated CodeMirror editor (no markdown dual-editor).
const isTextDoc = !isMermaid && isEditableTextDocFile(entry.docName);
-
// Per-Activity portal target for <EditorContent>. Stable DOM element
// exclusively owned by THIS ActivityEntry — `useState` with a lazy
// initializer ensures the same `HTMLDivElement` reference survives across
@@ -1114,22 +1197,22 @@ function ActivityEntry({
// so its length reliably signals "this doc will be expensive to render".
const ytextLength = entry.provider.document.getText('source').length;
- // The mode this entry actually displays. Only the active entry follows the
- // global flip; a hidden entry stays frozen at its last-active mode until it is
- // re-activated. Freezing is what keeps a global flip from mounting an editor
+ // The mode this entry actually displays. Every visible split pane follows the
+ // global flip; a hidden entry stays frozen at its last-visible mode until it is
+ // shown again. Freezing is what keeps a global flip from mounting an editor
// inside a hidden (display:none) subtree — every mode-derived decision below
// (visited tracking, mount gate, class swaps) keys off `effectiveIsSourceMode`,
// so a flip a hidden entry never displays cannot flip its render flags.
- const [lastActiveIsSourceMode, setLastActiveIsSourceMode] = useState(isSourceMode);
+ const [lastVisibleIsSourceMode, setLastVisibleIsSourceMode] = useState(isSourceMode);
useEffect(() => {
- if (isActive && lastActiveIsSourceMode !== isSourceMode) {
- setLastActiveIsSourceMode(isSourceMode);
+ if (isVisible && lastVisibleIsSourceMode !== isSourceMode) {
+ setLastVisibleIsSourceMode(isSourceMode);
}
- }, [isActive, isSourceMode, lastActiveIsSourceMode]);
+ }, [isVisible, isSourceMode, lastVisibleIsSourceMode]);
const effectiveIsSourceMode = computeEffectiveSourceMode(
- isActive,
+ isVisible,
isSourceMode,
- lastActiveIsSourceMode,
+ lastVisibleIsSourceMode,
);
// Track which modes have been visited. useState (not useRef) because React
@@ -1240,7 +1323,7 @@ function ActivityEntry({
useEffect(() => {
if (
!shouldEmitFirstToggle({
- isActive,
+ isActive: isVisible,
isLarge: gate.isLarge,
renderSource: gate.renderSource,
renderVisual: gate.renderVisual,
@@ -1258,7 +1341,7 @@ function ActivityEntry({
setHasEmittedFirstToggle(true);
}, [
hasEmittedFirstToggle,
- isActive,
+ isVisible,
gate.isLarge,
gate.renderSource,
gate.renderVisual,
@@ -1268,14 +1351,14 @@ function ActivityEntry({
]);
return (
- <Activity mode={isActive ? 'visible' : 'hidden'} name={`editor:${entry.docName}`}>
+ <Activity mode={isVisible ? 'visible' : 'hidden'} name={`editor:${entry.docName}`}>
{/* Per-Activity scroll container with save/restore across Activity
visibility flips. See ScrollPreservingContainer for the full
rationale. Hoisting the scroller to EditorArea would make scroll
state cross-document and collapse scrollHeight on hidden-mode
effect cleanup. */}
<ScrollPreservingContainer
- isActive={isActive}
+ isActive={isVisible}
docName={entry.docName}
mode={effectiveIsSourceMode ? 'source' : 'wysiwyg'}
initialScrollTop={warmSnapshot?.scrollTop}
@@ -1399,7 +1482,7 @@ function ActivityEntry({
>
<SourceEditorSlot
entry={entry}
- isActive={isActive}
+ isActive={isVisible}
isSourceMode={effectiveIsSourceMode}
editorPlaceholder={editorPlaceholder}
/>
@@ -1441,6 +1524,7 @@ function ActivityEntry({
</>
)}
</ScrollPreservingContainer>
+ {toolbar}
</Activity>
);
}
diff --git a/packages/app/src/components/EditorArea.dom.test.tsx b/packages/app/src/components/EditorArea.dom.test.tsx
index 58da42298..912a82484 100644
--- a/packages/app/src/components/EditorArea.dom.test.tsx
+++ b/packages/app/src/components/EditorArea.dom.test.tsx
@@ -136,6 +136,29 @@ vi.doMock('./TerminalDock', () => ({
},
}));
+vi.doMock('./EditorWorkspace', () => ({
+ EditorWorkspace: ({
+ renderHeader,
+ renderPane,
+ }: {
+ renderHeader: (tabs: ReactNode) => ReactNode;
+ renderPane: (context: {
+ pane: { id: string };
+ isFocused: boolean;
+ activityDocName: string | null;
+ }) => ReactNode;
+ }) => (
+ <>
+ {renderHeader(<div data-testid="workspace-tabs" />)}
+ {renderPane({
+ pane: { id: 'pane-test' },
+ isFocused: true,
+ activityDocName: null,
+ })}
+ </>
+ ),
+}));
+
// Spy substrate for the group-level layout assert (assertRightRailLayout).
// `groupLayout` is what the group "currently" holds (the assert derives the
// panel-ID set from it); `groupSetLayoutCalls` records every corrective write.
@@ -511,12 +534,27 @@ describe('EditorArea session-panel edge reveal tabs', () => {
test('the agents tab is up while the panel is hidden, even with no conversations', () => {
renderArea({ agentsVisible: false });
- expect(screen.getByRole('button', { name: 'Open agents panel' })).toBeTruthy();
+ const reveal = screen.getByRole('button', { name: 'Open agents panel' });
+ const header = document.querySelector('[data-editor-area-header]');
+ const panels = document.querySelector('[data-editor-area-panels]');
+
+ expect(header).toBeTruthy();
+ expect(panels).toBeTruthy();
+ expect(header?.contains(screen.getByTestId('workspace-tabs'))).toBe(true);
+ expect(panels?.contains(reveal)).toBe(true);
+ expect(header?.contains(reveal)).toBe(false);
});
test('the agents tab goes away once the panel is open', () => {
renderArea({ agentsVisible: true });
expect(screen.queryByRole('button', { name: 'Open agents panel' })).toBeNull();
+ const header = document.querySelector('[data-editor-area-header]');
+ const panels = document.querySelector('[data-editor-area-panels]');
+ const agentMount = document.querySelector('[data-agents-panel-mount]');
+
+ expect(header).toBeTruthy();
+ expect(panels?.contains(agentMount)).toBe(true);
+ expect(header?.contains(agentMount)).toBe(false);
});
});
diff --git a/packages/app/src/components/EditorArea.lint-config-dispatch.dom.test.tsx b/packages/app/src/components/EditorArea.lint-config-dispatch.dom.test.tsx
index 5e43a2b69..019050ed3 100644
--- a/packages/app/src/components/EditorArea.lint-config-dispatch.dom.test.tsx
+++ b/packages/app/src/components/EditorArea.lint-config-dispatch.dom.test.tsx
@@ -67,6 +67,22 @@ vi.doMock('@/components/EmptyEditorState', () => ({
vi.doMock('./TerminalDock', () => ({
TerminalDock: ({ children }: { children: ReactNode }) => <div>{children}</div>,
}));
+vi.doMock('./EditorWorkspace', () => ({
+ EditorWorkspace: ({
+ renderPane,
+ }: {
+ renderPane: (context: {
+ pane: { id: string };
+ isFocused: boolean;
+ activityDocName: string | null;
+ }) => ReactNode;
+ }) =>
+ renderPane({
+ pane: { id: 'pane-test' },
+ isFocused: true,
+ activityDocName: null,
+ }),
+}));
vi.doMock('react-resizable-panels', () => ({
usePanelRef: () => ({ current: { collapse: () => {}, expand: () => {} } }),
useGroupRef: () => ({ current: { getLayout: () => [], setLayout: () => {} } }),
diff --git a/packages/app/src/components/EditorArea.share-receive-miss.dom.test.tsx b/packages/app/src/components/EditorArea.share-receive-miss.dom.test.tsx
index 3cd166bba..004446bcb 100644
--- a/packages/app/src/components/EditorArea.share-receive-miss.dom.test.tsx
+++ b/packages/app/src/components/EditorArea.share-receive-miss.dom.test.tsx
@@ -54,6 +54,38 @@ vi.doMock('@/components/EmptyEditorState', () => ({
vi.doMock('./TerminalDock', () => ({
TerminalDock: ({ children }: { children: ReactNode }) => <div>{children}</div>,
}));
+vi.doMock('./EditorWorkspace', () => ({
+ EditorWorkspace: ({
+ renderActivityPool,
+ renderPane,
+ }: {
+ renderActivityPool?: (bindings: {
+ activityHosts: ReadonlyMap<string, HTMLElement>;
+ parkingHost: HTMLElement | null;
+ visibleDocNames: ReadonlySet<string>;
+ }) => ReactNode;
+ renderPane: (context: {
+ pane: { id: string };
+ isFocused: boolean;
+ activityDocName: string | null;
+ activityMount: ReactNode;
+ }) => ReactNode;
+ }) => (
+ <>
+ {renderPane({
+ pane: { id: 'pane-test' },
+ isFocused: true,
+ activityDocName: docCtx.activeDocName,
+ activityMount: <div data-testid="activity-mount" />,
+ })}
+ {renderActivityPool?.({
+ activityHosts: new Map(),
+ parkingHost: document.body,
+ visibleDocNames: new Set([docCtx.activeDocName]),
+ })}
+ </>
+ ),
+}));
vi.doMock('react-resizable-panels', () => ({
usePanelRef: () => ({ current: { collapse: () => {}, expand: () => {} } }),
// EditorArea imports `useGroupRef` alongside `usePanelRef`; the mock must
diff --git a/packages/app/src/components/EditorArea.tsx b/packages/app/src/components/EditorArea.tsx
index e160618fd..d556cddf5 100644
--- a/packages/app/src/components/EditorArea.tsx
+++ b/packages/app/src/components/EditorArea.tsx
@@ -1,3 +1,4 @@
+import type { HocuspocusProvider } from '@hocuspocus/provider';
import {
detectEmbeddedHostFromBrowser,
isFrontmatterSchemaAsset,
@@ -16,6 +17,7 @@ import {
useState,
useSyncExternalStore,
} from 'react';
+import { createPortal } from 'react-dom';
import { useGroupRef, usePanelRef } from 'react-resizable-panels';
import { AssetPreview } from '@/components/AssetPreview';
import { DocPanel, type PanelTab } from '@/components/DocPanel';
@@ -72,7 +74,6 @@ import { RIGHT_COLLAPSE_THRESHOLD, resolvePartition } from '@/lib/sidebar-partit
import { applyToggle, readPins, resolveEffectiveState } from '@/lib/sidebar-pin-store';
import { closeTimelineDiff, useTimelineDiffView } from '@/lib/timeline-diff-store';
import { useSettingsRoute } from '@/lib/use-settings-route';
-import { cn } from '@/lib/utils';
import { setViewMenuState } from '@/lib/view-menu-state-store';
import { useSyncStatus } from '@/presence/use-sync-status';
import { BottomComposer } from './BottomComposer';
@@ -81,6 +82,11 @@ import { EditorActivityPool } from './EditorActivityPool';
import { EditorFooter } from './EditorFooter';
import type { EditorMode } from './EditorPane';
import { EditorToolbar } from './EditorToolbar';
+import {
+ EditorWorkspace,
+ type EditorWorkspaceActivityBindings,
+ type EditorWorkspacePaneRenderContext,
+} from './EditorWorkspace';
import { shouldPaintOverlay } from './editor-area-overlay';
import { computeStickyRepinLayout } from './editor-area-sticky-repin';
import { TerminalDock } from './TerminalDock';
@@ -122,6 +128,55 @@ function ConfigEditorFallback() {
);
}
+function PaneDocumentToolbar({
+ docName,
+ provider,
+ isSourceMode,
+ onModeChange,
+ isPanelCollapsed,
+ onTogglePanel,
+ reserveRightGutter,
+}: {
+ docName: string;
+ provider: HocuspocusProvider;
+ isSourceMode: boolean;
+ onModeChange: (mode: EditorMode) => void;
+ isPanelCollapsed: boolean;
+ onTogglePanel: () => void;
+ reserveRightGutter: boolean;
+}) {
+ const { requestAddProperty } = useProperties();
+ const syncStatus = useSyncStatus(provider);
+ // Missing required properties have no property row or body anchor, so the
+ // pane toolbar is the only always-present surface that can report them.
+ const { data: frontmatterLintConfig } = useDocLintConfig(docName);
+ // Source mode has no Add-properties button, so avoid linting every keystroke
+ // for diagnostics that cannot render there.
+ const { missing: missingProperties } = partitionFrontmatterProblems(
+ useFrontmatterDiagnostics(
+ isSourceMode ? null : provider,
+ frontmatterLintConfig?.effective ?? null,
+ ),
+ );
+ const lifecycleStatus = useLifecycleStatus(docName);
+ if (lifecycleStatus === 'conflict') return null;
+
+ return (
+ <EditorToolbar
+ activeDocName={docName}
+ isSourceMode={isSourceMode}
+ sourceDisabled={syncStatus !== 'connected' && syncStatus !== 'synced'}
+ onModeChange={onModeChange}
+ showAddPropertyButton={!isSourceMode}
+ onAddProperty={() => requestAddProperty(docName)}
+ frontmatterProblems={missingProperties}
+ isPanelCollapsed={isPanelCollapsed}
+ onTogglePanel={onTogglePanel}
+ reserveRightGutter={reserveRightGutter}
+ />
+ );
+}
+
// The full-pane version diffs are overlays that only paint on user action (open
// a Timeline/agent diff), so they're code-split off the eager editor bundle —
// this keeps the rendered-diff engine + `prosemirror-recreate-transform` out of
@@ -189,16 +244,18 @@ interface EditorAreaProps {
terminalVisible?: boolean;
onTerminalVisibleChange?: (visible: boolean) => void;
/** Agents-panel visibility. Its own resizable column to the right of the
- * doc/agent panel (`#agents-column`, MD | PANE | AGENTS). Independent of the
- * terminal — both panels can be open at once. */
+ * doc/agent panel. Independent of the terminal. */
agentsVisible?: boolean;
onAgentsVisibleChange?: (visible: boolean) => void;
- /** Report both panels' attach points up to EditorPane (which owns the session
- * hosts). See {@link SessionPlacements}. */
+ /** Report both panels' attach points to the session hosts owned by EditorPane. */
onSessionPlacements?: (placements: SessionPlacements) => void;
- /** Reveal the agents panel — drives the right edge tab shown while it is
- * hidden. Provided on every host (agent threads are server-hosted). */
+ /** Reveal the agents panel from its right-edge affordance. */
onRevealAgents?: () => void;
+ renderWorkspaceHeader?: (tabs: ReactNode) => ReactNode;
+}
+
+function renderTabsWithoutHeader(tabs: ReactNode): ReactNode {
+ return tabs;
}
export function EditorArea(props: EditorAreaProps) {
@@ -262,6 +319,7 @@ function EditorAreaInner({
onAgentsVisibleChange,
onSessionPlacements,
onRevealAgents,
+ renderWorkspaceHeader = renderTabsWithoutHeader,
}: EditorAreaProps) {
const { t } = useLingui();
const {
@@ -276,31 +334,11 @@ function EditorAreaInner({
docPanelExpandSignal,
} = useDocumentContext();
const { openDocumentTransition } = useDocumentTransition();
- const { requestAddProperty } = useProperties();
const stats = useDocumentStats(activeProvider, activeDocName);
const selectionStats = useSelectionStats(
activeDocName,
editorMode === 'source' ? 'source' : 'wysiwyg',
);
- const syncStatus = useSyncStatus(activeProvider);
- const isConnected = syncStatus === 'connected' || syncStatus === 'synced';
- // Schema-required properties the doc does not have badge the toolbar's
- // Add-properties button: they have no body construct to mark and no property
- // row either (being absent is the problem), and on a doc with no properties
- // at all `PropertyPanel` renders nothing — so the toolbar is the only surface
- // always there to carry them. Present-but-invalid properties are the panel's.
- const { data: frontmatterLintConfig } = useDocLintConfig(activeDocName);
- // Source mode hides the Add-properties button entirely, so the pass has no
- // consumer there — short-circuit rather than lint on every keystroke for a
- // badge that cannot render.
- const { missing: missingProperties } = partitionFrontmatterProblems(
- useFrontmatterDiagnostics(
- editorMode === 'source' ? null : activeProvider,
- frontmatterLintConfig?.effective ?? null,
- ),
- );
- const lifecycleStatus = useLifecycleStatus(activeDocName);
- const isConflict = lifecycleStatus === 'conflict';
// Latches true once any provider has been active this session. It separates a
// genuine cold start (group never mounted, no docked terminal alive yet) from
// a mid-session navigation whose provider is transiently null — closing a tab
@@ -323,6 +361,7 @@ function EditorAreaInner({
// paint the updated shell before the editor mount cost begins. The
// shell-snap budget is ~250ms.
const deferredActiveDocName = useDeferredValue(activeDocName);
+ const isSourceMode = editorMode === 'source';
const isNewDoc = activeTarget?.kind === 'missing';
const showStats = !!activeDocName && activeTarget?.kind !== 'folder';
const editorPlaceholder = isNewDoc ? t`Start writing to create this page` : undefined;
@@ -421,6 +460,14 @@ function EditorAreaInner({
// panels (MD | PANE | AGENTS), present across EVERY view kind (the column just
// has no doc panel beside it on asset / large-file / empty views).
const [agentsContainer, setAgentsContainer] = useState<HTMLDivElement | null>(null);
+ // The global editor header sits above the complete horizontal workspace so
+ // every right-side panel begins below it. EditorWorkspace owns the tab DnD
+ // context, so it portals the rendered header into this mount instead of
+ // nesting it inside the editor-width panel.
+ const [workspaceHeaderContainer, setWorkspaceHeaderContainer] = useState<HTMLDivElement | null>(
+ null,
+ );
+ const [workspaceColumnEl, setWorkspaceColumnEl] = useState<HTMLDivElement | null>(null);
// The bottom-dock mount + the editor-region focus target, reported up by
// TerminalDock (the bottom shell). The terminal host portals into the container
// and both hosts return focus to the editor region when they hide.
@@ -533,6 +580,25 @@ function EditorAreaInner({
// subscribers with narrow deps would otherwise close over the initial null).
const groupContainerElRef = useRef<HTMLDivElement | null>(null);
+ // Tabs still follow the editor workspace width while the global actions stay
+ // pinned to the window edge. ResizeObserver updates the CSS width throughout
+ // a live panel drag, avoiding the lag that an onResize/React-state round trip
+ // would introduce.
+ useLayoutEffect(() => {
+ if (workspaceHeaderContainer == null || workspaceColumnEl == null) return;
+ const updateTabsWidth = () => {
+ workspaceHeaderContainer.style.setProperty(
+ '--editor-header-tabs-width',
+ `${workspaceColumnEl.getBoundingClientRect().width}px`,
+ );
+ };
+ updateTabsWidth();
+ if (typeof ResizeObserver === 'undefined') return;
+ const observer = new ResizeObserver(updateTabsWidth);
+ observer.observe(workspaceColumnEl);
+ return () => observer.disconnect();
+ }, [workspaceHeaderContainer, workspaceColumnEl]);
+
// Group-level imperative handle. Layout corrections MUST go through
// `setLayout` (the whole layout in one shot): the per-panel imperative APIs
// (`resize`/`collapse`/`expand`) always exchange space with the panel's flex
@@ -861,6 +927,7 @@ function EditorAreaInner({
// and view-kind changes.
let viewContent: ReactNode;
let rightPanel: ReactNode = null;
+ let renderFocusedDocument: ((activityMount: ReactNode) => ReactNode) | null = null;
// The agents column (when visible) is rendered once at the
// panel-group level below, to the right of `rightPanel`, so the branches here
@@ -1084,16 +1151,6 @@ function EditorAreaInner({
viewContent = <EmptyEditorState terminalOpen={terminalVisible} agentsOpen={agentsVisible} />;
}
} else {
- const isSourceMode = editorMode === 'source';
- const sourceDisabled = !isConnected;
-
- const isPanelCollapsed = isCollapsed;
-
- function openAddPropertyForm() {
- if (!activeDocName) return;
- requestAddProperty(activeDocName);
- }
-
// Visibility for the open doc's "Ask AI" composer — the pure gate in
// bottom-composer-gate.ts (hidden while either session panel is open, in
// embedded webviews, and with no doc open). The folder overview mounts its
@@ -1113,7 +1170,7 @@ function EditorAreaInner({
!(timelineDiff && timelineDiff.docName === activeDocName) &&
!(agentDiff && agentDiffDoc === activeDocName);
const externalSkillEdit = activeDocName ? parseExternalSkillDocName(activeDocName) : null;
- const editorContent = (
+ const renderEditorContent = (activityMount: ReactNode) => (
<div className="relative flex h-full flex-col">
{/* Detected-skill edit-in-place banner: a real layout row above the editor
(not the toolbar's absolute overlay), so it reads like the read-only
@@ -1125,11 +1182,13 @@ function EditorAreaInner({
) : null}
<div className="relative min-h-0 flex-1">
{/* Hybrid Activity + Suspense + ErrorBoundary render tree.
- EditorActivityPool keeps Tiptap eager and lazy-loads SourceEditor on
- the first source-mode visit for each doc, then preserves the per-doc
- display:none toggle after that initial load. Each Activity entry owns
- its own scroll container so scroll position is DOM-local to that
- doc's subtree and survives the Activity hidden-mode mount/unmount cycle.
+ EditorWorkspace supplies this pane-owned host while the single
+ EditorActivityPool portals each Activity entry into its visible pane.
+ The pool keeps Tiptap eager and lazy-loads SourceEditor on the first
+ source-mode visit for each doc, then preserves the per-doc display:none
+ toggle after that initial load. Each Activity entry owns its own scroll
+ container so scroll position is DOM-local to that doc's subtree and
+ survives the Activity hidden-mode mount/unmount cycle.
Error + Suspense scoping lives INSIDE EditorActivityPool — each
Activity wraps its own DocumentErrorBoundary + Suspense so a
@@ -1137,20 +1196,7 @@ function EditorAreaInner({
the visible UI. See EditorActivityPool.tsx file
docstring "ERROR + SUSPENSE SCOPING" for rationale. */}
<div className="relative h-full">
- <EditorActivityPool
- // Fall back to the urgent `activeDocName` when the deferred
- // value is still null (initial load, before the first
- // deferred-commit pass populates it). The
- // `!activeProvider || !activeDocName` null-guard above already
- // short-circuits with skeleton/empty-state when `activeDocName`
- // itself is null, so we can assert non-null here.
- activeDocName={deferredActiveDocName ?? activeDocName}
- isSourceMode={isSourceMode}
- editorPlaceholder={editorPlaceholder}
- previousDocName={previousDocName ?? undefined}
- onNavigateBack={navigateBackToDoc}
- onRecycle={recycleDocument}
- />
+ {activityMount}
<FindReplaceController activeDocName={activeDocName} isSourceMode={isSourceMode} />
{/* Nav-pending skeleton overlay. Rendered when the urgent
`activeDocName` (shell state — driving sidebar highlight +
@@ -1219,23 +1265,6 @@ function EditorAreaInner({
</Suspense>
) : null}
</div>
- {!isConflict && (
- <EditorToolbar
- activeDocName={activeDocName}
- isSourceMode={isSourceMode}
- sourceDisabled={sourceDisabled}
- onModeChange={onModeChange}
- showAddPropertyButton={!isSourceMode}
- onAddProperty={openAddPropertyForm}
- frontmatterProblems={missingProperties}
- isPanelCollapsed={isPanelCollapsed}
- onTogglePanel={togglePanel}
- // When the doc panel is collapsed, the action cluster reaches the
- // far-right corner where the agents reveal tab sits — shift it left
- // so the three stay in one row instead of overlapping.
- reserveRightGutter={rightRevealTabPresent && isPanelCollapsed}
- />
- )}
{/* Floats over the bottom of the scroll area (an absolute overlay, like
the toolbar at the top) so content scrolls under its faded top edge.
BottomComposer publishes its measured height as `--ask-composer-height`
@@ -1264,7 +1293,8 @@ function EditorAreaInner({
</div>
);
- viewContent = editorContent;
+ viewContent = null;
+ renderFocusedDocument = renderEditorContent;
// While the agents column is open and the doc panel is closed, the
// collapsed doc panel sits as a zero-width flex neighbor between the editor
// and the agents column. Its own handle is disabled whenever it is collapsed
@@ -1327,11 +1357,7 @@ function EditorAreaInner({
// in DOM, in Tab order, and announced by screen readers. `inert` removes the
// collapsed subtree from the a11y tree and focus order without remounting.
inert={isCollapsed}
- className={cn(
- 'flex flex-col bg-muted/20',
- !isDraggingDocHandle &&
- 'transition-[flex-grow] duration-200 ease-out motion-reduce:transition-none motion-reduce:duration-0',
- )}
+ className="flex flex-col bg-muted/20"
>
<DocPanel
docName={activeDocName}
@@ -1345,6 +1371,125 @@ function EditorAreaInner({
);
}
+ function renderUnfocusedPane({
+ activityMount,
+ pane,
+ }: EditorWorkspacePaneRenderContext): ReactNode {
+ const target = pane.activeTarget;
+ if (activityMount) return activityMount;
+ if (target?.kind === 'large-file') {
+ return (
+ <LargeFileEditorState docName={target.docName} size={target.size} limit={target.limit} />
+ );
+ }
+ if (target?.kind === 'folder') {
+ return <FolderOverview folderPath={target.folderPath} />;
+ }
+ if (
+ target?.kind === 'asset' &&
+ isMarkdownlintJsonConfig(target.assetPath.split('/').pop() ?? target.assetPath)
+ ) {
+ return (
+ <Suspense fallback={<ConfigEditorFallback />}>
+ <LazyLintConfigEditor key={target.assetPath} assetPath={target.assetPath} />
+ </Suspense>
+ );
+ }
+ if (target?.kind === 'asset' && isFrontmatterSchemaAsset(target.assetPath)) {
+ return (
+ <Suspense fallback={<ConfigEditorFallback />}>
+ <LazySchemaConfigEditor key={target.assetPath} assetPath={target.assetPath} />
+ </Suspense>
+ );
+ }
+ if (target?.kind === 'asset') {
+ return (
+ <AssetPreview
+ key={target.assetPath}
+ assetPath={target.assetPath}
+ mediaKind={target.mediaKind}
+ />
+ );
+ }
+ if (target?.kind === 'skill-file') {
+ return (
+ <SkillFileViewer
+ key={`${target.scope}/${target.name}/${target.host ?? ''}/${target.path}`}
+ scope={target.scope}
+ name={target.name}
+ path={target.path}
+ host={target.host}
+ />
+ );
+ }
+ if (target?.kind === 'skill-preview') {
+ return (
+ <SkillPreviewTab
+ key={`${target.flavor}:${target.source}:${target.name}:${target.level ?? ''}`}
+ flavor={target.flavor}
+ source={target.source}
+ name={target.name}
+ subtitle={target.subtitle}
+ level={target.level}
+ path={target.path}
+ />
+ );
+ }
+ if (pane.activeNewTabId && isSkillsNewTabId(pane.activeNewTabId)) {
+ return <SkillsBasePage sessionsDockOpen={false} />;
+ }
+ return <EmptyEditorState />;
+ }
+
+ function renderWorkspacePane(context: EditorWorkspacePaneRenderContext): ReactNode {
+ if (!context.isFocused) return renderUnfocusedPane(context);
+ return renderFocusedDocument ? renderFocusedDocument(context.activityMount) : viewContent;
+ }
+
+ function renderWorkspaceActivityPool({
+ activityHosts,
+ parkingHost,
+ visibleDocNames,
+ }: EditorWorkspaceActivityBindings): ReactNode {
+ const renderableVisibleDocNames = shareReceiveMiss
+ ? new Set([...visibleDocNames].filter((docName) => docName !== activeDocName))
+ : visibleDocNames;
+ const focusedDocName =
+ activeDocName && renderableVisibleDocNames.has(activeDocName) ? activeDocName : undefined;
+ const deferredDocName =
+ deferredActiveDocName && renderableVisibleDocNames.has(deferredActiveDocName)
+ ? deferredActiveDocName
+ : undefined;
+ const poolActiveDocName = focusedDocName
+ ? (deferredDocName ?? focusedDocName)
+ : renderableVisibleDocNames.values().next().value;
+ if (!poolActiveDocName) return null;
+ return (
+ <EditorActivityPool
+ activeDocName={poolActiveDocName}
+ visibleDocNames={renderableVisibleDocNames}
+ activityHosts={activityHosts}
+ parkingHost={parkingHost}
+ renderToolbar={(docName, provider) => (
+ <PaneDocumentToolbar
+ docName={docName}
+ provider={provider}
+ isSourceMode={isSourceMode}
+ onModeChange={onModeChange}
+ isPanelCollapsed={isCollapsed}
+ onTogglePanel={togglePanel}
+ reserveRightGutter={docName === activeDocName && rightRevealTabPresent && isCollapsed}
+ />
+ )}
+ isSourceMode={isSourceMode}
+ editorPlaceholder={poolActiveDocName === activeDocName ? editorPlaceholder : undefined}
+ previousDocName={previousDocName ?? undefined}
+ onNavigateBack={navigateBackToDoc}
+ onRecycle={recycleDocument}
+ />
+ );
+ }
+
// A single TerminalDock wraps the active view's left column. The skeleton
// below is structurally identical for every view kind, so the dock keeps one
// React position and its PTY survives tab switches and view-kind changes. It
@@ -1360,7 +1505,15 @@ function EditorAreaInner({
onBottomContainer={setBottomTerminalContainer}
onEditorRegion={setTerminalEditorRegion}
>
- {viewContent}
+ <EditorWorkspace
+ renderHeader={(tabs) =>
+ workspaceHeaderContainer == null
+ ? null
+ : createPortal(renderWorkspaceHeader(tabs), workspaceHeaderContainer)
+ }
+ renderPane={renderWorkspacePane}
+ renderActivityPool={renderWorkspaceActivityPool}
+ />
</TerminalDock>
);
@@ -1413,14 +1566,14 @@ function EditorAreaInner({
debouncedWriteAgentsWidth(size.inPixels);
}
}}
- className={cn(
- 'flex flex-col',
- !isDraggingAgentsHandle &&
- 'transition-[flex-grow] duration-200 ease-out motion-reduce:transition-none motion-reduce:duration-0',
- )}
+ className="flex flex-col"
>
{/* Mount point for the agents host's stable host div. */}
- <div ref={setAgentsContainer} className="flex min-h-0 flex-1 flex-col overflow-hidden" />
+ <div
+ ref={setAgentsContainer}
+ data-agents-panel-mount=""
+ className="flex min-h-0 flex-1 flex-col overflow-hidden"
+ />
</ResizablePanel>
</>
) : null;
@@ -1437,53 +1590,58 @@ function EditorAreaInner({
// Order: EDITOR | doc/agent panel | agents column. The agents panel is the
// far-right column, so it renders AFTER `rightPanel`.
return (
- <div
- className="relative flex min-h-0 flex-1"
- ref={(el) => {
- setGroupContainerEl(el);
- groupContainerElRef.current = el;
- }}
- >
- <ResizablePanelGroup
- orientation="horizontal"
- groupRef={groupRef}
- data-dragging={isDraggingDocHandle || isDraggingAgentsHandle || undefined}
+ <div className="flex min-h-0 flex-1 flex-col">
+ <div
+ ref={setWorkspaceHeaderContainer}
+ data-editor-area-header=""
+ className="relative z-30 shrink-0"
+ />
+ <div
+ data-editor-area-panels=""
+ className="relative flex min-h-0 flex-1"
+ ref={(el) => {
+ setGroupContainerEl(el);
+ groupContainerElRef.current = el;
+ }}
>
- <ResizablePanel
- // No explicit id: an id here changed how react-resizable-panels
- // redistributes on imperative resize and broke the doc-panel
- // pixel-width sticky restore. The
- // left panel is always the first child, so React keeps it mounted
- // across right-side toggles without one (the terminal still persists).
- //
- // With the terminal column mounted the editor yields to a 5% sliver so
- // the terminal can be dragged near-full width without ever fully
- // eclipsing the editor — the horizontal mirror of the bottom dock's
- // 95%/5% split (see the terminal column's maxSize below; the pair must
- // sum to 100% or the drag can't reach the max). Without the terminal
- // the 30% floor keeps the editor usable against the doc panel.
- minSize={agentsColumnPresent ? '5%' : '30%'}
- // Editor takes full width only when nothing on the right claims space;
- // otherwise it absorbs the residual while the pixel-sized doc panel and
- // terminal column hold their widths.
- {...(editorAbsorbsResidual ? {} : { defaultSize: '100%' })}
- className={cn(
- !(isDraggingDocHandle || isDraggingAgentsHandle) &&
- 'transition-[flex-grow] duration-200 ease-out motion-reduce:transition-none motion-reduce:duration-0',
- )}
+ <ResizablePanelGroup
+ orientation="horizontal"
+ groupRef={groupRef}
+ data-dragging={isDraggingDocHandle || isDraggingAgentsHandle || undefined}
>
- {leftColumn}
- </ResizablePanel>
- {rightPanel}
- {agentsColumn}
- </ResizablePanelGroup>
- {rightRevealTabPresent ? (
- // Pinned to the far-right top, vertically in line with the toolbar's
- // action buttons. When the doc panel is collapsed those buttons reach this
- // same corner; the toolbar shifts its cluster left (reserveRightGutter) so
- // all three sit in one row rather than overlapping.
- <TerminalRevealTab edge="right" onReveal={onRevealAgents} className="top-2.5 right-0" />
- ) : null}
+ <ResizablePanel
+ // No explicit id: an id here changed how react-resizable-panels
+ // redistributes on imperative resize and broke the doc-panel
+ // pixel-width sticky restore. The
+ // left panel is always the first child, so React keeps it mounted
+ // across right-side toggles without one (the terminal still persists).
+ //
+ // With the agents column mounted the editor yields to a 5% sliver so
+ // the panel can be dragged near-full width without ever fully
+ // eclipsing the editor — the horizontal mirror of the bottom dock's
+ // 95%/5% split (see the terminal column's maxSize below; the pair must
+ // sum to 100% or the drag can't reach the max). Without the terminal
+ // the 30% floor keeps the editor usable against the doc panel.
+ minSize={agentsColumnPresent ? '5%' : '30%'}
+ // Editor takes full width only when nothing on the right claims space;
+ // otherwise it absorbs the residual while the pixel-sized doc panel and
+ // agents column hold their widths.
+ {...(editorAbsorbsResidual ? {} : { defaultSize: '100%' })}
+ >
+ <div ref={setWorkspaceColumnEl} className="flex h-full min-w-0 flex-col">
+ {leftColumn}
+ </div>
+ </ResizablePanel>
+ {rightPanel}
+ {agentsColumn}
+ </ResizablePanelGroup>
+ {rightRevealTabPresent ? (
+ // This is intentionally inside the below-header workspace. It stays
+ // attached to the agents-panel edge without competing with global
+ // header actions.
+ <TerminalRevealTab edge="right" onReveal={onRevealAgents} className="top-2.5 right-0" />
+ ) : null}
+ </div>
</div>
);
}
diff --git a/packages/app/src/components/EditorHeader.dom.test.tsx b/packages/app/src/components/EditorHeader.dom.test.tsx
index 02e00b056..25d84f40a 100644
--- a/packages/app/src/components/EditorHeader.dom.test.tsx
+++ b/packages/app/src/components/EditorHeader.dom.test.tsx
@@ -1,7 +1,8 @@
import * as actualLinguiMacro from '@lingui/react/macro';
-import { cleanup, render, screen } from '@testing-library/react';
+import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import type { ComponentProps, ReactNode } from 'react';
+import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, describe, expect, test, vi } from 'vitest';
import { TooltipProvider } from '@/components/ui/tooltip';
import { formatShortcut, formatShortcutLabel } from '@/lib/keyboard-shortcuts';
@@ -22,14 +23,18 @@ vi.doMock('@lingui/react/macro', () => ({
let activeDocName: string | null = 'docs/notes';
let activeTarget: unknown = { kind: 'doc' };
let sidebarState: 'expanded' | 'collapsed' = 'expanded';
-let isDraggingRail = false;
+let paneCount = 1;
let singleFile = false;
// Captures the `input` prop EditorHeader hands to ShareButton.
let lastShareInput: unknown;
const onOpenSearch = vi.fn(() => {});
vi.doMock('@/editor/DocumentContext', () => ({
- useDocumentContext: () => ({ activeDocName, activeTarget }),
+ useDocumentContext: () => ({
+ activeDocName,
+ activeTarget,
+ panes: Array.from({ length: paneCount }, (_, index) => ({ id: `pane-${index}` })),
+ }),
}));
vi.doMock('@/lib/single-file-mode', () => ({
@@ -37,7 +42,7 @@ vi.doMock('@/lib/single-file-mode', () => ({
}));
vi.doMock('@/components/ui/sidebar', () => ({
- useSidebar: () => ({ state: sidebarState, isDraggingRail }),
+ useSidebar: () => ({ state: sidebarState }),
SidebarTrigger: ({ className, ...props }: ComponentProps<'button'>) => (
<button type="button" data-testid="sidebar-trigger" className={className} {...props}>
sidebar
@@ -49,10 +54,6 @@ vi.doMock('@/components/AppMenubar', () => ({
AppMenubar: () => <div data-testid="app-menubar" />,
}));
-vi.doMock('./EditorTabs', () => ({
- EditorTabs: () => <div data-testid="editor-tabs" />,
-}));
-
vi.doMock('./ShareButton', () => ({
ShareButton: ({ input }: { input: unknown }) => {
lastShareInput = input;
@@ -90,6 +91,10 @@ vi.doMock('./HelpPopover', () => ({
HelpPopover: () => <button type="button">Resources</button>,
}));
+vi.doMock('./InstanceBadge', () => ({
+ InstanceBadge: () => null,
+}));
+
function setElectronHost(enabled: boolean) {
Object.defineProperty(window, 'okDesktop', {
configurable: true,
@@ -104,11 +109,11 @@ function setWindowsHost() {
});
}
-async function renderHeader() {
+async function renderHeader(tabs?: ReactNode) {
const { EditorHeader } = await import('./EditorHeader');
render(
<TooltipProvider delayDuration={0}>
- <EditorHeader onOpenSearch={onOpenSearch} />
+ <EditorHeader onOpenSearch={onOpenSearch}>{tabs}</EditorHeader>
</TooltipProvider>,
);
return document.querySelector('header') as HTMLElement;
@@ -121,7 +126,7 @@ describe('EditorHeader runtime behavior', () => {
activeDocName = 'docs/notes';
activeTarget = { kind: 'doc' };
sidebarState = 'expanded';
- isDraggingRail = false;
+ paneCount = 1;
singleFile = false;
lastShareInput = undefined;
onOpenSearch.mockClear();
@@ -201,21 +206,19 @@ describe('EditorHeader runtime behavior', () => {
setElectronHost(true);
sidebarState = 'collapsed';
const header = await renderHeader();
+ const leadingZone = header.querySelector('[data-editor-header-leading-actions]') as HTMLElement;
expect(header.getAttribute('data-electron-drag')).toBe('');
- expectVisualClassTokens(header.className, [
- '[-webkit-app-region:drag]',
- 'pl-[var(--ok-titlebar-reserve-left,1rem)]',
- 'motion-safe:transition-[padding]',
- ]);
+ expectVisualClassTokens(header.className, ['[-webkit-app-region:drag]']);
+ expectVisualClassTokens(leadingZone.className, ['left-[var(--ok-titlebar-reserve-left,1rem)]']);
+ expectVisualClassTokensAbsent(leadingZone.className, ['motion-safe:transition-[left]']);
expectVisualClassTokens(screen.getByTestId('sidebar-trigger').className, [
'[-webkit-app-region:no-drag]',
]);
- const leftZone = header.children.item(0) as HTMLElement;
const workspaceNavigation = screen.getByRole('group', { name: 'Workspace navigation' });
const search = screen.getByRole('button', { name: /^Search/ });
const navigation = screen.getByTestId('navigation-history-controls');
- const separator = leftZone.querySelector('[data-slot="separator"]') as HTMLElement;
+ const separator = leadingZone.querySelector('[data-slot="separator"]') as HTMLElement;
expect(workspaceNavigation.contains(screen.getByTestId('sidebar-trigger'))).toBe(true);
expect(workspaceNavigation.contains(search)).toBe(true);
expect(workspaceNavigation.contains(navigation)).toBe(true);
@@ -229,28 +232,144 @@ describe('EditorHeader runtime behavior', () => {
navigation.compareDocumentPosition(separator) & Node.DOCUMENT_POSITION_FOLLOWING,
).toBeTruthy();
expectVisualClassTokens(navigation.className, ['[-webkit-app-region:no-drag]']);
- const rightZone = header.children.item(1) as HTMLElement;
+ const rightZone = header.querySelector('[data-editor-header-actions]') as HTMLElement;
expectVisualClassTokens(rightZone.className, ['*:[-webkit-app-region:no-drag]']);
});
- test('Electron expanded sidebar keeps drag region but does not reserve traffic-light padding', async () => {
+ test('Electron expanded sidebar keeps drag region but does not reserve traffic-light space', async () => {
setElectronHost(true);
sidebarState = 'expanded';
const header = await renderHeader();
+ const leadingZone = header.querySelector('[data-editor-header-leading-actions]') as HTMLElement;
expectVisualClassTokens(header.className, ['[-webkit-app-region:drag]']);
- expectVisualClassTokensAbsent(header.className, ['pl-[var(--ok-titlebar-reserve-left,1rem)]']);
+ expectVisualClassTokensAbsent(leadingZone.className, [
+ 'left-[var(--ok-titlebar-reserve-left,1rem)]',
+ ]);
+ expect(header.style.getPropertyValue('--editor-header-leading-offset')).toBe('0px');
expect(screen.queryByTestId('navigation-history-controls')).toBeNull();
});
+ test('keeps the sidebar offset separate from the measured leading action width', async () => {
+ setElectronHost(true);
+ sidebarState = 'collapsed';
+ const offsetWidth = vi
+ .spyOn(HTMLElement.prototype, 'offsetWidth', 'get')
+ .mockImplementation(function (this: HTMLElement) {
+ if (this.hasAttribute('data-editor-header-leading-actions')) return 224;
+ if (this.hasAttribute('data-editor-header-actions')) return 160;
+ return 0;
+ });
+
+ try {
+ const header = await renderHeader(<div>tabs</div>);
+
+ expect(header.style.getPropertyValue('--editor-header-leading-width')).toBe('224px');
+ expect(header.style.getPropertyValue('--editor-header-leading-offset')).toBe(
+ 'var(--ok-titlebar-reserve-left, 1rem)',
+ );
+ const tabHost = header.querySelector('[data-editor-header-tabs]') as HTMLElement;
+ await waitFor(() => expectVisualClassTokensAbsent(tabHost.className, ['invisible']));
+ } finally {
+ offsetWidth.mockRestore();
+ }
+ });
+
+ test('keeps tabs hidden on the first render until header chrome is measured', async () => {
+ const { EditorHeader } = await import('./EditorHeader');
+ const markup = renderToStaticMarkup(
+ <TooltipProvider delayDuration={0}>
+ <EditorHeader onOpenSearch={onOpenSearch}>
+ <div>restored tabs</div>
+ </EditorHeader>
+ </TooltipProvider>,
+ );
+ const container = document.createElement('div');
+ container.innerHTML = markup;
+ const tabHost = container.querySelector('[data-editor-header-tabs]') as HTMLElement;
+
+ expectVisualClassTokens(tabHost.className, ['invisible']);
+ });
+
+ test('keeps restored tabs hidden until two settled layout frames have passed', async () => {
+ const frames: FrameRequestCallback[] = [];
+ const requestFrame = vi
+ .spyOn(window, 'requestAnimationFrame')
+ .mockImplementation((callback) => {
+ frames.push(callback);
+ return frames.length;
+ });
+ const cancelFrame = vi.spyOn(window, 'cancelAnimationFrame').mockImplementation(() => {});
+
+ try {
+ const header = await renderHeader(<div>restored tabs</div>);
+ const tabHost = header.querySelector('[data-editor-header-tabs]') as HTMLElement;
+
+ expectVisualClassTokens(tabHost.className, ['invisible']);
+ act(() => frames.shift()?.(0));
+ expectVisualClassTokens(tabHost.className, ['invisible']);
+ act(() => frames.shift()?.(16));
+ expectVisualClassTokensAbsent(tabHost.className, ['invisible']);
+ } finally {
+ requestFrame.mockRestore();
+ cancelFrame.mockRestore();
+ }
+ });
+
+ test('reserves only the header actions that overlap the editor-width tab strip', async () => {
+ const offsetWidth = vi
+ .spyOn(HTMLElement.prototype, 'offsetWidth', 'get')
+ .mockImplementation(function (this: HTMLElement) {
+ if (this.tagName === 'HEADER') return 1_000;
+ if (this.hasAttribute('data-editor-header-tabs')) return 800;
+ if (this.hasAttribute('data-editor-header-actions')) return 300;
+ if (this.hasAttribute('data-editor-header-leading-actions')) return 100;
+ return 0;
+ });
+
+ try {
+ const header = await renderHeader(<div>tabs</div>);
+ expect(header.style.getPropertyValue('--editor-header-trailing-width')).toBe('100px');
+ } finally {
+ offsetWidth.mockRestore();
+ }
+ });
+
+ test('keeps sidebar chrome movement immediate after a post-mount state change', async () => {
+ setElectronHost(true);
+ sidebarState = 'collapsed';
+ const { EditorHeader } = await import('./EditorHeader');
+ const headerUi = () => (
+ <TooltipProvider delayDuration={0}>
+ <EditorHeader onOpenSearch={onOpenSearch}>
+ <div>restored tabs</div>
+ </EditorHeader>
+ </TooltipProvider>
+ );
+ const view = render(headerUi());
+ const header = document.querySelector('header') as HTMLElement;
+
+ const leadingZone = header.querySelector('[data-editor-header-leading-actions]') as HTMLElement;
+ expectVisualClassTokens(leadingZone.className, ['left-[var(--ok-titlebar-reserve-left,1rem)]']);
+ expectVisualClassTokensAbsent(leadingZone.className, ['motion-safe:transition-[left]']);
+
+ sidebarState = 'expanded';
+ view.rerender(headerUi());
+
+ expectVisualClassTokensAbsent(leadingZone.className, [
+ 'left-[var(--ok-titlebar-reserve-left,1rem)]',
+ 'motion-safe:transition-[left]',
+ ]);
+ });
+
test('Windows places Hide Files before the File menu', async () => {
setWindowsHost();
const header = await renderHeader();
const files = screen.getByTestId('sidebar-trigger');
const menubar = await screen.findByTestId('app-menubar');
- const leftZone = header.children.item(0) as HTMLElement;
- const separator = leftZone.querySelector('[data-slot="separator"]') as HTMLElement;
+ const leadingZone = header.querySelector('[data-editor-header-leading-actions]') as HTMLElement;
+ const separator = leadingZone.querySelector('[data-slot="separator"]') as HTMLElement;
expect(files.compareDocumentPosition(menubar) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
expect(
@@ -267,20 +386,6 @@ describe('EditorHeader runtime behavior', () => {
expect(screen.queryByTestId('sidebar-trigger')).toBeNull();
});
- test('rail drag keeps the reserve but drops the padding transition so it snaps with the sidebar', async () => {
- // During a rail drag the sidebar group runs duration-0 and collapses
- // instantly; an animated reserve would lag behind and park the
- // collapse/search controls under the traffic lights. The reserve must be
- // present (collapsed) but the transition must be absent (snap).
- setElectronHost(true);
- sidebarState = 'collapsed';
- isDraggingRail = true;
- const header = await renderHeader();
-
- expectVisualClassTokens(header.className, ['pl-[var(--ok-titlebar-reserve-left,1rem)]']);
- expectVisualClassTokensAbsent(header.className, ['motion-safe:transition-[padding]']);
- });
-
test('single-file mode omits collapsed navigation history with the rest of project chrome', async () => {
setElectronHost(true);
sidebarState = 'collapsed';
@@ -292,15 +397,37 @@ describe('EditorHeader runtime behavior', () => {
expect(screen.queryByTestId('navigation-history-controls')).toBeNull();
});
- test('renders tabs and action cluster without project or asset-title chrome', async () => {
- await renderHeader();
+ test('renders workspace tabs between the global action zones', async () => {
+ await renderHeader(<div data-testid="editor-tabs">tabs</div>);
- expect(screen.getByTestId('editor-tabs')).toBeTruthy();
+ const tabHost = document.querySelector('[data-editor-header-tabs]');
+ expect(tabHost?.contains(screen.getByTestId('editor-tabs'))).toBe(true);
expect(screen.queryByTestId('open-in-agent-menu')).toBeNull();
expect(screen.queryByText('projectName')).toBeNull();
expect(screen.queryByText('assetFileName')).toBeNull();
});
+ test('keeps the existing action-zone styling when workspace tabs share the header', async () => {
+ const header = await renderHeader(<div data-testid="editor-tabs">tabs</div>);
+ const leadingZone = header.querySelector('[data-editor-header-leading-actions]') as HTMLElement;
+ const trailingZone = header.querySelector('[data-editor-header-actions]') as HTMLElement;
+
+ expectVisualClassTokensAbsent(leadingZone.className, ['bg-muted/95']);
+ expectVisualClassTokensAbsent(trailingZone.className, ['bg-muted/95']);
+ });
+
+ test('keeps header actions inline with multiple editor panes', async () => {
+ paneCount = 3;
+ const header = await renderHeader();
+ const trailingZone = header.querySelector('[data-editor-header-actions]') as HTMLElement;
+
+ expect(screen.queryByRole('button', { name: 'More actions' })).toBeNull();
+ expect(trailingZone.contains(screen.getByRole('button', { name: 'Share' }))).toBe(true);
+ expect(trailingZone.contains(screen.getByRole('button', { name: 'Settings' }))).toBe(true);
+ expect(trailingZone.contains(screen.getByRole('button', { name: 'Resources' }))).toBe(true);
+ expect(document.querySelector('[data-editor-header-overflow-actions]')).toBeNull();
+ });
+
test('an active doc yields a doc-scope share input', async () => {
activeDocName = 'docs/notes';
activeTarget = { kind: 'doc' };
diff --git a/packages/app/src/components/EditorHeader.tsx b/packages/app/src/components/EditorHeader.tsx
index 9427ec15a..e2c5d0c53 100644
--- a/packages/app/src/components/EditorHeader.tsx
+++ b/packages/app/src/components/EditorHeader.tsx
@@ -1,7 +1,7 @@
import { parseManagedArtifactName } from '@inkeep/open-knowledge-core';
import { useLingui } from '@lingui/react/macro';
import { Search } from 'lucide-react';
-import { lazy, Suspense, useState } from 'react';
+import { lazy, type ReactNode, Suspense, useLayoutEffect, useRef, useState } from 'react';
import { shouldShowAppMenubar } from '@/components/app-menubar-gate';
import { Button } from '@/components/ui/button';
import { ButtonGroup } from '@/components/ui/button-group';
@@ -20,7 +20,6 @@ import { useSingleFileMode } from '@/lib/single-file-mode';
import { cn } from '@/lib/utils';
import { PresenceBar } from '@/presence/PresenceBar';
import { BetaBadge } from './BetaBadge';
-import { EditorTabs } from './EditorTabs';
import { HelpPopover } from './HelpPopover';
import { InstanceBadge } from './InstanceBadge';
import { NavigationHistoryControls } from './NavigationHistoryControls';
@@ -36,12 +35,18 @@ const AppMenubar = lazy(() =>
);
interface EditorHeaderProps {
+ children?: ReactNode;
onSignIn?: () => void;
onSetIdentity?: () => void;
onOpenSearch?: () => void;
}
-export function EditorHeader({ onSignIn, onSetIdentity, onOpenSearch }: EditorHeaderProps) {
+export function EditorHeader({
+ children,
+ onSignIn,
+ onSetIdentity,
+ onOpenSearch,
+}: EditorHeaderProps) {
const { t } = useLingui();
const { activeDocName, activeTarget } = useDocumentContext();
// Managed-artifact tabs (skills/templates) are ordinary docs but carry their
@@ -50,7 +55,7 @@ export function EditorHeader({ onSignIn, onSetIdentity, onOpenSearch }: EditorHe
// trigger gates on this. The agent-handoff for a skill lives in the Skills
// sidebar (SkillsSidebarSection / skill-actions), not the header.
const managedArtifact = activeDocName ? parseManagedArtifactName(activeDocName) : null;
- const { state: sidebarState, isDraggingRail } = useSidebar();
+ const { state: sidebarState } = useSidebar();
// No-project single-file session (`ok <file>`): drop the project chrome
// (sidebar toggle, tab strip, Settings) while leaving the editor + the
// doc-scoped actions (Share / sync / agent handoff) intact.
@@ -60,6 +65,13 @@ export function EditorHeader({ onSignIn, onSetIdentity, onOpenSearch }: EditorHe
const searchShortcut = formatShortcut('command-palette');
const searchShortcutLabel = formatShortcutLabel('command-palette');
const [publishOpen, setPublishOpen] = useState(false);
+ // Keep tabs hidden until their action-zone offsets are ready; otherwise
+ // the zero-width CSS fallback is visible for one frame during startup.
+ const [chromeMeasured, setChromeMeasured] = useState(false);
+ const headerRef = useRef<HTMLElement>(null);
+ const leadingActionsRef = useRef<HTMLDivElement>(null);
+ const tabsHostRef = useRef<HTMLDivElement>(null);
+ const trailingActionsRef = useRef<HTMLDivElement>(null);
// Share input for the header button: folder → folder-scope, doc → doc-scope,
// empty editor → project root; non-shareable surfaces yield null (disabled).
const shareInput: ShareTargetInput | null = (() => {
@@ -92,8 +104,7 @@ export function EditorHeader({ onSignIn, onSetIdentity, onOpenSearch }: EditorHe
// and the reserve is required to keep the SidebarTrigger clear of the
// traffic lights. The reserve uses the shared `--ok-titlebar-reserve-left`
// token (defined under `html.electron-mode`) so the magic 78px lives in one
- // place; the `,1rem` fallback is the precedent-#49 safe form. The padding
- // transition (and its drag-snap exception) is documented at the className.
+ // place; the `,1rem` fallback is the precedent-#49 safe form.
const isCollapsed = sidebarState === 'collapsed';
const appMenubar = shouldShowAppMenubar() ? (
<Suspense fallback={null}>
@@ -101,39 +112,90 @@ export function EditorHeader({ onSignIn, onSetIdentity, onOpenSearch }: EditorHe
</Suspense>
) : null;
+ useLayoutEffect(() => {
+ const header = headerRef.current;
+ const leadingActions = leadingActionsRef.current;
+ const tabsHost = tabsHostRef.current;
+ const trailingActions = trailingActionsRef.current;
+ if (!header || !leadingActions || !tabsHost || !trailingActions) return;
+
+ const updateChromeWidths = () => {
+ header.style.setProperty('--editor-header-leading-width', `${leadingActions.offsetWidth}px`);
+ const rightRailWidth = Math.max(0, header.offsetWidth - tabsHost.offsetWidth);
+ header.style.setProperty(
+ '--editor-header-trailing-width',
+ `${Math.max(0, trailingActions.offsetWidth - rightRailWidth)}px`,
+ );
+ };
+ updateChromeWidths();
+
+ // Let both the header chrome and the restored tab workspace settle before
+ // making the tabs visible. Revealing after the first measurement exposes
+ // the zero-width fallback briefly, then moves the tabs when layout catches
+ // up on the next frame.
+ let revealFrame = requestAnimationFrame(() => {
+ updateChromeWidths();
+ revealFrame = requestAnimationFrame(() => {
+ updateChromeWidths();
+ setChromeMeasured(true);
+ });
+ });
+
+ const observer =
+ typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(updateChromeWidths);
+ observer?.observe(header);
+ observer?.observe(leadingActions);
+ observer?.observe(tabsHost);
+ observer?.observe(trailingActions);
+ return () => {
+ cancelAnimationFrame(revealFrame);
+ observer?.disconnect();
+ };
+ }, []);
+
+ const headerActions = (
+ <>
+ {/* Share is a project surface: single-file `ok <file>` runs agents/MCP
+ off and on a throwaway server, so a share link would point at a
+ session that's gone on close. Hidden here (mirrors the
+ sidebar/Settings gates) rather than rendered disabled. */}
+ {!singleFile && (
+ <ShareButton input={shareInput} onClickWhenNoRemote={() => setPublishOpen(true)} />
+ )}
+ <SyncStatusBadge onSignIn={onSignIn} onSetIdentity={onSetIdentity} />
+ <PresenceBar />
+ <Separator orientation="vertical" className="h-4 shrink-0 data-vertical:self-center" />
+ <InstanceBadge />
+ <BetaBadge />
+ {/* Settings is unavailable in single-file mode (config editing is inert). */}
+ {!singleFile && <SettingsButton />}
+ <HelpPopover />
+ </>
+ );
+
return (
<header
+ ref={headerRef}
data-electron-drag={isElectronHost ? '' : undefined}
+ style={{
+ ['--editor-header-leading-offset' as string]:
+ isElectronHost && isCollapsed ? 'var(--ok-titlebar-reserve-left, 1rem)' : '0px',
+ }}
className={cn(
- 'flex h-12 shrink-0 items-center bg-muted/35 shadow-[inset_0_-1px_0_var(--border)]',
+ 'group/editor-header relative flex h-12 shrink-0 items-center bg-muted/35 shadow-[inset_0_-1px_0_var(--border)]',
isElectronHost && '[-webkit-app-region:drag]',
- isElectronHost && isCollapsed && 'pl-[var(--ok-titlebar-reserve-left,1rem)]',
- // Animate the reserve in lockstep with the sidebar's 200ms offcanvas
- // slide on a button/keyboard toggle — but SNAP it while the rail is
- // being dragged. A drag-collapse sets `data-dragging` on the sidebar
- // group, which forces `duration-0` on the sidebar's own slide, so the
- // sidebar vanishes instantly; an animated reserve would lag ~200ms
- // behind and park the collapse/search controls under the macOS traffic
- // lights for the length of the animation.
- isElectronHost &&
- !isDraggingRail &&
- 'motion-safe:transition-[padding] motion-safe:duration-200 motion-safe:ease-linear',
)}
>
- {/*
- Left zone uses per-child `no-drag` opt-outs (instead of the
- right zone's `[&>*]:` child-combinator) because EditorTabs is a
- direct child whose own root MUST stay draggable so the empty
- space inside the tab strip continues to drag the window. Adding
- a future interactive control here? Apply `[-webkit-app-region:
- no-drag]` (gated on `isElectronHost`) explicitly on the new
- element — the right zone's blanket opt-out is intentionally
- scoped to its zone.
- */}
- {/* The left zone (files toggle, search, tab strip) is project chrome —
- empty in single-file mode. The flex-1 container stays so the right
- zone keeps its position and the window-drag spacer is preserved. */}
- <div className="flex min-w-0 flex-1 items-center gap-1 px-3">
+ {/* The left zone (files toggle and search) is project chrome —
+ empty in single-file mode. */}
+ <div
+ ref={leadingActionsRef}
+ data-editor-header-leading-actions=""
+ className={cn(
+ 'absolute inset-y-0 left-0 z-20 flex items-center gap-1 px-3',
+ isElectronHost && isCollapsed && 'left-[var(--ok-titlebar-reserve-left,1rem)]',
+ )}
+ >
{/* The menubar renders in single-file windows too: the project-chrome
group below is absent there, so without this slot Window / Help /
Exit would have no reachable surface at all. */}
@@ -193,14 +255,27 @@ export function EditorHeader({ onSignIn, onSetIdentity, onOpenSearch }: EditorHe
orientation="vertical"
className="mr-1 h-4 shrink-0 data-vertical:self-center"
/>
- <EditorTabs />
</>
)}
</div>
<div
+ ref={tabsHostRef}
+ data-editor-header-tabs=""
className={cn(
- 'flex shrink-0 items-center justify-end gap-2 px-3',
+ 'absolute inset-y-0 left-0 z-10 flex min-w-0 w-[var(--editor-header-tabs-width,100%)] overflow-hidden',
+ !chromeMeasured && 'invisible',
+ isElectronHost && '[-webkit-app-region:no-drag]',
+ )}
+ >
+ {children}
+ </div>
+
+ <div
+ ref={trailingActionsRef}
+ data-editor-header-actions=""
+ className={cn(
+ 'absolute inset-y-0 right-0 z-20 flex items-center justify-end gap-2 px-3',
// Child-combinator opt-out: every direct DOM child of the right zone
// gets `app-region: no-drag` so clicks on Save / OpenInAgentMenu /
// SyncStatusBadge / PresenceBar / BetaBadge / SettingsButton /
@@ -215,24 +290,8 @@ export function EditorHeader({ onSignIn, onSetIdentity, onOpenSearch }: EditorHe
isElectronHost && 'mr-[var(--ok-titlebar-reserve-right,0px)]',
)}
>
- {/* Share is a project surface: single-file `ok <file>` runs agents/MCP
- off and on a throwaway server, so a share link would point at a
- session that's gone on close. Hidden here (mirrors the
- sidebar/Settings gates) rather than rendered disabled. */}
- {!singleFile && (
- <>
- <ShareButton input={shareInput} onClickWhenNoRemote={() => setPublishOpen(true)} />
- <PublishToGitHubDialog open={publishOpen} onOpenChange={setPublishOpen} />
- </>
- )}
- <SyncStatusBadge onSignIn={onSignIn} onSetIdentity={onSetIdentity} />
- <PresenceBar />
- <Separator orientation="vertical" className="h-4 shrink-0 data-vertical:self-center" />
- <InstanceBadge />
- <BetaBadge />
- {/* Settings is unavailable in single-file mode (config editing is inert). */}
- {!singleFile && <SettingsButton />}
- <HelpPopover />
+ {headerActions}
+ {!singleFile && <PublishToGitHubDialog open={publishOpen} onOpenChange={setPublishOpen} />}
</div>
</header>
);
diff --git a/packages/app/src/components/EditorPane.dom.test.tsx b/packages/app/src/components/EditorPane.dom.test.tsx
index 0a8dc26ab..8ebd5cea8 100644
--- a/packages/app/src/components/EditorPane.dom.test.tsx
+++ b/packages/app/src/components/EditorPane.dom.test.tsx
@@ -157,7 +157,9 @@ vi.doMock('@/editor/use-editor-mode', () => ({
}));
vi.doMock('./EditorHeader', () => ({
- EditorHeader: () => <div data-testid="editor-header" />,
+ EditorHeader: ({ children }: { children?: ReactNode }) => (
+ <div data-testid="editor-header">{children}</div>
+ ),
}));
// EditorArea renders the layout shells + reports both panels' placements up; the
@@ -167,7 +169,15 @@ vi.doMock('./EditorHeader', () => ({
// surfaces the threaded `surface` + `visible` + `launch` props so these tests keep
// asserting EditorPane's wiring across the prop boundary.
vi.doMock('./EditorArea', () => ({
- EditorArea: () => <div data-testid="editor-area" />,
+ EditorArea: ({
+ renderWorkspaceHeader,
+ }: {
+ renderWorkspaceHeader?: (tabs: ReactNode) => ReactNode;
+ }) => (
+ <div data-testid="editor-area">
+ {renderWorkspaceHeader?.(<div data-testid="workspace-tabs" />)}
+ </div>
+ ),
}));
// The agent-thread client binder opens a WS + polls /api/config on mount; stub it
// so these EditorPane tests exercise terminal/onboarding wiring in isolation.
@@ -495,6 +505,9 @@ describe('EditorPane session-panel wiring', () => {
expect(agents.getAttribute('data-terminal-capable')).toBe('false');
expect(screen.queryByTestId('terminal-dock')).toBeNull();
expect(screen.getByTestId('editor-header')).toBeTruthy();
+ expect(screen.getByTestId('editor-header').contains(screen.getByTestId('workspace-tabs'))).toBe(
+ true,
+ );
expect(screen.getByTestId('editor-area')).toBeTruthy();
});
diff --git a/packages/app/src/components/EditorPane.tsx b/packages/app/src/components/EditorPane.tsx
index a2c2cf8a5..cdf554e09 100644
--- a/packages/app/src/components/EditorPane.tsx
+++ b/packages/app/src/components/EditorPane.tsx
@@ -625,22 +625,10 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
<Suspense fallback={null}>
<AgentThreadClientBinder />
</Suspense>
- <EditorHeader
- onSignIn={() => {
- setAuthInitialStep('auth');
- setAuthModalOpen(true);
- }}
- onSetIdentity={() => {
- setAuthInitialStep('identity');
- setAuthModalOpen(true);
- }}
- onOpenSearch={onOpenSearch}
- />
{/* The editor takes the row's full width. Both session panels live WITHIN
- EditorArea — the terminal beneath the editor, the agents panel as its own
- right column past the doc panels; EditorArea owns that layout. The live
- hosts are mounted below (above EditorArea) so a view-kind change never
- remounts them. */}
+ EditorArea — the terminal below the editor and the agents panel in its
+ own right column. Their live hosts mount below, above EditorArea, so a
+ placement change never remounts a running session. */}
<div className="flex min-h-0 flex-1 overflow-hidden">
<div className="flex min-w-0 flex-1 flex-col">
<EditorArea
@@ -655,6 +643,21 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
onAgentsVisibleChange={setAgentsVisible}
onSessionPlacements={setPlacements}
onRevealAgents={revealAgents}
+ renderWorkspaceHeader={(tabs) => (
+ <EditorHeader
+ onSignIn={() => {
+ setAuthInitialStep('auth');
+ setAuthModalOpen(true);
+ }}
+ onSetIdentity={() => {
+ setAuthInitialStep('identity');
+ setAuthModalOpen(true);
+ }}
+ onOpenSearch={onOpenSearch}
+ >
+ {tabs}
+ </EditorHeader>
+ )}
/>
</div>
</div>
diff --git a/packages/app/src/components/EditorTabTargetMenuItems.tsx b/packages/app/src/components/EditorTabTargetMenuItems.tsx
new file mode 100644
index 000000000..5b3257d0e
--- /dev/null
+++ b/packages/app/src/components/EditorTabTargetMenuItems.tsx
@@ -0,0 +1,235 @@
+import { Trans, useLingui } from '@lingui/react/macro';
+import { toast } from 'sonner';
+import {
+ FileTargetMenuItems,
+ type FileTargetMenuPrimitives,
+} from '@/components/FileTargetMenuItems';
+import { buildOkignorePatternFromTarget } from '@/components/file-tree-okignore';
+import { hasOkPathSegment } from '@/components/file-tree-utils';
+import { OpenInAgentEmptySpaceSubmenu } from '@/components/handoff/OpenInAgentEmptySpaceSubmenu';
+import { useHandoffDispatch } from '@/components/handoff/useHandoffDispatch';
+import { useInstalledAgents } from '@/components/handoff/useInstalledAgents';
+import type { ResolvedNavigationTarget } from '@/components/navigation-targets';
+import {
+ appendPattern,
+ parseOkignoreDoc,
+ serializeOkignoreDoc,
+} from '@/components/settings/okignore-doc';
+import { TemplateMenuRows } from '@/components/template-menu-rows';
+import {
+ ContextMenuGroup,
+ ContextMenuItem,
+ ContextMenuSeparator,
+ ContextMenuSub,
+ ContextMenuSubContent,
+ ContextMenuSubTrigger,
+} from '@/components/ui/context-menu';
+import { useGitSyncStatusDetailed } from '@/hooks/use-git-sync-status';
+import { useConfigContext } from '@/lib/config-provider';
+import { emitCreateTopLevelFile } from '@/lib/create-file-events';
+import {
+ buildSendToAiInputForActiveTarget,
+ resolveActiveTargetRelativePath,
+} from '@/lib/file-menu-target-resolvers';
+import {
+ emitFileTreeMenuActionDelete,
+ emitFileTreeMenuActionDuplicate,
+ emitFileTreeMenuActionImportTemplate,
+} from '@/lib/file-tree-menu-action-events';
+import { scheduleClipboardWrite } from '@/lib/share/clipboard-adapter';
+import {
+ buildDocShareInput,
+ buildFolderShareInput,
+ runShareAction,
+ type ShareTargetInput,
+} from '@/lib/share/run-share-action';
+import { useWorkspace } from '@/lib/use-workspace';
+import { joinWorkspacePath } from '@/lib/workspace-paths';
+
+export type EditorTabFileTarget = Extract<
+ ResolvedNavigationTarget,
+ { kind: 'asset' | 'doc' | 'folder' }
+>;
+
+const CONTEXT_FILE_TARGET_MENU_PRIMITIVES = {
+ Group: ContextMenuGroup,
+ Item: ContextMenuItem,
+ Separator: ContextMenuSeparator,
+ Sub: ContextMenuSub,
+ SubContent: ContextMenuSubContent,
+ SubTrigger: ContextMenuSubTrigger,
+} satisfies FileTargetMenuPrimitives;
+
+function relativePathForTarget(target: EditorTabFileTarget, docExt?: string): string {
+ if (target.kind !== 'doc' || /\.(md|mdx)$/i.test(target.docName)) {
+ return resolveActiveTargetRelativePath(target);
+ }
+ return `${target.docName}${docExt ?? '.md'}`;
+}
+
+function shareInputForTarget(target: EditorTabFileTarget): ShareTargetInput | null {
+ if (target.kind === 'asset') return null;
+ if (target.kind === 'folder') return buildFolderShareInput(target.folderPath);
+ return buildDocShareInput(target.docName);
+}
+
+function okignoreTargetForTarget(
+ target: EditorTabFileTarget,
+ docExt?: string,
+): Parameters<typeof buildOkignorePatternFromTarget>[0] | null {
+ if (target.kind === 'doc') return { kind: 'file', path: target.docName, docExt };
+ if (target.kind === 'folder') return { kind: 'folder', path: target.folderPath };
+ return null;
+}
+
+interface EditorTabTargetMenuItemsProps {
+ docExt?: string;
+ target: EditorTabFileTarget;
+ onRename: () => void;
+}
+
+export function EditorTabTargetMenuItems({
+ docExt,
+ target,
+ onRename,
+}: EditorTabTargetMenuItemsProps) {
+ const { t } = useLingui();
+ const workspace = useWorkspace();
+ const { okignoreBinding } = useConfigContext();
+ const { status: gitSyncStatus } = useGitSyncStatusDetailed();
+ const installStates = useInstalledAgents().states;
+ const { dispatch } = useHandoffDispatch();
+ const relativePath = relativePathForTarget(target, docExt);
+ const isManaged = hasOkPathSegment(relativePath);
+ const isAsset = target.kind === 'asset';
+ const isFolder = target.kind === 'folder';
+ const bridge = typeof window !== 'undefined' ? window.okDesktop : undefined;
+ const handoffInput = isAsset ? null : buildSendToAiInputForActiveTarget(target, workspace);
+ const shareInput = shareInputForTarget(target);
+ const canShare = gitSyncStatus?.hasRemote === true && shareInput !== null;
+ const okignoreTarget = okignoreTargetForTarget(target, docExt);
+
+ function copyPath(path: string, successMessage: string, errorMessage: string) {
+ void scheduleClipboardWrite(path)
+ .then(() => toast.success(successMessage, { description: path }))
+ .catch((error: unknown) => {
+ console.warn('[EditorTabTargetMenuItems] clipboard write failed:', error);
+ toast.error(errorMessage);
+ });
+ }
+
+ function shareTarget() {
+ if (!shareInput) return;
+ void runShareAction(
+ {
+ ...shareInput,
+ hasRemote: true,
+ onClickWhenNoRemote: () => toast.error(t`Connect this project to GitHub to share.`),
+ },
+ {
+ clipboardWrite: scheduleClipboardWrite,
+ toastSuccess: (message) => toast.success(message),
+ toastError: (message) => toast.error(message),
+ logEvent: (message) => console.log(message),
+ },
+ );
+ }
+
+ function hideTarget() {
+ if (!okignoreBinding || !okignoreTarget) return;
+ const doc = parseOkignoreDoc(okignoreBinding.current());
+ const updated = appendPattern(doc, buildOkignorePatternFromTarget(okignoreTarget));
+ if (updated === doc) return;
+ okignoreBinding.patch(serializeOkignoreDoc(updated));
+ const basename = relativePath.split('/').pop() ?? relativePath;
+ toast.success(isFolder ? t`Hidden folder “${basename}”` : t`Hidden “${basename}”`, {
+ description: t`Manage hidden files in Settings → Ignore patterns.`,
+ duration: 5000,
+ });
+ }
+
+ let revealLabel = t`Open containing folder`;
+ if (bridge?.platform === 'darwin') revealLabel = t`Reveal in Finder`;
+ else if (bridge?.platform === 'win32') revealLabel = t`Reveal in File Explorer`;
+ const noWorkspaceHint = workspace ? null : t`No workspace`;
+ const fullPath = workspace
+ ? joinWorkspacePath(workspace.contentDir, relativePath, workspace.pathSeparator)
+ : '';
+
+ return (
+ <FileTargetMenuItems
+ primitives={CONTEXT_FILE_TARGET_MENU_PRIMITIVES}
+ workspaceReady={workspace !== null}
+ folderCreate={
+ isFolder && !isManaged
+ ? {
+ onNewFile: () => emitCreateTopLevelFile({ initialDir: target.folderPath }),
+ onNewFolder: () =>
+ emitCreateTopLevelFile({ initialDir: target.folderPath, kind: 'folder' }),
+ templateItems: (
+ <TemplateMenuRows
+ parentDir={target.folderPath}
+ onSelectTemplate={(templateName) =>
+ emitCreateTopLevelFile({
+ template: { folder: target.folderPath, name: templateName },
+ })
+ }
+ ItemComponent={ContextMenuItem}
+ />
+ ),
+ }
+ : undefined
+ }
+ reveal={
+ bridge
+ ? {
+ label: revealLabel,
+ ariaLabel: noWorkspaceHint ? `${revealLabel}, ${noWorkspaceHint}` : revealLabel,
+ disabled: !workspace,
+ hint: noWorkspaceHint,
+ onSelect: () => {
+ if (!workspace) return;
+ void bridge.shell.showItemInFolder(fullPath);
+ },
+ }
+ : undefined
+ }
+ openWithAi={
+ isAsset ? undefined : (
+ <OpenInAgentEmptySpaceSubmenu
+ input={handoffInput}
+ installStates={installStates}
+ dispatch={dispatch}
+ />
+ )
+ }
+ share={canShare ? { onSelect: shareTarget } : undefined}
+ onCopyFullPath={() => {
+ if (!workspace) return;
+ copyPath(fullPath, t`Copied full path`, t`Could not copy full path`);
+ }}
+ onCopyRelativePath={() =>
+ copyPath(relativePath, t`Copied relative path`, t`Could not copy relative path`)
+ }
+ onImportTemplate={
+ target.kind === 'doc' && !isManaged
+ ? (deleteSource) => emitFileTreeMenuActionImportTemplate(target, deleteSource)
+ : undefined
+ }
+ onDuplicate={
+ !isAsset && !isManaged ? () => emitFileTreeMenuActionDuplicate(target) : undefined
+ }
+ onRename={!isManaged ? onRename : undefined}
+ hide={
+ okignoreTarget && !isManaged
+ ? {
+ label: isFolder ? <Trans>Hide folder</Trans> : <Trans>Hide this file</Trans>,
+ disabled: okignoreBinding === null,
+ onSelect: hideTarget,
+ }
+ : undefined
+ }
+ onDelete={!isManaged ? () => emitFileTreeMenuActionDelete(target) : undefined}
+ />
+ );
+}
diff --git a/packages/app/src/components/EditorTabs.dom.test.tsx b/packages/app/src/components/EditorTabs.dom.test.tsx
index 2b0cda915..636d6d772 100644
--- a/packages/app/src/components/EditorTabs.dom.test.tsx
+++ b/packages/app/src/components/EditorTabs.dom.test.tsx
@@ -3,7 +3,7 @@ import { isMacOS } from '@tiptap/core';
import type { ReactNode } from 'react';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { TooltipProvider } from '@/components/ui/tooltip';
-import { assetTabId, folderTabId } from '@/editor/editor-tabs';
+import { assetTabId, folderTabId, skillFileTabId } from '@/editor/editor-tabs';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
import {
expectVisualClassTokens,
@@ -19,9 +19,11 @@ let openTabs: string[] = [];
let visibleTabIds: string[] = [];
let newTabIds: string[] = [];
let pinnedTabIds: string[] = [];
+let previewTabId: string | null = null;
let pageMeta: Map<string, { docExt?: string }> = new Map();
let lifecycleStatuses: Map<string, string> = new Map();
-let toastErrors: string[] = [];
+let focusedPaneId = 'pane-a';
+let skillsState: unknown = { status: 'idle' };
const activateTab = vi.fn(() => {});
const activateNewTab = vi.fn(() => {});
@@ -30,10 +32,13 @@ const closeTab = vi.fn(() => {});
const closeTabs = vi.fn(() => {});
const openNewTab = vi.fn(() => {});
const pinTab = vi.fn(() => {});
+const promoteTab = vi.fn(() => {});
const reopenClosedTab = vi.fn(() => {});
-const reconcileLocalRename = vi.fn(() => Promise.resolve());
const reorderTabs = vi.fn(() => {});
const unpinTab = vi.fn(() => {});
+const moveTabToNewPane = vi.fn(() => 'pane-new' as string | null);
+const requestSkillDelete = vi.fn(() => {});
+const requestSkillFileRename = vi.fn(() => {});
function primaryShortcutModifier(): Pick<KeyboardEventInit, 'ctrlKey' | 'metaKey'> {
return isMacOS() ? { metaKey: true } : { ctrlKey: true };
@@ -54,7 +59,13 @@ const sortableKeyboardCoordinatesToken = { name: 'sortableKeyboardCoordinates' }
const dndContextProps: DndContextProps[] = [];
const sensorCalls: Array<{ sensor: unknown; options: unknown }> = [];
const sortableContextProps: Array<{ items: string[]; strategy: unknown }> = [];
-const sortableOptions: Array<{ id: string; disabled?: boolean }> = [];
+const sortableOptions: Array<{
+ animateLayoutChanges?: () => boolean;
+ data?: unknown;
+ disabled?: boolean;
+ id: string;
+ transition?: unknown;
+}> = [];
// Stands in for dnd-kit's in-flight drag; non-null simulates a reorder drag.
let activeDrag: { id: string } | null = null;
@@ -114,8 +125,14 @@ vi.doMock('@dnd-kit/sortable', () => ({
sortableContextProps.push({ items: [...items], strategy });
return <div data-testid="sortable-context">{children}</div>;
},
- useSortable: ({ id, disabled }: { id: string; disabled?: boolean }) => {
- sortableOptions.push({ id, disabled });
+ useSortable: (options: {
+ animateLayoutChanges?: () => boolean;
+ data?: unknown;
+ id: string;
+ transition?: unknown;
+ }) => {
+ const { id } = options;
+ sortableOptions.push(options);
return {
attributes: {
role: 'button',
@@ -147,6 +164,7 @@ vi.doMock('@/components/ui/context-menu', () => ({
{children}
</div>
),
+ ContextMenuGroup: ({ children }: { children?: ReactNode }) => <>{children}</>,
ContextMenuItem: ({
children,
disabled,
@@ -174,6 +192,60 @@ vi.doMock('@/components/ui/context-menu', () => ({
ContextMenuTrigger: ({ children }: { children?: ReactNode }) => <>{children}</>,
}));
+vi.doMock('@/components/EditorTabTargetMenuItems', () => ({
+ EditorTabTargetMenuItems: () => null,
+}));
+
+vi.doMock('@/components/FileTargetRenameDialog', () => ({
+ FileTargetRenameDialog: () => null,
+}));
+
+vi.doMock('@/components/skill-actions', () => ({
+ SkillFileContextMenuItems: ({
+ actions,
+ filePath,
+ menuKind,
+ skill,
+ }: {
+ actions: { requestFileRename: (skill: unknown, filePath: string) => void };
+ filePath: string;
+ menuKind?: string;
+ skill: { name: string };
+ }) => (
+ <button
+ type="button"
+ role="menuitem"
+ data-menu-kind={menuKind}
+ onClick={() => actions.requestFileRename(skill, filePath)}
+ >
+ Rename skill file {filePath}
+ </button>
+ ),
+ SkillContextMenuItems: ({
+ actions,
+ menuKind,
+ skill,
+ }: {
+ actions: { requestDelete: (skill: unknown) => void };
+ menuKind?: string;
+ skill: { name: string };
+ }) => (
+ <button
+ type="button"
+ role="menuitem"
+ data-menu-kind={menuKind}
+ onClick={() => actions.requestDelete(skill)}
+ >
+ Delete skill {skill.name}
+ </button>
+ ),
+ useSkillActions: () => ({
+ dialogs: <div data-testid="skill-action-dialogs" />,
+ requestDelete: requestSkillDelete,
+ requestFileRename: requestSkillFileRename,
+ }),
+}));
+
vi.doMock('@/editor/DocumentContext', () => ({
useDocumentContext: () => ({
activeDocName,
@@ -192,10 +264,36 @@ vi.doMock('@/editor/DocumentContext', () => ({
pinTab,
pinnedTabIds,
reopenClosedTab,
- reconcileLocalRename,
reorderTabs,
unpinTab,
visibleTabIds,
+ visibleTabIdsByPane: new Map([['pane-a', visibleTabIds]]),
+ focusedPaneId,
+ panes: [
+ {
+ id: 'pane-a',
+ openTabs,
+ pinnedTabIds,
+ previewTabId,
+ activeTabId,
+ newTabIds,
+ activeNewTabId,
+ activeTarget:
+ activeTarget ??
+ (activeDocName ? { kind: 'doc', target: activeDocName, docName: activeDocName } : null),
+ size: 100,
+ },
+ ],
+ activateTabInPane: (_paneId: string, tabId: string) => activateTab(tabId),
+ activateNewTabInPane: (_paneId: string, tabId: string) => activateNewTab(tabId),
+ closeNewTabInPane: (_paneId: string, tabId: string) => closeNewTab(tabId),
+ closeTabInPane: (_paneId: string, tabId: string) => closeTab(tabId),
+ closeTabsInPane: (_paneId: string, tabIds: readonly string[]) => closeTabs(tabIds),
+ moveTabToNewPane,
+ openNewTabInPane: () => openNewTab(),
+ pinTabInPane: (_paneId: string, tabId: string) => pinTab(tabId),
+ promoteTabInPane: (_paneId: string, tabId: string) => promoteTab(tabId),
+ unpinTabInPane: (_paneId: string, tabId: string) => unpinTab(tabId),
}),
}));
@@ -209,12 +307,8 @@ vi.doMock('@/hooks/use-lifecycle-status', () => ({
useLifecycleStatus: (docName: string) => lifecycleStatuses.get(docName) ?? null,
}));
-vi.doMock('sonner', () => ({
- toast: {
- error: (message: string) => {
- toastErrors.push(message);
- },
- },
+vi.doMock('@/hooks/use-skills', () => ({
+ useSkills: () => skillsState,
}));
function defaultTabs() {
@@ -241,13 +335,15 @@ function resetState() {
visibleTabIds = visible;
newTabIds = [newId];
pinnedTabIds = [];
+ previewTabId = null;
pageMeta = new Map([
['docs/team/notes', { docExt: '.md' }],
['docs/team/spec', { docExt: '.mdx' }],
['docs/team/readme', { docExt: '.txt' }],
]);
lifecycleStatuses = new Map();
- toastErrors = [];
+ focusedPaneId = 'pane-a';
+ skillsState = { status: 'idle' };
activeDrag = null;
dndContextProps.length = 0;
sensorCalls.length = 0;
@@ -261,37 +357,42 @@ function resetState() {
closeTabs,
openNewTab,
pinTab,
+ promoteTab,
reopenClosedTab,
- reconcileLocalRename,
reorderTabs,
unpinTab,
+ moveTabToNewPane,
+ requestSkillDelete,
+ requestSkillFileRename,
]) {
fn.mockClear();
}
- reconcileLocalRename.mockImplementation(() => Promise.resolve());
Object.defineProperty(window, 'okDesktop', {
configurable: true,
value: undefined,
});
window.location.hash = '';
- globalThis.fetch = vi.fn(() => Promise.reject(new Error('unexpected fetch'))) as never;
}
-async function renderEditorTabs() {
+async function renderEditorTabs({
+ dropIndicatorIndex = null,
+ reserveLeadingChrome = false,
+}: {
+ dropIndicatorIndex?: number | null;
+ reserveLeadingChrome?: boolean;
+} = {}) {
const { EditorTabs } = await import('./EditorTabs');
return render(
<TooltipProvider>
- <EditorTabs />
+ <EditorTabs
+ dropIndicatorIndex={dropIndicatorIndex}
+ paneId="pane-a"
+ reserveLeadingChrome={reserveLeadingChrome}
+ />
</TooltipProvider>,
);
}
-function latestDndContext() {
- const latest = dndContextProps.at(-1);
- expect(latest).toBeDefined();
- return latest as DndContextProps;
-}
-
function tabButton(name: string) {
const button = screen
.getAllByRole('button', { name })
@@ -322,16 +423,19 @@ describe('EditorTabs runtime behavior', () => {
const markdownTab = tabButton('docs/team/notes.md');
expect(markdownTab.textContent).toBe('notes');
+ expect(markdownTab.getAttribute('title')).toBeNull();
expect(markdownTab.closest('[data-sortable-id]')?.getAttribute('aria-keyshortcuts')).toBe(
'Meta+1 Control+1',
);
const mdxTab = tabButton('docs/team/spec.mdx');
expect(mdxTab.textContent).toBe('spec');
+ expect(mdxTab.getAttribute('title')).toBeNull();
expect(mdxTab.closest('[data-sortable-id]')?.getAttribute('aria-current')).toBe('page');
const txtTab = tabButton('docs/team/readme.txt');
expect(txtTab.textContent).toBe('readme.txt');
+ expect(txtTab.getAttribute('title')).toBeNull();
});
// The visible label is only the base name, so two same-named files in
@@ -341,8 +445,6 @@ describe('EditorTabs runtime behavior', () => {
const markdownTab = tabButton('docs/team/notes.md');
expect(markdownTab.textContent).toBe('notes');
- // The native tooltip attribute is deliberately gone: it would double up
- // with the hover tooltip and renders OS-styled after a ~1s delay.
expect(markdownTab.getAttribute('title')).toBeNull();
fireEvent.pointerEnter(markdownTab, { pointerType: 'mouse' });
@@ -359,6 +461,7 @@ describe('EditorTabs runtime behavior', () => {
await renderEditorTabs();
const tab = tabButton(expectedPath);
+ expect(tab.getAttribute('title')).toBeNull();
fireEvent.pointerEnter(tab, { pointerType: 'mouse' });
fireEvent.pointerMove(tab, { pointerType: 'mouse' });
@@ -376,6 +479,7 @@ describe('EditorTabs runtime behavior', () => {
await Promise.resolve();
expect(screen.queryByRole('tooltip')).toBeNull();
+ expect(markdownTab.getAttribute('title')).toBeNull();
// Load-bearing, not incidental coupling: the tooltip opens on a timer, so
// the absence above would also hold in the split second before an
// unsuppressed tooltip appeared. Asserting the trigger is gone is what
@@ -394,6 +498,7 @@ describe('EditorTabs runtime behavior', () => {
const rootTab = tabButton('readme.txt');
expect(rootTab.textContent).toBe('readme.txt');
+ expect(rootTab.getAttribute('title')).toBeNull();
fireEvent.pointerEnter(rootTab, { pointerType: 'mouse' });
fireEvent.pointerMove(rootTab, { pointerType: 'mouse' });
@@ -402,6 +507,22 @@ describe('EditorTabs runtime behavior', () => {
expect(tooltipText(tooltip)).toBe('readme.txt');
});
+ test('advertises pane-local tab shortcuts only in the focused pane', async () => {
+ focusedPaneId = 'pane-b';
+ const { container } = await renderEditorTabs();
+
+ for (const tab of container.querySelectorAll('[data-sortable-id]')) {
+ expect(tab.getAttribute('aria-keyshortcuts')).toBeNull();
+ }
+ });
+
+ test('bolds the active tab only when its pane is focused', async () => {
+ focusedPaneId = 'pane-b';
+ await renderEditorTabs();
+
+ expectVisualClassTokensAbsent(tabButton('docs/team/spec.mdx').className, ['font-semibold']);
+ });
+
test('keeps folder, asset, and new-tab branches closeable and independently activatable', async () => {
const { assetId, folderId, newId } = defaultTabs();
await renderEditorTabs();
@@ -426,7 +547,153 @@ describe('EditorTabs runtime behavior', () => {
expect(openNewTab).toHaveBeenCalledTimes(1);
});
- test('Electron host applies drag only to the strip root and no-drag to the content wrapper', async () => {
+ test('reuses the sidebar skill actions for an editable skill tab', async () => {
+ const skill = {
+ scope: 'project',
+ name: 'release-notes',
+ path: '.ok/skills/release-notes/SKILL.md',
+ managed: false,
+ };
+ const skillTabId = '.ok/skills/release-notes/SKILL';
+ activeDocName = skillTabId;
+ activeTabId = skillTabId;
+ openTabs = [skillTabId];
+ visibleTabIds = [skillTabId];
+ newTabIds = [];
+ skillsState = { status: 'ready', data: [skill] };
+
+ await renderEditorTabs();
+
+ const deleteItem = screen.getByRole('menuitem', { name: 'Delete skill release-notes' });
+ expect(deleteItem.getAttribute('data-menu-kind')).toBe('context');
+ expect(screen.getByTestId('skill-action-dialogs')).toBeTruthy();
+
+ fireEvent.click(deleteItem);
+ expect(requestSkillDelete).toHaveBeenCalledWith(skill);
+ });
+
+ test('does not expose skill actions for a managed skill tab', async () => {
+ const skill = {
+ scope: 'project',
+ name: 'release-notes',
+ path: '.ok/skills/release-notes/SKILL.md',
+ managed: true,
+ };
+ const skillTabId = '.ok/skills/release-notes/SKILL';
+ activeDocName = skillTabId;
+ activeTabId = skillTabId;
+ openTabs = [skillTabId];
+ visibleTabIds = [skillTabId];
+ newTabIds = [];
+ skillsState = { status: 'ready', data: [skill] };
+
+ await renderEditorTabs();
+
+ expect(screen.queryByRole('menuitem', { name: 'Delete skill release-notes' })).toBeNull();
+ });
+
+ test('reuses the sidebar file actions for an editable skill-file tab', async () => {
+ const skill = {
+ scope: 'global',
+ name: 'ask-matt',
+ path: '.agents/skills/ask-matt/SKILL.md',
+ absolutePath: '/Users/example/.agents/skills/ask-matt/SKILL.md',
+ hosts: ['agents'],
+ managed: false,
+ };
+ const filePath = 'agents/openai.yml';
+ const skillTabId = skillFileTabId({ scope: 'global', name: skill.name, path: filePath });
+ activeDocName = null;
+ activeTabId = skillTabId;
+ openTabs = [skillTabId];
+ visibleTabIds = [skillTabId];
+ newTabIds = [];
+ skillsState = { status: 'ready', data: [skill] };
+
+ await renderEditorTabs();
+
+ const renameItem = screen.getByRole('menuitem', {
+ name: `Rename skill file ${filePath}`,
+ });
+ expect(renameItem.getAttribute('data-menu-kind')).toBe('context');
+
+ fireEvent.click(renameItem);
+ expect(requestSkillFileRename).toHaveBeenCalledWith(skill, filePath);
+ });
+
+ test('uses the host-qualified owner for an editable skill-file tab', async () => {
+ const agentsSkill = {
+ scope: 'global',
+ name: 'ask-matt',
+ path: '.agents/skills/ask-matt/SKILL.md',
+ hosts: ['agents'],
+ managed: false,
+ };
+ const claudeSkill = {
+ scope: 'global',
+ name: 'ask-matt',
+ path: '.claude/skills/ask-matt/SKILL.md',
+ hosts: ['claude'],
+ managed: false,
+ };
+ const filePath = 'agents/openai.yml';
+ const skillTabId = skillFileTabId({
+ scope: 'global',
+ name: agentsSkill.name,
+ path: filePath,
+ host: 'agents',
+ });
+ activeDocName = null;
+ activeTabId = skillTabId;
+ openTabs = [skillTabId];
+ visibleTabIds = [skillTabId];
+ newTabIds = [];
+ skillsState = { status: 'ready', data: [claudeSkill, agentsSkill] };
+
+ await renderEditorTabs();
+
+ fireEvent.click(
+ screen.getByRole('menuitem', {
+ name: `Rename skill file ${filePath}`,
+ }),
+ );
+ expect(requestSkillFileRename).toHaveBeenCalledWith(agentsSkill, filePath);
+ });
+
+ test('does not expose file actions when a host-less skill-file owner is ambiguous', async () => {
+ const filePath = 'agents/openai.yml';
+ const skillTabId = skillFileTabId({ scope: 'global', name: 'ask-matt', path: filePath });
+ activeDocName = null;
+ activeTabId = skillTabId;
+ openTabs = [skillTabId];
+ visibleTabIds = [skillTabId];
+ newTabIds = [];
+ skillsState = {
+ status: 'ready',
+ data: [
+ {
+ scope: 'global',
+ name: 'ask-matt',
+ path: '.agents/skills/ask-matt/SKILL.md',
+ hosts: ['agents'],
+ managed: false,
+ },
+ {
+ scope: 'global',
+ name: 'ask-matt',
+ path: '.claude/skills/ask-matt/SKILL.md',
+ hosts: ['claude'],
+ managed: false,
+ },
+ ],
+ };
+
+ await renderEditorTabs();
+
+ expect(screen.queryByRole('menuitem', { name: `Rename skill file ${filePath}` })).toBeNull();
+ });
+
+ test('Electron host keeps the pane-local strip and controls interactive', async () => {
Object.defineProperty(window, 'okDesktop', {
configurable: true,
value: {},
@@ -436,70 +703,377 @@ describe('EditorTabs runtime behavior', () => {
const root = container.firstElementChild as HTMLElement;
const wrapper = root.firstElementChild as HTMLElement;
- expect(root.getAttribute('data-electron-drag')).toBe('');
- expectVisualClassTokens(root.className, ['[-webkit-app-region:drag]']);
+ expect(root.getAttribute('data-editor-pane-tabs')).toBe('pane-a');
+ expect(root.getAttribute('data-electron-drag')).toBeNull();
+ expectVisualClassTokens(root.className, ['[-webkit-app-region:no-drag]']);
expectVisualClassTokens(wrapper.className, [
'[-webkit-app-region:no-drag]',
'flex',
'items-end',
- 'gap-1',
+ 'gap-px',
]);
- expectVisualClassTokensAbsent(wrapper.className, ['flex-1']);
+ expectVisualClassTokens(wrapper.className, ['min-w-0', 'flex-1']);
});
- test('web host keeps baseline scroll layout without app-region classes', async () => {
+ test('keeps restored-tab chrome alignment immediate', async () => {
+ const { container } = await renderEditorTabs({ reserveLeadingChrome: true });
+ const root = container.firstElementChild as HTMLElement;
+
+ expectVisualClassTokens(root.className, [
+ 'pl-[calc(var(--editor-header-leading-offset,0px)+var(--editor-header-leading-width,0px)+0.5rem)]',
+ ]);
+ expectVisualClassTokensAbsent(root.className, [
+ 'motion-safe:group-data-[sidebar-transition-ready]/editor-header:transition-[padding-left]',
+ 'motion-safe:transition-[padding-left]',
+ ]);
+ });
+
+ test('keeps every tab kind at the same wider resting width whether active or inactive', async () => {
const { container } = await renderEditorTabs();
const root = container.firstElementChild as HTMLElement;
const wrapper = root.firstElementChild as HTMLElement;
-
- expect(root.getAttribute('data-electron-drag')).toBeNull();
- expectVisualClassTokens(root.className, ['overflow-x-auto', 'scroll-fade-mask-x']);
- expectVisualClassTokensAbsent(root.className, ['[-webkit-app-region:drag]']);
+ const scrollStrip = container.querySelector<HTMLElement>('[data-editor-tab-scroll]');
+ const scrollViewport = scrollStrip?.parentElement;
+ const newTabButton = screen.getByTestId('editor-new-tab-button');
+ const sortableTabs = [...container.querySelectorAll<HTMLElement>('[data-editor-tab-sortable]')];
+
+ expect(root.getAttribute('data-editor-pane-tabs')).toBe('pane-a');
+ expectVisualClassTokens(root.className, ['overflow-hidden']);
+ expect(scrollStrip).toBeTruthy();
+ expectVisualClassTokens(scrollStrip?.className, [
+ 'scrollbar-none',
+ 'overflow-x-auto',
+ 'overflow-y-hidden',
+ 'overscroll-x-contain',
+ 'group-data-[overflow-left]/tab-overflow:mask-l-from-[calc(100%-4rem)]',
+ 'group-data-[overflow-right]/tab-overflow:mask-r-from-[calc(100%-4rem)]',
+ 'w-fit',
+ 'max-w-full',
+ ]);
+ expectVisualClassTokens(scrollViewport?.className, [
+ 'w-fit',
+ 'max-w-[calc(100%-1.75rem)]',
+ 'flex-none',
+ ]);
+ expect(newTabButton.parentElement).toBe(wrapper);
+ expect(wrapper.lastElementChild).toBe(newTabButton);
+ expectVisualClassTokens(wrapper.className, [
+ 'group/tab-overflow',
+ 'relative',
+ 'min-w-0',
+ 'flex-1',
+ ]);
+ expect(container.querySelector('[data-editor-tab-overflow-control]')).toBeNull();
+ expect(container.querySelector('[data-editor-tab-overflow-scrim]')).toBeNull();
+ expect(sortableTabs.map((tab) => tab.dataset.sortableId)).toEqual(visibleTabIds);
+ expect(sortableTabs.some((tab) => tab.dataset.activeTab === 'true')).toBe(true);
+ expect(sortableTabs.some((tab) => tab.dataset.activeTab !== 'true')).toBe(true);
+ for (const tab of sortableTabs) {
+ expectVisualClassTokens(tab.className, [
+ 'min-w-32',
+ 'max-w-48',
+ 'grow-0',
+ 'basis-36',
+ 'shrink',
+ 'outline-none',
+ 'focus-visible:ring-2',
+ 'focus-visible:ring-ring/50',
+ 'focus-visible:ring-inset',
+ ]);
+ expectVisualClassTokensAbsent(tab.className, [
+ 'max-w-40',
+ 'basis-auto',
+ 'basis-28',
+ 'basis-32',
+ 'max-w-80',
+ 'grow-[2]',
+ 'basis-40',
+ 'max-w-56',
+ 'basis-24',
+ 'min-w-28',
+ 'min-w-0',
+ 'shrink-0',
+ 'transition-colors',
+ 'duration-100',
+ ]);
+ }
+ const folderButton = tabButton('docs/team/');
+ expectVisualClassTokens(folderButton.className, ['pl-3', 'pr-1.5']);
+ expectVisualClassTokensAbsent(folderButton.className, ['px-3']);
+ const folderLabel = folderButton.children[0];
+ expect(folderLabel?.children[0]?.textContent).toBe('docs/');
+ expect(folderLabel?.children[1]?.textContent).toBe('team/');
+ expectVisualClassTokens(folderLabel?.className, ['min-w-0', 'flex-1', 'truncate']);
+ expectVisualClassTokens(folderLabel?.children[0]?.className, ['@max-[5rem]/tab:hidden']);
+ expectVisualClassTokensAbsent(folderLabel?.children[0]?.className, ['truncate', 'flex-1']);
+
+ const assetButton = tabButton('images/cat.png');
+ const assetLabel = assetButton.children[0];
+ expect(assetLabel?.children[0]?.textContent).toBe('images/');
+ expect(assetLabel?.children[1]?.textContent).toBe('cat.png');
+ expectVisualClassTokens(assetLabel?.className, ['min-w-0', 'flex-1', 'truncate']);
+ expectVisualClassTokens(assetLabel?.children[0]?.className, ['@max-[5rem]/tab:hidden']);
+ expectVisualClassTokensAbsent(assetLabel?.children[0]?.className, ['truncate', 'flex-1']);
+
+ expectVisualClassTokens(newTabButton.className, ['shrink-0']);
+ expectVisualClassTokensAbsent(root.className, ['[-webkit-app-region:no-drag]']);
expectVisualClassTokensAbsent(wrapper.className, ['[-webkit-app-region:no-drag]']);
});
- test('wires sortable sensors, visible items, drag-end reorder, and the accessibility portal at runtime', async () => {
+ test('does not scroll outer layout when a unified-header tab strip mounts', async () => {
+ const originalScrollIntoView = HTMLElement.prototype.scrollIntoView;
+ const scrollIntoView = vi.fn();
+ HTMLElement.prototype.scrollIntoView = scrollIntoView;
+
+ try {
+ await renderEditorTabs();
+ expect(scrollIntoView).not.toHaveBeenCalled();
+ } finally {
+ HTMLElement.prototype.scrollIntoView = originalScrollIntoView;
+ }
+ });
+
+ test('scrolls a newly selected tab into view without smooth motion', async () => {
+ const originalScrollIntoView = HTMLElement.prototype.scrollIntoView;
+ const scrollIntoView = vi.fn();
+ HTMLElement.prototype.scrollIntoView = scrollIntoView;
+
+ try {
+ const view = await renderEditorTabs();
+ const { EditorTabs } = await import('./EditorTabs');
+
+ activeDocName = 'docs/team/readme';
+ activeTabId = 'docs/team/readme';
+ view.rerender(
+ <TooltipProvider>
+ <EditorTabs paneId="pane-a" />
+ </TooltipProvider>,
+ );
+
+ expect(scrollIntoView).toHaveBeenCalledWith({ block: 'nearest', inline: 'nearest' });
+ } finally {
+ HTMLElement.prototype.scrollIntoView = originalScrollIntoView;
+ }
+ });
+
+ test('maps a vertical wheel gesture to the overflowing tab strip', async () => {
+ const { container } = await renderEditorTabs();
+ const scrollStrip = container.querySelector<HTMLElement>('[data-editor-tab-scroll]');
+ const overflowRoot = container.querySelector<HTMLElement>('[data-editor-tab-overflow-root]');
+ if (!scrollStrip) throw new Error('Expected editor tab scroll strip');
+ if (!overflowRoot) throw new Error('Expected editor tab overflow root');
+ Object.defineProperties(scrollStrip, {
+ clientWidth: { configurable: true, value: 320 },
+ scrollWidth: { configurable: true, value: 800 },
+ });
+
+ fireEvent.scroll(scrollStrip);
+ expect(overflowRoot.hasAttribute('data-overflow-left')).toBe(false);
+ expect(overflowRoot.hasAttribute('data-overflow-right')).toBe(true);
+
+ fireEvent.wheel(scrollStrip, { deltaX: 0, deltaY: 64 });
+
+ expect(scrollStrip.scrollLeft).toBe(64);
+ expect(overflowRoot.hasAttribute('data-overflow-left')).toBe(true);
+ expect(overflowRoot.hasAttribute('data-overflow-right')).toBe(true);
+
+ scrollStrip.scrollLeft = 480;
+ fireEvent.scroll(scrollStrip);
+ expect(overflowRoot.hasAttribute('data-overflow-left')).toBe(true);
+ expect(overflowRoot.hasAttribute('data-overflow-right')).toBe(false);
+ });
+
+ test('double-click and Keep open stabilize preview tabs without changing tab geometry', async () => {
+ previewTabId = 'docs/team/notes';
+ const { container } = await renderEditorTabs();
+
+ const previewButton = tabButton('docs/team/notes.md');
+ const activeButton = tabButton('docs/team/spec.mdx');
+ const previewTab = previewButton.closest<HTMLElement>('[data-editor-tab-sortable]');
+ const activeTab = activeButton.closest<HTMLElement>('[data-editor-tab-sortable]');
+
+ expect(previewTab?.dataset.previewTab).toBe('true');
+ expect(activeTab?.dataset.previewTab).toBeUndefined();
+ expectVisualClassTokens(previewButton.className, ['italic']);
+ expectVisualClassTokensAbsent(previewButton.className, ['font-semibold']);
+ expectVisualClassTokens(activeButton.className, ['font-semibold']);
+ expectVisualClassTokensAbsent(activeButton.className, ['italic']);
+ expect(previewTab?.className).toContain('basis-36');
+ expect(activeTab?.className).toContain('basis-36');
+
+ fireEvent.doubleClick(previewButton);
+ expect(promoteTab).toHaveBeenCalledWith('docs/team/notes');
+
+ promoteTab.mockClear();
+ fireEvent.click(screen.getByTestId('editor-tab-context-keep-open'));
+ expect(promoteTab).toHaveBeenCalledWith('docs/team/notes');
+ expect(container.querySelectorAll('[data-preview-tab="true"]')).toHaveLength(1);
+ });
+
+ test('suppresses the native outline on the mouse-focused tab title', async () => {
await renderEditorTabs();
- expect(sensorCalls).toEqual([
- { sensor: pointerSensorToken, options: { activationConstraint: { distance: 8 } } },
- {
- sensor: keyboardSensorToken,
- options: {
- coordinateGetter: sortableKeyboardCoordinatesToken,
- keyboardCodes: {
- cancel: ['Escape'],
- end: ['Space', 'Enter'],
- start: ['Space'],
- },
- },
- },
+ const titleButton = tabButton('docs/team/spec.mdx');
+ const sortableTab = titleButton.closest<HTMLElement>('[data-editor-tab-sortable]');
+
+ expectVisualClassTokens(titleButton.className, ['outline-none']);
+ expectVisualClassTokens(sortableTab?.className ?? '', [
+ 'focus-visible:ring-2',
+ 'focus-visible:ring-ring/50',
]);
- expect(latestDndContext().accessibility?.container).toBe(document.body);
- expect(latestDndContext().sensors).toEqual(sensorCalls.map((call) => call));
+ });
+
+ test('double-click stabilizes folder and asset tabs', async () => {
+ const { assetId, folderId } = defaultTabs();
+ await renderEditorTabs();
+
+ fireEvent.doubleClick(tabButton('docs/team/'));
+ expect(promoteTab).toHaveBeenCalledWith(folderId);
+
+ promoteTab.mockClear();
+ fireEvent.doubleClick(tabButton('images/cat.png'));
+ expect(promoteTab).toHaveBeenCalledWith(assetId);
+ });
+
+ test('uses one truncation owner for every path-based tab while preserving its full label', async () => {
+ const folderId = folderTabId('wiki/modules');
+ const assetId = assetTabId('images/brand/logo.png');
+ const skillId = skillFileTabId({
+ scope: 'project',
+ name: 'release-notes',
+ path: 'references/publishing.md',
+ });
+ openTabs = [folderId, assetId, skillId];
+ visibleTabIds = [folderId, assetId, skillId];
+ newTabIds = [];
+
+ await renderEditorTabs();
+
+ const pathTabs = [
+ tabButton('wiki/modules/'),
+ tabButton('images/brand/logo.png'),
+ tabButton('references/publishing.md'),
+ ];
+ expect(pathTabs.map((tab) => tab.textContent)).toEqual([
+ 'wiki/modules/',
+ 'images/brand/logo.png',
+ 'references/publishing.md',
+ ]);
+ expect(pathTabs.map((tab) => tab.querySelectorAll('.truncate').length)).toEqual([1, 1, 1]);
+ });
+
+ test('leaves the shared dnd context to the workspace and registers pane-owned sortables', async () => {
+ await renderEditorTabs();
+
+ expect(dndContextProps).toHaveLength(0);
+ expect(sensorCalls).toHaveLength(0);
expect(sortableContextProps.at(-1)).toEqual({
items: visibleTabIds,
strategy: horizontalListSortingStrategyToken,
});
-
- act(() => {
- latestDndContext().onDragEnd?.({
- active: { id: 'docs/team/readme' },
- over: { id: 'docs/team/notes' },
- });
+ expect(sortableOptions[0]?.data).toMatchObject({
+ kind: 'editor-tab',
+ paneId: 'pane-a',
+ tabId: 'docs/team/notes',
+ splittable: true,
+ });
+ expect(sortableOptions.at(-1)?.data).toMatchObject({
+ kind: 'editor-tab',
+ paneId: 'pane-a',
+ tabId: defaultTabs().newId,
+ splittable: true,
});
+ expect(sortableOptions.every((options) => options.transition === null)).toBe(true);
+ expect(sortableOptions.every((options) => options.animateLayoutChanges?.() === false)).toBe(
+ true,
+ );
+ });
- expect(reorderTabs).toHaveBeenCalledWith(
- [
- 'docs/team/readme',
- 'docs/team/notes',
- 'docs/team/spec',
- defaultTabs().folderId,
- defaultTabs().assetId,
- defaultTabs().newId,
- ],
- 'docs/team/readme',
+ test('shows a static primary separator at the requested drop boundary', async () => {
+ const { container } = await renderEditorTabs({ dropIndicatorIndex: 1 });
+
+ const indicators = container.querySelectorAll<HTMLElement>('[data-editor-tab-drop-indicator]');
+ expect(indicators).toHaveLength(1);
+ expect(indicators[0]?.dataset.editorTabDropIndicator).toBe('before');
+ expect(indicators[0]?.closest('[data-editor-tab-id]')?.getAttribute('data-editor-tab-id')).toBe(
+ visibleTabIds[1],
);
+ expectVisualClassTokens(indicators[0]?.className ?? '', [
+ 'bg-primary',
+ 'w-0.5',
+ 'rounded-full',
+ 'left-0',
+ ]);
+ expectVisualClassTokensAbsent(indicators[0]?.className ?? '', ['transition']);
+ });
+
+ test('fades active and hovered inactive tab titles before the close button', async () => {
+ await renderEditorTabs();
+
+ const activeTitle = tabButton('docs/team/spec.mdx').querySelector<HTMLElement>(
+ '[data-editor-tab-title-overflow="fade"]',
+ );
+ expect(activeTitle).not.toBeNull();
+ expectVisualClassTokens(activeTitle?.className ?? '', [
+ 'flex-1',
+ 'overflow-hidden',
+ 'whitespace-nowrap',
+ 'mask-r-from-[calc(100%-1.5rem)]',
+ 'mask-r-to-[100%]',
+ ]);
+ expectVisualClassTokensAbsent(activeTitle?.className ?? '', ['truncate']);
+
+ const inactiveTitle = tabButton('docs/team/notes.md').querySelector<HTMLElement>(
+ '[data-editor-tab-title-overflow="ellipsis"]',
+ );
+ expect(inactiveTitle).not.toBeNull();
+ expectVisualClassTokens(inactiveTitle?.className ?? '', [
+ 'truncate',
+ 'group-hover:text-clip',
+ 'group-hover:mask-r-from-[calc(100%-3rem)]',
+ 'group-hover:mask-r-to-[calc(100%-1.5rem)]',
+ ]);
+ expect(inactiveTitle?.className.split(/\s+/)).not.toContain('mask-r-to-[100%]');
+
+ const inactiveFolderTitle = tabButton('docs/team/').querySelector<HTMLElement>(
+ '[data-editor-tab-title-overflow="ellipsis"]',
+ );
+ expectVisualClassTokens(inactiveFolderTitle?.className ?? '', [
+ 'group-hover:text-clip',
+ 'group-hover:mask-r-from-[calc(100%-3rem)]',
+ 'group-hover:mask-r-to-[calc(100%-1.5rem)]',
+ ]);
+ });
+
+ test('does not fade the fixed new-tab label', async () => {
+ const { newId } = defaultTabs();
+ activeDocName = null;
+ activeTabId = null;
+ activeNewTabId = newId;
+ isNewTabActive = true;
+ await renderEditorTabs();
+
+ const title = screen
+ .getByTestId('editor-new-tab-placeholder-button')
+ .querySelector<HTMLElement>('[data-editor-tab-title-overflow]');
+
+ expect(title?.getAttribute('data-editor-tab-title-overflow')).toBe('ellipsis');
+ expectVisualClassTokens(title?.className ?? '', ['truncate']);
+ expectVisualClassTokensAbsent(title?.className ?? '', [
+ 'mask-r-from-[calc(100%-1.5rem)]',
+ 'mask-r-to-[100%]',
+ 'group-hover:mask-r-from-[calc(100%-3rem)]',
+ 'group-hover:mask-r-to-[100%]',
+ ]);
+ });
+
+ test('preserves a pane-local new-tab interleave', async () => {
+ const { newId, tabs } = defaultTabs();
+ visibleTabIds = [tabs[0], newId, ...tabs.slice(1)];
+
+ await renderEditorTabs();
+
+ expect(sortableContextProps.at(-1)?.items).toEqual(visibleTabIds);
});
test('handles tab keyboard shortcuts for create, navigation, jump, and reopen', async () => {
@@ -590,6 +1164,10 @@ describe('EditorTabs runtime behavior', () => {
expect(
screen.getAllByTestId('editor-tab-shortcut-hint').map((node) => node.textContent),
).toEqual(['⌘1', '⌘2', '⌘3', '⌘4', '⌘5', '⌘6']);
+ for (const hint of screen.getAllByTestId('editor-tab-shortcut-hint')) {
+ expectVisualClassTokens(hint.className, ['mr-1', 'w-fit', 'shrink-0']);
+ expectVisualClassTokensAbsent(hint.className, ['absolute', 'animate-in', 'zoom-in-95']);
+ }
expect(screen.queryByRole('button', { name: 'Close docs/team/notes.md' })).toBeNull();
expect(screen.queryByRole('button', { name: 'Close new tab' })).toBeNull();
@@ -640,6 +1218,48 @@ describe('EditorTabs runtime behavior', () => {
expect(closeNewTab).toHaveBeenCalledWith(newId);
});
+ test('context actions move document, folder, and blank tabs into a new pane', async () => {
+ const { folderId, newId } = defaultTabs();
+ await renderEditorTabs();
+
+ fireEvent.click(screen.getAllByTestId('editor-tab-context-split-left')[0]);
+ expect(moveTabToNewPane).toHaveBeenCalledWith('docs/team/notes', 'left');
+ const announcement = screen.getByTestId('editor-tab-split-announcement');
+ expect(announcement.getAttribute('aria-live')).toBe('polite');
+ expect(announcement.textContent).toBe('Moved docs/team/notes.md to a new pane on the left.');
+
+ fireEvent.click(screen.getAllByTestId('editor-tab-context-split-right')[1]);
+ expect(moveTabToNewPane).toHaveBeenCalledWith('docs/team/spec', 'right');
+ expect(announcement.textContent).toBe('Moved docs/team/spec.mdx to a new pane on the right.');
+
+ const folderTabIndex = visibleTabIds.indexOf(folderId);
+ fireEvent.click(screen.getAllByTestId('editor-tab-context-split-left')[folderTabIndex]);
+ expect(moveTabToNewPane).toHaveBeenCalledWith(folderId, 'left');
+
+ const blankTabIndex = visibleTabIds.indexOf(newId);
+ fireEvent.click(screen.getAllByTestId('editor-tab-context-split-right')[blankTabIndex]);
+ expect(moveTabToNewPane).toHaveBeenCalledWith(newId, 'right');
+ });
+
+ test('disables move-to-pane actions when the pane has only one tab', async () => {
+ activeDocName = 'docs/team/notes';
+ activeTabId = 'docs/team/notes';
+ openTabs = ['docs/team/notes'];
+ visibleTabIds = ['docs/team/notes'];
+ newTabIds = [];
+ await renderEditorTabs();
+
+ const moveLeft = screen.getByTestId('editor-tab-context-split-left') as HTMLButtonElement;
+ const moveRight = screen.getByTestId('editor-tab-context-split-right') as HTMLButtonElement;
+
+ expect(moveLeft.disabled).toBe(true);
+ expect(moveRight.disabled).toBe(true);
+
+ fireEvent.click(moveLeft);
+ fireEvent.click(moveRight);
+ expect(moveTabToNewPane).not.toHaveBeenCalled();
+ });
+
test('pin state changes close controls, menu actions, and middle-click behavior', async () => {
pinnedTabIds = ['docs/team/readme'];
await renderEditorTabs();
@@ -667,95 +1287,6 @@ describe('EditorTabs runtime behavior', () => {
expect(closeTab).not.toHaveBeenCalledWith('docs/team/readme');
});
- test('rename mode strips the file extension, disables sorting, reports invalid input, and keeps the extension addon', async () => {
- await renderEditorTabs();
-
- fireEvent.doubleClick(tabButton('docs/team/readme.txt'));
-
- const input = screen.getByTestId('editor-tab-rename-input') as HTMLInputElement;
- expect(input.value).toBe('readme');
- expect(screen.getByText('.txt')).toBeTruthy();
- expect(
- sortableOptions.some((options) => options.id === 'docs/team/readme' && options.disabled),
- ).toBe(true);
-
- fireEvent.change(input, { target: { value: 'bad/name.txt' } });
- expect(input.value).toBe('bad/name');
- fireEvent.keyDown(input, { key: 'Enter' });
-
- expect((await screen.findByRole('alert')).textContent).toBe(
- 'Name can’t be empty, ".", "..", or contain / or \\',
- );
- expect(globalThis.fetch).not.toHaveBeenCalled();
- });
-
- test('passes the successful response mapping to reconciliation before navigating', async () => {
- activeDocName = 'docs/team/readme';
- activeTabId = 'docs/team/readme';
- reconcileLocalRename.mockImplementation((input) => {
- expect(input).toEqual({
- renamed: [{ fromDocName: 'docs/team/readme', toDocName: 'docs/team/renamed' }],
- });
- expect(window.location.hash).toBe('');
- return Promise.resolve();
- });
- globalThis.fetch = vi.fn(() =>
- Promise.resolve(
- new Response(
- JSON.stringify({
- renamed: [{ fromDocName: 'docs/team/readme', toDocName: 'docs/team/renamed' }],
- renamedAssets: [],
- }),
- { headers: { 'Content-Type': 'application/json' }, status: 200 },
- ),
- ),
- ) as never;
-
- await renderEditorTabs();
- fireEvent.doubleClick(tabButton('docs/team/readme.txt'));
- const input = screen.getByTestId('editor-tab-rename-input') as HTMLInputElement;
- fireEvent.change(input, { target: { value: 'renamed.txt' } });
- fireEvent.keyDown(input, { key: 'Enter' });
-
- await waitFor(() => {
- expect(reconcileLocalRename).toHaveBeenCalledTimes(1);
- expect(window.location.hash).toBe('#/docs/team/renamed');
- });
- });
-
- test('rename post-commit reconciliation failures surface the refresh toast and skip navigation', async () => {
- activeDocName = 'docs/team/readme';
- activeTabId = 'docs/team/readme';
- reconcileLocalRename.mockImplementation(() => Promise.reject(new Error('idb clear failed')));
- globalThis.fetch = vi.fn(() =>
- Promise.resolve(
- new Response(
- JSON.stringify({
- renamed: [{ fromDocName: 'docs/team/readme', toDocName: 'docs/team/renamed' }],
- }),
- { headers: { 'Content-Type': 'application/json' }, status: 200 },
- ),
- ),
- ) as never;
-
- await renderEditorTabs();
- fireEvent.doubleClick(tabButton('docs/team/readme.txt'));
- const input = screen.getByTestId('editor-tab-rename-input') as HTMLInputElement;
- fireEvent.change(input, { target: { value: 'renamed.txt' } });
- fireEvent.keyDown(input, { key: 'Enter' });
-
- await waitFor(() => {
- expect(globalThis.fetch).toHaveBeenCalledTimes(1);
- });
- await waitFor(() => {
- expect(toastErrors).toContain(
- 'Rename succeeded but the tabstrip may be out of date — refresh to resync',
- );
- });
- expect(toastErrors).not.toContain('Network error — please try again');
- expect(window.location.hash).toBe('');
- });
-
test('tab context menus and active tab styling are visible behavior, not source-shape details', async () => {
lifecycleStatuses.set('docs/team/notes', 'conflict');
await renderEditorTabs();
@@ -764,6 +1295,7 @@ describe('EditorTabs runtime behavior', () => {
name: 'docs/team/notes.md (conflict)',
});
expect(conflictedTabButton).toBeTruthy();
+ expect(conflictedTabButton.getAttribute('title')).toBeNull();
// A conflict is the one case where the tooltip carries state beyond the
// path, so pin that it tracks the label rather than just the path.
fireEvent.pointerEnter(conflictedTabButton, { pointerType: 'mouse' });
@@ -773,11 +1305,12 @@ describe('EditorTabs runtime behavior', () => {
'true',
);
expect(screen.getAllByRole('menuitem', { name: 'Close' }).length).toBeGreaterThan(0);
- expect(screen.getAllByRole('menuitem', { name: 'Close others' }).length).toBeGreaterThan(0);
+ const closeOthersItems = screen.getAllByRole('menuitem', { name: 'Close others' });
+ expect(closeOthersItems.length).toBeGreaterThan(0);
+ expect(closeOthersItems[0]?.querySelector('svg.lucide-copy-x')).not.toBeNull();
expect(screen.getAllByRole('menuitem', { name: 'Close all' }).length).toBeGreaterThan(0);
expect(screen.getAllByRole('menuitem', { name: 'Pin tab' }).length).toBeGreaterThan(0);
expect(screen.getAllByTestId('context-menu-separator').length).toBeGreaterThan(0);
-
const activeSortable = screen
.getAllByRole('button', { name: 'docs/team/spec.mdx' })
.find((element) => element.tagName === 'BUTTON')
@@ -793,7 +1326,12 @@ describe('EditorTabs runtime behavior', () => {
const inactiveClose = within(
conflictedTabButton.closest('[data-sortable-id]') as HTMLElement,
).getByRole('button', { name: 'Close docs/team/notes.md' });
- expectVisualClassTokens(inactiveClose.className, ['mr-1.5']);
+ expectVisualClassTokens(inactiveClose.className, ['absolute', 'right-1']);
+ expectVisualClassTokensAbsent(inactiveClose.className, [
+ 'bg-background/80',
+ 'backdrop-blur-sm',
+ ]);
+ expectVisualClassTokensAbsent(inactiveClose.className, ['mr-1']);
const placeholderClose = screen.getByTestId('editor-new-tab-placeholder-close');
expectVisualClassTokens(placeholderClose.className, [
diff --git a/packages/app/src/components/EditorTabs.tsx b/packages/app/src/components/EditorTabs.tsx
index 91d10b52c..11a91cae9 100644
--- a/packages/app/src/components/EditorTabs.tsx
+++ b/packages/app/src/components/EditorTabs.tsx
@@ -1,119 +1,106 @@
// biome-ignore-all lint/plugin/no-raw-html-interactive-element: pre-rule backlog — file uses raw <button>/<input>/<textarea> awaiting shadcn migration; tracked at https://github.com/inkeep/open-knowledge/blob/main/biome-plugins/README.md#no-raw-html-interactive-elementgrit
-import {
- DndContext,
- type DragEndEvent,
- KeyboardSensor,
- PointerSensor,
- useDndContext,
- useSensor,
- useSensors,
-} from '@dnd-kit/core';
-import {
- arrayMove,
- horizontalListSortingStrategy,
- SortableContext,
- sortableKeyboardCoordinates,
- useSortable,
-} from '@dnd-kit/sortable';
-import { RenamePathSuccessSchema } from '@inkeep/open-knowledge-core';
+import { useDndContext } from '@dnd-kit/core';
+import { horizontalListSortingStrategy, SortableContext, useSortable } from '@dnd-kit/sortable';
import { Trans, useLingui } from '@lingui/react/macro';
-import { AlertTriangle, PinIcon, PlusIcon, XIcon } from 'lucide-react';
+import {
+ AlertTriangle,
+ CopyX,
+ PanelLeft,
+ PanelRight,
+ PinIcon,
+ PlusIcon,
+ Trash2,
+ XIcon,
+} from 'lucide-react';
import {
type HTMLAttributes,
type KeyboardEvent,
type ReactNode,
type Ref,
useEffect,
+ useLayoutEffect,
useRef,
useState,
} from 'react';
-import { toast } from 'sonner';
import {
- buildRenamedNodePath,
- isValidNodeName,
- normalizeRenameValue,
- remapActiveDocName,
-} from '@/components/file-tree-operations';
+ type EditorTabFileTarget,
+ EditorTabTargetMenuItems,
+} from '@/components/EditorTabTargetMenuItems';
+import { FileTargetRenameDialog } from '@/components/FileTargetRenameDialog';
+import {
+ SkillContextMenuItems,
+ SkillFileContextMenuItems,
+ useSkillActions,
+} from '@/components/skill-actions';
import { Button } from '@/components/ui/button';
import {
ContextMenu,
ContextMenuContent,
+ ContextMenuGroup,
ContextMenuItem,
ContextMenuSeparator,
ContextMenuTrigger,
} from '@/components/ui/context-menu';
-import {
- InputGroup,
- InputGroupAddon,
- InputGroupInput,
- InputGroupText,
-} from '@/components/ui/input-group';
import { Kbd } from '@/components/ui/kbd';
import { useDocumentContext } from '@/editor/DocumentContext';
import {
- docTabId,
filterClosableTabIds,
+ isSkillBundleShapedPath,
+ isSkillDocName,
parseEditorTabId,
tabIdForNavigationTarget,
tabParts,
} from '@/editor/editor-tabs';
import { useLifecycleStatus } from '@/hooks/use-lifecycle-status';
-import { hashFromDocName } from '@/lib/doc-hash';
-import { emitDocumentsChanged } from '@/lib/documents-events';
+import { useSkills } from '@/hooks/use-skills';
+import { emitFileTreeMenuActionRename } from '@/lib/file-tree-menu-action-events';
import { matchesKeyboardShortcut } from '@/lib/keyboard-shortcuts';
+import { skillEntryLiveDocName } from '@/lib/managed-artifact-doc-name';
import { isOverlayLayerOpen } from '@/lib/overlay-layers';
-import { parseServerResponse, parseSuccessOrWarn } from '@/lib/parse-server-response';
import { cn } from '@/lib/utils';
import {
- createTabReorderModifier,
+ type EditorTabDragData,
+ findEditorTabElement,
getSortableTabClassName,
getSortableTabKeyDownAction,
getSortableTabStyle,
getTabCloseButtonClass,
getTabCloseButtonTabIndex,
- measureTabReorderBounds,
- TAB_KEYBOARD_DRAG_CODES,
- TAB_REORDER_AUTO_SCROLL,
- type TabReorderBounds,
- tabRunCollisionDetection,
+ shouldOpenTabContextMenu,
} from './editor-tabs-chrome';
import { usePageList } from './PageListContext';
import { scrollTabStripOnWheel } from './tab-strip-wheel';
import { Tooltip, TooltipContent, TooltipTrigger } from './ui/tooltip';
-const TAB_RENAME_EXTENSIONS = ['.md', '.mdx'] as const;
const TAB_BASE_CLASS =
- 'group relative -mb-px flex h-10 min-w-28 max-w-64 shrink-0 cursor-pointer items-center overflow-hidden border border-transparent font-medium transition-colors';
+ 'group @container/tab relative -mb-px flex h-10 min-w-32 max-w-48 grow-0 basis-36 shrink cursor-grab items-center overflow-hidden border border-transparent font-medium outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-inset active:cursor-grabbing';
const TAB_ACTIVE_CLASS =
'z-10 rounded-t-lg rounded-b-none border-border border-b-0 bg-background text-foreground';
-const TAB_INACTIVE_CLASS = cn(
- TAB_ACTIVE_CLASS,
- 'bg-transparent hover:bg-muted focus-visible:bg-muted border-transparent hover:border-border focus-visible:border-border',
-);
+const TAB_INACTIVE_CLASS =
+ 'rounded-t-md text-muted-foreground hover:border-border/70 hover:bg-muted/60 hover:text-foreground focus-visible:border-border focus-visible:bg-muted focus-visible:text-foreground';
const TAB_BUTTON_CLASS =
- 'flex h-full min-w-0 flex-1 cursor-pointer items-center overflow-hidden px-3 text-left text-[13px]';
+ 'flex h-full min-w-0 flex-1 cursor-pointer items-center overflow-hidden pl-3 pr-1.5 text-left text-[13px] outline-none @max-[5rem]/tab:pl-2';
-function tabDomIdPart(docName: string): string {
- return docName.replace(/[^A-Za-z0-9_-]/g, '-');
+function tabTitleClassName(isFocusedActive: boolean, isPreview: boolean): string {
+ return cn(TAB_BUTTON_CLASS, isFocusedActive && 'font-semibold', isPreview && 'italic');
}
-function navigateToDoc(docName: string) {
- const nextHash = hashFromDocName(docName);
- if (window.location.hash !== nextHash) {
- window.location.hash = nextHash;
- }
+function tabTitleOverflowClassName(isActive: boolean): string {
+ return isActive
+ ? 'overflow-hidden whitespace-nowrap mask-r-from-[calc(100%-1.5rem)] mask-r-to-[100%]'
+ : 'truncate group-hover:text-clip group-hover:mask-r-from-[calc(100%-3rem)] group-hover:mask-r-to-[calc(100%-1.5rem)]';
}
-function stripRenameExtensionSuffix(value: string, docExt: string): string {
- const extensions = [docExt, ...TAB_RENAME_EXTENSIONS].filter(
- (ext, index, all) => ext && all.indexOf(ext) === index,
- );
- const lowerValue = value.toLowerCase();
- const extension = extensions.find(
- (ext) => value.length > ext.length && lowerValue.endsWith(ext.toLowerCase()),
+function syncTabOverflowIndicators(scrollContainer: HTMLElement): void {
+ const overflowRoot = scrollContainer.closest<HTMLElement>('[data-editor-tab-overflow-root]');
+ if (!overflowRoot) return;
+ const maxScrollLeft = Math.max(0, scrollContainer.scrollWidth - scrollContainer.clientWidth);
+ overflowRoot.toggleAttribute('data-overflow-left', scrollContainer.scrollLeft > 1);
+ overflowRoot.toggleAttribute(
+ 'data-overflow-right',
+ scrollContainer.scrollLeft < maxScrollLeft - 1,
);
- return extension ? value.slice(0, -extension.length) : value;
}
function hasTabShortcutModifier(event: globalThis.KeyboardEvent): boolean {
@@ -121,6 +108,7 @@ function hasTabShortcutModifier(event: globalThis.KeyboardEvent): boolean {
}
const TAB_SHORTCUT_HINT_DELAY_MS = 1000;
+const EMPTY_SKILL_NAME_SET: ReadonlySet<string> = new Set();
function shortcutDigitForIndex(index: number, tabCount: number): string | null {
if (index < 0 || index >= tabCount) return null;
@@ -128,10 +116,6 @@ function shortcutDigitForIndex(index: number, tabCount: number): string | null {
return index === tabCount - 1 ? '9' : null;
}
-function tabShortcutHintForIndex(index: number, tabCount: number): string | null {
- return shortcutDigitForIndex(index, tabCount);
-}
-
function tabAriaKeyShortcutsForIndex(index: number, tabCount: number): string | undefined {
const shortcutDigit = shortcutDigitForIndex(index, tabCount);
if (!shortcutDigit) return undefined;
@@ -155,12 +139,9 @@ function TabShortcutHint({ value }: { value: string }) {
<span
aria-hidden="true"
data-testid="editor-tab-shortcut-hint"
- className={cn(
- getTabCloseButtonClass(true),
- 'font-mono tabular-nums hover:bg-transparent animate-in fade-in-0 zoom-in-95 duration-150 motion-reduce:animate-none motion-reduce:duration-0',
- )}
+ className="mr-1 flex h-5 w-fit shrink-0 items-center justify-center font-mono tabular-nums @max-[5rem]/tab:hidden"
>
- <Kbd className="text-[10px]">{`⌘${value}`}</Kbd>
+ <Kbd className="px-0.5 text-[10px]">{`⌘${value}`}</Kbd>
</span>
);
}
@@ -169,9 +150,7 @@ function TabShortcutHint({ value }: { value: string }) {
* Sortable wrapper for one tab div, bound to `@dnd-kit/sortable`'s
* `useSortable` so the whole tab (not a separate drag handle) is draggable.
* Activation is gated by the outer DndContext's PointerSensor `distance: 8`
- * so plain clicks still activate / close the tab. While renaming, `disabled`
- * short-circuits the sortable bindings — the inline input keeps full
- * pointer/keyboard affordance and the tab stays in place.
+ * so plain clicks still activate / close the tab.
*
* Callers should not pass a `role` prop. `useSortable`'s `attributes` inject
* `role="button"` + `aria-roledescription="sortable"` so screen readers can
@@ -184,26 +163,42 @@ function TabShortcutHint({ value }: { value: string }) {
*/
function SortableTab({
activateFromKeyboard,
+ children,
className,
+ dropIndicatorSide,
+ label,
+ paneId,
+ splittable,
tabId,
- disabled,
onKeyDown,
ref: outerRef,
style: outerStyle,
...rest
}: {
activateFromKeyboard?: () => void;
+ dropIndicatorSide?: 'before' | 'after';
+ label: string;
+ paneId: string;
+ splittable: boolean;
tabId: string;
- disabled?: boolean;
ref?: Ref<HTMLDivElement>;
} & HTMLAttributes<HTMLDivElement>) {
const { attributes, listeners, rect, setNodeRef, transform, transition, isDragging } =
useSortable({
+ animateLayoutChanges: () => false,
id: tabId,
- disabled,
+ data: {
+ kind: 'editor-tab',
+ paneId,
+ tabId,
+ splittable,
+ label,
+ } satisfies EditorTabDragData,
+ transition: null,
});
const style = getSortableTabStyle({
activeWidth: rect.current?.width,
+ disableMovement: true,
isDragging,
outerStyle,
transform,
@@ -220,6 +215,20 @@ function SortableTab({
const sortableKeyDown = listeners?.onKeyDown;
function handleKeyDown(event: KeyboardEvent<HTMLDivElement>) {
onKeyDown?.(event);
+ if (!event.defaultPrevented && shouldOpenTabContextMenu(event)) {
+ event.preventDefault();
+ const rect = event.currentTarget.getBoundingClientRect();
+ event.currentTarget.dispatchEvent(
+ new MouseEvent('contextmenu', {
+ bubbles: true,
+ cancelable: true,
+ clientX: rect.left + Math.min(rect.width / 2, 16),
+ clientY: rect.top + rect.height / 2,
+ view: window,
+ }),
+ );
+ return;
+ }
const action = getSortableTabKeyDownAction({
event,
hasKeyboardActivation: Boolean(activateFromKeyboard),
@@ -238,85 +247,175 @@ function SortableTab({
<div
ref={composedRef}
data-editor-tab-sortable=""
+ data-editor-pane-id={paneId}
+ data-editor-tab-id={tabId}
className={getSortableTabClassName({ className, isDragging })}
style={style}
{...rest}
{...attributes}
{...listeners}
onKeyDown={handleKeyDown}
- />
+ >
+ {children}
+ {dropIndicatorSide ? (
+ <span
+ aria-hidden="true"
+ data-editor-tab-drop-indicator={dropIndicatorSide}
+ className={cn(
+ 'pointer-events-none absolute inset-y-1 z-30 w-0.5 rounded-full bg-primary',
+ dropIndicatorSide === 'before' ? 'left-0' : 'right-0',
+ )}
+ />
+ ) : null}
+ </div>
);
}
function EditorTabContextMenu({
+ canSplit = true,
children,
closeTab,
closeTabs,
canPin = true,
- disabled = false,
+ docExt,
+ isPreview = false,
openTabs,
pinTab,
pinnedTabIds,
+ promoteTab,
+ splitTab,
+ skillMenuItems,
+ tabLabel,
tabId,
+ target,
+ renameName,
unpinTab,
}: {
children: ReactNode;
canPin?: boolean;
+ canSplit?: boolean;
+ docExt?: string;
closeTab: (tabId: string) => void;
closeTabs: (tabIds: readonly string[]) => void;
- disabled?: boolean;
+ isPreview?: boolean;
openTabs: readonly string[];
pinTab: (tabId: string) => void;
pinnedTabIds: readonly string[];
+ promoteTab: (tabId: string) => void;
+ splitTab: (tabId: string, side: 'left' | 'right', label: string) => void;
+ skillMenuItems?: ReactNode;
+ tabLabel: string;
tabId: string;
+ target?: EditorTabFileTarget;
+ renameName?: string;
unpinTab: (tabId: string) => void;
}) {
- if (disabled) return children;
-
+ const [renameOpen, setRenameOpen] = useState(false);
const isPinned = canPin && pinnedTabIds.includes(tabId);
const otherTabIds = filterClosableTabIds(
openTabs.filter((openTabId) => openTabId !== tabId),
pinnedTabIds,
);
const closableTabIds = filterClosableTabIds(openTabs, pinnedTabIds);
+ const canMoveToNewPane = canSplit && openTabs.length > 1;
return (
- <ContextMenu>
- <ContextMenuTrigger asChild>{children}</ContextMenuTrigger>
- <ContextMenuContent className="min-w-40">
- <ContextMenuItem disabled={isPinned} onSelect={() => closeTab(tabId)}>
- <Trans>Close</Trans>
- </ContextMenuItem>
- <ContextMenuItem
- disabled={otherTabIds.length === 0}
- onSelect={() => {
- closeTabs(otherTabIds);
- }}
- >
- <Trans>Close others</Trans>
- </ContextMenuItem>
- <ContextMenuItem
- disabled={closableTabIds.length === 0}
- data-testid="editor-tab-context-close-all"
- onSelect={() => {
- closeTabs(closableTabIds);
- }}
- >
- {pinnedTabIds.length ? <Trans>Close all unpinned</Trans> : <Trans>Close all</Trans>}
- </ContextMenuItem>
- {canPin && (
- <>
- <ContextMenuSeparator />
+ <>
+ <ContextMenu>
+ <ContextMenuTrigger asChild>{children}</ContextMenuTrigger>
+ <ContextMenuContent className="min-w-56">
+ <ContextMenuGroup>
+ <ContextMenuItem disabled={isPinned} onSelect={() => closeTab(tabId)}>
+ <XIcon aria-hidden="true" />
+ <Trans>Close</Trans>
+ </ContextMenuItem>
<ContextMenuItem
- data-testid="editor-tab-context-pin-toggle"
- onSelect={() => (isPinned ? unpinTab(tabId) : pinTab(tabId))}
+ disabled={otherTabIds.length === 0}
+ onSelect={() => {
+ closeTabs(otherTabIds);
+ }}
>
- {isPinned ? <Trans>Unpin tab</Trans> : <Trans>Pin tab</Trans>}
+ <CopyX aria-hidden="true" />
+ <Trans>Close others</Trans>
</ContextMenuItem>
- </>
- )}
- </ContextMenuContent>
- </ContextMenu>
+ <ContextMenuItem
+ disabled={closableTabIds.length === 0}
+ data-testid="editor-tab-context-close-all"
+ onSelect={() => {
+ closeTabs(closableTabIds);
+ }}
+ >
+ <Trash2 aria-hidden="true" />
+ {pinnedTabIds.length ? <Trans>Close all unpinned</Trans> : <Trans>Close all</Trans>}
+ </ContextMenuItem>
+ </ContextMenuGroup>
+ {target || skillMenuItems ? (
+ <>
+ <ContextMenuSeparator />
+ {target ? (
+ <EditorTabTargetMenuItems
+ docExt={docExt}
+ target={target}
+ onRename={() => setRenameOpen(true)}
+ />
+ ) : null}
+ {skillMenuItems}
+ </>
+ ) : null}
+ {isPreview && (
+ <>
+ <ContextMenuSeparator />
+ <ContextMenuItem
+ data-testid="editor-tab-context-keep-open"
+ onSelect={() => promoteTab(tabId)}
+ >
+ <PinIcon aria-hidden="true" />
+ <Trans>Keep open</Trans>
+ </ContextMenuItem>
+ </>
+ )}
+ {canPin && (
+ <>
+ <ContextMenuSeparator />
+ <ContextMenuItem
+ data-testid="editor-tab-context-pin-toggle"
+ onSelect={() => (isPinned ? unpinTab(tabId) : pinTab(tabId))}
+ >
+ <PinIcon aria-hidden="true" />
+ {isPinned ? <Trans>Unpin tab</Trans> : <Trans>Pin tab</Trans>}
+ </ContextMenuItem>
+ </>
+ )}
+ <ContextMenuSeparator />
+ <ContextMenuGroup>
+ <ContextMenuItem
+ disabled={!canMoveToNewPane}
+ data-testid="editor-tab-context-split-left"
+ onSelect={() => splitTab(tabId, 'left', tabLabel)}
+ >
+ <PanelLeft aria-hidden="true" />
+ <Trans>Move to new pane left</Trans>
+ </ContextMenuItem>
+ <ContextMenuItem
+ disabled={!canMoveToNewPane}
+ data-testid="editor-tab-context-split-right"
+ onSelect={() => splitTab(tabId, 'right', tabLabel)}
+ >
+ <PanelRight aria-hidden="true" />
+ <Trans>Move to new pane right</Trans>
+ </ContextMenuItem>
+ </ContextMenuGroup>
+ </ContextMenuContent>
+ </ContextMenu>
+ {renameOpen && target && renameName ? (
+ <FileTargetRenameDialog
+ currentName={renameName}
+ open
+ onOpenChange={setRenameOpen}
+ onSave={(nextName) => emitFileTreeMenuActionRename(target, nextName)}
+ />
+ ) : null}
+ </>
);
}
@@ -383,21 +482,9 @@ function TabPinOrCloseButton({
}
/**
- * Full-path hover disclosure for a tab whose visible label is only the base
- * name — two `SPEC.md` tabs from different folders are otherwise
- * indistinguishable. Supersedes the native `title` attribute, which carried
- * the same string but renders OS-styled after the platform's own ~1s delay;
- * keeping both would stack a second tooltip under the first.
- *
- * Shown even where the label already reads as the whole name. Tabs cap at
- * `max-w-64` and truncate, so a long enough name is clipped whether or not a
- * folder prefix precedes it, and that clipped case is exactly where the
- * disclosure earns its keep. Suppressing the apparent echo would drop it.
- * Same reasoning as the terminal tab strip and the footer project path.
- *
- * Anchored to the inner label button, not the outer sortable tab, because
- * `SortableTab` spreads dnd-kit's `listeners` after `rest` — pointer handlers
- * a trigger injected there would be silently overwritten.
+ * Full-path hover disclosure for labels that may be visually truncated.
+ * Anchoring to the inner button avoids dnd-kit's sortable listeners replacing
+ * the tooltip trigger's pointer handlers on the outer tab.
*/
function TabPathTooltip({ children, path }: { children: ReactNode; path: string }) {
// A reorder drag keeps firing pointermove over the trigger, which re-opens
@@ -433,18 +520,24 @@ function DocumentTabButton({
activateTab,
baseName,
docName,
- enterRenameMode,
extension,
hideDocExtension,
+ isActive,
+ isFocusedPane,
+ isPreview,
+ promoteTab,
tabId,
}: {
accessibleLabel: string;
activateTab: (tabId: string) => void;
baseName: string;
docName: string;
- enterRenameMode: (tabId: string, docName: string) => void;
extension: string;
hideDocExtension: boolean;
+ isActive: boolean;
+ isFocusedPane: boolean;
+ isPreview: boolean;
+ promoteTab: (tabId: string) => void;
tabId: string;
}) {
const { t } = useLingui();
@@ -457,20 +550,25 @@ function DocumentTabButton({
<button
type="button"
aria-label={buttonAccessibleLabel}
- className={TAB_BUTTON_CLASS}
+ className={tabTitleClassName(isActive && isFocusedPane, isPreview)}
onClick={() => {
activateTab(tabId);
}}
onDoubleClick={(event) => {
event.preventDefault();
event.stopPropagation();
- enterRenameMode(tabId, docName);
+ promoteTab(tabId);
}}
tabIndex={-1}
>
<TabConflictBadge hasConflict={hasConflict} />
<span className="flex min-w-0 flex-1 items-center">
- <span className="min-w-0 truncate">{baseName}</span>
+ <span
+ data-editor-tab-title-overflow={isActive ? 'fade' : 'ellipsis'}
+ className={cn('min-w-0 flex-1', tabTitleOverflowClassName(isActive))}
+ >
+ {baseName}
+ </span>
{!hideDocExtension && <span className="shrink-0">{extension}</span>}
</span>
</button>
@@ -478,62 +576,204 @@ function DocumentTabButton({
);
}
-export function EditorTabs() {
- const {
- activeDocName,
- activeTabId: activeContextTabId,
- activeNewTabId,
- activeTarget,
- activateTab,
- activateNewTab,
- closeNewTab,
- closeTab,
- closeTabs,
- isNewTabActive,
- newTabIds,
- openNewTab,
- openTabs,
- pinTab,
- pinnedTabIds,
- reopenClosedTab,
- reconcileLocalRename,
- reorderTabs,
- unpinTab,
- visibleTabIds,
- } = useDocumentContext();
+interface EditorTabFrameProps {
+ accessibleLabel: string;
+ activateTab: (tabId: string) => void;
+ ariaKeyShortcuts?: string;
+ children: ReactNode;
+ closeTab: (tabId: string) => void;
+ closeTabs: (tabIds: readonly string[]) => void;
+ docExt?: string;
+ dropIndicatorSide?: 'before' | 'after';
+ forceCloseVisible: boolean;
+ isActive: boolean;
+ isPinned: boolean;
+ isPreview: boolean;
+ openTabs: readonly string[];
+ paneId: string;
+ pinTab: (tabId: string) => void;
+ pinnedTabIds: readonly string[];
+ promoteTab: (tabId: string) => void;
+ renameName?: string;
+ shortcutHint: string | null;
+ splitTab: (tabId: string, side: 'left' | 'right', label: string) => void;
+ skillMenuItems?: ReactNode;
+ tabId: string;
+ target?: EditorTabFileTarget;
+ unpinTab: (tabId: string) => void;
+}
+
+function EditorTabFrame({
+ accessibleLabel,
+ activateTab,
+ ariaKeyShortcuts,
+ children,
+ closeTab,
+ closeTabs,
+ docExt,
+ dropIndicatorSide,
+ forceCloseVisible,
+ isActive,
+ isPinned,
+ isPreview,
+ openTabs,
+ paneId,
+ pinTab,
+ pinnedTabIds,
+ promoteTab,
+ renameName,
+ shortcutHint,
+ splitTab,
+ skillMenuItems,
+ tabId,
+ target,
+ unpinTab,
+}: EditorTabFrameProps) {
+ return (
+ <EditorTabContextMenu
+ tabId={tabId}
+ docExt={docExt}
+ target={target}
+ renameName={renameName}
+ openTabs={openTabs}
+ closeTab={closeTab}
+ closeTabs={closeTabs}
+ isPreview={isPreview}
+ pinTab={pinTab}
+ pinnedTabIds={pinnedTabIds}
+ promoteTab={promoteTab}
+ splitTab={splitTab}
+ skillMenuItems={skillMenuItems}
+ tabLabel={accessibleLabel}
+ unpinTab={unpinTab}
+ >
+ <SortableTab
+ dropIndicatorSide={dropIndicatorSide}
+ label={accessibleLabel}
+ paneId={paneId}
+ splittable
+ tabId={tabId}
+ activateFromKeyboard={() => activateTab(tabId)}
+ aria-current={isActive ? 'page' : undefined}
+ aria-keyshortcuts={ariaKeyShortcuts}
+ data-active-tab={isActive ? 'true' : undefined}
+ data-preview-tab={isPreview ? 'true' : undefined}
+ className={cn(TAB_BASE_CLASS, isActive ? TAB_ACTIVE_CLASS : TAB_INACTIVE_CLASS)}
+ onAuxClick={(event) => {
+ if (event.button !== 1) return;
+ event.preventDefault();
+ if (!isPinned) closeTab(tabId);
+ }}
+ onClick={(event) => {
+ if (event.target === event.currentTarget) activateTab(tabId);
+ }}
+ >
+ {children}
+ <TabPinOrCloseButton
+ accessibleLabel={accessibleLabel}
+ closeTab={closeTab}
+ forceCloseVisible={forceCloseVisible}
+ isActive={isActive}
+ isPinned={isPinned}
+ shortcutHint={shortcutHint}
+ tabId={tabId}
+ unpinTab={unpinTab}
+ />
+ </SortableTab>
+ </EditorTabContextMenu>
+ );
+}
+
+interface EditorTabsProps {
+ dropIndicatorIndex?: number | null;
+ paneId: string;
+ onSplitComplete?: (paneId: string, tabId: string) => void;
+ reserveLeadingChrome?: boolean;
+ reserveTrailingChrome?: boolean;
+}
+
+export function EditorTabs({
+ dropIndicatorIndex = null,
+ paneId,
+ onSplitComplete,
+ reserveLeadingChrome = false,
+ reserveTrailingChrome = false,
+}: EditorTabsProps) {
const { t } = useLingui();
+ const context = useDocumentContext();
+ const { reopenClosedTab } = context;
+ const pane = context.panes.find((candidate) => candidate.id === paneId) ?? context.panes[0];
+ const resolvedPaneId = pane?.id ?? paneId;
+ const openTabs = pane?.openTabs ?? [];
+ const pinnedTabIds = pane?.pinnedTabIds ?? [];
+ const previewTabId = pane?.previewTabId ?? null;
+ const newTabIds = pane?.newTabIds ?? [];
+ const visibleTabIds = context.visibleTabIdsByPane.get(resolvedPaneId) ?? [
+ ...openTabs,
+ ...newTabIds,
+ ];
+ const activeTarget = pane?.activeTarget ?? null;
+ const activeContextTabId = pane?.activeTabId ?? null;
+ const activeNewTabId = pane?.activeNewTabId ?? null;
+ const isNewTabActive = activeNewTabId !== null;
+ const isFocusedPane = context.focusedPaneId === resolvedPaneId;
+ const hasSkillTab = visibleTabIds.some((tabId) => {
+ const tab = parseEditorTabId(tabId);
+ return tab.kind === 'skill-file' || (tab.kind === 'doc' && isSkillDocName(tab.docName));
+ });
+ const skillsState = useSkills({ enabled: hasSkillTab });
+ const skillActions = useSkillActions();
+ const editableSkills =
+ skillsState.status === 'ready' ? skillsState.data.filter((skill) => !skill.managed) : [];
+ const editableSkillsByTabId = new Map(
+ editableSkills.map((skill) => [skillEntryLiveDocName(skill), skill] as const),
+ );
+ const skillNamesByScope = new Map(
+ (['project', 'global'] as const).map((scope) => [
+ scope,
+ new Set(
+ skillsState.status === 'ready'
+ ? skillsState.data.filter((skill) => skill.scope === scope).map((skill) => skill.name)
+ : [],
+ ),
+ ]),
+ );
+ const activateTab = (tabId: string) => context.activateTabInPane(resolvedPaneId, tabId);
+ const activateNewTab = (tabId: string) => context.activateNewTabInPane(resolvedPaneId, tabId);
+ const closeTab = (tabId: string) => context.closeTabInPane(resolvedPaneId, tabId);
+ const closeTabs = (tabIds: readonly string[]) => context.closeTabsInPane(resolvedPaneId, tabIds);
+ const closeNewTab = (tabId: string) => context.closeNewTabInPane(resolvedPaneId, tabId);
+ const openNewTab = () => context.openNewTabInPane(resolvedPaneId);
+ const pinTab = (tabId: string) => context.pinTabInPane(resolvedPaneId, tabId);
+ const unpinTab = (tabId: string) => context.unpinTabInPane(resolvedPaneId, tabId);
+ const promoteTab = (tabId: string) => context.promoteTabInPane(resolvedPaneId, tabId);
+ const [splitAnnouncement, setSplitAnnouncement] = useState({ id: 0, text: '' });
+ function splitTab(tabId: string, side: 'left' | 'right', label: string) {
+ const nextPaneId = context.moveTabToNewPane(tabId, side);
+ if (!nextPaneId) return;
+ const text =
+ side === 'left'
+ ? t`Moved ${label} to a new pane on the left.`
+ : t`Moved ${label} to a new pane on the right.`;
+ setSplitAnnouncement((current) => ({ id: current.id + 1, text }));
+ onSplitComplete?.(nextPaneId, tabId);
+ }
const { pageMeta } = usePageList();
- const tabListRef = useRef<HTMLDivElement>(null);
- const [tabReorderBounds, setTabReorderBounds] = useState<TabReorderBounds | null>(null);
- const [renamingTab, setRenamingTab] = useState<{ docName: string; tabId: string } | null>(null);
- const [renameValue, setRenameValue] = useState('');
- const [renameError, setRenameError] = useState<string | null>(null);
- const [isRenameLoading, setIsRenameLoading] = useState(false);
const [showTabShortcutHints, setShowTabShortcutHints] = useState(false);
- const renameInputRef = useRef<HTMLInputElement>(null);
- const commitInProgressRef = useRef(false);
- const cancelRequestedRef = useRef(false);
- const lastFailedValueRef = useRef<string | null>(null);
- const activeDocNameRef = useRef(activeDocName);
+ const tabScrollRef = useRef<HTMLDivElement>(null);
const tabShortcutHintTimerRef = useRef<number | null>(null);
const isTabShortcutModifierHeldRef = useRef(false);
const showTabShortcutHintsRef = useRef(false);
const activeTabId =
- activeContextTabId ??
- (activeTarget
- ? tabIdForNavigationTarget(activeTarget)
- : activeDocName
- ? docTabId(activeDocName)
- : null);
- const activeTabScrollKey = isNewTabActive
- ? `${activeNewTabId ?? '__new-tab__'}\u0000${openTabs.join('\u0000')}\u0000${newTabIds.join('\u0000')}`
- : activeTabId
- ? `${activeTabId}\u0000${openTabs.join('\u0000')}`
- : '';
+ activeContextTabId ?? (activeTarget ? tabIdForNavigationTarget(activeTarget) : null);
- useEffect(() => {
- activeDocNameRef.current = activeDocName;
- }, [activeDocName]);
+ function dropIndicatorSideForTab(tabIndex: number): 'before' | 'after' | undefined {
+ if (dropIndicatorIndex === tabIndex) return 'before';
+ if (dropIndicatorIndex === visibleTabIds.length && tabIndex === visibleTabIds.length - 1) {
+ return 'after';
+ }
+ return undefined;
+ }
useEffect(() => {
return () => {
@@ -543,191 +783,10 @@ export function EditorTabs() {
};
}, []);
- useEffect(() => {
- if (!activeTabScrollKey) return;
- const activeTab = tabListRef.current?.querySelector<HTMLElement>('[data-active-tab="true"]');
- activeTab?.scrollIntoView({ block: 'nearest', inline: 'nearest' });
- }, [activeTabScrollKey]);
-
- useEffect(() => {
- if (!renamingTab) return;
- renameInputRef.current?.focus();
- renameInputRef.current?.select();
- }, [renamingTab]);
-
- useEffect(() => {
- if (!renamingTab || openTabs.includes(renamingTab.tabId)) return;
- cancelRequestedRef.current = true;
- lastFailedValueRef.current = null;
- setRenamingTab(null);
- setRenameValue('');
- setRenameError(null);
- setIsRenameLoading(false);
- }, [openTabs, renamingTab]);
-
- function enterRenameMode(tabId: string, docName: string) {
- const segments = docName.split('/');
- cancelRequestedRef.current = false;
- lastFailedValueRef.current = null;
- setRenamingTab({ docName, tabId });
- setRenameValue(segments[segments.length - 1]);
- setRenameError(null);
- }
-
- function cancelRename() {
- cancelRequestedRef.current = true;
- lastFailedValueRef.current = null;
- setRenamingTab(null);
- setRenameValue('');
- setRenameError(null);
- setIsRenameLoading(false);
- }
-
- async function commitRename() {
- if (cancelRequestedRef.current) {
- cancelRequestedRef.current = false;
- return;
- }
- if (commitInProgressRef.current) return;
-
- const docName = renamingTab?.docName;
- if (!docName) {
- cancelRename();
- return;
- }
-
- const docExt = pageMeta.get(docName)?.docExt ?? '.md';
- const normalized = normalizeRenameValue(
- 'file',
- stripRenameExtensionSuffix(renameValue, docExt),
- );
- const segments = docName.split('/');
- const currentName = segments[segments.length - 1];
-
- if (normalized === currentName) {
- cancelRename();
- return;
- }
- if (normalized === lastFailedValueRef.current) {
- renameInputRef.current?.focus();
- return;
- }
-
- if (!isValidNodeName(normalized)) {
- setRenameError(t`Name can’t be empty, ".", "..", or contain / or \\`);
- renameInputRef.current?.focus();
- return;
- }
-
- const newDocName = buildRenamedNodePath(
- { kind: 'file', path: docName, name: currentName },
- normalized,
- );
-
- commitInProgressRef.current = true;
- setIsRenameLoading(true);
- setRenameError(null);
-
- try {
- const res = await fetch('/api/rename-path', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ kind: 'file', fromPath: docName, toPath: newDocName }),
- });
-
- if (cancelRequestedRef.current) {
- setIsRenameLoading(false);
- commitInProgressRef.current = false;
- return;
- }
-
- const parsed = await parseServerResponse(res, `Server error (HTTP ${res.status})`);
-
- if (!parsed.ok) {
- setRenameError(parsed.title);
- setIsRenameLoading(false);
- commitInProgressRef.current = false;
- lastFailedValueRef.current = normalized;
- renameInputRef.current?.focus();
- return;
- }
-
- const success = parseSuccessOrWarn(RenamePathSuccessSchema, parsed.body, 'rename-path:tab', {
- renamed: [],
- renamedAssets: [],
- });
- const renamed = success.renamed;
- const currentActiveDocName = activeDocNameRef.current;
- const nextActiveDocName = remapActiveDocName(currentActiveDocName, renamed);
-
- // Split try/catch: server-side rename already committed
- // (`parsed.ok === true`). A failure inside the post-commit work
- // (persistence cleanup, tab remap, event dispatch)
- // is a client-side reconciliation failure, NOT a network error.
- // Labeling it "Network error — please try again" would misdirect
- // the user toward a retry that POSTs against a now-nonexistent
- // source path and fails differently. The correct recovery is to
- // refresh and resync with disk truth.
- let reconcileOk = true;
- try {
- await reconcileLocalRename({ renamed });
- emitDocumentsChanged(['files', 'backlinks', 'graph']);
- } catch (reconcileErr) {
- reconcileOk = false;
- console.warn('[EditorTabs] post-rename reconciliation failed', {
- err: reconcileErr,
- docName,
- newDocName,
- normalized,
- });
- toast.error(t`Rename succeeded but the tabstrip may be out of date — refresh to resync`);
- }
-
- cancelRequestedRef.current = true;
- setRenamingTab(null);
- setRenameValue('');
- setRenameError(null);
- setIsRenameLoading(false);
- commitInProgressRef.current = false;
- lastFailedValueRef.current = null;
-
- // Skip navigation when reconciliation failed: tab identities remain stale,
- // so no tab is keyed to nextActiveDocName. Calling navigateToDoc
- // would silently open a new tab and contradict the "refresh to resync"
- // toast. Refresh recovers consistent state.
- if (reconcileOk && nextActiveDocName && nextActiveDocName !== currentActiveDocName) {
- navigateToDoc(nextActiveDocName);
- }
- } catch (err) {
- console.warn('[EditorTabs] rename failed', { err, docName, newDocName, normalized });
- setRenameError(t`Network error — please try again`);
- setIsRenameLoading(false);
- commitInProgressRef.current = false;
- lastFailedValueRef.current = normalized;
- renameInputRef.current?.focus();
- }
- }
-
- // Electron-host gate. Two regions, split by geometry:
- //
- // • The strip ROOT stays a window-drag region (`-webkit-app-region: drag`).
- // The strip is h-12 (48px) and `items-end`, so the empty 8px band ABOVE
- // the h-10 (40px) tabs — plus all trailing space after the last tab when
- // the strip isn't full — is the root showing through, and stays draggable.
- // • An inner wrapper that hugs the tabs + add-button (content width, 40px
- // tall, bottom-aligned) declares `no-drag`. That covers the tabs AND the
- // 4px gaps between them, so they stay interactive.
- //
- // Why the split: macOS hijacks pointer/wheel events in drag regions at the OS
- // chrome level (the DOM never sees them; see the `[data-electron-drag]`
- // neutralization rule in globals.css). A draggable inter-tab gap therefore
- // killed wheel-scroll whenever the cursor sat between two tabs. Scoping
- // `no-drag` to the content-hugging wrapper keeps wheel-scroll alive over the
- // tabs and gaps while preserving the drag affordance on the genuinely-empty
- // top band and trailing space. Web mode (no `window.okDesktop`) is unchanged.
+ // Pane-local strips live below the global window chrome. Keep the entire
+ // strip interactive in Electron so blank strip space can accept tab drops.
const isElectronHost = typeof window !== 'undefined' && window.okDesktop != null;
const newTabIdSet = new Set(newTabIds);
- const tabReorderModifiers = [createTabReorderModifier(tabReorderBounds)];
function closeVisibleTabs(tabIds: readonly string[]) {
const documentTabIds: string[] = [];
@@ -746,7 +805,9 @@ export function EditorTabs() {
}
useEffect(() => {
+ if (!isFocusedPane) return;
const currentNewTabIds = new Set(newTabIds);
+ const currentVisibleTabIds = [...openTabs, ...newTabIds];
function clearTabShortcutHintTimer() {
if (tabShortcutHintTimerRef.current === null) return;
@@ -783,19 +844,22 @@ export function EditorTabs() {
function activateVisibleTab(tabId: string) {
if (currentNewTabIds.has(tabId)) {
- activateNewTab(tabId);
+ context.activateNewTabInPane(resolvedPaneId, tabId);
} else {
- activateTab(tabId);
+ context.activateTabInPane(resolvedPaneId, tabId);
}
}
function activateTabByOffset(offset: number) {
- if (visibleTabIds.length === 0) return;
+ if (currentVisibleTabIds.length === 0) return;
const activeVisibleTabId = isNewTabActive ? activeNewTabId : activeTabId;
- const activeIndex = activeVisibleTabId ? visibleTabIds.indexOf(activeVisibleTabId) : -1;
+ const activeIndex = activeVisibleTabId
+ ? currentVisibleTabIds.indexOf(activeVisibleTabId)
+ : -1;
const baseIndex = activeIndex >= 0 ? activeIndex : 0;
- const nextIndex = (baseIndex + offset + visibleTabIds.length) % visibleTabIds.length;
- activateVisibleTab(visibleTabIds[nextIndex]);
+ const nextIndex =
+ (baseIndex + offset + currentVisibleTabIds.length) % currentVisibleTabIds.length;
+ activateVisibleTab(currentVisibleTabIds[nextIndex]);
}
function onKeyDown(event: globalThis.KeyboardEvent) {
@@ -809,7 +873,7 @@ export function EditorTabs() {
if (matchesKeyboardShortcut(event, 'tab-new')) {
event.preventDefault();
- openNewTab();
+ context.openNewTabInPane(resolvedPaneId);
return;
}
if (matchesKeyboardShortcut(event, 'tab-reopen-closed')) {
@@ -828,10 +892,10 @@ export function EditorTabs() {
return;
}
- const jumpIndex = jumpTabIndexFromShortcut(event, visibleTabIds.length);
+ const jumpIndex = jumpTabIndexFromShortcut(event, currentVisibleTabIds.length);
if (jumpIndex === null) return;
event.preventDefault();
- activateVisibleTab(visibleTabIds[jumpIndex]);
+ activateVisibleTab(currentVisibleTabIds[jumpIndex]);
}
function onKeyUp(event: globalThis.KeyboardEvent) {
@@ -851,464 +915,428 @@ export function EditorTabs() {
}, [
activeNewTabId,
activeTabId,
- activateNewTab,
- activateTab,
+ context.activateNewTabInPane,
+ context.activateTabInPane,
+ context.openNewTabInPane,
+ isFocusedPane,
isNewTabActive,
newTabIds,
- openNewTab,
+ openTabs,
reopenClosedTab,
- visibleTabIds,
+ resolvedPaneId,
]);
-
- // Tab drag-reorder. PointerSensor `distance: 8` keeps plain clicks from
- // initiating a drag (tabs differ from the PropertyPanel drag-handle pattern,
- // where the handle is a dedicated child — here the entire tab is the drag
- // source, so the activation threshold has to be looser than the panel's 4px).
- // KeyboardSensor + sortableKeyboardCoordinates makes keyboard reorder work.
- // Space starts drag so Enter can stay available for one-stop tab activation
- // on the outer sortable tab while inner activation buttons remain tabIndex=-1.
- const sensors = useSensors(
- useSensor(PointerSensor, { activationConstraint: { distance: 8 } }),
- useSensor(KeyboardSensor, {
- coordinateGetter: sortableKeyboardCoordinates,
- keyboardCodes: TAB_KEYBOARD_DRAG_CODES,
- }),
- );
const forceTabCloseVisible = showTabShortcutHints;
+ const selectedTabId = isNewTabActive ? activeNewTabId : activeTabId;
+ const previousSelectedTabIdRef = useRef(selectedTabId);
- function handleDragStart() {
- setTabReorderBounds(measureTabReorderBounds(tabListRef.current, '[data-editor-tab-sortable]'));
- }
+ useLayoutEffect(() => {
+ const scrollContainer = tabScrollRef.current;
+ if (!scrollContainer) return;
+ syncTabOverflowIndicators(scrollContainer);
+ });
- function clearTabReorderBounds() {
- setTabReorderBounds(null);
- }
+ useLayoutEffect(() => {
+ const scrollContainer = tabScrollRef.current;
+ if (!scrollContainer || typeof ResizeObserver === 'undefined') return;
+ const observer = new ResizeObserver(() => syncTabOverflowIndicators(scrollContainer));
+ observer.observe(scrollContainer);
+ return () => observer.disconnect();
+ }, []);
- function handleDragEnd(event: DragEndEvent) {
- clearTabReorderBounds();
- const activeId = String(event.active.id);
- const overId = event.over ? String(event.over.id) : null;
- if (!overId || activeId === overId) return;
- const fromIndex = visibleTabIds.indexOf(activeId);
- const toIndex = visibleTabIds.indexOf(overId);
- if (fromIndex < 0 || toIndex < 0 || fromIndex === toIndex) return;
- reorderTabs(arrayMove([...visibleTabIds], fromIndex, toIndex), activeId);
- }
+ useEffect(() => {
+ const previousSelectedTabId = previousSelectedTabIdRef.current;
+ previousSelectedTabIdRef.current = selectedTabId;
+ if (selectedTabId === null || selectedTabId === previousSelectedTabId) return;
+
+ const scrollContainer = tabScrollRef.current;
+ if (!scrollContainer) return;
+ findEditorTabElement(scrollContainer, resolvedPaneId, selectedTabId)?.scrollIntoView({
+ block: 'nearest',
+ inline: 'nearest',
+ });
+ }, [resolvedPaneId, selectedTabId]);
return (
<div
- ref={tabListRef}
- data-electron-drag={isElectronHost ? '' : undefined}
+ data-editor-pane-tabs={resolvedPaneId}
className={cn(
- 'pl-2 flex h-12 min-w-0 touch-manipulation flex-1 items-end overflow-x-auto overflow-y-hidden overscroll-x-contain scroll-fade-mask-x [scrollbar-width:none]',
- isElectronHost && '[-webkit-app-region:drag]',
+ 'flex h-12 w-full min-w-0 touch-manipulation items-end overflow-hidden',
+ reserveLeadingChrome
+ ? 'pl-[calc(var(--editor-header-leading-offset,0px)+var(--editor-header-leading-width,0px)+0.5rem)]'
+ : 'pl-2',
+ reserveTrailingChrome && 'pr-[var(--editor-header-trailing-width,0px)]',
+ isElectronHost && '[-webkit-app-region:no-drag]',
)}
- onWheel={scrollTabStripOnWheel}
>
<div
+ data-editor-tab-overflow-root=""
className={cn(
- // Content-hugging, bottom-aligned no-drag wrapper. Hugs the tabs +
- // add-button (no flex-1) so the root's empty space stays draggable;
- // `no-drag` here keeps the tabs and inter-tab gaps wheel-scrollable.
- 'flex items-end gap-1',
+ 'group/tab-overflow relative flex min-w-0 flex-1 items-end gap-px overflow-hidden',
isElectronHost && '[-webkit-app-region:no-drag]',
)}
>
- <DndContext
- sensors={sensors}
- autoScroll={TAB_REORDER_AUTO_SCROLL}
- collisionDetection={tabRunCollisionDetection}
- modifiers={tabReorderModifiers}
- onDragStart={handleDragStart}
- onDragEnd={handleDragEnd}
- onDragCancel={clearTabReorderBounds}
- accessibility={{
- // Portal @dnd-kit's `DndDescribedBy` + `DndLiveRegion` SR helpers
- // out of the strip's flex container — without this they land as
- // siblings of the SortableTab list and the `+` button, occupying
- // the `:first-child` slot in the parent flex flow. That breaks
- // the `+` Button's `first:mb-3 mb-1.5` Tailwind variant when the
- // tabs list is empty, leaving the `+` button 6px below where it
- // should sit (cy=37 instead of cy=32). SSR/test-safe: only pass
- // `document.body` when `document` exists in the runtime.
- container: typeof document !== 'undefined' ? document.body : undefined,
- }}
+ <span
+ aria-atomic="true"
+ aria-live="polite"
+ data-testid="editor-tab-split-announcement"
+ className="sr-only"
>
- <SortableContext items={[...visibleTabIds]} strategy={horizontalListSortingStrategy}>
- {visibleTabIds.map((tabId, tabIndex) => {
- const shortcutHint = showTabShortcutHints
- ? tabShortcutHintForIndex(tabIndex, visibleTabIds.length)
- : null;
- const ariaKeyShortcuts = tabAriaKeyShortcutsForIndex(tabIndex, visibleTabIds.length);
- if (newTabIdSet.has(tabId)) {
- const isActive = tabId === activeNewTabId;
- return (
- <EditorTabContextMenu
- key={tabId}
- tabId={tabId}
- canPin={false}
- openTabs={visibleTabIds}
- closeTab={closeNewTab}
- closeTabs={closeVisibleTabs}
- pinTab={pinTab}
- pinnedTabIds={pinnedTabIds}
- unpinTab={unpinTab}
- >
- <SortableTab
+ <span key={splitAnnouncement.id}>{splitAnnouncement.text}</span>
+ </span>
+ <SortableContext items={[...visibleTabIds]} strategy={horizontalListSortingStrategy}>
+ <div className="relative h-10 w-fit max-w-[calc(100%-1.75rem)] min-w-0 flex-none self-end">
+ <div
+ ref={tabScrollRef}
+ data-editor-tab-scroll=""
+ className="scrollbar-none flex h-10 w-fit max-w-full min-w-0 items-end gap-px overflow-x-auto overflow-y-hidden overscroll-x-contain group-data-[overflow-left]/tab-overflow:mask-l-from-[calc(100%-4rem)] group-data-[overflow-right]/tab-overflow:mask-r-from-[calc(100%-4rem)]"
+ onScroll={(event) => syncTabOverflowIndicators(event.currentTarget)}
+ onWheel={(event) => {
+ scrollTabStripOnWheel(event);
+ syncTabOverflowIndicators(event.currentTarget);
+ }}
+ >
+ {visibleTabIds.length === 0 && dropIndicatorIndex === 0 ? (
+ <span
+ aria-hidden="true"
+ data-editor-tab-drop-indicator="before"
+ className="pointer-events-none absolute inset-y-1 left-0 z-30 w-0.5 rounded-full bg-primary"
+ />
+ ) : null}
+ {visibleTabIds.map((tabId, tabIndex) => {
+ const shortcutHint = showTabShortcutHints
+ ? shortcutDigitForIndex(tabIndex, visibleTabIds.length)
+ : null;
+ const ariaKeyShortcuts = isFocusedPane
+ ? tabAriaKeyShortcutsForIndex(tabIndex, visibleTabIds.length)
+ : undefined;
+ if (newTabIdSet.has(tabId)) {
+ const isActive = tabId === activeNewTabId;
+ return (
+ <EditorTabContextMenu
+ key={tabId}
tabId={tabId}
- activateFromKeyboard={() => activateNewTab(tabId)}
- aria-current={isActive ? 'page' : undefined}
- aria-keyshortcuts={ariaKeyShortcuts}
- data-active-tab={isActive ? 'true' : undefined}
- className={cn(
- TAB_BASE_CLASS,
- isActive ? TAB_ACTIVE_CLASS : TAB_INACTIVE_CLASS,
- )}
- onAuxClick={(event) => {
- if (event.button !== 1) return;
- event.preventDefault();
- closeNewTab(tabId);
- }}
- onClick={(event) => {
- if (event.target !== event.currentTarget) return;
- activateNewTab(tabId);
- }}
+ canPin={false}
+ openTabs={visibleTabIds}
+ closeTab={closeNewTab}
+ closeTabs={closeVisibleTabs}
+ pinTab={pinTab}
+ pinnedTabIds={pinnedTabIds}
+ promoteTab={promoteTab}
+ splitTab={splitTab}
+ tabLabel={t`New tab`}
+ unpinTab={unpinTab}
>
- <button
- type="button"
- aria-label={t`Activate new tab`}
- data-testid="editor-new-tab-placeholder-button"
- className={TAB_BUTTON_CLASS}
- onClick={() => activateNewTab(tabId)}
- tabIndex={-1}
+ <SortableTab
+ dropIndicatorSide={dropIndicatorSideForTab(tabIndex)}
+ label={t`New tab`}
+ paneId={resolvedPaneId}
+ splittable
+ tabId={tabId}
+ activateFromKeyboard={() => activateNewTab(tabId)}
+ aria-current={isActive ? 'page' : undefined}
+ aria-keyshortcuts={ariaKeyShortcuts}
+ data-active-tab={isActive ? 'true' : undefined}
+ className={cn(
+ TAB_BASE_CLASS,
+ isActive ? TAB_ACTIVE_CLASS : TAB_INACTIVE_CLASS,
+ )}
+ onAuxClick={(event) => {
+ if (event.button !== 1) return;
+ event.preventDefault();
+ closeNewTab(tabId);
+ }}
+ onClick={(event) => {
+ if (event.target !== event.currentTarget) return;
+ activateNewTab(tabId);
+ }}
>
- <span className="min-w-0 truncate">
- <Trans>New tab</Trans>
- </span>
- </button>
- {shortcutHint ? (
- <TabShortcutHint value={shortcutHint} />
- ) : (
<button
type="button"
- aria-label={t`Close new tab`}
- data-testid="editor-new-tab-placeholder-close"
- className={getTabCloseButtonClass(forceTabCloseVisible || isActive)}
- tabIndex={getTabCloseButtonTabIndex(isActive)}
- onClick={(event) => {
- event.stopPropagation();
- closeNewTab(tabId);
- }}
+ aria-label={t`Activate new tab`}
+ data-testid="editor-new-tab-placeholder-button"
+ className={tabTitleClassName(isActive && isFocusedPane, false)}
+ onClick={() => activateNewTab(tabId)}
+ tabIndex={-1}
>
- <XIcon aria-hidden="true" className="size-3.5" />
+ <span
+ data-editor-tab-title-overflow="ellipsis"
+ className="min-w-0 truncate"
+ >
+ <Trans>New tab</Trans>
+ </span>
</button>
- )}
- </SortableTab>
- </EditorTabContextMenu>
- );
- }
-
- const tab = parseEditorTabId(tabId);
- const isActive = tabId === activeTabId;
- const isPinned = pinnedTabIds.includes(tabId);
- if (tab.kind === 'folder') {
- const { baseName, label, prefix } = tabParts(tab.folderPath, '/');
- const accessibleLabel = `${prefix}${label}`;
- return (
- <EditorTabContextMenu
- key={tabId}
- tabId={tabId}
- openTabs={visibleTabIds}
- closeTab={closeTab}
- closeTabs={closeVisibleTabs}
- pinTab={pinTab}
- pinnedTabIds={pinnedTabIds}
- unpinTab={unpinTab}
- >
- <SortableTab
+ {shortcutHint ? (
+ <TabShortcutHint value={shortcutHint} />
+ ) : (
+ <button
+ type="button"
+ aria-label={t`Close new tab`}
+ data-testid="editor-new-tab-placeholder-close"
+ className={getTabCloseButtonClass(forceTabCloseVisible || isActive)}
+ tabIndex={getTabCloseButtonTabIndex(isActive)}
+ onClick={(event) => {
+ event.stopPropagation();
+ closeNewTab(tabId);
+ }}
+ >
+ <XIcon aria-hidden="true" className="size-3.5" />
+ </button>
+ )}
+ </SortableTab>
+ </EditorTabContextMenu>
+ );
+ }
+
+ const tab = parseEditorTabId(tabId);
+ const isActive = tabId === activeTabId;
+ const isPinned = pinnedTabIds.includes(tabId);
+ const isPreview = tabId === previewTabId;
+ if (tab.kind === 'folder') {
+ const { baseName, label, prefix } = tabParts(tab.folderPath, '/');
+ const accessibleLabel = `${prefix}${label}`;
+ return (
+ <EditorTabFrame
+ key={tabId}
+ accessibleLabel={accessibleLabel}
+ activateTab={activateTab}
+ ariaKeyShortcuts={ariaKeyShortcuts}
+ dropIndicatorSide={dropIndicatorSideForTab(tabIndex)}
tabId={tabId}
- activateFromKeyboard={() => activateTab(tabId)}
- aria-current={isActive ? 'page' : undefined}
- aria-keyshortcuts={ariaKeyShortcuts}
- data-active-tab={isActive ? 'true' : undefined}
- className={cn(
- TAB_BASE_CLASS,
- isActive ? TAB_ACTIVE_CLASS : TAB_INACTIVE_CLASS,
- )}
- onAuxClick={(event) => {
- if (event.button !== 1) return;
- event.preventDefault();
- if (isPinned) return;
- closeTab(tabId);
- }}
- onClick={(event) => {
- if (event.target !== event.currentTarget) return;
- activateTab(tabId);
+ paneId={resolvedPaneId}
+ target={{
+ kind: 'folder',
+ target: tab.folderPath,
+ folderPath: tab.folderPath,
}}
+ renameName={baseName}
+ openTabs={visibleTabIds}
+ closeTab={closeTab}
+ closeTabs={closeVisibleTabs}
+ forceCloseVisible={forceTabCloseVisible}
+ isActive={isActive}
+ isPinned={isPinned}
+ isPreview={isPreview}
+ pinTab={pinTab}
+ pinnedTabIds={pinnedTabIds}
+ promoteTab={promoteTab}
+ shortcutHint={shortcutHint}
+ splitTab={splitTab}
+ unpinTab={unpinTab}
>
<TabPathTooltip path={accessibleLabel}>
<button
type="button"
aria-label={accessibleLabel}
- className={TAB_BUTTON_CLASS}
- onClick={() => {
- activateTab(tabId);
+ className={tabTitleClassName(isActive && isFocusedPane, isPreview)}
+ onClick={() => activateTab(tabId)}
+ onDoubleClick={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ promoteTab(tabId);
}}
tabIndex={-1}
>
- {prefix && (
- <span
- className={cn(
- 'min-w-0 flex-1 truncate',
- isActive && 'text-muted-foreground',
- )}
- >
- {prefix}
- </span>
- )}
<span
- className={cn(
- 'flex min-w-0 items-center',
- prefix ? 'max-w-[70%] shrink-0' : 'flex-1',
- )}
+ data-editor-tab-title-overflow={isActive ? 'fade' : 'ellipsis'}
+ className={cn('min-w-0 flex-1', tabTitleOverflowClassName(isActive))}
>
- <span className="min-w-0 truncate">{baseName}</span>
- <span className="shrink-0">/</span>
+ {prefix && (
+ <span
+ className={cn(
+ '@max-[5rem]/tab:hidden',
+ isActive && 'text-muted-foreground',
+ )}
+ >
+ {prefix}
+ </span>
+ )}
+ <span>{baseName}/</span>
</span>
</button>
</TabPathTooltip>
- <TabPinOrCloseButton
- accessibleLabel={accessibleLabel}
- closeTab={closeTab}
- forceCloseVisible={forceTabCloseVisible}
- isActive={isActive}
- isPinned={isPinned}
- shortcutHint={shortcutHint}
- tabId={tabId}
- unpinTab={unpinTab}
- />
- </SortableTab>
- </EditorTabContextMenu>
- );
- }
-
- if (
- tab.kind === 'asset' ||
- tab.kind === 'skill-file' ||
- tab.kind === 'skills' ||
- tab.kind === 'skill-preview'
- ) {
- // Assets, skill bundle files, the Skills hub, and a pre-install
- // skill preview share the asset tab's read-only chrome. Label off
- // the asset path, the skill-relative path (`references/x.md`), the
- // previewed skill's name, or a fixed "Skills" label.
- const labelPath =
- tab.kind === 'asset'
- ? tab.assetPath
- : tab.kind === 'skill-file'
- ? tab.path
- : tab.kind === 'skill-preview'
- ? tab.name
- : t`Skills`;
- const { baseName, label, prefix } = tabParts(labelPath, '');
- const accessibleLabel = `${prefix}${label}`;
- return (
- <EditorTabContextMenu
- key={tabId}
- tabId={tabId}
- openTabs={visibleTabIds}
- closeTab={closeTab}
- closeTabs={closeVisibleTabs}
- pinTab={pinTab}
- pinnedTabIds={pinnedTabIds}
- unpinTab={unpinTab}
- >
- <SortableTab
+ </EditorTabFrame>
+ );
+ }
+
+ if (
+ tab.kind === 'asset' ||
+ tab.kind === 'skill-file' ||
+ tab.kind === 'skill-preview'
+ ) {
+ // Skill bundle files and marketplace previews share the asset
+ // tab's read-only chrome.
+ let labelPath: string;
+ switch (tab.kind) {
+ case 'asset':
+ labelPath = tab.assetPath;
+ break;
+ case 'skill-file':
+ labelPath = tab.path;
+ break;
+ case 'skill-preview':
+ labelPath = tab.name;
+ break;
+ }
+ const { baseName, label, prefix } = tabParts(labelPath, '');
+ const accessibleLabel = `${prefix}${label}`;
+ const skillFileCandidates =
+ tab.kind === 'skill-file'
+ ? editableSkills.filter(
+ (skill) => skill.scope === tab.scope && skill.name === tab.name,
+ )
+ : [];
+ const skillFileOwner =
+ tab.kind === 'skill-file'
+ ? tab.host
+ ? skillFileCandidates.find((skill) => skill.hosts[0] === tab.host)
+ : skillFileCandidates.length === 1
+ ? skillFileCandidates[0]
+ : undefined
+ : undefined;
+ return (
+ <EditorTabFrame
+ key={tabId}
+ accessibleLabel={accessibleLabel}
+ activateTab={activateTab}
+ ariaKeyShortcuts={ariaKeyShortcuts}
+ dropIndicatorSide={dropIndicatorSideForTab(tabIndex)}
tabId={tabId}
- activateFromKeyboard={() => activateTab(tabId)}
- aria-current={isActive ? 'page' : undefined}
- aria-keyshortcuts={ariaKeyShortcuts}
- data-active-tab={isActive ? 'true' : undefined}
- className={cn(
- TAB_BASE_CLASS,
- isActive ? TAB_ACTIVE_CLASS : TAB_INACTIVE_CLASS,
- )}
- onAuxClick={(event) => {
- if (event.button !== 1) return;
- event.preventDefault();
- if (isPinned) return;
- closeTab(tabId);
- }}
- onClick={(event) => {
- if (event.target !== event.currentTarget) return;
- activateTab(tabId);
- }}
+ paneId={resolvedPaneId}
+ target={
+ tab.kind === 'asset'
+ ? {
+ kind: 'asset',
+ target: tab.assetPath,
+ assetPath: tab.assetPath,
+ mediaKind: null,
+ }
+ : undefined
+ }
+ renameName={tab.kind === 'asset' ? baseName : undefined}
+ openTabs={visibleTabIds}
+ closeTab={closeTab}
+ closeTabs={closeVisibleTabs}
+ forceCloseVisible={forceTabCloseVisible}
+ isActive={isActive}
+ isPinned={isPinned}
+ isPreview={isPreview}
+ pinTab={pinTab}
+ pinnedTabIds={pinnedTabIds}
+ promoteTab={promoteTab}
+ shortcutHint={shortcutHint}
+ splitTab={splitTab}
+ skillMenuItems={
+ tab.kind === 'skill-file' && skillFileOwner ? (
+ <SkillFileContextMenuItems
+ actions={skillActions}
+ filePath={tab.path}
+ menuKind="context"
+ skill={skillFileOwner}
+ />
+ ) : undefined
+ }
+ unpinTab={unpinTab}
>
<TabPathTooltip path={accessibleLabel}>
<button
type="button"
aria-label={accessibleLabel}
- className={TAB_BUTTON_CLASS}
- onClick={() => {
- activateTab(tabId);
+ className={tabTitleClassName(isActive && isFocusedPane, isPreview)}
+ onClick={() => activateTab(tabId)}
+ onDoubleClick={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ promoteTab(tabId);
}}
tabIndex={-1}
>
- {prefix ? (
- <span
- className={cn(
- 'min-w-0 flex-1 truncate text-muted-foreground/60',
- isActive && 'text-muted-foreground',
- )}
- >
- {prefix}
- </span>
- ) : null}
<span
- className={cn(
- 'min-w-0 truncate',
- prefix ? 'max-w-[70%] shrink-0' : 'flex-1',
- )}
+ data-editor-tab-title-overflow={isActive ? 'fade' : 'ellipsis'}
+ className={cn('min-w-0 flex-1', tabTitleOverflowClassName(isActive))}
>
- {baseName}
+ {prefix ? (
+ <span
+ className={cn(
+ 'text-muted-foreground/60 @max-[5rem]/tab:hidden',
+ isActive && 'text-muted-foreground',
+ )}
+ >
+ {prefix}
+ </span>
+ ) : null}
+ <span>{baseName}</span>
</span>
</button>
</TabPathTooltip>
- <TabPinOrCloseButton
- accessibleLabel={accessibleLabel}
- closeTab={closeTab}
- forceCloseVisible={forceTabCloseVisible}
- isActive={isActive}
- isPinned={isPinned}
- shortcutHint={shortcutHint}
- tabId={tabId}
- unpinTab={unpinTab}
- />
- </SortableTab>
- </EditorTabContextMenu>
- );
- }
-
- const docName = tab.docName;
- const docExt = pageMeta.get(docName)?.docExt ?? '.md';
- const { baseName, extension, label, prefix } = tabParts(docName, docExt);
- const accessibleLabel = `${prefix}${label}`;
- const hideDocExtension = docExt === '.md' || docExt === '.mdx';
- const isRenaming = renamingTab?.tabId === tabId;
- const renameErrorId = `editor-tab-rename-error-${tabDomIdPart(docName)}`;
- return (
- <EditorTabContextMenu
- key={tabId}
- disabled={isRenaming}
- tabId={tabId}
- openTabs={visibleTabIds}
- closeTab={closeTab}
- closeTabs={closeVisibleTabs}
- pinTab={pinTab}
- pinnedTabIds={pinnedTabIds}
- unpinTab={unpinTab}
- >
- <SortableTab
+ </EditorTabFrame>
+ );
+ }
+
+ const docName = tab.docName;
+ const skill = editableSkillsByTabId.get(docName);
+ const docExt = pageMeta.get(docName)?.docExt ?? '.md';
+ const { baseName, extension, label, prefix } = tabParts(docName, docExt);
+ const accessibleLabel = `${prefix}${label}`;
+ const hideDocExtension = docExt === '.md' || docExt === '.mdx';
+ const hasFileTargetActions =
+ !isSkillDocName(docName) && !isSkillBundleShapedPath(docName);
+ return (
+ <EditorTabFrame
+ key={tabId}
+ accessibleLabel={accessibleLabel}
+ activateTab={activateTab}
+ ariaKeyShortcuts={ariaKeyShortcuts}
+ dropIndicatorSide={dropIndicatorSideForTab(tabIndex)}
tabId={tabId}
- activateFromKeyboard={() => activateTab(tabId)}
- disabled={isRenaming}
- aria-current={isActive ? 'page' : undefined}
- aria-keyshortcuts={ariaKeyShortcuts}
- data-active-tab={isActive ? 'true' : undefined}
- className={cn(
- TAB_BASE_CLASS,
- isActive ? TAB_ACTIVE_CLASS : TAB_INACTIVE_CLASS,
- isRenaming && renameError && 'border-destructive',
- )}
- onAuxClick={(event) => {
- if (event.button !== 1) return;
- event.preventDefault();
- if (isPinned) return;
- closeTab(tabId);
- }}
- onClick={(event) => {
- if (event.target !== event.currentTarget) return;
- activateTab(tabId);
- }}
- >
- {isRenaming ? (
- <>
- <InputGroup className="h-full min-w-0 flex-1 rounded-none border-0 bg-transparent dark:bg-transparent">
- <InputGroupInput
- ref={renameInputRef}
- value={renameValue}
- disabled={isRenameLoading}
- aria-label={t`Rename ${label}`}
- data-testid="editor-tab-rename-input"
- aria-invalid={renameError ? true : undefined}
- aria-describedby={renameError ? renameErrorId : undefined}
- aria-busy={isRenameLoading || undefined}
- title={renameError ?? docName}
- className="h-full min-w-0 px-2 py-0 font-medium text-foreground text-xs selection:bg-primary selection:text-primary-foreground"
- onChange={(event) => {
- setRenameValue(
- stripRenameExtensionSuffix(event.target.value, docExt),
- );
- setRenameError(null);
- lastFailedValueRef.current = null;
- }}
- onKeyDown={(event) => {
- if (event.key === 'Enter') {
- event.preventDefault();
- void commitRename();
- } else if (event.key === 'Escape') {
- event.preventDefault();
- cancelRename();
- }
- }}
- onBlur={commitRename}
- />
- <InputGroupAddon
- align="inline-end"
- aria-hidden="true"
- className="pr-2 text-xs"
- >
- <InputGroupText className="text-muted-foreground/60 text-xs">
- {docExt}
- </InputGroupText>
- </InputGroupAddon>
- </InputGroup>
- {renameError ? (
- <span id={renameErrorId} role="alert" className="sr-only">
- {renameError}
- </span>
- ) : null}
- </>
- ) : (
- <>
- <DocumentTabButton
- accessibleLabel={accessibleLabel}
- activateTab={activateTab}
- baseName={baseName}
- docName={docName}
- enterRenameMode={enterRenameMode}
- extension={extension}
- hideDocExtension={hideDocExtension}
- tabId={tabId}
- />
- <TabPinOrCloseButton
- accessibleLabel={accessibleLabel}
- closeTab={closeTab}
- forceCloseVisible={forceTabCloseVisible}
- isActive={isActive}
- isPinned={isPinned}
- shortcutHint={shortcutHint}
- tabId={tabId}
- unpinTab={unpinTab}
+ paneId={resolvedPaneId}
+ docExt={docExt}
+ target={
+ hasFileTargetActions ? { kind: 'doc', target: docName, docName } : undefined
+ }
+ renameName={hasFileTargetActions ? `${baseName}${extension}` : undefined}
+ openTabs={visibleTabIds}
+ closeTab={closeTab}
+ closeTabs={closeVisibleTabs}
+ forceCloseVisible={forceTabCloseVisible}
+ isActive={isActive}
+ isPinned={isPinned}
+ isPreview={isPreview}
+ pinTab={pinTab}
+ pinnedTabIds={pinnedTabIds}
+ promoteTab={promoteTab}
+ shortcutHint={shortcutHint}
+ splitTab={splitTab}
+ skillMenuItems={
+ skill ? (
+ <SkillContextMenuItems
+ actions={skillActions}
+ existingNames={skillNamesByScope.get(skill.scope) ?? EMPTY_SKILL_NAME_SET}
+ menuKind="context"
+ skill={skill}
/>
- </>
- )}
- </SortableTab>
- </EditorTabContextMenu>
- );
- })}
- </SortableContext>
- </DndContext>
+ ) : undefined
+ }
+ unpinTab={unpinTab}
+ >
+ <DocumentTabButton
+ accessibleLabel={accessibleLabel}
+ activateTab={activateTab}
+ baseName={baseName}
+ docName={docName}
+ extension={extension}
+ hideDocExtension={hideDocExtension}
+ isActive={isActive}
+ isFocusedPane={isFocusedPane}
+ isPreview={isPreview}
+ promoteTab={promoteTab}
+ tabId={tabId}
+ />
+ </EditorTabFrame>
+ );
+ })}
+ </div>
+ </div>
+ </SortableContext>
<Tooltip>
<TooltipTrigger asChild>
<Button
@@ -1317,7 +1345,7 @@ export function EditorTabs() {
variant="ghost"
aria-label={t`New tab`}
data-testid="editor-new-tab-button"
- className="first:mb-3 mb-1.5"
+ className="first:mb-3 mb-1.5 shrink-0"
onClick={openNewTab}
>
<PlusIcon aria-hidden="true" />
@@ -1328,6 +1356,7 @@ export function EditorTabs() {
</TooltipContent>
</Tooltip>
</div>
+ {skillActions.dialogs}
</div>
);
}
diff --git a/packages/app/src/components/EditorToolbar.dom.test.tsx b/packages/app/src/components/EditorToolbar.dom.test.tsx
index eac43b9cf..17f4f290e 100644
--- a/packages/app/src/components/EditorToolbar.dom.test.tsx
+++ b/packages/app/src/components/EditorToolbar.dom.test.tsx
@@ -26,7 +26,8 @@ vi.doMock('./EditorBreadcrumb', () => ({
// (no toggles set, binding absent) so the toolbar mounts standalone.
vi.doMock('@/lib/config-provider', () => ({
useConfigContext: () => ({
- merged: null,
+ merged: {},
+ projectLocalSynced: true,
projectLocalBinding: null,
}),
}));
diff --git a/packages/app/src/components/EditorWorkspace.dom.test.tsx b/packages/app/src/components/EditorWorkspace.dom.test.tsx
new file mode 100644
index 000000000..b0fdf80f3
--- /dev/null
+++ b/packages/app/src/components/EditorWorkspace.dom.test.tsx
@@ -0,0 +1,934 @@
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { createPortal } from 'react-dom';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import type { EditorPaneState } from '@/editor/editor-panes';
+import { OK_SIDEBAR_DRAG_MIME, serializeSidebarDragPayload } from '@/lib/sidebar-drag';
+import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
+import {
+ expectVisualClassTokens,
+ expectVisualClassTokensAbsent,
+} from '@/test-utils/visual-contract';
+
+const multiPaneFixture: EditorPaneState[] = [
+ {
+ id: 'pane-a',
+ openTabs: ['docs/a', 'docs/b'],
+ pinnedTabIds: [],
+ activeTabId: 'docs/a',
+ newTabIds: [],
+ activeNewTabId: null,
+ activeTarget: { kind: 'doc', target: 'docs/a', docName: 'docs/a' },
+ size: 60,
+ },
+ {
+ id: 'pane-b',
+ openTabs: ['docs/c'],
+ pinnedTabIds: [],
+ activeTabId: 'docs/c',
+ newTabIds: [],
+ activeNewTabId: null,
+ activeTarget: { kind: 'doc', target: 'docs/c', docName: 'docs/c' },
+ size: 40,
+ },
+];
+let panes = multiPaneFixture.map((pane) => ({ ...pane }));
+let tabSessionLoaded = true;
+
+const focusPane = vi.fn();
+const moveTabToPane = vi.fn();
+const openTarget = vi.fn();
+const openTargetInPane = vi.fn();
+const reorderTabsInPane = vi.fn();
+const resizePanes = vi.fn();
+const splitTab = vi.fn(() => 'pane-new');
+
+let dndProps: Record<string, unknown> = {};
+let dragOverlayProps: Record<string, unknown> = {};
+let layoutChange: ((layout: Record<string, number>) => void) | undefined;
+let layoutChanged:
+ | ((layout: Record<string, number>, meta: { isUserInteraction: boolean }) => void)
+ | undefined;
+let overDroppableId: string | null = null;
+const droppableData = new Map<string, unknown>();
+const setLayout = vi.fn();
+
+vi.doMock('@lingui/react/macro', async () => {
+ const actual = await vi.importActual<typeof import('@lingui/react/macro')>('@lingui/react/macro');
+ return {
+ ...actual,
+ Trans: ({ children }: { children?: ReactNode }) => <>{children}</>,
+ useLingui: () => ({ t: renderLinguiTemplate }),
+ };
+});
+
+vi.doMock('@dnd-kit/core', () => ({
+ closestCenter: () => [],
+ DndContext: (props: Record<string, unknown> & { children?: ReactNode }) => {
+ dndProps = props;
+ return <div data-testid="workspace-dnd">{props.children}</div>;
+ },
+ DragOverlay: (props: Record<string, unknown> & { children?: ReactNode }) => {
+ dragOverlayProps = props;
+ return <div data-testid="editor-tab-drag-overlay-host">{props.children}</div>;
+ },
+ KeyboardCode: {
+ Enter: 'Enter',
+ Esc: 'Escape',
+ Space: 'Space',
+ },
+ KeyboardSensor: { name: 'KeyboardSensor' },
+ PointerSensor: { name: 'PointerSensor' },
+ useDroppable: ({ data, disabled, id }: { data: unknown; disabled?: boolean; id: string }) => {
+ droppableData.set(id, data);
+ return {
+ isOver: !disabled && overDroppableId === id,
+ setNodeRef: () => {},
+ };
+ },
+ useSensor: (sensor: unknown, options: unknown) => ({ sensor, options }),
+ useSensors: (...sensors: unknown[]) => sensors,
+}));
+
+vi.doMock('@dnd-kit/sortable', () => ({
+ arrayMove: <T,>(items: T[], from: number, to: number) => {
+ const next = [...items];
+ const [item] = next.splice(from, 1);
+ next.splice(to, 0, item);
+ return next;
+ },
+ sortableKeyboardCoordinates: { name: 'sortableKeyboardCoordinates' },
+}));
+
+vi.doMock('react-resizable-panels', () => ({
+ useGroupRef: () => ({ current: { setLayout } }),
+}));
+
+vi.doMock('@/components/ui/resizable', () => ({
+ ResizablePanelGroup: ({
+ children,
+ onLayoutChange,
+ onLayoutChanged,
+ ...props
+ }: {
+ children?: ReactNode;
+ onLayoutChange?: typeof layoutChange;
+ onLayoutChanged?: typeof layoutChanged;
+ [key: string]: unknown;
+ }) => {
+ layoutChange = onLayoutChange;
+ layoutChanged = onLayoutChanged;
+ return (
+ <div data-testid="workspace-panel-group" data-orientation={String(props.orientation)}>
+ {children}
+ </div>
+ );
+ },
+ ResizablePanel: ({
+ children,
+ id,
+ minSize,
+ }: {
+ children?: ReactNode;
+ id?: string;
+ minSize?: string;
+ }) => (
+ <section data-panel-id={id} data-min-size={minSize}>
+ {children}
+ </section>
+ ),
+ ResizableHandle: (props: Record<string, unknown>) => (
+ <div
+ data-testid="pane-resize-handle"
+ data-editor-pane-resize-handle={String(props['data-editor-pane-resize-handle'])}
+ data-editor-pane-before={String(props['data-editor-pane-before'])}
+ data-editor-pane-after={String(props['data-editor-pane-after'])}
+ >
+ {props.children as ReactNode}
+ </div>
+ ),
+}));
+
+vi.doMock('@/editor/DocumentContext', () => ({
+ useDocumentContext: () => ({
+ focusPane,
+ focusedPaneId: 'pane-a',
+ moveTabToPane,
+ openTarget,
+ openTargetInPane,
+ panes,
+ reorderTabsInPane,
+ resizePanes,
+ splitTab,
+ tabSessionLoaded,
+ visibleTabIdsByPane: new Map(
+ panes.map((pane) => [pane.id, [...pane.openTabs, ...pane.newTabIds]]),
+ ),
+ }),
+}));
+
+vi.doMock('@/lib/single-file-mode', () => ({
+ useSingleFileMode: () => false,
+}));
+
+vi.doMock('./EditorTabs', () => ({
+ EditorTabs: ({
+ dropIndicatorIndex,
+ paneId,
+ reserveLeadingChrome,
+ reserveTrailingChrome,
+ }: {
+ dropIndicatorIndex?: number | null;
+ paneId: string;
+ reserveLeadingChrome?: boolean;
+ reserveTrailingChrome?: boolean;
+ }) => (
+ <div
+ data-editor-pane-tabs={paneId}
+ data-drop-indicator-index={dropIndicatorIndex ?? undefined}
+ data-reserve-leading-chrome={reserveLeadingChrome || undefined}
+ data-reserve-trailing-chrome={reserveTrailingChrome || undefined}
+ >
+ Tabs {paneId}
+ </div>
+ ),
+}));
+
+const { EditorWorkspace } = await import('./EditorWorkspace');
+
+function renderWorkspace(portaledPaneBody?: ReactNode) {
+ return render(
+ <EditorWorkspace
+ renderHeader={(tabs) => <header data-testid="main-editor-header">{tabs}</header>}
+ renderPane={({ activityMount, pane }) => (
+ <div data-testid={`pane-body-${pane.id}`}>{activityMount}</div>
+ )}
+ renderActivityPool={({ activityHosts, parkingHost, visibleDocNames }) => {
+ const paneBActivityHost = activityHosts.get('docs/c');
+ return (
+ <>
+ <div
+ data-testid="activity-bindings"
+ data-hosts={[...activityHosts.keys()].join(',')}
+ data-visible={[...visibleDocNames].join(',')}
+ data-parking={String(parkingHost !== null)}
+ />
+ {portaledPaneBody && paneBActivityHost
+ ? createPortal(portaledPaneBody, paneBActivityHost)
+ : null}
+ </>
+ );
+ }}
+ />,
+ );
+}
+
+function latestDndProps() {
+ type MockDragEvent = {
+ active: {
+ data: { current: unknown };
+ rect?: { current: { translated: DOMRect | null } };
+ };
+ delta?: { x: number; y: number };
+ over: { data: { current: unknown }; rect?: DOMRect } | null;
+ };
+ return dndProps as {
+ accessibility?: {
+ container?: HTMLElement;
+ screenReaderInstructions?: { draggable?: string };
+ announcements?: {
+ onDragStart?: (event: { active: { data: { current: unknown } } }) => string | undefined;
+ onDragOver?: (event: {
+ active: { data: { current: unknown } };
+ over: { data: { current: unknown } } | null;
+ }) => string | undefined;
+ };
+ };
+ modifiers?: unknown[];
+ onDragStart?: (event: { active: { data: { current: unknown } } }) => void;
+ onDragMove?: (event: MockDragEvent) => void;
+ onDragOver?: (event: MockDragEvent) => void;
+ onDragEnd?: (event: MockDragEvent) => void;
+ onDragCancel?: () => void;
+ };
+}
+
+function tabDrag(paneId: string, tabId: string) {
+ return {
+ kind: 'editor-tab' as const,
+ paneId,
+ tabId,
+ splittable: true,
+ label: tabId,
+ };
+}
+
+describe('EditorWorkspace', () => {
+ beforeEach(() => {
+ panes = multiPaneFixture.map((pane) => ({ ...pane }));
+ tabSessionLoaded = true;
+ dndProps = {};
+ dragOverlayProps = {};
+ layoutChange = undefined;
+ layoutChanged = undefined;
+ overDroppableId = null;
+ droppableData.clear();
+ document.body.removeAttribute('data-editor-tab-dragging');
+ for (const mock of [
+ focusPane,
+ moveTabToPane,
+ openTarget,
+ openTargetInPane,
+ reorderTabsInPane,
+ resizePanes,
+ splitTab,
+ setLayout,
+ ]) {
+ mock.mockClear();
+ }
+ splitTab.mockReturnValue('pane-new');
+ });
+
+ afterEach(() => {
+ cleanup();
+ });
+
+ test('renders one flat horizontal panel per pane with stable resize selectors', () => {
+ const { container } = renderWorkspace();
+
+ expect(screen.getByTestId('workspace-panel-group').dataset.orientation).toBe('horizontal');
+ expect(container.querySelector('[data-editor-workspace]')).toBeTruthy();
+ expect(container.querySelector('[data-editor-workspace-canvas]')).toBeTruthy();
+ expect(container.querySelectorAll('[data-editor-pane-id="pane-a"]')).not.toHaveLength(0);
+ expect(container.querySelectorAll('[data-editor-pane-id="pane-b"]')).not.toHaveLength(0);
+ expect(
+ container
+ .querySelector('[data-panel-id="editor-pane:pane-a"]')
+ ?.getAttribute('data-min-size'),
+ ).toBe('300px');
+ expect(screen.getAllByTestId('pane-resize-handle')).toHaveLength(1);
+ expect(screen.getByTestId('pane-resize-handle').dataset.editorPaneBefore).toBe('pane-a');
+ expect(screen.getByTestId('pane-resize-handle').dataset.editorPaneAfter).toBe('pane-b');
+ const header = screen.getByTestId('main-editor-header');
+ expect(header.querySelector('[data-editor-pane-tabs="pane-a"]')).toBeTruthy();
+ expect(header.querySelector('[data-editor-pane-tabs="pane-b"]')).toBeTruthy();
+ expect(
+ header
+ .querySelector('[data-editor-pane-tabs="pane-a"]')
+ ?.parentElement?.getAttribute('data-editor-pane-focused'),
+ ).toBe('true');
+ const focusedTabGroup = header.querySelector<HTMLElement>(
+ '[data-editor-pane-tab-group="pane-a"]',
+ );
+ const unfocusedTabGroup = header.querySelector<HTMLElement>(
+ '[data-editor-pane-tab-group="pane-b"]',
+ );
+ expectVisualClassTokensAbsent(focusedTabGroup?.className ?? '', ['after:bg-primary']);
+ expectVisualClassTokensAbsent(unfocusedTabGroup?.className ?? '', ['after:bg-primary']);
+ const firstPane = container.querySelector('[data-editor-pane-id="pane-a"]');
+ const secondPane = container.querySelector('[data-editor-pane-id="pane-b"]');
+ expect(firstPane?.querySelector('[data-editor-pane-tabs]')).toBeNull();
+ expect(secondPane?.querySelector('[data-editor-pane-tabs]')).toBeNull();
+ expect(screen.getByRole('region', { name: 'pane 1' })).toBe(firstPane);
+ expect(firstPane?.getAttribute('aria-label')).toBe('pane 1');
+ expect(firstPane?.getAttribute('aria-current')).toBe('true');
+ expect(secondPane?.getAttribute('aria-label')).toBe('pane 2');
+ expect(secondPane?.getAttribute('aria-current')).toBeNull();
+ });
+
+ test('does not paint a temporary desktop pane layout before session restore settles', () => {
+ const previousDesktopBridge = window.okDesktop;
+ Object.defineProperty(window, 'okDesktop', {
+ configurable: true,
+ writable: true,
+ value: { config: { mode: 'editor' } },
+ });
+ tabSessionLoaded = false;
+
+ const view = renderWorkspace();
+
+ expect(screen.getByTestId('main-editor-header').children).toHaveLength(0);
+ expect(view.container.querySelector('[data-editor-workspace-pending]')).toBeTruthy();
+ expect(view.container.querySelector('[data-editor-pane-id]')).toBeNull();
+
+ tabSessionLoaded = true;
+ view.rerender(
+ <EditorWorkspace
+ renderHeader={(tabs) => <header data-testid="main-editor-header">{tabs}</header>}
+ renderPane={({ pane }) => <div data-testid={`pane-body-${pane.id}`} />}
+ />,
+ );
+
+ expect(view.container.querySelector('[data-editor-workspace-pending]')).toBeNull();
+ expect(view.container.querySelector('[data-editor-pane-id="pane-a"]')).toBeTruthy();
+ Object.defineProperty(window, 'okDesktop', {
+ configurable: true,
+ writable: true,
+ value: previousDesktopBridge,
+ });
+ });
+
+ test('keeps header tab groups on the pane canvas geometry and scroll position', () => {
+ const { container } = renderWorkspace();
+ const workspace = container.querySelector<HTMLElement>('[data-editor-workspace]');
+ const headerCanvas = container.querySelector<HTMLElement>('[data-editor-header-tab-canvas]');
+ const headerGroups = [
+ ...container.querySelectorAll<HTMLElement>('[data-editor-pane-tab-group]'),
+ ];
+
+ expect(headerCanvas).toBeTruthy();
+ expect(headerCanvas?.classList.contains('min-w-(--editor-workspace-min-width)')).toBe(true);
+ expect(headerCanvas?.style.getPropertyValue('--editor-workspace-min-width')).toBe(
+ 'max(100%, 600px)',
+ );
+ expect(headerGroups).toHaveLength(2);
+ expect(headerGroups[0]?.classList.contains('basis-0')).toBe(true);
+ expect(headerGroups[0]?.style.flexGrow).toBe('60');
+ expect(headerGroups[1]?.classList.contains('basis-0')).toBe(true);
+ expect(headerGroups[1]?.style.flexGrow).toBe('40');
+ expect(container.querySelectorAll('[data-editor-header-pane-separator]')).toHaveLength(1);
+ expect(headerGroups[0]?.querySelector('[data-reserve-leading-chrome="true"]')).toBeTruthy();
+ expect(headerGroups[1]?.querySelector('[data-reserve-trailing-chrome="true"]')).toBeTruthy();
+
+ if (!workspace || !headerCanvas) throw new Error('Expected workspace and header canvas');
+ workspace.scrollLeft = 96;
+ fireEvent.scroll(workspace);
+ expect(headerCanvas.style.transform).toBe('translateX(-96px)');
+ });
+
+ test('resizes header tab groups continuously before persisting the panel layout', () => {
+ const { container } = renderWorkspace();
+ const headerGroups = [
+ ...container.querySelectorAll<HTMLElement>('[data-editor-pane-tab-group]'),
+ ];
+
+ act(() => layoutChange?.({ 'editor-pane:pane-a': 72, 'editor-pane:pane-b': 28 }));
+
+ expect(headerGroups[0]?.style.flexGrow).toBe('72');
+ expect(headerGroups[1]?.style.flexGrow).toBe('28');
+ expect(resizePanes).not.toHaveBeenCalled();
+
+ act(() =>
+ layoutChanged?.(
+ { 'editor-pane:pane-a': 72, 'editor-pane:pane-b': 28 },
+ { isUserInteraction: true },
+ ),
+ );
+ expect(resizePanes).toHaveBeenCalledWith(
+ new Map([
+ ['pane-a', 72],
+ ['pane-b', 28],
+ ]),
+ );
+ });
+
+ test('omits the focused tab-strip accent in single-pane mode', () => {
+ panes = [
+ {
+ id: 'pane-a',
+ openTabs: ['docs/a'],
+ pinnedTabIds: [],
+ activeTabId: 'docs/a',
+ newTabIds: [],
+ activeNewTabId: null,
+ activeTarget: { kind: 'doc', target: 'docs/a', docName: 'docs/a' },
+ size: 100,
+ },
+ ];
+
+ const { container } = renderWorkspace();
+ const pane = container.querySelector('[data-editor-pane-id="pane-a"]');
+ const tabGroup = container.querySelector<HTMLElement>('[data-editor-pane-tab-group="pane-a"]');
+
+ expect(pane?.getAttribute('aria-current')).toBe('true');
+ expect(pane?.getAttribute('data-editor-pane-focused')).toBe('true');
+ expectVisualClassTokensAbsent(tabGroup?.className ?? '', ['after:bg-primary']);
+ });
+
+ test('keeps a dragged tab visible outside the clipped header until the drag ends', () => {
+ renderWorkspace();
+ const active = tabDrag('pane-a', 'docs/b');
+
+ expect(screen.queryByTestId('editor-tab-drag-overlay')).toBeNull();
+ act(() => latestDndProps().onDragStart?.({ active: { data: { current: active } } }));
+ const overlay = screen.getByTestId('editor-tab-drag-overlay');
+ expect(overlay.textContent).toBe('docs/b');
+ expect(overlay.className).toContain('w-44');
+ expect(overlay.className).toContain('cursor-grabbing');
+ expect(dragOverlayProps.dropAnimation).toBeNull();
+ expect(document.body.hasAttribute('data-editor-tab-dragging')).toBe(true);
+
+ act(() =>
+ latestDndProps().onDragEnd?.({
+ active: { data: { current: active } },
+ over: null,
+ }),
+ );
+ expect(screen.queryByTestId('editor-tab-drag-overlay')).toBeNull();
+ expect(document.body.hasAttribute('data-editor-tab-dragging')).toBe(false);
+ expect(moveTabToPane).not.toHaveBeenCalled();
+ expect(reorderTabsInPane).not.toHaveBeenCalled();
+ expect(splitTab).not.toHaveBeenCalled();
+ });
+
+ test('moves a primary insertion boundary without moving the tab row', () => {
+ const { container } = renderWorkspace();
+ const active = tabDrag('pane-a', 'docs/b');
+
+ act(() => latestDndProps().onDragStart?.({ active: { data: { current: active } } }));
+ act(() =>
+ latestDndProps().onDragMove?.({
+ active: {
+ data: { current: active },
+ rect: { current: { translated: { left: 180, width: 40 } as DOMRect } },
+ },
+ over: {
+ data: { current: tabDrag('pane-b', 'docs/c') },
+ rect: { left: 100, width: 100 } as DOMRect,
+ },
+ }),
+ );
+
+ expect(
+ container
+ .querySelector('[data-editor-pane-tabs="pane-b"]')
+ ?.getAttribute('data-drop-indicator-index'),
+ ).toBe('1');
+ expect(
+ container
+ .querySelector('[data-editor-pane-tabs="pane-a"]')
+ ?.getAttribute('data-drop-indicator-index'),
+ ).toBeNull();
+
+ act(() => latestDndProps().onDragCancel?.());
+ expect(container.querySelector('[data-drop-indicator-index]')).toBeNull();
+ });
+
+ test('shows the separator before an earlier tab as soon as a leftward drag enters it', () => {
+ const { container } = renderWorkspace();
+ const active = tabDrag('pane-a', 'docs/b');
+
+ act(() => latestDndProps().onDragStart?.({ active: { data: { current: active } } }));
+ act(() =>
+ latestDndProps().onDragMove?.({
+ active: {
+ data: { current: active },
+ rect: { current: { translated: { left: 80, width: 40 } as DOMRect } },
+ },
+ delta: { x: -2, y: 0 },
+ over: {
+ data: { current: tabDrag('pane-a', 'docs/a') },
+ rect: { left: 0, width: 100 } as DOMRect,
+ },
+ }),
+ );
+
+ expect(
+ container
+ .querySelector('[data-editor-pane-tabs="pane-a"]')
+ ?.getAttribute('data-drop-indicator-index'),
+ ).toBe('0');
+ });
+
+ test('hides separators for no-op boundaries around the dragged tab', () => {
+ const { container } = renderWorkspace();
+ const active = tabDrag('pane-a', 'docs/b');
+
+ act(() => latestDndProps().onDragStart?.({ active: { data: { current: active } } }));
+ for (const x of [-2, 2]) {
+ act(() =>
+ latestDndProps().onDragMove?.({
+ active: {
+ data: { current: active },
+ rect: { current: { translated: { left: 100 + x, width: 100 } as DOMRect } },
+ },
+ delta: { x, y: 0 },
+ over: {
+ data: { current: active },
+ rect: { left: 100, width: 100 } as DOMRect,
+ },
+ }),
+ );
+ expect(container.querySelector('[data-drop-indicator-index]')).toBeNull();
+ }
+
+ act(() =>
+ latestDndProps().onDragEnd?.({
+ active: { data: { current: active } },
+ delta: { x: 2, y: 0 },
+ over: { data: { current: active } },
+ }),
+ );
+ expect(reorderTabsInPane).not.toHaveBeenCalled();
+ });
+
+ test('exposes visible document hosts and one hidden parking mount', async () => {
+ const { container } = renderWorkspace();
+ await act(async () => {});
+
+ expect(
+ container
+ .querySelector('[data-editor-activity-mount="pane-a"]')
+ ?.getAttribute('data-doc-name'),
+ ).toBe('docs/a');
+ expect(
+ container
+ .querySelector('[data-editor-activity-mount="pane-b"]')
+ ?.getAttribute('data-doc-name'),
+ ).toBe('docs/c');
+ expect(container.querySelectorAll('[data-editor-activity-parking]')).toHaveLength(1);
+ expect(screen.getByTestId('activity-bindings').dataset.visible).toBe('docs/a,docs/c');
+ });
+
+ test('focuses a pane from pointer and keyboard focus capture', () => {
+ const { container } = renderWorkspace();
+ const pane = container.querySelector<HTMLElement>('[data-editor-pane-id="pane-b"]');
+ const activityMount = container.querySelector<HTMLElement>(
+ '[data-editor-activity-mount="pane-b"]',
+ );
+ expect(pane).toBeTruthy();
+ expect(activityMount).toBeTruthy();
+
+ fireEvent.pointerDown(pane as HTMLElement);
+ fireEvent.focusIn(pane as HTMLElement);
+ expect(focusPane).toHaveBeenCalledTimes(2);
+
+ focusPane.mockClear();
+ fireEvent.pointerDown(activityMount as HTMLElement);
+
+ expect(focusPane).toHaveBeenCalled();
+ expect(focusPane).toHaveBeenLastCalledWith('pane-b');
+ });
+
+ test('accepts a sidebar file before its drag payload is readable and opens it on drop', () => {
+ panes = [
+ multiPaneFixture[0],
+ {
+ ...multiPaneFixture[1],
+ activeTabId: null,
+ newTabIds: ['new-tab:1'],
+ activeNewTabId: 'new-tab:1',
+ activeTarget: null,
+ },
+ ];
+ const { container } = renderWorkspace();
+ const pane = container.querySelector<HTMLElement>('[data-editor-pane-id="pane-b"]');
+ let payloadReadable = false;
+ const dataTransfer = {
+ types: [OK_SIDEBAR_DRAG_MIME],
+ getData: (type: string) =>
+ type === OK_SIDEBAR_DRAG_MIME && payloadReadable
+ ? serializeSidebarDragPayload({
+ v: 1,
+ kind: 'doc',
+ docName: 'notes/Dragged',
+ size: null,
+ })
+ : '',
+ dropEffect: 'none',
+ };
+
+ fireEvent.dragOver(pane as HTMLElement, { dataTransfer });
+ expect(pane?.getAttribute('data-sidebar-drop-active')).toBe('true');
+ expect(dataTransfer.dropEffect).toBe('copy');
+ expectVisualClassTokens(pane?.className ?? '', [
+ 'after:bg-primary/5',
+ 'after:ring-2',
+ 'after:ring-primary/70',
+ 'after:ring-inset',
+ ]);
+ expectVisualClassTokensAbsent(pane?.className ?? '', [
+ 'after:border-muted-foreground/35',
+ 'after:bg-muted/15',
+ ]);
+
+ payloadReadable = true;
+ fireEvent.drop(pane as HTMLElement, { dataTransfer });
+
+ expect(openTargetInPane).toHaveBeenCalledWith(
+ 'pane-b',
+ { kind: 'doc', target: 'notes/Dragged', docName: 'notes/Dragged' },
+ { disposition: 'permanent', consumeActiveNewTab: true },
+ );
+ expect(pane?.getAttribute('data-sidebar-drop-active')).toBeNull();
+ });
+
+ test('captures a sidebar drop from portaled editor DOM before the editor consumes it', () => {
+ const consumeDrop = vi.fn((event: Event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ });
+ const { container } = renderWorkspace(<div data-testid="portaled-pane-body" />);
+ const portaledPaneBody = screen.getByTestId('portaled-pane-body');
+ portaledPaneBody.addEventListener('drop', consumeDrop);
+ const dataTransfer = {
+ types: [OK_SIDEBAR_DRAG_MIME],
+ getData: (type: string) =>
+ type === OK_SIDEBAR_DRAG_MIME
+ ? serializeSidebarDragPayload({
+ v: 1,
+ kind: 'doc',
+ docName: 'notes/Nested',
+ size: null,
+ })
+ : '',
+ dropEffect: 'none',
+ };
+
+ expect(portaledPaneBody.closest('[data-editor-activity-mount="pane-b"]')).not.toBeNull();
+ fireEvent.drop(portaledPaneBody, { dataTransfer });
+
+ expect(openTargetInPane).toHaveBeenCalledTimes(1);
+ expect(openTargetInPane).toHaveBeenCalledWith(
+ 'pane-b',
+ { kind: 'doc', target: 'notes/Nested', docName: 'notes/Nested' },
+ { disposition: 'permanent', consumeActiveNewTab: false },
+ );
+ expect(consumeDrop).not.toHaveBeenCalled();
+ expect(
+ container
+ .querySelector('[data-editor-pane-id="pane-b"]')
+ ?.getAttribute('data-sidebar-drop-active'),
+ ).toBeNull();
+ portaledPaneBody.removeEventListener('drop', consumeDrop);
+ });
+
+ test('clears the sidebar preview without consuming a malformed custom drop', () => {
+ const { container } = renderWorkspace();
+ const pane = container.querySelector<HTMLElement>('[data-editor-pane-id="pane-b"]');
+ const nestedPaneBody = screen.getByTestId('pane-body-pane-b');
+ const nestedDrop = vi.fn();
+ nestedPaneBody.addEventListener('drop', nestedDrop);
+ const dataTransfer = {
+ types: [OK_SIDEBAR_DRAG_MIME],
+ getData: () => '{',
+ dropEffect: 'none',
+ };
+
+ fireEvent.dragOver(nestedPaneBody, { dataTransfer });
+ expect(pane?.getAttribute('data-sidebar-drop-active')).toBe('true');
+
+ fireEvent.drop(nestedPaneBody, { dataTransfer });
+
+ expect(nestedDrop).toHaveBeenCalledTimes(1);
+ expect(openTarget).not.toHaveBeenCalled();
+ expect(pane?.getAttribute('data-sidebar-drop-active')).toBeNull();
+
+ nestedPaneBody.removeEventListener('drop', nestedDrop);
+ });
+
+ test('clears the sidebar preview when the source drag ends outside the pane', () => {
+ const { container } = renderWorkspace();
+ const pane = container.querySelector<HTMLElement>('[data-editor-pane-id="pane-b"]');
+ const dataTransfer = {
+ types: [OK_SIDEBAR_DRAG_MIME],
+ getData: () => '',
+ dropEffect: 'none',
+ };
+
+ fireEvent.dragOver(pane as HTMLElement, { dataTransfer });
+ expect(pane?.getAttribute('data-sidebar-drop-active')).toBe('true');
+
+ fireEvent.dragEnd(window);
+
+ expect(pane?.getAttribute('data-sidebar-drop-active')).toBeNull();
+ expectVisualClassTokensAbsent(pane?.className ?? '', [
+ 'after:bg-primary/5',
+ 'after:ring-2',
+ 'after:ring-primary/70',
+ 'after:ring-inset',
+ ]);
+ });
+
+ test('prioritizes edge splits and clears the preview after drop', () => {
+ const { container, rerender } = renderWorkspace();
+ const active = tabDrag('pane-a', 'docs/b');
+
+ act(() => latestDndProps().onDragStart?.({ active: { data: { current: active } } }));
+ overDroppableId = 'editor-pane-edge:pane-b:right';
+ rerender(
+ <EditorWorkspace
+ renderHeader={(tabs) => <header data-testid="main-editor-header">{tabs}</header>}
+ renderPane={({ pane }) => <div data-testid={`pane-body-${pane.id}`} />}
+ />,
+ );
+
+ expect(
+ container
+ .querySelector('[data-pane-edge="right"][data-editor-pane-id="pane-b"]')
+ ?.getAttribute('data-pane-drop-side'),
+ ).toBe('right');
+ const highlightedEdge = container.querySelector(
+ '[data-pane-edge="right"][data-editor-pane-id="pane-b"]',
+ );
+ expect(highlightedEdge?.textContent).toBe('');
+ expect(highlightedEdge?.querySelector('svg')).toBeNull();
+
+ act(() =>
+ latestDndProps().onDragEnd?.({
+ active: { data: { current: active } },
+ over: {
+ data: {
+ current: { kind: 'pane-edge', paneId: 'pane-b', side: 'right' },
+ },
+ },
+ }),
+ );
+
+ expect(splitTab).toHaveBeenCalledWith('docs/b', 'pane-b', 'right');
+ expect(
+ container
+ .querySelector('[data-pane-edge="right"][data-editor-pane-id="pane-b"]')
+ ?.getAttribute('data-pane-drop-side'),
+ ).toBeNull();
+ });
+
+ test('shows one monolithic split highlight across an internal pane boundary', () => {
+ const { container, rerender } = renderWorkspace();
+ const active = tabDrag('pane-a', 'docs/b');
+ const boundary = () => container.querySelector<HTMLElement>('[data-pane-boundary-drop]');
+
+ act(() => latestDndProps().onDragStart?.({ active: { data: { current: active } } }));
+ overDroppableId = 'editor-pane-edge:pane-a:right';
+ rerender(
+ <EditorWorkspace
+ renderHeader={(tabs) => <header data-testid="main-editor-header">{tabs}</header>}
+ renderPane={({ pane }) => <div data-testid={`pane-body-${pane.id}`} />}
+ />,
+ );
+
+ expect(container.querySelectorAll('[data-pane-drop-side]')).toHaveLength(1);
+ expect(boundary()?.getAttribute('data-pane-drop-side')).toBe('right');
+ expectVisualClassTokens(boundary()?.className ?? '', [
+ 'w-24',
+ '-translate-x-1/2',
+ 'bg-primary/15',
+ 'ring-primary',
+ ]);
+ expect(boundary()?.textContent).toBe('');
+ expect(boundary()?.querySelector('svg')).toBeNull();
+
+ overDroppableId = 'editor-pane-edge:pane-b:left';
+ rerender(
+ <EditorWorkspace
+ renderHeader={(tabs) => <header data-testid="main-editor-header">{tabs}</header>}
+ renderPane={({ pane }) => <div data-testid={`pane-body-${pane.id}`} />}
+ />,
+ );
+
+ expect(container.querySelectorAll('[data-pane-drop-side]')).toHaveLength(1);
+ expect(boundary()?.getAttribute('data-pane-drop-side')).toBe('left');
+ expectVisualClassTokensAbsent(boundary()?.className ?? '', ['transition-opacity']);
+ });
+
+ test('lets a blank tab drag to a pane edge and participate in combined tab order', () => {
+ panes = [
+ {
+ ...multiPaneFixture[0],
+ newTabIds: ['new-tab:1'],
+ activeNewTabId: 'new-tab:1',
+ activeTabId: null,
+ activeTarget: null,
+ },
+ multiPaneFixture[1],
+ ];
+ renderWorkspace();
+ const active = tabDrag('pane-a', 'new-tab:1');
+
+ act(() =>
+ latestDndProps().onDragEnd?.({
+ active: { data: { current: active } },
+ over: {
+ data: {
+ current: { kind: 'pane-edge', paneId: 'pane-b', side: 'left' },
+ },
+ },
+ }),
+ );
+
+ expect(splitTab).toHaveBeenCalledWith('new-tab:1', 'pane-b', 'left');
+
+ act(() =>
+ latestDndProps().onDragEnd?.({
+ active: { data: { current: active } },
+ over: { data: { current: tabDrag('pane-a', 'docs/a') } },
+ }),
+ );
+ expect(reorderTabsInPane).toHaveBeenCalledWith(
+ 'pane-a',
+ ['new-tab:1', 'docs/a', 'docs/b'],
+ 'new-tab:1',
+ );
+ });
+
+ test('moves across panes, reorders in one strip, and ignores cancellation', () => {
+ renderWorkspace();
+
+ act(() =>
+ latestDndProps().onDragEnd?.({
+ active: { data: { current: tabDrag('pane-a', 'docs/b') } },
+ over: { data: { current: tabDrag('pane-b', 'docs/c') } },
+ }),
+ );
+ expect(moveTabToPane).toHaveBeenCalledWith('docs/b', 'pane-b', 0);
+
+ act(() =>
+ latestDndProps().onDragEnd?.({
+ active: { data: { current: tabDrag('pane-a', 'docs/b') } },
+ over: { data: { current: tabDrag('pane-a', 'docs/a') } },
+ }),
+ );
+ expect(reorderTabsInPane).toHaveBeenCalledWith('pane-a', ['docs/b', 'docs/a'], 'docs/b');
+
+ latestDndProps().onDragCancel?.();
+ expect(splitTab).not.toHaveBeenCalled();
+ });
+
+ test('persists only user-authored pane resize layouts', () => {
+ renderWorkspace();
+
+ act(() => {
+ layoutChanged?.(
+ { 'editor-pane:pane-a': 45, 'editor-pane:pane-b': 55 },
+ { isUserInteraction: false },
+ );
+ });
+ expect(resizePanes).not.toHaveBeenCalled();
+
+ act(() => {
+ layoutChanged?.(
+ { 'editor-pane:pane-a': 45, 'editor-pane:pane-b': 55 },
+ { isUserInteraction: true },
+ );
+ });
+ expect(resizePanes).toHaveBeenCalledWith(
+ new Map([
+ ['pane-a', 45],
+ ['pane-b', 55],
+ ]),
+ );
+ });
+
+ test('portals dnd accessibility output to document.body', () => {
+ renderWorkspace();
+ const accessibility = latestDndProps().accessibility;
+ expect(accessibility?.container).toBe(document.body);
+ expect(accessibility?.screenReaderInstructions?.draggable).toContain('Shift+F10');
+ expect(accessibility?.screenReaderInstructions?.draggable).toContain('Menu key');
+ expect(accessibility?.screenReaderInstructions?.draggable).toContain('close');
+ expect(accessibility?.screenReaderInstructions?.draggable).toContain('pin');
+ expect(
+ accessibility?.announcements?.onDragStart?.({
+ active: { data: { current: tabDrag('pane-a', 'docs/a') } },
+ }),
+ ).toBe('Picked up docs/a from pane 1.');
+ expect(
+ accessibility?.announcements?.onDragOver?.({
+ active: { data: { current: tabDrag('pane-a', 'docs/a') } },
+ over: {
+ data: { current: { kind: 'pane-edge', paneId: 'pane-b', side: 'right' } },
+ },
+ }),
+ ).toBe('docs/a is over a new pane to the right of pane 2.');
+ });
+});
diff --git a/packages/app/src/components/EditorWorkspace.tsx b/packages/app/src/components/EditorWorkspace.tsx
new file mode 100644
index 000000000..fe859004a
--- /dev/null
+++ b/packages/app/src/components/EditorWorkspace.tsx
@@ -0,0 +1,788 @@
+import {
+ DndContext,
+ type DragEndEvent,
+ DragOverlay,
+ type DragStartEvent,
+ KeyboardSensor,
+ PointerSensor,
+ useDroppable,
+ useSensor,
+ useSensors,
+} from '@dnd-kit/core';
+import { arrayMove, sortableKeyboardCoordinates } from '@dnd-kit/sortable';
+import { useLingui } from '@lingui/react/macro';
+import {
+ type CSSProperties,
+ Fragment,
+ type ReactNode,
+ type UIEvent,
+ useEffect,
+ useEffectEvent,
+ useLayoutEffect,
+ useRef,
+ useState,
+} from 'react';
+import { docNameForNavigationTarget } from '@/components/navigation-targets';
+import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from '@/components/ui/resizable';
+import { useDocumentContext } from '@/editor/DocumentContext';
+import type { EditorPaneState, PaneSide } from '@/editor/editor-panes';
+import { openSidebarDropPayload } from '@/editor/sidebar-drop';
+import { hasSidebarDragType, parseSidebarDragPayload } from '@/lib/sidebar-drag';
+import { useSingleFileMode } from '@/lib/single-file-mode';
+import { cn } from '@/lib/utils';
+import { EditorTabs } from './EditorTabs';
+import {
+ type EditorTabDragData,
+ editorWorkspaceCollisionDetection,
+ findEditorTabElement,
+ isEditorTabDragData,
+ isEditorTabDropData,
+ TAB_KEYBOARD_DRAG_CODES,
+} from './editor-tabs-chrome';
+
+const MIN_EDITOR_PANE_WIDTH = 300;
+
+export interface EditorWorkspaceActivityBindings {
+ activityHosts: ReadonlyMap<string, HTMLElement>;
+ parkingHost: HTMLElement | null;
+ visibleDocNames: ReadonlySet<string>;
+}
+
+export interface EditorWorkspacePaneRenderContext {
+ pane: EditorPaneState;
+ isFocused: boolean;
+ activityDocName: string | null;
+ activityMount: ReactNode;
+}
+
+interface EditorWorkspaceProps {
+ renderHeader: (tabs: ReactNode) => ReactNode;
+ renderPane: (context: EditorWorkspacePaneRenderContext) => ReactNode;
+ renderActivityPool?: (bindings: EditorWorkspaceActivityBindings) => ReactNode;
+}
+
+interface TabDropPlacement {
+ indicatorIndex: number;
+ pane: EditorPaneState;
+ targetIndex: number;
+ targetOrder: readonly string[];
+}
+
+type TabDropEvent = Pick<DragEndEvent, 'active' | 'over'> & Partial<Pick<DragEndEvent, 'delta'>>;
+
+function activityDocNameForPane(pane: EditorPaneState): string | null {
+ if (pane.activeTarget?.kind === 'large-file') return null;
+ return pane.activeTarget ? docNameForNavigationTarget(pane.activeTarget) : null;
+}
+
+function PaneStripDropTarget({
+ children,
+ index,
+ isFocused,
+ paneId,
+ size,
+}: {
+ children: ReactNode;
+ index: number;
+ isFocused: boolean;
+ paneId: string;
+ size: number;
+}) {
+ const { setNodeRef } = useDroppable({
+ id: `editor-pane-strip:${paneId}`,
+ data: { kind: 'pane-strip', paneId, index },
+ });
+ return (
+ <div
+ ref={setNodeRef}
+ data-editor-pane-tab-group={paneId}
+ data-editor-pane-focused={isFocused || undefined}
+ className="relative h-full min-w-0 shrink basis-0"
+ style={{ flexGrow: size }}
+ >
+ {children}
+ </div>
+ );
+}
+
+function PaneEdgeDropTarget({
+ drag,
+ paneId,
+ side,
+}: {
+ drag: EditorTabDragData | null;
+ paneId: string;
+ side: PaneSide;
+}) {
+ const { isOver, setNodeRef } = useDroppable({
+ id: `editor-pane-edge:${paneId}:${side}`,
+ data: { kind: 'pane-edge', paneId, side },
+ disabled: drag?.splittable !== true,
+ });
+ return (
+ <div
+ ref={setNodeRef}
+ aria-hidden="true"
+ data-pane-edge={side}
+ data-editor-pane-id={paneId}
+ data-pane-drop-side={isOver ? side : undefined}
+ className={cn(
+ 'pointer-events-none absolute inset-y-0 z-30 w-12 opacity-0',
+ side === 'left' ? 'left-0' : 'right-0',
+ isOver && 'bg-primary/15 opacity-100 ring-2 ring-primary ring-inset',
+ )}
+ />
+ );
+}
+
+function PaneBoundaryDropTarget({
+ drag,
+ leftPaneId,
+ rightPaneId,
+}: {
+ drag: EditorTabDragData | null;
+ leftPaneId: string;
+ rightPaneId: string;
+}) {
+ const { isOver: isLeftHalfOver, setNodeRef: setLeftHalfNodeRef } = useDroppable({
+ id: `editor-pane-edge:${leftPaneId}:right`,
+ data: { kind: 'pane-edge', paneId: leftPaneId, side: 'right' },
+ disabled: drag?.splittable !== true,
+ });
+ const { isOver: isRightHalfOver, setNodeRef: setRightHalfNodeRef } = useDroppable({
+ id: `editor-pane-edge:${rightPaneId}:left`,
+ data: { kind: 'pane-edge', paneId: rightPaneId, side: 'left' },
+ disabled: drag?.splittable !== true,
+ });
+ const side = isLeftHalfOver ? 'right' : isRightHalfOver ? 'left' : null;
+
+ return (
+ <>
+ <div
+ ref={setLeftHalfNodeRef}
+ aria-hidden="true"
+ data-pane-edge="right"
+ data-pane-edge-pane-id={leftPaneId}
+ className="pointer-events-none absolute inset-y-0 right-1/2 w-12"
+ />
+ <div
+ ref={setRightHalfNodeRef}
+ aria-hidden="true"
+ data-pane-edge="left"
+ data-pane-edge-pane-id={rightPaneId}
+ className="pointer-events-none absolute inset-y-0 left-1/2 w-12"
+ />
+ <div
+ aria-hidden="true"
+ data-pane-boundary-drop=""
+ data-pane-boundary-left={leftPaneId}
+ data-pane-boundary-right={rightPaneId}
+ data-pane-drop-side={side ?? undefined}
+ className={cn(
+ 'pointer-events-none absolute inset-y-0 left-1/2 z-30 w-24 -translate-x-1/2 opacity-0',
+ side && 'bg-primary/15 opacity-100 ring-2 ring-primary ring-inset',
+ )}
+ />
+ </>
+ );
+}
+
+function PaneActivityMount({
+ docName,
+ onActivityMount,
+ onPaneFocus,
+ paneId,
+}: {
+ docName: string;
+ onActivityMount: (paneId: string, element: HTMLElement | null) => void;
+ onPaneFocus: (paneId: string) => void;
+ paneId: string;
+}) {
+ const activityMountRef = useRef<HTMLDivElement>(null);
+ const notifyActivityMount = useEffectEvent(onActivityMount);
+ const notifyPaneFocus = useEffectEvent(onPaneFocus);
+
+ useLayoutEffect(() => {
+ const mount = activityMountRef.current;
+ if (!mount) return;
+ const focus = () => notifyPaneFocus(paneId);
+ mount.addEventListener('pointerdown', focus, true);
+ mount.addEventListener('focusin', focus, true);
+ notifyActivityMount(paneId, mount);
+ return () => {
+ mount.removeEventListener('pointerdown', focus, true);
+ mount.removeEventListener('focusin', focus, true);
+ notifyActivityMount(paneId, null);
+ };
+ }, [paneId]);
+
+ return (
+ <div
+ ref={activityMountRef}
+ data-editor-activity-mount={paneId}
+ data-doc-name={docName}
+ className="absolute inset-0"
+ />
+ );
+}
+
+function WorkspacePane({
+ drag,
+ isFocused,
+ label,
+ onActivityMount,
+ pane,
+ renderPane,
+ showOuterLeftDropTarget = false,
+ showOuterRightDropTarget = false,
+ showDropTargets = true,
+}: {
+ drag: EditorTabDragData | null;
+ isFocused: boolean;
+ label: string;
+ onActivityMount: (paneId: string, element: HTMLElement | null) => void;
+ pane: EditorPaneState;
+ renderPane: EditorWorkspaceProps['renderPane'];
+ showOuterLeftDropTarget?: boolean;
+ showOuterRightDropTarget?: boolean;
+ showDropTargets?: boolean;
+}) {
+ const { focusPane, openTargetInPane } = useDocumentContext();
+ const [sidebarDropActive, setSidebarDropActive] = useState(false);
+ const paneRef = useRef<HTMLElement | null>(null);
+ const activityDocName = activityDocNameForPane(pane);
+
+ useLayoutEffect(() => {
+ const element = paneRef.current;
+ if (!element) return;
+
+ const handleSidebarDragOver = (event: DragEvent) => {
+ if (!hasSidebarDragType(event.dataTransfer)) return;
+ event.preventDefault();
+ if (event.dataTransfer) event.dataTransfer.dropEffect = 'copy';
+ setSidebarDropActive(true);
+ };
+ const handleSidebarDragLeave = (event: DragEvent) => {
+ const relatedTarget = event.relatedTarget;
+ if (relatedTarget instanceof Node && element.contains(relatedTarget)) return;
+ setSidebarDropActive(false);
+ };
+ const clearSidebarDropActive = () => setSidebarDropActive(false);
+ const handleSidebarDrop = (event: DragEvent) => {
+ setSidebarDropActive(false);
+ const payload = parseSidebarDragPayload(event.dataTransfer);
+ if (!payload) return;
+ event.preventDefault();
+ event.stopPropagation();
+ openSidebarDropPayload(
+ payload,
+ (target, options) => openTargetInPane(pane.id, target, options),
+ pane.activeNewTabId !== null,
+ );
+ };
+
+ element.addEventListener('dragover', handleSidebarDragOver, true);
+ element.addEventListener('dragleave', handleSidebarDragLeave, true);
+ element.addEventListener('drop', handleSidebarDrop, true);
+ window.addEventListener('drop', clearSidebarDropActive, true);
+ window.addEventListener('dragend', clearSidebarDropActive, true);
+ return () => {
+ element.removeEventListener('dragover', handleSidebarDragOver, true);
+ element.removeEventListener('dragleave', handleSidebarDragLeave, true);
+ element.removeEventListener('drop', handleSidebarDrop, true);
+ window.removeEventListener('drop', clearSidebarDropActive, true);
+ window.removeEventListener('dragend', clearSidebarDropActive, true);
+ };
+ }, [openTargetInPane, pane.activeNewTabId, pane.id]);
+
+ return (
+ <section
+ ref={paneRef}
+ aria-current={isFocused ? 'true' : undefined}
+ aria-label={label}
+ data-editor-pane-id={pane.id}
+ data-editor-pane-focused={isFocused || undefined}
+ data-sidebar-drop-active={sidebarDropActive || undefined}
+ className={cn(
+ 'relative flex h-full min-h-0 min-w-0 flex-col bg-background',
+ sidebarDropActive &&
+ 'after:pointer-events-none after:absolute after:inset-2 after:z-20 after:rounded-lg after:bg-primary/5 after:ring-2 after:ring-primary/70 after:ring-inset',
+ )}
+ onPointerDownCapture={() => focusPane(pane.id)}
+ onFocusCapture={() => focusPane(pane.id)}
+ >
+ <div className="relative min-h-0 flex-1">
+ {renderPane({
+ pane,
+ isFocused,
+ activityDocName,
+ activityMount: activityDocName ? (
+ <PaneActivityMount
+ docName={activityDocName}
+ onActivityMount={onActivityMount}
+ onPaneFocus={focusPane}
+ paneId={pane.id}
+ />
+ ) : null,
+ })}
+ </div>
+ {showDropTargets && showOuterLeftDropTarget ? (
+ <PaneEdgeDropTarget drag={drag} paneId={pane.id} side="left" />
+ ) : null}
+ {showDropTargets && showOuterRightDropTarget ? (
+ <PaneEdgeDropTarget drag={drag} paneId={pane.id} side="right" />
+ ) : null}
+ </section>
+ );
+}
+
+export function EditorWorkspace({
+ renderActivityPool,
+ renderHeader,
+ renderPane,
+}: EditorWorkspaceProps) {
+ const { t } = useLingui();
+ const {
+ focusPane,
+ focusedPaneId,
+ moveTabToPane,
+ panes,
+ reorderTabsInPane,
+ resizePanes,
+ splitTab,
+ tabSessionLoaded,
+ visibleTabIdsByPane,
+ } = useDocumentContext();
+ const singleFile = useSingleFileMode();
+ const desktopSessionRestorePending =
+ !singleFile &&
+ !tabSessionLoaded &&
+ typeof window !== 'undefined' &&
+ window.okDesktop?.config.mode === 'editor';
+ const [drag, setDrag] = useState<EditorTabDragData | null>(null);
+ const [dropIndicator, setDropIndicator] = useState<{
+ index: number;
+ paneId: string;
+ } | null>(null);
+ const [activityMounts, setActivityMounts] = useState<ReadonlyMap<string, HTMLElement>>(
+ () => new Map(),
+ );
+ const [parkingHost, setParkingHost] = useState<HTMLElement | null>(null);
+ const focusFrameRef = useRef<number | null>(null);
+ const headerCanvasRef = useRef<HTMLDivElement>(null);
+ const paneKey = panes.map((pane) => pane.id).join('\u0000');
+ const savedLayout = Object.fromEntries(
+ panes.map((pane) => [`editor-pane:${pane.id}`, pane.size]),
+ );
+ const visibleDocNames = new Set<string>();
+ const activityHosts = new Map<string, HTMLElement>();
+ for (const pane of panes) {
+ const docName = activityDocNameForPane(pane);
+ if (!docName) continue;
+ visibleDocNames.add(docName);
+ const mount = activityMounts.get(pane.id);
+ if (mount) activityHosts.set(docName, mount);
+ }
+ const sensors = useSensors(
+ useSensor(PointerSensor, { activationConstraint: { distance: 8 } }),
+ useSensor(KeyboardSensor, {
+ coordinateGetter: sortableKeyboardCoordinates,
+ keyboardCodes: TAB_KEYBOARD_DRAG_CODES,
+ }),
+ );
+ const canvasStyle = {
+ '--editor-workspace-min-width': `max(100%, ${panes.length * MIN_EDITOR_PANE_WIDTH}px)`,
+ } as CSSProperties;
+
+ useEffect(() => {
+ return () => {
+ if (focusFrameRef.current !== null) cancelAnimationFrame(focusFrameRef.current);
+ };
+ }, []);
+
+ useEffect(() => {
+ if (!drag) return;
+ document.body.setAttribute('data-editor-tab-dragging', '');
+ return () => document.body.removeAttribute('data-editor-tab-dragging');
+ }, [drag]);
+
+ if (desktopSessionRestorePending) {
+ return (
+ <>
+ {renderHeader(null)}
+ <div data-editor-workspace-pending="" className="min-h-0 flex-1 bg-background" />
+ </>
+ );
+ }
+
+ function registerActivityMount(paneId: string, element: HTMLElement | null) {
+ setActivityMounts((current) => {
+ const prior = current.get(paneId);
+ if (prior === element) return current;
+ const next = new Map(current);
+ if (element) next.set(paneId, element);
+ else next.delete(paneId);
+ return next;
+ });
+ }
+
+ function requestTabFocus(paneId: string, tabId: string) {
+ if (focusFrameRef.current !== null) cancelAnimationFrame(focusFrameRef.current);
+ focusFrameRef.current = requestAnimationFrame(() => {
+ focusFrameRef.current = null;
+ findEditorTabElement(document, paneId, tabId)?.focus();
+ });
+ }
+
+ function visibleOrderForPane(pane: EditorPaneState): readonly string[] {
+ return visibleTabIdsByPane.get(pane.id) ?? [...pane.openTabs, ...pane.newTabIds];
+ }
+
+ function moveOrReorderTab(
+ active: EditorTabDragData,
+ targetPane: EditorPaneState,
+ targetIndex: number,
+ targetOrder?: readonly string[],
+ ) {
+ if (active.paneId !== targetPane.id) {
+ moveTabToPane(active.tabId, targetPane.id, targetIndex);
+ requestTabFocus(targetPane.id, active.tabId);
+ return;
+ }
+ if (!targetOrder) return;
+ const fromIndex = targetOrder.indexOf(active.tabId);
+ if (fromIndex < 0 || fromIndex === targetIndex) return;
+ reorderTabsInPane(
+ targetPane.id,
+ arrayMove([...targetOrder], fromIndex, targetIndex),
+ active.tabId,
+ );
+ }
+
+ function resolveTabDropPlacement(
+ event: TabDropEvent,
+ active: EditorTabDragData,
+ ): TabDropPlacement | null {
+ const overData = event.over?.data.current;
+ let paneId: string;
+ let indicatorIndex: number;
+
+ if (isEditorTabDragData(overData)) {
+ paneId = overData.paneId;
+ const targetPane = panes.find((pane) => pane.id === paneId);
+ if (!targetPane) return null;
+ const targetOrder = visibleOrderForPane(targetPane);
+ const overIndex = targetOrder.indexOf(overData.tabId);
+ if (overIndex < 0) return null;
+
+ const activeIndex = active.paneId === paneId ? targetOrder.indexOf(active.tabId) : -1;
+ const horizontalDelta = event.delta?.x ?? 0;
+ const activeRect = event.active.rect?.current.translated;
+ const overRect = event.over?.rect;
+ let afterHoveredTab: boolean;
+ if (activeIndex >= 0 && activeIndex !== overIndex) {
+ afterHoveredTab = activeIndex < overIndex;
+ } else if (activeIndex === overIndex && horizontalDelta !== 0) {
+ afterHoveredTab = horizontalDelta > 0;
+ } else {
+ afterHoveredTab =
+ activeRect !== null &&
+ activeRect !== undefined &&
+ overRect !== undefined &&
+ activeRect.left + activeRect.width / 2 > overRect.left + overRect.width / 2;
+ }
+ indicatorIndex = overIndex + (afterHoveredTab ? 1 : 0);
+ } else if (isEditorTabDropData(overData) && overData.kind === 'pane-strip') {
+ paneId = overData.paneId;
+ indicatorIndex = overData.index;
+ } else {
+ return null;
+ }
+
+ const pane = panes.find((candidate) => candidate.id === paneId);
+ if (!pane) return null;
+ const targetOrder = visibleOrderForPane(pane);
+ const boundedIndicatorIndex = Math.min(Math.max(indicatorIndex, 0), targetOrder.length);
+ const fromIndex = active.paneId === pane.id ? targetOrder.indexOf(active.tabId) : -1;
+ const targetIndex =
+ fromIndex >= 0 && boundedIndicatorIndex > fromIndex
+ ? boundedIndicatorIndex - 1
+ : boundedIndicatorIndex;
+ if (fromIndex >= 0 && targetIndex === fromIndex) return null;
+
+ return {
+ indicatorIndex: boundedIndicatorIndex,
+ pane,
+ targetIndex,
+ targetOrder,
+ };
+ }
+
+ function updateDropIndicator(event: TabDropEvent) {
+ const active = event.active.data.current;
+ const placement = isEditorTabDragData(active) ? resolveTabDropPlacement(event, active) : null;
+ const next = placement ? { index: placement.indicatorIndex, paneId: placement.pane.id } : null;
+ setDropIndicator((current) =>
+ current?.paneId === next?.paneId && current?.index === next?.index ? current : next,
+ );
+ }
+
+ function handleDragStart(event: DragStartEvent) {
+ const nextDrag = event.active.data.current;
+ if (!isEditorTabDragData(nextDrag)) return;
+ setDropIndicator(null);
+ setDrag(nextDrag);
+ focusPane(nextDrag.paneId);
+ }
+
+ function handleDragEnd(event: DragEndEvent) {
+ const active = event.active.data.current;
+ const over = event.over?.data.current;
+ const placement = isEditorTabDragData(active) ? resolveTabDropPlacement(event, active) : null;
+ setDropIndicator(null);
+ setDrag(null);
+ if (!isEditorTabDragData(active)) return;
+
+ if (placement) {
+ moveOrReorderTab(active, placement.pane, placement.targetIndex, placement.targetOrder);
+ return;
+ }
+
+ if (!isEditorTabDropData(over)) return;
+
+ if (over.kind === 'pane-edge') {
+ if (!active.splittable) return;
+ const newPaneId = splitTab(active.tabId, over.paneId, over.side);
+ if (newPaneId) requestTabFocus(newPaneId, active.tabId);
+ return;
+ }
+ }
+
+ function syncHeaderScroll(event: UIEvent<HTMLDivElement>) {
+ headerCanvasRef.current?.style.setProperty(
+ 'transform',
+ `translateX(-${event.currentTarget.scrollLeft}px)`,
+ );
+ }
+
+ function syncHeaderLayout(layout: Record<string, number>) {
+ const groups = headerCanvasRef.current?.querySelectorAll<HTMLElement>(
+ '[data-editor-pane-tab-group]',
+ );
+ groups?.forEach((group) => {
+ const paneId = group.dataset.editorPaneTabGroup;
+ const size = paneId ? layout[`editor-pane:${paneId}`] : undefined;
+ if (size !== undefined) group.style.setProperty('flex-grow', String(size));
+ });
+ }
+
+ function paneLabel(paneId: string): string {
+ const position = panes.findIndex((pane) => pane.id === paneId);
+ return position < 0 ? t`editor pane` : t`pane ${position + 1}`;
+ }
+
+ function dragDestinationDescription(data: unknown): string | null {
+ if (isEditorTabDragData(data)) return paneLabel(data.paneId);
+ if (!isEditorTabDropData(data)) return null;
+ if (data.kind === 'pane-edge') {
+ if (data.side === 'left') {
+ return t`a new pane to the left of ${paneLabel(data.paneId)}`;
+ }
+ return t`a new pane to the right of ${paneLabel(data.paneId)}`;
+ }
+ return paneLabel(data.paneId);
+ }
+
+ const paneGroup = (
+ <ResizablePanelGroup
+ key={paneKey}
+ id="editor-workspace-panes"
+ orientation="horizontal"
+ defaultLayout={savedLayout}
+ onLayoutChange={syncHeaderLayout}
+ onLayoutChanged={(layout, meta) => {
+ if (!meta.isUserInteraction) return;
+ resizePanes(
+ new Map(panes.map((pane) => [pane.id, layout[`editor-pane:${pane.id}`] ?? pane.size])),
+ );
+ }}
+ >
+ {panes.map((pane, index) => (
+ <Fragment key={pane.id}>
+ {index > 0 ? (
+ <ResizableHandle
+ withHandle
+ data-editor-pane-resize-handle=""
+ data-editor-pane-before={panes[index - 1]?.id}
+ data-editor-pane-after={pane.id}
+ >
+ <PaneBoundaryDropTarget
+ drag={drag}
+ leftPaneId={panes[index - 1]?.id ?? pane.id}
+ rightPaneId={pane.id}
+ />
+ </ResizableHandle>
+ ) : null}
+ <ResizablePanel
+ id={`editor-pane:${pane.id}`}
+ defaultSize={`${pane.size}%`}
+ minSize={`${MIN_EDITOR_PANE_WIDTH}px`}
+ >
+ <WorkspacePane
+ drag={drag}
+ isFocused={pane.id === focusedPaneId}
+ label={paneLabel(pane.id)}
+ onActivityMount={registerActivityMount}
+ pane={pane}
+ renderPane={renderPane}
+ showOuterLeftDropTarget={index === 0}
+ showOuterRightDropTarget={index === panes.length - 1}
+ />
+ </ResizablePanel>
+ </Fragment>
+ ))}
+ </ResizablePanelGroup>
+ );
+ const headerTabs = (
+ <div data-editor-header-tab-groups="" className="h-full min-w-0 flex-1 overflow-hidden">
+ <div
+ ref={headerCanvasRef}
+ data-editor-header-tab-canvas=""
+ className="flex h-full min-w-(--editor-workspace-min-width)"
+ style={canvasStyle}
+ >
+ {panes.map((pane, index) => (
+ <Fragment key={pane.id}>
+ {index > 0 ? (
+ <div
+ aria-hidden="true"
+ data-editor-header-pane-separator=""
+ className="w-px shrink-0 bg-border"
+ />
+ ) : null}
+ <PaneStripDropTarget
+ paneId={pane.id}
+ index={visibleOrderForPane(pane).length}
+ isFocused={pane.id === focusedPaneId}
+ size={pane.size}
+ >
+ <EditorTabs
+ dropIndicatorIndex={dropIndicator?.paneId === pane.id ? dropIndicator.index : null}
+ paneId={pane.id}
+ onSplitComplete={requestTabFocus}
+ reserveLeadingChrome={index === 0}
+ reserveTrailingChrome={index === panes.length - 1}
+ />
+ </PaneStripDropTarget>
+ </Fragment>
+ ))}
+ </div>
+ </div>
+ );
+
+ if (singleFile) {
+ const pane = panes.find((candidate) => candidate.id === focusedPaneId) ?? panes[0];
+ return (
+ <>
+ {renderHeader(null)}
+ <div data-editor-workspace="" className="relative min-h-0 flex-1 overflow-hidden">
+ {pane ? (
+ <WorkspacePane
+ drag={null}
+ isFocused
+ label={paneLabel(pane.id)}
+ onActivityMount={registerActivityMount}
+ pane={pane}
+ renderPane={renderPane}
+ showDropTargets={false}
+ />
+ ) : null}
+ <div ref={setParkingHost} data-editor-activity-parking="" className="hidden" inert />
+ {parkingHost !== null
+ ? renderActivityPool?.({ activityHosts, parkingHost, visibleDocNames })
+ : null}
+ </div>
+ </>
+ );
+ }
+
+ return (
+ <DndContext
+ sensors={sensors}
+ autoScroll={false}
+ collisionDetection={editorWorkspaceCollisionDetection}
+ onDragStart={handleDragStart}
+ onDragMove={updateDropIndicator}
+ onDragOver={updateDropIndicator}
+ onDragEnd={handleDragEnd}
+ onDragCancel={() => {
+ setDropIndicator(null);
+ setDrag(null);
+ }}
+ accessibility={{
+ container: typeof document !== 'undefined' ? document.body : undefined,
+ screenReaderInstructions: {
+ draggable: t`Press Space to pick up a tab. Use the arrow keys to move it within a tab strip, then press Space or Enter to drop it. Press Shift+F10 or the Menu key to open the tab context menu for split, close, pin, and other tab actions.`,
+ },
+ announcements: {
+ onDragStart: ({ active }) => {
+ const data = active.data.current;
+ return isEditorTabDragData(data)
+ ? t`Picked up ${data.label} from ${paneLabel(data.paneId)}.`
+ : undefined;
+ },
+ onDragOver: ({ active, over }) => {
+ const activeData = active.data.current;
+ if (!isEditorTabDragData(activeData) || !over) return undefined;
+ const destination = dragDestinationDescription(over.data.current);
+ return destination ? t`${activeData.label} is over ${destination}.` : undefined;
+ },
+ onDragEnd: ({ active, over }) => {
+ const activeData = active.data.current;
+ if (!isEditorTabDragData(activeData)) return undefined;
+ const destination = over ? dragDestinationDescription(over.data.current) : null;
+ return destination
+ ? t`Moved ${activeData.label} to ${destination}.`
+ : t`${activeData.label} was not moved.`;
+ },
+ onDragCancel: ({ active }) => {
+ const activeData = active.data.current;
+ return isEditorTabDragData(activeData)
+ ? t`Cancelled moving ${activeData.label}.`
+ : undefined;
+ },
+ },
+ }}
+ >
+ {renderHeader(headerTabs)}
+ <div
+ data-editor-workspace=""
+ className="relative min-h-0 flex-1 overflow-x-auto overflow-y-hidden"
+ onScroll={syncHeaderScroll}
+ >
+ <div
+ data-editor-workspace-canvas=""
+ className="h-full min-w-[var(--editor-workspace-min-width)]"
+ style={canvasStyle}
+ >
+ {paneGroup}
+ </div>
+ <div ref={setParkingHost} data-editor-activity-parking="" className="hidden" inert />
+ {parkingHost !== null
+ ? renderActivityPool?.({ activityHosts, parkingHost, visibleDocNames })
+ : null}
+ </div>
+ <DragOverlay dropAnimation={null}>
+ {drag ? (
+ <div
+ aria-hidden="true"
+ data-testid="editor-tab-drag-overlay"
+ className="pointer-events-none flex h-10 w-44 max-w-[calc(100vw-2rem)] cursor-grabbing items-center overflow-hidden rounded-md border border-border bg-background px-3 font-medium text-[13px] text-foreground shadow-lg"
+ >
+ <span className="min-w-0 truncate">{drag.label}</span>
+ </div>
+ ) : null}
+ </DragOverlay>
+ </DndContext>
+ );
+}
diff --git a/packages/app/src/components/FileSidebar.tsx b/packages/app/src/components/FileSidebar.tsx
index 8edd6d4ab..d57a88a83 100644
--- a/packages/app/src/components/FileSidebar.tsx
+++ b/packages/app/src/components/FileSidebar.tsx
@@ -287,7 +287,7 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
tree.createFromTemplate(request.template.folder, request.template.name);
return;
}
- tree.startCreating('file', dir);
+ tree.startCreating(request.kind ?? 'file', dir);
});
}, [tree]);
const hasFolders = folderState.folderCount > 0;
diff --git a/packages/app/src/components/FileTargetMenuItems.dom.test.tsx b/packages/app/src/components/FileTargetMenuItems.dom.test.tsx
new file mode 100644
index 000000000..394c17517
--- /dev/null
+++ b/packages/app/src/components/FileTargetMenuItems.dom.test.tsx
@@ -0,0 +1,117 @@
+import * as actualLinguiMacro from '@lingui/react/macro';
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { FileTargetMenuItems, type FileTargetMenuPrimitives } from './FileTargetMenuItems';
+
+vi.doMock('@lingui/react/macro', () => ({
+ ...actualLinguiMacro,
+ Trans: ({ children }: { children?: ReactNode }) => <>{children}</>,
+}));
+
+function Container({ children }: { children?: ReactNode }) {
+ return <>{children}</>;
+}
+
+function Item({
+ children,
+ disabled,
+ onSelect,
+ ...props
+}: {
+ children?: ReactNode;
+ disabled?: boolean;
+ onSelect?: () => void;
+ [key: string]: unknown;
+}) {
+ return (
+ <button type="button" role="menuitem" disabled={disabled} onClick={onSelect} {...props}>
+ {children}
+ </button>
+ );
+}
+
+const primitives = {
+ Group: Container,
+ Item,
+ Separator: () => <hr />,
+ Sub: Container,
+ SubContent: Container,
+ SubTrigger: Item,
+} satisfies FileTargetMenuPrimitives;
+
+afterEach(cleanup);
+
+describe('FileTargetMenuItems', () => {
+ test('keeps the shared target action catalog and callbacks together', () => {
+ const onDuplicate = vi.fn();
+ const onRename = vi.fn();
+ const onDelete = vi.fn();
+ render(
+ <div role="menu">
+ <FileTargetMenuItems
+ primitives={primitives}
+ workspaceReady
+ openWithAi={<Item>Open with AI</Item>}
+ share={{ onSelect: () => {} }}
+ onCopyFullPath={() => {}}
+ onCopyRelativePath={() => {}}
+ onImportTemplate={() => {}}
+ onDuplicate={onDuplicate}
+ onRename={onRename}
+ hide={{ label: 'Hide this file', onSelect: () => {} }}
+ onDelete={onDelete}
+ />
+ </div>,
+ );
+
+ for (const label of [
+ 'Open with AI',
+ 'Share',
+ 'Copy path',
+ 'Import as template',
+ 'Duplicate',
+ 'Rename',
+ 'Hide this file',
+ 'Delete',
+ ]) {
+ expect(screen.getByRole('menuitem', { name: label })).toBeTruthy();
+ }
+
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Duplicate' }));
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Rename' }));
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Delete' }));
+ expect(onDuplicate).toHaveBeenCalledTimes(1);
+ expect(onRename).toHaveBeenCalledTimes(1);
+ expect(onDelete).toHaveBeenCalledTimes(1);
+ });
+
+ test('adds folder creation and tree actions without changing the target action component', () => {
+ render(
+ <div role="menu">
+ <FileTargetMenuItems
+ primitives={primitives}
+ workspaceReady
+ folderCreate={{
+ onNewFile: () => {},
+ onNewFolder: () => {},
+ templateItems: <Item>Starter template</Item>,
+ }}
+ folderTree={{ onExpandAll: () => {}, onCollapseAll: () => {} }}
+ onCopyFullPath={() => {}}
+ onCopyRelativePath={() => {}}
+ />
+ </div>,
+ );
+
+ for (const label of [
+ 'New file',
+ 'New from template',
+ 'New folder',
+ 'Expand all',
+ 'Collapse all',
+ ]) {
+ expect(screen.getByRole('menuitem', { name: label })).toBeTruthy();
+ }
+ });
+});
diff --git a/packages/app/src/components/FileTargetMenuItems.tsx b/packages/app/src/components/FileTargetMenuItems.tsx
new file mode 100644
index 000000000..c5951ad23
--- /dev/null
+++ b/packages/app/src/components/FileTargetMenuItems.tsx
@@ -0,0 +1,264 @@
+import { Trans } from '@lingui/react/macro';
+import {
+ Copy,
+ CopyPlus,
+ EyeOff,
+ FileKey,
+ FilePlus,
+ FolderOpen,
+ FolderPlus,
+ FoldVertical,
+ Pencil,
+ Share2,
+ SquarePen,
+ Trash2,
+ UnfoldVertical,
+} from 'lucide-react';
+import type { ComponentType, ReactNode } from 'react';
+
+interface MenuItemProps {
+ children?: ReactNode;
+ disabled?: boolean;
+ onSelect?: () => void;
+ variant?: 'default' | 'destructive';
+ 'aria-label'?: string;
+ 'data-testid'?: string;
+}
+
+interface MenuContainerProps {
+ children?: ReactNode;
+ className?: string;
+}
+
+function MenuGroupFallback({ children }: MenuContainerProps) {
+ return children;
+}
+
+export interface FileTargetMenuPrimitives {
+ Group?: ComponentType<MenuContainerProps>;
+ Item: ComponentType<MenuItemProps>;
+ Separator: ComponentType;
+ Sub: ComponentType<MenuContainerProps>;
+ SubContent: ComponentType<MenuContainerProps>;
+ SubTrigger: ComponentType<MenuItemProps>;
+}
+
+interface RevealAction {
+ label: ReactNode;
+ ariaLabel?: string;
+ disabled?: boolean;
+ hint?: ReactNode;
+ onSelect: () => void;
+}
+
+interface FolderCreateActions {
+ onNewFile: () => void;
+ onNewFolder: () => void;
+ templateItems?: ReactNode;
+}
+
+interface FolderTreeActions {
+ onExpandAll?: () => void;
+ onCollapseAll?: () => void;
+}
+
+interface HideAction {
+ label: ReactNode;
+ disabled?: boolean;
+ onSelect: () => void;
+}
+
+export interface FileTargetMenuItemsProps {
+ busy?: boolean;
+ deleteLabel?: ReactNode;
+ folderCreate?: FolderCreateActions;
+ folderTree?: FolderTreeActions;
+ hide?: HideAction;
+ openWithAi?: ReactNode;
+ primitives: FileTargetMenuPrimitives;
+ reveal?: RevealAction;
+ share?: { onSelect: () => void };
+ onCopyFullPath: () => void;
+ onCopyRelativePath: () => void;
+ onDelete?: () => void;
+ onDuplicate?: () => void;
+ onImportTemplate?: (deleteSource: boolean) => void;
+ onRename?: () => void;
+ workspaceReady: boolean;
+}
+
+/**
+ * Target actions shared by file-tree rows and editor tabs. Callers supply the
+ * matching Radix primitive family so one action definition can live inside a
+ * DropdownMenu or ContextMenu without detaching keyboard navigation.
+ */
+export function FileTargetMenuItems({
+ busy = false,
+ deleteLabel,
+ folderCreate,
+ folderTree,
+ hide,
+ openWithAi,
+ primitives,
+ reveal,
+ share,
+ onCopyFullPath,
+ onCopyRelativePath,
+ onDelete,
+ onDuplicate,
+ onImportTemplate,
+ onRename,
+ workspaceReady,
+}: FileTargetMenuItemsProps) {
+ const { Item, Separator, Sub, SubContent, SubTrigger } = primitives;
+ const Group = primitives.Group ?? MenuGroupFallback;
+ const hasTreeActions = folderTree?.onExpandAll != null || folderTree?.onCollapseAll != null;
+ const hasMutationActions =
+ onImportTemplate != null ||
+ onDuplicate != null ||
+ onRename != null ||
+ hide != null ||
+ onDelete != null;
+
+ return (
+ <>
+ {folderCreate ? (
+ <>
+ <Group>
+ <Item disabled={busy} onSelect={folderCreate.onNewFile}>
+ <SquarePen aria-hidden="true" />
+ <Trans>New file</Trans>
+ </Item>
+ {folderCreate.templateItems ? (
+ <Sub>
+ <SubTrigger disabled={busy}>
+ <FilePlus aria-hidden="true" />
+ <Trans>New from template</Trans>
+ </SubTrigger>
+ <SubContent>
+ <Group>{folderCreate.templateItems}</Group>
+ </SubContent>
+ </Sub>
+ ) : null}
+ <Item disabled={busy} onSelect={folderCreate.onNewFolder}>
+ <FolderPlus aria-hidden="true" />
+ <Trans>New folder</Trans>
+ </Item>
+ </Group>
+ <Separator />
+ </>
+ ) : null}
+
+ <Group>
+ {reveal ? (
+ <Item disabled={reveal.disabled} onSelect={reveal.onSelect} aria-label={reveal.ariaLabel}>
+ <FolderOpen aria-hidden="true" />
+ <span className="flex-1">{reveal.label}</span>
+ {reveal.hint ? (
+ <span aria-hidden="true" className="ml-2 text-muted-foreground text-xs">
+ {reveal.hint}
+ </span>
+ ) : null}
+ </Item>
+ ) : null}
+ {openWithAi}
+ {share ? (
+ <Item data-testid="file-tree-menu-share" onSelect={share.onSelect}>
+ <Share2 aria-hidden="true" />
+ <Trans>Share</Trans>
+ </Item>
+ ) : null}
+ <Sub>
+ <SubTrigger>
+ <Copy aria-hidden="true" />
+ <Trans>Copy path</Trans>
+ </SubTrigger>
+ <SubContent>
+ <Group>
+ <Item disabled={!workspaceReady} onSelect={onCopyFullPath}>
+ <Trans>Full path</Trans>
+ </Item>
+ <Item onSelect={onCopyRelativePath}>
+ <Trans>Relative path</Trans>
+ </Item>
+ </Group>
+ </SubContent>
+ </Sub>
+ </Group>
+
+ {hasTreeActions ? (
+ <>
+ <Separator />
+ <Group>
+ {folderTree?.onExpandAll ? (
+ <Item onSelect={folderTree.onExpandAll}>
+ <UnfoldVertical aria-hidden="true" />
+ <Trans>Expand all</Trans>
+ </Item>
+ ) : null}
+ {folderTree?.onCollapseAll ? (
+ <Item onSelect={folderTree.onCollapseAll}>
+ <FoldVertical aria-hidden="true" />
+ <Trans>Collapse all</Trans>
+ </Item>
+ ) : null}
+ </Group>
+ </>
+ ) : null}
+
+ {hasMutationActions ? (
+ <>
+ <Separator />
+ <Group>
+ {onImportTemplate ? (
+ <Sub>
+ <SubTrigger disabled={busy}>
+ <FileKey aria-hidden="true" />
+ <Trans>Import as template</Trans>
+ </SubTrigger>
+ <SubContent>
+ <Group>
+ <Item disabled={busy} onSelect={() => onImportTemplate(false)}>
+ <Trans>Keep original file</Trans>
+ </Item>
+ <Item disabled={busy} onSelect={() => onImportTemplate(true)}>
+ <Trans>Convert (delete original)</Trans>
+ </Item>
+ </Group>
+ </SubContent>
+ </Sub>
+ ) : null}
+ {onDuplicate ? (
+ <Item disabled={busy} onSelect={onDuplicate}>
+ <CopyPlus aria-hidden="true" />
+ <Trans>Duplicate</Trans>
+ </Item>
+ ) : null}
+ {onRename ? (
+ <Item disabled={busy} onSelect={onRename}>
+ <Pencil aria-hidden="true" />
+ <Trans>Rename</Trans>
+ </Item>
+ ) : null}
+ {hide ? (
+ <Item
+ data-testid="file-tree-menu-hide"
+ disabled={hide.disabled}
+ onSelect={hide.onSelect}
+ >
+ <EyeOff aria-hidden="true" />
+ {hide.label}
+ </Item>
+ ) : null}
+ {onDelete ? (
+ <Item variant="destructive" disabled={busy} onSelect={onDelete}>
+ <Trash2 aria-hidden="true" />
+ {deleteLabel ?? <Trans>Delete</Trans>}
+ </Item>
+ ) : null}
+ </Group>
+ </>
+ ) : null}
+ </>
+ );
+}
diff --git a/packages/app/src/components/FileTargetRenameDialog.dom.test.tsx b/packages/app/src/components/FileTargetRenameDialog.dom.test.tsx
new file mode 100644
index 000000000..7160e9bcb
--- /dev/null
+++ b/packages/app/src/components/FileTargetRenameDialog.dom.test.tsx
@@ -0,0 +1,79 @@
+import * as actualLinguiMacro from '@lingui/react/macro';
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { FileTargetRenameDialog } from './FileTargetRenameDialog';
+
+vi.doMock('@lingui/react/macro', () => ({
+ ...actualLinguiMacro,
+ Trans: ({ children }: { children?: ReactNode }) => <>{children}</>,
+}));
+
+type WindowGlobals = { NodeFilter?: typeof NodeFilter };
+type GlobalWithDomShims = typeof globalThis &
+ WindowGlobals & { window?: WindowGlobals; ResizeObserver?: unknown };
+const globalWithDomShims = globalThis as GlobalWithDomShims;
+if (
+ globalWithDomShims.NodeFilter === undefined &&
+ globalWithDomShims.window?.NodeFilter !== undefined
+) {
+ globalWithDomShims.NodeFilter = globalWithDomShims.window.NodeFilter;
+}
+if (globalWithDomShims.ResizeObserver === undefined) {
+ class NoopResizeObserver {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ globalWithDomShims.ResizeObserver = NoopResizeObserver;
+}
+
+afterEach(cleanup);
+
+describe('FileTargetRenameDialog', () => {
+ test('shows the requested rename form and saves a valid name', () => {
+ const onOpenChange = vi.fn();
+ const onSave = vi.fn();
+ render(
+ <FileTargetRenameDialog
+ currentName="notes.md"
+ open
+ onOpenChange={onOpenChange}
+ onSave={onSave}
+ />,
+ );
+
+ expect(screen.getByRole('dialog')).toBeTruthy();
+ expect(screen.getByRole('heading', { name: 'Rename' })).toBeTruthy();
+ const input = screen.getByRole('textbox', { name: 'Name' });
+ expect((input as HTMLInputElement).value).toBe('notes.md');
+ expect(screen.getByRole('button', { name: 'Cancel' })).toBeTruthy();
+
+ fireEvent.change(input, { target: { value: 'renamed.md' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));
+
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ expect(onSave).toHaveBeenCalledWith('renamed.md');
+ });
+
+ test('keeps save disabled for unchanged or invalid names', () => {
+ render(
+ <FileTargetRenameDialog
+ currentName="notes.md"
+ open
+ onOpenChange={() => {}}
+ onSave={() => {}}
+ />,
+ );
+
+ const input = screen.getByRole('textbox', { name: 'Name' });
+ const save = screen.getByRole('button', { name: 'Save' }) as HTMLButtonElement;
+ expect(save.disabled).toBe(true);
+
+ fireEvent.change(input, { target: { value: 'nested/name.md' } });
+ expect(save.disabled).toBe(true);
+
+ fireEvent.change(input, { target: { value: 'valid.md' } });
+ expect(save.disabled).toBe(false);
+ });
+});
diff --git a/packages/app/src/components/FileTargetRenameDialog.tsx b/packages/app/src/components/FileTargetRenameDialog.tsx
new file mode 100644
index 000000000..97bd6b9e8
--- /dev/null
+++ b/packages/app/src/components/FileTargetRenameDialog.tsx
@@ -0,0 +1,73 @@
+import { Trans } from '@lingui/react/macro';
+import { useState } from 'react';
+import { isValidNodeName } from '@/components/file-tree-operations';
+import { Button } from '@/components/ui/button';
+import {
+ Dialog,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog';
+import { Field, FieldGroup, FieldLabel } from '@/components/ui/field';
+import { Input } from '@/components/ui/input';
+
+interface FileTargetRenameDialogProps {
+ currentName: string;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ onSave: (nextName: string) => void;
+}
+
+export function FileTargetRenameDialog({
+ currentName,
+ open,
+ onOpenChange,
+ onSave,
+}: FileTargetRenameDialogProps) {
+ const [name, setName] = useState(currentName);
+ const normalizedName = name.trim();
+ const canSave = isValidNodeName(normalizedName) && normalizedName !== currentName;
+
+ function handleSubmit(event: React.SubmitEvent<HTMLFormElement>) {
+ event.preventDefault();
+ if (!canSave) return;
+ onOpenChange(false);
+ onSave(normalizedName);
+ }
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent>
+ <form className="flex flex-col gap-6" onSubmit={handleSubmit}>
+ <DialogHeader>
+ <DialogTitle>
+ <Trans>Rename</Trans>
+ </DialogTitle>
+ </DialogHeader>
+ <FieldGroup>
+ <Field>
+ <FieldLabel htmlFor="file-target-rename-name">
+ <Trans>Name</Trans>
+ </FieldLabel>
+ <Input
+ id="file-target-rename-name"
+ autoFocus
+ value={name}
+ onChange={(event) => setName(event.currentTarget.value)}
+ />
+ </Field>
+ </FieldGroup>
+ <DialogFooter>
+ <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
+ <Trans>Cancel</Trans>
+ </Button>
+ <Button type="submit" disabled={!canSave}>
+ <Trans>Save</Trans>
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/packages/app/src/components/FileTree.duplicate.dom.test.tsx b/packages/app/src/components/FileTree.duplicate.dom.test.tsx
index 6d6def3a9..815fd2cfb 100644
--- a/packages/app/src/components/FileTree.duplicate.dom.test.tsx
+++ b/packages/app/src/components/FileTree.duplicate.dom.test.tsx
@@ -516,7 +516,7 @@ describe('FileTree duplicate action runtime behavior', () => {
target: 'notes/source copy',
docName: 'notes/source copy',
},
- { tabBehavior: 'replace-active' },
+ { disposition: 'preview', consumeActiveNewTab: true },
);
await waitFor(() => expect(model.getItem('notes/source copy.mdx')).not.toBeNull());
expect(closeMenuMock).toHaveBeenCalled();
@@ -590,7 +590,7 @@ describe('FileTree duplicate action runtime behavior', () => {
target: 'notes copy',
folderPath: 'notes copy',
},
- { tabBehavior: 'replace-active' },
+ { disposition: 'preview', consumeActiveNewTab: true },
);
await waitFor(() => expect(model.getItem('notes copy/')).not.toBeNull());
expect(toastSuccessMock).toHaveBeenCalledWith('Folder duplicated', {
@@ -1136,7 +1136,7 @@ describe('FileTree duplicate action runtime behavior', () => {
);
});
- test('delete event bus drops .ok targets before any delete side effect', async () => {
+ test('tab delete event opens the sidebar confirmation before any delete side effect', async () => {
renderFileTree();
await screen.findByRole('menuitem', { name: /duplicate/i });
fetchCalls = [];
@@ -1144,22 +1144,17 @@ describe('FileTree duplicate action runtime behavior', () => {
act(() => {
emitFileTreeMenuActionDelete({
kind: 'folder',
- target: '.ok',
- folderPath: '.ok',
+ target: 'notes',
+ folderPath: 'notes',
} satisfies ResolvedNavigationTarget);
});
- await new Promise((resolve) => setTimeout(resolve, 0));
+ await screen.findByTestId('delete-confirmation-dialog');
+ expect(deleteConfirmationProps?.itemName).toBe('notes/');
expect(deletePathCalls()).toHaveLength(0);
- // Same spine stays live for deletable targets — proves the drop above is
- // the .ok gate, not a dead subscription.
- act(() => {
- emitFileTreeMenuActionDelete({
- kind: 'folder',
- target: 'notes',
- folderPath: 'notes',
- } satisfies ResolvedNavigationTarget);
+ await act(async () => {
+ await deleteConfirmationProps?.onDelete?.();
});
await waitFor(() => expect(deletePathCalls()).toHaveLength(1));
@@ -1168,4 +1163,22 @@ describe('FileTree duplicate action runtime behavior', () => {
path: 'notes',
});
});
+
+ test('delete event bus drops .ok targets before opening confirmation', async () => {
+ renderFileTree();
+ await screen.findByRole('menuitem', { name: /duplicate/i });
+ fetchCalls = [];
+
+ act(() => {
+ emitFileTreeMenuActionDelete({
+ kind: 'folder',
+ target: '.ok',
+ folderPath: '.ok',
+ } satisfies ResolvedNavigationTarget);
+ });
+
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(deletePathCalls()).toHaveLength(0);
+ expect(screen.queryByTestId('delete-confirmation-dialog')).toBeNull();
+ });
});
diff --git a/packages/app/src/components/FileTree.preview-tabs.dom.test.tsx b/packages/app/src/components/FileTree.preview-tabs.dom.test.tsx
new file mode 100644
index 000000000..eb97bbc83
--- /dev/null
+++ b/packages/app/src/components/FileTree.preview-tabs.dom.test.tsx
@@ -0,0 +1,331 @@
+import { i18n } from '@lingui/core';
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import type { MouseEventHandler, ReactNode } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+
+i18n.load('en', {});
+i18n.activate('en');
+
+function PassThrough({ children }: { children?: ReactNode }) {
+ return <>{children}</>;
+}
+
+const DOCUMENTS = [
+ {
+ kind: 'document',
+ docName: 'note',
+ docExt: '.md',
+ size: 1,
+ modified: '2026-07-28T00:00:00.000Z',
+ },
+ {
+ kind: 'folder',
+ path: 'docs',
+ size: 0,
+ modified: '2026-07-28T00:00:00.000Z',
+ hasChildren: true,
+ },
+];
+
+let previewTabsEnabled = true;
+const openTargetMock = vi.fn(() => {});
+const notifySidebarFileSelectedMock = vi.fn(() => {});
+
+function jsonResponse(body: unknown): Response {
+ return new Response(JSON.stringify(body), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ });
+}
+
+function makeFetchMock() {
+ return vi.fn(async (input: RequestInfo | URL) => {
+ const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
+ if (url.startsWith('/api/documents')) {
+ return jsonResponse({ documents: DOCUMENTS, truncated: false });
+ }
+ if (url === '/api/workspace') {
+ return jsonResponse({
+ contentDir: '/tmp/open-knowledge',
+ pathSeparator: '/',
+ symlinkResolved: true,
+ });
+ }
+ return jsonResponse({ ok: true });
+ });
+}
+
+class StubItem {
+ expanded = false;
+ selected = false;
+
+ constructor(
+ readonly path: string,
+ private readonly directory: boolean,
+ ) {}
+
+ getPath() {
+ return this.path;
+ }
+
+ isDirectory() {
+ return this.directory;
+ }
+
+ isExpanded() {
+ return this.expanded;
+ }
+
+ expand() {
+ this.expanded = true;
+ }
+
+ collapse() {
+ this.expanded = false;
+ }
+
+ isSelected() {
+ return this.selected;
+ }
+
+ select() {
+ this.selected = true;
+ }
+
+ deselect() {
+ this.selected = false;
+ }
+
+ focus() {}
+}
+
+class StubModel {
+ focusedPath: string | null = null;
+ selectedPaths: string[] = [];
+ items = new Map<string, StubItem>();
+ startRenaming = vi.fn(() => {});
+
+ getFocusedPath() {
+ return this.focusedPath;
+ }
+
+ getFocusedIndex() {
+ return -1;
+ }
+
+ getItemHeight() {
+ return 24;
+ }
+
+ getSelectedPaths() {
+ return this.selectedPaths;
+ }
+
+ getItem(path: string) {
+ return this.items.get(path) ?? null;
+ }
+
+ resetPaths(paths: string[]) {
+ this.items.clear();
+ for (const path of paths) {
+ this.items.set(path, new StubItem(path, path.endsWith('/')));
+ }
+ }
+
+ subscribe() {
+ return () => {};
+ }
+
+ onMutation() {
+ return () => {};
+ }
+
+ isSearchOpen() {
+ return false;
+ }
+
+ add(path: string) {
+ this.items.set(path, new StubItem(path, path.endsWith('/')));
+ }
+
+ move() {}
+
+ remove() {}
+}
+
+const model = new StubModel();
+
+vi.doMock('sonner', () => ({
+ toast: { success: vi.fn(() => {}), error: vi.fn(() => {}) },
+}));
+vi.doMock('next-themes', () => ({
+ useTheme: () => ({ resolvedTheme: 'light' }),
+}));
+vi.doMock('@/editor/DocumentContext', () => ({
+ useDocumentContext: () => ({
+ activeDocName: null,
+ activeTarget: null,
+ closeTabs: vi.fn(() => {}),
+ closeDocument: vi.fn(() => {}),
+ isNewTabActive: false,
+ openTarget: openTargetMock,
+ prewarm: () => {},
+ reconcileLocalRemoval: vi.fn(async () => {}),
+ reconcileLocalRename: vi.fn(async () => {}),
+ setSkillsSidebar: vi.fn(() => {}),
+ }),
+}));
+vi.doMock('@/components/PageListContext', () => ({
+ usePageList: () => ({
+ addPage: vi.fn(() => {}),
+ pageMeta: new Map(),
+ pages: new Set<string>(),
+ }),
+}));
+vi.doMock('./ui/sidebar', () => ({
+ useSidebar: () => ({ notifySidebarFileSelected: notifySidebarFileSelectedMock }),
+}));
+vi.doMock('@/lib/config-provider', () => ({
+ useConfigContext: () => ({
+ okignoreBinding: null,
+ projectLocalBinding: null,
+ merged: {
+ appearance: { sidebar: {} },
+ editor: { previewTabs: previewTabsEnabled },
+ },
+ }),
+}));
+vi.doMock('./handoff/useInstalledAgents', () => ({
+ useInstalledAgents: () => ({ states: {} }),
+}));
+vi.doMock('./handoff/useHandoffDispatch', () => ({
+ buildFolderHandoffInput: () => null,
+ buildHandoffInput: () => null,
+ useHandoffDispatch: () => ({ dispatch: vi.fn(async () => ({ ok: true as const })) }),
+}));
+vi.doMock('./handoff/OpenInAgentContextSubmenu', () => ({
+ OpenInAgentContextSubmenu: () => null,
+}));
+vi.doMock('./sidebar-hover-prewarm', () => ({
+ cancelHoverPrewarm: () => {},
+ scheduleHoverPrewarm: () => {},
+}));
+vi.doMock('@/components/ui/button', () => ({
+ Button: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
+ <button type="button" {...props}>
+ {children}
+ </button>
+ ),
+}));
+vi.doMock('@/components/ui/dialog', () => ({ Dialog: PassThrough }));
+vi.doMock('@/components/ui/dropdown-menu', () => ({
+ DropdownMenu: PassThrough,
+ DropdownMenuContent: PassThrough,
+ DropdownMenuItem: PassThrough,
+ DropdownMenuSeparator: () => <hr />,
+ DropdownMenuSub: PassThrough,
+ DropdownMenuSubContent: PassThrough,
+ DropdownMenuSubTrigger: PassThrough,
+ DropdownMenuTrigger: PassThrough,
+}));
+vi.doMock('@/components/ui/skeleton', () => ({
+ Skeleton: ({ className }: { className?: string }) => <span className={className} />,
+}));
+vi.doMock('@/components/DeleteConfirmationDialog', () => ({
+ DeleteConfirmationDialog: () => null,
+}));
+vi.doMock('@/components/NewItemDialog', () => ({ NewItemDialog: () => null }));
+vi.doMock('@/components/TrashFailureModal', () => ({
+ TrashFailureModal: () => null,
+ coerceTrashFailureReason: (reason: string) => reason,
+}));
+vi.doMock('@/components/use-selection-mirror', () => ({
+ asDirectoryHandle: (item: StubItem | null) => (item?.isDirectory() ? item : null),
+ useSelectionMirror: () => {},
+}));
+vi.doMock('@pierre/trees', () => ({
+ FILE_TREE_TAG_NAME: 'ok-file-tree',
+ themeToTreeStyles: () => ({}),
+}));
+vi.doMock('@pierre/trees/react', () => ({
+ useFileTree: () => ({ model }),
+ FileTree: ({ onClickCapture }: { onClickCapture?: MouseEventHandler<HTMLDivElement> }) => (
+ <div data-testid="fake-pierre-tree" role="tree" onClickCapture={onClickCapture}>
+ <div
+ role="treeitem"
+ data-item-path="note.md"
+ data-item-type="file"
+ aria-selected="false"
+ tabIndex={-1}
+ >
+ note.md
+ </div>
+ <div
+ role="treeitem"
+ data-item-path="docs/"
+ data-item-type="folder"
+ aria-selected="false"
+ tabIndex={-1}
+ >
+ docs/
+ </div>
+ </div>
+ ),
+}));
+
+const { FileTree } = await import('./FileTree');
+
+describe('FileTree preview-tab activation', () => {
+ let consoleWarnSpy: ReturnType<typeof vi.spyOn>;
+
+ beforeEach(() => {
+ previewTabsEnabled = true;
+ model.items.clear();
+ model.selectedPaths = [];
+ openTargetMock.mockClear();
+ notifySidebarFileSelectedMock.mockClear();
+ window.location.hash = '';
+ globalThis.fetch = makeFetchMock() as unknown as typeof fetch;
+ consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ cleanup();
+ consoleWarnSpy.mockRestore();
+ });
+
+ test.each([
+ ['enabled', true, 'preview'],
+ ['disabled', false, 'permanent'],
+ ] as const)('opens document and folder rows as %s tabs without dropping hash or selection notifications', async (_state, enabled, disposition) => {
+ previewTabsEnabled = enabled;
+ render(<FileTree />);
+
+ await screen.findByTestId('fake-pierre-tree');
+ await waitFor(() => expect(model.getItem('docs/')).not.toBeNull());
+
+ fireEvent.click(screen.getByRole('treeitem', { name: 'note.md' }));
+
+ await waitFor(() =>
+ expect(openTargetMock).toHaveBeenNthCalledWith(
+ 1,
+ { kind: 'doc', target: 'note', docName: 'note' },
+ { disposition, consumeActiveNewTab: true },
+ ),
+ );
+ expect(window.location.hash).toBe('#/note');
+ expect(notifySidebarFileSelectedMock).toHaveBeenCalledTimes(1);
+
+ fireEvent.click(screen.getByRole('treeitem', { name: 'docs/' }));
+
+ await waitFor(() =>
+ expect(openTargetMock).toHaveBeenNthCalledWith(
+ 2,
+ { kind: 'folder', target: 'docs', folderPath: 'docs' },
+ { disposition, consumeActiveNewTab: true },
+ ),
+ );
+ expect(window.location.hash).toBe('#/docs/');
+ expect(notifySidebarFileSelectedMock).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/packages/app/src/components/FileTree.share.dom.test.tsx b/packages/app/src/components/FileTree.share.dom.test.tsx
index 65645a148..f74169883 100644
--- a/packages/app/src/components/FileTree.share.dom.test.tsx
+++ b/packages/app/src/components/FileTree.share.dom.test.tsx
@@ -1,7 +1,14 @@
-import { cleanup, render, screen, waitFor } from '@testing-library/react';
+import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
-import type { MouseEventHandler, ReactNode } from 'react';
+import {
+ createElement,
+ type MouseEventHandler,
+ type ReactNode,
+ useLayoutEffect,
+ useRef,
+} from 'react';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { OK_SIDEBAR_DRAG_MIME, parseSidebarDragPayload } from '@/lib/sidebar-drag';
import type { FileEntry } from './file-tree-utils';
// Controls the mocked git-sync hook's hasRemote signal per test.
@@ -316,6 +323,34 @@ vi.doMock('@pierre/trees', () => ({
themeToTreeStyles: () => ({}),
}));
+function PierreTreeDragSurface() {
+ const hostRef = useRef<HTMLElement | null>(null);
+
+ useLayoutEffect(() => {
+ const host = hostRef.current;
+ if (!host) return;
+ const shadow = host.attachShadow({ mode: 'open' });
+ const row = document.createElement('div');
+ row.dataset.itemPath = 'notes/source.mdx';
+ row.dataset.itemType = 'file';
+ row.dataset.testid = 'fake-pierre-tree-row';
+ shadow.append(row);
+
+ function handlePierreDragStart(event: Event) {
+ const dragEvent = event as DragEvent;
+ if (!dragEvent.dataTransfer) return;
+ dragEvent.dataTransfer.effectAllowed = 'move';
+ dragEvent.dataTransfer.dropEffect = 'move';
+ dragEvent.dataTransfer.setData('text/plain', 'notes/source.mdx');
+ }
+
+ row.addEventListener('dragstart', handlePierreDragStart);
+ return () => row.removeEventListener('dragstart', handlePierreDragStart);
+ }, []);
+
+ return createElement('ok-file-tree', { ref: hostRef });
+}
+
vi.doMock('@pierre/trees/react', () => ({
useFileTree: () => ({ model }),
FileTree: ({
@@ -332,15 +367,18 @@ vi.doMock('@pierre/trees/react', () => ({
onMouseMove?: MouseEventHandler<HTMLDivElement>;
onMouseLeave?: MouseEventHandler<HTMLDivElement>;
}) => (
- <div
- data-testid="fake-pierre-tree"
- role="tree"
- onClickCapture={onClickCapture}
- onMouseMove={onMouseMove}
- onMouseLeave={onMouseLeave}
- >
- {renderContextMenu?.(menuItem, { close: closeMenuMock })}
- </div>
+ <>
+ <PierreTreeDragSurface />
+ <div
+ data-testid="fake-pierre-tree"
+ role="tree"
+ onClickCapture={onClickCapture}
+ onMouseMove={onMouseMove}
+ onMouseLeave={onMouseLeave}
+ >
+ {renderContextMenu?.(menuItem, { close: closeMenuMock })}
+ </div>
+ </>
),
}));
@@ -350,6 +388,30 @@ function renderFileTree() {
return render(<FileTree />);
}
+class TestDragEvent extends Event {
+ readonly dataTransfer: DataTransfer;
+
+ constructor(type: string, dataTransfer: DataTransfer) {
+ super(type, { bubbles: true, composed: true });
+ this.dataTransfer = dataTransfer;
+ }
+}
+
+function createTestDataTransfer(): DataTransfer {
+ const values = new Map<string, string>();
+ const types: string[] = [];
+ return {
+ dropEffect: 'none',
+ effectAllowed: 'uninitialized',
+ getData: (type: string) => values.get(type) ?? '',
+ setData: (type: string, value: string) => {
+ values.set(type, value);
+ if (!types.includes(type)) types.push(type);
+ },
+ types,
+ } as DataTransfer;
+}
+
describe('FileTree context-menu Share action', () => {
let consoleLogSpy: ReturnType<typeof vi.spyOn>;
@@ -363,14 +425,44 @@ describe('FileTree context-menu Share action', () => {
runShareActionMock.mockClear();
toastSuccessMock.mockClear();
toastErrorMock.mockClear();
+ vi.stubGlobal('DragEvent', TestDragEvent);
consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
});
afterEach(() => {
cleanup();
+ vi.unstubAllGlobals();
consoleLogSpy.mockRestore();
});
+ test('publishes a pane-compatible sidebar payload after Pierre initializes its row drag', async () => {
+ const { container } = renderFileTree();
+ await screen.findByTestId('fake-pierre-tree');
+ const host = container.querySelector('ok-file-tree');
+ const row = host?.shadowRoot?.querySelector<HTMLElement>(
+ '[data-testid="fake-pierre-tree-row"]',
+ );
+ expect(row).toBeTruthy();
+
+ await waitFor(() => {
+ const probe = createTestDataTransfer();
+ row?.dispatchEvent(new TestDragEvent('dragstart', probe));
+ expect(probe.getData(OK_SIDEBAR_DRAG_MIME)).not.toBe('');
+ });
+
+ const dataTransfer = createTestDataTransfer();
+ act(() => {
+ row?.dispatchEvent(new TestDragEvent('dragstart', dataTransfer));
+ });
+
+ expect(parseSidebarDragPayload(dataTransfer)).toMatchObject({
+ v: 1,
+ kind: 'doc',
+ docName: 'notes/source',
+ });
+ expect(dataTransfer.effectAllowed).toBe('copyMove');
+ });
+
test('a doc row shows Share and dispatches a doc-scope share input', async () => {
const user = userEvent.setup();
renderFileTree();
diff --git a/packages/app/src/components/FileTree.showall-lazy.dom.test.tsx b/packages/app/src/components/FileTree.showall-lazy.dom.test.tsx
index 5069f78d2..63760343d 100644
--- a/packages/app/src/components/FileTree.showall-lazy.dom.test.tsx
+++ b/packages/app/src/components/FileTree.showall-lazy.dom.test.tsx
@@ -468,7 +468,7 @@ describe('FileTree showAll lazy root seed', () => {
assetPath: 'LICENSE',
mediaKind: null,
},
- { tabBehavior: 'replace-active' },
+ { disposition: 'preview', consumeActiveNewTab: true },
),
);
expect(window.location.hash).toBe('#/__asset__/LICENSE');
@@ -518,7 +518,7 @@ describe('FileTree showAll lazy root seed', () => {
target: 'README',
docName: 'README',
},
- { tabBehavior: 'replace-active' },
+ { disposition: 'preview', consumeActiveNewTab: true },
),
);
expect(window.location.hash).toBe('#/README');
@@ -547,7 +547,7 @@ describe('FileTree showAll lazy root seed', () => {
target: 'README',
docName: 'README',
},
- { tabBehavior: 'append' },
+ { disposition: 'permanent', consumeActiveNewTab: true },
),
);
window.location.hash = '';
@@ -575,7 +575,7 @@ describe('FileTree showAll lazy root seed', () => {
target: 'docs',
folderPath: 'docs',
},
- { tabBehavior: 'replace-active' },
+ { disposition: 'preview', consumeActiveNewTab: true },
),
);
expect(window.location.hash).toBe('#/docs/');
diff --git a/packages/app/src/components/FileTree.tsx b/packages/app/src/components/FileTree.tsx
index 416073891..c28e06ef7 100644
--- a/packages/app/src/components/FileTree.tsx
+++ b/packages/app/src/components/FileTree.tsx
@@ -24,24 +24,7 @@ import {
type FileTree as PierreFileTreeModel,
} from '@pierre/trees';
import { FileTree as PierreFileTree, useFileTree } from '@pierre/trees/react';
-import {
- Copy,
- CopyPlus,
- EyeOff,
- FileKey,
- FilePlus,
- FolderOpen,
- FolderPlus,
- FoldVertical,
- Info,
- Pencil,
- RefreshCw,
- Share2,
- SquarePen,
- Trash2,
- TriangleAlert,
- UnfoldVertical,
-} from 'lucide-react';
+import { Info, RefreshCw, TriangleAlert } from 'lucide-react';
import { useTheme } from 'next-themes';
import {
type DragEvent as ReactDragEvent,
@@ -50,6 +33,7 @@ import {
type Ref,
startTransition,
useEffect,
+ useEffectEvent,
useImperativeHandle,
useLayoutEffect,
useRef,
@@ -57,6 +41,10 @@ import {
} from 'react';
import { toast } from 'sonner';
import { DeleteConfirmationDialog } from '@/components/DeleteConfirmationDialog';
+import {
+ FileTargetMenuItems,
+ type FileTargetMenuPrimitives,
+} from '@/components/FileTargetMenuItems';
import { FileTreeFilteredToZeroNotice } from '@/components/FileTreeFilteredToZeroNotice';
import { MARKDOWN_FILE_ICON_VIEWBOX } from '@/components/file-entry-icon';
import {
@@ -106,6 +94,7 @@ import {
applyDeleteToDocuments,
applyDuplicateToDocuments,
applyRenameToDocuments,
+ buildRenamedNodePath,
buildTrashAbsPath,
canonicalizeAssetTargetForDelete,
type FileTreeTarget,
@@ -191,7 +180,7 @@ import {
import { Skeleton } from '@/components/ui/skeleton';
import { asDirectoryHandle, useSelectionMirror } from '@/components/use-selection-mirror';
import { getEditorForDoc } from '@/editor/active-editor';
-import { useDocumentContext } from '@/editor/DocumentContext';
+import { type OpenTargetOptions, useDocumentContext } from '@/editor/DocumentContext';
import { assetTabId, docTabId, folderTabId, remapPathForFolderRenames } from '@/editor/editor-tabs';
import { useConflicts } from '@/hooks/use-conflicts';
import { useFolderConfig } from '@/hooks/use-folder-config';
@@ -207,6 +196,7 @@ import { emitDocumentsChanged } from '@/lib/documents-events';
import {
subscribeToFileTreeMenuActionDelete,
subscribeToFileTreeMenuActionDuplicate,
+ subscribeToFileTreeMenuActionImportTemplate,
subscribeToFileTreeMenuActionRename,
} from '@/lib/file-tree-menu-action-events';
import { importTemplate } from '@/lib/folder-config-api';
@@ -219,7 +209,11 @@ import {
runShareAction,
type ShareTargetInput,
} from '@/lib/share/run-share-action';
-import { OK_SIDEBAR_DRAG_MIME, serializeSidebarDragPayload } from '@/lib/sidebar-drag';
+import {
+ hasSidebarDragType,
+ OK_SIDEBAR_DRAG_MIME,
+ serializeSidebarDragPayload,
+} from '@/lib/sidebar-drag';
import { cn } from '@/lib/utils';
import { getValidationSnapshot, subscribeToValidationStore } from '@/lib/validation-store';
import { joinWorkspacePath } from '@/lib/workspace-paths';
@@ -295,6 +289,55 @@ async function copyToClipboard(text: string, kind: 'full' | 'relative'): Promise
}
}
+function fileTreeTargetFromNavigationTarget(
+ target: ResolvedNavigationTarget,
+ documents: readonly FileEntry[],
+ documentPath: 'doc-name' | 'tree-path' = 'doc-name',
+): FileTreeTarget | null {
+ if (target.kind === 'doc' || target.kind === 'folder-index') {
+ const docEntry = documents.find(
+ (entry): entry is DocumentEntry => isDocumentEntry(entry) && entry.docName === target.docName,
+ );
+ const path =
+ documentPath === 'tree-path'
+ ? docNameToTreePath(target.docName, docEntry?.docExt)
+ : target.docName;
+ return {
+ kind: 'file',
+ path,
+ name: path.split('/').pop() ?? path,
+ docExt: docEntry?.docExt,
+ };
+ }
+ if (target.kind === 'folder') {
+ return {
+ kind: 'folder',
+ path: target.folderPath,
+ name: target.folderPath.split('/').pop() ?? target.folderPath,
+ };
+ }
+ if (target.kind === 'asset') {
+ return {
+ kind: 'asset',
+ path: target.assetPath,
+ name: target.assetPath.split('/').pop() ?? target.assetPath,
+ };
+ }
+ return null;
+}
+
+function warnUnsupportedMenuTarget(
+ action: 'delete' | 'duplicate' | 'rename',
+ target: ResolvedNavigationTarget,
+): void {
+ console.warn(
+ JSON.stringify({
+ event: `file-tree-menu-action-${action}-unsupported-kind`,
+ kind: target.kind,
+ }),
+ );
+}
+
// Drop-to-root affordance. The patched `@pierre/trees` sets
// `data-file-tree-root-drag-target="true"` on the virtualized root while an
// in-tree drag hovers empty content area (or a top-level file) — i.e. when the
@@ -436,69 +479,13 @@ function revealInFileManagerLabel(platform: 'darwin' | 'win32' | 'linux'): strin
return t`Open containing folder`;
}
-/**
- * File-tree menu row that opens the OS file manager with the target file/folder
- * selected. Hidden entirely on the web variant (no useful no-op without a host
- * filesystem) — the disabled-with-hint pattern used by `OpenInAgentContextSubmenu`
- * doesn't apply here because reveal has no cross-host fallback. When present but
- * the workspace metadata hasn't resolved yet, renders disabled with a "No workspace"
- * affordance mirroring the handoff submenu's pattern.
- */
-function RevealInFileManagerMenuItem({
- item,
- workspace,
- onClose,
-}: {
- item: ContextMenuItem;
- workspace: WorkspaceInfo | null;
- onClose: () => void;
-}) {
- const { t } = useLingui();
- const bridge = typeof window !== 'undefined' ? window.okDesktop : undefined;
- if (!bridge) return null;
- const platform = bridge.platform;
- const label = revealInFileManagerLabel(platform);
- const hint = !workspace ? t`No workspace` : null;
- // Per-platform aria-label so the catalog entry carries the literal label
- // (e.g. `Reveal in Finder, {hint}`) — `t`${label}, ${hint}`` would extract
- // a context-free `{label}, {hint}` that translators can't render naturally.
- const ariaLabel =
- platform === 'darwin'
- ? hint
- ? t`Reveal in Finder, ${hint}`
- : t`Reveal in Finder`
- : platform === 'win32'
- ? hint
- ? t`Reveal in File Explorer, ${hint}`
- : t`Reveal in File Explorer`
- : hint
- ? t`Open containing folder, ${hint}`
- : t`Open containing folder`;
- return (
- <DropdownMenuItem
- disabled={!workspace}
- onSelect={() => {
- if (!workspace) return;
- onClose();
- const full = joinWorkspacePath(
- workspace.contentDir,
- relativePathForTreeItem(item),
- workspace.pathSeparator,
- );
- void bridge.shell.showItemInFolder(full);
- }}
- aria-label={ariaLabel}
- >
- <FolderOpen aria-hidden="true" />
- <span className="flex-1">{label}</span>
- {hint ? (
- <span aria-hidden="true" className="ml-2 text-muted-foreground text-xs">
- {hint}
- </span>
- ) : null}
- </DropdownMenuItem>
- );
-}
+const DROPDOWN_FILE_TARGET_MENU_PRIMITIVES = {
+ Item: DropdownMenuItem,
+ Separator: DropdownMenuSeparator,
+ Sub: DropdownMenuSub,
+ SubContent: DropdownMenuSubContent,
+ SubTrigger: DropdownMenuSubTrigger,
+} satisfies FileTargetMenuPrimitives;
interface FileTreeMenuProps {
item: ContextMenuItem;
@@ -561,22 +548,12 @@ function FileTreeMenu({
const { t } = useLingui();
const target = treeItemToTarget(item, documents);
const isFolder = item.kind === 'directory';
- // Revealed `.ok` rows are inspect-only: no create/rename/delete/duplicate/
- // hide affordances (creates into `.ok` are server-refused; mutation of
- // OK-managed state belongs to its canonical editors). Path/tree actions
- // (Reveal, Copy path, Expand/Collapse) stay.
const isOkRow = hasOkPathSegment(item.path);
const okignoreTarget = target.kind === 'asset' ? null : target;
const canHide = okignoreTarget !== null && okignoreBinding !== null;
const hideLabel = isFolder ? t`Hide folder` : t`Hide this file`;
- // Drives the smart-hide of the folder menu's "New from template" submenu.
- // Only folder rows can fetch (null → idle, no request) and the menu mounts
- // on-demand per right-click, so this fetch fires once when the menu opens —
- // not eagerly for every tree row. Optimistic-true while loading mirrors the
- // toolbar + empty-space gates in FileSidebar: hide the submenu only once we
- // KNOW the resolved cascade is empty, so a slow cold fetch doesn't flicker
- // the entry out from under the cursor.
- const folderConfig = useFolderConfig(isFolder ? treeDirectoryPathToFolderPath(item.path) : null);
+ const folderPath = isFolder ? treeDirectoryPathToFolderPath(item.path) : null;
+ const folderConfig = useFolderConfig(folderPath);
const folderHasTemplates =
folderConfig.state.status === 'ready'
? (folderConfig.state.data.folder.templates_available?.length ?? 0) > 0
@@ -586,47 +563,32 @@ function FileTreeMenu({
? selectedTreePathsToDeleteTargets(selectedTreePaths, documents)
: [];
const deleteTargets = selectedDeleteTargets.length > 1 ? selectedDeleteTargets : [target];
- const deleteCount = deleteTargets.length;
- const deleteLabel = plural(deleteCount, { one: 'Delete', other: 'Delete # items' });
- // Per-row-type handoff input shape:
- // asset → null (assets still suppress the submenu via the render-time
- // `!isAsset` gate below; the helper short-circuits so the
- // submenu's `inputMissing` branch never runs for an asset that
- // was never going to render anyway)
- // folder → folder-scoped helper; cwd lands at `workspace.contentDir`
- // (project root) — folder focus rides on the directive prompt
- // file → today's doc-scoped helper
- const handoffInput: HandoffDispatchInput | null = isAsset
- ? null
- : isFolder
- ? buildFolderHandoffInput({
- // Relative path is the discriminator — dispatch hook picks
- // `composeFolderPrompt(folderRelativePath)` for the directive.
- folderRelativePath: relativePathForTreeItem(item),
- workspace,
- })
- : buildHandoffInput({
- docName: treeFilePathToDocumentDocName(item.path, documents),
- workspace,
- });
-
+ const deleteLabel = plural(deleteTargets.length, { one: 'Delete', other: 'Delete # items' });
+ const relativePath = relativePathForTreeItem(item);
+ let handoffInput: HandoffDispatchInput | null = null;
+ if (isFolder) {
+ handoffInput = buildFolderHandoffInput({ folderRelativePath: relativePath, workspace });
+ } else if (!isAsset) {
+ handoffInput = buildHandoffInput({
+ docName: treeFilePathToDocumentDocName(item.path, documents),
+ workspace,
+ });
+ }
const closeForInlineSurface = () => context.close({ restoreFocus: false });
const close = () => context.close();
- // Share is offered for folders and real docs (never assets) and only with a
- // GitHub remote; no-remote falls back to an explanatory toast.
const { status: gitSyncStatus } = useGitSyncStatusDetailed();
const hasRemote = gitSyncStatus?.hasRemote === true;
- const shareInput: ShareTargetInput | null =
- isAsset || target.kind === 'asset'
- ? null
- : isFolder
- ? buildFolderShareInput(treeDirectoryPathToFolderPath(item.path))
- : buildDocShareInput(treeFilePathToDocumentDocName(item.path, documents));
+ let shareInput: ShareTargetInput | null = null;
+ if (isFolder) {
+ shareInput = buildFolderShareInput(folderPath ?? '');
+ } else if (!isAsset && target.kind !== 'asset') {
+ shareInput = buildDocShareInput(treeFilePathToDocumentDocName(item.path, documents));
+ }
const canShare = hasRemote && shareInput !== null;
- const handleShare = () => {
+
+ function handleShare() {
if (!shareInput) return;
- // No popover here (unlike the header button), so let every toast through.
void runShareAction(
{
...shareInput,
@@ -642,36 +604,16 @@ function FileTreeMenu({
logEvent: (msg) => console.log(msg),
},
);
- };
- // Shared Share item — rendered in both the folder and file menu branches.
- const shareMenuItem = canShare ? (
- <DropdownMenuItem
- data-testid="file-tree-menu-share"
- onSelect={() => {
- close();
- handleShare();
- }}
- >
- <Share2 aria-hidden="true" />
- <Trans>Share</Trans>
- </DropdownMenuItem>
- ) : null;
-
- // Smart-hide for the subtree Expand/Collapse-All items — counts folders
- // under the right-clicked folder (root + descendants) using the same
- // `folderPath === root || folderPath.startsWith(root)` predicate that
- // `expandSubtree`/`collapseSubtree` apply, so visibility tracks the
- // action surface exactly. Mirrors the toolbar dropdown's hide rule:
- // hide "Expand all" when every folder is already expanded; hide
- // "Collapse all" when none are expanded.
+ }
+
let subtreeFolderCount = 0;
let subtreeExpandedCount = 0;
if (isFolder) {
const root = folderPathToTreeDirectoryPath(item.path);
- for (const folderPath of folderTreePaths) {
- if (folderPath === root || folderPath.startsWith(root)) {
+ for (const candidate of folderTreePaths) {
+ if (candidate === root || candidate.startsWith(root)) {
subtreeFolderCount++;
- if (asDirectoryHandle(model.getItem(folderPath))?.isExpanded()) {
+ if (asDirectoryHandle(model.getItem(candidate))?.isExpanded()) {
subtreeExpandedCount++;
}
}
@@ -679,6 +621,26 @@ function FileTreeMenu({
}
const showSubtreeExpandAll = isFolder && subtreeExpandedCount < subtreeFolderCount;
const showSubtreeCollapseAll = isFolder && subtreeExpandedCount > 0;
+ const bridge = typeof window !== 'undefined' ? window.okDesktop : undefined;
+ const revealHint = !workspace ? t`No workspace` : null;
+ const revealLabel = bridge ? revealInFileManagerLabel(bridge.platform) : null;
+ const revealAriaLabel = revealLabel && revealHint ? `${revealLabel}, ${revealHint}` : revealLabel;
+
+ function hideTarget() {
+ if (!okignoreBinding || !okignoreTarget) return;
+ close();
+ const pattern = buildOkignorePatternFromTarget(okignoreTarget);
+ const current = okignoreBinding.current();
+ const doc = parseOkignoreDoc(current);
+ const updated = appendPattern(doc, pattern);
+ if (updated === doc) return;
+ okignoreBinding.patch(serializeOkignoreDoc(updated));
+ const basename = okignoreTarget.path.split('/').pop() || okignoreTarget.path;
+ toast.success(isFolder ? t`Hidden folder “${basename}”` : t`Hidden “${basename}”`, {
+ description: t`Manage hidden files in Settings → Ignore patterns.`,
+ duration: 5000,
+ });
+ }
return (
<DropdownMenu
@@ -701,192 +663,57 @@ function FileTreeMenu({
data-file-tree-context-menu-root="true"
className="min-w-52"
>
- {isFolder ? (
- <>
- {!isOkRow ? (
- <>
- <DropdownMenuItem
- disabled={anyActionBusy}
- onSelect={() => {
+ <FileTargetMenuItems
+ busy={anyActionBusy}
+ deleteLabel={deleteLabel}
+ primitives={DROPDOWN_FILE_TARGET_MENU_PRIMITIVES}
+ workspaceReady={workspace != null}
+ folderCreate={
+ isFolder && !isOkRow && folderPath != null
+ ? {
+ onNewFile: () => {
closeForInlineSurface();
- onStartCreating('file', treeDirectoryPathToFolderPath(item.path));
- }}
- >
- <SquarePen aria-hidden="true" />
- <Trans>New file</Trans>
- </DropdownMenuItem>
- {folderHasTemplates ? (
- <DropdownMenuSub>
- <DropdownMenuSubTrigger disabled={anyActionBusy}>
- <FilePlus aria-hidden="true" />
- <Trans>New from template</Trans>
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent>
- <TemplateMenuRows
- parentDir={treeDirectoryPathToFolderPath(item.path)}
- onSelectTemplate={(templateName) => {
- closeForInlineSurface();
- onCreateFromTemplate(
- treeDirectoryPathToFolderPath(item.path),
- templateName,
- );
- }}
- ItemComponent={DropdownMenuItem}
- />
- </DropdownMenuSubContent>
- </DropdownMenuSub>
- ) : null}
- <DropdownMenuItem
- disabled={anyActionBusy}
- onSelect={() => {
+ onStartCreating('file', folderPath);
+ },
+ onNewFolder: () => {
closeForInlineSurface();
- onStartCreating('folder', treeDirectoryPathToFolderPath(item.path));
- }}
- >
- <FolderPlus aria-hidden="true" />
- <Trans>New folder</Trans>
- </DropdownMenuItem>
- <DropdownMenuSeparator />
- </>
- ) : null}
- <RevealInFileManagerMenuItem item={item} workspace={workspace} onClose={close} />
- <OpenInAgentContextSubmenu
- input={handoffInput}
- installStates={handoff.installStates}
- isElectronHost={handoff.isElectronHost}
- dispatch={handoff.dispatch}
- onBeforeLaunch={close}
- />
- {shareMenuItem}
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>
- <Copy aria-hidden="true" />
- <Trans>Copy path</Trans>
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent>
- <DropdownMenuItem
- disabled={!workspace}
- onSelect={() => {
+ onStartCreating('folder', folderPath);
+ },
+ templateItems: folderHasTemplates ? (
+ <TemplateMenuRows
+ parentDir={folderPath}
+ onSelectTemplate={(templateName) => {
+ closeForInlineSurface();
+ onCreateFromTemplate(folderPath, templateName);
+ }}
+ ItemComponent={DropdownMenuItem}
+ />
+ ) : undefined,
+ }
+ : undefined
+ }
+ reveal={
+ bridge
+ ? {
+ label: revealLabel,
+ ariaLabel: revealAriaLabel ?? undefined,
+ disabled: !workspace,
+ hint: revealHint,
+ onSelect: () => {
if (!workspace) return;
close();
const full = joinWorkspacePath(
workspace.contentDir,
- relativePathForTreeItem(item),
+ relativePath,
workspace.pathSeparator,
);
- void copyToClipboard(full, 'full');
- }}
- >
- <Trans>Full path</Trans>
- </DropdownMenuItem>
- <DropdownMenuItem
- onSelect={() => {
- close();
- void copyToClipboard(relativePathForTreeItem(item), 'relative');
- }}
- >
- <Trans>Relative path</Trans>
- </DropdownMenuItem>
- </DropdownMenuSubContent>
- </DropdownMenuSub>
- {/* Subtree-scoped Expand/Collapse, smart-hidden. The divider only
- renders when the section is non-empty so a fully-expanded or
- fully-collapsed subtree collapses to a single divider before
- the destructive section instead of an empty double rule. */}
- {showSubtreeExpandAll || showSubtreeCollapseAll ? <DropdownMenuSeparator /> : null}
- {showSubtreeExpandAll ? (
- <DropdownMenuItem
- onSelect={() => {
- close();
- onExpandSubtree(item.path);
- }}
- >
- <UnfoldVertical aria-hidden="true" />
- <Trans>Expand all</Trans>
- </DropdownMenuItem>
- ) : null}
- {showSubtreeCollapseAll ? (
- <DropdownMenuItem
- onSelect={() => {
- close();
- onCollapseSubtree(item.path);
- }}
- >
- <FoldVertical aria-hidden="true" />
- <Trans>Collapse all</Trans>
- </DropdownMenuItem>
- ) : null}
- {/* Destructive section (hidden for inspect-only .ok rows). Rename
- sits with Hide/Delete here (not at the top with creation) so
- the menu's read order is create → act → tree →
- mutate-or-remove. */}
- {!isOkRow ? (
- <>
- <DropdownMenuSeparator />
- <DropdownMenuItem
- disabled={anyActionBusy}
- onSelect={() => {
- if (target.kind === 'asset') return;
- close();
- onDuplicate(target);
- }}
- >
- <CopyPlus aria-hidden="true" />
- <Trans>Duplicate</Trans>
- </DropdownMenuItem>
- <DropdownMenuItem
- disabled={anyActionBusy}
- onSelect={() => {
- closeForInlineSurface();
- model.startRenaming(item.path);
- }}
- >
- <Pencil aria-hidden="true" />
- <Trans>Rename</Trans>
- </DropdownMenuItem>
- <DropdownMenuItem
- data-testid="file-tree-menu-hide"
- disabled={!canHide}
- onSelect={() => {
- if (!okignoreBinding || !okignoreTarget) return;
- close();
- const pattern = buildOkignorePatternFromTarget(okignoreTarget);
- const current = okignoreBinding.current();
- const doc = parseOkignoreDoc(current);
- // appendPattern returns the same doc reference for whitespace-only
- // input AND for duplicates; skip the patch on both no-ops so we
- // don't churn the Y.Text with identical bytes.
- const updated = appendPattern(doc, pattern);
- if (updated === doc) return;
- okignoreBinding.patch(serializeOkignoreDoc(updated));
- const basename = okignoreTarget.path.split('/').pop() || okignoreTarget.path;
- toast.success(t`Hidden folder “${basename}”`, {
- description: t`Manage hidden files in Settings → Ignore patterns.`,
- duration: 5000,
- });
- }}
- >
- <EyeOff aria-hidden="true" />
- {hideLabel}
- </DropdownMenuItem>
- <DropdownMenuItem
- variant="destructive"
- disabled={anyActionBusy}
- onSelect={() => {
- close();
- onDelete(deleteTargets);
- }}
- >
- <Trash2 aria-hidden="true" />
- {deleteLabel}
- </DropdownMenuItem>
- </>
- ) : null}
- </>
- ) : (
- <>
- <RevealInFileManagerMenuItem item={item} workspace={workspace} onClose={close} />
- {!isAsset && (
+ void bridge.shell.showItemInFolder(full);
+ },
+ }
+ : undefined
+ }
+ openWithAi={
+ isAsset ? undefined : (
<OpenInAgentContextSubmenu
input={handoffInput}
installStates={handoff.installStates}
@@ -894,140 +721,92 @@ function FileTreeMenu({
dispatch={handoff.dispatch}
onBeforeLaunch={close}
/>
- )}
- {shareMenuItem}
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>
- <Copy aria-hidden="true" />
- <Trans>Copy path</Trans>
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent>
- <DropdownMenuItem
- disabled={!workspace}
- onSelect={() => {
- if (!workspace) return;
- close();
- const full = joinWorkspacePath(
- workspace.contentDir,
- relativePathForTreeItem(item),
- workspace.pathSeparator,
- );
- void copyToClipboard(full, 'full');
- }}
- >
- <Trans>Full path</Trans>
- </DropdownMenuItem>
- <DropdownMenuItem
- onSelect={() => {
+ )
+ }
+ share={
+ canShare
+ ? {
+ onSelect: () => {
close();
- void copyToClipboard(relativePathForTreeItem(item), 'relative');
- }}
- >
- <Trans>Relative path</Trans>
- </DropdownMenuItem>
- </DropdownMenuSubContent>
- </DropdownMenuSub>
- {/* Mutate section (hidden for inspect-only .ok rows). */}
- {!isOkRow ? (
- <>
- <DropdownMenuSeparator />
- {!isAsset ? (
- <>
- <DropdownMenuSub>
- <DropdownMenuSubTrigger disabled={anyActionBusy}>
- <FileKey aria-hidden="true" />
- <Trans>Import as template</Trans>
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent>
- <DropdownMenuItem
- disabled={anyActionBusy}
- onSelect={() => {
- close();
- onImportTemplate(target, false);
- }}
- >
- <Trans>Keep original file</Trans>
- </DropdownMenuItem>
- <DropdownMenuItem
- disabled={anyActionBusy}
- onSelect={() => {
- close();
- onImportTemplate(target, true);
- }}
- >
- <Trans>Convert (delete original)</Trans>
- </DropdownMenuItem>
- </DropdownMenuSubContent>
- </DropdownMenuSub>
- <DropdownMenuItem
- disabled={anyActionBusy}
- onSelect={() => {
+ handleShare();
+ },
+ }
+ : undefined
+ }
+ onCopyFullPath={() => {
+ if (!workspace) return;
+ close();
+ const full = joinWorkspacePath(
+ workspace.contentDir,
+ relativePath,
+ workspace.pathSeparator,
+ );
+ void copyToClipboard(full, 'full');
+ }}
+ onCopyRelativePath={() => {
+ close();
+ void copyToClipboard(relativePath, 'relative');
+ }}
+ folderTree={
+ isFolder
+ ? {
+ onExpandAll: showSubtreeExpandAll
+ ? () => {
close();
- onDuplicate(target);
- }}
- >
- <CopyPlus aria-hidden="true" />
- <Trans>Duplicate</Trans>
- </DropdownMenuItem>
- </>
- ) : null}
- <DropdownMenuItem
- disabled={anyActionBusy}
- onSelect={() => {
- closeForInlineSurface();
- model.startRenaming(item.path);
- }}
- >
- <Pencil aria-hidden="true" />
- <Trans>Rename</Trans>
- </DropdownMenuItem>
- {okignoreTarget ? (
- <DropdownMenuItem
- data-testid="file-tree-menu-hide"
- disabled={!canHide}
- onSelect={() => {
- if (!okignoreBinding) return;
- close();
- const pattern = buildOkignorePatternFromTarget(okignoreTarget);
- const current = okignoreBinding.current();
- const doc = parseOkignoreDoc(current);
- // appendPattern returns the same doc reference for whitespace-only
- // input AND for duplicates; skip the patch on both no-ops so we
- // don't churn the Y.Text with identical bytes.
- const updated = appendPattern(doc, pattern);
- if (updated === doc) return;
- okignoreBinding.patch(serializeOkignoreDoc(updated));
- const basename = okignoreTarget.path.split('/').pop() || okignoreTarget.path;
- toast.success(t`Hidden “${basename}”`, {
- description: t`Manage hidden files in Settings → Ignore patterns.`,
- duration: 5000,
- });
- }}
- >
- <EyeOff aria-hidden="true" />
- {hideLabel}
- </DropdownMenuItem>
- ) : null}
- <DropdownMenuItem
- variant="destructive"
- disabled={anyActionBusy}
- onSelect={() => {
- close();
- onDelete(deleteTargets);
- }}
- >
- <Trash2 aria-hidden="true" />
- {deleteLabel}
- </DropdownMenuItem>
- </>
- ) : null}
- </>
- )}
+ onExpandSubtree(item.path);
+ }
+ : undefined,
+ onCollapseAll: showSubtreeCollapseAll
+ ? () => {
+ close();
+ onCollapseSubtree(item.path);
+ }
+ : undefined,
+ }
+ : undefined
+ }
+ onImportTemplate={
+ !isFolder && !isAsset && !isOkRow
+ ? (deleteSource) => {
+ close();
+ onImportTemplate(target, deleteSource);
+ }
+ : undefined
+ }
+ onDuplicate={
+ !isAsset && !isOkRow
+ ? () => {
+ close();
+ onDuplicate(target);
+ }
+ : undefined
+ }
+ onRename={
+ !isOkRow
+ ? () => {
+ closeForInlineSurface();
+ model.startRenaming(item.path);
+ }
+ : undefined
+ }
+ hide={
+ !isOkRow && okignoreTarget
+ ? { label: hideLabel, disabled: !canHide, onSelect: hideTarget }
+ : undefined
+ }
+ onDelete={
+ !isOkRow
+ ? () => {
+ close();
+ onDelete(deleteTargets);
+ }
+ : undefined
+ }
+ />
</DropdownMenuContent>
</DropdownMenu>
);
}
-
export interface FileTreeHandle {
startCreating(kind: 'file' | 'folder', parentDir: string): void;
/** Open NewItemDialog at the given parentDir so the template picker is
@@ -1110,7 +889,11 @@ export function FileTree({
const showHiddenFiles = merged?.appearance?.sidebar?.showHiddenFiles ?? false;
const showOnlyMarkdownFiles = merged?.appearance?.sidebar?.showOnlyMarkdownFiles ?? false;
const showOkFolders = merged?.appearance?.sidebar?.showOkFolders ?? false;
- const previewTabs = merged?.editor?.previewTabs ?? true;
+ const previewTabsEnabled = merged?.editor?.previewTabs ?? true;
+ const previewOpenOptions = {
+ disposition: previewTabsEnabled ? 'preview' : 'permanent',
+ consumeActiveNewTab: true,
+ } satisfies OpenTargetOptions;
const {
documents,
setDocuments,
@@ -1195,14 +978,12 @@ export function FileTree({
) {
if (target.kind === 'doc') {
if (target.registerPage) addPage(target.docName);
- openTarget(navigationTargetForDocument(target.docName, target.size), {
- tabBehavior: openTabBehavior(),
- });
+ openTarget(navigationTargetForDocument(target.docName, target.size), previewOpenOptions);
pushHashWithoutNavigation(hashFromDocName(target.docName));
} else if (target.kind === 'folder') {
openTarget(
{ kind: 'folder', target: target.folderPath, folderPath: target.folderPath },
- { tabBehavior: openTabBehavior() },
+ previewOpenOptions,
);
pushHashWithoutNavigation(hashFromFolderPath(target.folderPath));
} else {
@@ -1218,7 +999,7 @@ export function FileTree({
assetPath: target.assetPath,
mediaKind: entry?.mediaKind ?? null,
},
- { tabBehavior: openTabBehavior() },
+ previewOpenOptions,
);
pushHashWithoutNavigation(hashFromAssetPath(target.assetPath));
}
@@ -1248,7 +1029,7 @@ export function FileTree({
assetPath: action.path,
mediaKind: action.mediaKind,
},
- { tabBehavior: openTabBehavior() },
+ previewOpenOptions,
);
pushHashWithoutNavigation(action.hash);
notifySidebarFileSelected();
@@ -1271,7 +1052,7 @@ export function FileTree({
docExt: docEntry?.docExt,
});
if (okTarget?.kind === 'asset') {
- openTarget(okTarget, { tabBehavior: openTabBehavior() });
+ openTarget(okTarget, previewOpenOptions);
pushHashWithoutNavigation(hashFromAssetPath(okTarget.assetPath));
notifySidebarFileSelected();
return;
@@ -1317,13 +1098,6 @@ export function FileTree({
// Pierre reset helpers may run after an awaited mutation, so they read the
// latest `showOkFolders` setting rather than the render that started it.
const showOkFoldersRef = useRef<boolean>(false);
- // Preview-tab behavior: on (the default), a tree click reuses the active tab
- // the way an editor preview tab does; off, every click opens its own tab.
- // Same ref treatment as the view setting above — the open closures are
- // created at mount and must read the latest value at click time.
- const previewTabsRef = useRef<boolean>(true);
- const openTabBehavior = (): 'append' | 'replace-active' =>
- previewTabsRef.current ? 'replace-active' : 'append';
const fileTreeHostRef = useRef<HTMLDivElement | null>(null);
const handleSelectionChangeRef = useRef<(selectedPaths: readonly string[]) => void>(() => {});
const handleRenameRef = useRef<(event: FileTreeRenameEvent) => void>(() => {});
@@ -1371,6 +1145,13 @@ export function FileTree({
event.dataTransfer?.setData(OK_SIDEBAR_DRAG_MIME, serializeSidebarDragPayload(payload));
}
+ function finalizeSidebarDragStart(event: Event) {
+ if (!(event instanceof DragEvent)) return;
+ if (!hasSidebarDragType(event.dataTransfer)) return;
+ // Pierre's row handler runs between these shadow-root phases and resets this to move.
+ if (event.dataTransfer) event.dataTransfer.effectAllowed = 'copyMove';
+ }
+
function handleExternalFileDragOver(event: Event) {
if (!(event instanceof DragEvent)) return;
if (!isExternalFileDrag(event)) return;
@@ -1409,6 +1190,7 @@ export function FileTree({
}
shadow.addEventListener('dragstart', handleDragStart, { capture: true });
+ shadow.addEventListener('dragstart', finalizeSidebarDragStart);
shadow.addEventListener('dragover', handleExternalFileDragOver, { capture: true });
shadow.addEventListener('dragleave', handleExternalFileDragLeave, { capture: true });
shadow.addEventListener('drop', handleExternalFileDrop, { capture: true });
@@ -1417,6 +1199,7 @@ export function FileTree({
window.addEventListener('dragend', clearSidebarDragInProgressSoon, true);
return () => {
shadow.removeEventListener('dragstart', handleDragStart, { capture: true });
+ shadow.removeEventListener('dragstart', finalizeSidebarDragStart);
shadow.removeEventListener('dragover', handleExternalFileDragOver, { capture: true });
shadow.removeEventListener('dragleave', handleExternalFileDragLeave, { capture: true });
shadow.removeEventListener('drop', handleExternalFileDrop, { capture: true });
@@ -1729,62 +1512,6 @@ export function FileTree({
handleDuplicateTargetRef.current = handleDuplicateTarget;
});
- async function handleImportTemplate(target: FileTreeTarget, deleteSource: boolean) {
- if (target.kind !== 'file') return;
- if (deleteSource) {
- setTemplateConvertRequest(target);
- return;
- }
- await executeImportTemplate(target, false);
- }
-
- async function executeImportTemplate(target: FileTreeTarget, deleteSource: boolean) {
- if (busyPathRef.current !== null) return;
- const clearBusyState = () => {
- setBusyPath(null);
- busyPathRef.current = null;
- setTemplateConvertRequest(null);
- };
- busyPathRef.current = target.path;
- setBusyPath(target.path);
- setError(null);
-
- const appPath = target.path;
- const slash = appPath.lastIndexOf('/');
- const targetFolder = slash === -1 ? '' : appPath.slice(0, slash);
-
- const res = await importTemplate({
- sourcePath: target.path,
- targetFolder,
- deleteSource,
- });
-
- if (!res.ok) {
- toast.error(t`Failed to import template`, { description: res.error });
- clearBusyState();
- return;
- }
-
- if (deleteSource) {
- await applyDeleteAftermath([target], [target.path], []);
- // Optimistically remove from view if deleted, standard watcher sweeps later
- setDocuments((current) => {
- const next = current.filter(
- (entry) => !(isDocumentEntry(entry) && entry.docName === target.path),
- );
- resetModelToDocuments(next);
- markNextDocumentsAsApplied(next);
- return next;
- });
- emitDocumentsChanged(['files', 'backlinks', 'graph']);
- }
-
- toast.success(t`Template imported`, {
- description: res.path,
- });
- clearBusyState();
- }
-
function recoverMarkdownRenameConflict(message: string): boolean {
const bareDestinationPath = parseAlreadyExistsRenamePath(message);
if (!bareDestinationPath || markdownTreeExtension(bareDestinationPath)) return false;
@@ -2322,6 +2049,8 @@ export function FileTree({
}
}
+ const handleTreeRenameEvent = useEffectEvent(handleTreeRename);
+
async function handleDropComplete(event: FileTreeDropResult) {
const operations = event.draggedPaths
.map((sourcePath) => {
@@ -2759,7 +2488,6 @@ export function FileTree({
assetTreePathsRef.current = assetTreePaths;
busyPathRef.current = busyPath;
showOkFoldersRef.current = showOkFolders;
- previewTabsRef.current = previewTabs;
treePathsRef.current = treePaths;
folderTreePathsRef.current = folderTreePaths;
activeAncestorTreePathsRef.current = activeAncestorTreePaths;
@@ -3182,6 +2910,64 @@ export function FileTree({
emitDocumentsChanged(['files', 'backlinks', 'graph']);
}
+ async function executeImportTemplate(target: FileTreeTarget, deleteSource: boolean) {
+ if (busyPathRef.current !== null) return;
+ const clearBusyState = () => {
+ setBusyPath(null);
+ busyPathRef.current = null;
+ setTemplateConvertRequest(null);
+ };
+ busyPathRef.current = target.path;
+ setBusyPath(target.path);
+ setError(null);
+
+ const appPath = target.path;
+ const slash = appPath.lastIndexOf('/');
+ const targetFolder = slash === -1 ? '' : appPath.slice(0, slash);
+
+ const res = await importTemplate({
+ sourcePath: target.path,
+ targetFolder,
+ deleteSource,
+ });
+
+ if (!res.ok) {
+ toast.error(t`Failed to import template`, { description: res.error });
+ clearBusyState();
+ return;
+ }
+
+ if (deleteSource) {
+ await applyDeleteAftermath([target], [target.path], []);
+ // Optimistically remove from view if deleted, standard watcher sweeps later
+ setDocuments((current) => {
+ const next = current.filter(
+ (entry) => !(isDocumentEntry(entry) && entry.docName === target.path),
+ );
+ resetModelToDocuments(next);
+ markNextDocumentsAsApplied(next);
+ return next;
+ });
+ emitDocumentsChanged(['files', 'backlinks', 'graph']);
+ }
+
+ toast.success(t`Template imported`, {
+ description: res.path,
+ });
+ clearBusyState();
+ }
+
+ async function handleImportTemplate(target: FileTreeTarget, deleteSource: boolean) {
+ if (target.kind !== 'file') return;
+ if (deleteSource) {
+ setTemplateConvertRequest(target);
+ return;
+ }
+ await executeImportTemplate(target, false);
+ }
+
+ const handleImportTemplateEvent = useEffectEvent(handleImportTemplate);
+
/**
* Hard-delete via `POST /api/delete-path` — web mode and the Electron
* fallback path (Delete Permanently from `TrashFailureModal`). Iterates
@@ -3510,24 +3296,9 @@ export function FileTree({
await handleDeleteTargets(originals);
}
- // Hold a ref to handleDeleteTargets so the menu-action subscription
- // effect below can keep its closure off the latest function identity
- // without forcing the effect to re-bind on every render. Declared after
- // the function declaration to keep React Compiler's
- // `PruneHoistedContexts` pass from tripping on the forward-reference
- // pattern the earlier startCreating refs benefit from (those functions
- // are declared above their refs).
- const handleDeleteTargetsRef = useRef(handleDeleteTargets);
- useEffect(() => {
- handleDeleteTargetsRef.current = handleDeleteTargets;
- });
-
- // Subscribe to the macOS File menu's `move-to-trash` request bus. The
- // FileSidebar menu-action handler emits when the user picks File → Move
- // to Trash; we convert the navigation-target snapshot to the same
- // `FileTreeTarget` shape the row context menu produces and route through
- // the existing 2-step Trash spine. One subscription owns the
- // surface so a hot-reload / remount tears down cleanly.
+ // Editor tabs and the macOS File menu share this request bus. Convert their
+ // navigation target to the row menu's target shape, then open the same
+ // confirmation dialog instead of bypassing it for an immediate delete.
//
// docExt is looked up from `documentsRef` (the in-memory document list)
// at fire-time so document trash flow + downstream rename hints render the
@@ -3535,50 +3306,17 @@ export function FileTree({
// `kind: 'asset'` targets and share the same delete spine.
useEffect(() => {
return subscribeToFileTreeMenuActionDelete((target) => {
- if (target.kind === 'doc' || target.kind === 'folder-index') {
- const docName = target.docName;
- const docEntry = documentsRef.current.find(
- (entry): entry is DocumentEntry => isDocumentEntry(entry) && entry.docName === docName,
- );
- void handleDeleteTargetsRef.current([
- {
- kind: 'file',
- path: docName,
- name: docName.split('/').pop() ?? docName,
- docExt: docEntry?.docExt,
- },
- ]);
- return;
- }
- if (target.kind === 'folder') {
- void handleDeleteTargetsRef.current([
- {
- kind: 'folder',
- path: target.folderPath,
- name: target.folderPath.split('/').pop() ?? target.folderPath,
- },
- ]);
- return;
- }
- if (target.kind === 'asset') {
- void handleDeleteTargetsRef.current([
- {
- kind: 'asset',
- path: target.assetPath,
- name: target.assetPath.split('/').pop() ?? target.assetPath,
- },
- ]);
+ const fileTreeTarget = fileTreeTargetFromNavigationTarget(target, documentsRef.current);
+ if (fileTreeTarget) {
+ if (!hasOkPathSegment(fileTreeTarget.path)) {
+ setDeleteRequest({ targets: [fileTreeTarget] });
+ }
return;
}
// missing — File menu's Move to Trash is disabled for this scope
// upstream; the emit shouldn't fire. Logging the event so a future
// drift between the menu-enable gate and the emitter is caught.
- console.warn(
- JSON.stringify({
- event: 'file-tree-menu-action-delete-unsupported-kind',
- kind: target.kind,
- }),
- );
+ warnUnsupportedMenuTarget('delete', target);
});
}, []);
@@ -3587,71 +3325,51 @@ export function FileTree({
// doc + folder-index duplicate the file, folder duplicates the folder, and
// asset + missing are guarded upstream by menu enablement.
useEffect(() => {
- return subscribeToFileTreeMenuActionDuplicate((target: ResolvedNavigationTarget) => {
- if (target.kind === 'doc' || target.kind === 'folder-index') {
- const docName = target.docName;
- const docEntry = documentsRef.current.find(
- (entry): entry is DocumentEntry => isDocumentEntry(entry) && entry.docName === docName,
- );
- void handleDuplicateTargetRef.current({
- kind: 'file',
- path: docName,
- name: docName.split('/').pop() ?? docName,
- docExt: docEntry?.docExt,
- });
- return;
- }
- if (target.kind === 'folder') {
- void handleDuplicateTargetRef.current({
- kind: 'folder',
- path: target.folderPath,
- name: target.folderPath.split('/').pop() ?? target.folderPath,
- });
+ return subscribeToFileTreeMenuActionDuplicate((target) => {
+ const fileTreeTarget = fileTreeTargetFromNavigationTarget(target, documentsRef.current);
+ if (fileTreeTarget && fileTreeTarget.kind !== 'asset') {
+ void handleDuplicateTargetRef.current(fileTreeTarget);
return;
}
- console.warn(
- JSON.stringify({
- event: 'file-tree-menu-action-duplicate-unsupported-kind',
- kind: target.kind,
- }),
- );
+ warnUnsupportedMenuTarget('duplicate', target);
});
}, []);
- // macOS File menu's `rename` item bridges to Pierre's inline-rename via
- // the model API. Path resolution per kind: doc + folder-index use
- // `docNameToTreePath(docName, docExt)` (extension lookup from documentsRef
- // mirrors the delete subscriber); folder uses folderPath directly.
- // asset uses the raw asset path; missing falls through to a structured
- // warn because the menu enable gate disables rename for that scope.
+ // Menu-bar rename keeps Pierre's inline editor. Tab-menu rename supplies a
+ // destination name from its dialog and enters the same handleTreeRename
+ // spine directly, so both surfaces share validation and reconciliation.
useEffect(() => {
- return subscribeToFileTreeMenuActionRename((target) => {
- if (target.kind === 'doc' || target.kind === 'folder-index') {
- const docName = target.docName;
- const docEntry = documentsRef.current.find(
- (entry): entry is DocumentEntry => isDocumentEntry(entry) && entry.docName === docName,
- );
- const treePath = docNameToTreePath(docName, docEntry?.docExt);
- model.startRenaming(treePath);
- return;
- }
- if (target.kind === 'folder') {
- model.startRenaming(target.folderPath);
+ return subscribeToFileTreeMenuActionRename((target, nextName) => {
+ const renameTarget = fileTreeTargetFromNavigationTarget(
+ target,
+ documentsRef.current,
+ 'tree-path',
+ );
+ if (!renameTarget) {
+ warnUnsupportedMenuTarget('rename', target);
return;
}
- if (target.kind === 'asset') {
- model.startRenaming(target.assetPath);
+
+ if (nextName === undefined) {
+ model.startRenaming(renameTarget.path);
return;
}
- console.warn(
- JSON.stringify({
- event: 'file-tree-menu-action-rename-unsupported-kind',
- kind: target.kind,
- }),
- );
+ void handleTreeRenameEvent({
+ sourcePath: renameTarget.path,
+ destinationPath: buildRenamedNodePath(renameTarget, nextName),
+ isFolder: renameTarget.kind === 'folder',
+ });
});
}, [model]);
+ useEffect(() => {
+ return subscribeToFileTreeMenuActionImportTemplate((target, deleteSource) => {
+ const fileTreeTarget = fileTreeTargetFromNavigationTarget(target, documentsRef.current);
+ if (fileTreeTarget?.kind !== 'file') return;
+ void handleImportTemplateEvent(fileTreeTarget, deleteSource);
+ });
+ }, []);
+
function cancelCurrentHoverPrewarm() {
const current = hoveredPrewarmDocRef.current;
if (current) cancelHoverPrewarm(current);
diff --git a/packages/app/src/components/FilesSkillsToggle.tsx b/packages/app/src/components/FilesSkillsToggle.tsx
index 638178537..2163abfb4 100644
--- a/packages/app/src/components/FilesSkillsToggle.tsx
+++ b/packages/app/src/components/FilesSkillsToggle.tsx
@@ -19,9 +19,9 @@ interface FilesSkillsToggleProps {
* The collapsed segment carries a tooltip so its bare icon can still be named on
* hover. Both segments stay in the DOM at all times — the collapsed label is
* clipped, not removed, so it remains in the accessible name. Selecting flips
- * only the sidebar surface (via the ephemeral `skillsSidebar` flag) — it does
- * NOT navigate or open a hub tab, so the current doc stays open; the empty state
- * maps to the Skills base page in Skills mode (see `EditorArea`). The icon-only
+ * the sidebar surface. A surface with no remembered tab opens its ephemeral home
+ * tab; Skills home uses its canonical route so browser history restores the
+ * correct surface (see `EditorArea`). The icon-only
* width is content-sized (no `w-full`) so it can share the sidebar chrome row
* with the trailing search affordance.
*/
diff --git a/packages/app/src/components/FolderPropertiesCard.tsx b/packages/app/src/components/FolderPropertiesCard.tsx
index a6ae3527e..b18e9d846 100644
--- a/packages/app/src/components/FolderPropertiesCard.tsx
+++ b/packages/app/src/components/FolderPropertiesCard.tsx
@@ -210,12 +210,10 @@ export function FolderPropertiesCard({ folderPath, state, onChange }: Props) {
<CollapsibleTrigger className="flex w-full cursor-pointer items-center justify-between gap-2 px-3 py-2.5 data-[state=open]:border-b border-border">
<span className="flex items-center gap-1.5 text-xs font-semibold uppercase font-mono tracking-wider text-muted-foreground">
<ChevronRight
- className={`size-3 transition-transform ${collapsed ? '' : 'rotate-90'}`}
+ className={`size-3 shrink-0 motion-safe:transition-transform motion-safe:duration-150 motion-safe:ease-[cubic-bezier(0.23,1,0.32,1)] ${collapsed ? '' : 'rotate-90'}`}
aria-hidden
/>
- <span>
- <Trans>Folder properties</Trans>
- </span>
+ <Trans>Folder properties</Trans>
</span>
{/* Stop click bubbling so single / triple click on the path
doesn't toggle the collapsible. Drag-to-select never fires
@@ -226,7 +224,7 @@ export function FolderPropertiesCard({ folderPath, state, onChange }: Props) {
keyboard activation (Enter/Space → toggle). */}
{/* biome-ignore lint/a11y/useKeyWithClickEvents: <code> is non-focusable; keyboard activation lives on the wrapping <button>. */}
<code
- className="text-xs text-muted-foreground font-mono cursor-text select-text"
+ className="text-xs text-muted-foreground font-mono cursor-text select-text break-all"
onClick={(e) => e.stopPropagation()}
>
{filePath}
diff --git a/packages/app/src/components/NavigatorApp.menu-action.dom.test.tsx b/packages/app/src/components/NavigatorApp.menu-action.dom.test.tsx
index 3234dafaa..a6d7779c5 100644
--- a/packages/app/src/components/NavigatorApp.menu-action.dom.test.tsx
+++ b/packages/app/src/components/NavigatorApp.menu-action.dom.test.tsx
@@ -96,11 +96,18 @@ function makeNavigatorBridge(): NavigatorBridgeStub {
listRecent: async () => [],
removeRecent: async () => undefined,
getSessionState: async () => ({
- openTabs: [],
- pinnedTabIds: [],
- activeDocName: null,
- activeTabId: null,
+ activeTabByMode: { files: null, skills: null },
updatedAt: null,
+ panes: [
+ {
+ id: 'pane-main',
+ openTabs: [],
+ pinnedTabIds: [],
+ activeTabId: null,
+ size: 100,
+ },
+ ],
+ focusedPaneId: 'pane-main',
}),
setSessionState: async () => undefined,
open: async () => undefined,
diff --git a/packages/app/src/components/NavigatorApp.test.ts b/packages/app/src/components/NavigatorApp.test.ts
index 6c578e1e2..254ed2247 100644
--- a/packages/app/src/components/NavigatorApp.test.ts
+++ b/packages/app/src/components/NavigatorApp.test.ts
@@ -38,11 +38,18 @@ function makeBridge(overrides: Partial<MockBridge> = {}): MockBridge {
removeRecent: vi.fn(() => Promise.resolve()),
getSessionState: vi.fn(() =>
Promise.resolve({
- openTabs: [],
- pinnedTabIds: [],
- activeDocName: null,
- activeTabId: null,
+ activeTabByMode: { files: null, skills: null },
updatedAt: null,
+ panes: [
+ {
+ id: 'pane-main',
+ openTabs: [],
+ pinnedTabIds: [],
+ activeTabId: null,
+ size: 100,
+ },
+ ],
+ focusedPaneId: 'pane-main',
}),
),
setSessionState: vi.fn(() => Promise.resolve()),
@@ -81,11 +88,18 @@ describe('NavigatorApp bridge contract', () => {
removeRecent: vi.fn(() => Promise.resolve()),
getSessionState: vi.fn(() =>
Promise.resolve({
- openTabs: [],
- pinnedTabIds: [],
- activeDocName: null,
- activeTabId: null,
+ activeTabByMode: { files: null, skills: null },
updatedAt: null,
+ panes: [
+ {
+ id: 'pane-main',
+ openTabs: [],
+ pinnedTabIds: [],
+ activeTabId: null,
+ size: 100,
+ },
+ ],
+ focusedPaneId: 'pane-main',
}),
),
setSessionState: vi.fn(() => Promise.resolve()),
@@ -138,11 +152,18 @@ describe('NavigatorApp bridge contract', () => {
removeRecent: vi.fn(() => Promise.resolve()),
getSessionState: vi.fn(() =>
Promise.resolve({
- openTabs: [],
- pinnedTabIds: [],
- activeDocName: null,
- activeTabId: null,
+ activeTabByMode: { files: null, skills: null },
updatedAt: null,
+ panes: [
+ {
+ id: 'pane-main',
+ openTabs: [],
+ pinnedTabIds: [],
+ activeTabId: null,
+ size: 100,
+ },
+ ],
+ focusedPaneId: 'pane-main',
}),
),
setSessionState: vi.fn(() => Promise.resolve()),
diff --git a/packages/app/src/components/NotInSidebarIndicator.dom.test.tsx b/packages/app/src/components/NotInSidebarIndicator.dom.test.tsx
index 572fee6f3..18fc4a6c8 100644
--- a/packages/app/src/components/NotInSidebarIndicator.dom.test.tsx
+++ b/packages/app/src/components/NotInSidebarIndicator.dom.test.tsx
@@ -27,7 +27,8 @@ type SidebarVisibilityConfig = {
};
};
-let mergedConfig: SidebarVisibilityConfig | null = null;
+let mergedConfig: SidebarVisibilityConfig | null = {};
+let projectLocalSynced = true;
let projectLocalBindingNull = false;
let patchResultOk = true;
const patchCalls: unknown[] = [];
@@ -36,6 +37,7 @@ const toastErrors: unknown[][] = [];
vi.doMock('@/lib/config-provider', () => ({
useConfigContext: () => ({
merged: mergedConfig as Config | null,
+ projectLocalSynced,
projectLocalBinding: projectLocalBindingNull
? null
: {
@@ -64,7 +66,8 @@ const onlyMarkdownFlip = () => screen.queryByTestId('not-in-sidebar-flip-only-ma
describe('NotInSidebarIndicator', () => {
beforeEach(() => {
- mergedConfig = null;
+ mergedConfig = {};
+ projectLocalSynced = true;
projectLocalBindingNull = false;
patchResultOk = true;
patchCalls.length = 0;
@@ -81,6 +84,28 @@ describe('NotInSidebarIndicator', () => {
expect(onlyMarkdownFlip()).toBeNull();
});
+ test('renders nothing while merged config is unknown', () => {
+ mergedConfig = null;
+ projectLocalSynced = false;
+ render(<NotInSidebarIndicator entry={{ kind: 'document', docName: '.scratch/note' }} />);
+
+ expect(indicator()).toBeNull();
+ });
+
+ test('renders nothing while project-local config has defaults but is not synced', () => {
+ projectLocalSynced = false;
+ render(<NotInSidebarIndicator entry={{ kind: 'document', docName: '.scratch/note' }} />);
+
+ expect(indicator()).toBeNull();
+ });
+
+ test('renders nothing when resolved config shows hidden files', () => {
+ mergedConfig = { appearance: { sidebar: { showHiddenFiles: true } } };
+ render(<NotInSidebarIndicator entry={{ kind: 'document', docName: '.scratch/note' }} />);
+
+ expect(indicator()).toBeNull();
+ });
+
test('flip action patches the axis config leaf through the project-local binding', () => {
render(<NotInSidebarIndicator entry={{ kind: 'document', docName: '.scratch/note' }} />);
diff --git a/packages/app/src/components/NotInSidebarIndicator.tsx b/packages/app/src/components/NotInSidebarIndicator.tsx
index 6f7963704..cc2f34387 100644
--- a/packages/app/src/components/NotInSidebarIndicator.tsx
+++ b/packages/app/src/components/NotInSidebarIndicator.tsx
@@ -30,7 +30,8 @@ interface NotInSidebarIndicatorProps {
*/
export function NotInSidebarIndicator({ entry, className }: NotInSidebarIndicatorProps) {
const { t } = useLingui();
- const { projectLocalBinding, merged } = useConfigContext();
+ const { projectLocalBinding, projectLocalSynced, merged } = useConfigContext();
+ if (merged === null || !projectLocalSynced) return null;
const sidebar = merged?.appearance?.sidebar;
const axes = attributeTreeHiddenAxes(entry, {
showHiddenFiles: sidebar?.showHiddenFiles ?? false,
diff --git a/packages/app/src/components/OutlinePanel.tsx b/packages/app/src/components/OutlinePanel.tsx
index 614305f24..9a33438f4 100644
--- a/packages/app/src/components/OutlinePanel.tsx
+++ b/packages/app/src/components/OutlinePanel.tsx
@@ -70,6 +70,8 @@ const LEVEL_W = 12;
const MARKER_SIZE = 6;
export interface OutlineNavDetail {
+ /** The document that owns this navigation request. */
+ docName: string;
index: number;
slug: string;
mode: 'wysiwyg' | 'source';
@@ -151,6 +153,7 @@ function OutlinePanelInner({
function handleNav(index: number, slug: string) {
const detail: OutlineNavDetail = {
+ docName,
index,
slug,
mode: isSourceMode ? 'source' : 'wysiwyg',
diff --git a/packages/app/src/components/ProblemsPanel.dom.test.tsx b/packages/app/src/components/ProblemsPanel.dom.test.tsx
index 2780cf341..43ace11a9 100644
--- a/packages/app/src/components/ProblemsPanel.dom.test.tsx
+++ b/packages/app/src/components/ProblemsPanel.dom.test.tsx
@@ -14,6 +14,7 @@ import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { SWEEP_PROGRESS_CHUNK, sweepProgressInterval } from '@/components/problems-sweep';
import { TooltipProvider } from '@/components/ui/tooltip';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
+import type { LintNavDetail } from './ProblemsPanel';
// Both lingui macro specifiers alias to ONE shim module under the vitest dom
// config, so two mock registrations race for a single resolved module id and
@@ -518,15 +519,20 @@ describe('ProblemsPanel', () => {
});
test('clicking a row dispatches LINT_NAV_EVENT with the line', () => {
- let received: { line: number; column: number } | null = null;
+ let received: LintNavDetail | null = null;
const listener = (e: Event) => {
- received = (e as CustomEvent<{ line: number; column: number }>).detail;
+ received = (e as CustomEvent<LintNavDetail>).detail;
};
window.addEventListener(LINT_NAV_EVENT, listener);
try {
render(<ProblemsPanel docName="notes" diagnostics={[diag({ line: 7, column: 2 })]} />);
fireEvent.click(screen.getByRole('button'));
- expect(received).toEqual({ line: 7, column: 2, source: 'markdownlint' });
+ expect(received).toEqual({
+ docName: 'notes',
+ line: 7,
+ column: 2,
+ source: 'markdownlint',
+ });
} finally {
window.removeEventListener(LINT_NAV_EVENT, listener);
}
@@ -579,9 +585,9 @@ describe('ProblemsPanel', () => {
});
test('expanding a group lists each occurrence, and one click jumps to its line', () => {
- let received: { line: number; column: number } | null = null;
+ let received: LintNavDetail | null = null;
const listener = (e: Event) => {
- received = (e as CustomEvent<{ line: number; column: number }>).detail;
+ received = (e as CustomEvent<LintNavDetail>).detail;
};
window.addEventListener(LINT_NAV_EVENT, listener);
try {
@@ -602,7 +608,12 @@ describe('ProblemsPanel', () => {
// reads as a whole finding out of list context.
expect(occurrences[1]?.getAttribute('aria-label')).toBe('Hard tabs at line 9');
fireEvent.click(occurrences[1] as HTMLElement);
- expect(received).toEqual({ line: 9, column: 1, source: 'markdownlint' });
+ expect(received).toEqual({
+ docName: 'notes',
+ line: 9,
+ column: 1,
+ source: 'markdownlint',
+ });
} finally {
window.removeEventListener(LINT_NAV_EVENT, listener);
}
@@ -739,7 +750,7 @@ describe('ProblemsPanel', () => {
try {
render(<ProblemsPanel docName="notes" diagnostics={[linkDiag({ line: 5 })]} />);
fireEvent.click(screen.getByRole('button', { name: /does not resolve/ }));
- expect(received).toEqual({ line: 5, column: 1, source: 'links' });
+ expect(received).toEqual({ docName: 'notes', line: 5, column: 1, source: 'links' });
} finally {
window.removeEventListener(LINT_NAV_EVENT, listener);
}
@@ -752,7 +763,7 @@ describe('ProblemsPanel', () => {
// the next source-mode activation within the TTL replays it.
expect(consumePendingSourceNavigation('notes')).toEqual({
kind: 'lint',
- detail: { line: 7, column: 2, source: 'markdownlint' },
+ detail: { docName: 'notes', line: 7, column: 2, source: 'markdownlint' },
});
});
});
@@ -983,10 +994,15 @@ describe('ProblemsPanel — project scope', () => {
expect(window.location.hash).toBe('#/guides/setup');
expect(consumePendingSourceNavigation('guides/setup')).toEqual({
kind: 'lint',
- detail: { line: 4, column: 2, source: 'markdownlint' },
+ detail: {
+ docName: 'guides/setup',
+ line: 4,
+ column: 2,
+ source: 'markdownlint',
+ },
});
- // The in-doc nav event stays quiet on cross-doc clicks — it carries no
- // docName and would move the cursor in the doc that is still open.
+ // The in-doc nav event stays quiet on cross-doc clicks. The banked,
+ // document-scoped intent replays after the target editor activates.
expect(navEvents).toBe(0);
} finally {
window.removeEventListener(LINT_NAV_EVENT, listener);
@@ -1038,7 +1054,12 @@ describe('ProblemsPanel — project scope', () => {
expect(window.location.hash).toBe('#/guides/setup');
expect(consumePendingSourceNavigation('guides/setup')).toEqual({
kind: 'lint',
- detail: { line: 9, column: 1, source: 'frontmatter' },
+ detail: {
+ docName: 'guides/setup',
+ line: 9,
+ column: 1,
+ source: 'frontmatter',
+ },
});
// Cross-doc clicks stay off the in-doc event (it carries no docName).
expect(navEvents).toBe(0);
@@ -1050,9 +1071,9 @@ describe('ProblemsPanel — project scope', () => {
test('clicking a project-scope diagnostic for the open doc keeps the in-doc event fast path', async () => {
runLintAuditImpl = async () =>
auditResult({ files: [{ file: 'notes.md', diagnostics: [diag({ line: 7, column: 2 })] }] });
- let received: { line: number; column: number } | null = null;
+ let received: LintNavDetail | null = null;
const listener = (e: Event) => {
- received = (e as CustomEvent<{ line: number; column: number }>).detail;
+ received = (e as CustomEvent<LintNavDetail>).detail;
};
window.addEventListener(LINT_NAV_EVENT, listener);
try {
@@ -1064,11 +1085,16 @@ describe('ProblemsPanel — project scope', () => {
fireEvent.click(screen.getByRole('button', { name: /Hard tabs/ }));
- expect(received).toEqual({ line: 7, column: 2, source: 'markdownlint' });
+ expect(received).toEqual({
+ docName: 'notes',
+ line: 7,
+ column: 2,
+ source: 'markdownlint',
+ });
expect(window.location.hash).toBe(hashBefore);
expect(consumePendingSourceNavigation('notes')).toEqual({
kind: 'lint',
- detail: { line: 7, column: 2, source: 'markdownlint' },
+ detail: { docName: 'notes', line: 7, column: 2, source: 'markdownlint' },
});
} finally {
window.removeEventListener(LINT_NAV_EVENT, listener);
diff --git a/packages/app/src/components/ProblemsPanel.tsx b/packages/app/src/components/ProblemsPanel.tsx
index eafed55f6..03d2fcee8 100644
--- a/packages/app/src/components/ProblemsPanel.tsx
+++ b/packages/app/src/components/ProblemsPanel.tsx
@@ -48,6 +48,8 @@ import { replaceValidationFromAudit } from '@/lib/validation-store';
/** Jump-to-line intent dispatched when a problem row is clicked in source mode. */
export interface LintNavDetail {
+ /** The document that owns this navigation request. */
+ docName: string;
/** 1-based line in `Y.Text('source')` (full doc incl. frontmatter). */
line: number;
/** 1-based column. */
@@ -80,8 +82,9 @@ function compareDiagnostics(a: DiagnosticLike, b: DiagnosticLike): number {
}
/** The nav contract is 1-based (CodeMirror lines); the diagnostic range is 0-based LSP. */
-function lintNavDetailOf(diagnostic: DiagnosticLike): LintNavDetail {
+function lintNavDetailOf(docName: string, diagnostic: DiagnosticLike): LintNavDetail {
return {
+ docName,
line: diagnostic.range.start.line + 1,
column: diagnostic.range.start.character + 1,
source: diagnostic.source,
@@ -750,7 +753,7 @@ export function ProblemsPanel({
useEffect(() => subscribeToLintConfigChanged(() => onLintConfigChangedRef.current()), []);
function handleNav(diagnostic: DiagnosticLike) {
- const detail = lintNavDetailOf(diagnostic);
+ const detail = lintNavDetailOf(docName, diagnostic);
// Banked unconditionally: the visible editor (source line-jump, or the
// WYSIWYG block-jump in markdown-lint-decorations) consumes the event live
// and clears the intent; when neither can anchor it (frontmatter
@@ -768,11 +771,11 @@ export function ProblemsPanel({
}
rememberPendingSourceNavigation(targetDocName, {
kind: 'lint',
- detail: lintNavDetailOf(diagnostic),
+ detail: lintNavDetailOf(targetDocName, diagnostic),
});
- // No LINT_NAV_EVENT here: the event carries no docName and would move the
- // cursor in the doc that is still open. The banked intent replays once
- // the target doc's source editor activates.
+ // The focused document changes asynchronously. Keep this navigation banked
+ // until the target's own editor is active instead of sending a live event to
+ // another visible split pane.
window.location.hash = hashFromDocName(targetDocName);
}
diff --git a/packages/app/src/components/SettingsButton.tsx b/packages/app/src/components/SettingsButton.tsx
index 827a56dae..94d9cacc8 100644
--- a/packages/app/src/components/SettingsButton.tsx
+++ b/packages/app/src/components/SettingsButton.tsx
@@ -63,6 +63,13 @@ export const SettingsButton: FC = () => {
}
};
+ const openSettings = () => {
+ cancelPreload();
+ if (window.location.hash !== SETTINGS_OPEN_HASH) {
+ window.location.hash = SETTINGS_OPEN_HASH;
+ }
+ };
+
// Cleanup on unmount: clears any pending preload timer the leave/blur
// handlers didn't catch (e.g. component unmounts mid-hover). The
// current callback is ref-only + idempotent preload, so this guard is
@@ -89,12 +96,7 @@ export const SettingsButton: FC = () => {
onMouseLeave={cancelPreload}
onFocus={schedulePreload}
onBlur={cancelPreload}
- onClick={() => {
- cancelPreload();
- if (window.location.hash !== SETTINGS_OPEN_HASH) {
- window.location.hash = SETTINGS_OPEN_HASH;
- }
- }}
+ onClick={openSettings}
>
<Settings className="size-4" />
<span className="sr-only">
diff --git a/packages/app/src/components/SkillInstallMenu.tsx b/packages/app/src/components/SkillInstallMenu.tsx
index 5d9cdd5f2..fde1b44a1 100644
--- a/packages/app/src/components/SkillInstallMenu.tsx
+++ b/packages/app/src/components/SkillInstallMenu.tsx
@@ -15,13 +15,14 @@ import { toast } from 'sonner';
import { AgentBrandIcon } from '@/components/AgentIconCluster';
import { ChangedOutsideBadge } from '@/components/ChangedOutsideBadge';
import type { SkillActions } from '@/components/skill-actions';
-import { Button } from '@/components/ui/button';
import {
- DropdownMenuCheckboxItem,
- DropdownMenuItem,
- DropdownMenuLabel,
- DropdownMenuSeparator,
-} from '@/components/ui/dropdown-menu';
+ SkillMenuCheckboxItem,
+ SkillMenuItem,
+ type SkillMenuKind,
+ SkillMenuLabel,
+ SkillMenuSeparator,
+} from '@/components/skill-menu-primitives';
+import { Button } from '@/components/ui/button';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { useSkills } from '@/hooks/use-skills';
import { emitSkillsChanged } from '@/lib/documents-events';
@@ -80,9 +81,8 @@ export interface SkillHostToggles {
/**
* The per-editor install-state machine, shared by the editor toolbar's install
- * pill (`SkillEditorActions`) AND the sidebar three-dot menu (`SkillContextMenuItems`,
- * §9.3) so the two surfaces offer the SAME control instead of the toolbar's full
- * per-editor dropdown vs. the menu's single "Install".
+ * pill (`SkillEditorActions`) and every `SkillContextMenuItems` surface so the
+ * toolbar, sidebar, and editor tab all expose the same install controls.
*
* Optimistic host overlay so RAPID per-editor toggles compose correctly: each click
* builds on the LATEST intended set (via `liveHostsRef`, updated synchronously), not
@@ -91,7 +91,7 @@ export interface SkillHostToggles {
* the marker file. `actions` is passed in so both surfaces share one install-in-flight.
*
* The overlay itself lives in a module store keyed `scope:name`, NOT in component
- * state: all three surfaces can be on screen together, and a per-component overlay
+ * state: several surfaces can be on screen together, and a per-component overlay
* meant the clicked one read "Installed" while its neighbour still read "Install".
*/
export function useSkillHostToggles(
@@ -304,6 +304,7 @@ export function SkillInstallMenuItems({
skill,
onResolveFork,
onRunStart,
+ menuKind = 'dropdown',
}: {
toggles: SkillHostToggles;
/** Each row shows the REAL target path (`.codex/skills/<name>`) — path-first
@@ -334,6 +335,8 @@ export function SkillInstallMenuItems({
* half-converted state — they flip and then settle, which reads as breakage.
*/
onRunStart?: () => void;
+ /** Match the Radix primitive family of the parent menu. */
+ menuKind?: SkillMenuKind;
}) {
const { t } = useLingui();
const { hostSet, toggleEditor, installAll } = toggles;
@@ -597,7 +600,7 @@ export function SkillInstallMenuItems({
{/* "All" rides the section label instead of being its own bottom row —
the old footer (Install-on-all + Settings, each fenced by separators)
read as three stacked strips. */}
- <DropdownMenuLabel className="flex items-center justify-between gap-2">
+ <SkillMenuLabel menuKind={menuKind} className="flex items-center justify-between gap-2">
<Trans>Install on</Trans>
<Hint hint={t`Install on all agents`}>
<Button
@@ -611,14 +614,15 @@ export function SkillInstallMenuItems({
<Trans>All</Trans>
</Button>
</Hint>
- </DropdownMenuLabel>
+ </SkillMenuLabel>
{/* The skill's OWN folder when it isn't a standard editor dir (a store
bundle / unusual location) — the true SOURCE, shown so no occupied
location is ever invisible here. Static: the source can't be
unchecked (that would be deletion). */}
{sourceRow !== null ? (
<Hint hint={t`The skill's own folder — the source other locations copy or link from`}>
- <DropdownMenuCheckboxItem
+ <SkillMenuCheckboxItem
+ menuKind={menuKind}
disabled={busy}
checked
onSelect={(e) => e.preventDefault()}
@@ -646,7 +650,7 @@ export function SkillInstallMenuItems({
<Trans>source</Trans>
</span>
</span>
- </DropdownMenuCheckboxItem>
+ </SkillMenuCheckboxItem>
</Hint>
) : null}
{rows.map((editor) => {
@@ -675,7 +679,8 @@ export function SkillInstallMenuItems({
: t`Click to install in ${label}`
}
>
- <DropdownMenuCheckboxItem
+ <SkillMenuCheckboxItem
+ menuKind={menuKind}
disabled={busy}
checked={hostSet.has(editor)}
onCheckedChange={(on) => {
@@ -766,7 +771,7 @@ export function SkillInstallMenuItems({
</Hint>
) : null}
</span>
- </DropdownMenuCheckboxItem>
+ </SkillMenuCheckboxItem>
</Hint>
);
})}
@@ -786,7 +791,8 @@ export function SkillInstallMenuItems({
: t`Copies the skill to ${r.display}`
}
>
- <DropdownMenuCheckboxItem
+ <SkillMenuCheckboxItem
+ menuKind={menuKind}
disabled={busy}
checked={r.placed !== null}
onCheckedChange={(on) => {
@@ -847,7 +853,7 @@ export function SkillInstallMenuItems({
</>
) : null}
</span>
- </DropdownMenuCheckboxItem>
+ </SkillMenuCheckboxItem>
</Hint>
))}
@@ -919,8 +925,7 @@ export function SkillInstallMenuItems({
</Hint>
</div>
) : null}
-
- <DropdownMenuSeparator />
+ <SkillMenuSeparator menuKind={menuKind} />
{/* Folder-level wiring lives one level up from this menu: this menu places
THIS skill, that pane links whole FOLDERS (so two agents share every
skill) and registers custom roots. Named for what it manages rather
@@ -929,7 +934,8 @@ export function SkillInstallMenuItems({
<Hint
hint={t`Opens Settings → Skills, where you link a whole folder into another so both agents read the same skills, and add custom skill roots.`}
>
- <DropdownMenuItem
+ <SkillMenuItem
+ menuKind={menuKind}
onSelect={() => {
// Land on the pane that governs THIS skill's folders. A global skill's
// roots live under `~`, which the project pane doesn't manage at all,
@@ -940,7 +946,7 @@ export function SkillInstallMenuItems({
>
<SettingsIcon aria-hidden />
<Trans>Manage skill folders</Trans>
- </DropdownMenuItem>
+ </SkillMenuItem>
</Hint>
</>
);
diff --git a/packages/app/src/components/editor-tabs-chrome.test.ts b/packages/app/src/components/editor-tabs-chrome.test.ts
index 879eb65c3..1c95d1cf9 100644
--- a/packages/app/src/components/editor-tabs-chrome.test.ts
+++ b/packages/app/src/components/editor-tabs-chrome.test.ts
@@ -3,13 +3,17 @@ import { describe, expect, test } from 'vitest';
import {
createTabReorderModifier,
DRAGGING_TAB_Z_INDEX,
+ editorWorkspaceCollisionDetection,
getSortableTabClassName,
getSortableTabKeyDownAction,
getSortableTabStyle,
getTabCloseButtonClass,
getTabCloseButtonTabIndex,
+ isEditorTabDragData,
+ isEditorTabDropData,
measureTabReorderBounds,
shouldActivateSortableTabFromKeyDown,
+ shouldOpenTabContextMenu,
TAB_KEYBOARD_DRAG_CODES,
TAB_REORDER_AUTO_SCROLL,
type TabReorderBounds,
@@ -100,6 +104,81 @@ function collisionArgs(pointerX: number): CollisionArgs {
};
}
+function workspaceCollisionArgs({
+ dragRect = rect(100, 40),
+ includeStrip = false,
+ pointerCoordinates = { x: 24, y: 10 },
+ splittable = true,
+}: {
+ dragRect?: ReturnType<typeof rect>;
+ includeStrip?: boolean;
+ pointerCoordinates?: { x: number; y: number } | null;
+ splittable?: boolean;
+} = {}): CollisionArgs {
+ const edge = {
+ data: {
+ current: { kind: 'pane-edge', paneId: 'pane-b', side: 'left' },
+ },
+ disabled: false,
+ id: 'pane-b-left',
+ key: 'pane-b-left',
+ node: { current: null },
+ rect: { current: null },
+ };
+ const tab = {
+ data: {
+ current: {
+ kind: 'editor-tab',
+ label: 'B',
+ paneId: 'pane-b',
+ splittable: true,
+ tabId: 'doc-b',
+ },
+ },
+ disabled: false,
+ id: 'doc-b',
+ key: 'doc-b',
+ node: { current: null },
+ rect: { current: null },
+ };
+ const strip = {
+ data: {
+ current: { kind: 'pane-strip', paneId: 'pane-b', index: 1 },
+ },
+ disabled: false,
+ id: 'pane-b-strip',
+ key: 'pane-b-strip',
+ node: { current: null },
+ rect: { current: null },
+ };
+ const droppableContainers = includeStrip ? [edge, strip, tab] : [edge, tab];
+ const droppableRects = new Map([
+ [edge.id, rect(0, 48)],
+ [tab.id, rect(100, 40)],
+ ]);
+ if (includeStrip) droppableRects.set(strip.id, rect(80, 240));
+
+ return {
+ active: {
+ data: {
+ current: {
+ kind: 'editor-tab',
+ label: 'A',
+ paneId: 'pane-a',
+ splittable,
+ tabId: 'doc-a',
+ },
+ },
+ id: 'doc-a',
+ rect: { current: { initial: null, translated: null } },
+ },
+ collisionRect: dragRect,
+ droppableContainers,
+ droppableRects,
+ pointerCoordinates,
+ };
+}
+
function sortableTabKeyDownEvent(
code: KeyboardCode,
targetIsCurrentTarget = true,
@@ -139,15 +218,20 @@ function sortableTabKeyDownActionArgs({
}
describe('editor tab chrome helpers', () => {
- test('inactive close controls are hover-only and skipped by tab navigation', () => {
+ test('inactive close controls remain hover-only', () => {
const className = getTabCloseButtonClass(false);
expect(className).toContain('opacity-0');
expect(className).toContain('pointer-events-none');
expect(className).toContain('group-hover:opacity-100');
expect(className).toContain('group-hover:pointer-events-auto');
+ expect(className).toContain('absolute');
+ expect(className).toContain('right-1');
+ expect(className).not.toContain('bg-background/80');
+ expect(className).not.toContain('backdrop-blur-sm');
expect(className).not.toContain('group-focus-within:opacity-100');
expect(className).not.toContain('focus-visible:opacity-100');
+ expect(className).not.toContain('transition');
expect(getTabCloseButtonTabIndex(false)).toBe(-1);
});
@@ -155,6 +239,8 @@ describe('editor tab chrome helpers', () => {
const className = getTabCloseButtonClass(true);
expect(className).toContain('opacity-100');
+ expect(className).toContain('mr-1');
+ expect(className).not.toContain('absolute');
expect(className).not.toContain('opacity-0');
expect(getTabCloseButtonTabIndex(true)).toBeUndefined();
});
@@ -206,6 +292,12 @@ describe('editor tab chrome helpers', () => {
).toBe(false);
});
+ test('tab context menu recognizes both standard keyboard gestures', () => {
+ expect(shouldOpenTabContextMenu({ key: 'F10', shiftKey: true })).toBe(true);
+ expect(shouldOpenTabContextMenu({ key: 'ContextMenu', shiftKey: false })).toBe(true);
+ expect(shouldOpenTabContextMenu({ key: 'F10', shiftKey: false })).toBe(false);
+ });
+
test('sortable tab keydown action activates Enter only before dragging starts', () => {
expect(
getSortableTabKeyDownAction(sortableTabKeyDownActionArgs({ code: KeyboardCode.Enter })),
@@ -273,6 +365,18 @@ describe('editor tab chrome helpers', () => {
expect(style.transform).toBe('translate3d(12px, 8px, 0) scaleX(1) scaleY(1)');
});
+ test('static tab reorder feedback suppresses movement and transform transitions', () => {
+ const style = getSortableTabStyle({
+ disableMovement: true,
+ isDragging: true,
+ transform: { scaleX: 1, scaleY: 1, x: 48, y: 0 },
+ transition: 'transform 200ms ease',
+ });
+
+ expect(style.transform).toBeUndefined();
+ expect(style.transition).toBeUndefined();
+ });
+
test('non-dragged tab style preserves caller stacking', () => {
const style = getSortableTabStyle({
isDragging: false,
@@ -345,4 +449,105 @@ describe('editor tab chrome helpers', () => {
expect(collisions.length).toBeGreaterThan(0);
expect(collisions[0]?.id).toBe('tab-a');
});
+
+ test('workspace collision detection gives a pointer-hit pane edge priority', () => {
+ expect(editorWorkspaceCollisionDetection(workspaceCollisionArgs())[0]?.id).toBe('pane-b-left');
+ });
+
+ test('workspace collision detection excludes pane edges for blank tabs and keyboard drags', () => {
+ expect(
+ editorWorkspaceCollisionDetection(
+ workspaceCollisionArgs({
+ pointerCoordinates: { x: 120, y: 10 },
+ splittable: false,
+ }),
+ )[0]?.id,
+ ).toBe('doc-b');
+ expect(
+ editorWorkspaceCollisionDetection(workspaceCollisionArgs({ pointerCoordinates: null }))[0]
+ ?.id,
+ ).toBe('doc-b');
+ });
+
+ test('workspace collision detection prefers a pointer-hit tab over its overlapping strip', () => {
+ expect(
+ editorWorkspaceCollisionDetection(
+ workspaceCollisionArgs({
+ includeStrip: true,
+ pointerCoordinates: { x: 120, y: 10 },
+ splittable: false,
+ }),
+ )[0]?.id,
+ ).toBe('doc-b');
+ });
+
+ test('workspace collision detection keeps the strip target for blank tab-row space', () => {
+ expect(
+ editorWorkspaceCollisionDetection(
+ workspaceCollisionArgs({
+ includeStrip: true,
+ pointerCoordinates: { x: 250, y: 10 },
+ splittable: false,
+ }),
+ )[0]?.id,
+ ).toBe('pane-b-strip');
+ });
+
+ test('workspace collision detection keeps tab feedback while the dragged tab overlaps the strip', () => {
+ expect(
+ editorWorkspaceCollisionDetection(
+ workspaceCollisionArgs({
+ dragRect: rect(100, 40, 15, 40),
+ includeStrip: true,
+ pointerCoordinates: { x: 140, y: 80 },
+ }),
+ )[0]?.id,
+ ).toBe('doc-b');
+ });
+
+ test('workspace collision detection ignores drags fully outside strips and split edges', () => {
+ expect(
+ editorWorkspaceCollisionDetection(
+ workspaceCollisionArgs({
+ dragRect: rect(100, 40, 80, 40),
+ includeStrip: true,
+ pointerCoordinates: { x: 140, y: 80 },
+ }),
+ ),
+ ).toEqual([]);
+ });
+
+ test('workspace drag and drop guards reject incomplete payloads', () => {
+ expect(
+ isEditorTabDragData({
+ kind: 'editor-tab',
+ label: 'A',
+ paneId: 'pane-a',
+ splittable: true,
+ tabId: 'doc-a',
+ }),
+ ).toBe(true);
+ expect(
+ isEditorTabDragData({
+ kind: 'editor-tab',
+ paneId: 'pane-a',
+ splittable: true,
+ tabId: 'doc-a',
+ }),
+ ).toBe(false);
+ expect(
+ isEditorTabDropData({
+ kind: 'pane-edge',
+ paneId: 'pane-a',
+ side: 'right',
+ }),
+ ).toBe(true);
+ expect(
+ isEditorTabDropData({
+ kind: 'pane-strip',
+ index: 1.5,
+ paneId: 'pane-a',
+ }),
+ ).toBe(false);
+ });
});
diff --git a/packages/app/src/components/editor-tabs-chrome.ts b/packages/app/src/components/editor-tabs-chrome.ts
index 55ee00dfb..db3fefda4 100644
--- a/packages/app/src/components/editor-tabs-chrome.ts
+++ b/packages/app/src/components/editor-tabs-chrome.ts
@@ -8,10 +8,33 @@ type TabDroppableContainer = Parameters<CollisionDetection>[0]['droppableContain
type SortableTabKeyDownEvent = Pick<KeyboardEvent, 'code' | 'currentTarget' | 'target'>;
type SortableTabKeyDownDecisionEvent = SortableTabKeyDownEvent &
Pick<KeyboardEvent, 'defaultPrevented'>;
+type TabContextMenuKeyDownEvent = Pick<KeyboardEvent, 'key' | 'shiftKey'>;
type SortableTabKeyDownAction = 'activate-tab' | 'delegate-sortable' | 'ignore';
+export interface EditorTabDragData {
+ kind: 'editor-tab';
+ paneId: string;
+ tabId: string;
+ splittable: boolean;
+ label: string;
+}
+
+interface PaneEdgeDropData {
+ kind: 'pane-edge';
+ paneId: string;
+ side: 'left' | 'right';
+}
+
+interface PaneStripDropData {
+ kind: 'pane-strip';
+ paneId: string;
+ index: number;
+}
+
+export type EditorTabDropData = PaneEdgeDropData | PaneStripDropData;
+
const TAB_CLOSE_BUTTON_CLASS =
- 'mr-1.5 flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-sm text-muted-foreground outline-none transition hover:bg-foreground/10 hover:text-foreground hover:opacity-100 focus-visible:ring-2 focus-visible:ring-ring/50';
+ 'flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-sm text-muted-foreground outline-none hover:bg-foreground/10 hover:text-foreground hover:opacity-100 focus-visible:ring-2 focus-visible:ring-ring/50';
const DRAGGING_TAB_ACTIVE_CLASS =
'border-border bg-background text-foreground hover:bg-background focus-visible:bg-background';
export const DRAGGING_TAB_Z_INDEX = 20;
@@ -31,8 +54,8 @@ export function getTabCloseButtonClass(isActive: boolean): string {
return cn(
TAB_CLOSE_BUTTON_CLASS,
isActive
- ? 'opacity-100'
- : 'pointer-events-none opacity-0 group-hover:pointer-events-auto group-hover:opacity-100',
+ ? 'mr-1 opacity-100'
+ : 'pointer-events-none absolute right-1 opacity-0 group-hover:pointer-events-auto group-hover:opacity-100',
);
}
@@ -54,6 +77,23 @@ export function shouldActivateSortableTabFromKeyDown(event: SortableTabKeyDownEv
return event.code === KeyboardCode.Enter && event.target === event.currentTarget;
}
+export function shouldOpenTabContextMenu(event: TabContextMenuKeyDownEvent): boolean {
+ return event.key === 'ContextMenu' || (event.shiftKey && event.key === 'F10');
+}
+
+export function findEditorTabElement(
+ root: ParentNode,
+ paneId: string,
+ tabId: string,
+): HTMLElement | null {
+ for (const element of root.querySelectorAll<HTMLElement>('[data-editor-tab-id]')) {
+ if (element.dataset.editorPaneId === paneId && element.dataset.editorTabId === tabId) {
+ return element;
+ }
+ }
+ return null;
+}
+
export function getSortableTabKeyDownAction({
event,
hasKeyboardActivation,
@@ -72,12 +112,14 @@ export function getSortableTabKeyDownAction({
export function getSortableTabStyle({
activeWidth,
+ disableMovement = false,
isDragging,
outerStyle,
transform,
transition,
}: {
activeWidth?: number | null;
+ disableMovement?: boolean;
isDragging: boolean;
outerStyle?: CSSProperties;
transform: Transform | null;
@@ -86,8 +128,10 @@ export function getSortableTabStyle({
const stableWidth = isDragging && activeWidth ? activeWidth : undefined;
return {
...outerStyle,
- transform: CSS.Transform.toString(transform ? { ...transform, scaleX: 1, scaleY: 1 } : null),
- transition,
+ transform: disableMovement
+ ? undefined
+ : CSS.Transform.toString(transform ? { ...transform, scaleX: 1, scaleY: 1 } : null),
+ transition: disableMovement ? undefined : transition,
flexBasis: stableWidth ?? outerStyle?.flexBasis,
maxWidth: stableWidth ?? outerStyle?.maxWidth,
minWidth: stableWidth ?? outerStyle?.minWidth,
@@ -129,6 +173,118 @@ export function createTabReorderModifier(bounds: TabReorderBounds | null): Modif
};
}
+export function isEditorTabDragData(value: unknown): value is EditorTabDragData {
+ if (typeof value !== 'object' || value === null) return false;
+ const data = value as Partial<EditorTabDragData>;
+ return (
+ data.kind === 'editor-tab' &&
+ typeof data.paneId === 'string' &&
+ typeof data.tabId === 'string' &&
+ typeof data.splittable === 'boolean' &&
+ typeof data.label === 'string'
+ );
+}
+
+export function isEditorTabDropData(value: unknown): value is EditorTabDropData {
+ if (typeof value !== 'object' || value === null) return false;
+ const data = value as Partial<EditorTabDropData>;
+ if (data.kind === 'pane-edge') {
+ return typeof data.paneId === 'string' && (data.side === 'left' || data.side === 'right');
+ }
+ return (
+ data.kind === 'pane-strip' &&
+ typeof data.paneId === 'string' &&
+ typeof data.index === 'number' &&
+ Number.isInteger(data.index)
+ );
+}
+
+function pointerIsInsideRect(
+ pointer: { x: number; y: number },
+ rect: { top: number; right: number; bottom: number; left: number },
+): boolean {
+ return (
+ pointer.x >= rect.left &&
+ pointer.x <= rect.right &&
+ pointer.y >= rect.top &&
+ pointer.y <= rect.bottom
+ );
+}
+
+function rectsOverlap(
+ first: { top: number; right: number; bottom: number; left: number },
+ second: { top: number; right: number; bottom: number; left: number },
+): boolean {
+ return (
+ first.left < second.right &&
+ first.right > second.left &&
+ first.top < second.bottom &&
+ first.bottom > second.top
+ );
+}
+
+export const editorWorkspaceCollisionDetection: CollisionDetection = (args) => {
+ const edgeContainers = args.droppableContainers.filter(
+ (container) => container.data.current?.kind === 'pane-edge',
+ );
+ const tabAndStripContainers = args.droppableContainers.filter(
+ (container) => container.data.current?.kind !== 'pane-edge',
+ );
+ const activeData = args.active.data.current;
+
+ const pointerCoordinates = args.pointerCoordinates;
+ if (pointerCoordinates && isEditorTabDragData(activeData) && activeData.splittable) {
+ const edge = edgeContainers.find((container) => {
+ const rect = args.droppableRects.get(container.id);
+ return rect ? pointerIsInsideRect(pointerCoordinates, rect) : false;
+ });
+ if (edge) {
+ return [{ id: edge.id, data: { droppableContainer: edge, value: 0 } }];
+ }
+ }
+
+ if (pointerCoordinates) {
+ const pointerHitContainers = tabAndStripContainers.filter((container) => {
+ const rect = args.droppableRects.get(container.id);
+ return rect ? pointerIsInsideRect(pointerCoordinates, rect) : false;
+ });
+ if (pointerHitContainers.length > 0) {
+ const pointerHitTabs = pointerHitContainers.filter((container) =>
+ isEditorTabDragData(container.data.current),
+ );
+ return closestCenter({
+ ...args,
+ droppableContainers: pointerHitTabs.length > 0 ? pointerHitTabs : pointerHitContainers,
+ });
+ }
+
+ const overlappingStrips = tabAndStripContainers.filter((container) => {
+ const data = container.data.current;
+ const rect = args.droppableRects.get(container.id);
+ if (data?.kind !== 'pane-strip' || !rect) return false;
+ return rectsOverlap(args.collisionRect, rect);
+ });
+ if (overlappingStrips.length === 0) return [];
+
+ const paneIds = new Set(overlappingStrips.map((container) => container.data.current?.paneId));
+ const overlappingTabs = tabAndStripContainers.filter((container) => {
+ const data = container.data.current;
+ const rect = args.droppableRects.get(container.id);
+ if (!isEditorTabDragData(data) || !paneIds.has(data.paneId) || !rect) return false;
+ return rectsOverlap(args.collisionRect, rect);
+ });
+ return closestCenter({
+ ...args,
+ droppableContainers: overlappingTabs.length > 0 ? overlappingTabs : overlappingStrips,
+ });
+ }
+
+ return closestCenter({
+ ...args,
+ droppableContainers: tabAndStripContainers,
+ });
+};
+
export const tabRunCollisionDetection: CollisionDetection = (args) => {
const { droppableContainers, droppableRects, pointerCoordinates } = args;
if (pointerCoordinates) {
diff --git a/packages/app/src/components/settings/SettingsDialogBody.dom.test.tsx b/packages/app/src/components/settings/SettingsDialogBody.dom.test.tsx
index 08b3195ff..c42caa44b 100644
--- a/packages/app/src/components/settings/SettingsDialogBody.dom.test.tsx
+++ b/packages/app/src/components/settings/SettingsDialogBody.dom.test.tsx
@@ -141,6 +141,18 @@ describe('SettingsDialogBody preferences runtime', () => {
expect(field).toBeTruthy();
expect(field?.querySelector('[role="switch"]')?.getAttribute('aria-checked')).toBe('true');
+ expect(screen.getByText('Preview tabs')).toBeDefined();
+ expect(
+ screen.getByText(
+ 'Reuse one tab when clicking through the sidebars. Off opens every click in its own tab.',
+ ),
+ ).toBeDefined();
+ const previewTabsField = container.querySelector('[data-field="editor.previewTabs"]');
+ expect(previewTabsField).toBeTruthy();
+ expect(previewTabsField?.querySelector('[role="switch"]')?.getAttribute('aria-checked')).toBe(
+ 'true',
+ );
+
expect(screen.getByText('Open preview when agent edits')).toBeDefined();
expect(
screen.getByText(
@@ -168,6 +180,20 @@ describe('SettingsDialogBody preferences runtime', () => {
expect(wordWrapSwitch.getAttribute('aria-checked')).toBe('false');
});
+ test('commits editor.previewTabs changes through binding.patch', async () => {
+ const user = userEvent.setup();
+ const { binding, patches } = makeBinding();
+ renderPreferences(binding);
+
+ const previewTabsSwitch = screen.getByRole('switch', { name: 'Preview tabs' });
+ await user.click(previewTabsSwitch);
+
+ await waitFor(() => {
+ expect(patches).toEqual([{ editor: { previewTabs: false } }]);
+ });
+ expect(previewTabsSwitch.getAttribute('aria-checked')).toBe('false');
+ });
+
test('commits appearance.preview.autoOpen changes through binding.patch', async () => {
const user = userEvent.setup();
const { binding, patches } = makeBinding();
diff --git a/packages/app/src/components/settings/schema-walker.test.ts b/packages/app/src/components/settings/schema-walker.test.ts
index bdce35e87..b0e53f19d 100644
--- a/packages/app/src/components/settings/schema-walker.test.ts
+++ b/packages/app/src/components/settings/schema-walker.test.ts
@@ -56,6 +56,7 @@ describe('resolveLeafSchema against ConfigSchema', () => {
test('descends to defaulted boolean leaves', () => {
const leaf = requireLeaf(['editor', 'wordWrap']);
expect(getLeafTypeTag(leaf)).toBe('boolean');
+ expect(getLeafTypeTag(requireLeaf(['editor', 'previewTabs']))).toBe('boolean');
});
test('returns undefined for non-existent path', () => {
@@ -75,4 +76,8 @@ describe('getFieldDefault against ConfigSchema', () => {
test('returns defaults for editor.wordWrap', () => {
expect(getFieldDefault(requireLeaf(['editor', 'wordWrap']))).toBe(true);
});
+
+ test('returns defaults for editor.previewTabs', () => {
+ expect(getFieldDefault(requireLeaf(['editor', 'previewTabs']))).toBe(true);
+ });
});
diff --git a/packages/app/src/components/settings/settings-search-index.test.ts b/packages/app/src/components/settings/settings-search-index.test.ts
index 4e91bd4c9..08bffe9f9 100644
--- a/packages/app/src/components/settings/settings-search-index.test.ts
+++ b/packages/app/src/components/settings/settings-search-index.test.ts
@@ -1,6 +1,8 @@
import { MARKDOWNLINT_RULE_CATALOG } from '@inkeep/open-knowledge-core';
-import { describe, expect, test } from 'vitest';
+import type { MessageDescriptor } from '@lingui/core';
+import { describe, expect, test, vi } from 'vitest';
import { matchesCommandQuery } from '@/components/command-palette-search';
+import { FIELDS_USER_PREFERENCES } from './settings-fields';
import { buildSettingsSearchIndex } from './settings-search-index';
import type { SidebarGroup } from './settings-sidebar-types';
@@ -53,13 +55,40 @@ describe('buildSettingsSearchIndex', () => {
});
test('indexes preferences fields (visible section) with description keywords + targetField', () => {
- const entries = buildSettingsSearchIndex({ groups: groupsFixture({}), translate });
+ const previewField = FIELDS_USER_PREFERENCES.find(
+ (field) => field.path.join('.') === 'editor.previewTabs',
+ );
+ expect(previewField).toBeDefined();
+ if (!previewField?.description) throw new Error('expected preview tabs field description');
+
+ const labelSentinel = 'preview-tabs-label-sentinel';
+ const descriptionSentinel = 'preview-tabs-description-sentinel';
+ const structuralTranslate = vi.fn((message: MessageDescriptor) => {
+ if (message === previewField.label) return labelSentinel;
+ if (message === previewField.description) return descriptionSentinel;
+ return message.id ?? '';
+ });
+ const entries = buildSettingsSearchIndex({
+ groups: groupsFixture({}),
+ translate: structuralTranslate,
+ });
const fieldEntries = entries.filter((e) => e.kind === 'field' && e.sectionId === 'preferences');
expect(fieldEntries.length).toBeGreaterThan(0);
const wordWrap = fieldEntries.find((e) => e.targetField === 'editor.wordWrap');
expect(wordWrap).toBeDefined();
expect(wordWrap?.kind).toBe('field');
expect(wordWrap?.sectionId).toBe('preferences');
+
+ const previewTabs = fieldEntries.find((e) => e.targetField === 'editor.previewTabs');
+ expect(previewTabs).toMatchObject({
+ kind: 'field',
+ sectionId: 'preferences',
+ label: labelSentinel,
+ keywords: [descriptionSentinel],
+ targetField: 'editor.previewTabs',
+ });
+ expect(structuralTranslate).toHaveBeenCalledWith(previewField.label);
+ expect(structuralTranslate).toHaveBeenCalledWith(previewField.description);
});
test('theme field indexed only when the theme plugin is a visible section', () => {
diff --git a/packages/app/src/components/skill-actions.tsx b/packages/app/src/components/skill-actions.tsx
index 4c5d20a8c..3aa327736 100644
--- a/packages/app/src/components/skill-actions.tsx
+++ b/packages/app/src/components/skill-actions.tsx
@@ -18,6 +18,7 @@ import {
import { type ReactNode, useState } from 'react';
import { toast } from 'sonner';
import { OpenInAgentContextSubmenu } from '@/components/handoff/OpenInAgentContextSubmenu';
+import { OpenInAgentEmptySpaceSubmenu } from '@/components/handoff/OpenInAgentEmptySpaceSubmenu';
import {
buildSkillHandoffInput,
useHandoffDispatch,
@@ -41,15 +42,17 @@ import {
import { SkillRenameDialog } from '@/components/SkillRenameDialog';
import { SkillScopeMoveDialog, type SkillScopeMoveTarget } from '@/components/SkillScopeMoveDialog';
import {
- DropdownMenuItem,
- DropdownMenuSeparator,
- DropdownMenuSub,
- DropdownMenuSubContent,
- DropdownMenuSubTrigger,
-} from '@/components/ui/dropdown-menu';
+ SkillMenuGroup,
+ SkillMenuItem,
+ type SkillMenuKind,
+ SkillMenuSeparator,
+ SkillMenuSub,
+ SkillMenuSubContent,
+ SkillMenuSubTrigger,
+} from '@/components/skill-menu-primitives';
import { useOpenSkill } from '@/hooks/use-open-skill';
import { scheduleClipboardWrite } from '@/lib/share/clipboard-adapter';
-import { useSkillScopeLabels } from '@/lib/skill-scope';
+import { skillDir, useSkillScopeLabels } from '@/lib/skill-scope';
import { convertSkillLocation, duplicateSkill, installSkill } from '@/lib/skills-api';
import { useWorkspace } from '@/lib/use-workspace';
@@ -323,33 +326,26 @@ export function useSkillActions(): SkillActions {
const EMPTY_NAME_SET: ReadonlySet<string> = new Set();
/**
- * The full per-skill context menu for the file-sidebar Skills rows. Mirrors a
- * file row's menu (Reveal in Finder / Open with AI / Open in Terminal / Copy
- * Path / Duplicate / Rename / Delete) with Install/Uninstall in place of "Hide".
- * Reuses the file menu's own primitives — the desktop bridge (`showItemInFolder`),
- * `OpenInAgentContextSubmenu` (which carries the docked-terminal launch), and the
- * clipboard adapter — plus `useSkillActions` for the install/duplicate/rename/delete flow.
- * No "Edit" row: clicking the sidebar row opens the editor, like a file.
- */
-/**
- * Menu for a bundle FILE row (references/ + scripts/ + assets) inside a skill —
- * the skill-level actions (install/rename/delete) don't apply, so it offers just
- * Reveal + Copy Path, resolved against the file's own path (skill dir + the
- * file's relative path). Reuses the same desktop bridge + clipboard primitives.
+ * File actions shared by bundle-file rows in the Skills sidebar and editor tabs.
+ * Paths resolve from the skill directory rather than from its SKILL.md entry.
*/
export function SkillFileContextMenuItems({
skill,
filePath,
actions,
+ menuKind = 'dropdown',
}: {
skill: SkillsListEntry;
filePath: string;
actions: SkillActions;
+ menuKind?: SkillMenuKind;
}) {
const { t } = useLingui();
const bridge = typeof window !== 'undefined' ? window.okDesktop : undefined;
- const absoluteFile = skill.absolutePath ? `${skill.absolutePath}/${filePath}` : undefined;
- const relativeFile = `${skill.path}/${filePath}`;
+ const absoluteFile = skill.absolutePath
+ ? `${skillDir(skill.absolutePath)}/${filePath}`
+ : undefined;
+ const relativeFile = `${skillDir(skill.path)}/${filePath}`;
async function copy(text: string) {
try {
@@ -361,54 +357,113 @@ export function SkillFileContextMenuItems({
}
return (
- <>
- <DropdownMenuItem onSelect={() => actions.requestFileRename(skill, filePath)}>
+ <SkillMenuGroup menuKind={menuKind}>
+ <SkillMenuItem
+ menuKind={menuKind}
+ onSelect={() => actions.requestFileRename(skill, filePath)}
+ >
<PencilLine aria-hidden />
<Trans>Rename</Trans>
- </DropdownMenuItem>
+ </SkillMenuItem>
{bridge && absoluteFile ? (
- <DropdownMenuItem onSelect={() => void bridge.shell.showItemInFolder(absoluteFile)}>
+ <SkillMenuItem
+ menuKind={menuKind}
+ onSelect={() => void bridge.shell.showItemInFolder(absoluteFile)}
+ >
<FolderOpen aria-hidden />
<Trans>Reveal in Finder</Trans>
- </DropdownMenuItem>
+ </SkillMenuItem>
) : null}
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>
+ <SkillMenuSub menuKind={menuKind}>
+ <SkillMenuSubTrigger menuKind={menuKind}>
<Copy aria-hidden />
<Trans>Copy Path</Trans>
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent>
- {absoluteFile ? (
- <DropdownMenuItem onSelect={() => void copy(absoluteFile)}>
- <Trans>Full Path</Trans>
- </DropdownMenuItem>
- ) : null}
- <DropdownMenuItem onSelect={() => void copy(relativeFile)}>
- <Trans>Relative Path</Trans>
- </DropdownMenuItem>
- </DropdownMenuSubContent>
- </DropdownMenuSub>
- </>
+ </SkillMenuSubTrigger>
+ <SkillMenuSubContent menuKind={menuKind}>
+ <SkillMenuGroup menuKind={menuKind}>
+ {absoluteFile ? (
+ <SkillMenuItem menuKind={menuKind} onSelect={() => void copy(absoluteFile)}>
+ <Trans>Full Path</Trans>
+ </SkillMenuItem>
+ ) : null}
+ <SkillMenuItem menuKind={menuKind} onSelect={() => void copy(relativeFile)}>
+ <Trans>Relative Path</Trans>
+ </SkillMenuItem>
+ </SkillMenuGroup>
+ </SkillMenuSubContent>
+ </SkillMenuSub>
+ </SkillMenuGroup>
);
}
+/**
+ * The full per-skill action menu shared by Skills sidebar rows and editor tabs.
+ * Callers select the matching Radix primitive family while every mutation still
+ * routes through `useSkillActions`, keeping dialogs and confirmation behavior identical.
+ */
export function SkillContextMenuItems({
skill,
actions,
existingNames,
+ menuKind = 'dropdown',
}: {
skill: SkillsListEntry;
actions: SkillActions;
existingNames: ReadonlySet<string>;
+ menuKind?: SkillMenuKind;
}) {
- const { t } = useLingui();
const workspace = useWorkspace();
- const scopeLabels = useSkillScopeLabels();
const installStates = useInstalledAgents().states;
const { dispatch } = useHandoffDispatch();
+ const bridge = typeof window !== 'undefined' ? window.okDesktop : undefined;
+ const input = buildSkillHandoffInput({
+ skillName: skill.name,
+ scope: skill.scope,
+ workspace,
+ });
+
+ return (
+ <SkillTargetMenuItems
+ actions={actions}
+ existingNames={existingNames}
+ menuKind={menuKind}
+ skill={skill}
+ openWithAi={
+ menuKind === 'context' ? (
+ <OpenInAgentEmptySpaceSubmenu
+ input={input}
+ installStates={installStates}
+ dispatch={dispatch}
+ />
+ ) : (
+ <OpenInAgentContextSubmenu
+ input={input}
+ installStates={installStates}
+ isElectronHost={bridge != null}
+ dispatch={dispatch}
+ />
+ )
+ }
+ />
+ );
+}
+
+function SkillTargetMenuItems({
+ actions,
+ existingNames,
+ menuKind,
+ openWithAi,
+ skill,
+}: {
+ actions: SkillActions;
+ existingNames: ReadonlySet<string>;
+ menuKind: SkillMenuKind;
+ openWithAi: ReactNode;
+ skill: SkillsListEntry;
+}) {
+ const { t } = useLingui();
+ const scopeLabels = useSkillScopeLabels();
const hostToggles = useSkillHostToggles(skill, actions);
- // Desktop-only rows (Reveal / Terminal) render only in OK Desktop; the bridge
- // is absent on the web host, like the file menu's reveal row.
const bridge = typeof window !== 'undefined' ? window.okDesktop : undefined;
const absolutePath = skill.absolutePath;
@@ -423,88 +478,97 @@ export function SkillContextMenuItems({
return (
<>
- {bridge && absolutePath ? (
- <DropdownMenuItem onSelect={() => void bridge.shell.showItemInFolder(absolutePath)}>
- <FolderOpen aria-hidden />
- <Trans>Reveal in Finder</Trans>
- </DropdownMenuItem>
- ) : null}
- {/* Open in Terminal lives inside this submenu now (docked terminal + AI
- handoff) — the standalone system-terminal item was removed app-wide
- when the in-app shell landed. */}
- <OpenInAgentContextSubmenu
- input={buildSkillHandoffInput({ skillName: skill.name, scope: skill.scope, workspace })}
- installStates={installStates}
- isElectronHost={bridge != null}
- dispatch={dispatch}
- />
- {/* Always available: Relative Path needs no host. Full Path appears once
- the server has supplied the skill's absolute path (always, post-build;
- absent only on a cold partial entry). */}
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>
- <Copy aria-hidden />
- <Trans>Copy Path</Trans>
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent>
- {absolutePath ? (
- <DropdownMenuItem onSelect={() => void copy(absolutePath)}>
- <Trans>Full Path</Trans>
- </DropdownMenuItem>
- ) : null}
- <DropdownMenuItem onSelect={() => void copy(skill.path)}>
- <Trans>Relative Path</Trans>
- </DropdownMenuItem>
- </DropdownMenuSubContent>
- </DropdownMenuSub>
- <DropdownMenuSeparator />
- <DropdownMenuItem onSelect={() => void actions.duplicate(skill, existingNames)}>
- <CopyPlus aria-hidden />
- <Trans>Duplicate</Trans>
- </DropdownMenuItem>
- <DropdownMenuItem onSelect={() => actions.requestRename(skill, existingNames)}>
- <PencilLine aria-hidden />
- <Trans>Rename</Trans>
- </DropdownMenuItem>
- <DropdownMenuItem onSelect={() => actions.requestFileCreate(skill)}>
- <FilePlus aria-hidden />
- <Trans>New file</Trans>
- </DropdownMenuItem>
- {/* Per-editor install submenu — the SAME control as the editor toolbar's
- install pill, so the row menu no longer offers only a bare "Install" while
- the editor offers a per-platform dropdown (§9.3). */}
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>
- <DownloadCloud aria-hidden />
- <Trans>Install</Trans>
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent className={SKILL_INSTALL_MENU_WIDTH}>
- <SkillInstallMenuItems
- toggles={hostToggles}
- skill={skill}
- onResolveFork={(editor) => actions.requestForkResolve(skill, editor)}
- />
- </DropdownMenuSubContent>
- </DropdownMenuSub>
- {/* Scope switch in the menu (§9.5) — the toolbar's level Select hides when the
- pane is narrow, so surface the project↔global move here too. */}
- <DropdownMenuItem
- onSelect={() =>
- actions.requestScopeMove(skill, skill.scope === 'project' ? 'global' : 'project')
- }
- >
- <ArrowLeftRight aria-hidden />
- {skill.scope === 'project' ? (
- <Trans>Move to {scopeLabels.global}</Trans>
- ) : (
- <Trans>Move to {scopeLabels.project}</Trans>
- )}
- </DropdownMenuItem>
- <DropdownMenuSeparator />
- <DropdownMenuItem variant="destructive" onSelect={() => actions.requestDelete(skill)}>
- <Trash2 aria-hidden />
- <Trans>Delete</Trans>
- </DropdownMenuItem>
+ <SkillMenuGroup menuKind={menuKind}>
+ {bridge && absolutePath ? (
+ <SkillMenuItem
+ menuKind={menuKind}
+ onSelect={() => void bridge.shell.showItemInFolder(absolutePath)}
+ >
+ <FolderOpen aria-hidden />
+ <Trans>Reveal in Finder</Trans>
+ </SkillMenuItem>
+ ) : null}
+ {openWithAi}
+ <SkillMenuSub menuKind={menuKind}>
+ <SkillMenuSubTrigger menuKind={menuKind}>
+ <Copy aria-hidden />
+ <Trans>Copy Path</Trans>
+ </SkillMenuSubTrigger>
+ <SkillMenuSubContent menuKind={menuKind}>
+ <SkillMenuGroup menuKind={menuKind}>
+ {absolutePath ? (
+ <SkillMenuItem menuKind={menuKind} onSelect={() => void copy(absolutePath)}>
+ <Trans>Full Path</Trans>
+ </SkillMenuItem>
+ ) : null}
+ <SkillMenuItem menuKind={menuKind} onSelect={() => void copy(skill.path)}>
+ <Trans>Relative Path</Trans>
+ </SkillMenuItem>
+ </SkillMenuGroup>
+ </SkillMenuSubContent>
+ </SkillMenuSub>
+ </SkillMenuGroup>
+ <SkillMenuSeparator menuKind={menuKind} />
+ <SkillMenuGroup menuKind={menuKind}>
+ <SkillMenuItem
+ menuKind={menuKind}
+ onSelect={() => void actions.duplicate(skill, existingNames)}
+ >
+ <CopyPlus aria-hidden />
+ <Trans>Duplicate</Trans>
+ </SkillMenuItem>
+ <SkillMenuItem
+ menuKind={menuKind}
+ onSelect={() => actions.requestRename(skill, existingNames)}
+ >
+ <PencilLine aria-hidden />
+ <Trans>Rename</Trans>
+ </SkillMenuItem>
+ <SkillMenuItem menuKind={menuKind} onSelect={() => actions.requestFileCreate(skill)}>
+ <FilePlus aria-hidden />
+ <Trans>New file</Trans>
+ </SkillMenuItem>
+ <SkillMenuSub menuKind={menuKind}>
+ <SkillMenuSubTrigger menuKind={menuKind}>
+ <DownloadCloud aria-hidden />
+ <Trans>Install</Trans>
+ </SkillMenuSubTrigger>
+ <SkillMenuSubContent menuKind={menuKind} className={SKILL_INSTALL_MENU_WIDTH}>
+ <SkillMenuGroup menuKind={menuKind}>
+ <SkillInstallMenuItems
+ toggles={hostToggles}
+ skill={skill}
+ menuKind={menuKind}
+ onResolveFork={(editor) => actions.requestForkResolve(skill, editor)}
+ />
+ </SkillMenuGroup>
+ </SkillMenuSubContent>
+ </SkillMenuSub>
+ <SkillMenuItem
+ menuKind={menuKind}
+ onSelect={() =>
+ actions.requestScopeMove(skill, skill.scope === 'project' ? 'global' : 'project')
+ }
+ >
+ <ArrowLeftRight aria-hidden />
+ {skill.scope === 'project' ? (
+ <Trans>Move to {scopeLabels.global}</Trans>
+ ) : (
+ <Trans>Move to {scopeLabels.project}</Trans>
+ )}
+ </SkillMenuItem>
+ </SkillMenuGroup>
+ <SkillMenuSeparator menuKind={menuKind} />
+ <SkillMenuGroup menuKind={menuKind}>
+ <SkillMenuItem
+ menuKind={menuKind}
+ variant="destructive"
+ onSelect={() => actions.requestDelete(skill)}
+ >
+ <Trash2 aria-hidden />
+ <Trans>Delete</Trans>
+ </SkillMenuItem>
+ </SkillMenuGroup>
</>
);
}
diff --git a/packages/app/src/components/skill-menu-primitives.tsx b/packages/app/src/components/skill-menu-primitives.tsx
new file mode 100644
index 000000000..b7a4f3004
--- /dev/null
+++ b/packages/app/src/components/skill-menu-primitives.tsx
@@ -0,0 +1,105 @@
+import type { ComponentProps } from 'react';
+import {
+ ContextMenuCheckboxItem,
+ ContextMenuGroup,
+ ContextMenuItem,
+ ContextMenuLabel,
+ ContextMenuSeparator,
+ ContextMenuSub,
+ ContextMenuSubContent,
+ ContextMenuSubTrigger,
+} from '@/components/ui/context-menu';
+import {
+ DropdownMenuCheckboxItem,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
+} from '@/components/ui/dropdown-menu';
+
+export type SkillMenuKind = 'context' | 'dropdown';
+
+type MenuKindProp = { menuKind: SkillMenuKind };
+
+export function SkillMenuGroup({
+ menuKind,
+ ...props
+}: MenuKindProp & ComponentProps<typeof DropdownMenuGroup>) {
+ return menuKind === 'context' ? (
+ <ContextMenuGroup {...props} />
+ ) : (
+ <DropdownMenuGroup {...props} />
+ );
+}
+
+export function SkillMenuItem({
+ menuKind,
+ ...props
+}: MenuKindProp & ComponentProps<typeof DropdownMenuItem>) {
+ return menuKind === 'context' ? <ContextMenuItem {...props} /> : <DropdownMenuItem {...props} />;
+}
+
+export function SkillMenuCheckboxItem({
+ menuKind,
+ ...props
+}: MenuKindProp & ComponentProps<typeof DropdownMenuCheckboxItem>) {
+ return menuKind === 'context' ? (
+ <ContextMenuCheckboxItem {...props} />
+ ) : (
+ <DropdownMenuCheckboxItem {...props} />
+ );
+}
+
+export function SkillMenuLabel({
+ menuKind,
+ ...props
+}: MenuKindProp & ComponentProps<typeof DropdownMenuLabel>) {
+ return menuKind === 'context' ? (
+ <ContextMenuLabel {...props} />
+ ) : (
+ <DropdownMenuLabel {...props} />
+ );
+}
+
+export function SkillMenuSeparator({
+ menuKind,
+ ...props
+}: MenuKindProp & ComponentProps<typeof DropdownMenuSeparator>) {
+ return menuKind === 'context' ? (
+ <ContextMenuSeparator {...props} />
+ ) : (
+ <DropdownMenuSeparator {...props} />
+ );
+}
+
+export function SkillMenuSub({
+ menuKind,
+ ...props
+}: MenuKindProp & ComponentProps<typeof DropdownMenuSub>) {
+ return menuKind === 'context' ? <ContextMenuSub {...props} /> : <DropdownMenuSub {...props} />;
+}
+
+export function SkillMenuSubContent({
+ menuKind,
+ ...props
+}: MenuKindProp & ComponentProps<typeof DropdownMenuSubContent>) {
+ return menuKind === 'context' ? (
+ <ContextMenuSubContent {...props} />
+ ) : (
+ <DropdownMenuSubContent {...props} />
+ );
+}
+
+export function SkillMenuSubTrigger({
+ menuKind,
+ ...props
+}: MenuKindProp & ComponentProps<typeof DropdownMenuSubTrigger>) {
+ return menuKind === 'context' ? (
+ <ContextMenuSubTrigger {...props} />
+ ) : (
+ <DropdownMenuSubTrigger {...props} />
+ );
+}
diff --git a/packages/app/src/components/ui/resizable.tsx b/packages/app/src/components/ui/resizable.tsx
index ef5e40374..8e7739fcb 100644
--- a/packages/app/src/components/ui/resizable.tsx
+++ b/packages/app/src/components/ui/resizable.tsx
@@ -19,6 +19,7 @@ function ResizablePanel({ ...props }: ResizablePrimitive.PanelProps) {
function ResizableHandle({
withHandle,
className,
+ children,
...props
}: ResizablePrimitive.SeparatorProps & {
withHandle?: boolean;
@@ -33,6 +34,7 @@ function ResizableHandle({
{...props}
>
{withHandle && <div className="z-10 flex h-6 w-1 shrink-0 rounded-lg bg-border" />}
+ {children}
</ResizablePrimitive.Separator>
);
}
diff --git a/packages/app/src/editor/DocumentContext.dom.test.tsx b/packages/app/src/editor/DocumentContext.dom.test.tsx
index 44c3a26e9..971393cc6 100644
--- a/packages/app/src/editor/DocumentContext.dom.test.tsx
+++ b/packages/app/src/editor/DocumentContext.dom.test.tsx
@@ -5,7 +5,7 @@ import { afterEach, describe, expect, test, vi } from 'vitest';
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 } from './editor-tabs';
+import { assetTabId, docTabId, localTabSessionStorageKey, skillFileTabId } from './editor-tabs';
let mockCollabUrl: string | null = null;
@@ -25,56 +25,209 @@ const PINNED_TAB_ID = docTabId('Pinned.md');
const OTHER_TAB_ID = docTabId('Other.md');
const THIRD_TAB_ID = docTabId('Third.md');
const LICENSE_TAB_ID = assetTabId('LICENSE');
+const SKILL_TAB_ID = skillFileTabId({ scope: 'project', name: 'example', path: 'SKILL.md' });
const originalFetch = globalThis.fetch;
+function persistedTabSession(
+ openTabs: string[],
+ pinnedTabIds: string[],
+ activeTabId: string | null,
+ updatedAt: string | null,
+) {
+ return {
+ activeTabByMode: { files: null, skills: null },
+ updatedAt,
+ panes: [
+ {
+ id: 'pane-main',
+ openTabs,
+ pinnedTabIds,
+ activeTabId,
+ size: 100,
+ },
+ ],
+ focusedPaneId: 'pane-main',
+ };
+}
+
function seedTabSession() {
+ window.localStorage.setItem(
+ localTabSessionStorageKey(window.location.origin),
+ JSON.stringify(
+ persistedTabSession(
+ [PINNED_TAB_ID, OTHER_TAB_ID],
+ [PINNED_TAB_ID],
+ PINNED_TAB_ID,
+ new Date('2026-05-13T00:00:00.000Z').toISOString(),
+ ),
+ ),
+ );
+}
+
+function seedActiveOtherTabSession() {
+ window.localStorage.setItem(
+ localTabSessionStorageKey(window.location.origin),
+ JSON.stringify(
+ persistedTabSession(
+ [PINNED_TAB_ID, OTHER_TAB_ID],
+ [],
+ OTHER_TAB_ID,
+ new Date('2026-05-13T00:00:00.000Z').toISOString(),
+ ),
+ ),
+ );
+}
+
+function seedThreeTabSession() {
+ window.localStorage.setItem(
+ localTabSessionStorageKey(window.location.origin),
+ JSON.stringify(
+ persistedTabSession(
+ [PINNED_TAB_ID, OTHER_TAB_ID, THIRD_TAB_ID],
+ [],
+ PINNED_TAB_ID,
+ new Date('2026-05-13T00:00:00.000Z').toISOString(),
+ ),
+ ),
+ );
+}
+
+function seedOnlyPinnedTabSession() {
+ window.localStorage.setItem(
+ localTabSessionStorageKey(window.location.origin),
+ JSON.stringify(
+ persistedTabSession(
+ [PINNED_TAB_ID],
+ [PINNED_TAB_ID],
+ PINNED_TAB_ID,
+ new Date('2026-05-13T00:00:00.000Z').toISOString(),
+ ),
+ ),
+ );
+}
+
+function seedPaneWorkspaceSession() {
window.localStorage.setItem(
localTabSessionStorageKey(window.location.origin),
JSON.stringify({
- openTabs: [PINNED_TAB_ID, OTHER_TAB_ID],
- pinnedTabIds: [PINNED_TAB_ID],
- activeDocName: 'Pinned.md',
- activeTabId: PINNED_TAB_ID,
- updatedAt: new Date('2026-05-13T00:00:00.000Z').toISOString(),
+ activeTabByMode: { files: null, skills: null },
+ panes: [
+ {
+ id: 'pane-left',
+ openTabs: [PINNED_TAB_ID, OTHER_TAB_ID],
+ pinnedTabIds: [PINNED_TAB_ID],
+ activeTabId: PINNED_TAB_ID,
+ size: 50,
+ },
+ {
+ id: 'pane-right',
+ openTabs: [THIRD_TAB_ID],
+ pinnedTabIds: [],
+ activeTabId: THIRD_TAB_ID,
+ size: 50,
+ },
+ ],
+ focusedPaneId: 'pane-right',
+ updatedAt: new Date('2026-07-23T00:00:00.000Z').toISOString(),
}),
);
}
-function seedActiveOtherTabSession() {
+function seedSurfacePaneWorkspaceSession() {
window.localStorage.setItem(
localTabSessionStorageKey(window.location.origin),
JSON.stringify({
- openTabs: [PINNED_TAB_ID, OTHER_TAB_ID],
- pinnedTabIds: [],
- activeDocName: 'Other.md',
- activeTabId: OTHER_TAB_ID,
- updatedAt: new Date('2026-05-13T00:00:00.000Z').toISOString(),
+ activeTabByMode: { files: PINNED_TAB_ID, skills: SKILL_TAB_ID },
+ panes: [
+ {
+ id: 'pane-files',
+ openTabs: [PINNED_TAB_ID],
+ pinnedTabIds: [],
+ activeTabId: PINNED_TAB_ID,
+ size: 50,
+ },
+ {
+ id: 'pane-skills',
+ openTabs: [SKILL_TAB_ID],
+ pinnedTabIds: [],
+ activeTabId: SKILL_TAB_ID,
+ size: 50,
+ },
+ ],
+ focusedPaneId: 'pane-files',
+ updatedAt: new Date('2026-08-04T00:00:00.000Z').toISOString(),
}),
);
}
-function seedThreeTabSession() {
+function seedMixedSurfacePaneWorkspaceSession() {
window.localStorage.setItem(
localTabSessionStorageKey(window.location.origin),
JSON.stringify({
- openTabs: [PINNED_TAB_ID, OTHER_TAB_ID, THIRD_TAB_ID],
- pinnedTabIds: [],
- activeDocName: 'Pinned.md',
- activeTabId: PINNED_TAB_ID,
- updatedAt: new Date('2026-05-13T00:00:00.000Z').toISOString(),
+ panes: [
+ {
+ id: 'pane-left',
+ openTabs: [PINNED_TAB_ID],
+ pinnedTabIds: [],
+ activeTabId: PINNED_TAB_ID,
+ size: 50,
+ },
+ {
+ id: 'pane-right',
+ openTabs: [OTHER_TAB_ID, SKILL_TAB_ID],
+ pinnedTabIds: [],
+ activeTabId: SKILL_TAB_ID,
+ size: 50,
+ },
+ ],
+ focusedPaneId: 'pane-left',
+ updatedAt: new Date('2026-08-04T00:00:00.000Z').toISOString(),
}),
);
}
-function seedOnlyPinnedTabSession() {
+function seedReloadedFileOverSkillSession() {
window.localStorage.setItem(
localTabSessionStorageKey(window.location.origin),
JSON.stringify({
- openTabs: [PINNED_TAB_ID],
- pinnedTabIds: [PINNED_TAB_ID],
- activeDocName: 'Pinned.md',
- activeTabId: PINNED_TAB_ID,
- updatedAt: new Date('2026-05-13T00:00:00.000Z').toISOString(),
+ activeTabByMode: { files: OTHER_TAB_ID, skills: SKILL_TAB_ID },
+ panes: [
+ {
+ id: 'pane-main',
+ openTabs: [SKILL_TAB_ID, OTHER_TAB_ID],
+ pinnedTabIds: [],
+ activeTabId: OTHER_TAB_ID,
+ size: 100,
+ },
+ ],
+ focusedPaneId: 'pane-main',
+ updatedAt: new Date('2026-08-04T00:00:00.000Z').toISOString(),
+ }),
+ );
+}
+
+function seedCloseFallbackPaneSession(leftPinned = false) {
+ window.localStorage.setItem(
+ localTabSessionStorageKey(window.location.origin),
+ JSON.stringify({
+ panes: [
+ {
+ id: 'pane-left',
+ openTabs: [OTHER_TAB_ID],
+ pinnedTabIds: leftPinned ? [OTHER_TAB_ID] : [],
+ activeTabId: OTHER_TAB_ID,
+ size: 50,
+ },
+ {
+ id: 'pane-right',
+ openTabs: [PINNED_TAB_ID],
+ pinnedTabIds: [PINNED_TAB_ID],
+ activeTabId: PINNED_TAB_ID,
+ size: 50,
+ },
+ ],
+ focusedPaneId: 'pane-right',
+ updatedAt: new Date('2026-08-04T00:00:00.000Z').toISOString(),
}),
);
}
@@ -91,7 +244,9 @@ interface DeferredSessionBridgeStub {
resolveSession(): void;
}
-function makeEditorBridgeStub(): EditorBridgeStub {
+function makeEditorBridgeStub(
+ sessionState = persistedTabSession([], [], null, null),
+): EditorBridgeStub {
const bridge = {
config: {
mode: 'editor',
@@ -102,13 +257,7 @@ function makeEditorBridgeStub(): EditorBridgeStub {
},
onMenuAction: () => () => {},
project: {
- getSessionState: async () => ({
- openTabs: [],
- pinnedTabIds: [],
- activeDocName: null,
- activeTabId: null,
- updatedAt: null,
- }),
+ getSessionState: async () => sessionState,
setSessionState: async () => undefined,
},
} as unknown as OkDesktopBridge;
@@ -124,13 +273,9 @@ function makeEditorBridgeStub(): EditorBridgeStub {
};
}
-function makeDeferredSessionBridgeStub(state: {
- openTabs: string[];
- pinnedTabIds: string[];
- activeDocName: string | null;
- activeTabId: string | null;
- updatedAt: string | null;
-}): DeferredSessionBridgeStub {
+function makeDeferredSessionBridgeStub(
+ state: ReturnType<typeof persistedTabSession>,
+): DeferredSessionBridgeStub {
let resolveSession: (() => void) | null = null;
const sessionLoaded = new Promise<typeof state>((resolve) => {
resolveSession = () => resolve(state);
@@ -183,13 +328,45 @@ function CloseActiveHarness() {
<span data-testid="active-tab">{ctx.activeTabId ?? ''}</span>
<span data-testid="new-tabs">{ctx.newTabIds.join('|')}</span>
<span data-testid="active-new-tab">{ctx.activeNewTabId ?? ''}</span>
+ <span data-testid="skill-focused">{String(ctx.skillFocused)}</span>
+ <span data-testid="pane-state">
+ {ctx.panes
+ .map(
+ (pane) =>
+ `${pane.id}:${pane.openTabs.join(',')}:${pane.newTabIds.join(',')}:${pane.activeTabId ?? pane.activeNewTabId ?? ''}`,
+ )
+ .join('|')}
+ </span>
<span data-testid="close-handled">{handled}</span>
<button type="button" onClick={() => ctx.openNewTab()}>
Open new
</button>
+ <button type="button" onClick={() => ctx.setSkillsSidebar(false)}>
+ Show files
+ </button>
+ <button type="button" onClick={() => ctx.setSkillsSidebar(true)}>
+ Show skills
+ </button>
+ <button type="button" onClick={() => ctx.openNewTabInPane('pane-left')}>
+ Open new in left
+ </button>
+ <button type="button" onClick={() => ctx.focusPane('pane-right')}>
+ Focus right
+ </button>
<button type="button" onClick={() => ctx.openDocument('Other.md')}>
Open other
</button>
+ <button
+ type="button"
+ onClick={() =>
+ ctx.openTarget(
+ { kind: 'doc', target: 'Other.md', docName: 'Other.md' },
+ { disposition: 'permanent', consumeActiveNewTab: true },
+ )
+ }
+ >
+ Replace blank with other
+ </button>
<button type="button" onClick={() => ctx.closeTab(OTHER_TAB_ID)}>
Close other
</button>
@@ -226,12 +403,15 @@ function OpenLicenseDuringRestoreHarness() {
<button
type="button"
onClick={() =>
- ctx.openTarget({
- kind: 'asset',
- target: 'LICENSE',
- assetPath: 'LICENSE',
- mediaKind: null,
- })
+ ctx.openTarget(
+ {
+ kind: 'asset',
+ target: 'LICENSE',
+ assetPath: 'LICENSE',
+ mediaKind: null,
+ },
+ { disposition: 'permanent', consumeActiveNewTab: true },
+ )
}
>
Open license
@@ -240,6 +420,78 @@ function OpenLicenseDuringRestoreHarness() {
);
}
+function PaneWorkspaceHarness() {
+ const ctx = useDocumentContext();
+ return (
+ <>
+ <span data-testid="pane-count">{ctx.panes.length}</span>
+ <span data-testid="stored-pane-count">{ctx.workspace.panes.length}</span>
+ <span data-testid="focused-pane">{ctx.focusedPaneId}</span>
+ <span data-testid="active-pane-tab">{ctx.activeTabId ?? ''}</span>
+ <span data-testid="pane-tabs">
+ {ctx.panes.map((pane) => `${pane.id}:${pane.openTabs.join(',')}`).join('|')}
+ </span>
+ <span data-testid="pane-visible-tabs">
+ {ctx.panes
+ .map((pane) => `${pane.id}:${(ctx.visibleTabIdsByPane.get(pane.id) ?? []).join(',')}`)
+ .join('|')}
+ </span>
+ <span data-testid="session-loaded">{String(ctx.tabSessionLoaded)}</span>
+ <button type="button" onClick={() => ctx.focusPane('pane-left')}>
+ Focus left
+ </button>
+ <button type="button" onClick={() => ctx.focusPane('pane-right')}>
+ Focus right
+ </button>
+ <button type="button" onClick={() => ctx.activateTabInPane('pane-files', PINNED_TAB_ID)}>
+ Activate file surface
+ </button>
+ <button type="button" onClick={() => ctx.activateTabInPane('pane-skills', SKILL_TAB_ID)}>
+ Activate skill surface
+ </button>
+ <button type="button" onClick={() => ctx.activateTabInPane('pane-left', OTHER_TAB_ID)}>
+ Activate other in left
+ </button>
+ <button
+ type="button"
+ onClick={() =>
+ ctx.openTarget(
+ { kind: 'doc', target: 'Third.md', docName: 'Third.md' },
+ { disposition: 'permanent', consumeActiveNewTab: true },
+ )
+ }
+ >
+ Open existing third
+ </button>
+ <button type="button" onClick={() => ctx.splitTab(OTHER_TAB_ID, 'pane-left', 'right')}>
+ Split other
+ </button>
+ <button type="button" onClick={() => ctx.closeTabInPane('pane-left', OTHER_TAB_ID)}>
+ Close other in left
+ </button>
+ <button type="button" onClick={() => ctx.openNewTabInPane('pane-left')}>
+ Open blank in left
+ </button>
+ <button
+ type="button"
+ onClick={() => {
+ const newTabId = ctx.panes.find((pane) => pane.id === 'pane-left')?.newTabIds[0];
+ if (!newTabId) return;
+ ctx.reorderTabsInPane('pane-left', [PINNED_TAB_ID, newTabId, OTHER_TAB_ID], newTabId);
+ }}
+ >
+ Interleave blank in left
+ </button>
+ <button type="button" onClick={() => ctx.moveTabToPane(THIRD_TAB_ID, 'pane-left', 2)}>
+ Move third into visible slot
+ </button>
+ <button type="button" onClick={() => ctx.reopenClosedTab()}>
+ Reopen pane tab
+ </button>
+ </>
+ );
+}
+
function ProviderHarness({ children }: { children: ReactNode }) {
return <DocumentProvider>{children}</DocumentProvider>;
}
@@ -345,6 +597,23 @@ describe('DocumentContext tab close force contract', () => {
expect(screen.getByTestId('active-new-tab').textContent).toBe('');
});
+ test('permanent navigation consumes a blank tab when the target is already open', async () => {
+ mockCollabUrl = 'ws://localhost:1/collab';
+ globalThis.fetch = vi.fn(() => Promise.reject(new Error('unexpected fetch'))) as never;
+ seedActiveOtherTabSession();
+ render(<CloseActiveHarness />, { wrapper: ProviderHarness });
+
+ const user = userEvent.setup();
+ await user.click(screen.getByRole('button', { name: 'Open new' }));
+ expect(screen.getByTestId('active-new-tab').textContent).toBe('new-tab:1');
+
+ await user.click(screen.getByRole('button', { name: 'Replace blank with other' }));
+
+ expect(screen.getByTestId('new-tabs').textContent).toBe('');
+ expect(screen.getByTestId('active-new-tab').textContent).toBe('');
+ expect(screen.getByTestId('active-tab').textContent).toBe(OTHER_TAB_ID);
+ });
+
test('closeActiveTabOrWindow skips active pinned tab and closes the next visible unpinned tab', async () => {
seedTabSession();
render(<CloseActiveHarness />, { wrapper: ProviderHarness });
@@ -388,6 +657,39 @@ describe('DocumentContext tab close force contract', () => {
expect(screen.getByTestId('active-new-tab').textContent).toBe('');
});
+ test('closes the last Files new tab even when a hidden skill tab remains', async () => {
+ window.localStorage.setItem(
+ localTabSessionStorageKey(window.location.origin),
+ JSON.stringify(
+ persistedTabSession(
+ [SKILL_TAB_ID],
+ [],
+ SKILL_TAB_ID,
+ new Date('2026-08-04T00:00:00.000Z').toISOString(),
+ ),
+ ),
+ );
+ render(<CloseActiveHarness />, { wrapper: ProviderHarness });
+
+ const user = userEvent.setup();
+ await user.click(screen.getByRole('button', { name: 'Show files' }));
+ expect(screen.getByTestId('skill-focused').textContent).toBe('false');
+ expect(screen.getByTestId('active-new-tab').textContent).toMatch(/^new-tab:\d+$/);
+
+ await user.click(screen.getByRole('button', { name: 'Close active' }));
+
+ expect(screen.getByTestId('new-tabs').textContent).toBe('');
+ expect(screen.getByTestId('active-new-tab').textContent).toBe('');
+ expect(screen.getByTestId('active-tab').textContent).toBe('');
+ expect(screen.getByTestId('skill-focused').textContent).toBe('false');
+ expect(screen.getByTestId('open-tabs').textContent).toBe(SKILL_TAB_ID);
+
+ await user.click(screen.getByRole('button', { name: 'Show skills' }));
+
+ expect(screen.getByTestId('skill-focused').textContent).toBe('true');
+ expect(screen.getByTestId('active-tab').textContent).toBe(SKILL_TAB_ID);
+ });
+
test('closeActiveTabOrWindow reports unhandled when no visible tabs remain', async () => {
render(<CloseActiveHarness />, { wrapper: ProviderHarness });
@@ -399,10 +701,62 @@ describe('DocumentContext tab close force contract', () => {
expect(screen.getByTestId('active-tab').textContent).toBe('');
});
+ test('closeActiveTabOrWindow falls back to an unpinned tab in another pane', async () => {
+ seedCloseFallbackPaneSession();
+ render(<CloseActiveHarness />, { wrapper: ProviderHarness });
+
+ const user = userEvent.setup();
+ await user.click(screen.getByRole('button', { name: 'Close active' }));
+
+ expect(screen.getByTestId('close-handled').textContent).toBe('true');
+ expect(screen.getByTestId('pane-state').textContent).toBe(
+ `pane-right:${PINNED_TAB_ID}::${PINNED_TAB_ID}`,
+ );
+ });
+
+ test('closeActiveTabOrWindow reports unhandled when every pane contains only pinned tabs', async () => {
+ seedCloseFallbackPaneSession(true);
+ render(<CloseActiveHarness />, { wrapper: ProviderHarness });
+
+ const user = userEvent.setup();
+ await user.click(screen.getByRole('button', { name: 'Close active' }));
+
+ expect(screen.getByTestId('close-handled').textContent).toBe('false');
+ expect(screen.getByTestId('pane-state').textContent).toContain(
+ `pane-left:${OTHER_TAB_ID}::${OTHER_TAB_ID}`,
+ );
+ expect(screen.getByTestId('pane-state').textContent).toContain(
+ `pane-right:${PINNED_TAB_ID}::${PINNED_TAB_ID}`,
+ );
+ });
+
+ test('closeActiveTabOrWindow prefers a blank tab when falling back to another pane', async () => {
+ seedCloseFallbackPaneSession();
+ render(<CloseActiveHarness />, { wrapper: ProviderHarness });
+
+ const user = userEvent.setup();
+ await user.click(screen.getByRole('button', { name: 'Open new in left' }));
+ await user.click(screen.getByRole('button', { name: 'Focus right' }));
+ await user.click(screen.getByRole('button', { name: 'Close active' }));
+
+ expect(screen.getByTestId('close-handled').textContent).toBe('true');
+ expect(screen.getByTestId('pane-state').textContent).toContain(
+ `pane-left:${OTHER_TAB_ID}::${OTHER_TAB_ID}`,
+ );
+ expect(screen.getByTestId('pane-state').textContent).not.toContain('new-tab:1');
+ });
+
test('desktop close-active-tab-or-window action closes tabs before closing the editor window', async () => {
seedActiveOtherTabSession();
const closeSpy = vi.spyOn(window, 'close').mockImplementation(() => {});
- const stub = makeEditorBridgeStub();
+ const stub = makeEditorBridgeStub(
+ persistedTabSession(
+ [PINNED_TAB_ID, OTHER_TAB_ID],
+ [],
+ OTHER_TAB_ID,
+ new Date('2026-05-13T00:00:00.000Z').toISOString(),
+ ),
+ );
render(<BridgeCloseActiveHarness bridge={stub.bridge} />, { wrapper: ProviderHarness });
await new Promise((r) => setTimeout(r, 0));
@@ -437,13 +791,14 @@ const REORDER_C = docTabId('C.md');
function seedReorderSession() {
window.localStorage.setItem(
localTabSessionStorageKey(window.location.origin),
- JSON.stringify({
- openTabs: [REORDER_A, REORDER_B, REORDER_C],
- pinnedTabIds: [REORDER_A],
- activeDocName: 'A.md',
- activeTabId: REORDER_A,
- updatedAt: new Date('2026-05-16T00:00:00.000Z').toISOString(),
- }),
+ JSON.stringify(
+ persistedTabSession(
+ [REORDER_A, REORDER_B, REORDER_C],
+ [REORDER_A],
+ REORDER_A,
+ new Date('2026-05-16T00:00:00.000Z').toISOString(),
+ ),
+ ),
);
}
@@ -518,7 +873,7 @@ describe('DocumentContext reorderTabs — order + drag-mutable pin', () => {
expect(screen.getByTestId('open-tabs').textContent).toBe(
`${REORDER_C}|${REORDER_A}|${REORDER_B}`,
);
- expect(screen.getByTestId('pinned-tabs').textContent).toBe(`${REORDER_A}|${REORDER_C}`);
+ expect(screen.getByTestId('pinned-tabs').textContent).toBe(`${REORDER_C}|${REORDER_A}`);
});
test('reorderTabs is a no-op when the supplied order matches the current order', async () => {
@@ -617,26 +972,28 @@ function seedColdStartSession() {
// is already open + active while the page list is still loading.
window.localStorage.setItem(
localTabSessionStorageKey(window.location.origin),
- JSON.stringify({
- openTabs: [COLD_START_DOC],
- pinnedTabIds: [],
- activeDocName: 'event_watcher',
- activeTabId: COLD_START_DOC,
- updatedAt: new Date('2026-06-07T00:00:00.000Z').toISOString(),
- }),
+ JSON.stringify(
+ persistedTabSession(
+ [COLD_START_DOC],
+ [],
+ COLD_START_DOC,
+ new Date('2026-06-07T00:00:00.000Z').toISOString(),
+ ),
+ ),
);
}
function seedSameStemActiveMdxSession() {
window.localStorage.setItem(
localTabSessionStorageKey(window.location.origin),
- JSON.stringify({
- openTabs: [SAME_STEM_MD_TAB, SAME_STEM_MDX_TAB],
- pinnedTabIds: [],
- activeDocName: 'foo.mdx',
- activeTabId: SAME_STEM_MDX_TAB,
- updatedAt: new Date('2026-06-07T00:00:00.000Z').toISOString(),
- }),
+ JSON.stringify(
+ persistedTabSession(
+ [SAME_STEM_MD_TAB, SAME_STEM_MDX_TAB],
+ [],
+ SAME_STEM_MDX_TAB,
+ new Date('2026-06-07T00:00:00.000Z').toISOString(),
+ ),
+ ),
);
}
@@ -750,6 +1107,32 @@ describe('DocumentContext tab restore', () => {
window.location.hash = '';
});
+ test('restores the desktop session before collaboration identity resolves', async () => {
+ mockCollabUrl = 'ws://localhost:1/collab';
+ globalThis.fetch = vi.fn(() => new Promise(() => {})) as never;
+ const stub = makeDeferredSessionBridgeStub(
+ persistedTabSession(
+ [OTHER_TAB_ID],
+ [],
+ OTHER_TAB_ID,
+ new Date('2026-07-28T00:00:00.000Z').toISOString(),
+ ),
+ );
+ window.okDesktop = stub.bridge;
+
+ render(<PaneWorkspaceHarness />, { wrapper: ProviderHarness });
+
+ expect(screen.getByTestId('session-loaded').textContent).toBe('false');
+ act(() => {
+ stub.resolveSession();
+ });
+
+ await waitFor(() => {
+ expect(screen.getByTestId('session-loaded').textContent).toBe('true');
+ expect(screen.getByTestId('active-pane-tab').textContent).toBe(OTHER_TAB_ID);
+ });
+ });
+
test('restores an extension-qualified mdx tab over an ambiguous extensionless hash', async () => {
mockCollabUrl = 'ws://localhost:1/collab';
globalThis.fetch = vi.fn(() => Promise.reject(new Error('unexpected fetch'))) as never;
@@ -767,13 +1150,14 @@ describe('DocumentContext tab restore', () => {
test('keeps saved tab order when an active asset hash opens before session restore resolves', async () => {
mockCollabUrl = 'ws://localhost:1/collab';
globalThis.fetch = vi.fn(() => Promise.reject(new Error('unexpected fetch'))) as never;
- const stub = makeDeferredSessionBridgeStub({
- openTabs: [OTHER_TAB_ID, LICENSE_TAB_ID],
- pinnedTabIds: [],
- activeDocName: null,
- activeTabId: LICENSE_TAB_ID,
- updatedAt: new Date('2026-06-07T00:00:00.000Z').toISOString(),
- });
+ const stub = makeDeferredSessionBridgeStub(
+ persistedTabSession(
+ [OTHER_TAB_ID, LICENSE_TAB_ID],
+ [],
+ LICENSE_TAB_ID,
+ new Date('2026-06-07T00:00:00.000Z').toISOString(),
+ ),
+ );
window.okDesktop = stub.bridge;
window.location.hash = hashFromAssetPath('LICENSE');
@@ -797,6 +1181,195 @@ describe('DocumentContext tab restore', () => {
});
expect(window.location.hash).toBe(hashFromAssetPath('LICENSE'));
});
+
+ test('keeps a new tab active when session restore resolves afterward', async () => {
+ mockCollabUrl = 'ws://localhost:1/collab';
+ globalThis.fetch = vi.fn(() => Promise.reject(new Error('unexpected fetch'))) as never;
+ const stub = makeDeferredSessionBridgeStub(
+ persistedTabSession(
+ [OTHER_TAB_ID],
+ [],
+ OTHER_TAB_ID,
+ new Date('2026-06-07T00:00:00.000Z').toISOString(),
+ ),
+ );
+ window.okDesktop = stub.bridge;
+ window.location.hash = '#/Other.md';
+
+ render(<CloseActiveHarness />, { wrapper: ProviderHarness });
+
+ const user = userEvent.setup();
+ await user.click(screen.getByRole('button', { name: 'Open new' }));
+ expect(screen.getByTestId('active-new-tab').textContent).toBe('new-tab:1');
+
+ act(() => {
+ stub.resolveSession();
+ });
+
+ await waitFor(() => {
+ expect(screen.getByTestId('active-new-tab').textContent).toBe('new-tab:1');
+ expect(screen.getByTestId('active-tab').textContent).toBe('');
+ });
+ });
+});
+
+describe('DocumentContext pane workspace', () => {
+ afterEach(() => {
+ cleanup();
+ delete window.okDesktop;
+ mockCollabUrl = null;
+ globalThis.fetch = originalFetch;
+ window.localStorage.clear();
+ window.location.hash = '';
+ });
+
+ test('restores pane membership and projects the focused pane through compatibility globals', async () => {
+ seedPaneWorkspaceSession();
+ render(<PaneWorkspaceHarness />, { wrapper: ProviderHarness });
+
+ expect(screen.getByTestId('pane-count').textContent).toBe('2');
+ expect(screen.getByTestId('focused-pane').textContent).toBe('pane-right');
+ expect(screen.getByTestId('active-pane-tab').textContent).toBe(THIRD_TAB_ID);
+
+ const user = userEvent.setup();
+ await user.click(screen.getByRole('button', { name: 'Activate other in left' }));
+
+ expect(screen.getByTestId('focused-pane').textContent).toBe('pane-left');
+ expect(screen.getByTestId('active-pane-tab').textContent).toBe(OTHER_TAB_ID);
+ expect(window.location.hash).toBe('#/Other.md');
+ });
+
+ test('activates the first tab when a reloaded pane has no valid active tab', () => {
+ seedPaneWorkspaceSession();
+ const storageKey = localTabSessionStorageKey(window.location.origin);
+ const session = JSON.parse(window.localStorage.getItem(storageKey) ?? '{}');
+ session.panes[1].activeTabId = 'missing';
+ window.localStorage.setItem(storageKey, JSON.stringify(session));
+ window.location.hash = '#/not-open';
+
+ render(<PaneWorkspaceHarness />, { wrapper: ProviderHarness });
+
+ expect(screen.getByTestId('focused-pane').textContent).toBe('pane-right');
+ expect(screen.getByTestId('active-pane-tab').textContent).toBe(THIRD_TAB_ID);
+ });
+
+ test('removes panes with no tabs on the active surface without deleting their workspace state', async () => {
+ seedSurfacePaneWorkspaceSession();
+ render(<PaneWorkspaceHarness />, { wrapper: ProviderHarness });
+
+ expect(screen.getByTestId('pane-count').textContent).toBe('1');
+ expect(screen.getByTestId('stored-pane-count').textContent).toBe('2');
+ expect(screen.getByTestId('focused-pane').textContent).toBe('pane-files');
+
+ const user = userEvent.setup();
+ await user.click(screen.getByRole('button', { name: 'Activate skill surface' }));
+
+ expect(screen.getByTestId('pane-count').textContent).toBe('1');
+ expect(screen.getByTestId('stored-pane-count').textContent).toBe('2');
+ expect(screen.getByTestId('focused-pane').textContent).toBe('pane-skills');
+
+ await user.click(screen.getByRole('button', { name: 'Activate file surface' }));
+
+ expect(screen.getByTestId('pane-count').textContent).toBe('1');
+ expect(screen.getByTestId('stored-pane-count').textContent).toBe('2');
+ expect(screen.getByTestId('focused-pane').textContent).toBe('pane-files');
+ });
+
+ test('focuses a pane through its active-surface tab instead of revealing a hidden tab', async () => {
+ seedMixedSurfacePaneWorkspaceSession();
+ render(<PaneWorkspaceHarness />, { wrapper: ProviderHarness });
+
+ expect(screen.getByTestId('pane-count').textContent).toBe('2');
+ expect(screen.getByTestId('focused-pane').textContent).toBe('pane-left');
+
+ const user = userEvent.setup();
+ await user.click(screen.getByRole('button', { name: 'Focus right' }));
+
+ expect(screen.getByTestId('pane-count').textContent).toBe('2');
+ expect(screen.getByTestId('focused-pane').textContent).toBe('pane-right');
+ expect(screen.getByTestId('active-pane-tab').textContent).toBe(OTHER_TAB_ID);
+ });
+
+ test('does not reveal a restored skill tab when the active file tab closes', async () => {
+ seedReloadedFileOverSkillSession();
+ render(<CloseActiveHarness />, { wrapper: ProviderHarness });
+
+ expect(screen.getByTestId('active-tab').textContent).toBe(OTHER_TAB_ID);
+ expect(screen.getByTestId('skill-focused').textContent).toBe('false');
+
+ const user = userEvent.setup();
+ await user.click(screen.getByRole('button', { name: 'Close other' }));
+
+ expect(screen.getByTestId('skill-focused').textContent).toBe('false');
+ expect(screen.getByTestId('active-tab').textContent).toBe('');
+ expect(screen.getByTestId('active-new-tab').textContent).toMatch(/^new-tab:\d+$/);
+ expect(screen.getByTestId('open-tabs').textContent).toBe(SKILL_TAB_ID);
+ });
+
+ test('focuses the owning pane instead of duplicating an already-open target', async () => {
+ mockCollabUrl = 'ws://localhost:1/collab';
+ globalThis.fetch = vi.fn(() => Promise.reject(new Error('unexpected fetch'))) as never;
+ seedPaneWorkspaceSession();
+ render(<PaneWorkspaceHarness />, { wrapper: ProviderHarness });
+
+ await waitFor(() => {
+ expect(screen.getByTestId('session-loaded').textContent).toBe('true');
+ });
+ const user = userEvent.setup();
+ await user.click(screen.getByRole('button', { name: 'Focus left' }));
+ await user.click(screen.getByRole('button', { name: 'Open existing third' }));
+
+ expect(screen.getByTestId('focused-pane').textContent).toBe('pane-right');
+ expect(screen.getByTestId('active-pane-tab').textContent).toBe(THIRD_TAB_ID);
+ expect(screen.getByTestId('pane-tabs').textContent?.match(/Third\.md/g)).toHaveLength(1);
+ });
+
+ test('splits a tab into a focused pane without duplicating its target', async () => {
+ seedPaneWorkspaceSession();
+ render(<PaneWorkspaceHarness />, { wrapper: ProviderHarness });
+
+ const user = userEvent.setup();
+ await user.click(screen.getByRole('button', { name: 'Split other' }));
+
+ expect(screen.getByTestId('pane-count').textContent).toBe('3');
+ expect(screen.getByTestId('focused-pane').textContent).toBe('pane-1');
+ expect(screen.getByTestId('active-pane-tab').textContent).toBe(OTHER_TAB_ID);
+ expect(screen.getByTestId('pane-tabs').textContent?.match(/Other\.md/g)).toHaveLength(1);
+ });
+
+ test('maps a cross-pane visible drop slot around a blank tab to regular-tab order', async () => {
+ seedPaneWorkspaceSession();
+ render(<PaneWorkspaceHarness />, { wrapper: ProviderHarness });
+
+ const user = userEvent.setup();
+ await user.click(screen.getByRole('button', { name: 'Open blank in left' }));
+ await user.click(screen.getByRole('button', { name: 'Interleave blank in left' }));
+ await user.click(screen.getByRole('button', { name: 'Move third into visible slot' }));
+
+ expect(screen.getByTestId('pane-tabs').textContent).toBe(
+ `pane-left:${PINNED_TAB_ID},${THIRD_TAB_ID},${OTHER_TAB_ID}`,
+ );
+ expect(screen.getByTestId('pane-visible-tabs').textContent).toBe(
+ `pane-left:${PINNED_TAB_ID},new-tab:1,${THIRD_TAB_ID},${OTHER_TAB_ID}`,
+ );
+ });
+
+ test('reopens a background pane tab in its surviving owner pane', async () => {
+ seedPaneWorkspaceSession();
+ render(<PaneWorkspaceHarness />, { wrapper: ProviderHarness });
+
+ const user = userEvent.setup();
+ await user.click(screen.getByRole('button', { name: 'Close other in left' }));
+ expect(screen.getByTestId('pane-tabs').textContent).not.toContain(OTHER_TAB_ID);
+
+ await user.click(screen.getByRole('button', { name: 'Reopen pane tab' }));
+
+ expect(screen.getByTestId('focused-pane').textContent).toBe('pane-left');
+ expect(screen.getByTestId('active-pane-tab').textContent).toBe(OTHER_TAB_ID);
+ expect(screen.getByTestId('pane-tabs').textContent).toContain(
+ `pane-left:${PINNED_TAB_ID},${OTHER_TAB_ID}`,
+ );
+ });
});
const RENAME_FOO = docTabId('foo.md');
@@ -806,13 +1379,14 @@ const RENAME_BAZZ = docTabId('bazz.md');
function seedRenameSession() {
window.localStorage.setItem(
localTabSessionStorageKey(window.location.origin),
- JSON.stringify({
- openTabs: [RENAME_FOO, RENAME_BAR],
- pinnedTabIds: [],
- activeDocName: 'foo.md',
- activeTabId: RENAME_FOO,
- updatedAt: new Date('2026-05-16T00:00:00.000Z').toISOString(),
- }),
+ JSON.stringify(
+ persistedTabSession(
+ [RENAME_FOO, RENAME_BAR],
+ [],
+ RENAME_FOO,
+ new Date('2026-05-16T00:00:00.000Z').toISOString(),
+ ),
+ ),
);
}
@@ -838,7 +1412,12 @@ function AuthRenameHarness() {
return (
<button
type="button"
- onClick={() => ctx.openTarget({ kind: 'doc', target: 'from.md', docName: 'from.md' })}
+ onClick={() =>
+ ctx.openTarget(
+ { kind: 'doc', target: 'from.md', docName: 'from.md' },
+ { disposition: 'permanent', consumeActiveNewTab: true },
+ )
+ }
>
Select source
</button>
diff --git a/packages/app/src/editor/DocumentContext.tsx b/packages/app/src/editor/DocumentContext.tsx
index bbd28a83b..a732a3e33 100644
--- a/packages/app/src/editor/DocumentContext.tsx
+++ b/packages/app/src/editor/DocumentContext.tsx
@@ -17,7 +17,6 @@ import {
hashFromSkillFile,
hashFromSkillPreview,
hashFromSkills,
- selectedPathForSkillPreview,
skillFileFromHash,
skillPreviewFromHash,
} from '@/lib/doc-hash';
@@ -36,9 +35,27 @@ import {
} from './client-removal-reconciliation';
import { captureRenameSnapshots, subscribePoolEviction } from './editor-cache';
import {
- addOpenTab,
- addPinnedTab,
- applyDragPinMutation,
+ type EditorPaneId,
+ type EditorPaneState,
+ type EditorWorkspaceState,
+ type ExistingTabOpenBehavior,
+ findPaneOwningTab,
+ flattenWorkspacePinnedTabs,
+ flattenWorkspaceTabs,
+ focusEditorPane,
+ focusedPane,
+ hydrateEditorWorkspace,
+ normalizeEditorWorkspace,
+ type PaneSide,
+ projectVisibleEditorWorkspace,
+ type RecentlyClosedEditorTab,
+ recordRecentlyClosedTab,
+ type TabOpenDisposition,
+ tabBucketIndexForVisibleInsertion,
+ transitionEditorWorkspace,
+ updateEditorPane,
+} from './editor-panes';
+import {
assetTabId,
createEditorTabSessionState,
docNameForTabId,
@@ -48,19 +65,12 @@ import {
folderTabId,
isSkillTabId,
localTabSessionStorageKey,
- nextActiveTabAfterClose,
- nextActiveTabAfterCloseMany,
- normalizePinnedTabIds,
- openDocTab,
- openTab,
parseEditorTabId,
parseEditorTabSessionState,
readLocalTabSessionState,
reconcileVisibleTabOrder,
remapOpenTabs,
remapVisibleTabsForRename,
- removeOpenTab,
- removePinnedTab,
shouldPersistTabSession,
skillFileTabId,
skillPreviewTabId,
@@ -107,15 +117,51 @@ interface DocumentContextValue {
activeTabId: string | null;
activeDocName: string | null;
activeProvider: HocuspocusProvider | null;
+ /** Canonical side-by-side editor workspace. Flat tab fields below are compatibility projections. */
+ workspace: EditorWorkspaceState;
+ panes: ReadonlyArray<EditorPaneState>;
+ focusedPaneId: EditorPaneId;
+ focusPane: (paneId: EditorPaneId) => void;
+ activateTabInPane: (paneId: EditorPaneId, tabId: string) => void;
+ activateNewTabInPane: (paneId: EditorPaneId, tabId: string) => void;
+ openNewTabInPane: (paneId: EditorPaneId) => void;
+ closeTabInPane: (paneId: EditorPaneId, tabId: string) => void;
+ closeTabsInPane: (
+ paneId: EditorPaneId,
+ tabIds: readonly string[],
+ options?: CloseTabsOptions,
+ ) => void;
+ closeNewTabInPane: (paneId: EditorPaneId, tabId: string) => void;
+ pinTabInPane: (paneId: EditorPaneId, tabId: string) => void;
+ unpinTabInPane: (paneId: EditorPaneId, tabId: string) => void;
+ reorderTabsInPane: (
+ paneId: EditorPaneId,
+ newOrder: readonly string[],
+ draggedTabId: string,
+ ) => void;
+ moveTabToPane: (tabId: string, targetPaneId: EditorPaneId, targetIndex: number) => void;
+ splitTab: (tabId: string, targetPaneId: EditorPaneId, side: PaneSide) => EditorPaneId | null;
+ moveTabToNewPane: (tabId: string, side: PaneSide) => EditorPaneId | null;
+ resizePanes: (sizesByPane: ReadonlyMap<EditorPaneId, number>) => void;
/**
* User-open tabs, distinct from `poolEntries`: prewarmed providers can be
* pool-resident without becoming visible tabs. Document tabs use the
* docName as their ID; folder and asset tabs use internal tab IDs.
+ * Compatibility projection; pane-aware code should use `panes[].openTabs`.
*/
openTabs: ReadonlyArray<string>;
- /** Tab IDs protected from tab-strip close affordances until explicitly unpinned. */
+ /**
+ * Tab IDs protected from tab-strip close affordances until explicitly unpinned.
+ * Compatibility projection; pane-aware code should use `panes[].pinnedTabIds`.
+ */
pinnedTabIds: ReadonlyArray<string>;
- /** Visible tab-strip order across document/folder tabs and ephemeral blank tabs. */
+ /** Visible tab-strip order keyed by pane. */
+ visibleTabIdsByPane: ReadonlyMap<EditorPaneId, ReadonlyArray<string>>;
+ previewTabIdsByPane: ReadonlyMap<EditorPaneId, string | null>;
+ /**
+ * Visible tab-strip order across document/folder tabs and ephemeral blank tabs.
+ * Compatibility projection; pane-aware code should use `visibleTabIdsByPane`.
+ */
visibleTabIds: ReadonlyArray<string>;
/** True once persisted tab session restore has either applied or intentionally skipped. */
tabSessionLoaded: boolean;
@@ -150,6 +196,12 @@ interface DocumentContextValue {
* sets the new-doc intent and opens the pooled provider.
*/
openTarget: (target: ResolvedNavigationTarget, options?: OpenTargetOptions) => void;
+ /** Open a target in a specific pane, moving an existing tab there when necessary. */
+ openTargetInPane: (
+ paneId: EditorPaneId,
+ target: ResolvedNavigationTarget,
+ options?: OpenTargetOptions,
+ ) => void;
/**
* Hash-driven navigation entry (`NavigationHandler` in `App.tsx`). Kept
* alongside `openTarget` for API symmetry with `openDocumentTransition`.
@@ -158,6 +210,8 @@ interface DocumentContextValue {
* non-transition callers (tests, direct agent actions).
*/
openTargetTransition: (target: ResolvedNavigationTarget, options?: OpenTargetOptions) => void;
+ promoteTabInPane: (paneId: EditorPaneId, tabId: string) => void;
+ promoteAllPreviewTabs: () => void;
clearTarget: () => void;
closeDocument: (docName: string) => void;
/** Close the active tab if one exists; returns false when the window should close instead. */
@@ -180,7 +234,7 @@ interface DocumentContextValue {
* Every other tab keeps its pin state, so pinned and unpinned tabs still
* interleave freely (no enforced visual pin-section boundary). pinTab/
* unpinTab remain the explicit toggles. Persistence is automatic via the
- * existing effect watching openTabs/pinnedTabIds.
+ * existing effect watching workspace.
*/
reorderTabs: (newOrder: readonly string[], draggedTabId: string) => void;
/** Empty tab placeholders created by the tab strip's New tab button. */
@@ -192,8 +246,8 @@ interface DocumentContextValue {
/**
* Explicit Files/Skills surface pin. `null` = autofollow the active doc's
* surface (the default); `true`/`false` = an explicit toggle. The pin only
- * survives until the next navigation — `commitActiveTabId` re-arms it to
- * `null` — so autofollow keeps working after a toggle. Not persisted. Prefer
+ * survives until the next navigation, when pane activation re-arms it to
+ * `null`, so autofollow keeps working after a toggle. Not persisted. Prefer
* reading `skillFocused` (the resolved surface); this is the raw override.
*/
skillsSidebar: boolean | null;
@@ -372,7 +426,10 @@ interface DocumentContextValue {
closeActivityPanel: () => void;
}
-interface OpenTargetOptions {
+export interface OpenTargetOptions {
+ disposition?: TabOpenDisposition;
+ consumeActiveNewTab?: boolean;
+ /** Compatibility policy used by sidebar callers and the preview-tabs setting. */
tabBehavior?: 'append' | 'replace-active';
}
@@ -446,35 +503,11 @@ function getLocalTabSessionKey(): string | null {
}
function readInitialLocalTabSession() {
- if (typeof window === 'undefined') return parseEditorTabSessionState(null, MAX_POOL);
+ if (typeof window === 'undefined') return parseEditorTabSessionState(null);
const key = getLocalTabSessionKey();
- if (!key) return parseEditorTabSessionState(null, MAX_POOL);
+ if (!key) return parseEditorTabSessionState(null);
const storage = typeof window.localStorage !== 'undefined' ? window.localStorage : null;
- return readLocalTabSessionState(storage, key, MAX_POOL);
-}
-
-function readInitialLocalTabs(): string[] {
- return readInitialLocalTabSession().openTabs;
-}
-
-function readInitialLocalPinnedTabIds(): string[] {
- return readInitialLocalTabSession().pinnedTabIds;
-}
-
-function readInitialLocalActiveTabId(): string | null {
- // Hydrate the active-tab selection synchronously from localStorage so the
- // tab UI highlights the correct tab on first paint. A non-empty URL hash
- // is a deep-link and takes precedence — the async hydration effect handles
- // the hash-matches-saved-active case after the desktop bridge resolves.
- if (typeof window === 'undefined') return null;
- if (window.location.hash.length > 0) return null;
- const session = readInitialLocalTabSession();
- return (
- session.activeTabId ??
- (session.activeDocName ? docTabId(session.activeDocName) : null) ??
- session.openTabs[0] ??
- null
- );
+ return readLocalTabSessionState(storage, key);
}
// New tabs are ephemeral placeholders (never persisted) keyed only by identity,
@@ -495,7 +528,6 @@ export function isSkillsNewTabId(id: string | null | undefined): boolean {
function tabIdIsSkillSurface(id: string): boolean {
return isSkillsNewTabId(id) || isSkillTabId(id);
}
-
function hashFromTabId(tabId: string): string {
const tab = parseEditorTabId(tabId);
switch (tab.kind) {
@@ -507,8 +539,6 @@ function hashFromTabId(tabId: string): string {
return hashFromAssetPath(tab.assetPath);
case 'skill-file':
return hashFromSkillFile({ scope: tab.scope, name: tab.name, path: tab.path });
- case 'skills':
- return hashFromSkills();
case 'skill-preview':
return hashFromSkillPreview({
flavor: tab.flavor,
@@ -519,8 +549,10 @@ function hashFromTabId(tabId: string): string {
}
}
-function setLocationHash(hash: string) {
- if (typeof window !== 'undefined') window.location.hash = hash;
+function navigateToHash(nextHash: string): void {
+ if (typeof window !== 'undefined' && window.location.hash !== nextHash) {
+ window.location.hash = nextHash;
+ }
}
function requireRemovalReconciler(
@@ -530,6 +562,76 @@ function requireRemovalReconciler(
return reconciler;
}
+function resolvedTargetForTabId(tabId: string): ResolvedNavigationTarget {
+ const tab = parseEditorTabId(tabId);
+ switch (tab.kind) {
+ case 'doc':
+ return { kind: 'doc', target: tab.docName, docName: tab.docName };
+ case 'folder':
+ return { kind: 'folder', target: tab.folderPath, folderPath: tab.folderPath };
+ case 'asset':
+ return assetTargetForPath(tab.assetPath);
+ case 'skill-file':
+ return {
+ kind: 'skill-file',
+ target: `${tab.scope}/${tab.name}${tab.host ? `:${tab.host}` : ''}/${tab.path}`,
+ scope: tab.scope,
+ name: tab.name,
+ path: tab.path,
+ ...(tab.host ? { host: tab.host } : {}),
+ };
+ case 'skill-preview':
+ return {
+ kind: 'skill-preview',
+ target: `${tab.flavor}/${tab.source}/${tab.name}`,
+ flavor: tab.flavor,
+ source: tab.source,
+ name: tab.name,
+ subtitle: tab.subtitle,
+ level: tab.level,
+ };
+ }
+}
+
+function paneWithResolvedTarget(pane: EditorPaneState): EditorPaneState {
+ if (pane.activeNewTabId !== null || pane.activeTabId === null) {
+ return pane.activeTarget === null ? pane : { ...pane, activeTarget: null };
+ }
+ const currentTargetTabId = pane.activeTarget ? tabIdForNavigationTarget(pane.activeTarget) : null;
+ if (currentTargetTabId === pane.activeTabId) {
+ return pane;
+ }
+ return { ...pane, activeTarget: resolvedTargetForTabId(pane.activeTabId) };
+}
+
+function workspaceWithResolvedTargets(workspace: EditorWorkspaceState): EditorWorkspaceState {
+ return {
+ ...workspace,
+ panes: workspace.panes.map(paneWithResolvedTarget),
+ };
+}
+
+function readInitialEditorWorkspace(): EditorWorkspaceState {
+ const session = readInitialLocalTabSession();
+ return workspaceWithResolvedTargets(
+ hydrateEditorWorkspace({ panes: session.panes, focusedPaneId: session.focusedPaneId }),
+ );
+}
+
+function providerDocNameForPane(pane: EditorPaneState): string | null {
+ if (!pane.activeTarget || pane.activeTarget.kind === 'large-file') return null;
+ return docNameForNavigationTarget(pane.activeTarget);
+}
+
+function visibleProviderDocNames(workspace: EditorWorkspaceState): Set<string> {
+ const names = new Set<string>();
+ for (const pane of workspace.panes) {
+ const docName = providerDocNameForPane(pane);
+ if (docName) names.add(docName);
+ }
+ return names;
+}
+
function tabIdFromHash(hash: string): string | null {
const assetPath = assetPathFromHash(hash);
if (assetPath) return assetTabId(assetPath);
@@ -571,26 +673,6 @@ function assetTargetForPath(
};
}
-function activeTabIdForTarget(
- activeTarget: ResolvedNavigationTarget | null,
- activeDocName: string | null,
-): string | null {
- if (activeTarget) return tabIdForNavigationTarget(activeTarget);
- return activeDocName ? docTabId(activeDocName) : null;
-}
-
-function hasOpenDocTab(
- tabs: readonly string[],
- docName: string,
- excluding: ReadonlySet<string>,
-): boolean {
- return tabs.some((tabId) => !excluding.has(tabId) && docNameForTabId(tabId) === docName);
-}
-
-function sameTabIds(a: readonly string[], b: readonly string[]): boolean {
- return a.length === b.length && a.every((tabId, index) => tabId === b[index]);
-}
-
function navigationTargetKey(target: ResolvedNavigationTarget): string {
switch (target.kind) {
case 'doc':
@@ -691,13 +773,26 @@ function takeSnapshot(p: ProviderPool): Snapshot {
export function DocumentProvider({ children }: { children: ReactNode }) {
const [snapshot, setSnapshot] = useState<Snapshot>(EMPTY_SNAPSHOT);
- const [activeTarget, setActiveTarget] = useState<ResolvedNavigationTarget | null>(null);
- const [activeTabId, setActiveTabId] = useState<string | null>(readInitialLocalActiveTabId);
- const [openTabs, setOpenTabs] = useState<string[]>(readInitialLocalTabs);
- const [pinnedTabIds, setPinnedTabIds] = useState(readInitialLocalPinnedTabIds);
- const [newTabIds, setNewTabIds] = useState<string[]>([]);
- const [visibleTabIds, setVisibleTabIds] = useState<string[]>(openTabs);
- const [activeNewTabId, setActiveNewTabId] = useState<string | null>(null);
+ const [workspace, setWorkspace] = useState<EditorWorkspaceState>(readInitialEditorWorkspace);
+ const workspaceRef = useRef(workspace);
+ const [visibleTabIdsByPane, setVisibleTabIdsByPane] = useState(
+ () => new Map(workspace.panes.map((pane) => [pane.id, [...pane.openTabs, ...pane.newTabIds]])),
+ );
+ const visibleTabIdsByPaneRef = useRef(visibleTabIdsByPane);
+ const currentPane = focusedPane(workspace);
+ const activeTarget = currentPane.activeTarget;
+ const activeTabId = currentPane.activeTabId;
+ const openTabs = flattenWorkspaceTabs(workspace);
+ const pinnedTabIds = flattenWorkspacePinnedTabs(workspace);
+ const previewTabIdsByPane = new Map(
+ workspace.panes.map((pane) => [pane.id, pane.previewTabId] as const),
+ );
+ const activeNewTabId = currentPane.activeNewTabId;
+ const visibleTabIds = reconcileVisibleTabOrder(
+ visibleTabIdsByPane.get(currentPane.id) ?? [],
+ currentPane.openTabs,
+ currentPane.newTabIds,
+ );
const [skillsSidebar, setSkillsSidebarState] = useState<boolean | null>(null);
// Per-surface active-tab memory: switching Files/Skills restores the tab you
// last had active in that surface (or clears to its empty/home state). Kept in
@@ -707,21 +802,22 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
skills: null,
});
const [tabSessionLoaded, setTabSessionLoaded] = useState(false);
- const activeTargetRef = useRef<ResolvedNavigationTarget | null>(activeTarget);
- const activeTabIdRef = useRef<string | null>(activeTabId);
- const openTabsRef = useRef<string[]>(openTabs);
- const pinnedTabIdsRef = useRef(pinnedTabIds);
- const activeNewTabIdRef = useRef<string | null>(activeNewTabId);
- const newTabIdsRef = useRef<string[]>(newTabIds);
- const visibleTabIdsRef = useRef<string[]>(visibleTabIds);
const nextNewTabOrdinalRef = useRef(1);
- const recentlyClosedTabsRef = useRef<string[]>([]);
+ const nextPaneOrdinalRef = useRef(1);
+ const recentlyClosedTabsRef = useRef<RecentlyClosedEditorTab[]>([]);
+ const removalReconcilerRef = useRef<ClientRemovalReconciler | null>(null);
+ // Set true when the user explicitly CLOSES (or unpins/replaces) a tab during
+ // the async session-restore window. Bails the restore merge so a freshly-
+ // closed tab cannot resurrect from the about-to-arrive restored snapshot.
+ //
+ // OPENS (hash-nav, sidebar clicks, agent links) intentionally do NOT set this
+ // ref — the restore merge is additive, so an opened-during-restore tab
+ // coexists with the restored set without collision.
const tabSessionUserClosedRef = useRef(false);
// Only true once a session read RESOLVES this mount. Guards the persist
// effect below so a failed restore never overwrites the stored session with
// our empty in-memory state (a rejected read leaves it false → no write).
const restoreSucceededRef = useRef(false);
- const [tabIdentityResolved, setTabIdentityResolved] = useState(false);
const [principal, setPrincipal] = useState<Principal | null>(null);
const [systemProvider, setSystemProvider] = useState<HocuspocusProvider | null>(null);
const [docPanelMode, setDocPanelModeState] = useState<'doc' | 'agent'>('doc');
@@ -734,306 +830,99 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
retry: retryCollab,
} = useCollabUrl();
- function commitActiveTabId(nextActiveTabId: string | null) {
- const previousActiveTabId = activeTabIdRef.current;
- activeTabIdRef.current = nextActiveTabId;
- setActiveTabId(nextActiveTabId);
- // Opening a DIFFERENT tab re-arms autofollow so the sidebar surface tracks
- // the opened doc's mode (an explicit Files/Skills pin only survives until the
- // next real navigation). Two things must NOT re-arm, or an explicit pin dies:
- // - Clears (null) — the toggle's empty-surface path pins then clears.
- // - Re-activating the SAME tab — a server-driven provider reset (e.g. the
- // auth rejection when the open skill doc is deleted) re-fires a hashchange
- // for the same doc; re-arming there drops the delete-time Skills pin, and
- // once the skill target clears autofollow falls back to Files.
- if (nextActiveTabId !== null && nextActiveTabId !== previousActiveTabId) {
- setSkillsSidebarState(null);
- }
- }
-
- function commitActiveNewTabId(nextActiveNewTabId: string | null) {
- activeNewTabIdRef.current = nextActiveNewTabId;
- setActiveNewTabId(nextActiveNewTabId);
- }
-
- function commitVisibleTabIds(nextVisibleTabIds: string[]) {
- visibleTabIdsRef.current = nextVisibleTabIds;
- setVisibleTabIds((current) =>
- sameTabIds(current, nextVisibleTabIds) ? current : nextVisibleTabIds,
- );
- }
-
- function commitPinnedTabIds(nextPinnedTabIds: string[]) {
- pinnedTabIdsRef.current = nextPinnedTabIds;
- setPinnedTabIds((current) =>
- sameTabIds(current, nextPinnedTabIds) ? current : nextPinnedTabIds,
- );
- }
-
- function commitTabState(nextOpenTabs: string[], nextPinnedTabIds: readonly string[]) {
- const normalizedPinnedTabIds = normalizePinnedTabIds(nextPinnedTabIds, nextOpenTabs);
- openTabsRef.current = nextOpenTabs;
- pinnedTabIdsRef.current = normalizedPinnedTabIds;
- setOpenTabs((current) => (sameTabIds(current, nextOpenTabs) ? current : nextOpenTabs));
- setPinnedTabIds((current) =>
- sameTabIds(current, normalizedPinnedTabIds) ? current : normalizedPinnedTabIds,
- );
- commitVisibleTabIds(
- reconcileVisibleTabOrder(visibleTabIdsRef.current, nextOpenTabs, newTabIdsRef.current),
- );
- }
-
- function commitOpenTabs(nextOpenTabs: string[]) {
- commitTabState(nextOpenTabs, pinnedTabIdsRef.current);
+ function createPaneId(): EditorPaneId {
+ let paneId = '';
+ do {
+ paneId = `pane-${nextPaneOrdinalRef.current}`;
+ nextPaneOrdinalRef.current += 1;
+ } while (workspaceRef.current.panes.some((pane) => pane.id === paneId));
+ return paneId;
}
- function updateOpenTabs(updater: (current: string[]) => string[]) {
- commitOpenTabs(updater(openTabsRef.current));
- }
-
- // Set true when the user explicitly CLOSES (or unpins/replaces) a tab during
- // the async session-restore window. Bails the restore merge so a freshly-
- // closed tab cannot resurrect from the about-to-arrive restored snapshot.
- //
- // OPENS (hash-nav, sidebar clicks, agent links) intentionally do NOT set this
- // ref — the restore merge below is additive (state.openTabs ∪ openTabsRef.current),
- // so an opened-during-restore tab coexists with the restored set without
- // collision. Earlier code bailed on every mutation, which dropped the entire
- // restore on any open and broke hash-nav-while-restore-pending paths.
- //
- // Closes (and close-like replace-active) during the restore window bail the
- // restore merge. Other mutations (open, pin, activate) remain additive.
- const markTabSessionClosedDuringRestore = () => {
- if (!tabSessionLoaded) tabSessionUserClosedRef.current = true;
- };
-
- function remapTabsForRename(
- renamed: readonly { fromDocName: string; toDocName: string }[],
- renamedFolders: readonly { fromPath: string; toPath: string }[] = [],
- renamedAssets: readonly { fromPath: string; toPath: string }[] = [],
- ) {
- markTabSessionClosedDuringRestore();
- const next = remapOpenTabs(
- openTabsRef.current,
- renamed,
- MAX_POOL,
- renamedFolders,
- pinnedTabIdsRef.current,
- renamedAssets,
- );
- const nextPinnedTabIds = normalizePinnedTabIds(
- remapOpenTabs(
- pinnedTabIdsRef.current,
- renamed,
- Number.MAX_SAFE_INTEGER,
- renamedFolders,
- [],
- renamedAssets,
- ),
- next,
- );
+ function syncPoolToWorkspace(nextWorkspace: EditorWorkspaceState, updateHash = false) {
+ const focused = focusedPane(nextWorkspace);
if (collabUrl !== null) {
const p = getPool(collabUrl);
- for (const tabId of next) {
- const docName = docNameForTabId(tabId);
- if (docName) p.open(docName);
+ const visibleDocNames = visibleProviderDocNames(nextWorkspace);
+ p.setVisibleDocNames(visibleDocNames);
+ for (const docName of visibleDocNames) p.open(docName);
+
+ const docName = providerDocNameForPane(focused);
+ if (docName) {
+ p.open(docName);
+ p.setActive(docName);
+ } else {
+ p.clearActive();
}
}
- commitVisibleTabIds(
- remapVisibleTabsForRename(visibleTabIdsRef.current, renamed, renamedFolders, renamedAssets),
- );
- commitTabState(next, nextPinnedTabIds);
- const currentActiveTabId = activeTabIdRef.current;
- if (!currentActiveTabId) return;
- const remappedActiveTabId = remapOpenTabs(
- [currentActiveTabId],
- renamed,
- 1,
- renamedFolders,
- [],
- renamedAssets,
- )[0];
- if (remappedActiveTabId && next.includes(remappedActiveTabId)) {
- commitActiveTabId(remappedActiveTabId);
+ if (!updateHash) return;
+ let nextHash = '';
+ if (focused.activeNewTabId !== null) {
+ if (isSkillsNewTabId(focused.activeNewTabId)) nextHash = hashFromSkills();
+ } else if (focused.activeTabId !== null) {
+ nextHash = hashFromTabId(focused.activeTabId);
}
+ navigateToHash(nextHash);
}
- function pushRecentlyClosedTabs(tabIds: readonly string[]) {
- if (tabIds.length === 0) return;
- recentlyClosedTabsRef.current = [...recentlyClosedTabsRef.current, ...tabIds].slice(-50);
- }
-
- function closeTabIds(
- tabIds: readonly string[],
- { rememberRecentlyClosed = false }: { rememberRecentlyClosed?: boolean } = {},
- ) {
- const closingTabIds = new Set(tabIds.filter((tabId) => tabId.length > 0));
- if (closingTabIds.size === 0) return;
- markTabSessionClosedDuringRestore();
- if (rememberRecentlyClosed) {
- pushRecentlyClosedTabs(openTabsRef.current.filter((tabId) => closingTabIds.has(tabId)));
- }
- if (collabUrl !== null) {
- const p = getPool(collabUrl);
- const closingByDocName = new Map<string, Set<string>>();
- for (const tabId of closingTabIds) {
- const docName = docNameForTabId(tabId);
- if (!docName) continue;
- const tabsForDoc = closingByDocName.get(docName) ?? new Set<string>();
- tabsForDoc.add(tabId);
- closingByDocName.set(docName, tabsForDoc);
- }
- for (const [docName, tabsForDoc] of closingByDocName) {
- if (!hasOpenDocTab(openTabsRef.current, docName, tabsForDoc)) p.close(docName);
- }
+ function isSameWorkspace(left: EditorWorkspaceState, right: EditorWorkspaceState): boolean {
+ if (left.focusedPaneId !== right.focusedPaneId || left.panes.length !== right.panes.length) {
+ return false;
}
- let nextActiveTabId: string | null = null;
- const currentActiveTabId =
- activeTabId ?? activeTabIdForTarget(activeTarget, snapshot.activeDocName);
- // Keep the successor on the active tab's SURFACE (Files vs Skills): closing
- // the last skill tab must not teleport focus to a Files tab (and vice
- // versa) — the surface's empty/home state should show instead.
- const activeIsSkill = currentActiveTabId ? tabIdIsSkillSurface(currentActiveTabId) : false;
- updateOpenTabs((current) => {
- const sameSurface = current.filter((id) => tabIdIsSkillSurface(id) === activeIsSkill);
- nextActiveTabId = nextActiveTabAfterCloseMany(sameSurface, currentActiveTabId, closingTabIds);
- return current.filter((tabId) => !closingTabIds.has(tabId));
+ return left.panes.every((pane, index) => {
+ const other = right.panes[index];
+ return (
+ other !== undefined &&
+ pane.id === other.id &&
+ pane.activeTabId === other.activeTabId &&
+ pane.activeNewTabId === other.activeNewTabId &&
+ pane.previewTabId === other.previewTabId &&
+ Math.abs(pane.size - other.size) < 1e-9 &&
+ sameNavigationTarget(pane.activeTarget, other.activeTarget) &&
+ pane.openTabs.join('\0') === other.openTabs.join('\0') &&
+ pane.pinnedTabIds.join('\0') === other.pinnedTabIds.join('\0') &&
+ pane.newTabIds.join('\0') === other.newTabIds.join('\0')
+ );
});
- if (!currentActiveTabId || !closingTabIds.has(currentActiveTabId)) {
- if (!currentActiveTabId) {
- setActiveTarget((current) => {
- if (!current) return current;
- const targetTabId = tabIdForNavigationTarget(current);
- return targetTabId && closingTabIds.has(targetTabId) ? null : current;
- });
- }
+ }
+
+ function commitWorkspace(nextWorkspace: EditorWorkspaceState, updateHash = false) {
+ const normalized = workspaceWithResolvedTargets(normalizeEditorWorkspace(nextWorkspace));
+ if (isSameWorkspace(workspaceRef.current, normalized)) {
+ syncPoolToWorkspace(workspaceRef.current, updateHash);
return;
}
- if (nextActiveTabId) {
- commitActiveTabId(nextActiveTabId);
- setLocationHash(hashFromTabId(nextActiveTabId));
- return;
+ workspaceRef.current = normalized;
+ const paneIds = new Set(normalized.panes.map((pane) => pane.id));
+ for (const paneId of visibleTabIdsByPaneRef.current.keys()) {
+ if (!paneIds.has(paneId)) visibleTabIdsByPaneRef.current.delete(paneId);
}
- // No tab left on this surface → pin it so its empty/home state shows.
- setSkillsSidebarState(activeIsSkill);
- if (collabUrl !== null) getPool(collabUrl).clearActive();
- setActiveTarget(null);
- commitActiveTabId(null);
- setLocationHash('');
- }
-
- function createRemovalReconciler() {
- return createClientRemovalReconciler({
- captureRenameSnapshots,
- getActivePoolDocName: () =>
- collabUrl === null ? null : getPool(collabUrl).getActiveDocName(),
- hasPooledDocument: (docName) => collabUrl !== null && getPool(collabUrl).has(docName),
- closeAndClear: async (docName) => {
- if (collabUrl !== null) await getPool(collabUrl).closeAndClearPersistence(docName);
- },
- openAndActivate: (docName) => {
- if (collabUrl === null) return;
- const p = getPool(collabUrl);
- p.open(docName);
- p.setActive(docName);
- },
- remapTabs: ({ renamed, renamedFolders, renamedAssets }) =>
- remapTabsForRename(renamed, renamedFolders, renamedAssets),
- closeTabs: closeTabIds,
- removeDocumentTab: (docName) =>
- commitTabState(removeOpenTab(openTabsRef.current, docName), pinnedTabIdsRef.current),
- remapActiveTargetForRename: (fromDocName, toDocName) => {
- const current = activeTargetRef.current;
- const remapped = current !== null && docNameForNavigationTarget(current) === fromDocName;
- if (!remapped) return false;
- const next = { kind: 'doc' as const, target: toDocName, docName: toDocName };
- activeTargetRef.current = next;
- setActiveTarget((current) => {
- if (!current || docNameForNavigationTarget(current) !== fromDocName) return current;
- return next;
- });
- return true;
- },
- clearActiveTargetForRemoval: (docName) => {
- setActiveTarget((current) =>
- current && docNameForNavigationTarget(current) === docName ? null : current,
- );
- },
- navigateToDocument: (docName) => {
- setLocationHash(hashFromDocName(docName));
- },
- navigateHome: () => {
- setLocationHash('');
- },
- });
- }
-
- const removalReconcilerRef = useRef<ClientRemovalReconciler | null>(null);
-
- function commitNewTabIds(nextNewTabIds: string[]) {
- newTabIdsRef.current = nextNewTabIds;
- setNewTabIds((current) => (sameTabIds(current, nextNewTabIds) ? current : nextNewTabIds));
- commitVisibleTabIds(
- reconcileVisibleTabOrder(visibleTabIdsRef.current, openTabsRef.current, nextNewTabIds),
- );
- }
-
- function removeActiveNewTab(replacementTabId?: string | null) {
- const activeBlankTabId = activeNewTabIdRef.current;
- if (!activeBlankTabId) return;
- const nextNewTabIds = newTabIdsRef.current.filter((tabId) => tabId !== activeBlankTabId);
- newTabIdsRef.current = nextNewTabIds;
- setNewTabIds((current) => (sameTabIds(current, nextNewTabIds) ? current : nextNewTabIds));
- commitActiveNewTabId(null);
-
- const orderWithReplacement: string[] = [];
- const seen = new Set<string>();
- for (const tabId of visibleTabIdsRef.current) {
- const nextTabId = tabId === activeBlankTabId ? replacementTabId : tabId;
- if (!nextTabId || seen.has(nextTabId)) continue;
- seen.add(nextTabId);
- orderWithReplacement.push(nextTabId);
+ for (const pane of normalized.panes) {
+ visibleTabIdsByPaneRef.current.set(
+ pane.id,
+ reconcileVisibleTabOrder(
+ visibleTabIdsByPaneRef.current.get(pane.id) ?? [],
+ pane.openTabs,
+ pane.newTabIds,
+ ),
+ );
}
- commitVisibleTabIds(
- reconcileVisibleTabOrder(orderWithReplacement, openTabsRef.current, nextNewTabIds),
- );
+ setVisibleTabIdsByPane(new Map(visibleTabIdsByPaneRef.current));
+ setWorkspace((current) => (current === normalized ? current : normalized));
+ syncPoolToWorkspace(normalized, updateHash);
}
- useEffect(() => {
- activeTargetRef.current = activeTarget;
- }, [activeTarget]);
-
- // No dependency array: auth callbacks need a reconciler with the latest
- // collab URL and locally-scoped state helpers after every render.
- useEffect(() => {
- removalReconcilerRef.current = createRemovalReconciler();
- });
-
- useEffect(() => {
- activeTabIdRef.current = activeTabId;
- }, [activeTabId]);
-
- useEffect(() => {
- openTabsRef.current = openTabs;
- }, [openTabs]);
-
- useEffect(() => {
- pinnedTabIdsRef.current = pinnedTabIds;
- }, [pinnedTabIds]);
-
- useEffect(() => {
- activeNewTabIdRef.current = activeNewTabId;
- }, [activeNewTabId]);
-
- useEffect(() => {
- newTabIdsRef.current = newTabIds;
- }, [newTabIds]);
-
- useEffect(() => {
- visibleTabIdsRef.current = visibleTabIds;
- }, [visibleTabIds]);
-
- const isNewTabActive = activeNewTabId !== null;
+ function updatePaneState(
+ paneId: EditorPaneId,
+ update: (pane: EditorPaneState) => EditorPaneState,
+ options: { focus?: boolean; updateHash?: boolean } = {},
+ ) {
+ const current = workspaceRef.current;
+ if (!current.panes.some((pane) => pane.id === paneId)) return;
+ const updatedWorkspace = updateEditorPane(current, paneId, update);
+ const next = options.focus ? { ...updatedWorkspace, focusedPaneId: paneId } : updatedWorkspace;
+ commitWorkspace(next, options.updateHash);
+ }
// The active sidebar/tab surface. An explicit pin (`skillsSidebar`
// true/false) wins; the default `null` follows whichever surface the open doc
@@ -1062,9 +951,20 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
const visibleTabIdsForMode = visibleTabIds.filter(
(id) => tabIdIsSkillSurface(id) === skillFocused,
);
+ const visibleTabIdsByPaneForMode = new Map(
+ [...visibleTabIdsByPane].map(([paneId, tabIds]) => [
+ paneId,
+ tabIds.filter((tabId) => tabIdIsSkillSurface(tabId) === skillFocused),
+ ]),
+ );
+ const surfaceWorkspace = workspaceWithResolvedTargets(
+ projectVisibleEditorWorkspace(workspace, visibleTabIdsByPaneForMode),
+ );
+ const surfacePane = focusedPane(surfaceWorkspace);
+ // biome-ignore lint/correctness/useExhaustiveDependencies: workspace mutations read the live ref; collaboration readiness and load state are the restore triggers.
useEffect(() => {
- if (collabUrl === null || tabSessionLoaded || !tabIdentityResolved) return;
+ if (collabUrl === null || tabSessionLoaded) return;
let cancelled = false;
const bridge = getDesktopBridge();
const localKey = getLocalTabSessionKey();
@@ -1072,67 +972,93 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
const loaded = bridge
? bridge.project.getSessionState()
: Promise.resolve(
- localKey
- ? readLocalTabSessionState(storage, localKey, MAX_POOL)
- : {
- openTabs: [],
- pinnedTabIds: [],
- activeDocName: null,
- activeTabId: null,
- updatedAt: null,
- },
+ localKey ? readLocalTabSessionState(storage, localKey) : parseEditorTabSessionState(null),
);
loaded
.then((raw) => {
restoreSucceededRef.current = true;
if (cancelled) return;
- const state = parseEditorTabSessionState(raw, MAX_POOL);
+ const state = parseEditorTabSessionState(raw);
if (tabSessionUserClosedRef.current) return;
- const p = getPool(collabUrl);
- for (const tabId of state.openTabs) {
- const docName = docNameForTabId(tabId);
- if (docName) p.open(docName);
+ const currentWorkspace = workspaceRef.current;
+ let nextWorkspace = workspaceWithResolvedTargets(
+ hydrateEditorWorkspace({ panes: state.panes, focusedPaneId: state.focusedPaneId }),
+ );
+ const restoredFocusedPaneId = nextWorkspace.focusedPaneId;
+
+ // Restore is authoritative for pane layout and ordering, while opens
+ // that raced it remain additive in the restored focused pane.
+ for (const current of currentWorkspace.panes) {
+ for (const tabId of current.openTabs) {
+ const owner = findPaneOwningTab(nextWorkspace, tabId);
+ if (owner) {
+ if (!owner.openTabs.includes(tabId)) {
+ nextWorkspace = updateEditorPane(nextWorkspace, owner.id, (pane) => ({
+ ...pane,
+ openTabs: [...pane.openTabs, tabId],
+ pinnedTabIds: current.pinnedTabIds.includes(tabId)
+ ? [...pane.pinnedTabIds, tabId]
+ : pane.pinnedTabIds,
+ }));
+ continue;
+ }
+ if (current.pinnedTabIds.includes(tabId) && !owner.pinnedTabIds.includes(tabId)) {
+ nextWorkspace = updateEditorPane(nextWorkspace, owner.id, (pane) => ({
+ ...pane,
+ pinnedTabIds: [...pane.pinnedTabIds, tabId],
+ }));
+ }
+ continue;
+ }
+ nextWorkspace = updateEditorPane(nextWorkspace, restoredFocusedPaneId, (pane) => ({
+ ...pane,
+ openTabs: [...pane.openTabs, tabId],
+ pinnedTabIds: current.pinnedTabIds.includes(tabId)
+ ? [...pane.pinnedTabIds, tabId]
+ : pane.pinnedTabIds,
+ }));
+ }
}
- const mergedPinnedTabIds = [...state.pinnedTabIds, ...pinnedTabIdsRef.current];
- let nextTabs = state.openTabs;
- for (const tabId of openTabsRef.current) {
- nextTabs = addOpenTab(nextTabs, tabId, MAX_POOL, mergedPinnedTabIds);
+
+ const currentFocused = focusedPane(currentWorkspace);
+ if (currentFocused.newTabIds.length > 0) {
+ nextWorkspace = updateEditorPane(nextWorkspace, restoredFocusedPaneId, (pane) => ({
+ ...pane,
+ newTabIds: [...new Set([...pane.newTabIds, ...currentFocused.newTabIds])],
+ activeNewTabId: currentFocused.activeNewTabId,
+ activeTabId: currentFocused.activeNewTabId ? null : pane.activeTabId,
+ activeTarget: currentFocused.activeNewTabId ? null : pane.activeTarget,
+ }));
}
- const normalizedPinnedTabIds = normalizePinnedTabIds(mergedPinnedTabIds, nextTabs);
- openTabsRef.current = nextTabs;
- pinnedTabIdsRef.current = normalizedPinnedTabIds;
- // Restore each surface's last-active tab, but only fill slots not already
- // set by a tab opened during the async restore window (additive, matching
- // the openTabs merge above). Persisted ids were validated against the
- // saved openTabs, a subset of nextTabs, so they remain valid here.
+ // Restore each surface's last-active tab without overwriting a tab
+ // opened while the async session read was in flight.
activeTabByModeRef.current = {
files: activeTabByModeRef.current.files ?? state.activeTabByMode.files,
skills: activeTabByModeRef.current.skills ?? state.activeTabByMode.skills,
};
- setOpenTabs((current) => (sameTabIds(current, nextTabs) ? current : nextTabs));
- setPinnedTabIds((current) =>
- sameTabIds(current, normalizedPinnedTabIds) ? current : normalizedPinnedTabIds,
- );
- // A hash target can open before async session restore resolves. When a
- // saved session exists, keep the restored tab order authoritative so the
- // hash-opened tab does not jump to the front of the strip on reload.
- const visibleOrderSeed = state.openTabs.length > 0 ? nextTabs : visibleTabIdsRef.current;
- const nextVisibleTabIds = reconcileVisibleTabOrder(
- visibleOrderSeed,
- nextTabs,
- newTabIdsRef.current,
- );
- visibleTabIdsRef.current = nextVisibleTabIds;
- setVisibleTabIds((current) =>
- sameTabIds(current, nextVisibleTabIds) ? current : nextVisibleTabIds,
- );
+
+ const hash = window.location.hash;
+ const hashTabId = tabIdFromHash(hash);
+ const hashOwner = hashTabId ? findPaneOwningTab(nextWorkspace, hashTabId) : null;
+ if (hashOwner && hashTabId && currentFocused.activeNewTabId === null) {
+ const currentOwner = findPaneOwningTab(currentWorkspace, hashTabId);
+ const currentTarget =
+ currentOwner?.activeTabId === hashTabId ? currentOwner.activeTarget : null;
+ nextWorkspace = {
+ ...updateEditorPane(nextWorkspace, hashOwner.id, (pane) =>
+ paneWithResolvedTarget({
+ ...pane,
+ activeTabId: hashTabId,
+ activeNewTabId: null,
+ activeTarget: currentTarget,
+ }),
+ ),
+ focusedPaneId: hashOwner.id,
+ };
+ }
const currentHashDoc = docNameFromHash(window.location.hash);
- const restoredActive =
- state.activeTabId ??
- (state.activeDocName ? docTabId(state.activeDocName) : null) ??
- state.openTabs[0] ??
- null;
+ const restoredActive = focusedPane(nextWorkspace).activeTabId;
const restoredActiveHash = restoredActive ? hashFromTabId(restoredActive) : null;
const restoredActiveDocName = restoredActive ? docNameForTabId(restoredActive) : null;
const shouldRestoreActive =
@@ -1143,15 +1069,14 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
window.location.hash,
restoredActiveDocName,
);
- if (shouldRestoreActive && restoredActive) {
- activeTabIdRef.current = restoredActive;
- setActiveTabId(restoredActive);
- const nextHash = hashFromTabId(restoredActive);
- if (window.location.hash !== nextHash) window.location.hash = nextHash;
+ nextWorkspace = workspaceWithResolvedTargets(normalizeEditorWorkspace(nextWorkspace));
+ for (const pane of nextWorkspace.panes) {
+ visibleTabIdsByPaneRef.current.set(pane.id, [...pane.openTabs, ...pane.newTabIds]);
}
+ commitWorkspace(nextWorkspace, shouldRestoreActive && restoredActive !== null);
})
.catch((err: unknown) => {
- console.warn('[editor-tabs] failed to restore tab session:', err);
+ console.error('[editor-tabs] failed to restore tab session:', err);
})
.finally(() => {
if (!cancelled) setTabSessionLoaded(true);
@@ -1160,17 +1085,12 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
return () => {
cancelled = true;
};
- }, [collabUrl, tabIdentityResolved, tabSessionLoaded]);
+ }, [collabUrl, tabSessionLoaded]);
useEffect(() => {
if (!tabSessionLoaded) return;
if (!shouldPersistTabSession(restoreSucceededRef.current, openTabs.length)) return;
- const state = createEditorTabSessionState(
- openTabs,
- activeTabId ?? activeTabIdForTarget(activeTarget, snapshot.activeDocName),
- pinnedTabIds,
- activeTabByModeRef.current,
- );
+ const state = createEditorTabSessionState(workspace, activeTabByModeRef.current);
const bridge = getDesktopBridge();
if (bridge) {
void bridge.project.setSessionState(state).catch((err: unknown) => {
@@ -1182,12 +1102,230 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
if (!localKey) return;
const storage = typeof localStorage !== 'undefined' ? localStorage : null;
writeLocalTabSessionState(storage, localKey, state);
- }, [activeTabId, activeTarget, openTabs, pinnedTabIds, snapshot.activeDocName, tabSessionLoaded]);
+ }, [openTabs.length, tabSessionLoaded, workspace]);
+
+ // Closes (and close-like preview replacement) during the restore window bail the
+ // restore merge. Other mutations (open, pin, activate) are no-ops here because
+ // the restore merge is additive — see tabSessionUserClosedRef declaration for
+ // the full rationale.
+ function markTabSessionClosedDuringRestore() {
+ if (!tabSessionLoaded) tabSessionUserClosedRef.current = true;
+ }
+
+ function remapTabsForRename(
+ renamed: readonly { fromDocName: string; toDocName: string }[],
+ renamedFolders: readonly { fromPath: string; toPath: string }[] = [],
+ renamedAssets: readonly { fromPath: string; toPath: string }[] = [],
+ ) {
+ markTabSessionClosedDuringRestore();
+ const remapTabId = (tabId: string) =>
+ remapOpenTabs(
+ [tabId],
+ renamed,
+ Number.MAX_SAFE_INTEGER,
+ renamedFolders,
+ [],
+ renamedAssets,
+ )[0] ?? null;
+ for (const [paneId, order] of visibleTabIdsByPaneRef.current) {
+ visibleTabIdsByPaneRef.current.set(
+ paneId,
+ remapVisibleTabsForRename(order, renamed, renamedFolders, renamedAssets),
+ );
+ }
+ const previousFocusedTabId = focusedPane(workspaceRef.current).activeTabId;
+ const nextWorkspace = transitionEditorWorkspace(workspaceRef.current, {
+ type: 'remap-tabs',
+ remap: remapTabId,
+ }).workspace;
+ const nextFocusedTabId = focusedPane(nextWorkspace).activeTabId;
+ commitWorkspace(
+ nextWorkspace,
+ previousFocusedTabId !== null && previousFocusedTabId !== nextFocusedTabId,
+ );
+ }
+
+ function closeProvidersWithoutOpenTabs(
+ removedTabIds: Iterable<string>,
+ nextWorkspace: EditorWorkspaceState,
+ ) {
+ if (collabUrl === null) return;
+ const remainingDocNames = new Set<string>();
+ for (const tabId of flattenWorkspaceTabs(nextWorkspace)) {
+ const docName = docNameForTabId(tabId);
+ if (docName) remainingDocNames.add(docName);
+ }
+ const p = getPool(collabUrl);
+ for (const tabId of removedTabIds) {
+ const docName = docNameForTabId(tabId);
+ if (docName && !remainingDocNames.has(docName)) p.close(docName);
+ }
+ }
+
+ function preserveClosedTabSurface(
+ previousPane: EditorPaneState,
+ closingTabIds: ReadonlySet<string>,
+ workspaceAfterClose: EditorWorkspaceState,
+ ): EditorWorkspaceState {
+ const closedActiveTabId =
+ previousPane.activeTabId && closingTabIds.has(previousPane.activeTabId)
+ ? previousPane.activeTabId
+ : previousPane.activeNewTabId && closingTabIds.has(previousPane.activeNewTabId)
+ ? previousPane.activeNewTabId
+ : null;
+ if (!closedActiveTabId) return workspaceAfterClose;
+
+ const nextPane = workspaceAfterClose.panes.find((pane) => pane.id === previousPane.id);
+ const nextActiveTabId = nextPane?.activeTabId ?? nextPane?.activeNewTabId ?? null;
+ const closedSkillsTab = tabIdIsSkillSurface(closedActiveTabId);
+ if (!nextPane || !nextActiveTabId || tabIdIsSkillSurface(nextActiveTabId) === closedSkillsTab) {
+ return workspaceAfterClose;
+ }
+
+ const visibleOrder = reconcileVisibleTabOrder(
+ visibleTabIdsByPaneRef.current.get(previousPane.id) ?? [],
+ previousPane.openTabs,
+ previousPane.newTabIds,
+ );
+ const activeIndex = visibleOrder.indexOf(closedActiveTabId);
+ const candidates =
+ activeIndex < 0
+ ? visibleOrder
+ : [...visibleOrder.slice(activeIndex + 1), ...visibleOrder.slice(0, activeIndex).reverse()];
+ const remainingTabIds = new Set([...nextPane.openTabs, ...nextPane.newTabIds]);
+ const fallbackTabId = candidates.find(
+ (tabId) =>
+ !closingTabIds.has(tabId) &&
+ remainingTabIds.has(tabId) &&
+ tabIdIsSkillSurface(tabId) === closedSkillsTab,
+ );
+
+ if (fallbackTabId) {
+ return updateEditorPane(workspaceAfterClose, previousPane.id, (pane) => ({
+ ...pane,
+ activeTabId: pane.openTabs.includes(fallbackTabId) ? fallbackTabId : null,
+ activeNewTabId: pane.newTabIds.includes(fallbackTabId) ? fallbackTabId : null,
+ activeTarget: null,
+ }));
+ }
+
+ const prefix = closedSkillsTab ? SKILLS_NEW_TAB_PREFIX : NEW_TAB_PREFIX;
+ const newTabId = `${prefix}${nextNewTabOrdinalRef.current}`;
+ nextNewTabOrdinalRef.current += 1;
+ return updateEditorPane(workspaceAfterClose, previousPane.id, (pane) => ({
+ ...pane,
+ newTabIds: [...pane.newTabIds, newTabId],
+ activeTabId: null,
+ activeNewTabId: newTabId,
+ activeTarget: null,
+ }));
+ }
+
+ const closeTabsInPaneById = (
+ paneId: EditorPaneId,
+ tabIds: readonly string[],
+ options: CloseTabsOptions = {},
+ ) => {
+ const pane = workspaceRef.current.panes.find((candidate) => candidate.id === paneId);
+ if (!pane) return;
+ const closingTabIds = new Set(
+ options.force
+ ? tabIds.filter((tabId) => pane.openTabs.includes(tabId))
+ : filterClosableTabIds(tabIds, pane.pinnedTabIds).filter((tabId) =>
+ pane.openTabs.includes(tabId),
+ ),
+ );
+ if (closingTabIds.size === 0) return;
+ markTabSessionClosedDuringRestore();
+ if (!options.force) {
+ for (const tabId of pane.openTabs.filter((candidate) => closingTabIds.has(candidate))) {
+ recentlyClosedTabsRef.current = recordRecentlyClosedTab(
+ recentlyClosedTabsRef.current,
+ { paneId, tabId },
+ 50,
+ );
+ }
+ }
+ const wasFocused = workspaceRef.current.focusedPaneId === paneId;
+ const nextWorkspace = preserveClosedTabSurface(
+ pane,
+ closingTabIds,
+ transitionEditorWorkspace(workspaceRef.current, {
+ type: 'close-tabs',
+ paneId,
+ tabIds: [...closingTabIds],
+ }).workspace,
+ );
+ closeProvidersWithoutOpenTabs(closingTabIds, nextWorkspace);
+ commitWorkspace(nextWorkspace, wasFocused);
+ };
+
+ function closeTabsAcrossPanes(tabIds: readonly string[], options: CloseTabsOptions = {}) {
+ const requested = new Set(tabIds.filter((tabId) => tabId.length > 0));
+ for (const paneId of workspaceRef.current.panes.map((pane) => pane.id)) {
+ const pane = workspaceRef.current.panes.find((candidate) => candidate.id === paneId);
+ if (!pane) continue;
+ const inPane = pane.openTabs.filter((tabId) => requested.has(tabId));
+ if (inPane.length > 0) closeTabsInPaneById(paneId, inPane, options);
+ }
+ }
+ function createRemovalReconciler() {
+ return createClientRemovalReconciler({
+ captureRenameSnapshots,
+ getActivePoolDocName: () =>
+ collabUrl === null ? null : getPool(collabUrl).getActiveDocName(),
+ hasPooledDocument: (docName) => collabUrl !== null && getPool(collabUrl).has(docName),
+ closeAndClear: async (docName) => {
+ if (collabUrl !== null) await getPool(collabUrl).closeAndClearPersistence(docName);
+ },
+ openAndActivate: (docName) => {
+ if (collabUrl === null) return;
+ const p = getPool(collabUrl);
+ p.open(docName);
+ p.setActive(docName);
+ },
+ remapTabs: ({ renamed, renamedFolders, renamedAssets }) =>
+ remapTabsForRename(renamed, renamedFolders, renamedAssets),
+ closeTabs: (tabIds) => closeTabsAcrossPanes(tabIds, { force: true }),
+ removeDocumentTab: (docName) => {
+ const nextWorkspace = transitionEditorWorkspace(workspaceRef.current, {
+ type: 'prune-tabs',
+ keep: (tabId) => docNameForTabId(tabId) !== docName,
+ }).workspace;
+ commitWorkspace(nextWorkspace);
+ },
+ remapActiveTargetForRename: (_fromDocName, toDocName) =>
+ providerDocNameForPane(focusedPane(workspaceRef.current)) === toDocName,
+ clearActiveTargetForRemoval: (docName) => {
+ const nextWorkspace = {
+ ...workspaceRef.current,
+ panes: workspaceRef.current.panes.map((pane) =>
+ pane.activeTarget && docNameForNavigationTarget(pane.activeTarget) === docName
+ ? { ...pane, activeTarget: null }
+ : pane,
+ ),
+ };
+ commitWorkspace(nextWorkspace);
+ },
+ navigateToDocument: (docName) => navigateToHash(hashFromDocName(docName)),
+ navigateHome: () => {
+ const focused = focusedPane(workspaceRef.current);
+ navigateToHash(focused.activeTabId ? hashFromTabId(focused.activeTabId) : '');
+ },
+ });
+ }
+
+ // No dependency array: auth callbacks need a reconciler with the latest
+ // collab URL and locally-scoped state helpers after every render.
+ useEffect(() => {
+ removalReconcilerRef.current = createRemovalReconciler();
+ });
+
+ // biome-ignore lint/correctness/useExhaustiveDependencies: pool wiring is scoped to the collab URL; callbacks read the live workspace ref.
useEffect(() => {
if (collabUrl === null) return;
let cancelled = false;
- setTabIdentityResolved(false);
const p = getPool(collabUrl);
// Reuses the previous snapshot when nothing observable changed, so a pool
@@ -1201,6 +1339,7 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
// Sync initial state
commitSnapshot();
+ syncPoolToWorkspace(workspaceRef.current);
// Late-join branch backstop. Auth-token `expectedBranch` claim
// mismatch (server is on branch B, client claims branch A) routes
@@ -1320,9 +1459,6 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
.catch((err: unknown) => {
if (cancelled) return;
warnPrincipalFetchOnce(err);
- })
- .finally(() => {
- if (!cancelled) setTabIdentityResolved(true);
});
// CRDT server-restart recovery boot fetch: pull the server's
@@ -1400,31 +1536,64 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
};
}, [collabUrl]);
+ function focusPaneById(paneId: EditorPaneId, updateHash = true) {
+ const pane = workspaceRef.current.panes.find((candidate) => candidate.id === paneId);
+ if (!pane) return;
+ const surfacePane = surfaceWorkspace.panes.find((candidate) => candidate.id === paneId);
+ let nextWorkspace = workspaceRef.current;
+ if (surfacePane?.activeTabId && surfacePane.activeTabId !== pane.activeTabId) {
+ setSkillsSidebarState(null);
+ nextWorkspace = transitionEditorWorkspace(nextWorkspace, {
+ type: 'activate-tab',
+ paneId,
+ tabId: surfacePane.activeTabId,
+ }).workspace;
+ } else if (surfacePane?.activeNewTabId && surfacePane.activeNewTabId !== pane.activeNewTabId) {
+ setSkillsSidebarState(null);
+ nextWorkspace = updateEditorPane(nextWorkspace, paneId, (candidate) => ({
+ ...candidate,
+ activeTabId: null,
+ activeNewTabId: surfacePane.activeNewTabId,
+ activeTarget: null,
+ }));
+ } else if (nextWorkspace.focusedPaneId === paneId) {
+ return;
+ }
+ commitWorkspace(
+ focusEditorPane(
+ {
+ ...nextWorkspace,
+ panes: nextWorkspace.panes.map((candidate) =>
+ candidate.id === paneId ? paneWithResolvedTarget(candidate) : candidate,
+ ),
+ },
+ paneId,
+ ),
+ updateHash,
+ );
+ }
+
+ function activateTabInPaneById(paneId: EditorPaneId, tabId: string, updateHash = true) {
+ const pane = workspaceRef.current.panes.find((candidate) => candidate.id === paneId);
+ if (!pane) return;
+ if (!pane.openTabs.includes(tabId)) return;
+ setSkillsSidebarState(null);
+ commitWorkspace(
+ transitionEditorWorkspace(workspaceRef.current, {
+ type: 'activate-tab',
+ paneId,
+ tabId,
+ }).workspace,
+ updateHash,
+ );
+ }
+
const openDocument = (docName: string) => {
mark('ok/nav/open-document', { docName, transition: false });
- if (collabUrl === null) return;
- // Intentionally does NOT mark the session as closed-during-restore.
- // Opens are additive: the restore-merge unions state.openTabs with
- // openTabsRef.current, so an opened-during-restore tab coexists with
- // the restored set. Marking would bail the entire restore on the
- // hash-nav-while-restore-pending path.
- const p = getPool(collabUrl);
- const entry = p.open(docName);
- if (!entry) return; // reserved doc (e.g. __system__) — pool refused admission
- // Deterministic prewarm-then-click correlation by poolEventId. Emits
- // ok/sidebar/prewarm-clicked when the entry was prewarmed recently
- // and the IDs match.
- consumePrewarmClick(docName, entry.poolEventId);
- const nextTabId = docTabId(docName);
- updateOpenTabs((current) => addOpenTab(current, nextTabId, MAX_POOL, pinnedTabIdsRef.current));
- removeActiveNewTab(nextTabId);
- commitActiveTabId(nextTabId);
- p.setActive(docName);
- // Set a doc-kind ResolvedNavigationTarget so downstream consumers
- // (EditorArea's isNewDoc, EditorPane's folder-mode effect) stay in sync.
- // openTarget() is the canonical path for folder/missing kinds; openDocument
- // stays as a direct-doc affordance for non-resolver callers (tests, etc.).
- setActiveTarget({ kind: 'doc', target: docName, docName });
+ openTargetWithOptions(
+ { kind: 'doc', target: docName, docName },
+ { disposition: 'permanent', consumeActiveNewTab: true },
+ );
};
// Pass-through wrapper. React's default Suspense behavior handles cold
// (skeleton) and warm (no suspension → fast commit) without deferring
@@ -1437,359 +1606,388 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
openDocument(docName);
};
+ function activateOrOpenSurfaceNewTab(paneId: EditorPaneId, skills: boolean) {
+ const pane = workspaceRef.current.panes.find((candidate) => candidate.id === paneId);
+ if (!pane) return;
+ const existingTabId = pane.newTabIds.find((tabId) => isSkillsNewTabId(tabId) === skills);
+ setSkillsSidebarState(null);
+ if (existingTabId) {
+ updatePaneState(
+ pane.id,
+ (current) => ({
+ ...current,
+ activeNewTabId: existingTabId,
+ activeTabId: null,
+ activeTarget: null,
+ }),
+ { updateHash: true },
+ );
+ return;
+ }
+
+ const prefix = skills ? SKILLS_NEW_TAB_PREFIX : NEW_TAB_PREFIX;
+ const nextNewTabId = `${prefix}${nextNewTabOrdinalRef.current}`;
+ nextNewTabOrdinalRef.current += 1;
+ commitWorkspace(
+ transitionEditorWorkspace(workspaceRef.current, {
+ type: 'open-new-tab',
+ paneId: pane.id,
+ tabId: nextNewTabId,
+ }).workspace,
+ true,
+ );
+ }
+
const openTargetWithOptions = (
target: ResolvedNavigationTarget,
options: OpenTargetOptions = {},
+ requestedPaneId?: EditorPaneId,
+ existingTabBehavior: ExistingTabOpenBehavior = 'activate-owner',
) => {
if (collabUrl === null) return;
- // `replace-active` displaces the previously-active tab (close-like) — must
- // bail the restore merge so it cannot resurrect. Plain opens (any other
- // tabBehavior) are additive; the merge handles them.
- if (options.tabBehavior === 'replace-active') {
- markTabSessionClosedDuringRestore();
- }
+ const paneId = requestedPaneId ?? workspaceRef.current.focusedPaneId;
const p = getPool(collabUrl);
+ if (target.kind === 'skills') {
+ activateOrOpenSurfaceNewTab(paneId, true);
+ return;
+ }
const docName = docNameForNavigationTarget(target);
- const activeBlankTabId = activeNewTabIdRef.current;
- const replacingBlankTab = activeBlankTabId !== null && options.tabBehavior === 'replace-active';
- const currentActiveTabId = activeBlankTabId
- ? null
- : (activeTabIdRef.current ?? activeTabIdForTarget(activeTarget, snapshot.activeDocName));
- const hasCurrentActiveTab =
- currentActiveTabId !== null && openTabsRef.current.includes(currentActiveTabId);
- const currentActiveTabIsPinned =
- currentActiveTabId !== null && pinnedTabIdsRef.current.includes(currentActiveTabId);
- const behavior =
- options.tabBehavior === 'replace-active' && currentActiveTabIsPinned
- ? 'append'
- : options.tabBehavior === 'replace-active' && !replacingBlankTab && !hasCurrentActiveTab
- ? 'append'
- : (options.tabBehavior ?? 'append');
+ const nextTabId = tabIdForNavigationTarget(target);
+ if (!nextTabId) return;
if (docName && target.kind !== 'large-file') {
const entry = p.open(docName);
if (!entry) return;
consumePrewarmClick(docName, entry.poolEventId);
- const opened = openDocTab(openTabsRef.current, docName, {
- behavior,
- currentTabId: currentActiveTabId,
- limit: MAX_POOL,
- pinnedTabIds: pinnedTabIdsRef.current,
- });
- commitOpenTabs(opened.tabs);
- removeActiveNewTab(opened.activeTabId);
- commitActiveTabId(opened.activeTabId);
- p.setActive(docName);
- } else {
- p.clearActive();
- if (target.kind === 'skills') {
- // Skills is a new-tab surface, not a standing titled tab: focus an
- // existing skills new tab or open one, so it reads as "New tab" and
- // never persists across reloads. Renders via `isSkillsNewTabId`
- // (activeTarget stays null), same path as a `+`-opened skills new tab.
- const existing = newTabIdsRef.current.find(isSkillsNewTabId);
- if (existing) {
- commitActiveNewTabId(existing);
- } else {
- const nextNewTabId = `${SKILLS_NEW_TAB_PREFIX}${nextNewTabOrdinalRef.current}`;
- nextNewTabOrdinalRef.current += 1;
- commitNewTabIds([...newTabIdsRef.current, nextNewTabId]);
- commitActiveNewTabId(nextNewTabId);
- }
- commitActiveTabId(null);
- setActiveTarget(null);
- // Opening the Skills surface re-arms autofollow (commitActiveTabId(null)
- // above does not), so `skillFocused` tracks the skills new tab even if a
- // Files pin was active.
- setSkillsSidebarState(null);
- return;
- }
- const nextTabId = tabIdForNavigationTarget(target);
- if (nextTabId) {
- const opened = openTab(openTabsRef.current, nextTabId, {
- behavior,
- currentTabId: currentActiveTabId,
- limit: MAX_POOL,
- pinnedTabIds: pinnedTabIdsRef.current,
- });
- commitOpenTabs(opened.tabs);
- commitActiveTabId(opened.activeTabId);
- removeActiveNewTab(opened.activeTabId);
- } else {
- removeActiveNewTab(nextTabId);
- }
}
- setActiveTarget((current) => (sameNavigationTarget(current, target) ? current : target));
+
+ const transition = transitionEditorWorkspace(workspaceRef.current, {
+ type: 'open-target',
+ paneId,
+ tabId: nextTabId,
+ target,
+ disposition:
+ options.disposition ?? (options.tabBehavior === 'replace-active' ? 'preview' : 'permanent'),
+ consumeActiveNewTab: options.consumeActiveNewTab ?? true,
+ existingTabBehavior,
+ });
+ if (transition.replacedPreviewTabId !== null) markTabSessionClosedDuringRestore();
+ setSkillsSidebarState(null);
+ commitWorkspace(transition.workspace);
};
- const openTarget = (target: ResolvedNavigationTarget, options: OpenTargetOptions = {}) => {
+ const openTarget = (target: ResolvedNavigationTarget, options?: OpenTargetOptions) => {
openTargetWithOptions(target, options);
};
- const openTargetTransition = (
+ const openTargetInPane = (
+ paneId: EditorPaneId,
target: ResolvedNavigationTarget,
- options: OpenTargetOptions = {},
+ options?: OpenTargetOptions,
) => {
+ openTargetWithOptions(target, options, paneId, 'open-in-pane');
+ };
+ const openTargetTransition = (target: ResolvedNavigationTarget, options?: OpenTargetOptions) => {
const docName = docNameForNavigationTarget(target);
mark('ok/nav/open-target', { docName, kind: target.kind, transition: false });
openTargetWithOptions(target, options);
};
- const activateTabById = (tabId: string) => {
- const tab = parseEditorTabId(tabId);
- commitActiveNewTabId(null);
- commitActiveTabId(tabId);
- if (tab.kind === 'doc') {
- if (collabUrl !== null) {
- const p = getPool(collabUrl);
- const entry = p.open(tab.docName);
- if (!entry) return;
- p.setActive(tab.docName);
- }
- setActiveTarget({ kind: 'doc', target: tab.docName, docName: tab.docName });
- const nextHash = hashFromDocName(tab.docName);
- if (window.location.hash !== nextHash) window.location.hash = nextHash;
- return;
- }
- if (collabUrl !== null) {
- const p = getPool(collabUrl);
- p.clearActive();
- }
- if (tab.kind === 'asset') {
- setActiveTarget(assetTargetForPath(tab.assetPath));
- const nextHash = hashFromAssetPath(tab.assetPath);
- if (window.location.hash !== nextHash) window.location.hash = nextHash;
- return;
- }
- if (tab.kind === 'skill-file') {
- // Carry the host through: dropping it here would re-resolve the file
- // against whichever same-named skill a bare name lookup lands on, so
- // re-activating the tab could swap in another skill's bytes.
- setActiveTarget({
- kind: 'skill-file',
- target: `${tab.scope}/${tab.name}${tab.host ? `:${tab.host}` : ''}/${tab.path}`,
- scope: tab.scope,
- name: tab.name,
- path: tab.path,
- ...(tab.host ? { host: tab.host } : {}),
- });
- const nextHash = hashFromSkillFile({
- scope: tab.scope,
- name: tab.name,
- path: tab.path,
- ...(tab.host ? { host: tab.host } : {}),
- });
- if (window.location.hash !== nextHash) window.location.hash = nextHash;
- return;
- }
- if (tab.kind === 'skill-preview') {
- // The tab IDENTITY is path-less (one preview tab), so the selected-file
- // `path` lives only in the hash. Preserve it only when that hash describes
- // THIS preview; otherwise a bundle path selected in the prior preview
- // would leak into the newly activated tab.
- const hashPath = selectedPathForSkillPreview(window.location.hash, tab);
- const previewTarget = {
- flavor: tab.flavor,
- source: tab.source,
- name: tab.name,
- subtitle: tab.subtitle,
- level: tab.level,
- ...(hashPath ? { path: hashPath } : {}),
- };
- setActiveTarget({
- kind: 'skill-preview',
- target: `${tab.flavor}/${tab.source}/${tab.name}`,
- ...previewTarget,
- });
- const nextHash = hashFromSkillPreview(previewTarget);
- if (window.location.hash !== nextHash) window.location.hash = nextHash;
- return;
- }
- if (tab.kind === 'folder') {
- setActiveTarget({ kind: 'folder', target: tab.folderPath, folderPath: tab.folderPath });
- const nextHash = hashFromFolderPath(tab.folderPath);
- if (window.location.hash !== nextHash) window.location.hash = nextHash;
- }
- // A `skills` tab id is unreachable here (isValidTabId prunes it so it never
- // enters the open-tab list) — no branch, so it no-ops rather than restoring
- // the retired standing Skills tab.
- };
+ const activateTabById = (tabId: string) =>
+ activateTabInPaneById(workspaceRef.current.focusedPaneId, tabId);
- const openNewTabById = () => {
- // Open a blank tab — additive, no close-during-restore mark. Inherit the
- // current surface (incl. an explicit Files/Skills pin) so a new tab opened
- // from Skills lands on the Skills home, not the Files empty state.
+ const openNewTabInPaneById = (paneId: EditorPaneId) => {
+ const pane = workspaceRef.current.panes.find((candidate) => candidate.id === paneId);
+ if (!pane) return;
const prefix = skillFocused ? SKILLS_NEW_TAB_PREFIX : NEW_TAB_PREFIX;
const nextNewTabId = `${prefix}${nextNewTabOrdinalRef.current}`;
nextNewTabOrdinalRef.current += 1;
- commitNewTabIds([...newTabIdsRef.current, nextNewTabId]);
- commitActiveNewTabId(nextNewTabId);
- if (collabUrl !== null) {
- const p = getPool(collabUrl);
- p.clearActive();
- }
- setActiveTarget(null);
- commitActiveTabId(null);
- if (window.location.hash !== '') {
- window.location.hash = '';
- }
+ commitWorkspace(
+ transitionEditorWorkspace(workspaceRef.current, {
+ type: 'open-new-tab',
+ paneId,
+ tabId: nextNewTabId,
+ }).workspace,
+ true,
+ );
+ };
+ const openNewTabById = () => openNewTabInPaneById(workspaceRef.current.focusedPaneId);
+
+ const closeTabInPaneById = (paneId: EditorPaneId, tabId: string) =>
+ closeTabsInPaneById(paneId, [tabId]);
+ const closeTabById = (tabId: string) =>
+ closeTabInPaneById(workspaceRef.current.focusedPaneId, tabId);
+
+ const closeNewTabInPaneById = (paneId: EditorPaneId, tabId: string) => {
+ markTabSessionClosedDuringRestore();
+ const pane = workspaceRef.current.panes.find((candidate) => candidate.id === paneId);
+ if (!pane?.newTabIds.includes(tabId)) return;
+ const wasActive = pane.activeNewTabId === tabId;
+ const nextWorkspace = transitionEditorWorkspace(workspaceRef.current, {
+ type: 'close-tabs',
+ paneId,
+ tabIds: [tabId],
+ }).workspace;
+ const nextPane = nextWorkspace.panes.find((candidate) => candidate.id === paneId);
+ const nextActiveTabId = nextPane?.activeTabId ?? nextPane?.activeNewTabId ?? null;
+ const closedSkillsTab = isSkillsNewTabId(tabId);
+ const remainsOnClosedSurface =
+ nextActiveTabId !== null && tabIdIsSkillSurface(nextActiveTabId) === closedSkillsTab;
+ if (wasActive && !remainsOnClosedSurface) setSkillsSidebarState(closedSkillsTab);
+ commitWorkspace(
+ nextWorkspace,
+ workspaceRef.current.focusedPaneId === paneId && wasActive && remainsOnClosedSurface,
+ );
};
+ const closeNewTabById = (tabId: string) =>
+ closeNewTabInPaneById(workspaceRef.current.focusedPaneId, tabId);
- // Files/Skills toggle. `null` just re-arms autofollow. An explicit surface
- // choice restores that surface's last-active tab (so the editor swaps to it),
- // or — when it has none open — pins the surface and clears the editor so its
- // empty/home state shows. A no-op when already on the requested surface.
+ // Files/Skills toggle. Each surface remembers its last active tab even when
+ // that tab lives in a different split pane. With no remembered tab, retain
+ // the workspace and activate that surface's ephemeral home tab.
const setSkillsSidebar = (next: boolean | null) => {
if (next === null) {
setSkillsSidebarState(null);
return;
}
+
const targetMode = next ? 'skills' : 'files';
if ((skillFocused ? 'skills' : 'files') === targetMode) {
setSkillsSidebarState(next);
return;
}
- const remembered = activeTabByModeRef.current[targetMode];
- if (remembered && openTabsRef.current.includes(remembered)) {
- // activateTabById re-arms autofollow; `skillFocused` then tracks the
- // restored tab's own surface, which equals targetMode.
- activateTabById(remembered);
- return;
- }
- // Target surface has no open tab → pin it and clear the editor so its
- // empty/home surface renders (Skills hub for skills, "create" for files).
- setSkillsSidebarState(next);
- if (collabUrl !== null) getPool(collabUrl).clearActive();
- commitActiveNewTabId(null);
- commitActiveTabId(null);
- setActiveTarget(null);
- if (window.location.hash !== '') window.location.hash = '';
- };
-
- const closeTabById = (tabId: string) => {
- if (pinnedTabIdsRef.current.includes(tabId)) return;
- if (!openTabsRef.current.includes(tabId)) {
- // A tab the user can SEE must always be closable. `visibleTabIds` is
- // normally a subset of openTabs ∪ newTabIds, but if the two ever diverge
- // the strip renders a tab whose close is a silent no-op — un-closable
- // short of a restart. Prune it here rather than returning into that trap.
- if (visibleTabIdsRef.current.includes(tabId)) {
- commitVisibleTabIds(visibleTabIdsRef.current.filter((id) => id !== tabId));
- }
- return;
- }
- markTabSessionClosedDuringRestore();
- const closingIsSkill = tabIdIsSkillSurface(tabId);
- let nextActiveTabId: string | null = null;
- const closingDocName = docNameForTabId(tabId);
- pushRecentlyClosedTabs([tabId]);
- if (collabUrl !== null) {
- const p = getPool(collabUrl);
- if (closingDocName && !hasOpenDocTab(openTabsRef.current, closingDocName, new Set([tabId]))) {
- p.close(closingDocName);
- }
- }
- const currentActiveTabId =
- activeTabId ?? activeTabIdForTarget(activeTarget, snapshot.activeDocName);
- updateOpenTabs((current) => {
- // Pick the successor from the SAME surface, so closing the last Skills tab
- // lands on the Skills empty state instead of jumping to a Files tab.
- const sameSurface = current.filter((id) => tabIdIsSkillSurface(id) === closingIsSkill);
- nextActiveTabId = nextActiveTabAfterClose(sameSurface, currentActiveTabId, tabId);
- return removeOpenTab(current, tabId);
- });
- if (currentActiveTabId !== tabId) return;
- if (nextActiveTabId) {
- commitActiveTabId(nextActiveTabId);
- window.location.hash = hashFromTabId(nextActiveTabId);
- return;
- }
- // No tab left on this surface → pin it so its own empty/home state shows
- // rather than falling back to Files via autofollow.
- setSkillsSidebarState(closingIsSkill);
- if (collabUrl !== null) {
- const p = getPool(collabUrl);
- p.clearActive();
- }
- setActiveTarget(null);
- commitActiveTabId(null);
- window.location.hash = '';
- };
- const closeNewTabById = (tabId: string) => {
- markTabSessionClosedDuringRestore();
- const currentNewTabIds = newTabIdsRef.current;
- if (!currentNewTabIds.includes(tabId)) return;
- const nextNewTabIds = currentNewTabIds.filter((id) => id !== tabId);
- commitNewTabIds(nextNewTabIds);
- if (activeNewTabIdRef.current !== tabId) return;
-
- const closedIndex = currentNewTabIds.indexOf(tabId);
- const nextNewTabId = nextNewTabIds[closedIndex] ?? nextNewTabIds[closedIndex - 1] ?? null;
- if (nextNewTabId) {
- commitActiveNewTabId(nextNewTabId);
- if (collabUrl !== null) {
- const p = getPool(collabUrl);
- p.clearActive();
- }
- setActiveTarget(null);
- commitActiveTabId(null);
- if (window.location.hash !== '') {
- window.location.hash = '';
- }
+ const rememberedTabId = activeTabByModeRef.current[targetMode];
+ const owner = rememberedTabId ? findPaneOwningTab(workspaceRef.current, rememberedTabId) : null;
+ if (rememberedTabId && owner) {
+ setSkillsSidebarState(null);
+ activateTabInPaneById(owner.id, rememberedTabId);
return;
}
- commitActiveNewTabId(null);
- // Fall back to the most-recent open tab on the closed placeholder's OWN
- // surface, so closing a Skills "New tab" stays in Skills.
- const closingNewIsSkill = isSkillsNewTabId(tabId);
- const sameSurfaceOpen = openTabsRef.current.filter(
- (id) => tabIdIsSkillSurface(id) === closingNewIsSkill,
- );
- const nextActiveTabId = sameSurfaceOpen[sameSurfaceOpen.length - 1] ?? null;
- if (nextActiveTabId) {
- commitActiveTabId(nextActiveTabId);
- window.location.hash = hashFromTabId(nextActiveTabId);
- return;
- }
- // Nothing open on this surface → pin it so its empty/home state shows.
- setSkillsSidebarState(closingNewIsSkill);
- if (collabUrl !== null) {
- const p = getPool(collabUrl);
- p.clearActive();
- }
- setActiveTarget(null);
- commitActiveTabId(null);
- window.location.hash = '';
+ const pane = focusedPane(workspaceRef.current);
+ activateOrOpenSurfaceNewTab(pane.id, next);
};
const closeActiveTabOrWindow = (): boolean => {
- const activeNewTab = activeNewTabIdRef.current;
+ const pane = focusedPane(workspaceRef.current);
+ const activeNewTab = pane.activeNewTabId;
if (activeNewTab) {
- closeNewTabById(activeNewTab);
+ closeNewTabInPaneById(pane.id, activeNewTab);
return true;
}
- const pinnedTabSet = new Set(pinnedTabIdsRef.current);
- const openTabSet = new Set(openTabsRef.current.filter((id) => !pinnedTabSet.has(id)));
+ const pinnedTabSet = new Set(pane.pinnedTabIds);
+ const openTabSet = new Set(pane.openTabs.filter((id) => !pinnedTabSet.has(id)));
const activeOpenTab =
- activeTabIdRef.current && openTabSet.has(activeTabIdRef.current)
- ? activeTabIdRef.current
- : null;
- const targetTabId = activeOpenTab ?? visibleTabIdsRef.current.find((id) => openTabSet.has(id));
+ pane.activeTabId && openTabSet.has(pane.activeTabId) ? pane.activeTabId : null;
+ const visibleOrder = visibleTabIdsByPaneRef.current.get(pane.id) ?? [];
+ const targetTabId = activeOpenTab ?? visibleOrder.find((id) => openTabSet.has(id));
if (targetTabId) {
- closeTabById(targetTabId);
+ closeTabInPaneById(pane.id, targetTabId);
return true;
}
- const newTabSet = new Set(newTabIdsRef.current);
- const targetNewTabId = visibleTabIdsRef.current.find((id) => newTabSet.has(id));
+ const newTabSet = new Set(pane.newTabIds);
+ const targetNewTabId = visibleOrder.find((id) => newTabSet.has(id));
if (targetNewTabId) {
- closeNewTabById(targetNewTabId);
+ closeNewTabInPaneById(pane.id, targetNewTabId);
return true;
}
- return false;
+ const fallbackPane = workspaceRef.current.panes.find(
+ (candidate) =>
+ candidate.newTabIds.length > 0 ||
+ candidate.openTabs.some((tabId) => !candidate.pinnedTabIds.includes(tabId)),
+ );
+ if (!fallbackPane) return false;
+ const fallbackNewTab = fallbackPane.activeNewTabId ?? fallbackPane.newTabIds[0] ?? null;
+ if (fallbackNewTab) {
+ closeNewTabInPaneById(fallbackPane.id, fallbackNewTab);
+ return true;
+ }
+ const fallbackTab =
+ (fallbackPane.activeTabId && !fallbackPane.pinnedTabIds.includes(fallbackPane.activeTabId)
+ ? fallbackPane.activeTabId
+ : null) ??
+ fallbackPane.openTabs.find((tabId) => !fallbackPane.pinnedTabIds.includes(tabId));
+ if (!fallbackTab) return false;
+ closeTabInPaneById(fallbackPane.id, fallbackTab);
+ return true;
};
+ function activateNewTabInPaneById(paneId: EditorPaneId, tabId: string) {
+ const pane = workspaceRef.current.panes.find((candidate) => candidate.id === paneId);
+ if (!pane?.newTabIds.includes(tabId)) return;
+ commitWorkspace(
+ transitionEditorWorkspace(workspaceRef.current, {
+ type: 'activate-tab',
+ paneId,
+ tabId,
+ }).workspace,
+ true,
+ );
+ }
+
+ function pinTabInPaneById(paneId: EditorPaneId, tabId: string) {
+ const pane = workspaceRef.current.panes.find((candidate) => candidate.id === paneId);
+ if (!pane?.openTabs.includes(tabId)) return;
+ commitWorkspace(
+ transitionEditorWorkspace(workspaceRef.current, {
+ type: 'pin-tab',
+ paneId,
+ tabId,
+ }).workspace,
+ );
+ }
+
+ function unpinTabInPaneById(paneId: EditorPaneId, tabId: string) {
+ const pane = workspaceRef.current.panes.find((candidate) => candidate.id === paneId);
+ if (!pane?.pinnedTabIds.includes(tabId)) return;
+ markTabSessionClosedDuringRestore();
+ commitWorkspace(
+ transitionEditorWorkspace(workspaceRef.current, {
+ type: 'unpin-tab',
+ paneId,
+ tabId,
+ }).workspace,
+ );
+ }
+
+ function reorderTabsInPaneById(
+ paneId: EditorPaneId,
+ newOrder: readonly string[],
+ draggedTabId: string,
+ ) {
+ const pane = workspaceRef.current.panes.find((candidate) => candidate.id === paneId);
+ if (!pane) return;
+ const known = new Set([...pane.openTabs, ...pane.newTabIds]);
+ const seed = newOrder.filter((tabId) => known.has(tabId));
+ for (const tabId of [...pane.openTabs, ...pane.newTabIds]) {
+ if (!seed.includes(tabId)) seed.push(tabId);
+ }
+ visibleTabIdsByPaneRef.current.set(paneId, seed);
+ setVisibleTabIdsByPane(new Map(visibleTabIdsByPaneRef.current));
+ const openOrder = seed.filter((tabId) => pane.openTabs.includes(tabId));
+ const newTabOrder = seed.filter((tabId) => pane.newTabIds.includes(tabId));
+ const reordered = transitionEditorWorkspace(workspaceRef.current, {
+ type: 'reorder-tabs',
+ paneId,
+ tabIds: openOrder,
+ draggedTabId,
+ }).workspace;
+ commitWorkspace({
+ ...reordered,
+ panes: reordered.panes.map((candidate) =>
+ candidate.id === paneId ? { ...candidate, newTabIds: newTabOrder } : candidate,
+ ),
+ });
+ }
+
+ function moveTabToPaneById(tabId: string, targetPaneId: EditorPaneId, targetIndex: number) {
+ const sourcePane = workspaceRef.current.panes.find(
+ (pane) => pane.openTabs.includes(tabId) || pane.newTabIds.includes(tabId),
+ );
+ const targetPane = workspaceRef.current.panes.find((pane) => pane.id === targetPaneId);
+ if (!sourcePane || !targetPane) return;
+ const targetOrder = reconcileVisibleTabOrder(
+ visibleTabIdsByPaneRef.current.get(targetPaneId) ?? [],
+ targetPane.openTabs,
+ targetPane.newTabIds,
+ ).filter((candidate) => candidate !== tabId);
+ const visibleTargetIndex = Math.max(0, Math.min(targetIndex, targetOrder.length));
+ const targetBucket = sourcePane.newTabIds.includes(tabId)
+ ? targetPane.newTabIds
+ : targetPane.openTabs;
+ const targetBucketIndex = tabBucketIndexForVisibleInsertion(
+ targetOrder,
+ targetBucket,
+ visibleTargetIndex,
+ );
+ const nextWorkspace = transitionEditorWorkspace(workspaceRef.current, {
+ type: 'move-tab',
+ tabId,
+ paneId: targetPaneId,
+ index: targetBucketIndex,
+ }).workspace;
+ if (sourcePane.id !== targetPaneId) {
+ visibleTabIdsByPaneRef.current.set(
+ sourcePane.id,
+ reconcileVisibleTabOrder(
+ visibleTabIdsByPaneRef.current.get(sourcePane.id) ?? [],
+ sourcePane.openTabs,
+ sourcePane.newTabIds,
+ ).filter((candidate) => candidate !== tabId),
+ );
+ targetOrder.splice(visibleTargetIndex, 0, tabId);
+ visibleTabIdsByPaneRef.current.set(targetPaneId, targetOrder);
+ }
+ commitWorkspace(nextWorkspace, true);
+ }
+
+ function splitTabById(
+ tabId: string,
+ targetPaneId: EditorPaneId,
+ side: PaneSide,
+ ): EditorPaneId | null {
+ const sourcePane = workspaceRef.current.panes.find(
+ (pane) => pane.openTabs.includes(tabId) || pane.newTabIds.includes(tabId),
+ );
+ if (!sourcePane) return null;
+ const newPaneId = createPaneId();
+ const nextWorkspace = transitionEditorWorkspace(workspaceRef.current, {
+ type: 'split-tab',
+ tabId,
+ paneId: targetPaneId,
+ side,
+ newPaneId,
+ }).workspace;
+ const newPane = nextWorkspace.panes.find((pane) => pane.id === newPaneId);
+ if (!newPane) return null;
+ visibleTabIdsByPaneRef.current.set(
+ sourcePane.id,
+ reconcileVisibleTabOrder(
+ visibleTabIdsByPaneRef.current.get(sourcePane.id) ?? [],
+ sourcePane.openTabs,
+ sourcePane.newTabIds,
+ ).filter((candidate) => candidate !== tabId),
+ );
+ visibleTabIdsByPaneRef.current.set(newPane.id, [tabId]);
+ commitWorkspace(nextWorkspace, true);
+ return newPane.id;
+ }
+
+ function moveTabToNewPaneById(tabId: string, side: PaneSide): EditorPaneId | null {
+ const owner = findPaneOwningTab(workspaceRef.current, tabId);
+ if (!owner) return null;
+ return splitTabById(tabId, owner.id, side);
+ }
+
+ function resizeEditorPanes(sizesByPane: ReadonlyMap<EditorPaneId, number>) {
+ if (sizesByPane.size === 0) return;
+ commitWorkspace(
+ transitionEditorWorkspace(workspaceRef.current, {
+ type: 'resize-panes',
+ sizes: workspaceRef.current.panes.map((pane) => sizesByPane.get(pane.id) ?? pane.size),
+ }).workspace,
+ );
+ }
+
+ function promoteTabInPaneById(paneId: EditorPaneId, tabId: string) {
+ commitWorkspace(
+ transitionEditorWorkspace(workspaceRef.current, {
+ type: 'promote-preview',
+ paneId,
+ tabId,
+ }).workspace,
+ );
+ }
+
+ function promoteAllPreviewTabs() {
+ commitWorkspace(
+ transitionEditorWorkspace(workspaceRef.current, {
+ type: 'promote-all-previews',
+ }).workspace,
+ );
+ }
+
useEffect(() => {
return subscribeLocalMenuAction((action) => {
if (action !== 'close-active-tab-or-window') return;
@@ -1800,17 +1998,42 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
closeActiveTabOrWindow,
]);
+ const activeDocName = providerDocNameForPane(surfacePane);
+ const activeProvider =
+ snapshot.activeDocName === activeDocName
+ ? snapshot.activeProvider
+ : (snapshot.poolEntries.find((entry) => entry.docName === activeDocName)?.provider ?? null);
+
const value: DocumentContextValue = {
principal,
- activeTarget,
- activeTabId,
- activeDocName: snapshot.activeDocName,
- activeProvider: snapshot.activeProvider,
+ activeTarget: surfacePane.activeTarget,
+ activeTabId: surfacePane.activeTabId,
skillsSidebar,
setSkillsSidebar,
skillFocused,
+ activeDocName,
+ activeProvider,
+ workspace,
+ panes: surfaceWorkspace.panes,
+ focusedPaneId: surfaceWorkspace.focusedPaneId,
+ focusPane: focusPaneById,
+ activateTabInPane: activateTabInPaneById,
+ activateNewTabInPane: activateNewTabInPaneById,
+ openNewTabInPane: openNewTabInPaneById,
+ closeTabInPane: closeTabInPaneById,
+ closeTabsInPane: closeTabsInPaneById,
+ closeNewTabInPane: closeNewTabInPaneById,
+ pinTabInPane: pinTabInPaneById,
+ unpinTabInPane: unpinTabInPaneById,
+ reorderTabsInPane: reorderTabsInPaneById,
+ moveTabToPane: moveTabToPaneById,
+ splitTab: splitTabById,
+ moveTabToNewPane: moveTabToNewPaneById,
+ resizePanes: resizeEditorPanes,
openTabs,
pinnedTabIds,
+ visibleTabIdsByPane: visibleTabIdsByPaneForMode,
+ previewTabIdsByPane,
visibleTabIds: visibleTabIdsForMode,
tabSessionLoaded,
syncState: snapshot.syncState,
@@ -1819,177 +2042,76 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
openDocument,
openDocumentTransition,
openTarget,
+ openTargetInPane,
openTargetTransition,
+ promoteTabInPane: promoteTabInPaneById,
+ promoteAllPreviewTabs,
clearTarget: () => {
- if (collabUrl === null) {
- setActiveTarget((current) => (current === null ? current : null));
- activeTabIdRef.current = null;
- setActiveTabId((current) => (current === null ? current : null));
- return;
- }
- const p = getPool(collabUrl);
- if (p.getActiveDocName() !== null) p.clearActive();
- setActiveTarget((current) => (current === null ? current : null));
- activeTabIdRef.current = null;
- setActiveTabId((current) => (current === null ? current : null));
+ const pane = focusedPane(workspaceRef.current);
+ if (pane.activeNewTabId !== null && !isSkillsNewTabId(pane.activeNewTabId)) return;
+ activateOrOpenSurfaceNewTab(pane.id, false);
},
closeDocument: (docName: string) => {
- if (collabUrl === null) return;
markTabSessionClosedDuringRestore();
- const p = getPool(collabUrl);
- p.close(docName);
- updateOpenTabs((current) => removeOpenTab(current, docTabId(docName)));
- setActiveTabId((current) => {
- const next = current && docNameForTabId(current) === docName ? null : current;
- activeTabIdRef.current = next;
- return next;
- });
- setActiveTarget((current) => {
- if (!current) return current;
- return docNameForNavigationTarget(current) === docName ? null : current;
- });
+ const focusedWasClosed =
+ providerDocNameForPane(focusedPane(workspaceRef.current)) === docName;
+ const nextWorkspace = transitionEditorWorkspace(workspaceRef.current, {
+ type: 'prune-tabs',
+ keep: (tabId) => docNameForTabId(tabId) !== docName,
+ }).workspace;
+ if (collabUrl !== null) getPool(collabUrl).close(docName);
+ commitWorkspace(nextWorkspace, focusedWasClosed);
},
closeActiveTabOrWindow,
closeTab: closeTabById,
- pinTab: (tabId: string) => {
- const nextPinnedTabIds = addPinnedTab(pinnedTabIdsRef.current, tabId, openTabsRef.current);
- if (sameTabIds(pinnedTabIdsRef.current, nextPinnedTabIds)) return;
- // Pin is additive; the restore merge unions pinned IDs. No close-during-restore mark.
- commitPinnedTabIds(nextPinnedTabIds);
- },
- unpinTab: (tabId: string) => {
- const nextPinnedTabIds = removePinnedTab(pinnedTabIdsRef.current, tabId);
- if (sameTabIds(pinnedTabIdsRef.current, nextPinnedTabIds)) return;
- // Unpin removes a tab from the pinned set — close-like for the pinned slot.
- // Mark so the restore merge doesn't re-pin it from the restored snapshot.
- markTabSessionClosedDuringRestore();
- commitPinnedTabIds(nextPinnedTabIds);
- },
- activateTab: (tabId: string) => {
- // Activate doesn't open/close tabs — only changes the active tab. The
- // restore's shouldRestoreActive gate respects the current hash, so no mark.
- activateTabById(tabId);
- },
- reorderTabs: (newOrder: readonly string[], draggedTabId: string) => {
- // Tab drag-reorder. newOrder is the desired visibleTabIds order after
- // a drop — a mix of openTab IDs and new-tab placeholders. Only the
- // dragged tab's pin state can flip, and only if it crossed the
- // pinned/unpinned divide (see applyDragPinMutation + the interface doc
- // above). Persistence rides the existing openTabs/pinnedTabIds effect.
- const openTabsSet = new Set(openTabsRef.current);
- const newTabIdsSet = new Set(newTabIdsRef.current);
- const seen = new Set<string>();
- const nextOpenTabs: string[] = [];
- const nextNewTabIds: string[] = [];
- const seedVisibleTabIds: string[] = [];
- for (const tabId of newOrder) {
- if (seen.has(tabId)) continue;
- if (openTabsSet.has(tabId)) {
- nextOpenTabs.push(tabId);
- seedVisibleTabIds.push(tabId);
- seen.add(tabId);
- } else if (newTabIdsSet.has(tabId)) {
- nextNewTabIds.push(tabId);
- seedVisibleTabIds.push(tabId);
- seen.add(tabId);
- }
- }
- // Defensive: append any open/new tab id the caller forgot to include so
- // we never silently drop a tab. The caller (EditorTabs handleDragEnd)
- // passes visibleTabIds, so this is a backstop.
- for (const tabId of openTabsRef.current) {
- if (!seen.has(tabId)) {
- nextOpenTabs.push(tabId);
- seedVisibleTabIds.push(tabId);
- seen.add(tabId);
- }
- }
- for (const tabId of newTabIdsRef.current) {
- if (!seen.has(tabId)) {
- nextNewTabIds.push(tabId);
- seedVisibleTabIds.push(tabId);
- seen.add(tabId);
- }
- }
- const sameOpenOrder = sameTabIds(openTabsRef.current, nextOpenTabs);
- const sameNewOrder = sameTabIds(newTabIdsRef.current, nextNewTabIds);
- // Dragging a new-tab placeholder among doc-tabs (or vice versa) leaves
- // the per-bucket orders unchanged but mutates the visible interleave —
- // checking only the buckets early-returns valid reorders and drops them
- // on the floor.
- const sameVisibleOrder = sameTabIds(visibleTabIdsRef.current, seedVisibleTabIds);
- if (sameOpenOrder && sameNewOrder && sameVisibleOrder) return;
- // Reorder changes positions only — no opens/closes. The restore merge
- // preserves the restored order; user's drag is then persisted by the
- // next save effect. No close-during-restore mark needed.
- // Seed visibleTabIdsRef so commitTabState's reconcileVisibleTabOrder
- // uses the new drag-determined order as its starting point.
- visibleTabIdsRef.current = seedVisibleTabIds;
- if (!sameNewOrder) {
- newTabIdsRef.current = nextNewTabIds;
- setNewTabIds((current) => (sameTabIds(current, nextNewTabIds) ? current : nextNewTabIds));
- }
- const nextPinnedTabIds = applyDragPinMutation(
- nextOpenTabs,
- pinnedTabIdsRef.current,
- draggedTabId,
- );
- commitTabState(nextOpenTabs, nextPinnedTabIds);
- },
- newTabIds,
- activeNewTabId,
- isNewTabActive,
+ pinTab: (tabId: string) => pinTabInPaneById(workspaceRef.current.focusedPaneId, tabId),
+ unpinTab: (tabId: string) => unpinTabInPaneById(workspaceRef.current.focusedPaneId, tabId),
+ activateTab: activateTabById,
+ reorderTabs: (newOrder: readonly string[], draggedTabId: string) =>
+ reorderTabsInPaneById(workspaceRef.current.focusedPaneId, newOrder, draggedTabId),
+ newTabIds: surfacePane.newTabIds,
+ activeNewTabId: surfacePane.activeNewTabId,
+ isNewTabActive: surfacePane.activeNewTabId !== null,
openNewTab: openNewTabById,
- activateNewTab: (tabId: string) => {
- // Activate only — no open/close. No close-during-restore mark.
- if (!newTabIdsRef.current.includes(tabId)) return;
- if (collabUrl !== null) {
- const p = getPool(collabUrl);
- p.clearActive();
- }
- setActiveTarget(null);
- commitActiveTabId(null);
- commitActiveNewTabId(tabId);
- if (window.location.hash !== '') {
- window.location.hash = '';
- }
- },
+ activateNewTab: (tabId: string) =>
+ activateNewTabInPaneById(workspaceRef.current.focusedPaneId, tabId),
closeNewTab: closeNewTabById,
reopenClosedTab: () => {
const stack = [...recentlyClosedTabsRef.current];
while (stack.length > 0) {
- const tabId = stack.pop();
- if (!tabId) continue;
- if (openTabsRef.current.includes(tabId)) {
+ const closed = stack.shift();
+ if (!closed) continue;
+ if (findPaneOwningTab(workspaceRef.current, closed.tabId)) {
recentlyClosedTabsRef.current = stack;
continue;
}
- const nextOpenTabs = addOpenTab(
- openTabsRef.current,
- tabId,
- MAX_POOL,
- pinnedTabIdsRef.current,
- );
- if (!nextOpenTabs.includes(tabId)) return;
+ const targetPane =
+ workspaceRef.current.panes.find((pane) => pane.id === closed.paneId) ??
+ focusedPane(workspaceRef.current);
recentlyClosedTabsRef.current = stack;
- commitOpenTabs(nextOpenTabs);
- activateTabById(tabId);
+ const target = resolvedTargetForTabId(closed.tabId);
+ commitWorkspace(
+ transitionEditorWorkspace(workspaceRef.current, {
+ type: 'open-target',
+ paneId: targetPane.id,
+ tabId: closed.tabId,
+ target,
+ disposition: 'permanent',
+ consumeActiveNewTab: false,
+ }).workspace,
+ true,
+ );
return;
}
recentlyClosedTabsRef.current = [];
},
- closeTabs: (tabIds: readonly string[], options: CloseTabsOptions = {}) => {
- const requestedTabIds = tabIds.filter((tabId) => tabId.length > 0);
- if (options.force) {
- closeTabIds(requestedTabIds);
- return;
- }
- closeTabIds(filterClosableTabIds(requestedTabIds, pinnedTabIdsRef.current), {
- rememberRecentlyClosed: true,
- });
- },
+ closeTabs: closeTabsAcrossPanes,
syncOpenTabsWithKnownTargets: ({ pages, folderPaths, assetPaths, filePaths }) => {
- const keepMissingDocName = activeTarget?.kind === 'missing' ? activeTarget.target : null;
+ const missingDocNames = new Set(
+ workspaceRef.current.panes.flatMap((pane) =>
+ pane.activeTarget?.kind === 'missing' ? [pane.activeTarget.target] : [],
+ ),
+ );
// Never evict the doc the hash currently points at: on cold start the page
// list arrives empty-then-populated, and a sync firing in that window would
// otherwise prune the just-seeded doc and clear the hash (→ empty-state
@@ -1998,69 +2120,29 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
// can race ahead of.
const keepHashDocName =
typeof window !== 'undefined' ? docNameFromHash(window.location.hash) : null;
- const nextOpenTabs = filterOpenTabsForKnownTargets(openTabs, {
- pages,
+ const allOpenTabs = flattenWorkspaceTabs(workspaceRef.current);
+ const nextOpenTabs = filterOpenTabsForKnownTargets(allOpenTabs, {
+ pages: new Set([...pages, ...missingDocNames]),
folderPaths,
assetPaths,
filePaths,
- keepMissingDocName,
+ keepMissingDocName: null,
keepHashDocName,
});
- if (nextOpenTabs.length === openTabs.length) return;
+ if (nextOpenTabs.length === allOpenTabs.length) return;
const nextTabIds = new Set(nextOpenTabs);
- const staleTabIds = openTabs.filter((tabId) => !nextTabIds.has(tabId));
- const staleTabIdSet = new Set(staleTabIds);
+ const staleTabIds = allOpenTabs.filter((tabId) => !nextTabIds.has(tabId));
markTabSessionClosedDuringRestore();
- if (collabUrl !== null) {
- const p = getPool(collabUrl);
- for (const tabId of staleTabIds) {
- const docName = docNameForTabId(tabId);
- if (docName) p.close(docName);
- }
- }
-
- commitOpenTabs(nextOpenTabs);
-
- const hashTabId = typeof window !== 'undefined' ? tabIdFromHash(window.location.hash) : null;
- const currentActiveTabId =
- activeTabId ?? activeTabIdForTarget(activeTarget, snapshot.activeDocName);
- const tabToReplace =
- hashTabId && staleTabIdSet.has(hashTabId)
- ? hashTabId
- : currentActiveTabId && staleTabIdSet.has(currentActiveTabId)
- ? currentActiveTabId
- : null;
-
- if (!tabToReplace) {
- setActiveTarget((current) => {
- if (!current) return current;
- const targetTabId = tabIdForNavigationTarget(current);
- return targetTabId && staleTabIdSet.has(targetTabId) ? null : current;
- });
- return;
- }
-
- // Keep the successor on the evicted tab's surface, so deleting the open
- // skill doc lands on the Skills empty state instead of a Files tab.
- const activeIsSkill = tabIdIsSkillSurface(tabToReplace);
- const sameSurface = openTabs.filter((id) => tabIdIsSkillSurface(id) === activeIsSkill);
- const nextActiveTabId = nextActiveTabAfterCloseMany(sameSurface, tabToReplace, staleTabIds);
- if (nextActiveTabId) {
- commitActiveTabId(nextActiveTabId);
- window.location.hash = hashFromTabId(nextActiveTabId);
- return;
- }
- // No tab left on this surface → pin it so its empty/home state shows.
- setSkillsSidebarState(activeIsSkill);
- if (collabUrl !== null) {
- const p = getPool(collabUrl);
- p.clearActive();
- }
- setActiveTarget(null);
- commitActiveTabId(null);
- window.location.hash = '';
+ const focusedActiveTabId = focusedPane(workspaceRef.current).activeTabId;
+ const focusedWasPruned = focusedActiveTabId !== null && !nextTabIds.has(focusedActiveTabId);
+ const nextWorkspace = transitionEditorWorkspace(workspaceRef.current, {
+ type: 'prune-tabs',
+ keep: (tabId) => nextTabIds.has(tabId),
+ }).workspace;
+ closeProvidersWithoutOpenTabs(staleTabIds, nextWorkspace);
+ commitWorkspace(nextWorkspace, focusedWasPruned);
},
reconcileLocalRename: (input) => createRemovalReconciler().reconcileLocalRename(input),
reconcileLocalRemoval: (input) => createRemovalReconciler().reconcileLocalRemoval(input),
@@ -2133,8 +2215,8 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
// agent mode. Return early so a double-click landing before the
// hashchange resolves (activeDocName still null) can't fall through to
// the toggle guard below and flip the just-opened panel back to doc mode.
- if (!snapshot.activeDocName && targetDoc) {
- window.location.hash = hashFromDocName(targetDoc);
+ if (!activeDocName && targetDoc) {
+ navigateToHash(hashFromDocName(targetDoc));
setDocPanelAgentId(connectionId);
setDocPanelModeState('agent');
setDocPanelExpandSignal((prev) => prev + 1);
diff --git a/packages/app/src/editor/SourceEditor.dom.test.tsx b/packages/app/src/editor/SourceEditor.dom.test.tsx
index f0c743b6a..eaf873643 100644
--- a/packages/app/src/editor/SourceEditor.dom.test.tsx
+++ b/packages/app/src/editor/SourceEditor.dom.test.tsx
@@ -290,13 +290,51 @@ describe('SourceEditor outline navigation', () => {
globalThis.fetch = originalFetch;
});
- async function dispatchOutlineNav(index: number, slug: string): Promise<void> {
- const detail: OutlineNavDetail = { index, slug, mode: 'source' };
+ async function dispatchOutlineNav(docName: string, index: number, slug: string): Promise<void> {
+ const detail: OutlineNavDetail = { docName, index, slug, mode: 'source' };
await act(async () => {
window.dispatchEvent(new CustomEvent(OUTLINE_NAV_EVENT, { detail }));
});
}
+ test('only the source editor matching the navigation document moves its cursor', async () => {
+ const first = makeProvider('source-outline-owner', '# First\n\n## First target');
+ const second = makeProvider('source-outline-bystander', '# Second\n\n## Second target');
+ const { container } = render(
+ <>
+ <Harness provider={first.provider} ytext={first.ytext} wordWrap={true} />
+ <Harness provider={second.provider} ytext={second.ytext} wordWrap={true} />
+ </>,
+ );
+
+ await waitFor(() => {
+ expect(container.querySelectorAll('.cm-content')).toHaveLength(2);
+ });
+ const [firstContent, secondContent] = container.querySelectorAll<HTMLElement>('.cm-content');
+ const firstView = EditorView.findFromDOM(firstContent);
+ const secondView = EditorView.findFromDOM(secondContent);
+ expect(firstView).toBeTruthy();
+ expect(secondView).toBeTruthy();
+ if (!firstView || !secondView) return;
+
+ const secondSelectionBefore = secondView.state.selection.main.head;
+ await act(async () => {
+ window.dispatchEvent(
+ new CustomEvent(OUTLINE_NAV_EVENT, {
+ detail: {
+ docName: 'source-outline-owner',
+ index: 1,
+ slug: 'first-target',
+ mode: 'source',
+ } satisfies OutlineNavDetail,
+ }),
+ );
+ });
+
+ expect(firstView.state.selection.main.head).toBe(firstView.state.doc.line(3).from);
+ expect(secondView.state.selection.main.head).toBe(secondSelectionBefore);
+ });
+
test('skips a frontmatter region whose opening fence carries a trailing space', async () => {
// `--- ` is one in-tolerance keystroke away from `---`. The outline list
// comes from the server's extractHeadings (core fence contract — FM
@@ -320,7 +358,7 @@ describe('SourceEditor outline navigation', () => {
expect(view).toBeTruthy();
if (!view) return;
- await dispatchOutlineNav(0, 'real-heading');
+ await dispatchOutlineNav('source-outline-nav-fm-ws', 0, 'real-heading');
const headingLine = view.state.doc.line(6);
expect(headingLine.text).toBe('# Real Heading');
@@ -344,7 +382,7 @@ describe('SourceEditor outline navigation', () => {
expect(view).toBeTruthy();
if (!view) return;
- await dispatchOutlineNav(0, 'real-heading');
+ await dispatchOutlineNav('source-outline-nav-fm-close-ws', 0, 'real-heading');
const headingLine = view.state.doc.line(6);
expect(headingLine.text).toBe('# Real Heading');
@@ -370,7 +408,7 @@ describe('SourceEditor outline navigation', () => {
expect(view).toBeTruthy();
if (!view) return;
- await dispatchOutlineNav(1, 'second');
+ await dispatchOutlineNav('source-outline-nav-fm-bare', 1, 'second');
const headingLine = view.state.doc.line(8);
expect(headingLine.text).toBe('## Second');
diff --git a/packages/app/src/editor/SourceEditor.tsx b/packages/app/src/editor/SourceEditor.tsx
index d27f3d32c..f5267d462 100644
--- a/packages/app/src/editor/SourceEditor.tsx
+++ b/packages/app/src/editor/SourceEditor.tsx
@@ -514,7 +514,8 @@ export function SourceEditor({
useEffect(() => {
function onNav(e: Event) {
const detail = (e as CustomEvent<OutlineNavDetail>).detail;
- if (!detail || detail.mode !== 'source' || !isSourceModeActive) return;
+ if (!detail || detail.docName !== docName || detail.mode !== 'source' || !isSourceModeActive)
+ return;
const view = viewRef.current;
if (!view) return;
applyOutlineNavigation(view, detail, docName);
@@ -528,7 +529,7 @@ export function SourceEditor({
useEffect(() => {
function onLintNav(e: Event) {
const detail = (e as CustomEvent<LintNavDetail>).detail;
- if (!detail || !isSourceModeActive) return;
+ if (!detail || detail.docName !== docName || !isSourceModeActive) return;
const view = viewRef.current;
if (!view) return;
applyLintNavigation(view, detail, docName);
diff --git a/packages/app/src/editor/TiptapEditor.tsx b/packages/app/src/editor/TiptapEditor.tsx
index 96c32c9e0..4e6506016 100644
--- a/packages/app/src/editor/TiptapEditor.tsx
+++ b/packages/app/src/editor/TiptapEditor.tsx
@@ -39,7 +39,6 @@ import { OUTLINE_NAV_EVENT, type OutlineNavDetail } from '@/components/OutlinePa
import { anchorFromHash } from '@/lib/doc-hash';
import { mark } from '@/lib/perf';
import { wrapExtensionsWithTiming } from '@/lib/perf/cold-mount-instrumentation';
-import type { SidebarDragPayload } from '@/lib/sidebar-drag';
import { useIdentity } from '../presence/identity';
import { registerEditor, unregisterEditor } from './active-editor';
import { applyLintFixes } from './apply-lint-fix.ts';
@@ -82,7 +81,6 @@ import {
SELECTION_STATS_DEBOUNCE_MS,
selectionStatsFromWysiwyg,
} from './selection-stats';
-import { createSidebarAwareHandleDrop, openSidebarDropPayload } from './sidebar-drop';
import {
consumePendingWysiwygNavigation,
peekPendingWysiwygNavigation,
@@ -296,7 +294,6 @@ interface BuildEditorOptionsArgs {
* DocumentContext; the guard's publication gate protects either way.
*/
onWedged?: (detail: WedgeDetail) => void;
- onSidebarDrop?: (payload: SidebarDragPayload) => void;
}
/**
@@ -512,7 +509,7 @@ function buildEditorOptions(args: BuildEditorOptionsArgs): Partial<EditorOptions
clipboardTextSerializer: (slice, view) => clipboard.text(slice, view),
clipboardSerializer: clipboard.html.serializer,
handlePaste: (view, event) => clipboard.paste(view, event),
- handleDrop: createSidebarAwareHandleDrop(clipboard.drop, args.onSidebarDrop),
+ handleDrop: clipboard.drop,
handleDOMEvents: {
copy: (view, event) => clipboard.copy(view, event as ClipboardEvent, false),
cut: (view, event) => clipboard.copy(view, event as ClipboardEvent, true),
@@ -533,7 +530,6 @@ interface BuildPatternDConstructorOptionsArgs {
clipboard: ClipboardState;
ctorStart: number;
onWedged?: (detail: WedgeDetail) => void;
- onSidebarDrop?: (payload: SidebarDragPayload) => void;
}
/**
@@ -584,7 +580,7 @@ type PatternDConstructorOptions = Partial<EditorOptions> & { element: null };
export function buildPatternDConstructorOptions(
args: BuildPatternDConstructorOptionsArgs,
): PatternDConstructorOptions {
- const { provider, placeholder, clipboard, ctorStart, onWedged, onSidebarDrop } = args;
+ const { provider, placeholder, clipboard, ctorStart, onWedged } = args;
const fragment = provider.document.getXmlFragment('default');
// Stable Map wired to Collaboration's `ySyncOptions.mapping` via
// `buildPrewarmBoundCollaboration`. Starts empty; the wrapped
@@ -598,7 +594,6 @@ export function buildPatternDConstructorOptions(
ctorStart,
prebuiltMapping,
onWedged,
- onSidebarDrop,
});
const baseOnBeforeCreate = baseOptions.onBeforeCreate;
return {
@@ -659,7 +654,7 @@ export const TiptapEditor: FC<TiptapEditorProps> = ({
const wrapperRef = useRef<HTMLDivElement | null>(null);
const flashStateRef = useRef(INITIAL_FLASH_STATE);
const identity = useIdentity();
- const { principal, activeDocName, recycleDocument, openTarget } = useDocumentContext();
+ const { principal, activeDocName, recycleDocument } = useDocumentContext();
const docName = provider.configuration.name ?? '';
const [clipboard] = useState(buildClipboardState);
@@ -699,9 +694,6 @@ export const TiptapEditor: FC<TiptapEditorProps> = ({
mark('ok/editor/binding-wedge-recycle', { docName, externalSeq, appliedSeq });
recycleDocument(docName);
},
- onSidebarDrop: (payload) => {
- openSidebarDropPayload(payload, openTarget);
- },
}),
);
return {
@@ -1578,7 +1570,8 @@ const TiptapEditorChrome: FC<TiptapEditorChromeProps> = ({
useEffect(() => {
function onNav(e: Event) {
const detail = (e as CustomEvent<OutlineNavDetail>).detail;
- if (!detail || detail.mode !== 'wysiwyg' || editor.isDestroyed) return;
+ if (!detail || detail.docName !== docName || detail.mode !== 'wysiwyg' || editor.isDestroyed)
+ return;
// `getEditorView` is the non-throwing accessor for the underlying
// ProseMirror EditorView (see utils/get-editor-view.ts). Returns
// undefined pre-mount, never throws on the recycle/remount race.
diff --git a/packages/app/src/editor/active-editor.ts b/packages/app/src/editor/active-editor.ts
index 7c7cde650..455c70c61 100644
--- a/packages/app/src/editor/active-editor.ts
+++ b/packages/app/src/editor/active-editor.ts
@@ -10,11 +10,11 @@
* sequences where the key command reads PM internal state require a
* PM-state-aware wait, not a DOM-frame yield.
*
- * Registry is module-scope, not pooled — `EditorActivityPool` can mount up
- * to `ACTIVITY_MOUNT_LIMIT` (3) editors concurrently. Last-writer wins per
- * docName; `getEditorForDoc` resolves via `activeDocName` in DocumentContext
- * so the getter picks the currently-active entry, not whichever registered
- * last.
+ * Registry is module-scope, not pooled — `EditorActivityPool` mounts every
+ * visible pane plus an `ACTIVITY_MOUNT_LIMIT` (3) warm-background floor.
+ * Last-writer wins per docName; split view keeps one editor per docName, and
+ * `getEditorForDoc` resolves via `activeDocName` in DocumentContext so the
+ * getter picks the focused entry rather than whichever registered last.
*/
import type { Editor } from '@tiptap/core';
diff --git a/packages/app/src/editor/clipboard/wysiwyg-stop-rule.test.ts b/packages/app/src/editor/clipboard/wysiwyg-stop-rule.test.ts
index 922afe3af..57c954321 100644
--- a/packages/app/src/editor/clipboard/wysiwyg-stop-rule.test.ts
+++ b/packages/app/src/editor/clipboard/wysiwyg-stop-rule.test.ts
@@ -27,6 +27,7 @@ describe('WYSIWYG STOP rule — ProseMirror clipboard hooks', () => {
expect(typeof props.clipboardTextSerializer).toBe('function');
expect(props.clipboardSerializer).toBe(fakeClipboard.html.serializer);
+ expect(props.handleDrop).toBe(fakeClipboard.drop);
});
test('wires copy/cut ONLY to the comment-carriage intercept; dragstart stays PM-native', () => {
diff --git a/packages/app/src/editor/editor-panes.test.ts b/packages/app/src/editor/editor-panes.test.ts
new file mode 100644
index 000000000..b3cf06c19
--- /dev/null
+++ b/packages/app/src/editor/editor-panes.test.ts
@@ -0,0 +1,939 @@
+import { describe, expect, test } from 'vitest';
+import {
+ closeTabsInPane,
+ createEmptyEditorPane,
+ createEmptyEditorWorkspace,
+ type EditorWorkspaceState,
+ findPaneOwningTab,
+ flattenWorkspacePinnedTabs,
+ flattenWorkspaceTabs,
+ focusEditorPane,
+ hydrateEditorWorkspace,
+ moveTabToPane,
+ normalizeEditorWorkspace,
+ parsePersistedEditorWorkspace,
+ persistEditorWorkspace,
+ projectVisibleEditorWorkspace,
+ pruneEmptyEditorPanes,
+ recordRecentlyClosedTab,
+ remapWorkspaceTabs,
+ reorderPaneTabs,
+ splitTabToPane,
+ tabBucketIndexForVisibleInsertion,
+ transitionEditorWorkspace,
+} from './editor-panes';
+
+function docTarget(docName: string) {
+ return { kind: 'doc' as const, target: docName, docName };
+}
+
+function pane(
+ id: string,
+ openTabs: string[],
+ activeTabId: string | null = openTabs[0] ?? null,
+ size = 100,
+) {
+ return {
+ ...createEmptyEditorPane(id, size),
+ openTabs,
+ activeTabId,
+ activeTarget: activeTabId ? docTarget(activeTabId) : null,
+ };
+}
+
+describe('editor pane workspace', () => {
+ test('rejects malformed workspaces and drops legacy occurrence ids', () => {
+ const malformed = parsePersistedEditorWorkspace({ panes: [{ id: '', openTabs: ['a'] }] });
+ const legacy = parsePersistedEditorWorkspace({
+ panes: [
+ {
+ id: 'pane-a',
+ openTabs: ['a', 'a\u0000doc-tab:1', 'b', 42],
+ pinnedTabIds: ['a\u0000doc-tab:1', 'missing'],
+ activeTabId: 'a\u0000doc-tab:1',
+ size: 0,
+ },
+ ],
+ focusedPaneId: 'missing-pane',
+ });
+
+ expect(malformed).toEqual({
+ panes: [{ id: 'pane-main', openTabs: [], pinnedTabIds: [], activeTabId: null, size: 100 }],
+ focusedPaneId: 'pane-main',
+ });
+ expect(legacy).toEqual({
+ panes: [
+ {
+ id: 'pane-a',
+ openTabs: ['a', 'b'],
+ pinnedTabIds: [],
+ activeTabId: 'a',
+ size: 100,
+ },
+ ],
+ focusedPaneId: 'pane-a',
+ });
+ });
+
+ test('hydrates persisted panes with empty runtime-only state', () => {
+ expect(
+ hydrateEditorWorkspace({
+ panes: [
+ {
+ id: 'pane-a',
+ openTabs: ['a'],
+ pinnedTabIds: ['a'],
+ activeTabId: 'a',
+ size: 100,
+ },
+ ],
+ focusedPaneId: 'pane-a',
+ }),
+ ).toEqual({
+ panes: [
+ {
+ id: 'pane-a',
+ openTabs: ['a'],
+ pinnedTabIds: ['a'],
+ activeTabId: 'a',
+ previewTabId: null,
+ newTabIds: [],
+ activeNewTabId: null,
+ activeTarget: null,
+ size: 100,
+ },
+ ],
+ focusedPaneId: 'pane-a',
+ });
+ });
+
+ test('normalizes current ids, target ownership, pins, focus, and size percentages', () => {
+ const workspace = normalizeEditorWorkspace({
+ panes: [
+ {
+ ...pane('pane-a', ['a', 'a\u0000doc-tab:1', 'b'], 'missing', 1),
+ pinnedTabIds: ['a', 'missing'],
+ },
+ { ...pane('pane-a', ['c'], 'c', 1) },
+ { ...pane('pane-b', ['b', 'c'], 'c', 3) },
+ ],
+ focusedPaneId: 'missing',
+ });
+
+ expect(workspace).toEqual({
+ panes: [
+ {
+ ...pane('pane-a', ['a', 'b'], 'a', 25),
+ pinnedTabIds: ['a'],
+ activeTarget: null,
+ },
+ { ...pane('pane-b', ['c'], 'c', 75) },
+ ],
+ focusedPaneId: 'pane-a',
+ });
+ expect(flattenWorkspaceTabs(workspace)).toEqual(['a', 'b', 'c']);
+ expect(flattenWorkspacePinnedTabs(workspace)).toEqual(['a']);
+ expect(findPaneOwningTab(workspace, 'a')?.id).toBe('pane-a');
+ expect(findPaneOwningTab(workspace, 'a\u0000doc-tab:7')).toBeNull();
+ });
+
+ test('falls back to the first tab when a persisted pane has no valid active tab', () => {
+ const workspace = parsePersistedEditorWorkspace({
+ panes: [
+ {
+ id: 'pane-a',
+ openTabs: ['a', 'b'],
+ pinnedTabIds: [],
+ activeTabId: null,
+ size: 50,
+ },
+ {
+ id: 'pane-b',
+ openTabs: ['c', 'd'],
+ pinnedTabIds: [],
+ activeTabId: 'missing',
+ size: 50,
+ },
+ ],
+ focusedPaneId: 'pane-b',
+ });
+
+ expect(workspace.panes.map(({ id, activeTabId }) => ({ id, activeTabId }))).toEqual([
+ { id: 'pane-a', activeTabId: 'a' },
+ { id: 'pane-b', activeTabId: 'c' },
+ ]);
+ });
+
+ test('normalizes every non-empty runtime pane to exactly one active tab', () => {
+ const workspace = normalizeEditorWorkspace({
+ panes: [
+ { ...pane('pane-a', ['a'], null, 50), activeTarget: docTarget('stale') },
+ {
+ ...pane('pane-b', [], null, 50),
+ newTabIds: ['new-tab:1'],
+ activeNewTabId: null,
+ },
+ ],
+ focusedPaneId: 'pane-a',
+ });
+
+ expect(workspace.panes[0]).toMatchObject({
+ activeTabId: 'a',
+ activeNewTabId: null,
+ activeTarget: null,
+ });
+ expect(workspace.panes[1]).toMatchObject({
+ activeTabId: null,
+ activeNewTabId: 'new-tab:1',
+ activeTarget: null,
+ });
+ });
+
+ test('lets the focused pane claim document tabs first, prunes empty panes, and normalizes sizes', () => {
+ const workspace = parsePersistedEditorWorkspace({
+ panes: [
+ {
+ id: 'pane-a',
+ openTabs: ['a', 'b'],
+ pinnedTabIds: ['a'],
+ activeTabId: 'b',
+ size: 25,
+ },
+ {
+ id: 'pane-b',
+ openTabs: ['a'],
+ pinnedTabIds: ['a'],
+ activeTabId: 'a',
+ size: 50,
+ },
+ {
+ id: 'pane-c',
+ openTabs: ['a', 'c'],
+ pinnedTabIds: [],
+ activeTabId: 'c',
+ size: 25,
+ },
+ {
+ id: 'pane-d',
+ openTabs: ['a'],
+ pinnedTabIds: [],
+ activeTabId: 'a',
+ size: 100,
+ },
+ ],
+ focusedPaneId: 'pane-b',
+ });
+
+ expect(workspace).toEqual({
+ panes: [
+ { id: 'pane-a', openTabs: ['b'], pinnedTabIds: [], activeTabId: 'b', size: 25 },
+ { id: 'pane-b', openTabs: ['a'], pinnedTabIds: ['a'], activeTabId: 'a', size: 50 },
+ { id: 'pane-c', openTabs: ['c'], pinnedTabIds: [], activeTabId: 'c', size: 25 },
+ ],
+ focusedPaneId: 'pane-b',
+ });
+ expect(parsePersistedEditorWorkspace(workspace)).toEqual(workspace);
+ });
+
+ test('splits a tab into a new side-by-side pane, clears the new selection target, and preserves the old selection', () => {
+ const workspace: EditorWorkspaceState = {
+ panes: [pane('pane-a', ['a', 'b'], 'a')],
+ focusedPaneId: 'pane-a',
+ };
+
+ const split = splitTabToPane(workspace, 'b', 'pane-a', 'right', () => 'pane-b');
+
+ expect(split.panes).toEqual([
+ { ...pane('pane-a', ['a'], 'a', 50) },
+ { ...pane('pane-b', ['b'], 'b', 50), activeTarget: null },
+ ]);
+ expect(split.focusedPaneId).toBe('pane-b');
+ expect(splitTabToPane(split, 'b', 'pane-b', 'left', () => 'pane-c')).toEqual(split);
+ expect(splitTabToPane(workspace, 'b', 'pane-a', 'right', () => 'pane-a')).toBe(workspace);
+ });
+
+ test('splits folder and blank tabs when they share a pane', () => {
+ const folderTabId = '\u0000folder:New Folder 5';
+ const newTabId = 'new-tab:1';
+ const workspace: EditorWorkspaceState = {
+ panes: [
+ {
+ ...pane('pane-a', [folderTabId], folderTabId),
+ newTabIds: [newTabId],
+ },
+ ],
+ focusedPaneId: 'pane-a',
+ };
+
+ const folderSplit = splitTabToPane(
+ workspace,
+ folderTabId,
+ 'pane-a',
+ 'left',
+ () => 'pane-folder',
+ );
+ expect(folderSplit.panes[0]).toMatchObject({
+ id: 'pane-folder',
+ openTabs: [folderTabId],
+ activeTabId: folderTabId,
+ newTabIds: [],
+ activeNewTabId: null,
+ });
+ expect(folderSplit.panes[1]).toMatchObject({
+ id: 'pane-a',
+ openTabs: [],
+ newTabIds: [newTabId],
+ activeNewTabId: newTabId,
+ });
+
+ const blankSplit = splitTabToPane(workspace, newTabId, 'pane-a', 'right', () => 'pane-blank');
+ expect(blankSplit.panes[0]).toMatchObject({
+ id: 'pane-a',
+ openTabs: [folderTabId],
+ newTabIds: [],
+ });
+ expect(blankSplit.panes[1]).toMatchObject({
+ id: 'pane-blank',
+ openTabs: [],
+ activeTabId: null,
+ newTabIds: [newTabId],
+ activeNewTabId: newTabId,
+ });
+ expect(findPaneOwningTab(workspace, newTabId)?.id).toBe('pane-a');
+ });
+
+ test('moves tabs between panes, maintains pins, and clears any stale active target', () => {
+ const workspace: EditorWorkspaceState = {
+ panes: [
+ { ...pane('pane-a', ['a', 'b'], 'b'), pinnedTabIds: ['b'] },
+ pane('pane-b', ['c'], 'c'),
+ ],
+ focusedPaneId: 'pane-a',
+ };
+
+ const moved = moveTabToPane(workspace, 'b', 'pane-b', 1);
+
+ expect(moved.panes).toEqual([
+ { ...pane('pane-a', ['a'], 'a', 50), activeTarget: null },
+ { ...pane('pane-b', ['c', 'b'], 'b', 50), pinnedTabIds: ['b'], activeTarget: null },
+ ]);
+ expect(moved.focusedPaneId).toBe('pane-b');
+ });
+
+ test('translates a visible insertion around interleaved blank tabs to its bucket index', () => {
+ const visibleOrder = ['doc-a', 'new-tab:1', 'doc-b', 'new-tab:2'];
+
+ expect(tabBucketIndexForVisibleInsertion([], [], 0)).toBe(0);
+ expect(tabBucketIndexForVisibleInsertion(visibleOrder, ['doc-a', 'doc-b'], 0)).toBe(0);
+ expect(tabBucketIndexForVisibleInsertion(visibleOrder, ['doc-a', 'doc-b'], 2)).toBe(1);
+ expect(tabBucketIndexForVisibleInsertion(visibleOrder, ['new-tab:1', 'new-tab:2'], 3)).toBe(1);
+ expect(tabBucketIndexForVisibleInsertion(visibleOrder, ['doc-a', 'doc-b'], 99)).toBe(2);
+ });
+
+ test('moves blank tabs between panes and activates them at the destination', () => {
+ const workspace: EditorWorkspaceState = {
+ panes: [
+ { ...pane('pane-a', ['a'], null), newTabIds: ['new-tab:1'], activeNewTabId: 'new-tab:1' },
+ pane('pane-b', ['b'], 'b'),
+ ],
+ focusedPaneId: 'pane-a',
+ };
+
+ const moved = moveTabToPane(workspace, 'new-tab:1', 'pane-b', 0);
+
+ expect(moved.panes[0]).toMatchObject({
+ id: 'pane-a',
+ openTabs: ['a'],
+ activeTabId: 'a',
+ newTabIds: [],
+ activeNewTabId: null,
+ });
+ expect(moved.panes[1]).toMatchObject({
+ id: 'pane-b',
+ openTabs: ['b'],
+ activeTabId: null,
+ newTabIds: ['new-tab:1'],
+ activeNewTabId: 'new-tab:1',
+ activeTarget: null,
+ });
+ expect(moved.focusedPaneId).toBe('pane-b');
+ });
+
+ test('reorders a tab within its current pane through the move operation', () => {
+ const workspace: EditorWorkspaceState = {
+ panes: [{ ...pane('pane-a', ['a', 'b', 'c'], 'b'), pinnedTabIds: ['a'] }],
+ focusedPaneId: 'pane-a',
+ };
+
+ expect(moveTabToPane(workspace, 'c', 'pane-a', 0).panes[0]).toEqual({
+ ...pane('pane-a', ['c', 'a', 'b'], 'b'),
+ pinnedTabIds: ['c', 'a'],
+ });
+ expect(moveTabToPane(workspace, 'a', 'pane-a', 99).panes[0]).toEqual({
+ ...pane('pane-a', ['b', 'c', 'a'], 'b'),
+ pinnedTabIds: [],
+ });
+ });
+
+ test('reorders tabs in one pane and adjusts only the dragged tab pin state', () => {
+ const workspace: EditorWorkspaceState = {
+ panes: [{ ...pane('pane-a', ['pinned', 'a', 'b'], 'a'), pinnedTabIds: ['pinned'] }],
+ focusedPaneId: 'pane-a',
+ };
+
+ expect(reorderPaneTabs(workspace, 'pane-a', ['b', 'pinned', 'a'], 'b').panes[0]).toEqual({
+ ...pane('pane-a', ['b', 'pinned', 'a'], 'a'),
+ pinnedTabIds: ['b', 'pinned'],
+ });
+ });
+
+ test('prunes empty panes, preserves one empty workspace, and focuses a surviving pane', () => {
+ const workspace: EditorWorkspaceState = {
+ panes: [pane('pane-a', [], null), pane('pane-b', ['b'], 'b', 25), pane('pane-c', [], null)],
+ focusedPaneId: 'pane-a',
+ };
+
+ expect(pruneEmptyEditorPanes(workspace)).toEqual({
+ panes: [{ ...pane('pane-b', ['b'], 'b', 100) }],
+ focusedPaneId: 'pane-b',
+ });
+ expect(
+ pruneEmptyEditorPanes({ panes: [pane('pane-a', [], null)], focusedPaneId: 'pane-a' }),
+ ).toEqual(createEmptyEditorWorkspace(() => 'pane-a'));
+ });
+
+ test('projects only panes with visible tabs without deleting the saved workspace', () => {
+ const workspace: EditorWorkspaceState = {
+ panes: [
+ pane('pane-files', ['file-a'], 'file-a', 25),
+ {
+ ...pane('pane-mixed', ['file-b', 'skill-b'], 'file-b', 50),
+ pinnedTabIds: ['file-b', 'skill-b'],
+ previewTabId: 'file-b',
+ },
+ pane('pane-skills', ['skill-c'], 'skill-c', 25),
+ ],
+ focusedPaneId: 'pane-files',
+ };
+
+ const projected = projectVisibleEditorWorkspace(
+ workspace,
+ new Map([
+ ['pane-files', []],
+ ['pane-mixed', ['skill-b']],
+ ['pane-skills', ['skill-c']],
+ ]),
+ );
+
+ expect(projected).toEqual({
+ panes: [
+ {
+ ...pane('pane-mixed', ['skill-b'], 'skill-b', 100 * (2 / 3)),
+ pinnedTabIds: ['skill-b'],
+ activeTarget: null,
+ },
+ pane('pane-skills', ['skill-c'], 'skill-c', 100 * (1 / 3)),
+ ],
+ focusedPaneId: 'pane-mixed',
+ });
+ expect(workspace.panes.map((candidate) => candidate.openTabs)).toEqual([
+ ['file-a'],
+ ['file-b', 'skill-b'],
+ ['skill-c'],
+ ]);
+ });
+
+ test('projects a valid empty workspace when no pane has visible tabs', () => {
+ const workspace: EditorWorkspaceState = {
+ panes: [pane('pane-skills', ['skill-a'], 'skill-a')],
+ focusedPaneId: 'pane-skills',
+ };
+
+ expect(projectVisibleEditorWorkspace(workspace, new Map([['pane-skills', []]]))).toEqual(
+ createEmptyEditorWorkspace(() => 'pane-skills'),
+ );
+ });
+
+ test('preserves a preview tab when it remains visible in the projected pane', () => {
+ const workspace: EditorWorkspaceState = {
+ panes: [
+ {
+ ...pane('pane-files', ['file-a', 'file-preview'], 'file-a'),
+ previewTabId: 'file-preview',
+ },
+ ],
+ focusedPaneId: 'pane-files',
+ };
+
+ expect(
+ projectVisibleEditorWorkspace(
+ workspace,
+ new Map([['pane-files', ['file-a', 'file-preview']]]),
+ ),
+ ).toEqual(workspace);
+ });
+
+ test('closes and remaps tabs without retaining a target for a changed selection', () => {
+ const workspace: EditorWorkspaceState = {
+ panes: [pane('pane-a', ['a', 'b'], 'a')],
+ focusedPaneId: 'pane-a',
+ };
+
+ const closed = closeTabsInPane(workspace, 'pane-a', ['a']);
+ expect(closed.panes[0]).toEqual({ ...pane('pane-a', ['b'], 'b', 100), activeTarget: null });
+
+ const remapped = remapWorkspaceTabs(
+ { panes: [pane('pane-a', ['a', 'b'], 'b')], focusedPaneId: 'pane-a' },
+ (tabId) => (tabId === 'b' ? 'renamed-b' : tabId),
+ );
+ expect(remapped.panes[0]).toEqual({
+ ...pane('pane-a', ['a', 'renamed-b'], 'renamed-b', 100),
+ activeTarget: null,
+ });
+
+ const duplicates = remapWorkspaceTabs(
+ {
+ panes: [pane('pane-a', ['a']), pane('pane-b', ['b'])],
+ focusedPaneId: 'pane-a',
+ },
+ () => 'renamed',
+ );
+ expect(duplicates.panes).toEqual([
+ { ...pane('pane-a', ['renamed'], 'renamed', 100), activeTarget: null },
+ ]);
+ });
+
+ test('replaces only the pane preview and reports displacement without closing history', () => {
+ const workspace: EditorWorkspaceState = {
+ panes: [
+ {
+ ...pane('pane-a', ['permanent', 'preview-old'], 'permanent'),
+ previewTabId: 'preview-old',
+ },
+ ],
+ focusedPaneId: 'pane-a',
+ };
+
+ const transition = transitionEditorWorkspace(workspace, {
+ type: 'open-target',
+ paneId: 'pane-a',
+ tabId: 'preview-new',
+ target: docTarget('preview-new'),
+ disposition: 'preview',
+ consumeActiveNewTab: false,
+ });
+
+ expect(transition).toMatchObject({
+ openedTabId: 'preview-new',
+ replacedPreviewTabId: 'preview-old',
+ consumedNewTabId: null,
+ });
+ expect(transition.workspace.panes[0]).toMatchObject({
+ openTabs: ['permanent', 'preview-new'],
+ activeTabId: 'preview-new',
+ previewTabId: 'preview-new',
+ activeTarget: docTarget('preview-new'),
+ });
+ });
+
+ test('promotes an existing preview for permanent intent and never demotes a permanent tab', () => {
+ const workspace: EditorWorkspaceState = {
+ panes: [
+ {
+ ...pane('pane-a', ['preview'], 'preview', 50),
+ previewTabId: 'preview',
+ },
+ pane('pane-b', ['permanent'], 'permanent', 50),
+ ],
+ focusedPaneId: 'pane-a',
+ };
+
+ const promoted = transitionEditorWorkspace(workspace, {
+ type: 'open-target',
+ paneId: 'pane-a',
+ tabId: 'preview',
+ target: docTarget('preview'),
+ disposition: 'permanent',
+ consumeActiveNewTab: false,
+ });
+ expect(promoted.workspace.panes[0]?.previewTabId).toBeNull();
+
+ const existingPermanent = transitionEditorWorkspace(promoted.workspace, {
+ type: 'open-target',
+ paneId: 'pane-a',
+ tabId: 'permanent',
+ target: docTarget('permanent'),
+ disposition: 'preview',
+ consumeActiveNewTab: false,
+ });
+ expect(existingPermanent.workspace.focusedPaneId).toBe('pane-b');
+ expect(existingPermanent.workspace.panes[1]).toMatchObject({
+ openTabs: ['permanent'],
+ activeTabId: 'permanent',
+ previewTabId: null,
+ });
+ });
+
+ test('opens an existing folder tab in an explicitly targeted pane without removing the other pane copy', () => {
+ const fooFolderTabId = '\u0000folder:foo';
+ const barFolderTabId = '\u0000folder:bar';
+ const workspace: EditorWorkspaceState = {
+ panes: [
+ pane('pane-a', ['foo.md'], 'foo.md', 50),
+ pane('pane-b', [fooFolderTabId, barFolderTabId], barFolderTabId, 50),
+ ],
+ focusedPaneId: 'pane-b',
+ };
+ const fooFolderTarget = { kind: 'folder' as const, target: 'foo', folderPath: 'foo' };
+
+ const transition = transitionEditorWorkspace(workspace, {
+ type: 'open-target',
+ paneId: 'pane-a',
+ tabId: fooFolderTabId,
+ target: fooFolderTarget,
+ disposition: 'permanent',
+ consumeActiveNewTab: false,
+ existingTabBehavior: 'open-in-pane',
+ });
+
+ expect(transition.workspace.focusedPaneId).toBe('pane-a');
+ expect(transition.workspace.panes[0]).toMatchObject({
+ id: 'pane-a',
+ openTabs: ['foo.md', fooFolderTabId],
+ activeTabId: fooFolderTabId,
+ activeTarget: fooFolderTarget,
+ });
+ expect(transition.workspace.panes[1]).toMatchObject({
+ id: 'pane-b',
+ openTabs: [fooFolderTabId, barFolderTabId],
+ activeTabId: barFolderTabId,
+ });
+ });
+
+ test('preserves independent view tabs across panes while keeping document tabs unique', () => {
+ const folderTabId = '\u0000folder:foo';
+ const folderTarget = { kind: 'folder' as const, target: 'foo', folderPath: 'foo' };
+ const workspace = normalizeEditorWorkspace({
+ panes: [
+ {
+ ...pane('pane-a', ['foo.md', folderTabId], folderTabId, 50),
+ pinnedTabIds: [folderTabId],
+ activeTarget: folderTarget,
+ },
+ {
+ ...pane('pane-b', ['foo.md', folderTabId], folderTabId, 50),
+ activeTarget: folderTarget,
+ },
+ ],
+ focusedPaneId: 'pane-b',
+ });
+
+ expect(workspace.panes).toEqual([
+ {
+ ...pane('pane-a', ['foo.md', folderTabId], folderTabId, 50),
+ pinnedTabIds: [folderTabId],
+ activeTarget: folderTarget,
+ },
+ {
+ ...pane('pane-b', [folderTabId], folderTabId, 50),
+ activeTarget: folderTarget,
+ },
+ ]);
+ expect(parsePersistedEditorWorkspace(persistEditorWorkspace(workspace))).toEqual({
+ panes: workspace.panes.map(({ id, openTabs, pinnedTabIds, activeTabId, size }) => ({
+ id,
+ openTabs,
+ pinnedTabIds,
+ activeTabId,
+ size,
+ })),
+ focusedPaneId: 'pane-b',
+ });
+
+ const renamedFolderTabId = '\u0000folder:renamed';
+ const remapped = remapWorkspaceTabs(workspace, (tabId) =>
+ tabId === folderTabId ? renamedFolderTabId : tabId,
+ );
+ expect(
+ remapped.panes.map(({ openTabs, pinnedTabIds }) => ({ openTabs, pinnedTabIds })),
+ ).toEqual([
+ { openTabs: ['foo.md', renamedFolderTabId], pinnedTabIds: [renamedFolderTabId] },
+ { openTabs: [renamedFolderTabId], pinnedTabIds: [] },
+ ]);
+ });
+
+ test('appends a permanent tab without promoting an unrelated preview', () => {
+ const workspace: EditorWorkspaceState = {
+ panes: [
+ {
+ ...pane('pane-a', ['preview'], 'preview'),
+ previewTabId: 'preview',
+ },
+ ],
+ focusedPaneId: 'pane-a',
+ };
+
+ const transition = transitionEditorWorkspace(workspace, {
+ type: 'open-target',
+ paneId: 'pane-a',
+ tabId: 'permanent',
+ target: docTarget('permanent'),
+ disposition: 'permanent',
+ consumeActiveNewTab: false,
+ });
+
+ expect(transition.workspace.panes[0]).toMatchObject({
+ openTabs: ['preview', 'permanent'],
+ activeTabId: 'permanent',
+ previewTabId: 'preview',
+ });
+ });
+
+ test.each([
+ 'preview',
+ 'permanent',
+ ] as const)('consumes an active blank independently of %s disposition', (disposition) => {
+ const workspace: EditorWorkspaceState = {
+ panes: [
+ {
+ ...pane('pane-a', ['existing'], null),
+ newTabIds: ['new-tab:1'],
+ activeNewTabId: 'new-tab:1',
+ },
+ ],
+ focusedPaneId: 'pane-a',
+ };
+
+ const transition = transitionEditorWorkspace(workspace, {
+ type: 'open-target',
+ paneId: 'pane-a',
+ tabId: 'opened',
+ target: docTarget('opened'),
+ disposition,
+ consumeActiveNewTab: true,
+ });
+
+ expect(transition.consumedNewTabId).toBe('new-tab:1');
+ expect(transition.workspace.panes[0]).toMatchObject({
+ openTabs: ['existing', 'opened'],
+ newTabIds: [],
+ activeNewTabId: null,
+ previewTabId: disposition === 'preview' ? 'opened' : null,
+ });
+ });
+
+ test('activates, creates, closes, pins, and promotes tabs through the command boundary', () => {
+ let workspace: EditorWorkspaceState = {
+ panes: [pane('pane-a', ['a'], 'a')],
+ focusedPaneId: 'pane-a',
+ };
+
+ workspace = transitionEditorWorkspace(workspace, {
+ type: 'open-new-tab',
+ paneId: 'pane-a',
+ tabId: 'new-tab:1',
+ }).workspace;
+ expect(workspace.panes[0]?.activeNewTabId).toBe('new-tab:1');
+
+ workspace = transitionEditorWorkspace(workspace, {
+ type: 'activate-tab',
+ paneId: 'pane-a',
+ tabId: 'a',
+ }).workspace;
+ expect(workspace.panes[0]).toMatchObject({ activeTabId: 'a', activeNewTabId: null });
+
+ workspace = transitionEditorWorkspace(
+ {
+ ...workspace,
+ panes: workspace.panes.map((pane) => ({ ...pane, previewTabId: 'a' })),
+ },
+ { type: 'pin-tab', paneId: 'pane-a', tabId: 'a' },
+ ).workspace;
+ expect(workspace.panes[0]).toMatchObject({ pinnedTabIds: ['a'], previewTabId: null });
+
+ workspace = transitionEditorWorkspace(workspace, {
+ type: 'unpin-tab',
+ paneId: 'pane-a',
+ tabId: 'a',
+ }).workspace;
+ expect(workspace.panes[0]?.pinnedTabIds).toEqual([]);
+
+ workspace = transitionEditorWorkspace(
+ {
+ ...workspace,
+ panes: workspace.panes.map((pane) => ({ ...pane, previewTabId: 'a' })),
+ },
+ { type: 'promote-preview', paneId: 'pane-a', tabId: 'a' },
+ ).workspace;
+ expect(workspace.panes[0]?.previewTabId).toBeNull();
+
+ workspace = transitionEditorWorkspace(workspace, {
+ type: 'close-tabs',
+ paneId: 'pane-a',
+ tabIds: ['new-tab:1'],
+ }).workspace;
+ expect(workspace.panes[0]?.newTabIds).toEqual([]);
+ });
+
+ test('routes organization commands through normalized workspace invariants', () => {
+ let workspace: EditorWorkspaceState = {
+ panes: [
+ { ...pane('pane-a', ['a', 'b'], 'a', 50), previewTabId: 'b' },
+ pane('pane-b', ['c'], 'c', 50),
+ ],
+ focusedPaneId: 'pane-a',
+ };
+
+ workspace = transitionEditorWorkspace(workspace, {
+ type: 'reorder-tabs',
+ paneId: 'pane-a',
+ tabIds: ['b', 'a'],
+ draggedTabId: 'b',
+ }).workspace;
+ expect(workspace.panes[0]).toMatchObject({
+ openTabs: ['b', 'a'],
+ pinnedTabIds: [],
+ previewTabId: null,
+ });
+
+ workspace = transitionEditorWorkspace(workspace, {
+ type: 'move-tab',
+ tabId: 'b',
+ paneId: 'pane-b',
+ index: 1,
+ }).workspace;
+ expect(workspace.panes[1]?.openTabs).toEqual(['c', 'b']);
+
+ workspace = transitionEditorWorkspace(workspace, {
+ type: 'split-tab',
+ tabId: 'b',
+ paneId: 'pane-b',
+ side: 'right',
+ newPaneId: 'pane-c',
+ }).workspace;
+ expect(workspace.panes.map((item) => item.id)).toEqual(['pane-a', 'pane-b', 'pane-c']);
+
+ workspace = transitionEditorWorkspace(workspace, {
+ type: 'resize-panes',
+ sizes: [20, 30, 50],
+ }).workspace;
+ expect(workspace.panes.map((item) => item.size)).toEqual([20, 30, 50]);
+
+ workspace = transitionEditorWorkspace(workspace, {
+ type: 'remap-tabs',
+ remap: (tabId) => (tabId === 'b' ? 'renamed-b' : tabId),
+ }).workspace;
+ expect(flattenWorkspaceTabs(workspace)).toEqual(['a', 'c', 'renamed-b']);
+
+ workspace = transitionEditorWorkspace(workspace, {
+ type: 'prune-tabs',
+ keep: (tabId) => tabId !== 'c',
+ }).workspace;
+ expect(flattenWorkspaceTabs(workspace)).toEqual(['a', 'renamed-b']);
+ expect(workspace.panes.reduce((sum, item) => sum + item.size, 0)).toBeCloseTo(100);
+ });
+
+ test('promotes every preview without closing tabs', () => {
+ const workspace: EditorWorkspaceState = {
+ panes: [
+ { ...pane('pane-a', ['a'], 'a', 50), previewTabId: 'a' },
+ { ...pane('pane-b', ['b'], 'b', 50), previewTabId: 'b' },
+ ],
+ focusedPaneId: 'pane-a',
+ };
+
+ const promoted = transitionEditorWorkspace(workspace, { type: 'promote-all-previews' });
+ expect(promoted.workspace.panes.map((item) => item.previewTabId)).toEqual([null, null]);
+ expect(flattenWorkspaceTabs(promoted.workspace)).toEqual(['a', 'b']);
+ expect(promoted.replacedPreviewTabId).toBeNull();
+ });
+
+ test('records recently closed tabs once per tab and bounds history', () => {
+ const entries = recordRecentlyClosedTab(
+ recordRecentlyClosedTab([], { paneId: 'pane-a', tabId: 'a' }),
+ { paneId: 'pane-b', tabId: 'a' },
+ 2,
+ );
+
+ expect(entries).toEqual([{ paneId: 'pane-b', tabId: 'a' }]);
+ expect(recordRecentlyClosedTab(entries, { paneId: 'pane-a', tabId: 'b' }, 1)).toEqual([
+ { paneId: 'pane-a', tabId: 'b' },
+ ]);
+ });
+
+ test('accepts 25 persisted panes without applying an editor-count cap', () => {
+ const restored = parsePersistedEditorWorkspace({
+ panes: Array.from({ length: 25 }, (_, index) => ({
+ id: `pane-${index}`,
+ openTabs: [`doc-${index}`],
+ pinnedTabIds: [],
+ activeTabId: `doc-${index}`,
+ size: 1,
+ })),
+ focusedPaneId: 'pane-24',
+ });
+
+ expect(restored.panes).toHaveLength(25);
+ expect(restored.focusedPaneId).toBe('pane-24');
+ expect(restored.panes.reduce((sum, item) => sum + item.size, 0)).toBeCloseTo(100);
+ expect(
+ persistEditorWorkspace({
+ ...restored,
+ panes: restored.panes.map((item) => ({
+ ...item,
+ previewTabId: null,
+ newTabIds: [],
+ activeNewTabId: null,
+ activeTarget: null,
+ })),
+ }),
+ ).toEqual(restored);
+ });
+
+ test('does not focus an unknown pane', () => {
+ const workspace = createEmptyEditorWorkspace(() => 'pane-a');
+ expect(focusEditorPane(workspace, 'missing')).toBe(workspace);
+ });
+
+ test('clears previewTabId when the preview tab is renamed to a different id', () => {
+ const workspace: EditorWorkspaceState = {
+ panes: [
+ {
+ ...pane('pane-a', ['preview', 'other'], 'preview'),
+ previewTabId: 'preview',
+ },
+ ],
+ focusedPaneId: 'pane-a',
+ };
+ const remapped = remapWorkspaceTabs(workspace, (tabId) =>
+ tabId === 'preview' ? 'renamed-preview' : tabId,
+ );
+ expect(remapped.panes[0]?.previewTabId).toBeNull();
+ expect(remapped.panes[0]?.openTabs).toContain('renamed-preview');
+ });
+
+ test('resize-panes returns unchanged workspace on mismatched count or invalid sizes', () => {
+ const workspace: EditorWorkspaceState = {
+ panes: [pane('pane-a', ['a'], 'a', 50), pane('pane-b', ['b'], 'b', 50)],
+ focusedPaneId: 'pane-a',
+ };
+
+ const mismatch = transitionEditorWorkspace(workspace, {
+ type: 'resize-panes',
+ sizes: [100],
+ });
+ expect(mismatch.workspace).toBe(workspace);
+
+ const nanSizes = transitionEditorWorkspace(workspace, {
+ type: 'resize-panes',
+ sizes: [NaN, 50],
+ });
+ expect(nanSizes.workspace).toBe(workspace);
+
+ const zeroSize = transitionEditorWorkspace(workspace, {
+ type: 'resize-panes',
+ sizes: [0, 50],
+ });
+ expect(zeroSize.workspace).toBe(workspace);
+ });
+});
diff --git a/packages/app/src/editor/editor-panes.ts b/packages/app/src/editor/editor-panes.ts
new file mode 100644
index 000000000..6a2bc088e
--- /dev/null
+++ b/packages/app/src/editor/editor-panes.ts
@@ -0,0 +1,1051 @@
+import type { ResolvedNavigationTarget } from '@/components/navigation-targets';
+
+/** A stable identity for one side-by-side editor column. */
+export type EditorPaneId = string;
+
+/**
+ * Runtime-only state for one editor pane. `activeTarget` and blank-tab state
+ * are deliberately not persisted: both are derived while restoring the tab
+ * session and may be stale by the next launch.
+ */
+export interface EditorPaneState {
+ id: EditorPaneId;
+ openTabs: string[];
+ pinnedTabIds: string[];
+ activeTabId: string | null;
+ previewTabId: string | null;
+ newTabIds: string[];
+ activeNewTabId: string | null;
+ activeTarget: ResolvedNavigationTarget | null;
+ /** Percentage of the flat, horizontal editor workspace. */
+ size: number;
+}
+
+export interface EditorWorkspaceState {
+ panes: EditorPaneState[];
+ focusedPaneId: EditorPaneId;
+}
+
+/** The durable, bridge-safe subset of an editor pane. */
+export interface PersistedEditorPane {
+ id: EditorPaneId;
+ openTabs: string[];
+ pinnedTabIds: string[];
+ activeTabId: string | null;
+ size: number;
+}
+
+export interface PersistedEditorWorkspace {
+ panes: PersistedEditorPane[];
+ focusedPaneId: EditorPaneId;
+}
+
+export interface RecentlyClosedEditorTab {
+ paneId: EditorPaneId;
+ tabId: string;
+}
+
+export type PaneSide = 'left' | 'right';
+export type PaneIdFactory = () => EditorPaneId;
+
+export type TabOpenDisposition = 'preview' | 'permanent';
+export type ExistingTabOpenBehavior = 'activate-owner' | 'open-in-pane';
+
+export type EditorWorkspaceCommand =
+ | {
+ type: 'open-target';
+ paneId: EditorPaneId;
+ tabId: string;
+ target: ResolvedNavigationTarget;
+ disposition: TabOpenDisposition;
+ consumeActiveNewTab: boolean;
+ existingTabBehavior?: ExistingTabOpenBehavior;
+ }
+ | { type: 'activate-tab'; paneId: EditorPaneId; tabId: string }
+ | { type: 'promote-preview'; paneId: EditorPaneId; tabId: string }
+ | { type: 'promote-all-previews' }
+ | { type: 'open-new-tab'; paneId: EditorPaneId; tabId: string }
+ | { type: 'close-tabs'; paneId: EditorPaneId; tabIds: readonly string[] }
+ | {
+ type: 'pin-tab';
+ paneId: EditorPaneId;
+ tabId: string;
+ }
+ | { type: 'unpin-tab'; paneId: EditorPaneId; tabId: string }
+ | {
+ type: 'reorder-tabs';
+ paneId: EditorPaneId;
+ tabIds: readonly string[];
+ draggedTabId: string;
+ }
+ | { type: 'move-tab'; tabId: string; paneId: EditorPaneId; index: number }
+ | {
+ type: 'split-tab';
+ tabId: string;
+ paneId: EditorPaneId;
+ side: PaneSide;
+ newPaneId: EditorPaneId;
+ }
+ | { type: 'resize-panes'; sizes: readonly number[] }
+ | { type: 'remap-tabs'; remap: (tabId: string) => string | null }
+ | { type: 'prune-tabs'; keep: (tabId: string) => boolean };
+
+export interface EditorWorkspaceTransition {
+ workspace: EditorWorkspaceState;
+ openedTabId: string | null;
+ replacedPreviewTabId: string | null;
+ consumedNewTabId: string | null;
+}
+
+const DEFAULT_PANE_ID = 'pane-main';
+
+function isCurrentTabId(value: unknown): value is string {
+ return isTabId(value) && !value.includes('\u0000doc-tab:');
+}
+
+function isIndependentViewTabId(tabId: string): boolean {
+ return tabId.startsWith('\u0000');
+}
+
+function isPaneId(value: unknown): value is EditorPaneId {
+ return typeof value === 'string' && !!value;
+}
+
+function isTabId(value: unknown): value is string {
+ return typeof value === 'string' && !!value;
+}
+
+function isPositiveFiniteNumber(value: unknown): value is number {
+ return typeof value === 'number' && Number.isFinite(value) && value > 0;
+}
+
+function normalizeTabIds(value: unknown, claimedTabIds = new Set<string>()): string[] {
+ if (!Array.isArray(value)) return [];
+ const seen = new Set<string>();
+ const tabIds: string[] = [];
+ for (const candidate of value) {
+ if (!isCurrentTabId(candidate) || seen.has(candidate)) continue;
+ if (!isIndependentViewTabId(candidate) && claimedTabIds.has(candidate)) continue;
+ seen.add(candidate);
+ if (!isIndependentViewTabId(candidate)) claimedTabIds.add(candidate);
+ tabIds.push(candidate);
+ }
+ return tabIds;
+}
+
+function normalizePinnedTabIds(value: unknown, openTabs: readonly string[]): string[] {
+ if (!Array.isArray(value)) return [];
+ const openTabIds = new Set(openTabs);
+ const seen = new Set<string>();
+ const pinnedTabIds: string[] = [];
+ for (const candidate of value) {
+ if (!isTabId(candidate) || !openTabIds.has(candidate) || seen.has(candidate)) continue;
+ seen.add(candidate);
+ pinnedTabIds.push(candidate);
+ }
+ return pinnedTabIds;
+}
+
+function activeTabIdFor(openTabs: readonly string[], value: unknown): string | null {
+ return isTabId(value) && openTabs.includes(value) ? value : null;
+}
+
+function nearestTabAfterRemoving(
+ tabs: readonly string[],
+ activeTabId: string | null,
+ removed: ReadonlySet<string>,
+): string | null {
+ if (!activeTabId || !removed.has(activeTabId)) return activeTabId;
+ const index = tabs.indexOf(activeTabId);
+ for (let next = index + 1; next < tabs.length; next++) {
+ if (!removed.has(tabs[next])) return tabs[next] ?? null;
+ }
+ for (let previous = index - 1; previous >= 0; previous--) {
+ if (!removed.has(tabs[previous])) return tabs[previous] ?? null;
+ }
+ return null;
+}
+
+function normalizePane(
+ pane: Omit<EditorPaneState, 'size'> & { size?: unknown },
+ claimedTargets = new Set<string>(),
+): EditorPaneState | null {
+ if (!isPaneId(pane.id)) return null;
+ const openTabs = normalizeTabIds(pane.openTabs, claimedTargets);
+ const newTabIds = Array.isArray(pane.newTabIds)
+ ? pane.newTabIds.filter((tabId): tabId is string => isTabId(tabId) && !openTabs.includes(tabId))
+ : [];
+ const requestedActiveTabId = activeTabIdFor(openTabs, pane.activeTabId);
+ const requestedActiveNewTabId =
+ isTabId(pane.activeNewTabId) && newTabIds.includes(pane.activeNewTabId)
+ ? pane.activeNewTabId
+ : null;
+ const activeTabId =
+ requestedActiveTabId ?? (requestedActiveNewTabId === null ? (openTabs[0] ?? null) : null);
+ const activeNewTabId =
+ activeTabId === null ? (requestedActiveNewTabId ?? newTabIds[0] ?? null) : null;
+ const pinnedTabIds = normalizePinnedTabIds(pane.pinnedTabIds, openTabs);
+ const previewTabId =
+ isCurrentTabId(pane.previewTabId) &&
+ openTabs.includes(pane.previewTabId) &&
+ !pinnedTabIds.includes(pane.previewTabId)
+ ? pane.previewTabId
+ : null;
+ return {
+ id: pane.id,
+ openTabs,
+ pinnedTabIds,
+ activeTabId,
+ previewTabId,
+ newTabIds,
+ activeNewTabId,
+ // A resolved target belongs to the exact selected tab. When normalization
+ // selects a fallback, the resolver must rebuild that target instead of
+ // projecting stale navigation state into the editor.
+ activeTarget:
+ activeTabId !== null && activeTabId === requestedActiveTabId
+ ? (pane.activeTarget ?? null)
+ : null,
+ size: isPositiveFiniteNumber(pane.size) ? pane.size : 1,
+ };
+}
+
+function normalizePaneSizes<T extends { size: number }>(panes: readonly T[]): T[] {
+ if (panes.length === 0) return [];
+ const total = panes.reduce(
+ (sum, pane) => sum + (isPositiveFiniteNumber(pane.size) ? pane.size : 0),
+ 0,
+ );
+ if (total <= 0) {
+ const equalSize = 100 / panes.length;
+ return panes.map((pane) => ({ ...pane, size: equalSize }));
+ }
+ return panes.map((pane) => ({
+ ...pane,
+ size: ((isPositiveFiniteNumber(pane.size) ? pane.size : 0) / total) * 100,
+ }));
+}
+
+export function createEmptyEditorPane(id: EditorPaneId, size = 100): EditorPaneState {
+ return {
+ id,
+ openTabs: [],
+ pinnedTabIds: [],
+ activeTabId: null,
+ previewTabId: null,
+ newTabIds: [],
+ activeNewTabId: null,
+ activeTarget: null,
+ size,
+ };
+}
+
+export function createEmptyEditorWorkspace(
+ createPaneId: PaneIdFactory = () => DEFAULT_PANE_ID,
+): EditorWorkspaceState {
+ const pane = createEmptyEditorPane(createPaneId());
+ return { panes: [pane], focusedPaneId: pane.id };
+}
+
+/** Converts persisted session data into runtime state without resolving targets. */
+export function hydrateEditorWorkspace(session: PersistedEditorWorkspace): EditorWorkspaceState {
+ const panes = session.panes.map((pane) => ({
+ ...pane,
+ previewTabId: null,
+ newTabIds: [],
+ activeNewTabId: null,
+ activeTarget: null,
+ }));
+ return {
+ panes,
+ focusedPaneId: panes.some((p) => p.id === session.focusedPaneId)
+ ? session.focusedPaneId
+ : (panes[0]?.id ?? DEFAULT_PANE_ID),
+ };
+}
+
+/** Removes runtime-only fields before session persistence / IPC transport. */
+export function persistEditorWorkspace(workspace: EditorWorkspaceState): PersistedEditorWorkspace {
+ const normalized = normalizeEditorWorkspace(workspace);
+ return {
+ panes: normalized.panes.map(({ id, openTabs, pinnedTabIds, activeTabId, size }) => ({
+ id,
+ openTabs,
+ pinnedTabIds,
+ activeTabId,
+ size,
+ })),
+ focusedPaneId: normalized.focusedPaneId,
+ };
+}
+
+/**
+ * Defensively parses persisted pane data. Provider-backed document tabs remain
+ * globally unique, while independent folder and asset views may occupy more
+ * than one pane.
+ */
+export function parsePersistedEditorWorkspace(
+ value: unknown,
+ createPaneId: PaneIdFactory = () => DEFAULT_PANE_ID,
+): PersistedEditorWorkspace {
+ const fallback = () => {
+ const id = createPaneId();
+ return {
+ panes: [{ id, openTabs: [], pinnedTabIds: [], activeTabId: null, size: 100 }],
+ focusedPaneId: id,
+ };
+ };
+ if (typeof value !== 'object' || value === null) return fallback();
+ const raw = value as Record<string, unknown>;
+ if (!Array.isArray(raw.panes)) return fallback();
+
+ const claimedPaneIds = new Set<string>();
+ const candidates: Array<{
+ pane: Record<string, unknown>;
+ id: EditorPaneId;
+ visualIndex: number;
+ }> = [];
+ for (const [visualIndex, rawPane] of raw.panes.entries()) {
+ if (typeof rawPane !== 'object' || rawPane === null) continue;
+ const pane = rawPane as Record<string, unknown>;
+ if (!isPaneId(pane.id) || claimedPaneIds.has(pane.id)) continue;
+ claimedPaneIds.add(pane.id);
+ candidates.push({ pane, id: pane.id, visualIndex });
+ }
+ if (candidates.length === 0) return fallback();
+
+ const requestedFocus = isPaneId(raw.focusedPaneId) ? raw.focusedPaneId : null;
+ const claimOrder = [...candidates].sort((left, right) => {
+ if (left.id === requestedFocus) return -1;
+ if (right.id === requestedFocus) return 1;
+ return left.visualIndex - right.visualIndex;
+ });
+ const claimedTabIds = new Set<string>();
+ const claimedPanes = new Map<EditorPaneId, PersistedEditorPane>();
+ for (const { pane, id } of claimOrder) {
+ const openTabs = normalizeTabIds(pane.openTabs, claimedTabIds);
+ const activeTabId = activeTabIdFor(openTabs, pane.activeTabId);
+ claimedPanes.set(id, {
+ id,
+ openTabs,
+ pinnedTabIds: normalizePinnedTabIds(pane.pinnedTabIds, openTabs),
+ activeTabId: activeTabId ?? openTabs[0] ?? null,
+ size: isPositiveFiniteNumber(pane.size) ? pane.size : 1,
+ });
+ }
+
+ const panes = candidates.flatMap(({ id }) => {
+ const pane = claimedPanes.get(id);
+ return pane && pane.openTabs.length > 0 ? [pane] : [];
+ });
+ if (panes.length === 0) return fallback();
+ const normalizedPanes = normalizePaneSizes(panes);
+ const focusedPaneId =
+ requestedFocus && normalizedPanes.some((pane) => pane.id === requestedFocus)
+ ? requestedFocus
+ : normalizedPanes[0].id;
+ return { panes: normalizedPanes, focusedPaneId };
+}
+
+export function normalizeEditorWorkspace(workspace: EditorWorkspaceState): EditorWorkspaceState {
+ const claimedPaneIds = new Set<string>();
+ const claimedTabIds = new Set<string>();
+ const panes = workspace.panes.flatMap((pane) => {
+ // Reject duplicate pane identities before normalizing tabs. Otherwise a
+ // discarded duplicate would still claim its targets and silently evict
+ // valid tabs from a later, distinct pane.
+ if (!isPaneId(pane.id) || claimedPaneIds.has(pane.id)) return [];
+ const normalized = normalizePane(pane, claimedTabIds);
+ if (!normalized) return [];
+ claimedPaneIds.add(normalized.id);
+ return [normalized];
+ });
+ if (panes.length === 0) return createEmptyEditorWorkspace();
+ const normalizedPanes = normalizePaneSizes(panes);
+ return {
+ panes: normalizedPanes,
+ focusedPaneId: normalizedPanes.some((pane) => pane.id === workspace.focusedPaneId)
+ ? workspace.focusedPaneId
+ : normalizedPanes[0].id,
+ };
+}
+
+export function focusedPane(workspace: EditorWorkspaceState): EditorPaneState {
+ return (
+ workspace.panes.find((pane) => pane.id === workspace.focusedPaneId) ??
+ workspace.panes[0] ??
+ createEmptyEditorPane(DEFAULT_PANE_ID)
+ );
+}
+
+export function focusEditorPane(
+ workspace: EditorWorkspaceState,
+ paneId: EditorPaneId,
+): EditorWorkspaceState {
+ if (!workspace.panes.some((pane) => pane.id === paneId)) return workspace;
+ return { ...workspace, focusedPaneId: paneId };
+}
+
+function findPaneContainingTab(
+ workspace: EditorWorkspaceState,
+ tabId: string,
+): EditorPaneState | null {
+ const focused = workspace.panes.find((pane) => pane.id === workspace.focusedPaneId);
+ if (focused?.openTabs.includes(tabId) || focused?.newTabIds.includes(tabId)) return focused;
+ return (
+ workspace.panes.find(
+ (pane) => pane.openTabs.includes(tabId) || pane.newTabIds.includes(tabId),
+ ) ?? null
+ );
+}
+
+export function findPaneOwningTab(
+ workspace: EditorWorkspaceState,
+ tabId: string,
+): EditorPaneState | null {
+ return isCurrentTabId(tabId) ? findPaneContainingTab(workspace, tabId) : null;
+}
+
+export function flattenWorkspaceTabs(workspace: EditorWorkspaceState): string[] {
+ return workspace.panes.flatMap((pane) => pane.openTabs);
+}
+
+export function flattenWorkspacePinnedTabs(workspace: EditorWorkspaceState): string[] {
+ const open = new Set(flattenWorkspaceTabs(workspace));
+ return workspace.panes.flatMap((pane) => pane.pinnedTabIds.filter((tabId) => open.has(tabId)));
+}
+
+export function updateEditorPane(
+ workspace: EditorWorkspaceState,
+ paneId: EditorPaneId,
+ update: (pane: EditorPaneState) => EditorPaneState,
+): EditorWorkspaceState {
+ return {
+ ...workspace,
+ panes: workspace.panes.map((pane) => (pane.id === paneId ? update(pane) : pane)),
+ };
+}
+
+export function reorderPaneTabs(
+ workspace: EditorWorkspaceState,
+ paneId: EditorPaneId,
+ nextOpenTabs: readonly string[],
+ draggedTabId: string,
+): EditorWorkspaceState {
+ const pane = workspace.panes.find((candidate) => candidate.id === paneId);
+ if (!pane) return workspace;
+ const allowed = new Set(pane.openTabs);
+ const ordered = nextOpenTabs.filter((tabId) => allowed.has(tabId));
+ for (const tabId of pane.openTabs) if (!ordered.includes(tabId)) ordered.push(tabId);
+ const previousPinned = new Set(pane.pinnedTabIds);
+ const draggedIndex = ordered.indexOf(draggedTabId);
+ const shouldPin = draggedIndex >= 0 && draggedIndex < pane.pinnedTabIds.length;
+ const pinnedTabIds = pane.openTabs.includes(draggedTabId)
+ ? ordered.filter((tabId) => (tabId === draggedTabId ? shouldPin : previousPinned.has(tabId)))
+ : pane.pinnedTabIds;
+ return updateEditorPane(workspace, paneId, (current) => ({
+ ...current,
+ openTabs: ordered,
+ pinnedTabIds,
+ previewTabId: current.previewTabId === draggedTabId ? null : current.previewTabId,
+ }));
+}
+
+function removeTabFromPane(pane: EditorPaneState, tabId: string): EditorPaneState {
+ const newTabIndex = pane.newTabIds.indexOf(tabId);
+ if (newTabIndex >= 0) {
+ const newTabIds = pane.newTabIds.filter((candidate) => candidate !== tabId);
+ const wasActive = pane.activeNewTabId === tabId;
+ const activeNewTabId = wasActive
+ ? (newTabIds[newTabIndex] ?? newTabIds[newTabIndex - 1] ?? null)
+ : pane.activeNewTabId;
+ const activeTabId =
+ wasActive && activeNewTabId === null
+ ? (pane.openTabs[pane.openTabs.length - 1] ?? null)
+ : pane.activeTabId;
+ return {
+ ...pane,
+ newTabIds,
+ activeNewTabId,
+ activeTabId,
+ activeTarget:
+ activeNewTabId === null && activeTabId === pane.activeTabId ? pane.activeTarget : null,
+ };
+ }
+
+ const index = pane.openTabs.indexOf(tabId);
+ if (index < 0) return pane;
+ const removed = new Set([tabId]);
+ const activeTabId = nearestTabAfterRemoving(pane.openTabs, pane.activeTabId, removed);
+ const activeNewTabId =
+ pane.activeTabId === tabId && activeTabId === null
+ ? (pane.activeNewTabId ?? pane.newTabIds[pane.newTabIds.length - 1] ?? null)
+ : pane.activeNewTabId;
+ return {
+ ...pane,
+ openTabs: pane.openTabs.filter((candidate) => candidate !== tabId),
+ pinnedTabIds: pane.pinnedTabIds.filter((candidate) => candidate !== tabId),
+ activeTabId,
+ activeNewTabId,
+ previewTabId: pane.previewTabId === tabId ? null : pane.previewTabId,
+ activeTarget:
+ activeNewTabId === null && activeTabId === pane.activeTabId ? pane.activeTarget : null,
+ };
+}
+
+export function pruneEmptyEditorPanes(workspace: EditorWorkspaceState): EditorWorkspaceState {
+ const nonEmpty = workspace.panes.filter((pane) => pane.openTabs.length || pane.newTabIds.length);
+ if (nonEmpty.length === 0)
+ return createEmptyEditorWorkspace(() => workspace.focusedPaneId || DEFAULT_PANE_ID);
+ const panes = normalizePaneSizes(nonEmpty);
+ return {
+ panes,
+ focusedPaneId: panes.some((pane) => pane.id === workspace.focusedPaneId)
+ ? workspace.focusedPaneId
+ : panes[0].id,
+ };
+}
+
+/**
+ * Build the pane layout for a filtered tab surface without mutating the saved
+ * workspace. Panes whose tabs are all hidden disappear from this projection;
+ * switching surfaces can still restore their original tabs and pane identity.
+ */
+export function projectVisibleEditorWorkspace(
+ workspace: EditorWorkspaceState,
+ visibleTabIdsByPane: ReadonlyMap<EditorPaneId, readonly string[]>,
+): EditorWorkspaceState {
+ const panes = workspace.panes.flatMap((pane) => {
+ const paneTabIds = new Set([...pane.openTabs, ...pane.newTabIds]);
+ const visibleTabIds = (visibleTabIdsByPane.get(pane.id) ?? []).filter(
+ (tabId, index, tabs) => paneTabIds.has(tabId) && tabs.indexOf(tabId) === index,
+ );
+ if (visibleTabIds.length === 0) return [];
+
+ const visible = new Set(visibleTabIds);
+ const openTabs = pane.openTabs.filter((tabId) => visible.has(tabId));
+ const newTabIds = pane.newTabIds.filter((tabId) => visible.has(tabId));
+ const selectedTabId =
+ (pane.activeTabId && visible.has(pane.activeTabId) ? pane.activeTabId : null) ??
+ (pane.activeNewTabId && visible.has(pane.activeNewTabId) ? pane.activeNewTabId : null) ??
+ visibleTabIds[0];
+ const activeTabId = openTabs.includes(selectedTabId) ? selectedTabId : null;
+ const activeNewTabId = newTabIds.includes(selectedTabId) ? selectedTabId : null;
+
+ return [
+ {
+ ...pane,
+ openTabs,
+ pinnedTabIds: pane.pinnedTabIds.filter((tabId) => visible.has(tabId)),
+ activeTabId,
+ previewTabId:
+ pane.previewTabId && visible.has(pane.previewTabId) ? pane.previewTabId : null,
+ newTabIds,
+ activeNewTabId,
+ activeTarget: activeTabId === pane.activeTabId ? pane.activeTarget : null,
+ },
+ ];
+ });
+
+ if (panes.length === 0) {
+ return createEmptyEditorWorkspace(() => workspace.focusedPaneId || DEFAULT_PANE_ID);
+ }
+
+ const normalizedPanes = normalizePaneSizes(panes);
+ return {
+ panes: normalizedPanes,
+ focusedPaneId: normalizedPanes.some((pane) => pane.id === workspace.focusedPaneId)
+ ? workspace.focusedPaneId
+ : normalizedPanes[0].id,
+ };
+}
+
+export function tabBucketIndexForVisibleInsertion(
+ visibleOrder: readonly string[],
+ bucketTabIds: readonly string[],
+ visibleIndex: number,
+): number {
+ const bucket = new Set(bucketTabIds);
+ const boundedIndex = Math.max(0, Math.min(visibleIndex, visibleOrder.length));
+ let bucketIndex = 0;
+ for (let index = 0; index < boundedIndex; index += 1) {
+ const tabId = visibleOrder[index];
+ if (tabId && bucket.has(tabId)) bucketIndex += 1;
+ }
+ return bucketIndex;
+}
+
+export function moveTabToPane(
+ workspace: EditorWorkspaceState,
+ tabId: string,
+ targetPaneId: EditorPaneId,
+ targetIndex: number,
+): EditorWorkspaceState {
+ const sourcePane = findPaneContainingTab(workspace, tabId);
+ const targetPane = workspace.panes.find((pane) => pane.id === targetPaneId);
+ if (!sourcePane || !targetPane) return workspace;
+ const isNewTab = sourcePane.newTabIds.includes(tabId);
+ if (sourcePane.id === targetPane.id) {
+ if (isNewTab) {
+ const without = sourcePane.newTabIds.filter((candidate) => candidate !== tabId);
+ const index = Math.max(0, Math.min(targetIndex, without.length));
+ return updateEditorPane(workspace, targetPaneId, (pane) => ({
+ ...pane,
+ newTabIds: [...without.slice(0, index), tabId, ...without.slice(index)],
+ activeNewTabId: tabId,
+ activeTabId: null,
+ activeTarget: null,
+ }));
+ }
+ const without = sourcePane.openTabs.filter((candidate) => candidate !== tabId);
+ const index = Math.max(0, Math.min(targetIndex, without.length));
+ const openTabs = [...without.slice(0, index), tabId, ...without.slice(index)];
+ return reorderPaneTabs(workspace, targetPaneId, openTabs, tabId);
+ }
+ const wasPinned = sourcePane.pinnedTabIds.includes(tabId);
+ const withoutSource = removeTabFromPane(sourcePane, tabId);
+ const insertedIndex = Math.max(
+ 0,
+ Math.min(targetIndex, isNewTab ? targetPane.newTabIds.length : targetPane.openTabs.length),
+ );
+ const withTarget: EditorPaneState = isNewTab
+ ? {
+ ...targetPane,
+ newTabIds: [
+ ...targetPane.newTabIds.slice(0, insertedIndex),
+ tabId,
+ ...targetPane.newTabIds.slice(insertedIndex),
+ ],
+ activeNewTabId: tabId,
+ activeTabId: null,
+ activeTarget: null,
+ }
+ : {
+ ...targetPane,
+ openTabs: [
+ ...targetPane.openTabs.slice(0, insertedIndex),
+ tabId,
+ ...targetPane.openTabs.slice(insertedIndex),
+ ],
+ pinnedTabIds: wasPinned ? [...targetPane.pinnedTabIds, tabId] : targetPane.pinnedTabIds,
+ activeNewTabId: null,
+ activeTabId: tabId,
+ activeTarget: null,
+ };
+ const panes = workspace.panes.map((pane) =>
+ pane.id === sourcePane.id ? withoutSource : pane.id === targetPane.id ? withTarget : pane,
+ );
+ return focusEditorPane(pruneEmptyEditorPanes({ ...workspace, panes }), targetPane.id);
+}
+
+export function splitTabToPane(
+ workspace: EditorWorkspaceState,
+ tabId: string,
+ targetPaneId: EditorPaneId,
+ side: PaneSide,
+ createPaneId: PaneIdFactory,
+): EditorWorkspaceState {
+ const sourcePane = findPaneContainingTab(workspace, tabId);
+ const targetPane = workspace.panes.find((pane) => pane.id === targetPaneId);
+ if (!sourcePane || !targetPane) return workspace;
+ // There is nothing to split when the only tab is dragged to its own edge.
+ if (
+ sourcePane.id === targetPane.id &&
+ sourcePane.openTabs.length + sourcePane.newTabIds.length === 1
+ )
+ return focusEditorPane(workspace, sourcePane.id);
+ const newPaneId = createPaneId();
+ if (!isPaneId(newPaneId) || workspace.panes.some((pane) => pane.id === newPaneId))
+ return workspace;
+ const wasPinned = sourcePane.pinnedTabIds.includes(tabId);
+ const sourceAfterMove = removeTabFromPane(sourcePane, tabId);
+ const targetAfterSplit = sourcePane.id === targetPane.id ? sourceAfterMove : targetPane;
+ const halfSize = targetAfterSplit.size / 2;
+ const resizedTarget = { ...targetAfterSplit, size: halfSize };
+ const isNewTab = sourcePane.newTabIds.includes(tabId);
+ const newPane: EditorPaneState = {
+ ...createEmptyEditorPane(newPaneId, halfSize),
+ openTabs: isNewTab ? [] : [tabId],
+ pinnedTabIds: wasPinned && !isNewTab ? [tabId] : [],
+ activeTabId: isNewTab ? null : tabId,
+ previewTabId: null,
+ newTabIds: isNewTab ? [tabId] : [],
+ activeNewTabId: isNewTab ? tabId : null,
+ };
+ const panesWithoutSource = workspace.panes.map((pane) => {
+ if (pane.id === sourcePane.id) return sourceAfterMove;
+ return pane;
+ });
+ const targetIndex = panesWithoutSource.findIndex((pane) => pane.id === targetPane.id);
+ if (targetIndex < 0) return workspace;
+ panesWithoutSource[targetIndex] = resizedTarget;
+ const insertIndex = side === 'left' ? targetIndex : targetIndex + 1;
+ const panes = [
+ ...panesWithoutSource.slice(0, insertIndex),
+ newPane,
+ ...panesWithoutSource.slice(insertIndex),
+ ];
+ return focusEditorPane(pruneEmptyEditorPanes({ ...workspace, panes }), newPaneId);
+}
+
+export function closeTabsInPane(
+ workspace: EditorWorkspaceState,
+ paneId: EditorPaneId,
+ tabIds: readonly string[],
+): EditorWorkspaceState {
+ const closing = new Set(tabIds);
+ const pane = workspace.panes.find((candidate) => candidate.id === paneId);
+ if (!pane || closing.size === 0) return workspace;
+ const activeTabId = nearestTabAfterRemoving(pane.openTabs, pane.activeTabId, closing);
+ const next = updateEditorPane(workspace, paneId, (current) => {
+ const withoutOpenTabs = {
+ ...current,
+ openTabs: current.openTabs.filter((tabId) => !closing.has(tabId)),
+ pinnedTabIds: current.pinnedTabIds.filter((tabId) => !closing.has(tabId)),
+ activeTabId,
+ previewTabId:
+ current.previewTabId && closing.has(current.previewTabId) ? null : current.previewTabId,
+ activeTarget: activeTabId === current.activeTabId ? current.activeTarget : null,
+ };
+ return current.newTabIds.reduce(
+ (result, tabId) => (closing.has(tabId) ? removeTabFromPane(result, tabId) : result),
+ withoutOpenTabs,
+ );
+ });
+ return pruneEmptyEditorPanes(next);
+}
+
+export function remapWorkspaceTabs(
+ workspace: EditorWorkspaceState,
+ remapTabId: (tabId: string) => string | null,
+): EditorWorkspaceState {
+ const mappedByOriginal = new Map<string, string | null>();
+ const mappedPinnedTabIds = new Set<string>();
+ for (const pane of workspace.panes) {
+ for (const tabId of pane.openTabs) {
+ const mapped = remapTabId(tabId);
+ const canonical = isCurrentTabId(mapped) ? mapped : null;
+ mappedByOriginal.set(tabId, canonical);
+ if (canonical && !isIndependentViewTabId(canonical) && pane.pinnedTabIds.includes(tabId)) {
+ mappedPinnedTabIds.add(canonical);
+ }
+ }
+ }
+
+ const claimedTabIds = new Set<string>();
+ const panes = workspace.panes.map((pane) => {
+ const mapping = new Map<string, string>();
+ const seenTabIds = new Set<string>();
+ const openTabs: string[] = [];
+ for (const tabId of pane.openTabs) {
+ const mapped = mappedByOriginal.get(tabId);
+ if (!mapped || seenTabIds.has(mapped)) continue;
+ if (!isIndependentViewTabId(mapped) && claimedTabIds.has(mapped)) continue;
+ seenTabIds.add(mapped);
+ if (!isIndependentViewTabId(mapped)) claimedTabIds.add(mapped);
+ mapping.set(tabId, mapped);
+ openTabs.push(mapped);
+ }
+ const localPinnedTabIds = new Set(
+ pane.pinnedTabIds.flatMap((tabId) => mapping.get(tabId) ?? []),
+ );
+ const pinnedTabIds = openTabs.filter((tabId) =>
+ isIndependentViewTabId(tabId) ? localPinnedTabIds.has(tabId) : mappedPinnedTabIds.has(tabId),
+ );
+ const activeTabId = pane.activeTabId ? (mapping.get(pane.activeTabId) ?? null) : null;
+ const previewTabId =
+ pane.previewTabId && mapping.get(pane.previewTabId) === pane.previewTabId
+ ? pane.previewTabId
+ : null;
+ return {
+ ...pane,
+ openTabs,
+ pinnedTabIds,
+ activeTabId,
+ previewTabId: previewTabId && !pinnedTabIds.includes(previewTabId) ? previewTabId : null,
+ activeTarget:
+ activeTabId !== null && activeTabId === pane.activeTabId ? pane.activeTarget : null,
+ };
+ });
+ return pruneEmptyEditorPanes({ ...workspace, panes });
+}
+
+function pruneWorkspaceTabs(
+ workspace: EditorWorkspaceState,
+ keepTabId: (tabId: string) => boolean,
+): EditorWorkspaceState {
+ return remapWorkspaceTabs(workspace, (tabId) => (keepTabId(tabId) ? tabId : null));
+}
+
+function unchangedTransition(workspace: EditorWorkspaceState): EditorWorkspaceTransition {
+ return {
+ workspace,
+ openedTabId: null,
+ replacedPreviewTabId: null,
+ consumedNewTabId: null,
+ };
+}
+
+function finishTransition(
+ workspace: EditorWorkspaceState,
+ metadata: Omit<EditorWorkspaceTransition, 'workspace'> = {
+ openedTabId: null,
+ replacedPreviewTabId: null,
+ consumedNewTabId: null,
+ },
+): EditorWorkspaceTransition {
+ return { workspace: normalizeEditorWorkspace(workspace), ...metadata };
+}
+
+function activateTabInPane(
+ workspace: EditorWorkspaceState,
+ paneId: EditorPaneId,
+ tabId: string,
+): EditorWorkspaceState {
+ const pane = workspace.panes.find((candidate) => candidate.id === paneId);
+ if (!pane) return workspace;
+ if (pane.newTabIds.includes(tabId)) {
+ return focusEditorPane(
+ updateEditorPane(workspace, paneId, (current) => ({
+ ...current,
+ activeTabId: null,
+ activeNewTabId: tabId,
+ activeTarget: null,
+ })),
+ paneId,
+ );
+ }
+ if (!pane.openTabs.includes(tabId)) return workspace;
+ return focusEditorPane(
+ updateEditorPane(workspace, paneId, (current) => ({
+ ...current,
+ activeTabId: tabId,
+ activeNewTabId: null,
+ activeTarget: current.activeTabId === tabId ? current.activeTarget : null,
+ })),
+ paneId,
+ );
+}
+
+export function transitionEditorWorkspace(
+ workspace: EditorWorkspaceState,
+ command: EditorWorkspaceCommand,
+): EditorWorkspaceTransition {
+ switch (command.type) {
+ case 'open-target': {
+ if (!isCurrentTabId(command.tabId)) return unchangedTransition(workspace);
+ const requestedPane = workspace.panes.find((pane) => pane.id === command.paneId);
+ if (!requestedPane) return unchangedTransition(workspace);
+
+ const consumedNewTabId =
+ command.consumeActiveNewTab && requestedPane.activeNewTabId
+ ? requestedPane.activeNewTabId
+ : null;
+ let next =
+ consumedNewTabId === null
+ ? workspace
+ : updateEditorPane(workspace, requestedPane.id, (pane) =>
+ removeTabFromPane(pane, consumedNewTabId),
+ );
+ const requestedOwner = next.panes.find(
+ (pane) => pane.id === command.paneId && pane.openTabs.includes(command.tabId),
+ );
+ const existingOwner = requestedOwner ?? findPaneContainingTab(next, command.tabId);
+ const shouldOpenIndependentCopy =
+ existingOwner !== null &&
+ existingOwner.id !== command.paneId &&
+ command.existingTabBehavior === 'open-in-pane' &&
+ isIndependentViewTabId(command.tabId);
+ if (existingOwner && !shouldOpenIndependentCopy) {
+ if (existingOwner.id !== command.paneId && command.existingTabBehavior === 'open-in-pane') {
+ next = moveTabToPane(next, command.tabId, command.paneId, requestedPane.openTabs.length);
+ next = updateEditorPane(next, command.paneId, (pane) => ({
+ ...pane,
+ activeTarget: command.target,
+ previewTabId:
+ command.disposition === 'permanent' && pane.previewTabId === command.tabId
+ ? null
+ : pane.previewTabId,
+ }));
+ return finishTransition(next, {
+ openedTabId: command.tabId,
+ replacedPreviewTabId: null,
+ consumedNewTabId,
+ });
+ }
+ next = updateEditorPane(next, existingOwner.id, (pane) => ({
+ ...pane,
+ activeTabId: command.tabId,
+ activeNewTabId: null,
+ activeTarget: command.target,
+ previewTabId:
+ command.disposition === 'permanent' && pane.previewTabId === command.tabId
+ ? null
+ : pane.previewTabId,
+ }));
+ next = focusEditorPane(next, existingOwner.id);
+ next = pruneEmptyEditorPanes(next);
+ return finishTransition(next, {
+ openedTabId: command.tabId,
+ replacedPreviewTabId: null,
+ consumedNewTabId,
+ });
+ }
+
+ const paneAfterConsumption = next.panes.find((pane) => pane.id === command.paneId);
+ if (!paneAfterConsumption) return unchangedTransition(workspace);
+ const replacedPreviewTabId =
+ command.disposition === 'preview' ? paneAfterConsumption.previewTabId : null;
+ next = updateEditorPane(next, command.paneId, (pane) => {
+ const replacementIndex = replacedPreviewTabId
+ ? pane.openTabs.indexOf(replacedPreviewTabId)
+ : -1;
+ const withoutPreview = replacedPreviewTabId
+ ? pane.openTabs.filter((tabId) => tabId !== replacedPreviewTabId)
+ : pane.openTabs;
+ const openTabs =
+ replacementIndex < 0
+ ? [...withoutPreview, command.tabId]
+ : [
+ ...withoutPreview.slice(0, replacementIndex),
+ command.tabId,
+ ...withoutPreview.slice(replacementIndex),
+ ];
+ return {
+ ...pane,
+ openTabs,
+ pinnedTabIds: pane.pinnedTabIds.filter((tabId) => tabId !== replacedPreviewTabId),
+ activeTabId: command.tabId,
+ activeNewTabId: null,
+ activeTarget: command.target,
+ previewTabId: command.disposition === 'preview' ? command.tabId : pane.previewTabId,
+ };
+ });
+ next = focusEditorPane(next, command.paneId);
+ return finishTransition(next, {
+ openedTabId: command.tabId,
+ replacedPreviewTabId,
+ consumedNewTabId,
+ });
+ }
+
+ case 'activate-tab':
+ return finishTransition(activateTabInPane(workspace, command.paneId, command.tabId));
+
+ case 'promote-preview':
+ return finishTransition(
+ updateEditorPane(workspace, command.paneId, (pane) => ({
+ ...pane,
+ previewTabId: pane.previewTabId === command.tabId ? null : pane.previewTabId,
+ })),
+ );
+
+ case 'promote-all-previews':
+ return finishTransition({
+ ...workspace,
+ panes: workspace.panes.map((pane) => ({ ...pane, previewTabId: null })),
+ });
+
+ case 'open-new-tab': {
+ if (!isTabId(command.tabId)) return unchangedTransition(workspace);
+ const owner = findPaneContainingTab(workspace, command.tabId);
+ if (owner) return finishTransition(activateTabInPane(workspace, owner.id, command.tabId));
+ if (!workspace.panes.some((pane) => pane.id === command.paneId))
+ return unchangedTransition(workspace);
+ return finishTransition(
+ focusEditorPane(
+ updateEditorPane(workspace, command.paneId, (pane) => ({
+ ...pane,
+ newTabIds: [...pane.newTabIds, command.tabId],
+ activeTabId: null,
+ activeNewTabId: command.tabId,
+ activeTarget: null,
+ })),
+ command.paneId,
+ ),
+ );
+ }
+
+ case 'close-tabs':
+ return finishTransition(closeTabsInPane(workspace, command.paneId, command.tabIds));
+
+ case 'pin-tab':
+ return finishTransition(
+ updateEditorPane(workspace, command.paneId, (pane) =>
+ pane.openTabs.includes(command.tabId)
+ ? {
+ ...pane,
+ pinnedTabIds: pane.pinnedTabIds.includes(command.tabId)
+ ? pane.pinnedTabIds
+ : [...pane.pinnedTabIds, command.tabId],
+ previewTabId: pane.previewTabId === command.tabId ? null : pane.previewTabId,
+ }
+ : pane,
+ ),
+ );
+
+ case 'unpin-tab':
+ return finishTransition(
+ updateEditorPane(workspace, command.paneId, (pane) => ({
+ ...pane,
+ pinnedTabIds: pane.pinnedTabIds.filter((tabId) => tabId !== command.tabId),
+ })),
+ );
+
+ case 'reorder-tabs':
+ return finishTransition(
+ reorderPaneTabs(workspace, command.paneId, command.tabIds, command.draggedTabId),
+ );
+
+ case 'move-tab':
+ return finishTransition(
+ moveTabToPane(workspace, command.tabId, command.paneId, command.index),
+ );
+
+ case 'split-tab':
+ return finishTransition(
+ splitTabToPane(
+ workspace,
+ command.tabId,
+ command.paneId,
+ command.side,
+ () => command.newPaneId,
+ ),
+ );
+
+ case 'resize-panes': {
+ if (
+ command.sizes.length !== workspace.panes.length ||
+ command.sizes.some((size) => !isPositiveFiniteNumber(size))
+ )
+ return unchangedTransition(workspace);
+ return finishTransition({
+ ...workspace,
+ panes: workspace.panes.map((pane, index) => ({
+ ...pane,
+ size: command.sizes[index] ?? pane.size,
+ })),
+ });
+ }
+
+ case 'remap-tabs':
+ return finishTransition(remapWorkspaceTabs(workspace, command.remap));
+
+ case 'prune-tabs':
+ return finishTransition(pruneWorkspaceTabs(workspace, command.keep));
+
+ default: {
+ command satisfies never;
+ return unchangedTransition(workspace);
+ }
+ }
+}
+
+export function recordRecentlyClosedTab(
+ entries: readonly RecentlyClosedEditorTab[],
+ entry: RecentlyClosedEditorTab,
+ limit = 25,
+): RecentlyClosedEditorTab[] {
+ if (!isPaneId(entry.paneId) || !isTabId(entry.tabId) || limit <= 0) return [...entries];
+ return [entry, ...entries.filter((candidate) => candidate.tabId !== entry.tabId)].slice(0, limit);
+}
diff --git a/packages/app/src/editor/editor-tabs.test.ts b/packages/app/src/editor/editor-tabs.test.ts
index 58aaab596..96529f811 100644
Binary files a/packages/app/src/editor/editor-tabs.test.ts and b/packages/app/src/editor/editor-tabs.test.ts differ
diff --git a/packages/app/src/editor/editor-tabs.ts b/packages/app/src/editor/editor-tabs.ts
index 3ac8aa8d2..35fcd0420 100644
--- a/packages/app/src/editor/editor-tabs.ts
+++ b/packages/app/src/editor/editor-tabs.ts
@@ -15,17 +15,19 @@ import {
} from '@/lib/doc-hash';
import { parseProjectSkillContentDocName } from '@/lib/managed-artifact-doc-name';
import { skillDisplayName } from '@/lib/skill-scope';
+import {
+ type EditorWorkspaceState,
+ type PersistedEditorPane,
+ parsePersistedEditorWorkspace,
+ persistEditorWorkspace,
+} from './editor-panes';
/** Narrow a free string to a known skill scope (`project` | `global`). */
function isSkillScope(value: string): value is SkillScope {
return (MANAGED_ARTIFACT_SCOPES as readonly string[]).includes(value);
}
-interface EditorTabSessionState {
- openTabs: string[];
- pinnedTabIds: string[];
- activeDocName: string | null;
- activeTabId: string | null;
+export interface EditorTabSessionState {
/**
* Last-active tab per surface (Files vs Skills), so a reload can restore the
* tab you had open in EACH surface — not just the active one. Each entry is an
@@ -33,6 +35,9 @@ interface EditorTabSessionState {
*/
activeTabByMode: { files: string | null; skills: string | null };
updatedAt: string | null;
+ /** Authoritative persisted split-workspace layout. */
+ panes: PersistedEditorPane[];
+ focusedPaneId: string;
}
/** An open-tab id valid for `surface`, else null (guards stale/hand-edited state). */
@@ -47,14 +52,7 @@ function surfaceActiveTab(
/** A fresh empty session — factory (not a shared const) so callers can't alias it. */
function emptyTabSessionState(): EditorTabSessionState {
- return {
- openTabs: [],
- pinnedTabIds: [],
- activeDocName: null,
- activeTabId: null,
- activeTabByMode: { files: null, skills: null },
- updatedAt: null,
- };
+ return sessionStateFromWorkspace(parsePersistedEditorWorkspace(null), null, {});
}
export interface RenamedFolderMapping {
@@ -90,36 +88,8 @@ const ASSET_TAB_PREFIX = '\u0000asset:';
// unambiguously even though `path` may contain slashes.
const SKILL_FILE_TAB_PREFIX = '\u0000skill-file:';
const SKILL_PREVIEW_TAB_PREFIX = '\u0000skill-preview:';
-const TAB_INSTANCE_SEPARATOR = '\u0000doc-tab:';
-// The Skills destination hub was a singleton full-pane tab. Nothing mints this
-// id anymore; the constant survives only to prune it out of legacy persisted
-// state. Matched EXACTLY rather than by `skills:` prefix — it is the one tab id
-// with no `\u0000` sentinel, so a prefix test also swallowed a real content-root
-// doc named `skills:…` (legal on POSIX), leaving it unopenable and routing its
-// hash to the hub.
-const SKILLS_HUB_TAB_ID = 'skills:hub';
const MARKDOWN_TAB_EXTENSION_PATTERN = /\.(md|mdx)$/i;
-interface OpenTabOptions {
- behavior: 'append' | 'replace-active';
- currentTabId: string | null;
- limit: number;
- pinnedTabIds?: readonly string[];
-}
-
-function splitTabInstance(tabId: string): { baseTabId: string; instanceSuffix: string } {
- const separatorIndex = tabId.lastIndexOf(TAB_INSTANCE_SEPARATOR);
- if (separatorIndex < 0) return { baseTabId: tabId, instanceSuffix: '' };
- return {
- baseTabId: tabId.slice(0, separatorIndex),
- instanceSuffix: tabId.slice(separatorIndex),
- };
-}
-
-function baseTabId(tabId: string): string {
- return splitTabInstance(tabId).baseTabId;
-}
-
function stripMarkdownTabExtension(path: string): string | null {
return MARKDOWN_TAB_EXTENSION_PATTERN.test(path)
? path.replace(MARKDOWN_TAB_EXTENSION_PATTERN, '')
@@ -127,17 +97,13 @@ function stripMarkdownTabExtension(path: string): string | null {
}
function isValidTabId(value: unknown): value is string {
- if (typeof value !== 'string' || value.length === 0) return false;
- const base = baseTabId(value);
+ if (typeof value !== 'string' || value.length === 0 || value.includes('\u0000doc-tab:')) {
+ return false;
+ }
+ const base = value;
if (base.startsWith(FOLDER_TAB_PREFIX)) return base.length > FOLDER_TAB_PREFIX.length;
if (base.startsWith(ASSET_TAB_PREFIX)) return base.length > ASSET_TAB_PREFIX.length;
if (base.startsWith(SKILL_FILE_TAB_PREFIX)) return parseSkillFileTabBody(base) !== null;
- // Skills is an ephemeral new-tab surface (`new-tab:skills:*`), never a standing
- // tab: `openTarget` opens it as a `new-tab:` placeholder that renders the Skills base page
- // without persisting. Reject the `skills:hub` id here so a stale standing tab
- // (from before the ephemeral move, or a rebase regression) is pruned on load
- // instead of restoring Skills as the default tab.
- if (base === SKILLS_HUB_TAB_ID) return false;
if (base.startsWith(SKILL_PREVIEW_TAB_PREFIX)) return parseSkillPreviewTabBody(base) !== null;
return true;
}
@@ -324,9 +290,8 @@ export function tabIdForNavigationTarget(
case 'skill-file':
return skillFileTabId(target);
case 'skills':
- // No tab id: `isValidTabId` rejects the `skills:` prefix, so one could
- // never enter `openTabs`. The Skills destination is a sidebar section,
- // not an editor tab. The arm stays for exhaustiveness.
+ // The Skills destination is an ephemeral new-tab surface, not a standing
+ // editor tab with a persistable id. The arm stays for exhaustiveness.
return null;
case 'skill-preview':
return skillPreviewTabId(target);
@@ -338,7 +303,6 @@ export function parseEditorTabId(tabId: string):
| { kind: 'folder'; folderPath: string }
| { kind: 'asset'; assetPath: string }
| { kind: 'skill-file'; scope: SkillScope; name: string; path: string; host?: string }
- | { kind: 'skills'; target: string }
| {
kind: 'skill-preview';
flavor: SkillPreviewFlavor;
@@ -347,16 +311,13 @@ export function parseEditorTabId(tabId: string):
subtitle: string;
level?: SkillScope;
} {
- const base = baseTabId(tabId);
+ const base = tabId;
if (base.startsWith(FOLDER_TAB_PREFIX)) {
return { kind: 'folder', folderPath: base.slice(FOLDER_TAB_PREFIX.length) };
}
if (base.startsWith(ASSET_TAB_PREFIX)) {
return { kind: 'asset', assetPath: base.slice(ASSET_TAB_PREFIX.length) };
}
- if (base === SKILLS_HUB_TAB_ID) {
- return { kind: 'skills', target: 'skills' };
- }
const skillPreview = parseSkillPreviewTabBody(base);
if (skillPreview) {
return { kind: 'skill-preview', ...skillPreview };
@@ -425,13 +386,12 @@ export function isSkillBundleShapedPath(docName: string): boolean {
/**
* Classify a tab id as belonging to the Skills surface vs the Files surface,
- * from the id alone (no snapshot lookup). Skill tabs: the skills hub, read-only
- * bundle-file / skill-preview viewers, and `doc` tabs whose name is a skill doc.
+ * from the id alone (no snapshot lookup). Skill tabs are read-only bundle-file
+ * or skill-preview viewers and `doc` tabs whose name is a skill doc.
*/
export function isSkillTabId(tabId: string): boolean {
const tab = parseEditorTabId(tabId);
return (
- tab.kind === 'skills' ||
tab.kind === 'skill-file' ||
tab.kind === 'skill-preview' ||
(tab.kind === 'doc' && (isSkillDocName(tab.docName) || isSkillBundleShapedPath(tab.docName)))
@@ -543,89 +503,6 @@ export function applyDragPinMutation(
: removePinnedTab(prevPinned, draggedTabId);
}
-export function addOpenTab(
- tabs: readonly string[],
- tabId: string,
- limit: number,
- pinnedTabIds: readonly string[] = [],
-): string[] {
- const normalized = capOpenTabsPreservingPinned(tabs, limit, pinnedTabIds);
- if (!isValidTabId(tabId) || normalized.includes(tabId)) return normalized;
- const next = [...normalized, tabId];
- return capOpenTabsPreservingPinned(next, limit, pinnedTabIds);
-}
-
-export function replaceOpenTab(
- tabs: readonly string[],
- currentTabId: string | null,
- nextTabId: string,
- limit: number,
- pinnedTabIds: readonly string[] = [],
-): string[] {
- const normalized = capOpenTabsPreservingPinned(tabs, limit, pinnedTabIds);
- if (!isValidTabId(nextTabId)) return normalized;
- if (!currentTabId || currentTabId === nextTabId) {
- return addOpenTab(normalized, nextTabId, limit, pinnedTabIds);
- }
-
- const tabsWithoutNext = normalized.filter((tab) => tab !== nextTabId);
- const currentIndex = tabsWithoutNext.indexOf(currentTabId);
- if (currentIndex < 0) return addOpenTab(tabsWithoutNext, nextTabId, limit, pinnedTabIds);
-
- const next = [...tabsWithoutNext];
- next[currentIndex] = nextTabId;
- return capOpenTabsPreservingPinned(next, limit, pinnedTabIds);
-}
-
-export function openDocTab(
- tabs: readonly string[],
- docName: string,
- options: OpenTabOptions,
-): { tabs: string[]; activeTabId: string } {
- return openTab(tabs, docTabId(docName), options);
-}
-
-export function openTab(
- tabs: readonly string[],
- tabId: string,
- { behavior, currentTabId, limit, pinnedTabIds = [] }: OpenTabOptions,
-): { tabs: string[]; activeTabId: string } {
- const normalized = capOpenTabsPreservingPinned(tabs, limit, pinnedTabIds);
- const canonicalTabId = baseTabId(tabId);
- if (
- currentTabId &&
- normalized.includes(currentTabId) &&
- baseTabId(currentTabId) === canonicalTabId
- ) {
- return {
- tabs: normalized,
- activeTabId: currentTabId,
- };
- }
- // Focus an already-open tab for this target rather than opening a second tab
- // for the same doc/folder/asset. Without this, opening a target that is open
- // in a non-active tab — or while a blank new-tab is active — would mint a
- // duplicate tab for the same file.
- const existingTabId = normalized.find((openTabId) => baseTabId(openTabId) === canonicalTabId);
- if (existingTabId) {
- return {
- tabs: normalized,
- activeTabId: existingTabId,
- };
- }
- if (behavior !== 'replace-active') {
- return {
- tabs: addOpenTab(normalized, canonicalTabId, limit, pinnedTabIds),
- activeTabId: canonicalTabId,
- };
- }
-
- return {
- tabs: replaceOpenTab(normalized, currentTabId, canonicalTabId, limit, pinnedTabIds),
- activeTabId: canonicalTabId,
- };
-}
-
export function removeOpenTab(tabs: readonly string[], tabId: string): string[] {
return tabs.filter((tab) => tab !== tabId);
}
@@ -682,9 +559,6 @@ export function filterOpenTabsForKnownTargets(
// coordinates (not a page) — keep it like skill-file so a page-list sync
// doesn't prune the open preview mid-session.
if (tab.kind === 'skill-preview') return true;
- // Skills is an ephemeral new-tab surface, not a standing tab: drop any
- // persisted `skills:hub` so a page-list sync doesn't resurrect it.
- if (tab.kind === 'skills') return false;
const markdownStem = stripMarkdownTabExtension(tab.docName);
return (
pages.has(tab.docName) ||
@@ -739,33 +613,35 @@ export function remapOpenTabs(
const next: string[] = [];
const seen = new Set<string>();
for (const tab of tabs) {
- const { instanceSuffix } = splitTabInstance(tab);
+ if (!isValidTabId(tab)) continue;
const parsed = parseEditorTabId(tab);
// Skill-file tabs aren't renameable doc/folder/asset paths — pass through.
- const mappedBase =
+ const mapped =
parsed.kind === 'doc'
- ? remapDocTabBase(parsed.docName, baseTabId(tab))
+ ? remapDocTabBase(parsed.docName, tab)
: parsed.kind === 'folder'
? folderTabId(remapPathForFolderRenames(parsed.folderPath, folderMappings))
: parsed.kind === 'asset'
? remapAssetTabBase(parsed.assetPath)
- : baseTabId(tab);
- const mapped = `${mappedBase}${instanceSuffix}`;
+ : tab;
if (seen.has(mapped)) continue;
seen.add(mapped);
next.push(mapped);
if (pinnedTabIds.length === 0 && next.length >= limit) break;
}
if (pinnedTabIds.length === 0) return next;
- const remappedPinnedTabIds = pinnedTabIds.map((tabId) => {
+ const remappedPinnedTabIds = pinnedTabIds.flatMap((tabId) => {
+ if (!isValidTabId(tabId)) return [];
const parsed = parseEditorTabId(tabId);
- return parsed.kind === 'doc'
- ? remapDocTabBase(parsed.docName, tabId)
- : parsed.kind === 'folder'
- ? folderTabId(remapPathForFolderRenames(parsed.folderPath, folderMappings))
- : parsed.kind === 'asset'
- ? remapAssetTabBase(parsed.assetPath)
- : baseTabId(tabId);
+ const mapped =
+ parsed.kind === 'doc'
+ ? remapDocTabBase(parsed.docName, tabId)
+ : parsed.kind === 'folder'
+ ? folderTabId(remapPathForFolderRenames(parsed.folderPath, folderMappings))
+ : parsed.kind === 'asset'
+ ? remapAssetTabBase(parsed.assetPath)
+ : tabId;
+ return [mapped];
});
return capOpenTabsPreservingPinned(next, limit, remappedPinnedTabIds);
}
@@ -845,69 +721,56 @@ export function nextActiveTabAfterCloseMany(
return null;
}
-export function parseEditorTabSessionState(value: unknown, limit: number): EditorTabSessionState {
+export function parseEditorTabSessionState(value: unknown): EditorTabSessionState {
if (typeof value !== 'object' || value === null) {
return emptyTabSessionState();
}
const record = value as Record<string, unknown>;
- const rawOpenTabs = normalizeOpenTabs(record.openTabs, Number.MAX_SAFE_INTEGER);
- const rawPinnedTabIds = normalizePinnedTabIds(record.pinnedTabIds, rawOpenTabs);
- const openTabs =
- rawPinnedTabIds.length === 0
- ? normalizeOpenTabs(record.openTabs, limit)
- : capOpenTabsPreservingPinned(rawOpenTabs, limit, rawPinnedTabIds);
- const pinnedTabIds = normalizePinnedTabIds(record.pinnedTabIds, openTabs);
- const activeTabId =
- typeof record.activeTabId === 'string' && openTabs.includes(record.activeTabId)
- ? record.activeTabId
- : typeof record.activeDocName === 'string' && openTabs.includes(record.activeDocName)
- ? record.activeDocName
- : null;
- const activeTab = activeTabId ? parseEditorTabId(activeTabId) : null;
+ if (!Array.isArray(record.panes)) return emptyTabSessionState();
const rawActiveByMode: Record<string, unknown> =
typeof record.activeTabByMode === 'object' &&
record.activeTabByMode !== null &&
!Array.isArray(record.activeTabByMode)
? (record.activeTabByMode as Record<string, unknown>)
: {};
+ const workspace = parsePersistedEditorWorkspace(record);
+ return sessionStateFromWorkspace(
+ workspace,
+ typeof record.updatedAt === 'string' ? record.updatedAt : null,
+ rawActiveByMode,
+ );
+}
+
+function sessionStateFromWorkspace(
+ workspace: ReturnType<typeof parsePersistedEditorWorkspace>,
+ updatedAt: string | null,
+ rawActiveByMode: Record<string, unknown>,
+): EditorTabSessionState {
+ const openTabs = workspace.panes.flatMap((pane) => pane.openTabs);
return {
- openTabs,
- pinnedTabIds,
- activeDocName: activeTab?.kind === 'doc' ? activeTab.docName : null,
- activeTabId,
activeTabByMode: {
files: surfaceActiveTab(rawActiveByMode.files, 'files', openTabs),
skills: surfaceActiveTab(rawActiveByMode.skills, 'skills', openTabs),
},
- updatedAt: typeof record.updatedAt === 'string' ? record.updatedAt : null,
+ updatedAt,
+ panes: workspace.panes,
+ focusedPaneId: workspace.focusedPaneId,
};
}
export function createEditorTabSessionState(
- openTabs: readonly string[],
- activeTabId: string | null,
- pinnedTabIds: readonly string[] = [],
+ workspace: EditorWorkspaceState,
activeTabByMode: { files: string | null; skills: string | null } = {
files: null,
skills: null,
},
now: () => Date = () => new Date(),
): EditorTabSessionState {
- const normalized = normalizeOpenTabs(openTabs, Number.MAX_SAFE_INTEGER);
- const normalizedActiveTabId =
- activeTabId && normalized.includes(activeTabId) ? activeTabId : null;
- const activeTab = normalizedActiveTabId ? parseEditorTabId(normalizedActiveTabId) : null;
- return {
- openTabs: normalized,
- pinnedTabIds: normalizePinnedTabIds(pinnedTabIds, normalized),
- activeDocName: activeTab?.kind === 'doc' ? activeTab.docName : null,
- activeTabId: normalizedActiveTabId,
- activeTabByMode: {
- files: surfaceActiveTab(activeTabByMode.files, 'files', normalized),
- skills: surfaceActiveTab(activeTabByMode.skills, 'skills', normalized),
- },
- updatedAt: now().toISOString(),
- };
+ return sessionStateFromWorkspace(
+ persistEditorWorkspace(workspace),
+ now().toISOString(),
+ activeTabByMode,
+ );
}
export function localTabSessionStorageKey(projectKey: string): string {
@@ -917,7 +780,6 @@ export function localTabSessionStorageKey(projectKey: string): string {
export function readLocalTabSessionState(
storage: Pick<Storage, 'getItem'> | null,
key: string,
- limit: number,
): EditorTabSessionState {
if (!storage) {
return emptyTabSessionState();
@@ -927,7 +789,7 @@ export function readLocalTabSessionState(
if (!raw) {
return emptyTabSessionState();
}
- return parseEditorTabSessionState(JSON.parse(raw), limit);
+ return parseEditorTabSessionState(JSON.parse(raw));
} catch (err) {
console.warn('[editor-tabs] failed to read local tab session:', err);
return emptyTabSessionState();
@@ -941,7 +803,7 @@ export function writeLocalTabSessionState(
): void {
if (!storage) return;
try {
- storage.setItem(key, JSON.stringify(state));
+ storage.setItem(key, JSON.stringify(parseEditorTabSessionState(state)));
} catch (err) {
console.warn('[editor-tabs] failed to write local tab session:', err);
// Private browsing and quota failures should not affect editing.
diff --git a/packages/app/src/editor/extensions/markdown-lint-decorations.test.ts b/packages/app/src/editor/extensions/markdown-lint-decorations.test.ts
index 99ba2561e..1c9c053cb 100644
--- a/packages/app/src/editor/extensions/markdown-lint-decorations.test.ts
+++ b/packages/app/src/editor/extensions/markdown-lint-decorations.test.ts
@@ -13,6 +13,7 @@
import {
sharedExtensions as coreExtensions,
+ DEFAULT_LINTER_CONFIG,
type LintDiagnostic,
MarkdownManager,
} from '@inkeep/open-knowledge-core';
@@ -310,7 +311,7 @@ describe('Problems-row navigation — scroll suppression', () => {
}
function clickProblemsRow(line: number, source?: string): void {
- const detail: LintNavDetail = { line, column: 1, source };
+ const detail: LintNavDetail = { docName: DOC, line, column: 1, source };
window.dispatchEvent(new CustomEvent<LintNavDetail>(LINT_NAV_EVENT, { detail }));
}
@@ -318,7 +319,7 @@ describe('Problems-row navigation — scroll suppression', () => {
__resetScrollRestoreCoordination();
originalFetch = globalThis.fetch;
globalThis.fetch = vi.fn(async () =>
- Response.json({ effective: {} }),
+ Response.json({ effective: DEFAULT_LINTER_CONFIG }),
) as unknown as typeof fetch;
scrollIntoView = vi.fn();
originalScrollIntoView = Object.getOwnPropertyDescriptor(
diff --git a/packages/app/src/editor/extensions/markdown-lint-decorations.ts b/packages/app/src/editor/extensions/markdown-lint-decorations.ts
index 9483b3f70..c2ad28243 100644
--- a/packages/app/src/editor/extensions/markdown-lint-decorations.ts
+++ b/packages/app/src/editor/extensions/markdown-lint-decorations.ts
@@ -580,7 +580,7 @@ export const MarkdownLintDecorations = Extension.create<MarkdownLintDecorationsO
// path banks its intent instead (replayed in recompute on mount).
function onLintNav(event: Event) {
const detail = (event as CustomEvent<LintNavDetail>).detail;
- if (!detail || destroyed) return;
+ if (!detail || detail.docName !== docName || destroyed) return;
// Consumed here — a later flip to source mode must not replay it.
if (scrollToLintBlock(detail)) clearPendingSourceNavigation(docName);
}
diff --git a/packages/app/src/editor/provider-pool.test.ts b/packages/app/src/editor/provider-pool.test.ts
index 4693a9668..c596f8cdc 100644
--- a/packages/app/src/editor/provider-pool.test.ts
+++ b/packages/app/src/editor/provider-pool.test.ts
@@ -255,6 +255,53 @@ describe('ProviderPool LRU eviction', () => {
expect(pool.has('doc3')).toBe(true);
});
+ test('never evicts a visible non-focused document', () => {
+ pool = new ProviderPool(3, DUMMY_WS);
+ pool.open('focused');
+ pool.open('visible');
+ pool.open('hidden');
+ pool.setActive('focused');
+ pool.setVisibleDocNames(new Set(['focused', 'visible']));
+
+ pool.open('new-doc');
+
+ expect(pool.has('focused')).toBe(true);
+ expect(pool.has('visible')).toBe(true);
+ expect(pool.has('hidden')).toBe(false);
+ expect(pool.has('new-doc')).toBe(true);
+ });
+
+ test('grows beyond the normal capacity for visible documents and trims after pane removal', () => {
+ pool = new ProviderPool(2, DUMMY_WS);
+ pool.setVisibleDocNames(new Set(['a', 'b', 'c', 'd']));
+ pool.open('a');
+ pool.open('b');
+ pool.open('c');
+ pool.open('d');
+ pool.setActive('a');
+
+ expect(pool.entries.size).toBe(4);
+
+ pool.setVisibleDocNames(new Set(['a']));
+
+ expect(pool.entries.size).toBe(2);
+ expect(pool.has('a')).toBe(true);
+ });
+
+ test('ignores system documents in the visible protection set', () => {
+ pool = new ProviderPool(2, DUMMY_WS);
+ pool.open('a');
+ pool.open('b');
+ pool.setActive('a');
+ pool.setVisibleDocNames(new Set(['a', '__system__']));
+
+ pool.open('c');
+
+ expect(pool.has('a')).toBe(true);
+ expect(pool.has('b')).toBe(false);
+ expect(pool.has('c')).toBe(true);
+ });
+
test('LRU order updates when document is re-opened', () => {
pool = new ProviderPool(3, DUMMY_WS);
pool.open('doc1');
diff --git a/packages/app/src/editor/provider-pool.ts b/packages/app/src/editor/provider-pool.ts
index 9b496148c..f58b9d28a 100644
--- a/packages/app/src/editor/provider-pool.ts
+++ b/packages/app/src/editor/provider-pool.ts
@@ -471,6 +471,16 @@ export class ProviderPool {
}
private lruOrder: string[] = [];
private activeDocName: string | null = null;
+ /**
+ * Documents rendered in visible editor panes. These entries must survive LRU
+ * churn even when they are not the globally focused document: every visible
+ * pane owns a live editor bound to its provider.
+ *
+ * The set deliberately stores names rather than PoolEntry references. A
+ * recycle replaces an entry in place while the pane continues to own the
+ * document, and the next `open()` must retain that protection.
+ */
+ private visibleDocNames = new Set<string>();
private readonly maxSize: number;
private readonly wsUrl: string;
private readonly recycleDebounceMs: number;
@@ -1652,11 +1662,62 @@ export class ProviderPool {
this.lruOrder.push(docName);
}
+ /**
+ * Replace the workspace's visible document set.
+ *
+ * Visible panes are a resource-policy exemption, not another active-document
+ * concept: `activeDocName` still identifies the one focused pane for global
+ * shortcuts and awareness. System documents are never admitted to either
+ * layer. Shrinking the set eagerly returns the provider pool to its ordinary
+ * budget by evicting only entries that are no longer protected.
+ */
+ setVisibleDocNames(names: ReadonlySet<string>): void {
+ const next = new Set<string>();
+ for (const docName of names) {
+ if (!isSystemDoc(docName)) next.add(docName);
+ }
+
+ if (
+ next.size === this.visibleDocNames.size &&
+ [...next].every((docName) => this.visibleDocNames.has(docName))
+ ) {
+ return;
+ }
+
+ this.visibleDocNames = next;
+ this.trimToCapacity();
+ mark('ok/pool/visible-set', {
+ visibleCount: this.visibleDocNames.size,
+ poolSize: this.entries.size,
+ });
+ }
+
+ private isProtected(docName: string): boolean {
+ return docName === this.activeDocName || this.visibleDocNames.has(docName);
+ }
+
+ private effectiveCapacity(): number {
+ // The focused document is normally in visibleDocNames. Counting it here as
+ // well keeps the active-document protection intact during transient
+ // workspace updates where a focused target changes before its pane list.
+ const protectedCount =
+ this.visibleDocNames.size +
+ (this.activeDocName !== null && !this.visibleDocNames.has(this.activeDocName) ? 1 : 0);
+ return Math.max(this.maxSize, protectedCount);
+ }
+
+ private trimToCapacity(): void {
+ while (this.entries.size > this.effectiveCapacity() && this.evictLru()) {
+ // `evictLru` synchronously removes one unprotected entry. Continue until
+ // the normal budget is restored or every remaining entry is protected.
+ }
+ }
+
/**
* Open (or reuse) a document. Returns the pool entry, or `null` if the
* docName is reserved (the `__system__` pseudo-doc carries CC1 signals and
* is never user-editable). If the pool is at
- * capacity, evicts the LRU entry (never the active doc).
+ * capacity, evicts the LRU entry (never an active or visible-pane doc).
*/
open(docName: string): PoolEntry | null {
if (isSystemDoc(docName)) return null;
@@ -1687,8 +1748,11 @@ export class ProviderPool {
// start/end pair captured around the body is faithful.
const openStartMs = Date.now();
- // Evict if at capacity
- if (this.entries.size >= this.maxSize) {
+ // Keep MAX_POOL as the normal warm-provider budget, while allowing every
+ // visible editor pane to retain its provider. If all current entries are
+ // protected, admission may temporarily exceed the baseline; the next
+ // visible-set shrink trims unprotected entries back to budget.
+ if (this.entries.size >= this.effectiveCapacity()) {
this.evictLru();
}
@@ -3456,6 +3520,7 @@ export class ProviderPool {
this._entries.clear();
this.lruOrder = [];
this.activeDocName = null;
+ this.visibleDocNames.clear();
this.onChange = null;
// Reset every mutable field so a disposed pool can't bleed stale state
// into a future test or reused harness instance. Production HMR drops
@@ -3509,15 +3574,18 @@ export class ProviderPool {
this.flushOnHideEnabled = true;
}
- private evictLru(): void {
- // Find the LRU entry that is NOT the active doc
+ private evictLru(): boolean {
+ // Visible panes and the focused document are both protected. Their
+ // providers back live editor trees, so evicting either would orphan a
+ // mounted Y.Doc under split-view pressure.
for (const docName of this.lruOrder) {
- if (docName !== this.activeDocName) {
+ if (!this.isProtected(docName)) {
mark('ok/pool/evict-lru', { docName });
this.close(docName);
- return;
+ return true;
}
}
+ return false;
}
private destroyEntry(entry: PoolEntry): void {
diff --git a/packages/app/src/editor/sidebar-drop.test.ts b/packages/app/src/editor/sidebar-drop.test.ts
index ee663172e..9d60724be 100644
--- a/packages/app/src/editor/sidebar-drop.test.ts
+++ b/packages/app/src/editor/sidebar-drop.test.ts
@@ -1,74 +1,9 @@
import { describe, expect, test, vi } from 'vitest';
import { isManagedHashHistoryState } from '@/lib/doc-hash';
-import {
- OK_SIDEBAR_DRAG_MIME,
- type SidebarDragPayload,
- serializeSidebarDragPayload,
-} from '@/lib/sidebar-drag';
-import {
- createSidebarAwareHandleDrop,
- openSidebarDropPayload,
- type SidebarOpenTarget,
-} from './sidebar-drop';
-
-type EditorHandleDrop = ReturnType<typeof createSidebarAwareHandleDrop>;
-type DropView = Parameters<EditorHandleDrop>[0];
-type DropEvent = Parameters<EditorHandleDrop>[1];
-
-function dataTransfer(data: Record<string, string>): Pick<DataTransfer, 'types' | 'getData'> {
- return {
- types: Object.keys(data),
- getData: (type: string) => data[type] ?? '',
- };
-}
-
-function dropEvent(data: Record<string, string>): {
- event: DropEvent;
- preventDefault: ReturnType<typeof vi.fn>;
-} {
- const preventDefault = vi.fn(() => {});
- return {
- event: {
- dataTransfer: dataTransfer(data),
- preventDefault,
- } as unknown as DropEvent,
- preventDefault,
- };
-}
-
-describe('createSidebarAwareHandleDrop', () => {
- test('claims sidebar drags before generic clipboard drop handling', () => {
- const payload: SidebarDragPayload = { v: 1, kind: 'doc', docName: 'notes/Intro', size: null };
- const clipboardDrop = vi.fn((_view: DropView, _event: DragEvent) => false);
- const onSidebarDrop = vi.fn((_payload: SidebarDragPayload) => {});
- const handleDrop = createSidebarAwareHandleDrop(clipboardDrop, onSidebarDrop);
- const { event, preventDefault } = dropEvent({
- [OK_SIDEBAR_DRAG_MIME]: serializeSidebarDragPayload(payload),
- 'text/plain': 'notes/Intro.md',
- });
-
- expect(handleDrop({} as DropView, event)).toBe(true);
- expect(preventDefault).toHaveBeenCalledTimes(1);
- expect(onSidebarDrop).toHaveBeenCalledWith(payload);
- expect(clipboardDrop).not.toHaveBeenCalled();
- });
-
- test('falls through to clipboard drop for non-sidebar drags', () => {
- const view = {} as DropView;
- const clipboardDrop = vi.fn((_view: DropView, _event: DragEvent) => false);
- const onSidebarDrop = vi.fn((_payload: SidebarDragPayload) => {});
- const handleDrop = createSidebarAwareHandleDrop(clipboardDrop, onSidebarDrop);
- const { event, preventDefault } = dropEvent({ 'text/plain': 'notes/Intro.md' });
-
- expect(handleDrop(view, event)).toBe(false);
- expect(preventDefault).not.toHaveBeenCalled();
- expect(onSidebarDrop).not.toHaveBeenCalled();
- expect(clipboardDrop).toHaveBeenCalledWith(view, event);
- });
-});
+import { openSidebarDropPayload, type SidebarOpenTarget } from './sidebar-drop';
describe('openSidebarDropPayload', () => {
- test('opens sidebar payloads as appended tabs and pushes the hash directly', () => {
+ test('opens sidebar payloads permanently, preserves blank intent, and pushes the hash directly', () => {
const restoreWindow = installFakeWindow({
hash: '#/old',
pathname: '/app',
@@ -78,14 +13,18 @@ describe('openSidebarDropPayload', () => {
(_target: Parameters<SidebarOpenTarget>[0], _options: Parameters<SidebarOpenTarget>[1]) => {},
);
try {
- openSidebarDropPayload({ v: 1, kind: 'doc', docName: 'notes/Intro', size: null }, openTarget);
+ openSidebarDropPayload(
+ { v: 1, kind: 'doc', docName: 'notes/Intro', size: null },
+ openTarget,
+ true,
+ );
} finally {
restoreWindow();
}
expect(openTarget).toHaveBeenCalledWith(
{ kind: 'doc', target: 'notes/Intro', docName: 'notes/Intro' },
- { tabBehavior: 'append' },
+ { disposition: 'permanent', consumeActiveNewTab: true },
);
expect(fakePushState).toHaveBeenCalledWith(
expect.anything(),
diff --git a/packages/app/src/editor/sidebar-drop.ts b/packages/app/src/editor/sidebar-drop.ts
index 2ceffb9fc..cd07bdb05 100644
--- a/packages/app/src/editor/sidebar-drop.ts
+++ b/packages/app/src/editor/sidebar-drop.ts
@@ -1,39 +1,18 @@
-import type { EditorOptions } from '@tiptap/core';
import { pushHashWithoutNavigation } from '@/lib/doc-hash';
-import {
- navigationForSidebarDragPayload,
- parseSidebarDragPayload,
- type SidebarDragPayload,
-} from '@/lib/sidebar-drag';
+import { navigationForSidebarDragPayload, type SidebarDragPayload } from '@/lib/sidebar-drag';
+import type { TabOpenDisposition } from './editor-panes';
-type EditorHandleDrop = NonNullable<NonNullable<EditorOptions['editorProps']>['handleDrop']>;
-type EditorDropView = Parameters<EditorHandleDrop>[0];
export type SidebarOpenTarget = (
target: ReturnType<typeof navigationForSidebarDragPayload>['target'],
- options: { tabBehavior: 'append' },
+ options: { disposition: TabOpenDisposition; consumeActiveNewTab: boolean },
) => void;
-export function createSidebarAwareHandleDrop(
- clipboardDrop: (view: EditorDropView, event: DragEvent) => boolean,
- onSidebarDrop?: (payload: SidebarDragPayload) => void,
-): EditorHandleDrop {
- return (view, event) => {
- const dragEvent = event as DragEvent;
- const sidebarPayload = parseSidebarDragPayload(dragEvent.dataTransfer);
- if (sidebarPayload) {
- dragEvent.preventDefault();
- onSidebarDrop?.(sidebarPayload);
- return true;
- }
- return clipboardDrop(view, dragEvent);
- };
-}
-
export function openSidebarDropPayload(
payload: SidebarDragPayload,
openTarget: SidebarOpenTarget,
+ consumeActiveNewTab: boolean,
): void {
const navigation = navigationForSidebarDragPayload(payload);
- openTarget(navigation.target, { tabBehavior: 'append' });
+ openTarget(navigation.target, { disposition: 'permanent', consumeActiveNewTab });
pushHashWithoutNavigation(navigation.hash);
}
diff --git a/packages/app/src/globals.css b/packages/app/src/globals.css
index bd1d29638..964e64161 100644
--- a/packages/app/src/globals.css
+++ b/packages/app/src/globals.css
@@ -2347,6 +2347,11 @@
cursor: grabbing;
}
+body[data-editor-tab-dragging],
+body[data-editor-tab-dragging] * {
+ cursor: grabbing;
+}
+
/* Keyboard focus indicator — mirrors the editor-wide pattern used by
.tag, [data-link], a.ok-file-attachment, and task-list checkboxes.
The grip carries tabindex="-1" today, so the indicator only fires on
diff --git a/packages/app/src/lib/create-file-events.test.ts b/packages/app/src/lib/create-file-events.test.ts
index ddcdfaf77..95cb98f24 100644
--- a/packages/app/src/lib/create-file-events.test.ts
+++ b/packages/app/src/lib/create-file-events.test.ts
@@ -109,6 +109,17 @@ describe('create-file event bridge', () => {
expect(received[0]?.initialDir).toBe('meetings');
});
+ test('folder creation requests preserve their item kind', () => {
+ installFakeWindow();
+ const received: Array<{ initialDir?: string; kind?: 'file' | 'folder' }> = [];
+ const off = subscribeToCreateTopLevelFile((request) => received.push(request));
+
+ emitCreateTopLevelFile({ initialDir: 'reports', kind: 'folder' });
+ off();
+
+ expect(received).toEqual([{ initialDir: 'reports', kind: 'folder' }]);
+ });
+
test('template payload is forwarded verbatim (folder + name)', () => {
installFakeWindow();
const received: Array<{ template?: { folder: string; name: string } }> = [];
diff --git a/packages/app/src/lib/create-file-events.ts b/packages/app/src/lib/create-file-events.ts
index d2804685c..d184eaf9b 100644
--- a/packages/app/src/lib/create-file-events.ts
+++ b/packages/app/src/lib/create-file-events.ts
@@ -25,6 +25,8 @@ const CREATE_TOP_LEVEL_FILE_EVENT = 'open-knowledge:create-top-level-file';
export interface CreateFileRequest {
/** Folder to create the file in. Empty string = project root. */
initialDir?: string;
+ /** Item kind for inline creation. Defaults to `file` for legacy callers. */
+ kind?: 'file' | 'folder';
/**
* When set, scaffold from a template. `folder` is the template's
* `source_folder` (the folder owning `.ok/templates/<name>.md`);
diff --git a/packages/app/src/lib/file-tree-menu-action-events.test.ts b/packages/app/src/lib/file-tree-menu-action-events.test.ts
index 30483face..48f6892fc 100644
--- a/packages/app/src/lib/file-tree-menu-action-events.test.ts
+++ b/packages/app/src/lib/file-tree-menu-action-events.test.ts
@@ -12,9 +12,11 @@ import type { ResolvedNavigationTarget } from '@/components/navigation-targets';
import {
emitFileTreeMenuActionDelete,
emitFileTreeMenuActionDuplicate,
+ emitFileTreeMenuActionImportTemplate,
emitFileTreeMenuActionRename,
subscribeToFileTreeMenuActionDelete,
subscribeToFileTreeMenuActionDuplicate,
+ subscribeToFileTreeMenuActionImportTemplate,
subscribeToFileTreeMenuActionRename,
} from './file-tree-menu-action-events';
@@ -118,6 +120,17 @@ describe('file-tree-menu-action-events bus', () => {
unsubscribe();
});
+ test('rename delivers the dialog name when supplied', () => {
+ installFakeWindow();
+ const received: Array<[ResolvedNavigationTarget, string | undefined]> = [];
+ const unsubscribe = subscribeToFileTreeMenuActionRename((target, nextName) =>
+ received.push([target, nextName]),
+ );
+ emitFileTreeMenuActionRename(DOC_TARGET, 'renamed.md');
+ expect(received).toEqual([[DOC_TARGET, 'renamed.md']]);
+ unsubscribe();
+ });
+
test('rename + delete buses are independent channels', () => {
installFakeWindow();
const renameReceived: ResolvedNavigationTarget[] = [];
@@ -171,4 +184,15 @@ describe('file-tree-menu-action-events bus', () => {
unsubRename();
unsubDelete();
});
+
+ test('import-template delivers the target and conversion choice', () => {
+ installFakeWindow();
+ const received: Array<[ResolvedNavigationTarget, boolean]> = [];
+ const unsubscribe = subscribeToFileTreeMenuActionImportTemplate((target, deleteSource) =>
+ received.push([target, deleteSource]),
+ );
+ emitFileTreeMenuActionImportTemplate(DOC_TARGET, true);
+ expect(received).toEqual([[DOC_TARGET, true]]);
+ unsubscribe();
+ });
});
diff --git a/packages/app/src/lib/file-tree-menu-action-events.ts b/packages/app/src/lib/file-tree-menu-action-events.ts
index ebd037e14..fdb356f1a 100644
--- a/packages/app/src/lib/file-tree-menu-action-events.ts
+++ b/packages/app/src/lib/file-tree-menu-action-events.ts
@@ -29,67 +29,89 @@ import type { ResolvedNavigationTarget } from '@/components/navigation-targets';
const FILE_TREE_MENU_ACTION_DELETE_EVENT = 'open-knowledge:file-tree-menu-action-delete';
const FILE_TREE_MENU_ACTION_RENAME_EVENT = 'open-knowledge:file-tree-menu-action-rename';
const FILE_TREE_MENU_ACTION_DUPLICATE_EVENT = 'open-knowledge:file-tree-menu-action-duplicate';
+const FILE_TREE_MENU_ACTION_IMPORT_TEMPLATE_EVENT =
+ 'open-knowledge:file-tree-menu-action-import-template';
interface MenuActionEventDetail {
readonly target: ResolvedNavigationTarget;
}
-export function emitFileTreeMenuActionDelete(target: ResolvedNavigationTarget): void {
- window.dispatchEvent(
- new CustomEvent<MenuActionEventDetail>(FILE_TREE_MENU_ACTION_DELETE_EVENT, {
- detail: { target },
- }),
- );
+interface RenameMenuActionEventDetail extends MenuActionEventDetail {
+ readonly nextName?: string;
}
-export function subscribeToFileTreeMenuActionDelete(
- onRequest: (target: ResolvedNavigationTarget) => void,
+interface ImportTemplateMenuActionEventDetail extends MenuActionEventDetail {
+ readonly deleteSource: boolean;
+}
+
+function emitMenuAction<T>(type: string, detail: T): void {
+ window.dispatchEvent(new CustomEvent<T>(type, { detail }));
+}
+
+function subscribeToMenuAction<T extends MenuActionEventDetail>(
+ type: string,
+ onRequest: (detail: T) => void,
): () => void {
const listener = (event: Event) => {
- const detail = (event as CustomEvent<MenuActionEventDetail>).detail;
- if (!detail?.target) return;
- onRequest(detail.target);
+ const detail = (event as CustomEvent<T>).detail;
+ if (detail?.target) onRequest(detail);
};
- window.addEventListener(FILE_TREE_MENU_ACTION_DELETE_EVENT, listener);
- return () => window.removeEventListener(FILE_TREE_MENU_ACTION_DELETE_EVENT, listener);
+ window.addEventListener(type, listener);
+ return () => window.removeEventListener(type, listener);
}
-export function emitFileTreeMenuActionRename(target: ResolvedNavigationTarget): void {
- window.dispatchEvent(
- new CustomEvent<MenuActionEventDetail>(FILE_TREE_MENU_ACTION_RENAME_EVENT, {
- detail: { target },
- }),
+export function emitFileTreeMenuActionDelete(target: ResolvedNavigationTarget): void {
+ emitMenuAction(FILE_TREE_MENU_ACTION_DELETE_EVENT, { target });
+}
+
+export function subscribeToFileTreeMenuActionDelete(
+ onRequest: (target: ResolvedNavigationTarget) => void,
+): () => void {
+ return subscribeToMenuAction(FILE_TREE_MENU_ACTION_DELETE_EVENT, ({ target }) =>
+ onRequest(target),
);
}
+export function emitFileTreeMenuActionRename(
+ target: ResolvedNavigationTarget,
+ nextName?: string,
+): void {
+ emitMenuAction(FILE_TREE_MENU_ACTION_RENAME_EVENT, { target, nextName });
+}
+
export function subscribeToFileTreeMenuActionRename(
- onRequest: (target: ResolvedNavigationTarget) => void,
+ onRequest: (target: ResolvedNavigationTarget, nextName?: string) => void,
): () => void {
- const listener = (event: Event) => {
- const detail = (event as CustomEvent<MenuActionEventDetail>).detail;
- if (!detail?.target) return;
- onRequest(detail.target);
- };
- window.addEventListener(FILE_TREE_MENU_ACTION_RENAME_EVENT, listener);
- return () => window.removeEventListener(FILE_TREE_MENU_ACTION_RENAME_EVENT, listener);
+ return subscribeToMenuAction<RenameMenuActionEventDetail>(
+ FILE_TREE_MENU_ACTION_RENAME_EVENT,
+ ({ target, nextName }) => onRequest(target, nextName),
+ );
}
export function emitFileTreeMenuActionDuplicate(target: ResolvedNavigationTarget): void {
- window.dispatchEvent(
- new CustomEvent<MenuActionEventDetail>(FILE_TREE_MENU_ACTION_DUPLICATE_EVENT, {
- detail: { target },
- }),
- );
+ emitMenuAction(FILE_TREE_MENU_ACTION_DUPLICATE_EVENT, { target });
}
export function subscribeToFileTreeMenuActionDuplicate(
onRequest: (target: ResolvedNavigationTarget) => void,
): () => void {
- const listener = (event: Event) => {
- const detail = (event as CustomEvent<MenuActionEventDetail>).detail;
- if (!detail?.target) return;
- onRequest(detail.target);
- };
- window.addEventListener(FILE_TREE_MENU_ACTION_DUPLICATE_EVENT, listener);
- return () => window.removeEventListener(FILE_TREE_MENU_ACTION_DUPLICATE_EVENT, listener);
+ return subscribeToMenuAction(FILE_TREE_MENU_ACTION_DUPLICATE_EVENT, ({ target }) =>
+ onRequest(target),
+ );
+}
+
+export function emitFileTreeMenuActionImportTemplate(
+ target: ResolvedNavigationTarget,
+ deleteSource: boolean,
+): void {
+ emitMenuAction(FILE_TREE_MENU_ACTION_IMPORT_TEMPLATE_EVENT, { target, deleteSource });
+}
+
+export function subscribeToFileTreeMenuActionImportTemplate(
+ onRequest: (target: ResolvedNavigationTarget, deleteSource: boolean) => void,
+): () => void {
+ return subscribeToMenuAction<ImportTemplateMenuActionEventDetail>(
+ FILE_TREE_MENU_ACTION_IMPORT_TEMPLATE_EVENT,
+ ({ target, deleteSource }) => onRequest(target, deleteSource),
+ );
}
diff --git a/packages/app/src/lib/install-deep-link-listener.test.ts b/packages/app/src/lib/install-deep-link-listener.test.ts
index fbdf21800..abb728363 100644
--- a/packages/app/src/lib/install-deep-link-listener.test.ts
+++ b/packages/app/src/lib/install-deep-link-listener.test.ts
@@ -47,11 +47,18 @@ function makeBridge(overrides: Partial<OkDesktopBridge> = {}): OkDesktopBridge &
removeRecent: vi.fn(() => Promise.resolve()),
getSessionState: vi.fn(() =>
Promise.resolve({
- openTabs: [],
- pinnedTabIds: [],
- activeDocName: null,
- activeTabId: null,
+ activeTabByMode: { files: null, skills: null },
updatedAt: null,
+ panes: [
+ {
+ id: 'pane-main',
+ openTabs: [],
+ pinnedTabIds: [],
+ activeTabId: null,
+ size: 100,
+ },
+ ],
+ focusedPaneId: 'pane-main',
}),
),
setSessionState: vi.fn(() => Promise.resolve()),
diff --git a/packages/app/src/lib/managed-artifact-doc-name.ts b/packages/app/src/lib/managed-artifact-doc-name.ts
index 786dff1a3..f931b60f2 100644
--- a/packages/app/src/lib/managed-artifact-doc-name.ts
+++ b/packages/app/src/lib/managed-artifact-doc-name.ts
@@ -16,17 +16,13 @@
import {
MANAGED_ARTIFACT_PREFIX_TEMPLATE,
parseProjectSkillBundleDoc,
- projectSkillContentDocName,
type SkillsListEntry,
skillFileLiveDocName,
skillLiveDocName,
stripMdExt,
} from '@inkeep/open-knowledge-core';
-// `projectSkillContentDocName` + `skillLiveDocName` are the SINGLE source of
-// truth in core, shared with the server. Re-exported here so existing app call
-// sites keep importing them from this module unchanged.
-export { projectSkillContentDocName, skillLiveDocName };
+export { skillLiveDocName };
// NOTE: there is intentionally no `skillDocName(scope, name)` builder. Project
// skills are CONTENT docs (`.ok/skills/<name>/SKILL`), not `__skill__/project/…`
diff --git a/packages/app/src/lib/sidebar-drag.test.ts b/packages/app/src/lib/sidebar-drag.test.ts
index 98df6e965..f83e8a873 100644
--- a/packages/app/src/lib/sidebar-drag.test.ts
+++ b/packages/app/src/lib/sidebar-drag.test.ts
@@ -1,6 +1,7 @@
import { DOCUMENT_OPEN_BYTE_LIMIT } from '@inkeep/open-knowledge-core';
import { describe, expect, test } from 'vitest';
import {
+ hasSidebarDragType,
navigationForSidebarDragPayload,
OK_SIDEBAR_DRAG_MIME,
parseSidebarDragPayload,
@@ -16,6 +17,16 @@ function dataTransfer(data: Record<string, string>) {
}
describe('sidebar drag payload', () => {
+ test('recognizes sidebar drags from the MIME type before payload bytes are readable', () => {
+ expect(
+ hasSidebarDragType({
+ types: [OK_SIDEBAR_DRAG_MIME],
+ }),
+ ).toBe(true);
+ expect(hasSidebarDragType({ types: ['text/plain'] })).toBe(false);
+ expect(hasSidebarDragType(null)).toBe(false);
+ });
+
test('round-trips doc, folder, and asset payloads', () => {
const payloads: SidebarDragPayload[] = [
{ v: 1, kind: 'doc', docName: 'notes/Intro', size: null },
diff --git a/packages/app/src/lib/sidebar-drag.ts b/packages/app/src/lib/sidebar-drag.ts
index dbb37d4d6..67904da8e 100644
--- a/packages/app/src/lib/sidebar-drag.ts
+++ b/packages/app/src/lib/sidebar-drag.ts
@@ -26,6 +26,12 @@ export function serializeSidebarDragPayload(payload: SidebarDragPayload): string
return JSON.stringify(payload);
}
+export function hasSidebarDragType(
+ dataTransfer: Pick<DataTransfer, 'types'> | null | undefined,
+): boolean {
+ return dataTransfer ? Array.from(dataTransfer.types).includes(OK_SIDEBAR_DRAG_MIME) : false;
+}
+
export function navigationForSidebarDragPayload(payload: SidebarDragPayload): {
target: ResolvedNavigationTarget;
hash: string;
@@ -60,9 +66,7 @@ export function navigationForSidebarDragPayload(payload: SidebarDragPayload): {
export function parseSidebarDragPayload(
dataTransfer: Pick<DataTransfer, 'types' | 'getData'> | null | undefined,
): SidebarDragPayload | null {
- if (!dataTransfer) return null;
- const types = Array.from(dataTransfer.types);
- if (!types.includes(OK_SIDEBAR_DRAG_MIME)) return null;
+ if (!dataTransfer || !hasSidebarDragType(dataTransfer)) return null;
const raw = dataTransfer.getData(OK_SIDEBAR_DRAG_MIME);
if (!raw) return null;
diff --git a/packages/app/src/lib/use-collab-url.test.ts b/packages/app/src/lib/use-collab-url.test.ts
index 997ad87be..06c9e3043 100644
--- a/packages/app/src/lib/use-collab-url.test.ts
+++ b/packages/app/src/lib/use-collab-url.test.ts
@@ -437,4 +437,22 @@ describe('Electron host short-circuit (US-010)', () => {
expect(state.terminal).toBe(false);
expect(state.lastError).toBeNull();
});
+
+ test('initialCollabUrlState exposes Electron collaboration before effects run', async () => {
+ const { initialCollabUrlState } = await import('./use-collab-url');
+ expect(
+ initialCollabUrlState({
+ collabUrl: 'ws://localhost:52000/collab',
+ apiOrigin: 'http://localhost:52000',
+ projectPath: '/tmp/project',
+ projectName: 'Project',
+ mode: 'editor',
+ }),
+ ).toEqual({
+ collabUrl: 'ws://localhost:52000/collab',
+ attempts: 0,
+ terminal: false,
+ lastError: null,
+ });
+ });
});
diff --git a/packages/app/src/lib/use-collab-url.ts b/packages/app/src/lib/use-collab-url.ts
index 22a099fc4..faa37fbf0 100644
--- a/packages/app/src/lib/use-collab-url.ts
+++ b/packages/app/src/lib/use-collab-url.ts
@@ -94,6 +94,17 @@ interface CollabPollState {
lastError: CollabUrlError | null;
}
+export function initialCollabUrlState(config: OkDesktopConfig | undefined): CollabPollState {
+ return config
+ ? electronStateFromConfig(config)
+ : {
+ collabUrl: null,
+ attempts: 0,
+ terminal: false,
+ lastError: null,
+ };
+}
+
interface CollabPollHandle {
/** Stop the loop and abort any in-flight fetch. Safe to call multiple times. */
cancel: () => void;
@@ -214,12 +225,11 @@ interface LoopState {
export function useCollabUrl(): UseCollabUrlState {
const [state, setState] = useState<
Pick<UseCollabUrlState, 'collabUrl' | 'attempts' | 'terminal' | 'lastError'>
- >({
- collabUrl: null,
- attempts: 0,
- terminal: false,
- lastError: null,
- });
+ >(() =>
+ initialCollabUrlState(
+ tryElectronBridge(typeof window === 'undefined' ? undefined : window)?.config,
+ ),
+ );
// Bump on manual retry to invalidate any in-flight loop state. Stored in a
// ref because we don't want a bump to trigger a re-render on its own — the
// effect reacts via a separate `retrySignal` state.
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index 9c633314b..5cd9c3863 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -210,6 +210,7 @@
"38foVZ": ["Loading diff"],
"3BLniE": ["Configuration problems"],
"3BnyYc": ["This doc isn't on GitHub yet. The link won't work until it's pushed."],
+ "3C2nIJ": ["Moved ", ["label"], " to a new pane on the left."],
"3DJEEt": [
["sizeText"],
" · secrets redacted · ",
@@ -262,6 +263,7 @@
"3l_knd": ["Press the sun or moon on “Custom” above to use this scheme."],
"3m2GBo": ["Searching docs"],
"3mFsc3": ["Restore with remote changes"],
+ "3nnyi_": [["0", "plural", { "one": ["Delete"], "other": ["Delete ", "#", " items"] }]],
"3o3tur": ["Starter content"],
"3oEK1e": ["Resuming the conversation"],
"3oh0nQ": ["Nested .okignore error in ", ["path"]],
@@ -598,6 +600,7 @@
"99eR72": ["Visual editor table selection"],
"9Bd18D": ["Failed to load hub pages"],
"9HKBNN": ["commands"],
+ "9Ii3uK": ["a new pane to the left of ", ["0"]],
"9J8xNg": ["Imported ", ["importedLabel"]],
"9KooKn": ["Run a project audit from the Problems panel."],
"9NJWgv": ["Backlinks"],
@@ -874,7 +877,6 @@
"Dut9Ht": ["Describe the skill you want to create"],
"Dvr1Sg": ["Copying"],
"Dvwa0U": ["Create a worktree from this branch"],
- "Dw1T_W": ["Rename ", ["label"]],
"Dz7fsq": ["Zoom In"],
"E1Da_b": [
"This permanently removes ",
@@ -1024,7 +1026,6 @@
"Fr8JGg": ["Zip file"],
"Fsx78O": ["Add the <0>ok</0> command to your terminal"],
"FvMSms": ["Renaming changes the file on disk and the id agents use to pick this template."],
- "FvpFSZ": ["Reveal in Finder, ", ["hint"]],
"Fxf4jq": ["Description (optional)"],
"Fy4GgU": [
"Explain how your codebase works so teammates and AI agents can find their way around. Good for documenting the architecture, the main parts, and the questions new contributors always ask."
@@ -1049,6 +1050,7 @@
"GBQjiV": ["Add skill"],
"GDvlUT": ["Role"],
"GGsM4y": ["Selected in graph"],
+ "GH02QY": ["Keep open"],
"GHsJb8": ["Show .ok folders"],
"GJH-AT": [
["docName"],
@@ -1073,14 +1075,19 @@
"G_hVTP": ["Enable Themes"],
"G_mWXb": ["Filter languages"],
"GamjcN": ["Template saved"],
+ "GceAYf": ["Moved ", ["label"], " to a new pane on the right."],
"GemPfn": ["Failed to parse forward-links error response (HTTP ", ["status"], ")"],
"Gfr4fu": ["Server can't open documents"],
"GhjUB_": ["Reconnected"],
"GidGkh": ["Update from source"],
"GkYV_4": ["Renamed ", ["0"], " → ", ["1"]],
"Gp_twO": ["Local path"],
+ "GrBgX_": [
+ "Press Space to pick up a tab. Use the arrow keys to move it within a tab strip, then press Space or Enter to drop it. Press Shift+F10 or the Menu key to open the tab context menu for split, close, pin, and other tab actions."
+ ],
"GsBUCk": ["Loading settings"],
"Gt4gOO": ["This folder has unpushed changes. Recipients will see the last pushed version."],
+ "Gu9pRm": [["0"], " was not moved."],
"GuLeuE": [
"Search matches file names, paths, and folders. Open a file to search its body <0>",
["0"],
@@ -1219,6 +1226,7 @@
"JkCD2u": ["Sync paused — you don't have permission to push to this repo"],
"JlFcis": ["Send"],
"JmfgFc": ["(a worktree of ", ["0"], ")"],
+ "Jnz9AY": [["0"], " is over ", ["destination"], "."],
"Jqqevv": ["System error"],
"JsY1p5": ["Denied"],
"JtD-Br": ["Page link"],
@@ -1401,7 +1409,6 @@
"A symlink is a pointer to the source folder rather than a folder of its own. Every location reads the exact same bytes, so nothing can drift, and a location stops working if the source is deleted."
],
"MTs6g3": ["Couldn't reconnect after server restart"],
- "MUBR8r": ["Rename succeeded but the tabstrip may be out of date — refresh to resync"],
"MUrVEo": ["No recent projects."],
"MV-Dkb": ["Found ", ["countDisplay"], " markdown files"],
"MVxpbf": ["Find and replace"],
@@ -1558,7 +1565,6 @@
"P47EWZ": ["Could not update sidebar settings"],
"P6gXB-": ["Replace ", ["keyName"]],
"P6lAT3": ["Folder target: ", ["linkTitle"], ". Click to open the overview."],
- "P8yDjG": ["Name can’t be empty, \".\", \"..\", or contain / or \\"],
"PB4upl": ["Find previous match"],
"PBwmDJ": ["Searching by meaning"],
"PBxg_E": ["Not now"],
@@ -1831,6 +1837,7 @@
"UPWItY": ["A folder containing SKILL.md."],
"UPjaXD": ["Couldn't duplicate \"", ["0"], "\": ", ["1"]],
"UQAp48": ["Search templates"],
+ "URN-cv": ["Cancelled moving ", ["0"], "."],
"URmyfc": ["Details"],
"UTNVyS": ["Select the full source document."],
"UTZ97u": ["Selection must be inside the project"],
@@ -2199,6 +2206,7 @@
"_PACVa": ["Release notes"],
"_PBJRl": ["Add at least one letter or number."],
"_Pmhxt": ["… earlier output trimmed"],
+ "_PnPuw": ["Picked up ", ["0"], " from ", ["1"], "."],
"_QwkMu": ["No matching paths"],
"_RcqUM": [
"You picked your home directory. OpenKnowledge will index everything in your home tree — large and may surface personal files."
@@ -2469,9 +2477,6 @@
"dbhUX1": ["Hide this file"],
"dbtjJh": ["(opens in new tab)"],
"djc1l9": ["More than ", ["0"], " requests were blocked by the preview's security policy"],
- "djjdjr": [
- ["deleteCount", "plural", { "one": ["Delete"], "other": ["Delete ", "#", " items"] }]
- ],
"dprWmL": ["Anchor in this page"],
"dr1vFs": ["Replace all matches"],
"drzzZw": ["Preview tabs"],
@@ -2569,6 +2574,7 @@
"fiMNLl": ["Sync settings not yet loaded — try again in a moment"],
"fj5YiP": ["Downloads a fresh copy from GitHub."],
"fnlBN4": ["Auto-approve settings not yet loaded — try again in a moment"],
+ "fo6CCk": ["pane ", ["0"]],
"fqSfXY": ["Replace"],
"fru3T7": ["Could not fix ", ["0"], " of ", ["1"], " files."],
"ft-BOm": ["Report a bug…"],
@@ -2635,6 +2641,7 @@
"gmJ0An": ["Failed to open folder."],
"goO4Ll": ["Editor status bar"],
"gp3I7-": ["Before syncing, set your identity for git commits:"],
+ "gqk-3R": ["Moved ", ["0"], " to ", ["destination"], "."],
"gtEbeW": ["Highlight"],
"gtGQ9S": ["Start ", ["agentName"], ", ", ["hint"]],
"gv5w9J": ["owner/repo, a git URL, or a local path"],
@@ -2818,6 +2825,7 @@
"j_Z6g7": ["Shared default"],
"jbSG8V": ["Show Files (", ["sidebarShortcutLabel"], ")"],
"jdGUeI": ["Couldn't create template: ", ["error"]],
+ "jeCFV7": ["Move to new pane right"],
"jeJexw": ["Couldn't finish installing ", ["0"], " — see below."],
"jerqF0": ["Loading branch state"],
"jhtG3I": [" Your selection has been restored."],
@@ -2827,6 +2835,7 @@
],
"jng7Ko": ["conflict"],
"jol95m": ["Failed to open Project Navigator."],
+ "jp6I-2": ["a new pane to the right of ", ["0"]],
"jpctdh": ["View"],
"jpoCue": [".myteam/skills"],
"jqe7Yq": [
@@ -3080,6 +3089,7 @@
"mwMF9u": ["Open CodeMirror search in source editor mode."],
"mxGJVE": ["Switch worktree…"],
"mxY24F": ["Duplicate the focused file-tree item when focus is in the Files sidebar."],
+ "n2XqGH": ["editor pane"],
"n2lRue": ["Commit or stash changes to switch:"],
"n3T3EE": ["Installed in ", ["label"], " — click to remove"],
"n3wx1q": ["Restore to this version?"],
@@ -3160,7 +3170,6 @@
"o0bHtA": ["By OpenKnowledge"],
"o2yoFu": ["Reveal in Finder, No workspace"],
"o49mDZ": ["Loading timeline history"],
- "o4dcAf": ["Reveal in File Explorer, ", ["hint"]],
"o5jB-D": ["Collapse panel"],
"o9CrsQ": ["research-note"],
"o9fPtM": ["Auto-update from source"],
@@ -3223,6 +3232,7 @@
"p9sdCy": ["New ignore pattern"],
"pAgkuZ": ["Reopening \"", ["docName"], "\" with a fresh local collaboration cache."],
"pBROkv": ["Thanks for subscribing. Watch your inbox for product updates."],
+ "pCralD": ["Move to new pane left"],
"pEQFsW": ["No matching projects."],
"pFPzHA": ["Emoji picker"],
"pFRz_E": ["Leave these comments out of this message"],
@@ -3819,7 +3829,6 @@
"zLak8b": ["Activate new tab"],
"zO-IiA": ["The terminal isn't available here — the comments are still waiting to send."],
"zQBg2C": ["Move the current block up or down one position."],
- "zUhPuR": ["Open containing folder, ", ["hint"]],
"zXj1rA": ["Search by meaning"],
"zYp8Sr": [
"A <0>Modified</0> badge marks rules your config sets explicitly — directly, or inherited through <1>extends</1>. Unmarked rules keep their default state."
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index 8b109bd6b..107ba5400 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -206,6 +206,11 @@ msgstr "{0, plural, one {# use} other {# uses}}"
msgid "{0, plural, one {# warning} other {# warnings}}"
msgstr "{0, plural, one {# warning} other {# warnings}}"
+#. placeholder {0}: deleteTargets.length
+#: src/components/FileTree.tsx
+msgid "{0, plural, one {Delete} other {Delete # items}}"
+msgstr "{0, plural, one {Delete} other {Delete # items}}"
+
#. placeholder {0}: fileRows.length
#: src/components/CreatedItemsList.tsx
msgid "{0, plural, one {File} other {Files}}"
@@ -250,6 +255,11 @@ msgstr "{0} at line {displayLine}"
msgid "{0} can't continue this conversation — the transcript is kept, but the agent session is gone."
msgstr "{0} can't continue this conversation — the transcript is kept, but the agent session is gone."
+#. placeholder {0}: activeData.label
+#: src/components/EditorWorkspace.tsx
+msgid "{0} is over {destination}."
+msgstr "{0} is over {destination}."
+
#. placeholder {0}: resolvedTarget.displayName
#. placeholder {0}: target.displayName
#: src/comments/use-comment-delivery.ts
@@ -303,6 +313,11 @@ msgstr "{0} templates available"
msgid "{0} total"
msgstr "{0} total"
+#. placeholder {0}: activeData.label
+#: src/components/EditorWorkspace.tsx
+msgid "{0} was not moved."
+msgstr "{0} was not moved."
+
#. placeholder {0}: share.owner
#. placeholder {1}: share.repo
#. placeholder {2}: shareTargetPath(share.target)
@@ -442,10 +457,6 @@ msgstr "{days, plural, one {# day ago} other {# days ago}}"
msgid "{days}d ago"
msgstr "{days}d ago"
-#: src/components/FileTree.tsx
-msgid "{deleteCount, plural, one {Delete} other {Delete # items}}"
-msgstr "{deleteCount, plural, one {Delete} other {Delete # items}}"
-
#: src/editor/extensions/JsxComponentView.tsx
msgid "{descriptorLabel} — render error, source editable below"
msgstr "{descriptorLabel} — render error, source editable below"
@@ -892,6 +903,16 @@ msgstr "A memory snapshot from the crash, and the artifact that helps us most. I
msgid "A network problem or GitHub outage interrupted the clone."
msgstr "A network problem or GitHub outage interrupted the clone."
+#. placeholder {0}: paneLabel(data.paneId)
+#: src/components/EditorWorkspace.tsx
+msgid "a new pane to the left of {0}"
+msgstr "a new pane to the left of {0}"
+
+#. placeholder {0}: paneLabel(data.paneId)
+#: src/components/EditorWorkspace.tsx
+msgid "a new pane to the right of {0}"
+msgstr "a new pane to the right of {0}"
+
#: src/components/settings/SettingsDialogErrorBoundary.tsx
#: src/components/TerminalGate.tsx
msgid "A newer version may have been deployed since this tab opened."
@@ -1874,6 +1895,7 @@ msgstr "Can't safely edit this tool's config"
#: src/components/CreateProjectDialog.tsx
#: src/components/DeleteConfirmationDialog.tsx
#: src/components/EnableSyncConfirmDialog.tsx
+#: src/components/FileTargetRenameDialog.tsx
#: src/components/FrontmatterRow.tsx
#: src/components/ImportSkillForm.tsx
#: src/components/InstallInClaudeDesktopDialog.tsx
@@ -1912,6 +1934,11 @@ msgstr "Cancel editing"
msgid "Cancelled"
msgstr "Cancelled"
+#. placeholder {0}: activeData.label
+#: src/components/EditorWorkspace.tsx
+msgid "Cancelled moving {0}."
+msgstr "Cancelled moving {0}."
+
#: src/editor/image-upload/index.ts
msgid "Cannot upload: no document is open"
msgstr "Cannot upload: no document is open"
@@ -2285,7 +2312,7 @@ msgstr "Collapse {keyName}"
#: src/components/AppMenubar.tsx
#: src/components/command-palette-commands.ts
#: src/components/FileSidebar.tsx
-#: src/components/FileTree.tsx
+#: src/components/FileTargetMenuItems.tsx
msgid "Collapse all"
msgstr "Collapse all"
@@ -2488,6 +2515,7 @@ msgstr "Connect OpenKnowledge to other tools you use."
msgid "Connect the AI tools you use to this specific project. These files live in the project folder, so anyone who opens it gets the same setup."
msgstr "Connect the AI tools you use to this specific project. These files live in the project folder, so anyone who opens it gets the same setup."
+#: src/components/EditorTabTargetMenuItems.tsx
#: src/components/FileSidebar.tsx
#: src/components/FileTree.tsx
msgid "Connect this project to GitHub to share."
@@ -2609,7 +2637,7 @@ msgstr "Continue in browser"
msgid "Convert"
msgstr "Convert"
-#: src/components/FileTree.tsx
+#: src/components/FileTargetMenuItems.tsx
msgid "Convert (delete original)"
msgstr "Convert (delete original)"
@@ -2643,6 +2671,7 @@ msgstr "Converting..."
msgid "Copied"
msgstr "Copied"
+#: src/components/EditorTabTargetMenuItems.tsx
#: src/components/FileSidebar.tsx
#: src/components/FileTree.tsx
msgid "Copied full path"
@@ -2652,6 +2681,7 @@ msgstr "Copied full path"
msgid "Copied path"
msgstr "Copied path"
+#: src/components/EditorTabTargetMenuItems.tsx
#: src/components/FileSidebar.tsx
#: src/components/FileTree.tsx
msgid "Copied relative path"
@@ -2720,7 +2750,7 @@ msgid "Copy full path, No workspace"
msgstr "Copy full path, No workspace"
#: src/components/AppMenubar.tsx
-#: src/components/FileTree.tsx
+#: src/components/FileTargetMenuItems.tsx
msgid "Copy path"
msgstr "Copy path"
@@ -2764,11 +2794,13 @@ msgstr "Could not complete delete"
msgid "Could not construct share URL."
msgstr "Could not construct share URL."
+#: src/components/EditorTabTargetMenuItems.tsx
#: src/components/FileSidebar.tsx
#: src/components/FileTree.tsx
msgid "Could not copy full path"
msgstr "Could not copy full path"
+#: src/components/EditorTabTargetMenuItems.tsx
#: src/components/FileSidebar.tsx
#: src/components/FileTree.tsx
msgid "Could not copy relative path"
@@ -3527,6 +3559,7 @@ msgstr "Default: <0>{0}</0>"
#: src/components/acp/ThreadHistoryMenu.tsx
#: src/components/DeleteConfirmationDialog.tsx
+#: src/components/FileTargetMenuItems.tsx
#: src/components/skill-actions.tsx
#: src/components/TemplateRow.tsx
#: src/editor/extensions/JsxComponentView.tsx
@@ -3974,7 +4007,7 @@ msgstr "Drag item {0} to reorder"
#: src/components/AppMenubar.tsx
#: src/components/command-palette-commands.ts
-#: src/components/FileTree.tsx
+#: src/components/FileTargetMenuItems.tsx
#: src/components/skill-actions.tsx
msgid "Duplicate"
msgstr "Duplicate"
@@ -4131,6 +4164,10 @@ msgstr "Editor"
msgid "Editor mode"
msgstr "Editor mode"
+#: src/components/EditorWorkspace.tsx
+msgid "editor pane"
+msgstr "editor pane"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Editor selection"
msgstr "Editor selection"
@@ -4391,7 +4428,7 @@ msgstr "Expand {keyName}"
#: src/components/AppMenubar.tsx
#: src/components/command-palette-commands.ts
#: src/components/FileSidebar.tsx
-#: src/components/FileTree.tsx
+#: src/components/FileTargetMenuItems.tsx
msgid "Expand all"
msgstr "Expand all"
@@ -5092,7 +5129,7 @@ msgid "Full guide"
msgstr "Full guide"
#: src/components/AppMenubar.tsx
-#: src/components/FileTree.tsx
+#: src/components/FileTargetMenuItems.tsx
msgid "Full path"
msgstr "Full path"
@@ -5313,6 +5350,7 @@ msgstr "Help"
msgid "Helps your coding agent recognize OpenKnowledge projects and route reads and writes through it."
msgstr "Helps your coding agent recognize OpenKnowledge projects and route reads and writes through it."
+#: src/components/EditorTabTargetMenuItems.tsx
#: src/components/FileTree.tsx
msgid "Hidden “{basename}”"
msgstr "Hidden “{basename}”"
@@ -5322,6 +5360,7 @@ msgstr "Hidden “{basename}”"
msgid "Hidden files"
msgstr "Hidden files"
+#: src/components/EditorTabTargetMenuItems.tsx
#: src/components/FileTree.tsx
msgid "Hidden folder “{basename}”"
msgstr "Hidden folder “{basename}”"
@@ -5360,6 +5399,7 @@ msgstr "Hide Files ({sidebarShortcutLabel})"
msgid "Hide files and folders from your knowledge base. Hidden items don’t appear in the file tree, search, or AI tools. <0>Learn more about patterns</0>."
msgstr "Hide files and folders from your knowledge base. Hidden items don’t appear in the file tree, search, or AI tools. <0>Learn more about patterns</0>."
+#: src/components/EditorTabTargetMenuItems.tsx
#: src/components/FileTree.tsx
msgid "Hide folder"
msgstr "Hide folder"
@@ -5407,6 +5447,7 @@ msgstr "Hide Terminal"
msgid "Hide these comments"
msgstr "Hide these comments"
+#: src/components/EditorTabTargetMenuItems.tsx
#: src/components/FileTree.tsx
msgid "Hide this file"
msgstr "Hide this file"
@@ -5531,7 +5572,7 @@ msgstr "Ignore patterns (raw text)"
msgid "Import"
msgstr "Import"
-#: src/components/FileTree.tsx
+#: src/components/FileTargetMenuItems.tsx
msgid "Import as template"
msgstr "Import as template"
@@ -5955,7 +5996,11 @@ msgstr "Keep mine"
msgid "Keep my version"
msgstr "Keep my version"
-#: src/components/FileTree.tsx
+#: src/components/EditorTabs.tsx
+msgid "Keep open"
+msgstr "Keep open"
+
+#: src/components/FileTargetMenuItems.tsx
msgid "Keep original file"
msgstr "Keep original file"
@@ -6303,6 +6348,7 @@ msgstr "Make this knowledge base available as a Claude Skill."
msgid "Make this the source — the skill's real folder moves here"
msgstr "Make this the source — the skill's real folder moves here"
+#: src/components/EditorTabTargetMenuItems.tsx
#: src/components/FileTree.tsx
msgid "Manage hidden files in Settings → Ignore patterns."
msgstr "Manage hidden files in Settings → Ignore patterns."
@@ -6532,6 +6578,14 @@ msgstr "Move to {0}"
msgid "Move to {0}?"
msgstr "Move to {0}?"
+#: src/components/EditorTabs.tsx
+msgid "Move to new pane left"
+msgstr "Move to new pane left"
+
+#: src/components/EditorTabs.tsx
+msgid "Move to new pane right"
+msgstr "Move to new pane right"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Move to the next CodeMirror lint diagnostic."
msgstr "Move to the next CodeMirror lint diagnostic."
@@ -6563,6 +6617,11 @@ msgstr "Move up"
msgid "Moved \"{0}\" to {1}"
msgstr "Moved \"{0}\" to {1}"
+#. placeholder {0}: activeData.label
+#: src/components/EditorWorkspace.tsx
+msgid "Moved {0} to {destination}."
+msgstr "Moved {0} to {destination}."
+
#. placeholder {0}: moved.label
#. placeholder {1}: moved.position
#. placeholder {2}: moved.total
@@ -6570,6 +6629,14 @@ msgstr "Moved \"{0}\" to {1}"
msgid "Moved {0} to position {1} of {2}"
msgstr "Moved {0} to position {1} of {2}"
+#: src/components/EditorTabs.tsx
+msgid "Moved {label} to a new pane on the left."
+msgstr "Moved {label} to a new pane on the left."
+
+#: src/components/EditorTabs.tsx
+msgid "Moved {label} to a new pane on the right."
+msgstr "Moved {label} to a new pane on the right."
+
#: src/components/FolderTimelineCard.tsx
msgid "moved template"
msgstr "moved template"
@@ -6601,6 +6668,7 @@ msgid "name"
msgstr "name"
#: src/components/AuthModal.tsx
+#: src/components/FileTargetRenameDialog.tsx
#: src/components/FolderOverview.tsx
#: src/components/NewSkillDialog.tsx
#: src/components/SkillRenameDialog.tsx
@@ -6612,10 +6680,6 @@ msgstr "Name"
msgid "Name (e.g. {login})"
msgstr "Name (e.g. {login})"
-#: src/components/EditorTabs.tsx
-msgid "Name can’t be empty, \".\", \"..\", or contain / or \\"
-msgstr "Name can’t be empty, \".\", \"..\", or contain / or \\"
-
#: src/components/NewItemDialog.tsx
#: src/components/NewSkillDialog.tsx
msgid "Name cannot be empty"
@@ -6655,7 +6719,6 @@ msgstr "Nested fields"
msgid "Network error - {kind} \"{createdPath}\" still exists on disk"
msgstr "Network error - {kind} \"{createdPath}\" still exists on disk"
-#: src/components/EditorTabs.tsx
#: src/components/FileTree.tsx
#: src/components/NewItemDialog.tsx
msgid "Network error — please try again"
@@ -6699,7 +6762,7 @@ msgstr "New changes from your remote appear in your copy automatically."
#: src/components/AppMenubar.tsx
#: src/components/command-palette-commands.ts
#: src/components/FileSidebar.tsx
-#: src/components/FileTree.tsx
+#: src/components/FileTargetMenuItems.tsx
#: src/components/NewItemDialog.tsx
#: src/components/skill-actions.tsx
#: src/components/SkillsTree.tsx
@@ -6722,7 +6785,7 @@ msgstr "New file in this skill"
#: src/components/AppMenubar.tsx
#: src/components/command-palette-commands.ts
#: src/components/FileSidebar.tsx
-#: src/components/FileTree.tsx
+#: src/components/FileTargetMenuItems.tsx
#: src/components/NewItemDialog.tsx
#: src/lib/keyboard-shortcuts.ts
msgid "New folder"
@@ -6734,7 +6797,7 @@ msgstr "New from scratch"
#: src/components/command-palette-commands.ts
#: src/components/FileSidebar.tsx
-#: src/components/FileTree.tsx
+#: src/components/FileTargetMenuItems.tsx
msgid "New from template"
msgstr "New from template"
@@ -7147,6 +7210,7 @@ msgstr "No templates yet. Add one in this folder's Templates section, or in Sett
msgid "No templates yet. Add one to give new docs in this folder a ready-made starting point."
msgstr "No templates yet. Add one to give new docs in this folder a ready-made starting point."
+#: src/components/EditorTabTargetMenuItems.tsx
#: src/components/FileSidebar.tsx
#: src/components/FileTree.tsx
#: src/components/handoff/OpenInAgentContextSubmenu.tsx
@@ -7446,14 +7510,11 @@ msgstr "Open CodeMirror's lint diagnostics panel."
msgid "Open comment"
msgstr "Open comment"
+#: src/components/EditorTabTargetMenuItems.tsx
#: src/components/FileTree.tsx
msgid "Open containing folder"
msgstr "Open containing folder"
-#: src/components/FileTree.tsx
-msgid "Open containing folder, {hint}"
-msgstr "Open containing folder, {hint}"
-
#: src/components/PropertyWidgets.tsx
msgid "Open date picker for {keyName}"
msgstr "Open date picker for {keyName}"
@@ -7848,6 +7909,11 @@ msgstr "Pan right"
msgid "Pan up"
msgstr "Pan up"
+#. placeholder {0}: position + 1
+#: src/components/EditorWorkspace.tsx
+msgid "pane {0}"
+msgstr "pane {0}"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Paragraph"
msgstr "Paragraph"
@@ -8022,6 +8088,12 @@ msgstr "Pick the skills to install. Each one lands as an editable skill you own.
msgid "Pick up where you left off"
msgstr "Pick up where you left off"
+#. placeholder {0}: data.label
+#. placeholder {1}: paneLabel(data.paneId)
+#: src/components/EditorWorkspace.tsx
+msgid "Picked up {0} from {1}."
+msgstr "Picked up {0} from {1}."
+
#: src/components/EditorTabs.tsx
msgid "Pin tab"
msgstr "Pin tab"
@@ -8085,6 +8157,10 @@ msgstr "Preparing share URL..."
msgid "Preparing to uninstall OpenKnowledge"
msgstr "Preparing to uninstall OpenKnowledge"
+#: src/components/EditorWorkspace.tsx
+msgid "Press Space to pick up a tab. Use the arrow keys to move it within a tab strip, then press Space or Enter to drop it. Press Shift+F10 or the Menu key to open the tab context menu for split, close, pin, and other tab actions."
+msgstr "Press Space to pick up a tab. Use the arrow keys to move it within a tab strip, then press Space or Enter to drop it. Press Shift+F10 or the Menu key to open the tab context menu for split, close, pin, and other tab actions."
+
#: src/components/settings/CustomThemeEditor.tsx
msgid "Press the sun or moon on “Custom” above to use this scheme."
msgstr "Press the sun or moon on “Custom” above to use this scheme."
@@ -8466,7 +8542,7 @@ msgid "Reject"
msgstr "Reject"
#: src/components/AppMenubar.tsx
-#: src/components/FileTree.tsx
+#: src/components/FileTargetMenuItems.tsx
msgid "Relative path"
msgstr "Relative path"
@@ -8627,7 +8703,8 @@ msgstr "Removing OpenKnowledge files…"
#: src/components/AppMenubar.tsx
#: src/components/command-palette-commands.ts
-#: src/components/FileTree.tsx
+#: src/components/FileTargetMenuItems.tsx
+#: src/components/FileTargetRenameDialog.tsx
#: src/components/skill-actions.tsx
#: src/components/SkillFileRenameDialog.tsx
#: src/components/SkillRenameDialog.tsx
@@ -8643,10 +8720,6 @@ msgstr "Rename {0}"
msgid "Rename {keyName}"
msgstr "Rename {keyName}"
-#: src/components/EditorTabs.tsx
-msgid "Rename {label}"
-msgstr "Rename {label}"
-
#. placeholder {0}: result.error
#: src/components/SkillFileRenameDialog.tsx
msgid "Rename failed: {0}"
@@ -8664,10 +8737,6 @@ msgstr "Rename skill"
msgid "Rename succeeded but the sidebar may be out of date — refresh to resync"
msgstr "Rename succeeded but the sidebar may be out of date — refresh to resync"
-#: src/components/EditorTabs.tsx
-msgid "Rename succeeded but the tabstrip may be out of date — refresh to resync"
-msgstr "Rename succeeded but the tabstrip may be out of date — refresh to resync"
-
#. placeholder {0}: docLeaf(descriptor.from)
#. placeholder {1}: docLeaf(descriptor.to)
#: src/components/TimelinePanel.tsx
@@ -9004,16 +9073,14 @@ msgstr "Reuse one tab when clicking through the sidebars. Off opens every click
msgid "Reused if it already exists, created if not."
msgstr "Reused if it already exists, created if not."
+#: src/components/EditorTabTargetMenuItems.tsx
#: src/components/FileTree.tsx
msgid "Reveal in File Explorer"
msgstr "Reveal in File Explorer"
-#: src/components/FileTree.tsx
-msgid "Reveal in File Explorer, {hint}"
-msgstr "Reveal in File Explorer, {hint}"
-
#: src/components/BugReportHistory.tsx
#: src/components/command-palette-commands.ts
+#: src/components/EditorTabTargetMenuItems.tsx
#: src/components/FileSidebar.tsx
#: src/components/FileTree.tsx
#: src/components/ReportBugDialogBody.tsx
@@ -9021,10 +9088,6 @@ msgstr "Reveal in File Explorer, {hint}"
msgid "Reveal in Finder"
msgstr "Reveal in Finder"
-#: src/components/FileTree.tsx
-msgid "Reveal in Finder, {hint}"
-msgstr "Reveal in Finder, {hint}"
-
#: src/components/FileSidebar.tsx
msgid "Reveal in Finder, No workspace"
msgstr "Reveal in Finder, No workspace"
@@ -9107,6 +9170,7 @@ msgid "Sandboxed HTML embed — write HTML, see the rendered preview live."
msgstr "Sandboxed HTML embed — write HTML, see the rendered preview live."
#: src/components/AuthModal.tsx
+#: src/components/FileTargetRenameDialog.tsx
#: src/components/settings/SearchSection.tsx
#: src/components/settings/ThemePreviewCanvas.tsx
#: src/editor/components/CodePreviewEditModal.tsx
@@ -9609,7 +9673,7 @@ msgid "Setup OpenKnowledge in this folder?"
msgstr "Setup OpenKnowledge in this folder?"
#: src/components/FileSidebar.tsx
-#: src/components/FileTree.tsx
+#: src/components/FileTargetMenuItems.tsx
#: src/components/ShareButton.tsx
msgid "Share"
msgstr "Share"
@@ -9891,7 +9955,6 @@ msgid "Skill discovery powered by <0>skills.sh</0>"
msgstr "Skill discovery powered by <0>skills.sh</0>"
#: src/components/command-palette-commands.ts
-#: src/components/EditorTabs.tsx
#: src/components/FileSidebar.tsx
#: src/components/FilesSkillsToggle.tsx
#: src/components/settings/SettingsDialogShell.tsx
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index c6d6aa700..a7a3bee31 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -210,6 +210,7 @@
"38foVZ": ["Ĺōàďĩńĝ ďĩƒƒ"],
"3BLniE": ["Ćōńƒĩĝũŕàţĩōń ƥŕōƀĺēḿś"],
"3BnyYc": ["Ţĥĩś ďōć ĩśń'ţ ōń ĜĩţĤũƀ ŷēţ. Ţĥē ĺĩńķ ŵōń'ţ ŵōŕķ ũńţĩĺ ĩţ'ś ƥũśĥēď."],
+ "3C2nIJ": ["Ḿōvēď ", ["label"], " ţō à ńēŵ ƥàńē ōń ţĥē ĺēƒţ."],
"3DJEEt": [
["sizeText"],
" · śēćŕēţś ŕēďàćţēď · ",
@@ -262,6 +263,7 @@
"3l_knd": ["Ƥŕēśś ţĥē śũń ōŕ ḿōōń ōń “Ćũśţōḿ” àƀōvē ţō ũśē ţĥĩś śćĥēḿē."],
"3m2GBo": ["Śēàŕćĥĩńĝ ďōćś"],
"3mFsc3": ["Ŕēśţōŕē ŵĩţĥ ŕēḿōţē ćĥàńĝēś"],
+ "3nnyi_": [["0", "plural", { "one": ["Ďēĺēţē"], "other": ["Ďēĺēţē ", "#", " ĩţēḿś"] }]],
"3o3tur": ["Śţàŕţēŕ ćōńţēńţ"],
"3oEK1e": ["Ŕēśũḿĩńĝ ţĥē ćōńvēŕśàţĩōń"],
"3oh0nQ": ["Ńēśţēď .ōķĩĝńōŕē ēŕŕōŕ ĩń ", ["path"]],
@@ -598,6 +600,7 @@
"99eR72": ["Vĩśũàĺ ēďĩţōŕ ţàƀĺē śēĺēćţĩōń"],
"9Bd18D": ["Ƒàĩĺēď ţō ĺōàď ĥũƀ ƥàĝēś"],
"9HKBNN": ["ćōḿḿàńďś"],
+ "9Ii3uK": ["à ńēŵ ƥàńē ţō ţĥē ĺēƒţ ōƒ ", ["0"]],
"9J8xNg": ["Ĩḿƥōŕţēď ", ["importedLabel"]],
"9KooKn": ["Ŕũń à ƥŕōĴēćţ àũďĩţ ƒŕōḿ ţĥē Ƥŕōƀĺēḿś ƥàńēĺ."],
"9NJWgv": ["ßàćķĺĩńķś"],
@@ -874,7 +877,6 @@
"Dut9Ht": ["Ďēśćŕĩƀē ţĥē śķĩĺĺ ŷōũ ŵàńţ ţō ćŕēàţē"],
"Dvr1Sg": ["Ćōƥŷĩńĝ"],
"Dvwa0U": ["Ćŕēàţē à ŵōŕķţŕēē ƒŕōḿ ţĥĩś ƀŕàńćĥ"],
- "Dw1T_W": ["Ŕēńàḿē ", ["label"]],
"Dz7fsq": ["Źōōḿ Ĩń"],
"E1Da_b": [
"Ţĥĩś ƥēŕḿàńēńţĺŷ ŕēḿōvēś ",
@@ -1024,7 +1026,6 @@
"Fr8JGg": ["Źĩƥ ƒĩĺē"],
"Fsx78O": ["Àďď ţĥē <0>ōķ</0> ćōḿḿàńď ţō ŷōũŕ ţēŕḿĩńàĺ"],
"FvMSms": ["Ŕēńàḿĩńĝ ćĥàńĝēś ţĥē ƒĩĺē ōń ďĩśķ àńď ţĥē ĩď àĝēńţś ũśē ţō ƥĩćķ ţĥĩś ţēḿƥĺàţē."],
- "FvpFSZ": ["Ŕēvēàĺ ĩń Ƒĩńďēŕ, ", ["hint"]],
"Fxf4jq": ["Ďēśćŕĩƥţĩōń (ōƥţĩōńàĺ)"],
"Fy4GgU": [
"Ēxƥĺàĩń ĥōŵ ŷōũŕ ćōďēƀàśē ŵōŕķś śō ţēàḿḿàţēś àńď ÀĨ àĝēńţś ćàń ƒĩńď ţĥēĩŕ ŵàŷ àŕōũńď. Ĝōōď ƒōŕ ďōćũḿēńţĩńĝ ţĥē àŕćĥĩţēćţũŕē, ţĥē ḿàĩń ƥàŕţś, àńď ţĥē ǫũēśţĩōńś ńēŵ ćōńţŕĩƀũţōŕś àĺŵàŷś àśķ."
@@ -1049,6 +1050,7 @@
"GBQjiV": ["Àďď śķĩĺĺ"],
"GDvlUT": ["Ŕōĺē"],
"GGsM4y": ["Śēĺēćţēď ĩń ĝŕàƥĥ"],
+ "GH02QY": ["Ķēēƥ ōƥēń"],
"GHsJb8": ["Śĥōŵ .ōķ ƒōĺďēŕś"],
"GJH-AT": [
["docName"],
@@ -1073,14 +1075,19 @@
"G_hVTP": ["Ēńàƀĺē Ţĥēḿēś"],
"G_mWXb": ["Ƒĩĺţēŕ ĺàńĝũàĝēś"],
"GamjcN": ["Ţēḿƥĺàţē śàvēď"],
+ "GceAYf": ["Ḿōvēď ", ["label"], " ţō à ńēŵ ƥàńē ōń ţĥē ŕĩĝĥţ."],
"GemPfn": ["Ƒàĩĺēď ţō ƥàŕśē ƒōŕŵàŕď-ĺĩńķś ēŕŕōŕ ŕēśƥōńśē (ĤŢŢƤ ", ["status"], ")"],
"Gfr4fu": ["Śēŕvēŕ ćàń'ţ ōƥēń ďōćũḿēńţś"],
"GhjUB_": ["Ŕēćōńńēćţēď"],
"GidGkh": ["Ũƥďàţē ƒŕōḿ śōũŕćē"],
"GkYV_4": ["Ŕēńàḿēď ", ["0"], " → ", ["1"]],
"Gp_twO": ["Ĺōćàĺ ƥàţĥ"],
+ "GrBgX_": [
+ "Ƥŕēśś Śƥàćē ţō ƥĩćķ ũƥ à ţàƀ. Ũśē ţĥē àŕŕōŵ ķēŷś ţō ḿōvē ĩţ ŵĩţĥĩń à ţàƀ śţŕĩƥ, ţĥēń ƥŕēśś Śƥàćē ōŕ Ēńţēŕ ţō ďŕōƥ ĩţ. Ƥŕēśś Śĥĩƒţ+Ƒ10 ōŕ ţĥē Ḿēńũ ķēŷ ţō ōƥēń ţĥē ţàƀ ćōńţēxţ ḿēńũ ƒōŕ śƥĺĩţ, ćĺōśē, ƥĩń, àńď ōţĥēŕ ţàƀ àćţĩōńś."
+ ],
"GsBUCk": ["Ĺōàďĩńĝ śēţţĩńĝś"],
"Gt4gOO": ["Ţĥĩś ƒōĺďēŕ ĥàś ũńƥũśĥēď ćĥàńĝēś. Ŕēćĩƥĩēńţś ŵĩĺĺ śēē ţĥē ĺàśţ ƥũśĥēď vēŕśĩōń."],
+ "Gu9pRm": [["0"], " ŵàś ńōţ ḿōvēď."],
"GuLeuE": [
"Śēàŕćĥ ḿàţćĥēś ƒĩĺē ńàḿēś, ƥàţĥś, àńď ƒōĺďēŕś. Ōƥēń à ƒĩĺē ţō śēàŕćĥ ĩţś ƀōďŷ <0>",
["0"],
@@ -1219,6 +1226,7 @@
"JkCD2u": ["Śŷńć ƥàũśēď — ŷōũ ďōń'ţ ĥàvē ƥēŕḿĩśśĩōń ţō ƥũśĥ ţō ţĥĩś ŕēƥō"],
"JlFcis": ["Śēńď"],
"JmfgFc": ["(à ŵōŕķţŕēē ōƒ ", ["0"], ")"],
+ "Jnz9AY": [["0"], " ĩś ōvēŕ ", ["destination"], "."],
"Jqqevv": ["Śŷśţēḿ ēŕŕōŕ"],
"JsY1p5": ["Ďēńĩēď"],
"JtD-Br": ["Ƥàĝē ĺĩńķ"],
@@ -1401,7 +1409,6 @@
"À śŷḿĺĩńķ ĩś à ƥōĩńţēŕ ţō ţĥē śōũŕćē ƒōĺďēŕ ŕàţĥēŕ ţĥàń à ƒōĺďēŕ ōƒ ĩţś ōŵń. Ēvēŕŷ ĺōćàţĩōń ŕēàďś ţĥē ēxàćţ śàḿē ƀŷţēś, śō ńōţĥĩńĝ ćàń ďŕĩƒţ, àńď à ĺōćàţĩōń śţōƥś ŵōŕķĩńĝ ĩƒ ţĥē śōũŕćē ĩś ďēĺēţēď."
],
"MTs6g3": ["Ćōũĺďń'ţ ŕēćōńńēćţ àƒţēŕ śēŕvēŕ ŕēśţàŕţ"],
- "MUBR8r": ["Ŕēńàḿē śũććēēďēď ƀũţ ţĥē ţàƀśţŕĩƥ ḿàŷ ƀē ōũţ ōƒ ďàţē — ŕēƒŕēśĥ ţō ŕēśŷńć"],
"MUrVEo": ["Ńō ŕēćēńţ ƥŕōĴēćţś."],
"MV-Dkb": ["Ƒōũńď ", ["countDisplay"], " ḿàŕķďōŵń ƒĩĺēś"],
"MVxpbf": ["Ƒĩńď àńď ŕēƥĺàćē"],
@@ -1558,7 +1565,6 @@
"P47EWZ": ["Ćōũĺď ńōţ ũƥďàţē śĩďēƀàŕ śēţţĩńĝś"],
"P6gXB-": ["Ŕēƥĺàćē ", ["keyName"]],
"P6lAT3": ["Ƒōĺďēŕ ţàŕĝēţ: ", ["linkTitle"], ". Ćĺĩćķ ţō ōƥēń ţĥē ōvēŕvĩēŵ."],
- "P8yDjG": ["Ńàḿē ćàń’ţ ƀē ēḿƥţŷ, \".\", \"..\", ōŕ ćōńţàĩń / ōŕ \\"],
"PB4upl": ["Ƒĩńď ƥŕēvĩōũś ḿàţćĥ"],
"PBwmDJ": ["Śēàŕćĥĩńĝ ƀŷ ḿēàńĩńĝ"],
"PBxg_E": ["Ńōţ ńōŵ"],
@@ -1831,6 +1837,7 @@
"UPWItY": ["À ƒōĺďēŕ ćōńţàĩńĩńĝ ŚĶĨĹĹ.ḿď."],
"UPjaXD": ["Ćōũĺďń'ţ ďũƥĺĩćàţē \"", ["0"], "\": ", ["1"]],
"UQAp48": ["Śēàŕćĥ ţēḿƥĺàţēś"],
+ "URN-cv": ["Ćàńćēĺĺēď ḿōvĩńĝ ", ["0"], "."],
"URmyfc": ["Ďēţàĩĺś"],
"UTNVyS": ["Śēĺēćţ ţĥē ƒũĺĺ śōũŕćē ďōćũḿēńţ."],
"UTZ97u": ["Śēĺēćţĩōń ḿũśţ ƀē ĩńśĩďē ţĥē ƥŕōĴēćţ"],
@@ -2199,6 +2206,7 @@
"_PACVa": ["Ŕēĺēàśē ńōţēś"],
"_PBJRl": ["Àďď àţ ĺēàśţ ōńē ĺēţţēŕ ōŕ ńũḿƀēŕ."],
"_Pmhxt": ["… ēàŕĺĩēŕ ōũţƥũţ ţŕĩḿḿēď"],
+ "_PnPuw": ["Ƥĩćķēď ũƥ ", ["0"], " ƒŕōḿ ", ["1"], "."],
"_QwkMu": ["Ńō ḿàţćĥĩńĝ ƥàţĥś"],
"_RcqUM": [
"Ŷōũ ƥĩćķēď ŷōũŕ ĥōḿē ďĩŕēćţōŕŷ. ŌƥēńĶńōŵĺēďĝē ŵĩĺĺ ĩńďēx ēvēŕŷţĥĩńĝ ĩń ŷōũŕ ĥōḿē ţŕēē — ĺàŕĝē àńď ḿàŷ śũŕƒàćē ƥēŕśōńàĺ ƒĩĺēś."
@@ -2469,9 +2477,6 @@
"dbhUX1": ["Ĥĩďē ţĥĩś ƒĩĺē"],
"dbtjJh": ["(ōƥēńś ĩń ńēŵ ţàƀ)"],
"djc1l9": ["Ḿōŕē ţĥàń ", ["0"], " ŕēǫũēśţś ŵēŕē ƀĺōćķēď ƀŷ ţĥē ƥŕēvĩēŵ'ś śēćũŕĩţŷ ƥōĺĩćŷ"],
- "djjdjr": [
- ["deleteCount", "plural", { "one": ["Ďēĺēţē"], "other": ["Ďēĺēţē ", "#", " ĩţēḿś"] }]
- ],
"dprWmL": ["Àńćĥōŕ ĩń ţĥĩś ƥàĝē"],
"dr1vFs": ["Ŕēƥĺàćē àĺĺ ḿàţćĥēś"],
"drzzZw": ["Ƥŕēvĩēŵ ţàƀś"],
@@ -2569,6 +2574,7 @@
"fiMNLl": ["Śŷńć śēţţĩńĝś ńōţ ŷēţ ĺōàďēď — ţŕŷ àĝàĩń ĩń à ḿōḿēńţ"],
"fj5YiP": ["Ďōŵńĺōàďś à ƒŕēśĥ ćōƥŷ ƒŕōḿ ĜĩţĤũƀ."],
"fnlBN4": ["Àũţō-àƥƥŕōvē śēţţĩńĝś ńōţ ŷēţ ĺōàďēď — ţŕŷ àĝàĩń ĩń à ḿōḿēńţ"],
+ "fo6CCk": ["ƥàńē ", ["0"]],
"fqSfXY": ["Ŕēƥĺàćē"],
"fru3T7": ["Ćōũĺď ńōţ ƒĩx ", ["0"], " ōƒ ", ["1"], " ƒĩĺēś."],
"ft-BOm": ["Ŕēƥōŕţ à ƀũĝ…"],
@@ -2635,6 +2641,7 @@
"gmJ0An": ["Ƒàĩĺēď ţō ōƥēń ƒōĺďēŕ."],
"goO4Ll": ["Ēďĩţōŕ śţàţũś ƀàŕ"],
"gp3I7-": ["ßēƒōŕē śŷńćĩńĝ, śēţ ŷōũŕ ĩďēńţĩţŷ ƒōŕ ĝĩţ ćōḿḿĩţś:"],
+ "gqk-3R": ["Ḿōvēď ", ["0"], " ţō ", ["destination"], "."],
"gtEbeW": ["Ĥĩĝĥĺĩĝĥţ"],
"gtGQ9S": ["Śţàŕţ ", ["agentName"], ", ", ["hint"]],
"gv5w9J": ["ōŵńēŕ/ŕēƥō, à ĝĩţ ŨŔĹ, ōŕ à ĺōćàĺ ƥàţĥ"],
@@ -2818,6 +2825,7 @@
"j_Z6g7": ["Śĥàŕēď ďēƒàũĺţ"],
"jbSG8V": ["Śĥōŵ Ƒĩĺēś (", ["sidebarShortcutLabel"], ")"],
"jdGUeI": ["Ćōũĺďń'ţ ćŕēàţē ţēḿƥĺàţē: ", ["error"]],
+ "jeCFV7": ["Ḿōvē ţō ńēŵ ƥàńē ŕĩĝĥţ"],
"jeJexw": ["Ćōũĺďń'ţ ƒĩńĩśĥ ĩńśţàĺĺĩńĝ ", ["0"], " — śēē ƀēĺōŵ."],
"jerqF0": ["Ĺōàďĩńĝ ƀŕàńćĥ śţàţē"],
"jhtG3I": [" Ŷōũŕ śēĺēćţĩōń ĥàś ƀēēń ŕēśţōŕēď."],
@@ -2827,6 +2835,7 @@
],
"jng7Ko": ["ćōńƒĺĩćţ"],
"jol95m": ["Ƒàĩĺēď ţō ōƥēń ƤŕōĴēćţ Ńàvĩĝàţōŕ."],
+ "jp6I-2": ["à ńēŵ ƥàńē ţō ţĥē ŕĩĝĥţ ōƒ ", ["0"]],
"jpctdh": ["Vĩēŵ"],
"jpoCue": [".ḿŷţēàḿ/śķĩĺĺś"],
"jqe7Yq": [
@@ -3080,6 +3089,7 @@
"mwMF9u": ["Ōƥēń ĆōďēḾĩŕŕōŕ śēàŕćĥ ĩń śōũŕćē ēďĩţōŕ ḿōďē."],
"mxGJVE": ["Śŵĩţćĥ ŵōŕķţŕēē…"],
"mxY24F": ["Ďũƥĺĩćàţē ţĥē ƒōćũśēď ƒĩĺē-ţŕēē ĩţēḿ ŵĥēń ƒōćũś ĩś ĩń ţĥē Ƒĩĺēś śĩďēƀàŕ."],
+ "n2XqGH": ["ēďĩţōŕ ƥàńē"],
"n2lRue": ["Ćōḿḿĩţ ōŕ śţàśĥ ćĥàńĝēś ţō śŵĩţćĥ:"],
"n3T3EE": ["Ĩńśţàĺĺēď ĩń ", ["label"], " — ćĺĩćķ ţō ŕēḿōvē"],
"n3wx1q": ["Ŕēśţōŕē ţō ţĥĩś vēŕśĩōń?"],
@@ -3160,7 +3170,6 @@
"o0bHtA": ["ßŷ ŌƥēńĶńōŵĺēďĝē"],
"o2yoFu": ["Ŕēvēàĺ ĩń Ƒĩńďēŕ, Ńō ŵōŕķśƥàćē"],
"o49mDZ": ["Ĺōàďĩńĝ ţĩḿēĺĩńē ĥĩśţōŕŷ"],
- "o4dcAf": ["Ŕēvēàĺ ĩń Ƒĩĺē Ēxƥĺōŕēŕ, ", ["hint"]],
"o5jB-D": ["Ćōĺĺàƥśē ƥàńēĺ"],
"o9CrsQ": ["ŕēśēàŕćĥ-ńōţē"],
"o9fPtM": ["Àũţō-ũƥďàţē ƒŕōḿ śōũŕćē"],
@@ -3223,6 +3232,7 @@
"p9sdCy": ["Ńēŵ ĩĝńōŕē ƥàţţēŕń"],
"pAgkuZ": ["Ŕēōƥēńĩńĝ \"", ["docName"], "\" ŵĩţĥ à ƒŕēśĥ ĺōćàĺ ćōĺĺàƀōŕàţĩōń ćàćĥē."],
"pBROkv": ["Ţĥàńķś ƒōŕ śũƀśćŕĩƀĩńĝ. Ŵàţćĥ ŷōũŕ ĩńƀōx ƒōŕ ƥŕōďũćţ ũƥďàţēś."],
+ "pCralD": ["Ḿōvē ţō ńēŵ ƥàńē ĺēƒţ"],
"pEQFsW": ["Ńō ḿàţćĥĩńĝ ƥŕōĴēćţś."],
"pFPzHA": ["ĒḿōĴĩ ƥĩćķēŕ"],
"pFRz_E": ["Ĺēàvē ţĥēśē ćōḿḿēńţś ōũţ ōƒ ţĥĩś ḿēśśàĝē"],
@@ -3819,7 +3829,6 @@
"zLak8b": ["Àćţĩvàţē ńēŵ ţàƀ"],
"zO-IiA": ["Ţĥē ţēŕḿĩńàĺ ĩśń'ţ àvàĩĺàƀĺē ĥēŕē — ţĥē ćōḿḿēńţś àŕē śţĩĺĺ ŵàĩţĩńĝ ţō śēńď."],
"zQBg2C": ["Ḿōvē ţĥē ćũŕŕēńţ ƀĺōćķ ũƥ ōŕ ďōŵń ōńē ƥōśĩţĩōń."],
- "zUhPuR": ["Ōƥēń ćōńţàĩńĩńĝ ƒōĺďēŕ, ", ["hint"]],
"zXj1rA": ["Śēàŕćĥ ƀŷ ḿēàńĩńĝ"],
"zYp8Sr": [
"À <0>Ḿōďĩƒĩēď</0> ƀàďĝē ḿàŕķś ŕũĺēś ŷōũŕ ćōńƒĩĝ śēţś ēxƥĺĩćĩţĺŷ — ďĩŕēćţĺŷ, ōŕ ĩńĥēŕĩţēď ţĥŕōũĝĥ <1>ēxţēńďś</1>. Ũńḿàŕķēď ŕũĺēś ķēēƥ ţĥēĩŕ ďēƒàũĺţ śţàţē."
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index 95a54d14b..8c2a1f58b 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -206,6 +206,11 @@ msgstr ""
msgid "{0, plural, one {# warning} other {# warnings}}"
msgstr ""
+#. placeholder {0}: deleteTargets.length
+#: src/components/FileTree.tsx
+msgid "{0, plural, one {Delete} other {Delete # items}}"
+msgstr ""
+
#. placeholder {0}: fileRows.length
#: src/components/CreatedItemsList.tsx
msgid "{0, plural, one {File} other {Files}}"
@@ -250,6 +255,11 @@ msgstr ""
msgid "{0} can't continue this conversation — the transcript is kept, but the agent session is gone."
msgstr ""
+#. placeholder {0}: activeData.label
+#: src/components/EditorWorkspace.tsx
+msgid "{0} is over {destination}."
+msgstr ""
+
#. placeholder {0}: resolvedTarget.displayName
#. placeholder {0}: target.displayName
#: src/comments/use-comment-delivery.ts
@@ -303,6 +313,11 @@ msgstr ""
msgid "{0} total"
msgstr ""
+#. placeholder {0}: activeData.label
+#: src/components/EditorWorkspace.tsx
+msgid "{0} was not moved."
+msgstr ""
+
#. placeholder {0}: share.owner
#. placeholder {1}: share.repo
#. placeholder {2}: shareTargetPath(share.target)
@@ -442,10 +457,6 @@ msgstr ""
msgid "{days}d ago"
msgstr ""
-#: src/components/FileTree.tsx
-msgid "{deleteCount, plural, one {Delete} other {Delete # items}}"
-msgstr ""
-
#: src/editor/extensions/JsxComponentView.tsx
msgid "{descriptorLabel} — render error, source editable below"
msgstr ""
@@ -888,6 +899,16 @@ msgstr ""
msgid "A network problem or GitHub outage interrupted the clone."
msgstr ""
+#. placeholder {0}: paneLabel(data.paneId)
+#: src/components/EditorWorkspace.tsx
+msgid "a new pane to the left of {0}"
+msgstr ""
+
+#. placeholder {0}: paneLabel(data.paneId)
+#: src/components/EditorWorkspace.tsx
+msgid "a new pane to the right of {0}"
+msgstr ""
+
#: src/components/settings/SettingsDialogErrorBoundary.tsx
#: src/components/TerminalGate.tsx
msgid "A newer version may have been deployed since this tab opened."
@@ -1870,6 +1891,7 @@ msgstr ""
#: src/components/CreateProjectDialog.tsx
#: src/components/DeleteConfirmationDialog.tsx
#: src/components/EnableSyncConfirmDialog.tsx
+#: src/components/FileTargetRenameDialog.tsx
#: src/components/FrontmatterRow.tsx
#: src/components/ImportSkillForm.tsx
#: src/components/InstallInClaudeDesktopDialog.tsx
@@ -1908,6 +1930,11 @@ msgstr ""
msgid "Cancelled"
msgstr ""
+#. placeholder {0}: activeData.label
+#: src/components/EditorWorkspace.tsx
+msgid "Cancelled moving {0}."
+msgstr ""
+
#: src/editor/image-upload/index.ts
msgid "Cannot upload: no document is open"
msgstr ""
@@ -2281,7 +2308,7 @@ msgstr ""
#: src/components/AppMenubar.tsx
#: src/components/command-palette-commands.ts
#: src/components/FileSidebar.tsx
-#: src/components/FileTree.tsx
+#: src/components/FileTargetMenuItems.tsx
msgid "Collapse all"
msgstr ""
@@ -2484,6 +2511,7 @@ msgstr ""
msgid "Connect the AI tools you use to this specific project. These files live in the project folder, so anyone who opens it gets the same setup."
msgstr ""
+#: src/components/EditorTabTargetMenuItems.tsx
#: src/components/FileSidebar.tsx
#: src/components/FileTree.tsx
msgid "Connect this project to GitHub to share."
@@ -2605,7 +2633,7 @@ msgstr ""
msgid "Convert"
msgstr ""
-#: src/components/FileTree.tsx
+#: src/components/FileTargetMenuItems.tsx
msgid "Convert (delete original)"
msgstr ""
@@ -2639,6 +2667,7 @@ msgstr ""
msgid "Copied"
msgstr ""
+#: src/components/EditorTabTargetMenuItems.tsx
#: src/components/FileSidebar.tsx
#: src/components/FileTree.tsx
msgid "Copied full path"
@@ -2648,6 +2677,7 @@ msgstr ""
msgid "Copied path"
msgstr ""
+#: src/components/EditorTabTargetMenuItems.tsx
#: src/components/FileSidebar.tsx
#: src/components/FileTree.tsx
msgid "Copied relative path"
@@ -2716,7 +2746,7 @@ msgid "Copy full path, No workspace"
msgstr ""
#: src/components/AppMenubar.tsx
-#: src/components/FileTree.tsx
+#: src/components/FileTargetMenuItems.tsx
msgid "Copy path"
msgstr ""
@@ -2760,11 +2790,13 @@ msgstr ""
msgid "Could not construct share URL."
msgstr ""
+#: src/components/EditorTabTargetMenuItems.tsx
#: src/components/FileSidebar.tsx
#: src/components/FileTree.tsx
msgid "Could not copy full path"
msgstr ""
+#: src/components/EditorTabTargetMenuItems.tsx
#: src/components/FileSidebar.tsx
#: src/components/FileTree.tsx
msgid "Could not copy relative path"
@@ -3523,6 +3555,7 @@ msgstr ""
#: src/components/acp/ThreadHistoryMenu.tsx
#: src/components/DeleteConfirmationDialog.tsx
+#: src/components/FileTargetMenuItems.tsx
#: src/components/skill-actions.tsx
#: src/components/TemplateRow.tsx
#: src/editor/extensions/JsxComponentView.tsx
@@ -3970,7 +4003,7 @@ msgstr ""
#: src/components/AppMenubar.tsx
#: src/components/command-palette-commands.ts
-#: src/components/FileTree.tsx
+#: src/components/FileTargetMenuItems.tsx
#: src/components/skill-actions.tsx
msgid "Duplicate"
msgstr ""
@@ -4127,6 +4160,10 @@ msgstr ""
msgid "Editor mode"
msgstr ""
+#: src/components/EditorWorkspace.tsx
+msgid "editor pane"
+msgstr ""
+
#: src/lib/keyboard-shortcuts.ts
msgid "Editor selection"
msgstr ""
@@ -4387,7 +4424,7 @@ msgstr ""
#: src/components/AppMenubar.tsx
#: src/components/command-palette-commands.ts
#: src/components/FileSidebar.tsx
-#: src/components/FileTree.tsx
+#: src/components/FileTargetMenuItems.tsx
msgid "Expand all"
msgstr ""
@@ -5088,7 +5125,7 @@ msgid "Full guide"
msgstr ""
#: src/components/AppMenubar.tsx
-#: src/components/FileTree.tsx
+#: src/components/FileTargetMenuItems.tsx
msgid "Full path"
msgstr ""
@@ -5309,6 +5346,7 @@ msgstr ""
msgid "Helps your coding agent recognize OpenKnowledge projects and route reads and writes through it."
msgstr ""
+#: src/components/EditorTabTargetMenuItems.tsx
#: src/components/FileTree.tsx
msgid "Hidden “{basename}”"
msgstr ""
@@ -5318,6 +5356,7 @@ msgstr ""
msgid "Hidden files"
msgstr ""
+#: src/components/EditorTabTargetMenuItems.tsx
#: src/components/FileTree.tsx
msgid "Hidden folder “{basename}”"
msgstr ""
@@ -5356,6 +5395,7 @@ msgstr ""
msgid "Hide files and folders from your knowledge base. Hidden items don’t appear in the file tree, search, or AI tools. <0>Learn more about patterns</0>."
msgstr ""
+#: src/components/EditorTabTargetMenuItems.tsx
#: src/components/FileTree.tsx
msgid "Hide folder"
msgstr ""
@@ -5403,6 +5443,7 @@ msgstr ""
msgid "Hide these comments"
msgstr ""
+#: src/components/EditorTabTargetMenuItems.tsx
#: src/components/FileTree.tsx
msgid "Hide this file"
msgstr ""
@@ -5527,7 +5568,7 @@ msgstr ""
msgid "Import"
msgstr ""
-#: src/components/FileTree.tsx
+#: src/components/FileTargetMenuItems.tsx
msgid "Import as template"
msgstr ""
@@ -5951,7 +5992,11 @@ msgstr ""
msgid "Keep my version"
msgstr ""
-#: src/components/FileTree.tsx
+#: src/components/EditorTabs.tsx
+msgid "Keep open"
+msgstr ""
+
+#: src/components/FileTargetMenuItems.tsx
msgid "Keep original file"
msgstr ""
@@ -6299,6 +6344,7 @@ msgstr ""
msgid "Make this the source — the skill's real folder moves here"
msgstr ""
+#: src/components/EditorTabTargetMenuItems.tsx
#: src/components/FileTree.tsx
msgid "Manage hidden files in Settings → Ignore patterns."
msgstr ""
@@ -6528,6 +6574,14 @@ msgstr ""
msgid "Move to {0}?"
msgstr ""
+#: src/components/EditorTabs.tsx
+msgid "Move to new pane left"
+msgstr ""
+
+#: src/components/EditorTabs.tsx
+msgid "Move to new pane right"
+msgstr ""
+
#: src/lib/keyboard-shortcuts.ts
msgid "Move to the next CodeMirror lint diagnostic."
msgstr ""
@@ -6559,6 +6613,11 @@ msgstr ""
msgid "Moved \"{0}\" to {1}"
msgstr ""
+#. placeholder {0}: activeData.label
+#: src/components/EditorWorkspace.tsx
+msgid "Moved {0} to {destination}."
+msgstr ""
+
#. placeholder {0}: moved.label
#. placeholder {1}: moved.position
#. placeholder {2}: moved.total
@@ -6566,6 +6625,14 @@ msgstr ""
msgid "Moved {0} to position {1} of {2}"
msgstr ""
+#: src/components/EditorTabs.tsx
+msgid "Moved {label} to a new pane on the left."
+msgstr ""
+
+#: src/components/EditorTabs.tsx
+msgid "Moved {label} to a new pane on the right."
+msgstr ""
+
#: src/components/FolderTimelineCard.tsx
msgid "moved template"
msgstr ""
@@ -6597,6 +6664,7 @@ msgid "name"
msgstr ""
#: src/components/AuthModal.tsx
+#: src/components/FileTargetRenameDialog.tsx
#: src/components/FolderOverview.tsx
#: src/components/NewSkillDialog.tsx
#: src/components/SkillRenameDialog.tsx
@@ -6608,10 +6676,6 @@ msgstr ""
msgid "Name (e.g. {login})"
msgstr ""
-#: src/components/EditorTabs.tsx
-msgid "Name can’t be empty, \".\", \"..\", or contain / or \\"
-msgstr ""
-
#: src/components/NewItemDialog.tsx
#: src/components/NewSkillDialog.tsx
msgid "Name cannot be empty"
@@ -6651,7 +6715,6 @@ msgstr ""
msgid "Network error - {kind} \"{createdPath}\" still exists on disk"
msgstr ""
-#: src/components/EditorTabs.tsx
#: src/components/FileTree.tsx
#: src/components/NewItemDialog.tsx
msgid "Network error — please try again"
@@ -6695,7 +6758,7 @@ msgstr ""
#: src/components/AppMenubar.tsx
#: src/components/command-palette-commands.ts
#: src/components/FileSidebar.tsx
-#: src/components/FileTree.tsx
+#: src/components/FileTargetMenuItems.tsx
#: src/components/NewItemDialog.tsx
#: src/components/skill-actions.tsx
#: src/components/SkillsTree.tsx
@@ -6718,7 +6781,7 @@ msgstr ""
#: src/components/AppMenubar.tsx
#: src/components/command-palette-commands.ts
#: src/components/FileSidebar.tsx
-#: src/components/FileTree.tsx
+#: src/components/FileTargetMenuItems.tsx
#: src/components/NewItemDialog.tsx
#: src/lib/keyboard-shortcuts.ts
msgid "New folder"
@@ -6730,7 +6793,7 @@ msgstr ""
#: src/components/command-palette-commands.ts
#: src/components/FileSidebar.tsx
-#: src/components/FileTree.tsx
+#: src/components/FileTargetMenuItems.tsx
msgid "New from template"
msgstr ""
@@ -7143,6 +7206,7 @@ msgstr ""
msgid "No templates yet. Add one to give new docs in this folder a ready-made starting point."
msgstr ""
+#: src/components/EditorTabTargetMenuItems.tsx
#: src/components/FileSidebar.tsx
#: src/components/FileTree.tsx
#: src/components/handoff/OpenInAgentContextSubmenu.tsx
@@ -7442,14 +7506,11 @@ msgstr ""
msgid "Open comment"
msgstr ""
+#: src/components/EditorTabTargetMenuItems.tsx
#: src/components/FileTree.tsx
msgid "Open containing folder"
msgstr ""
-#: src/components/FileTree.tsx
-msgid "Open containing folder, {hint}"
-msgstr ""
-
#: src/components/PropertyWidgets.tsx
msgid "Open date picker for {keyName}"
msgstr ""
@@ -7844,6 +7905,11 @@ msgstr ""
msgid "Pan up"
msgstr ""
+#. placeholder {0}: position + 1
+#: src/components/EditorWorkspace.tsx
+msgid "pane {0}"
+msgstr ""
+
#: src/lib/keyboard-shortcuts.ts
msgid "Paragraph"
msgstr ""
@@ -8018,6 +8084,12 @@ msgstr ""
msgid "Pick up where you left off"
msgstr ""
+#. placeholder {0}: data.label
+#. placeholder {1}: paneLabel(data.paneId)
+#: src/components/EditorWorkspace.tsx
+msgid "Picked up {0} from {1}."
+msgstr ""
+
#: src/components/EditorTabs.tsx
msgid "Pin tab"
msgstr ""
@@ -8081,6 +8153,10 @@ msgstr ""
msgid "Preparing to uninstall OpenKnowledge"
msgstr ""
+#: src/components/EditorWorkspace.tsx
+msgid "Press Space to pick up a tab. Use the arrow keys to move it within a tab strip, then press Space or Enter to drop it. Press Shift+F10 or the Menu key to open the tab context menu for split, close, pin, and other tab actions."
+msgstr ""
+
#: src/components/settings/CustomThemeEditor.tsx
msgid "Press the sun or moon on “Custom” above to use this scheme."
msgstr ""
@@ -8462,7 +8538,7 @@ msgid "Reject"
msgstr ""
#: src/components/AppMenubar.tsx
-#: src/components/FileTree.tsx
+#: src/components/FileTargetMenuItems.tsx
msgid "Relative path"
msgstr ""
@@ -8623,7 +8699,8 @@ msgstr ""
#: src/components/AppMenubar.tsx
#: src/components/command-palette-commands.ts
-#: src/components/FileTree.tsx
+#: src/components/FileTargetMenuItems.tsx
+#: src/components/FileTargetRenameDialog.tsx
#: src/components/skill-actions.tsx
#: src/components/SkillFileRenameDialog.tsx
#: src/components/SkillRenameDialog.tsx
@@ -8639,10 +8716,6 @@ msgstr ""
msgid "Rename {keyName}"
msgstr ""
-#: src/components/EditorTabs.tsx
-msgid "Rename {label}"
-msgstr ""
-
#. placeholder {0}: result.error
#: src/components/SkillFileRenameDialog.tsx
msgid "Rename failed: {0}"
@@ -8660,10 +8733,6 @@ msgstr ""
msgid "Rename succeeded but the sidebar may be out of date — refresh to resync"
msgstr ""
-#: src/components/EditorTabs.tsx
-msgid "Rename succeeded but the tabstrip may be out of date — refresh to resync"
-msgstr ""
-
#. placeholder {0}: docLeaf(descriptor.from)
#. placeholder {1}: docLeaf(descriptor.to)
#: src/components/TimelinePanel.tsx
@@ -9000,16 +9069,14 @@ msgstr ""
msgid "Reused if it already exists, created if not."
msgstr ""
+#: src/components/EditorTabTargetMenuItems.tsx
#: src/components/FileTree.tsx
msgid "Reveal in File Explorer"
msgstr ""
-#: src/components/FileTree.tsx
-msgid "Reveal in File Explorer, {hint}"
-msgstr ""
-
#: src/components/BugReportHistory.tsx
#: src/components/command-palette-commands.ts
+#: src/components/EditorTabTargetMenuItems.tsx
#: src/components/FileSidebar.tsx
#: src/components/FileTree.tsx
#: src/components/ReportBugDialogBody.tsx
@@ -9017,10 +9084,6 @@ msgstr ""
msgid "Reveal in Finder"
msgstr ""
-#: src/components/FileTree.tsx
-msgid "Reveal in Finder, {hint}"
-msgstr ""
-
#: src/components/FileSidebar.tsx
msgid "Reveal in Finder, No workspace"
msgstr ""
@@ -9103,6 +9166,7 @@ msgid "Sandboxed HTML embed — write HTML, see the rendered preview live."
msgstr ""
#: src/components/AuthModal.tsx
+#: src/components/FileTargetRenameDialog.tsx
#: src/components/settings/SearchSection.tsx
#: src/components/settings/ThemePreviewCanvas.tsx
#: src/editor/components/CodePreviewEditModal.tsx
@@ -9605,7 +9669,7 @@ msgid "Setup OpenKnowledge in this folder?"
msgstr ""
#: src/components/FileSidebar.tsx
-#: src/components/FileTree.tsx
+#: src/components/FileTargetMenuItems.tsx
#: src/components/ShareButton.tsx
msgid "Share"
msgstr ""
@@ -9887,7 +9951,6 @@ msgid "Skill discovery powered by <0>skills.sh</0>"
msgstr ""
#: src/components/command-palette-commands.ts
-#: src/components/EditorTabs.tsx
#: src/components/FileSidebar.tsx
#: src/components/FilesSkillsToggle.tsx
#: src/components/settings/SettingsDialogShell.tsx
diff --git a/packages/app/tests/stress/blank-line-preservation.e2e.ts b/packages/app/tests/stress/blank-line-preservation.e2e.ts
index 4d0c30f7f..403231f39 100644
--- a/packages/app/tests/stress/blank-line-preservation.e2e.ts
+++ b/packages/app/tests/stress/blank-line-preservation.e2e.ts
@@ -53,8 +53,18 @@ test.describe('blank lines typed in the visual editor', () => {
test('survive a source-mode round trip and a reload', async ({ page }) => {
// Three Enters at the end of the first paragraph: three empty paragraphs,
// i.e. three blank lines the user means to keep.
- await page.locator('.ProseMirror:not(.composer-prosemirror) p').first().click();
- await page.keyboard.press('End');
+ const firstParagraph = page
+ .locator('.ProseMirror:not(.composer-prosemirror)')
+ .getByText('Above.', { exact: true });
+ await firstParagraph.evaluate((paragraph) => {
+ paragraph.closest<HTMLElement>('.ProseMirror')?.focus();
+ const selection = window.getSelection();
+ const range = document.createRange();
+ range.selectNodeContents(paragraph);
+ range.collapse(false);
+ selection?.removeAllRanges();
+ selection?.addRange(range);
+ });
await page.keyboard.press('Enter');
await page.keyboard.press('Enter');
await page.keyboard.press('Enter');
diff --git a/packages/app/tests/stress/docs-open.e2e.ts b/packages/app/tests/stress/docs-open.e2e.ts
index 4a3c50a82..3369c562c 100644
--- a/packages/app/tests/stress/docs-open.e2e.ts
+++ b/packages/app/tests/stress/docs-open.e2e.ts
@@ -161,32 +161,37 @@ test.describe('docs-open — hybrid navigation UX', () => {
// Pre-assertion: small.md is currently active in the sidebar.
await expect(sidebarItem(page, 'small.md')).toHaveAttribute('aria-selected', 'true');
- // Install an in-page timer that observes the aria-selected mutation so we
- // measure wall-clock time from click to shell-snap — Playwright's own
- // poll intervals (50-200ms) would round up our measurement and hide
- // subframe regressions. MutationObserver fires synchronously after the
- // microtask that flips the attribute, so the delta captures exactly
- // "click dispatch → React commit of new activeDocName".
- await page.evaluate(() => {
+ // Resolve Playwright's actionability work before timing so scrolling and
+ // locator stability do not count against the shell response budget.
+ await bigRow.click({ trial: true });
+
+ // Install an in-page timer that starts on the real browser click and
+ // observes the row's aria-selected mutation. Starting from the trusted
+ // event excludes Playwright's protocol latency while preserving the
+ // application's actual navigation path.
+ await bigRow.evaluate((target) => {
window.__f0Result = null;
- const root = document.querySelector('file-tree-container')?.shadowRoot;
- if (!root) return;
- const start = performance.now();
+ if (!(target instanceof HTMLElement)) return;
+ window.__f0Start = undefined;
const observer = new MutationObserver(() => {
- const current = root.querySelector('[aria-selected="true"]');
- if (current?.getAttribute('aria-label') === 'big.md') {
+ const start = window.__f0Start;
+ if (target.getAttribute('aria-selected') === 'true' && start !== undefined) {
window.__f0Result = { shellMs: performance.now() - start };
observer.disconnect();
}
});
- observer.observe(root, {
- subtree: true,
+ observer.observe(target, {
attributes: true,
attributeFilter: ['aria-selected'],
});
- window.__f0Start = start;
+ window.addEventListener(
+ 'click',
+ () => {
+ window.__f0Start = performance.now();
+ },
+ { capture: true, once: true },
+ );
});
-
await bigRow.click();
// Poll for the shell-snap result; the MutationObserver fills it as soon
diff --git a/packages/app/tests/stress/editor-split-view.e2e.ts b/packages/app/tests/stress/editor-split-view.e2e.ts
new file mode 100644
index 000000000..1a4b9fa08
--- /dev/null
+++ b/packages/app/tests/stress/editor-split-view.e2e.ts
@@ -0,0 +1,613 @@
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { Locator, Page } from '@playwright/test';
+import { expect, test, waitForActiveProviderSynced } from './_helpers';
+
+const WIDE_VIEWPORT = { width: 2400, height: 900 } as const;
+const MIN_EDITOR_PANE_WIDTH = 300;
+
+function testId(): string {
+ return randomUUID().slice(0, 8);
+}
+
+function paneTabs(page: Page): Locator {
+ return page.locator('[data-editor-header-tabs] [data-editor-pane-tabs]');
+}
+
+async function paneIds(page: Page): Promise<string[]> {
+ return paneTabs(page).evaluateAll((strips) =>
+ strips.flatMap((strip) => {
+ const paneId = strip.getAttribute('data-editor-pane-tabs');
+ return paneId ? [paneId] : [];
+ }),
+ );
+}
+
+function paneRoot(page: Page, paneId: string): Locator {
+ return page.locator(`section[data-editor-pane-id="${paneId}"]`);
+}
+
+async function paneWidths(page: Page): Promise<number[]> {
+ return Promise.all(
+ (await paneIds(page)).map(
+ async (paneId) => (await paneRoot(page, paneId).boundingBox())?.width ?? 0,
+ ),
+ );
+}
+
+async function expectHeaderGroupsAlignedWithPanes(page: Page): Promise<void> {
+ await expect
+ .poll(() =>
+ page.evaluate(() => {
+ const groups = Array.from(
+ document.querySelectorAll<HTMLElement>('[data-editor-pane-tab-group]'),
+ );
+ const groupTops = groups.map((group) => group.getBoundingClientRect().top);
+ const deltas = groups.flatMap((group) => {
+ const paneId = group
+ .querySelector<HTMLElement>('[data-editor-pane-tabs]')
+ ?.getAttribute('data-editor-pane-tabs');
+ const pane = paneId
+ ? document.querySelector<HTMLElement>(`section[data-editor-pane-id="${paneId}"]`)
+ : null;
+ if (!pane) return [Number.POSITIVE_INFINITY];
+
+ const groupRect = group.getBoundingClientRect();
+ const paneRect = pane.getBoundingClientRect();
+ return [
+ Math.abs(groupRect.left - paneRect.left),
+ Math.abs(groupRect.right - paneRect.right),
+ Math.abs(groupRect.width - paneRect.width),
+ ];
+ });
+ const topDelta = groupTops.length > 0 ? Math.max(...groupTops) - Math.min(...groupTops) : 0;
+ return Math.max(topDelta, ...deltas);
+ }),
+ )
+ .toBeLessThanOrEqual(1);
+}
+
+function tabInPane(page: Page, paneId: string, tabId: string): Locator {
+ return page
+ .locator(`[data-editor-pane-tabs="${paneId}"]`)
+ .locator(`[data-editor-tab-sortable][data-editor-tab-id="${tabId}"]`);
+}
+
+function editorForDoc(page: Page, docName: string): Locator {
+ return page
+ .locator(`[data-editor-activity-mount][data-doc-name="${docName}"]`)
+ .locator('.ProseMirror:not(.composer-prosemirror)');
+}
+
+function sourceEditorForDoc(page: Page, docName: string): Locator {
+ return page
+ .locator(`[data-editor-activity-mount][data-doc-name="${docName}"]`)
+ .locator('.cm-content');
+}
+
+async function openDocFromSidebar(page: Page, docName: string): Promise<void> {
+ await page
+ .locator('[data-slot="sidebar-container"]')
+ .getByRole('treeitem', { name: `${docName}.md`, exact: true })
+ .click();
+ await waitForActiveProviderSynced(page);
+ const tab = page.locator(
+ `[data-editor-pane-focused] [data-editor-tab-sortable][data-editor-tab-id="${docName}"]`,
+ );
+ if ((await tab.getAttribute('data-preview-tab')) === 'true') {
+ await tab.click({ button: 'right' });
+ await page.getByTestId('editor-tab-context-keep-open').click();
+ }
+}
+
+async function dragTabToPaneEdge(
+ page: Page,
+ tab: Locator,
+ targetPaneId: string,
+ side: 'left' | 'right',
+): Promise<void> {
+ const tabBox = await tab.boundingBox();
+ expect(tabBox).not.toBeNull();
+ if (!tabBox) return;
+
+ const startX = tabBox.x + tabBox.width / 2;
+ const startY = tabBox.y + tabBox.height / 2;
+ await page.mouse.move(startX, startY);
+ await page.mouse.down();
+ await page.mouse.move(startX + 12, startY, { steps: 2 });
+
+ const edge = paneRoot(page, targetPaneId).locator(`[data-pane-edge="${side}"]`);
+ await expect(edge).toBeAttached();
+ const edgeBox = await edge.boundingBox();
+ expect(edgeBox).not.toBeNull();
+ if (!edgeBox) {
+ await page.mouse.up();
+ return;
+ }
+
+ await page.mouse.move(edgeBox.x + edgeBox.width / 2, edgeBox.y + edgeBox.height / 2, {
+ steps: 8,
+ });
+ await expect(edge).toHaveAttribute('data-pane-drop-side', side);
+ await expect(edge).toBeVisible();
+ await page.mouse.up();
+}
+
+async function dragTabToPaneCenter(page: Page, tab: Locator, targetPaneId: string): Promise<void> {
+ const tabBox = await tab.boundingBox();
+ expect(tabBox).not.toBeNull();
+ if (!tabBox) return;
+
+ const startX = tabBox.x + tabBox.width / 2;
+ const startY = tabBox.y + tabBox.height / 2;
+ await page.mouse.move(startX, startY);
+ await page.mouse.down();
+ await page.mouse.move(startX + 12, startY, { steps: 2 });
+
+ const tabStripBox = await page.locator(`[data-editor-pane-tabs="${targetPaneId}"]`).boundingBox();
+ expect(tabStripBox).not.toBeNull();
+ if (!tabStripBox) {
+ await page.mouse.up();
+ return;
+ }
+
+ const targetX = tabStripBox.x + tabStripBox.width / 2;
+ const targetY = tabStripBox.y + tabStripBox.height / 2;
+ await page.mouse.move(targetX - 1, targetY, { steps: 8 });
+ await page.mouse.move(targetX, targetY);
+ await expect(page.locator('[data-pane-drop-side]')).toHaveCount(0);
+ await page.mouse.up();
+}
+
+async function readDocument(page: Page, docName: string): Promise<string> {
+ const response = await page.request.get(`/api/document?docName=${encodeURIComponent(docName)}`);
+ if (!response.ok()) return '';
+ const result = (await response.json()) as { content?: string };
+ return result.content ?? '';
+}
+
+async function portalGeneration(page: Page, docName: string): Promise<string> {
+ return page.evaluate((name) => {
+ const element = document.querySelector(`[data-ok-editor-portal="${name}"]`);
+ if (!element) return 'absent';
+ const key = '__okSplitPortalGenerations';
+ const testWindow = window as unknown as Record<string, unknown>;
+ let generations = testWindow[key] as WeakMap<Element, string> | undefined;
+ if (!generations) {
+ generations = new WeakMap<Element, string>();
+ testWindow[key] = generations;
+ }
+ const existing = generations.get(element);
+ if (existing) return existing;
+ const generation = `generation-${Math.random().toString(36).slice(2)}`;
+ generations.set(element, generation);
+ return generation;
+ }, docName);
+}
+
+test.describe('vertical editor splits', () => {
+ test.afterEach(({ workerServer }) => {
+ writeFileSync(join(workerServer.contentDir, '.ok', 'config.yml'), '', 'utf-8');
+ });
+
+ test('pointer edge splits create four live, isolated editors and restore their layout', async ({
+ page,
+ api,
+ }) => {
+ const suffix = testId();
+ const docs = ['alpha', 'bravo', 'charlie', 'delta'].map((label) => ({
+ name: `split-${label}-${suffix}`,
+ markdown: `# ${label}-${suffix}\n\n${label} body`,
+ }));
+ await api.seedDocs(docs);
+ await page.setViewportSize(WIDE_VIEWPORT);
+ await page.goto(`/#/${docs[0].name}`);
+ await waitForActiveProviderSynced(page);
+ await expect(editorForDoc(page, docs[0].name)).toBeVisible();
+ await expect(page.getByRole('button', { name: 'Share doc' })).toBeVisible();
+
+ for (const doc of docs.slice(1)) {
+ await page
+ .locator('[data-editor-pane-focused] [data-editor-pane-tabs]')
+ .getByTestId('editor-new-tab-button')
+ .click();
+ await openDocFromSidebar(page, doc.name);
+ const ids = await paneIds(page);
+ const focusedPaneId = ids.at(-1);
+ expect(focusedPaneId).toBeTruthy();
+ if (!focusedPaneId) return;
+ await dragTabToPaneEdge(
+ page,
+ tabInPane(page, focusedPaneId, doc.name),
+ focusedPaneId,
+ 'right',
+ );
+ await expect(paneTabs(page)).toHaveCount(ids.length + 1);
+ }
+
+ const splitPaneIds = await paneIds(page);
+ expect(splitPaneIds).toHaveLength(4);
+ await expect(page.locator('[data-editor-workspace-canvas]')).toHaveCSS(
+ 'min-width',
+ /1280px|100%/,
+ );
+ for (const doc of docs) {
+ await expect(editorForDoc(page, doc.name)).toBeVisible();
+ }
+ await expect(
+ page.locator('[data-editor-workspace] [data-editor-pane-resize-handle]'),
+ ).toHaveCount(3);
+ await expectHeaderGroupsAlignedWithPanes(page);
+
+ const uniqueToken = `isolated-${suffix}`;
+ const editedDoc = docs[1];
+ await editorForDoc(page, editedDoc.name).locator('p').last().click();
+ await page.keyboard.press('End');
+ await page.keyboard.type(` ${uniqueToken}`);
+ await expect.poll(() => readDocument(page, editedDoc.name)).toContain(uniqueToken);
+ for (const other of docs.filter((doc) => doc.name !== editedDoc.name)) {
+ await expect.poll(() => readDocument(page, other.name)).not.toContain(uniqueToken);
+ }
+
+ await expect.poll(() => windowHash(page)).toContain(editedDoc.name);
+ await expect(
+ page.locator('#panel-outline').getByRole('button', {
+ name: `${editedDoc.name.split('-')[1]}-${suffix}`,
+ exact: true,
+ }),
+ ).toBeVisible();
+
+ const generationsBefore = Object.fromEntries(
+ await Promise.all(
+ docs.map(async (doc) => [doc.name, await portalGeneration(page, doc.name)] as const),
+ ),
+ );
+ expect(Object.values(generationsBefore)).not.toContain('absent');
+
+ const firstHandle = page
+ .locator('[data-editor-workspace] [data-editor-pane-resize-handle]')
+ .first();
+ const handleBox = await firstHandle.boundingBox();
+ expect(handleBox).not.toBeNull();
+ if (!handleBox) return;
+ const widthsBefore = await paneWidths(page);
+ await page.mouse.move(handleBox.x + handleBox.width / 2, handleBox.y + handleBox.height / 2);
+ await page.mouse.down();
+ await page.mouse.move(handleBox.x + 110, handleBox.y + handleBox.height / 2, { steps: 8 });
+ await expectHeaderGroupsAlignedWithPanes(page);
+ await page.mouse.up();
+ await expect
+ .poll(async () => {
+ const widths = await paneWidths(page);
+ return Math.round(widths[0] - widthsBefore[0]);
+ })
+ .toBeGreaterThan(30);
+ await expectHeaderGroupsAlignedWithPanes(page);
+
+ const widthsAfterResize = await paneWidths(page);
+ for (const doc of docs) {
+ expect(await portalGeneration(page, doc.name)).toBe(generationsBefore[doc.name]);
+ }
+ await expect
+ .poll(() =>
+ page.evaluate(() => {
+ const raw = localStorage.getItem(`ok-editor-tabs-v1:${window.location.origin}`);
+ if (!raw) return 0;
+ const session = JSON.parse(raw) as { panes?: unknown[] };
+ return session.panes?.length ?? 0;
+ }),
+ )
+ .toBe(4);
+
+ await page.reload();
+ await waitForActiveProviderSynced(page);
+ await expect(paneTabs(page)).toHaveCount(4);
+ await expectHeaderGroupsAlignedWithPanes(page);
+ const widthsAfterReload = await paneWidths(page);
+ expect(Math.abs(widthsAfterReload[0] - widthsAfterResize[0])).toBeLessThan(40);
+ await expect.poll(() => windowHash(page)).toContain(editedDoc.name);
+ for (const doc of docs) {
+ expect(await portalGeneration(page, doc.name)).not.toBe('absent');
+ }
+
+ await page.setViewportSize({ width: 1200, height: 800 });
+ await page.locator('[data-editor-workspace]').evaluate((workspace) => {
+ workspace.scrollLeft = 96;
+ workspace.dispatchEvent(new Event('scroll'));
+ });
+ await expectHeaderGroupsAlignedWithPanes(page);
+ });
+
+ test('diagonal pointer movement keeps the dragged tab visible before an edge split', async ({
+ page,
+ api,
+ }) => {
+ const docName = `split-vertical-drag-${testId()}`;
+ await api.seedDocs([{ name: docName, markdown: '# Vertical drag' }]);
+ await page.setViewportSize(WIDE_VIEWPORT);
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+
+ const [paneId] = await paneIds(page);
+ expect(paneId).toBeTruthy();
+ if (!paneId) return;
+
+ const tab = tabInPane(page, paneId, docName);
+ const tabBox = await tab.boundingBox();
+ expect(tabBox).not.toBeNull();
+ if (!tabBox) return;
+
+ const startX = tabBox.x + tabBox.width / 2;
+ const startY = tabBox.y + tabBox.height / 2;
+ await page.mouse.move(startX, startY);
+ await page.mouse.down();
+
+ try {
+ await page.mouse.move(startX + 12, startY, { steps: 2 });
+ await page.mouse.move(startX + 500, startY + 180, { steps: 8 });
+
+ const dragOverlay = page.getByTestId('editor-tab-drag-overlay');
+ await expect(dragOverlay).toBeVisible();
+ const draggedTabBox = await dragOverlay.boundingBox();
+ expect(draggedTabBox).not.toBeNull();
+ if (!draggedTabBox) return;
+ expect(draggedTabBox.y).toBeGreaterThan(tabBox.y + 100);
+
+ const edge = paneRoot(page, paneId).locator('[data-pane-edge="right"]');
+ const edgeBox = await edge.boundingBox();
+ expect(edgeBox).not.toBeNull();
+ if (!edgeBox) return;
+
+ await page.mouse.move(edgeBox.x + edgeBox.width / 2, edgeBox.y + edgeBox.height / 2, {
+ steps: 8,
+ });
+ await expect(edge).toHaveAttribute('data-pane-drop-side', 'right');
+ await expect(edge).toBeVisible();
+ } finally {
+ await page.mouse.up();
+ }
+ });
+
+ test('tabs retain a usable minimum width and scroll within a narrow pane', async ({
+ page,
+ api,
+ }) => {
+ const suffix = testId();
+ const docs = Array.from({ length: 6 }, (_, index) => ({
+ name: `shrink-tab-${index}-${suffix}`,
+ markdown: `# Shrink tab ${index}`,
+ }));
+ await api.seedDocs(docs);
+ await page.setViewportSize(WIDE_VIEWPORT);
+ await page.goto(`/#/${docs[0].name}`);
+ await waitForActiveProviderSynced(page);
+
+ for (const doc of docs.slice(1)) {
+ await page
+ .locator('[data-editor-pane-focused] [data-editor-pane-tabs]')
+ .getByTestId('editor-new-tab-button')
+ .click();
+ await openDocFromSidebar(page, doc.name);
+ }
+
+ await page.setViewportSize({ width: 900, height: 800 });
+ const paneStrip = paneTabs(page).first();
+ await expect(paneStrip.locator('[data-editor-tab-sortable]')).toHaveCount(docs.length);
+ const scrollViewport = paneStrip.locator('[data-editor-tab-scroll]');
+ const geometry = await scrollViewport.evaluate((element) => ({
+ clientWidth: element.clientWidth,
+ scrollWidth: element.scrollWidth,
+ tabWidths: Array.from(
+ element.querySelectorAll<HTMLElement>('[data-editor-tab-sortable]'),
+ (tab) => tab.getBoundingClientRect().width,
+ ),
+ }));
+
+ expect(geometry.scrollWidth).toBeGreaterThan(geometry.clientWidth + 1);
+ expect(Math.min(...geometry.tabWidths)).toBeGreaterThanOrEqual(128);
+
+ const scrolled = await scrollViewport.evaluate((element) => {
+ element.scrollLeft = element.scrollWidth;
+ const lastTab = element.querySelector<HTMLElement>('[data-editor-tab-sortable]:last-child');
+ return {
+ scrollLeft: element.scrollLeft,
+ stripRight: element.getBoundingClientRect().right,
+ lastTabRight: lastTab?.getBoundingClientRect().right ?? Number.POSITIVE_INFINITY,
+ };
+ });
+ expect(scrolled.scrollLeft).toBeGreaterThan(0);
+ expect(scrolled.lastTabRight).toBeLessThanOrEqual(scrolled.stripRight + 1);
+ });
+
+ test('pane resizing stops before the unified header becomes unusable', async ({ page, api }) => {
+ const suffix = testId();
+ const [left, right] = [`minimum-left-${suffix}`, `minimum-right-${suffix}`];
+ await api.seedDocs([
+ { name: left, markdown: '# Left pane' },
+ { name: right, markdown: '# Right pane' },
+ ]);
+ await page.setViewportSize({ width: 2000, height: 800 });
+ await page.goto(`/#/${left}`);
+ await waitForActiveProviderSynced(page);
+
+ await page
+ .locator('[data-editor-pane-focused] [data-editor-pane-tabs]')
+ .getByTestId('editor-new-tab-button')
+ .click();
+ await openDocFromSidebar(page, right);
+
+ const [initialPaneId] = await paneIds(page);
+ expect(initialPaneId).toBeTruthy();
+ if (!initialPaneId) return;
+ await dragTabToPaneEdge(page, tabInPane(page, initialPaneId, right), initialPaneId, 'right');
+ await expect(paneTabs(page)).toHaveCount(2);
+
+ const handle = page.locator('[data-editor-workspace] [data-editor-pane-resize-handle]').first();
+ const handleBox = await handle.boundingBox();
+ const widthsBefore = await paneWidths(page);
+ expect(handleBox).not.toBeNull();
+ if (!handleBox) return;
+
+ await page.mouse.move(handleBox.x + handleBox.width / 2, handleBox.y + handleBox.height / 2);
+ await page.mouse.down();
+ await page.mouse.move(handleBox.x + 500, handleBox.y + handleBox.height / 2, { steps: 12 });
+ await page.mouse.up();
+
+ const widths = await paneWidths(page);
+ expect(widths[0] - widthsBefore[0]).toBeGreaterThan(200);
+ expect(Math.min(...widths)).toBeGreaterThanOrEqual(MIN_EDITOR_PANE_WIDTH - 1);
+ await expectHeaderGroupsAlignedWithPanes(page);
+ expect(
+ await paneRoot(page, initialPaneId).evaluate(
+ (element) => !element.getAttribute('class')?.includes('ring-'),
+ ),
+ ).toBe(true);
+ });
+
+ test('pointer drag moves a tab between existing panes without creating a split', async ({
+ page,
+ api,
+ }) => {
+ const suffix = testId();
+ const [first, second, third] = ['alpha', 'bravo', 'charlie'].map(
+ (label) => `move-${label}-${suffix}`,
+ );
+ await api.seedDocs([
+ { name: first, markdown: `# First ${suffix}` },
+ { name: second, markdown: `# Second ${suffix}` },
+ { name: third, markdown: `# Third ${suffix}` },
+ ]);
+ await page.setViewportSize(WIDE_VIEWPORT);
+ await page.goto(`/#/${first}`);
+ await waitForActiveProviderSynced(page);
+ await page
+ .locator('[data-editor-pane-focused] [data-editor-pane-tabs]')
+ .getByTestId('editor-new-tab-button')
+ .click();
+ await openDocFromSidebar(page, second);
+
+ const [initialPaneId] = await paneIds(page);
+ expect(initialPaneId).toBeTruthy();
+ if (!initialPaneId) return;
+ await dragTabToPaneEdge(page, tabInPane(page, initialPaneId, second), initialPaneId, 'right');
+ await expect(paneTabs(page)).toHaveCount(2);
+
+ const [leftPaneId, rightPaneId] = await paneIds(page);
+ expect(leftPaneId).toBeTruthy();
+ expect(rightPaneId).toBeTruthy();
+ if (!leftPaneId || !rightPaneId) return;
+ await editorForDoc(page, first).click();
+ await page
+ .locator('[data-editor-pane-focused] [data-editor-pane-tabs]')
+ .getByTestId('editor-new-tab-button')
+ .click();
+ await openDocFromSidebar(page, third);
+ await expect(tabInPane(page, leftPaneId, third)).toBeVisible();
+
+ await dragTabToPaneCenter(page, tabInPane(page, leftPaneId, third), rightPaneId);
+
+ await expect(paneTabs(page)).toHaveCount(2);
+ await expect(tabInPane(page, leftPaneId, third)).toHaveCount(0);
+ await expect(tabInPane(page, rightPaneId, third)).toBeVisible();
+ await expect(paneRoot(page, rightPaneId)).toHaveAttribute('data-editor-pane-focused', 'true');
+ await expect(editorForDoc(page, first)).toBeVisible();
+ await expect(editorForDoc(page, third)).toBeVisible();
+ await expect.poll(() => windowHash(page)).toContain(third);
+ });
+
+ test('keyboard split isolates source navigation and closing tabs leave an active home tab', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ const suffix = testId();
+ const first = `split-keyboard-a-${suffix}`;
+ const second = `split-keyboard-b-${suffix}`;
+ mkdirSync(join(workerServer.contentDir, '.ok'), { recursive: true });
+ writeFileSync(
+ join(workerServer.contentDir, '.ok', 'config.yml'),
+ 'contentRules:\n markdownlint:\n enabled: true\n',
+ 'utf-8',
+ );
+ await api.seedDocs([
+ { name: first, markdown: `# First ${suffix}\n\nfirst body` },
+ { name: second, markdown: `# Second ${suffix}\n\n\tindented with a hard tab` },
+ ]);
+ await page.setViewportSize(WIDE_VIEWPORT);
+ await page.goto(`/#/${first}`);
+ await waitForActiveProviderSynced(page);
+ await page
+ .locator('[data-editor-pane-focused] [data-editor-pane-tabs]')
+ .getByTestId('editor-new-tab-button')
+ .click();
+ await openDocFromSidebar(page, second);
+
+ const [initialPaneId] = await paneIds(page);
+ expect(initialPaneId).toBeTruthy();
+ if (!initialPaneId) return;
+ const secondTab = tabInPane(page, initialPaneId, second);
+ await secondTab.focus();
+ await secondTab.press('Shift+F10');
+ await page.getByTestId('editor-tab-context-split-right').click();
+ await expect(paneTabs(page)).toHaveCount(2);
+
+ await page.evaluate(() => {
+ localStorage.setItem('ok-editor-mode-v1', 'source');
+ });
+ await page.reload();
+ await waitForActiveProviderSynced(page);
+ await expect(sourceEditorForDoc(page, first)).toBeVisible();
+ await expect(sourceEditorForDoc(page, second)).toBeVisible();
+
+ await sourceEditorForDoc(page, second).click();
+ await expect.poll(() => windowHash(page)).toContain(second);
+ const firstActiveLineBefore = await sourceEditorForDoc(page, first)
+ .locator('xpath=ancestor::*[contains(@class,"cm-editor")][1]')
+ .locator('.cm-activeLine')
+ .textContent();
+
+ await page.locator('#tab-problems').click();
+ const firstProblem = page.locator('#panel-problems ul li button').first();
+ await expect(firstProblem).toBeVisible();
+ await firstProblem.click();
+ await expect
+ .poll(() =>
+ sourceEditorForDoc(page, second)
+ .locator('xpath=ancestor::*[contains(@class,"cm-editor")][1]')
+ .locator('.cm-activeLine')
+ .textContent(),
+ )
+ .toContain('indented with a hard tab');
+ expect(
+ await sourceEditorForDoc(page, first)
+ .locator('xpath=ancestor::*[contains(@class,"cm-editor")][1]')
+ .locator('.cm-activeLine')
+ .textContent(),
+ ).toBe(firstActiveLineBefore);
+
+ const ids = await paneIds(page);
+ const secondClose = page
+ .locator(`[data-editor-pane-tabs="${ids[1]}"]`)
+ .getByTestId('editor-tab-close-button');
+ await secondClose.click();
+ await expect(paneTabs(page)).toHaveCount(1);
+
+ const onlyPaneId = (await paneIds(page))[0];
+ await page
+ .locator(`[data-editor-pane-tabs="${onlyPaneId}"]`)
+ .getByTestId('editor-tab-close-button')
+ .click();
+ await expect(paneTabs(page)).toHaveCount(1);
+ const remainingTabs = page.locator(
+ `[data-editor-pane-tabs="${onlyPaneId}"] [data-editor-tab-sortable]`,
+ );
+ await expect(remainingTabs).toHaveCount(1);
+ await expect(remainingTabs).toHaveAttribute('data-active-tab', 'true');
+ await expect(remainingTabs.getByTestId('editor-new-tab-placeholder-button')).toBeVisible();
+ });
+});
+
+async function windowHash(page: Page): Promise<string> {
+ return page.evaluate(() => window.location.hash);
+}
diff --git a/packages/app/tests/stress/editor-tabs.e2e.ts b/packages/app/tests/stress/editor-tabs.e2e.ts
index 462939c2e..b9c48d4ac 100644
--- a/packages/app/tests/stress/editor-tabs.e2e.ts
+++ b/packages/app/tests/stress/editor-tabs.e2e.ts
@@ -84,7 +84,6 @@ async function installLocalTabSession(
state: {
openTabs: string[];
pinnedTabIds?: string[];
- activeDocName: string | null;
activeTabId: string | null;
},
) {
@@ -92,9 +91,18 @@ async function installLocalTabSession(
window.localStorage.setItem(
`ok-editor-tabs-v1:${window.location.origin}`,
JSON.stringify({
- pinnedTabIds: [],
- ...sessionState,
+ activeTabByMode: { files: null, skills: null },
updatedAt: '2026-05-12T00:00:00.000Z',
+ panes: [
+ {
+ id: 'pane-main',
+ openTabs: sessionState.openTabs,
+ pinnedTabIds: sessionState.pinnedTabIds ?? [],
+ activeTabId: sessionState.activeTabId,
+ size: 100,
+ },
+ ],
+ focusedPaneId: 'pane-main',
}),
);
}, state);
@@ -164,10 +172,13 @@ async function expectPersistedTabSession(
page.evaluate(() => {
const raw = window.localStorage.getItem(`ok-editor-tabs-v1:${window.location.origin}`);
if (!raw) return null;
- const parsed = JSON.parse(raw) as { openTabs?: unknown; activeTabId?: unknown };
+ const parsed = JSON.parse(raw) as {
+ panes?: Array<{ openTabs?: unknown; activeTabId?: unknown }>;
+ };
+ const pane = parsed.panes?.[0];
return {
- openTabs: Array.isArray(parsed.openTabs) ? parsed.openTabs : null,
- activeTabId: typeof parsed.activeTabId === 'string' ? parsed.activeTabId : null,
+ openTabs: Array.isArray(pane?.openTabs) ? pane.openTabs : null,
+ activeTabId: typeof pane?.activeTabId === 'string' ? pane.activeTabId : null,
};
}),
)
@@ -180,33 +191,36 @@ async function expectPersistedPinnedTabs(page: Page, expected: string[]) {
page.evaluate(() => {
const raw = window.localStorage.getItem(`ok-editor-tabs-v1:${window.location.origin}`);
if (!raw) return null;
- const parsed = JSON.parse(raw) as { pinnedTabIds?: unknown };
- return Array.isArray(parsed.pinnedTabIds) ? parsed.pinnedTabIds : null;
+ const parsed = JSON.parse(raw) as { panes?: Array<{ pinnedTabIds?: unknown }> };
+ const pinnedTabIds = parsed.panes?.[0]?.pinnedTabIds;
+ return Array.isArray(pinnedTabIds) ? pinnedTabIds : null;
}),
)
.toEqual(expected);
}
async function editorTabOrder(page: Page): Promise<string[]> {
- return page.locator('header div[aria-roledescription="sortable"]').evaluateAll((tabEls) =>
- tabEls.flatMap((tabEl) => {
- // Anchor on data-testids, not Lingui-wrapped accessible names — the
- // placeholder/close labels route through the i18n catalog. The primary
- // button's aria-label is the doc/folder/asset filename (not Lingui-routed),
- // so it stays the order key.
- if (tabEl.querySelector('[data-testid="editor-new-tab-placeholder-button"]')) {
- return ['new-tab'];
- }
- const primaryButton = [...tabEl.querySelectorAll('button[aria-label]')].find(
- (button) =>
- !button.matches(
- '[data-testid="editor-tab-close-button"], [data-testid="editor-tab-unpin-button"]',
- ),
- );
- const label = primaryButton?.getAttribute('aria-label');
- return label ? [label] : [];
- }),
- );
+ return page
+ .locator('[data-editor-pane-focused] [data-editor-pane-tabs] [data-editor-tab-sortable]')
+ .evaluateAll((tabEls) =>
+ tabEls.flatMap((tabEl) => {
+ // Anchor on data-testids, not Lingui-wrapped accessible names — the
+ // placeholder/close labels route through the i18n catalog. The primary
+ // button's aria-label is the doc/folder/asset filename (not Lingui-routed),
+ // so it stays the order key.
+ if (tabEl.querySelector('[data-testid="editor-new-tab-placeholder-button"]')) {
+ return ['new-tab'];
+ }
+ const primaryButton = [...tabEl.querySelectorAll('button[aria-label]')].find(
+ (button) =>
+ !button.matches(
+ '[data-testid="editor-tab-close-button"], [data-testid="editor-tab-unpin-button"]',
+ ),
+ );
+ const label = primaryButton?.getAttribute('aria-label');
+ return label ? [label] : [];
+ }),
+ );
}
async function expectDocumentListContainsAsset(baseURL: string, assetPath: string) {
@@ -370,7 +384,7 @@ test.describe('Editor tabs', () => {
.toEqual([firstLabel, 'new-tab', 'new-tab', selectedLabel]);
});
- test('sidebar folder click replaces the active file tab with the folder tab', async ({
+ test('sidebar folder click opens a preview beside the permanent file tab', async ({
page,
api,
workerServer,
@@ -397,12 +411,14 @@ test.describe('Editor tabs', () => {
await sidebarTreeItem(page, folder).click();
await expect(page).toHaveURL(new RegExp(`#/${folder}/$`));
- await expect(fileTabs).toHaveCount(0);
+ await expect(fileTabs).toHaveCount(1);
await expect(folderTabs).toHaveCount(1);
await expectActiveTab(folderTabs.first());
+ await expect(editorTabChrome(folderTabs.first())).toHaveAttribute('data-preview-tab', 'true');
+ await expect.poll(() => editorTabOrder(page)).toEqual([fileLabel, folderLabel]);
});
- test('sidebar asset click replaces the active file tab with an asset tab', async ({
+ test('sidebar asset click opens a preview beside the permanent file tab', async ({
page,
api,
workerServer,
@@ -423,50 +439,14 @@ test.describe('Editor tabs', () => {
await sidebarTreeItem(page, assetPath).click();
const assetTab = editorTabButtons(page, assetPath);
- await expect(docTab).toHaveCount(0);
+ await expect(docTab).toHaveCount(1);
await expect(assetTab).toHaveCount(1);
await expectActiveTab(assetTab.first());
- await expect.poll(() => editorTabOrder(page)).toEqual([assetPath]);
+ await expect(editorTabChrome(assetTab.first())).toHaveAttribute('data-preview-tab', 'true');
+ await expect.poll(() => editorTabOrder(page)).toEqual([docLabel, assetPath]);
await expect(page).toHaveURL(new RegExp(`#/__asset__/${assetPath.replace('.', '\\.')}$`));
});
- test('sidebar asset click focuses the existing asset tab when that asset is already open', async ({
- page,
- api,
- workerServer,
- }) => {
- test.skip(
- true,
- 'Asset setup currently times out before tab assertions; focus-existing behavior is covered by editor-tabs.test.ts.',
- );
- const id = testId();
- const docName = `asset-new-tab-doc-${id}`;
- const assetPath = `asset-new-tab-${id}.png`;
- const assetTabId = `\u0000asset:${assetPath}`;
-
- await seedReferencedAssetDoc(api, workerServer, docName, assetPath);
-
- await page.goto(`/#/__asset__/${assetPath}`);
- const assetTabs = editorTabButtons(page, assetPath);
- await expect(assetTabs).toHaveCount(1, { timeout: 10_000 });
- await expectActiveTab(assetTabs.first());
-
- await editorNewTabButton(page).click();
- await expect(activateNewTabButtons(page)).toHaveCount(1);
- await expectActiveTab(activateNewTabButtons(page).first());
-
- await sidebarTreeItem(page, assetPath).click();
-
- await expect(assetTabs).toHaveCount(1);
- await expect(activateNewTabButtons(page)).toHaveCount(0);
- await expect(activeEditorTabButtons(page, assetPath)).toHaveCount(1);
- await expect.poll(() => editorTabOrder(page)).toEqual([assetPath]);
- await expectPersistedTabSession(page, {
- openTabs: [assetTabId],
- activeTabId: assetTabId,
- });
- });
-
test('sidebar folder click focuses the existing folder tab when that folder is already open', async ({
page,
api,
@@ -552,7 +532,6 @@ test.describe('Editor tabs', () => {
await installLocalTabSession(page, {
openTabs: [fooDoc, barDoc],
- activeDocName: barDoc,
activeTabId: barDoc,
});
@@ -576,80 +555,43 @@ test.describe('Editor tabs', () => {
});
});
- test('refresh preserves a restored session where two tabs point at the same file', async ({
+ test('sidebar previews replace the previous preview and Keep open promotes it', async ({
page,
api,
}) => {
const id = testId();
- const fooDoc = `foo-refresh-${id}`;
- const barDoc = `bar-refresh-${id}`;
+ const fooDoc = `foo-preview-${id}`;
+ const barDoc = `bar-preview-${id}`;
+ const bazDoc = `baz-preview-${id}`;
const fooLabel = `${fooDoc}.md`;
const barLabel = `${barDoc}.md`;
- const duplicateFooTabId = `${fooDoc}\u0000doc-tab:1`;
+ const bazLabel = `${bazDoc}.md`;
await seedMarkdownDocs(api, [
- { name: fooDoc, markdown: `# Foo Refresh ${id}` },
- { name: barDoc, markdown: `# Bar Refresh ${id}` },
+ { name: fooDoc, markdown: `# Foo Preview ${id}` },
+ { name: barDoc, markdown: `# Bar Preview ${id}` },
+ { name: bazDoc, markdown: `# Baz Preview ${id}` },
]);
- // Two tabs pointing at the same file can only exist in a restored session
- // now (focus-in-place prevents creating a second one via the UI); assert the
- // legacy duplicate survives a reload.
- await installLocalTabSession(page, {
- openTabs: [fooDoc, barDoc, duplicateFooTabId],
- activeDocName: fooDoc,
- activeTabId: fooDoc,
- });
-
await page.goto(`/#/${fooDoc}`);
const fooTabs = editorTabButtons(page, fooLabel);
const barTabs = editorTabButtons(page, barLabel);
- await expect(fooTabs).toHaveCount(2, { timeout: 10_000 });
- await expect(barTabs).toHaveCount(1);
- await expectActiveTab(fooTabs.nth(0));
- await expectInactiveTab(fooTabs.nth(1));
- await expectPersistedTabSession(page, {
- openTabs: [fooDoc, barDoc, duplicateFooTabId],
- activeTabId: fooDoc,
- });
-
- await page.reload();
+ const bazTabs = editorTabButtons(page, bazLabel);
+ await expect(fooTabs).toHaveCount(1, { timeout: 10_000 });
- await expect(fooTabs).toHaveCount(2, { timeout: 10_000 });
+ await sidebarTreeItem(page, barLabel).click();
await expect(barTabs).toHaveCount(1);
- await expectActiveTab(fooTabs.nth(0));
- await expectInactiveTab(fooTabs.nth(1));
- await expectPersistedTabSession(page, {
- openTabs: [fooDoc, barDoc, duplicateFooTabId],
- activeTabId: fooDoc,
- });
- });
-
- test('renaming one duplicate file tab does not restyle the sibling duplicate tab', async ({
- page,
- api,
- }) => {
- const id = testId();
- const fooDoc = `foo-duplicate-rename-${id}`;
- const duplicateFooTabId = `${fooDoc}\u0000doc-tab:1`;
- const fooLabel = `${fooDoc}.md`;
-
- await seedMarkdownDocs(api, [{ name: fooDoc, markdown: `# Foo Duplicate Rename ${id}` }]);
+ await expect(editorTabChrome(barTabs.first())).toHaveAttribute('data-preview-tab', 'true');
- await installLocalTabSession(page, {
- openTabs: [fooDoc, duplicateFooTabId],
- activeDocName: fooDoc,
- activeTabId: fooDoc,
- });
-
- await page.goto(`/#/${fooDoc}`);
- const fooTabs = editorTabButtons(page, fooLabel);
- await expect(fooTabs).toHaveCount(2, { timeout: 10_000 });
+ await editorTabChrome(barTabs.first()).click({ button: 'right' });
+ await page.getByTestId('editor-tab-context-keep-open').click();
+ await expect(editorTabChrome(barTabs.first())).not.toHaveAttribute('data-preview-tab');
- await fooTabs.nth(0).dblclick();
-
- await expect(page.getByRole('main').getByTestId('editor-tab-rename-input')).toHaveCount(1);
+ await sidebarTreeItem(page, bazLabel).click();
await expect(fooTabs).toHaveCount(1);
+ await expect(barTabs).toHaveCount(1);
+ await expect(bazTabs).toHaveCount(1);
+ await expect(editorTabChrome(bazTabs.first())).toHaveAttribute('data-preview-tab', 'true');
});
test('tab click selects the already-open foo.md tab without rewriting the bar.md tab', async ({
@@ -710,7 +652,6 @@ test.describe('Editor tabs', () => {
]);
await installLocalTabSession(page, {
openTabs: [barDoc],
- activeDocName: barDoc,
activeTabId: barDoc,
});
@@ -740,36 +681,34 @@ test.describe('Editor tabs', () => {
await expectInactiveTab(editorTabButtons(page, helloLabel).first());
});
- test('clicking the second duplicate .mdx tab activates that exact tab instance', async ({
+ test('double-clicking a preview tab promotes it without entering rename mode', async ({
page,
api,
}) => {
const id = testId();
- const folder = `dup-${id}`;
+ const folder = `preview-rename-${id}`;
+ const baseDoc = `${folder}/base-${id}`;
const barDoc = `${folder}/bar-${id}`;
+ const baseLabel = `${folder}/base-${id}.mdx`;
const barLabel = `${folder}/bar-${id}.mdx`;
- await seedMdxDocs(api, [{ name: barDoc, markdown: `# Duplicate Bar ${id}` }]);
-
- await installLocalTabSession(page, {
- openTabs: [barDoc, `${barDoc}\u0000doc-tab:1`],
- activeDocName: barDoc,
- activeTabId: barDoc,
- });
+ await seedMdxDocs(api, [
+ { name: baseDoc, markdown: `# Base ${id}` },
+ { name: barDoc, markdown: `# Preview Bar ${id}` },
+ ]);
- const duplicateTabs = editorTabButtons(page, barLabel);
- await page.goto(`/#/${barDoc}`);
- await expect(duplicateTabs).toHaveCount(2, { timeout: 10_000 });
- await expectActiveTab(duplicateTabs.nth(0));
- await expectInactiveTab(duplicateTabs.nth(1));
+ await page.goto(`/#/${baseDoc}`);
+ await expect(editorTabButtons(page, baseLabel)).toHaveCount(1, { timeout: 10_000 });
+ await sidebarTreeItem(page, `bar-${id}.mdx`).click();
- await duplicateTabs.nth(1).click();
- await expectActiveTab(duplicateTabs.nth(1));
- await expectInactiveTab(duplicateTabs.nth(0));
+ const previewTab = editorTabButtons(page, barLabel);
+ const previewChrome = page.getByRole('main').locator(`[data-editor-tab-id="${barDoc}"]`);
+ await expect(previewTab).toHaveCount(1);
+ await expect(previewChrome).toHaveAttribute('data-preview-tab', 'true');
- await duplicateTabs.nth(0).click();
- await expectActiveTab(duplicateTabs.nth(0));
- await expectInactiveTab(duplicateTabs.nth(1));
+ await previewTab.dblclick();
+ await expect(previewChrome).not.toHaveAttribute('data-preview-tab');
+ await expect(page.getByRole('main').getByTestId('editor-tab-rename-input')).toHaveCount(0);
});
test('pinning a tab replaces close with pin and bulk close keeps it open', async ({
@@ -789,7 +728,6 @@ test.describe('Editor tabs', () => {
await installLocalTabSession(page, {
openTabs: [pinnedDoc, otherDoc],
- activeDocName: otherDoc,
activeTabId: otherDoc,
});
@@ -848,7 +786,6 @@ test.describe('Editor tabs', () => {
await installLocalTabSession(page, {
openTabs: [pinnedDoc],
- activeDocName: pinnedDoc,
activeTabId: pinnedDoc,
});
diff --git a/packages/app/tests/stress/file-tree-create.e2e.ts b/packages/app/tests/stress/file-tree-create.e2e.ts
index 7796d10c0..5ced25145 100644
--- a/packages/app/tests/stress/file-tree-create.e2e.ts
+++ b/packages/app/tests/stress/file-tree-create.e2e.ts
@@ -1,6 +1,7 @@
import { existsSync, readdirSync, rmSync, statSync } from 'node:fs';
import { join } from 'node:path';
import type { Page } from '@playwright/test';
+import type { EditorTabSessionState } from '../../src/editor/editor-tabs';
import {
type ApiHelpers,
createFileViaSidebar,
@@ -197,12 +198,7 @@ async function gotoRootAndAwaitSidebar(page: Page): Promise<void> {
async function installDelayedDesktopSessionBridge(
page: Page,
workerServer: { baseURL: string; port: number; contentDir: string },
- initialSession: {
- openTabs: string[];
- pinnedTabIds: string[];
- activeDocName: string | null;
- activeTabId: string | null;
- },
+ initialSession: Omit<EditorTabSessionState, 'updatedAt'>,
): Promise<void> {
await page.addInitScript(
({ baseURL, contentDir, initialSession, port }) => {
@@ -380,10 +376,17 @@ test.describe('FileTree sidebar create', () => {
workerServer,
}) => {
await installDelayedDesktopSessionBridge(page, workerServer, {
- openTabs: ['test-doc', 'sidebar-folder/nested-doc'],
- pinnedTabIds: [],
- activeDocName: 'sidebar-folder/nested-doc',
- activeTabId: 'sidebar-folder/nested-doc',
+ panes: [
+ {
+ id: 'pane-main',
+ openTabs: ['test-doc', 'sidebar-folder/nested-doc'],
+ pinnedTabIds: [],
+ activeTabId: 'sidebar-folder/nested-doc',
+ size: 100,
+ },
+ ],
+ focusedPaneId: 'pane-main',
+ activeTabByMode: { files: 'sidebar-folder/nested-doc', skills: null },
});
await page.goto('/#/test-doc');
@@ -702,14 +705,12 @@ test.describe('FileTree sidebar create', () => {
for (const folderName of folderNames.slice(0, 2)) {
await sidebarTreeItem(page, folderName).click();
await expect(sidebarTreeItem(page, folderName)).toBeVisible({ timeout: 10_000 });
- await expect(page.getByRole('button', { name: `${folderName}/`, exact: true })).toBeVisible(
- { timeout: 10_000 },
- );
+ const folderTab = page.getByRole('button', { name: `${folderName}/`, exact: true });
+ await expect(folderTab).toBeVisible({ timeout: 10_000 });
+ await folderTab.dblclick();
}
- await page.evaluate(() => {
- window.location.hash = '#/';
- });
+ await gotoRootAndAwaitSidebar(page);
await commitDefaultFolderCreate(page, 'New Folder');
await selectAllSidebarItems(page, 'New Folder');
@@ -854,12 +855,9 @@ test.describe('FileTree sidebar create', () => {
// `navigateToFolderWithPulse`), so `activeTarget.kind === 'folder'`
// and the sidebar's New File button would create inside it.
// This test needs the file as a ROOT SIBLING of the folder (same
- // basename, different kinds), so reset the URL hash to the workspace
- // root before clicking New File.
- await page.evaluate(() => {
- window.location.hash = '#/';
- });
- await expect(page).toHaveURL(/#\/$/);
+ // basename, different kinds), so fully navigate to the workspace root
+ // before clicking New File.
+ await gotoRootAndAwaitSidebar(page);
await createFileViaSidebar(page, name);
const fileItem = await visibleSidebarItemByPath(page, `${name}.md`);
await expect(editorTabButton(page, `${name}/`).first()).toBeVisible();
diff --git a/packages/app/tests/stress/fixtures/handoff-mocks.ts b/packages/app/tests/stress/fixtures/handoff-mocks.ts
index b5eae7fab..283bd1af1 100644
--- a/packages/app/tests/stress/fixtures/handoff-mocks.ts
+++ b/packages/app/tests/stress/fixtures/handoff-mocks.ts
@@ -400,12 +400,18 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): P
// mutations. Both must resolve cleanly or the editor tree never
// installs the __activeProvider getter the e2e helper polls.
getSessionState: async () => ({
- openTabs: [],
- pinnedTabIds: [],
- activeDocName: null,
- activeTabId: null,
activeTabByMode: { files: null, skills: null },
updatedAt: null,
+ panes: [
+ {
+ id: 'pane-main',
+ openTabs: [],
+ pinnedTabIds: [],
+ activeTabId: null,
+ size: 100,
+ },
+ ],
+ focusedPaneId: 'pane-main',
}),
setSessionState: async () => {},
open: async () => {},
diff --git a/packages/app/tests/stress/navigation-history.e2e.ts b/packages/app/tests/stress/navigation-history.e2e.ts
index ffd40bb4a..0bead8bde 100644
--- a/packages/app/tests/stress/navigation-history.e2e.ts
+++ b/packages/app/tests/stress/navigation-history.e2e.ts
@@ -42,6 +42,13 @@ async function expectAsset(page: Page, hash: string, assetName: string): Promise
});
}
+async function expectSkillsHome(page: Page): Promise<void> {
+ await expectHash(page, '#/__skills__');
+ await expect(page.getByRole('heading', { name: 'Create a skill.', exact: true })).toBeVisible({
+ timeout: 15_000,
+ });
+}
+
async function expectSkillFile(
page: Page,
hash: string,
@@ -166,10 +173,9 @@ test('browser history traverses every user-facing navigation target and truncate
const sidebar = page.locator('[data-slot="sidebar-container"]');
// The surface switch is an icon-first ToggleGroup (Radix radios, not
// buttons), so address it by test id rather than by role+name.
- // Switching to Skills clears the hash (the Skills base page) and so is its
- // own history entry — the traversal below accounts for it.
+ // The Skills base page has its own canonical route and history entry.
await sidebar.getByTestId('sidebar-skills-toggle').click();
- await expectHash(page, '');
+ await expectSkillsHome(page);
// Pierre's tree renders each label twice (a visible copy and an
// aria-hidden overflow measurement copy), so take the first match.
const projectGroup = sidebar.getByText('Project', { exact: true }).first();
@@ -189,7 +195,7 @@ test('browser history traverses every user-facing navigation target and truncate
await page.goBack();
await expectDocument(page, skillDocHash, `Navigation Skill ${id}`);
await page.goBack();
- await expectHash(page, '');
+ await expectSkillsHome(page);
await page.goBack();
await expectAsset(page, assetHash, assetName);
await page.goBack();
@@ -210,7 +216,7 @@ test('browser history traverses every user-facing navigation target and truncate
await page.goForward();
await expectAsset(page, assetHash, assetName);
await page.goForward();
- await expectHash(page, '');
+ await expectSkillsHome(page);
await page.goForward();
await expectDocument(page, skillDocHash, `Navigation Skill ${id}`);
await page.goForward();
@@ -219,7 +225,7 @@ test('browser history traverses every user-facing navigation target and truncate
await page.goBack();
await expectDocument(page, skillDocHash, `Navigation Skill ${id}`);
await page.goBack();
- await expectHash(page, '');
+ await expectSkillsHome(page);
await page.goBack();
await expectAsset(page, assetHash, assetName);
// Back on the asset, the sidebar is still showing Skills — switch to Files
diff --git a/packages/app/tests/stress/qa-sidebar-responsive.e2e.ts b/packages/app/tests/stress/qa-sidebar-responsive.e2e.ts
index 55671cc74..8395e0f0e 100644
--- a/packages/app/tests/stress/qa-sidebar-responsive.e2e.ts
+++ b/packages/app/tests/stress/qa-sidebar-responsive.e2e.ts
@@ -426,10 +426,7 @@ test.describe('non-embedded UA', () => {
await page.keyboard.press('Escape');
});
- test('QA-021: right panel has a transition class (animated, gated on drag)', async ({
- page,
- api,
- }) => {
+ test('QA-021: right panel resizing does not animate', async ({ page, api }) => {
await seedDoc(api, 'qa-021');
await page.setViewportSize(WIDE);
await page.goto('/#/qa-021');
@@ -437,39 +434,10 @@ test.describe('non-embedded UA', () => {
timeout: 60_000,
});
await expect(page.locator('#doc-panel')).toBeAttached({ timeout: 10_000 });
- // react-resizable-panels v3 puts id on a wrapper but className on the inner data-slot=resizable-panel element.
- // Probe both: scan the doc-panel subtree for any element carrying the transition class.
- const probe = await page.evaluate(() => {
- const root = document.querySelector('#doc-panel');
- if (!root) return { rootExists: false };
- // Walk root + descendants for the transition class
- const allWithClass = [root, ...root.querySelectorAll('*')].map((el) => ({
- tag: el.tagName,
- id: el.id || null,
- slot: (el as HTMLElement).getAttribute('data-slot'),
- className: (el as HTMLElement).className,
- }));
- // Find one that contains 'transition-[flex-grow]'
- const match = allWithClass.find(
- (e) => typeof e.className === 'string' && e.className.includes('transition-[flex-grow]'),
- );
- return {
- rootExists: true,
- rootClassName: (root as HTMLElement).className,
- rootSlot: root.getAttribute('data-slot'),
- match,
- descendantCount: allWithClass.length,
- };
- });
- console.log('QA-021 className probe:', JSON.stringify(probe, null, 2));
- expect(probe.rootExists, '#doc-panel mounted').toBe(true);
- // Either the root or a descendant must carry the transition class
- const className = probe.match?.className ?? probe.rootClassName ?? '';
- expect(className, 'transition class located somewhere in doc-panel subtree').toBeTruthy();
- expect(className).toContain('transition-[flex-grow]');
- expect(className).toContain('duration-200');
- expect(className).toContain('ease-out');
- expect(className).toContain('motion-reduce:transition-none');
+ const transitionDuration = await page
+ .locator('#doc-panel')
+ .evaluate((element) => getComputedStyle(element).transitionDuration);
+ expect(transitionDuration).toBe('0s');
});
test('QA-022: data-dragging attribute appears during handle drag', async ({ page, api }) => {
diff --git a/packages/app/tests/stress/settings-search.e2e.ts b/packages/app/tests/stress/settings-search.e2e.ts
index 7ed857b61..dcdc09732 100644
--- a/packages/app/tests/stress/settings-search.e2e.ts
+++ b/packages/app/tests/stress/settings-search.e2e.ts
@@ -83,6 +83,25 @@ test.describe('Settings search — navigation + pinned layout', () => {
await expect(field).toHaveClass(/animate-settings-nav-flash/, { timeout: 2_000 });
await expect(field).not.toHaveClass(/animate-settings-nav-flash/, { timeout: 3_000 });
});
+
+ test('Preview tabs is searchable from its catalog-backed label and description', async ({
+ page,
+ }) => {
+ await openSettings(page);
+
+ for (const query of ['preview', 'reuse']) {
+ await page.getByTestId('settings-search-input').fill(query);
+ const result = page.getByTestId(
+ 'settings-search-result-field:preferences:editor.previewTabs',
+ );
+ await expect(result).toBeVisible({ timeout: 5_000 });
+ await result.click();
+
+ const field = page.locator('[data-field="editor.previewTabs"]');
+ await expect(field).toBeVisible({ timeout: 5_000 });
+ await expect(field).toBeInViewport();
+ }
+ });
});
test.describe('Settings search — scope badges + markdownlint rules', () => {
diff --git a/packages/app/tests/stress/slash-command-auto-open.e2e.ts b/packages/app/tests/stress/slash-command-auto-open.e2e.ts
index 635e532b2..3d358ac69 100644
--- a/packages/app/tests/stress/slash-command-auto-open.e2e.ts
+++ b/packages/app/tests/stress/slash-command-auto-open.e2e.ts
@@ -105,11 +105,14 @@ test('SLASH-AUTOOPEN-IMG-MULTI: slash-inserting Image with a prior Image auto-op
// Wait for the seeded img NodeView to mount.
await expect(page.locator('[data-jsx-component]')).toHaveCount(1);
- // Land cursor at end of doc (in the trailing empty paragraph). Typing the
- // trigger before the caret has actually moved there types '/image' at a stale
- // position, where the suggestion never matches — prove the move landed first.
- await page.click('.ProseMirror:not(.composer-prosemirror)');
- await page.keyboard.press('ControlOrMeta+End');
+ // Land cursor at end of doc (in the trailing empty paragraph). This test
+ // covers slash insertion, so position the caret through TipTap rather than
+ // depending on a platform keyboard shortcut for its setup.
+ await page.evaluate(() => {
+ const editor = window.__activeEditor;
+ if (!editor) throw new Error('window.__activeEditor not set');
+ editor.chain().focus().setTextSelection(editor.state.doc.content.size).run();
+ });
await focusEditor(page);
await expect
.poll(() =>
diff --git a/packages/core/src/config/bind-config-doc.test.ts b/packages/core/src/config/bind-config-doc.test.ts
index f1835dfc3..61a52d9e4 100644
--- a/packages/core/src/config/bind-config-doc.test.ts
+++ b/packages/core/src/config/bind-config-doc.test.ts
@@ -49,6 +49,7 @@ describe('bindConfigDoc — current()', () => {
expect(config.content).toBeDefined();
expect(config.appearance).toBeDefined();
expect(config.editor?.wordWrap).toBe(true);
+ expect(config.editor?.previewTabs).toBe(true);
binding.dispose();
});
@@ -124,6 +125,21 @@ describe('bindConfigDoc — patch()', () => {
binding.dispose();
});
+ test('writes editor.previewTabs to empty Y.Text + returns effective config', () => {
+ const binding = bindConfigDoc(provider, 'user');
+ const result = binding.patch({ editor: { previewTabs: false } });
+
+ expect(result.ok).toBe(true);
+ if (!result.ok) throw new Error('expected ok');
+ expect(result.appliedPaths).toEqual(['editor.previewTabs']);
+ expect(result.effective.editor?.previewTabs).toBe(false);
+
+ const ytext = doc.getText('source').toString();
+ expect(ytext).toContain('editor:');
+ expect(ytext).toContain('previewTabs: false');
+ binding.dispose();
+ });
+
test('writes the sidebar view toggles via a project-local binding + returns effective config', () => {
const binding = bindConfigDoc(provider, 'project-local');
const result = binding.patch({
diff --git a/packages/core/src/config/merge-layered.test.ts b/packages/core/src/config/merge-layered.test.ts
index 428e3994f..4df3675a9 100644
--- a/packages/core/src/config/merge-layered.test.ts
+++ b/packages/core/src/config/merge-layered.test.ts
@@ -87,6 +87,15 @@ describe('mergeLayered — scope-aware leaf short-circuits', () => {
expect(merged.editor?.wordWrap).toBe(false);
});
+ test("scope: 'user' (editor.previewTabs) returns user preference even when other layers differ", () => {
+ const user = makeConfig({ editor: { previewTabs: false } });
+ const project = makeConfig({ editor: { previewTabs: true } });
+ const projectLocal = makeConfig({ editor: { previewTabs: true } });
+
+ const merged = mergeLayered(user, project, projectLocal);
+ expect(merged.editor?.previewTabs).toBe(false);
+ });
+
test("scope: 'project' (content.dir) returns project, ignoring project-local", () => {
// `content.dir` is a `scope: 'project'` leaf. The project-over-project-local
// short-circuit applies — pinning here so the scope: 'project'
diff --git a/packages/core/src/config/schema-jsonschema.test.ts b/packages/core/src/config/schema-jsonschema.test.ts
index 382eeab42..08447e479 100644
--- a/packages/core/src/config/schema-jsonschema.test.ts
+++ b/packages/core/src/config/schema-jsonschema.test.ts
@@ -64,6 +64,16 @@ const FIXTURES: Fixture[] = [
input: { editor: { wordWrap: 'false' } },
shouldAccept: false,
},
+ {
+ name: 'editor.previewTabs=false accepted',
+ input: { editor: { previewTabs: false } },
+ shouldAccept: true,
+ },
+ {
+ name: 'editor.previewTabs string rejected',
+ input: { editor: { previewTabs: 'false' } },
+ shouldAccept: false,
+ },
{
name: 'appearance.preview.autoOpen=false accepted',
input: { appearance: { preview: { autoOpen: false } } },
@@ -155,6 +165,18 @@ describe('JSON Schema ↔ runtime equivalence', () => {
expect(ajvAccept).toBe(shouldAccept);
expect(zodAccept).toBe(shouldAccept);
});
+
+ test('user schema exposes optional editor.previewTabs boolean with default true', () => {
+ const editorSchema = jsonSchema.properties?.editor as {
+ properties?: Record<string, { type?: string; default?: unknown }>;
+ required?: string[];
+ };
+ expect(editorSchema.properties?.previewTabs).toMatchObject({
+ type: 'boolean',
+ default: true,
+ });
+ expect(editorSchema.required ?? []).not.toContain('previewTabs');
+ });
});
describe('loose-mode forgiveness', () => {
diff --git a/packages/core/src/config/schema-leaf.test.ts b/packages/core/src/config/schema-leaf.test.ts
index 0b6d4c299..183143714 100644
--- a/packages/core/src/config/schema-leaf.test.ts
+++ b/packages/core/src/config/schema-leaf.test.ts
@@ -59,6 +59,16 @@ describe('getLeafFieldMeta', () => {
});
});
+ test('returns metadata for the user-scope editor.previewTabs leaf', () => {
+ const meta = getLeafFieldMeta(ConfigSchema, ['editor', 'previewTabs']);
+ expect(meta).toEqual({
+ scope: 'user',
+ agentSettable: false,
+ defaultScope: 'user',
+ description: expect.any(String),
+ });
+ });
+
test('returns project-local metadata for the linkPreviews.enabled egress opt-in', () => {
const meta = getLeafFieldMeta(ConfigSchema, ['linkPreviews', 'enabled']);
expect(meta).toEqual({
diff --git a/packages/core/src/config/schema.test.ts b/packages/core/src/config/schema.test.ts
index d62635cea..2903dad2a 100644
--- a/packages/core/src/config/schema.test.ts
+++ b/packages/core/src/config/schema.test.ts
@@ -171,6 +171,13 @@ describe('appearance.sidebar view toggles', () => {
});
});
+describe('editor preferences', () => {
+ test('preview tabs default on and preserve an explicit opt-out', () => {
+ expect(ConfigSchema.parse({}).editor.previewTabs).toBe(true);
+ expect(ConfigSchema.parse({ editor: { previewTabs: false } }).editor.previewTabs).toBe(false);
+ });
+});
+
describe('linkPreviews.enabled (external link-hover preview egress default)', () => {
test('defaults to enabled when the block is absent', () => {
expect(ConfigSchema.parse({}).linkPreviews).toEqual({ enabled: true });
diff --git a/packages/core/src/config/validate-patch-scopes.test.ts b/packages/core/src/config/validate-patch-scopes.test.ts
index a87ad556e..10cf52ed8 100644
--- a/packages/core/src/config/validate-patch-scopes.test.ts
+++ b/packages/core/src/config/validate-patch-scopes.test.ts
@@ -99,6 +99,21 @@ describe('validatePatchScopes', () => {
expect(validatePatchScopes({ editor: { wordWrap: false } }, 'user')).toBeNull();
});
+ test('accepts editor.previewTabs only from a user writer', () => {
+ expect(validatePatchScopes({ editor: { previewTabs: false } }, 'user')).toBeNull();
+
+ const projectViolation = validatePatchScopes({ editor: { previewTabs: false } }, 'project');
+ expect(projectViolation?.code).toBe('SCOPE_VIOLATION');
+ expect(projectViolation?.path).toEqual(['editor', 'previewTabs']);
+
+ const projectLocalViolation = validatePatchScopes(
+ { editor: { previewTabs: false } },
+ 'project-local',
+ );
+ expect(projectLocalViolation?.code).toBe('SCOPE_VIOLATION');
+ expect(projectLocalViolation?.path).toEqual(['editor', 'previewTabs']);
+ });
+
test('returns null for a project field written by a project writer', () => {
// content.dir is scope: 'project'.
expect(validatePatchScopes({ content: { dir: 'docs' } }, 'project')).toBeNull();
diff --git a/packages/core/src/desktop-bridge.ts b/packages/core/src/desktop-bridge.ts
index e8d738a6a..929be4fdf 100644
--- a/packages/core/src/desktop-bridge.ts
+++ b/packages/core/src/desktop-bridge.ts
@@ -142,13 +142,19 @@ export type OkMenuAction =
*/
export type OkUnsubscribe = () => void;
-export interface ProjectSessionState {
+export interface PersistedEditorPane {
+ id: string;
openTabs: string[];
pinnedTabIds: string[];
- activeDocName: string | null;
activeTabId: string | null;
+ size: number;
+}
+
+export interface ProjectSessionState {
activeTabByMode: { files: string | null; skills: string | null };
updatedAt: string | null;
+ panes: PersistedEditorPane[];
+ focusedPaneId: string;
}
/**
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index 68b7e86bf..2b1ec4a32 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -348,6 +348,7 @@ import {
addRecentFile,
addRecentProject,
annotateMissing,
+ emptyProjectSessionState,
emptyState,
evaluateSchemaCompatibility,
getProjectSessionState,
@@ -4979,25 +4980,9 @@ function registerIpcHandlers() {
handle('ok:project:get-session-state', async (event) => {
const win = BrowserWindow.fromWebContents(event.sender);
- if (!win || !wm)
- return {
- openTabs: [],
- pinnedTabIds: [],
- activeDocName: null,
- activeTabId: null,
- activeTabByMode: { files: null, skills: null },
- updatedAt: null,
- };
+ if (!win || !wm) return emptyProjectSessionState();
const ctx = wm.getContextForBrowserWindow(win as unknown as BrowserWindowLike);
- if (!ctx)
- return {
- openTabs: [],
- pinnedTabIds: [],
- activeDocName: null,
- activeTabId: null,
- activeTabByMode: { files: null, skills: null },
- updatedAt: null,
- };
+ if (!ctx) return emptyProjectSessionState();
return getProjectSessionState(appState, ctx.projectPath);
});
diff --git a/packages/desktop/src/main/state-store.ts b/packages/desktop/src/main/state-store.ts
index 5eaec565c..a9be9f2e9 100644
--- a/packages/desktop/src/main/state-store.ts
+++ b/packages/desktop/src/main/state-store.ts
@@ -50,6 +50,15 @@ export interface PersistedWindowBounds {
isFullScreen: boolean;
}
+/** Keep field-for-field with the canonical and IPC ProjectSessionState pane shape. */
+interface PersistedEditorPane {
+ id: string;
+ openTabs: string[];
+ pinnedTabIds: string[];
+ activeTabId: string | null;
+ size: number;
+}
+
/**
* One entry in the persisted session-restore snapshot. A restart reopens the
* full set of windows open at the last clean exit — each is either a project
@@ -84,19 +93,15 @@ interface RecentFile {
lastOpenedAt: string;
}
-interface ProjectSessionState {
- /** User-open tabs for this project, in visible tab order. */
- openTabs: string[];
- /** Visible tab IDs protected from tab-strip close affordances. */
- pinnedTabIds: string[];
- /** Most recently active document tab, or null when the project had no active doc. */
- activeDocName: string | null;
- /** Most recently active tab, including folder overview tabs. */
- activeTabId: string | null;
+export interface ProjectSessionState {
/** Last-active tab per sidebar surface (Files vs Skills), each an open-tab id or null. */
activeTabByMode: { files: string | null; skills: string | null };
/** ISO-8601 timestamp of the last tab-session write. */
updatedAt: string | null;
+ /** Authoritative flat, side-by-side editor workspace. */
+ panes: PersistedEditorPane[];
+ /** Pane that owns the active editor target. */
+ focusedPaneId: string;
}
/**
@@ -328,14 +333,20 @@ export function setSpellCheckEnabled(state: AppState, enabled: boolean): AppStat
return { ...state, spellCheckEnabled: enabled };
}
-function emptyProjectSessionState(): ProjectSessionState {
+export function emptyProjectSessionState(): ProjectSessionState {
return {
- openTabs: [],
- pinnedTabIds: [],
- activeDocName: null,
- activeTabId: null,
activeTabByMode: { files: null, skills: null },
updatedAt: null,
+ panes: [
+ {
+ id: 'pane-main',
+ openTabs: [],
+ pinnedTabIds: [],
+ activeTabId: null,
+ size: 100,
+ },
+ ],
+ focusedPaneId: 'pane-main',
};
}
@@ -360,34 +371,71 @@ function sanitizeStringArray(value: unknown): string[] {
return result;
}
+function isPositiveFiniteNumber(value: unknown): value is number {
+ return typeof value === 'number' && Number.isFinite(value) && value > 0;
+}
+
+function sanitizeOpenTabIds(value: unknown, claimedTargets = new Set<string>()): string[] {
+ return sanitizeStringArray(value).filter((tabId) => {
+ if (tabId.includes('\u0000doc-tab:')) return false;
+ if (tabId.startsWith('\u0000')) return true;
+ if (claimedTargets.has(tabId)) return false;
+ claimedTargets.add(tabId);
+ return true;
+ });
+}
+
+function normalizePaneSizes(panes: PersistedEditorPane[]): PersistedEditorPane[] {
+ if (panes.length === 0) return [];
+ const total = panes.reduce((sum, pane) => sum + pane.size, 0);
+ const fallbackSize = 100 / panes.length;
+ return panes.map((pane) => ({
+ ...pane,
+ size: total > 0 ? (pane.size / total) * 100 : fallbackSize,
+ }));
+}
+
+function parsePersistedEditorPanes(raw: unknown): PersistedEditorPane[] | null {
+ if (!Array.isArray(raw)) return null;
+ const paneIds = new Set<string>();
+ const tabTargets = new Set<string>();
+ const panes: PersistedEditorPane[] = [];
+ for (const candidate of raw) {
+ if (typeof candidate !== 'object' || candidate === null) continue;
+ const pane = candidate as Record<string, unknown>;
+ if (typeof pane.id !== 'string' || pane.id.length === 0 || paneIds.has(pane.id)) continue;
+ paneIds.add(pane.id);
+ const openTabs = sanitizeOpenTabIds(pane.openTabs, tabTargets);
+ const openTabIds = new Set(openTabs);
+ panes.push({
+ id: pane.id,
+ openTabs,
+ pinnedTabIds: sanitizeStringArray(pane.pinnedTabIds).filter((tabId) => openTabIds.has(tabId)),
+ activeTabId:
+ typeof pane.activeTabId === 'string' && openTabIds.has(pane.activeTabId)
+ ? pane.activeTabId
+ : (openTabs[0] ?? null),
+ size: isPositiveFiniteNumber(pane.size) ? pane.size : 1,
+ });
+ }
+ return panes.length === 0 ? null : normalizePaneSizes(panes);
+}
+
function parseProjectSessionState(raw: unknown): ProjectSessionState {
if (typeof raw !== 'object' || raw === null) return emptyProjectSessionState();
const obj = raw as Record<string, unknown>;
- const openTabs = sanitizeStringArray(obj.openTabs);
- const openTabSet = new Set(openTabs);
- const pinnedTabIds = sanitizeStringArray(obj.pinnedTabIds).filter((tabId) =>
- openTabSet.has(tabId),
- );
- const activeDocName =
- typeof obj.activeDocName === 'string' && openTabs.includes(obj.activeDocName)
- ? obj.activeDocName
- : null;
- const activeTabId =
- typeof obj.activeTabId === 'string' && openTabs.includes(obj.activeTabId)
- ? obj.activeTabId
- : activeDocName;
+ const panes = parsePersistedEditorPanes(obj.panes);
+ if (panes === null) return emptyProjectSessionState();
+ const paneOpenTabs = panes.flatMap((pane) => pane.openTabs);
+ const focusedPane = panes.find((pane) => pane.id === obj.focusedPaneId) ?? panes[0];
return {
- openTabs,
- pinnedTabIds,
- activeDocName,
- activeTabId,
- // Persist per-surface active as open-tab ids; the app re-validates surface
- // membership via parseEditorTabSessionState on read.
activeTabByMode: {
- files: readModeSlot(obj.activeTabByMode, 'files', openTabs),
- skills: readModeSlot(obj.activeTabByMode, 'skills', openTabs),
+ files: readModeSlot(obj.activeTabByMode, 'files', paneOpenTabs),
+ skills: readModeSlot(obj.activeTabByMode, 'skills', paneOpenTabs),
},
updatedAt: typeof obj.updatedAt === 'string' ? obj.updatedAt : null,
+ panes,
+ focusedPaneId: focusedPane.id,
};
}
diff --git a/packages/desktop/src/shared/ipc-channels.ts b/packages/desktop/src/shared/ipc-channels.ts
index a5a3c4909..ed5f86911 100644
--- a/packages/desktop/src/shared/ipc-channels.ts
+++ b/packages/desktop/src/shared/ipc-channels.ts
@@ -258,13 +258,19 @@ type ShareValidateFolderResult =
| { readonly kind: 'non-github' }
| { readonly kind: 'symlink-escape' };
-interface ProjectSessionState {
+interface PersistedEditorPane {
+ id: string;
openTabs: string[];
pinnedTabIds: string[];
- activeDocName: string | null;
activeTabId: string | null;
+ size: number;
+}
+
+interface ProjectSessionState {
activeTabByMode: { files: string | null; skills: string | null };
updatedAt: string | null;
+ panes: PersistedEditorPane[];
+ focusedPaneId: string;
}
/** Outcome of a spawn probe — narrow shape so renderer can branch cleanly without inspecting strings. */
diff --git a/packages/desktop/tests/main/state-store.test.ts b/packages/desktop/tests/main/state-store.test.ts
index 6dad08ba7..e3226919f 100644
--- a/packages/desktop/tests/main/state-store.test.ts
+++ b/packages/desktop/tests/main/state-store.test.ts
@@ -19,6 +19,42 @@ import {
setSpellCheckEnabled,
} from '../../src/main/state-store.ts';
+function persistedWorkspace(
+ openTabs: string[],
+ pinnedTabIds: string[],
+ activeTabId: string | null,
+) {
+ return {
+ panes: [
+ {
+ id: 'pane-main',
+ openTabs,
+ pinnedTabIds,
+ activeTabId,
+ size: 100,
+ },
+ ],
+ focusedPaneId: 'pane-main',
+ };
+}
+
+function projectSession(
+ openTabs: string[],
+ pinnedTabIds: string[],
+ activeTabId: string | null,
+ updatedAt: string | null = null,
+ activeTabByMode: { files: string | null; skills: string | null } = {
+ files: null,
+ skills: null,
+ },
+) {
+ return {
+ activeTabByMode,
+ updatedAt,
+ ...persistedWorkspace(openTabs, pinnedTabIds, activeTabId),
+ };
+}
+
describe('state-store (recent projects + LRU)', () => {
test('addRecentProject prepends to empty list', () => {
const next = addRecentProject(emptyState(), '/tmp/p1', 'p1');
@@ -67,60 +103,42 @@ describe('state-store (recent projects + LRU)', () => {
});
test('project session state persists by project path', () => {
- const state = setProjectSessionState(emptyState(), '/tmp/a', {
- openTabs: ['README', 'docs/guide'],
- pinnedTabIds: ['README'],
- activeDocName: 'docs/guide',
- activeTabId: 'docs/guide',
- updatedAt: '2026-05-06T00:00:00Z',
- });
- expect(getProjectSessionState(state, '/tmp/a')).toEqual({
- openTabs: ['README', 'docs/guide'],
- pinnedTabIds: ['README'],
- activeDocName: 'docs/guide',
- activeTabId: 'docs/guide',
- activeTabByMode: { files: null, skills: null },
- updatedAt: '2026-05-06T00:00:00Z',
- });
- expect(getProjectSessionState(state, '/tmp/b')).toEqual({
- openTabs: [],
- pinnedTabIds: [],
- activeDocName: null,
- activeTabId: null,
- activeTabByMode: { files: null, skills: null },
- updatedAt: null,
- });
+ const session = projectSession(
+ ['README', 'docs/guide'],
+ ['README'],
+ 'docs/guide',
+ '2026-05-06T00:00:00Z',
+ );
+ const state = setProjectSessionState(emptyState(), '/tmp/a', session);
+ expect(getProjectSessionState(state, '/tmp/a')).toEqual(session);
+ expect(getProjectSessionState(state, '/tmp/b')).toEqual(projectSession([], [], null));
});
test('project session state preserves active folder tabs', () => {
const folderTabId = '\u0000folder:docs';
- const state = setProjectSessionState(emptyState(), '/tmp/a', {
- openTabs: ['README', folderTabId],
- pinnedTabIds: [folderTabId],
- activeDocName: null,
- activeTabId: folderTabId,
- updatedAt: '2026-05-06T00:00:00Z',
- });
- expect(getProjectSessionState(state, '/tmp/a')).toEqual({
- openTabs: ['README', folderTabId],
- pinnedTabIds: [folderTabId],
- activeDocName: null,
- activeTabId: folderTabId,
- activeTabByMode: { files: null, skills: null },
- updatedAt: '2026-05-06T00:00:00Z',
- });
+ const session = projectSession(
+ ['README', folderTabId],
+ [folderTabId],
+ folderTabId,
+ '2026-05-06T00:00:00Z',
+ );
+ const state = setProjectSessionState(emptyState(), '/tmp/a', session);
+ expect(getProjectSessionState(state, '/tmp/a')).toEqual(session);
});
test('project session state round-trips per-surface active tabs', () => {
- const state = setProjectSessionState(emptyState(), '/tmp/a', {
- openTabs: ['README', 'docs/guide'],
- pinnedTabIds: [],
- activeDocName: 'docs/guide',
- activeTabId: 'docs/guide',
- // 'docs/guide' is open → kept; 'gone' is not an open tab → dropped to null.
- activeTabByMode: { files: 'docs/guide', skills: 'gone' },
- updatedAt: '2026-05-06T00:00:00Z',
- });
+ const state = setProjectSessionState(
+ emptyState(),
+ '/tmp/a',
+ projectSession(
+ ['README', 'docs/guide'],
+ [],
+ 'docs/guide',
+ '2026-05-06T00:00:00Z',
+ // 'docs/guide' is open → kept; 'gone' is not an open tab → dropped to null.
+ { files: 'docs/guide', skills: 'gone' },
+ ),
+ );
expect(getProjectSessionState(state, '/tmp/a').activeTabByMode).toEqual({
files: 'docs/guide',
skills: null,
@@ -128,22 +146,13 @@ describe('state-store (recent projects + LRU)', () => {
});
test('removeRecentProject drops matching session state', () => {
- const withSession = setProjectSessionState(emptyState(), '/tmp/a', {
- openTabs: ['README'],
- pinnedTabIds: ['README'],
- activeDocName: 'README',
- activeTabId: 'README',
- updatedAt: '2026-05-06T00:00:00Z',
- });
+ const withSession = setProjectSessionState(
+ emptyState(),
+ '/tmp/a',
+ projectSession(['README'], ['README'], 'README', '2026-05-06T00:00:00Z'),
+ );
const next = removeRecentProject(withSession, '/tmp/a');
- expect(getProjectSessionState(next, '/tmp/a')).toEqual({
- openTabs: [],
- pinnedTabIds: [],
- activeDocName: null,
- activeTabId: null,
- activeTabByMode: { files: null, skills: null },
- updatedAt: null,
- });
+ expect(getProjectSessionState(next, '/tmp/a')).toEqual(projectSession([], [], null));
});
test('annotateMissing flips missing for non-existent paths', () => {
@@ -154,7 +163,7 @@ describe('state-store (recent projects + LRU)', () => {
expect(annotated.find((p) => p.path === '/tmp/missing')?.missing).toBe(true);
});
- test('parseAppState accepts well-formed state', () => {
+ test('parseAppState ignores flat legacy project sessions', () => {
const raw = {
recentProjects: [{ path: '/tmp/a', name: 'a', lastOpenedAt: '2026-04-20T00:00:00Z' }],
lastOpenedProject: '/tmp/a',
@@ -172,13 +181,60 @@ describe('state-store (recent projects + LRU)', () => {
expect(parsed).not.toBeNull();
expect(parsed?.recentProjects.length).toBe(1);
expect(parsed?.lastOpenedProject).toBe('/tmp/a');
+ expect(parsed?.projectSessions['/tmp/a']).toEqual(projectSession([], [], null));
+ });
+
+ test('parseAppState drops legacy occurrence ids without transforming them', () => {
+ const parsed = parseAppState({
+ recentProjects: [],
+ projectSessions: {
+ '/tmp/a': {
+ panes: [
+ {
+ id: 'pane-a',
+ openTabs: ['docs/a', 'docs/a\u0000doc-tab:1', 'docs/b'],
+ pinnedTabIds: ['docs/a'],
+ activeTabId: 'docs/a',
+ size: 1,
+ },
+ {
+ id: 'pane-b',
+ openTabs: ['docs/d', 'docs/c\u0000doc-tab:1'],
+ pinnedTabIds: ['docs/d', 'docs/c\u0000doc-tab:1'],
+ activeTabId: 'docs/c\u0000doc-tab:1',
+ size: 1,
+ },
+ ],
+ focusedPaneId: 'pane-b',
+ activeTabByMode: {
+ files: 'docs/a\u0000doc-tab:1',
+ skills: 'docs/c\u0000doc-tab:1',
+ },
+ updatedAt: '2026-05-06T00:00:00Z',
+ },
+ },
+ });
+
expect(parsed?.projectSessions['/tmp/a']).toEqual({
- openTabs: ['README', 'docs/guide'],
- pinnedTabIds: ['README'],
- activeDocName: 'docs/guide',
- activeTabId: 'docs/guide',
activeTabByMode: { files: null, skills: null },
updatedAt: '2026-05-06T00:00:00Z',
+ panes: [
+ {
+ id: 'pane-a',
+ openTabs: ['docs/a', 'docs/b'],
+ pinnedTabIds: ['docs/a'],
+ activeTabId: 'docs/a',
+ size: 50,
+ },
+ {
+ id: 'pane-b',
+ openTabs: ['docs/d'],
+ pinnedTabIds: ['docs/d'],
+ activeTabId: 'docs/d',
+ size: 50,
+ },
+ ],
+ focusedPaneId: 'pane-b',
});
});
diff --git a/packages/desktop/tests/smoke/sidebar-pill-lockstep-fade.e2e.ts b/packages/desktop/tests/smoke/sidebar-pill-lockstep-fade.e2e.ts
index 27540c436..66fc13994 100644
--- a/packages/desktop/tests/smoke/sidebar-pill-lockstep-fade.e2e.ts
+++ b/packages/desktop/tests/smoke/sidebar-pill-lockstep-fade.e2e.ts
@@ -141,13 +141,19 @@ test.describe('sidebar search pill — Electron lockstep-fade smoke', () => {
await pill.waitFor({ state: 'visible', timeout: 10_000 });
const sidebarHeader = page.locator('[data-slot="sidebar-header"]');
- const editorHeader = page.locator('[data-slot="sidebar-inset"] > header');
+ const editorHeaderLeadingActions = page.locator('[data-editor-header-leading-actions]');
const backButtons = page.getByRole('button', { name: 'Back', exact: true });
const forwardButtons = page.getByRole('button', { name: 'Forward', exact: true });
const sidebarBack = sidebarHeader.getByRole('button', { name: 'Back', exact: true });
const sidebarForward = sidebarHeader.getByRole('button', { name: 'Forward', exact: true });
- const headerBack = editorHeader.getByRole('button', { name: 'Back', exact: true });
- const headerForward = editorHeader.getByRole('button', { name: 'Forward', exact: true });
+ const headerBack = editorHeaderLeadingActions.getByRole('button', {
+ name: 'Back',
+ exact: true,
+ });
+ const headerForward = editorHeaderLeadingActions.getByRole('button', {
+ name: 'Forward',
+ exact: true,
+ });
// Expanded placement: SidebarHeader owns the only Back/Forward pair.
await expect(sidebarBack).toHaveCount(1);
diff --git a/packages/server/src/mcp/tools/get-preview-url.test.ts b/packages/server/src/mcp/tools/get-preview-url.test.ts
index e374156a8..dc360fc90 100644
--- a/packages/server/src/mcp/tools/get-preview-url.test.ts
+++ b/packages/server/src/mcp/tools/get-preview-url.test.ts
@@ -510,6 +510,7 @@ describe('preview_url tool — file branch (out-of-project)', () => {
offCwdResolverDeps: mockOffCwdDeps([
{ contentDir: '/loose', baseUrl: 'http://localhost:6001' },
]),
+ resolveUserAutoOpen: () => true,
});
const result = await handler({ file: '/loose/notes.md' });
expect(result.isError).toBeUndefined();