Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Lay out the workspace panes on a dock tree (#7122)

Abraham457d6d8a2c85
diff --git a/.changeset/dock-tree-workspace-panes.md b/.changeset/dock-tree-workspace-panes.md
new file mode 100644
index 000000000..e6aaf8c19
--- /dev/null
+++ b/.changeset/dock-tree-workspace-panes.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge-app": minor
+---
+
+The editor, Agents panel and terminal now split the window by proportion, and each project remembers its own arrangement. Panes no longer close when dragged small or when another one opens; hide them with the header buttons.
diff --git a/docs/content/features/editor.mdx b/docs/content/features/editor.mdx
index 2a5a82590..310964f12 100644
--- a/docs/content/features/editor.mdx
+++ b/docs/content/features/editor.mdx
@@ -183,7 +183,7 @@ Select text in the WYSIWYG editor and the selection bubble menu shows a **Commen
## Terminal
-The desktop app on macOS, Windows, and Linux has a built-in terminal with real interactive shells inside the editor window. On Windows, the terminal requires Windows 10 version 1809 (build 17763) or later, Windows 11, or Windows Server 2019 or later. On Linux, OpenKnowledge inherits Electron's supported distribution range: releases of the major distributions that both Chromium and the distribution vendor still support. Toggle it with `Cmd+J` on macOS or `Ctrl+J` on Windows and Linux, with `` Ctrl+` `` on any desktop platform (which also works from inside a focused terminal), with **View ▸ Show / Hide Terminal**, or with the **Terminal** button at the right end of the header at the top of the window, which is highlighted while the Terminal is open. That button appears in project windows and in windows showing a single file, wherever a terminal can run and is turned on for the project; single-file windows offer it in the shared header when available. It opens at the placement saved for this installation (the bottom dock by default). Right-click a bottom-dock tab and choose **Move to right panel**, use the matching command in the command palette or **Terminal** menu, or use the right-panel header button to move it back to the bottom. Moving or hiding the Terminal keeps its live shells, tabs, and scrollback intact.
+The desktop app on macOS, Windows, and Linux has a built-in terminal with real interactive shells inside the editor window. On Windows, the terminal requires Windows 10 version 1809 (build 17763) or later, Windows 11, or Windows Server 2019 or later. On Linux, OpenKnowledge inherits Electron's supported distribution range: releases of the major distributions that both Chromium and the distribution vendor still support. Toggle it with `Cmd+J` on macOS or `Ctrl+J` on Windows and Linux, with `` Ctrl+` `` on any desktop platform (which also works from inside a focused terminal), with **View ▸ Show / Hide Terminal**, or with the **Terminal** button at the right end of the header at the top of the window, which is highlighted while the Terminal is open. That button appears in project windows and in windows showing a single file, wherever a terminal can run and is turned on for the project; single-file windows offer it in the shared header when available. It opens where it was last placed in this project. A project with no saved arrangement uses the placement from before arrangements were saved per project, or opens it below the editor. Right-click a bottom-dock tab and choose **Move to right panel**, use the matching command in the command palette or **Terminal** menu, or use the right-panel header button to move it back to the bottom. Moving or hiding the Terminal keeps its live shells, tabs, and scrollback intact.
The terminal is also the editor's AI-chat surface: opening it starts your remembered CLI pick, or a plain shell when you have none, and the tab strip's **+** button opens another tab with whatever you picked last — a CLI chat or a plain shell. Its dropdown switches that pick and opens a tab in the thing you picked, in one action. A CLI pick sticks and is shared with the Ask AI composer; the plain-shell pick is remembered for the terminal only. In-app agents run in the Agents panel, which has its own tab strip and **+** button; picking an agent there sticks the same way and also becomes your Ask AI default. Each agent tab carries a dot for its chat's state: pulsing blue while the agent starts, signs in or works, amber while it waits for your approval or for you to sign in, green when it is ready (pulsing while it has activity you have not seen), red once the agent has stopped or hit an error, and grey for a past chat reopened from history. Hovering a tab shows its full title, that state in words, whether it has new activity, and when it was last active, and screen readers hear the state and any new activity as part of the tab's name. Picking a different agent while the open chat has not been sent yet switches that chat to the chosen agent and keeps what you have typed and attached; until that new chat has started, the agents in the **+** menu are greyed out, and the original chat stays if the new one cannot start (while a dropped file is still being read, the pick opens a new chat beside the original instead); a chat that already has a message keeps its agent, and the pick opens a new chat beside it. In an in-app chat, the **Add to prompt (+)** menu offers files and page mentions, plus selected comments when available. **Commands** appears when the selected agent provides commands and the prompt draft is empty. `Cmd+J` on macOS, `Ctrl+J` on Windows or Linux, and `` Ctrl+` `` on any desktop platform only show and hide the Terminal, even with text selected. With text selected in the editor, `Cmd+Shift+J` on macOS or `Ctrl+Shift+J` on Windows or Linux stages it into a new session with your preferred AI (a new CLI tab when that is a CLI); the passage sits in the input for you to add to, and nothing is submitted until you press Enter. **Terminal ▸ New Terminal Window** (see [Terminal menu](#terminal-menu)) opens a dedicated window with the same multi-session tabs, switched with `Cmd+<number>` on macOS or `Ctrl+<number>` on Windows and Linux, and shells starting at the project root.
@@ -191,7 +191,7 @@ On Windows, type `wsl` in any terminal tab to enter your default WSL distributio
Rename a tab by double-clicking it or pressing `F2`; the name you set pins over whatever title the running program reports, and clearing it falls back to that title. Reorder tabs by dragging, or move the active tab with `Cmd+Shift+←` / `Cmd+Shift+→` — untitled tabs keep a number that stays with their session as the strip is rearranged.
-The desktop app restores the Terminal's placement, right-panel width, tab order, active tab, and tab names after a full app restart. A full quit ends the shell processes and discards their scrollback; the restored tabs start new shells. This differs from moving, hiding, or reloading the editor window, which keeps the existing live sessions.
+The desktop app restores the Terminal's placement and size, tab order, active tab, and tab names after a full app restart. A full quit ends the shell processes and discards their scrollback; the restored tabs start new shells. This differs from moving, hiding, or reloading the editor window, which keeps the existing live sessions.
The **Agents** button at the right end of the header shows and hides the Agents panel in project windows and single-file windows on desktop and on the web, and is highlighted while the panel is open. `Cmd+L` on macOS or `Ctrl+L` on Windows and Linux, with nothing selected, shows and hides it too. With text selected in the editor, the same shortcut stages the passage in the Agents panel instead (**Ask AI about selection**), ready for you to add to and send. While the editor is [hidden](#hide-the-editor), `Cmd+L` only shows and hides the panel.
@@ -207,7 +207,7 @@ To report a problem with a chat in the desktop app, choose **Report a problem wi
Messages in an agent chat link the references they mention. A qualified GitHub reference such as `inkeep/open-knowledge#1284` links to that issue or pull request on github.com, or on your project's GitHub Enterprise host when the project's remote is on a host declared under [`git.hosts`](../reference/configuration.mdx), a per-machine setting. Ticket prefixes you list under [`autolinks`](../reference/configuration.mdx) in `.ok/config.yml` turn tokens such as `PRD-123` into links to the URL you give. A bare `#123` stays plain text, since agents write the same form for ordinals like "step #2", and references inside code stay as written. Hovering a link to a GitHub pull request or issue, whether written out in full or as a qualified reference, shows a card with its title, state, and author, and a pull request also shows its lines changed and whether it can merge. The card comes from GitHub's API, signed in as you when OpenKnowledge can use your GitHub sign-in, so private repositories you can read work too; with a sign-in, an open pull request also shows what it is waiting on, such as its place in the merge queue, a requested review, or failing checks. It follows the [link previews](../reference/configuration.mdx#link-previews) setting, and a reference GitHub can't answer for stays a plain link.
-When a window at least 48rem wide is too narrow to fit both, the right-side Terminal and Agents panel cannot remain open together. Opening either one closes the other and shows an in-app notice; closing the visible panel does not reopen the one that was displaced. Below 48rem only one of Editor, Agents and Terminal is shown at a time instead; see [Narrow windows](#narrow-windows).
+The editor, the Agents panel and the terminal split the window by proportion. Drag the gap between two of them, or focus it and use the arrow keys, to change their shares; each project remembers its own arrangement. Opening a panel never closes another one to make room. Dragging a gap stops at each panel's minimum size; when there is not room for the open panels' minimum sizes, they shrink below them in proportion, so a right-side Terminal between the editor and the Agents panel can drop under 40 columns. Below 48rem only one of Editor, Agents and Terminal is shown at a time; see [Narrow windows](#narrow-windows).
The shells run at full user privilege. To turn the terminal off for a project on this machine, use **Settings ▸ Terminal** or set `terminal.enabled: false` in `.ok/local/config.yml` (see the [configuration reference](../reference/configuration.mdx)); the setting is project-local, never shared via git or sync, and not agent-settable — only a human can flip it. On Windows, set `terminal.shell` in the same file to an absolute shell executable if you want to override automatic PowerShell and `cmd.exe` discovery. PowerShell, `cmd.exe`, and Git Bash (`bash.exe`) support OpenKnowledge-managed launches (agent chat tabs and fixed commands such as **Resolve in terminal** or **Install Slidev**) and dropped-file path insertion. A different existing executable remains active for plain terminal tabs and shows a capability notice; requested agent and command launches open only the plain shell without running the agent or command, and dropped-file paths are refused. Enter WSL by running `wsl` inside a supported shell rather than setting `wsl.exe` as the override.
@@ -219,14 +219,12 @@ Hiding the editor hides all of it: the file sidebar, the tabs, the document, the
The panels that are still open fill the space:
-- A bottom terminal takes the full height of its column, and keeps its share of the row beside the Agents panel when that is open.
-- A right-side terminal and the Agents panel share the row in proportion to their widths.
+- A bottom terminal fills the column it shares with the editor, top to bottom, and beside the Agents panel that column takes the same share of the row whether the editor is shown or hidden.
+- A right-side terminal and the Agents panel divide the row in the ratio of their shares, as far as each one's minimum width allows.
- A single remaining panel fills the window.
- The Agents panel on its own keeps the conversation and the message box at a comfortable reading width, centered.
-The [side-panel width rule](#terminal) still applies while the editor is hidden, with the same width threshold as when the editor is shown. That threshold still counts room for the editor and the document panel, so opening the right-side terminal or the Agents panel can close the other one, with the same notice, even when both would fit on screen.
-
-Dragging a divider while the editor is hidden is temporary: showing the editor puts every panel back to the size it had before the editor was hidden.
+Sizes you drag while the editor is hidden are kept. A bottom terminal shares its column with the editor, so dragging the gap beside the Agents panel also sets the editor's width; with a right-side terminal, the editor keeps its own size.
Any deliberate way of opening a document shows the editor again with that document: search and quick open, links in the Agents panel and the terminal, an agent navigating, deep and share links, back and forward, creating a page, the sync badge, dialogs that open a file, and opening the document that is already active. Agent navigation includes following an agent with a chat's **Follow the agent's edits** toggle, so with it on, the next agent turn that moves to a document shows the editor again. Editor shortcuts and menu actions show the editor first and then act: the tab shortcuts, reopening or closing a tab, **New File**, **New Folder**, **New from Template…**, **Rename**, **Duplicate**, **Move to Trash**, showing or hiding the document panel or the file sidebar, the file sidebar's view options (hidden files, `.ok` folders, Markdown only, the skills section) and **Expand all** / **Collapse all**, **Skills**, **Blob Run**, **Initialize starter pack** once it applies, and **View in source**. Reloading the window or restarting the app never shows a hidden editor.
diff --git a/packages/app/src/components/DockWorkspace.dom.test.tsx b/packages/app/src/components/DockWorkspace.dom.test.tsx
new file mode 100644
index 000000000..1525746d6
--- /dev/null
+++ b/packages/app/src/components/DockWorkspace.dom.test.tsx
@@ -0,0 +1,575 @@
+import * as actualLinguiMacro from '@lingui/react/macro';
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { type ReactNode, useState } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import type { DockExtent, DockLayout } from '@/lib/dock-layout';
+import { DEFAULT_DOCK_TREE, type DockNode, moveDockPane } from '@/lib/dock-tree';
+import type { PaneId } from '@/lib/pane-visibility-store';
+import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
+
+vi.doMock('@lingui/react/macro', () => ({
+ ...actualLinguiMacro,
+ Trans: ({ children }: { children: ReactNode }) => children,
+ useLingui: () => ({ t: renderLinguiTemplate }),
+}));
+
+const { DockWorkspace } = await import('./DockWorkspace');
+
+const WIDTH = 1200;
+const HEIGHT = 800;
+const GAP = 8;
+const MINS: Record<PaneId, DockExtent> = {
+ editor: { width: 340, height: 180 },
+ agents: { width: 290, height: 170 },
+ terminal: { width: 325, height: 120 },
+};
+const LABELS: Record<PaneId, string> = { editor: 'Editor', agents: 'Agents', terminal: 'Terminal' };
+const EVERY_PANE: Record<PaneId, boolean> = { editor: true, agents: true, terminal: true };
+
+let direction = 'ltr';
+let workspaceSize = { width: WIDTH, height: HEIGHT };
+let resizeCallbacks: ResizeObserverCallback[] = [];
+
+beforeEach(() => {
+ direction = 'ltr';
+ workspaceSize = { width: WIDTH, height: HEIGHT };
+ resizeCallbacks = [];
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(callback: ResizeObserverCallback) {
+ resizeCallbacks.push(callback);
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (
+ this: HTMLElement,
+ ) {
+ const { width, height } = this.hasAttribute('data-dock-workspace')
+ ? workspaceSize
+ : { width: 0, height: 0 };
+ return {
+ x: 0,
+ y: 0,
+ top: 0,
+ left: 0,
+ right: width,
+ bottom: height,
+ width,
+ height,
+ toJSON() {},
+ } as DOMRect;
+ });
+ const realComputedStyle = window.getComputedStyle.bind(window);
+ vi.spyOn(window, 'getComputedStyle').mockImplementation((element, pseudo) => {
+ const style = realComputedStyle(element, pseudo);
+ return new Proxy(style, {
+ get(target, property) {
+ if (property === 'direction') return direction;
+ const value = Reflect.get(target, property);
+ return typeof value === 'function' ? value.bind(target) : value;
+ },
+ });
+ });
+});
+
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+function unit(pane: PaneId): HTMLElement {
+ const element = document.querySelector<HTMLElement>(`[data-dock-unit="${pane}"]`);
+ if (element === null) throw new Error(`no ${pane} unit`);
+ return element;
+}
+
+function px(
+ element: HTMLElement,
+ property: 'width' | 'height' | 'insetInlineStart' | 'insetBlockStart',
+) {
+ return Number.parseFloat(element.style[property]);
+}
+
+function Workspace({
+ tree,
+ visible = EVERY_PANE,
+ onTreeChange = () => {},
+ onLayoutChange,
+ units,
+}: {
+ tree: DockNode;
+ visible?: Record<PaneId, boolean>;
+ onTreeChange?: (update: (tree: DockNode) => DockNode) => void;
+ onLayoutChange?: (layout: DockLayout) => void;
+ units?: Record<PaneId, ReactNode>;
+}) {
+ return (
+ <DockWorkspace
+ tree={tree}
+ visible={visible}
+ units={units ?? { editor: 'editor', agents: 'agents', terminal: 'terminal' }}
+ gap={GAP}
+ minExtent={(pane) => MINS[pane]}
+ paneLabel={(pane) => LABELS[pane]}
+ onTreeChange={onTreeChange}
+ onLayoutChange={onLayoutChange}
+ />
+ );
+}
+
+describe('DockWorkspace', () => {
+ test('places each unit from the tree, with the gap between them', () => {
+ render(<Workspace tree={DEFAULT_DOCK_TREE} />);
+ const editor = unit('editor');
+ const terminal = unit('terminal');
+ const agents = unit('agents');
+ expect(px(editor, 'insetInlineStart')).toBe(0);
+ expect(px(agents, 'insetInlineStart')).toBe(px(editor, 'width') + GAP);
+ expect(px(agents, 'insetInlineStart') + px(agents, 'width')).toBe(WIDTH);
+ expect(px(terminal, 'insetBlockStart')).toBe(px(editor, 'height') + GAP);
+ expect(px(terminal, 'insetBlockStart') + px(terminal, 'height')).toBe(HEIGHT);
+ });
+
+ test('lays the units out again when the workspace is resized, keeping their shares', () => {
+ render(<Workspace tree={DEFAULT_DOCK_TREE} />);
+ const agentsShare = px(unit('agents'), 'width') / (WIDTH - GAP);
+
+ workspaceSize = { width: 1100, height: 600 };
+ act(() => {
+ for (const callback of resizeCallbacks) callback([], {} as ResizeObserver);
+ });
+
+ expect(px(unit('agents'), 'insetInlineStart') + px(unit('agents'), 'width')).toBe(1100);
+ expect(px(unit('agents'), 'height')).toBe(600);
+ expect(px(unit('terminal'), 'insetBlockStart') + px(unit('terminal'), 'height')).toBe(600);
+ expect(px(unit('agents'), 'width') / (1100 - GAP)).toBeCloseTo(agentsShare, 2);
+ });
+
+ test('keeps a pane that is off inside the workspace when the workspace narrows', () => {
+ const { rerender } = render(<Workspace tree={DEFAULT_DOCK_TREE} />);
+ rerender(<Workspace tree={DEFAULT_DOCK_TREE} visible={{ ...EVERY_PANE, agents: false }} />);
+ const agents = unit('agents');
+ expect(px(agents, 'insetInlineStart')).toBeGreaterThan(600);
+
+ workspaceSize = { width: 600, height: 500 };
+ act(() => {
+ for (const callback of resizeCallbacks) callback([], {} as ResizeObserver);
+ });
+
+ expect(agents.classList.contains('invisible')).toBe(true);
+ expect(px(agents, 'insetInlineStart') + px(agents, 'width')).toBeLessThanOrEqual(600);
+ expect(px(agents, 'insetBlockStart') + px(agents, 'height')).toBeLessThanOrEqual(500);
+ expect(px(unit('editor'), 'insetInlineStart') + px(unit('editor'), 'width')).toBe(600);
+ });
+
+ test('hides a pane that was never on and gives its room to the others', () => {
+ render(<Workspace tree={DEFAULT_DOCK_TREE} visible={{ ...EVERY_PANE, terminal: false }} />);
+ expect(unit('terminal').hidden).toBe(true);
+ expect(unit('terminal').hasAttribute('inert')).toBe(true);
+ expect(px(unit('editor'), 'height')).toBe(HEIGHT);
+ expect(screen.getAllByRole('separator')).toHaveLength(1);
+ });
+
+ test('keeps a pane that turns off at its last size, invisible and inert, so its content does not reflow', () => {
+ const { rerender } = render(<Workspace tree={DEFAULT_DOCK_TREE} />);
+ const width = px(unit('editor'), 'width');
+ const height = px(unit('editor'), 'height');
+ rerender(<Workspace tree={DEFAULT_DOCK_TREE} visible={{ ...EVERY_PANE, editor: false }} />);
+ const editor = unit('editor');
+ expect(editor.hidden).toBe(false);
+ expect(editor.hasAttribute('inert')).toBe(true);
+ expect(editor.classList.contains('invisible')).toBe(true);
+ expect(px(editor, 'width')).toBe(width);
+ expect(px(editor, 'height')).toBe(height);
+ expect(px(unit('terminal'), 'insetBlockStart')).toBe(0);
+ });
+
+ test('names each seam after the pane it resizes and reports its position', () => {
+ render(<Workspace tree={DEFAULT_DOCK_TREE} />);
+ const agentsSeam = screen.getByRole('separator', { name: 'Resize Agents' });
+ expect(agentsSeam.getAttribute('aria-orientation')).toBe('vertical');
+ expect(agentsSeam.getAttribute('aria-controls')).toBe('dock-unit-agents');
+ const terminalSeam = screen.getByRole('separator', { name: 'Resize Terminal' });
+ expect(terminalSeam.getAttribute('aria-orientation')).toBe('horizontal');
+ expect(terminalSeam.getAttribute('aria-controls')).toBe('dock-unit-terminal');
+ const now = Number(agentsSeam.getAttribute('aria-valuenow'));
+ expect(now).toBe(Math.round((px(unit('agents'), 'width') / (WIDTH - GAP)) * 100));
+ expect(now).toBeGreaterThanOrEqual(Number(agentsSeam.getAttribute('aria-valuemin')));
+ expect(now).toBeLessThanOrEqual(Number(agentsSeam.getAttribute('aria-valuemax')));
+ });
+
+ test('arrow keys move a seam by a step, Home shrinks the pane it names to its minimum and End grows it to its maximum', () => {
+ function Harness() {
+ const [tree, setTree] = useState<DockNode>(DEFAULT_DOCK_TREE);
+ return <Workspace tree={tree} onTreeChange={setTree} />;
+ }
+ render(<Harness />);
+ const seam = screen.getByRole('separator', { name: 'Resize Agents' });
+ const before = px(unit('editor'), 'width');
+ fireEvent.keyDown(seam, { key: 'ArrowRight' });
+ expect(px(unit('editor'), 'width')).toBe(before + 16);
+ fireEvent.keyDown(seam, { key: 'ArrowLeft', shiftKey: true });
+ expect(px(unit('editor'), 'width')).toBe(before + 16 - 64);
+ fireEvent.keyDown(seam, { key: 'Home' });
+ expect(px(unit('agents'), 'width')).toBe(MINS.agents.width);
+ expect(seam.getAttribute('aria-valuenow')).toBe(seam.getAttribute('aria-valuemin'));
+ fireEvent.keyDown(seam, { key: 'End' });
+ expect(px(unit('editor'), 'width')).toBe(MINS.editor.width);
+ expect(seam.getAttribute('aria-valuenow')).toBe(seam.getAttribute('aria-valuemax'));
+ });
+
+ test('up and down arrows move a seam between stacked panes', () => {
+ function Harness() {
+ const [tree, setTree] = useState<DockNode>(DEFAULT_DOCK_TREE);
+ return <Workspace tree={tree} onTreeChange={setTree} />;
+ }
+ render(<Harness />);
+ const seam = screen.getByRole('separator', { name: 'Resize Terminal' });
+ const before = px(unit('editor'), 'height');
+ fireEvent.keyDown(seam, { key: 'ArrowUp' });
+ expect(px(unit('editor'), 'height')).toBe(before - 16);
+ fireEvent.keyDown(seam, { key: 'ArrowDown', shiftKey: true });
+ expect(px(unit('editor'), 'height')).toBe(before - 16 + 64);
+ fireEvent.keyDown(seam, { key: 'ArrowLeft' });
+ expect(px(unit('editor'), 'height')).toBe(before - 16 + 64);
+ });
+
+ test.each(['altKey', 'ctrlKey', 'metaKey'] as const)(
+ 'a seam key pressed with %s leaves the layout alone and reaches the shortcut that owns it',
+ (modifier) => {
+ function Harness() {
+ const [tree, setTree] = useState<DockNode>(DEFAULT_DOCK_TREE);
+ return <Workspace tree={tree} onTreeChange={setTree} />;
+ }
+ render(<Harness />);
+ const agentsSeam = screen.getByRole('separator', { name: 'Resize Agents' });
+ const terminalSeam = screen.getByRole('separator', { name: 'Resize Terminal' });
+ const width = px(unit('editor'), 'width');
+ const height = px(unit('editor'), 'height');
+ for (const key of ['ArrowLeft', 'ArrowRight', 'Home', 'End']) {
+ expect(fireEvent.keyDown(agentsSeam, { key, [modifier]: true })).toBe(true);
+ }
+ for (const key of ['ArrowUp', 'ArrowDown']) {
+ expect(fireEvent.keyDown(terminalSeam, { key, [modifier]: true, shiftKey: true })).toBe(
+ true,
+ );
+ }
+ expect(px(unit('editor'), 'width')).toBe(width);
+ expect(px(unit('editor'), 'height')).toBe(height);
+ fireEvent.keyDown(agentsSeam, { key: 'ArrowRight' });
+ expect(px(unit('editor'), 'width')).toBe(width + 16);
+ },
+ );
+
+ test('right to left, the arrow toward the start grows the pane before the seam', () => {
+ direction = 'rtl';
+ function Harness() {
+ const [tree, setTree] = useState<DockNode>(DEFAULT_DOCK_TREE);
+ return <Workspace tree={tree} onTreeChange={setTree} />;
+ }
+ render(<Harness />);
+ const seam = screen.getByRole('separator', { name: 'Resize Agents' });
+ const before = px(unit('editor'), 'width');
+ fireEvent.keyDown(seam, { key: 'ArrowLeft' });
+ expect(px(unit('editor'), 'width')).toBe(before + 16);
+ });
+
+ test('a switch to right to left after mount turns the arrow keys and a drag around', () => {
+ function Harness() {
+ const [tree, setTree] = useState<DockNode>(DEFAULT_DOCK_TREE);
+ return <Workspace tree={tree} onTreeChange={setTree} />;
+ }
+ render(<Harness />);
+ direction = 'rtl';
+ const seam = screen.getByRole('separator', { name: 'Resize Agents' });
+ const before = px(unit('editor'), 'width');
+
+ fireEvent.keyDown(seam, { key: 'ArrowLeft' });
+ expect(px(unit('editor'), 'width')).toBe(before + 16);
+
+ fireEvent.pointerDown(seam, { button: 0, pointerId: 1, clientX: 500 });
+ fireEvent.pointerMove(seam, { pointerId: 1, clientX: 470 });
+ fireEvent.pointerUp(seam, { pointerId: 1, clientX: 470 });
+ expect(px(unit('editor'), 'width')).toBe(before + 16 + 30);
+ });
+
+ test('a drag whose seam goes away ends, and the remaining units take the pointer again', () => {
+ const onTreeChange = vi.fn();
+ const { rerender } = render(<Workspace tree={DEFAULT_DOCK_TREE} onTreeChange={onTreeChange} />);
+ const workspace = document.querySelector('[data-dock-workspace]');
+ const seam = screen.getByRole('separator', { name: 'Resize Terminal' });
+ fireEvent.pointerDown(seam, { button: 0, pointerId: 1, clientY: 500 });
+ fireEvent.pointerMove(seam, { pointerId: 1, clientY: 450 });
+ expect(workspace?.hasAttribute('data-dragging')).toBe(true);
+ expect(unit('editor').classList.contains('pointer-events-none')).toBe(true);
+
+ rerender(
+ <Workspace
+ tree={DEFAULT_DOCK_TREE}
+ visible={{ ...EVERY_PANE, terminal: false }}
+ onTreeChange={onTreeChange}
+ />,
+ );
+
+ expect(screen.queryByRole('separator', { name: 'Resize Terminal' })).toBeNull();
+ expect(workspace?.hasAttribute('data-dragging')).toBe(false);
+ expect(unit('editor').classList.contains('pointer-events-none')).toBe(false);
+ expect(unit('agents').classList.contains('pointer-events-none')).toBe(false);
+ fireEvent.pointerUp(window, { pointerId: 1, clientY: 450 });
+ expect(onTreeChange).not.toHaveBeenCalled();
+ });
+
+ test('a drag follows the pointer anywhere in the window and ends on its release there', () => {
+ function Harness({ visible }: { visible: Record<PaneId, boolean> }) {
+ const [tree, setTree] = useState<DockNode>(DEFAULT_DOCK_TREE);
+ return <Workspace tree={tree} visible={visible} onTreeChange={setTree} />;
+ }
+ const { rerender } = render(<Harness visible={EVERY_PANE} />);
+ const workspace = document.querySelector('[data-dock-workspace]');
+ const seam = screen.getByRole('separator', { name: 'Resize Agents' });
+ const before = px(unit('editor'), 'width');
+ fireEvent.pointerDown(seam, { button: 0, pointerId: 1, clientX: before });
+ rerender(<Harness visible={{ ...EVERY_PANE, terminal: false }} />);
+
+ fireEvent.pointerMove(window, { pointerId: 1, clientX: before - 100 });
+ expect(px(unit('editor'), 'width')).toBe(before - 100);
+ fireEvent.pointerUp(window, { pointerId: 1, clientX: before - 100 });
+
+ expect(workspace?.hasAttribute('data-dragging')).toBe(false);
+ expect(px(unit('editor'), 'width')).toBe(before - 100);
+ });
+
+ test('a drag ends when the tree changes under it, and its release keeps the new tree', () => {
+ let replaceTree: (tree: DockNode) => void = () => {};
+ let ownerTree: DockNode = DEFAULT_DOCK_TREE;
+ function Harness() {
+ const [tree, setTree] = useState<DockNode>(DEFAULT_DOCK_TREE);
+ replaceTree = setTree;
+ ownerTree = tree;
+ return <Workspace tree={tree} onTreeChange={setTree} />;
+ }
+ render(<Harness />);
+ const workspace = document.querySelector('[data-dock-workspace]');
+ const seam = screen.getByRole('separator', { name: 'Resize Agents' });
+ const before = px(unit('editor'), 'width');
+ fireEvent.pointerDown(seam, { button: 0, pointerId: 1, clientX: before });
+ fireEvent.pointerMove(seam, { pointerId: 1, clientX: before - 100 });
+ expect(workspace?.hasAttribute('data-dragging')).toBe(true);
+
+ const moved = moveDockPane(DEFAULT_DOCK_TREE, 'terminal', 'editor', 'end');
+ act(() => replaceTree(moved));
+ expect(workspace?.hasAttribute('data-dragging')).toBe(false);
+ fireEvent.pointerUp(seam, { pointerId: 1, clientX: before - 100 });
+
+ expect(ownerTree).toBe(moved);
+ });
+
+ test('a resize handed to the owner leaves alone any tree but the one it measured', () => {
+ const onTreeChange = vi.fn();
+ render(<Workspace tree={DEFAULT_DOCK_TREE} onTreeChange={onTreeChange} />);
+ fireEvent.keyDown(screen.getByRole('separator', { name: 'Resize Agents' }), {
+ key: 'ArrowLeft',
+ });
+ const update = onTreeChange.mock.calls[0]?.[0] as ((tree: DockNode) => DockNode) | undefined;
+ if (update === undefined) throw new Error('the seam handed the owner no resize');
+ const moved = moveDockPane(DEFAULT_DOCK_TREE, 'terminal', 'editor', 'end');
+
+ expect(update(moved)).toBe(moved);
+ expect(update(DEFAULT_DOCK_TREE)).not.toBe(DEFAULT_DOCK_TREE);
+ });
+
+ test('a click on a seam, or a key that would push it past its bound, leaves the tree alone', () => {
+ const changes: unknown[] = [];
+ function Harness() {
+ const [tree, setTree] = useState<DockNode>(DEFAULT_DOCK_TREE);
+ return (
+ <Workspace
+ tree={tree}
+ onTreeChange={(next) => {
+ changes.push(next);
+ setTree(next);
+ }}
+ />
+ );
+ }
+ render(<Harness />);
+ const workspace = document.querySelector('[data-dock-workspace]');
+ const seam = screen.getByRole('separator', { name: 'Resize Agents' });
+
+ fireEvent.pointerDown(seam, { button: 0, pointerId: 1, clientX: 500 });
+ expect(workspace?.hasAttribute('data-dragging')).toBe(true);
+ fireEvent.pointerUp(seam, { pointerId: 1, clientX: 500 });
+ expect(workspace?.hasAttribute('data-dragging')).toBe(false);
+ expect(changes).toHaveLength(0);
+
+ fireEvent.keyDown(seam, { key: 'Home' });
+ expect(changes).toHaveLength(1);
+ fireEvent.keyDown(seam, { key: 'Home' });
+ expect(changes).toHaveLength(1);
+ });
+
+ test('a focused seam keeps focus when hiding a pane or moving the terminal changes what it follows', () => {
+ const right = moveDockPane(DEFAULT_DOCK_TREE, 'terminal', 'editor', 'end');
+ const { rerender } = render(<Workspace tree={DEFAULT_DOCK_TREE} />);
+ const seam = screen.getByRole('separator', { name: 'Resize Agents' });
+ act(() => seam.focus());
+ expect(document.activeElement).toBe(seam);
+
+ rerender(<Workspace tree={DEFAULT_DOCK_TREE} visible={{ ...EVERY_PANE, terminal: false }} />);
+ expect(document.activeElement).toBe(seam);
+ expect(seam.getAttribute('aria-label')).toBe('Resize Agents');
+
+ rerender(<Workspace tree={right} />);
+ expect(document.activeElement).toBe(seam);
+
+ rerender(<Workspace tree={right} visible={{ ...EVERY_PANE, terminal: false }} />);
+ expect(document.activeElement).toBe(seam);
+ expect(seam.getAttribute('aria-label')).toBe('Resize Agents');
+ });
+
+ test('units and seams sit in document order the way they are arranged, and a placement move moves no unit', () => {
+ function order() {
+ return Array.from(
+ document.querySelectorAll('[data-dock-workspace] [data-dock-unit], [role="separator"]'),
+ (element) => element.getAttribute('data-dock-unit') ?? element.getAttribute('aria-label'),
+ );
+ }
+ const { rerender } = render(<Workspace tree={DEFAULT_DOCK_TREE} />);
+ expect(order()).toEqual(['editor', 'Resize Terminal', 'terminal', 'Resize Agents', 'agents']);
+ const workspace = document.querySelector('[data-dock-workspace]');
+ if (workspace === null) throw new Error('no dock workspace');
+ const removed: Node[] = [];
+ const observer = new MutationObserver((records) => {
+ for (const record of records) removed.push(...record.removedNodes);
+ });
+ observer.observe(workspace, { childList: true });
+
+ rerender(<Workspace tree={moveDockPane(DEFAULT_DOCK_TREE, 'terminal', 'editor', 'end')} />);
+ for (const record of observer.takeRecords()) removed.push(...record.removedNodes);
+ observer.disconnect();
+
+ expect(order()).toEqual(['editor', 'Resize Terminal', 'terminal', 'Resize Agents', 'agents']);
+ expect(
+ removed.filter((node) => node instanceof HTMLElement && node.hasAttribute('data-dock-unit')),
+ ).toEqual([]);
+ });
+
+ test('a pointer drag previews the move and commits it once on release', () => {
+ const onTreeChange = vi.fn();
+ render(<Workspace tree={DEFAULT_DOCK_TREE} onTreeChange={onTreeChange} />);
+ const seam = screen.getByRole('separator', { name: 'Resize Agents' });
+ const before = px(unit('editor'), 'width');
+ fireEvent.pointerDown(seam, { button: 0, pointerId: 1, clientX: before });
+ fireEvent.pointerMove(seam, { pointerId: 1, clientX: before - 100 });
+ expect(px(unit('editor'), 'width')).toBe(before - 100);
+ expect(onTreeChange).not.toHaveBeenCalled();
+ fireEvent.pointerUp(seam, { pointerId: 1, clientX: before - 100 });
+ expect(onTreeChange).toHaveBeenCalledTimes(1);
+ });
+
+ test('a drag with a button other than the primary one does nothing', () => {
+ const onTreeChange = vi.fn();
+ render(<Workspace tree={DEFAULT_DOCK_TREE} onTreeChange={onTreeChange} />);
+ const workspace = document.querySelector('[data-dock-workspace]');
+ const seam = screen.getByRole('separator', { name: 'Resize Agents' });
+ const before = px(unit('editor'), 'width');
+ fireEvent.pointerDown(seam, { button: 2, pointerId: 1, clientX: before });
+ expect(workspace?.hasAttribute('data-dragging')).toBe(false);
+ fireEvent.pointerMove(seam, { pointerId: 1, clientX: before - 100 });
+ fireEvent.pointerUp(seam, { pointerId: 1, clientX: before - 100 });
+ expect(px(unit('editor'), 'width')).toBe(before);
+ expect(onTreeChange).not.toHaveBeenCalled();
+ });
+
+ test('another pointer neither moves nor ends a drag', () => {
+ function Harness() {
+ const [tree, setTree] = useState<DockNode>(DEFAULT_DOCK_TREE);
+ return <Workspace tree={tree} onTreeChange={setTree} />;
+ }
+ render(<Harness />);
+ const workspace = document.querySelector('[data-dock-workspace]');
+ const seam = screen.getByRole('separator', { name: 'Resize Agents' });
+ const before = px(unit('editor'), 'width');
+ fireEvent.pointerDown(seam, { button: 0, pointerId: 1, clientX: before });
+ fireEvent.pointerMove(window, { pointerId: 2, clientX: before - 200 });
+ fireEvent.pointerCancel(window, { pointerId: 2 });
+ fireEvent.pointerUp(window, { pointerId: 2, clientX: before - 200 });
+ expect(workspace?.hasAttribute('data-dragging')).toBe(true);
+ expect(px(unit('editor'), 'width')).toBe(before);
+
+ fireEvent.pointerMove(window, { pointerId: 1, clientX: before - 100 });
+ fireEvent.pointerUp(window, { pointerId: 1, clientX: before - 100 });
+ expect(workspace?.hasAttribute('data-dragging')).toBe(false);
+ expect(px(unit('editor'), 'width')).toBe(before - 100);
+ });
+
+ test('a workspace unmounted mid-drag hands the owner nothing when the pointer moves on or lifts', () => {
+ const onTreeChange = vi.fn();
+ const { unmount } = render(<Workspace tree={DEFAULT_DOCK_TREE} onTreeChange={onTreeChange} />);
+ const seam = screen.getByRole('separator', { name: 'Resize Agents' });
+ const before = px(unit('editor'), 'width');
+ fireEvent.pointerDown(seam, { button: 0, pointerId: 1, clientX: before });
+ fireEvent.pointerMove(window, { pointerId: 1, clientX: before - 100 });
+ expect(document.querySelector('[data-dock-workspace]')?.hasAttribute('data-dragging')).toBe(
+ true,
+ );
+
+ unmount();
+ fireEvent.pointerMove(window, { pointerId: 1, clientX: before - 150 });
+ fireEvent.pointerUp(window, { pointerId: 1, clientX: before - 150 });
+
+ expect(onTreeChange).not.toHaveBeenCalled();
+ });
+
+ test('a cancelled drag puts the seam back', () => {
+ const onTreeChange = vi.fn();
+ render(<Workspace tree={DEFAULT_DOCK_TREE} onTreeChange={onTreeChange} />);
+ const seam = screen.getByRole('separator', { name: 'Resize Agents' });
+ const before = px(unit('editor'), 'width');
+ fireEvent.pointerDown(seam, { button: 0, pointerId: 1, clientX: before });
+ fireEvent.pointerMove(seam, { pointerId: 1, clientX: before - 100 });
+ fireEvent.pointerCancel(seam, { pointerId: 1 });
+ expect(px(unit('editor'), 'width')).toBe(before);
+ expect(onTreeChange).not.toHaveBeenCalled();
+ });
+
+ test('reports the layout it drew', () => {
+ const onLayoutChange = vi.fn();
+ render(<Workspace tree={DEFAULT_DOCK_TREE} onLayoutChange={onLayoutChange} />);
+ const layout = onLayoutChange.mock.calls.at(-1)?.[0] as DockLayout;
+ expect([...layout.panes.keys()].toSorted()).toEqual(['agents', 'editor', 'terminal']);
+ });
+
+ test('keeps each unit mounted when the tree moves it', () => {
+ let mounts = 0;
+ function Counter({ name }: { name: string }) {
+ const [id] = useState(() => {
+ mounts += 1;
+ return mounts;
+ });
+ return <span data-testid={name}>{id}</span>;
+ }
+ const units = {
+ editor: <Counter name="editor-content" />,
+ agents: <Counter name="agents-content" />,
+ terminal: <Counter name="terminal-content" />,
+ };
+ const { rerender } = render(<Workspace tree={DEFAULT_DOCK_TREE} units={units} />);
+ expect(mounts).toBe(3);
+ act(() => {
+ rerender(
+ <Workspace
+ tree={moveDockPane(DEFAULT_DOCK_TREE, 'terminal', 'agents', 'top')}
+ units={units}
+ />,
+ );
+ });
+ expect(mounts).toBe(3);
+ expect(px(unit('terminal'), 'insetInlineStart')).toBe(px(unit('agents'), 'insetInlineStart'));
+ });
+});
diff --git a/packages/app/src/components/DockWorkspace.tsx b/packages/app/src/components/DockWorkspace.tsx
new file mode 100644
index 000000000..563c41fa8
--- /dev/null
+++ b/packages/app/src/components/DockWorkspace.tsx
@@ -0,0 +1,349 @@
+import { useLingui } from '@lingui/react/macro';
+import {
+ Fragment,
+ type KeyboardEvent,
+ type PointerEvent,
+ type ReactNode,
+ useEffect,
+ useEffectEvent,
+ useLayoutEffect,
+ useRef,
+ useState,
+} from 'react';
+import { flushSync } from 'react-dom';
+import {
+ clampDockSeam,
+ type DockExtent,
+ type DockLayout,
+ type DockRect,
+ type DockSeam,
+ dockSeamPercent,
+ dockSeamShares,
+ EMPTY_DOCK_LAYOUT,
+ layoutDock,
+} from '@/lib/dock-layout';
+import { DOCK_PANES, type DockNode, resizeDockGroup, visibleDockTree } from '@/lib/dock-tree';
+import type { PaneId } from '@/lib/pane-visibility-store';
+import { cn } from '@/lib/utils';
+
+const KEYBOARD_STEP_PX = 16;
+const KEYBOARD_LARGE_STEP_PX = 64;
+
+function dockUnitId(pane: PaneId): string {
+ return `dock-unit-${pane}`;
+}
+
+interface DockWorkspaceProps {
+ readonly tree: DockNode;
+ readonly visible: Readonly<Record<PaneId, boolean>>;
+ readonly units: Readonly<Record<PaneId, ReactNode>>;
+ readonly gap: number;
+ readonly minExtent: (pane: PaneId) => DockExtent;
+ readonly paneLabel: (pane: PaneId) => string;
+ readonly onTreeChange: (update: (tree: DockNode) => DockNode) => void;
+ readonly onLayoutChange?: (layout: DockLayout) => void;
+}
+
+interface DockDrag {
+ readonly tree: DockNode;
+ readonly seam: DockSeam;
+ readonly key: string;
+ readonly origin: number;
+ readonly rtl: boolean;
+ readonly length: number;
+}
+
+function seamKey(seam: DockSeam): string {
+ return `${seam.path.join('.')}:${seam.index}`;
+}
+
+function dragLength(drag: DockDrag, event: { clientX: number; clientY: number }): number {
+ const row = drag.seam.direction === 'row';
+ const moved = (row ? event.clientX : event.clientY) - drag.origin;
+ const delta = row && drag.rtl ? -moved : moved;
+ return (drag.seam.lengths[drag.seam.index] ?? 0) + delta;
+}
+
+function layoutSignature(layout: DockLayout): string {
+ return DOCK_PANES.map((pane) => {
+ const rect = layout.panes.get(pane);
+ return rect === undefined
+ ? `${pane}:-`
+ : `${pane}:${rect.x},${rect.y},${rect.width},${rect.height}`;
+ }).join('|');
+}
+
+function withinBounds(rect: DockRect, bounds: DockRect | null): DockRect {
+ if (bounds === null) return rect;
+ const width = Math.min(rect.width, bounds.width);
+ const height = Math.min(rect.height, bounds.height);
+ return {
+ x: Math.max(0, Math.min(rect.x, bounds.width - width)),
+ y: Math.max(0, Math.min(rect.y, bounds.height - height)),
+ width,
+ height,
+ };
+}
+
+function placement(rect: DockRect) {
+ return {
+ insetInlineStart: rect.x,
+ insetBlockStart: rect.y,
+ width: rect.width,
+ height: rect.height,
+ };
+}
+
+export function DockWorkspace({
+ tree,
+ visible,
+ units,
+ gap,
+ minExtent,
+ paneLabel,
+ onTreeChange,
+ onLayoutChange,
+}: DockWorkspaceProps) {
+ const { t } = useLingui();
+ const containerRef = useRef<HTMLDivElement | null>(null);
+ const [bounds, setBounds] = useState<DockRect | null>(null);
+ const [drag, setDrag] = useState<DockDrag | null>(null);
+ const [retainedRects, setRetainedRects] = useState<ReadonlyMap<PaneId, DockRect>>(
+ () => new Map(),
+ );
+ const releaseDragRef = useRef<(() => void) | null>(null);
+ const onTreeChangeRef = useRef(onTreeChange);
+ useLayoutEffect(() => {
+ onTreeChangeRef.current = onTreeChange;
+ });
+
+ useLayoutEffect(() => {
+ const element = containerRef.current;
+ if (element === null) return;
+ const measure = () => {
+ const { width, height } = element.getBoundingClientRect();
+ setBounds((current) =>
+ current !== null && current.width === width && current.height === height
+ ? current
+ : { x: 0, y: 0, width, height },
+ );
+ };
+ measure();
+ if (typeof ResizeObserver === 'undefined') return;
+ const observer = new ResizeObserver(() => flushSync(measure));
+ observer.observe(element);
+ return () => observer.disconnect();
+ }, []);
+
+ function layoutOf(shown: DockNode): DockLayout {
+ if (bounds === null) return EMPTY_DOCK_LAYOUT;
+ return layoutDock(
+ visibleDockTree(shown, (pane) => visible[pane]),
+ bounds,
+ gap,
+ minExtent,
+ );
+ }
+ const baseLayout = layoutOf(tree);
+ const liveDrag =
+ drag !== null &&
+ drag.tree === tree &&
+ baseLayout.seams.some((seam) => seamKey(seam) === drag.key)
+ ? drag
+ : null;
+ const layout =
+ liveDrag === null
+ ? baseLayout
+ : layoutOf(
+ resizeDockGroup(tree, liveDrag.seam.path, dockSeamShares(liveDrag.seam, liveDrag.length)),
+ );
+ const signature = layoutSignature(layout);
+ const reportLayout = useEffectEvent(() => {
+ setRetainedRects((current) => {
+ const next = new Map(current);
+ for (const [pane, rect] of layout.panes) next.set(pane, rect);
+ return next;
+ });
+ onLayoutChange?.(layout);
+ });
+ // biome-ignore lint/correctness/useExhaustiveDependencies: the layout signature names every unit rect, so it is the change that owns a report
+ useLayoutEffect(() => {
+ reportLayout();
+ }, [signature]);
+
+ function stopDragging() {
+ releaseDragRef.current?.();
+ releaseDragRef.current = null;
+ setDrag(null);
+ }
+ const dragOutlived = drag !== null && liveDrag === null;
+ const endOutlivedDrag = useEffectEvent(() => {
+ stopDragging();
+ });
+ useLayoutEffect(() => {
+ if (dragOutlived) endOutlivedDrag();
+ }, [dragOutlived]);
+ useEffect(() => () => releaseDragRef.current?.(), []);
+
+ function isRtl(): boolean {
+ const element = containerRef.current;
+ return element !== null && getComputedStyle(element).direction === 'rtl';
+ }
+
+ function commitSeam(base: DockNode, seam: DockSeam, length: number) {
+ if (clampDockSeam(seam, length) === (seam.lengths[seam.index] ?? 0)) return;
+ const shares = dockSeamShares(seam, length);
+ onTreeChangeRef.current((current) =>
+ current === base ? resizeDockGroup(current, seam.path, shares) : current,
+ );
+ }
+
+ function beginDrag(seam: DockSeam, event: PointerEvent<HTMLDivElement>) {
+ if (event.button !== 0) return;
+ event.preventDefault();
+ event.currentTarget.setPointerCapture?.(event.pointerId);
+ stopDragging();
+ const pointerId = event.pointerId;
+ const started: DockDrag = {
+ tree,
+ seam,
+ key: seamKey(seam),
+ origin: seam.direction === 'row' ? event.clientX : event.clientY,
+ rtl: isRtl(),
+ length: seam.lengths[seam.index] ?? 0,
+ };
+ const follow = (moveEvent: globalThis.PointerEvent) => {
+ if (moveEvent.pointerId !== pointerId) return;
+ setDrag({ ...started, length: dragLength(started, moveEvent) });
+ };
+ const finish = (upEvent: globalThis.PointerEvent) => {
+ if (upEvent.pointerId !== pointerId) return;
+ stopDragging();
+ commitSeam(started.tree, started.seam, dragLength(started, upEvent));
+ };
+ const abandon = (cancelEvent: globalThis.PointerEvent) => {
+ if (cancelEvent.pointerId === pointerId) stopDragging();
+ };
+ window.addEventListener('pointermove', follow);
+ window.addEventListener('pointerup', finish);
+ window.addEventListener('pointercancel', abandon);
+ releaseDragRef.current = () => {
+ window.removeEventListener('pointermove', follow);
+ window.removeEventListener('pointerup', finish);
+ window.removeEventListener('pointercancel', abandon);
+ };
+ setDrag(started);
+ }
+
+ function resizeFromKeyboard(seam: DockSeam, event: KeyboardEvent<HTMLDivElement>) {
+ if (event.altKey || event.ctrlKey || event.metaKey) return;
+ const row = seam.direction === 'row';
+ const step = event.shiftKey ? KEYBOARD_LARGE_STEP_PX : KEYBOARD_STEP_PX;
+ const current = seam.lengths[seam.index] ?? 0;
+ let next: number | null = null;
+ if (row && (event.key === 'ArrowLeft' || event.key === 'ArrowRight')) {
+ const towardStart = event.key === (isRtl() ? 'ArrowRight' : 'ArrowLeft');
+ next = current + (towardStart ? -step : step);
+ } else if (!row && (event.key === 'ArrowUp' || event.key === 'ArrowDown')) {
+ next = current + (event.key === 'ArrowUp' ? -step : step);
+ } else if (event.key === 'Home') {
+ next = Number.POSITIVE_INFINITY;
+ } else if (event.key === 'End') {
+ next = 0;
+ }
+ if (next === null) return;
+ event.preventDefault();
+ commitSeam(tree, seam, next);
+ }
+
+ const dragging = liveDrag !== null;
+ const seamBefore = new Map<PaneId, DockSeam>();
+ for (const seam of layout.seams) {
+ const resized = seam.after[0];
+ if (resized !== undefined) seamBefore.set(resized, seam);
+ }
+
+ function renderUnit(pane: PaneId) {
+ const rect = layout.panes.get(pane);
+ const retained = retainedRects.get(pane);
+ const shownRect = rect ?? (retained === undefined ? undefined : withinBounds(retained, bounds));
+ return (
+ <div
+ key="unit"
+ id={dockUnitId(pane)}
+ data-dock-unit={pane}
+ data-dock-unit-off={rect === undefined ? '' : undefined}
+ hidden={shownRect === undefined}
+ inert={rect === undefined}
+ className={cn(
+ 'absolute flex min-h-0 min-w-0',
+ rect === undefined && 'invisible',
+ dragging && 'pointer-events-none',
+ )}
+ style={shownRect === undefined ? undefined : placement(shownRect)}
+ >
+ {units[pane]}
+ </div>
+ );
+ }
+
+ function renderSeam(resized: PaneId, seam: DockSeam) {
+ const row = seam.direction === 'row';
+ const value = dockSeamPercent(seam);
+ const pane = paneLabel(resized);
+ return (
+ // biome-ignore lint/a11y/useSemanticElements: the suggested <hr> is a thematic break, a non-interactive element with no value. This seam is a focusable window splitter that reports and changes a size.
+ <div
+ key="seam"
+ role="separator"
+ tabIndex={0}
+ aria-orientation={row ? 'vertical' : 'horizontal'}
+ aria-valuenow={value.now}
+ aria-valuemin={value.min}
+ aria-valuemax={value.max}
+ aria-controls={seam.after.map(dockUnitId).join(' ')}
+ aria-label={t`Resize ${pane}`}
+ data-dock-seam={seam.direction}
+ data-dragging={liveDrag?.key === seamKey(seam) ? '' : undefined}
+ className={cn(
+ 'group/seam absolute z-20 flex touch-none select-none items-center justify-center rounded-sm',
+ 'before:absolute before:content-[""] focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring',
+ row
+ ? 'cursor-col-resize before:-inset-x-1 before:inset-y-0'
+ : 'cursor-row-resize before:-inset-y-1 before:inset-x-0',
+ )}
+ style={placement(seam.rect)}
+ onPointerDown={(event) => beginDrag(seam, event)}
+ onKeyDown={(event) => resizeFromKeyboard(seam, event)}
+ >
+ <span
+ aria-hidden="true"
+ className={cn(
+ 'pointer-events-none rounded-full bg-border opacity-0 transition-[opacity,background-color] duration-150 ease-out motion-reduce:transition-none',
+ 'group-hover/seam:opacity-100 group-focus-visible/seam:opacity-100 group-data-[dragging]/seam:bg-primary group-data-[dragging]/seam:opacity-100',
+ row ? 'h-8 w-0.5' : 'h-0.5 w-8',
+ )}
+ />
+ </div>
+ );
+ }
+
+ return (
+ <div
+ ref={containerRef}
+ data-dock-workspace=""
+ data-dragging={dragging ? '' : undefined}
+ className={cn('relative min-h-0 min-w-0 flex-1', dragging && 'select-none')}
+ >
+ {DOCK_PANES.map((pane) => {
+ const seam = seamBefore.get(pane);
+ return (
+ <Fragment key={pane}>
+ {seam === undefined ? null : renderSeam(pane, seam)}
+ {renderUnit(pane)}
+ </Fragment>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/packages/app/src/components/EditorArea.composer-surface.dom.test.tsx b/packages/app/src/components/EditorArea.composer-surface.dom.test.tsx
index 72c057ebf..4952da1f7 100644
--- a/packages/app/src/components/EditorArea.composer-surface.dom.test.tsx
+++ b/packages/app/src/components/EditorArea.composer-surface.dom.test.tsx
@@ -3,6 +3,7 @@ import type { ReactNode } from 'react';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { SidebarProvider } from '@/components/ui/sidebar';
import { ConfigProvider } from '@/lib/config-provider';
+import { DEFAULT_DOCK_TREE } from '@/lib/dock-tree';
type EditorMode = 'wysiwyg' | 'source';
@@ -62,9 +63,6 @@ vi.doMock('@/components/EditorSkeleton', () => ({
vi.doMock('@/components/EmptyEditorState', () => ({
EmptyEditorState: () => <div data-testid="empty-editor-state" />,
}));
-vi.doMock('./TerminalDock', () => ({
- TerminalDock: ({ children }: { children: ReactNode }) => <div>{children}</div>,
-}));
vi.doMock('./EditorWorkspace', () => ({
EditorWorkspace: ({
renderPane,
@@ -119,6 +117,8 @@ function renderEditorArea(editorMode: EditorMode) {
onModeChange={() => {}}
activeTab="timeline"
onActiveTabChange={() => {}}
+ dockTree={DEFAULT_DOCK_TREE}
+ onDockTreeChange={() => {}}
/>
</SidebarProvider>
</ConfigProvider>,
diff --git a/packages/app/src/components/EditorArea.dom.test.tsx b/packages/app/src/components/EditorArea.dom.test.tsx
index 6b34cea87..655d16c31 100644
--- a/packages/app/src/components/EditorArea.dom.test.tsx
+++ b/packages/app/src/components/EditorArea.dom.test.tsx
@@ -1,13 +1,15 @@
import type { HocuspocusProvider } from '@hocuspocus/provider';
import { act, cleanup, fireEvent, render as rtlRender, screen } from '@testing-library/react';
-import { type CSSProperties, type ReactNode, useEffect, useRef, useState } from 'react';
-import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import {
- AGENTS_PANEL_WIDTH_KEY,
- getInitialAgentsPanelWidth,
- MIN_AGENTS_PANEL_WIDTH,
-} from '@/lib/agents-panel-width-store';
-import { DOC_PANEL_WIDTH_KEY } from '@/lib/doc-panel-width-store';
+ type ComponentProps,
+ type CSSProperties,
+ type ReactNode,
+ useEffect,
+ useRef,
+ useState,
+} from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { DEFAULT_DOCK_TREE, type DockNode, moveDockPane } from '@/lib/dock-tree';
import {
__resetPaneVisibilityStoreForTests,
type PaneId,
@@ -15,11 +17,8 @@ import {
paneVisibilityStore,
} from '@/lib/pane-visibility-store';
import { SIDEBAR_PINS_KEY } from '@/lib/sidebar-pin-store';
-import {
- expectVisualClassTokens,
- expectVisualClassTokensAbsent,
-} from '@/test-utils/visual-contract';
import type { PanelTab } from './DocPanel';
+import type { SessionPlacements } from './EditorArea';
import { FileListHostProvider } from './FileListHost';
type SettingsDialogShellProps = {
@@ -30,25 +29,11 @@ type SettingsDialogShellProps = {
let settingsRouteOpen = false;
let closeSettingsRouteMock = vi.fn(() => {});
let shellProps: SettingsDialogShellProps[] = [];
-let toastInfoMessages: string[] = [];
-const railPanelOnResizeById = new Map<
+const panelOnResizeById = new Map<
string,
((size: { asPercentage: number; inPixels: number }) => void) | null
>();
-vi.doMock('sonner', async (importOriginal) => {
- const actual = await importOriginal<typeof import('sonner')>();
- return {
- ...actual,
- toast: {
- ...actual.toast,
- info: (message: string) => {
- toastInfoMessages.push(message);
- },
- },
- };
-});
-
vi.doMock('@/lib/perf', () => ({
mark: () => {},
ProfilerBoundary: ({ children }: { children: ReactNode }) => children,
@@ -168,36 +153,10 @@ vi.doMock('@/components/EmptyEditorState', () => ({
),
}));
-let terminalDockMounts = 0;
vi.doMock('@/components/EditorSkeleton', () => ({
EditorSkeleton: () => <div data-testid="editor-skeleton" />,
}));
-vi.doMock('./TerminalDock', () => ({
- TerminalDock: ({
- children,
- placement,
- visible,
- }: {
- children: ReactNode;
- placement?: string;
- visible?: boolean;
- }) => {
- useEffect(() => {
- terminalDockMounts += 1;
- }, []);
- return (
- <div
- data-testid="terminal-dock"
- data-placement={placement ?? 'bottom'}
- data-visible={String(visible)}
- >
- {children}
- </div>
- );
- },
-}));
-
let editorWorkspaceMounts = 0;
vi.doMock('./EditorWorkspace', () => ({
EditorWorkspace: ({
@@ -227,56 +186,63 @@ vi.doMock('./EditorWorkspace', () => ({
},
}));
-type EditorRow = 'outer' | 'inner';
type MockLayout = Record<string, number>;
-type LayoutChangedHandler = (layout: MockLayout, meta: { isUserInteraction: boolean }) => void;
const INNER_LAYOUT_DOC_CLOSED: MockLayout = { 'workspace-main': 100, 'doc-panel': 0 };
-let groupLayout: MockLayout = {};
+const WORKSPACE_WIDTH_PX = 1360;
+const WORKSPACE_HEIGHT_PX = 800;
let innerLayout: MockLayout = { ...INNER_LAYOUT_DOC_CLOSED };
-let groupSetLayoutCalls: MockLayout[] = [];
let innerSetLayoutCalls: MockLayout[] = [];
-let rejectNextGroupLayoutWrite = false;
-let rejectGroupLayoutWrites = false;
-let groupOnLayoutChanged: LayoutChangedHandler | null = null;
-let groupOnLayoutChange: ((layout: MockLayout) => void) | null = null;
-const innerRowHandlers: {
- onLayoutChanged: LayoutChangedHandler | null;
- onLayoutChange: ((layout: MockLayout) => void) | null;
-} = {
- onLayoutChanged: null,
- onLayoutChange: null,
-};
+let innerSetLayoutPx: number[] = [];
+let innerOnLayoutChange: ((layout: MockLayout) => void) | null = null;
let panelIsCollapsed = false;
-let mockGroupPx = 1360;
-let mockInnerPx: number | null = null;
+let mockEditorUnitPx = 1360;
let mockFileListPx = 0;
let mockPanelPercentage: number | null = null;
let mockPanelPx: number | null = null;
-let deferPanelGeometryCommit = false;
-let committedGroupLayout: MockLayout = {};
-let committedInnerLayout: MockLayout = {};
-let innerSetLayoutPx: number[] = [];
let deliverDocPanelResizeAfterLayout = false;
+let refuseNextInnerLayoutWrite = false;
+let refuseInnerLayoutWrites = false;
+let innerLayoutWriteError: Error | null = null;
+let innerLayoutReads = 0;
let lastDeliveredDocPanelSize: { asPercentage: number; inPixels: number } | null = null;
beforeEach(() => {
mockPanelPercentage = null;
mockPanelPx = null;
- rejectGroupLayoutWrites = false;
- deferPanelGeometryCommit = false;
- committedGroupLayout = {};
- committedInnerLayout = {};
innerLayout = { ...INNER_LAYOUT_DOC_CLOSED };
innerSetLayoutCalls = [];
innerSetLayoutPx = [];
+ innerOnLayoutChange = null;
deliverDocPanelResizeAfterLayout = false;
+ refuseNextInnerLayoutWrite = false;
+ refuseInnerLayoutWrites = false;
+ innerLayoutWriteError = null;
+ innerLayoutReads = 0;
lastDeliveredDocPanelSize = null;
- innerRowHandlers.onLayoutChanged = null;
- innerRowHandlers.onLayoutChange = null;
- mockInnerPx = null;
mockFileListPx = 0;
conflictedDocName = null;
+ const measure = HTMLElement.prototype.getBoundingClientRect;
+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (
+ this: HTMLElement,
+ ) {
+ if (!this.hasAttribute('data-dock-workspace')) return measure.call(this);
+ return {
+ x: 0,
+ y: 0,
+ top: 0,
+ left: 0,
+ right: WORKSPACE_WIDTH_PX,
+ bottom: WORKSPACE_HEIGHT_PX,
+ width: WORKSPACE_WIDTH_PX,
+ height: WORKSPACE_HEIGHT_PX,
+ toJSON() {},
+ } as DOMRect;
+ });
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
});
const renderedInnerPanelIds = () =>
@@ -298,61 +264,19 @@ function lastInnerWritePx(id: string): number | null {
return pct == null || px == null ? null : (pct / 100) * px;
}
-function rowOf(element: Element | null | undefined): EditorRow {
- return element?.closest('[data-editor-row]')?.getAttribute('data-editor-row') === 'inner'
- ? 'inner'
- : 'outer';
-}
-
-function rowLayout(row: EditorRow): MockLayout {
- return row === 'inner' ? innerLayout : groupLayout;
-}
-
-function assignRowLayout(row: EditorRow, layout: MockLayout) {
- if (row === 'inner') innerLayout = layout;
- else groupLayout = layout;
-}
-
-function assignCommittedRowLayout(row: EditorRow, layout: MockLayout) {
- if (row === 'inner') committedInnerLayout = layout;
- else committedGroupLayout = layout;
-}
-
-function rowSetLayoutCalls(row: EditorRow): MockLayout[] {
- return row === 'inner' ? innerSetLayoutCalls : groupSetLayoutCalls;
-}
-
-function geometryLayout(row: EditorRow): MockLayout {
- if (!deferPanelGeometryCommit) return rowLayout(row);
- return row === 'inner' ? committedInnerLayout : committedGroupLayout;
+function innerRowPx(): number {
+ return Math.max(0, mockEditorUnitPx - mockFileListPx);
}
-function residualPanelWidthPx(element: HTMLElement, row: EditorRow): number {
- const layout = geometryLayout(row);
- const group = element.parentElement;
- if (group == null) return 0;
+function mockedPanelWidthPx(element: HTMLElement): number {
+ if (element.id !== '') return ((innerLayout[element.id] ?? 0) / 100) * innerRowPx();
let claimedPercentage = 0;
- for (const sibling of group.querySelectorAll<HTMLElement>(':scope > [data-panel]')) {
- if (sibling.id !== '') claimedPercentage += layout[sibling.id] ?? 0;
+ for (const sibling of element.parentElement?.querySelectorAll<HTMLElement>(
+ ':scope > [data-panel]',
+ ) ?? []) {
+ if (sibling.id !== '') claimedPercentage += innerLayout[sibling.id] ?? 0;
}
- return (Math.max(0, 100 - claimedPercentage) / 100) * rowPx(row);
-}
-
-function rowPx(row: EditorRow): number {
- if (row === 'outer') return mockGroupPx;
- if (mockInnerPx != null) return mockInnerPx;
- const outerResidual = document.querySelector<HTMLElement>(
- '[data-editor-row="outer"] > [data-panel]:not([id])',
- );
- const editorColumnPx =
- outerResidual == null ? mockGroupPx : residualPanelWidthPx(outerResidual, 'outer');
- return Math.max(0, editorColumnPx - mockFileListPx);
-}
-
-function mockedPanelWidthPx(element: HTMLElement): number {
- const row = rowOf(element.parentElement);
- if (element.id !== '') return ((geometryLayout(row)[element.id] ?? 0) / 100) * rowPx(row);
- return residualPanelWidthPx(element, row);
+ return (Math.max(0, 100 - claimedPercentage) / 100) * innerRowPx();
}
function measureMockedPanel(element: HTMLDivElement | null) {
@@ -370,112 +294,78 @@ function measureMockedPanel(element: HTMLDivElement | null) {
});
}
-function createGroupHandle(row: EditorRow) {
- return {
- getLayout: () => rowLayout(row),
- setLayout: (layout: MockLayout) => {
- rowSetLayoutCalls(row).push(layout);
- if (row === 'inner') innerSetLayoutPx.push(rowPx('inner'));
- if (rejectNextGroupLayoutWrite && row === 'outer') {
- rejectNextGroupLayoutWrite = false;
- return;
- }
- if (rejectGroupLayoutWrites) return;
- assignRowLayout(row, layout);
- if (deferPanelGeometryCommit) {
- queueMicrotask(() => {
- assignCommittedRowLayout(row, layout);
- });
- } else {
- assignCommittedRowLayout(row, layout);
- }
- if (row === 'inner' && deliverDocPanelResizeAfterLayout) {
- const size = docPanelSizeFromRow();
- if (
- lastDeliveredDocPanelSize?.asPercentage !== size.asPercentage ||
- lastDeliveredDocPanelSize.inPixels !== size.inPixels
- ) {
- lastDeliveredDocPanelSize = size;
- panelIsCollapsed = size.asPercentage === 0;
- railPanelOnResizeById.get('doc-panel')?.(size);
- }
- }
- },
- };
+function docPanelSizeFromRow() {
+ const pct = innerLayout['doc-panel'] ?? 0;
+ return { asPercentage: pct, inPixels: (pct / 100) * innerRowPx() };
}
-const groupHandles: Record<EditorRow, ReturnType<typeof createGroupHandle>> = {
- outer: createGroupHandle('outer'),
- inner: createGroupHandle('inner'),
+const innerGroupHandle = {
+ getLayout: () => {
+ innerLayoutReads += 1;
+ return innerLayout;
+ },
+ setLayout: (layout: MockLayout) => {
+ innerSetLayoutCalls.push(layout);
+ innerSetLayoutPx.push(innerRowPx());
+ if (innerLayoutWriteError !== null) throw innerLayoutWriteError;
+ if (refuseInnerLayoutWrites) return;
+ if (refuseNextInnerLayoutWrite) {
+ refuseNextInnerLayoutWrite = false;
+ return;
+ }
+ innerLayout = layout;
+ if (!deliverDocPanelResizeAfterLayout) return;
+ const size = docPanelSizeFromRow();
+ if (
+ lastDeliveredDocPanelSize?.asPercentage === size.asPercentage &&
+ lastDeliveredDocPanelSize.inPixels === size.inPixels
+ ) {
+ return;
+ }
+ lastDeliveredDocPanelSize = size;
+ panelIsCollapsed = size.asPercentage === 0;
+ panelOnResizeById.get('doc-panel')?.(size);
+ },
};
-let panelRefCalls = 0;
-const PANEL_REF_ORDER = ['doc-panel', 'agents-column', 'terminal-column'] as const;
-
-function docPanelSizeFromRow() {
- const pct = rowLayout('inner')['doc-panel'] ?? 0;
- return { asPercentage: pct, inPixels: (pct / 100) * rowPx('inner') };
-}
-
vi.doMock('react-resizable-panels', () => ({
- usePanelRef: () => {
- const slot = PANEL_REF_ORDER[panelRefCalls % PANEL_REF_ORDER.length];
- panelRefCalls += 1;
- return {
- current: {
- collapse: () => {},
- expand: () => {},
- getSize: () => {
- if (slot !== 'doc-panel') {
- return {
- asPercentage: mockPanelPercentage ?? 25,
- inPixels: mockPanelPx ?? mockGroupPx / 4,
- };
- }
- const fromRow = docPanelSizeFromRow();
- return {
- asPercentage: mockPanelPercentage ?? fromRow.asPercentage,
- inPixels: mockPanelPx ?? fromRow.inPixels,
- };
- },
- isCollapsed: () =>
- deliverDocPanelResizeAfterLayout
- ? (slot === 'doc-panel' ? innerLayout : groupLayout)[slot] === 0
- : panelIsCollapsed,
+ usePanelRef: () => ({
+ current: {
+ collapse: () => {},
+ expand: () => {},
+ getSize: () => {
+ const fromRow = docPanelSizeFromRow();
+ return {
+ asPercentage: mockPanelPercentage ?? fromRow.asPercentage,
+ inPixels: mockPanelPx ?? fromRow.inPixels,
+ };
},
- };
- },
- useGroupRef: () => useRef<ReturnType<typeof createGroupHandle> | null>(null),
+ isCollapsed: () =>
+ deliverDocPanelResizeAfterLayout ? innerLayout['doc-panel'] === 0 : panelIsCollapsed,
+ },
+ }),
+ useGroupRef: () => useRef<typeof innerGroupHandle | null>(null),
}));
vi.doMock('@/components/ui/resizable', () => ({
ResizablePanelGroup: ({
children,
onLayoutChange,
- onLayoutChanged,
groupRef,
- 'data-editor-row': rowProp,
+ 'data-editor-row': row,
'data-dragging': dragging,
}: {
children: ReactNode;
onLayoutChange?: (layout: MockLayout) => void;
- onLayoutChanged?: LayoutChangedHandler;
- groupRef?: { current: ReturnType<typeof createGroupHandle> | null };
+ groupRef?: { current: typeof innerGroupHandle | null };
'data-editor-row'?: string;
'data-dragging'?: boolean;
}) => {
- const row: EditorRow = rowProp === 'inner' ? 'inner' : 'outer';
- if (groupRef != null) groupRef.current = groupHandles[row];
- if (row === 'inner') {
- innerRowHandlers.onLayoutChanged = onLayoutChanged ?? null;
- innerRowHandlers.onLayoutChange = onLayoutChange ?? null;
- } else {
- groupOnLayoutChanged = onLayoutChanged ?? null;
- groupOnLayoutChange = onLayoutChange ?? null;
- }
+ if (groupRef != null) groupRef.current = innerGroupHandle;
+ innerOnLayoutChange = onLayoutChange ?? null;
return (
<div
- data-testid={row === 'inner' ? 'resizable-group-inner' : 'resizable-group'}
+ data-testid="resizable-group-inner"
data-group="true"
data-editor-row={row}
data-dragging={dragging || undefined}
@@ -506,7 +396,7 @@ vi.doMock('@/components/ui/resizable', () => ({
'aria-label'?: string;
inert?: boolean;
}) => {
- if (id != null) railPanelOnResizeById.set(id, onResize ?? null);
+ if (id != null) panelOnResizeById.set(id, onResize ?? null);
return (
<div
id={id}
@@ -642,15 +532,26 @@ vi.doMock('@/lib/use-settings-route', () => ({
}),
}));
-const { EditorArea } = await import('./EditorArea');
+const { EditorArea: DockedEditorArea } = await import('./EditorArea');
const { SidebarProvider } = await import('@/components/ui/sidebar');
const { TooltipProvider } = await import('@/components/ui/tooltip');
const { SingleFileModeProvider } = await import('@/lib/single-file-mode');
const { emitLocalMenuAction } = await import('@/lib/local-menu-action-bus');
const { requestDocPanelTab } = await import('./doc-panel-events');
-const { AGENTS_COLUMN_ID, TERMINAL_COLUMN_ID } = await import('./editor-area-rail-registry');
-const { MAX_RAIL_PIN_EXHAUSTED_REPORTS } = await import('./EditorArea');
-const { RIGHT_TERMINAL_PANEL_MIN_WIDTH_PX } = await import('./right-rail-admission');
+
+const RIGHT_TERMINAL_TREE = moveDockPane(DEFAULT_DOCK_TREE, 'terminal', 'editor', 'end', 0.3);
+
+type DockedEditorAreaProps = ComponentProps<typeof DockedEditorArea>;
+type EditorAreaProps = Omit<DockedEditorAreaProps, 'dockTree' | 'onDockTreeChange'> &
+ Partial<Pick<DockedEditorAreaProps, 'dockTree' | 'onDockTreeChange'>>;
+
+function EditorArea({
+ dockTree = DEFAULT_DOCK_TREE,
+ onDockTreeChange = () => {},
+ ...props
+}: EditorAreaProps) {
+ return <DockedEditorArea dockTree={dockTree} onDockTreeChange={onDockTreeChange} {...props} />;
+}
function render(ui: ReactNode) {
return rtlRender(ui, { wrapper: SidebarProvider });
@@ -667,6 +568,40 @@ function renderEditorArea() {
);
}
+function dockUnit(pane: PaneId): HTMLElement {
+ const unit = document.querySelector<HTMLElement>(`[data-dock-unit="${pane}"]`);
+ if (unit == null) throw new Error(`the ${pane} unit is absent`);
+ return unit;
+}
+
+function unitPx(
+ pane: PaneId,
+ property: 'width' | 'height' | 'insetInlineStart' | 'insetBlockStart',
+): number {
+ return Number.parseFloat(dockUnit(pane).style[property]);
+}
+
+function dockSeam(name: string): HTMLElement {
+ const seam = screen.getByRole('separator', { name });
+ if (!seam.hasAttribute('data-dock-seam')) throw new Error(`${name} is not a dock seam`);
+ return seam;
+}
+
+function paneCard(pane: PaneId): HTMLElement | null {
+ return document.querySelector<HTMLElement>(`[data-slot="pane-card"][data-pane="${pane}"]`);
+}
+
+function terminalMount(): HTMLElement | null {
+ return document.querySelector<HTMLElement>('[data-terminal-panel-mount]');
+}
+
+function agentsMount(): HTMLElement | null {
+ return document.querySelector<HTMLElement>('[data-agents-panel-mount]');
+}
+
+const flushFrame = () =>
+ act(() => new Promise<void>((resolve) => requestAnimationFrame(() => resolve())));
+
describe('EditorArea SettingsDialogPortal runtime wiring', () => {
beforeEach(() => {
cleanup();
@@ -701,7 +636,7 @@ describe('EditorArea empty-state terminal host', () => {
docCtx = EMPTY_DOC_CTX;
});
- test('hosts the docked terminal on the empty state when a terminal bridge is present', () => {
+ test('places the terminal unit beside the empty state when a terminal bridge is present', () => {
render(
<EditorArea
editorMode="wysiwyg"
@@ -710,16 +645,15 @@ describe('EditorArea empty-state terminal host', () => {
onActiveTabChange={() => {}}
terminalBridge={{} as never}
terminalVisible
- onTerminalVisibleChange={() => {}}
/>,
);
- const dock = screen.getByTestId('terminal-dock');
- expect(dock.getAttribute('data-visible')).toBe('true');
- const emptyState = dock.querySelector('[data-testid="empty-editor-state"]');
- expect(emptyState).not.toBeNull();
- expect(emptyState?.getAttribute('data-terminal-open')).toBe('true');
- expect(emptyState?.getAttribute('data-agents-open')).toBe('false');
+ const emptyState = screen.getByTestId('empty-editor-state');
+ expect(dockUnit('editor').contains(emptyState)).toBe(true);
+ expect(emptyState.getAttribute('data-terminal-open')).toBe('true');
+ expect(emptyState.getAttribute('data-agents-open')).toBe('false');
+ expect(dockUnit('terminal').hidden).toBe(false);
+ expect(dockUnit('terminal').contains(terminalMount())).toBe(true);
});
test('collapses the empty state to the header-only view when the agents panel is open', () => {
@@ -730,7 +664,6 @@ describe('EditorArea empty-state terminal host', () => {
activeTab="timeline"
onActiveTabChange={() => {}}
agentsVisible
- onAgentsVisibleChange={() => {}}
/>,
);
@@ -739,7 +672,7 @@ describe('EditorArea empty-state terminal host', () => {
expect(emptyState.getAttribute('data-terminal-open')).toBe('false');
});
- test('renders the empty state; the dock shell is present but inactive on the web host', () => {
+ test('renders the empty state with no terminal unit on the web host', () => {
render(
<EditorArea
editorMode="wysiwyg"
@@ -749,7 +682,8 @@ describe('EditorArea empty-state terminal host', () => {
/>,
);
- expect(screen.getByTestId('terminal-dock').getAttribute('data-visible')).toBe('false');
+ expect(dockUnit('terminal').hidden).toBe(true);
+ expect(terminalMount()).toBeNull();
const emptyState = screen.getByTestId('empty-editor-state');
expect(emptyState.getAttribute('data-terminal-open')).toBe('false');
expect(emptyState.getAttribute('data-agents-open')).toBe('false');
@@ -764,8 +698,6 @@ describe('EditorArea empty-state terminal host', () => {
onActiveTabChange={() => {}}
terminalBridge={{} as never}
terminalVisible
- terminalPlacement="bottom"
- onTerminalVisibleChange={() => {}}
/>,
);
@@ -783,8 +715,7 @@ describe('EditorArea empty-state terminal host', () => {
onActiveTabChange={() => {}}
terminalBridge={{} as never}
terminalVisible
- terminalPlacement="right"
- onTerminalVisibleChange={() => {}}
+ dockTree={RIGHT_TERMINAL_TREE}
/>,
);
@@ -801,8 +732,6 @@ describe('EditorArea empty-state terminal host', () => {
activeTab="timeline"
onActiveTabChange={() => {}}
terminalBridge={{} as never}
- terminalPlacement="bottom"
- onTerminalVisibleChange={() => {}}
/>,
);
@@ -812,7 +741,7 @@ describe('EditorArea empty-state terminal host', () => {
});
});
-describe('EditorArea right-rail layout assert on column mount/unmount', () => {
+describe('EditorArea document panel slot', () => {
const setViewportWidth = (px: number) => {
Object.defineProperty(window, 'innerWidth', {
value: px,
@@ -827,16 +756,10 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
activeTab: 'timeline',
onActiveTabChange: () => {},
terminalBridge: {} as never,
- onAgentsVisibleChange: () => {},
} as const;
- const MOCK_GROUP_PX = 1360;
- const pctOf = (px: number) => (px / MOCK_GROUP_PX) * 100;
- const getAgentsHandle = () => {
- const handle = screen.getAllByTestId('resizable-handle').at(-1);
- if (handle == null) throw new Error('agents resize handle not found');
- return handle;
- };
+ const pctOf = (px: number) => (px / mockEditorUnitPx) * 100;
+
const controlAnimationFrames = () => {
const callbacks = new Map<number, FrameRequestCallback>();
let nextId = 1;
@@ -871,278 +794,37 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
};
};
+ const exhaustionReports = () => {
+ const reports: Record<string, unknown>[] = [];
+ vi.spyOn(console, 'warn').mockImplementation((message: unknown) => {
+ const text = String(message);
+ if (!text.startsWith('{')) return;
+ const report = JSON.parse(text) as Record<string, unknown>;
+ if (report.event === 'rail-layout-retry-exhausted') reports.push(report);
+ });
+ return reports;
+ };
+
+ const BLOCKED_INNER_ROW: MockLayout = { 'workspace-main': 100 };
+
+ const expectPinRetryWaitingOnAFrame = (frames: ReturnType<typeof controlAnimationFrames>) => {
+ const reads = innerLayoutReads;
+ frames.run(frames.pendingCount());
+ expect(innerLayoutReads).toBeGreaterThan(reads);
+ };
+
beforeEach(() => {
cleanup();
localStorage.clear();
docCtx = EMPTY_DOC_CTX;
- groupLayout = {};
- groupSetLayoutCalls = [];
- rejectNextGroupLayoutWrite = false;
- rejectGroupLayoutWrites = false;
panelIsCollapsed = false;
- mockGroupPx = 1360;
- mockPanelPercentage = null;
- mockPanelPx = null;
- deferPanelGeometryCommit = false;
- committedGroupLayout = {};
- groupOnLayoutChanged = null;
- groupOnLayoutChange = null;
- toastInfoMessages = [];
- });
-
- const renderedPanelIds = () =>
- [...screen.getByTestId('resizable-group').children].map((el) => el.id).filter(Boolean);
-
- test('moving the terminal right at a narrow width closes agents without moving focus', async () => {
- setViewportWidth(650);
- mockGroupPx = 650;
- const agentsChanges: boolean[] = [];
- const focusTarget = document.createElement('button');
- document.body.append(focusTarget);
- focusTarget.focus();
- const view = render(
- <EditorArea
- {...baseProps}
- agentsVisible
- terminalVisible
- terminalPlacement="bottom"
- onAgentsVisibleChange={(visible: boolean) => {
- agentsChanges.push(visible);
- }}
- onTerminalVisibleChange={() => {}}
- />,
- );
- groupLayout = { 'editor-main': 52, 'terminal-column': 30, 'agents-column': 18 };
-
- view.rerender(
- <EditorArea
- {...baseProps}
- agentsVisible
- terminalVisible
- terminalPlacement="right"
- onAgentsVisibleChange={(visible: boolean) => {
- agentsChanges.push(visible);
- }}
- onTerminalVisibleChange={() => {}}
- />,
- );
- await act(async () => {});
-
- expect(agentsChanges).toEqual([false]);
- expect(toastInfoMessages).toEqual(['Agent panel closed to keep Terminal readable.']);
- expect(document.activeElement).toBe(focusTarget);
- });
-
- test('a narrow restored layout keeps the right terminal and closes agents', async () => {
- setViewportWidth(650);
- mockGroupPx = 650;
- const agentsChanges: boolean[] = [];
- const terminalChanges: boolean[] = [];
- render(
- <EditorArea
- {...baseProps}
- agentsVisible
- terminalVisible
- terminalPlacement="right"
- onAgentsVisibleChange={(visible: boolean) => {
- agentsChanges.push(visible);
- }}
- onTerminalVisibleChange={(visible: boolean) => {
- terminalChanges.push(visible);
- }}
- />,
- );
- groupLayout = { 'editor-main': 52, 'terminal-column': 30, 'agents-column': 18 };
- await act(async () => {});
-
- expect(agentsChanges).toEqual([false]);
- expect(terminalChanges).toHaveLength(0);
- expect(toastInfoMessages).toEqual(['Agent panel closed to keep Terminal readable.']);
- });
-
- test('opening agents at a narrow width closes the existing right terminal', async () => {
- setViewportWidth(650);
- mockGroupPx = 650;
- const terminalChanges: boolean[] = [];
- const view = render(
- <EditorArea
- {...baseProps}
- agentsVisible={false}
- terminalVisible
- terminalPlacement="right"
- onTerminalVisibleChange={(visible: boolean) => {
- terminalChanges.push(visible);
- }}
- />,
- );
- groupLayout = { 'editor-main': 52, 'terminal-column': 30, 'agents-column': 18 };
-
- view.rerender(
- <EditorArea
- {...baseProps}
- agentsVisible
- terminalVisible
- terminalPlacement="right"
- onTerminalVisibleChange={(visible: boolean) => {
- terminalChanges.push(visible);
- }}
- />,
- );
- await act(async () => {});
-
- expect(terminalChanges).toEqual([false]);
- expect(toastInfoMessages).toEqual(['Terminal closed to make room for the agent panel.']);
- });
-
- test('a wide workspace keeps both rails and their independent size constraints', async () => {
- setViewportWidth(2000);
- mockGroupPx = 2000;
- groupLayout = { 'editor-main': 47, 'terminal-column': 37, 'agents-column': 16 };
- const agentsChanges: boolean[] = [];
- const terminalChanges: boolean[] = [];
- render(
- <EditorArea
- {...baseProps}
- agentsVisible
- terminalVisible
- terminalPlacement="right"
- onAgentsVisibleChange={(visible: boolean) => {
- agentsChanges.push(visible);
- }}
- onTerminalVisibleChange={(visible: boolean) => {
- terminalChanges.push(visible);
- }}
- />,
- );
- await act(async () => {});
-
- const terminalPanel = document.getElementById('terminal-column');
- const agentsPanel = document.getElementById('agents-column');
- expect(terminalPanel?.getAttribute('data-min-size')).toBe('325px');
- expect(terminalPanel?.hasAttribute('data-max-size')).toBe(false);
- expect(agentsPanel?.getAttribute('data-min-size')).toBe('0px');
- expect(agentsPanel?.getAttribute('data-max-size')).toBe('95%');
- expect(agentsChanges).toHaveLength(0);
- expect(terminalChanges).toHaveLength(0);
- });
-
- test('a hidden right terminal is clamped out of flex flow', () => {
- render(<EditorArea {...baseProps} terminalPlacement="right" />);
-
- const terminalPanel = document.getElementById('terminal-column');
- expect(terminalPanel?.getAttribute('data-min-size')).toBe('0px');
- expect(terminalPanel?.getAttribute('data-max-size')).toBe('0px');
- });
-
- test('repeated resize events below the boundary close agents once and keep Terminal open', async () => {
- const originalResizeObserver = globalThis.ResizeObserver;
- const observations: Array<{
- callback: ResizeObserverCallback;
- observer: ResizeObserver;
- target: Element;
- }> = [];
- class TestResizeObserver implements ResizeObserver {
- readonly callback: ResizeObserverCallback;
-
- constructor(callback: ResizeObserverCallback) {
- this.callback = callback;
- }
-
- observe(target: Element) {
- observations.push({ callback: this.callback, observer: this, target });
- }
-
- unobserve() {}
-
- disconnect() {}
- }
- Object.defineProperty(globalThis, 'ResizeObserver', {
- value: TestResizeObserver,
- configurable: true,
- writable: true,
- });
-
- try {
- setViewportWidth(2000);
- mockGroupPx = 2000;
- groupLayout = { 'editor-main': 47, 'terminal-column': 37, 'agents-column': 16 };
- const agentsChanges: boolean[] = [];
- const terminalChanges: boolean[] = [];
- render(
- <EditorArea
- {...baseProps}
- agentsVisible
- terminalVisible
- terminalPlacement="right"
- onAgentsVisibleChange={(visible: boolean) => {
- agentsChanges.push(visible);
- }}
- onTerminalVisibleChange={(visible: boolean) => {
- terminalChanges.push(visible);
- }}
- />,
- );
- await act(async () => {});
- expect(agentsChanges).toHaveLength(0);
-
- mockGroupPx = 650;
- const panels = document.querySelector('[data-editor-area-panels]');
- const panelObservation = observations.find(({ target }) => target === panels);
- expect(panelObservation).toBeDefined();
- act(() => {
- panelObservation?.callback([], panelObservation.observer);
- panelObservation?.callback([], panelObservation.observer);
- });
-
- expect(agentsChanges).toEqual([false]);
- expect(terminalChanges).toHaveLength(0);
- expect(toastInfoMessages).toEqual(['Agent panel closed to keep Terminal readable.']);
- } finally {
- Object.defineProperty(globalThis, 'ResizeObserver', {
- value: originalResizeObserver,
- configurable: true,
- writable: true,
- });
- }
+ mockEditorUnitPx = 1360;
});
- test('revealing the right terminal pins its width and routes the remainder to the editor', async () => {
- setViewportWidth(1400);
- const view = render(
- <EditorArea
- {...baseProps}
- terminalVisible
- terminalPlacement="bottom"
- onTerminalVisibleChange={() => {}}
- />,
- );
- groupLayout = { 'editor-main': 65, 'terminal-column': 35 };
-
- view.rerender(
- <EditorArea
- {...baseProps}
- terminalVisible
- terminalPlacement="right"
- onTerminalVisibleChange={() => {}}
- />,
- );
- await act(async () => {});
-
- const corrected = groupSetLayoutCalls.at(-1);
- expect(corrected?.['terminal-column']).toBeCloseTo(pctOf(740), 3);
- expect(corrected?.['editor-main']).toBeCloseTo(100 - pctOf(740), 3);
- });
-
- test('opens the collapsed doc panel while both permanent rail columns are hidden', () => {
+ test('opens the collapsed doc panel from the toggle', () => {
setViewportWidth(1024);
docCtx = DOC_LIVE_CTX;
render(<EditorArea {...baseProps} />);
- groupLayout = {
- 'editor-main': 100,
- 'terminal-column': 0,
- 'agents-column': 0,
- };
- groupSetLayoutCalls = [];
innerSetLayoutCalls = [];
act(() => emitLocalMenuAction('toggle-doc-panel'));
@@ -1151,21 +833,12 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
expect(correctedInner?.['doc-panel']).toBeCloseTo(pctOf(320), 3);
expect(lastInnerWritePx('doc-panel')).toBeCloseTo(320, 3);
expect(correctedInner?.['workspace-main']).toBeCloseTo(100 - pctOf(320), 3);
- const corrected = groupSetLayoutCalls.at(-1);
- expect(corrected?.['terminal-column']).toBe(0);
- expect(corrected?.['agents-column']).toBe(0);
- expect(corrected?.['editor-main']).toBe(100);
});
test('a second toggle re-opens the doc panel the first toggle collapsed', () => {
setViewportWidth(1400);
docCtx = DOC_LIVE_CTX;
render(<EditorArea {...baseProps} />);
- groupLayout = {
- 'editor-main': 100,
- 'terminal-column': 0,
- 'agents-column': 0,
- };
innerLayout = { 'workspace-main': 75, 'doc-panel': 25 };
innerSetLayoutCalls = [];
@@ -1177,493 +850,319 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
expect(lastInnerWritePx('doc-panel')).toBeCloseTo(320, 3);
});
- test('hiding the agents panel re-asserts the collapsed doc panel over the stale panel-set restore', async () => {
- setViewportWidth(1024);
+ test('showing or hiding the agents pane keeps the side panel at its pixel width', async () => {
+ setViewportWidth(1400);
docCtx = DOC_LIVE_CTX;
- const view = render(<EditorArea {...baseProps} agentsVisible />);
- expect(groupSetLayoutCalls).toHaveLength(0);
- expect(innerSetLayoutCalls).toHaveLength(0);
- groupLayout = { 'editor-main': 70, 'agents-column': 30 };
- innerLayout = { 'workspace-main': 70, 'doc-panel': 30 };
- view.rerender(<EditorArea {...baseProps} agentsVisible={false} />);
+ innerLayout = innerRowWithDoc(320, 1360);
+ const view = render(<EditorArea {...baseProps} />);
await act(async () => {});
- const correctedInner = innerSetLayoutCalls.at(-1);
- expect(correctedInner).toBeDefined();
- expect(correctedInner?.['doc-panel']).toBe(0);
- expect(correctedInner?.['workspace-main']).toBe(100);
- const corrected = groupSetLayoutCalls.at(-1);
- expect(corrected?.['agents-column']).toBe(0);
- expect(corrected?.['editor-main']).toBe(100);
- });
-
- test('the terminal pin is taken against rendered panel space, not a panel-ratio estimate', async () => {
- setViewportWidth(1900);
- mockGroupPx = 1610;
- docCtx = DOC_LIVE_CTX;
- mockPanelPercentage = (319.51 / 1610) * 100;
- mockPanelPx = 320;
- const view = render(
- <EditorArea {...baseProps} terminalVisible terminalPlacement="right" agentsVisible={false} />,
- );
- groupLayout = { ...RAIL_OUTER_1610 };
- innerLayout = { ...RAIL_INNER_1610 };
- groupSetLayoutCalls = [];
- view.rerender(
- <EditorArea {...baseProps} terminalVisible terminalPlacement="right" agentsVisible />,
- );
+ innerSetLayoutCalls = [];
+ mockEditorUnitPx = 966;
+ view.rerender(<EditorArea {...baseProps} agentsVisible />);
await act(async () => {});
+ expect(lastInnerWritePx('doc-panel')).toBeCloseTo(320, 3);
- const corrected = groupSetLayoutCalls.at(-1);
- expect(corrected).toBeDefined();
- const terminalPercentage = corrected?.['terminal-column'];
- if (terminalPercentage == null) throw new Error('terminal column was not pinned');
- expect((terminalPercentage / 100) * 1610).toBeGreaterThan(739);
- expect(terminalPercentage).toBeCloseTo((740 / 1610) * 100, 3);
- });
-
- const RAIL_OUTER_1610 = {
- 'editor-main': 100 - (740 / 1610) * 100,
- 'terminal-column': (740 / 1610) * 100,
- 'agents-column': 0,
- };
- const RAIL_INNER_1610 = innerRowWithDoc(320, 1610 - 740);
- const strandedOuter1610 = (terminalPercentage: number): MockLayout => ({
- 'editor-main': 100 - terminalPercentage,
- 'terminal-column': terminalPercentage,
- 'agents-column': 0,
+ innerSetLayoutCalls = [];
+ mockEditorUnitPx = 1360;
+ view.rerender(<EditorArea {...baseProps} />);
+ await act(async () => {});
+ expect(lastInnerWritePx('doc-panel')).toBeCloseTo(320, 3);
+ expect(renderedInnerPanelIds()).toEqual(['doc-panel']);
});
- const strandedInner1610 = (terminalPercentage: number): MockLayout =>
- innerRowWithDoc(320, ((100 - terminalPercentage) / 100) * 1610);
-
- const readExhaustedReports = (warnings: readonly string[]) =>
- warnings
- .map((message) => {
- try {
- return JSON.parse(message) as {
- event?: string;
- trigger?: string;
- stage?: string;
- refusal?: string;
- shortfall?: Record<string, unknown>;
- unaccountedIds?: readonly string[];
- };
- } catch {
- return null;
- }
- })
- .filter((entry) => entry?.event === 'right-rail-pin-exhausted');
-
- async function withSynchronousFrames(run: () => void | Promise<void>) {
- const warnings: string[] = [];
- const warnSpy = vi.spyOn(console, 'warn').mockImplementation((message: unknown) => {
- warnings.push(String(message));
- });
- const realRequestAnimationFrame = globalThis.requestAnimationFrame;
- globalThis.requestAnimationFrame = ((callback: FrameRequestCallback) => {
- callback(0);
- return 0;
- }) as typeof globalThis.requestAnimationFrame;
- try {
- await run();
- await act(async () => {});
- } finally {
- globalThis.requestAnimationFrame = realRequestAnimationFrame;
- warnSpy.mockRestore();
- }
- return warnings;
- }
- test('the terminal pin is verified against the write, not the frame the panels still show', async () => {
- setViewportWidth(1900);
- mockGroupPx = 1610;
+ test('showing or hiding the agents pane keeps a hidden side panel hidden', async () => {
+ setViewportWidth(1400);
docCtx = DOC_LIVE_CTX;
- const view = render(
- <EditorArea {...baseProps} terminalVisible terminalPlacement="right" agentsVisible={false} />,
- );
- groupLayout = { ...RAIL_OUTER_1610 };
- committedGroupLayout = { ...RAIL_OUTER_1610 };
- innerLayout = { ...RAIL_INNER_1610 };
- committedInnerLayout = { ...RAIL_INNER_1610 };
- deferPanelGeometryCommit = true;
- groupSetLayoutCalls = [];
-
- const warnings = await withSynchronousFrames(() => {
- view.rerender(
- <EditorArea {...baseProps} terminalVisible terminalPlacement="right" agentsVisible />,
- );
- });
+ innerLayout = innerRowWithDoc(320, 1360);
+ const view = render(<EditorArea {...baseProps} />);
+ await act(async () => {});
+ act(() => emitLocalMenuAction('toggle-doc-panel'));
+ expect(innerLayout['doc-panel']).toBe(0);
+ const editorWidth = unitPx('editor', 'width');
+
+ mockEditorUnitPx = 966;
+ view.rerender(<EditorArea {...baseProps} agentsVisible />);
+ await act(async () => {});
+ expect(unitPx('editor', 'width')).toBeLessThan(editorWidth);
+ expect(innerLayout['doc-panel']).toBe(0);
- const corrected = groupSetLayoutCalls.at(-1);
- expect(corrected).toBeDefined();
- expect(corrected?.['terminal-column']).toBeCloseTo((740 / 1610) * 100, 3);
- expect(readExhaustedReports(warnings)).toEqual([]);
+ mockEditorUnitPx = 1360;
+ view.rerender(<EditorArea {...baseProps} />);
+ await act(async () => {});
+ expect(unitPx('editor', 'width')).toBe(editorWidth);
+ expect(innerLayout['doc-panel']).toBe(0);
});
- test('an exhausted terminal pin reports the width the column actually got', async () => {
- setViewportWidth(1900);
- mockGroupPx = 1610;
+ test('the side panel row keeps one panel-ID set from a document to a new tab', () => {
+ setViewportWidth(1400);
docCtx = DOC_LIVE_CTX;
- const strandedTerminalPercentage = 44;
- const view = render(
- <EditorArea {...baseProps} terminalVisible terminalPlacement="right" agentsVisible={false} />,
- );
- groupLayout = strandedOuter1610(strandedTerminalPercentage);
- innerLayout = strandedInner1610(strandedTerminalPercentage);
- rejectGroupLayoutWrites = true;
+ const view = render(<EditorArea {...baseProps} agentsVisible />);
+ expect(renderedInnerPanelIds()).toEqual(['doc-panel']);
- const warnings = await withSynchronousFrames(() => {
- view.rerender(
- <EditorArea {...baseProps} terminalVisible terminalPlacement="right" agentsVisible />,
- );
- });
+ docCtx = EMPTY_DOC_CTX;
+ view.rerender(<EditorArea {...baseProps} agentsVisible />);
- const exhausted = readExhaustedReports(warnings).at(0);
- expect(exhausted).toBeDefined();
- expect(exhausted?.trigger).toBe('rail-column-sync');
- expect(exhausted?.stage).toBe('width-shortfall');
- expect(exhausted?.shortfall?.['terminal-column']).toEqual({
- targetPx: 740,
- renderedPx: expect.closeTo((strandedTerminalPercentage / 100) * 1610, 6),
- });
+ expect(renderedInnerPanelIds()).toEqual(['doc-panel']);
+ expect(document.getElementById('doc-panel')?.textContent).toBe('');
});
- test('a second exhausted loop reports its own outcome, not the one before it', async () => {
- setViewportWidth(1900);
- mockGroupPx = 1610;
- docCtx = DOC_LIVE_CTX;
- const view = render(
- <EditorArea {...baseProps} terminalVisible terminalPlacement="right" agentsVisible={false} />,
- );
- groupLayout = strandedOuter1610(44);
- innerLayout = strandedInner1610(44);
- rejectGroupLayoutWrites = true;
-
- const warnings = await withSynchronousFrames(() => {
- view.rerender(
- <EditorArea {...baseProps} terminalVisible terminalPlacement="right" agentsVisible />,
- );
- mockGroupPx = 0;
- docCtx = EMPTY_DOC_CTX;
- view.rerender(
- <EditorArea {...baseProps} terminalVisible terminalPlacement="right" agentsVisible />,
- );
- });
-
- const [fromColumnSync, fromDocSlot] = readExhaustedReports(warnings);
- expect(fromColumnSync?.trigger).toBe('rail-column-sync');
- expect(fromColumnSync?.stage).toBe('width-shortfall');
- expect(fromColumnSync?.shortfall?.['terminal-column']).toEqual({
- targetPx: 740,
- renderedPx: expect.closeTo((44 / 100) * 1610, 6),
- });
- expect(fromDocSlot?.trigger).toBe('doc-slot-presence');
- expect(fromDocSlot?.stage).toBe('panel-space-unresolved');
- expect(fromDocSlot?.refusal).toBe('panel-space-empty');
- expect(fromDocSlot?.shortfall).toBeUndefined();
+ test('the side panel row keeps one panel-ID set across every view kind', () => {
+ setViewportWidth(1400);
+ for (const ctx of [
+ DOC_LIVE_CTX,
+ EMPTY_DOC_CTX,
+ FOLDER_DOC_CTX,
+ FOLDER_AGENT_CTX,
+ ASSET_DOC_CTX,
+ LARGE_FILE_DOC_CTX,
+ ]) {
+ cleanup();
+ docCtx = ctx;
+ render(<EditorArea {...baseProps} agentsVisible />);
+ expect(renderedInnerPanelIds()).toEqual(['doc-panel']);
+ }
});
- test('a layout carrying stray ids reports them instead of a bare missing-residual', async () => {
- setViewportWidth(1900);
- mockGroupPx = 1610;
- docCtx = DOC_LIVE_CTX;
- const view = render(
- <EditorArea
- {...baseProps}
- terminalVisible={false}
- terminalPlacement="right"
- agentsVisible={false}
- />,
- );
- groupLayout = { 'editor-main': 50, 'preview-main': 50 };
- groupSetLayoutCalls = [];
-
- const warnings = await withSynchronousFrames(() => {
- view.rerender(
- <EditorArea
- {...baseProps}
- terminalVisible
- terminalPlacement="right"
- agentsVisible={false}
- />,
- );
- });
-
- expect(groupSetLayoutCalls).toHaveLength(0);
- const exhausted = readExhaustedReports(warnings).at(0);
- expect(exhausted).toBeDefined();
- expect(exhausted?.trigger).toBe('rail-column-sync');
- expect(exhausted?.stage).toBe('layout-unaccounted');
- expect(exhausted?.unaccountedIds).toEqual(['editor-main', 'preview-main']);
- });
+ test('an empty slot is clamped out of flex flow', () => {
+ setViewportWidth(1400);
+ docCtx = ASSET_DOC_CTX;
+ const view = render(<EditorArea {...baseProps} agentsVisible />);
+ expect(document.getElementById('doc-panel')?.dataset.maxSize).toBe('0px');
- test('a rail with no room for its floor widths reports the pin it could not place', async () => {
- setViewportWidth(500);
- mockGroupPx = 300;
docCtx = DOC_LIVE_CTX;
- const view = render(
- <EditorArea
- {...baseProps}
- terminalVisible={false}
- terminalPlacement="right"
- agentsVisible={false}
- />,
- );
- groupLayout = {
- 'editor-main': 60,
- 'terminal-column': 40,
- 'agents-column': 0,
- };
- groupSetLayoutCalls = [];
+ view.rerender(<EditorArea {...baseProps} agentsVisible />);
+ expect(document.getElementById('doc-panel')?.dataset.maxSize).toBe('600px');
+ });
- const warnings = await withSynchronousFrames(() => {
- view.rerender(
- <EditorArea
- {...baseProps}
- terminalVisible
- terminalPlacement="right"
- agentsVisible={false}
- />,
- );
- });
+ test('the mid-session load gap keeps the panel-ID set and fills the slot', () => {
+ setViewportWidth(1400);
+ docCtx = FOLDER_LIVE_CTX;
+ const view = render(<EditorArea {...baseProps} agentsVisible />);
+ window.location.hash = '#/incoming-doc';
+ docCtx = DOC_COLD_CTX;
+ view.rerender(<EditorArea {...baseProps} agentsVisible />);
- expect(groupSetLayoutCalls).toHaveLength(0);
- const exhausted = readExhaustedReports(warnings).at(0);
- expect(exhausted).toBeDefined();
- expect(exhausted?.trigger).toBe('rail-column-sync');
- expect(exhausted?.stage).toBe('pins-do-not-fit');
- expect(exhausted?.shortfall?.['terminal-column']).toEqual({
- targetPx: RIGHT_TERMINAL_PANEL_MIN_WIDTH_PX,
- renderedPx: expect.closeTo((40 / 100) * 300, 6),
- });
+ expect(screen.getByTestId('editor-skeleton')).toBeTruthy();
+ expect(renderedInnerPanelIds()).toEqual(['doc-panel']);
+ expect(document.getElementById('doc-panel')?.childElementCount).toBe(1);
+ window.location.hash = '';
});
- test('a rail short of its floors leaves out the column that is already wide enough', async () => {
- const DOC_PANEL_FLOOR_PX = 300;
- const groupPx = DOC_PANEL_FLOOR_PX + RIGHT_TERMINAL_PANEL_MIN_WIDTH_PX - 5;
- const terminalRenderedPx = RIGHT_TERMINAL_PANEL_MIN_WIDTH_PX + 175;
- const docRenderedPx = 40;
- setViewportWidth(700);
- mockGroupPx = groupPx;
- docCtx = DOC_LIVE_CTX;
- const view = render(
- <EditorArea
- {...baseProps}
- terminalVisible={false}
- terminalPlacement="right"
- agentsVisible={false}
- />,
- );
- act(() => emitLocalMenuAction('toggle-doc-panel'));
- groupLayout = {
- 'editor-main': ((groupPx - terminalRenderedPx) / groupPx) * 100,
- 'terminal-column': (terminalRenderedPx / groupPx) * 100,
- 'agents-column': 0,
- };
- innerLayout = innerRowWithDoc(docRenderedPx, groupPx - terminalRenderedPx);
+ test('a document arriving opens the side panel even when the first write is refused', async () => {
+ setViewportWidth(1400);
+ const view = render(<EditorArea {...baseProps} />);
+ await act(async () => {});
+ innerSetLayoutCalls = [];
- const warnings = await withSynchronousFrames(() => {
- view.rerender(
- <EditorArea
- {...baseProps}
- terminalVisible
- terminalPlacement="right"
- agentsVisible={false}
- />,
- );
- });
+ refuseNextInnerLayoutWrite = true;
+ docCtx = DOC_LIVE_CTX;
+ view.rerender(<EditorArea {...baseProps} />);
+ await act(async () => {});
+ await flushFrame();
- const exhausted = readExhaustedReports(warnings).at(0);
- expect(exhausted).toBeDefined();
- expect(exhausted?.trigger).toBe('rail-column-sync');
- expect(exhausted?.stage).toBe('pins-do-not-fit');
- expect(Object.keys(exhausted?.shortfall ?? {})).toEqual(['doc-panel']);
- expect(exhausted?.shortfall?.['doc-panel']).toEqual({
- targetPx: DOC_PANEL_FLOOR_PX,
- renderedPx: expect.closeTo(docRenderedPx, 6),
- });
+ expect(innerSetLayoutCalls.length).toBeGreaterThanOrEqual(2);
+ expect(lastInnerWritePx('doc-panel')).toBeCloseTo(320, 3);
+ expect(((innerLayout['doc-panel'] ?? 0) / 100) * innerRowPx()).toBeCloseTo(320, 3);
});
- test('a pin that can never land stops reporting once the mount has had its say', async () => {
- setViewportWidth(1900);
- mockGroupPx = 1610;
- docCtx = DOC_LIVE_CTX;
- const view = render(
- <EditorArea {...baseProps} terminalVisible terminalPlacement="right" agentsVisible={false} />,
- );
- groupLayout = strandedOuter1610(44);
- innerLayout = strandedInner1610(44);
- rejectGroupLayoutWrites = true;
-
- const warnings = await withSynchronousFrames(() => {
- for (let toggle = 0; toggle < MAX_RAIL_PIN_EXHAUSTED_REPORTS + 3; toggle += 1) {
- view.rerender(
- <EditorArea
- {...baseProps}
- terminalVisible
- terminalPlacement="right"
- agentsVisible={toggle % 2 === 0}
- />,
- );
- }
+ test('a side panel pin that never lands reports the width it aimed for and the width it got', async () => {
+ setViewportWidth(1400);
+ const view = render(<EditorArea {...baseProps} />);
+ await act(async () => {});
+ const reports = exhaustionReports();
+ vi.spyOn(window, 'requestAnimationFrame').mockImplementation((callback) => {
+ callback(performance.now());
+ return 1;
});
- expect(
- readExhaustedReports(warnings).filter((report) => report.trigger === 'rail-column-sync')
- .length,
- ).toBe(MAX_RAIL_PIN_EXHAUSTED_REPORTS);
- });
-
- test('one exhausted trigger does not spend the budget the other trigger needs', async () => {
- setViewportWidth(1900);
- mockGroupPx = 1610;
+ refuseInnerLayoutWrites = true;
docCtx = DOC_LIVE_CTX;
- const view = render(
- <EditorArea {...baseProps} terminalVisible terminalPlacement="right" agentsVisible={false} />,
- );
- groupLayout = strandedOuter1610(44);
- innerLayout = strandedInner1610(44);
- rejectGroupLayoutWrites = true;
-
- const warnings = await withSynchronousFrames(() => {
- for (let toggle = 0; toggle < MAX_RAIL_PIN_EXHAUSTED_REPORTS + 3; toggle += 1) {
- view.rerender(
- <EditorArea
- {...baseProps}
- terminalVisible
- terminalPlacement="right"
- agentsVisible={toggle % 2 === 0}
- />,
- );
- }
- mockGroupPx = 0;
- docCtx = EMPTY_DOC_CTX;
- view.rerender(
- <EditorArea {...baseProps} terminalVisible terminalPlacement="right" agentsVisible />,
- );
- });
+ view.rerender(<EditorArea {...baseProps} />);
+ await act(async () => {});
- const reports = readExhaustedReports(warnings);
- expect(reports.filter((report) => report.trigger === 'rail-column-sync').length).toBe(
- MAX_RAIL_PIN_EXHAUSTED_REPORTS,
- );
- expect(reports.filter((report) => report.trigger === 'doc-slot-presence').length).toBe(1);
+ expect(reports).toEqual([
+ expect.objectContaining({
+ decision: 'sync-doc-presence',
+ targetWidthPx: 320,
+ cause: 'width-missed',
+ pinnedWidthPx: 320,
+ landedWidthPx: 0,
+ }),
+ ]);
});
- test('an editor hide the row never settles into reports its own pin outcome under its own cap', async () => {
+ test('a side panel pin whose write keeps throwing reports the error it threw', async () => {
setViewportWidth(1400);
- docCtx = DOC_LIVE_CTX;
- const view = render(<EditorArea {...baseProps} agentsVisible />);
- groupLayout = { 'editor-main': 65, 'terminal-column': 0, 'agents-column': 35 };
+ const view = render(<EditorArea {...baseProps} />);
await act(async () => {});
- rejectGroupLayoutWrites = true;
-
- const warnings = await withSynchronousFrames(async () => {
- for (let toggle = 0; toggle <= MAX_RAIL_PIN_EXHAUSTED_REPORTS * 2; toggle += 1) {
- view.rerender(<EditorArea {...baseProps} agentsVisible editorVisible={toggle % 2 === 1} />);
- await act(async () => {});
- }
+ const reports = exhaustionReports();
+ vi.spyOn(window, 'requestAnimationFrame').mockImplementation((callback) => {
+ callback(performance.now());
+ return 1;
});
- const reports = readExhaustedReports(warnings).filter(
- (report) => report.trigger === 'editor-visibility',
- );
- expect(reports.length).toBe(MAX_RAIL_PIN_EXHAUSTED_REPORTS);
- expect(reports[0]?.stage).toBe('editor-hidden-unsettled');
- });
-
- test('revealing the agents panel keeps the open doc panel open despite a stale cached layout', async () => {
- setViewportWidth(1400);
+ innerLayoutWriteError = new Error('Layout not found for Panel doc-panel');
docCtx = DOC_LIVE_CTX;
- const view = render(<EditorArea {...baseProps} agentsVisible={false} />);
- groupLayout = { 'editor-main': 70, 'agents-column': 30 };
- innerLayout = innerRowWithDoc(340, 0.7 * 1360);
- view.rerender(<EditorArea {...baseProps} agentsVisible />);
+ view.rerender(<EditorArea {...baseProps} />);
await act(async () => {});
- const corrected = groupSetLayoutCalls.at(-1);
- expect(corrected).toBeDefined();
- expect(lastInnerWritePx('doc-panel')).toBeCloseTo(320, 3);
- expect(corrected?.['agents-column']).toBeCloseTo(pctOf(480), 3);
- expect(corrected?.['editor-main']).toBeCloseTo(100 - pctOf(480), 3);
- const innerWrite = innerSetLayoutCalls.at(-1);
- expect(innerWrite).toBeDefined();
- expect(
- ((innerWrite?.['workspace-main'] ?? 0) / 100) * (innerSetLayoutPx.at(-1) ?? 0),
- ).toBeCloseTo(1360 - 480 - 320, 3);
+
+ expect(reports).toEqual([
+ expect.objectContaining({
+ decision: 'sync-doc-presence',
+ cause: 'write-threw',
+ writeError: 'Layout not found for Panel doc-panel',
+ }),
+ ]);
});
- test('the rail keeps one panel-ID set from a document to a new tab', () => {
+ test('a side panel pin that stays blocked reports once at its deadline, with no frame to run', () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
setViewportWidth(1400);
- docCtx = DOC_LIVE_CTX;
- const view = render(<EditorArea {...baseProps} agentsVisible />);
- const withDocument = renderedPanelIds();
- const withDocumentInner = renderedInnerPanelIds();
- expect(withDocument).toEqual(['terminal-column', 'agents-column']);
- expect(withDocumentInner).toEqual(['doc-panel']);
+ const frames = controlAnimationFrames();
+ const reports = exhaustionReports();
+ try {
+ const view = render(<EditorArea {...baseProps} />);
+ innerLayout = { ...BLOCKED_INNER_ROW };
+ docCtx = DOC_LIVE_CTX;
+ view.rerender(<EditorArea {...baseProps} />);
+ expectPinRetryWaitingOnAFrame(frames);
+ expect(reports).toEqual([]);
- docCtx = EMPTY_DOC_CTX;
- view.rerender(<EditorArea {...baseProps} agentsVisible />);
+ act(() => vi.advanceTimersByTime(60_000));
- expect(renderedPanelIds()).toEqual(withDocument);
- expect(renderedInnerPanelIds()).toEqual(withDocumentInner);
- expect(document.getElementById('doc-panel')?.textContent).toBe('');
+ expect(reports).toEqual([
+ expect.objectContaining({
+ decision: 'sync-doc-presence',
+ cause: 'layout-without-doc-panel',
+ }),
+ ]);
+ frames.run(frames.pendingCount(), 61_000);
+ act(() => vi.advanceTimersByTime(60_000));
+ expect(reports).toHaveLength(1);
+ } finally {
+ cleanup();
+ frames.restore();
+ vi.useRealTimers();
+ }
});
- test('the rail keeps one panel-ID set across every view kind', () => {
+ test('a newer side panel change replaces a pin still waiting on a frame', () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
setViewportWidth(1400);
- const expected = ['terminal-column', 'agents-column'];
- const expectedInner = ['doc-panel'];
- for (const ctx of [
- DOC_LIVE_CTX,
- EMPTY_DOC_CTX,
- FOLDER_DOC_CTX,
- FOLDER_AGENT_CTX,
- ASSET_DOC_CTX,
- LARGE_FILE_DOC_CTX,
- ]) {
+ const frames = controlAnimationFrames();
+ const reports = exhaustionReports();
+ try {
+ const view = render(<EditorArea {...baseProps} />);
+ innerLayout = { ...BLOCKED_INNER_ROW };
+ docCtx = DOC_LIVE_CTX;
+ view.rerender(<EditorArea {...baseProps} />);
+ expectPinRetryWaitingOnAFrame(frames);
+
+ innerLayout = { 'workspace-main': 100, 'doc-panel': 0 };
+ docCtx = EMPTY_DOC_CTX;
+ view.rerender(<EditorArea {...baseProps} />);
+ frames.run(frames.pendingCount(), 61_000);
+ act(() => vi.advanceTimersByTime(60_000));
+
+ expect(reports).toEqual([]);
+ } finally {
cleanup();
- docCtx = ctx;
- render(<EditorArea {...baseProps} agentsVisible />);
- expect(renderedPanelIds()).toEqual(expected);
- expect(renderedInnerPanelIds()).toEqual(expectedInner);
+ frames.restore();
+ vi.useRealTimers();
}
});
- test('an empty slot is clamped out of flex flow, like every hidden rail column', () => {
+ test('unmounting cancels a side panel pin still waiting on a frame', () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
setViewportWidth(1400);
- docCtx = ASSET_DOC_CTX;
- const view = render(<EditorArea {...baseProps} agentsVisible />);
- expect(document.getElementById('doc-panel')?.dataset.maxSize).toBe('0px');
+ const frames = controlAnimationFrames();
+ const reports = exhaustionReports();
+ try {
+ const view = render(<EditorArea {...baseProps} />);
+ innerLayout = { ...BLOCKED_INNER_ROW };
+ docCtx = DOC_LIVE_CTX;
+ view.rerender(<EditorArea {...baseProps} />);
+ expectPinRetryWaitingOnAFrame(frames);
- docCtx = DOC_LIVE_CTX;
- view.rerender(<EditorArea {...baseProps} agentsVisible />);
- expect(document.getElementById('doc-panel')?.dataset.maxSize).toBe('600px');
+ act(() => view.unmount());
+ frames.run(frames.pendingCount(), 61_000);
+ act(() => vi.advanceTimersByTime(60_000));
+
+ expect(reports).toEqual([]);
+ } finally {
+ frames.restore();
+ vi.useRealTimers();
+ }
});
- test('the mid-session load gap keeps the panel-ID set and fills the slot', () => {
+ test('a side panel pin waits out a handle drag without writing or spending its retries, then lands', () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
setViewportWidth(1400);
- docCtx = FOLDER_LIVE_CTX;
- const view = render(<EditorArea {...baseProps} agentsVisible />);
- window.location.hash = '#/incoming-doc';
- docCtx = DOC_COLD_CTX;
- view.rerender(<EditorArea {...baseProps} agentsVisible />);
+ const frames = controlAnimationFrames();
+ const reports = exhaustionReports();
+ try {
+ const failing = render(<EditorArea {...baseProps} />);
+ refuseInnerLayoutWrites = true;
+ docCtx = DOC_LIVE_CTX;
+ failing.rerender(<EditorArea {...baseProps} />);
+ const FAILING_PIN_FRAME_CEILING = 10_000;
+ let framesToGiveUp = 0;
+ while (reports.length === 0 && frames.pendingCount() > 0) {
+ if (framesToGiveUp === FAILING_PIN_FRAME_CEILING) {
+ throw new Error(
+ `a pin whose writes are refused was still retrying after ${FAILING_PIN_FRAME_CEILING} frames`,
+ );
+ }
+ frames.run(1, 0);
+ framesToGiveUp += 1;
+ }
+ expect(reports).toHaveLength(1);
+ failing.unmount();
+ reports.length = 0;
+ refuseInnerLayoutWrites = false;
+
+ innerLayout = innerRowWithDoc(320, 1360);
+ const view = render(<EditorArea {...baseProps} />);
+ const handle = document.getElementById('doc-panel')?.previousElementSibling;
+ if (!(handle instanceof HTMLElement)) throw new Error('doc-panel resize handle not found');
+ act(() => {
+ fireEvent.pointerDown(handle, { pointerId: 1 });
+ });
+ innerSetLayoutCalls = [];
- expect(screen.getByTestId('editor-skeleton')).toBeTruthy();
- expect(renderedPanelIds()).toEqual(['terminal-column', 'agents-column']);
- expect(renderedInnerPanelIds()).toEqual(['doc-panel']);
- expect(document.getElementById('doc-panel')?.childElementCount).toBe(1);
- window.location.hash = '';
+ docCtx = EMPTY_DOC_CTX;
+ view.rerender(<EditorArea {...baseProps} />);
+ frames.run(framesToGiveUp + 5, 0);
+ expect(innerSetLayoutCalls).toEqual([]);
+ expect(reports).toEqual([]);
+
+ refuseInnerLayoutWrites = true;
+ act(() => {
+ fireEvent.pointerUp(window, { pointerId: 1 });
+ });
+ frames.run(1);
+ expect(innerSetLayoutCalls.length).toBeGreaterThan(0);
+ expect(reports).toEqual([]);
+
+ refuseInnerLayoutWrites = false;
+ frames.run(5);
+ act(() => vi.advanceTimersByTime(60_000));
+
+ expect(lastInnerWritePx('doc-panel')).toBe(0);
+ expect(innerLayout['doc-panel']).toBe(0);
+ expect(reports).toEqual([]);
+ } finally {
+ cleanup();
+ frames.restore();
+ vi.useRealTimers();
+ }
});
test('emptying the slot hands its width to the editor; refilling takes it back', async () => {
setViewportWidth(1400);
docCtx = DOC_LIVE_CTX;
const view = render(<EditorArea {...baseProps} />);
- groupLayout = {
- 'editor-main': 100,
- 'terminal-column': 0,
- 'agents-column': 0,
- };
innerLayout = { 'workspace-main': 60, 'doc-panel': 40 };
innerSetLayoutCalls = [];
@@ -1697,11 +1196,6 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
setViewportWidth(1024);
docCtx = FOLDER_DOC_CTX;
const view = render(<EditorArea {...baseProps} />);
- groupLayout = {
- 'editor-main': 100,
- 'terminal-column': 0,
- 'agents-column': 0,
- };
innerSetLayoutCalls = [];
docCtx = { ...FOLDER_AGENT_CTX, docPanelExpandSignal: 1 };
@@ -1720,11 +1214,6 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
const requests: PaneVisibilityRequest[] = [];
paneVisibilityStore.subscribeRequests((request) => requests.push(request));
const view = render(<EditorArea {...baseProps} editorVisible={false} />);
- groupLayout = {
- 'editor-main': 100,
- 'terminal-column': 0,
- 'agents-column': 0,
- };
await act(async () => {});
innerSetLayoutCalls = [];
@@ -1742,1276 +1231,517 @@ describe('EditorArea right-rail layout assert on column mount/unmount', () => {
test('a view with no document pane pins the slot shut and ignores the toggle', async () => {
setViewportWidth(1400);
docCtx = ASSET_DOC_CTX;
- groupLayout = {
- 'editor-main': 100 - pctOf(480),
- 'terminal-column': 0,
- 'agents-column': pctOf(480),
- };
render(<EditorArea {...baseProps} agentsVisible />);
- groupSetLayoutCalls = [];
innerSetLayoutCalls = [];
- groupLayout = {
- 'editor-main': 70,
- 'terminal-column': 0,
- 'agents-column': 30,
- };
innerLayout = { 'workspace-main': 75, 'doc-panel': 25 };
act(() => emitLocalMenuAction('toggle-doc-panel'));
await act(async () => {});
- expect(groupSetLayoutCalls).toHaveLength(0);
expect(innerSetLayoutCalls).toHaveLength(0);
});
+});
- test('releasing an agents-handle drag below the close threshold hides the panel', async () => {
- setViewportWidth(1400);
- const visibleChanges: boolean[] = [];
- render(
- <EditorArea
- {...baseProps}
- agentsVisible
- onAgentsVisibleChange={(visible: boolean) => {
- visibleChanges.push(visible);
- }}
- />,
- );
- const handle = getAgentsHandle();
- act(() => {
- fireEvent.pointerDown(handle, { pointerId: 1 });
- });
- mockPanelPx = 0;
- mockPanelPercentage = 0;
- panelIsCollapsed = true;
- act(() => {
- fireEvent.pointerUp(window, { pointerId: 1 });
- });
- expect(visibleChanges.at(-1)).toBe(false);
+describe('EditorArea agents panel region', () => {
+ beforeEach(() => {
+ cleanup();
+ docCtx = EMPTY_DOC_CTX;
});
- test('a divider drag that closes chat while its history covers the panel leaves it collapsed without changing visibility', async () => {
- setViewportWidth(1400);
- const visibleChanges: boolean[] = [];
+ test('the agents panel mounts in the panels region, not the header', () => {
render(
<EditorArea
- {...baseProps}
+ editorMode="wysiwyg"
+ onModeChange={() => {}}
+ activeTab="timeline"
+ onActiveTabChange={() => {}}
+ terminalBridge={{ terminal: {} } as never}
agentsVisible
- onAgentsVisibleChange={(visible: boolean) => {
- visibleChanges.push(visible);
- }}
/>,
);
- const mount = document.querySelector('[data-agents-panel-mount]');
- if (mount == null) throw new Error('no chat mount to hold the history cover');
- const cover = document.createElement('aside');
- cover.setAttribute('data-history-mode', 'cover');
- mount.appendChild(cover);
- const handle = getAgentsHandle();
- act(() => {
- fireEvent.pointerDown(handle, { pointerId: 1 });
- });
- mockPanelPx = 0;
- mockPanelPercentage = 0;
- panelIsCollapsed = true;
- act(() => {
- fireEvent.pointerUp(window, { pointerId: 1 });
- });
- expect(visibleChanges).toEqual([]);
- cover.remove();
+ 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(agentMount).toBeTruthy();
+ expect(panels?.contains(agentMount)).toBe(true);
+ expect(header?.contains(agentMount)).toBe(false);
});
+});
- test('releasing an agents-handle drag in the middle band settles at the minimum', () => {
- setViewportWidth(1400);
- const visibleChanges: boolean[] = [];
+describe('EditorArea dock units', () => {
+ const unitProps = {
+ editorMode: 'wysiwyg',
+ onModeChange: () => {},
+ activeTab: 'timeline',
+ onActiveTabChange: () => {},
+ terminalBridge: {} as never,
+ } as const;
+
+ beforeEach(() => {
+ cleanup();
+ localStorage.clear();
+ docCtx = DOC_LIVE_CTX;
+ editorWorkspaceMounts = 0;
+ });
+
+ test('places a bottom terminal under the editor, with chat beside the column', () => {
+ render(<EditorArea {...unitProps} terminalVisible agentsVisible />);
+
+ expect(unitPx('editor', 'insetInlineStart')).toBe(0);
+ expect(unitPx('terminal', 'insetInlineStart')).toBe(0);
+ expect(unitPx('terminal', 'insetBlockStart')).toBeGreaterThan(unitPx('editor', 'height'));
+ expect(unitPx('terminal', 'width')).toBe(unitPx('editor', 'width'));
+ expect(unitPx('agents', 'insetInlineStart')).toBeGreaterThan(unitPx('editor', 'width'));
+ expect(unitPx('agents', 'height')).toBe(WORKSPACE_HEIGHT_PX);
+ expect(paneCard('terminal')?.getAttribute('data-placement')).toBe('bottom');
+ });
+
+ test('places a right terminal between the editor and chat', () => {
+ const placements: SessionPlacements[] = [];
render(
<EditorArea
- {...baseProps}
+ {...unitProps}
+ dockTree={RIGHT_TERMINAL_TREE}
+ terminalVisible
agentsVisible
- onAgentsVisibleChange={(visible: boolean) => {
- visibleChanges.push(visible);
- }}
+ onSessionPlacements={(value) => placements.push(value)}
/>,
);
- groupLayout = { 'editor-main': 100 - pctOf(250), 'agents-column': pctOf(250) };
- groupSetLayoutCalls = [];
- const handle = getAgentsHandle();
- act(() => {
- fireEvent.pointerDown(handle, { pointerId: 1 });
- });
- mockPanelPx = 250;
- mockPanelPercentage = pctOf(250);
- act(() => {
- fireEvent.pointerUp(window, { pointerId: 1 });
- });
- expect(visibleChanges).toHaveLength(0);
- expect(groupSetLayoutCalls.at(-1)?.['agents-column']).toBeCloseTo(pctOf(320), 3);
- });
- test('a rejected first agents pointer settlement still reaches the minimum', async () => {
- setViewportWidth(1400);
- groupLayout = {
- 'editor-main': 100 - pctOf(480),
- 'agents-column': pctOf(480),
- };
- render(<EditorArea {...baseProps} agentsVisible />);
- await act(async () => {});
+ const editorEnd = unitPx('editor', 'insetInlineStart') + unitPx('editor', 'width');
+ const terminalStart = unitPx('terminal', 'insetInlineStart');
+ const terminalEnd = terminalStart + unitPx('terminal', 'width');
+ expect(terminalStart).toBeGreaterThan(editorEnd);
+ expect(unitPx('agents', 'insetInlineStart')).toBeGreaterThan(terminalEnd);
+ expect(unitPx('terminal', 'height')).toBe(WORKSPACE_HEIGHT_PX);
+ expect(paneCard('terminal')?.getAttribute('data-placement')).toBe('right');
+ expect(placements.at(-1)?.terminal.container).toBe(terminalMount());
+ expect(placements.at(-1)?.terminal.isShowing).toBe(true);
+ });
- groupLayout = {
- 'editor-main': 100 - pctOf(250),
- 'agents-column': pctOf(250),
- };
- mockPanelPx = 250;
- mockPanelPercentage = pctOf(250);
- rejectNextGroupLayoutWrite = true;
- const handle = getAgentsHandle();
+ test('a right terminal and chat are their own cards in their own units, outside the editor card', () => {
+ render(
+ <TooltipProvider>
+ <EditorArea {...unitProps} dockTree={RIGHT_TERMINAL_TREE} terminalVisible agentsVisible />
+ </TooltipProvider>,
+ );
- act(() => {
- fireEvent.pointerDown(handle, { pointerId: 1 });
- fireEvent.pointerUp(window, { pointerId: 1 });
- });
+ const editorCard = paneCard('editor');
+ const terminalCard = paneCard('terminal');
+ const chatCard = paneCard('agents');
+ expect(terminalCard?.getAttribute('data-variant')).toBe('card');
+ expect(chatCard?.getAttribute('data-variant')).toBe('card');
+ expect(dockUnit('editor').contains(editorCard)).toBe(true);
+ expect(dockUnit('terminal').contains(terminalCard)).toBe(true);
+ expect(dockUnit('agents').contains(chatCard)).toBe(true);
+ expect(terminalCard?.contains(terminalMount())).toBe(true);
+ expect(chatCard?.contains(agentsMount())).toBe(true);
+ expect(editorCard?.contains(terminalCard)).toBe(false);
+ expect(editorCard?.contains(chatCard)).toBe(false);
+ });
- await act(
- () =>
- new Promise<void>((resolve) => {
- requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
- }),
+ test('without a terminal, as on the web, the terminal unit stays hidden and draws no card', () => {
+ render(
+ <TooltipProvider>
+ <EditorArea {...unitProps} terminalBridge={undefined} agentsVisible terminalVisible />
+ </TooltipProvider>,
);
- expect(groupLayout['agents-column']).toBeCloseTo(pctOf(320), 3);
+ expect(paneCard('terminal')).toBeNull();
+ expect(terminalMount()).toBeNull();
+ expect(dockUnit('terminal').hidden).toBe(true);
+ expect(paneCard('agents')).not.toBeNull();
+ expect(unitPx('agents', 'height')).toBe(WORKSPACE_HEIGHT_PX);
+ expect(unitPx('editor', 'height')).toBe(WORKSPACE_HEIGHT_PX);
});
- test.each([
- ['document', 'doc-panel'],
- ['terminal', TERMINAL_COLUMN_ID],
- ] as const)(
- 'an active %s drag blocks agents settlement without spending its failure budget',
- (_label, columnId) => {
- setViewportWidth(1400);
- docCtx = FOLDER_DOC_CTX;
- groupLayout = {
- 'editor-main': 100 - pctOf(440 + 480),
- 'terminal-column': pctOf(440),
- 'agents-column': pctOf(480),
- };
- innerLayout = innerRowWithDoc(320, 1360 - 440 - 480);
- const frames = controlAnimationFrames();
- const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
- try {
- render(
- <EditorArea
- {...baseProps}
- agentsVisible
- terminalVisible
- terminalPlacement="right"
- onTerminalVisibleChange={() => {}}
- />,
- );
- groupLayout = {
- 'editor-main': 100 - pctOf(440 + 250),
- 'terminal-column': pctOf(440),
- 'agents-column': pctOf(250),
- };
- innerLayout = innerRowWithDoc(320, 1360 - 440 - 250);
- mockPanelPx = 250;
- mockPanelPercentage = pctOf(250);
- rejectNextGroupLayoutWrite = true;
-
- act(() => {
- fireEvent.pointerDown(getAgentsHandle(), { pointerId: 1 });
- fireEvent.pointerUp(window, { pointerId: 1 });
- });
-
- const panel = document.getElementById(columnId);
- const handle = panel?.previousElementSibling;
- if (!(handle instanceof HTMLElement))
- throw new Error(`${columnId} resize handle not found`);
- rejectGroupLayoutWrites = true;
- act(() => {
- fireEvent.pointerDown(handle, { pointerId: 2 });
- });
- const writesBeforeBlockedFrames = groupSetLayoutCalls.length;
-
- frames.run(40);
-
- expect.soft(groupSetLayoutCalls).toHaveLength(writesBeforeBlockedFrames);
- expect.soft(warnSpy.mock.calls).toEqual([]);
- expect.soft(frames.pendingCount()).toBe(1);
-
- rejectGroupLayoutWrites = false;
- act(() => {
- fireEvent.pointerUp(window, { pointerId: 2 });
- });
- frames.run(1);
-
- expect.soft(groupLayout['agents-column']).toBeCloseTo(pctOf(320), 3);
- expect.soft(frames.pendingCount()).toBe(0);
- } finally {
- warnSpy.mockRestore();
- frames.restore();
- }
- },
- );
-
- test('a permanently blocked agents settlement reports without an animation frame', () => {
- const blockedRetryTimeoutMs = 60_000;
- vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
- setViewportWidth(1400);
- docCtx = FOLDER_DOC_CTX;
- groupLayout = {
- 'editor-main': 100 - pctOf(480),
- 'agents-column': pctOf(480),
- };
- innerLayout = innerRowWithDoc(320, 1360 - 480);
- const frames = controlAnimationFrames();
- const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
- try {
- render(<EditorArea {...baseProps} agentsVisible />);
- groupLayout = {
- 'editor-main': 100 - pctOf(250),
- 'agents-column': pctOf(250),
- };
- innerLayout = innerRowWithDoc(320, 1360 - 250);
- mockPanelPx = 250;
- mockPanelPercentage = pctOf(250);
- rejectNextGroupLayoutWrite = true;
+ test('pane mounts are inert while their panes are off', () => {
+ render(<EditorArea {...unitProps} />);
- act(() => {
- fireEvent.pointerDown(getAgentsHandle(), { pointerId: 1 });
- fireEvent.pointerUp(window, { pointerId: 1 });
- });
+ expect(agentsMount()?.hasAttribute('inert')).toBe(true);
+ expect(terminalMount()?.hasAttribute('inert')).toBe(true);
+ expect(dockUnit('agents').hidden).toBe(true);
+ expect(dockUnit('terminal').hidden).toBe(true);
+ });
- const docPanel = document.getElementById('doc-panel');
- const docHandle = docPanel?.previousElementSibling;
- if (!(docHandle instanceof HTMLElement)) throw new Error('doc-panel resize handle not found');
- act(() => {
- fireEvent.pointerDown(docHandle, { pointerId: 2 });
- });
+ test('pane mounts stay focusable while their panes are on', () => {
+ render(<EditorArea {...unitProps} agentsVisible terminalVisible />);
- act(() => vi.advanceTimersByTime(blockedRetryTimeoutMs));
-
- expect.soft(warnSpy.mock.calls).toEqual([
- [
- JSON.stringify({
- event: 'rail-layout-retry-exhausted',
- error: 'Rail layout did not apply within the retry budget',
- decision: 'settle-minimum',
- targetWidthPx: 320,
- }),
- ],
- ]);
- expect.soft(frames.pendingCount()).toBe(0);
- } finally {
- cleanup();
- warnSpy.mockRestore();
- frames.restore();
- vi.useRealTimers();
- }
+ expect(agentsMount()?.hasAttribute('inert')).toBe(false);
+ expect(terminalMount()?.hasAttribute('inert')).toBe(false);
+ expect(dockUnit('agents').hasAttribute('inert')).toBe(false);
+ expect(dockUnit('terminal').hasAttribute('inert')).toBe(false);
});
- test('an agents pointer settlement reports once after exhausting its retry budget', () => {
- setViewportWidth(1400);
- groupLayout = {
- 'editor-main': 100 - pctOf(480),
- 'agents-column': pctOf(480),
- };
- const frames = controlAnimationFrames();
- const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
- try {
- render(<EditorArea {...baseProps} agentsVisible />);
- groupLayout = {
- 'editor-main': 100 - pctOf(250),
- 'agents-column': pctOf(250),
- };
- mockPanelPx = 250;
- mockPanelPercentage = pctOf(250);
- rejectGroupLayoutWrites = true;
- const handle = getAgentsHandle();
+ test('a pane reports that it is showing only while it is on', () => {
+ const placements: SessionPlacements[] = [];
+ const area = (agentsVisible: boolean, terminalVisible: boolean) => (
+ <EditorArea
+ {...unitProps}
+ agentsVisible={agentsVisible}
+ terminalVisible={terminalVisible}
+ onSessionPlacements={(value) => placements.push(value)}
+ />
+ );
+ const view = render(area(true, true));
+ expect(placements.at(-1)?.agents.isShowing).toBe(true);
+ expect(placements.at(-1)?.terminal.isShowing).toBe(true);
- act(() => {
- fireEvent.pointerDown(handle, { pointerId: 1 });
- fireEvent.pointerUp(window, { pointerId: 1 });
- });
- frames.run(30);
-
- expect(frames.pendingCount()).toBe(0);
- expect(warnSpy.mock.calls).toEqual([
- [
- JSON.stringify({
- event: 'rail-layout-retry-exhausted',
- error: 'Rail layout did not apply within the retry budget',
- decision: 'settle-minimum',
- targetWidthPx: 320,
- }),
- ],
- ]);
- } finally {
- warnSpy.mockRestore();
- frames.restore();
- }
+ view.rerender(area(false, true));
+ expect(placements.at(-1)?.agents.isShowing).toBe(false);
+ expect(placements.at(-1)?.agents.container).toBe(agentsMount());
+ expect(placements.at(-1)?.terminal.isShowing).toBe(true);
+
+ view.rerender(area(false, false));
+ expect(placements.at(-1)?.terminal.isShowing).toBe(false);
+ expect(placements.at(-1)?.terminal.container).toBe(terminalMount());
+
+ view.rerender(area(true, true));
+ expect(placements.at(-1)?.agents.isShowing).toBe(true);
+ expect(placements.at(-1)?.terminal.isShowing).toBe(true);
});
- test('a production close reports exhaustion with its decision and target width', () => {
- setViewportWidth(1400);
- groupLayout = {
- 'editor-main': 100 - pctOf(480),
- 'agents-column': pctOf(480),
- };
- const frames = controlAnimationFrames();
- const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
- function ControlledAgentsVisibility() {
- const [agentsVisible, setAgentsVisible] = useState(true);
- return (
- <EditorArea
- {...baseProps}
- agentsVisible={agentsVisible}
- onAgentsVisibleChange={setAgentsVisible}
- />
+ test('moving or hiding the terminal, and showing or hiding chat, never remounts the open editor', () => {
+ const { rerender } = render(
+ <TooltipProvider>
+ <EditorArea {...unitProps} terminalVisible agentsVisible={false} />
+ </TooltipProvider>,
+ );
+ const tabs = screen.getByTestId('workspace-tabs');
+ const editorRegion = document.querySelector('[data-editor-region]');
+ const terminal = terminalMount();
+ const chat = agentsMount();
+ expect(editorWorkspaceMounts).toBe(1);
+
+ const steps: Array<{
+ terminalVisible: boolean;
+ dockTree: DockNode;
+ agentsVisible: boolean;
+ }> = [
+ { terminalVisible: true, dockTree: RIGHT_TERMINAL_TREE, agentsVisible: false },
+ { terminalVisible: true, dockTree: RIGHT_TERMINAL_TREE, agentsVisible: true },
+ { terminalVisible: false, dockTree: RIGHT_TERMINAL_TREE, agentsVisible: true },
+ { terminalVisible: true, dockTree: DEFAULT_DOCK_TREE, agentsVisible: true },
+ { terminalVisible: false, dockTree: DEFAULT_DOCK_TREE, agentsVisible: false },
+ { terminalVisible: true, dockTree: DEFAULT_DOCK_TREE, agentsVisible: false },
+ ];
+ for (const step of steps) {
+ rerender(
+ <TooltipProvider>
+ <EditorArea {...unitProps} {...step} />
+ </TooltipProvider>,
);
}
- try {
- render(<ControlledAgentsVisibility />);
- groupLayout = {
- 'editor-main': 100 - pctOf(100),
- 'agents-column': pctOf(100),
- };
- mockPanelPx = 100;
- mockPanelPercentage = pctOf(100);
- rejectGroupLayoutWrites = true;
+ act(() => emitLocalMenuAction('toggle-doc-panel'));
+ act(() => emitLocalMenuAction('toggle-doc-panel'));
- act(() => {
- fireEvent.pointerDown(getAgentsHandle(), { pointerId: 1 });
- fireEvent.pointerUp(window, { pointerId: 1 });
- });
- frames.run(30);
-
- expect(frames.pendingCount()).toBe(0);
- expect(warnSpy.mock.calls).toEqual([
- [
- JSON.stringify({
- event: 'rail-layout-retry-exhausted',
- error: 'Rail layout did not apply within the retry budget',
- decision: 'close',
- targetWidthPx: 0,
- }),
- ],
- ]);
- } finally {
- warnSpy.mockRestore();
- frames.restore();
- }
+ expect(editorWorkspaceMounts).toBe(1);
+ expect(screen.getByTestId('workspace-tabs')).toBe(tabs);
+ expect(document.querySelector('[data-editor-region]')).toBe(editorRegion);
+ expect(terminalMount()).toBe(terminal);
+ expect(agentsMount()).toBe(chat);
+ expect(screen.getByRole('main').contains(tabs)).toBe(true);
});
+});
- test('a newer agents-handle interaction supersedes a pending settlement frame', () => {
- vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
- setViewportWidth(1400);
- groupLayout = {
- 'editor-main': 100 - pctOf(480),
- 'agents-column': pctOf(480),
- };
- const frames = controlAnimationFrames();
- const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
- try {
- render(<EditorArea {...baseProps} agentsVisible />);
- groupLayout = {
- 'editor-main': 100 - pctOf(250),
- 'agents-column': pctOf(250),
- };
- mockPanelPx = 250;
- mockPanelPercentage = pctOf(250);
- rejectNextGroupLayoutWrite = true;
- const handle = getAgentsHandle();
+describe('EditorArea dock seams', () => {
+ const seamProps = {
+ editorMode: 'wysiwyg',
+ onModeChange: () => {},
+ activeTab: 'timeline',
+ onActiveTabChange: () => {},
+ terminalBridge: {} as never,
+ } as const;
- act(() => {
- fireEvent.pointerDown(handle, { pointerId: 1 });
- fireEvent.pointerUp(window, { pointerId: 1 });
- });
- const pendingAfterFirstRelease = frames.pendingCount();
-
- groupLayout = {
- 'editor-main': 100 - pctOf(600),
- 'agents-column': pctOf(600),
- };
- mockPanelPx = 600;
- mockPanelPercentage = pctOf(600);
- act(() => {
- fireEvent.pointerDown(handle, { pointerId: 2 });
- });
- const pendingDuringSecondDrag = frames.pendingCount();
- act(() => {
- fireEvent.pointerUp(window, { pointerId: 2 });
- });
- frames.run(30);
- act(() => vi.advanceTimersByTime(60_000));
+ beforeEach(() => {
+ cleanup();
+ localStorage.clear();
+ docCtx = DOC_LIVE_CTX;
+ });
- expect.soft(pendingAfterFirstRelease).toBeGreaterThan(0);
- expect.soft(pendingDuringSecondDrag).toBe(0);
- expect.soft(groupLayout['agents-column']).toBeCloseTo(pctOf(600), 3);
- expect(warnSpy.mock.calls).toEqual([]);
- } finally {
- cleanup();
- warnSpy.mockRestore();
- frames.restore();
- vi.useRealTimers();
- }
+ test('names each seam for the pane it resizes, next to the side panel separator', () => {
+ render(<EditorArea {...seamProps} agentsVisible terminalVisible />);
+
+ expect(
+ screen
+ .getByRole('separator', { name: 'Resize document panel' })
+ .getAttribute('aria-controls'),
+ ).toBe('doc-panel');
+ expect(dockSeam('Resize Agents').getAttribute('aria-controls')).toBe(dockUnit('agents').id);
+ expect(dockSeam('Resize Agents').getAttribute('aria-orientation')).toBe('vertical');
+ expect(dockSeam('Resize Terminal').getAttribute('aria-controls')).toBe(dockUnit('terminal').id);
+ expect(dockSeam('Resize Terminal').getAttribute('aria-orientation')).toBe('horizontal');
});
- test('unmount cancels a pending agents pointer settlement frame', () => {
- vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
- setViewportWidth(1400);
- groupLayout = {
- 'editor-main': 100 - pctOf(480),
- 'agents-column': pctOf(480),
- };
- const frames = controlAnimationFrames();
- const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
- try {
- const view = render(<EditorArea {...baseProps} agentsVisible />);
- groupLayout = {
- 'editor-main': 100 - pctOf(250),
- 'agents-column': pctOf(250),
- };
- mockPanelPx = 250;
- mockPanelPercentage = pctOf(250);
- rejectNextGroupLayoutWrite = true;
- const handle = getAgentsHandle();
+ test('a pane that is off takes its seam with it', () => {
+ render(<EditorArea {...seamProps} agentsVisible />);
- act(() => {
- fireEvent.pointerDown(handle, { pointerId: 1 });
- fireEvent.pointerUp(window, { pointerId: 1 });
- });
- const pendingBeforeUnmount = frames.pendingCount();
- const writesBeforeUnmount = groupSetLayoutCalls.length;
- act(() => view.unmount());
- const pendingAfterUnmount = frames.pendingCount();
- frames.run(30);
- act(() => vi.advanceTimersByTime(60_000));
+ expect(dockSeam('Resize Agents')).toBeTruthy();
+ expect(screen.queryByRole('separator', { name: 'Resize Terminal' })).toBeNull();
+ });
- expect.soft(pendingBeforeUnmount).toBeGreaterThan(0);
- expect.soft(pendingAfterUnmount).toBe(0);
- expect.soft(groupSetLayoutCalls).toHaveLength(writesBeforeUnmount);
- expect.soft(groupLayout['agents-column']).toBeCloseTo(pctOf(250), 3);
- expect(warnSpy.mock.calls).toEqual([]);
- } finally {
- warnSpy.mockRestore();
- frames.restore();
- vi.useRealTimers();
+ test('a seam reports the resized tree, and the panes follow it', () => {
+ function DockHost() {
+ const [tree, setTree] = useState<DockNode>(DEFAULT_DOCK_TREE);
+ return (
+ <EditorArea
+ {...seamProps}
+ agentsVisible
+ terminalVisible
+ dockTree={tree}
+ onDockTreeChange={(update) => {
+ const next = update(tree);
+ trees.push(next);
+ setTree(next);
+ }}
+ />
+ );
}
- });
+ const trees: DockNode[] = [];
+ render(<DockHost />);
+ const agentsWidth = unitPx('agents', 'width');
- test('releasing an agents-handle drag above the minimum commits the measured width', () => {
- setViewportWidth(1400);
- render(<EditorArea {...baseProps} agentsVisible />);
- groupLayout = { 'editor-main': 100 - pctOf(600), 'agents-column': pctOf(600) };
- groupSetLayoutCalls = [];
- const handle = getAgentsHandle();
- act(() => {
- fireEvent.pointerDown(handle, { pointerId: 1 });
- });
- mockPanelPx = 600;
- mockPanelPercentage = pctOf(600);
- act(() => {
- fireEvent.pointerUp(window, { pointerId: 1 });
- });
- expect(groupSetLayoutCalls.at(-1)?.['agents-column']).toBeCloseTo(pctOf(600), 3);
- expect(localStorage.getItem('ok-terminal-width-v1')).toBe('600');
+ fireEvent.keyDown(dockSeam('Resize Agents'), { key: 'ArrowLeft' });
+
+ expect(trees).toHaveLength(1);
+ expect(unitPx('agents', 'width')).toBe(agentsWidth + 16);
});
- test('a close-threshold release without a visibility callback restores the preferred width', () => {
- setViewportWidth(1400);
- render(<EditorArea {...baseProps} agentsVisible onAgentsVisibleChange={undefined} />);
- groupLayout = { 'editor-main': 100 - pctOf(100), 'agents-column': pctOf(100) };
- groupSetLayoutCalls = [];
- const handle = getAgentsHandle();
- act(() => {
- fireEvent.pointerDown(handle, { pointerId: 1 });
- });
- mockPanelPx = 100;
- mockPanelPercentage = pctOf(100);
- act(() => {
- fireEvent.pointerUp(window, { pointerId: 1 });
+ test('a seam that resizes the editor re-pins the side panel at its pixel width without waiting for a frame', () => {
+ Object.defineProperty(window, 'innerWidth', {
+ value: 1400,
+ configurable: true,
+ writable: true,
});
- expect(groupSetLayoutCalls.at(-1)?.['agents-column']).toBeCloseTo(pctOf(480), 3);
- });
+ mockEditorUnitPx = 1360;
+ innerLayout = innerRowWithDoc(320, 1360);
+ function DockHost() {
+ const [tree, setTree] = useState<DockNode>(DEFAULT_DOCK_TREE);
+ return <EditorArea {...seamProps} agentsVisible dockTree={tree} onDockTreeChange={setTree} />;
+ }
+ render(<DockHost />);
+ innerSetLayoutCalls = [];
- test('a close-threshold fallback reports the closed target when settlement exhausts', () => {
- setViewportWidth(1400);
- groupLayout = {
- 'editor-main': 100 - pctOf(480),
- 'agents-column': pctOf(480),
- };
- const frames = controlAnimationFrames();
- const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
- try {
- render(<EditorArea {...baseProps} agentsVisible onAgentsVisibleChange={undefined} />);
- groupLayout = {
- 'editor-main': 100 - pctOf(100),
- 'agents-column': pctOf(100),
- };
- mockPanelPx = 100;
- mockPanelPercentage = pctOf(100);
- rejectGroupLayoutWrites = true;
+ mockEditorUnitPx = 1360 - 16;
+ fireEvent.keyDown(dockSeam('Resize Agents'), { key: 'ArrowLeft' });
- act(() => {
- fireEvent.pointerDown(getAgentsHandle(), { pointerId: 1 });
- fireEvent.pointerUp(window, { pointerId: 1 });
- });
- frames.run(30);
-
- expect(frames.pendingCount()).toBe(0);
- expect(warnSpy.mock.calls).toEqual([
- [
- JSON.stringify({
- event: 'rail-layout-retry-exhausted',
- error: 'Rail layout did not apply within the retry budget',
- decision: 'close',
- targetWidthPx: 0,
- }),
- ],
- ]);
- } finally {
- warnSpy.mockRestore();
- frames.restore();
- }
+ expect(innerSetLayoutCalls.length).toBeGreaterThan(0);
+ expect(lastInnerWritePx('doc-panel')).toBeCloseTo(320, 3);
});
- test('transient drag widths never reach durable storage', () => {
- vi.useFakeTimers();
- try {
- setViewportWidth(1400);
- render(<EditorArea {...baseProps} agentsVisible />);
- const handle = getAgentsHandle();
- act(() => {
- fireEvent.pointerDown(handle, { pointerId: 1 });
- railPanelOnResizeById.get(AGENTS_COLUMN_ID)?.({
- asPercentage: pctOf(250),
- inPixels: 250,
- });
- vi.advanceTimersByTime(101);
- });
- expect(localStorage.getItem('ok-terminal-width-v1')).toBeNull();
- act(() => {
- fireEvent.pointerCancel(window, { pointerId: 1 });
- });
- } finally {
- vi.useRealTimers();
- }
- });
+ test('a seam drag marks the dock workspace and not the side panel row', () => {
+ render(<EditorArea {...seamProps} agentsVisible />);
+ const workspace = document.querySelector('[data-dock-workspace]');
+ const seam = dockSeam('Resize Agents');
- test('names the agents-only separator for the Agents pane it resizes', () => {
- setViewportWidth(1400);
- render(<EditorArea {...baseProps} agentsVisible />);
+ fireEvent.pointerDown(seam, { pointerId: 3, button: 0, clientX: 900 });
- const handle = screen.getByRole('separator', { name: 'Agents' });
- expect(handle).toBe(getAgentsHandle());
- expect(handle.getAttribute('aria-controls')).toBe(AGENTS_COLUMN_ID);
+ expect(workspace?.hasAttribute('data-dragging')).toBe(true);
+ expect(screen.getByTestId('resizable-group-inner').hasAttribute('data-dragging')).toBe(false);
+ fireEvent.pointerUp(seam, { pointerId: 3, clientX: 900 });
+ expect(workspace?.hasAttribute('data-dragging')).toBe(false);
});
+});
- test('names the side panel and right terminal separators for the panes they resize', () => {
- setViewportWidth(1400);
- docCtx = DOC_LIVE_CTX;
- render(<EditorArea {...baseProps} agentsVisible terminalVisible terminalPlacement="right" />);
+describe('EditorArea terminal unit across view kinds', () => {
+ const viewKinds = [
+ { name: 'folder', ctx: FOLDER_DOC_CTX, content: 'folder-overview' },
+ { name: 'large-file', ctx: LARGE_FILE_DOC_CTX, content: 'large-file-state' },
+ { name: 'asset', ctx: ASSET_DOC_CTX, content: 'asset-preview' },
+ ] as const;
- expect(
- screen
- .getByRole('separator', { name: 'Resize document panel' })
- .getAttribute('aria-controls'),
- ).toBe('doc-panel');
- expect(
- screen.getByRole('separator', { name: 'Resize terminal' }).getAttribute('aria-controls'),
- ).toBe(TERMINAL_COLUMN_ID);
- expect(screen.getByRole('separator', { name: 'Terminal' })).toBe(getAgentsHandle());
- });
-
- test('keyboard resizing floors only the focused agents separator', () => {
- setViewportWidth(1400);
- render(<EditorArea {...baseProps} agentsVisible terminalVisible terminalPlacement="right" />);
- const handle = getAgentsHandle();
- expect(screen.getByRole('separator', { name: 'Terminal' })).toBe(handle);
- expect(handle.getAttribute('aria-controls')).toBe(TERMINAL_COLUMN_ID);
- handle.focus();
- const activeElement = document.activeElement;
- groupLayout = {
- 'editor-main': 70,
- 'terminal-column': 10,
- 'agents-column': 20,
- };
- groupSetLayoutCalls = [];
- act(() => {
- groupOnLayoutChanged?.(groupLayout, { isUserInteraction: true });
- });
- expect(groupSetLayoutCalls.at(-1)?.['agents-column']).toBeCloseTo(pctOf(320), 3);
- expect(document.activeElement).toBe(activeElement);
- expect(localStorage.getItem('ok-terminal-width-v1')).toBeNull();
-
- const terminalHandle = screen.getAllByTestId('resizable-handle').at(-2);
- terminalHandle?.focus();
- groupSetLayoutCalls = [];
- act(() => {
- groupOnLayoutChanged?.(groupLayout, { isUserInteraction: true });
- });
- expect(groupSetLayoutCalls).toHaveLength(0);
- });
-
- test('keyboard resizing reaches the minimum after the first layout write is refused', () => {
- setViewportWidth(1400);
- groupLayout = {
- 'editor-main': 100 - pctOf(480),
- 'agents-column': pctOf(480),
- };
- const frames = controlAnimationFrames();
- try {
- render(<EditorArea {...baseProps} agentsVisible />);
- getAgentsHandle().focus();
- groupLayout = {
- 'editor-main': 100 - pctOf(250),
- 'agents-column': pctOf(250),
- };
- rejectNextGroupLayoutWrite = true;
-
- act(() => {
- groupOnLayoutChanged?.(groupLayout, { isUserInteraction: true });
- });
-
- expect(groupLayout['agents-column']).toBeCloseTo(pctOf(250), 3);
- frames.run(1);
- expect(groupLayout['agents-column']).toBeCloseTo(pctOf(320), 3);
- expect(frames.pendingCount()).toBe(0);
- } finally {
- frames.restore();
- }
+ beforeEach(() => {
+ cleanup();
});
- test('keyboard retry recomputes the minimum after the group width changes', () => {
- setViewportWidth(1400);
- groupLayout = {
- 'editor-main': 100 - pctOf(480),
- 'agents-column': pctOf(480),
- };
- const frames = controlAnimationFrames();
- try {
- render(<EditorArea {...baseProps} agentsVisible />);
- getAgentsHandle().focus();
- groupLayout = {
- 'editor-main': 100 - pctOf(250),
- 'agents-column': pctOf(250),
- };
- rejectNextGroupLayoutWrite = true;
-
- act(() => {
- groupOnLayoutChanged?.(groupLayout, { isUserInteraction: true });
- });
-
- const writesAfterRejectedAttempt = groupSetLayoutCalls.length;
- mockGroupPx = 0;
- frames.run(1);
- expect(groupSetLayoutCalls).toHaveLength(writesAfterRejectedAttempt);
- expect(frames.pendingCount()).toBe(1);
-
- mockGroupPx = 1000;
- frames.run(1);
-
- expect(groupLayout['agents-column']).toBeCloseTo(32, 3);
- expect(document.getElementById('agents-column')?.getBoundingClientRect().width).toBeCloseTo(
- 320,
- 3,
+ test.each(viewKinds)(
+ 'places the terminal unit beside the $name view when a bridge is present',
+ ({ ctx, content }) => {
+ docCtx = ctx;
+ render(
+ <EditorArea
+ editorMode="wysiwyg"
+ onModeChange={() => {}}
+ activeTab="timeline"
+ onActiveTabChange={() => {}}
+ terminalBridge={{} as never}
+ terminalVisible
+ />,
);
- expect(frames.pendingCount()).toBe(0);
- } finally {
- frames.restore();
- }
- });
-
- test('keyboard resizing reports exhaustion with its minimum width target', () => {
- setViewportWidth(1400);
- groupLayout = {
- 'editor-main': 100 - pctOf(480),
- 'agents-column': pctOf(480),
- };
- const frames = controlAnimationFrames();
- const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
- try {
- render(<EditorArea {...baseProps} agentsVisible />);
- getAgentsHandle().focus();
- groupLayout = {
- 'editor-main': 100 - pctOf(250),
- 'agents-column': pctOf(250),
- };
- rejectGroupLayoutWrites = true;
-
- act(() => {
- groupOnLayoutChanged?.(groupLayout, { isUserInteraction: true });
- });
- frames.run(30);
-
- expect(groupLayout['agents-column']).toBeCloseTo(pctOf(250), 3);
- expect(frames.pendingCount()).toBe(0);
- expect(warnSpy.mock.calls).toEqual([
- [
- JSON.stringify({
- event: 'rail-layout-retry-exhausted',
- error: 'Rail layout did not apply within the retry budget',
- decision: 'keyboard-settle-minimum',
- targetWidthPx: MIN_AGENTS_PANEL_WIDTH,
- }),
- ],
- ]);
- } finally {
- warnSpy.mockRestore();
- frames.restore();
- }
- });
- test('a newer keyboard width cancels a refused minimum settlement', () => {
- setViewportWidth(1400);
- groupLayout = {
- 'editor-main': 100 - pctOf(480),
- 'agents-column': pctOf(480),
- };
- const frames = controlAnimationFrames();
- try {
- render(<EditorArea {...baseProps} agentsVisible />);
- getAgentsHandle().focus();
- groupLayout = {
- 'editor-main': 100 - pctOf(250),
- 'agents-column': pctOf(250),
- };
- rejectNextGroupLayoutWrite = true;
- act(() => {
- groupOnLayoutChanged?.(groupLayout, { isUserInteraction: true });
- });
- expect(frames.pendingCount()).toBe(1);
+ expect(dockUnit('editor').contains(screen.getByTestId(content))).toBe(true);
+ expect(dockUnit('terminal').hidden).toBe(false);
+ expect(dockUnit('terminal').contains(terminalMount())).toBe(true);
+ },
+ );
- groupLayout = {
- 'editor-main': 100 - pctOf(600),
- 'agents-column': pctOf(600),
- };
- act(() => {
- groupOnLayoutChanged?.(groupLayout, { isUserInteraction: true });
- });
- frames.run(30);
+ test.each(viewKinds)(
+ 'renders the $name view with no terminal unit on the web host',
+ ({ ctx, content }) => {
+ docCtx = ctx;
+ renderEditorArea();
- expect(groupLayout['agents-column']).toBeCloseTo(pctOf(600), 3);
- expect(frames.pendingCount()).toBe(0);
- } finally {
- frames.restore();
- }
- });
+ expect(dockUnit('editor').contains(screen.getByTestId(content))).toBe(true);
+ expect(dockUnit('terminal').hidden).toBe(true);
+ expect(terminalMount()).toBeNull();
+ },
+ );
- test('a focused keyboard width supersedes a refused pointer settlement', () => {
- setViewportWidth(1400);
- groupLayout = {
- 'editor-main': 100 - pctOf(480),
- 'agents-column': pctOf(480),
+ test('keeps the same terminal mount while the active view kind changes', () => {
+ docCtx = FOLDER_DOC_CTX;
+ const props = {
+ editorMode: 'wysiwyg' as const,
+ onModeChange: () => {},
+ activeTab: 'timeline' as const,
+ onActiveTabChange: () => {},
+ terminalBridge: {} as never,
+ terminalVisible: true,
};
- const frames = controlAnimationFrames();
- try {
- render(<EditorArea {...baseProps} agentsVisible />);
- groupLayout = {
- 'editor-main': 100 - pctOf(250),
- 'agents-column': pctOf(250),
- };
- mockPanelPx = 250;
- mockPanelPercentage = pctOf(250);
- rejectNextGroupLayoutWrite = true;
- const handle = getAgentsHandle();
-
- act(() => {
- fireEvent.pointerDown(handle, { pointerId: 1 });
- fireEvent.pointerUp(window, { pointerId: 1 });
- });
- expect(frames.pendingCount()).toBe(1);
-
- handle.focus();
- groupLayout = {
- 'editor-main': 100 - pctOf(600),
- 'agents-column': pctOf(600),
- };
- mockPanelPx = 600;
- mockPanelPercentage = pctOf(600);
- act(() => {
- groupOnLayoutChanged?.(groupLayout, { isUserInteraction: true });
- });
- frames.run(30);
+ const { rerender } = render(<EditorArea {...props} />);
+ const mount = terminalMount();
+ expect(mount).not.toBeNull();
- expect(groupLayout['agents-column']).toBeCloseTo(pctOf(600), 3);
- expect(frames.pendingCount()).toBe(0);
- } finally {
- frames.restore();
+ for (const { ctx, content } of [...viewKinds].reverse()) {
+ docCtx = ctx;
+ rerender(<EditorArea {...props} />);
+ expect(dockUnit('editor').contains(screen.getByTestId(content))).toBe(true);
+ expect(terminalMount()).toBe(mount);
}
});
+});
- test('a different focused handle supersedes a refused keyboard settlement', () => {
- setViewportWidth(1400);
- docCtx = FOLDER_DOC_CTX;
- groupLayout = {
- 'editor-main': 100 - pctOf(480),
- 'agents-column': pctOf(480),
- };
- innerLayout = innerRowWithDoc(320, 1360 - 480);
- const frames = controlAnimationFrames();
- try {
- render(<EditorArea {...baseProps} agentsVisible />);
- getAgentsHandle().focus();
- groupLayout = {
- 'editor-main': 100 - pctOf(250),
- 'agents-column': pctOf(250),
- };
- innerLayout = innerRowWithDoc(320, 1360 - 250);
- rejectNextGroupLayoutWrite = true;
- act(() => {
- groupOnLayoutChanged?.(groupLayout, { isUserInteraction: true });
- });
- expect(frames.pendingCount()).toBe(1);
-
- const docPanel = document.getElementById('doc-panel');
- const docHandle = docPanel?.previousElementSibling;
- if (!(docHandle instanceof HTMLElement)) throw new Error('doc-panel resize handle not found');
- docHandle.focus();
- groupLayout = {
- 'editor-main': 100 - pctOf(600),
- 'agents-column': pctOf(600),
- };
- innerLayout = innerRowWithDoc(320, 1360 - 600);
- act(() => {
- innerRowHandlers.onLayoutChanged?.(innerLayout, { isUserInteraction: true });
- });
- frames.run(30);
-
- expect(groupLayout['agents-column']).toBeCloseTo(pctOf(600), 3);
- expect(frames.pendingCount()).toBe(0);
- } finally {
- frames.restore();
- }
+describe('EditorArea hash-load skeleton renders inside the editor card (cold start)', () => {
+ beforeEach(() => {
+ cleanup();
+ docCtx = DOC_COLD_CTX;
+ });
+ afterEach(() => {
+ window.location.hash = '';
});
- test.each([
- { label: 'doc', panelId: 'doc-panel', terminalVisible: false },
- { label: 'Terminal', panelId: 'terminal-column', terminalVisible: true },
- ])(
- 'a $label handle drag pauses a refused keyboard settlement',
- ({ panelId, terminalVisible }) => {
- setViewportWidth(1400);
- if (!terminalVisible) docCtx = FOLDER_DOC_CTX;
- const outerRowWith = (agentsPx: number): MockLayout =>
+ test('renders the load skeleton in the document area, with the panel rows and the side panel slot in place', () => {
+ window.location.hash = '#/some-doc';
+ render(
+ <EditorArea
+ editorMode="wysiwyg"
+ onModeChange={() => {}}
+ activeTab="timeline"
+ onActiveTabChange={() => {}}
+ terminalBridge={{} as never}
terminalVisible
- ? {
- 'editor-main': 100 - pctOf(320 + agentsPx),
- 'terminal-column': pctOf(320),
- 'agents-column': pctOf(agentsPx),
- }
- : { 'editor-main': 100 - pctOf(agentsPx), 'agents-column': pctOf(agentsPx) };
- groupLayout = outerRowWith(480);
- if (!terminalVisible) innerLayout = innerRowWithDoc(320, 1360 - 480);
- const frames = controlAnimationFrames();
- try {
- render(
- <EditorArea
- {...baseProps}
- agentsVisible
- terminalVisible={terminalVisible}
- terminalPlacement="right"
- />,
- );
- getAgentsHandle().focus();
- groupLayout = outerRowWith(250);
- if (!terminalVisible) innerLayout = innerRowWithDoc(320, 1360 - 250);
- rejectNextGroupLayoutWrite = true;
- act(() => {
- groupOnLayoutChanged?.(groupLayout, { isUserInteraction: true });
- });
- expect(frames.pendingCount()).toBe(1);
-
- const panel = document.getElementById(panelId);
- const handle = panel?.previousElementSibling;
- if (!(handle instanceof HTMLElement)) throw new Error(`${panelId} resize handle not found`);
- const writesBeforeDrag = groupSetLayoutCalls.length;
- act(() => {
- fireEvent.pointerDown(handle, { pointerId: 1 });
- });
- handle.focus();
- act(() => {
- if (panelId === 'doc-panel') {
- innerRowHandlers.onLayoutChanged?.(innerLayout, { isUserInteraction: true });
- } else {
- groupOnLayoutChanged?.(groupLayout, { isUserInteraction: true });
- }
- });
- frames.run(30);
-
- expect(groupLayout['agents-column']).toBeCloseTo(pctOf(250), 3);
- expect(groupSetLayoutCalls).toHaveLength(writesBeforeDrag);
- expect(frames.pendingCount()).toBe(1);
-
- act(() => {
- fireEvent.pointerUp(window, { pointerId: 1 });
- });
- frames.run(1);
-
- expect(groupLayout['agents-column']).toBeCloseTo(pctOf(320), 3);
- expect(frames.pendingCount()).toBe(0);
- } finally {
- frames.restore();
- }
- },
- );
-
- test('keyboard resizing uses the current group box when panel pixels lag the layout callback', () => {
- setViewportWidth(1200);
- render(<EditorArea {...baseProps} agentsVisible />);
- const handle = getAgentsHandle();
- handle.focus();
- const panelWidths = [880, 0, 320];
- const panelElements = screen
- .getByTestId('resizable-group')
- .querySelectorAll(':scope > [data-slot="resizable-panel"]');
- expect(panelElements).toHaveLength(panelWidths.length);
- panelElements.forEach((element, index) => {
- Object.defineProperty(element, 'getBoundingClientRect', {
- configurable: true,
- value: () => {
- const width = panelWidths[index] ?? 0;
- return { width, height: 0, top: 0, left: 0, right: width, bottom: 0, x: 0, y: 0 };
- },
- });
- });
- mockPanelPercentage = (260 / 1200) * 100;
- mockPanelPx = 320.004;
- groupLayout = {
- 'editor-main': 100 - mockPanelPercentage,
- 'terminal-column': 0,
- 'agents-column': mockPanelPercentage,
- };
- groupSetLayoutCalls = [];
-
- act(() => {
- groupOnLayoutChanged?.(groupLayout, { isUserInteraction: true });
- });
+ />,
+ );
- expect(groupSetLayoutCalls.at(-1)?.['agents-column']).toBeCloseTo((320 / 1200) * 100, 3);
+ const skeleton = screen.getByTestId('editor-skeleton');
+ expect(skeleton.closest('[data-editor-workspace-column]')).not.toBeNull();
+ expect(skeleton.closest('[data-slot="pane-card"][data-pane="editor"]')).not.toBeNull();
+ expect(renderedInnerPanelIds()).toEqual(['doc-panel']);
+ expect(document.getElementById('doc-panel')?.getAttribute('data-max-size')).toBe('600px');
});
- test('keyboard collapse leaves logical visibility unchanged', () => {
- setViewportWidth(1400);
- const visibleChanges: boolean[] = [];
+ test('keeps the file list drawn in the editor card while the skeleton shows', () => {
+ window.location.hash = '#/some-doc';
render(
- <EditorArea
- {...baseProps}
- agentsVisible
- onAgentsVisibleChange={(visible: boolean) => {
- visibleChanges.push(visible);
- }}
- />,
+ <FileListHostProvider enabled fileList={<nav data-testid="cold-load-file-list" />}>
+ <EditorArea
+ editorMode="wysiwyg"
+ onModeChange={() => {}}
+ activeTab="timeline"
+ onActiveTabChange={() => {}}
+ />
+ </FileListHostProvider>,
);
- getAgentsHandle().focus();
- groupLayout = {
- 'editor-main': 100,
- 'terminal-column': 0,
- 'agents-column': 0,
- };
- groupSetLayoutCalls = [];
- act(() => {
- groupOnLayoutChanged?.(groupLayout, { isUserInteraction: true });
- railPanelOnResizeById.get(AGENTS_COLUMN_ID)?.({ asPercentage: 0, inPixels: 0 });
- });
- expect(groupSetLayoutCalls).toHaveLength(0);
- expect(visibleChanges).toHaveLength(0);
+
+ expect(screen.getByTestId('editor-skeleton')).toBeTruthy();
+ const card = document.querySelector('[data-slot="pane-card"][data-pane="editor"]');
+ expect(card?.contains(screen.getByTestId('cold-load-file-list'))).toBe(true);
+ expect(card?.contains(screen.getByTestId('editor-skeleton'))).toBe(true);
});
- test('releasing an agents-handle drag with the column still open does NOT hide the panel', async () => {
- setViewportWidth(1400);
- const visibleChanges: boolean[] = [];
+ test('ignores a side panel toggle while the skeleton holds the slot, so no pin is written before the target is known', () => {
+ localStorage.clear();
+ window.location.hash = '#/some-folder';
render(
<EditorArea
- {...baseProps}
- agentsVisible
- onAgentsVisibleChange={(visible: boolean) => {
- visibleChanges.push(visible);
- }}
+ editorMode="wysiwyg"
+ onModeChange={() => {}}
+ activeTab="timeline"
+ onActiveTabChange={() => {}}
/>,
);
- const handle = getAgentsHandle();
- act(() => {
- fireEvent.pointerDown(handle);
- });
- act(() => {
- fireEvent.pointerUp(window);
- });
- expect(visibleChanges).toHaveLength(0);
+ expect(screen.getByTestId('editor-skeleton')).toBeTruthy();
+
+ act(() => emitLocalMenuAction('toggle-doc-panel'));
+
+ expect(localStorage.getItem('ok-sidebar-pins-v2')).toBeNull();
});
- test('a pointercancel-terminated drag still clears the flag that gates the layout assert', async () => {
- setViewportWidth(1400);
- const view = render(<EditorArea {...baseProps} agentsVisible />);
- const handle = getAgentsHandle();
- act(() => {
- fireEvent.pointerDown(handle);
- });
+ test('keeps the side panel slot the same panel when the document arrives, so its width restore is undisturbed', () => {
+ window.location.hash = '#/docs/notes';
+ const props = {
+ editorMode: 'wysiwyg' as const,
+ onModeChange: () => {},
+ activeTab: 'timeline' as const,
+ onActiveTabChange: () => {},
+ };
+ const { rerender } = render(<EditorArea {...props} />);
+ const docPanel = document.getElementById('doc-panel');
+ expect(docPanel?.getAttribute('data-max-size')).toBe('600px');
+
act(() => {
- fireEvent.pointerCancel(window);
+ docCtx = DOC_LIVE_CTX;
});
- groupSetLayoutCalls = [];
+ rerender(<EditorArea {...props} />);
- groupLayout = { 'editor-main': 70, 'agents-column': 30 };
- view.rerender(<EditorArea {...baseProps} agentsVisible={false} />);
- await act(async () => {});
- expect(groupSetLayoutCalls.length).toBeGreaterThan(0);
+ expect(screen.queryByTestId('editor-skeleton')).toBeNull();
+ expect(document.getElementById('doc-panel')).toBe(docPanel);
+ expect(docPanel?.getAttribute('data-max-size')).toBe('600px');
+ expect(renderedInnerPanelIds()).toEqual(['doc-panel']);
});
+});
- test('a pointercancel restores the rail pins rather than committing a drag-to-close', async () => {
- setViewportWidth(1400);
- const visibleChanges: boolean[] = [];
- render(
- <EditorArea
- {...baseProps}
- agentsVisible
- onAgentsVisibleChange={(visible: boolean) => {
- visibleChanges.push(visible);
- }}
- />,
- );
- groupLayout = { 'editor-main': 70, 'agents-column': 30 };
- const handle = getAgentsHandle();
- act(() => {
- fireEvent.pointerDown(handle);
- });
- panelIsCollapsed = true;
- act(() => {
- fireEvent.pointerCancel(window);
- });
- expect(visibleChanges).toHaveLength(0);
- expect(groupSetLayoutCalls.at(-1)?.['agents-column']).toBeCloseTo(pctOf(480), 3);
+describe('EditorArea document panel host ownership', () => {
+ beforeEach(() => {
+ cleanup();
+ docCtx = DOC_LIVE_CTX;
});
- test('a drag interrupted by unmount does not commit a drag-to-close afterwards', async () => {
- setViewportWidth(1400);
- const visibleChanges: boolean[] = [];
- const view = render(
+ test('releases the document panel host when the editor area unmounts', () => {
+ const { unmount } = render(
<EditorArea
- {...baseProps}
- agentsVisible
- onAgentsVisibleChange={(visible: boolean) => {
- visibleChanges.push(visible);
- }}
+ editorMode="wysiwyg"
+ onModeChange={() => {}}
+ activeTab="outline"
+ onActiveTabChange={() => {}}
/>,
);
- const handle = getAgentsHandle();
- act(() => {
- fireEvent.pointerDown(handle, { pointerId: 1 });
- });
- panelIsCollapsed = true;
- act(() => {
- view.unmount();
- });
- act(() => {
- fireEvent.pointerUp(window, { pointerId: 1 });
- });
- expect(visibleChanges).toHaveLength(0);
- });
-
- test('a different pointer cancelling does not end an in-flight drag', async () => {
- setViewportWidth(1400);
- const view = render(<EditorArea {...baseProps} agentsVisible />);
- const handle = getAgentsHandle();
- act(() => {
- fireEvent.pointerDown(handle, { pointerId: 1 });
- });
- groupSetLayoutCalls = [];
- groupLayout = { 'editor-main': 70, 'agents-column': 30 };
-
- act(() => {
- fireEvent.pointerCancel(window, { pointerId: 2 });
- });
- expect(groupSetLayoutCalls).toHaveLength(0);
-
- view.rerender(<EditorArea {...baseProps} agentsVisible={false} />);
- await act(async () => {});
- expect(groupSetLayoutCalls).toHaveLength(0);
-
- act(() => {
- fireEvent.pointerCancel(window, { pointerId: 1 });
- });
- expect(groupSetLayoutCalls.length).toBeGreaterThan(0);
- });
-});
-
-describe('EditorArea agents panel region', () => {
- beforeEach(() => {
- cleanup();
- docCtx = EMPTY_DOC_CTX;
- });
-
- test('the agents panel mounts in the panels region, not the header', () => {
- render(
- <EditorArea
- editorMode="wysiwyg"
- onModeChange={() => {}}
- activeTab="timeline"
- onActiveTabChange={() => {}}
- terminalBridge={{ terminal: {} } as never}
- onAgentsVisibleChange={() => {}}
- onTerminalVisibleChange={() => {}}
- agentsVisible
- />,
- );
- 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(agentMount).toBeTruthy();
- expect(panels?.contains(agentMount)).toBe(true);
- expect(header?.contains(agentMount)).toBe(false);
- });
-});
-
-describe('EditorArea terminal placement', () => {
- beforeEach(() => {
- cleanup();
- docCtx = DOC_LIVE_CTX;
- });
-
- test('places a visible right terminal between the document and agents rails', () => {
- const placements: unknown[] = [];
- render(
- <EditorArea
- editorMode="wysiwyg"
- onModeChange={() => {}}
- activeTab="timeline"
- onActiveTabChange={() => {}}
- terminalBridge={{} as never}
- terminalVisible
- terminalPlacement="right"
- agentsVisible
- onTerminalVisibleChange={() => {}}
- onSessionPlacements={(value) => placements.push(value)}
- />,
- );
-
- const documentPanel = document.getElementById('doc-panel');
- const terminalPanel = document.getElementById('terminal-column');
- const agentsPanel = document.getElementById('agents-column');
- expect(terminalPanel).not.toBeNull();
- expect(
- documentPanel?.compareDocumentPosition(terminalPanel as Node) &
- Node.DOCUMENT_POSITION_FOLLOWING,
- ).toBeTruthy();
- expect(
- terminalPanel?.compareDocumentPosition(agentsPanel as Node) &
- Node.DOCUMENT_POSITION_FOLLOWING,
- ).toBeTruthy();
- expect(screen.getByTestId('terminal-dock').getAttribute('data-placement')).toBe('right');
- const latest = placements.at(-1) as {
- terminal?: { container?: Element; isShowing?: boolean };
- };
- expect(latest.terminal?.container).toBe(document.querySelector('[data-terminal-panel-mount]'));
- expect(latest.terminal?.isShowing).toBe(true);
- });
-});
-
-describe('EditorArea folder-view terminal host', () => {
- beforeEach(() => {
- cleanup();
- docCtx = FOLDER_DOC_CTX;
- });
-
- test('hosts the docked terminal in folder view when a terminal bridge is present', () => {
- render(
- <EditorArea
- editorMode="wysiwyg"
- onModeChange={() => {}}
- activeTab="timeline"
- onActiveTabChange={() => {}}
- terminalBridge={{} as never}
- terminalVisible
- onTerminalVisibleChange={() => {}}
- />,
- );
-
- const dock = screen.getByTestId('terminal-dock');
- expect(dock.getAttribute('data-visible')).toBe('true');
- expect(dock.querySelector('[data-testid="folder-overview"]')).not.toBeNull();
- });
-
- test('renders the folder view; the dock shell is present but inactive on the web host', () => {
- renderEditorArea();
-
- expect(screen.getByTestId('terminal-dock').getAttribute('data-visible')).toBe('false');
- expect(screen.getByTestId('folder-overview').textContent).toBe('folder');
- });
-});
-
-describe('EditorArea large-file-view terminal host', () => {
- beforeEach(() => {
- cleanup();
- docCtx = LARGE_FILE_DOC_CTX;
- });
-
- test('hosts the docked terminal in the large-file view when a bridge is present', () => {
- render(
- <EditorArea
- editorMode="wysiwyg"
- onModeChange={() => {}}
- activeTab="timeline"
- onActiveTabChange={() => {}}
- terminalBridge={{} as never}
- terminalVisible
- onTerminalVisibleChange={() => {}}
- />,
- );
-
- const dock = screen.getByTestId('terminal-dock');
- expect(dock.getAttribute('data-visible')).toBe('true');
- expect(dock.querySelector('[data-testid="large-file-state"]')).not.toBeNull();
- });
+ const panel = document.getElementById('doc-panel');
+ const dock = panel?.firstElementChild;
+ const host = dock?.firstElementChild;
+ expect(panel).not.toBeNull();
+ expect(host).not.toBeNull();
+ expect(host?.parentElement).toBe(dock);
- test('renders the large-file view; the dock shell is present but inactive on the web host', () => {
- renderEditorArea();
+ unmount();
- expect(screen.getByTestId('terminal-dock').getAttribute('data-visible')).toBe('false');
- expect(screen.getByTestId('large-file-state')).toBeTruthy();
+ expect(document.getElementById('doc-panel')).toBeNull();
+ expect(host?.parentElement).toBeNull();
});
});
-describe('EditorArea asset-view terminal host', () => {
+describe('EditorArea terminal persists across a mid-session cold navigation', () => {
beforeEach(() => {
cleanup();
- docCtx = ASSET_DOC_CTX;
- });
-
- test('hosts the docked terminal in the asset view when a bridge is present', () => {
- render(
- <EditorArea
- editorMode="wysiwyg"
- onModeChange={() => {}}
- activeTab="timeline"
- onActiveTabChange={() => {}}
- terminalBridge={{} as never}
- terminalVisible
- onTerminalVisibleChange={() => {}}
- />,
- );
-
- const dock = screen.getByTestId('terminal-dock');
- expect(dock.getAttribute('data-visible')).toBe('true');
- expect(dock.querySelector('[data-testid="asset-preview"]')).not.toBeNull();
- });
-
- test('renders the asset view; the dock shell is present but inactive on the web host', () => {
- renderEditorArea();
-
- expect(screen.getByTestId('terminal-dock').getAttribute('data-visible')).toBe('false');
- expect(screen.getByTestId('asset-preview')).toBeTruthy();
+ window.location.hash = '';
+ docCtx = FOLDER_LIVE_CTX;
});
-});
-
-describe('EditorArea terminal persists across view-kind switches', () => {
- beforeEach(() => {
- cleanup();
- terminalDockMounts = 0;
- docCtx = FOLDER_DOC_CTX;
+ afterEach(() => {
+ window.location.hash = '';
});
- test('keeps a single TerminalDock instance mounted while the active view kind changes', () => {
+ test('keeps the terminal mount when a tab close/switch transiently nulls the provider', () => {
const props = {
editorMode: 'wysiwyg' as const,
onModeChange: () => {},
@@ -3019,240 +1749,69 @@ describe('EditorArea terminal persists across view-kind switches', () => {
onActiveTabChange: () => {},
terminalBridge: {} as never,
terminalVisible: true,
- onTerminalVisibleChange: () => {},
};
const { rerender } = render(<EditorArea {...props} />);
- const mountsAfterInitial = terminalDockMounts;
- expect(mountsAfterInitial).toBeGreaterThan(0);
- expect(
- screen.getByTestId('terminal-dock').querySelector('[data-testid="folder-overview"]'),
- ).not.toBeNull();
+ const mount = terminalMount();
+ expect(mount).not.toBeNull();
+ expect(dockUnit('editor').contains(screen.getByTestId('folder-overview'))).toBe(true);
- docCtx = ASSET_DOC_CTX;
- rerender(<EditorArea {...props} />);
- expect(
- screen.getByTestId('terminal-dock').querySelector('[data-testid="asset-preview"]'),
- ).not.toBeNull();
-
- docCtx = LARGE_FILE_DOC_CTX;
+ act(() => {
+ docCtx = DOC_COLD_CTX;
+ window.location.hash = '#/some-doc';
+ });
rerender(<EditorArea {...props} />);
- expect(
- screen.getByTestId('terminal-dock').querySelector('[data-testid="large-file-state"]'),
- ).not.toBeNull();
-
- expect(terminalDockMounts).toBe(mountsAfterInitial);
- });
-});
-describe('EditorArea hash-load skeleton renders inside the editor card (cold start)', () => {
- beforeEach(() => {
- cleanup();
- docCtx = DOC_COLD_CTX;
- });
- afterEach(() => {
- window.location.hash = '';
+ expect(dockUnit('editor').contains(screen.getByTestId('editor-skeleton'))).toBe(true);
+ expect(terminalMount()).toBe(mount);
+ expect(dockUnit('terminal').hidden).toBe(false);
});
- test('renders the load skeleton in the document area, with the panel rows and the side panel slot in place', () => {
- window.location.hash = '#/some-doc';
- render(
- <EditorArea
- editorMode="wysiwyg"
- onModeChange={() => {}}
- activeTab="timeline"
- onActiveTabChange={() => {}}
- terminalBridge={{} as never}
- terminalVisible
- onTerminalVisibleChange={() => {}}
- />,
- );
+ test('web host keeps chat on screen through a mid-session cold nav, with the skeleton in the document area', () => {
+ const webProps = {
+ editorMode: 'wysiwyg' as const,
+ onModeChange: () => {},
+ activeTab: 'timeline' as const,
+ onActiveTabChange: () => {},
+ agentsVisible: true,
+ };
+ const { rerender } = render(<EditorArea {...webProps} />);
+ const agentsMount = document.querySelector('[data-agents-panel-mount]');
+ expect(agentsMount).not.toBeNull();
+ act(() => {
+ docCtx = DOC_COLD_CTX;
+ window.location.hash = '#/some-doc';
+ });
+ rerender(<EditorArea {...webProps} />);
const skeleton = screen.getByTestId('editor-skeleton');
expect(skeleton.closest('[data-editor-workspace-column]')).not.toBeNull();
- expect(skeleton.closest('[data-slot="pane-card"][data-pane="editor"]')).not.toBeNull();
- expect(screen.getByTestId('resizable-group')).toBeTruthy();
- expect(renderedInnerPanelIds()).toEqual(['doc-panel']);
- expect(document.getElementById('doc-panel')?.getAttribute('data-max-size')).toBe('600px');
+ expect(document.querySelector('[data-agents-panel-mount]')).toBe(agentsMount);
});
+});
- test('keeps the file list drawn in the editor card while the skeleton shows', () => {
- window.location.hash = '#/some-doc';
- render(
- <FileListHostProvider enabled fileList={<nav data-testid="cold-load-file-list" />}>
+describe('EditorArea doc-panel tab requests', () => {
+ function TabHost({
+ initialTab,
+ onActiveTabChange,
+ }: {
+ initialTab: PanelTab;
+ onActiveTabChange?: (tab: PanelTab) => void;
+ }) {
+ const [tab, setTab] = useState<PanelTab>(initialTab);
+ return (
+ <TooltipProvider>
<EditorArea
editorMode="wysiwyg"
onModeChange={() => {}}
- activeTab="timeline"
- onActiveTabChange={() => {}}
+ activeTab={tab}
+ onActiveTabChange={(nextTab) => {
+ onActiveTabChange?.(nextTab);
+ setTab(nextTab);
+ }}
/>
- </FileListHostProvider>,
- );
-
- expect(screen.getByTestId('editor-skeleton')).toBeTruthy();
- const card = document.querySelector('[data-slot="pane-card"][data-pane="editor"]');
- expect(card?.contains(screen.getByTestId('cold-load-file-list'))).toBe(true);
- expect(card?.contains(screen.getByTestId('editor-skeleton'))).toBe(true);
- });
-
- test('ignores a side panel toggle while the skeleton holds the slot, so no pin is written before the target is known', () => {
- localStorage.clear();
- window.location.hash = '#/some-folder';
- render(
- <EditorArea
- editorMode="wysiwyg"
- onModeChange={() => {}}
- activeTab="timeline"
- onActiveTabChange={() => {}}
- />,
+ </TooltipProvider>
);
- expect(screen.getByTestId('editor-skeleton')).toBeTruthy();
-
- act(() => emitLocalMenuAction('toggle-doc-panel'));
-
- expect(localStorage.getItem('ok-sidebar-pins-v2')).toBeNull();
- });
-
- test('keeps the side panel slot the same panel when the document arrives, so its width restore is undisturbed', () => {
- window.location.hash = '#/docs/notes';
- const props = {
- editorMode: 'wysiwyg' as const,
- onModeChange: () => {},
- activeTab: 'timeline' as const,
- onActiveTabChange: () => {},
- };
- const { rerender } = render(<EditorArea {...props} />);
- const docPanel = document.getElementById('doc-panel');
- expect(docPanel?.getAttribute('data-max-size')).toBe('600px');
-
- act(() => {
- docCtx = DOC_LIVE_CTX;
- });
- rerender(<EditorArea {...props} />);
-
- expect(screen.queryByTestId('editor-skeleton')).toBeNull();
- expect(document.getElementById('doc-panel')).toBe(docPanel);
- expect(docPanel?.getAttribute('data-max-size')).toBe('600px');
- expect(renderedInnerPanelIds()).toEqual(['doc-panel']);
- });
-});
-
-describe('EditorArea document panel host ownership', () => {
- beforeEach(() => {
- cleanup();
- docCtx = DOC_LIVE_CTX;
- });
-
- test('releases the document panel host when the editor area unmounts', () => {
- const { unmount } = render(
- <EditorArea
- editorMode="wysiwyg"
- onModeChange={() => {}}
- activeTab="outline"
- onActiveTabChange={() => {}}
- />,
- );
- const panel = document.getElementById('doc-panel');
- const dock = panel?.firstElementChild;
- const host = dock?.firstElementChild;
- expect(panel).not.toBeNull();
- expect(host).not.toBeNull();
- expect(host?.parentElement).toBe(dock);
-
- unmount();
-
- expect(document.getElementById('doc-panel')).toBeNull();
- expect(host?.parentElement).toBeNull();
- });
-});
-
-describe('EditorArea terminal persists across a mid-session cold navigation', () => {
- beforeEach(() => {
- cleanup();
- terminalDockMounts = 0;
- window.location.hash = '';
- docCtx = FOLDER_LIVE_CTX;
- });
- afterEach(() => {
- window.location.hash = '';
- });
-
- test('keeps the dock mounted when a tab close/switch transiently nulls the provider', () => {
- const props = {
- editorMode: 'wysiwyg' as const,
- onModeChange: () => {},
- activeTab: 'timeline' as const,
- onActiveTabChange: () => {},
- terminalBridge: {} as never,
- terminalVisible: true,
- onTerminalVisibleChange: () => {},
- };
- const { rerender } = render(<EditorArea {...props} />);
- const mountsAfterInitial = terminalDockMounts;
- expect(mountsAfterInitial).toBeGreaterThan(0);
- expect(
- screen.getByTestId('terminal-dock').querySelector('[data-testid="folder-overview"]'),
- ).not.toBeNull();
-
- act(() => {
- docCtx = DOC_COLD_CTX;
- window.location.hash = '#/some-doc';
- });
- rerender(<EditorArea {...props} />);
-
- const dock = screen.getByTestId('terminal-dock');
- expect(dock.querySelector('[data-testid="editor-skeleton"]')).not.toBeNull();
- expect(terminalDockMounts).toBe(mountsAfterInitial);
- expect(screen.getByTestId('resizable-group')).toBeTruthy();
- });
-
- test('web host keeps chat on screen through a mid-session cold nav, with the skeleton in the document area', () => {
- const webProps = {
- editorMode: 'wysiwyg' as const,
- onModeChange: () => {},
- activeTab: 'timeline' as const,
- onActiveTabChange: () => {},
- agentsVisible: true,
- onAgentsVisibleChange: () => {},
- };
- const { rerender } = render(<EditorArea {...webProps} />);
- const agentsMount = document.querySelector('[data-agents-panel-mount]');
- expect(agentsMount).not.toBeNull();
- act(() => {
- docCtx = DOC_COLD_CTX;
- window.location.hash = '#/some-doc';
- });
- rerender(<EditorArea {...webProps} />);
-
- const skeleton = screen.getByTestId('editor-skeleton');
- expect(skeleton.closest('[data-editor-workspace-column]')).not.toBeNull();
- expect(screen.getByTestId('resizable-group')).toBeTruthy();
- expect(document.querySelector('[data-agents-panel-mount]')).toBe(agentsMount);
- });
-});
-
-describe('EditorArea doc-panel tab requests', () => {
- function TabHost({
- initialTab,
- onActiveTabChange,
- }: {
- initialTab: PanelTab;
- onActiveTabChange?: (tab: PanelTab) => void;
- }) {
- const [tab, setTab] = useState<PanelTab>(initialTab);
- return (
- <TooltipProvider>
- <EditorArea
- editorMode="wysiwyg"
- onModeChange={() => {}}
- activeTab={tab}
- onActiveTabChange={(nextTab) => {
- onActiveTabChange?.(nextTab);
- setTab(nextTab);
- }}
- />
- </TooltipProvider>
- );
- }
+ }
function mountTabHost(initialTab: PanelTab, onActiveTabChange?: (tab: PanelTab) => void) {
const resizeObserver = installResizeObserver();
@@ -3263,1870 +1822,413 @@ describe('EditorArea doc-panel tab requests', () => {
for (const element of [card, inner]) {
Object.defineProperty(element, 'getBoundingClientRect', {
configurable: true,
- value: () => ({ width: rowPx('inner'), height: 0, top: 0, left: 0 }),
- });
- }
- resizeObserver.fire('[data-slot="pane-card"][data-pane="editor"]');
- resizeObserver.fire('[data-editor-inner-panels]');
- return { view, resizeObserver };
- }
-
- const infoWidthPx = () => document.getElementById('doc-panel')?.getBoundingClientRect().width;
- const docPanelToggle = () => {
- const toggle = document.querySelector<HTMLElement>('[data-doc-panel-toggle]');
- if (toggle == null) throw new Error('the document panel toggle is absent');
- return toggle;
- };
-
- beforeEach(() => {
- cleanup();
- localStorage.clear();
- localStorage.setItem(
- SIDEBAR_PINS_KEY,
- JSON.stringify({ right: { above: 'collapsed', below: 'collapsed', embedded: 'collapsed' } }),
- );
- docCtx = { ...DOC_LIVE_CTX, docPanelMode: 'doc' };
- groupLayout = { 'editor-main': 100 };
- innerLayout = { ...INNER_LAYOUT_DOC_CLOSED };
- groupSetLayoutCalls = [];
- mockGroupPx = 1360;
- Object.defineProperty(window, 'innerWidth', {
- value: 1400,
- configurable: true,
- writable: true,
- });
- panelIsCollapsed = true;
- deliverDocPanelResizeAfterLayout = true;
- closeActivityPanelCalls = 0;
- });
-
- test('a doc-scoped problems request opens the Problems tab and expands the collapsed rail', async () => {
- const { resizeObserver } = mountTabHost('timeline');
- try {
- expect(infoWidthPx()).toBe(0);
- expect(docPanelToggle().getAttribute('aria-expanded')).toBe('false');
-
- const storedPins = localStorage.getItem('ok-sidebar-pins-v2');
- act(() => requestDocPanelTab('problems', { scope: 'doc' }));
- await act(async () => {});
-
- expect(localStorage.getItem('ok-sidebar-pins-v2')).toBe(storedPins);
-
- expect(screen.getByRole('tabpanel').getAttribute('id')).toBe('panel-problems');
- expect(screen.getByTestId('panel-scope-doc').getAttribute('data-state')).toBe('on');
- expect(docPanelToggle().getAttribute('aria-expanded')).toBe('true');
- expect(infoWidthPx()).toBeCloseTo(320, 0);
- expect(innerResidualWidthPx()).toBeGreaterThanOrEqual(300);
- } finally {
- resizeObserver.restore();
- }
- });
-
- test('a panel already parked on Problems in project scope comes back in doc scope', async () => {
- const { resizeObserver } = mountTabHost('problems');
- try {
- act(() => requestDocPanelTab('problems', { scope: 'doc' }));
- await act(async () => {});
- fireEvent.click(screen.getByTestId('panel-scope-project'));
- expect(screen.getByTestId('problems-project-scope')).toBeTruthy();
- fireEvent.click(docPanelToggle());
- await act(async () => {});
- expect(infoWidthPx()).toBe(0);
- expect(docPanelToggle().getAttribute('aria-expanded')).toBe('false');
-
- act(() => requestDocPanelTab('problems', { scope: 'doc' }));
- await act(async () => {});
-
- expect(screen.getByRole('tabpanel').getAttribute('id')).toBe('panel-problems');
- expect(screen.getByTestId('panel-scope-doc').getAttribute('data-state')).toBe('on');
- expect(screen.queryByTestId('problems-project-scope')).toBeNull();
- expect(infoWidthPx()).toBeCloseTo(320, 0);
- expect(innerResidualWidthPx()).toBeGreaterThanOrEqual(300);
- } finally {
- resizeObserver.restore();
- }
- });
-
- test('a tab request takes the rail back from the agent drill-in', () => {
- docCtx = { ...DOC_LIVE_CTX, docPanelMode: 'agent', docPanelAgentId: 'agent-1' };
- const { resizeObserver } = mountTabHost('timeline');
- expect(screen.queryByRole('tabpanel')).toBeNull();
-
- act(() => requestDocPanelTab('problems', { scope: 'doc' }));
-
- expect(closeActivityPanelCalls).toBe(1);
- resizeObserver.restore();
- });
-
- test('re-rendering does not stack the subscription, and unmounting drops it', () => {
- const onActiveTabChange = vi.fn();
- const { view, resizeObserver } = mountTabHost('timeline', onActiveTabChange);
- try {
- for (let i = 0; i < 3; i += 1) {
- view.rerender(<TabHost initialTab="timeline" onActiveTabChange={onActiveTabChange} />);
- }
-
- act(() => requestDocPanelTab('problems', { scope: 'doc' }));
- expect(onActiveTabChange).toHaveBeenCalledTimes(1);
- expect(onActiveTabChange).toHaveBeenCalledWith('problems');
- expect(infoWidthPx()).toBeCloseTo(320, 0);
-
- view.unmount();
- act(() => requestDocPanelTab('problems', { scope: 'doc' }));
- expect(onActiveTabChange).toHaveBeenCalledTimes(1);
- } finally {
- resizeObserver.restore();
- }
- });
-});
-
-describe('EditorArea rail mount inert', () => {
- const railProps = {
- editorMode: 'wysiwyg',
- onModeChange: () => {},
- activeTab: 'timeline',
- onActiveTabChange: () => {},
- onAgentsVisibleChange: () => {},
- } as const;
-
- beforeEach(() => {
- cleanup();
- panelIsCollapsed = false;
- mockPanelPercentage = null;
- mockPanelPx = null;
- railPanelOnResizeById.clear();
- });
-
- const renderArea = (props: Record<string, unknown>) =>
- render(
- <TooltipProvider>
- <EditorArea {...railProps} {...props} />
- </TooltipProvider>,
- );
-
- test('both rail mounts are inert while their columns are absent', () => {
- const { container } = renderArea({});
-
- expect(
- container.querySelector('[data-agents-panel-mount]')?.getAttribute('inert'),
- ).not.toBeNull();
- expect(
- container.querySelector('[data-terminal-panel-mount]')?.getAttribute('inert'),
- ).not.toBeNull();
- });
-
- test('both rail mounts stay focusable while their columns are open', () => {
- const { container } = renderArea({
- agentsVisible: true,
- terminalBridge: { terminal: {} } as never,
- terminalVisible: true,
- terminalPlacement: 'right',
- });
-
- expect(container.querySelector('[data-agents-panel-mount]')?.getAttribute('inert')).toBeNull();
- expect(
- container.querySelector('[data-terminal-panel-mount]')?.getAttribute('inert'),
- ).toBeNull();
- });
-
- test('a drag-collapsed rail column stays focusable while the hold bridges the drag and goes inert once pointerup clears its presence', () => {
- const RailVisibilityHost = () => {
- const [agentsVisible, setAgentsVisible] = useState(true);
- const [terminalVisible, setTerminalVisible] = useState(true);
- return (
- <TooltipProvider>
- <EditorArea
- {...railProps}
- agentsVisible={agentsVisible}
- onAgentsVisibleChange={setAgentsVisible}
- terminalBridge={{ terminal: {} } as never}
- terminalVisible={terminalVisible}
- terminalPlacement="right"
- onTerminalVisibleChange={setTerminalVisible}
- />
- </TooltipProvider>
- );
- };
- const { container } = render(<RailVisibilityHost />);
- const agentsMount = () => container.querySelector('[data-agents-panel-mount]');
- const terminalMount = () => container.querySelector('[data-terminal-panel-mount]');
- const railHandle = (position: -1 | -2) => {
- const handle = screen.getAllByTestId('resizable-handle').at(position);
- if (handle == null) throw new Error('rail resize handle not found');
- return handle;
- };
- expect(agentsMount()?.getAttribute('inert')).toBeNull();
- expect(terminalMount()?.getAttribute('inert')).toBeNull();
-
- act(() => {
- fireEvent.pointerDown(railHandle(-1), { pointerId: 1 });
- });
- act(() => {
- railPanelOnResizeById.get(AGENTS_COLUMN_ID)?.({ asPercentage: 0, inPixels: 0 });
- });
- expect(agentsMount()?.getAttribute('inert')).toBeNull();
-
- panelIsCollapsed = true;
- mockPanelPercentage = 0;
- mockPanelPx = 0;
- act(() => {
- fireEvent.pointerUp(window, { pointerId: 1 });
- });
- expect(agentsMount()?.getAttribute('inert')).not.toBeNull();
-
- act(() => {
- fireEvent.pointerDown(railHandle(-2), { pointerId: 2 });
- });
- act(() => {
- railPanelOnResizeById.get(TERMINAL_COLUMN_ID)?.({ asPercentage: 0, inPixels: 0 });
- });
- expect(terminalMount()?.getAttribute('inert')).toBeNull();
-
- act(() => {
- fireEvent.pointerUp(window, { pointerId: 2 });
- });
- expect(terminalMount()?.getAttribute('inert')).not.toBeNull();
- expect(agentsMount()?.getAttribute('inert')).not.toBeNull();
- });
-
- test('a present-but-measured-collapsed rail reports isShowing false so reveal focus waits for expansion', () => {
- const placements: Array<{
- agents?: { isShowing?: boolean };
- terminal?: { isShowing?: boolean };
- }> = [];
- const { container } = renderArea({
- agentsVisible: true,
- terminalBridge: { terminal: {} } as never,
- terminalVisible: true,
- terminalPlacement: 'right',
- onSessionPlacements: (placement: unknown) =>
- placements.push(
- placement as {
- agents?: { isShowing?: boolean };
- terminal?: { isShowing?: boolean };
- },
- ),
- });
- expect(placements.at(-1)?.agents?.isShowing).toBe(true);
- expect(placements.at(-1)?.terminal?.isShowing).toBe(true);
-
- act(() => {
- railPanelOnResizeById.get(AGENTS_COLUMN_ID)?.({ asPercentage: 0, inPixels: 0 });
- });
- expect(
- container.querySelector('[data-agents-panel-mount]')?.getAttribute('inert'),
- ).not.toBeNull();
- expect(placements.at(-1)?.agents?.isShowing).toBe(false);
-
- act(() => {
- railPanelOnResizeById.get(TERMINAL_COLUMN_ID)?.({ asPercentage: 0, inPixels: 0 });
- });
- expect(
- container.querySelector('[data-terminal-panel-mount]')?.getAttribute('inert'),
- ).not.toBeNull();
- expect(placements.at(-1)?.terminal?.isShowing).toBe(false);
-
- act(() => {
- railPanelOnResizeById.get(AGENTS_COLUMN_ID)?.({ asPercentage: 25, inPixels: 300 });
- });
- expect(container.querySelector('[data-agents-panel-mount]')?.getAttribute('inert')).toBeNull();
- expect(placements.at(-1)?.agents?.isShowing).toBe(true);
-
- act(() => {
- railPanelOnResizeById.get(TERMINAL_COLUMN_ID)?.({ asPercentage: 25, inPixels: 300 });
- });
- expect(
- container.querySelector('[data-terminal-panel-mount]')?.getAttribute('inert'),
- ).toBeNull();
- expect(placements.at(-1)?.terminal?.isShowing).toBe(true);
- });
-
- test('a drag that dips a rail to zero and back — repeatedly — never flips its showing signal', () => {
- const placements: Array<{
- agents?: { isShowing?: boolean };
- terminal?: { isShowing?: boolean };
- }> = [];
- const { container } = renderArea({
- agentsVisible: true,
- terminalBridge: { terminal: {} } as never,
- terminalVisible: true,
- terminalPlacement: 'right',
- onSessionPlacements: (placement: unknown) =>
- placements.push(
- placement as {
- agents?: { isShowing?: boolean };
- terminal?: { isShowing?: boolean };
- },
- ),
- });
- expect(placements.at(-1)?.agents?.isShowing).toBe(true);
- expect(placements.at(-1)?.terminal?.isShowing).toBe(true);
-
- const railHandle = (position: -1 | -2) => {
- const handle = screen.getAllByTestId('resizable-handle').at(position);
- if (handle == null) throw new Error('rail resize handle not found');
- return handle;
- };
- const dip = (columnId: string) => {
- act(() => {
- railPanelOnResizeById.get(columnId)?.({ asPercentage: 0, inPixels: 0 });
- });
- };
- const recover = (columnId: string) => {
- act(() => {
- railPanelOnResizeById.get(columnId)?.({ asPercentage: 25, inPixels: 300 });
- });
- };
-
- const agentsDragStart = placements.length;
- act(() => {
- fireEvent.pointerDown(railHandle(-1), { pointerId: 1 });
- });
- for (let i = 0; i < 2; i += 1) {
- dip(AGENTS_COLUMN_ID);
- expect(
- container.querySelector('[data-agents-panel-mount]')?.getAttribute('inert'),
- ).toBeNull();
- expect(placements.at(-1)?.agents?.isShowing).toBe(true);
- recover(AGENTS_COLUMN_ID);
- expect(
- container.querySelector('[data-agents-panel-mount]')?.getAttribute('inert'),
- ).toBeNull();
- expect(placements.at(-1)?.agents?.isShowing).toBe(true);
- }
- act(() => {
- fireEvent.pointerUp(window, { pointerId: 1 });
- });
- expect(placements.at(-1)?.agents?.isShowing).toBe(true);
- expect(
- placements.slice(agentsDragStart).some((placement) => placement.agents?.isShowing === false),
- ).toBe(false);
-
- const terminalDragStart = placements.length;
- act(() => {
- fireEvent.pointerDown(railHandle(-2), { pointerId: 2 });
- });
- for (let i = 0; i < 2; i += 1) {
- dip(TERMINAL_COLUMN_ID);
- expect(
- container.querySelector('[data-terminal-panel-mount]')?.getAttribute('inert'),
- ).toBeNull();
- expect(placements.at(-1)?.terminal?.isShowing).toBe(true);
- recover(TERMINAL_COLUMN_ID);
- expect(
- container.querySelector('[data-terminal-panel-mount]')?.getAttribute('inert'),
- ).toBeNull();
- expect(placements.at(-1)?.terminal?.isShowing).toBe(true);
- }
- act(() => {
- fireEvent.pointerUp(window, { pointerId: 2 });
- });
- expect(placements.at(-1)?.terminal?.isShowing).toBe(true);
- expect(
- placements
- .slice(terminalDragStart)
- .some((placement) => placement.terminal?.isShowing === false),
- ).toBe(false);
-
- act(() => {
- railPanelOnResizeById.get(AGENTS_COLUMN_ID)?.({ asPercentage: 0, inPixels: 0 });
- });
- expect(placements.at(-1)?.agents?.isShowing).toBe(false);
- act(() => {
- railPanelOnResizeById.get(TERMINAL_COLUMN_ID)?.({ asPercentage: 0, inPixels: 0 });
- });
- expect(placements.at(-1)?.terminal?.isShowing).toBe(false);
- });
-
- test('a pointercancel at measured collapse holds the showing signal until the drag-free expansion lands', () => {
- const placements: Array<{
- agents?: { isShowing?: boolean };
- terminal?: { isShowing?: boolean };
- }> = [];
- const { container } = renderArea({
- agentsVisible: true,
- terminalBridge: { terminal: {} } as never,
- terminalVisible: true,
- terminalPlacement: 'right',
- onSessionPlacements: (placement: unknown) =>
- placements.push(
- placement as {
- agents?: { isShowing?: boolean };
- terminal?: { isShowing?: boolean };
- },
- ),
- });
-
- const railHandle = (position: -1 | -2) => {
- const handle = screen.getAllByTestId('resizable-handle').at(position);
- if (handle == null) throw new Error('rail resize handle not found');
- return handle;
- };
-
- const agentsDragStart = placements.length;
- act(() => {
- fireEvent.pointerDown(railHandle(-1), { pointerId: 1 });
- });
- act(() => {
- railPanelOnResizeById.get(AGENTS_COLUMN_ID)?.({ asPercentage: 0, inPixels: 0 });
- });
- panelIsCollapsed = true;
- act(() => {
- fireEvent.pointerCancel(window, { pointerId: 1 });
- });
- expect(container.querySelector('[data-agents-panel-mount]')?.getAttribute('inert')).toBeNull();
- expect(placements.at(-1)?.agents?.isShowing).toBe(true);
- expect(
- placements.slice(agentsDragStart).some((placement) => placement.agents?.isShowing === false),
- ).toBe(false);
-
- panelIsCollapsed = false;
- act(() => {
- railPanelOnResizeById.get(AGENTS_COLUMN_ID)?.({ asPercentage: 25, inPixels: 300 });
- });
- expect(container.querySelector('[data-agents-panel-mount]')?.getAttribute('inert')).toBeNull();
- expect(placements.at(-1)?.agents?.isShowing).toBe(true);
- act(() => {
- railPanelOnResizeById.get(AGENTS_COLUMN_ID)?.({ asPercentage: 0, inPixels: 0 });
- });
- expect(placements.at(-1)?.agents?.isShowing).toBe(false);
-
- const terminalDragStart = placements.length;
- act(() => {
- fireEvent.pointerDown(railHandle(-2), { pointerId: 2 });
- });
- act(() => {
- railPanelOnResizeById.get(TERMINAL_COLUMN_ID)?.({ asPercentage: 0, inPixels: 0 });
- });
- panelIsCollapsed = true;
- act(() => {
- fireEvent.pointerCancel(window, { pointerId: 2 });
- });
- expect(
- container.querySelector('[data-terminal-panel-mount]')?.getAttribute('inert'),
- ).toBeNull();
- expect(placements.at(-1)?.terminal?.isShowing).toBe(true);
- expect(
- placements
- .slice(terminalDragStart)
- .some((placement) => placement.terminal?.isShowing === false),
- ).toBe(false);
-
- panelIsCollapsed = false;
- act(() => {
- railPanelOnResizeById.get(TERMINAL_COLUMN_ID)?.({ asPercentage: 25, inPixels: 300 });
- });
- expect(
- container.querySelector('[data-terminal-panel-mount]')?.getAttribute('inert'),
- ).toBeNull();
- expect(placements.at(-1)?.terminal?.isShowing).toBe(true);
- act(() => {
- railPanelOnResizeById.get(TERMINAL_COLUMN_ID)?.({ asPercentage: 0, inPixels: 0 });
- });
- expect(placements.at(-1)?.terminal?.isShowing).toBe(false);
- });
-});
-
-type Observation = {
- callback: ResizeObserverCallback;
- observer: ResizeObserver;
- target: Element;
-};
-const installResizeObserver = () => {
- const original = globalThis.ResizeObserver;
- const observations = new Set<Observation>();
- class TestResizeObserver implements ResizeObserver {
- readonly callback: ResizeObserverCallback;
- constructor(callback: ResizeObserverCallback) {
- this.callback = callback;
- }
- observe(target: Element) {
- observations.add({ callback: this.callback, observer: this, target });
- }
- unobserve(target: Element) {
- for (const observation of observations) {
- if (observation.observer === this && observation.target === target) {
- observations.delete(observation);
- }
- }
- }
- disconnect() {
- for (const observation of observations) {
- if (observation.observer === this) observations.delete(observation);
- }
- }
- }
- Object.defineProperty(globalThis, 'ResizeObserver', {
- value: TestResizeObserver,
- configurable: true,
- writable: true,
- });
- return {
- fire: (selector: string) => {
- const target = document.querySelector(selector);
- const matching = [...observations].filter((entry) => entry.target === target);
- if (matching.length === 0) throw new Error(`${selector} is not observed`);
- act(() => {
- for (const observation of matching) observation.callback([], observation.observer);
- });
- },
- restore: () => {
- Object.defineProperty(globalThis, 'ResizeObserver', {
- value: original,
- configurable: true,
- writable: true,
- });
- },
- };
-};
-
-describe('EditorArea editor card rows', () => {
- const rowProps = {
- editorMode: 'wysiwyg',
- onModeChange: () => {},
- activeTab: 'timeline',
- onActiveTabChange: () => {},
- terminalBridge: {} as never,
- onAgentsVisibleChange: () => {},
- onTerminalVisibleChange: () => {},
- } as const;
- const FILE_LIST_PX = 288;
- const SHELL_CHROME_PX = 8;
- const setViewportWidth = (px: number) => {
- Object.defineProperty(window, 'innerWidth', { value: px, configurable: true, writable: true });
- };
- const pctOfRow = (px: number, rowPx: number) => (px / rowPx) * 100;
- const docHandle = () => {
- const handle = document.getElementById('doc-panel')?.previousElementSibling;
- if (!(handle instanceof HTMLElement)) throw new Error('doc-panel resize handle not found');
- return handle;
- };
- const agentsHandle = () => {
- const handle = screen.getAllByTestId('resizable-handle').at(-1);
- if (handle == null) throw new Error('agents resize handle not found');
- return handle;
- };
- const terminalHandle = () => {
- const handle = document.querySelector<HTMLElement>('[data-terminal-panel-handle]');
- if (handle == null) throw new Error('terminal resize handle not found');
- return handle;
- };
- const flushFrame = () => act(async () => {});
- const measureEditorCardForRow = (resizeObserver: ReturnType<typeof installResizeObserver>) => {
- const card = document.querySelector<HTMLElement>('[data-slot="pane-card"][data-pane="editor"]');
- if (card == null) throw new Error('the editor card is absent');
- Object.defineProperty(card, 'getBoundingClientRect', {
- configurable: true,
- value: () => ({ width: rowPx('inner'), height: 0, top: 0, left: 0 }),
- });
- resizeObserver.fire('[data-slot="pane-card"][data-pane="editor"]');
- };
-
- beforeEach(() => {
- cleanup();
- localStorage.clear();
- docCtx = EMPTY_DOC_CTX;
- groupLayout = {};
- groupSetLayoutCalls = [];
- rejectNextGroupLayoutWrite = false;
- rejectGroupLayoutWrites = false;
- panelIsCollapsed = false;
- mockGroupPx = 1360;
- mockPanelPercentage = null;
- mockPanelPx = null;
- toastInfoMessages = [];
- });
-
- test('a project window puts the tab row, the workspace and the side panel inside one editor card row', () => {
- setViewportWidth(1400);
- docCtx = DOC_LIVE_CTX;
- render(<EditorArea {...rowProps} agentsVisible terminalVisible terminalPlacement="right" />);
-
- const card = document.querySelector('[data-slot="pane-card"][data-pane="editor"]');
- const outer = screen.getByTestId('resizable-group');
- const inner = screen.getByTestId('resizable-group-inner');
- const header = document.querySelector('[data-editor-area-header]');
- const column = document.querySelector('[data-editor-workspace-column]');
- const docPanel = document.getElementById('doc-panel');
- const terminalPanel = document.getElementById('terminal-column');
- const agentsPanel = document.getElementById('agents-column');
- if (card == null || header == null || column == null || docPanel == null) {
- throw new Error('editor card structure is incomplete');
- }
-
- expect(card.getAttribute('data-variant')).toBe('card');
- expect(card.closest('[data-panel]')).toBe(outer.firstElementChild);
- expect(outer.querySelector(':scope > [data-slot="pane-card"]')).toBeNull();
- expect(card.contains(inner)).toBe(true);
- expect(inner.contains(docPanel)).toBe(true);
- expect(inner.contains(column)).toBe(true);
- expect(column.firstElementChild).toBe(header);
- expect(header.contains(screen.getByTestId('workspace-tabs'))).toBe(true);
- expect(docPanel.contains(header)).toBe(false);
- expect(card.contains(terminalPanel)).toBe(false);
- expect(card.contains(agentsPanel)).toBe(false);
- expect(
- docPanel.compareDocumentPosition(terminalPanel as Node) & Node.DOCUMENT_POSITION_FOLLOWING,
- ).toBeTruthy();
- expect(document.querySelector('[data-editor-inner-panels]')?.firstElementChild).toBe(inner);
- });
-
- test('a note window keeps the tab row target above the row and renders the flat card', () => {
- Object.defineProperty(window, 'okDesktop', {
- configurable: true,
- value: {
- config: { mode: 'note' },
- editor: { notifyViewMenuStateChanged: () => {} },
- },
- });
- try {
- render(<EditorArea {...rowProps} />);
- const panels = document.querySelector('[data-editor-area-panels]');
- const header = document.querySelector('[data-editor-area-header]');
- const card = document.querySelector('[data-slot="pane-card"][data-pane="editor"]');
- expect(header?.nextElementSibling).toBe(panels);
- expect(panels?.contains(header)).toBe(false);
- expect(card?.getAttribute('data-variant')).toBe('flat');
- expect(screen.getByTestId('resizable-group-inner').contains(card)).toBe(false);
- expect(card?.contains(screen.getByTestId('resizable-group-inner'))).toBe(true);
- } finally {
- Reflect.deleteProperty(window, 'okDesktop');
- }
- });
-
- test('a single-file window renders the normal editor card', () => {
- Object.defineProperty(window, 'okDesktop', {
- configurable: true,
- value: {
- config: { singleFile: true },
- editor: { notifyViewMenuStateChanged: () => {} },
- },
- });
- try {
- render(
- <SingleFileModeProvider>
- <EditorArea {...rowProps} />
- </SingleFileModeProvider>,
- );
- const card = document.querySelector('[data-slot="pane-card"][data-pane="editor"]');
- expect(card?.getAttribute('data-variant')).toBe('card');
- } finally {
- Reflect.deleteProperty(window, 'okDesktop');
- }
- });
-
- test('while the chat divider is dragged the inner row follows the outer move in the same write and keeps the side panel width', async () => {
- setViewportWidth(1400);
- docCtx = DOC_LIVE_CTX;
- groupLayout = {
- 'editor-main': 100 - pctOfRow(480, 1360),
- 'agents-column': pctOfRow(480, 1360),
- };
- innerLayout = innerRowWithDoc(320, 1360 - 480);
- render(<EditorArea {...rowProps} agentsVisible />);
- await act(async () => {});
- groupSetLayoutCalls = [];
- innerSetLayoutCalls = [];
-
- act(() => {
- fireEvent.pointerDown(agentsHandle(), { pointerId: 1 });
- agentsHandle().setAttribute('data-separator', 'active');
- });
- groupLayout = {
- 'editor-main': 100 - pctOfRow(600, 1360),
- 'agents-column': pctOfRow(600, 1360),
- };
- act(() => {
- groupOnLayoutChange?.(groupLayout);
- });
-
- expect(groupSetLayoutCalls).toHaveLength(0);
- expect(lastInnerWritePx('doc-panel')).toBeCloseTo(320, 3);
- expect(document.getElementById('doc-panel')?.getBoundingClientRect().width).toBeCloseTo(320, 3);
- expect(innerResidualWidthPx()).toBeCloseTo(1360 - 600 - 320, 3);
-
- act(() => {
- groupOnLayoutChanged?.(groupLayout, { isUserInteraction: true });
- fireEvent.pointerUp(window, { pointerId: 1 });
- });
- expect(document.getElementById('doc-panel')?.getBoundingClientRect().width).toBeCloseTo(320, 3);
- });
-
- test('a collapsed side panel stays collapsed while the outer row is dragged', async () => {
- setViewportWidth(1024);
- docCtx = DOC_LIVE_CTX;
- groupLayout = {
- 'editor-main': 100 - pctOfRow(480, 1360),
- 'agents-column': pctOfRow(480, 1360),
- };
- render(<EditorArea {...rowProps} agentsVisible />);
- await act(async () => {});
- innerSetLayoutCalls = [];
-
- act(() => {
- fireEvent.pointerDown(agentsHandle(), { pointerId: 1 });
- agentsHandle().setAttribute('data-separator', 'active');
- });
- groupLayout = {
- 'editor-main': 100 - pctOfRow(600, 1360),
- 'agents-column': pctOfRow(600, 1360),
- };
- act(() => {
- groupOnLayoutChange?.(groupLayout);
- });
- act(() => {
- groupOnLayoutChanged?.(groupLayout, { isUserInteraction: true });
- fireEvent.pointerUp(window, { pointerId: 1 });
- });
-
- for (const write of innerSetLayoutCalls) expect(write['doc-panel']).toBe(0);
- expect(document.getElementById('doc-panel')?.getBoundingClientRect().width).toBe(0);
- });
-
- test('each row marks only its own drag', () => {
- setViewportWidth(1400);
- docCtx = DOC_LIVE_CTX;
- render(<EditorArea {...rowProps} agentsVisible />);
- const outer = screen.getByTestId('resizable-group');
- const inner = screen.getByTestId('resizable-group-inner');
-
- act(() => {
- fireEvent.pointerDown(docHandle(), { pointerId: 1 });
- });
- expect(inner.getAttribute('data-dragging')).toBe('true');
- expect(outer.hasAttribute('data-dragging')).toBe(false);
- act(() => {
- fireEvent.pointerUp(window, { pointerId: 1 });
- });
- expect(inner.hasAttribute('data-dragging')).toBe(false);
-
- act(() => {
- fireEvent.pointerDown(agentsHandle(), { pointerId: 2 });
- });
- expect(outer.getAttribute('data-dragging')).toBe('true');
- expect(inner.hasAttribute('data-dragging')).toBe(false);
- act(() => {
- fireEvent.pointerUp(window, { pointerId: 2 });
- });
- expect(outer.hasAttribute('data-dragging')).toBe(false);
- });
-
- test('at a 1400px window with the file list open every column drops to its floor and the document keeps 159px', async () => {
- const rowPx = 1400 - FILE_LIST_PX - SHELL_CHROME_PX;
- setViewportWidth(1400);
- mockGroupPx = rowPx;
- docCtx = DOC_LIVE_CTX;
- const view = render(
- <EditorArea
- {...rowProps}
- agentsVisible={false}
- terminalVisible={false}
- terminalPlacement="right"
- />,
- );
- groupLayout = { 'editor-main': 40, 'terminal-column': 40, 'agents-column': 20 };
- innerLayout = { 'workspace-main': 50, 'doc-panel': 50 };
- groupSetLayoutCalls = [];
- innerSetLayoutCalls = [];
-
- view.rerender(
- <EditorArea {...rowProps} agentsVisible terminalVisible terminalPlacement="right" />,
- );
- await act(async () => {});
-
- const outer = groupSetLayoutCalls.at(-1);
- expect(outer).toBeDefined();
- expect(((outer?.['terminal-column'] ?? 0) / 100) * rowPx).toBeCloseTo(
- RIGHT_TERMINAL_PANEL_MIN_WIDTH_PX,
- 3,
- );
- expect(((outer?.['agents-column'] ?? 0) / 100) * rowPx).toBeCloseTo(MIN_AGENTS_PANEL_WIDTH, 3);
- expect(lastInnerWritePx('doc-panel')).toBeCloseTo(300, 3);
- const innerWrite = innerSetLayoutCalls.at(-1);
- const innerWritePx = innerSetLayoutPx.at(-1) ?? 0;
- expect(innerWritePx - ((innerWrite?.['doc-panel'] ?? 0) / 100) * innerWritePx).toBeCloseTo(
- rowPx - RIGHT_TERMINAL_PANEL_MIN_WIDTH_PX - MIN_AGENTS_PANEL_WIDTH - 300,
- 3,
- );
- expect(innerWritePx - ((innerWrite?.['doc-panel'] ?? 0) / 100) * innerWritePx).toBeCloseTo(
- 159,
- 3,
- );
- });
-
- test('at a 1300px window with a document open, chat and the right terminal cannot both stay', async () => {
- const rowPx = 1300 - FILE_LIST_PX - SHELL_CHROME_PX;
- setViewportWidth(1300);
- mockGroupPx = rowPx;
- mockPanelPx = 320;
- mockPanelPercentage = pctOfRow(320, rowPx);
- docCtx = DOC_LIVE_CTX;
- const terminalChanges: boolean[] = [];
- const view = render(
- <EditorArea
- {...rowProps}
- agentsVisible={false}
- terminalVisible
- terminalPlacement="right"
- onTerminalVisibleChange={(visible: boolean) => {
- terminalChanges.push(visible);
- }}
- />,
- );
- groupLayout = {
- 'editor-main': 100 - pctOfRow(740, rowPx),
- 'terminal-column': pctOfRow(740, rowPx),
- 'agents-column': 0,
- };
- innerLayout = innerRowWithDoc(320, rowPx - 740);
-
- view.rerender(
- <EditorArea
- {...rowProps}
- agentsVisible
- terminalVisible
- terminalPlacement="right"
- onTerminalVisibleChange={(visible: boolean) => {
- terminalChanges.push(visible);
- }}
- />,
- );
- await act(async () => {});
-
- expect(terminalChanges).toEqual([false]);
- expect(toastInfoMessages).toEqual(['Terminal closed to make room for the agent panel.']);
- });
-
- function FileListShell({ children }: { children: ReactNode }) {
- return (
- <FileListHostProvider enabled fileList={<nav data-testid="card-file-list" />}>
- {children}
- </FileListHostProvider>
- );
- }
- const measureFileListSlot = () => {
- const slot = document.querySelector<HTMLElement>('[data-editor-file-list-slot]');
- if (slot == null) throw new Error('the editor card has no file list slot');
- Object.defineProperty(slot, 'getBoundingClientRect', {
- configurable: true,
- value: () => ({
- width: mockFileListPx,
- height: 0,
- top: 0,
- left: 0,
- right: mockFileListPx,
- bottom: 0,
- x: 0,
- y: 0,
- }),
- });
- return slot;
- };
-
- test('draws the file list in the editor card slot, ahead of the content column', () => {
- docCtx = DOC_LIVE_CTX;
- render(
- <FileListShell>
- <EditorArea {...rowProps} agentsVisible={false} terminalVisible={false} />
- </FileListShell>,
- );
-
- const card = document.querySelector('[data-slot="pane-card"][data-pane="editor"]');
- const slot = measureFileListSlot();
- const content = card?.querySelector('[data-slot="sidebar-inset"]');
- expect(slot.parentElement).toBe(card);
- expect(slot.contains(screen.getByTestId('card-file-list'))).toBe(true);
- expect(content?.parentElement).toBe(card);
- expect(
- slot.compareDocumentPosition(content as Element) & Node.DOCUMENT_POSITION_FOLLOWING,
- ).toBeTruthy();
- expect(content?.contains(screen.getByTestId('resizable-group-inner'))).toBe(true);
- });
-
- test('with the file list inside the card, a 1400px window still floors every column and leaves the document 159px', async () => {
- const outerPx = 1400 - SHELL_CHROME_PX;
- const rowPx = outerPx - FILE_LIST_PX;
- setViewportWidth(1400);
- mockGroupPx = outerPx;
- mockFileListPx = FILE_LIST_PX;
- docCtx = DOC_LIVE_CTX;
- const view = render(
- <FileListShell>
- <EditorArea
- {...rowProps}
- agentsVisible={false}
- terminalVisible={false}
- terminalPlacement="right"
- />
- </FileListShell>,
- );
- measureFileListSlot();
- groupLayout = { 'editor-main': 40, 'terminal-column': 40, 'agents-column': 20 };
- innerLayout = { 'workspace-main': 50, 'doc-panel': 50 };
- groupSetLayoutCalls = [];
- innerSetLayoutCalls = [];
-
- view.rerender(
- <FileListShell>
- <EditorArea {...rowProps} agentsVisible terminalVisible terminalPlacement="right" />
- </FileListShell>,
- );
- await act(async () => {});
- await act(
- () =>
- new Promise<void>((resolve) =>
- requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
- ),
- );
-
- const outer = groupSetLayoutCalls.at(-1);
- expect(outer).toBeDefined();
- expect(((outer?.['terminal-column'] ?? 0) / 100) * outerPx).toBeCloseTo(
- RIGHT_TERMINAL_PANEL_MIN_WIDTH_PX,
- 3,
- );
- expect(((outer?.['agents-column'] ?? 0) / 100) * outerPx).toBeCloseTo(
- MIN_AGENTS_PANEL_WIDTH,
- 3,
- );
- expect(lastInnerWritePx('doc-panel')).toBeCloseTo(300, 3);
- const innerWrite = innerSetLayoutCalls.at(-1);
- const innerWritePx = innerSetLayoutPx.at(-1) ?? 0;
- expect(innerWritePx - ((innerWrite?.['doc-panel'] ?? 0) / 100) * innerWritePx).toBeCloseTo(
- rowPx - RIGHT_TERMINAL_PANEL_MIN_WIDTH_PX - MIN_AGENTS_PANEL_WIDTH - 300,
- 3,
- );
- expect(innerWritePx - ((innerWrite?.['doc-panel'] ?? 0) / 100) * innerWritePx).toBeCloseTo(
- 159,
- 3,
- );
- });
-
- test('with the file list inside the card, a 1300px window still closes the right terminal for chat', async () => {
- const outerPx = 1300 - SHELL_CHROME_PX;
- const rowPx = outerPx - FILE_LIST_PX;
- setViewportWidth(1300);
- mockGroupPx = outerPx;
- mockFileListPx = FILE_LIST_PX;
- mockPanelPx = 320;
- mockPanelPercentage = pctOfRow(320, rowPx);
- docCtx = DOC_LIVE_CTX;
- const terminalChanges: boolean[] = [];
- const renderRow = (agentsVisible: boolean) => (
- <FileListShell>
- <EditorArea
- {...rowProps}
- agentsVisible={agentsVisible}
- terminalVisible
- terminalPlacement="right"
- onTerminalVisibleChange={(visible: boolean) => {
- terminalChanges.push(visible);
- }}
- />
- </FileListShell>
- );
- const view = render(renderRow(false));
- measureFileListSlot();
- groupLayout = {
- 'editor-main': 100 - pctOfRow(740, outerPx),
- 'terminal-column': pctOfRow(740, outerPx),
- 'agents-column': 0,
- };
- innerLayout = innerRowWithDoc(320, rowPx - 740);
-
- view.rerender(renderRow(true));
- await act(async () => {});
-
- expect(terminalChanges).toEqual([false]);
- expect(toastInfoMessages).toEqual(['Terminal closed to make room for the agent panel.']);
- });
-
- test('a terminal close decided while Files is still collapsing applies once the file list has no width', async () => {
- const resizeObserver = installResizeObserver();
- try {
- const outerPx = 900 - SHELL_CHROME_PX;
- setViewportWidth(900);
- mockGroupPx = outerPx;
- mockFileListPx = FILE_LIST_PX;
- docCtx = DOC_LIVE_CTX;
- const terminalChanges: boolean[] = [];
- const renderRow = (agentsVisible: boolean) => (
- <FileListShell>
- <EditorArea
- {...rowProps}
- agentsVisible={agentsVisible}
- terminalVisible
- terminalPlacement="right"
- onTerminalVisibleChange={(visible: boolean) => {
- terminalChanges.push(visible);
- }}
- />
- </FileListShell>
- );
- const view = render(renderRow(false));
- measureFileListSlot();
- groupLayout = {
- 'editor-main': 100 - pctOfRow(740, outerPx),
- 'terminal-column': pctOfRow(740, outerPx),
- 'agents-column': 0,
- };
-
- view.rerender(renderRow(true));
- await act(async () => {});
- expect(document.querySelector('[data-editor-file-list-slot]')).not.toBeNull();
- expect(toastInfoMessages).toEqual([]);
-
- mockFileListPx = 0;
- resizeObserver.fire('[data-editor-file-list-slot]');
-
- expect(terminalChanges).toEqual([false]);
- expect(toastInfoMessages).toEqual(['Terminal closed to make room for the agent panel.']);
- } finally {
- resizeObserver.restore();
- }
- });
-
- test('a transient over-wide side panel reading while chat opens does not close the right terminal at 1900px', async () => {
- const outerPx = 1900 - SHELL_CHROME_PX;
- const rowPx = outerPx - FILE_LIST_PX;
- setViewportWidth(1900);
- mockGroupPx = outerPx;
- mockFileListPx = FILE_LIST_PX;
- mockPanelPx = 1122;
- mockPanelPercentage = pctOfRow(1122, rowPx);
- docCtx = DOC_LIVE_CTX;
- const terminalChanges: boolean[] = [];
- const renderRow = (agentsVisible: boolean) => (
- <FileListShell>
- <EditorArea
- {...rowProps}
- agentsVisible={agentsVisible}
- terminalVisible
- terminalPlacement="right"
- onTerminalVisibleChange={(visible: boolean) => {
- terminalChanges.push(visible);
- }}
- />
- </FileListShell>
- );
- const view = render(renderRow(false));
- measureFileListSlot();
- groupLayout = {
- 'editor-main': 100 - pctOfRow(740, outerPx),
- 'terminal-column': pctOfRow(740, outerPx),
- 'agents-column': 0,
- };
- innerLayout = innerRowWithDoc(320, rowPx - 740);
+ value: () => ({ width: innerRowPx(), height: 0, top: 0, left: 0 }),
+ });
+ }
+ resizeObserver.fire('[data-slot="pane-card"][data-pane="editor"]');
+ resizeObserver.fire('[data-editor-inner-panels]');
+ return { view, resizeObserver };
+ }
- view.rerender(renderRow(true));
- await act(async () => {});
+ const infoWidthPx = () => document.getElementById('doc-panel')?.getBoundingClientRect().width;
+ const docPanelToggle = () => {
+ const toggle = document.querySelector<HTMLElement>('[data-doc-panel-toggle]');
+ if (toggle == null) throw new Error('the document panel toggle is absent');
+ return toggle;
+ };
- expect(terminalChanges).toEqual([]);
- expect(toastInfoMessages).toEqual([]);
+ beforeEach(() => {
+ cleanup();
+ localStorage.clear();
+ localStorage.setItem(
+ SIDEBAR_PINS_KEY,
+ JSON.stringify({ right: { above: 'collapsed', below: 'collapsed', embedded: 'collapsed' } }),
+ );
+ docCtx = { ...DOC_LIVE_CTX, docPanelMode: 'doc' };
+ innerLayout = { ...INNER_LAYOUT_DOC_CLOSED };
+ mockEditorUnitPx = 1360;
+ Object.defineProperty(window, 'innerWidth', {
+ value: 1400,
+ configurable: true,
+ writable: true,
+ });
+ panelIsCollapsed = true;
+ deliverDocPanelResizeAfterLayout = true;
+ closeActivityPanelCalls = 0;
});
- test('opening the file list inside the card re-plans the side panel, right terminal and chat against the narrower row', async () => {
- const resizeObserver = installResizeObserver();
+ test('a doc-scoped problems request opens the Problems tab and expands the collapsed rail', async () => {
+ const { resizeObserver } = mountTabHost('timeline');
try {
- const outerPx = 1400 - SHELL_CHROME_PX;
- setViewportWidth(1400);
- mockGroupPx = outerPx;
- mockFileListPx = 0;
- docCtx = DOC_LIVE_CTX;
- const renderRow = () => (
- <FileListShell>
- <EditorArea
- {...rowProps}
- agentsVisible
- terminalVisible
- terminalPlacement="right"
- terminalRightWidth={480}
- />
- </FileListShell>
- );
- render(renderRow());
- measureFileListSlot();
- await flushFrame();
- groupLayout = { 'editor-main': 40, 'terminal-column': 40, 'agents-column': 20 };
- innerLayout = { 'workspace-main': 50, 'doc-panel': 50 };
- groupSetLayoutCalls = [];
- innerSetLayoutCalls = [];
- resizeObserver.fire('[data-editor-inner-panels]');
- const preferredOuter = groupSetLayoutCalls.at(-1) ?? groupLayout;
- expect(((preferredOuter['terminal-column'] ?? 0) / 100) * outerPx).toBeCloseTo(480, 3);
- expect(((preferredOuter['agents-column'] ?? 0) / 100) * outerPx).toBeCloseTo(480, 3);
+ expect(infoWidthPx()).toBe(0);
+ expect(docPanelToggle().getAttribute('aria-expanded')).toBe('false');
- mockFileListPx = FILE_LIST_PX;
- groupSetLayoutCalls = [];
- innerSetLayoutCalls = [];
- resizeObserver.fire('[data-editor-inner-panels]');
+ const storedPins = localStorage.getItem('ok-sidebar-pins-v2');
+ act(() => requestDocPanelTab('problems', { scope: 'doc' }));
+ await act(async () => {});
- const flooredOuter = groupSetLayoutCalls.at(-1);
- expect(flooredOuter).toBeDefined();
- expect(((flooredOuter?.['terminal-column'] ?? 0) / 100) * outerPx).toBeCloseTo(
- RIGHT_TERMINAL_PANEL_MIN_WIDTH_PX,
- 3,
- );
- expect(((flooredOuter?.['agents-column'] ?? 0) / 100) * outerPx).toBeCloseTo(
- MIN_AGENTS_PANEL_WIDTH,
- 3,
- );
- expect(lastInnerWritePx('doc-panel')).toBeCloseTo(300, 3);
+ expect(localStorage.getItem('ok-sidebar-pins-v2')).toBe(storedPins);
+
+ expect(screen.getByRole('tabpanel').getAttribute('id')).toBe('panel-problems');
+ expect(screen.getByTestId('panel-scope-doc').getAttribute('data-state')).toBe('on');
+ expect(docPanelToggle().getAttribute('aria-expanded')).toBe('true');
+ expect(infoWidthPx()).toBeCloseTo(320, 0);
+ expect(innerResidualWidthPx()).toBeGreaterThanOrEqual(300);
} finally {
resizeObserver.restore();
}
});
- test('at a 1400px window with a document open, chat joins the right terminal', async () => {
- const resizeObserver = installResizeObserver();
+ test('a panel already parked on Problems in project scope comes back in doc scope', async () => {
+ const { resizeObserver } = mountTabHost('problems');
try {
- const rowPx = 1400 - FILE_LIST_PX - SHELL_CHROME_PX;
- setViewportWidth(1400);
- mockGroupPx = rowPx;
- mockPanelPx = 320;
- mockPanelPercentage = pctOfRow(320, rowPx);
- docCtx = DOC_LIVE_CTX;
- const terminalChanges: boolean[] = [];
- const agentsChanges: boolean[] = [];
- const view = render(
- <EditorArea
- {...rowProps}
- agentsVisible={false}
- terminalVisible
- terminalPlacement="right"
- onAgentsVisibleChange={(visible: boolean) => {
- agentsChanges.push(visible);
- }}
- onTerminalVisibleChange={(visible: boolean) => {
- terminalChanges.push(visible);
- }}
- />,
- );
- groupLayout = {
- 'editor-main': 100 - pctOfRow(740, rowPx),
- 'terminal-column': pctOfRow(740, rowPx),
- 'agents-column': 0,
- };
- innerLayout = innerRowWithDoc(320, rowPx - 740);
- const inner = document.querySelector<HTMLElement>('[data-editor-inner-panels]');
- if (inner == null) throw new Error('the editor inner row is absent');
- Object.defineProperty(inner, 'getBoundingClientRect', {
- configurable: true,
- value: () => ({ width: rowPx - 740 }),
- });
- resizeObserver.fire('[data-editor-inner-panels]');
+ act(() => requestDocPanelTab('problems', { scope: 'doc' }));
+ await act(async () => {});
+ fireEvent.click(screen.getByTestId('panel-scope-project'));
+ expect(screen.getByTestId('problems-project-scope')).toBeTruthy();
+ fireEvent.click(docPanelToggle());
+ await act(async () => {});
+ expect(infoWidthPx()).toBe(0);
+ expect(docPanelToggle().getAttribute('aria-expanded')).toBe('false');
- view.rerender(
- <EditorArea
- {...rowProps}
- agentsVisible
- terminalVisible
- terminalPlacement="right"
- onAgentsVisibleChange={(visible: boolean) => {
- agentsChanges.push(visible);
- }}
- onTerminalVisibleChange={(visible: boolean) => {
- terminalChanges.push(visible);
- }}
- />,
- );
+ act(() => requestDocPanelTab('problems', { scope: 'doc' }));
await act(async () => {});
- expect(terminalChanges).toEqual([]);
- expect(agentsChanges).toEqual([]);
- expect(toastInfoMessages).toEqual([]);
+ expect(screen.getByRole('tabpanel').getAttribute('id')).toBe('panel-problems');
+ expect(screen.getByTestId('panel-scope-doc').getAttribute('data-state')).toBe('on');
+ expect(screen.queryByTestId('problems-project-scope')).toBeNull();
+ expect(infoWidthPx()).toBeCloseTo(320, 0);
+ expect(innerResidualWidthPx()).toBeGreaterThanOrEqual(300);
} finally {
resizeObserver.restore();
}
});
- test('a re-plan and an admission check that arrive during a side-panel drag wait for the drag to end', async () => {
- const resizeObserver = installResizeObserver();
- try {
- setViewportWidth(2000);
- mockGroupPx = 2000;
- mockPanelPx = 320;
- docCtx = DOC_LIVE_CTX;
- const agentsChanges: boolean[] = [];
- groupLayout = {
- 'editor-main': 100 - pctOfRow(740 + 480, 2000),
- 'terminal-column': pctOfRow(740, 2000),
- 'agents-column': pctOfRow(480, 2000),
- };
- innerLayout = innerRowWithDoc(320, 2000 - 740 - 480);
- render(
- <EditorArea
- {...rowProps}
- agentsVisible
- terminalVisible
- terminalPlacement="right"
- onAgentsVisibleChange={(visible: boolean) => {
- agentsChanges.push(visible);
- }}
- />,
- );
- await act(async () => {});
-
- act(() => {
- fireEvent.pointerDown(docHandle(), { pointerId: 1 });
- });
- groupSetLayoutCalls = [];
- innerSetLayoutCalls = [];
- toastInfoMessages = [];
- mockGroupPx = 1000;
- resizeObserver.fire('[data-editor-area-panels]');
- resizeObserver.fire('[data-editor-inner-panels]');
-
- expect(groupSetLayoutCalls).toHaveLength(0);
- expect(innerSetLayoutCalls).toHaveLength(0);
- expect(agentsChanges).toEqual([]);
- expect(toastInfoMessages).toEqual([]);
+ test('a tab request takes the rail back from the agent drill-in', () => {
+ docCtx = { ...DOC_LIVE_CTX, docPanelMode: 'agent', docPanelAgentId: 'agent-1' };
+ const { resizeObserver } = mountTabHost('timeline');
+ expect(screen.queryByRole('tabpanel')).toBeNull();
- act(() => {
- fireEvent.pointerUp(window, { pointerId: 1 });
- });
+ act(() => requestDocPanelTab('problems', { scope: 'doc' }));
- expect(groupSetLayoutCalls.length).toBeGreaterThan(0);
- expect(agentsChanges).toEqual([false]);
- expect(toastInfoMessages).toEqual(['Agent panel closed to keep Terminal readable.']);
- } finally {
- resizeObserver.restore();
- }
+ expect(closeActivityPanelCalls).toBe(1);
+ resizeObserver.restore();
});
- test('a chat drag the library starts beside the divider takes the drag lock, marks the outer row, and re-plans on release', async () => {
- const resizeObserver = installResizeObserver();
+ test('re-rendering does not stack the subscription, and unmounting drops it', () => {
+ const onActiveTabChange = vi.fn();
+ const { view, resizeObserver } = mountTabHost('timeline', onActiveTabChange);
try {
- setViewportWidth(2000);
- mockGroupPx = 2000;
- deliverDocPanelResizeAfterLayout = true;
- docCtx = DOC_LIVE_CTX;
- const agentsChanges: boolean[] = [];
- groupLayout = {
- 'editor-main': 100 - pctOfRow(740 + 480, 2000),
- 'terminal-column': pctOfRow(740, 2000),
- 'agents-column': pctOfRow(480, 2000),
- };
- innerLayout = innerRowWithDoc(320, 2000 - 740 - 480);
- render(
- <EditorArea
- {...rowProps}
- agentsVisible
- terminalVisible
- terminalPlacement="right"
- onAgentsVisibleChange={(visible: boolean) => {
- agentsChanges.push(visible);
- }}
- />,
- );
- await act(async () => {});
- measureEditorCardForRow(resizeObserver);
- const outerRow = screen.getByTestId('resizable-group');
- expect(outerRow.getAttribute('data-dragging')).toBeNull();
-
- agentsHandle().setAttribute('data-separator', 'active');
- groupLayout = {
- 'editor-main': 100 - pctOfRow(740 + 630, 2000),
- 'terminal-column': pctOfRow(740, 2000),
- 'agents-column': pctOfRow(630, 2000),
- };
- act(() => {
- groupOnLayoutChange?.(groupLayout);
- railPanelOnResizeById.get(AGENTS_COLUMN_ID)?.({
- asPercentage: groupLayout[AGENTS_COLUMN_ID],
- inPixels: 630,
- });
- });
- expect(outerRow.getAttribute('data-dragging')).toBe('true');
- expect(document.getElementById(AGENTS_COLUMN_ID)?.getBoundingClientRect().width).toBeCloseTo(
- 630,
- 0,
- );
- expect(lastInnerWritePx('doc-panel')).toBeCloseTo(320, 3);
-
- groupSetLayoutCalls = [];
- innerSetLayoutCalls = [];
- toastInfoMessages = [];
- setViewportWidth(1000);
- mockGroupPx = 1000;
- measureEditorCardForRow(resizeObserver);
- resizeObserver.fire('[data-editor-area-panels]');
- resizeObserver.fire('[data-editor-inner-panels]');
-
- expect(groupSetLayoutCalls).toHaveLength(0);
- expect(document.getElementById('doc-panel')?.getBoundingClientRect().width).toBe(0);
- expect(innerResidualWidthPx()).toBeGreaterThanOrEqual(300);
- expect(agentsChanges).toEqual([]);
- expect(toastInfoMessages).toEqual([]);
-
- setViewportWidth(2200);
- mockGroupPx = 2200;
- measureEditorCardForRow(resizeObserver);
- resizeObserver.fire('[data-editor-area-panels]');
- resizeObserver.fire('[data-editor-inner-panels]');
- expect(groupSetLayoutCalls).toHaveLength(0);
- expect(document.getElementById('doc-panel')?.getBoundingClientRect().width).toBeCloseTo(
- 320,
- 0,
- );
- expect(innerResidualWidthPx()).toBeGreaterThanOrEqual(300);
- expect(agentsChanges).toEqual([]);
- expect(toastInfoMessages).toEqual([]);
-
- setViewportWidth(1000);
- mockGroupPx = 1000;
- measureEditorCardForRow(resizeObserver);
- resizeObserver.fire('[data-editor-area-panels]');
- resizeObserver.fire('[data-editor-inner-panels]');
- expect(groupSetLayoutCalls).toHaveLength(0);
- expect(document.getElementById('doc-panel')?.getBoundingClientRect().width).toBe(0);
- expect(innerResidualWidthPx()).toBeGreaterThanOrEqual(300);
-
- setViewportWidth(850);
- mockGroupPx = 850;
- measureEditorCardForRow(resizeObserver);
- resizeObserver.fire('[data-editor-area-panels]');
- resizeObserver.fire('[data-editor-inner-panels]');
- expect(groupSetLayoutCalls).toHaveLength(0);
- expect(agentsChanges).toEqual([]);
- expect(toastInfoMessages).toEqual([]);
+ for (let i = 0; i < 3; i += 1) {
+ view.rerender(<TabHost initialTab="timeline" onActiveTabChange={onActiveTabChange} />);
+ }
- agentsHandle().removeAttribute('data-separator');
- act(() => {
- fireEvent.pointerUp(window, { pointerId: 7 });
- });
+ act(() => requestDocPanelTab('problems', { scope: 'doc' }));
+ expect(onActiveTabChange).toHaveBeenCalledTimes(1);
+ expect(onActiveTabChange).toHaveBeenCalledWith('problems');
+ expect(infoWidthPx()).toBeCloseTo(320, 0);
- expect(outerRow.getAttribute('data-dragging')).toBeNull();
- expect(groupSetLayoutCalls.length).toBeGreaterThan(0);
- expect(agentsChanges).toEqual([false]);
- expect(toastInfoMessages).toEqual(['Agent panel closed to keep Terminal readable.']);
+ view.unmount();
+ act(() => requestDocPanelTab('problems', { scope: 'doc' }));
+ expect(onActiveTabChange).toHaveBeenCalledTimes(1);
} finally {
resizeObserver.restore();
}
});
+});
- test('a side-panel drag the library starts beside the divider takes the drag lock, marks the inner row, and re-plans on release', async () => {
- const resizeObserver = installResizeObserver();
- try {
- setViewportWidth(1400);
- mockGroupPx = 1360;
- docCtx = DOC_LIVE_CTX;
- groupLayout = {
- 'editor-main': 100 - pctOfRow(480, 1360),
- 'agents-column': pctOfRow(480, 1360),
- };
- innerLayout = innerRowWithDoc(320, 1360 - 480);
- render(<EditorArea {...rowProps} agentsVisible />);
- await act(async () => {});
- const innerRow = screen.getByTestId('resizable-group-inner');
- expect(innerRow.getAttribute('data-dragging')).toBeNull();
-
- docHandle().setAttribute('data-separator', 'active');
- innerLayout = innerRowWithDoc(360, 1360 - 480);
+type Observation = {
+ callback: ResizeObserverCallback;
+ observer: ResizeObserver;
+ target: Element;
+};
+const installResizeObserver = () => {
+ const original = globalThis.ResizeObserver;
+ const observations = new Set<Observation>();
+ class TestResizeObserver implements ResizeObserver {
+ readonly callback: ResizeObserverCallback;
+ constructor(callback: ResizeObserverCallback) {
+ this.callback = callback;
+ }
+ observe(target: Element) {
+ observations.add({ callback: this.callback, observer: this, target });
+ }
+ unobserve(target: Element) {
+ for (const observation of observations) {
+ if (observation.observer === this && observation.target === target) {
+ observations.delete(observation);
+ }
+ }
+ }
+ disconnect() {
+ for (const observation of observations) {
+ if (observation.observer === this) observations.delete(observation);
+ }
+ }
+ }
+ Object.defineProperty(globalThis, 'ResizeObserver', {
+ value: TestResizeObserver,
+ configurable: true,
+ writable: true,
+ });
+ return {
+ fire: (selector: string) => {
+ const target = document.querySelector(selector);
+ const matching = [...observations].filter((entry) => entry.target === target);
+ if (matching.length === 0) throw new Error(`${selector} is not observed`);
act(() => {
- innerRowHandlers.onLayoutChange?.(innerLayout);
+ for (const observation of matching) observation.callback([], observation.observer);
});
- expect(innerRow.getAttribute('data-dragging')).toBe('true');
-
- groupSetLayoutCalls = [];
- innerSetLayoutCalls = [];
- mockGroupPx = 1000;
- resizeObserver.fire('[data-editor-area-panels]');
- resizeObserver.fire('[data-editor-inner-panels]');
- expect(groupSetLayoutCalls).toHaveLength(0);
- expect(innerSetLayoutCalls).toHaveLength(0);
-
- docHandle().removeAttribute('data-separator');
- act(() => {
- fireEvent.pointerUp(window, { pointerId: 7 });
+ },
+ restore: () => {
+ Object.defineProperty(globalThis, 'ResizeObserver', {
+ value: original,
+ configurable: true,
+ writable: true,
});
- expect(innerRow.getAttribute('data-dragging')).toBeNull();
- expect(groupSetLayoutCalls.length).toBeGreaterThan(0);
- } finally {
- resizeObserver.restore();
- }
- });
-
- test('the joint plan’s own outer write never adopts a drag from a separator that still reads active', async () => {
- setViewportWidth(1400);
- mockGroupPx = 1360;
- docCtx = DOC_LIVE_CTX;
- groupLayout = {
- 'editor-main': 100 - pctOfRow(480, 1360),
- 'agents-column': pctOfRow(480, 1360),
- };
- innerLayout = innerRowWithDoc(320, 1360 - 480);
- render(<EditorArea {...rowProps} agentsVisible />);
- await act(async () => {});
- const outerRow = screen.getByTestId('resizable-group');
+ },
+ };
+};
- agentsHandle().setAttribute('data-separator', 'active');
- groupLayout = { 'editor-main': 60, 'agents-column': 40 };
- act(() => {
- groupOnLayoutChange?.(groupLayout);
- });
- expect(outerRow.getAttribute('data-dragging')).toBe('true');
+describe('EditorArea editor card rows', () => {
+ const rowProps = {
+ editorMode: 'wysiwyg',
+ onModeChange: () => {},
+ activeTab: 'timeline',
+ onActiveTabChange: () => {},
+ terminalBridge: {} as never,
+ } as const;
+ const setViewportWidth = (px: number) => {
+ Object.defineProperty(window, 'innerWidth', { value: px, configurable: true, writable: true });
+ };
+ const docHandle = () => {
+ const handle = document.getElementById('doc-panel')?.previousElementSibling;
+ if (!(handle instanceof HTMLElement)) throw new Error('doc-panel resize handle not found');
+ return handle;
+ };
- const echoOuterWrites = groupHandles.outer.setLayout;
- groupHandles.outer.setLayout = (layout: MockLayout) => {
- echoOuterWrites(layout);
- groupOnLayoutChange?.(layout);
- };
- try {
- groupSetLayoutCalls = [];
- act(() => {
- fireEvent.pointerUp(window, { pointerId: 7 });
- });
- expect(groupSetLayoutCalls.length).toBeGreaterThan(0);
- expect(outerRow.getAttribute('data-dragging')).toBeNull();
- } finally {
- groupHandles.outer.setLayout = echoOuterWrites;
- }
+ beforeEach(() => {
+ cleanup();
+ localStorage.clear();
+ docCtx = EMPTY_DOC_CTX;
+ panelIsCollapsed = false;
+ mockEditorUnitPx = 1360;
});
- test('every side-panel drag end re-plans both rows', async () => {
+ test('a project window puts the tab row, the workspace and the side panel inside one editor card', () => {
setViewportWidth(1400);
docCtx = DOC_LIVE_CTX;
- groupLayout = {
- 'editor-main': 100 - pctOfRow(480, 1360),
- 'agents-column': pctOfRow(480, 1360),
- };
- innerLayout = innerRowWithDoc(320, 1360 - 480);
- render(<EditorArea {...rowProps} agentsVisible />);
- await act(async () => {});
- groupLayout = { 'editor-main': 60, 'agents-column': 40 };
- innerLayout = innerRowWithDoc(300, 0.6 * 1360);
- groupSetLayoutCalls = [];
- innerSetLayoutCalls = [];
+ render(
+ <EditorArea {...rowProps} agentsVisible terminalVisible dockTree={RIGHT_TERMINAL_TREE} />,
+ );
- act(() => {
- fireEvent.pointerDown(docHandle(), { pointerId: 1 });
- });
- expect(groupSetLayoutCalls).toHaveLength(0);
- act(() => {
- fireEvent.pointerUp(window, { pointerId: 1 });
- });
+ const card = paneCard('editor');
+ const inner = screen.getByTestId('resizable-group-inner');
+ const header = document.querySelector('[data-editor-area-header]');
+ const column = document.querySelector('[data-editor-workspace-column]');
+ const docPanel = document.getElementById('doc-panel');
+ if (card == null || header == null || column == null || docPanel == null) {
+ throw new Error('editor card structure is incomplete');
+ }
- expect(((groupSetLayoutCalls.at(-1)?.['agents-column'] ?? 0) / 100) * 1360).toBeCloseTo(480, 3);
- expect(lastInnerWritePx('doc-panel')).toBeCloseTo(320, 3);
+ expect(card.getAttribute('data-variant')).toBe('card');
+ expect(card.parentElement).toBe(dockUnit('editor'));
+ expect(card.contains(inner)).toBe(true);
+ expect(inner.contains(docPanel)).toBe(true);
+ expect(inner.contains(column)).toBe(true);
+ expect(column.firstElementChild).toBe(header);
+ expect(header.contains(screen.getByTestId('workspace-tabs'))).toBe(true);
+ expect(docPanel.contains(header)).toBe(false);
+ expect(card.contains(terminalMount())).toBe(false);
+ expect(card.contains(agentsMount())).toBe(false);
+ expect(document.querySelector('[data-editor-inner-panels]')?.firstElementChild).toBe(inner);
});
- test('a chat drag the library started beside the divider commits the released width as the preferred width', async () => {
- const resizeObserver = installResizeObserver();
+ test('a note window keeps the tab row target above the row and renders the flat card', () => {
+ Object.defineProperty(window, 'okDesktop', {
+ configurable: true,
+ value: {
+ config: { mode: 'note' },
+ editor: { notifyViewMenuStateChanged: () => {} },
+ },
+ });
try {
- setViewportWidth(1400);
- mockGroupPx = 1360;
- docCtx = DOC_LIVE_CTX;
- groupLayout = {
- 'editor-main': 100 - pctOfRow(480, 1360),
- 'agents-column': pctOfRow(480, 1360),
- };
- innerLayout = innerRowWithDoc(320, 1360 - 480);
- render(<EditorArea {...rowProps} agentsVisible />);
- await act(async () => {});
-
- agentsHandle().setAttribute('data-separator', 'active');
- groupLayout = {
- 'editor-main': 100 - pctOfRow(630, 1360),
- 'agents-column': pctOfRow(630, 1360),
- };
- act(() => {
- groupOnLayoutChange?.(groupLayout);
- });
- mockPanelPx = 630;
- mockPanelPercentage = pctOfRow(630, 1360);
- agentsHandle().removeAttribute('data-separator');
- act(() => {
- fireEvent.pointerUp(window, { pointerId: 7 });
- });
- mockPanelPx = null;
- mockPanelPercentage = null;
-
- groupSetLayoutCalls = [];
- mockGroupPx = 1300;
- resizeObserver.fire('[data-editor-area-panels]');
- expect(((groupSetLayoutCalls.at(-1)?.['agents-column'] ?? 0) / 100) * 1300).toBeCloseTo(
- 630,
- 3,
- );
+ render(<EditorArea {...rowProps} />);
+ const panels = document.querySelector('[data-editor-area-panels]');
+ const header = document.querySelector('[data-editor-area-header]');
+ const card = document.querySelector('[data-slot="pane-card"][data-pane="editor"]');
+ expect(header?.nextElementSibling).toBe(panels);
+ expect(panels?.contains(header)).toBe(false);
+ expect(card?.getAttribute('data-variant')).toBe('flat');
+ expect(screen.getByTestId('resizable-group-inner').contains(card)).toBe(false);
+ expect(card?.contains(screen.getByTestId('resizable-group-inner'))).toBe(true);
} finally {
- resizeObserver.restore();
+ Reflect.deleteProperty(window, 'okDesktop');
}
});
- test('a chat drag the library started beside the divider that closes the column leaves it collapsed without changing visibility', async () => {
- setViewportWidth(1400);
- mockGroupPx = 1360;
- docCtx = DOC_LIVE_CTX;
- const agentsChanges: boolean[] = [];
- groupLayout = {
- 'editor-main': 100 - pctOfRow(480, 1360),
- 'agents-column': pctOfRow(480, 1360),
- };
- innerLayout = innerRowWithDoc(320, 1360 - 480);
- render(
- <EditorArea
- {...rowProps}
- agentsVisible
- onAgentsVisibleChange={(visible: boolean) => {
- agentsChanges.push(visible);
- }}
- />,
- );
- await act(async () => {});
- const outerRow = screen.getByTestId('resizable-group');
-
- agentsHandle().setAttribute('data-separator', 'active');
- groupLayout = { 'editor-main': 100, 'agents-column': 0 };
- act(() => {
- groupOnLayoutChange?.(groupLayout);
- });
- expect(outerRow.getAttribute('data-dragging')).toBe('true');
- groupSetLayoutCalls = [];
- mockPanelPx = 0;
- mockPanelPercentage = 0;
- panelIsCollapsed = true;
- agentsHandle().removeAttribute('data-separator');
- act(() => {
- fireEvent.pointerUp(window, { pointerId: 7 });
+ test('a single-file window renders the normal editor card', () => {
+ Object.defineProperty(window, 'okDesktop', {
+ configurable: true,
+ value: {
+ config: { singleFile: true },
+ editor: { notifyViewMenuStateChanged: () => {} },
+ },
});
-
- expect(outerRow.getAttribute('data-dragging')).toBeNull();
- expect(agentsChanges).toEqual([]);
- expect(groupSetLayoutCalls).toHaveLength(0);
- });
-
- test('a right-terminal drag the library starts beside the divider takes the drag lock, marks the outer row, and re-plans on release', async () => {
- const resizeObserver = installResizeObserver();
try {
- setViewportWidth(2000);
- mockGroupPx = 2000;
- deliverDocPanelResizeAfterLayout = true;
- docCtx = DOC_LIVE_CTX;
- const agentsChanges: boolean[] = [];
- groupLayout = {
- 'editor-main': 100 - pctOfRow(740 + 480, 2000),
- 'terminal-column': pctOfRow(740, 2000),
- 'agents-column': pctOfRow(480, 2000),
- };
- innerLayout = innerRowWithDoc(320, 2000 - 740 - 480);
render(
- <EditorArea
- {...rowProps}
- agentsVisible
- terminalVisible
- terminalPlacement="right"
- onAgentsVisibleChange={(visible: boolean) => {
- agentsChanges.push(visible);
- }}
- />,
- );
- await act(async () => {});
- measureEditorCardForRow(resizeObserver);
- const outerRow = screen.getByTestId('resizable-group');
- expect(outerRow.getAttribute('data-dragging')).toBeNull();
-
- terminalHandle().setAttribute('data-separator', 'active');
- groupLayout = {
- 'editor-main': 100 - pctOfRow(890 + 480, 2000),
- 'terminal-column': pctOfRow(890, 2000),
- 'agents-column': pctOfRow(480, 2000),
- };
- act(() => {
- groupOnLayoutChange?.(groupLayout);
- railPanelOnResizeById.get(TERMINAL_COLUMN_ID)?.({
- asPercentage: groupLayout[TERMINAL_COLUMN_ID],
- inPixels: 890,
- });
- });
- expect(outerRow.getAttribute('data-dragging')).toBe('true');
- expect(
- document.getElementById(TERMINAL_COLUMN_ID)?.getBoundingClientRect().width,
- ).toBeCloseTo(890, 0);
- expect(lastInnerWritePx('doc-panel')).toBeCloseTo(320, 3);
-
- groupSetLayoutCalls = [];
- innerSetLayoutCalls = [];
- toastInfoMessages = [];
- setViewportWidth(1000);
- mockGroupPx = 1000;
- measureEditorCardForRow(resizeObserver);
- resizeObserver.fire('[data-editor-area-panels]');
- resizeObserver.fire('[data-editor-inner-panels]');
-
- expect(groupSetLayoutCalls).toHaveLength(0);
- expect(document.getElementById('doc-panel')?.getBoundingClientRect().width).toBe(0);
- expect(innerResidualWidthPx()).toBeGreaterThanOrEqual(300);
- expect(agentsChanges).toEqual([]);
- expect(toastInfoMessages).toEqual([]);
-
- setViewportWidth(2200);
- mockGroupPx = 2200;
- measureEditorCardForRow(resizeObserver);
- resizeObserver.fire('[data-editor-area-panels]');
- resizeObserver.fire('[data-editor-inner-panels]');
- expect(groupSetLayoutCalls).toHaveLength(0);
- expect(document.getElementById('doc-panel')?.getBoundingClientRect().width).toBeCloseTo(
- 320,
- 0,
+ <SingleFileModeProvider>
+ <EditorArea {...rowProps} />
+ </SingleFileModeProvider>,
);
- expect(innerResidualWidthPx()).toBeGreaterThanOrEqual(300);
- expect(agentsChanges).toEqual([]);
- expect(toastInfoMessages).toEqual([]);
-
- setViewportWidth(1000);
- mockGroupPx = 1000;
- measureEditorCardForRow(resizeObserver);
- resizeObserver.fire('[data-editor-area-panels]');
- resizeObserver.fire('[data-editor-inner-panels]');
- expect(groupSetLayoutCalls).toHaveLength(0);
- expect(document.getElementById('doc-panel')?.getBoundingClientRect().width).toBe(0);
- expect(innerResidualWidthPx()).toBeGreaterThanOrEqual(300);
-
- setViewportWidth(850);
- mockGroupPx = 850;
- measureEditorCardForRow(resizeObserver);
- resizeObserver.fire('[data-editor-area-panels]');
- resizeObserver.fire('[data-editor-inner-panels]');
- expect(groupSetLayoutCalls).toHaveLength(0);
- expect(agentsChanges).toEqual([]);
- expect(toastInfoMessages).toEqual([]);
-
- terminalHandle().removeAttribute('data-separator');
- act(() => {
- fireEvent.pointerUp(window, { pointerId: 7 });
- });
- await act(async () => {});
-
- expect(outerRow.getAttribute('data-dragging')).toBeNull();
- expect(groupSetLayoutCalls.length).toBeGreaterThan(0);
- expect(agentsChanges).toEqual([false]);
- expect(toastInfoMessages).toEqual(['Agent panel closed to keep Terminal readable.']);
+ const card = document.querySelector('[data-slot="pane-card"][data-pane="editor"]');
+ expect(card?.getAttribute('data-variant')).toBe('card');
} finally {
- resizeObserver.restore();
+ Reflect.deleteProperty(window, 'okDesktop');
}
});
- test('a right-terminal drag the library started beside the divider that closes the column leaves it collapsed without changing visibility', async () => {
- setViewportWidth(2000);
- mockGroupPx = 2000;
+ test('a side panel drag marks only the side panel row', () => {
+ setViewportWidth(1400);
docCtx = DOC_LIVE_CTX;
- const terminalChanges: boolean[] = [];
- groupLayout = {
- 'editor-main': 100 - pctOfRow(740, 2000),
- 'terminal-column': pctOfRow(740, 2000),
- };
- innerLayout = innerRowWithDoc(320, 2000 - 740);
- render(
- <EditorArea
- {...rowProps}
- terminalVisible
- terminalPlacement="right"
- onTerminalVisibleChange={(visible: boolean) => {
- terminalChanges.push(visible);
- }}
- />,
- );
- await act(async () => {});
- const outerRow = screen.getByTestId('resizable-group');
+ render(<EditorArea {...rowProps} agentsVisible />);
+ const inner = screen.getByTestId('resizable-group-inner');
+ const workspace = document.querySelector('[data-dock-workspace]');
- terminalHandle().setAttribute('data-separator', 'active');
- groupLayout = { 'editor-main': 100, 'terminal-column': 0 };
act(() => {
- groupOnLayoutChange?.(groupLayout);
+ fireEvent.pointerDown(docHandle(), { pointerId: 1 });
});
- expect(outerRow.getAttribute('data-dragging')).toBe('true');
- groupSetLayoutCalls = [];
- panelIsCollapsed = true;
- terminalHandle().removeAttribute('data-separator');
+ expect(inner.getAttribute('data-dragging')).toBe('true');
+ expect(workspace?.hasAttribute('data-dragging')).toBe(false);
act(() => {
- fireEvent.pointerUp(window, { pointerId: 7 });
+ fireEvent.pointerUp(window, { pointerId: 1 });
});
-
- expect(outerRow.getAttribute('data-dragging')).toBeNull();
- expect(terminalChanges).toEqual([]);
- expect(groupSetLayoutCalls).toHaveLength(0);
+ expect(inner.hasAttribute('data-dragging')).toBe(false);
});
- test('a drag end that closes a column leaves the follow-up pin to the column sync', () => {
- setViewportWidth(1400);
- docCtx = DOC_LIVE_CTX;
- const agentsChanges: boolean[] = [];
- render(
- <EditorArea
- {...rowProps}
- agentsVisible
- onAgentsVisibleChange={(visible: boolean) => {
- agentsChanges.push(visible);
- }}
- />,
+ function FileListShell({ children }: { children: ReactNode }) {
+ return (
+ <FileListHostProvider enabled fileList={<nav data-testid="card-file-list" />}>
+ {children}
+ </FileListHostProvider>
);
- groupLayout = { 'editor-main': 100, 'agents-column': 0 };
- groupSetLayoutCalls = [];
- act(() => {
- fireEvent.pointerDown(agentsHandle(), { pointerId: 1 });
- });
- mockPanelPx = 0;
- mockPanelPercentage = 0;
- panelIsCollapsed = true;
- act(() => {
- fireEvent.pointerUp(window, { pointerId: 1 });
+ }
+ const measureFileListSlot = () => {
+ const slot = document.querySelector<HTMLElement>('[data-editor-file-list-slot]');
+ if (slot == null) throw new Error('the editor card has no file list slot');
+ Object.defineProperty(slot, 'getBoundingClientRect', {
+ configurable: true,
+ value: () => ({
+ width: mockFileListPx,
+ height: 0,
+ top: 0,
+ left: 0,
+ right: mockFileListPx,
+ bottom: 0,
+ x: 0,
+ y: 0,
+ }),
});
+ return slot;
+ };
- expect(agentsChanges).toEqual([false]);
- expect(groupSetLayoutCalls).toHaveLength(0);
- });
-
- test('the inner row observer re-plans and re-checks admission on its own', async () => {
- const resizeObserver = installResizeObserver();
- try {
- setViewportWidth(2000);
- mockGroupPx = 2000;
- mockPanelPx = 320;
- docCtx = DOC_LIVE_CTX;
- const agentsChanges: boolean[] = [];
- groupLayout = {
- 'editor-main': 100 - pctOfRow(740 + 480, 2000),
- 'terminal-column': pctOfRow(740, 2000),
- 'agents-column': pctOfRow(480, 2000),
- };
- innerLayout = innerRowWithDoc(320, 2000 - 740 - 480);
- render(
- <EditorArea
- {...rowProps}
- agentsVisible
- terminalVisible
- terminalPlacement="right"
- onAgentsVisibleChange={(visible: boolean) => {
- agentsChanges.push(visible);
- }}
- />,
- );
- await act(async () => {});
- groupSetLayoutCalls = [];
- innerSetLayoutCalls = [];
-
- mockGroupPx = 1000;
- resizeObserver.fire('[data-editor-inner-panels]');
-
- expect(groupSetLayoutCalls.length).toBeGreaterThan(0);
- expect(agentsChanges).toEqual([false]);
- expect(toastInfoMessages).toEqual(['Agent panel closed to keep Terminal readable.']);
- } finally {
- resizeObserver.restore();
- }
- });
-
- const renderWideRowsWithTerminalAndChat = async (agentsChanges: boolean[]) => {
- setViewportWidth(2000);
- mockGroupPx = 2000;
- mockPanelPx = 320;
+ test('draws the file list in the editor card slot, ahead of the content column', () => {
docCtx = DOC_LIVE_CTX;
- groupLayout = {
- 'editor-main': 100 - pctOfRow(740 + 480, 2000),
- 'terminal-column': pctOfRow(740, 2000),
- 'agents-column': pctOfRow(480, 2000),
- };
- innerLayout = innerRowWithDoc(320, 2000 - 740 - 480);
render(
- <EditorArea
- {...rowProps}
- agentsVisible
- terminalVisible
- terminalPlacement="right"
- onAgentsVisibleChange={(visible: boolean) => {
- agentsChanges.push(visible);
- }}
- />,
+ <FileListShell>
+ <EditorArea {...rowProps} agentsVisible={false} terminalVisible={false} />
+ </FileListShell>,
);
- await act(async () => {});
- };
-
- test('the inner row observer skips the resize an outer row layout change explains while every pin is in place, and re-plans on the next one', async () => {
- const resizeObserver = installResizeObserver();
- try {
- const agentsChanges: boolean[] = [];
- await renderWideRowsWithTerminalAndChat(agentsChanges);
- groupSetLayoutCalls = [];
- innerSetLayoutCalls = [];
-
- mockGroupPx = 1000;
- act(() => groupOnLayoutChange?.(groupLayout));
- resizeObserver.fire('[data-editor-inner-panels]');
- await flushFrame();
-
- expect(groupSetLayoutCalls).toHaveLength(0);
- expect(innerSetLayoutCalls).toHaveLength(0);
- expect(agentsChanges).toEqual([]);
- expect(toastInfoMessages).toEqual([]);
- resizeObserver.fire('[data-editor-inner-panels]');
- await flushFrame();
-
- expect(groupSetLayoutCalls.length).toBeGreaterThan(0);
- expect(agentsChanges).toEqual([false]);
- expect(toastInfoMessages).toEqual(['Agent panel closed to keep Terminal readable.']);
- } finally {
- resizeObserver.restore();
- }
+ const card = document.querySelector('[data-slot="pane-card"][data-pane="editor"]');
+ const slot = measureFileListSlot();
+ const content = card?.querySelector('[data-slot="sidebar-inset"]');
+ expect(slot.parentElement).toBe(card);
+ expect(slot.contains(screen.getByTestId('card-file-list'))).toBe(true);
+ expect(content?.parentElement).toBe(card);
+ expect(
+ slot.compareDocumentPosition(content as Element) & Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+ expect(content?.contains(screen.getByTestId('resizable-group-inner'))).toBe(true);
});
- test('an outer layout change that leaves the editor column width alone does not swallow the next inner resize', async () => {
+ test('a side-panel drag the library starts beside the divider takes the drag lock, marks the inner row, and re-pins on release', async () => {
const resizeObserver = installResizeObserver();
try {
- const agentsChanges: boolean[] = [];
- await renderWideRowsWithTerminalAndChat(agentsChanges);
- act(() => groupOnLayoutChange?.(groupLayout));
- resizeObserver.fire('[data-editor-inner-panels]');
- await flushFrame();
+ setViewportWidth(1400);
+ docCtx = DOC_LIVE_CTX;
+ innerLayout = innerRowWithDoc(320, 1360);
+ render(<EditorArea {...rowProps} agentsVisible />);
+ await act(async () => {});
+ const innerRow = screen.getByTestId('resizable-group-inner');
+ expect(innerRow.getAttribute('data-dragging')).toBeNull();
- groupLayout = {
- 'editor-main': groupLayout['editor-main'],
- 'terminal-column': pctOfRow(700, 2000),
- 'agents-column': pctOfRow(520, 2000),
- };
- act(() => groupOnLayoutChange?.(groupLayout));
- groupSetLayoutCalls = [];
- innerSetLayoutCalls = [];
+ docHandle().setAttribute('data-separator', 'active');
+ innerLayout = innerRowWithDoc(360, 1360);
+ act(() => {
+ innerOnLayoutChange?.(innerLayout);
+ });
+ expect(innerRow.getAttribute('data-dragging')).toBe('true');
- innerLayout = innerRowWithDoc(300, 2000 - 740 - 480);
+ innerSetLayoutCalls = [];
+ mockEditorUnitPx = 1000;
resizeObserver.fire('[data-editor-inner-panels]');
await flushFrame();
+ expect(innerSetLayoutCalls).toHaveLength(0);
+ docHandle().removeAttribute('data-separator');
+ act(() => {
+ fireEvent.pointerUp(window, { pointerId: 7 });
+ });
+ expect(innerRow.getAttribute('data-dragging')).toBeNull();
expect(innerSetLayoutCalls.length).toBeGreaterThan(0);
- expect(lastInnerWritePx('doc-panel')).toBeCloseTo(320, 0);
} finally {
resizeObserver.restore();
}
});
- test('the inner row observer still re-plans after an outer row layout change when the last plan left a pin unplaced', async () => {
+ test('every side-panel drag end re-pins the side panel width', async () => {
+ setViewportWidth(1400);
+ docCtx = DOC_LIVE_CTX;
+ innerLayout = innerRowWithDoc(320, 1360);
+ render(<EditorArea {...rowProps} agentsVisible />);
+ await act(async () => {});
+ innerLayout = innerRowWithDoc(300, 1360);
+ innerSetLayoutCalls = [];
+
+ act(() => {
+ fireEvent.pointerDown(docHandle(), { pointerId: 1 });
+ });
+ expect(innerSetLayoutCalls).toHaveLength(0);
+ act(() => {
+ fireEvent.pointerUp(window, { pointerId: 1 });
+ });
+
+ expect(lastInnerWritePx('doc-panel')).toBeCloseTo(320, 3);
+ });
+
+ test('the inner row observer re-pins the side panel width on its own', async () => {
const resizeObserver = installResizeObserver();
try {
- const agentsChanges: boolean[] = [];
- await renderWideRowsWithTerminalAndChat(agentsChanges);
-
- mockGroupPx = 0;
- resizeObserver.fire('[data-editor-area-panels]');
- await flushFrame();
- expect(agentsChanges).toEqual([]);
- groupSetLayoutCalls = [];
+ setViewportWidth(2000);
+ mockPanelPx = 320;
+ docCtx = DOC_LIVE_CTX;
+ innerLayout = innerRowWithDoc(320, 1360);
+ render(<EditorArea {...rowProps} agentsVisible />);
+ await act(async () => {});
innerSetLayoutCalls = [];
- mockGroupPx = 1000;
- act(() => groupOnLayoutChange?.(groupLayout));
+ mockEditorUnitPx = 1000;
resizeObserver.fire('[data-editor-inner-panels]');
await flushFrame();
- expect(groupSetLayoutCalls.length).toBeGreaterThan(0);
- expect(agentsChanges).toEqual([false]);
- expect(toastInfoMessages).toEqual(['Agent panel closed to keep Terminal readable.']);
+ expect(lastInnerWritePx('doc-panel')).toBeCloseTo(320, 3);
} finally {
resizeObserver.restore();
}
});
- test('the observers stay off inside an embedded host', () => {
+ test('the inner row observer stays off inside an embedded host', async () => {
const resizeObserver = installResizeObserver();
const originalUserAgent = navigator.userAgent;
Object.defineProperty(navigator, 'userAgent', {
@@ -5137,11 +2239,10 @@ describe('EditorArea editor card rows', () => {
setViewportWidth(1400);
docCtx = DOC_LIVE_CTX;
render(<EditorArea {...rowProps} agentsVisible />);
- expect(() => resizeObserver.fire('[data-editor-area-panels]')).toThrow(/not observed/);
- groupSetLayoutCalls = [];
innerSetLayoutCalls = [];
+ mockEditorUnitPx = 1000;
resizeObserver.fire('[data-editor-inner-panels]');
- expect(groupSetLayoutCalls).toHaveLength(0);
+ await flushFrame();
expect(innerSetLayoutCalls).toHaveLength(0);
} finally {
Object.defineProperty(navigator, 'userAgent', {
@@ -5159,118 +2260,22 @@ describe('EditorArea terminal and chat cards', () => {
onModeChange: () => {},
activeTab: 'timeline',
onActiveTabChange: () => {},
- onAgentsVisibleChange: () => {},
- onTerminalVisibleChange: () => {},
} as const;
const setViewportWidth = (px: number) => {
Object.defineProperty(window, 'innerWidth', { value: px, configurable: true, writable: true });
};
- const pctOfRow = (px: number, rowPx: number) => (px / rowPx) * 100;
- const cardOf = (pane: PaneId) =>
- document.querySelector<HTMLElement>(`[data-slot="pane-card"][data-pane="${pane}"]`);
+ const cardOf = paneCard;
beforeEach(() => {
cleanup();
localStorage.clear();
docCtx = DOC_LIVE_CTX;
- groupLayout = {};
- groupSetLayoutCalls = [];
- rejectNextGroupLayoutWrite = false;
- rejectGroupLayoutWrites = false;
panelIsCollapsed = false;
- mockGroupPx = 1360;
- mockPanelPercentage = null;
- mockPanelPx = null;
- toastInfoMessages = [];
+ mockEditorUnitPx = 1360;
editorWorkspaceMounts = 0;
setViewportWidth(1400);
});
- test('a right terminal and chat are their own cards in their columns, and the editor card sits inside the terminal split', () => {
- render(
- <TooltipProvider>
- <EditorArea
- {...cardProps}
- terminalBridge={{} as never}
- terminalVisible
- terminalPlacement="right"
- agentsVisible
- />
- </TooltipProvider>,
- );
-
- const editorCard = cardOf('editor');
- const terminalCard = cardOf('terminal');
- const chatCard = cardOf('agents');
- expect(terminalCard?.getAttribute('data-placement')).toBe('right');
- expect(terminalCard?.getAttribute('data-variant')).toBe('card');
- expect(chatCard?.getAttribute('data-variant')).toBe('card');
- expect(document.getElementById('terminal-column')?.contains(terminalCard)).toBe(true);
- expect(document.getElementById('agents-column')?.contains(chatCard)).toBe(true);
- expect(terminalCard?.contains(document.querySelector('[data-terminal-panel-mount]'))).toBe(
- true,
- );
- expect(chatCard?.contains(document.querySelector('[data-agents-panel-mount]'))).toBe(true);
- expect(screen.getByTestId('terminal-dock').contains(editorCard)).toBe(true);
- expect(editorCard?.contains(terminalCard)).toBe(false);
- expect(editorCard?.contains(chatCard)).toBe(false);
- });
-
- test('without a terminal, as on the web, the terminal column keeps its mount but draws no card', () => {
- render(
- <TooltipProvider>
- <EditorArea {...cardProps} agentsVisible />
- </TooltipProvider>,
- );
-
- expect(cardOf('terminal')).toBeNull();
- expect(cardOf('agents')).not.toBeNull();
- expect(
- document
- .getElementById('terminal-column')
- ?.contains(document.querySelector('[data-terminal-panel-mount]')),
- ).toBe(true);
- });
-
- test('the chat and right terminal cards cast their shadow only while their column shows', () => {
- const area = (visible: boolean) => (
- <TooltipProvider>
- <EditorArea
- {...cardProps}
- terminalBridge={{} as never}
- terminalVisible={visible}
- terminalPlacement="right"
- agentsVisible={visible}
- />
- </TooltipProvider>
- );
- const expectShadow = (casting: boolean) => {
- for (const pane of ['terminal', 'agents'] as const) {
- const card = cardOf(pane);
- expect(card, `${pane} card`).not.toBeNull();
- if (casting) expectVisualClassTokensAbsent(card?.className, ['shadow-none']);
- else expectVisualClassTokens(card?.className, ['shadow-none']);
- }
- };
- const view = render(area(true));
- expectShadow(true);
-
- act(() => {
- railPanelOnResizeById.get(TERMINAL_COLUMN_ID)?.({ asPercentage: 0, inPixels: 0 });
- railPanelOnResizeById.get(AGENTS_COLUMN_ID)?.({ asPercentage: 0, inPixels: 0 });
- });
- expectShadow(false);
-
- act(() => {
- railPanelOnResizeById.get(TERMINAL_COLUMN_ID)?.({ asPercentage: 25, inPixels: 300 });
- railPanelOnResizeById.get(AGENTS_COLUMN_ID)?.({ asPercentage: 25, inPixels: 300 });
- });
- expectShadow(true);
-
- view.rerender(area(false));
- expectShadow(false);
- });
-
test('main wraps the document column; the file list, chat and the side panel sit outside it as their own landmarks', () => {
render(
<TooltipProvider>
@@ -5317,7 +2322,7 @@ describe('EditorArea terminal and chat cards', () => {
fireEvent.click(toggles[0] as Element);
act(() => {
- railPanelOnResizeById.get('doc-panel')?.({ asPercentage: 0, inPixels: 0 });
+ panelOnResizeById.get('doc-panel')?.({ asPercentage: 0, inPixels: 0 });
});
expect(document.querySelector('[data-doc-panel-toggle]')?.getAttribute('aria-expanded')).toBe(
'false',
@@ -5354,45 +2359,6 @@ describe('EditorArea terminal and chat cards', () => {
expect(document.querySelector('[data-doc-panel-toggle]')).toBeNull();
});
- test('moving or hiding the terminal, and showing or hiding chat, never remounts the open editor', () => {
- const props = { ...cardProps, terminalBridge: {} as never };
- const { rerender } = render(
- <TooltipProvider>
- <EditorArea {...props} terminalVisible terminalPlacement="bottom" agentsVisible={false} />
- </TooltipProvider>,
- );
- const tabs = screen.getByTestId('workspace-tabs');
- const editorRegion = document.querySelector('[data-editor-region]');
- expect(editorWorkspaceMounts).toBe(1);
-
- const steps: Array<{
- terminalVisible: boolean;
- terminalPlacement: 'bottom' | 'right';
- agentsVisible: boolean;
- }> = [
- { terminalVisible: true, terminalPlacement: 'right', agentsVisible: false },
- { terminalVisible: true, terminalPlacement: 'right', agentsVisible: true },
- { terminalVisible: false, terminalPlacement: 'right', agentsVisible: true },
- { terminalVisible: true, terminalPlacement: 'bottom', agentsVisible: true },
- { terminalVisible: false, terminalPlacement: 'bottom', agentsVisible: false },
- { terminalVisible: true, terminalPlacement: 'bottom', agentsVisible: false },
- ];
- for (const step of steps) {
- rerender(
- <TooltipProvider>
- <EditorArea {...props} {...step} />
- </TooltipProvider>,
- );
- }
- act(() => emitLocalMenuAction('toggle-doc-panel'));
- act(() => emitLocalMenuAction('toggle-doc-panel'));
-
- expect(editorWorkspaceMounts).toBe(1);
- expect(screen.getByTestId('workspace-tabs')).toBe(tabs);
- expect(document.querySelector('[data-editor-region]')).toBe(editorRegion);
- expect(screen.getByRole('main').contains(tabs)).toBe(true);
- });
-
test('a single-file window renders every normal card', () => {
Object.defineProperty(window, 'okDesktop', {
configurable: true,
@@ -5409,7 +2375,7 @@ describe('EditorArea terminal and chat cards', () => {
{...cardProps}
terminalBridge={{} as never}
terminalVisible
- terminalPlacement="right"
+ dockTree={RIGHT_TERMINAL_TREE}
agentsVisible
/>
</SingleFileModeProvider>
@@ -5457,143 +2423,6 @@ describe('EditorArea terminal and chat cards', () => {
);
expect(screen.getByTestId('bottom-composer')).toBeTruthy();
});
-
- test('the joint plan keeps a minimum width for Chat beside a right Terminal in both shared card shells', async () => {
- const initialOuterWidthPx = 1600;
- const outerWidthPx = 1128;
- const planAgentsWidth = async (singleFile: boolean) => {
- cleanup();
- localStorage.clear();
- localStorage.setItem(AGENTS_PANEL_WIDTH_KEY, '480');
- localStorage.setItem(DOC_PANEL_WIDTH_KEY, '320');
- localStorage.setItem(
- SIDEBAR_PINS_KEY,
- JSON.stringify({ right: { above: 'open', below: 'open', embedded: 'open' } }),
- );
- setViewportWidth(initialOuterWidthPx);
- mockGroupPx = initialOuterWidthPx;
- mockInnerPx = null;
- mockFileListPx = 0;
- mockPanelPx = null;
- mockPanelPercentage = null;
- panelIsCollapsed = false;
- panelRefCalls = 0;
- lastDeliveredDocPanelSize = null;
- deliverDocPanelResizeAfterLayout = true;
- railPanelOnResizeById.clear();
- groupLayout = {
- 'editor-main': 100 - pctOfRow(RIGHT_TERMINAL_PANEL_MIN_WIDTH_PX + 480, initialOuterWidthPx),
- 'terminal-column': pctOfRow(RIGHT_TERMINAL_PANEL_MIN_WIDTH_PX, initialOuterWidthPx),
- 'agents-column': pctOfRow(480, initialOuterWidthPx),
- };
- innerLayout = innerRowWithDoc(
- 320,
- initialOuterWidthPx - RIGHT_TERMINAL_PANEL_MIN_WIDTH_PX - 480,
- );
- committedGroupLayout = { ...groupLayout };
- committedInnerLayout = { ...innerLayout };
- groupSetLayoutCalls = [];
- innerSetLayoutCalls = [];
- innerSetLayoutPx = [];
- toastInfoMessages = [];
- Reflect.deleteProperty(window, 'okDesktop');
- if (singleFile) {
- Object.defineProperty(window, 'okDesktop', {
- configurable: true,
- value: {
- config: { singleFile: true },
- editor: { notifyViewMenuStateChanged: () => {} },
- },
- });
- }
- const resizeObserver = installResizeObserver();
- try {
- const withColumns = {
- ...cardProps,
- terminalBridge: {} as never,
- terminalVisible: true,
- terminalPlacement: 'right',
- terminalRightWidth: RIGHT_TERMINAL_PANEL_MIN_WIDTH_PX,
- } as const;
- const wrap = (node: ReactNode) =>
- singleFile ? (
- <TooltipProvider>
- <SingleFileModeProvider>{node}</SingleFileModeProvider>
- </TooltipProvider>
- ) : (
- <TooltipProvider>{node}</TooltipProvider>
- );
- render(wrap(<EditorArea {...withColumns} agentsVisible />));
- const card = cardOf('editor');
- const inner = document.querySelector<HTMLElement>('[data-editor-inner-panels]');
- if (card == null || inner == null)
- throw new Error('the editor card or inner row is absent');
- for (const element of [card, inner]) {
- Object.defineProperty(element, 'getBoundingClientRect', {
- configurable: true,
- value: () => ({ width: rowPx('inner'), height: 0, top: 0, left: 0 }),
- });
- }
- resizeObserver.fire('[data-slot="pane-card"][data-pane="editor"]');
- resizeObserver.fire('[data-editor-inner-panels]');
- await act(async () => {});
- const initialInfoWidthPx = document
- .getElementById('doc-panel')
- ?.getBoundingClientRect().width;
- const initialDocumentWidthPx = innerResidualWidthPx();
- const initialCardWidthPx = card.getBoundingClientRect().width;
- groupSetLayoutCalls = [];
- setViewportWidth(outerWidthPx);
- mockGroupPx = outerWidthPx;
- resizeObserver.fire('[data-slot="pane-card"][data-pane="editor"]');
- resizeObserver.fire('[data-editor-area-panels]');
- resizeObserver.fire('[data-editor-inner-panels]');
- resizeObserver.fire('[data-slot="pane-card"][data-pane="editor"]');
- await act(async () => {});
- return {
- initialInfoWidthPx,
- initialDocumentWidthPx,
- initialCardWidthPx,
- chatWidthPx: document.getElementById(AGENTS_COLUMN_ID)?.getBoundingClientRect().width,
- terminalWidthPx: document.getElementById(TERMINAL_COLUMN_ID)?.getBoundingClientRect()
- .width,
- infoWidthPx: document.getElementById('doc-panel')?.getBoundingClientRect().width,
- documentWidthPx: innerResidualWidthPx(),
- cardWidthPx: card.getBoundingClientRect().width,
- chatLayoutWrites: groupSetLayoutCalls.filter((layout) => layout[AGENTS_COLUMN_ID] > 0)
- .length,
- toasts: [...toastInfoMessages],
- };
- } finally {
- cleanup();
- resizeObserver.restore();
- Reflect.deleteProperty(window, 'okDesktop');
- }
- };
-
- const project = await planAgentsWidth(false);
- const singleFile = await planAgentsWidth(true);
- for (const variant of [project, singleFile]) {
- expect(variant.initialCardWidthPx).toBeCloseTo(
- initialOuterWidthPx - RIGHT_TERMINAL_PANEL_MIN_WIDTH_PX - 480,
- 0,
- );
- expect(variant.initialInfoWidthPx).toBeCloseTo(320, 0);
- expect(variant.initialDocumentWidthPx).toBeGreaterThanOrEqual(300);
- expect(variant.chatLayoutWrites).toBeGreaterThan(0);
- expect(variant.chatWidthPx).toBeGreaterThanOrEqual(MIN_AGENTS_PANEL_WIDTH);
- expect(variant.chatWidthPx).toBeCloseTo(480, 0);
- expect(variant.terminalWidthPx).toBeCloseTo(RIGHT_TERMINAL_PANEL_MIN_WIDTH_PX, 0);
- expect(variant.infoWidthPx).toBe(0);
- expect(variant.documentWidthPx).toBeGreaterThanOrEqual(300);
- expect(variant.cardWidthPx).toBeCloseTo(
- outerWidthPx - RIGHT_TERMINAL_PANEL_MIN_WIDTH_PX - 480,
- 0,
- );
- expect(variant.toasts).toEqual([]);
- }
- expect(singleFile.chatWidthPx).toBeCloseTo(project.chatWidthPx, 3);
- });
});
describe('EditorArea with the editor hidden', () => {
@@ -5603,43 +2432,23 @@ describe('EditorArea with the editor hidden', () => {
activeTab: 'timeline',
onActiveTabChange: () => {},
terminalBridge: {} as never,
- onAgentsVisibleChange: () => {},
- onTerminalVisibleChange: () => {},
} as const;
- const ROW_PX = 1360;
- const pctOfRow = (px: number) => (px / ROW_PX) * 100;
- const editorColumn = () => {
- const column = document.querySelector<HTMLElement>(
- '[data-editor-row="outer"] > [data-panel]:not([id])',
- );
- if (column == null) throw new Error('editor column not rendered');
- return column;
- };
- const agentsHandle = () => {
- const handle = document.querySelector<HTMLElement>('[data-agents-panel-resize-handle]');
- if (handle == null) throw new Error('agents resize handle not found');
- return handle;
- };
- const terminalHandle = () => {
- const handle = document.querySelector<HTMLElement>('[data-terminal-panel-handle]');
- if (handle == null) throw new Error('terminal resize handle not found');
- return handle;
- };
const settle = () => act(async () => {});
+ const unitStyles = () =>
+ (['editor', 'agents', 'terminal'] as const).map((pane) => dockUnit(pane).getAttribute('style'));
+ const rowShare = (tree: DockNode, pane: PaneId) => {
+ if (!('items' in tree)) throw new Error('expected a row of panes');
+ const item = tree.items.find(({ node }) => 'pane' in node && node.pane === pane);
+ if (item === undefined) throw new Error(`${pane} is not in the row`);
+ return item.size;
+ };
beforeEach(() => {
cleanup();
localStorage.clear();
docCtx = DOC_LIVE_CTX;
- groupLayout = {};
- groupSetLayoutCalls = [];
- rejectNextGroupLayoutWrite = false;
- rejectGroupLayoutWrites = false;
panelIsCollapsed = false;
- mockGroupPx = ROW_PX;
- mockPanelPercentage = null;
- mockPanelPx = null;
- toastInfoMessages = [];
+ mockEditorUnitPx = 1360;
Object.defineProperty(window, 'innerWidth', {
value: 1400,
configurable: true,
@@ -5647,24 +2456,19 @@ describe('EditorArea with the editor hidden', () => {
});
});
- test('chat alone fills the row and the editor column may reach zero', async () => {
+ test('chat alone fills the workspace while the editor keeps its last size out of reach', async () => {
const view = render(<EditorArea {...hiddenProps} agentsVisible />);
- groupLayout = { 'editor-main': 65, 'terminal-column': 0, 'agents-column': 35 };
await settle();
- const innerWritesBeforeHide = innerSetLayoutCalls.length;
+ const editorWidth = unitPx('editor', 'width');
view.rerender(<EditorArea {...hiddenProps} agentsVisible editorVisible={false} />);
await settle();
- expect(groupSetLayoutCalls.at(-1)).toEqual({
- 'editor-main': 0,
- 'terminal-column': 0,
- 'agents-column': 100,
- });
- expect(innerSetLayoutCalls).toHaveLength(innerWritesBeforeHide);
- expect(editorColumn().getAttribute('data-min-size')).toBe('0%');
- expect(document.getElementById('agents-column')?.getAttribute('data-max-size')).toBe('100%');
- expect(agentsHandle().style.display).toBe('none');
+ expect(unitPx('agents', 'insetInlineStart')).toBe(0);
+ expect(unitPx('agents', 'width')).toBe(WORKSPACE_WIDTH_PX);
+ expect(dockUnit('editor').hasAttribute('data-dock-unit-off')).toBe(true);
+ expect(unitPx('editor', 'width')).toBe(editorWidth);
+ expect(document.querySelectorAll('[data-dock-seam]')).toHaveLength(0);
});
test.each([
@@ -5675,8 +2479,8 @@ describe('EditorArea with the editor hidden', () => {
},
{
pane: 'a right Terminal',
- open: { terminalVisible: true, terminalPlacement: 'right' },
- closed: { terminalVisible: false, terminalPlacement: 'right' },
+ open: { terminalVisible: true, dockTree: RIGHT_TERMINAL_TREE },
+ closed: { terminalVisible: false, dockTree: RIGHT_TERMINAL_TREE },
},
] as const)(
'closing $pane while the editor is hidden mounts no composer until the editor shows',
@@ -5712,18 +2516,10 @@ describe('EditorArea with the editor hidden', () => {
},
);
- test('a right terminal and chat share the row in proportion to their current widths', async () => {
- groupLayout = { 'editor-main': 40, 'terminal-column': 25, 'agents-column': 35 };
+ test('a right terminal and chat share the workspace in proportion to their shares of the tree', async () => {
const view = render(
- <EditorArea
- {...hiddenProps}
- agentsVisible
- terminalVisible
- terminalPlacement="right"
- terminalRightWidth={400}
- />,
+ <EditorArea {...hiddenProps} agentsVisible terminalVisible dockTree={RIGHT_TERMINAL_TREE} />,
);
- groupLayout = { 'editor-main': 40, 'terminal-column': 25, 'agents-column': 35 };
await settle();
view.rerender(
@@ -5731,76 +2527,59 @@ describe('EditorArea with the editor hidden', () => {
{...hiddenProps}
agentsVisible
terminalVisible
- terminalPlacement="right"
- terminalRightWidth={400}
+ dockTree={RIGHT_TERMINAL_TREE}
editorVisible={false}
/>,
);
await settle();
- const written = groupSetLayoutCalls.at(-1);
- expect(written?.['editor-main']).toBe(0);
- expect(written?.['terminal-column']).toBeCloseTo((25 / (25 + 35)) * 100);
- expect(written?.['agents-column']).toBeCloseTo((35 / (25 + 35)) * 100);
- expect(terminalHandle().style.display).toBe('none');
- expect(agentsHandle().style.display).toBe('');
+ const terminalWidth = unitPx('terminal', 'width');
+ const agentsWidth = unitPx('agents', 'width');
+ expect(unitPx('terminal', 'insetInlineStart')).toBe(0);
+ expect(unitPx('agents', 'insetInlineStart') + agentsWidth).toBe(WORKSPACE_WIDTH_PX);
+ expect(terminalWidth / agentsWidth).toBeCloseTo(
+ rowShare(RIGHT_TERMINAL_TREE, 'terminal') / rowShare(RIGHT_TERMINAL_TREE, 'agents'),
+ 2,
+ );
});
- test('with no right column the editor column keeps the row and nothing is written', async () => {
- const view = render(<EditorArea {...hiddenProps} />);
- groupLayout = { 'editor-main': 100, 'terminal-column': 0, 'agents-column': 0 };
- await settle();
- const writesBeforeHide = groupSetLayoutCalls.length;
-
- view.rerender(<EditorArea {...hiddenProps} editorVisible={false} />);
+ test('showing the editor again restores the layout it had before it was hidden', async () => {
+ const changes: DockNode[] = [];
+ const area = (editorVisible: boolean) => (
+ <EditorArea
+ {...hiddenProps}
+ agentsVisible
+ terminalVisible
+ editorVisible={editorVisible}
+ onDockTreeChange={(update) => changes.push(update(DEFAULT_DOCK_TREE))}
+ />
+ );
+ const view = render(area(true));
await settle();
+ const before = unitStyles();
- expect(groupSetLayoutCalls).toHaveLength(writesBeforeHide);
- expect(editorColumn().getAttribute('data-min-size')).toBe('0%');
- });
-
- test('showing the editor re-plans both rows back to the pre-hide chat width', async () => {
- const view = render(<EditorArea {...hiddenProps} agentsVisible />);
- groupLayout = { 'editor-main': 65, 'terminal-column': 0, 'agents-column': 35 };
- await settle();
- view.rerender(<EditorArea {...hiddenProps} agentsVisible editorVisible={false} />);
+ view.rerender(area(false));
await settle();
- expect(groupLayout['agents-column']).toBe(100);
- const innerWritesWhileHidden = innerSetLayoutCalls.length;
-
- view.rerender(<EditorArea {...hiddenProps} agentsVisible />);
+ expect(unitStyles()).not.toEqual(before);
+ view.rerender(area(true));
await settle();
- const chatPct = pctOfRow(getInitialAgentsPanelWidth());
- expect(groupLayout['agents-column']).toBeCloseTo(chatPct);
- expect(groupLayout['editor-main']).toBeCloseTo(100 - chatPct);
- expect(editorColumn().getAttribute('data-min-size')).toBe('5%');
- expect(document.getElementById('agents-column')?.getAttribute('data-max-size')).toBe('95%');
- expect(agentsHandle().style.display).toBe('');
- expect(innerSetLayoutCalls.length).toBeGreaterThanOrEqual(innerWritesWhileHidden);
+ expect(unitStyles()).toEqual(before);
+ expect(changes).toEqual([]);
});
- const editorCard = () => {
- const card = document.querySelector<HTMLElement>('[data-slot="pane-card"][data-pane="editor"]');
- if (card == null) throw new Error('editor card not rendered');
- return card;
- };
-
- test('hiding keeps the same editor card, workspace and file list mounted, pinned at their size and out of reach', async () => {
+ test('hiding keeps the same editor card, workspace and file list mounted, at their size and out of reach', async () => {
const view = render(
<FileListHostProvider enabled>
<EditorArea {...hiddenProps} agentsVisible />
</FileListHostProvider>,
);
- groupLayout = { 'editor-main': 65, 'terminal-column': 0, 'agents-column': 35 };
await settle();
- const card = editorCard();
+ const card = paneCard('editor');
const fileListSlot = document.querySelector('[data-editor-file-list-slot]');
const tabsTarget = document.querySelector('[data-editor-area-header]');
- Object.defineProperty(card, 'getBoundingClientRect', {
- configurable: true,
- value: () => ({ width: 840, height: 610, top: 0, left: 0, right: 840, bottom: 610 }),
- });
+ const width = unitPx('editor', 'width');
+ const height = unitPx('editor', 'height');
const workspaceMountsBefore = editorWorkspaceMounts;
view.rerender(
@@ -5810,15 +2589,15 @@ describe('EditorArea with the editor hidden', () => {
);
await settle();
- expect(editorCard()).toBe(card);
+ expect(paneCard('editor')).toBe(card);
expect(document.querySelector('[data-editor-file-list-slot]')).toBe(fileListSlot);
expect(document.querySelector('[data-editor-area-header]')).toBe(tabsTarget);
expect(editorWorkspaceMounts).toBe(workspaceMountsBefore);
- expect(card.hasAttribute('inert')).toBe(true);
- expect(card.classList.contains('invisible')).toBe(true);
- expect(card.style.width).toBe('840px');
- expect(card.style.height).toBe('610px');
- expect(editorColumn().style.overflow).toBe('hidden');
+ expect(card?.hasAttribute('inert')).toBe(true);
+ expect(dockUnit('editor').hasAttribute('inert')).toBe(true);
+ expect(dockUnit('editor').classList.contains('invisible')).toBe(true);
+ expect(unitPx('editor', 'width')).toBe(width);
+ expect(unitPx('editor', 'height')).toBe(height);
view.rerender(
<FileListHostProvider enabled>
@@ -5826,15 +2605,12 @@ describe('EditorArea with the editor hidden', () => {
</FileListHostProvider>,
);
await settle();
- await act(() => new Promise<void>((resolve) => requestAnimationFrame(() => resolve())));
- expect(groupLayout['editor-main']).toBeGreaterThan(0);
- expect(editorCard()).toBe(card);
+ expect(paneCard('editor')).toBe(card);
expect(editorWorkspaceMounts).toBe(workspaceMountsBefore);
- expect(card.hasAttribute('inert')).toBe(false);
- expect(card.classList.contains('invisible')).toBe(false);
- expect(card.style.width).toBe('');
- expect(editorColumn().style.overflow).toBe('visible');
+ expect(card?.hasAttribute('inert')).toBe(false);
+ expect(dockUnit('editor').hasAttribute('inert')).toBe(false);
+ expect(dockUnit('editor').classList.contains('invisible')).toBe(false);
});
test('hiding the editor while focus is inside it moves focus to the header Editor button', async () => {
@@ -5896,81 +2672,49 @@ describe('EditorArea with the editor hidden', () => {
composer.remove();
});
- test('a chat divider dragged while the editor is hidden is not saved, and showing the editor restores the pre-hide widths', async () => {
- vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
- try {
- const pastWidthWriteDebounceMs = 101;
- const terminalWidths: number[] = [];
- const props = {
- ...hiddenProps,
- agentsVisible: true,
- terminalVisible: true,
- terminalPlacement: 'right',
- terminalRightWidth: 400,
- onTerminalRightWidthChange: (px: number) => terminalWidths.push(px),
- } as const;
- const view = render(<EditorArea {...props} />);
- groupLayout = { 'editor-main': 40, 'terminal-column': 25, 'agents-column': 35 };
- await settle();
-
- fireEvent.pointerDown(terminalHandle(), { pointerId: 6 });
- act(() => {
- railPanelOnResizeById.get('terminal-column')?.({
- asPercentage: pctOfRow(400),
- inPixels: 400,
- });
- });
- act(() => {
- window.dispatchEvent(new PointerEvent('pointerup', { pointerId: 6 }));
- });
- act(() => vi.advanceTimersByTime(pastWidthWriteDebounceMs));
- expect(terminalWidths).toEqual([400]);
-
- view.rerender(<EditorArea {...props} editorVisible={false} />);
- await settle();
- const preferredChatPx = getInitialAgentsPanelWidth();
-
- fireEvent.pointerDown(agentsHandle(), { pointerId: 7 });
- groupLayout = { 'editor-main': 0, 'terminal-column': 30, 'agents-column': 70 };
- mockPanelPx = 0.7 * ROW_PX;
- act(() => {
- railPanelOnResizeById.get('terminal-column')?.({
- asPercentage: 30,
- inPixels: 0.3 * ROW_PX,
- });
- });
- act(() => {
- window.dispatchEvent(new PointerEvent('pointerup', { pointerId: 7 }));
- });
- await settle();
-
- expect(groupLayout).toEqual({ 'editor-main': 0, 'terminal-column': 30, 'agents-column': 70 });
- expect(localStorage.getItem(AGENTS_PANEL_WIDTH_KEY)).toBeNull();
- act(() => vi.advanceTimersByTime(pastWidthWriteDebounceMs));
- expect(terminalWidths).toEqual([400]);
+ test('a seam moved while the editor is hidden leaves the editor share alone', async () => {
+ const trees: DockNode[] = [];
+ function DockHost({ editorVisible }: { editorVisible: boolean }) {
+ const [tree, setTree] = useState<DockNode>(RIGHT_TERMINAL_TREE);
+ return (
+ <EditorArea
+ {...hiddenProps}
+ agentsVisible
+ terminalVisible
+ editorVisible={editorVisible}
+ dockTree={tree}
+ onDockTreeChange={(update) => {
+ const next = update(tree);
+ trees.push(next);
+ setTree(next);
+ }}
+ />
+ );
+ }
+ const view = render(<DockHost editorVisible />);
+ await settle();
+ view.rerender(<DockHost editorVisible={false} />);
+ await settle();
+ const terminalWidth = unitPx('terminal', 'width');
- mockPanelPx = null;
- view.rerender(<EditorArea {...props} />);
- await settle();
- await act(() => new Promise<void>((resolve) => requestAnimationFrame(() => resolve())));
+ fireEvent.keyDown(dockSeam('Resize Agents'), { key: 'ArrowRight', shiftKey: true });
+ await settle();
- expect(groupLayout['agents-column']).toBeCloseTo(pctOfRow(preferredChatPx));
- expect(groupLayout['terminal-column']).toBeCloseTo(pctOfRow(400));
- } finally {
- vi.useRealTimers();
- }
+ const moved = trees.at(-1);
+ if (moved === undefined) throw new Error('the seam reported no tree');
+ expect(unitPx('terminal', 'width')).toBeGreaterThan(terminalWidth);
+ expect(rowShare(moved, 'editor')).toBeCloseTo(rowShare(RIGHT_TERMINAL_TREE, 'editor'), 10);
+ expect(rowShare(moved, 'terminal')).toBeGreaterThan(rowShare(RIGHT_TERMINAL_TREE, 'terminal'));
});
test('chat is marked as the only pane only while the editor is hidden and no terminal shows', async () => {
- const mount = () => document.querySelector('[data-agents-panel-mount]');
const view = render(<EditorArea {...hiddenProps} agentsVisible />);
- groupLayout = { 'editor-main': 65, 'terminal-column': 0, 'agents-column': 35 };
await settle();
- expect(mount()?.hasAttribute('data-chat-alone')).toBe(false);
+ expect(agentsMount()?.hasAttribute('data-chat-alone')).toBe(false);
view.rerender(<EditorArea {...hiddenProps} agentsVisible editorVisible={false} />);
await settle();
- expect(mount()?.hasAttribute('data-chat-alone')).toBe(true);
+ expect(agentsMount()?.hasAttribute('data-chat-alone')).toBe(true);
view.rerender(
<EditorArea
@@ -5978,11 +2722,11 @@ describe('EditorArea with the editor hidden', () => {
agentsVisible
editorVisible={false}
terminalVisible
- terminalPlacement="right"
+ dockTree={RIGHT_TERMINAL_TREE}
/>,
);
await settle();
- expect(mount()?.hasAttribute('data-chat-alone')).toBe(false);
+ expect(agentsMount()?.hasAttribute('data-chat-alone')).toBe(false);
});
test('Nothing open appears only when the editor, chat and terminal are all hidden', async () => {
@@ -6011,94 +2755,21 @@ describe('EditorArea with the editor hidden', () => {
expect(document.activeElement).toBe(document.querySelector('[data-nothing-open]'));
});
- test('a column closing while the editor is hidden hands its width to the other column, not the hidden editor', async () => {
- const view = render(
- <EditorArea {...hiddenProps} agentsVisible terminalVisible terminalPlacement="right" />,
- );
- groupLayout = { 'editor-main': 40, 'terminal-column': 25, 'agents-column': 35 };
- await settle();
- view.rerender(
- <EditorArea
- {...hiddenProps}
- agentsVisible
- terminalVisible
- terminalPlacement="right"
- editorVisible={false}
- />,
- );
- await settle();
-
- view.rerender(
- <EditorArea
- {...hiddenProps}
- agentsVisible={false}
- terminalVisible
- terminalPlacement="right"
- editorVisible={false}
- />,
- );
- act(() => {
- railPanelOnResizeById.get('agents-column')?.({ asPercentage: 40, inPixels: 544 });
- });
- await settle();
-
- expect(groupLayout).toEqual({ 'editor-main': 0, 'terminal-column': 100, 'agents-column': 0 });
- });
-
- test('hiding the editor beside chat keeps the column that holds a bottom terminal at its share', async () => {
- const props = { ...hiddenProps, agentsVisible: true, terminalVisible: true } as const;
- groupLayout = { 'editor-main': 65, 'terminal-column': 0, 'agents-column': 35 };
- const view = render(<EditorArea {...props} terminalPlacement="bottom" />);
- groupLayout = { 'editor-main': 65, 'terminal-column': 0, 'agents-column': 35 };
- await settle();
-
- view.rerender(<EditorArea {...props} terminalPlacement="bottom" editorVisible={false} />);
- await settle();
-
- expect(groupLayout).toEqual({ 'editor-main': 65, 'terminal-column': 0, 'agents-column': 35 });
- expect(editorColumn().getAttribute('data-min-size')).toBe('5%');
- expect(document.getElementById('agents-column')?.getAttribute('data-max-size')).toBe('95%');
- expect(agentsHandle().style.display).toBe('');
- });
-
- test('a bottom terminal opened beside chat alone takes back the column at chat’s preferred width', async () => {
- const view = render(<EditorArea {...hiddenProps} agentsVisible editorVisible={false} />);
- groupLayout = { 'editor-main': 0, 'terminal-column': 0, 'agents-column': 100 };
- await settle();
-
- view.rerender(
- <EditorArea
- {...hiddenProps}
- agentsVisible
- terminalVisible
- terminalPlacement="bottom"
- editorVisible={false}
- />,
+ test('hiding the editor above a bottom terminal hands the column to the terminal and keeps chat at its share', async () => {
+ const area = (editorVisible: boolean) => (
+ <EditorArea {...hiddenProps} agentsVisible terminalVisible editorVisible={editorVisible} />
);
+ const view = render(area(true));
await settle();
+ const agentsStyle = dockUnit('agents').getAttribute('style');
+ const columnWidth = unitPx('editor', 'width');
- const chatPct = pctOfRow(getInitialAgentsPanelWidth());
- expect(Object.keys(groupSetLayoutCalls.at(-1) ?? {})).toEqual([
- 'editor-main',
- 'terminal-column',
- 'agents-column',
- ]);
- expect(groupLayout['editor-main']).toBeCloseTo(100 - chatPct);
- expect(groupLayout['terminal-column']).toBe(0);
- expect(groupLayout['agents-column']).toBeCloseTo(chatPct);
- });
-
- test('chat opened beside a full-height bottom terminal takes its preferred width, not the whole row', async () => {
- const props = { ...hiddenProps, terminalVisible: true, editorVisible: false } as const;
- const view = render(<EditorArea {...props} terminalPlacement="bottom" />);
- groupLayout = { 'editor-main': 100, 'terminal-column': 0, 'agents-column': 0 };
- await settle();
-
- view.rerender(<EditorArea {...props} terminalPlacement="bottom" agentsVisible />);
+ view.rerender(area(false));
await settle();
- const chatPct = pctOfRow(getInitialAgentsPanelWidth());
- expect(groupLayout['editor-main']).toBeCloseTo(100 - chatPct);
- expect(groupLayout['agents-column']).toBeCloseTo(chatPct);
+ expect(unitPx('terminal', 'insetBlockStart')).toBe(0);
+ expect(unitPx('terminal', 'height')).toBe(WORKSPACE_HEIGHT_PX);
+ expect(unitPx('terminal', 'width')).toBe(columnWidth);
+ expect(dockUnit('agents').getAttribute('style')).toBe(agentsStyle);
});
});
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 dfeb4ab58..5454fa055 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
@@ -3,6 +3,7 @@ import type { ReactNode } from 'react';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { SidebarProvider } from '@/components/ui/sidebar';
import { ConfigProvider } from '@/lib/config-provider';
+import { DEFAULT_DOCK_TREE } from '@/lib/dock-tree';
function assetCtx(assetPath: string) {
return {
@@ -52,9 +53,6 @@ vi.doMock('@/components/EditorSkeleton', () => ({
vi.doMock('@/components/EmptyEditorState', () => ({
EmptyEditorState: () => <div data-testid="empty-editor-state" />,
}));
-vi.doMock('./TerminalDock', () => ({
- TerminalDock: ({ children }: { children: ReactNode }) => <div>{children}</div>,
-}));
vi.doMock('./EditorWorkspace', () => ({
EditorWorkspace: ({
renderPane,
@@ -123,6 +121,8 @@ function renderEditorArea() {
onModeChange={() => {}}
activeTab="timeline"
onActiveTabChange={() => {}}
+ dockTree={DEFAULT_DOCK_TREE}
+ onDockTreeChange={() => {}}
/>
</SidebarProvider>
</ConfigProvider>,
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 146f709eb..94f634ab8 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
@@ -3,6 +3,7 @@ import type { ReactNode } from 'react';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { SidebarProvider } from '@/components/ui/sidebar';
import { ConfigProvider } from '@/lib/config-provider';
+import { DEFAULT_DOCK_TREE } from '@/lib/dock-tree';
import { pendingReceiveNavStore } from '@/lib/share/pending-receive-nav-store';
const MISSING_DOC_CTX = {
@@ -47,9 +48,6 @@ vi.doMock('@/components/EditorSkeleton', () => ({
vi.doMock('@/components/EmptyEditorState', () => ({
EmptyEditorState: () => <div data-testid="empty-editor-state" />,
}));
-vi.doMock('./TerminalDock', () => ({
- TerminalDock: ({ children }: { children: ReactNode }) => <div>{children}</div>,
-}));
vi.doMock('./EditorWorkspace', () => ({
EditorWorkspace: ({
renderActivityPool,
@@ -125,6 +123,8 @@ function renderEditorArea() {
onModeChange={() => {}}
activeTab="timeline"
onActiveTabChange={() => {}}
+ dockTree={DEFAULT_DOCK_TREE}
+ onDockTreeChange={() => {}}
/>
</SidebarProvider>
</ConfigProvider>,
diff --git a/packages/app/src/components/EditorArea.tsx b/packages/app/src/components/EditorArea.tsx
index 5453001c9..336b18537 100644
--- a/packages/app/src/components/EditorArea.tsx
+++ b/packages/app/src/components/EditorArea.tsx
@@ -7,12 +7,9 @@ import {
isFrontmatterSchemaAsset,
isMarkdownlintJsonConfig,
} from '@inkeep/open-knowledge-core/markdown/lint';
-import {
- PREFERRED_TERMINAL_RIGHT_WIDTH,
- type TerminalPlacement,
-} from '@inkeep/open-knowledge-core/terminal-layout';
import { Trans, useLingui } from '@lingui/react/macro';
import { ChevronLeft, PanelRightClose } from 'lucide-react';
+import { useTheme } from 'next-themes';
import {
lazy,
type ReactNode,
@@ -32,6 +29,7 @@ import { useGroupRef, usePanelRef } from 'react-resizable-panels';
import { toast } from 'sonner';
import { AssetPreview } from '@/components/AssetPreview';
import { DocChangeNotice } from '@/components/DocChangeNotice';
+import { DockWorkspace } from '@/components/DockWorkspace';
import { DocPanel, type PanelTab } from '@/components/DocPanel';
import { DocPanelToggle } from '@/components/DocPanelToggle';
import {
@@ -47,17 +45,15 @@ import { MountStalledAffordance } from '@/components/MountStalledAffordance';
import { NothingOpen } from '@/components/NothingOpen';
import { OkBlobRunnerPage } from '@/components/OkBlobRunnerPage';
import { PropertyProvider, useProperties } from '@/components/PropertyContext';
+import { PANE_LABEL } from '@/components/pane-icons';
import { ShareReceiveMissPanel } from '@/components/ShareReceiveMissPanel';
import { SkillFileViewer } from '@/components/SkillFileViewer';
import { SkillPreviewTab } from '@/components/SkillPreviewTab';
import { SettingsDialogShell } from '@/components/settings/SettingsDialogShell';
import { Button } from '@/components/ui/button';
import {
- PANE_CARD_GAP_LEAD_INSET_PX,
- PANE_CARD_GAP_TRAIL_INSET_PX,
- PANE_CARD_INSET_PX,
+ PANE_CARD_GAP_PX,
PaneCard,
- paneCardDividerClass,
SECONDARY_PANEL_SURFACE_CLASS,
} from '@/components/ui/pane-card';
import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from '@/components/ui/resizable';
@@ -81,23 +77,19 @@ import { useDocConflict } from '@/hooks/use-conflicts';
import { useDocumentStats } from '@/hooks/use-document-stats';
import { useSelectionStats } from '@/hooks/use-selection-stats';
import { closeAgentDiff, useAgentDiffView } from '@/lib/agent-diff-store';
-import {
- type AgentsPanelPointerReleaseDecision,
- getInitialAgentsPanelWidth,
- MIN_AGENTS_PANEL_WIDTH,
- resolveAgentsPanelPointerRelease,
- writeAgentsPanelWidth,
-} from '@/lib/agents-panel-width-store';
import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
import { docNameFromHash, hashFromDocName, isSameHash } from '@/lib/doc-hash';
import { getInitialDocPanelWidth, writeDocPanelWidth } from '@/lib/doc-panel-width-store';
+import { dockTerminalPlacement } from '@/lib/dock-arrangement-store';
+import { type DockLayout, dockPaneMinExtent, EMPTY_DOCK_LAYOUT } from '@/lib/dock-layout';
+import type { DockNode } from '@/lib/dock-tree';
import { focusAwayFromHiddenEditor, focusWaitsForEditor } from '@/lib/editor-hidden-focus';
import { type EditorSidebar, resolveEditorSidebarFit } from '@/lib/editor-sidebar-fit';
import { matchesKeyboardShortcut } from '@/lib/keyboard-shortcuts';
import { subscribeLocalMenuAction } from '@/lib/local-menu-action-bus';
import { isNoteWindow } from '@/lib/note-window-mode';
import { isOverlayLayerOpen } from '@/lib/overlay-layers';
-import { assertNeverPaneId, type PaneId } from '@/lib/pane-visibility-store';
+import type { PaneId } from '@/lib/pane-visibility-store';
import { ProfilerBoundary } from '@/lib/perf';
import { moveHostPreservingScroll, observeHostScrollRestore } from '@/lib/preserve-subtree-scroll';
import { revealEditor, revealEditorBeforeActing } from '@/lib/reveal-editor';
@@ -130,38 +122,17 @@ import {
type EditorWorkspaceActivityBindings,
type EditorWorkspacePaneRenderContext,
} from './EditorWorkspace';
-import {
- computeEditorHiddenLayout,
- editorHiddenLayoutLanded,
- isEditorHiddenLayoutSettled,
-} from './editor-area-hidden-editor';
-import { computeInnerFollowLayout, predictInnerPanelSpacePx } from './editor-area-inner-follow';
import { shouldPaintOverlay } from './editor-area-overlay';
import {
- describeRailFloorShortfall,
- describeRailWidthShortfall,
type RailPanelSpaceRefusal,
- type RailPanelSpaceResult,
- type RailWidthShortfall,
reportUnexpectedPanelGroupFailure,
- resolveInnerRowChromePx,
resolveRailPanelSpace,
resolveRailPanelSpacePx,
} from './editor-area-panel-space';
-import {
- AGENTS_COLUMN_ID,
- accountRailLayout,
- DOC_PANEL_ID,
- findResidualPanelId,
- TERMINAL_COLUMN_ID,
-} from './editor-area-rail-registry';
+import { DOC_PANEL_ID, findResidualPanelId } from './editor-area-rail-registry';
import { computeStickyRepinLayout } from './editor-area-sticky-repin';
-import {
- RIGHT_TERMINAL_PANEL_MIN_WIDTH_PX,
- resolveRightRailAdmission,
-} from './right-rail-admission';
import { isSlidesHost } from './slides-host-gate';
-import { TerminalDock, type TerminalDockHandle } from './TerminalDock';
+import { useLiveXtermTheme } from './use-live-xterm-theme';
const LazyActivityModeContent = lazy(async () => {
const mod = await import('@/components/ActivityModeContent');
@@ -273,34 +244,23 @@ function useFilesRequestCoordinator(inputs: FilesRequestCoordinatorInputs) {
return coordinate;
}
-type AgentsPanelCloseRetryContext = {
- readonly decision: 'close';
- readonly targetWidthPx: 0;
-};
-
-type AgentsPanelPointerReleaseRetryContext =
- | AgentsPanelCloseRetryContext
- | { readonly decision: 'restore-preferred'; readonly targetWidthPx: number }
- | { readonly decision: 'settle-minimum'; readonly targetWidthPx: number }
- | { readonly decision: 'commit-preferred'; readonly targetWidthPx: number };
-
-type RailLayoutSyncRetryContext = {
- readonly decision: 'sync-rail-columns' | 'sync-doc-presence' | 'observed-doc-width';
+type RailLayoutRetryContext = {
+ readonly decision: 'sync-doc-presence' | 'show-editor' | 'observed-doc-width';
readonly targetWidthPx: number;
};
-type AgentsPanelKeyboardRetryContext = {
- readonly decision: 'keyboard-settle-minimum';
- readonly targetWidthPx: typeof MIN_AGENTS_PANEL_WIDTH;
-};
-
-type RailLayoutRetryContext =
- | AgentsPanelPointerReleaseRetryContext
- | AgentsPanelKeyboardRetryContext
- | RailLayoutSyncRetryContext;
-
type RailLayoutRetryOutcome = 'applied' | 'blocked' | 'failed';
+type DocPanelPinMiss =
+ | { readonly cause: 'dragging' | 'group-missing' | 'layout-without-doc-panel' }
+ | { readonly cause: 'write-threw'; readonly writeError: string }
+ | { readonly cause: 'panel-space-unresolved'; readonly refusal: RailPanelSpaceRefusal }
+ | {
+ readonly cause: 'width-missed';
+ readonly pinnedWidthPx: number;
+ readonly landedWidthPx: number;
+ };
+
type RailLayoutRetryController = {
frameId: number;
deadlineTimer: ReturnType<typeof setTimeout> | null;
@@ -311,23 +271,6 @@ type RailLayoutRetryControllerRef = {
current: RailLayoutRetryController;
};
-function createAgentsPanelPointerReleaseRetryContext(
- decision: AgentsPanelPointerReleaseDecision,
-): AgentsPanelPointerReleaseRetryContext {
- switch (decision.kind) {
- case 'close':
- return { decision: decision.kind, targetWidthPx: 0 };
- case 'restore-preferred':
- case 'settle-minimum':
- case 'commit-preferred':
- return { decision: decision.kind, targetWidthPx: decision.widthPx };
- default: {
- const exhaustiveDecision: never = decision;
- return exhaustiveDecision;
- }
- }
-}
-
function cancelRailLayoutRetry(retryRef: RailLayoutRetryControllerRef) {
if (retryRef.current.frameId !== 0) cancelAnimationFrame(retryRef.current.frameId);
if (retryRef.current.deadlineTimer != null) clearTimeout(retryRef.current.deadlineTimer);
@@ -340,31 +283,23 @@ function runRailLayoutRetry({
retryRef,
attempt,
context,
- onComplete,
- onExhausted,
+ describeMiss,
}: {
retryRef: RailLayoutRetryControllerRef;
attempt: () => RailLayoutRetryOutcome;
context: RailLayoutRetryContext;
- onComplete?: () => void;
- onExhausted?: () => void;
+ describeMiss?: () => DocPanelPinMiss | null;
}) {
cancelRailLayoutRetry(retryRef);
retryRef.current.context = context;
const deadlineTimestamp = performance.now() + BLOCKED_RAIL_LAYOUT_RETRY_DEADLINE_MS;
- const completeRetry = () => {
- cancelRailLayoutRetry(retryRef);
- onComplete?.();
- };
const completeExhaustedRetry = () => {
cancelRailLayoutRetry(retryRef);
reportUnexpectedPanelGroupFailure(
'rail-layout-retry-exhausted',
new Error('Rail layout did not apply within the retry budget'),
- context,
+ { ...context, ...describeMiss?.() },
);
- onExhausted?.();
- onComplete?.();
};
retryRef.current.deadlineTimer = setTimeout(
completeExhaustedRetry,
@@ -379,7 +314,7 @@ function runRailLayoutRetry({
const outcome = attempt();
switch (outcome) {
case 'applied':
- completeRetry();
+ cancelRailLayoutRetry(retryRef);
return;
case 'blocked':
retryRef.current.frameId = requestAnimationFrame((timestamp) =>
@@ -476,32 +411,10 @@ const LazyAgentDiffPane = lazy(async () => {
return { default: mod.AgentDiffPane };
});
-export const MAX_RAIL_PIN_EXHAUSTED_REPORTS = 5;
-
-type RailPinOutcome =
- | { readonly stage: 'pinned' }
- | { readonly stage: 'group-missing' }
- | { readonly stage: 'read-failed' }
- | { readonly stage: 'panel-space-unresolved'; readonly refusal: RailPanelSpaceRefusal }
- | { readonly stage: 'layout-unaccounted'; readonly unaccountedIds: readonly string[] }
- | { readonly stage: 'no-residual-panel' }
- | { readonly stage: 'no-pinned-columns' }
- | { readonly stage: 'pins-do-not-fit'; readonly shortfall: Record<string, RailWidthShortfall> }
- | { readonly stage: 'write-failed' }
- | { readonly stage: 'verify-failed' }
- | { readonly stage: 'width-shortfall'; readonly shortfall: Record<string, RailWidthShortfall> }
- | { readonly stage: 'editor-hidden-unsettled' };
-
-type RailPinExhaustedTrigger = 'rail-column-sync' | 'doc-slot-presence' | 'editor-visibility';
-
const DOC_PANEL_MIN_WIDTH_PX = 300;
const DOC_USABLE_MIN_WIDTH_PX = 300;
const DOC_PANEL_MIN_SIZE = `${DOC_PANEL_MIN_WIDTH_PX}px`;
const DOC_PANEL_MAX_SIZE = '600px';
-const RIGHT_TERMINAL_GAP_END_INSET_PX = 1;
-const EDITOR_COLUMN_COLLAPSED_PCT = 0.5;
-const NO_CARD_INSETS = { start: 0, end: 0 } as const;
-
interface SessionPanelPlacement {
readonly container: HTMLElement | null;
readonly isShowing: boolean;
@@ -517,17 +430,6 @@ type PanesOnScreen = Readonly<Record<PaneId, boolean>>;
export interface EditorAreaHandle {
panesOnScreen(): PanesOnScreen;
- bringBackPane(pane: PaneId): void;
-}
-
-interface EditorCardSize {
- readonly width: number;
- readonly height: number;
-}
-
-function measureEditorCard(card: HTMLElement): EditorCardSize | null {
- const { width, height } = card.getBoundingClientRect();
- return width > 0 && height > 0 ? { width, height } : null;
}
function hasExtent(element: HTMLElement | null): boolean {
@@ -550,12 +452,9 @@ interface EditorAreaProps {
terminalBridge?: OkDesktopBridge | null;
editorVisible?: boolean;
terminalVisible?: boolean;
- terminalPlacement?: TerminalPlacement;
- terminalRightWidth?: number;
- onTerminalVisibleChange?: (visible: boolean) => void;
- onTerminalRightWidthChange?: (width: number) => void;
agentsVisible?: boolean;
- onAgentsVisibleChange?: (visible: boolean) => void;
+ dockTree: DockNode;
+ onDockTreeChange: (update: (tree: DockNode) => DockNode) => void;
onSessionPlacements?: (placements: SessionPlacements) => void;
renderWorkspaceHeader?: (tabs: ReactNode, chrome: WorkspaceHeaderChrome) => ReactNode;
}
@@ -689,12 +588,9 @@ function EditorAreaInner({
terminalBridge,
editorVisible = true,
terminalVisible = false,
- terminalPlacement = 'bottom',
- terminalRightWidth,
- onTerminalVisibleChange,
- onTerminalRightWidthChange,
agentsVisible = false,
- onAgentsVisibleChange,
+ dockTree,
+ onDockTreeChange,
onSessionPlacements,
renderWorkspaceHeader = renderTabsWithoutHeader,
}: EditorAreaProps) {
@@ -774,8 +670,6 @@ function EditorAreaInner({
resolvePartition(embeddedHost, window.innerWidth, 'right'),
);
const panelRef = usePanelRef();
- const agentsColumnPanelRef = usePanelRef();
- const terminalColumnPanelRef = usePanelRef();
const [initialRightCollapsed] = useState(() => {
const pins = readPins();
return resolveEffectiveState('right', initialRightPartition, pins) === 'collapsed';
@@ -841,7 +735,6 @@ function EditorAreaInner({
}, [docPanelHost]);
const {
cover: filesCover,
- canDock: filesCanDock,
dismissCover: dismissFilesCover,
setCanDock: setFilesCanDock,
registerOpenRequestHandler: registerFilesOpenRequestHandler,
@@ -853,51 +746,21 @@ function EditorAreaInner({
const [filesCoverTarget, setFilesCoverTarget] = useState<HTMLDivElement | null>(null);
const [agentsContainer, setAgentsContainer] = useState<HTMLElement | null>(null);
- const [rightTerminalContainer, setRightTerminalContainer] = useState<HTMLDivElement | null>(null);
+ const [terminalContainer, setTerminalContainer] = useState<HTMLDivElement | null>(null);
const [workspaceHeaderContainer, setWorkspaceHeaderContainer] = useState<HTMLDivElement | null>(
null,
);
const [workspaceColumnEl, setWorkspaceColumnEl] = useState<HTMLElement | null>(null);
- const [bottomTerminalContainer, setBottomTerminalContainer] = useState<HTMLDivElement | null>(
- null,
- );
const [terminalEditorRegion, setTerminalEditorRegion] = useState<HTMLDivElement | null>(null);
+ const { resolvedTheme } = useTheme();
+ const xtermBackground = useLiveXtermTheme(resolvedTheme).background;
- const agentsColumnPresent = !noteWindow && agentsVisible;
- const terminalColumnPresent = !noteWindow && terminalVisible && terminalPlacement === 'right';
- const [agentsColumnCollapsed, setAgentsColumnCollapsed] = useState(false);
- const [terminalColumnCollapsed, setTerminalColumnCollapsed] = useState(false);
- const terminalCollapsedByUserRef = useRef(false);
- const [bottomTerminalCollapsed, setBottomTerminalCollapsed] = useState(false);
- const terminalDockRef = useRef<TerminalDockHandle>(null);
- const [agentsShowingHold, setAgentsShowingHold] = useState(false);
- const [terminalShowingHold, setTerminalShowingHold] = useState(false);
- const resizableRailColumnPresent = terminalColumnPresent || agentsColumnPresent;
- const rightTerminalCardShowing = terminalColumnPresent && !terminalColumnCollapsed;
- const rightColumnPresent = terminalColumnPresent || agentsColumnPresent;
- const bottomTerminalHeld = terminalAvailable && terminalVisible && terminalPlacement === 'bottom';
- const editorColumnHoldsPane = editorVisible || bottomTerminalHeld;
- const editorColumnChromePx =
- cardLook && rightColumnPresent && editorColumnHoldsPane ? PANE_CARD_GAP_LEAD_INSET_PX : 0;
- const terminalCardInsets = cardLook
- ? {
- start: editorVisible ? PANE_CARD_GAP_TRAIL_INSET_PX : 0,
- end: agentsColumnPresent ? RIGHT_TERMINAL_GAP_END_INSET_PX : 0,
- }
- : NO_CARD_INSETS;
- const agentsCardInsetStartPx = !cardLook
- ? 0
- : terminalColumnPresent
- ? PANE_CARD_INSET_PX - RIGHT_TERMINAL_GAP_END_INSET_PX
- : editorColumnHoldsPane
- ? PANE_CARD_GAP_TRAIL_INSET_PX
- : 0;
- const editorColumnChromePxRef = useRef(editorColumnChromePx);
+ const agentsUnitShown = !noteWindow && agentsVisible;
+ const terminalUnitShown = !noteWindow && terminalAvailable && terminalVisible;
+ const terminalPlacement = dockTerminalPlacement(dockTree);
+ const [dockLayout, setDockLayout] = useState<DockLayout>(EMPTY_DOCK_LAYOUT);
const editorVisibleRef = useRef(editorVisible);
- const bottomTerminalHeldRef = useRef(bottomTerminalHeld);
const editorCardRef = useRef<HTMLDivElement | null>(null);
- const lastEditorCardSizeRef = useRef<EditorCardSize | null>(null);
- const [editorCardPin, setEditorCardPin] = useState<EditorCardSize | null>(null);
const [paneVisibilityWhileEditorShown, setPaneVisibilityWhileEditorShown] = useState({
terminalVisible,
agentsVisible,
@@ -909,41 +772,22 @@ function EditorAreaInner({
) {
setPaneVisibilityWhileEditorShown({ terminalVisible, agentsVisible });
}
- useLayoutEffect(() => {
- const card = editorCardRef.current;
- if (card == null || !editorVisible || typeof ResizeObserver === 'undefined') return;
- const observer = new ResizeObserver(() => {
- const size = measureEditorCard(card);
- if (size != null) lastEditorCardSizeRef.current = size;
- });
- observer.observe(card);
- return () => observer.disconnect();
- }, [editorVisible]);
const editorVisibleBeforeRef = useRef(editorVisible);
useLayoutEffect(() => {
const wasVisible = editorVisibleBeforeRef.current;
editorVisibleBeforeRef.current = editorVisible;
+ editorVisibleRef.current = editorVisible;
if (editorVisible) {
if (!wasVisible && focusWaitsForEditor()) terminalEditorRegion?.focus();
return;
}
const card = editorCardRef.current;
- if (card == null) return;
- setEditorCardPin(
- (current) => current ?? lastEditorCardSizeRef.current ?? measureEditorCard(card),
- );
- if (card.contains(document.activeElement)) focusAwayFromHiddenEditor();
+ if (card?.contains(document.activeElement)) focusAwayFromHiddenEditor();
}, [editorVisible, terminalEditorRegion]);
- const terminalContainer =
- terminalPlacement === 'right' ? rightTerminalContainer : bottomTerminalContainer;
const terminalShowing =
- terminalVisible &&
- terminalContainer != null &&
- (terminalPlacement === 'right'
- ? !terminalColumnCollapsed || terminalShowingHold
- : !bottomTerminalCollapsed);
+ terminalUnitShown && terminalContainer != null && dockLayout.panes.has('terminal');
const agentsShowing =
- agentsColumnPresent && (!agentsColumnCollapsed || agentsShowingHold) && agentsContainer != null;
+ agentsUnitShown && agentsContainer != null && dockLayout.panes.has('agents');
useEffect(() => {
onSessionPlacements?.({
terminal: { container: terminalContainer, isShowing: terminalShowing },
@@ -958,13 +802,6 @@ function EditorAreaInner({
agentsShowing,
terminalEditorRegion,
]);
- useEffect(() => {
- if (!agentsColumnPresent) setAgentsShowingHold(false);
- if (!terminalColumnPresent) {
- setTerminalShowingHold(false);
- terminalCollapsedByUserRef.current = false;
- }
- }, [agentsColumnPresent, terminalColumnPresent]);
const onPaneExtentChangeRef = useRef(onPaneExtentChange);
useLayoutEffect(() => {
@@ -983,14 +820,12 @@ function EditorAreaInner({
useLayoutEffect(() => {
const observer = paneExtentObserverRef.current;
if (observer == null) return;
- const mounts = [agentsContainer, rightTerminalContainer, bottomTerminalContainer].filter(
- (mount) => mount != null,
- );
+ const mounts = [agentsContainer, terminalContainer].filter((mount) => mount != null);
for (const mount of mounts) observer.observe(mount);
return () => {
for (const mount of mounts) observer.unobserve(mount);
};
- }, [agentsContainer, rightTerminalContainer, bottomTerminalContainer]);
+ }, [agentsContainer, terminalContainer]);
useEffect(() => {
isCollapsedRef.current = isCollapsed;
@@ -1010,56 +845,16 @@ function EditorAreaInner({
}, 100);
}
- const [initialAgentsWidthPx] = useState(() => getInitialAgentsPanelWidth());
- const agentsPreferredWidthPxRef = useRef(initialAgentsWidthPx);
- const [isDraggingAgentsHandle, setIsDraggingAgentsHandle] = useState(false);
- const isDraggingAgentsHandleRef = useRef(false);
- const agentsSettlementRetryRef = useRef<RailLayoutRetryController>({
- frameId: 0,
- deadlineTimer: null,
- });
- const railColumnSyncRetryRef = useRef<RailLayoutRetryController>({
- frameId: 0,
- deadlineTimer: null,
- });
- const pendingAgentsVisibilityRetryContextRef = useRef<AgentsPanelCloseRetryContext | null>(null);
-
- const [initialTerminalWidthPx] = useState(() =>
- Math.max(
- terminalRightWidth ?? PREFERRED_TERMINAL_RIGHT_WIDTH,
- RIGHT_TERMINAL_PANEL_MIN_WIDTH_PX,
- ),
- );
- const terminalWidthPxRef = useRef(initialTerminalWidthPx);
- const [isDraggingTerminalHandle, setIsDraggingTerminalHandle] = useState(false);
- const isDraggingTerminalHandleRef = useRef(false);
- const terminalWriteTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
- function debouncedWriteTerminalWidth(px: number) {
- if (terminalWriteTimerRef.current != null) clearTimeout(terminalWriteTimerRef.current);
- terminalWriteTimerRef.current = setTimeout(() => {
- onTerminalRightWidthChange?.(px);
- terminalWriteTimerRef.current = null;
- }, 100);
- }
-
useEffect(
() => () => {
if (writeTimerRef.current != null) clearTimeout(writeTimerRef.current);
- if (terminalWriteTimerRef.current != null) clearTimeout(terminalWriteTimerRef.current);
- cancelRailLayoutRetry(agentsSettlementRetryRef);
},
[],
);
- const [groupContainerEl, setGroupContainerEl] = useState<HTMLDivElement | null>(null);
- const groupContainerElRef = useRef<HTMLDivElement | null>(null);
const [innerContainerEl, setInnerContainerEl] = useState<HTMLDivElement | null>(null);
const innerContainerElRef = useRef<HTMLDivElement | null>(null);
- const {
- node: fileListSlotEl,
- nodeRef: fileListSlotElRef,
- slotRef: fileListSlotRef,
- } = useFileListSlot();
+ const { node: fileListSlotEl, slotRef: fileListSlotRef } = useFileListSlot();
useLayoutEffect(() => {
if (docPanelCover || isCollapsed) return;
const focusedPanelControl = docPanelDockFocusRef.current;
@@ -1102,577 +897,100 @@ function EditorAreaInner({
frameId: 0,
deadlineTimer: null,
});
- const editorVisibilityRetryRef = useRef<RailLayoutRetryController>({
- frameId: 0,
- deadlineTimer: null,
- });
const observedDocWidthRetryRef = useRef<RailLayoutRetryController>({
frameId: 0,
deadlineTimer: null,
});
- const railPinOutcomeRef = useRef<RailPinOutcome>({ stage: 'group-missing' });
- const railPlanWriteInProgressRef = useRef(false);
- const railPinExhaustedReportsRef = useRef<Record<RailPinExhaustedTrigger, number>>({
- 'rail-column-sync': 0,
- 'doc-slot-presence': 0,
- 'editor-visibility': 0,
- });
-
- const reportRailPinExhausted = useEffectEvent((trigger: RailPinExhaustedTrigger) => {
- if (railPinExhaustedReportsRef.current[trigger] >= MAX_RAIL_PIN_EXHAUSTED_REPORTS) return;
- railPinExhaustedReportsRef.current[trigger] += 1;
- console.warn(
- JSON.stringify({
- event: 'right-rail-pin-exhausted',
- trigger,
- ...railPinOutcomeRef.current,
- }),
- );
- });
- const groupRef = useGroupRef();
const innerGroupRef = useGroupRef();
- function readDocPanelPx(): number | null {
- try {
- const size = panelRef.current?.getSize();
- return size == null || !Number.isFinite(size.inPixels) ? null : size.inPixels;
- } catch (error) {
- reportUnexpectedPanelGroupFailure('read-doc-panel-px-failed', error);
- return null;
- }
- }
- function resolveGroupPxWidth(): number | null {
- return resolveRailPanelSpacePx(groupContainerElRef.current);
- }
function resolveInnerGroupPxWidth(): number | null {
return resolveRailPanelSpacePx(innerContainerElRef.current);
}
- function measureInnerChromePx(innerPx: number): number {
- const chromePx = resolveInnerRowChromePx(
- groupContainerElRef.current,
- innerContainerElRef.current,
- innerPx,
- );
- if (chromePx != null) return chromePx;
- reportUnexpectedPanelGroupFailure(
- 'measure-inner-chrome-column-missing',
- new Error('No outer row column holds the inner row'),
- );
- return 0;
- }
- function readFileListWidthPx(): number {
- const width = fileListSlotElRef.current?.getBoundingClientRect().width ?? 0;
- return Number.isFinite(width) && width > 0 ? width : 0;
- }
- function sharedRowPxFrom(outerPx: number): number {
- return Math.max(0, outerPx - editorColumnChromePxRef.current - readFileListWidthPx());
- }
- function resolveSharedRowPxWidth(): number | null {
- const outerPx = resolveGroupPxWidth();
- return outerPx == null ? null : sharedRowPxFrom(outerPx);
- }
-
- function resolveAdmissionMetrics(): {
- workspaceWidthPx: number;
- otherRailWidthPx: number;
- } | null {
- const group = groupRef.current;
- if (group == null) return null;
- try {
- const workspaceWidthPx = resolveSharedRowPxWidth();
- if (workspaceWidthPx == null) return null;
- if (!docSlotPresentRef.current) {
- return { workspaceWidthPx, otherRailWidthPx: 0 };
- }
- if (isCollapsedRef.current) {
- return { workspaceWidthPx, otherRailWidthPx: 0 };
- }
- const measuredWidthPx = readDocPanelPx();
- const docWidthPx =
- measuredWidthPx != null && measuredWidthPx > 0
- ? Math.min(measuredWidthPx, docPanelWidthPxRef.current)
- : docPanelWidthPxRef.current;
- return {
- workspaceWidthPx,
- otherRailWidthPx: Math.max(docWidthPx, DOC_PANEL_MIN_WIDTH_PX),
- };
- } catch (error) {
- reportUnexpectedPanelGroupFailure('resolve-admission-metrics-failed', error);
- return null;
- }
- }
- type AdmissionVisibility = {
- readonly terminalRightVisible: boolean;
- readonly agentsVisible: boolean;
- };
- const admissionVisibility: AdmissionVisibility = {
- terminalRightVisible: terminalColumnPresent,
- agentsVisible,
- };
- const admissionVisibilityRef = useRef(admissionVisibility);
- const previousAdmissionVisibilityRef = useRef(admissionVisibility);
- const previousAdmissionCollapsedRef = useRef(isCollapsed);
- const pendingAdmissionCloseRef = useRef<'close-agents' | 'close-terminal' | null>(null);
- const filesCanDockRef = useRef(filesCanDock);
- const dragCloseRequestedRef = useRef(false);
- const admissionDeferredByFilesRef = useRef<{
- readonly trigger: 'state-change' | 'resize';
- readonly previous: AdmissionVisibility;
- } | null>(null);
- const admissionDeferredByDragRef = useRef<{
- readonly trigger: 'state-change' | 'resize';
- readonly previous: AdmissionVisibility;
- } | null>(null);
-
- function railDragInProgress(): boolean {
- return (
- isDraggingDocHandleRef.current ||
- isDraggingTerminalHandleRef.current ||
- isDraggingAgentsHandleRef.current
- );
- }
-
- function enforceRightRailAdmission(
- trigger: 'state-change' | 'resize',
- previous: AdmissionVisibility,
- ) {
- if (railDragInProgress()) {
- admissionDeferredByDragRef.current = { trigger, previous };
- return;
- }
- admissionDeferredByDragRef.current = null;
- const filesSettling = !filesCanDockRef.current && readFileListWidthPx() > 0;
- const deferredByFiles = filesSettling ? null : admissionDeferredByFilesRef.current;
- const admissionTrigger = deferredByFiles?.trigger ?? trigger;
- const admissionPrevious = deferredByFiles?.previous ?? previous;
- const metrics = resolveAdmissionMetrics();
- if (metrics == null) return;
- const decision = resolveRightRailAdmission({
- ...metrics,
- editorMinimumWidthPx: docSlotPresentRef.current ? DOC_USABLE_MIN_WIDTH_PX : 0,
- agentsMinimumWidthPx: MIN_AGENTS_PANEL_WIDTH,
- previous: admissionPrevious,
- current: admissionVisibilityRef.current,
- trigger: admissionTrigger,
- });
- if (filesSettling) {
- if (
- decision.kind !== 'none' &&
- (admissionDeferredByFilesRef.current == null || trigger === 'state-change')
- ) {
- admissionDeferredByFilesRef.current = { trigger, previous };
- }
- return;
- }
- admissionDeferredByFilesRef.current = null;
- if (decision.kind === 'none' || pendingAdmissionCloseRef.current === decision.kind) return;
-
- if (decision.kind === 'close-agents') {
- if (onAgentsVisibleChange == null) return;
- pendingAdmissionCloseRef.current = decision.kind;
- onAgentsVisibleChange(false);
- toast.info(t`Agent panel closed to keep Terminal readable.`);
- return;
- }
-
- if (onTerminalVisibleChange == null) return;
- pendingAdmissionCloseRef.current = decision.kind;
- onTerminalVisibleChange(false);
- toast.info(t`Terminal closed to make room for the agent panel.`);
- }
-
- const enforceRightRailAdmissionRef = useRef(enforceRightRailAdmission);
- useLayoutEffect(() => {
- enforceRightRailAdmissionRef.current = enforceRightRailAdmission;
- filesCanDockRef.current = filesCanDock;
- admissionVisibilityRef.current = admissionVisibility;
- editorColumnChromePxRef.current = editorColumnChromePx;
- editorVisibleRef.current = editorVisible;
- bottomTerminalHeldRef.current = bottomTerminalHeld;
- });
-
- useLayoutEffect(() => {
- if (!agentsVisible && pendingAdmissionCloseRef.current === 'close-agents') {
- pendingAdmissionCloseRef.current = null;
- }
- if (!terminalColumnPresent && pendingAdmissionCloseRef.current === 'close-terminal') {
- pendingAdmissionCloseRef.current = null;
- }
- const previous = previousAdmissionVisibilityRef.current;
- const previousCollapsed = previousAdmissionCollapsedRef.current;
- previousAdmissionVisibilityRef.current = {
- terminalRightVisible: terminalColumnPresent,
- agentsVisible,
+ function attemptDocPanelPin(
+ docCollapsed: boolean,
+ recordMiss: (miss: DocPanelPinMiss) => void = () => {},
+ ): RailLayoutRetryOutcome {
+ const missDocPanelPin = (miss: DocPanelPinMiss, outcome: 'blocked' | 'failed') => {
+ recordMiss(miss);
+ return outcome;
};
- previousAdmissionCollapsedRef.current = isCollapsed;
- queueMicrotask(() => {
- enforceRightRailAdmissionRef.current(
- previousCollapsed === isCollapsed ? 'state-change' : 'resize',
- previous,
+ isCollapsedRef.current = docCollapsed;
+ if (!editorVisibleRef.current) return 'applied';
+ if (isDraggingDocHandleRef.current) return missDocPanelPin({ cause: 'dragging' }, 'blocked');
+ const group = innerGroupRef.current;
+ if (group == null) return missDocPanelPin({ cause: 'group-missing' }, 'blocked');
+ const space = resolveRailPanelSpace(innerContainerElRef.current);
+ if (!space.ok) {
+ return missDocPanelPin(
+ { cause: 'panel-space-unresolved', refusal: space.refusal },
+ 'blocked',
);
- });
- }, [agentsVisible, terminalColumnPresent, isCollapsed]);
-
- function applyEditorHiddenLayout(): boolean {
- const outerGroup = groupRef.current;
- if (outerGroup == null) {
- railPinOutcomeRef.current = { stage: 'group-missing' };
- return false;
- }
- let outerSpace: RailPanelSpaceResult;
- let outerLayout: Record<string, number>;
- try {
- outerSpace = resolveRailPanelSpace(groupContainerElRef.current);
- outerLayout = outerGroup.getLayout();
- } catch (error) {
- railPinOutcomeRef.current = { stage: 'read-failed' };
- reportUnexpectedPanelGroupFailure('apply-editor-hidden-layout-read-failed', error);
- return false;
- }
- if (!outerSpace.ok) {
- railPinOutcomeRef.current = { stage: 'panel-space-unresolved', refusal: outerSpace.refusal };
- return false;
- }
- const outerAccounting = accountRailLayout(Object.keys(outerLayout));
- if (!outerAccounting.ok) {
- railPinOutcomeRef.current =
- outerAccounting.unaccountedIds.length === 0
- ? { stage: 'no-residual-panel' }
- : { stage: 'layout-unaccounted', unaccountedIds: outerAccounting.unaccountedIds };
- return false;
}
- const outerPx = outerSpace.panelSpacePx;
- const currentOrPreferredPx = (id: string, visible: boolean, preferredPx: number) => {
- if (!visible) return 0;
- const currentPx = ((outerLayout[id] ?? 0) / 100) * outerPx;
- return currentPx > 0 ? currentPx : preferredPx;
- };
- const editorColumnId = outerAccounting.residualId;
- const chatBesideBottomTerminalPx = admissionVisibilityRef.current.agentsVisible
- ? agentsPreferredWidthPxRef.current
- : 0;
- const plan = {
- currentLayout: outerLayout,
- editorColumnId,
- visibleColumnPx: bottomTerminalHeldRef.current
- ? {
- [editorColumnId]: Math.max(outerPx - chatBesideBottomTerminalPx, 1),
- [AGENTS_COLUMN_ID]: chatBesideBottomTerminalPx,
- }
- : {
- [TERMINAL_COLUMN_ID]: currentOrPreferredPx(
- TERMINAL_COLUMN_ID,
- admissionVisibilityRef.current.terminalRightVisible,
- terminalWidthPxRef.current,
- ),
- [AGENTS_COLUMN_ID]: currentOrPreferredPx(
- AGENTS_COLUMN_ID,
- admissionVisibilityRef.current.agentsVisible,
- agentsPreferredWidthPxRef.current,
- ),
- },
- };
- if (isEditorHiddenLayoutSettled(plan)) {
- railPinOutcomeRef.current = { stage: 'pinned' };
- return true;
- }
- const next = computeEditorHiddenLayout(plan);
- railPlanWriteInProgressRef.current = true;
- let readBack: Record<string, number>;
- try {
- outerGroup.setLayout(next);
- readBack = outerGroup.getLayout();
- } catch (error) {
- railPlanWriteInProgressRef.current = false;
- railPinOutcomeRef.current = { stage: 'write-failed' };
- reportUnexpectedPanelGroupFailure('apply-editor-hidden-layout-write-failed', error);
- return false;
- }
- railPlanWriteInProgressRef.current = false;
- const landed = editorHiddenLayoutLanded(next, readBack);
- railPinOutcomeRef.current = landed ? { stage: 'pinned' } : { stage: 'editor-hidden-unsettled' };
- return landed;
- }
-
- function reopenCollapsedEditorColumn(
- outerGroup: NonNullable<typeof groupRef.current>,
- outerLayout: Record<string, number>,
- outerPx: number,
- ) {
- const { residualId } = accountRailLayout(Object.keys(outerLayout));
- if (residualId == null || (outerLayout[residualId] ?? 0) > EDITOR_COLUMN_COLLAPSED_PCT) return;
- const pinnedPx: Record<string, number> = {};
- if (TERMINAL_COLUMN_ID in outerLayout) {
- pinnedPx[TERMINAL_COLUMN_ID] = admissionVisibilityRef.current.terminalRightVisible
- ? terminalWidthPxRef.current
- : 0;
- }
- if (AGENTS_COLUMN_ID in outerLayout) {
- pinnedPx[AGENTS_COLUMN_ID] = admissionVisibilityRef.current.agentsVisible
- ? agentsPreferredWidthPxRef.current
- : 0;
- }
- const next = computeStickyRepinLayout({
- currentLayout: outerLayout,
- containerPx: outerPx,
- pinnedPx,
- residualId,
- });
- if (next === outerLayout) return;
- railPlanWriteInProgressRef.current = true;
+ const innerPx = space.panelSpacePx;
try {
- outerGroup.setLayout(next);
- } catch (error) {
- reportUnexpectedPanelGroupFailure('reopen-editor-column-write-failed', error);
- }
- railPlanWriteInProgressRef.current = false;
- }
-
- function applyRailLayout(
- docCollapsed: boolean,
- {
- agentsWidthOverridePx,
- }: {
- agentsWidthOverridePx?: number;
- } = {},
- ): boolean {
- if (!editorVisibleRef.current) return applyEditorHiddenLayout();
- const outerGroup = groupRef.current;
- const innerGroup = innerGroupRef.current;
- if (outerGroup == null || innerGroup == null) {
- railPinOutcomeRef.current = { stage: 'group-missing' };
- return false;
- }
- let outerSpace: RailPanelSpaceResult;
- let innerSpace: RailPanelSpaceResult;
- let outerLayout: Record<string, number>;
- let innerLayout: Record<string, number>;
- try {
- outerSpace = resolveRailPanelSpace(groupContainerElRef.current);
- innerSpace = resolveRailPanelSpace(innerContainerElRef.current);
- outerLayout = outerGroup.getLayout();
- innerLayout = innerGroup.getLayout();
- } catch (error) {
- railPinOutcomeRef.current = { stage: 'read-failed' };
- reportUnexpectedPanelGroupFailure('apply-rail-layout-read-failed', error);
- return false;
- }
- if (!outerSpace.ok) {
- railPinOutcomeRef.current = { stage: 'panel-space-unresolved', refusal: outerSpace.refusal };
- return false;
- }
- if (!innerSpace.ok) {
- railPinOutcomeRef.current = { stage: 'panel-space-unresolved', refusal: innerSpace.refusal };
- reopenCollapsedEditorColumn(outerGroup, outerLayout, outerSpace.panelSpacePx);
- return false;
- }
- const outerPx = outerSpace.panelSpacePx;
- const innerPx = innerSpace.panelSpacePx;
- const sharedRowPx = sharedRowPxFrom(outerPx);
- const outerAccounting = accountRailLayout(Object.keys(outerLayout));
- const innerAccounting = accountRailLayout(Object.keys(innerLayout));
- if (!outerAccounting.ok || !innerAccounting.ok) {
- const unaccountedIds = [...outerAccounting.unaccountedIds, ...innerAccounting.unaccountedIds];
- railPinOutcomeRef.current =
- unaccountedIds.length === 0
- ? { stage: 'no-residual-panel' }
- : { stage: 'layout-unaccounted', unaccountedIds };
- if (import.meta.env.DEV) {
- console.warn(
- JSON.stringify({
- event: 'right-rail-accounting-failed',
- unaccountedIds,
- }),
- );
- }
- return false;
- }
-
- const buildPins = (atFloor: boolean) => {
- const inner: Record<string, number> = {};
- const outer: Record<string, number> = {};
- if (DOC_PANEL_ID in innerLayout) {
- inner[DOC_PANEL_ID] =
- !docSlotPresentRef.current || docCollapsed
- ? 0
- : atFloor
- ? DOC_PANEL_MIN_WIDTH_PX
- : docPanelWidthPxRef.current;
- }
- if (TERMINAL_COLUMN_ID in outerLayout) {
- outer[TERMINAL_COLUMN_ID] =
- !admissionVisibilityRef.current.terminalRightVisible || terminalCollapsedByUserRef.current
- ? 0
- : atFloor
- ? RIGHT_TERMINAL_PANEL_MIN_WIDTH_PX
- : terminalWidthPxRef.current;
- }
- if (AGENTS_COLUMN_ID in outerLayout) {
- outer[AGENTS_COLUMN_ID] = !admissionVisibilityRef.current.agentsVisible
- ? 0
- : atFloor
- ? MIN_AGENTS_PANEL_WIDTH
- : (agentsWidthOverridePx ?? agentsPreferredWidthPxRef.current);
+ const layout = group.getLayout();
+ const residualId = findResidualPanelId(Object.keys(layout));
+ if (residualId == null || !(DOC_PANEL_ID in layout)) {
+ return missDocPanelPin({ cause: 'layout-without-doc-panel' }, 'blocked');
}
- return { inner, outer, all: { ...inner, ...outer } };
- };
-
- const renderedWidths = (
- outerPcts: Record<string, number>,
- innerPcts: Record<string, number>,
- innerRowPx = innerPx,
- ) => {
- const widths = new Map<string, number>();
- for (const [id, pct] of Object.entries(outerPcts)) widths.set(id, (pct / 100) * outerPx);
- for (const [id, pct] of Object.entries(innerPcts)) widths.set(id, (pct / 100) * innerRowPx);
- return widths;
- };
- const fitsSharedRow = (pins: Record<string, number>) =>
- Object.values(pins).reduce((total, px) => total + px, 0) <= sharedRowPx;
-
- const docRenderedPx = readDocPanelPx();
- const withDocRendered = (widths: Map<string, number>) => {
- if (docRenderedPx != null && widths.has(DOC_PANEL_ID))
- widths.set(DOC_PANEL_ID, docRenderedPx);
- return widths;
- };
-
- let pins = buildPins(false);
- if (Object.keys(pins.all).length === 0) {
- railPinOutcomeRef.current = { stage: 'no-pinned-columns' };
- return false;
- }
- if (!fitsSharedRow(pins.all)) pins = buildPins(true);
- if (!fitsSharedRow(pins.all)) {
- const shortfall = describeRailFloorShortfall(
- pins.all,
- withDocRendered(renderedWidths(outerLayout, innerLayout)),
+ const pinnedPx = docCollapsed || !docSlotPresentRef.current ? 0 : docPanelWidthPxRef.current;
+ const next = computeStickyRepinLayout({
+ currentLayout: layout,
+ containerPx: innerPx,
+ pinnedPx: { [DOC_PANEL_ID]: pinnedPx },
+ residualId,
+ });
+ if (next === layout) return 'applied';
+ group.setLayout(next);
+ const landedPx = ((group.getLayout()[DOC_PANEL_ID] ?? 0) / 100) * innerPx;
+ if (Math.abs(landedPx - pinnedPx) <= 1) return 'applied';
+ return missDocPanelPin(
+ { cause: 'width-missed', pinnedWidthPx: pinnedPx, landedWidthPx: landedPx },
+ 'failed',
);
- const pinned = Object.keys(shortfall).length === 0;
- railPinOutcomeRef.current = pinned
- ? { stage: 'pinned' }
- : { stage: 'pins-do-not-fit', shortfall };
- return pinned;
- }
-
- const nextOuter = computeStickyRepinLayout({
- currentLayout: outerLayout,
- containerPx: outerPx,
- pinnedPx: pins.outer,
- residualId: outerAccounting.residualId,
- });
- const innerTargetPx =
- predictInnerPanelSpacePx({
- outerLayout: nextOuter,
- outerResidualId: outerAccounting.residualId,
- outerPanelSpacePx: outerPx,
- innerChromePx: measureInnerChromePx(innerPx),
- }) ?? innerPx;
- const docPinPx = pins.inner[DOC_PANEL_ID];
- const docProjectedPx =
- docPinPx == null ? null : ((innerLayout[DOC_PANEL_ID] ?? 0) / 100) * innerTargetPx;
- const docAlreadyPinned =
- docPinPx != null && docProjectedPx != null && Math.abs(docProjectedPx - docPinPx) <= 1;
- const nextInner = docAlreadyPinned
- ? innerLayout
- : computeStickyRepinLayout({
- currentLayout: innerLayout,
- containerPx: innerTargetPx,
- pinnedPx: pins.inner,
- residualId: innerAccounting.residualId,
- });
- railPlanWriteInProgressRef.current = true;
- try {
- if (nextOuter !== outerLayout) outerGroup.setLayout(nextOuter);
- if (nextInner !== innerLayout) innerGroup.setLayout(nextInner);
- } catch (error) {
- railPlanWriteInProgressRef.current = false;
- railPinOutcomeRef.current = { stage: 'write-failed' };
- reportUnexpectedPanelGroupFailure('apply-rail-layout-write-failed', error);
- return false;
- }
- railPlanWriteInProgressRef.current = false;
- let outerReadBack: Record<string, number>;
- let innerReadBack: Record<string, number>;
- try {
- outerReadBack = outerGroup.getLayout();
- innerReadBack = innerGroup.getLayout();
} catch (error) {
- railPinOutcomeRef.current = { stage: 'verify-failed' };
- reportUnexpectedPanelGroupFailure('apply-rail-layout-verify-failed', error);
- return false;
+ reportUnexpectedPanelGroupFailure('pin-doc-panel-failed', error);
+ return missDocPanelPin(
+ {
+ cause: 'write-threw',
+ writeError: error instanceof Error ? error.message : String(error),
+ },
+ 'failed',
+ );
}
- const shortfall = describeRailWidthShortfall(
- pins.all,
- renderedWidths(outerReadBack, innerReadBack, innerTargetPx),
- );
- const pinned = Object.keys(shortfall).length === 0;
- railPinOutcomeRef.current = pinned
- ? { stage: 'pinned' }
- : { stage: 'width-shortfall', shortfall };
- return pinned;
}
- function followOuterLayout(outerLayout: Record<string, number>) {
- if (!editorVisibleRef.current) return;
- const innerGroup = innerGroupRef.current;
- if (innerGroup == null) return;
- const outerPx = resolveGroupPxWidth();
- const innerPx = resolveInnerGroupPxWidth();
- if (outerPx == null || innerPx == null) return;
- let innerLayout: Record<string, number>;
- try {
- innerLayout = innerGroup.getLayout();
- } catch (error) {
- reportUnexpectedPanelGroupFailure('follow-outer-layout-read-failed', error);
- return;
- }
- const outerAccounting = accountRailLayout(Object.keys(outerLayout));
- const innerAccounting = accountRailLayout(Object.keys(innerLayout));
- if (!outerAccounting.ok || !innerAccounting.ok || !(DOC_PANEL_ID in innerLayout)) return;
- const docPinPx =
- !docSlotPresentRef.current || isCollapsedRef.current ? 0 : docPanelWidthPxRef.current;
- const next = computeInnerFollowLayout({
- outerLayout,
- outerResidualId: outerAccounting.residualId,
- outerPanelSpacePx: outerPx,
- innerChromePx: measureInnerChromePx(innerPx),
- innerLayout,
- innerResidualId: innerAccounting.residualId,
- pinnedPx: { [DOC_PANEL_ID]: docPinPx },
- });
- if (next === innerLayout) return;
- try {
- innerGroup.setLayout(next);
- } catch (error) {
- reportUnexpectedPanelGroupFailure('follow-outer-layout-write-failed', error);
- }
+ function pinDocPanel(docCollapsed: boolean): boolean {
+ return attemptDocPanelPin(docCollapsed) !== 'failed';
}
- function reclaimHiddenRailColumn(columnId: string, present: boolean, widthPx: number) {
+ const pinDocPanelRef = useRef(pinDocPanel);
+ useEffect(() => {
+ pinDocPanelRef.current = pinDocPanel;
+ });
+
+ function reclaimHiddenDocPanel(present: boolean, widthPx: number) {
if (present || widthPx <= 0) return;
queueMicrotask(() => {
- const innerRow = columnId === DOC_PANEL_ID;
- if (!innerRow && !editorVisibleRef.current) return;
- const group = innerRow ? innerGroupRef.current : groupRef.current;
+ const group = innerGroupRef.current;
if (group == null) return;
let layout: Record<string, number>;
let containerPx: number | null;
try {
layout = group.getLayout();
- containerPx = innerRow ? resolveInnerGroupPxWidth() : resolveGroupPxWidth();
+ containerPx = resolveInnerGroupPxWidth();
} catch (error) {
reportUnexpectedPanelGroupFailure('reclaim-hidden-rail-read-failed', error);
return;
}
- if (containerPx == null || !(columnId in layout) || layout[columnId] === 0) return;
+ if (containerPx == null || !(DOC_PANEL_ID in layout) || layout[DOC_PANEL_ID] === 0) return;
const residualId = findResidualPanelId(Object.keys(layout));
if (residualId == null) return;
const next = computeStickyRepinLayout({
currentLayout: layout,
containerPx,
- pinnedPx: { [columnId]: 0 },
+ pinnedPx: { [DOC_PANEL_ID]: 0 },
residualId,
});
if (next === layout) return;
@@ -1684,69 +1002,7 @@ function EditorAreaInner({
});
}
- function attemptRailLayout(
- docCollapsed: boolean,
- overrides?: { agentsWidthOverridePx?: number },
- ): RailLayoutRetryOutcome {
- if (railDragInProgress()) {
- if (isDraggingDocHandleRef.current) return 'blocked';
- const group = innerGroupRef.current;
- const containerPx = resolveInnerGroupPxWidth();
- if (group == null || containerPx == null) return 'blocked';
- try {
- const layout = group.getLayout();
- const residualId = findResidualPanelId(Object.keys(layout));
- if (residualId == null || !(DOC_PANEL_ID in layout)) return 'blocked';
- const collapsed =
- docCollapsed || containerPx < docPanelWidthPxRef.current + DOC_USABLE_MIN_WIDTH_PX;
- isCollapsedRef.current = collapsed;
- group.setLayout(
- computeStickyRepinLayout({
- currentLayout: layout,
- containerPx,
- pinnedPx: { [DOC_PANEL_ID]: collapsed ? 0 : docPanelWidthPxRef.current },
- residualId,
- }),
- );
- return 'blocked';
- } catch (error) {
- reportUnexpectedPanelGroupFailure('fit-information-during-outer-drag-failed', error);
- return 'failed';
- }
- }
- isCollapsedRef.current = docCollapsed;
- return applyRailLayout(docCollapsed, overrides) ? 'applied' : 'failed';
- }
-
- function assertRightRailLayout(docCollapsed: boolean): boolean {
- return attemptRailLayout(docCollapsed) !== 'failed';
- }
-
- const assertRightRailLayoutRef = useRef(assertRightRailLayout);
- useEffect(() => {
- assertRightRailLayoutRef.current = assertRightRailLayout;
- });
-
const endHandleDragRef = useRef<(() => void) | null>(null);
- function railLayoutRetryPending(): boolean {
- return (
- agentsSettlementRetryRef.current.context != null ||
- railColumnSyncRetryRef.current.context != null ||
- presenceRepinRetryRef.current.context != null ||
- editorVisibilityRetryRef.current.context != null
- );
- }
- function replanAfterDragEnd() {
- const closeRequested = dragCloseRequestedRef.current;
- dragCloseRequestedRef.current = false;
- const deferredAdmission = admissionDeferredByDragRef.current;
- admissionDeferredByDragRef.current = null;
- if (closeRequested) return;
- if (!railLayoutRetryPending()) assertRightRailLayoutRef.current(isCollapsedRef.current);
- if (deferredAdmission != null) {
- enforceRightRailAdmissionRef.current(deferredAdmission.trigger, deferredAdmission.previous);
- }
- }
function trackHandleDrag(
pointerId: number | null,
setDragging: (dragging: boolean) => void,
@@ -1769,12 +1025,12 @@ function EditorAreaInner({
if (pointerId != null && event.pointerId !== pointerId) return;
end();
onCommit?.();
- replanAfterDragEnd();
+ pinDocPanelRef.current(isCollapsedRef.current);
}
function onPointerCancel(event: PointerEvent) {
if (pointerId != null && event.pointerId !== pointerId) return;
end();
- assertRightRailLayoutRef.current(isCollapsedRef.current);
+ pinDocPanelRef.current(isCollapsedRef.current);
}
endHandleDragRef.current = end;
window.addEventListener('pointerup', onPointerUp);
@@ -1791,243 +1047,23 @@ function EditorAreaInner({
() => setPreferredDocPanelWidthPx(docPanelWidthPxRef.current),
);
}
- function beginTerminalHandleDrag(pointerId: number | null) {
- const startedOnSeparator = pointerId != null;
- trackHandleDrag(
- pointerId,
- setIsDraggingTerminalHandle,
- isDraggingTerminalHandleRef,
- () => {
- if (!terminalColumnPanelRef.current?.isCollapsed()) return;
- dragCloseRequestedRef.current = true;
- if (startedOnSeparator && onTerminalVisibleChange != null) onTerminalVisibleChange(false);
- },
- () => {
- if (!startedOnSeparator || !terminalColumnPanelRef.current?.isCollapsed()) {
- setTerminalShowingHold(false);
- }
- },
- );
- }
- function beginAgentsHandleDrag(pointerId: number | null) {
- const chatHistoryCovering =
- agentsContainer?.querySelector('[data-history-mode="cover"]') != null;
- const startedOnSeparator = pointerId != null && !chatHistoryCovering;
- cancelAgentsSettlement();
- trackHandleDrag(
- pointerId,
- setIsDraggingAgentsHandle,
- isDraggingAgentsHandleRef,
- () => settleAgentsPointerRelease({ leaveCollapsed: !startedOnSeparator }),
- () => {
- if (!startedOnSeparator || !agentsColumnPanelRef.current?.isCollapsed()) {
- setAgentsShowingHold(false);
- }
- },
+ function adoptLibraryDrag() {
+ const active = innerContainerElRef.current?.querySelector(
+ ':scope > [data-group] > [data-separator="active"]',
);
- }
- function adoptLibraryDrag(row: 'outer' | 'inner') {
- const container = row === 'outer' ? groupContainerElRef.current : innerContainerElRef.current;
- const active = container?.querySelector(':scope > [data-group] > [data-separator="active"]');
if (!(active instanceof HTMLElement)) return;
- if (row === 'inner') {
- if (active.hasAttribute('data-doc-panel-handle') && !isDraggingDocHandleRef.current) {
- beginDocHandleDrag(null);
- }
- return;
- }
- if (active.hasAttribute('data-terminal-panel-handle') && !isDraggingTerminalHandleRef.current) {
- beginTerminalHandleDrag(null);
- } else if (
- active.hasAttribute('data-agents-panel-resize-handle') &&
- !isDraggingAgentsHandleRef.current
- ) {
- beginAgentsHandleDrag(null);
+ if (active.hasAttribute('data-doc-panel-handle') && !isDraggingDocHandleRef.current) {
+ beginDocHandleDrag(null);
}
}
useEffect(() => () => endHandleDragRef.current?.(), []);
- function cancelAgentsSettlement() {
- cancelRailLayoutRetry(agentsSettlementRetryRef);
- }
-
- function cancelAgentsKeyboardSettlement() {
- if (agentsSettlementRetryRef.current.context?.decision === 'keyboard-settle-minimum') {
- cancelAgentsSettlement();
- }
- }
-
- function superviseAgentsPointerSettlement(context: AgentsPanelPointerReleaseRetryContext) {
- runRailLayoutRetry({
- retryRef: agentsSettlementRetryRef,
- attempt: () => attemptRailLayout(isCollapsedRef.current),
- context,
- });
- }
-
- function settleAgentsPointerRelease(options?: { readonly leaveCollapsed: boolean }) {
- cancelAgentsSettlement();
- const measuredWidthPx = agentsColumnPanelRef.current?.getSize().inPixels;
- const decision = resolveAgentsPanelPointerRelease(
- measuredWidthPx,
- agentsPreferredWidthPxRef.current,
- );
- const context = createAgentsPanelPointerReleaseRetryContext(decision);
- if (!editorVisibleRef.current && context.decision !== 'close') {
- superviseAgentsPointerSettlement(context);
- return;
- }
- switch (context.decision) {
- case 'close':
- if (options?.leaveCollapsed) {
- dragCloseRequestedRef.current = true;
- } else if (onAgentsVisibleChange != null) {
- pendingAgentsVisibilityRetryContextRef.current = context;
- dragCloseRequestedRef.current = true;
- onAgentsVisibleChange(false);
- } else {
- superviseAgentsPointerSettlement(context);
- }
- return;
- case 'restore-preferred':
- agentsPreferredWidthPxRef.current = context.targetWidthPx;
- superviseAgentsPointerSettlement(context);
- return;
- case 'settle-minimum':
- case 'commit-preferred':
- agentsPreferredWidthPxRef.current = context.targetWidthPx;
- writeAgentsPanelWidth(context.targetWidthPx);
- superviseAgentsPointerSettlement(context);
- return;
- default: {
- const exhaustiveContext: never = context;
- return exhaustiveContext;
- }
- }
- }
-
- function settleAgentsKeyboardLayout(layout: Record<string, number>, isUserInteraction: boolean) {
- if (!isUserInteraction || railDragInProgress() || !editorVisibleRef.current) return;
- const activeElement = document.activeElement;
- if (
- !(activeElement instanceof HTMLElement) ||
- !activeElement.hasAttribute('data-agents-panel-resize-handle')
- ) {
- cancelAgentsKeyboardSettlement();
- return;
- }
- cancelAgentsSettlement();
- const agentsPercentage = layout[AGENTS_COLUMN_ID];
- const groupWidthPx = resolveGroupPxWidth();
- if (agentsPercentage == null || groupWidthPx == null) return;
- const measuredWidthPx = (agentsPercentage / 100) * groupWidthPx;
- if (measuredWidthPx <= 0 || measuredWidthPx >= MIN_AGENTS_PANEL_WIDTH) return;
- runRailLayoutRetry({
- retryRef: agentsSettlementRetryRef,
- attempt: () =>
- attemptRailLayout(isCollapsedRef.current, {
- agentsWidthOverridePx: MIN_AGENTS_PANEL_WIDTH,
- }),
- context: {
- decision: 'keyboard-settle-minimum',
- targetWidthPx: MIN_AGENTS_PANEL_WIDTH,
- },
- });
- }
-
- // biome-ignore lint/correctness/useExhaustiveDependencies: agentsVisible and render-bound attemptRailLayout are sampled only when rail column presence changes; the presence dependencies own retry replacement
- useEffect(() => {
- if (pendingAgentsVisibilityRetryContextRef.current?.decision === 'close' && agentsVisible) {
- pendingAgentsVisibilityRetryContextRef.current = null;
- }
- const pendingContext = pendingAgentsVisibilityRetryContextRef.current;
- const context: RailLayoutRetryContext = pendingContext ?? {
- decision: 'sync-rail-columns',
- targetWidthPx: agentsVisible ? agentsPreferredWidthPxRef.current : 0,
- };
- runRailLayoutRetry({
- retryRef: railColumnSyncRetryRef,
- attempt: () => attemptRailLayout(isCollapsedRef.current),
- context,
- onExhausted:
- pendingContext == null ? () => reportRailPinExhausted('rail-column-sync') : undefined,
- onComplete: () => {
- if (pendingAgentsVisibilityRetryContextRef.current === context) {
- pendingAgentsVisibilityRetryContextRef.current = null;
- }
- },
- });
- return () => cancelRailLayoutRetry(railColumnSyncRetryRef);
- }, [terminalColumnPresent, agentsColumnPresent]);
-
- const previousEditorColumnRef = useRef({ editorVisible, editorColumnHoldsPane });
- // biome-ignore lint/correctness/useExhaustiveDependencies: render-bound attemptRailLayout is sampled when editor visibility or the editor column's contents flip; the flip owns retry replacement
- useEffect(() => {
- const previous = previousEditorColumnRef.current;
- if (
- previous.editorVisible === editorVisible &&
- previous.editorColumnHoldsPane === editorColumnHoldsPane
- ) {
- return;
- }
- previousEditorColumnRef.current = { editorVisible, editorColumnHoldsPane };
- let cancelled = false;
- queueMicrotask(() => {
- if (cancelled) return;
- runRailLayoutRetry({
- retryRef: editorVisibilityRetryRef,
- attempt: () => attemptRailLayout(isCollapsedRef.current),
- context: {
- decision: 'sync-rail-columns',
- targetWidthPx: agentsVisible ? agentsPreferredWidthPxRef.current : 0,
- },
- onComplete: () => {
- if (editorVisibleRef.current) setEditorCardPin(null);
- },
- onExhausted: () => reportRailPinExhausted('editor-visibility'),
- });
- });
- return () => {
- cancelled = true;
- cancelRailLayoutRetry(editorVisibilityRetryRef);
- };
- }, [editorVisible, editorColumnHoldsPane]);
-
- function bringBackRailColumn(targetWidthPx: number) {
- runRailLayoutRetry({
- retryRef: railColumnSyncRetryRef,
- attempt: () => attemptRailLayout(isCollapsedRef.current),
- context: { decision: 'sync-rail-columns', targetWidthPx },
- });
- }
-
useImperativeHandle(ref, () => ({
panesOnScreen: () => ({
- editor: editorVisible,
+ editor: editorVisible && dockLayout.panes.has('editor'),
agents: hasExtent(agentsContainer),
terminal: hasExtent(terminalContainer),
}),
- bringBackPane: (pane) => {
- switch (pane) {
- case 'editor':
- return;
- case 'agents':
- if (agentsColumnPresent) bringBackRailColumn(agentsPreferredWidthPxRef.current);
- return;
- case 'terminal':
- if (terminalPlacement === 'right') {
- if (terminalColumnPresent) {
- terminalCollapsedByUserRef.current = false;
- bringBackRailColumn(terminalWidthPxRef.current);
- }
- } else {
- terminalDockRef.current?.bringBackBottom();
- }
- return;
- default:
- return assertNeverPaneId(pane);
- }
- },
}));
function docPanelToggleable(): boolean {
@@ -2173,7 +1209,7 @@ function EditorAreaInner({
}
docPanelCoverOpenerRef.current =
document.activeElement instanceof HTMLElement ? document.activeElement : null;
- assertRightRailLayout(true);
+ pinDocPanel(true);
setDocPanelCover(true);
}
@@ -2182,31 +1218,13 @@ function EditorAreaInner({
revealEditorBeforeActing();
if (docPanelCover || (!isCollapsedRef.current && docPanelIntentOpen)) {
writeDocPanelIntent(false);
- assertRightRailLayout(true);
+ pinDocPanel(true);
if (docPanelCover) dismissDocPanelCover();
return;
}
expandDocPanel(true);
}
- const outerLayoutChangedRef = useRef(false);
- const lastEditorColumnPxRef = useRef<number | null>(null);
- function noteOuterLayout(layout: Record<string, number>) {
- const { residualId } = accountRailLayout(Object.keys(layout));
- const outerPx = resolveGroupPxWidth();
- const editorColumnPx =
- residualId == null || outerPx == null ? null : ((layout[residualId] ?? 0) / 100) * outerPx;
- const previousPx = lastEditorColumnPxRef.current;
- lastEditorColumnPxRef.current = editorColumnPx;
- if (
- editorColumnPx == null ||
- previousPx == null ||
- Math.abs(editorColumnPx - previousPx) > 0.5
- ) {
- outerLayoutChangedRef.current = true;
- }
- }
-
const attemptObservedDocWidth = useEffectEvent((): RailLayoutRetryOutcome => {
if (!editorVisibleRef.current) return 'applied';
if (isDraggingDocHandleRef.current) return 'blocked';
@@ -2257,52 +1275,34 @@ function EditorAreaInner({
});
});
+ const editorUnitWidthPx = dockLayout.panes.get('editor')?.width ?? null;
+ const followEditorUnit = useEffectEvent(() => {
+ attemptDocPanelPin(isCollapsedRef.current);
+ });
+ useLayoutEffect(() => {
+ if (editorUnitWidthPx !== null) followEditorUnit();
+ }, [editorUnitWidthPx]);
+
useEffect(() => {
- if (groupContainerEl == null || innerContainerEl == null) return;
+ if (innerContainerEl == null) return;
if (isEmbedded) return;
- const replanAndAdmit = () => {
- assertRightRailLayoutRef.current(isCollapsedRef.current);
- enforceRightRailAdmissionRef.current('resize', admissionVisibilityRef.current);
- };
- const outerObserver = new ResizeObserver(replanAndAdmit);
const docPanel = innerContainerEl.querySelector<HTMLElement>(`#${DOC_PANEL_ID}`);
let docSettlementFrame = 0;
- const innerObserver = new ResizeObserver((entries) => {
- if (entries.some((entry) => entry.target === docPanel)) {
- if (docSettlementFrame === 0) {
- docSettlementFrame = requestAnimationFrame(() => {
- docSettlementFrame = 0;
- settleObservedDocWidth();
- });
- }
- if (entries.every((entry) => entry.target === docPanel)) return;
- }
- if (outerLayoutChangedRef.current) {
- outerLayoutChangedRef.current = false;
- if (railPinOutcomeRef.current.stage === 'pinned') return;
- }
- replanAndAdmit();
+ const observer = new ResizeObserver(() => {
+ if (docSettlementFrame !== 0) return;
+ docSettlementFrame = requestAnimationFrame(() => {
+ docSettlementFrame = 0;
+ settleObservedDocWidth();
+ });
});
- outerObserver.observe(groupContainerEl);
- innerObserver.observe(innerContainerEl);
- if (docPanel != null) innerObserver.observe(docPanel);
+ observer.observe(innerContainerEl);
+ if (docPanel != null) observer.observe(docPanel);
return () => {
- outerObserver.disconnect();
- innerObserver.disconnect();
+ observer.disconnect();
if (docSettlementFrame !== 0) cancelAnimationFrame(docSettlementFrame);
cancelRailLayoutRetry(observedDocWidthRetryRef);
};
- }, [groupContainerEl, innerContainerEl, isEmbedded]);
-
- useEffect(() => {
- if (fileListSlotEl == null) return;
- const observer = new ResizeObserver(() => {
- if (admissionDeferredByFilesRef.current == null) return;
- enforceRightRailAdmissionRef.current('resize', admissionVisibilityRef.current);
- });
- observer.observe(fileListSlotEl);
- return () => observer.disconnect();
- }, [fileListSlotEl]);
+ }, [innerContainerEl, isEmbedded]);
const openRequestedDocPanelTab = useEffectEvent((tab: PanelTab) => {
revealEditor();
@@ -2713,7 +1713,7 @@ function EditorAreaInner({
return;
}
const collapsed = !docPanelIntentOpen || !docPanelCanDock || !docPanelDockReady;
- if (isCollapsedRef.current !== collapsed) assertRightRailLayoutRef.current(collapsed);
+ if (isCollapsedRef.current !== collapsed) pinDocPanelRef.current(collapsed);
if (docPanelCover && docPanelCanDock && docPanelDockReady) {
const pendingDestination = pendingDocPanelDestinationRef.current;
if (pendingDestination !== null) {
@@ -2836,19 +1836,29 @@ function EditorAreaInner({
return () => window.removeEventListener('keydown', onKeyDown);
}, [docPanelCover]);
+ const editorVisibleAtPinRef = useRef(editorVisible);
useLayoutEffect(() => {
const docSlotPresenceChanged = docSlotPresentRef.current !== docSlotPresent;
+ const editorShown = editorVisible && !editorVisibleAtPinRef.current;
docSlotPresentRef.current = docSlotPresent;
docSlotHeldForLoadRef.current = docSlotHeldForLoad;
- if (!docSlotPresenceChanged) return;
+ editorVisibleAtPinRef.current = editorVisible;
+ if (!docSlotPresenceChanged && !editorShown) return;
+ const docCollapsed = isCollapsedRef.current;
+ let lastMiss: DocPanelPinMiss | null = null;
runRailLayoutRetry({
retryRef: presenceRepinRetryRef,
- attempt: () => attemptRailLayout(isCollapsedRef.current),
+ attempt: () => {
+ lastMiss = null;
+ return attemptDocPanelPin(docCollapsed, (miss) => {
+ lastMiss = miss;
+ });
+ },
context: {
- decision: 'sync-doc-presence',
- targetWidthPx: agentsVisible ? agentsPreferredWidthPxRef.current : 0,
+ decision: docSlotPresenceChanged ? 'sync-doc-presence' : 'show-editor',
+ targetWidthPx: docPanelWidthPxRef.current,
},
- onExhausted: () => reportRailPinExhausted('doc-slot-presence'),
+ describeMiss: () => lastMiss,
});
});
useEffect(() => () => cancelRailLayoutRetry(presenceRepinRetryRef), []);
@@ -3027,7 +2037,7 @@ function EditorAreaInner({
adoptDraggedDocPanelWidth(size.inPixels);
debouncedWriteDocPanelWidth(size.inPixels);
}
- reclaimHiddenRailColumn(DOC_PANEL_ID, docSlotPresent, size.inPixels);
+ reclaimHiddenDocPanel(docSlotPresent, size.inPixels);
}}
inert={!docSlotPresent || isCollapsed}
className={cn('flex flex-col', SECONDARY_PANEL_SURFACE_CLASS)}
@@ -3039,152 +2049,7 @@ function EditorAreaInner({
const chatAlone = !editorVisible && agentsShowing && !terminalShowing;
const nothingOpen = !editorVisible && !agentsVisible && !terminalVisible;
- const terminalHandleShown = terminalColumnPresent && editorVisible;
- const agentsHandleShown = agentsColumnPresent && (editorColumnHoldsPane || terminalColumnPresent);
-
- const rightTerminalMount = (
- <div
- ref={setRightTerminalContainer}
- data-terminal-panel-mount=""
- inert={!terminalColumnPresent || (terminalColumnCollapsed && !terminalShowingHold)}
- className="flex min-h-0 flex-1 flex-col overflow-hidden"
- />
- );
-
- const terminalColumn = (
- <>
- <ResizableHandle
- data-terminal-panel-handle=""
- aria-controls={TERMINAL_COLUMN_ID}
- aria-label={t`Resize terminal`}
- withHandle={terminalHandleShown}
- className={cn(
- paneCardDividerClass(cardVariant, 'vertical'),
- !terminalHandleShown && 'pointer-events-none',
- )}
- style={terminalHandleShown ? undefined : { display: 'none' }}
- onPointerDown={(event) => {
- beginTerminalHandleDrag(event.pointerId);
- }}
- />
- <ResizablePanel
- id={TERMINAL_COLUMN_ID}
- panelRef={terminalColumnPanelRef}
- defaultSize={terminalColumnPresent ? `${initialTerminalWidthPx}px` : 0}
- minSize={terminalColumnPresent ? `${RIGHT_TERMINAL_PANEL_MIN_WIDTH_PX}px` : '0px'}
- maxSize={terminalColumnPresent ? undefined : '0px'}
- collapsible
- collapsedSize={0}
- onResize={(size) => {
- if (
- size.inPixels === 0 &&
- document.activeElement?.hasAttribute('data-terminal-panel-handle')
- ) {
- terminalCollapsedByUserRef.current = true;
- }
- if (
- size.inPixels > 0 &&
- isDraggingTerminalHandleRef.current &&
- editorVisibleRef.current
- ) {
- terminalWidthPxRef.current = size.inPixels;
- debouncedWriteTerminalWidth(size.inPixels);
- }
- setTerminalColumnCollapsed(size.inPixels === 0);
- if (size.inPixels > 0) terminalCollapsedByUserRef.current = false;
- if (size.inPixels === 0 && isDraggingTerminalHandleRef.current) {
- setTerminalShowingHold(true);
- } else if (size.inPixels > 0 && !isDraggingTerminalHandleRef.current) {
- setTerminalShowingHold(false);
- }
- reclaimHiddenRailColumn(TERMINAL_COLUMN_ID, terminalColumnPresent, size.inPixels);
- }}
- className="flex flex-col"
- style={{ overflow: 'visible' }}
- >
- {terminalAvailable ? (
- <PaneCard
- pane="terminal"
- variant={cardVariant}
- data-placement="right"
- className={cn(!rightTerminalCardShowing && 'shadow-none')}
- style={{
- marginInlineStart: terminalCardInsets.start,
- marginInlineEnd: terminalCardInsets.end,
- }}
- >
- {rightTerminalMount}
- </PaneCard>
- ) : (
- rightTerminalMount
- )}
- </ResizablePanel>
- </>
- );
-
- const agentsColumn = (
- <>
- <ResizableHandle
- withHandle={agentsHandleShown}
- aria-controls={terminalColumnPresent ? TERMINAL_COLUMN_ID : AGENTS_COLUMN_ID}
- aria-label={terminalColumnPresent ? t`Terminal` : t`Agents`}
- data-agents-panel-resize-handle=""
- className={cn(
- paneCardDividerClass(cardVariant, 'vertical'),
- !agentsHandleShown && 'pointer-events-none',
- )}
- style={agentsHandleShown ? undefined : { display: 'none' }}
- onPointerDown={(event) => {
- beginAgentsHandleDrag(event.pointerId);
- }}
- />
- <ResizablePanel
- id={AGENTS_COLUMN_ID}
- panelRef={agentsColumnPanelRef}
- defaultSize={agentsColumnPresent ? `${initialAgentsWidthPx}px` : 0}
- minSize="0px"
- maxSize={agentsColumnPresent ? (editorColumnHoldsPane ? '95%' : '100%') : '0px'}
- collapsible
- collapsedSize={0}
- onResize={(size) => {
- setAgentsColumnCollapsed(size.inPixels === 0);
- if (size.inPixels === 0 && isDraggingAgentsHandleRef.current) {
- setAgentsShowingHold(true);
- } else if (size.inPixels > 0 && !isDraggingAgentsHandleRef.current) {
- setAgentsShowingHold(false);
- }
- reclaimHiddenRailColumn(AGENTS_COLUMN_ID, agentsColumnPresent, size.inPixels);
- }}
- className="flex flex-col"
- style={{ overflow: 'visible' }}
- >
- <PaneCard
- pane="agents"
- variant={cardVariant}
- className={cn(
- !agentsVisible && 'invisible',
- !(agentsColumnPresent && !agentsColumnCollapsed) && 'shadow-none',
- )}
- inert={!agentsVisible}
- style={{ marginInlineStart: agentsCardInsetStartPx }}
- >
- <section
- ref={setAgentsContainer}
- data-agents-panel-mount=""
- data-chat-alone={chatAlone ? '' : undefined}
- aria-label={t`Agent panel`}
- inert={!agentsColumnPresent || (agentsColumnCollapsed && !agentsShowingHold)}
- className="flex min-h-0 flex-1 flex-col overflow-hidden"
- />
- </PaneCard>
- </ResizablePanel>
- </>
- );
-
- const railColumnMinSize = resizableRailColumnPresent ? '5%' : '30%';
- const editorColumnMinSize = editorColumnHoldsPane ? railColumnMinSize : '0%';
const workspaceAbsorbsResidual = docSlotPresent && !initialRightCollapsed;
- const outerRowDragging = isDraggingTerminalHandle || isDraggingAgentsHandle;
const workspaceHeaderTarget = (
<div
ref={setWorkspaceHeaderContainer}
@@ -3193,190 +2058,162 @@ function EditorAreaInner({
/>
);
- return (
- <div className="flex min-h-0 flex-1 flex-col">
- {noteWindow ? workspaceHeaderTarget : null}
- <div
- data-editor-area-panels=""
- className="relative flex min-h-0 flex-1"
- ref={(el) => {
- setGroupContainerEl(el);
- groupContainerElRef.current = el;
- }}
- >
- <ResizablePanelGroup
- orientation="horizontal"
- groupRef={groupRef}
- data-editor-row="outer"
- style={{ overflow: 'visible' }}
- onLayoutChange={(layout) => {
- noteOuterLayout(layout);
- if (railPlanWriteInProgressRef.current) return;
- adoptLibraryDrag('outer');
- if (isDraggingTerminalHandleRef.current || isDraggingAgentsHandleRef.current) {
- followOuterLayout(layout);
- }
- }}
- onLayoutChanged={(layout, meta) => {
- if (meta.isUserInteraction) followOuterLayout(layout);
- settleAgentsKeyboardLayout(layout, meta.isUserInteraction);
+ const editorUnit = (
+ <PaneCard
+ ref={editorCardRef}
+ pane="editor"
+ variant={cardVariant}
+ className="flex-row"
+ inert={!editorVisible}
+ data-editor-hidden={editorVisible ? undefined : ''}
+ >
+ {fileListHost != null ? (
+ <div
+ data-editor-file-list-slot=""
+ inert={docPanelCover}
+ className="relative flex shrink-0"
+ ref={fileListSlotRef}
+ />
+ ) : null}
+ <SidebarInset inert={docPanelCover || filesCover} className="min-w-0 overflow-hidden">
+ <div
+ data-editor-inner-panels=""
+ className="relative flex min-h-0 flex-1"
+ ref={(el) => {
+ setInnerContainerEl(el);
+ innerContainerElRef.current = el;
}}
- data-dragging={outerRowDragging || undefined}
>
- <ResizablePanel
- minSize={editorColumnMinSize}
- {...(resizableRailColumnPresent ? {} : { defaultSize: '100%' })}
- className="flex flex-col"
- style={{
- paddingInlineEnd: editorColumnChromePx,
- overflow: editorVisible && editorCardPin == null ? 'visible' : 'hidden',
- }}
+ <ResizablePanelGroup
+ orientation="horizontal"
+ groupRef={innerGroupRef}
+ data-editor-row="inner"
+ onLayoutChange={adoptLibraryDrag}
+ data-dragging={isDraggingDocHandle || undefined}
>
- <TerminalDock
- ref={terminalDockRef}
- editorVisible={editorVisible}
- onBottomCollapsedChange={setBottomTerminalCollapsed}
- placement={terminalPlacement}
- visible={terminalVisible}
- available={terminalAvailable}
- variant={cardVariant}
- onVisibleChange={onTerminalVisibleChange ?? (() => {})}
- onBottomContainer={setBottomTerminalContainer}
+ <ResizablePanel
+ minSize={docSlotPresent && !isCollapsed ? `${DOC_USABLE_MIN_WIDTH_PX}px` : '0%'}
+ {...(workspaceAbsorbsResidual ? {} : { defaultSize: '100%' })}
>
- <PaneCard
- ref={editorCardRef}
- pane="editor"
- variant={cardVariant}
- className={editorVisible ? 'flex-row' : 'invisible flex-row'}
- inert={!editorVisible}
- data-editor-hidden={editorVisible ? undefined : ''}
- style={
- editorCardPin == null
- ? undefined
- : { width: editorCardPin.width, height: editorCardPin.height, flex: 'none' }
- }
+ <main
+ ref={setWorkspaceColumnEl}
+ data-editor-workspace-column=""
+ className="flex h-full min-w-0 flex-col"
>
- {fileListHost != null ? (
- <div
- data-editor-file-list-slot=""
- inert={docPanelCover}
- className="relative flex shrink-0"
- ref={fileListSlotRef}
- />
- ) : null}
- <SidebarInset
- inert={docPanelCover || filesCover}
- className="min-w-0 overflow-hidden"
+ {noteWindow ? null : workspaceHeaderTarget}
+ {documentArea}
+ </main>
+ </ResizablePanel>
+ {docSlot}
+ </ResizablePanelGroup>
+ </div>
+ </SidebarInset>
+ {filesCover && fileListHost != null ? (
+ <section
+ aria-label={t`Files`}
+ data-files-cover=""
+ className={cn(
+ 'absolute inset-0 z-20 flex min-h-0 min-w-0 flex-col',
+ SECONDARY_PANEL_SURFACE_CLASS,
+ )}
+ >
+ <div ref={setFilesCoverTarget} className="relative min-h-0 flex-1" />
+ </section>
+ ) : null}
+ {docPanelCover && docSlotPresent ? (
+ <section
+ id="doc-panel-cover"
+ aria-label={t`Document panel`}
+ data-doc-panel-cover=""
+ className={cn(
+ 'absolute inset-0 z-20 flex min-h-0 min-w-0 flex-col',
+ SECONDARY_PANEL_SURFACE_CLASS,
+ )}
+ >
+ <div className="flex h-11 shrink-0 items-center gap-1 px-2">
+ <Button
+ ref={docPanelBackRef}
+ data-doc-panel-back=""
+ variant="ghost"
+ size="icon-sm"
+ aria-label={t`Back to editor`}
+ title={t`Back to editor`}
+ onClick={dismissDocPanelCover}
+ onKeyDown={(event) => {
+ if (event.key !== 'Escape' || isOverlayLayerOpen()) return;
+ event.preventDefault();
+ dismissDocPanelCover();
+ }}
+ >
+ <ChevronLeft aria-hidden="true" />
+ </Button>
+ <h2 className="min-w-0 flex-1 truncate font-mono text-xs font-normal uppercase tracking-wide text-muted-foreground">
+ {activeDocName ?? t`Activity`}
+ </h2>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ data-doc-panel-hide=""
+ variant="ghost"
+ size="icon-sm"
+ aria-label={t`Hide panel`}
+ onClick={togglePanel}
>
- <div
- data-editor-inner-panels=""
- className="relative flex min-h-0 flex-1"
- ref={(el) => {
- setInnerContainerEl(el);
- innerContainerElRef.current = el;
- }}
- >
- <ResizablePanelGroup
- orientation="horizontal"
- groupRef={innerGroupRef}
- data-editor-row="inner"
- onLayoutChange={() => {
- if (railPlanWriteInProgressRef.current) return;
- adoptLibraryDrag('inner');
- }}
- onLayoutChanged={(layout, meta) => {
- settleAgentsKeyboardLayout(layout, meta.isUserInteraction);
- }}
- data-dragging={isDraggingDocHandle || undefined}
- >
- <ResizablePanel
- minSize={
- docSlotPresent && !isCollapsed ? `${DOC_USABLE_MIN_WIDTH_PX}px` : '0%'
- }
- {...(workspaceAbsorbsResidual ? {} : { defaultSize: '100%' })}
- >
- <main
- ref={setWorkspaceColumnEl}
- data-editor-workspace-column=""
- className="flex h-full min-w-0 flex-col"
- >
- {noteWindow ? null : workspaceHeaderTarget}
- {documentArea}
- </main>
- </ResizablePanel>
- {docSlot}
- </ResizablePanelGroup>
- </div>
- </SidebarInset>
- {filesCover && fileListHost != null ? (
- <section
- aria-label={t`Files`}
- data-files-cover=""
- className={cn(
- 'absolute inset-0 z-20 flex min-h-0 min-w-0 flex-col',
- SECONDARY_PANEL_SURFACE_CLASS,
- )}
- >
- <div ref={setFilesCoverTarget} className="relative min-h-0 flex-1" />
- </section>
- ) : null}
- {docPanelCover && docSlotPresent ? (
- <section
- id="doc-panel-cover"
- aria-label={t`Document panel`}
- data-doc-panel-cover=""
- className={cn(
- 'absolute inset-0 z-20 flex min-h-0 min-w-0 flex-col',
- SECONDARY_PANEL_SURFACE_CLASS,
- )}
- >
- <div className="flex h-11 shrink-0 items-center gap-1 px-2">
- <Button
- ref={docPanelBackRef}
- data-doc-panel-back=""
- variant="ghost"
- size="icon-sm"
- aria-label={t`Back to editor`}
- title={t`Back to editor`}
- onClick={dismissDocPanelCover}
- onKeyDown={(event) => {
- if (event.key !== 'Escape' || isOverlayLayerOpen()) return;
- event.preventDefault();
- dismissDocPanelCover();
- }}
- >
- <ChevronLeft aria-hidden="true" />
- </Button>
- <h2 className="min-w-0 flex-1 truncate font-mono text-xs font-normal uppercase tracking-wide text-muted-foreground">
- {activeDocName ?? t`Activity`}
- </h2>
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- data-doc-panel-hide=""
- variant="ghost"
- size="icon-sm"
- aria-label={t`Hide panel`}
- onClick={togglePanel}
- >
- <PanelRightClose aria-hidden="true" />
- </Button>
- </TooltipTrigger>
- <TooltipContent
- side="bottom"
- sideOffset={8}
- >{t`Hide panel`}</TooltipContent>
- </Tooltip>
- </div>
- <div ref={docPanelCoverRef} className="min-h-0 flex-1" />
- </section>
- ) : null}
- </PaneCard>
- </TerminalDock>
- </ResizablePanel>
- {terminalColumn}
- {agentsColumn}
- </ResizablePanelGroup>
+ <PanelRightClose aria-hidden="true" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent side="bottom" sideOffset={8}>{t`Hide panel`}</TooltipContent>
+ </Tooltip>
+ </div>
+ <div ref={docPanelCoverRef} className="min-h-0 flex-1" />
+ </section>
+ ) : null}
+ </PaneCard>
+ );
+
+ const agentsUnit = noteWindow ? null : (
+ <PaneCard pane="agents" variant={cardVariant}>
+ <section
+ ref={setAgentsContainer}
+ data-agents-panel-mount=""
+ data-chat-alone={chatAlone ? '' : undefined}
+ aria-label={t`Agent panel`}
+ inert={!agentsUnitShown}
+ className="flex min-h-0 flex-1 flex-col overflow-hidden"
+ />
+ </PaneCard>
+ );
+
+ const terminalUnit = terminalAvailable ? (
+ <PaneCard
+ pane="terminal"
+ variant={cardVariant}
+ data-placement={terminalPlacement}
+ style={{ backgroundColor: xtermBackground }}
+ >
+ <div
+ ref={setTerminalContainer}
+ data-terminal-panel-mount=""
+ inert={!terminalUnitShown}
+ className="flex min-h-0 flex-1 flex-col overflow-hidden"
+ />
+ </PaneCard>
+ ) : null;
+
+ return (
+ <div className="flex min-h-0 flex-1 flex-col">
+ {noteWindow ? workspaceHeaderTarget : null}
+ <div data-editor-area-panels="" className="relative flex min-h-0 flex-1">
+ <DockWorkspace
+ tree={dockTree}
+ visible={{ editor: editorVisible, agents: agentsUnitShown, terminal: terminalUnitShown }}
+ units={{ editor: editorUnit, agents: agentsUnit, terminal: terminalUnit }}
+ gap={cardLook ? PANE_CARD_GAP_PX : 0}
+ minExtent={dockPaneMinExtent}
+ paneLabel={(pane) => t(PANE_LABEL[pane])}
+ onTreeChange={onDockTreeChange}
+ onLayoutChange={setDockLayout}
+ />
{nothingOpen ? <NothingOpen /> : null}
</div>
{createPortal(docSlotContent, docPanelHost)}
diff --git a/packages/app/src/components/EditorPane.agents-panel-reload-visibility.dom.test.tsx b/packages/app/src/components/EditorPane.agents-panel-reload-visibility.dom.test.tsx
index 47629f211..b770b4652 100644
--- a/packages/app/src/components/EditorPane.agents-panel-reload-visibility.dom.test.tsx
+++ b/packages/app/src/components/EditorPane.agents-panel-reload-visibility.dom.test.tsx
@@ -1,6 +1,6 @@
import type { ThreadInfo } from '@inkeep/open-knowledge-core/acp/thread-protocol';
import * as actualLinguiMacro from '@lingui/react/macro';
-import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
import type { ReactNode } from 'react';
import { useEffect, useState, useSyncExternalStore } from 'react';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
@@ -171,11 +171,9 @@ vi.doMock('./EditorHeader', () => ({
vi.doMock('./EditorArea', () => ({
EditorArea: ({
agentsVisible,
- onAgentsVisibleChange,
onSessionPlacements,
}: {
agentsVisible?: boolean;
- onAgentsVisibleChange?: (visible: boolean) => void;
onSessionPlacements?: (placements: unknown) => void;
}) => {
const [agentsContainer] = useState(() => document.createElement('div'));
@@ -195,17 +193,7 @@ vi.doMock('./EditorArea', () => ({
terminalContainer.remove();
};
}, [agentsContainer, terminalContainer]);
- if (agentsVisible)
- return (
- <div data-testid="agents-column">
- <button
- type="button"
- data-testid="agents-collapse"
- onClick={() => onAgentsVisibleChange?.(false)}
- />
- </div>
- );
- return null;
+ return agentsVisible ? <div data-testid="agents-column" /> : null;
},
}));
@@ -390,7 +378,7 @@ describe('EditorPane agents-panel reload visibility', () => {
expect(screen.queryByTestId('agents-column')).not.toBeNull();
});
- test('web: a thread arriving after a persisted-open reload is collapsed reveals the panel', async () => {
+ test('web: a thread arriving after a persisted-open reload is closed reveals the panel', async () => {
seedPersistedAgentsPanelLevel(true);
await renderPane(3);
@@ -401,7 +389,7 @@ describe('EditorPane agents-panel reload visibility', () => {
deliverRosterThreads([makeThread({ threadId: 't1' })]);
});
await act(async () => {
- fireEvent.click(screen.getByTestId('agents-collapse'));
+ paneVisibilityStore.request('agents', false);
});
expect(paneVisibilityStore.getSnapshot().agents?.open).toBe(false);
@@ -800,7 +788,7 @@ describe('EditorPane agents-panel reload visibility', () => {
paneVisibilityStore.request('agents', true);
});
await act(async () => {
- fireEvent.click(screen.getByTestId('agents-collapse'));
+ paneVisibilityStore.request('agents', false);
});
expect(viewMenuStates).not.toContainEqual({
agentPanelVisible: true,
@@ -850,7 +838,7 @@ describe('EditorPane agents-panel reload visibility', () => {
paneVisibilityStore.request('agents', true);
});
await act(async () => {
- fireEvent.click(screen.getByTestId('agents-collapse'));
+ paneVisibilityStore.request('agents', false);
});
expect(viewMenuStates).not.toContainEqual({
agentPanelVisible: false,
@@ -919,7 +907,7 @@ describe('EditorPane agents-panel reload visibility', () => {
).toBe(true);
await act(async () => {
- fireEvent.click(screen.getByTestId('agents-collapse'));
+ paneVisibilityStore.request('agents', false);
});
expect(viewMenuStates).toContainEqual({
diff --git a/packages/app/src/components/EditorPane.dom.test.tsx b/packages/app/src/components/EditorPane.dom.test.tsx
index e8767d9c7..6f7c6a749 100644
--- a/packages/app/src/components/EditorPane.dom.test.tsx
+++ b/packages/app/src/components/EditorPane.dom.test.tsx
@@ -4,7 +4,7 @@ import userEvent from '@testing-library/user-event';
import { type Editor, getSchema, isMacOS } from '@tiptap/core';
import type { Node as PmNode } from '@tiptap/pm/model';
import { type ReactNode, type Ref, useEffect, useImperativeHandle } from 'react';
-import { afterEach, describe, expect, test, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import * as Y from 'yjs';
import { registerEditor, unregisterEditor } from '@/editor/active-editor';
import { collectImageParts } from '@/editor/composer-drop.test-helper';
@@ -23,6 +23,16 @@ import {
reloadRegisteredAgentsFromStorage,
setDetectedRegisteredAgentSuggestions,
} from '@/lib/acp/registered-agents';
+import {
+ type DockArrangement,
+ dockArrangementStorageKey,
+ dockTerminalPlacement,
+ legacyDockArrangement,
+ readDockArrangement,
+ withDockTerminalPlacement,
+ writeDockArrangement,
+} from '@/lib/dock-arrangement-store';
+import { type DockNode, moveDockPane } from '@/lib/dock-tree';
import { narrowWorkspaceSessionKey } from '@/lib/narrow-workspace-session';
import {
__resetPaneVisibilityStoreForTests,
@@ -184,8 +194,10 @@ vi.doMock('@/lib/config-provider', () => ({
}));
let workspaceContentDir: string | null = '/tmp/project';
+let workspaceKnown = true;
vi.doMock('@/lib/use-workspace', () => ({
- useWorkspace: () => ({ contentDir: workspaceContentDir, pathSeparator: '/' }),
+ useWorkspace: () =>
+ workspaceKnown ? { contentDir: workspaceContentDir, pathSeparator: '/' } : null,
}));
let activeProvider: { document: Y.Doc } | undefined;
@@ -222,7 +234,7 @@ type MockPlacements = {
let reportedPlacements: MockPlacements | null = null;
type MockPaneExtents = Record<PaneId, boolean>;
-const PANES_WITH_EXTENT: MockPaneExtents = { agents: true, terminal: true };
+const PANES_WITH_EXTENT: MockPaneExtents = { editor: true, agents: true, terminal: true };
let paneExtents: MockPaneExtents = { ...PANES_WITH_EXTENT };
let reportPaneExtentChange: (() => void) | undefined;
@@ -233,7 +245,6 @@ function setPaneExtent(pane: PaneId, hasExtent: boolean): void {
type MockEditorAreaHandle = {
panesOnScreen(): MockPaneExtents;
- bringBackPane(pane: PaneId): void;
};
function MockPaneExtentHandle({
@@ -246,10 +257,6 @@ function MockPaneExtentHandle({
reportPaneExtentChange = onPaneExtentChange;
useImperativeHandle(handleRef, () => ({
panesOnScreen: () => ({ ...paneExtents }),
- bringBackPane: (pane) => {
- paneExtents = { ...paneExtents, [pane]: true };
- onPaneExtentChange?.();
- },
}));
return null;
}
@@ -265,13 +272,16 @@ function ReportPlacements({
return null;
}
+let drawnDockTrees: DockNode[] = [];
+let changeDrawnDockTree: ((update: (tree: DockNode) => DockNode) => void) | undefined;
+
vi.doMock('./EditorArea', () => ({
EditorArea: ({
ref,
onPaneExtentChange,
renderWorkspaceHeader,
- terminalPlacement,
- terminalRightWidth,
+ dockTree,
+ onDockTreeChange,
editorVisible,
onSessionPlacements,
}: {
@@ -279,21 +289,24 @@ vi.doMock('./EditorArea', () => ({
editorVisible?: boolean;
onPaneExtentChange?: () => void;
renderWorkspaceHeader?: (tabs: ReactNode, chrome: { trailing: ReactNode }) => ReactNode;
- terminalPlacement?: string;
- terminalRightWidth?: number;
+ dockTree: DockNode;
+ onDockTreeChange: (update: (tree: DockNode) => DockNode) => void;
onSessionPlacements?: (placements: MockPlacements) => void;
- }) => (
- <div
- data-testid="editor-area"
- data-terminal-placement={terminalPlacement}
- data-terminal-right-width={terminalRightWidth}
- data-editor-visible={String(editorVisible)}
- >
- {renderWorkspaceHeader?.(<div data-testid="workspace-tabs" />, { trailing: null })}
- <ReportPlacements onSessionPlacements={onSessionPlacements} />
- <MockPaneExtentHandle handleRef={ref} onPaneExtentChange={onPaneExtentChange} />
- </div>
- ),
+ }) => {
+ drawnDockTrees.push(dockTree);
+ changeDrawnDockTree = onDockTreeChange;
+ return (
+ <div
+ data-testid="editor-area"
+ data-terminal-placement={dockTerminalPlacement(dockTree)}
+ data-editor-visible={String(editorVisible)}
+ >
+ {renderWorkspaceHeader?.(<div data-testid="workspace-tabs" />, { trailing: null })}
+ <ReportPlacements onSessionPlacements={onSessionPlacements} />
+ <MockPaneExtentHandle handleRef={ref} onPaneExtentChange={onPaneExtentChange} />
+ </div>
+ );
+ },
}));
vi.doMock('./acp/AgentThreadClientBinder', () => ({
AgentThreadClientBinder: () => null,
@@ -802,6 +815,28 @@ describe('EditorPane session-panel wiring', () => {
expect(placement()).toBe('bottom');
});
+ test('desktop: two move-terminal actions in one task bring the terminal back where it started', async () => {
+ const desk = makeOkDesktopStub();
+ (window as { okDesktop?: unknown }).okDesktop = desk.stub;
+ await renderEditorPane();
+ const placement = () =>
+ screen.getByTestId('editor-area').getAttribute('data-terminal-placement');
+ expect(placement()).toBe('bottom');
+
+ act(() => {
+ desk.dispatchMenuAction('move-terminal');
+ desk.dispatchMenuAction('move-terminal');
+ });
+ expect(placement()).toBe('bottom');
+
+ act(() => {
+ desk.dispatchMenuAction('move-terminal');
+ desk.dispatchMenuAction('move-terminal');
+ desk.dispatchMenuAction('move-terminal');
+ });
+ expect(placement()).toBe('right');
+ });
+
test('desktop: hiding the terminal clears the launch intent so a reopen is blank (regression)', async () => {
const desk = makeOkDesktopStub();
(window as { okDesktop?: unknown }).okDesktop = desk.stub;
@@ -1055,9 +1090,8 @@ describe('EditorPane session-panel wiring', () => {
expect(screen.getByTestId('terminal-dock').getAttribute('data-visible')).toBe('true');
});
- test('desktop: per-install right layout reaches both editor and stable terminal host', async () => {
+ test('desktop: a per-install right placement reaches both the editor and the stable terminal host', async () => {
localStorage.setItem('ok-terminal-placement-v1', 'right');
- localStorage.setItem('ok-terminal-right-width-v1', '812');
const desk = makeOkDesktopStub(async () => ({
terminalVisible: true,
agentPanelVisible: false,
@@ -1067,7 +1101,6 @@ describe('EditorPane session-panel wiring', () => {
await renderEditorPane();
expect(screen.getByTestId('editor-area').getAttribute('data-terminal-placement')).toBe('right');
- expect(screen.getByTestId('editor-area').getAttribute('data-terminal-right-width')).toBe('812');
expect(screen.getByTestId('terminal-dock').getAttribute('data-terminal-placement')).toBe(
'right',
);
@@ -1076,7 +1109,6 @@ describe('EditorPane session-panel wiring', () => {
test('desktop: a late project-state restore cannot override a user-owned per-install layout', async () => {
localStorage.setItem('ok-terminal-placement-v1', 'right');
- localStorage.setItem('ok-terminal-right-width-v1', '812');
let resolveDockState: ((state: DockStateResult) => void) | undefined;
const desk = makeOkDesktopStub(
() =>
@@ -1089,7 +1121,6 @@ describe('EditorPane session-panel wiring', () => {
render(<EditorPane />);
expect(screen.getByTestId('editor-area').getAttribute('data-terminal-placement')).toBe('right');
- expect(screen.getByTestId('editor-area').getAttribute('data-terminal-right-width')).toBe('812');
await userEvent.click(screen.getByRole('button', { name: 'Move mock Terminal bottom' }));
expect(screen.getByTestId('editor-area').getAttribute('data-terminal-placement')).toBe(
@@ -1108,7 +1139,6 @@ describe('EditorPane session-panel wiring', () => {
expect(screen.getByTestId('editor-area').getAttribute('data-terminal-placement')).toBe(
'bottom',
);
- expect(screen.getByTestId('editor-area').getAttribute('data-terminal-right-width')).toBe('812');
expect(desk.dockStateUpdates).toEqual([]);
});
@@ -2017,32 +2047,6 @@ describe('EditorPane pane visibility for the header', () => {
});
});
- test('a show request for an open pane at zero size brings it back without hiding and reshowing it', async () => {
- const desk = makeOkDesktopStub(async () => ({
- terminalVisible: true,
- agentPanelVisible: true,
- }));
- (window as { okDesktop?: unknown }).okDesktop = desk.stub;
- await renderEditorPane();
- setPaneExtent('terminal', false);
- setPaneExtent('agents', false);
- const opensBefore = terminalOpenedCalls.length;
- const menuPushesBefore = desk.viewMenuPushes.length;
-
- act(() => paneVisibilityStore.request('terminal', true));
- act(() => paneVisibilityStore.request('agents', true));
-
- expect(paneVisibilityStore.getSnapshot()).toEqual({
- editor: { open: true, onScreen: true },
- agents: { open: true, onScreen: true },
- terminal: { open: true, onScreen: true },
- });
- expect(screen.getByTestId('terminal-dock').getAttribute('data-visible')).toBe('true');
- expect(screen.getByTestId('agents-panel').getAttribute('data-visible')).toBe('true');
- expect(terminalOpenedCalls).toHaveLength(opensBefore);
- expect(desk.viewMenuPushes.slice(menuPushesBefore)).toEqual([]);
- });
-
test('a hide request for a pane on screen still hides it', async () => {
(window as { okDesktop?: unknown }).okDesktop = makeOkDesktopStub(async () => ({
terminalVisible: true,
@@ -2735,6 +2739,132 @@ describe('EditorPane saves and restores whether the editor is shown', () => {
});
});
+describe('EditorPane keeps each project its own dock arrangement', () => {
+ beforeEach(() => {
+ drawnDockTrees = [];
+ (window as { okDesktop?: unknown }).okDesktop = makeOkDesktopStub().stub;
+ });
+
+ afterEach(() => {
+ cleanup();
+ delete (window as { okDesktop?: unknown }).okDesktop;
+ localStorage.clear();
+ workspaceContentDir = '/tmp/project';
+ workspaceKnown = true;
+ drawnDockTrees = [];
+ changeDrawnDockTree = undefined;
+ });
+
+ const NO_LEGACY_KEYS = { getItem: () => null };
+ const seed = (): DockArrangement =>
+ legacyDockArrangement(
+ { widthPx: window.innerWidth, heightPx: window.innerHeight },
+ NO_LEGACY_KEYS,
+ );
+ const rightTerminal = (): DockArrangement => withDockTerminalPlacement(seed(), 'right');
+ const drawnPlacement = () =>
+ screen.getByTestId('editor-area').getAttribute('data-terminal-placement');
+ function storedDockKeys(): string[] {
+ const keys: string[] = [];
+ for (let index = 0; index < localStorage.length; index += 1) {
+ const key = localStorage.key(index);
+ if (key?.startsWith('ok-dock-arrangement-v1')) keys.push(key);
+ }
+ return keys;
+ }
+ const moveTerminalRight = (tree: DockNode) => moveDockPane(tree, 'terminal', 'editor', 'end');
+
+ test('the first layout drawn is the arrangement the project stored', async () => {
+ writeDockArrangement(dockArrangementStorageKey('/tmp/project'), rightTerminal());
+ await renderEditorPane();
+
+ const first = drawnDockTrees[0];
+ if (first === undefined) throw new Error('the editor area never drew');
+ expect(dockTerminalPlacement(first)).toBe('right');
+ expect(drawnPlacement()).toBe('right');
+ });
+
+ test('nothing is saved until the layout changes, and a change is saved under the project key', async () => {
+ await renderEditorPane();
+ expect(drawnPlacement()).toBe('bottom');
+ expect(storedDockKeys()).toEqual([]);
+
+ act(() => changeDrawnDockTree?.(moveTerminalRight));
+
+ expect(drawnPlacement()).toBe('right');
+ expect(storedDockKeys()).toEqual([dockArrangementStorageKey('/tmp/project')]);
+ const saved = readDockArrangement(dockArrangementStorageKey('/tmp/project'));
+ expect(saved === null ? null : dockTerminalPlacement(saved.tree)).toBe('right');
+ });
+
+ test('a project switch draws that project’s arrangement, or the same seed a reload gives it', async () => {
+ writeDockArrangement(dockArrangementStorageKey('/tmp/project-b'), rightTerminal());
+ workspaceContentDir = '/tmp/project-a';
+ const view = await renderEditorPane();
+ const { EditorPane } = await import('./EditorPane');
+ expect(drawnPlacement()).toBe('bottom');
+
+ workspaceContentDir = '/tmp/project-b';
+ act(() => view.rerender(<EditorPane />));
+ expect(drawnPlacement()).toBe('right');
+
+ workspaceContentDir = '/tmp/project-c';
+ act(() => view.rerender(<EditorPane />));
+ expect(drawnPlacement()).toBe('bottom');
+ const switched = drawnDockTrees.at(-1);
+
+ cleanup();
+ await renderEditorPane();
+ expect(drawnDockTrees.at(-1)).toEqual(switched);
+ expect(storedDockKeys()).toEqual([dockArrangementStorageKey('/tmp/project-b')]);
+ });
+
+ test('on the web the first layout drawn is the one stored for the origin, and it holds when the project becomes known', async () => {
+ delete (window as { okDesktop?: unknown }).okDesktop;
+ writeDockArrangement(dockArrangementStorageKey(null), rightTerminal());
+ workspaceKnown = false;
+ const view = await renderEditorPane();
+ const { EditorPane } = await import('./EditorPane');
+
+ const first = drawnDockTrees[0];
+ if (first === undefined) throw new Error('the editor area never drew');
+ expect(dockTerminalPlacement(first)).toBe('right');
+
+ workspaceKnown = true;
+ act(() => view.rerender(<EditorPane />));
+
+ expect(drawnDockTrees.length).toBeGreaterThan(1);
+ expect(drawnDockTrees.map(dockTerminalPlacement)).toEqual(drawnDockTrees.map(() => 'right'));
+ });
+
+ test('a layout change in one project stays with it when the window switches to a project with none saved', async () => {
+ workspaceContentDir = '/tmp/project-a';
+ const view = await renderEditorPane();
+ const { EditorPane } = await import('./EditorPane');
+ act(() => changeDrawnDockTree?.(moveTerminalRight));
+ expect(drawnPlacement()).toBe('right');
+
+ workspaceContentDir = '/tmp/project-b';
+ act(() => view.rerender(<EditorPane />));
+
+ expect(drawnPlacement()).toBe('bottom');
+ expect(storedDockKeys()).toEqual([dockArrangementStorageKey('/tmp/project-a')]);
+ });
+
+ test('on the web a layout change is saved under the origin’s name while the project is still unknown', async () => {
+ delete (window as { okDesktop?: unknown }).okDesktop;
+ workspaceKnown = false;
+ await renderEditorPane();
+ act(() => changeDrawnDockTree?.(moveTerminalRight));
+ await act(async () => {});
+
+ expect(drawnPlacement()).toBe('right');
+ expect(storedDockKeys()).toEqual([dockArrangementStorageKey(null)]);
+ const saved = readDockArrangement(dockArrangementStorageKey(null));
+ expect(saved === null ? null : dockTerminalPlacement(saved.tree)).toBe('right');
+ });
+});
+
describe('EditorPane mode switch promotes the preview tab', () => {
afterEach(() => {
cleanup();
diff --git a/packages/app/src/components/EditorPane.tsx b/packages/app/src/components/EditorPane.tsx
index 1057dce40..a7b1bf01c 100644
--- a/packages/app/src/components/EditorPane.tsx
+++ b/packages/app/src/components/EditorPane.tsx
@@ -36,7 +36,17 @@ import { usePreferredSessionSelection } from '@/lib/acp/use-preferred-session-se
import type { AuthPromptStep } from '@/lib/auth-prompt-store';
import { loadBoolPref, saveBoolPref } from '@/lib/bool-pref';
import { useConfigContext } from '@/lib/config-provider';
+import {
+ type DockArrangement,
+ dockArrangementStorageKey,
+ dockTerminalPlacement,
+ legacyDockArrangement,
+ readDockArrangement,
+ withDockTerminalPlacement,
+ writeDockArrangement,
+} from '@/lib/dock-arrangement-store';
import { readWebDockSessionOrder } from '@/lib/dock-session-persistence';
+import type { DockNode } from '@/lib/dock-tree';
import { focusAwayFromHiddenEditor } from '@/lib/editor-hidden-focus';
import { matchesKeyboardShortcut, matchesRendererShortcut } from '@/lib/keyboard-shortcuts';
import { subscribeLocalMenuAction } from '@/lib/local-menu-action-bus';
@@ -57,8 +67,6 @@ import {
import { RESTORE_SETTLE_TIMEOUT_MS } from '@/lib/restore-settle-timeout';
import { revealEditorBeforeActing } from '@/lib/reveal-editor';
import { useSingleFileMode } from '@/lib/single-file-mode';
-import { readTerminalPlacement, writeTerminalPlacement } from '@/lib/terminal-placement-store';
-import { readTerminalRightWidth, writeTerminalRightWidth } from '@/lib/terminal-right-width-store';
import { recordTerminalOpened } from '@/lib/terminal-telemetry';
import { useWorkspace } from '@/lib/use-workspace';
import { setViewMenuState } from '@/lib/view-menu-state-store';
@@ -476,6 +484,19 @@ function narrowWorkspaceSnapshot(): boolean {
return window.matchMedia(NARROW_WORKSPACE_QUERY).matches;
}
+interface ProjectDock {
+ readonly key: string;
+ readonly arrangement: DockArrangement;
+ readonly edited: boolean;
+}
+
+function loadDockArrangement(key: string): DockArrangement {
+ return (
+ readDockArrangement(key) ??
+ legacyDockArrangement({ widthPx: window.innerWidth, heightPx: window.innerHeight })
+ );
+}
+
function makeRestoreVisibilityGate(mountLevel: boolean): RestoreVisibilityGate {
return { pendingWithhold: false, levelEstablished: false, lastLevel: mountLevel };
}
@@ -587,16 +608,51 @@ export function EditorPane() {
}, [exclusive, readyNarrowSessionKey, narrowSessionKey, narrowSelection]);
const [terminalVisible, setTerminalVisible] = useState<boolean>(RESTORE_UNESTABLISHED_LEVEL);
const [terminalRestoreRevealNonce, setTerminalRestoreRevealNonce] = useState(0);
- const [terminalPlacement, setTerminalPlacement] = useState<TerminalPlacement>(() =>
- readTerminalPlacement(),
+ const dockArrangementKey = dockArrangementStorageKey(
+ desktopBridge === null ? null : (workspace?.contentDir ?? null),
);
- const [terminalRightWidth, setTerminalRightWidth] = useState(() => readTerminalRightWidth());
- useEffect(() => {
- writeTerminalPlacement(terminalPlacement);
- }, [terminalPlacement]);
+ const [dock, setDock] = useState<ProjectDock>(() => ({
+ key: dockArrangementKey,
+ arrangement: loadDockArrangement(dockArrangementKey),
+ edited: false,
+ }));
+ if (dock.key !== dockArrangementKey) {
+ setDock({
+ key: dockArrangementKey,
+ arrangement: loadDockArrangement(dockArrangementKey),
+ edited: false,
+ });
+ }
useEffect(() => {
- writeTerminalRightWidth(terminalRightWidth);
- }, [terminalRightWidth]);
+ if (dock.edited) writeDockArrangement(dock.key, dock.arrangement);
+ }, [dock]);
+ function updateDockArrangement(update: (current: DockArrangement) => DockArrangement) {
+ setDock((current) => {
+ const arrangement = update(current.arrangement);
+ return arrangement === current.arrangement
+ ? current
+ : { key: current.key, arrangement, edited: true };
+ });
+ }
+ function changeDockTree(update: (tree: DockNode) => DockNode) {
+ updateDockArrangement((current) => {
+ const tree = update(current.tree);
+ return tree === current.tree ? current : { tree, terminalShares: current.terminalShares };
+ });
+ }
+ const dockTree = dock.arrangement.tree;
+ const terminalPlacement = dockTerminalPlacement(dockTree);
+ function placeTerminal(placement: TerminalPlacement) {
+ updateDockArrangement((current) => withDockTerminalPlacement(current, placement));
+ }
+ const moveTerminalEvent = useEffectEvent(() => {
+ updateDockArrangement((current) =>
+ withDockTerminalPlacement(
+ current,
+ dockTerminalPlacement(current.tree) === 'bottom' ? 'right' : 'bottom',
+ ),
+ );
+ });
const [agentsVisible, setAgentsVisible] = useState<boolean>(() =>
desktopBridge == null
? (readWebDockSessionOrder('agents')?.agentPanelVisible ?? false)
@@ -807,11 +863,6 @@ export function EditorPane() {
applyPaneRequest(pane, open);
return;
}
- const shown = paneVisibilityStore.getSnapshot()[pane];
- if (open && shown?.open === true && !shown.onScreen) {
- editorAreaRef.current?.bringBackPane(pane);
- return;
- }
switch (pane) {
case 'editor':
if (!editorToggleable) return;
@@ -904,7 +955,7 @@ export function EditorPane() {
if (action === 'toggle-terminal') {
toggleTerminalEvent();
} else if (action === 'move-terminal') {
- setTerminalPlacement((placement) => (placement === 'bottom' ? 'right' : 'bottom'));
+ moveTerminalEvent();
} else if (action === 'new-terminal') {
showTerminalEvent();
} else if (action === 'toggle-agent-panel') {
@@ -1248,12 +1299,9 @@ export function EditorPane() {
terminalBridge={terminalAvailable ? desktopBridge : null}
editorVisible={effectiveEditorVisible}
terminalVisible={noteWindow ? false : effectiveTerminalVisible}
- terminalPlacement={terminalPlacement}
- terminalRightWidth={terminalRightWidth}
- onTerminalVisibleChange={handleTerminalVisibleChange}
- onTerminalRightWidthChange={setTerminalRightWidth}
agentsVisible={noteWindow ? false : effectiveAgentsVisible}
- onAgentsVisibleChange={handleAgentsVisibleChange}
+ dockTree={dockTree}
+ onDockTreeChange={changeDockTree}
onSessionPlacements={setPlacements}
renderWorkspaceHeader={createWorkspaceHeaderRenderer({
noteWindow,
@@ -1292,7 +1340,7 @@ export function EditorPane() {
<SessionsHost
surface="terminal-dock"
terminalPlacement={terminalPlacement}
- onTerminalPlacementChange={setTerminalPlacement}
+ onTerminalPlacementChange={placeTerminal}
bridge={desktopBridge}
terminalCapable
visible={effectiveTerminalVisible}
diff --git a/packages/app/src/components/HeaderPaneButtons.tsx b/packages/app/src/components/HeaderPaneButtons.tsx
index fef9d67aa..6a82ac2b2 100644
--- a/packages/app/src/components/HeaderPaneButtons.tsx
+++ b/packages/app/src/components/HeaderPaneButtons.tsx
@@ -1,6 +1,6 @@
import { useLingui } from '@lingui/react/macro';
import { useEffect, useState, useSyncExternalStore } from 'react';
-import { PANE_ICON } from '@/components/pane-icons';
+import { PANE_ICON, PANE_LABEL } from '@/components/pane-icons';
import { Button } from '@/components/ui/button';
import { Kbd } from '@/components/ui/kbd';
import { Separator } from '@/components/ui/separator';
@@ -66,12 +66,7 @@ export function useHeaderPaneButtonSet(): readonly PaneId[] {
function HeaderPaneButton({ pane, pressed }: HeaderPaneButtonState) {
const { t } = useLingui();
- const names: Record<PaneId, string> = {
- editor: t`Editor`,
- agents: t`Agents`,
- terminal: t`Terminal`,
- };
- const name = names[pane];
+ const name = t(PANE_LABEL[pane]);
const Icon = PANE_ICON[pane];
const shortcutId = PANE_SHORTCUT[pane];
diff --git a/packages/app/src/components/TerminalDock.dom.test.tsx b/packages/app/src/components/SessionsHost.terminal-dock.dom.test.tsx
similarity index 79%
rename from packages/app/src/components/TerminalDock.dom.test.tsx
rename to packages/app/src/components/SessionsHost.terminal-dock.dom.test.tsx
index 4828f6630..3015fae25 100644
--- a/packages/app/src/components/TerminalDock.dom.test.tsx
+++ b/packages/app/src/components/SessionsHost.terminal-dock.dom.test.tsx
@@ -1,7 +1,7 @@
import type { TerminalCli } from '@inkeep/open-knowledge-core';
-import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
+import { act, cleanup, render, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
-import { type PointerEventHandler, useEffect, useRef, useState } from 'react';
+import { useEffect, useRef, useState } from 'react';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { TooltipProvider } from '@/components/ui/tooltip';
import type { OkDesktopBridge, OkMenuAction } from '@/lib/desktop-bridge-types';
@@ -11,83 +11,16 @@ import {
} from '@/lib/local-menu-action-bus';
import { writePreferBareTerminal } from '@/lib/terminal-new-tab-store';
import { saveStickyAgent, terminalCliId } from '@/lib/unified-agent-store';
-import {
- expectVisualClassTokens,
- expectVisualClassTokensAbsent,
-} from '@/test-utils/visual-contract';
import { composeTerminalSelectionPaste } from './handoff/compose-terminal-selection';
import { requestPreferredSession } from './handoff/preferred-session-events';
import { requestActiveTerminalInput } from './handoff/terminal-input-events';
import { subscribeToTerminalLaunchRequests } from './handoff/terminal-launch-events';
import { registerBracketedPasteProbe } from './handoff/terminal-paste-mode';
-const TERMINAL_PANEL_ID = 'terminal-dock-panel';
-
-// biome-ignore lint/suspicious/noExplicitAny: captured mock-component props, asserted structurally
-let terminalPanelProps: Record<string, any> | null = null;
-
-const panelHandle = {
- collapse: vi.fn(() => terminalPanelProps?.onResize?.({ asPercentage: 0, inPixels: 0 })),
- expand: vi.fn(() => terminalPanelProps?.onResize?.({ asPercentage: 40, inPixels: 240 })),
- resize: vi.fn((s: string) => {
- const px = Number.parseInt(s, 10) || 0;
- terminalPanelProps?.onResize?.({ asPercentage: px > 0 ? 30 : 0, inPixels: px });
- }),
-};
-const sharedPanelRef: { current: unknown } = { current: panelHandle };
-
vi.doMock('@tanstack/react-query', () => ({
useQuery: () => ({ data: undefined, isLoading: false, isError: false }),
}));
-vi.doMock('react-resizable-panels', () => ({
- usePanelRef: () => sharedPanelRef,
-}));
-
-vi.doMock('@/components/ui/resizable', () => ({
- // biome-ignore lint/suspicious/noExplicitAny: test stub
- ResizablePanelGroup: ({ children, orientation }: any) => (
- <div data-testid="rrp-group" data-orientation={orientation}>
- {children}
- </div>
- ),
- // biome-ignore lint/suspicious/noExplicitAny: test stub
- ResizablePanel: (props: any) => {
- if (props.id === TERMINAL_PANEL_ID) terminalPanelProps = props;
- return (
- <div
- id={props.id}
- data-panel={props.id ?? 'editor'}
- data-inert={props.inert ? 'true' : undefined}
- >
- {props.children}
- </div>
- );
- },
- ResizableHandle: ({
- onPointerDown,
- disabled,
- withHandle,
- 'aria-label': ariaLabel,
- 'aria-controls': ariaControls,
- }: {
- onPointerDown?: PointerEventHandler<HTMLHRElement>;
- disabled?: boolean;
- withHandle?: boolean;
- 'aria-label'?: string;
- 'aria-controls'?: string;
- }) => (
- <hr
- aria-label={ariaLabel}
- aria-controls={ariaControls}
- data-testid="terminal-resize-handle"
- data-disabled={disabled ? 'true' : 'false'}
- data-with-handle={withHandle ? 'true' : 'false'}
- onPointerDown={onPointerDown}
- />
- ),
-}));
-
const titleEmitters = new Map<string, (title: string) => void>();
function emitTitle(ptyId: string, title: string): boolean {
const emit = titleEmitters.get(ptyId);
@@ -147,13 +80,6 @@ vi.doMock('@/lib/acp/launch-agent-thread', () => ({
hasInflightThreadLaunch: () => mockInflightThreadLaunch,
}));
-vi.doMock('@/lib/terminal-height-store', () => ({
- getInitialTerminalHeight: () => 240,
- writeTerminalHeight: () => {},
- clampTerminalHeight: (px: number) => px,
-}));
-
-const { TerminalDock, MAX_STRANDED_REPORTS } = await import('./TerminalDock');
const { SessionsHost } = await import('./SessionsHost');
const { STAGE_PASTE_SETTLE_MS } = await import('./TerminalPanel');
@@ -211,18 +137,10 @@ function DockHarness({
const [editorRegionEl, setEditorRegionEl] = useState<HTMLDivElement | null>(null);
return (
<TooltipProvider>
- <TerminalDock
- placement={p}
- visible={v}
- available
- variant="card"
- onVisibleChange={onVisibleChange}
- onBottomContainer={setBottomContainer}
- >
- <div ref={setEditorRegionEl} tabIndex={-1} data-testid="editor-region">
- {children ?? <div data-testid="editor-child" />}
- </div>
- </TerminalDock>
+ <div ref={setEditorRegionEl} tabIndex={-1} data-testid="editor-region">
+ {children ?? <div data-testid="editor-child" />}
+ </div>
+ {p === 'bottom' ? <div ref={setBottomContainer} data-testid="terminal-bottom-mount" /> : null}
{p === 'right' && targetAvailable ? (
<div ref={setRightContainer} data-testid="terminal-right-mount" />
) : null}
@@ -307,14 +225,9 @@ async function addTerminalTab(user: ReturnType<typeof userEvent.setup>) {
await user.click(screen.getByRole('button', { name: 'New terminal' }));
}
-describe('TerminalDock multi-session', () => {
+describe('SessionsHost terminal dock sessions', () => {
beforeEach(() => {
localStorage.clear();
- terminalPanelProps = null;
- panelHandle.collapse.mockClear();
- panelHandle.resize.mockClear();
- panelHandle.expand.mockClear();
- sharedPanelRef.current = panelHandle;
titleEmitters.clear();
__resetLocalMenuActionBusForTests();
});
@@ -336,12 +249,12 @@ describe('TerminalDock multi-session', () => {
expect(screen.getByTestId('terminal-session')).toBe(session);
expect(dock.create).toHaveBeenCalledTimes(1);
expect(dock.kill).not.toHaveBeenCalled();
- expect(document.getElementById(TERMINAL_PANEL_ID)).toBeNull();
+ expect(screen.queryByTestId('terminal-bottom-mount')).toBeNull();
dock.rerender(true, null, 'bottom');
await waitFor(() => {
- expect(document.getElementById(TERMINAL_PANEL_ID)?.contains(session)).toBe(true);
+ expect(screen.getByTestId('terminal-bottom-mount').contains(session)).toBe(true);
});
expect(screen.getByTestId('terminal-session')).toBe(session);
expect(screen.queryByTestId('terminal-right-mount')).toBeNull();
@@ -390,79 +303,12 @@ describe('TerminalDock multi-session', () => {
expect(dock.create).toHaveBeenCalledTimes(2);
expect(dock.kill).not.toHaveBeenCalled();
expect(document.querySelectorAll('[data-terminal-session]')).toHaveLength(2);
- expect(document.getElementById(TERMINAL_PANEL_ID)).toBeNull();
+ expect(screen.queryByTestId('terminal-bottom-mount')).toBeNull();
expect(
screen.getByTestId('terminal-right-mount').querySelectorAll('[data-terminal-session]'),
).toHaveLength(2);
});
- test('moving the terminal between bottom and right, and hiding it, never remounts the editor', async () => {
- let editorMounts = 0;
- function CountingEditor() {
- useEffect(() => {
- editorMounts += 1;
- }, []);
- return <div data-testid="counting-editor" />;
- }
- const onVisibleChange = vi.fn((_v: boolean) => {});
- const { bridge, create, kill } = makeBridge();
- const ui = (v: boolean, p: 'bottom' | 'right') => (
- <DockHarness v={v} l={null} p={p} onVisibleChange={onVisibleChange} bridge={bridge}>
- <CountingEditor />
- </DockHarness>
- );
- const view = render(ui(true, 'bottom'));
- await waitFor(() => expect(create).toHaveBeenCalledTimes(1));
- const editor = screen.getByTestId('counting-editor');
- const region = screen.getByTestId('editor-region');
- const card = document.querySelector('[data-slot="pane-card"][data-pane="terminal"]');
- expect(card?.getAttribute('data-placement')).toBe('bottom');
- expect(document.getElementById(TERMINAL_PANEL_ID)?.contains(card)).toBe(true);
- expect(editorMounts).toBe(1);
-
- view.rerender(ui(true, 'right'));
- view.rerender(ui(false, 'right'));
- view.rerender(ui(true, 'right'));
- view.rerender(ui(true, 'bottom'));
- view.rerender(ui(false, 'bottom'));
- view.rerender(ui(true, 'bottom'));
-
- expect(editorMounts).toBe(1);
- expect(screen.getByTestId('counting-editor')).toBe(editor);
- expect(screen.getByTestId('editor-region')).toBe(region);
- expect(screen.getByTestId('rrp-group').contains(editor)).toBe(true);
- expect(create).toHaveBeenCalledTimes(1);
- expect(kill).not.toHaveBeenCalled();
- });
-
- test('names the bottom terminal divider for the pane it resizes', () => {
- renderDock(true);
- const divider = screen.getByRole('separator', { name: 'Resize terminal' });
- expect(divider.getAttribute('aria-controls')).toBe(TERMINAL_PANEL_ID);
- });
-
- test('renders no bottom terminal panel or divider when no terminal is available, as on the web', () => {
- render(
- <TooltipProvider>
- <TerminalDock
- placement="bottom"
- visible={false}
- available={false}
- variant="card"
- onVisibleChange={() => {}}
- onBottomContainer={() => {}}
- >
- <div data-testid="editor-child" />
- </TerminalDock>
- </TooltipProvider>,
- );
-
- expect(screen.getByTestId('editor-child')).toBeTruthy();
- expect(document.getElementById(TERMINAL_PANEL_ID)).toBeNull();
- expect(screen.queryByTestId('terminal-resize-handle')).toBeNull();
- expect(document.querySelector('[data-slot="pane-card"][data-pane="terminal"]')).toBeNull();
- });
-
test('tab strip carries no in-pane collapse, dock or drag controls', () => {
renderDock(true);
expect(screen.queryByRole('button', { name: /^Collapse/ })).toBeNull();
@@ -1309,59 +1155,6 @@ describe('TerminalDock multi-session', () => {
}
});
- test('a pointercancel-terminated drag stops later resizes reading as user drags', () => {
- const view = renderDock(true);
- const handle = screen.getByTestId('terminal-resize-handle');
- act(() => {
- fireEvent.pointerDown(handle);
- });
- act(() => {
- fireEvent.pointerCancel(window);
- });
- view.onVisibleChange.mockClear();
-
- act(() => {
- terminalPanelProps?.onResize?.({ asPercentage: 0, inPixels: 0 });
- });
- expect(view.onVisibleChange).not.toHaveBeenCalled();
- });
-
- test('a different pointer cancelling does not end an in-flight dock drag', () => {
- const view = renderDock(true);
- const handle = screen.getByTestId('terminal-resize-handle');
- act(() => {
- fireEvent.pointerDown(handle, { pointerId: 1 });
- });
-
- act(() => {
- fireEvent.pointerCancel(window, { pointerId: 2 });
- });
- view.onVisibleChange.mockClear();
- act(() => {
- terminalPanelProps?.onResize?.({ asPercentage: 0, inPixels: 0 });
- });
- expect(view.onVisibleChange).toHaveBeenCalledWith(false);
-
- act(() => {
- fireEvent.pointerCancel(window, { pointerId: 1 });
- });
- view.onVisibleChange.mockClear();
- act(() => {
- terminalPanelProps?.onResize?.({ asPercentage: 0, inPixels: 0 });
- });
- expect(view.onVisibleChange).not.toHaveBeenCalled();
- });
-
- test('persists the bottom panel config (collapsible, sized, inert when hidden)', () => {
- renderDock(false);
- expect(terminalPanelProps?.collapsible).toBe(true);
- expect(terminalPanelProps?.collapsedSize).toBe(0);
- expect(terminalPanelProps?.minSize).toBe('120px');
- expect(terminalPanelProps?.maxSize).toBe('95%');
- expect(terminalPanelProps?.defaultSize).toBe(0);
- expect(terminalPanelProps?.inert).toBe(true);
- });
-
test('focuses the active session on reveal so the user can type immediately', () => {
const view = renderDock(true);
const session = screen.getByTestId('terminal-session');
@@ -1372,49 +1165,10 @@ describe('TerminalDock multi-session', () => {
act(() => view.rerender(true));
expect(document.activeElement).toBe(session);
});
-
- test('the bottom terminal card casts its shadow only while the dock is open', () => {
- const card = () => {
- const el = document.querySelector<HTMLElement>(
- '[data-slot="pane-card"][data-pane="terminal"]',
- );
- if (el == null) throw new Error('no bottom terminal card rendered');
- return el;
- };
- const view = renderDock(true);
- expectVisualClassTokensAbsent(card().className, ['shadow-none']);
-
- act(() => {
- terminalPanelProps?.onResize?.({ asPercentage: 0, inPixels: 0 });
- });
- expectVisualClassTokens(card().className, ['shadow-none']);
-
- act(() => view.rerender(false));
- expectVisualClassTokens(card().className, ['shadow-none']);
-
- act(() => view.rerender(true));
- expectVisualClassTokensAbsent(card().className, ['shadow-none']);
- });
-
- test('disables the resize handle while hidden so there is no drag-to-open', () => {
- const view = renderDock(false);
- expect(screen.getByTestId('terminal-resize-handle').getAttribute('data-disabled')).toBe('true');
-
- act(() => view.rerender(true));
- expect(screen.getByTestId('terminal-resize-handle').getAttribute('data-disabled')).toBe(
- 'false',
- );
- });
});
-describe('TerminalDock extraction pins', () => {
- beforeEach(() => {
- terminalPanelProps = null;
- panelHandle.collapse.mockClear();
- panelHandle.resize.mockClear();
- panelHandle.expand.mockClear();
- sharedPanelRef.current = panelHandle;
- });
+describe('SessionsHost terminal dock pins', () => {
+ beforeEach(() => {});
afterEach(() => {
cleanup();
});
@@ -1503,92 +1257,3 @@ describe('TerminalDock extraction pins', () => {
await waitFor(() => expect(document.activeElement).toBe(focusSink));
});
});
-
-describe('TerminalDock hidden-dock invariant', () => {
- beforeEach(() => {
- localStorage.clear();
- terminalPanelProps = null;
- panelHandle.collapse.mockClear();
- panelHandle.resize.mockClear();
- panelHandle.expand.mockClear();
- sharedPanelRef.current = panelHandle;
- __resetLocalMenuActionBusForTests();
- });
- afterEach(() => {
- cleanup();
- __resetLocalMenuActionBusForTests();
- });
-
- function reportSize(inPixels: number, asPercentage: number) {
- act(() => {
- terminalPanelProps?.onResize?.({ asPercentage, inPixels });
- });
- }
-
- function strandedLogs(warn: ReturnType<typeof vi.spyOn>): string[] {
- return warn.mock.calls
- .map((call) => String(call[0]))
- .filter((line) => line.includes('ok-terminal-dock-stranded-while-hidden'));
- }
-
- test('a hidden dock that reports a non-zero height is snapped shut', () => {
- renderDock(false);
- panelHandle.collapse.mockClear();
-
- reportSize(588, 42.5);
-
- expect(panelHandle.collapse).toHaveBeenCalled();
- });
-
- test('an unmeasurable group (NaN percentage, zero pixels) is left alone', () => {
- renderDock(false);
- panelHandle.collapse.mockClear();
-
- reportSize(0, Number.NaN);
-
- expect(panelHandle.collapse).not.toHaveBeenCalled();
- });
-
- test('an open dock keeps the height it reports', () => {
- renderDock(true);
- panelHandle.collapse.mockClear();
-
- reportSize(240, 30);
-
- expect(panelHandle.collapse).not.toHaveBeenCalled();
- });
-
- test('the repair is reported with the geometry needed to diagnose it', () => {
- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
- try {
- renderDock(false);
- reportSize(588, 42.5);
-
- const [line] = strandedLogs(warn);
- expect(line).toBeDefined();
- expect(JSON.parse(line as string)).toMatchObject({
- event: 'ok-terminal-dock-stranded-while-hidden',
- panelPx: 588,
- panelPct: 42.5,
- visible: false,
- });
- const payload = JSON.parse(line as string);
- expect(typeof payload.innerHeight).toBe('number');
- expect(typeof payload.dockHeightPx).toBe('number');
- } finally {
- warn.mockRestore();
- }
- });
-
- test('the report is capped so a fight with another layout writer cannot flood the log', () => {
- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
- try {
- renderDock(false);
- for (let i = 0; i < MAX_STRANDED_REPORTS + 4; i++) reportSize(588, 42.5);
-
- expect(strandedLogs(warn)).toHaveLength(MAX_STRANDED_REPORTS);
- } finally {
- warn.mockRestore();
- }
- });
-});
diff --git a/packages/app/src/components/TerminalDock.reload-survival.dom.test.tsx b/packages/app/src/components/SessionsHost.terminal-reload-survival.dom.test.tsx
similarity index 86%
rename from packages/app/src/components/TerminalDock.reload-survival.dom.test.tsx
rename to packages/app/src/components/SessionsHost.terminal-reload-survival.dom.test.tsx
index aeffd9a82..d71dfa64a 100644
--- a/packages/app/src/components/TerminalDock.reload-survival.dom.test.tsx
+++ b/packages/app/src/components/SessionsHost.terminal-reload-survival.dom.test.tsx
@@ -7,34 +7,10 @@ import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
import { requestActiveTerminalInput } from './handoff/terminal-input-events';
import { subscribeToTerminalLaunchRequests } from './handoff/terminal-launch-events';
-const TERMINAL_PANEL_ID = 'terminal-dock-panel';
-
-// biome-ignore lint/suspicious/noExplicitAny: captured mock-component props
-let terminalPanelProps: Record<string, any> | null = null;
-const panelHandle = {
- collapse: vi.fn(() => terminalPanelProps?.onResize?.({ asPercentage: 0, inPixels: 0 })),
- expand: vi.fn(() => terminalPanelProps?.onResize?.({ asPercentage: 40, inPixels: 240 })),
- resize: vi.fn(() => {}),
-};
-const sharedPanelRef: { current: unknown } = { current: panelHandle };
-
vi.doMock('@tanstack/react-query', () => ({
useQuery: () => ({ data: undefined, isLoading: false, isError: false }),
}));
-vi.doMock('react-resizable-panels', () => ({ usePanelRef: () => sharedPanelRef }));
-vi.doMock('@/components/ui/resizable', () => ({
- // biome-ignore lint/suspicious/noExplicitAny: test stub
- ResizablePanelGroup: ({ children }: any) => <div>{children}</div>,
- // biome-ignore lint/suspicious/noExplicitAny: test stub
- ResizablePanel: (props: any) => {
- if (props.id === TERMINAL_PANEL_ID) terminalPanelProps = props;
- return <div id={props.id}>{props.children}</div>;
- },
- // biome-ignore lint/suspicious/noExplicitAny: test stub
- ResizableHandle: ({ onPointerDown }: any) => <div onPointerDown={onPointerDown} />,
-}));
-
vi.doMock('./TerminalGate', () => ({
// biome-ignore lint/suspicious/noExplicitAny: test stub
TerminalGate: ({ adoptPtyId, onPtyId }: any) => {
@@ -50,12 +26,6 @@ vi.doMock('./TerminalGate', () => ({
},
}));
-vi.doMock('@/lib/terminal-height-store', () => ({
- getInitialTerminalHeight: () => 240,
- writeTerminalHeight: () => {},
-}));
-
-const { TerminalDock } = await import('./TerminalDock');
const { SessionsHost } = await import('./SessionsHost');
function ReloadHarness({
@@ -72,15 +42,8 @@ function ReloadHarness({
const [bottomContainer, setBottomContainer] = useState<HTMLDivElement | null>(null);
return (
<TooltipProvider>
- <TerminalDock
- visible={visible}
- available
- variant="card"
- onVisibleChange={() => {}}
- onBottomContainer={setBottomContainer}
- >
- <div data-testid="editor-child" />
- </TerminalDock>
+ <div data-testid="editor-child" />
+ <div ref={setBottomContainer} data-testid="terminal-bottom-mount" />
<SessionsHost
surface="terminal-dock"
bridge={bridge}
@@ -141,7 +104,6 @@ function renderDock(bridge: OkDesktopBridge, visible: boolean) {
describe('issue #351 — the terminal dock rehydrates surviving sessions after a renderer reload', () => {
afterEach(() => {
cleanup();
- terminalPanelProps = null;
});
test('recovers a tab per surviving session instead of seeding a single fresh one', async () => {
diff --git a/packages/app/src/components/SessionsHost.terminal-restore-detached-host.dom.test.tsx b/packages/app/src/components/SessionsHost.terminal-restore-detached-host.dom.test.tsx
index 69d237fbb..db958404b 100644
--- a/packages/app/src/components/SessionsHost.terminal-restore-detached-host.dom.test.tsx
+++ b/packages/app/src/components/SessionsHost.terminal-restore-detached-host.dom.test.tsx
@@ -6,6 +6,7 @@ import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { SidebarProvider } from '@/components/ui/sidebar';
import { TooltipProvider } from '@/components/ui/tooltip';
import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
+import { DEFAULT_DOCK_TREE, moveDockPane } from '@/lib/dock-tree';
import type { SessionPlacements } from './EditorArea';
import { tabTitles } from './sessions-host-tabs.test-helper';
@@ -62,9 +63,6 @@ vi.doMock('@/components/EditorSkeleton', () => ({
vi.doMock('@/components/EmptyEditorState', () => ({
EmptyEditorState: () => <div data-testid="empty-editor-state" />,
}));
-vi.doMock('./TerminalDock', () => ({
- TerminalDock: ({ children }: { children: ReactNode }) => <div>{children}</div>,
-}));
vi.doMock('./EditorWorkspace', () => ({
EditorWorkspace: ({
renderPane,
@@ -381,8 +379,8 @@ function CompositionHarness({ bridge }: { bridge: OkDesktopBridge }) {
onActiveTabChange={() => {}}
terminalBridge={bridge}
terminalVisible
- terminalPlacement="right"
- onTerminalVisibleChange={() => {}}
+ dockTree={moveDockPane(DEFAULT_DOCK_TREE, 'terminal', 'editor', 'end', 0.3)}
+ onDockTreeChange={() => {}}
onSessionPlacements={setPlacements}
/>
<SessionsHost
diff --git a/packages/app/src/components/TerminalDock.editor-hidden.dom.test.tsx b/packages/app/src/components/TerminalDock.editor-hidden.dom.test.tsx
deleted file mode 100644
index 66ca811f7..000000000
--- a/packages/app/src/components/TerminalDock.editor-hidden.dom.test.tsx
+++ /dev/null
@@ -1,182 +0,0 @@
-import { act, cleanup, render } from '@testing-library/react';
-import { createRef, type ReactNode, type Ref } from 'react';
-import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
-
-type PanelProps = {
- readonly id?: string;
- readonly minSize?: string;
- readonly maxSize?: string;
- readonly children?: ReactNode;
-};
-
-const panelPropsById = new Map<string, PanelProps>();
-const resizeCalls: string[] = [];
-const panelHandle = {
- collapse: vi.fn(),
- resize: vi.fn((size: string) => {
- resizeCalls.push(size);
- }),
-};
-
-const panelRef = { current: panelHandle };
-
-vi.doMock('react-resizable-panels', () => ({
- usePanelRef: () => panelRef,
-}));
-
-vi.doMock('@/components/ui/resizable', () => ({
- ResizablePanelGroup: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- ResizablePanel: (props: PanelProps) => {
- panelPropsById.set(props.id ?? 'editor-card', props);
- return <div id={props.id}>{props.children}</div>;
- },
- ResizableHandle: ({ style }: { style?: { display?: string } }) => (
- <hr data-testid="bottom-handle" data-display={style?.display ?? ''} />
- ),
-}));
-
-const { TerminalDock } = await import('./TerminalDock');
-type TerminalDockHandle = import('./TerminalDock').TerminalDockHandle;
-
-function Dock({
- editorVisible,
- visible = true,
- dockRef,
-}: {
- editorVisible: boolean;
- visible?: boolean;
- dockRef?: Ref<TerminalDockHandle>;
-}) {
- return (
- <TerminalDock
- ref={dockRef}
- editorVisible={editorVisible}
- placement="bottom"
- visible={visible}
- available
- variant="card"
- onVisibleChange={() => {}}
- onBottomContainer={() => {}}
- >
- <div data-testid="editor-card" />
- </TerminalDock>
- );
-}
-
-const flush = () => act(async () => {});
-
-beforeEach(() => {
- localStorage.clear();
- panelPropsById.clear();
- resizeCalls.length = 0;
- panelHandle.resize.mockClear();
-});
-
-afterEach(() => cleanup());
-
-describe('the bottom terminal while the editor is hidden', () => {
- test('takes the full column height and hides the divider above it', async () => {
- const view = render(<Dock editorVisible />);
- await flush();
- resizeCalls.length = 0;
-
- view.rerender(<Dock editorVisible={false} />);
- await flush();
-
- expect(resizeCalls.at(-1)).toBe('100%');
- expect(panelPropsById.get('terminal-dock-panel')?.maxSize).toBe('100%');
- expect(panelPropsById.get('editor-card')?.minSize).toBe('0%');
- expect(view.getByTestId('bottom-handle').getAttribute('data-display')).toBe('none');
- });
-
- test('returns to its saved height when the editor is shown again', async () => {
- const view = render(<Dock editorVisible />);
- await flush();
- const savedHeight = resizeCalls.at(-1);
- view.rerender(<Dock editorVisible={false} />);
- await flush();
-
- view.rerender(<Dock editorVisible />);
- await flush();
-
- expect(savedHeight).toMatch(/px$/);
- expect(resizeCalls.at(-1)).toBe(savedHeight);
- expect(panelPropsById.get('terminal-dock-panel')?.maxSize).toBe('95%');
- expect(panelPropsById.get('editor-card')?.minSize).toBe('5%');
- expect(view.getByTestId('bottom-handle').getAttribute('data-display')).toBe('');
- });
-
- test('a window resize while hidden does not shrink it back to its saved height', async () => {
- const view = render(<Dock editorVisible />);
- await flush();
- view.rerender(<Dock editorVisible={false} />);
- await flush();
- resizeCalls.length = 0;
-
- Object.defineProperty(window, 'innerHeight', { value: 200, configurable: true });
- act(() => {
- window.dispatchEvent(new Event('resize'));
- });
-
- expect(resizeCalls).toEqual([]);
- });
-
- test('a resize that fails for an unexpected reason is reported, and one before the panel registers is not', async () => {
- const warnings: string[] = [];
- const warnSpy = vi.spyOn(console, 'warn').mockImplementation((message: unknown) => {
- warnings.push(String(message));
- });
- const view = render(<Dock editorVisible />);
- await flush();
-
- panelHandle.resize.mockImplementationOnce(() => {
- throw new Error('Group :r3: not found');
- });
- view.rerender(<Dock editorVisible={false} />);
- await flush();
- expect(warnings).toEqual([]);
-
- panelHandle.resize.mockImplementationOnce(() => {
- throw new Error('size out of range');
- });
- view.rerender(<Dock editorVisible />);
- await flush();
- warnSpy.mockRestore();
-
- expect(warnings.map((message) => JSON.parse(message))).toEqual([
- { event: 'terminal-dock-fill-resize-failed', error: 'size out of range' },
- ]);
- });
-
- test('bringing back a hidden-editor terminal reports an unexpected resize failure', async () => {
- const warnings: string[] = [];
- const warnSpy = vi.spyOn(console, 'warn').mockImplementation((message: unknown) => {
- warnings.push(String(message));
- });
- const dockRef = createRef<TerminalDockHandle>();
- render(<Dock editorVisible={false} dockRef={dockRef} />);
- await flush();
-
- panelHandle.resize.mockImplementationOnce(() => {
- throw new Error('size out of range');
- });
- act(() => dockRef.current?.bringBackBottom());
- warnSpy.mockRestore();
-
- expect(panelHandle.resize).toHaveBeenLastCalledWith('100%');
- expect(warnings.map((message) => JSON.parse(message))).toEqual([
- { event: 'terminal-dock-bring-back-failed', error: 'size out of range' },
- ]);
- });
-
- test('a hidden terminal is not resized when the editor hides', async () => {
- const view = render(<Dock editorVisible visible={false} />);
- await flush();
- resizeCalls.length = 0;
-
- view.rerender(<Dock editorVisible={false} visible={false} />);
- await flush();
-
- expect(resizeCalls).toEqual([]);
- });
-});
diff --git a/packages/app/src/components/TerminalDock.tsx b/packages/app/src/components/TerminalDock.tsx
deleted file mode 100644
index bf84ebec6..000000000
--- a/packages/app/src/components/TerminalDock.tsx
+++ /dev/null
@@ -1,286 +0,0 @@
-import type { TerminalPlacement } from '@inkeep/open-knowledge-core/terminal-layout';
-import { useLingui } from '@lingui/react/macro';
-import { useTheme } from 'next-themes';
-import {
- type ReactNode,
- type Ref,
- useEffect,
- useImperativeHandle,
- useLayoutEffect,
- useRef,
- useState,
-} from 'react';
-import { usePanelRef } from 'react-resizable-panels';
-import {
- PANE_CARD_GAP_LEAD_INSET_PX,
- PANE_CARD_GAP_TRAIL_INSET_PX,
- PaneCard,
- type PaneCardVariant,
- paneCardDividerClass,
-} from '@/components/ui/pane-card';
-import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from '@/components/ui/resizable';
-import {
- clampTerminalHeight,
- getInitialTerminalHeight,
- writeTerminalHeight,
-} from '@/lib/terminal-height-store';
-import { cn } from '@/lib/utils';
-import { reportUnexpectedPanelGroupFailure } from './editor-area-panel-space';
-import { useLiveXtermTheme } from './use-live-xterm-theme';
-
-const TERMINAL_PANEL_ID = 'terminal-dock-panel';
-const FULL_COLUMN = '100%';
-
-export const MAX_STRANDED_REPORTS = 5;
-
-export interface TerminalDockHandle {
- bringBackBottom(): void;
-}
-
-interface TerminalDockProps {
- readonly ref?: Ref<TerminalDockHandle>;
- readonly editorVisible?: boolean;
- readonly onBottomCollapsedChange?: (collapsed: boolean) => void;
- readonly children: ReactNode;
- readonly placement?: TerminalPlacement;
- readonly visible: boolean;
- readonly available: boolean;
- readonly variant: PaneCardVariant;
- readonly onVisibleChange: (visible: boolean) => void;
- readonly onBottomContainer: (el: HTMLDivElement | null) => void;
-}
-
-export function TerminalDock({
- ref,
- editorVisible = true,
- onBottomCollapsedChange,
- children,
- placement = 'bottom',
- visible,
- available,
- variant,
- onVisibleChange,
- onBottomContainer,
-}: TerminalDockProps) {
- const { t } = useLingui();
- const { resolvedTheme } = useTheme();
- const panelRef = usePanelRef();
- const bottomPresent = placement === 'bottom' && available;
- const bottomVisible = bottomPresent && visible;
- const fillsColumn = bottomVisible && !editorVisible;
- const bottomHandleShown = bottomVisible && editorVisible;
- const cardLook = variant === 'card';
- const [isCollapsed, setIsCollapsed] = useState(!bottomVisible);
- const xtermBackground = useLiveXtermTheme(resolvedTheme).background;
- const [initialHeightPx] = useState(() => getInitialTerminalHeight());
- const heightPxRef = useRef(initialHeightPx);
-
- const [isDragging, setIsDragging] = useState(false);
- const isDraggingRef = useRef(false);
-
- const writeTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
- function debouncedWriteHeight(px: number) {
- if (writeTimerRef.current != null) clearTimeout(writeTimerRef.current);
- writeTimerRef.current = setTimeout(() => {
- writeTerminalHeight(px);
- writeTimerRef.current = null;
- }, 100);
- }
- const strandedReportsRef = useRef(0);
- function reportStrandedDock(panelPx: number, panelPct: number) {
- if (strandedReportsRef.current >= MAX_STRANDED_REPORTS) return;
- strandedReportsRef.current += 1;
- console.warn(
- JSON.stringify({
- event: 'ok-terminal-dock-stranded-while-hidden',
- panelPx: Math.round(panelPx),
- panelPct: Number.isFinite(panelPct) ? Math.round(panelPct * 10) / 10 : null,
- visible,
- dockHeightPx: heightPxRef.current,
- innerWidth: window.innerWidth,
- innerHeight: window.innerHeight,
- devicePixelRatio: window.devicePixelRatio,
- }),
- );
- }
-
- const endDragRef = useRef<(() => void) | null>(null);
- useEffect(
- () => () => {
- if (writeTimerRef.current != null) clearTimeout(writeTimerRef.current);
- endDragRef.current?.();
- },
- [],
- );
-
- function bottomTargetSize(): string {
- return fillsColumn ? FULL_COLUMN : `${heightPxRef.current}px`;
- }
-
- useLayoutEffect(() => {
- const panel = panelRef.current;
- if (panel == null) return;
- try {
- if (bottomVisible) {
- panel.resize(`${heightPxRef.current}px`);
- } else {
- panel.collapse();
- }
- } catch {}
- }, [bottomVisible, panelRef]);
-
- const previousFillsColumnRef = useRef(false);
- // biome-ignore lint/correctness/useExhaustiveDependencies: the resize target is sampled when the column-filling state flips; the flip owns the resize
- useLayoutEffect(() => {
- const changed = previousFillsColumnRef.current !== fillsColumn;
- previousFillsColumnRef.current = fillsColumn;
- if (!changed) return;
- const target = bottomTargetSize();
- let cancelled = false;
- queueMicrotask(() => {
- if (cancelled || !bottomVisible) return;
- try {
- panelRef.current?.resize(target);
- } catch (error) {
- reportUnexpectedPanelGroupFailure('terminal-dock-fill-resize-failed', error);
- }
- });
- return () => {
- cancelled = true;
- };
- }, [fillsColumn]);
-
- useImperativeHandle(ref, () => ({
- bringBackBottom: () => {
- if (!bottomVisible) return;
- try {
- panelRef.current?.resize(bottomTargetSize());
- } catch (error) {
- reportUnexpectedPanelGroupFailure('terminal-dock-bring-back-failed', error);
- }
- },
- }));
-
- useEffect(() => {
- const reclampToViewport = () => {
- const next = clampTerminalHeight(heightPxRef.current);
- if (next === heightPxRef.current) return;
- heightPxRef.current = next;
- if (!bottomVisible || fillsColumn) return;
- try {
- panelRef.current?.resize(`${next}px`);
- } catch {}
- };
- window.addEventListener('resize', reclampToViewport);
- return () => window.removeEventListener('resize', reclampToViewport);
- }, [bottomVisible, fillsColumn, panelRef]);
-
- return (
- <ResizablePanelGroup
- orientation="vertical"
- className="min-h-0 flex-1"
- data-editor-column-split=""
- style={{ overflow: 'visible' }}
- data-dragging={isDragging || undefined}
- >
- <ResizablePanel
- minSize={editorVisible ? '5%' : '0%'}
- className="flex min-h-0 flex-col"
- style={{
- paddingBlockEnd:
- cardLook && bottomVisible && editorVisible ? PANE_CARD_GAP_LEAD_INSET_PX : 0,
- overflow: editorVisible ? 'visible' : 'hidden',
- }}
- >
- {children}
- </ResizablePanel>
- {}
- {bottomPresent ? (
- <>
- <ResizableHandle
- aria-controls={TERMINAL_PANEL_ID}
- aria-label={t`Resize terminal`}
- withHandle={bottomHandleShown}
- disabled={!bottomHandleShown}
- className={paneCardDividerClass(variant, 'horizontal')}
- style={bottomHandleShown ? undefined : { display: 'none' }}
- onPointerDown={(event) => {
- if (!bottomHandleShown) return;
- endDragRef.current?.();
- setIsDragging(true);
- isDraggingRef.current = true;
- const { pointerId } = event;
- const end = () => {
- setIsDragging(false);
- isDraggingRef.current = false;
- window.removeEventListener('pointerup', onEnd);
- window.removeEventListener('pointercancel', onEnd);
- endDragRef.current = null;
- };
- const onEnd = (ev: PointerEvent) => {
- if (ev.pointerId !== pointerId) return;
- end();
- };
- endDragRef.current = end;
- window.addEventListener('pointerup', onEnd);
- window.addEventListener('pointercancel', onEnd);
- }}
- />
- <ResizablePanel
- id={TERMINAL_PANEL_ID}
- style={{ overflow: 'visible' }}
- panelRef={panelRef}
- defaultSize={bottomVisible ? `${initialHeightPx}px` : 0}
- minSize="120px"
- maxSize={editorVisible ? '95%' : FULL_COLUMN}
- collapsible
- collapsedSize={0}
- onResize={(size) => {
- const collapsed = size.asPercentage === 0;
- setIsCollapsed(collapsed);
- onBottomCollapsedChange?.(collapsed);
- if (!bottomVisible && size.inPixels > 0 && !isDraggingRef.current) {
- reportStrandedDock(size.inPixels, size.asPercentage);
- try {
- panelRef.current?.collapse();
- } catch {}
- return;
- }
- if (isDraggingRef.current) {
- if (collapsed && bottomVisible) onVisibleChange(false);
- else if (!collapsed && !bottomVisible) onVisibleChange(true);
- if (size.inPixels > 0) {
- heightPxRef.current = size.inPixels;
- debouncedWriteHeight(size.inPixels);
- }
- }
- }}
- inert={isCollapsed}
- className={cn(
- 'flex flex-col',
- !isDragging &&
- 'transition-[flex-grow] duration-150 ease-out motion-reduce:transition-none motion-reduce:duration-0',
- )}
- >
- <PaneCard
- pane="terminal"
- variant={variant}
- data-placement="bottom"
- className={cn(isCollapsed && 'shadow-none')}
- style={{
- backgroundColor: xtermBackground,
- marginBlockStart: cardLook && editorVisible ? PANE_CARD_GAP_TRAIL_INSET_PX : 0,
- }}
- >
- {}
- <div
- ref={onBottomContainer}
- className="flex min-h-0 flex-1 flex-col overflow-hidden"
- />
- </PaneCard>
- </ResizablePanel>
- </>
- ) : null}
- </ResizablePanelGroup>
- );
-}
diff --git a/packages/app/src/components/editor-area-hidden-editor.dom.test.tsx b/packages/app/src/components/editor-area-hidden-editor.dom.test.tsx
deleted file mode 100644
index 28c5859ff..000000000
--- a/packages/app/src/components/editor-area-hidden-editor.dom.test.tsx
+++ /dev/null
@@ -1,184 +0,0 @@
-import { act, cleanup, render } from '@testing-library/react';
-import { Group, Panel, Separator, useGroupRef } from 'react-resizable-panels';
-import { afterEach, beforeEach, describe, expect, test } from 'vitest';
-import { computeEditorHiddenLayout } from './editor-area-hidden-editor';
-
-let originalOffsetWidth: PropertyDescriptor | undefined;
-let originalOffsetHeight: PropertyDescriptor | undefined;
-let originalResizeObserver: typeof ResizeObserver | undefined;
-
-class InertResizeObserver implements ResizeObserver {
- observe() {}
- unobserve() {}
- disconnect() {}
-}
-
-function setResizeObserver(value: typeof ResizeObserver | undefined) {
- for (const scope of [globalThis, document.defaultView].filter((s) => s != null)) {
- Object.defineProperty(scope, 'ResizeObserver', { value, configurable: true, writable: true });
- }
-}
-
-const ROW_PX = 1200;
-
-beforeEach(() => {
- originalResizeObserver = globalThis.ResizeObserver;
- setResizeObserver(InertResizeObserver);
- originalOffsetWidth = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'offsetWidth');
- originalOffsetHeight = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'offsetHeight');
- Object.defineProperty(HTMLElement.prototype, 'offsetWidth', {
- configurable: true,
- get(this: HTMLElement) {
- return Number(this.getAttribute('data-mock-width') ?? 0);
- },
- });
- Object.defineProperty(HTMLElement.prototype, 'offsetHeight', {
- configurable: true,
- get(this: HTMLElement) {
- return Number(this.getAttribute('data-mock-height') ?? 0);
- },
- });
-});
-
-afterEach(() => {
- cleanup();
- setResizeObserver(originalResizeObserver);
- for (const [key, descriptor] of [
- ['offsetWidth', originalOffsetWidth],
- ['offsetHeight', originalOffsetHeight],
- ] as const) {
- if (descriptor) Object.defineProperty(HTMLElement.prototype, key, descriptor);
- else Reflect.deleteProperty(HTMLElement.prototype, key);
- }
-});
-
-let rowRef: ReturnType<typeof useGroupRef> | null = null;
-
-function OuterRow({ editorVisible }: { editorVisible: boolean }) {
- const row = useGroupRef();
- rowRef = row;
- return (
- <Group orientation="horizontal" groupRef={row} data-mock-width={ROW_PX}>
- <Panel id="editor" minSize={editorVisible ? '5%' : '0%'} data-mock-width={800} />
- <Separator />
- <Panel
- id="terminal-column"
- minSize="0px"
- maxSize="0px"
- collapsible
- collapsedSize={0}
- data-mock-width={0}
- />
- <Separator />
- <Panel
- id="agents-column"
- minSize="0px"
- maxSize={editorVisible ? '95%' : '100%'}
- defaultSize="400px"
- collapsible
- collapsedSize={0}
- data-mock-width={400}
- />
- </Group>
- );
-}
-
-function BottomSplit({ editorVisible }: { editorVisible: boolean }) {
- const split = useGroupRef();
- rowRef = split;
- return (
- <Group orientation="vertical" groupRef={split} data-mock-height={800}>
- <Panel id="editor-card" minSize={editorVisible ? '5%' : '0%'} data-mock-height={560} />
- <Separator />
- <Panel
- id="terminal-dock-panel"
- minSize="120px"
- maxSize={editorVisible ? '95%' : '100%'}
- defaultSize="240px"
- collapsible
- collapsedSize={0}
- data-mock-height={240}
- />
- </Group>
- );
-}
-
-function currentRow() {
- if (rowRef?.current == null) throw new Error('the row is not mounted');
- return rowRef.current;
-}
-
-async function mount(ui: Parameters<typeof render>[0]) {
- let result: ReturnType<typeof render> | undefined;
- await act(async () => {
- result = render(ui);
- });
- if (result == null) throw new Error('render did not return');
- const mounted = result;
- return {
- rerender: async (next: Parameters<typeof render>[0]) => {
- await act(async () => {
- mounted.rerender(next);
- });
- },
- };
-}
-
-function writeHiddenPlan() {
- const row = currentRow();
- const target = computeEditorHiddenLayout({
- currentLayout: row.getLayout(),
- editorColumnId: 'editor',
- visibleColumnPx: { 'agents-column': 400 },
- });
- act(() => {
- row.setLayout(target);
- });
- return row.getLayout();
-}
-
-describe('the resize library accepts the hidden-editor plan only under the hidden limits', () => {
- test('with today’s limits the editor column stops at 5% and chat at 95%', async () => {
- await mount(<OuterRow editorVisible />);
- const landed = writeHiddenPlan();
- expect(landed.editor).toBeCloseTo(5);
- expect(landed['agents-column']).toBeCloseTo(95);
- });
-
- test('with the hidden limits chat takes the whole row and the editor column reaches zero', async () => {
- const { rerender } = await mount(<OuterRow editorVisible />);
- await rerender(<OuterRow editorVisible={false} />);
- const landed = writeHiddenPlan();
- expect(landed.editor).toBeCloseTo(0);
- expect(landed['agents-column']).toBeCloseTo(100);
- });
-
- test('the bottom terminal can take the whole column once the editor card may reach zero', async () => {
- const { rerender } = await mount(<BottomSplit editorVisible />);
- await rerender(<BottomSplit editorVisible={false} />);
- const split = currentRow();
- act(() => {
- split.setLayout({ 'editor-card': 0, 'terminal-dock-panel': 100 });
- });
- expect(split.getLayout()['terminal-dock-panel']).toBeCloseTo(100);
- expect(split.getLayout()['editor-card']).toBeCloseTo(0);
- });
-
- test('restoring the shown limits lifts the editor column to its floor, and a write in the group’s key order lands', async () => {
- const { rerender } = await mount(<OuterRow editorVisible />);
- await rerender(<OuterRow editorVisible={false} />);
- writeHiddenPlan();
- await rerender(<OuterRow editorVisible />);
- const row = currentRow();
- expect(row.getLayout().editor).toBeCloseTo(5);
- const shown: Record<string, number> = { editor: 60, 'terminal-column': 0, 'agents-column': 40 };
- const inGroupOrder = Object.fromEntries(
- Object.keys(row.getLayout()).map((id) => [id, shown[id] ?? 0]),
- );
- act(() => {
- row.setLayout(inGroupOrder);
- });
- expect(row.getLayout().editor).toBeCloseTo(60);
- expect(row.getLayout()['agents-column']).toBeCloseTo(40);
- });
-});
diff --git a/packages/app/src/components/editor-area-hidden-editor.test.ts b/packages/app/src/components/editor-area-hidden-editor.test.ts
deleted file mode 100644
index 508c71f66..000000000
--- a/packages/app/src/components/editor-area-hidden-editor.test.ts
+++ /dev/null
@@ -1,165 +0,0 @@
-import { describe, expect, test } from 'vitest';
-import {
- computeEditorHiddenLayout,
- editorHiddenLayoutLanded,
- isEditorHiddenLayoutSettled,
-} from './editor-area-hidden-editor';
-
-const EDITOR = 'editor-column';
-const TERMINAL = 'terminal-column';
-const CHAT = 'agents-column';
-
-describe('the outer row with the editor hidden', () => {
- test('a right terminal and chat share the row in proportion to their widths', () => {
- const next = computeEditorHiddenLayout({
- currentLayout: { [EDITOR]: 50, [TERMINAL]: 20, [CHAT]: 30 },
- editorColumnId: EDITOR,
- visibleColumnPx: { [TERMINAL]: 300, [CHAT]: 450 },
- });
- expect(next[EDITOR]).toBe(0);
- expect(next[TERMINAL]).toBeCloseTo(40);
- expect(next[CHAT]).toBeCloseTo(60);
- });
-
- test('one remaining column fills the row and a hidden one gets nothing', () => {
- const next = computeEditorHiddenLayout({
- currentLayout: { [EDITOR]: 70, [TERMINAL]: 0, [CHAT]: 30 },
- editorColumnId: EDITOR,
- visibleColumnPx: { [TERMINAL]: 0, [CHAT]: 450 },
- });
- expect(next).toEqual({ [EDITOR]: 0, [TERMINAL]: 0, [CHAT]: 100 });
- });
-
- test('with no right column the editor column keeps the whole row', () => {
- const next = computeEditorHiddenLayout({
- currentLayout: { [EDITOR]: 80, [TERMINAL]: 0, [CHAT]: 20 },
- editorColumnId: EDITOR,
- visibleColumnPx: { [TERMINAL]: 0, [CHAT]: 0 },
- });
- expect(next).toEqual({ [EDITOR]: 100, [TERMINAL]: 0, [CHAT]: 0 });
- });
-
- test('the written layout keeps the group’s own key order', () => {
- const next = computeEditorHiddenLayout({
- currentLayout: { [EDITOR]: 50, [TERMINAL]: 20, [CHAT]: 30 },
- editorColumnId: EDITOR,
- visibleColumnPx: { [CHAT]: 450, [TERMINAL]: 300 },
- });
- expect(Object.keys(next)).toEqual([EDITOR, TERMINAL, CHAT]);
- });
-
- test('an editor column that still holds a pane takes its share like any other column', () => {
- const next = computeEditorHiddenLayout({
- currentLayout: { [EDITOR]: 0, [TERMINAL]: 0, [CHAT]: 100 },
- editorColumnId: EDITOR,
- visibleColumnPx: { [EDITOR]: 900, [CHAT]: 300 },
- });
- expect(next).toEqual({ [EDITOR]: 75, [TERMINAL]: 0, [CHAT]: 25 });
- });
-
- test('a column the group does not hold is ignored', () => {
- const next = computeEditorHiddenLayout({
- currentLayout: { [EDITOR]: 60, [CHAT]: 40 },
- editorColumnId: EDITOR,
- visibleColumnPx: { [TERMINAL]: 300, [CHAT]: 450 },
- });
- expect(next).toEqual({ [EDITOR]: 0, [CHAT]: 100 });
- });
-});
-
-describe('a hidden-editor row that is already settled is left alone', () => {
- test('a divider dragged while hidden keeps its shares', () => {
- expect(
- isEditorHiddenLayoutSettled({
- currentLayout: { [EDITOR]: 0, [TERMINAL]: 70, [CHAT]: 30 },
- editorColumnId: EDITOR,
- visibleColumnPx: { [TERMINAL]: 300, [CHAT]: 450 },
- }),
- ).toBe(true);
- });
-
- test('an editor column still holding width is not settled', () => {
- expect(
- isEditorHiddenLayoutSettled({
- currentLayout: { [EDITOR]: 5, [TERMINAL]: 65, [CHAT]: 30 },
- editorColumnId: EDITOR,
- visibleColumnPx: { [TERMINAL]: 300, [CHAT]: 450 },
- }),
- ).toBe(false);
- });
-
- test('a column that closed while hidden but still holds width is not settled', () => {
- expect(
- isEditorHiddenLayoutSettled({
- currentLayout: { [EDITOR]: 0, [TERMINAL]: 70, [CHAT]: 30 },
- editorColumnId: EDITOR,
- visibleColumnPx: { [TERMINAL]: 300, [CHAT]: 0 },
- }),
- ).toBe(false);
- });
-
- test('a column that opened while hidden but has no width yet is not settled', () => {
- expect(
- isEditorHiddenLayoutSettled({
- currentLayout: { [EDITOR]: 0, [TERMINAL]: 100, [CHAT]: 0 },
- editorColumnId: EDITOR,
- visibleColumnPx: { [TERMINAL]: 300, [CHAT]: 450 },
- }),
- ).toBe(false);
- });
-
- test('an editor column that still holds a pane is settled only while it has width', () => {
- const params = {
- editorColumnId: EDITOR,
- visibleColumnPx: { [EDITOR]: 900, [CHAT]: 300 },
- };
- expect(
- isEditorHiddenLayoutSettled({
- ...params,
- currentLayout: { [EDITOR]: 65, [TERMINAL]: 0, [CHAT]: 35 },
- }),
- ).toBe(true);
- expect(
- isEditorHiddenLayoutSettled({
- ...params,
- currentLayout: { [EDITOR]: 0, [TERMINAL]: 0, [CHAT]: 100 },
- }),
- ).toBe(false);
- });
-
- test('no right column is settled only when the editor column holds the row', () => {
- const params = {
- editorColumnId: EDITOR,
- visibleColumnPx: { [TERMINAL]: 0, [CHAT]: 0 },
- };
- expect(
- isEditorHiddenLayoutSettled({
- ...params,
- currentLayout: { [EDITOR]: 100, [TERMINAL]: 0, [CHAT]: 0 },
- }),
- ).toBe(true);
- expect(
- isEditorHiddenLayoutSettled({
- ...params,
- currentLayout: { [EDITOR]: 80, [TERMINAL]: 0, [CHAT]: 20 },
- }),
- ).toBe(false);
- });
-});
-
-describe('a written hidden-editor layout is checked against what the group read back', () => {
- test('a clamped write does not count as landed', () => {
- expect(
- editorHiddenLayoutLanded({ [EDITOR]: 0, [CHAT]: 100 }, { [EDITOR]: 5, [CHAT]: 95 }),
- ).toBe(false);
- });
-
- test('a write within rounding counts as landed', () => {
- expect(
- editorHiddenLayoutLanded(
- { [EDITOR]: 0, [TERMINAL]: 40, [CHAT]: 60 },
- { [EDITOR]: 0, [TERMINAL]: 40.2, [CHAT]: 59.8 },
- ),
- ).toBe(true);
- });
-});
diff --git a/packages/app/src/components/editor-area-hidden-editor.ts b/packages/app/src/components/editor-area-hidden-editor.ts
deleted file mode 100644
index b581bff72..000000000
--- a/packages/app/src/components/editor-area-hidden-editor.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import type { Layout } from 'react-resizable-panels';
-
-const SETTLED_TOLERANCE_PCT = 0.5;
-
-interface EditorHiddenLayoutParams {
- readonly currentLayout: Layout;
- readonly editorColumnId: string;
- readonly visibleColumnPx: Readonly<Record<string, number>>;
-}
-
-function visibleColumnIds({
- currentLayout,
- visibleColumnPx,
-}: EditorHiddenLayoutParams): readonly string[] {
- return Object.entries(visibleColumnPx)
- .filter(([id, px]) => id in currentLayout && px > 0)
- .map(([id]) => id);
-}
-
-export function isEditorHiddenLayoutSettled(params: EditorHiddenLayoutParams): boolean {
- const { currentLayout, editorColumnId } = params;
- if (!(editorColumnId in currentLayout)) return false;
- const visible = new Set(visibleColumnIds(params));
- if (visible.size === 0) visible.add(editorColumnId);
- let visibleSum = 0;
- for (const [id, pct] of Object.entries(currentLayout)) {
- if (visible.has(id)) {
- if (pct <= SETTLED_TOLERANCE_PCT) return false;
- visibleSum += pct;
- } else if (pct > SETTLED_TOLERANCE_PCT) {
- return false;
- }
- }
- return Math.abs(visibleSum - 100) <= SETTLED_TOLERANCE_PCT;
-}
-
-export function computeEditorHiddenLayout(params: EditorHiddenLayoutParams): Layout {
- const { currentLayout, editorColumnId, visibleColumnPx } = params;
- if (!(editorColumnId in currentLayout)) return currentLayout;
- const visible = visibleColumnIds(params);
- const next: Layout = {};
- for (const id of Object.keys(currentLayout)) next[id] = 0;
- if (visible.length === 0) {
- next[editorColumnId] = 100;
- return next;
- }
- const totalPx = visible.reduce((sum, id) => sum + (visibleColumnPx[id] ?? 0), 0);
- for (const id of visible) next[id] = ((visibleColumnPx[id] ?? 0) / totalPx) * 100;
- return next;
-}
-
-export function editorHiddenLayoutLanded(target: Layout, readBack: Layout): boolean {
- return Object.entries(target).every(
- ([id, pct]) => Math.abs((readBack[id] ?? 0) - pct) <= SETTLED_TOLERANCE_PCT,
- );
-}
diff --git a/packages/app/src/components/editor-area-inner-follow.test.ts b/packages/app/src/components/editor-area-inner-follow.test.ts
deleted file mode 100644
index 16223a5ca..000000000
--- a/packages/app/src/components/editor-area-inner-follow.test.ts
+++ /dev/null
@@ -1,90 +0,0 @@
-import { describe, expect, test } from 'vitest';
-import { computeInnerFollowLayout, predictInnerPanelSpacePx } from './editor-area-inner-follow';
-
-const OUTER_PX = 1400;
-
-describe('predictInnerPanelSpacePx', () => {
- test('is the editor column’s share of the outer row minus the chrome between the rows', () => {
- expect(
- predictInnerPanelSpacePx({
- outerLayout: { editor: 50, chat: 50 },
- outerResidualId: 'editor',
- outerPanelSpacePx: OUTER_PX,
- innerChromePx: 1,
- }),
- ).toBe(699);
- });
-
- test('refuses an outer layout without the editor column or an empty row', () => {
- expect(
- predictInnerPanelSpacePx({
- outerLayout: { chat: 100 },
- outerResidualId: 'editor',
- outerPanelSpacePx: OUTER_PX,
- innerChromePx: 0,
- }),
- ).toBeNull();
- expect(
- predictInnerPanelSpacePx({
- outerLayout: { editor: 50, chat: 50 },
- outerResidualId: 'editor',
- outerPanelSpacePx: 0,
- innerChromePx: 0,
- }),
- ).toBeNull();
- expect(
- predictInnerPanelSpacePx({
- outerLayout: { editor: 0, chat: 100 },
- outerResidualId: 'editor',
- outerPanelSpacePx: OUTER_PX,
- innerChromePx: 0,
- }),
- ).toBeNull();
- });
-});
-
-describe('computeInnerFollowLayout', () => {
- const innerLayout = { doc: 320 / 7, workspace: 100 - 320 / 7 };
-
- test('keeps the side panel at its pixel pin against the editor column the outer move produces', () => {
- const next = computeInnerFollowLayout({
- outerLayout: { editor: (550 / OUTER_PX) * 100, chat: (850 / OUTER_PX) * 100 },
- outerResidualId: 'editor',
- outerPanelSpacePx: OUTER_PX,
- innerChromePx: 0,
- innerLayout,
- innerResidualId: 'workspace',
- pinnedPx: { doc: 320 },
- });
- expect((next.doc / 100) * 550).toBeCloseTo(320, 6);
- expect((next.workspace / 100) * 550).toBeCloseTo(230, 6);
- expect(Object.keys(next)).toEqual(Object.keys(innerLayout));
- });
-
- test('pins a collapsed side panel at zero', () => {
- const next = computeInnerFollowLayout({
- outerLayout: { editor: 50, chat: 50 },
- outerResidualId: 'editor',
- outerPanelSpacePx: OUTER_PX,
- innerChromePx: 0,
- innerLayout,
- innerResidualId: 'workspace',
- pinnedPx: { doc: 0 },
- });
- expect(next.doc).toBe(0);
- expect(next.workspace).toBe(100);
- });
-
- test('leaves the inner row alone when the pin no longer fits the predicted column', () => {
- const next = computeInnerFollowLayout({
- outerLayout: { editor: (200 / OUTER_PX) * 100, chat: (1200 / OUTER_PX) * 100 },
- outerResidualId: 'editor',
- outerPanelSpacePx: OUTER_PX,
- innerChromePx: 0,
- innerLayout,
- innerResidualId: 'workspace',
- pinnedPx: { doc: 320 },
- });
- expect(next).toBe(innerLayout);
- });
-});
diff --git a/packages/app/src/components/editor-area-inner-follow.ts b/packages/app/src/components/editor-area-inner-follow.ts
deleted file mode 100644
index e571a6380..000000000
--- a/packages/app/src/components/editor-area-inner-follow.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-import type { Layout } from 'react-resizable-panels';
-import { computeStickyRepinLayout } from './editor-area-sticky-repin';
-
-interface InnerFollowParams {
- readonly outerLayout: Layout;
- readonly outerResidualId: string;
- readonly outerPanelSpacePx: number;
- readonly innerChromePx: number;
- readonly innerLayout: Layout;
- readonly innerResidualId: string;
- readonly pinnedPx: Record<string, number>;
-}
-
-export function predictInnerPanelSpacePx({
- outerLayout,
- outerResidualId,
- outerPanelSpacePx,
- innerChromePx,
-}: Pick<
- InnerFollowParams,
- 'outerLayout' | 'outerResidualId' | 'outerPanelSpacePx' | 'innerChromePx'
->): number | null {
- const residualPct = outerLayout[outerResidualId];
- if (residualPct == null || outerPanelSpacePx <= 0) return null;
- const innerPx = (residualPct / 100) * outerPanelSpacePx - innerChromePx;
- return innerPx > 0 ? innerPx : null;
-}
-
-export function computeInnerFollowLayout(params: InnerFollowParams): Layout {
- const innerPx = predictInnerPanelSpacePx(params);
- if (innerPx == null) return params.innerLayout;
- return computeStickyRepinLayout({
- currentLayout: params.innerLayout,
- containerPx: innerPx,
- pinnedPx: params.pinnedPx,
- residualId: params.innerResidualId,
- });
-}
diff --git a/packages/app/src/components/editor-area-panel-space.dom.test.tsx b/packages/app/src/components/editor-area-panel-space.dom.test.tsx
index e0208be11..1ad340366 100644
--- a/packages/app/src/components/editor-area-panel-space.dom.test.tsx
+++ b/packages/app/src/components/editor-area-panel-space.dom.test.tsx
@@ -1,21 +1,14 @@
-import { act, cleanup, fireEvent, render } from '@testing-library/react';
+import { act, cleanup, render } from '@testing-library/react';
import * as ResizablePrimitive from 'react-resizable-panels';
import { afterEach, describe, expect, test, vi } from 'vitest';
import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from '@/components/ui/resizable';
import {
- describeRailFloorShortfall,
- describeRailWidthShortfall,
findRailPanelGroup,
reportUnexpectedPanelGroupFailure,
- resolveInnerRowChromePx,
resolveRailPanelSpace,
resolveRailPanelSpacePx,
} from './editor-area-panel-space';
-import { RIGHT_TERMINAL_PANEL_MIN_WIDTH_PX } from './right-rail-admission';
-const PREFERRED_TERMINAL_WIDTH_PX = 740;
-const SPEC_TERMINAL_WIDTH_FLOOR_PX = 739;
-const DOC_PANEL_FLOOR_PX = 300;
const SEPARATOR_WIDTH_PX = 1;
function railPanels(group: HTMLElement) {
@@ -101,8 +94,8 @@ describe('a panel library failure is reported only when it is not the library st
test.each([
'Could not find Group with id ":r1:"',
'Group :r1: not found',
- 'Layout not found for Panel terminal-dock-panel',
- 'Panel constraints not found for Panel terminal-dock-panel',
+ 'Layout not found for Panel doc-panel',
+ 'Panel constraints not found for Panel doc-panel',
])('%s is expected and stays quiet', (message) => {
expect(warningsFor(new Error(message))).toEqual([]);
});
@@ -120,24 +113,19 @@ describe('a panel library failure is reported only when it is not the library st
warningsFor(new Error('size out of range'), {
event: 'renamed',
error: 'masked',
- decision: 'sync-rail-columns',
+ decision: 'sync-doc-presence',
}),
).toEqual([
- { event: 'panel-resize-failed', error: 'size out of range', decision: 'sync-rail-columns' },
+ { event: 'panel-resize-failed', error: 'size out of range', decision: 'sync-doc-presence' },
]);
});
});
describe('rail panel space is the sum of the panels, not an estimate from one of them', () => {
test('resolves the exact fractional space a flex container distributes', () => {
- const container = buildRailContainer([
- 'editor-main',
- 'doc-panel',
- 'terminal-column',
- 'agents-column',
- ]);
+ const container = buildRailContainer(['editor-workspace', 'doc-panel']);
const panelSpacePx = 1609.4;
- const shares = [0.29, 0.1988, 0.4598, 0.0514];
+ const shares = [0.8012, 0.1988];
stubPanelWidths(
container,
shares.map((share) => share * panelSpacePx),
@@ -151,8 +139,8 @@ describe('rail panel space is the sum of the panels, not an estimate from one of
});
test('a panel whose offsetWidth rounds away from its rendered width does not move the result', () => {
- const container = buildRailContainer(['editor-main', 'doc-panel', 'terminal-column']);
- const widths = [1000.25, 320.4998, PREFERRED_TERMINAL_WIDTH_PX];
+ const container = buildRailContainer(['editor-workspace', 'doc-panel']);
+ const widths = [1000.25, 320.4998];
stubPanelWidths(container, widths);
const docPanel = container.querySelector('#doc-panel');
@@ -165,37 +153,18 @@ describe('rail panel space is the sum of the panels, not an estimate from one of
);
});
- test('a terminal pin taken against the resolved space renders above the spec floor', () => {
- const container = buildRailContainer([
- 'editor-main',
- 'doc-panel',
- 'terminal-column',
- 'agents-column',
- ]);
- const panelSpacePx = 1609.4;
- stubPanelWidths(container, [469.4, 320, PREFERRED_TERMINAL_WIDTH_PX, 80]);
-
- const resolvedSpacePx = resolveRailPanelSpacePx(container);
- if (resolvedSpacePx == null) throw new Error('panel space did not resolve');
- const renderedWidthPx =
- ((PREFERRED_TERMINAL_WIDTH_PX / resolvedSpacePx) * 100 * panelSpacePx) / 100;
-
- expect(renderedWidthPx).toBeCloseTo(PREFERRED_TERMINAL_WIDTH_PX, 6);
- expect(renderedWidthPx).toBeGreaterThan(SPEC_TERMINAL_WIDTH_FLOOR_PX);
- });
-
test('a nested group inside a panel does not contribute its panels', () => {
- const container = buildRailContainer(['editor-main', 'terminal-column']);
- const editorPanel = container.querySelector('#editor-main');
+ const container = buildRailContainer(['editor-workspace', 'doc-panel']);
+ const editorPanel = container.querySelector('#editor-workspace');
if (!(editorPanel instanceof HTMLElement)) throw new Error('editor panel not found');
const nestedGroup = document.createElement('div');
nestedGroup.setAttribute('data-group', 'true');
const nestedPanel = document.createElement('div');
nestedPanel.setAttribute('data-panel', 'true');
- nestedPanel.id = 'bottom-dock';
+ nestedPanel.id = 'editor-split-pane';
nestedGroup.append(nestedPanel);
editorPanel.append(nestedGroup);
- stubPanelWidths(container, [900, PREFERRED_TERMINAL_WIDTH_PX]);
+ stubPanelWidths(container, [1320, 320]);
expect(resolveRailPanelSpacePx(container)).toBeCloseTo(1640, 6);
});
@@ -232,7 +201,7 @@ describe('a refusal to resolve the panel space names the structure that was miss
});
test('panels that rendered with no width of their own refuse on the space, not the markup', () => {
- const container = buildRailContainer(['editor-main', 'terminal-column']);
+ const container = buildRailContainer(['editor-workspace', 'doc-panel']);
const group = findRailPanelGroup(container);
if (group == null) throw new Error('panel group not found');
stubPanelWidths(container, [0, 0]);
@@ -243,116 +212,26 @@ describe('a refusal to resolve the panel space names the structure that was miss
});
});
-describe('a pin that did not land is reported with the width it actually got', () => {
- test('names every pinned column whose width missed its target by more than a pixel', () => {
- const shortfall = describeRailWidthShortfall(
- { 'terminal-column': PREFERRED_TERMINAL_WIDTH_PX, 'agents-column': 400 },
- new Map([
- ['terminal-column', 738.62],
- ['agents-column', 400.38],
- ]),
- );
-
- expect(Object.keys(shortfall)).toEqual(['terminal-column']);
- expect(shortfall['terminal-column']?.targetPx).toBe(PREFERRED_TERMINAL_WIDTH_PX);
- expect(shortfall['terminal-column']?.renderedPx).toBeCloseTo(738.62, 6);
- });
-
- test('reports nothing when every pinned column landed', () => {
- expect(
- describeRailWidthShortfall(
- { 'terminal-column': PREFERRED_TERMINAL_WIDTH_PX },
- new Map([
- ['editor-main', 870],
- ['terminal-column', PREFERRED_TERMINAL_WIDTH_PX],
- ]),
- ),
- ).toEqual({});
- });
-
- test('a pinned column with no width of its own is not reported the way a landed pin is', () => {
- expect(
- describeRailWidthShortfall(
- { 'terminal-column': PREFERRED_TERMINAL_WIDTH_PX },
- new Map([['doc-panel', 320]]),
- ),
- ).toEqual({ 'terminal-column': { targetPx: PREFERRED_TERMINAL_WIDTH_PX, renderedPx: null } });
- });
-});
-
-describe('a floor that could not be honoured names only the columns rendered under it', () => {
- test('a column wider than its floor is left out while a column under its floor is named', () => {
- const shortfall = describeRailFloorShortfall(
- {
- 'terminal-column': RIGHT_TERMINAL_PANEL_MIN_WIDTH_PX,
- 'doc-panel': DOC_PANEL_FLOOR_PX,
- },
- new Map([
- ['terminal-column', PREFERRED_TERMINAL_WIDTH_PX],
- ['doc-panel', 40],
- ]),
- );
-
- expect(Object.keys(shortfall)).toEqual(['doc-panel']);
- expect(shortfall['doc-panel']).toEqual({ targetPx: DOC_PANEL_FLOOR_PX, renderedPx: 40 });
- });
-
- test('a hidden column still holding width is named even though it is over its pin', () => {
- const shortfall = describeRailFloorShortfall(
- {
- 'agents-column': 0,
- 'terminal-column': RIGHT_TERMINAL_PANEL_MIN_WIDTH_PX,
- },
- new Map([
- ['agents-column', 400],
- ['terminal-column', PREFERRED_TERMINAL_WIDTH_PX],
- ]),
- );
-
- expect(Object.keys(shortfall)).toEqual(['agents-column']);
- expect(shortfall['agents-column']).toEqual({ targetPx: 0, renderedPx: 400 });
- });
-
- test('reports nothing when every column sits within a pixel of the floor it needs', () => {
- expect(
- describeRailFloorShortfall(
- {
- 'terminal-column': RIGHT_TERMINAL_PANEL_MIN_WIDTH_PX,
- 'doc-panel': DOC_PANEL_FLOOR_PX,
- },
- new Map([
- ['terminal-column', RIGHT_TERMINAL_PANEL_MIN_WIDTH_PX - 0.5],
- ['doc-panel', DOC_PANEL_FLOOR_PX],
- ]),
- ),
- ).toEqual({});
- });
-});
-
describe('the markers the resolver keys on are the ones the panel library guarantees', () => {
test('a rendered ResizablePanelGroup exposes them, and flex-grow shares drive panel widths', () => {
const view = render(
- <div data-editor-area-panels="">
+ <div data-editor-inner-panels="">
<ResizablePanelGroup orientation="horizontal">
- <ResizablePanel id="editor-main" defaultSize="29%" />
+ <ResizablePanel defaultSize="80%" />
<ResizableHandle />
- <ResizablePanel id="terminal-column" defaultSize="46%" />
- <ResizableHandle />
- <ResizablePanel id="agents-column" defaultSize="25%" />
+ <ResizablePanel id="doc-panel" defaultSize="20%" />
</ResizablePanelGroup>
</div>,
);
- const container = view.container.querySelector('[data-editor-area-panels]');
- if (!(container instanceof HTMLElement)) throw new Error('rail container not found');
+ const container = view.container.querySelector('[data-editor-inner-panels]');
+ if (!(container instanceof HTMLElement)) throw new Error('inner row not found');
const group = findRailPanelGroup(container);
expect(group).toBe(container.firstElementChild);
if (group == null) throw new Error('panel group not found');
- expect(railPanels(group).map((panel) => panel.id)).toEqual([
- 'editor-main',
- 'terminal-column',
- 'agents-column',
- ]);
+ const panels = railPanels(group);
+ expect(panels).toHaveLength(2);
+ expect(panels.at(-1)?.id).toBe('doc-panel');
let measured: ReturnType<typeof measurePanelsFromFlexGrow> | null = null;
act(() => {
@@ -360,200 +239,26 @@ describe('the markers the resolver keys on are the ones the panel library guaran
});
if (measured == null) throw new Error('panels were not measured');
const { panelSpacePx } = measured;
- expect(panelSpacePx).toBe(1610);
+ expect(panelSpacePx).toBe(1611);
expect(resolveRailPanelSpacePx(container)).toBeCloseTo(panelSpacePx, 6);
});
- test('the agents-only separator reports and keyboard-resizes the Agents pane', () => {
- const offsetWidth = vi
- .spyOn(HTMLElement.prototype, 'offsetWidth', 'get')
- .mockImplementation(function () {
- if (this.id === 'editor-main') return 700;
- if (this.id === 'agents-column') return 300;
- return 0;
- });
- const offsetLeft = vi
- .spyOn(HTMLElement.prototype, 'offsetLeft', 'get')
- .mockImplementation(function () {
- if (this.id === 'terminal-column') return 700;
- if (this.id === 'agents-column') return 701;
- if (this.hasAttribute('data-separator')) {
- const separators = [...(this.parentElement?.querySelectorAll('[data-separator]') ?? [])];
- return separators.indexOf(this) === 0 ? 699 : 700;
- }
- return 0;
- });
- try {
- const view = render(
- <ResizablePanelGroup
- id="agents-only-aria-group"
- orientation="horizontal"
- defaultLayout={{ 'editor-main': 70, 'terminal-column': 0, 'agents-column': 30 }}
- >
- <ResizablePanel id="editor-main" minSize="5%" />
- <ResizableHandle />
- <ResizablePanel id="terminal-column" minSize="0%" maxSize="0%">
- Terminal
- </ResizablePanel>
- <ResizableHandle aria-label="Agents" aria-controls="agents-column" />
- <ResizablePanel
- id="agents-column"
- minSize="0%"
- maxSize="95%"
- collapsible
- collapsedSize="0%"
- >
- Agents
- </ResizablePanel>
- </ResizablePanelGroup>,
- );
-
- const separator = view.getByRole('separator', { name: 'Agents' });
- expect.soft(separator.getAttribute('aria-controls')).toBe('agents-column');
- const primaryPane = view.container.querySelector('#agents-column');
- if (!(primaryPane instanceof HTMLElement)) throw new Error('primary pane not found');
- const hiddenTerminal = view.container.querySelector('#terminal-column');
- if (!(hiddenTerminal instanceof HTMLElement)) throw new Error('hidden terminal not found');
- expect(primaryPane.textContent).toBe('Agents');
- expect(Number(hiddenTerminal.style.flexGrow)).toBe(0);
-
- const valueMin = Number(separator.getAttribute('aria-valuemin'));
- const valueNow = Number(separator.getAttribute('aria-valuenow'));
- const valueMax = Number(separator.getAttribute('aria-valuemax'));
- expect.soft(valueMin).toBeLessThan(valueMax);
- expect.soft(valueNow).toBeGreaterThanOrEqual(valueMin);
- expect.soft(valueNow).toBeLessThanOrEqual(valueMax);
- expect.soft(valueNow).toBe(Number(primaryPane.style.flexGrow));
-
- const previousAgentsSize = Number(primaryPane.style.flexGrow);
- fireEvent.keyDown(separator, { key: 'ArrowLeft' });
- expect(Number(primaryPane.style.flexGrow)).toBeGreaterThan(previousAgentsSize);
- expect(Number(hiddenTerminal.style.flexGrow)).toBe(0);
- expect(separator.getAttribute('aria-valuenow')).toBe(primaryPane.style.flexGrow);
-
- fireEvent.keyDown(separator, { key: 'Home' });
- expect(Number(primaryPane.style.flexGrow)).toBe(valueMin);
- fireEvent.keyDown(separator, { key: 'End' });
- expect(Number(primaryPane.style.flexGrow)).toBe(valueMax);
- fireEvent.keyDown(separator, { key: 'Enter' });
- expect(Number(primaryPane.style.flexGrow)).toBe(valueMin);
- fireEvent.keyDown(separator, { key: 'Enter' });
- expect(Number(primaryPane.style.flexGrow)).toBe(valueMax);
- } finally {
- offsetLeft.mockRestore();
- offsetWidth.mockRestore();
- }
- });
-
- test('the terminal-visible separator reports and keyboard-resizes the Terminal pane', () => {
- const offsetWidth = vi
- .spyOn(HTMLElement.prototype, 'offsetWidth', 'get')
- .mockImplementation(function () {
- if (this.id === 'editor-main') return 200;
- if (this.id === 'terminal-column') return 500;
- if (this.id === 'agents-column') return 300;
- return 0;
- });
- const offsetLeft = vi
- .spyOn(HTMLElement.prototype, 'offsetLeft', 'get')
- .mockImplementation(function () {
- if (this.id === 'terminal-column') return 201;
- if (this.id === 'agents-column') return 702;
- if (this.hasAttribute('data-separator')) {
- const separators = [...(this.parentElement?.querySelectorAll('[data-separator]') ?? [])];
- return separators.indexOf(this) === 0 ? 200 : 701;
- }
- return 0;
- });
- try {
- const view = render(
- <ResizablePanelGroup
- id="terminal-visible-aria-group"
- orientation="horizontal"
- defaultLayout={{ 'editor-main': 20, 'terminal-column': 50, 'agents-column': 30 }}
- >
- <ResizablePanel id="editor-main" minSize="20%" maxSize="20%" />
- <ResizableHandle />
- <ResizablePanel
- id="terminal-column"
- minSize="0%"
- maxSize="70%"
- collapsible
- collapsedSize="0%"
- >
- Terminal
- </ResizablePanel>
- <ResizableHandle aria-label="Terminal" aria-controls="terminal-column" />
- <ResizablePanel id="agents-column" minSize="10%" maxSize="80%">
- Agents
- </ResizablePanel>
- </ResizablePanelGroup>,
- );
-
- const separator = view.getByRole('separator', { name: 'Terminal' });
- expect.soft(separator.getAttribute('aria-controls')).toBe('terminal-column');
- const editorPane = view.container.querySelector('#editor-main');
- if (!(editorPane instanceof HTMLElement)) throw new Error('editor pane not found');
- const primaryPane = view.container.querySelector('#terminal-column');
- if (!(primaryPane instanceof HTMLElement)) throw new Error('primary pane not found');
- const agentsPane = view.container.querySelector('#agents-column');
- if (!(agentsPane instanceof HTMLElement)) throw new Error('agents pane not found');
- expect(primaryPane.textContent).toBe('Terminal');
-
- const valueMin = Number(separator.getAttribute('aria-valuemin'));
- const valueNow = Number(separator.getAttribute('aria-valuenow'));
- const valueMax = Number(separator.getAttribute('aria-valuemax'));
- expect.soft(valueMin).toBeLessThan(valueMax);
- expect.soft(valueNow).toBeGreaterThanOrEqual(valueMin);
- expect.soft(valueNow).toBeLessThanOrEqual(valueMax);
- expect.soft(valueNow).toBe(Number(primaryPane.style.flexGrow));
-
- const previousTerminalSize = Number(primaryPane.style.flexGrow);
- const previousAgentsSize = Number(agentsPane.style.flexGrow);
- fireEvent.keyDown(separator, { key: 'ArrowRight' });
- expect(Number(primaryPane.style.flexGrow)).toBe(previousTerminalSize + 5);
- expect(Number(agentsPane.style.flexGrow)).toBe(previousAgentsSize - 5);
- expect(Number(editorPane.style.flexGrow)).toBe(20);
- expect(separator.getAttribute('aria-valuenow')).toBe(primaryPane.style.flexGrow);
-
- fireEvent.keyDown(separator, { key: 'Home' });
- expect(Number(primaryPane.style.flexGrow)).toBe(valueMin);
- expect(Number(agentsPane.style.flexGrow)).toBe(80);
- expect(Number(editorPane.style.flexGrow)).toBe(20);
- fireEvent.keyDown(separator, { key: 'End' });
- expect(Number(primaryPane.style.flexGrow)).toBe(valueMax);
- expect(Number(agentsPane.style.flexGrow)).toBe(10);
- expect(Number(editorPane.style.flexGrow)).toBe(20);
- fireEvent.keyDown(separator, { key: 'Enter' });
- expect(Number(primaryPane.style.flexGrow)).toBe(valueMin);
- expect(Number(agentsPane.style.flexGrow)).toBe(80);
- expect(Number(editorPane.style.flexGrow)).toBe(20);
- fireEvent.keyDown(separator, { key: 'Enter' });
- expect(Number(primaryPane.style.flexGrow)).toBe(valueMax);
- expect(Number(agentsPane.style.flexGrow)).toBe(10);
- expect(Number(editorPane.style.flexGrow)).toBe(20);
- } finally {
- offsetLeft.mockRestore();
- offsetWidth.mockRestore();
- }
- });
-
test('a panel rendered straight from the library still counts toward the panel space', () => {
const view = render(
- <div data-editor-area-panels="">
+ <div data-editor-inner-panels="">
<ResizablePanelGroup orientation="horizontal">
- <ResizablePanel id="editor-main" defaultSize="50%" />
+ <ResizablePanel defaultSize="50%" />
<ResizableHandle />
- <ResizablePrimitive.Panel id="terminal-column" defaultSize="50%" />
+ <ResizablePrimitive.Panel id="doc-panel" defaultSize="50%" />
</ResizablePanelGroup>
</div>,
);
- const container = view.container.querySelector('[data-editor-area-panels]');
- if (!(container instanceof HTMLElement)) throw new Error('rail container not found');
- const terminalPanel = container.querySelector('#terminal-column');
- if (!(terminalPanel instanceof HTMLElement)) throw new Error('terminal panel not found');
- expect(terminalPanel.getAttribute('data-slot')).toBeNull();
+ const container = view.container.querySelector('[data-editor-inner-panels]');
+ if (!(container instanceof HTMLElement)) throw new Error('inner row not found');
+ const docPanel = container.querySelector('#doc-panel');
+ if (!(docPanel instanceof HTMLElement)) throw new Error('doc panel not found');
+ expect(docPanel.getAttribute('data-slot')).toBeNull();
let measured: ReturnType<typeof measurePanelsFromFlexGrow> | null = null;
act(() => {
@@ -566,52 +271,3 @@ describe('the markers the resolver keys on are the ones the panel library guaran
expect(resolveRailPanelSpacePx(container)).toBeCloseTo(panelSpacePx, 6);
});
});
-
-describe('the inner row chrome is measured against the outer column that holds the inner row', () => {
- const INNER_PANEL_SPACE_PX = 700;
-
- function renderEditorRows() {
- const view = render(
- <div data-editor-area-panels="">
- <ResizablePanelGroup orientation="horizontal">
- <ResizablePanel defaultSize="60%">
- <div data-editor-inner-panels="">
- <ResizablePanelGroup orientation="horizontal">
- <ResizablePanel defaultSize="60%" />
- <ResizableHandle />
- <ResizablePanel id="doc-panel" defaultSize="40%" />
- </ResizablePanelGroup>
- </div>
- </ResizablePanel>
- <ResizableHandle />
- <ResizablePanel id="agents-column" defaultSize="40%" />
- </ResizablePanelGroup>
- </div>,
- );
- const outer = view.container.querySelector('[data-editor-area-panels]');
- const inner = view.container.querySelector('[data-editor-inner-panels]');
- if (!(outer instanceof HTMLElement) || !(inner instanceof HTMLElement)) {
- throw new Error('editor rows not rendered');
- }
- return { outer, inner };
- }
-
- test('the column the library rendered with a generated id yields the width around the inner panels', () => {
- const { outer, inner } = renderEditorRows();
- const group = findRailPanelGroup(outer);
- if (group == null) throw new Error('outer panel group not found');
- expect(railPanels(group)[0]?.id).not.toBe('');
- stubPanelWidths(outer, [INNER_PANEL_SPACE_PX + SEPARATOR_WIDTH_PX, 400]);
-
- expect(resolveInnerRowChromePx(outer, inner, INNER_PANEL_SPACE_PX)).toBe(SEPARATOR_WIDTH_PX);
- });
-
- test('an inner row outside every outer column refuses instead of reading as zero chrome', () => {
- const { outer } = renderEditorRows();
- const strayInner = document.createElement('div');
- document.body.append(strayInner);
- stubPanelWidths(outer, [INNER_PANEL_SPACE_PX, 400]);
-
- expect(resolveInnerRowChromePx(outer, strayInner, INNER_PANEL_SPACE_PX)).toBeNull();
- });
-});
diff --git a/packages/app/src/components/editor-area-panel-space.ts b/packages/app/src/components/editor-area-panel-space.ts
index d804710fb..a674d98df 100644
--- a/packages/app/src/components/editor-area-panel-space.ts
+++ b/packages/app/src/components/editor-area-panel-space.ts
@@ -81,61 +81,3 @@ export function resolveRailPanelSpacePx(container: Element | null | undefined):
const result = resolveRailPanelSpace(container);
return result.ok ? result.panelSpacePx : null;
}
-
-export function resolveInnerRowChromePx(
- outerContainer: Element | null | undefined,
- innerContainer: Element | null | undefined,
- innerPanelSpacePx: number,
-): number | null {
- const group = findRailPanelGroup(outerContainer);
- if (group == null || innerContainer == null) return null;
- for (const column of group.querySelectorAll(PANEL_SELECTOR)) {
- if (column.contains(innerContainer)) {
- return Math.max(0, column.getBoundingClientRect().width - innerPanelSpacePx);
- }
- }
- return null;
-}
-
-export interface RailWidthShortfall {
- readonly targetPx: number;
- readonly renderedPx: number | null;
-}
-
-function missesExactTarget(renderedPx: number, targetPx: number): boolean {
- return Math.abs(renderedPx - targetPx) > 1;
-}
-
-function collectShortfall(
- targetsPx: Readonly<Record<string, number>>,
- renderedWidths: ReadonlyMap<string, number>,
- isShort: (renderedPx: number, targetPx: number) => boolean,
-): Record<string, RailWidthShortfall> {
- const shortfall: Record<string, RailWidthShortfall> = {};
- for (const [id, targetPx] of Object.entries(targetsPx)) {
- const renderedPx = renderedWidths.get(id);
- if (renderedPx == null) {
- shortfall[id] = { targetPx, renderedPx: null };
- continue;
- }
- if (!isShort(renderedPx, targetPx)) continue;
- shortfall[id] = { targetPx, renderedPx };
- }
- return shortfall;
-}
-
-export function describeRailWidthShortfall(
- pinnedPx: Readonly<Record<string, number>>,
- renderedWidths: ReadonlyMap<string, number>,
-): Record<string, RailWidthShortfall> {
- return collectShortfall(pinnedPx, renderedWidths, missesExactTarget);
-}
-
-export function describeRailFloorShortfall(
- floorPx: Readonly<Record<string, number>>,
- renderedWidths: ReadonlyMap<string, number>,
-): Record<string, RailWidthShortfall> {
- return collectShortfall(floorPx, renderedWidths, (renderedPx, targetPx) =>
- targetPx === 0 ? missesExactTarget(renderedPx, targetPx) : renderedPx < targetPx - 1,
- );
-}
diff --git a/packages/app/src/components/editor-area-rail-registry.test.ts b/packages/app/src/components/editor-area-rail-registry.test.ts
index 2e02d7309..eb450295d 100644
--- a/packages/app/src/components/editor-area-rail-registry.test.ts
+++ b/packages/app/src/components/editor-area-rail-registry.test.ts
@@ -1,88 +1,17 @@
import { describe, expect, test } from 'vitest';
-import {
- AGENTS_COLUMN_ID,
- accountRailLayout,
- DOC_PANEL_ID,
- findResidualPanelId,
- isRightRailPanelId,
- RIGHT_RAIL_PANEL_ORDER,
- TERMINAL_COLUMN_ID,
-} from './editor-area-rail-registry';
+import { DOC_PANEL_ID, findResidualPanelId } from './editor-area-rail-registry';
-const EDITOR = 'editor-residual';
-
-function powerset<T>(items: readonly T[]): T[][] {
- let result: T[][] = [[]];
- for (const item of items) {
- const next: T[][] = [];
- for (const subset of result) {
- next.push(subset);
- next.push(subset.concat(item));
- }
- result = next;
- }
- return result;
-}
-
-describe('right-rail panel registry', () => {
- test('registers exactly the three rail peers in canonical order', () => {
- expect([...RIGHT_RAIL_PANEL_ORDER]).toEqual([
- DOC_PANEL_ID,
- TERMINAL_COLUMN_ID,
- AGENTS_COLUMN_ID,
- ]);
- });
-
- test('recognizes every registered id and rejects the editor', () => {
- for (const id of RIGHT_RAIL_PANEL_ORDER) {
- expect(isRightRailPanelId(id)).toBe(true);
- }
- expect(isRightRailPanelId(EDITOR)).toBe(false);
- });
-});
-
-describe('residual editor discovery across reachable layouts', () => {
- test('resolves exactly the editor and accounts for every peer in all combinations', () => {
- for (const peers of powerset(RIGHT_RAIL_PANEL_ORDER)) {
- const layout = [EDITOR, ...peers];
- expect(findResidualPanelId(layout)).toBe(EDITOR);
- const accounting = accountRailLayout(layout);
- expect(accounting.ok).toBe(true);
- expect(accounting.residualId).toBe(EDITOR);
- expect(accounting.presentPeers).toEqual(peers);
- expect(accounting.unaccountedIds).toEqual([]);
- }
- });
-
- test('accounts cleanly for the full rail', () => {
- const layout = [EDITOR, DOC_PANEL_ID, TERMINAL_COLUMN_ID, AGENTS_COLUMN_ID];
- const accounting = accountRailLayout(layout);
- expect(accounting.ok).toBe(true);
- expect(accounting.residualId).toBe(EDITOR);
- expect(accounting.presentPeers).toEqual([DOC_PANEL_ID, TERMINAL_COLUMN_ID, AGENTS_COLUMN_ID]);
+describe('residual panel discovery in the side panel row', () => {
+ test('finds the workspace column beside the side panel, in either order', () => {
+ expect(findResidualPanelId(['workspace-main', DOC_PANEL_ID])).toBe('workspace-main');
+ expect(findResidualPanelId([DOC_PANEL_ID, 'workspace-main'])).toBe('workspace-main');
});
- test('accounts cleanly for a narrow rail (agents closed)', () => {
- const layout = [EDITOR, DOC_PANEL_ID, TERMINAL_COLUMN_ID];
- const accounting = accountRailLayout(layout);
- expect(accounting.ok).toBe(true);
- expect(accounting.residualId).toBe(EDITOR);
- expect(accounting.presentPeers).toEqual([DOC_PANEL_ID, TERMINAL_COLUMN_ID]);
- });
-});
-
-describe('the layout invariant fires on model defects', () => {
- test('an unregistered rendered column breaks residual resolution and accounting', () => {
- const layout = [EDITOR, DOC_PANEL_ID, 'ghost-column'];
- expect(findResidualPanelId(layout)).toBeNull();
- const accounting = accountRailLayout(layout);
- expect(accounting.ok).toBe(false);
- expect(accounting.unaccountedIds).toContain('ghost-column');
+ test('a row holding only the side panel has no residual', () => {
+ expect(findResidualPanelId([DOC_PANEL_ID])).toBeNull();
});
- test('a layout missing the residual editor fails the invariant', () => {
- const layout = [DOC_PANEL_ID, AGENTS_COLUMN_ID];
- expect(findResidualPanelId(layout)).toBeNull();
- expect(accountRailLayout(layout).ok).toBe(false);
+ test('an unregistered second column breaks residual resolution', () => {
+ expect(findResidualPanelId(['workspace-main', 'stray-column', DOC_PANEL_ID])).toBeNull();
});
});
diff --git a/packages/app/src/components/editor-area-rail-registry.ts b/packages/app/src/components/editor-area-rail-registry.ts
index 4bcd491b2..781b349d0 100644
--- a/packages/app/src/components/editor-area-rail-registry.ts
+++ b/packages/app/src/components/editor-area-rail-registry.ts
@@ -1,52 +1,13 @@
export const DOC_PANEL_ID = 'doc-panel';
-export const TERMINAL_COLUMN_ID = 'terminal-column';
-export const AGENTS_COLUMN_ID = 'agents-column';
-
-export const RIGHT_RAIL_PANEL_ORDER = [DOC_PANEL_ID, TERMINAL_COLUMN_ID, AGENTS_COLUMN_ID] as const;
-
-export type RightRailPanelId = (typeof RIGHT_RAIL_PANEL_ORDER)[number];
-
-const RIGHT_RAIL_PANEL_ID_SET: ReadonlySet<string> = new Set(RIGHT_RAIL_PANEL_ORDER);
-
-export function isRightRailPanelId(id: string): id is RightRailPanelId {
- return RIGHT_RAIL_PANEL_ID_SET.has(id);
-}
export function findResidualPanelId(layoutIds: Iterable<string>): string | null {
let residual: string | null = null;
let count = 0;
for (const id of layoutIds) {
- if (isRightRailPanelId(id)) continue;
+ if (id === DOC_PANEL_ID) continue;
residual = id;
count += 1;
if (count > 1) return null;
}
return count === 1 ? residual : null;
}
-
-export type RailLayoutAccounting =
- | {
- readonly ok: true;
- readonly residualId: string;
- readonly presentPeers: readonly RightRailPanelId[];
- readonly unaccountedIds: readonly string[];
- }
- | {
- readonly ok: false;
- readonly residualId: string | null;
- readonly presentPeers: readonly RightRailPanelId[];
- readonly unaccountedIds: readonly string[];
- };
-
-export function accountRailLayout(layoutIds: Iterable<string>): RailLayoutAccounting {
- const ids = [...layoutIds];
- const residualId = findResidualPanelId(ids);
- const presentPeers = RIGHT_RAIL_PANEL_ORDER.filter((id) => ids.includes(id));
- const accounted = new Set<string>(presentPeers);
- if (residualId != null) accounted.add(residualId);
- const unaccountedIds = ids.filter((id) => !accounted.has(id));
- if (residualId == null || unaccountedIds.length > 0) {
- return { ok: false, residualId, presentPeers, unaccountedIds };
- }
- return { ok: true, residualId, presentPeers, unaccountedIds };
-}
diff --git a/packages/app/src/components/editor-card-rows-preserve-side-panel.dom.test.tsx b/packages/app/src/components/editor-card-rows-preserve-side-panel.dom.test.tsx
deleted file mode 100644
index d289c0a71..000000000
--- a/packages/app/src/components/editor-card-rows-preserve-side-panel.dom.test.tsx
+++ /dev/null
@@ -1,240 +0,0 @@
-import { act, cleanup, render } from '@testing-library/react';
-import { Group, Panel, Separator, useGroupRef } from 'react-resizable-panels';
-import { afterEach, beforeEach, describe, expect, test } from 'vitest';
-import { computeInnerFollowLayout } from './editor-area-inner-follow';
-
-type Observation = {
- readonly callback: ResizeObserverCallback;
- readonly observer: ResizeObserver;
- readonly target: Element;
-};
-
-let observations: Observation[] = [];
-let originalResizeObserver: typeof ResizeObserver | undefined;
-let originalOffsetWidth: PropertyDescriptor | undefined;
-
-class CapturingResizeObserver implements ResizeObserver {
- readonly callback: ResizeObserverCallback;
- constructor(callback: ResizeObserverCallback) {
- this.callback = callback;
- }
- observe(target: Element) {
- observations.push({ callback: this.callback, observer: this, target });
- }
- unobserve() {}
- disconnect() {}
-}
-
-const OUTER_PX = 1400;
-const TERMINAL_PX = 300;
-const CHAT_PX = 400;
-const EDITOR_PX = OUTER_PX - TERMINAL_PX - CHAT_PX;
-const DOC_PX = 320;
-const WORKSPACE_PX = EDITOR_PX - DOC_PX;
-
-beforeEach(() => {
- observations = [];
- originalResizeObserver = globalThis.ResizeObserver;
- const install = (scope: object) => {
- Object.defineProperty(scope, 'ResizeObserver', {
- value: CapturingResizeObserver,
- configurable: true,
- writable: true,
- });
- };
- install(globalThis);
- if (document.defaultView != null) install(document.defaultView);
- originalOffsetWidth = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'offsetWidth');
- Object.defineProperty(HTMLElement.prototype, 'offsetWidth', {
- configurable: true,
- get(this: HTMLElement) {
- return Number(this.getAttribute('data-mock-width') ?? 0);
- },
- });
-});
-
-afterEach(() => {
- cleanup();
- const restore = (scope: object) => {
- Object.defineProperty(scope, 'ResizeObserver', {
- value: originalResizeObserver,
- configurable: true,
- writable: true,
- });
- };
- restore(globalThis);
- if (document.defaultView != null) restore(document.defaultView);
- if (originalOffsetWidth) {
- Object.defineProperty(HTMLElement.prototype, 'offsetWidth', originalOffsetWidth);
- } else {
- Reflect.deleteProperty(HTMLElement.prototype, 'offsetWidth');
- }
-});
-
-let outerRef: ReturnType<typeof useGroupRef> | null = null;
-let innerRef: ReturnType<typeof useGroupRef> | null = null;
-
-function EditorCardRows() {
- const outer = useGroupRef();
- const inner = useGroupRef();
- outerRef = outer;
- innerRef = inner;
- return (
- <Group orientation="horizontal" groupRef={outer}>
- <Panel id="editor" minSize="5%" data-mock-width={EDITOR_PX}>
- <Group orientation="horizontal" groupRef={inner}>
- <Panel id="workspace" minSize="5%" data-mock-width={WORKSPACE_PX} />
- <Separator />
- <Panel
- id="doc"
- minSize="300px"
- maxSize="600px"
- defaultSize={`${DOC_PX}px`}
- collapsible
- collapsedSize={0}
- data-mock-width={DOC_PX}
- />
- </Group>
- </Panel>
- <Separator />
- <Panel
- id="terminal"
- minSize={`${TERMINAL_PX}px`}
- defaultSize={`${TERMINAL_PX}px`}
- data-mock-width={TERMINAL_PX}
- />
- <Separator />
- <Panel id="chat" minSize="0px" defaultSize={`${CHAT_PX}px`} data-mock-width={CHAT_PX} />
- </Group>
- );
-}
-
-function element(selector: string): HTMLElement {
- const el = document.querySelector<HTMLElement>(selector);
- if (el == null) throw new Error(`${selector} is not rendered`);
- return el;
-}
-
-function pxOf(layout: Record<string, number>, id: string, groupPx: number): number {
- return ((layout[id] ?? 0) / 100) * groupPx;
-}
-
-function pct(px: number, groupPx: number): number {
- return (px / groupPx) * 100;
-}
-
-async function layOutEditorColumn(editorPx: number) {
- element('#editor').setAttribute('data-mock-width', String(editorPx));
- element('#workspace').setAttribute('data-mock-width', String(editorPx / 2));
- element('#doc').setAttribute('data-mock-width', String(editorPx / 2));
- const innerRow = element('#doc').parentElement;
- if (innerRow == null) throw new Error('the side panel has no row');
- const observation = observations.findLast((entry) => entry.target === innerRow);
- if (observation == null) throw new Error('the inner row is not observed by the library');
- await act(async () => {
- observation.callback(
- [{ target: innerRow, borderBoxSize: [] } as unknown as ResizeObserverEntry],
- observation.observer,
- );
- });
-}
-
-describe('the side panel keeps its pixel width while an outer divider is dragged', () => {
- test.each([
- { divider: 'chat', terminalPx: TERMINAL_PX, chatPx: CHAT_PX + 150 },
- { divider: 'terminal', terminalPx: TERMINAL_PX + 100, chatPx: CHAT_PX },
- { divider: 'chat', terminalPx: TERMINAL_PX, chatPx: CHAT_PX - 120 },
- ])(
- 'the $divider column taking width from the editor column leaves the side panel at its width',
- async ({ terminalPx, chatPx }) => {
- await act(async () => {
- render(<EditorCardRows />);
- });
- const outer = outerRef?.current;
- const inner = innerRef?.current;
- if (!outer || !inner) throw new Error('group imperative handles were not attached');
- expect(pxOf(inner.getLayout(), 'doc', EDITOR_PX)).toBeCloseTo(DOC_PX, 1);
-
- const editorPxAfterDrag = OUTER_PX - terminalPx - chatPx;
- const movedOuter = {
- ...outer.getLayout(),
- editor: pct(editorPxAfterDrag, OUTER_PX),
- terminal: pct(terminalPx, OUTER_PX),
- chat: pct(chatPx, OUTER_PX),
- };
- const follow = () =>
- inner.setLayout(
- computeInnerFollowLayout({
- outerLayout: movedOuter,
- outerResidualId: 'editor',
- outerPanelSpacePx: OUTER_PX,
- innerChromePx: 0,
- innerLayout: inner.getLayout(),
- innerResidualId: 'workspace',
- pinnedPx: { doc: DOC_PX },
- }),
- );
- await act(async () => {
- outer.setLayout(movedOuter);
- follow();
- });
- expect(pxOf(outer.getLayout(), 'editor', OUTER_PX)).toBeCloseTo(editorPxAfterDrag, 1);
- const sidePanelMinPct = pct(300, EDITOR_PX);
- const expectedFirstWritePct = Math.max(pct(DOC_PX, editorPxAfterDrag), sidePanelMinPct);
- expect(inner.getLayout().doc).toBeCloseTo(expectedFirstWritePct, 2);
-
- await layOutEditorColumn(editorPxAfterDrag);
- await act(async () => {
- follow();
- });
-
- const settled = inner.getLayout();
- expect(pxOf(settled, 'doc', editorPxAfterDrag)).toBeCloseTo(DOC_PX, 1);
- expect(pxOf(settled, 'workspace', editorPxAfterDrag)).toBeCloseTo(
- editorPxAfterDrag - DOC_PX,
- 1,
- );
- },
- );
-
- test('a collapsed side panel stays collapsed when the editor column resizes', async () => {
- await act(async () => {
- render(<EditorCardRows />);
- });
- const inner = innerRef?.current;
- if (!inner) throw new Error('inner group imperative handle was not attached');
- await act(async () => {
- inner.setLayout({ ...inner.getLayout(), workspace: 100, doc: 0 });
- });
- expect(pxOf(inner.getLayout(), 'doc', EDITOR_PX)).toBe(0);
-
- await layOutEditorColumn(EDITOR_PX - 150);
-
- expect(pxOf(inner.getLayout(), 'doc', EDITOR_PX - 150)).toBe(0);
- expect(inner.getLayout().workspace).toBeCloseTo(100, 3);
- });
-
- test('a layout write must keep the group’s own key order, which the follow helper preserves', async () => {
- await act(async () => {
- render(<EditorCardRows />);
- });
- const inner = innerRef?.current;
- if (!inner) throw new Error('inner group imperative handle was not attached');
- const groupKeyOrder = Object.keys(inner.getLayout());
- const followed = computeInnerFollowLayout({
- outerLayout: { editor: 40, terminal: 20, chat: 40 },
- outerResidualId: 'editor',
- outerPanelSpacePx: OUTER_PX,
- innerChromePx: 0,
- innerLayout: inner.getLayout(),
- innerResidualId: 'workspace',
- pinnedPx: { doc: DOC_PX },
- });
- expect(Object.keys(followed)).toEqual(groupKeyOrder);
-
- await act(async () => {
- inner.setLayout(followed);
- });
- expect(pxOf(inner.getLayout(), 'doc', 0.4 * OUTER_PX)).toBeCloseTo(DOC_PX, 1);
- });
-});
diff --git a/packages/app/src/components/pane-icons.ts b/packages/app/src/components/pane-icons.ts
index 40b3481a2..86b96e53e 100644
--- a/packages/app/src/components/pane-icons.ts
+++ b/packages/app/src/components/pane-icons.ts
@@ -1,3 +1,5 @@
+import type { MessageDescriptor } from '@lingui/core';
+import { msg } from '@lingui/core/macro';
import { Sparkles, SquareTerminal } from 'lucide-react';
import type { ComponentType, SVGProps } from 'react';
import { EditorPaneIcon } from '@/components/icons/editor-pane';
@@ -8,3 +10,9 @@ export const PANE_ICON = {
agents: Sparkles,
terminal: SquareTerminal,
} as const satisfies Record<PaneId, ComponentType<SVGProps<SVGSVGElement>>>;
+
+export const PANE_LABEL = {
+ editor: msg`Editor`,
+ agents: msg`Agents`,
+ terminal: msg`Terminal`,
+} as const satisfies Record<PaneId, MessageDescriptor>;
diff --git a/packages/app/src/components/right-rail-admission.test.ts b/packages/app/src/components/right-rail-admission.test.ts
deleted file mode 100644
index ddcc947d3..000000000
--- a/packages/app/src/components/right-rail-admission.test.ts
+++ /dev/null
@@ -1,100 +0,0 @@
-import { describe, expect, test } from 'vitest';
-import {
- MIN_USABLE_RIGHT_TERMINAL_WIDTH_PX,
- minimumWorkspaceWidthForRightRailPeers,
- resolveRightRailAdmission,
-} from './right-rail-admission';
-
-const BOTH_COLUMNS_FIT_PX = minimumWorkspaceWidthForRightRailPeers({
- otherRailWidthPx: 320,
- agentsMinimumWidthPx: 320,
-});
-const TOO_NARROW_PX = BOTH_COLUMNS_FIT_PX - 1;
-
-describe('right rail admission', () => {
- test('admits both panels at the exact width that preserves the terminal floor', () => {
- const minimumWidth = BOTH_COLUMNS_FIT_PX;
-
- expect(MIN_USABLE_RIGHT_TERMINAL_WIDTH_PX).toBe(324);
- expect(minimumWidth).toBe(1015);
- expect(
- resolveRightRailAdmission({
- workspaceWidthPx: minimumWidth,
- otherRailWidthPx: 320,
- agentsMinimumWidthPx: 320,
- previous: { terminalRightVisible: true, agentsVisible: false },
- current: { terminalRightVisible: true, agentsVisible: true },
- trigger: 'state-change',
- }),
- ).toEqual({ kind: 'none' });
- });
-
- test('moving the terminal right closes agents one pixel below the boundary', () => {
- expect(
- resolveRightRailAdmission({
- workspaceWidthPx: TOO_NARROW_PX,
- otherRailWidthPx: 320,
- agentsMinimumWidthPx: 320,
- previous: { terminalRightVisible: false, agentsVisible: true },
- current: { terminalRightVisible: true, agentsVisible: true },
- trigger: 'state-change',
- }),
- ).toEqual({ kind: 'close-agents' });
- });
-
- test('opening agents closes an existing right terminal when space is infeasible', () => {
- expect(
- resolveRightRailAdmission({
- workspaceWidthPx: TOO_NARROW_PX,
- otherRailWidthPx: 320,
- agentsMinimumWidthPx: 320,
- previous: { terminalRightVisible: true, agentsVisible: false },
- current: { terminalRightVisible: true, agentsVisible: true },
- trigger: 'state-change',
- }),
- ).toEqual({ kind: 'close-terminal' });
- });
-
- test('a resize into infeasibility keeps the terminal and closes agents', () => {
- const visibility = { terminalRightVisible: true, agentsVisible: true } as const;
- expect(
- resolveRightRailAdmission({
- workspaceWidthPx: TOO_NARROW_PX,
- otherRailWidthPx: 320,
- agentsMinimumWidthPx: 320,
- previous: visibility,
- current: visibility,
- trigger: 'resize',
- }),
- ).toEqual({ kind: 'close-agents' });
- });
-
- test.each([
- {
- name: 'closing agents',
- previous: { terminalRightVisible: true, agentsVisible: true },
- current: { terminalRightVisible: true, agentsVisible: false },
- },
- {
- name: 'closing the terminal',
- previous: { terminalRightVisible: true, agentsVisible: true },
- current: { terminalRightVisible: false, agentsVisible: true },
- },
- {
- name: 'a bottom terminal',
- previous: { terminalRightVisible: false, agentsVisible: true },
- current: { terminalRightVisible: false, agentsVisible: true },
- },
- ])('$name never opens the other panel', ({ previous, current }) => {
- expect(
- resolveRightRailAdmission({
- workspaceWidthPx: 900,
- otherRailWidthPx: 320,
- agentsMinimumWidthPx: 320,
- previous,
- current,
- trigger: 'state-change',
- }),
- ).toEqual({ kind: 'none' });
- });
-});
diff --git a/packages/app/src/components/right-rail-admission.ts b/packages/app/src/components/right-rail-admission.ts
deleted file mode 100644
index b54a48291..000000000
--- a/packages/app/src/components/right-rail-admission.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-import { MIN_TERMINAL_RIGHT_WIDTH } from '@inkeep/open-knowledge-core/terminal-layout';
-
-export const MIN_USABLE_RIGHT_TERMINAL_WIDTH_PX = MIN_TERMINAL_RIGHT_WIDTH;
-
-export const RIGHT_TERMINAL_PANEL_MIN_WIDTH_PX = MIN_USABLE_RIGHT_TERMINAL_WIDTH_PX + 1;
-
-const EDITOR_RESIDUAL_FRACTION = 0.05;
-
-interface RightRailVisibility {
- readonly terminalRightVisible: boolean;
- readonly agentsVisible: boolean;
-}
-
-interface RightRailAdmissionInput {
- readonly workspaceWidthPx: number;
- readonly otherRailWidthPx: number;
- readonly editorMinimumWidthPx?: number;
- readonly agentsMinimumWidthPx: number;
- readonly previous: RightRailVisibility;
- readonly current: RightRailVisibility;
- readonly trigger: 'state-change' | 'resize';
-}
-
-export type RightRailAdmissionDecision =
- | { readonly kind: 'none' }
- | { readonly kind: 'close-agents' }
- | { readonly kind: 'close-terminal' };
-
-export function minimumWorkspaceWidthForRightRailPeers({
- otherRailWidthPx,
- editorMinimumWidthPx = 0,
- agentsMinimumWidthPx,
-}: {
- readonly otherRailWidthPx: number;
- readonly editorMinimumWidthPx?: number;
- readonly agentsMinimumWidthPx: number;
-}): number {
- const peerWidthPx = otherRailWidthPx + agentsMinimumWidthPx + MIN_USABLE_RIGHT_TERMINAL_WIDTH_PX;
- return Math.max(
- Math.ceil(peerWidthPx / (1 - EDITOR_RESIDUAL_FRACTION)),
- peerWidthPx + editorMinimumWidthPx,
- );
-}
-
-export function resolveRightRailAdmission({
- workspaceWidthPx,
- otherRailWidthPx,
- editorMinimumWidthPx,
- agentsMinimumWidthPx,
- previous,
- current,
- trigger,
-}: RightRailAdmissionInput): RightRailAdmissionDecision {
- if (!current.terminalRightVisible || !current.agentsVisible) return { kind: 'none' };
-
- const minimumWidthPx = minimumWorkspaceWidthForRightRailPeers({
- otherRailWidthPx,
- editorMinimumWidthPx,
- agentsMinimumWidthPx,
- });
- if (workspaceWidthPx >= minimumWidthPx) return { kind: 'none' };
- if (trigger === 'resize') return { kind: 'close-agents' };
-
- const agentsJustOpened = !previous.agentsVisible && current.agentsVisible;
- const terminalWasAlreadyRight = previous.terminalRightVisible;
- return agentsJustOpened && terminalWasAlreadyRight
- ? { kind: 'close-terminal' }
- : { kind: 'close-agents' };
-}
diff --git a/packages/app/src/components/ui/pane-card.tsx b/packages/app/src/components/ui/pane-card.tsx
index d1d835b39..d84917e07 100644
--- a/packages/app/src/components/ui/pane-card.tsx
+++ b/packages/app/src/components/ui/pane-card.tsx
@@ -3,7 +3,7 @@ import type * as React from 'react';
import type { PaneId } from '@/lib/pane-visibility-store';
import { cn } from '@/lib/utils';
-export type PaneCardVariant = 'card' | 'flat';
+type PaneCardVariant = 'card' | 'flat';
export const PANE_CARD_GAP_PX = 8;
export const PANE_CARD_DIVIDER_PX = 1;
diff --git a/packages/app/src/lib/agents-panel-width-store.test.ts b/packages/app/src/lib/agents-panel-width-store.test.ts
index fb02f3e6c..a86759012 100644
--- a/packages/app/src/lib/agents-panel-width-store.test.ts
+++ b/packages/app/src/lib/agents-panel-width-store.test.ts
@@ -1,13 +1,8 @@
-import { afterEach, describe, expect, test } from 'vitest';
+import { describe, expect, test } from 'vitest';
import {
AGENTS_PANEL_WIDTH_KEY,
- DEFAULT_AGENTS_PANEL_WIDTH,
- getInitialAgentsPanelWidth,
- MIN_AGENTS_PANEL_WIDTH,
readAgentsPanelWidth,
- resolveAgentsPanelPointerRelease,
type WidthStorage,
- writeAgentsPanelWidth,
} from './agents-panel-width-store.ts';
function memoryStorage(initial: Record<string, string> = {}): WidthStorage {
@@ -16,15 +11,12 @@ function memoryStorage(initial: Record<string, string> = {}): WidthStorage {
getItem(key) {
return data.get(key) ?? null;
},
- setItem(key, value) {
- data.set(key, value);
- },
};
}
describe('readAgentsPanelWidth', () => {
- test('absent key returns default', () => {
- expect(readAgentsPanelWidth(memoryStorage())).toBe(DEFAULT_AGENTS_PANEL_WIDTH);
+ test('an absent key reads as no stored width', () => {
+ expect(readAgentsPanelWidth(memoryStorage())).toBeNull();
});
test('valid stored width is returned', () => {
@@ -34,7 +26,7 @@ describe('readAgentsPanelWidth', () => {
test('width below floor is clamped to MIN', () => {
const s = memoryStorage({ [AGENTS_PANEL_WIDTH_KEY]: '200' });
- expect(readAgentsPanelWidth(s)).toBe(MIN_AGENTS_PANEL_WIDTH);
+ expect(readAgentsPanelWidth(s)).toBe(320);
});
test('wide stored width is preserved (no pixel ceiling — layout constraints bound it)', () => {
@@ -42,14 +34,14 @@ describe('readAgentsPanelWidth', () => {
expect(readAgentsPanelWidth(s)).toBe(9999);
});
- test('non-numeric value falls back to default', () => {
+ test('a non-numeric value reads as no stored width', () => {
const s = memoryStorage({ [AGENTS_PANEL_WIDTH_KEY]: 'not a number' });
- expect(readAgentsPanelWidth(s)).toBe(DEFAULT_AGENTS_PANEL_WIDTH);
+ expect(readAgentsPanelWidth(s)).toBeNull();
});
- test('empty string falls back to default', () => {
+ test('an empty string reads as no stored width', () => {
const s = memoryStorage({ [AGENTS_PANEL_WIDTH_KEY]: '' });
- expect(readAgentsPanelWidth(s)).toBe(DEFAULT_AGENTS_PANEL_WIDTH);
+ expect(readAgentsPanelWidth(s)).toBeNull();
});
test('floating-point string is truncated by parseInt', () => {
@@ -58,89 +50,6 @@ describe('readAgentsPanelWidth', () => {
});
});
-describe('writeAgentsPanelWidth', () => {
- test('writes a clamped integer to storage', () => {
- const s = memoryStorage();
- writeAgentsPanelWidth(640, s);
- expect(s.getItem(AGENTS_PANEL_WIDTH_KEY)).toBe('640');
- });
-
- test('clamps to MIN on write below floor', () => {
- const s = memoryStorage();
- writeAgentsPanelWidth(100, s);
- expect(s.getItem(AGENTS_PANEL_WIDTH_KEY)).toBe(String(MIN_AGENTS_PANEL_WIDTH));
- });
-
- test('wide width is written unclamped (no pixel ceiling — layout constraints bound it)', () => {
- const s = memoryStorage();
- writeAgentsPanelWidth(9999, s);
- expect(s.getItem(AGENTS_PANEL_WIDTH_KEY)).toBe('9999');
- });
-
- test('rounds floating-point input before write', () => {
- const s = memoryStorage();
- writeAgentsPanelWidth(640.7, s);
- expect(s.getItem(AGENTS_PANEL_WIDTH_KEY)).toBe('641');
- });
-
- test('quota-exceeded throw is swallowed (in-memory only)', () => {
- const throwing: WidthStorage = {
- getItem() {
- return null;
- },
- setItem() {
- throw new Error('QuotaExceededError');
- },
- };
- expect(() => writeAgentsPanelWidth(640, throwing)).not.toThrow();
- });
-});
-
-describe('resolveAgentsPanelPointerRelease', () => {
- test.each([
- [Number.NaN, { kind: 'restore-preferred', widthPx: 480 }],
- [-1, { kind: 'restore-preferred', widthPx: 480 }],
- [0, { kind: 'close' }],
- [159.999, { kind: 'close' }],
- [160, { kind: 'settle-minimum', widthPx: 320 }],
- [319.999, { kind: 'settle-minimum', widthPx: 320 }],
- [320, { kind: 'commit-preferred', widthPx: 320 }],
- [640.5, { kind: 'commit-preferred', widthPx: 641 }],
- ] as const)('resolves a %s px release', (measuredWidthPx, expected) => {
- expect(resolveAgentsPanelPointerRelease(measuredWidthPx, 480)).toEqual(expected);
- });
-
- test('restores a clamped durable preference when measurement is missing', () => {
- expect(resolveAgentsPanelPointerRelease(undefined, 200)).toEqual({
- kind: 'restore-preferred',
- widthPx: MIN_AGENTS_PANEL_WIDTH,
- });
- });
-});
-
test('the storage key keeps its legacy terminal-width value (migration contract)', () => {
expect(AGENTS_PANEL_WIDTH_KEY).toBe('ok-terminal-width-v1');
});
-
-describe('getInitialAgentsPanelWidth on a storage-restricted host', () => {
- const original = Object.getOwnPropertyDescriptor(globalThis, 'localStorage');
- afterEach(() => {
- if (original) Object.defineProperty(globalThis, 'localStorage', original);
- else Reflect.deleteProperty(globalThis as object, 'localStorage');
- });
-
- test('falls back to the default when the localStorage getter throws', () => {
- Object.defineProperty(globalThis, 'localStorage', {
- configurable: true,
- get() {
- throw new Error('SecurityError: access denied');
- },
- });
- expect(getInitialAgentsPanelWidth()).toBe(DEFAULT_AGENTS_PANEL_WIDTH);
- });
-
- test('falls back to the default when localStorage is absent', () => {
- Reflect.deleteProperty(globalThis as object, 'localStorage');
- expect(getInitialAgentsPanelWidth()).toBe(DEFAULT_AGENTS_PANEL_WIDTH);
- });
-});
diff --git a/packages/app/src/lib/agents-panel-width-store.ts b/packages/app/src/lib/agents-panel-width-store.ts
index 103dded58..bb09af3a0 100644
--- a/packages/app/src/lib/agents-panel-width-store.ts
+++ b/packages/app/src/lib/agents-panel-width-store.ts
@@ -1,66 +1,15 @@
export const AGENTS_PANEL_WIDTH_KEY = 'ok-terminal-width-v1';
-export const DEFAULT_AGENTS_PANEL_WIDTH = 480;
-export const MIN_AGENTS_PANEL_WIDTH = 320;
-const AGENTS_PANEL_CLOSE_THRESHOLD_PX = 160;
-
-export type AgentsPanelPointerReleaseDecision =
- | { readonly kind: 'close' }
- | { readonly kind: 'restore-preferred'; readonly widthPx: number }
- | { readonly kind: 'settle-minimum'; readonly widthPx: number }
- | { readonly kind: 'commit-preferred'; readonly widthPx: number };
+const MIN_AGENTS_PANEL_WIDTH = 320;
export interface WidthStorage {
getItem(key: string): string | null;
- setItem(key: string, value: string): void;
-}
-
-function clamp(px: number): number {
- if (!Number.isFinite(px)) return DEFAULT_AGENTS_PANEL_WIDTH;
- if (px < MIN_AGENTS_PANEL_WIDTH) return MIN_AGENTS_PANEL_WIDTH;
- return Math.round(px);
-}
-
-export function resolveAgentsPanelPointerRelease(
- measuredWidthPx: number | null | undefined,
- preferredWidthPx: number,
-): AgentsPanelPointerReleaseDecision {
- const restoredWidthPx = clamp(preferredWidthPx);
- if (measuredWidthPx == null || !Number.isFinite(measuredWidthPx) || measuredWidthPx < 0) {
- return { kind: 'restore-preferred', widthPx: restoredWidthPx };
- }
- if (measuredWidthPx < AGENTS_PANEL_CLOSE_THRESHOLD_PX) return { kind: 'close' };
- if (measuredWidthPx < MIN_AGENTS_PANEL_WIDTH) {
- return { kind: 'settle-minimum', widthPx: MIN_AGENTS_PANEL_WIDTH };
- }
- return { kind: 'commit-preferred', widthPx: clamp(measuredWidthPx) };
-}
-
-export function readAgentsPanelWidth(storage?: WidthStorage): number {
- try {
- const s = storage ?? localStorage;
- const raw = s.getItem(AGENTS_PANEL_WIDTH_KEY);
- if (raw == null) return DEFAULT_AGENTS_PANEL_WIDTH;
- const parsed = Number.parseInt(raw, 10);
- if (!Number.isFinite(parsed)) return DEFAULT_AGENTS_PANEL_WIDTH;
- return clamp(parsed);
- } catch {
- return DEFAULT_AGENTS_PANEL_WIDTH;
- }
-}
-
-export function writeAgentsPanelWidth(px: number, storage?: WidthStorage): void {
- try {
- const s = storage ?? localStorage;
- s.setItem(AGENTS_PANEL_WIDTH_KEY, String(clamp(px)));
- } catch {}
}
-export function getInitialAgentsPanelWidth(): number {
- try {
- if (typeof localStorage === 'undefined') return DEFAULT_AGENTS_PANEL_WIDTH;
- return readAgentsPanelWidth();
- } catch {
- return DEFAULT_AGENTS_PANEL_WIDTH;
- }
+export function readAgentsPanelWidth(storage: WidthStorage): number | null {
+ const raw = storage.getItem(AGENTS_PANEL_WIDTH_KEY);
+ if (raw === null) return null;
+ const parsed = Number.parseInt(raw, 10);
+ if (!Number.isFinite(parsed)) return null;
+ return Math.max(parsed, MIN_AGENTS_PANEL_WIDTH);
}
diff --git a/packages/app/src/lib/dock-arrangement-store.test.ts b/packages/app/src/lib/dock-arrangement-store.test.ts
new file mode 100644
index 000000000..f86a36822
--- /dev/null
+++ b/packages/app/src/lib/dock-arrangement-store.test.ts
@@ -0,0 +1,436 @@
+import { PREFERRED_TERMINAL_RIGHT_WIDTH } from '@inkeep/open-knowledge-core/terminal-layout';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { PANE_CARD_GAP_PX } from '../components/ui/pane-card.tsx';
+import {
+ type DockArrangement,
+ type DockArrangementStorage,
+ dockArrangementStorageKey,
+ dockTerminalPlacement,
+ legacyDockArrangement,
+ readDockArrangement,
+ withDockTerminalPlacement,
+ writeDockArrangement,
+} from './dock-arrangement-store.ts';
+import { dockPaneMinExtent, layoutDock } from './dock-layout.ts';
+import {
+ DEFAULT_CHAT_SHARE,
+ DEFAULT_DOCK_TREE,
+ type DockNode,
+ isDockLeaf,
+ visibleDockTree,
+} from './dock-tree.ts';
+import type { PaneId } from './pane-visibility-store.ts';
+
+function memoryStorage(initial: Record<string, string> = {}): DockArrangementStorage & {
+ data: Map<string, string>;
+} {
+ const data = new Map(Object.entries(initial));
+ return {
+ data,
+ getItem: (key) => data.get(key) ?? null,
+ setItem: (key, value) => {
+ data.set(key, value);
+ },
+ };
+}
+
+function shape(node: DockNode): unknown {
+ if (isDockLeaf(node)) return node.pane;
+ return { [node.direction]: node.items.map((item) => shape(item.node)) };
+}
+
+function shares(node: DockNode): unknown {
+ if (isDockLeaf(node)) return node.pane;
+ return node.items.map((item) => [Number(item.size.toFixed(4)), shares(item.node)]);
+}
+
+function rawShares(node: DockNode): unknown {
+ if (isDockLeaf(node)) return node.pane;
+ return node.items.map((item) => [Number(item.size.toFixed(10)), rawShares(item.node)]);
+}
+
+function rowShare(tree: DockNode, pane: string): number | undefined {
+ if (isDockLeaf(tree)) return undefined;
+ return tree.items.find((item) => isDockLeaf(item.node) && item.node.pane === pane)?.size;
+}
+
+const workspace = { widthPx: 1400, heightPx: 900 };
+const defaultArrangement = (): DockArrangement => legacyDockArrangement(workspace, memoryStorage());
+
+describe('dock arrangement storage', () => {
+ test('scopes the key to the project', () => {
+ expect(dockArrangementStorageKey('/a/notes')).not.toBe(dockArrangementStorageKey('/b/notes'));
+ expect(dockArrangementStorageKey('/a/notes')).toMatch(/^ok-dock-arrangement-v1:/);
+ });
+
+ test('a host whose origin already belongs to one project uses the unscoped name', () => {
+ expect(dockArrangementStorageKey(null)).toBe('ok-dock-arrangement-v1');
+ });
+
+ test('reads back a written arrangement', () => {
+ const storage = memoryStorage();
+ const key = dockArrangementStorageKey('/a/notes');
+ const written = withDockTerminalPlacement(defaultArrangement(), 'right');
+ writeDockArrangement(key, written, storage);
+ const read = readDockArrangement(key, storage);
+ expect(read === null ? null : shares(read.tree)).toEqual(shares(written.tree));
+ expect(read?.terminalShares).toEqual(written.terminalShares);
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ test('says nothing when no arrangement was ever stored', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ expect(readDockArrangement(dockArrangementStorageKey('/a/notes'), memoryStorage())).toBeNull();
+ expect(warn).not.toHaveBeenCalled();
+ });
+
+ test.each([
+ ['text that is not JSON', '{not json'],
+ [
+ 'JSON that is not a tree',
+ JSON.stringify({
+ tree: { direction: 'row', items: [] },
+ terminalShares: { bottom: 0.3, right: 0.5 },
+ }),
+ ],
+ [
+ 'a tree missing a pane',
+ JSON.stringify({
+ tree: {
+ direction: 'row',
+ items: [
+ { size: 1, node: { pane: 'editor' } },
+ { size: 1, node: { pane: 'agents' } },
+ ],
+ },
+ terminalShares: { bottom: 0.3, right: 0.5 },
+ }),
+ ],
+ ['a tree with no terminal shares', JSON.stringify({ tree: DEFAULT_DOCK_TREE })],
+ [
+ 'a terminal share that is not a fraction',
+ JSON.stringify({ tree: DEFAULT_DOCK_TREE, terminalShares: { bottom: 0.3, right: 1 } }),
+ ],
+ ['a bare tree', JSON.stringify(DEFAULT_DOCK_TREE)],
+ ])('gives no arrangement for %s, and names the record it ignored', (_label, raw) => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const key = dockArrangementStorageKey('/a/notes');
+ expect(readDockArrangement(key, memoryStorage({ [key]: raw }))).toBeNull();
+ expect(warn).toHaveBeenCalledTimes(1);
+ expect(String(warn.mock.calls[0]?.[0])).toContain(key);
+ });
+
+ test('gives no tree when storage itself throws, and names the key it could not use', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const storage: DockArrangementStorage = {
+ getItem: () => {
+ throw new Error('denied');
+ },
+ setItem: () => {
+ throw new Error('denied');
+ },
+ };
+ expect(readDockArrangement('ok-dock-arrangement-v1:blocked', storage)).toBeNull();
+ expect(() =>
+ writeDockArrangement('ok-dock-arrangement-v1:blocked', defaultArrangement(), storage),
+ ).not.toThrow();
+ expect(warn.mock.calls.map(([message]) => String(message))).toEqual([
+ expect.stringContaining('reading ok-dock-arrangement-v1:blocked failed'),
+ expect.stringContaining('writing ok-dock-arrangement-v1:blocked failed'),
+ ]);
+ });
+});
+
+describe('legacyDockArrangement', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ test('a profile that never stored a layout gets the default tree', () => {
+ expect(shares(defaultArrangement().tree)).toEqual(shares(DEFAULT_DOCK_TREE));
+ });
+
+ test.each(['', 'not a number'])(
+ 'an unreadable stored chat width or terminal height %j seeds what no stored value does',
+ (value) => {
+ const { tree } = legacyDockArrangement(
+ workspace,
+ memoryStorage({ 'ok-terminal-width-v1': value, 'ok-terminal-height-v1': value }),
+ );
+ expect(shape(tree)).toEqual(shape(DEFAULT_DOCK_TREE));
+ expect(shares(tree)).toEqual(shares(DEFAULT_DOCK_TREE));
+ },
+ );
+
+ test("a stored chat width becomes chat's share of the window", () => {
+ const { tree } = legacyDockArrangement(
+ workspace,
+ memoryStorage({ 'ok-terminal-width-v1': '700' }),
+ );
+ expect(shape(tree)).toEqual({ row: [{ column: ['editor', 'terminal'] }, 'agents'] });
+ expect(shares(tree)).toEqual([
+ [
+ 0.5,
+ [
+ [Number((2.3 / 3.3).toFixed(4)), 'editor'],
+ [Number((1 / 3.3).toFixed(4)), 'terminal'],
+ ],
+ ],
+ [0.5, 'agents'],
+ ]);
+ });
+
+ test('a stored bottom terminal height becomes its share of the column', () => {
+ const { tree } = legacyDockArrangement(
+ workspace,
+ memoryStorage({ 'ok-terminal-height-v1': '360' }),
+ );
+ expect(shares(tree)).toEqual([
+ [
+ Number((2.5 / 3.5).toFixed(4)),
+ [
+ [0.6, 'editor'],
+ [0.4, 'terminal'],
+ ],
+ ],
+ [Number((1 / 3.5).toFixed(4)), 'agents'],
+ ]);
+ });
+
+ test('a stored right placement puts the terminal between the editor and chat, at its preferred width as its share of the space beside the editor', () => {
+ const { tree } = legacyDockArrangement(
+ workspace,
+ memoryStorage({ 'ok-terminal-placement-v1': 'right' }),
+ );
+ expect(shape(tree)).toEqual({ row: ['editor', 'terminal', 'agents'] });
+ expect(dockTerminalPlacement(tree)).toBe('right');
+ expect(shares(tree)).toEqual(
+ shares(withDockTerminalPlacement(defaultArrangement(), 'right').tree),
+ );
+ expect(rowShare(tree, 'terminal')).toBeCloseTo(
+ (PREFERRED_TERMINAL_RIGHT_WIDTH / 1400) * (1 - DEFAULT_CHAT_SHARE),
+ 10,
+ );
+ });
+
+ test("a stored right width becomes the right terminal's share of the space beside the editor", () => {
+ const { tree } = legacyDockArrangement(
+ workspace,
+ memoryStorage({ 'ok-terminal-placement-v1': 'right', 'ok-terminal-right-width-v1': '420' }),
+ );
+ expect(shares(tree)).toEqual([
+ [Number(((2.5 / 3.5) * 0.7).toFixed(4)), 'editor'],
+ [Number(((2.5 / 3.5) * 0.3).toFixed(4)), 'terminal'],
+ [Number((1 / 3.5).toFixed(4)), 'agents'],
+ ]);
+ });
+
+ test('a window with no size yet seeds the default shares', () => {
+ const { tree } = legacyDockArrangement(
+ { widthPx: 0, heightPx: 0 },
+ memoryStorage({ 'ok-terminal-width-v1': '700', 'ok-terminal-height-v1': '360' }),
+ );
+ expect(shares(tree)).toEqual(shares(DEFAULT_DOCK_TREE));
+ });
+
+ const bottomColumn = [
+ [Number((2.3 / 3.3).toFixed(4)), 'editor'],
+ [Number((1 / 3.3).toFixed(4)), 'terminal'],
+ ];
+
+ test('a stored chat width wider than three fifths of the window is held to three fifths', () => {
+ const { tree } = legacyDockArrangement(
+ { widthPx: 1000, heightPx: 900 },
+ memoryStorage({ 'ok-terminal-width-v1': '900' }),
+ );
+ expect(shares(tree)).toEqual([
+ [0.4, bottomColumn],
+ [0.6, 'agents'],
+ ]);
+ });
+
+ test('a stored chat width under a tenth of the window is raised to a tenth', () => {
+ const { tree } = legacyDockArrangement(
+ { widthPx: 4000, heightPx: 900 },
+ memoryStorage({ 'ok-terminal-width-v1': '320' }),
+ );
+ expect(shares(tree)).toEqual([
+ [0.9, bottomColumn],
+ [0.1, 'agents'],
+ ]);
+ });
+
+ test('a stored terminal height under a tenth of the window is raised to a tenth', () => {
+ const { tree } = legacyDockArrangement(
+ { widthPx: 1400, heightPx: 2000 },
+ memoryStorage({ 'ok-terminal-height-v1': '120' }),
+ );
+ expect(shares(tree)).toEqual([
+ [
+ Number((2.5 / 3.5).toFixed(4)),
+ [
+ [0.9, 'editor'],
+ [0.1, 'terminal'],
+ ],
+ ],
+ [Number((1 / 3.5).toFixed(4)), 'agents'],
+ ]);
+ });
+
+ test("a right terminal's preferred width wider than three fifths of the window is held to three fifths of the space beside the editor", () => {
+ const { tree } = legacyDockArrangement(
+ { widthPx: 1000, heightPx: 900 },
+ memoryStorage({ 'ok-terminal-placement-v1': 'right' }),
+ );
+ expect(shares(tree)).toEqual([
+ [Number(((2.5 / 3.5) * 0.4).toFixed(4)), 'editor'],
+ [Number(((2.5 / 3.5) * 0.6).toFixed(4)), 'terminal'],
+ [Number((1 / 3.5).toFixed(4)), 'agents'],
+ ]);
+ });
+
+ test('a stored right width under a tenth of the window is raised to a tenth of the space beside the editor', () => {
+ const { tree } = legacyDockArrangement(
+ { widthPx: 4000, heightPx: 900 },
+ memoryStorage({ 'ok-terminal-placement-v1': 'right', 'ok-terminal-right-width-v1': '360' }),
+ );
+ expect(shares(tree)).toEqual([
+ [Number(((2.5 / 3.5) * 0.9).toFixed(4)), 'editor'],
+ [Number(((2.5 / 3.5) * 0.1).toFixed(4)), 'terminal'],
+ [Number((1 / 3.5).toFixed(4)), 'agents'],
+ ]);
+ });
+
+ test('storage that throws falls back to the default tree, and names the keys it could not read', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const storage: DockArrangementStorage = {
+ getItem: () => {
+ throw new Error('denied');
+ },
+ setItem: () => {},
+ };
+ expect(shares(legacyDockArrangement(workspace, storage).tree)).toEqual(
+ shares(DEFAULT_DOCK_TREE),
+ );
+ expect(unreadLegacyKeys(warn)).toEqual(EVERY_LEGACY_KEY);
+ });
+});
+
+const EVERY_LEGACY_KEY = [
+ 'ok-terminal-height-v1',
+ 'ok-terminal-placement-v1',
+ 'ok-terminal-right-width-v1',
+ 'ok-terminal-width-v1',
+];
+
+function unreadLegacyKeys(warn: { mock: { calls: unknown[][] } }): string[] {
+ return warn.mock.calls
+ .map(([message]) => /reading (\S+) failed/u.exec(String(message))?.[1] ?? String(message))
+ .toSorted();
+}
+
+describe('legacyDockArrangement on a storage-restricted host', () => {
+ const original = Object.getOwnPropertyDescriptor(globalThis, 'localStorage');
+ afterEach(() => {
+ if (original) Object.defineProperty(globalThis, 'localStorage', original);
+ else Reflect.deleteProperty(globalThis as object, 'localStorage');
+ vi.restoreAllMocks();
+ });
+
+ test('a localStorage getter that throws seeds the default tree, and names every legacy key it could not read', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ Object.defineProperty(globalThis, 'localStorage', {
+ configurable: true,
+ get() {
+ throw new DOMException('access denied', 'SecurityError');
+ },
+ });
+
+ expect(shares(legacyDockArrangement(workspace).tree)).toEqual(shares(DEFAULT_DOCK_TREE));
+ expect(unreadLegacyKeys(warn)).toEqual(EVERY_LEGACY_KEY);
+ });
+
+ test('a host with no localStorage at all seeds the default tree, and names every legacy key it could not read', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ Reflect.deleteProperty(globalThis as object, 'localStorage');
+
+ expect(shares(legacyDockArrangement(workspace).tree)).toEqual(shares(DEFAULT_DOCK_TREE));
+ expect(unreadLegacyKeys(warn)).toEqual(EVERY_LEGACY_KEY);
+ });
+});
+
+describe('terminal placement on the tree', () => {
+ test('moves the terminal beside the editor and back under it', () => {
+ const right = withDockTerminalPlacement(defaultArrangement(), 'right');
+ expect(dockTerminalPlacement(right.tree)).toBe('right');
+ expect(shape(right.tree)).toEqual({ row: ['editor', 'terminal', 'agents'] });
+ const bottom = withDockTerminalPlacement(right, 'bottom');
+ expect(dockTerminalPlacement(bottom.tree)).toBe('bottom');
+ expect(shape(bottom.tree)).toEqual({ row: [{ column: ['editor', 'terminal'] }, 'agents'] });
+ });
+
+ test('a move resizes only the terminal and the editor, and moving back returns every share', () => {
+ const start = legacyDockArrangement(
+ workspace,
+ memoryStorage({ 'ok-terminal-width-v1': '420', 'ok-terminal-height-v1': '360' }),
+ );
+ let arrangement = start;
+ for (let trip = 0; trip < 3; trip += 1) {
+ arrangement = withDockTerminalPlacement(arrangement, 'right');
+ expect(rowShare(arrangement.tree, 'agents')).toBeCloseTo(0.3, 10);
+ expect(rowShare(arrangement.tree, 'terminal')).toBeCloseTo(
+ (PREFERRED_TERMINAL_RIGHT_WIDTH / 1400) * 0.7,
+ 10,
+ );
+ arrangement = withDockTerminalPlacement(arrangement, 'bottom');
+ expect(rawShares(arrangement.tree)).toEqual(rawShares(start.tree));
+ }
+ });
+
+ test('moving the terminal to the bottom and back returns the right-hand shares', () => {
+ const start = legacyDockArrangement(
+ workspace,
+ memoryStorage({ 'ok-terminal-placement-v1': 'right', 'ok-terminal-right-width-v1': '420' }),
+ );
+ const bottom = withDockTerminalPlacement(start, 'bottom');
+ expect(rowShare(bottom.tree, 'agents')).toBeCloseTo(DEFAULT_CHAT_SHARE, 10);
+ expect(rawShares(withDockTerminalPlacement(bottom, 'right').tree)).toEqual(
+ rawShares(start.tree),
+ );
+ });
+
+ test('leaves the arrangement alone when the terminal is already there', () => {
+ const arrangement = defaultArrangement();
+ expect(withDockTerminalPlacement(arrangement, 'bottom')).toBe(arrangement);
+ });
+});
+
+describe('the first move right at a 1440px window', () => {
+ function widthsAfterMovingRight(isVisible: (pane: PaneId) => boolean) {
+ const seeded = legacyDockArrangement({ widthPx: 1440, heightPx: 900 }, memoryStorage());
+ const { tree } = withDockTerminalPlacement(seeded, 'right');
+ const layout = layoutDock(
+ visibleDockTree(tree, isVisible),
+ { x: 0, y: 0, width: 1440, height: 900 },
+ PANE_CARD_GAP_PX,
+ dockPaneMinExtent,
+ );
+ return Object.fromEntries(
+ [...layout.panes].map(([pane, rect]) => [pane, Math.round(rect.width)]),
+ );
+ }
+
+ test('with Agents open the terminal takes its share beside the editor, and the editor keeps more than its minimum', () => {
+ expect(widthsAfterMovingRight(() => true)).toEqual({ editor: 494, terminal: 523, agents: 407 });
+ });
+
+ test('with Agents closed the terminal opens at about its preferred width', () => {
+ expect(widthsAfterMovingRight((pane) => pane !== 'agents')).toEqual({
+ editor: 696,
+ terminal: 736,
+ });
+ });
+});
diff --git a/packages/app/src/lib/dock-arrangement-store.ts b/packages/app/src/lib/dock-arrangement-store.ts
new file mode 100644
index 000000000..f57a2436f
--- /dev/null
+++ b/packages/app/src/lib/dock-arrangement-store.ts
@@ -0,0 +1,186 @@
+import type { TerminalPlacement } from '@inkeep/open-knowledge-core/terminal-layout';
+import { readAgentsPanelWidth } from './agents-panel-width-store';
+import {
+ bottomTerminalDockTree,
+ DEFAULT_BOTTOM_TERMINAL_SHARE,
+ DEFAULT_CHAT_SHARE,
+ type DockNode,
+ dockPaneDirection,
+ dockPaneHeirShare,
+ moveDockPane,
+ parseDockTree,
+} from './dock-tree';
+import { scopedStorageKey } from './storage-scope';
+import { readTerminalHeight } from './terminal-height-store';
+import { readTerminalPlacement } from './terminal-placement-store';
+import { readTerminalRightWidth } from './terminal-right-width-store';
+
+const DOCK_ARRANGEMENT_KEY = 'ok-dock-arrangement-v1';
+const UNMEASURED_RIGHT_TERMINAL_SHARE = 0.3;
+const LEGACY_MIN_SHARE = 0.1;
+const LEGACY_MAX_SHARE = 0.6;
+
+type DockTerminalShares = Readonly<Record<TerminalPlacement, number>>;
+
+export interface DockArrangement {
+ readonly tree: DockNode;
+ readonly terminalShares: DockTerminalShares;
+}
+
+export interface DockArrangementStorage {
+ getItem(key: string): string | null;
+ setItem(key: string, value: string): void;
+}
+
+export function dockArrangementStorageKey(contentDir: string | null): string {
+ return scopedStorageKey(DOCK_ARRANGEMENT_KEY, contentDir);
+}
+
+function parseTerminalShare(value: unknown): number | null {
+ return typeof value === 'number' && value > 0 && value < 1 ? value : null;
+}
+
+function parseDockArrangement(value: unknown): DockArrangement | null {
+ if (typeof value !== 'object' || value === null) return null;
+ const record = value as Record<string, unknown>;
+ const tree = parseDockTree(record.tree);
+ const shares = record.terminalShares;
+ if (tree === null || typeof shares !== 'object' || shares === null) return null;
+ const bottom = parseTerminalShare((shares as Record<string, unknown>).bottom);
+ const right = parseTerminalShare((shares as Record<string, unknown>).right);
+ if (bottom === null || right === null) return null;
+ return { tree, terminalShares: { bottom, right } };
+}
+
+export function readDockArrangement(
+ key: string,
+ storage?: DockArrangementStorage,
+): DockArrangement | null {
+ let raw: string | null;
+ try {
+ raw = (storage ?? localStorage).getItem(key);
+ } catch (err) {
+ console.warn(`[dock-arrangement-store] reading ${key} failed: ${String(err)}`);
+ return null;
+ }
+ if (raw === null) return null;
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(raw);
+ } catch (err) {
+ console.warn(
+ `[dock-arrangement-store] stored ${key} record was not valid JSON; ignoring it: ${String(err)}`,
+ );
+ return null;
+ }
+ const arrangement = parseDockArrangement(parsed);
+ if (arrangement === null) {
+ console.warn(
+ `[dock-arrangement-store] stored ${key} record is not a dock arrangement; ignoring it`,
+ );
+ }
+ return arrangement;
+}
+
+export function writeDockArrangement(
+ key: string,
+ arrangement: DockArrangement,
+ storage?: DockArrangementStorage,
+): void {
+ try {
+ (storage ?? localStorage).setItem(key, JSON.stringify(arrangement));
+ } catch (err) {
+ console.warn(`[dock-arrangement-store] writing ${key} failed: ${String(err)}`);
+ }
+}
+
+export interface LegacyDockStorage {
+ getItem(key: string): string | null;
+}
+
+export interface DockWorkspaceExtent {
+ readonly widthPx: number;
+ readonly heightPx: number;
+}
+
+function legacyShare(px: number | null, total: number, fallback: number): number {
+ if (px === null || !Number.isFinite(px) || !Number.isFinite(total) || total <= 0) {
+ return fallback;
+ }
+ return Math.min(Math.max(px / total, LEGACY_MIN_SHARE), LEGACY_MAX_SHARE);
+}
+
+// precedent #59: seeded from the retired app-global layout keys, which nothing writes any more.
+function seededDockArrangement(
+ workspace: DockWorkspaceExtent,
+ source: LegacyDockStorage,
+): DockArrangement {
+ const chatShare = legacyShare(
+ readAgentsPanelWidth(source),
+ workspace.widthPx,
+ DEFAULT_CHAT_SHARE,
+ );
+ const rightShare = legacyShare(
+ readTerminalRightWidth(source),
+ workspace.widthPx,
+ UNMEASURED_RIGHT_TERMINAL_SHARE,
+ );
+ const bottomShare = legacyShare(
+ readTerminalHeight(source, workspace.heightPx),
+ workspace.heightPx,
+ DEFAULT_BOTTOM_TERMINAL_SHARE,
+ );
+ const bottom: DockArrangement = {
+ tree: bottomTerminalDockTree(chatShare, bottomShare),
+ terminalShares: { bottom: bottomShare, right: rightShare },
+ };
+ return readTerminalPlacement(source) === 'right'
+ ? withDockTerminalPlacement(bottom, 'right')
+ : bottom;
+}
+
+function legacyStorage(storage: LegacyDockStorage | undefined): LegacyDockStorage {
+ return {
+ getItem(key) {
+ try {
+ return (storage ?? localStorage).getItem(key);
+ } catch (err) {
+ console.warn(`[dock-arrangement-store] reading ${key} failed: ${String(err)}`);
+ return null;
+ }
+ },
+ };
+}
+
+export function legacyDockArrangement(
+ workspace: DockWorkspaceExtent,
+ storage?: LegacyDockStorage,
+): DockArrangement {
+ return seededDockArrangement(workspace, legacyStorage(storage));
+}
+
+export function dockTerminalPlacement(tree: DockNode): TerminalPlacement {
+ return dockPaneDirection(tree, 'terminal') === 'column' ? 'bottom' : 'right';
+}
+
+export function withDockTerminalPlacement(
+ arrangement: DockArrangement,
+ placement: TerminalPlacement,
+): DockArrangement {
+ const leaving = dockTerminalPlacement(arrangement.tree);
+ if (leaving === placement) return arrangement;
+ const leavingShare = dockPaneHeirShare(arrangement.tree, 'terminal');
+ return {
+ tree: moveDockPane(
+ arrangement.tree,
+ 'terminal',
+ 'editor',
+ placement === 'bottom' ? 'bottom' : 'end',
+ arrangement.terminalShares[placement],
+ ),
+ terminalShares:
+ leavingShare === null
+ ? arrangement.terminalShares
+ : { ...arrangement.terminalShares, [leaving]: leavingShare },
+ };
+}
diff --git a/packages/app/src/lib/dock-layout.test.ts b/packages/app/src/lib/dock-layout.test.ts
new file mode 100644
index 000000000..ff83627f2
--- /dev/null
+++ b/packages/app/src/lib/dock-layout.test.ts
@@ -0,0 +1,168 @@
+import { describe, expect, test } from 'vitest';
+import {
+ clampDockSeam,
+ type DockExtent,
+ type DockRect,
+ dockSeamPercent,
+ dockSeamShares,
+ EMPTY_DOCK_LAYOUT,
+ fitDockLengths,
+ layoutDock,
+ minDockExtent,
+} from './dock-layout.ts';
+import { DEFAULT_DOCK_TREE, resizeDockGroup, visibleDockTree } from './dock-tree.ts';
+import type { PaneId } from './pane-visibility-store.ts';
+
+const MINS: Record<PaneId, DockExtent> = {
+ editor: { width: 340, height: 180 },
+ agents: { width: 290, height: 170 },
+ terminal: { width: 325, height: 120 },
+};
+const minOf = (pane: PaneId) => MINS[pane];
+const GAP = 8;
+const BOUNDS: DockRect = { x: 0, y: 0, width: 1200, height: 800 };
+const everyPane = () => true;
+
+describe('fitDockLengths', () => {
+ test('keeps lengths that already meet their minimums', () => {
+ expect(fitDockLengths([600, 400], [100, 100], 1000)).toEqual([600, 400]);
+ });
+
+ test('raises an item to its minimum and takes the difference from the others in proportion', () => {
+ const lengths = fitDockLengths([900, 50, 50], [100, 200, 0], 1000);
+ expect(lengths[1]).toBe(200);
+ expect(lengths[0]).toBeCloseTo((900 / 950) * 800);
+ expect(lengths[2]).toBeCloseTo((50 / 950) * 800);
+ expect(lengths.reduce((sum, length) => sum + length, 0)).toBeCloseTo(1000);
+ });
+
+ test('raises an item that raising another pushed under its own minimum', () => {
+ const lengths = fitDockLengths([300, 400, 300], [340, 325, 290], 1000);
+ expect(lengths[0]).toBe(340);
+ expect(lengths[2]).toBe(290);
+ expect(lengths[1]).toBeCloseTo(1000 - 340 - 290);
+ });
+
+ test('shares the room by minimum when every minimum cannot fit', () => {
+ expect(fitDockLengths([500, 500], [300, 100], 200)).toEqual([150, 50]);
+ });
+
+ test('gives nothing when there is no room', () => {
+ expect(fitDockLengths([0, 0], [0, 0], 0)).toEqual([0, 0]);
+ });
+});
+
+describe('minDockExtent', () => {
+ test('adds minimums along a group and takes the largest across it', () => {
+ const tree = visibleDockTree(DEFAULT_DOCK_TREE, everyPane);
+ if (tree === null) throw new Error('expected a tree');
+ expect(minDockExtent(tree, minOf, GAP)).toEqual({
+ width: 340 + GAP + 290,
+ height: 180 + GAP + 120,
+ });
+ });
+});
+
+describe('layoutDock', () => {
+ test('lays the default tree out edge to edge with a gap between units', () => {
+ const layout = layoutDock(visibleDockTree(DEFAULT_DOCK_TREE, everyPane), BOUNDS, GAP, minOf);
+ const editor = layout.panes.get('editor');
+ const terminal = layout.panes.get('terminal');
+ const agents = layout.panes.get('agents');
+ if (editor === undefined || terminal === undefined || agents === undefined) {
+ throw new Error('expected every pane');
+ }
+ expect(editor.x).toBe(0);
+ expect(editor.y).toBe(0);
+ expect(terminal.x).toBe(0);
+ expect(terminal.y).toBe(editor.height + GAP);
+ expect(terminal.y + terminal.height).toBe(BOUNDS.height);
+ expect(agents.x).toBe(editor.width + GAP);
+ expect(agents.x + agents.width).toBe(BOUNDS.width);
+ expect(agents.height).toBe(BOUNDS.height);
+ expect(editor.width / agents.width).toBeCloseTo(2.5, 1);
+ expect(editor.height / terminal.height).toBeCloseTo(2.3, 1);
+ expect(layout.seams).toHaveLength(2);
+ });
+
+ test('puts each seam in the gap between the units it separates', () => {
+ const layout = layoutDock(visibleDockTree(DEFAULT_DOCK_TREE, everyPane), BOUNDS, GAP, minOf);
+ const editor = layout.panes.get('editor');
+ const row = layout.seams.find((seam) => seam.direction === 'row');
+ const column = layout.seams.find((seam) => seam.direction === 'column');
+ if (editor === undefined || row === undefined || column === undefined) {
+ throw new Error('expected both seams');
+ }
+ expect(row.rect).toEqual({ x: editor.width, y: 0, width: GAP, height: BOUNDS.height });
+ expect(row.after).toEqual(['agents']);
+ expect(column.rect).toEqual({ x: 0, y: editor.height, width: editor.width, height: GAP });
+ expect(column.path).toEqual([0]);
+ });
+
+ test('gives a lone pane the whole workspace and no seams', () => {
+ const layout = layoutDock(
+ visibleDockTree(DEFAULT_DOCK_TREE, (pane) => pane === 'agents'),
+ BOUNDS,
+ GAP,
+ minOf,
+ );
+ expect(layout.panes.get('agents')).toEqual(BOUNDS);
+ expect(layout.seams).toHaveLength(0);
+ });
+
+ test('lays out nothing without a tree or without room', () => {
+ expect(layoutDock(null, BOUNDS, GAP, minOf)).toBe(EMPTY_DOCK_LAYOUT);
+ expect(
+ layoutDock(
+ visibleDockTree(DEFAULT_DOCK_TREE, everyPane),
+ { ...BOUNDS, width: 0 },
+ GAP,
+ minOf,
+ ),
+ ).toBe(EMPTY_DOCK_LAYOUT);
+ });
+
+ test('keeps each pane at its minimum when the stored share is smaller', () => {
+ const squeezed = resizeDockGroup(
+ DEFAULT_DOCK_TREE,
+ [],
+ new Map([
+ [0, 0.97],
+ [1, 0.03],
+ ]),
+ );
+ const layout = layoutDock(visibleDockTree(squeezed, everyPane), BOUNDS, GAP, minOf);
+ expect(layout.panes.get('agents')?.width).toBe(290);
+ });
+});
+
+describe('dock seams', () => {
+ const layout = layoutDock(visibleDockTree(DEFAULT_DOCK_TREE, everyPane), BOUNDS, GAP, minOf);
+ const rowSeam = layout.seams.find((seam) => seam.direction === 'row');
+ if (rowSeam === undefined) throw new Error('expected a row seam');
+
+ test('a drag past a minimum stops at it', () => {
+ expect(clampDockSeam(rowSeam, 10)).toBe(340);
+ const pair = (rowSeam.lengths[0] ?? 0) + (rowSeam.lengths[1] ?? 0);
+ expect(clampDockSeam(rowSeam, pair)).toBe(pair - 290);
+ });
+
+ test('moving a seam keeps the other units and lands where it was dropped', () => {
+ const shares = dockSeamShares(rowSeam, 700);
+ expect([...shares.values()].reduce((sum, share) => sum + share, 0)).toBeCloseTo(1);
+ const resized = resizeDockGroup(DEFAULT_DOCK_TREE, rowSeam.path, shares);
+ const after = layoutDock(visibleDockTree(resized, everyPane), BOUNDS, GAP, minOf);
+ expect(after.panes.get('editor')?.width).toBe(700);
+ expect(after.panes.get('agents')?.width).toBe(BOUNDS.width - 700 - GAP);
+ });
+
+ test('reports the share of the pane after it as a percentage within its limits', () => {
+ const value = dockSeamPercent(rowSeam);
+ const pair = (rowSeam.lengths[0] ?? 0) + (rowSeam.lengths[1] ?? 0);
+ expect(value.now).toBe(Math.round(((rowSeam.lengths[1] ?? 0) / pair) * 100));
+ expect(value.min).toBeLessThanOrEqual(value.now);
+ expect(value.now).toBeLessThanOrEqual(value.max);
+ expect(value.max).toBeLessThanOrEqual(100);
+ expect(value.min).toBeGreaterThanOrEqual(0);
+ });
+});
diff --git a/packages/app/src/lib/dock-layout.ts b/packages/app/src/lib/dock-layout.ts
new file mode 100644
index 000000000..54b52fb0e
--- /dev/null
+++ b/packages/app/src/lib/dock-layout.ts
@@ -0,0 +1,229 @@
+import { MIN_TERMINAL_RIGHT_WIDTH } from '@inkeep/open-knowledge-core/terminal-layout';
+import {
+ type DockDirection,
+ type DockPath,
+ isVisibleDockLeaf,
+ type VisibleDockGroup,
+ type VisibleDockNode,
+} from './dock-tree';
+import type { PaneId } from './pane-visibility-store';
+
+export interface DockRect {
+ readonly x: number;
+ readonly y: number;
+ readonly width: number;
+ readonly height: number;
+}
+
+export interface DockExtent {
+ readonly width: number;
+ readonly height: number;
+}
+
+export interface DockSeam {
+ readonly path: DockPath;
+ readonly direction: DockDirection;
+ readonly index: number;
+ readonly rect: DockRect;
+ readonly slots: readonly number[];
+ readonly lengths: readonly number[];
+ readonly minLengths: readonly number[];
+ readonly after: readonly PaneId[];
+}
+
+export interface DockLayout {
+ readonly panes: ReadonlyMap<PaneId, DockRect>;
+ readonly seams: readonly DockSeam[];
+}
+
+export const EMPTY_DOCK_LAYOUT: DockLayout = { panes: new Map(), seams: [] };
+
+const DOCK_PANE_MIN_EXTENT: Readonly<Record<PaneId, DockExtent>> = {
+ editor: { width: 340, height: 180 },
+ agents: { width: 290, height: 170 },
+ terminal: { width: MIN_TERMINAL_RIGHT_WIDTH, height: 120 },
+};
+
+export function dockPaneMinExtent(pane: PaneId): DockExtent {
+ return DOCK_PANE_MIN_EXTENT[pane];
+}
+
+type MinExtentOf = (pane: PaneId) => DockExtent;
+
+function axisLength(extent: DockExtent, direction: DockDirection): number {
+ return direction === 'row' ? extent.width : extent.height;
+}
+
+export function minDockExtent(node: VisibleDockNode, minOf: MinExtentOf, gap: number): DockExtent {
+ if (isVisibleDockLeaf(node)) return minOf(node.pane);
+ const children = node.items.map((item) => minDockExtent(item.node, minOf, gap));
+ const gaps = gap * (children.length - 1);
+ const along = children.reduce((sum, child) => sum + axisLength(child, node.direction), 0) + gaps;
+ const across = Math.max(
+ ...children.map((child) => axisLength(child, node.direction === 'row' ? 'column' : 'row')),
+ );
+ return node.direction === 'row'
+ ? { width: along, height: across }
+ : { width: across, height: along };
+}
+
+export function fitDockLengths(
+ desired: readonly number[],
+ mins: readonly number[],
+ total: number,
+): number[] {
+ const room = Math.max(total, 0);
+ const minTotal = mins.reduce((sum, min) => sum + min, 0);
+ if (minTotal >= room) {
+ return minTotal === 0 ? desired.map(() => 0) : mins.map((min) => (min / minTotal) * room);
+ }
+ const fixed = new Set<number>();
+ let lengths = [...desired];
+ for (let round = 0; round <= desired.length; round += 1) {
+ const fixedLength = [...fixed].reduce((sum, index) => sum + (mins[index] ?? 0), 0);
+ const freeDesired = desired.reduce(
+ (sum, length, index) => (fixed.has(index) ? sum : sum + length),
+ 0,
+ );
+ const freeRoom = room - fixedLength;
+ lengths = desired.map((length, index) => {
+ if (fixed.has(index)) return mins[index] ?? 0;
+ return freeDesired > 0
+ ? (length / freeDesired) * freeRoom
+ : freeRoom / (desired.length - fixed.size);
+ });
+ const short = lengths.findIndex(
+ (length, index) => !fixed.has(index) && length < (mins[index] ?? 0),
+ );
+ if (short < 0) break;
+ lengths.forEach((length, index) => {
+ if (!fixed.has(index) && length < (mins[index] ?? 0)) fixed.add(index);
+ });
+ }
+ return lengths;
+}
+
+function panesOf(node: VisibleDockNode): PaneId[] {
+ if (isVisibleDockLeaf(node)) return [node.pane];
+ return node.items.flatMap((item) => panesOf(item.node));
+}
+
+function layoutGroup(
+ group: VisibleDockGroup,
+ bounds: DockRect,
+ gap: number,
+ minOf: MinExtentOf,
+ panes: Map<PaneId, DockRect>,
+ seams: DockSeam[],
+) {
+ const row = group.direction === 'row';
+ const along = row ? bounds.width : bounds.height;
+ const room = along - gap * (group.items.length - 1);
+ const mins = group.items.map((item) =>
+ axisLength(minDockExtent(item.node, minOf, gap), group.direction),
+ );
+ const lengths = fitDockLengths(
+ group.items.map((item) => item.share * Math.max(room, 0)),
+ mins,
+ room,
+ );
+ let cursor = row ? bounds.x : bounds.y;
+ const starts: number[] = [];
+ const ends: number[] = [];
+ group.items.forEach((item, index) => {
+ const start = Math.round(cursor);
+ const end = Math.round(cursor + (lengths[index] ?? 0));
+ const rect: DockRect = row
+ ? { x: start, y: bounds.y, width: end - start, height: bounds.height }
+ : { x: bounds.x, y: start, width: bounds.width, height: end - start };
+ layoutNode(item.node, rect, gap, minOf, panes, seams);
+ starts.push(start);
+ ends.push(end);
+ cursor += (lengths[index] ?? 0) + gap;
+ });
+ const roundedLengths = ends.map((end, index) => end - (starts[index] ?? end));
+ for (let index = 0; index < group.items.length - 1; index += 1) {
+ const seamStart = ends[index] ?? 0;
+ const after = group.items[index + 1];
+ if (after === undefined) continue;
+ seams.push({
+ path: group.path,
+ direction: group.direction,
+ index,
+ rect: row
+ ? { x: seamStart, y: bounds.y, width: gap, height: bounds.height }
+ : { x: bounds.x, y: seamStart, width: bounds.width, height: gap },
+ slots: group.items.map((item) => item.slot),
+ lengths: roundedLengths,
+ minLengths: mins,
+ after: panesOf(after.node),
+ });
+ }
+}
+
+function layoutNode(
+ node: VisibleDockNode,
+ bounds: DockRect,
+ gap: number,
+ minOf: MinExtentOf,
+ panes: Map<PaneId, DockRect>,
+ seams: DockSeam[],
+) {
+ if (isVisibleDockLeaf(node)) {
+ panes.set(node.pane, bounds);
+ return;
+ }
+ layoutGroup(node, bounds, gap, minOf, panes, seams);
+}
+
+export function layoutDock(
+ node: VisibleDockNode | null,
+ bounds: DockRect,
+ gap: number,
+ minOf: MinExtentOf,
+): DockLayout {
+ if (node === null || bounds.width <= 0 || bounds.height <= 0) return EMPTY_DOCK_LAYOUT;
+ const panes = new Map<PaneId, DockRect>();
+ const seams: DockSeam[] = [];
+ layoutNode(node, bounds, gap, minOf, panes, seams);
+ return { panes, seams };
+}
+
+export function clampDockSeam(seam: DockSeam, beforeLength: number): number {
+ const before = seam.lengths[seam.index] ?? 0;
+ const after = seam.lengths[seam.index + 1] ?? 0;
+ const pair = before + after;
+ const minBefore = seam.minLengths[seam.index] ?? 0;
+ const minAfter = seam.minLengths[seam.index + 1] ?? 0;
+ if (minBefore + minAfter >= pair) return before;
+ return Math.min(Math.max(beforeLength, minBefore), pair - minAfter);
+}
+
+export function dockSeamShares(seam: DockSeam, beforeLength: number): Map<number, number> {
+ const clamped = clampDockSeam(seam, beforeLength);
+ const lengths = [...seam.lengths];
+ const pair = (lengths[seam.index] ?? 0) + (lengths[seam.index + 1] ?? 0);
+ lengths[seam.index] = clamped;
+ lengths[seam.index + 1] = pair - clamped;
+ const total = lengths.reduce((sum, length) => sum + length, 0);
+ const shares = new Map<number, number>();
+ seam.slots.forEach((slot, index) => {
+ shares.set(slot, total > 0 ? (lengths[index] ?? 0) / total : 1 / seam.slots.length);
+ });
+ return shares;
+}
+
+export function dockSeamPercent(seam: DockSeam): { now: number; min: number; max: number } {
+ const before = seam.lengths[seam.index] ?? 0;
+ const after = seam.lengths[seam.index + 1] ?? 0;
+ const pair = before + after;
+ if (pair <= 0) return { now: 50, min: 0, max: 100 };
+ const minBefore = seam.minLengths[seam.index] ?? 0;
+ const minAfter = seam.minLengths[seam.index + 1] ?? 0;
+ const percent = (value: number) => Math.round((value / pair) * 100);
+ return {
+ now: percent(after),
+ min: Math.min(percent(minAfter), percent(after)),
+ max: Math.max(100 - percent(minBefore), percent(after)),
+ };
+}
diff --git a/packages/app/src/lib/dock-tree.test.ts b/packages/app/src/lib/dock-tree.test.ts
new file mode 100644
index 000000000..d95b58ae2
--- /dev/null
+++ b/packages/app/src/lib/dock-tree.test.ts
@@ -0,0 +1,319 @@
+import { describe, expect, test } from 'vitest';
+import {
+ DEFAULT_DOCK_TREE,
+ type DockGroup,
+ type DockNode,
+ dockPaneDirection,
+ dockTreePanes,
+ isDockLeaf,
+ isVisibleDockLeaf,
+ moveDockPane,
+ normalizeDockTree,
+ parseDockTree,
+ resizeDockGroup,
+ type VisibleDockGroup,
+ visibleDockTree,
+} from './dock-tree.ts';
+import type { PaneId } from './pane-visibility-store.ts';
+
+function shape(node: DockNode): unknown {
+ if (isDockLeaf(node)) return node.pane;
+ return { [node.direction]: node.items.map((item) => shape(item.node)) };
+}
+
+function sizes(node: DockNode): number[] {
+ return isDockLeaf(node) ? [] : node.items.map((item) => Number(item.size.toFixed(4)));
+}
+
+function only(...panes: PaneId[]) {
+ return (pane: PaneId) => panes.includes(pane);
+}
+
+const everyPane = only('editor', 'agents', 'terminal');
+
+describe('parseDockTree', () => {
+ test('reads back the default tree', () => {
+ const parsed = parseDockTree(JSON.parse(JSON.stringify(DEFAULT_DOCK_TREE)));
+ expect(parsed).not.toBeNull();
+ if (parsed === null) return;
+ expect(shape(parsed)).toEqual({ row: [{ column: ['editor', 'terminal'] }, 'agents'] });
+ expect(sizes(parsed).reduce((sum, size) => sum + size, 0)).toBeCloseTo(1);
+ });
+
+ test.each([
+ ['a value that is not a tree', 'editor'],
+ ['null', null],
+ [
+ 'an unknown pane',
+ {
+ direction: 'row',
+ items: [
+ { size: 1, node: { pane: 'graph' } },
+ { size: 1, node: { pane: 'editor' } },
+ ],
+ },
+ ],
+ [
+ 'a pane listed twice',
+ {
+ direction: 'row',
+ items: [
+ { size: 1, node: { pane: 'editor' } },
+ { size: 1, node: { pane: 'editor' } },
+ { size: 1, node: { pane: 'agents' } },
+ ],
+ },
+ ],
+ [
+ 'a missing pane',
+ {
+ direction: 'row',
+ items: [
+ { size: 1, node: { pane: 'editor' } },
+ { size: 1, node: { pane: 'agents' } },
+ ],
+ },
+ ],
+ [
+ 'an unknown direction',
+ {
+ direction: 'diagonal',
+ items: [
+ { size: 1, node: { pane: 'editor' } },
+ { size: 1, node: { pane: 'agents' } },
+ { size: 1, node: { pane: 'terminal' } },
+ ],
+ },
+ ],
+ [
+ 'a group with one item',
+ {
+ direction: 'row',
+ items: [
+ {
+ size: 1,
+ node: {
+ direction: 'column',
+ items: [{ size: 1, node: { pane: 'editor' } }],
+ },
+ },
+ { size: 1, node: { pane: 'agents' } },
+ { size: 1, node: { pane: 'terminal' } },
+ ],
+ },
+ ],
+ [
+ 'a size of zero',
+ {
+ direction: 'row',
+ items: [
+ { size: 0, node: { pane: 'editor' } },
+ { size: 1, node: { pane: 'agents' } },
+ { size: 1, node: { pane: 'terminal' } },
+ ],
+ },
+ ],
+ [
+ 'a size that is not a number',
+ {
+ direction: 'row',
+ items: [
+ { size: '1', node: { pane: 'editor' } },
+ { size: 1, node: { pane: 'agents' } },
+ { size: 1, node: { pane: 'terminal' } },
+ ],
+ },
+ ],
+ [
+ 'sizes too large to add up',
+ {
+ direction: 'row',
+ items: [
+ { size: 1e308, node: { pane: 'editor' } },
+ {
+ size: 1e308,
+ node: {
+ direction: 'column',
+ items: [
+ { size: 1, node: { pane: 'agents' } },
+ { size: 1, node: { pane: 'terminal' } },
+ ],
+ },
+ },
+ ],
+ },
+ ],
+ [
+ 'a nested size too small to keep',
+ {
+ direction: 'row',
+ items: [
+ {
+ size: 5e-324,
+ node: {
+ direction: 'row',
+ items: [
+ { size: 5e-324, node: { pane: 'editor' } },
+ { size: 5e-324, node: { pane: 'agents' } },
+ ],
+ },
+ },
+ { size: 1, node: { pane: 'terminal' } },
+ ],
+ },
+ ],
+ ])('refuses %s', (_label, value) => {
+ expect(parseDockTree(value)).toBeNull();
+ });
+
+ test('flattens a row nested in a row and keeps the proportions', () => {
+ const parsed = parseDockTree({
+ direction: 'row',
+ items: [
+ {
+ size: 2,
+ node: {
+ direction: 'row',
+ items: [
+ { size: 1, node: { pane: 'editor' } },
+ { size: 1, node: { pane: 'terminal' } },
+ ],
+ },
+ },
+ { size: 2, node: { pane: 'agents' } },
+ ],
+ });
+ expect(parsed).not.toBeNull();
+ if (parsed === null) return;
+ expect(shape(parsed)).toEqual({ row: ['editor', 'terminal', 'agents'] });
+ expect(sizes(parsed)).toEqual([0.25, 0.25, 0.5]);
+ });
+});
+
+describe('normalizeDockTree', () => {
+ test('unwraps a group left with one item', () => {
+ const tree: DockGroup = {
+ direction: 'row',
+ items: [
+ { size: 1, node: { direction: 'column', items: [{ size: 1, node: { pane: 'editor' } }] } },
+ { size: 1, node: { pane: 'agents' } },
+ ],
+ };
+ expect(shape(normalizeDockTree(tree))).toEqual({ row: ['editor', 'agents'] });
+ });
+});
+
+describe('visibleDockTree', () => {
+ test('keeps every pane and the full-tree slot of each item', () => {
+ const visible = visibleDockTree(DEFAULT_DOCK_TREE, everyPane) as VisibleDockGroup;
+ expect(visible.path).toEqual([]);
+ expect(visible.items.map((item) => item.slot)).toEqual([0, 1]);
+ const column = visible.items[0]?.node as VisibleDockGroup;
+ expect(column.path).toEqual([0]);
+ expect(column.items.map((item) => item.slot)).toEqual([0, 1]);
+ });
+
+ test('a hidden terminal leaves the editor in its column slot, sharing the row with chat', () => {
+ const visible = visibleDockTree(
+ DEFAULT_DOCK_TREE,
+ only('editor', 'agents'),
+ ) as VisibleDockGroup;
+ expect(visible.direction).toBe('row');
+ expect(
+ visible.items.map((item) => [item.slot, isVisibleDockLeaf(item.node) && item.node.pane]),
+ ).toEqual([
+ [0, 'editor'],
+ [1, 'agents'],
+ ]);
+ expect(visible.items.reduce((sum, item) => sum + item.share, 0)).toBeCloseTo(1);
+ });
+
+ test('a single visible pane is the whole tree', () => {
+ expect(visibleDockTree(DEFAULT_DOCK_TREE, only('agents'))).toEqual({ pane: 'agents' });
+ });
+
+ test('nothing visible gives no tree', () => {
+ expect(visibleDockTree(DEFAULT_DOCK_TREE, only())).toBeNull();
+ });
+});
+
+describe('resizeDockGroup', () => {
+ test('changes the visible slots and keeps a hidden slot for when it comes back', () => {
+ const tree: DockGroup = {
+ direction: 'row',
+ items: [
+ { size: 0.5, node: { pane: 'editor' } },
+ { size: 0.25, node: { pane: 'terminal' } },
+ { size: 0.25, node: { pane: 'agents' } },
+ ],
+ };
+ const resized = resizeDockGroup(
+ tree,
+ [],
+ new Map([
+ [0, 0.25],
+ [2, 0.75],
+ ]),
+ );
+ expect(sizes(resized)).toEqual([0.1875, 0.25, 0.5625]);
+ const visible = visibleDockTree(resized, only('editor', 'agents')) as VisibleDockGroup;
+ expect(visible.items.map((item) => Number(item.share.toFixed(4)))).toEqual([0.25, 0.75]);
+ });
+
+ test('leaves the tree alone for a path that is not a group', () => {
+ expect(resizeDockGroup(DEFAULT_DOCK_TREE, [1], new Map([[0, 1]]))).toBe(DEFAULT_DOCK_TREE);
+ expect(resizeDockGroup(DEFAULT_DOCK_TREE, [7], new Map([[0, 1]]))).toBe(DEFAULT_DOCK_TREE);
+ });
+
+ test('leaves the tree alone for a share that is not positive', () => {
+ expect(
+ resizeDockGroup(
+ DEFAULT_DOCK_TREE,
+ [],
+ new Map([
+ [0, 0],
+ [1, 1],
+ ]),
+ ),
+ ).toBe(DEFAULT_DOCK_TREE);
+ });
+});
+
+describe('moveDockPane', () => {
+ test('moves the terminal from under the editor to beside it, and back', () => {
+ const beside = moveDockPane(DEFAULT_DOCK_TREE, 'terminal', 'editor', 'end');
+ expect(shape(beside)).toEqual({ row: ['editor', 'terminal', 'agents'] });
+ expect(dockPaneDirection(beside, 'terminal')).toBe('row');
+ const under = moveDockPane(beside, 'terminal', 'editor', 'bottom', 0.3);
+ expect(shape(under)).toEqual({ row: [{ column: ['editor', 'terminal'] }, 'agents'] });
+ expect(dockPaneDirection(under, 'terminal')).toBe('column');
+ });
+
+ test('puts chat above the editor', () => {
+ const moved = moveDockPane(DEFAULT_DOCK_TREE, 'agents', 'editor', 'top');
+ expect(shape(moved)).toEqual({ column: ['agents', 'editor', 'terminal'] });
+ });
+
+ test('puts chat at the start of the terminal, in a row under the editor', () => {
+ const moved = moveDockPane(DEFAULT_DOCK_TREE, 'agents', 'terminal', 'start');
+ expect(shape(moved)).toEqual({ column: ['editor', { row: ['agents', 'terminal'] }] });
+ });
+
+ test('every move keeps all three panes, each once', () => {
+ const edges = ['start', 'end', 'top', 'bottom'] as const;
+ const panes: PaneId[] = ['editor', 'agents', 'terminal'];
+ for (const pane of panes) {
+ for (const target of panes) {
+ for (const edge of edges) {
+ const moved = moveDockPane(DEFAULT_DOCK_TREE, pane, target, edge);
+ expect(dockTreePanes(moved).toSorted()).toEqual(['agents', 'editor', 'terminal']);
+ expect(parseDockTree(JSON.parse(JSON.stringify(moved)))).not.toBeNull();
+ }
+ }
+ }
+ });
+
+ test('moving a pane onto itself changes nothing', () => {
+ expect(moveDockPane(DEFAULT_DOCK_TREE, 'editor', 'editor', 'end')).toBe(DEFAULT_DOCK_TREE);
+ });
+});
diff --git a/packages/app/src/lib/dock-tree.ts b/packages/app/src/lib/dock-tree.ts
new file mode 100644
index 000000000..b0154f6c3
--- /dev/null
+++ b/packages/app/src/lib/dock-tree.ts
@@ -0,0 +1,326 @@
+import { isPaneId, type PaneId } from './pane-visibility-store';
+
+export type DockDirection = 'row' | 'column';
+
+export type DockEdge = 'start' | 'end' | 'top' | 'bottom';
+
+export interface DockLeaf {
+ readonly pane: PaneId;
+}
+
+interface DockItem {
+ readonly size: number;
+ readonly node: DockNode;
+}
+
+export interface DockGroup {
+ readonly direction: DockDirection;
+ readonly items: readonly DockItem[];
+}
+
+export type DockNode = DockLeaf | DockGroup;
+
+export type DockPath = readonly number[];
+
+export interface VisibleDockLeaf {
+ readonly pane: PaneId;
+}
+
+interface VisibleDockItem {
+ readonly slot: number;
+ readonly share: number;
+ readonly node: VisibleDockNode;
+}
+
+export interface VisibleDockGroup {
+ readonly path: DockPath;
+ readonly direction: DockDirection;
+ readonly items: readonly VisibleDockItem[];
+}
+
+export type VisibleDockNode = VisibleDockLeaf | VisibleDockGroup;
+
+const DOCK_PANE_ORDER = { editor: true, terminal: true, agents: true } satisfies Record<
+ PaneId,
+ true
+>;
+
+export const DOCK_PANES = Object.keys(DOCK_PANE_ORDER) as readonly PaneId[];
+
+const MAX_DOCK_DEPTH = DOCK_PANES.length;
+
+export const DEFAULT_CHAT_SHARE = 1 / 3.5;
+export const DEFAULT_BOTTOM_TERMINAL_SHARE = 1 / 3.3;
+
+export function bottomTerminalDockTree(chatShare: number, terminalShare: number): DockGroup {
+ return {
+ direction: 'row',
+ items: [
+ {
+ size: 1 - chatShare,
+ node: {
+ direction: 'column',
+ items: [
+ { size: 1 - terminalShare, node: { pane: 'editor' } },
+ { size: terminalShare, node: { pane: 'terminal' } },
+ ],
+ },
+ },
+ { size: chatShare, node: { pane: 'agents' } },
+ ],
+ };
+}
+
+export const DEFAULT_DOCK_TREE: DockGroup = bottomTerminalDockTree(
+ DEFAULT_CHAT_SHARE,
+ DEFAULT_BOTTOM_TERMINAL_SHARE,
+);
+
+export function isDockLeaf(node: DockNode): node is DockLeaf {
+ return 'pane' in node;
+}
+
+export function isVisibleDockLeaf(node: VisibleDockNode): node is VisibleDockLeaf {
+ return 'pane' in node;
+}
+
+function dockEdgeDirection(edge: DockEdge): DockDirection {
+ return edge === 'start' || edge === 'end' ? 'row' : 'column';
+}
+
+function edgeLeads(edge: DockEdge): boolean {
+ return edge === 'start' || edge === 'top';
+}
+
+export function dockTreePanes(node: DockNode): PaneId[] {
+ if (isDockLeaf(node)) return [node.pane];
+ return node.items.flatMap((item) => dockTreePanes(item.node));
+}
+
+function parseDockNode(value: unknown, depth: number): DockNode | null {
+ if (typeof value !== 'object' || value === null || depth > MAX_DOCK_DEPTH) return null;
+ const record = value as Record<string, unknown>;
+ if ('pane' in record) return isPaneId(record.pane) ? { pane: record.pane } : null;
+ if (record.direction !== 'row' && record.direction !== 'column') return null;
+ if (!Array.isArray(record.items) || record.items.length < 2) return null;
+ const items: DockItem[] = [];
+ for (const raw of record.items) {
+ if (typeof raw !== 'object' || raw === null) return null;
+ const { size, node } = raw as Record<string, unknown>;
+ if (typeof size !== 'number' || !Number.isFinite(size) || size <= 0) return null;
+ const child = parseDockNode(node, depth + 1);
+ if (child === null) return null;
+ items.push({ size, node: child });
+ }
+ return { direction: record.direction, items };
+}
+
+function hasUsableSizes(node: DockNode): boolean {
+ return (
+ isDockLeaf(node) ||
+ node.items.every(
+ (item) => Number.isFinite(item.size) && item.size > 0 && hasUsableSizes(item.node),
+ )
+ );
+}
+
+export function parseDockTree(value: unknown): DockNode | null {
+ const node = parseDockNode(value, 0);
+ if (node === null) return null;
+ const panes = dockTreePanes(node);
+ if (panes.length !== DOCK_PANES.length || new Set(panes).size !== panes.length) return null;
+ const tree = normalizeDockTree(node);
+ return hasUsableSizes(tree) ? tree : null;
+}
+
+function normalizedItems(items: readonly DockItem[]): DockItem[] {
+ const total = items.reduce((sum, item) => sum + item.size, 0);
+ return items.map((item) => ({ size: item.size / total, node: item.node }));
+}
+
+export function normalizeDockTree(node: DockNode): DockNode {
+ if (isDockLeaf(node)) return node;
+ const items: DockItem[] = [];
+ for (const item of node.items) {
+ const child = normalizeDockTree(item.node);
+ if (!isDockLeaf(child) && child.direction === node.direction) {
+ for (const nested of child.items) {
+ items.push({ size: item.size * nested.size, node: nested.node });
+ }
+ } else {
+ items.push({ size: item.size, node: child });
+ }
+ }
+ const only = items[0];
+ if (items.length === 1 && only !== undefined) return only.node;
+ return { direction: node.direction, items: normalizedItems(items) };
+}
+
+function visibleDockNode(
+ node: DockNode,
+ path: DockPath,
+ isVisible: (pane: PaneId) => boolean,
+): VisibleDockNode | null {
+ if (isDockLeaf(node)) return isVisible(node.pane) ? { pane: node.pane } : null;
+ const kept: { slot: number; size: number; node: VisibleDockNode }[] = [];
+ node.items.forEach((item, slot) => {
+ const child = visibleDockNode(item.node, [...path, slot], isVisible);
+ if (child !== null) kept.push({ slot, size: item.size, node: child });
+ });
+ const only = kept[0];
+ if (kept.length === 1 && only !== undefined) return only.node;
+ if (kept.length === 0) return null;
+ const total = kept.reduce((sum, item) => sum + item.size, 0);
+ return {
+ path,
+ direction: node.direction,
+ items: kept.map((item) => ({ slot: item.slot, share: item.size / total, node: item.node })),
+ };
+}
+
+export function visibleDockTree(
+ tree: DockNode,
+ isVisible: (pane: PaneId) => boolean,
+): VisibleDockNode | null {
+ return visibleDockNode(tree, [], isVisible);
+}
+
+function groupAt(tree: DockNode, path: DockPath): DockGroup | null {
+ let node = tree;
+ for (const slot of path) {
+ if (isDockLeaf(node)) return null;
+ const item = node.items[slot];
+ if (item === undefined) return null;
+ node = item.node;
+ }
+ return isDockLeaf(node) ? null : node;
+}
+
+function replaceAt(tree: DockNode, path: DockPath, next: DockNode): DockNode {
+ const [slot, ...rest] = path;
+ if (slot === undefined) return next;
+ if (isDockLeaf(tree)) return tree;
+ return {
+ direction: tree.direction,
+ items: tree.items.map((item, index) =>
+ index === slot ? { size: item.size, node: replaceAt(item.node, rest, next) } : item,
+ ),
+ };
+}
+
+export function resizeDockGroup(
+ tree: DockNode,
+ path: DockPath,
+ shares: ReadonlyMap<number, number>,
+): DockNode {
+ const group = groupAt(tree, path);
+ if (group === null) return tree;
+ let visibleTotal = 0;
+ let shareTotal = 0;
+ for (const [slot, share] of shares) {
+ const item = group.items[slot];
+ if (item === undefined || !Number.isFinite(share) || share <= 0) return tree;
+ visibleTotal += item.size;
+ shareTotal += share;
+ }
+ if (visibleTotal <= 0 || shareTotal <= 0) return tree;
+ const items = group.items.map((item, slot) => {
+ const share = shares.get(slot);
+ return share === undefined
+ ? item
+ : { size: (share / shareTotal) * visibleTotal, node: item.node };
+ });
+ return replaceAt(tree, path, { direction: group.direction, items: normalizedItems(items) });
+}
+
+function heirIndex(index: number): number {
+ return index > 0 ? index - 1 : index + 1;
+}
+
+function withoutPane(node: DockNode, pane: PaneId): DockNode | null {
+ if (isDockLeaf(node)) return node.pane === pane ? null : node;
+ const kept = node.items.map((item) => ({ size: item.size, node: withoutPane(item.node, pane) }));
+ const removed = kept.findIndex((item) => item.node === null);
+ const heir = kept[heirIndex(removed)];
+ const gone = kept[removed];
+ if (heir !== undefined && gone !== undefined) heir.size += gone.size;
+ const items = kept.flatMap((item) =>
+ item.node === null ? [] : [{ size: item.size, node: item.node }],
+ );
+ const only = items[0];
+ if (items.length === 1 && only !== undefined) return only.node;
+ if (items.length === 0) return null;
+ return { direction: node.direction, items };
+}
+
+export function dockPaneHeirShare(tree: DockNode, pane: PaneId): number | null {
+ if (isDockLeaf(tree)) return null;
+ const index = tree.items.findIndex((item) => isDockLeaf(item.node) && item.node.pane === pane);
+ const item = tree.items[index];
+ const heir = tree.items[heirIndex(index)];
+ if (item !== undefined && heir !== undefined) return item.size / (item.size + heir.size);
+ for (const child of tree.items) {
+ const share = dockPaneHeirShare(child.node, pane);
+ if (share !== null) return share;
+ }
+ return null;
+}
+
+function withPaneBeside(
+ node: DockNode,
+ target: PaneId,
+ pane: PaneId,
+ edge: DockEdge,
+ share: number,
+): DockNode {
+ const direction = dockEdgeDirection(edge);
+ if (isDockLeaf(node)) {
+ if (node.pane !== target) return node;
+ const inserted: DockItem = { size: share, node: { pane } };
+ const kept: DockItem = { size: 1 - share, node };
+ return { direction, items: edgeLeads(edge) ? [inserted, kept] : [kept, inserted] };
+ }
+ const index = node.items.findIndex((item) => isDockLeaf(item.node) && item.node.pane === target);
+ const item = node.items[index];
+ if (item !== undefined && node.direction === direction) {
+ const kept: DockItem = { size: item.size * (1 - share), node: item.node };
+ const placed: DockItem = { size: item.size * share, node: { pane } };
+ const items = [...node.items];
+ items.splice(index, 1, ...(edgeLeads(edge) ? [placed, kept] : [kept, placed]));
+ return { direction: node.direction, items };
+ }
+ return {
+ direction: node.direction,
+ items: node.items.map((child) => ({
+ size: child.size,
+ node: withPaneBeside(child.node, target, pane, edge, share),
+ })),
+ };
+}
+
+function clampDockShare(share: number): number {
+ return Math.min(Math.max(share, 0.05), 0.95);
+}
+
+export function moveDockPane(
+ tree: DockNode,
+ pane: PaneId,
+ target: PaneId,
+ edge: DockEdge,
+ share = 0.5,
+): DockNode {
+ if (pane === target) return tree;
+ const rest = withoutPane(tree, pane);
+ if (rest === null || !dockTreePanes(rest).includes(target)) return tree;
+ return normalizeDockTree(withPaneBeside(rest, target, pane, edge, clampDockShare(share)));
+}
+
+export function dockPaneDirection(tree: DockNode, pane: PaneId): DockDirection | null {
+ if (isDockLeaf(tree)) return null;
+ for (const item of tree.items) {
+ if (isDockLeaf(item.node) && item.node.pane === pane) return tree.direction;
+ const nested = dockPaneDirection(item.node, pane);
+ if (nested !== null) return nested;
+ }
+ return null;
+}
diff --git a/packages/app/src/lib/terminal-height-store.test.ts b/packages/app/src/lib/terminal-height-store.test.ts
index 38f108716..65c7cfa86 100644
--- a/packages/app/src/lib/terminal-height-store.test.ts
+++ b/packages/app/src/lib/terminal-height-store.test.ts
@@ -1,12 +1,8 @@
import { describe, expect, test } from 'vitest';
import {
- clampTerminalHeight,
- DEFAULT_TERMINAL_HEIGHT,
type HeightStorage,
- MIN_TERMINAL_HEIGHT,
readTerminalHeight,
TERMINAL_HEIGHT_KEY,
- writeTerminalHeight,
} from './terminal-height-store.ts';
function memoryStorage(initial: Record<string, string> = {}): HeightStorage {
@@ -15,22 +11,14 @@ function memoryStorage(initial: Record<string, string> = {}): HeightStorage {
getItem(key) {
return data.get(key) ?? null;
},
- setItem(key, value) {
- data.set(key, value);
- },
};
}
const TALL = 1000;
-const TALL_DEFAULT = 333;
describe('readTerminalHeight', () => {
- test('absent key returns the ~1/3-viewport default (1000 → 333)', () => {
- expect(readTerminalHeight(memoryStorage(), TALL)).toBe(TALL_DEFAULT);
- });
-
- test('default below the floor on a short viewport clamps up to MIN (300 → 100 → 120)', () => {
- expect(readTerminalHeight(memoryStorage(), 300)).toBe(MIN_TERMINAL_HEIGHT);
+ test('an absent key reads as no stored height', () => {
+ expect(readTerminalHeight(memoryStorage(), TALL)).toBeNull();
});
test('valid stored height is returned', () => {
@@ -40,7 +28,7 @@ describe('readTerminalHeight', () => {
test('height below floor is clamped to MIN', () => {
const s = memoryStorage({ [TERMINAL_HEIGHT_KEY]: '80' });
- expect(readTerminalHeight(s, TALL)).toBe(MIN_TERMINAL_HEIGHT);
+ expect(readTerminalHeight(s, TALL)).toBe(120);
});
test('height above the 50vh ceiling is clamped to half the viewport', () => {
@@ -54,84 +42,18 @@ describe('readTerminalHeight', () => {
expect(readTerminalHeight(s, 600)).toBe(300);
});
- test('non-numeric value falls back to default', () => {
+ test('a non-numeric value reads as no stored height', () => {
const s = memoryStorage({ [TERMINAL_HEIGHT_KEY]: 'not a number' });
- expect(readTerminalHeight(s, TALL)).toBe(TALL_DEFAULT);
+ expect(readTerminalHeight(s, TALL)).toBeNull();
});
- test('empty string falls back to default', () => {
+ test('an empty string reads as no stored height', () => {
const s = memoryStorage({ [TERMINAL_HEIGHT_KEY]: '' });
- expect(readTerminalHeight(s, TALL)).toBe(TALL_DEFAULT);
+ expect(readTerminalHeight(s, TALL)).toBeNull();
});
test('floating-point value is rounded', () => {
const s = memoryStorage({ [TERMINAL_HEIGHT_KEY]: '240.6' });
expect(readTerminalHeight(s, TALL)).toBe(240);
});
-
- test('throwing storage falls back to the fixed pixel default', () => {
- const throwing: HeightStorage = {
- getItem() {
- throw new Error('SecurityError');
- },
- setItem() {},
- };
- expect(readTerminalHeight(throwing, TALL)).toBe(DEFAULT_TERMINAL_HEIGHT);
- });
-});
-
-describe('writeTerminalHeight', () => {
- test('writes a clamped integer to storage', () => {
- const s = memoryStorage();
- writeTerminalHeight(300, s, TALL);
- expect(s.getItem(TERMINAL_HEIGHT_KEY)).toBe('300');
- });
-
- test('clamps to MIN on write below floor', () => {
- const s = memoryStorage();
- writeTerminalHeight(80, s, TALL);
- expect(s.getItem(TERMINAL_HEIGHT_KEY)).toBe(String(MIN_TERMINAL_HEIGHT));
- });
-
- test('clamps to the 50vh ceiling on write above it', () => {
- const s = memoryStorage();
- writeTerminalHeight(9999, s, 600);
- expect(s.getItem(TERMINAL_HEIGHT_KEY)).toBe('300');
- });
-
- test('rounds floating-point input before write', () => {
- const s = memoryStorage();
- writeTerminalHeight(240.7, s, TALL);
- expect(s.getItem(TERMINAL_HEIGHT_KEY)).toBe('241');
- });
-
- test('quota-exceeded throw is swallowed (in-memory only)', () => {
- const throwing: HeightStorage = {
- getItem() {
- return null;
- },
- setItem() {
- throw new Error('QuotaExceededError');
- },
- };
- expect(() => writeTerminalHeight(240, throwing, TALL)).not.toThrow();
- });
-});
-
-describe('clampTerminalHeight', () => {
- test('caps a height carried over from a taller viewport', () => {
- expect(clampTerminalHeight(588, 1000)).toBe(500);
- });
-
- test('leaves a height that already fits', () => {
- expect(clampTerminalHeight(240, TALL)).toBe(240);
- });
-
- test('raises a height below the floor', () => {
- expect(clampTerminalHeight(10, TALL)).toBe(MIN_TERMINAL_HEIGHT);
- });
-
- test('keeps the floor reachable on a viewport too short for it', () => {
- expect(clampTerminalHeight(400, 100)).toBe(MIN_TERMINAL_HEIGHT);
- });
});
diff --git a/packages/app/src/lib/terminal-height-store.ts b/packages/app/src/lib/terminal-height-store.ts
index c7de321d7..e1aeea1e0 100644
--- a/packages/app/src/lib/terminal-height-store.ts
+++ b/packages/app/src/lib/terminal-height-store.ts
@@ -1,13 +1,10 @@
export const TERMINAL_HEIGHT_KEY = 'ok-terminal-height-v1';
-export const DEFAULT_TERMINAL_HEIGHT = 240;
-export const MIN_TERMINAL_HEIGHT = 120;
-const DEFAULT_TERMINAL_HEIGHT_FRACTION = 1 / 3;
+const MIN_TERMINAL_HEIGHT = 120;
const MAX_TERMINAL_HEIGHT_FRACTION = 0.5;
export interface HeightStorage {
getItem(key: string): string | null;
- setItem(key: string, value: string): void;
}
function maxHeight(viewportHeight: number): number {
@@ -15,60 +12,10 @@ function maxHeight(viewportHeight: number): number {
return Math.max(MIN_TERMINAL_HEIGHT, Math.round(vh * MAX_TERMINAL_HEIGHT_FRACTION));
}
-function defaultHeight(viewportHeight: number): number {
- const vh = Number.isFinite(viewportHeight) ? viewportHeight : 0;
- if (vh <= 0) return DEFAULT_TERMINAL_HEIGHT;
- return Math.round(vh * DEFAULT_TERMINAL_HEIGHT_FRACTION);
-}
-
-function clamp(px: number, viewportHeight: number): number {
- const max = maxHeight(viewportHeight);
- if (!Number.isFinite(px)) return Math.min(defaultHeight(viewportHeight), max);
- if (px < MIN_TERMINAL_HEIGHT) return MIN_TERMINAL_HEIGHT;
- if (px > max) return max;
- return Math.round(px);
-}
-
-function currentViewportHeight(): number {
- if (typeof window === 'undefined') return 0;
- return window.innerHeight;
-}
-
-export function clampTerminalHeight(px: number, viewportHeight?: number): number {
- return clamp(px, viewportHeight ?? currentViewportHeight());
-}
-
-export function readTerminalHeight(storage?: HeightStorage, viewportHeight?: number): number {
- try {
- const s = storage ?? localStorage;
- const vh = viewportHeight ?? currentViewportHeight();
- const raw = s.getItem(TERMINAL_HEIGHT_KEY);
- if (raw == null) return clamp(defaultHeight(vh), vh);
- const parsed = Number.parseInt(raw, 10);
- if (!Number.isFinite(parsed)) return clamp(defaultHeight(vh), vh);
- return clamp(parsed, vh);
- } catch {
- return DEFAULT_TERMINAL_HEIGHT;
- }
-}
-
-export function writeTerminalHeight(
- px: number,
- storage?: HeightStorage,
- viewportHeight?: number,
-): void {
- try {
- const s = storage ?? localStorage;
- const vh = viewportHeight ?? currentViewportHeight();
- s.setItem(TERMINAL_HEIGHT_KEY, String(clamp(px, vh)));
- } catch {}
-}
-
-export function getInitialTerminalHeight(): number {
- try {
- if (typeof localStorage === 'undefined') return DEFAULT_TERMINAL_HEIGHT;
- return readTerminalHeight();
- } catch {
- return DEFAULT_TERMINAL_HEIGHT;
- }
+export function readTerminalHeight(storage: HeightStorage, viewportHeight: number): number | null {
+ const raw = storage.getItem(TERMINAL_HEIGHT_KEY);
+ if (raw === null) return null;
+ const parsed = Number.parseInt(raw, 10);
+ if (!Number.isFinite(parsed)) return null;
+ return Math.min(Math.max(parsed, MIN_TERMINAL_HEIGHT), maxHeight(viewportHeight));
}
diff --git a/packages/app/src/lib/terminal-placement-store.test.ts b/packages/app/src/lib/terminal-placement-store.test.ts
index cbd2c40f4..89a2551a7 100644
--- a/packages/app/src/lib/terminal-placement-store.test.ts
+++ b/packages/app/src/lib/terminal-placement-store.test.ts
@@ -1,10 +1,9 @@
+import { DEFAULT_TERMINAL_PLACEMENT } from '@inkeep/open-knowledge-core/terminal-layout';
import { describe, expect, test } from 'vitest';
import {
- DEFAULT_TERMINAL_PLACEMENT,
readTerminalPlacement,
TERMINAL_PLACEMENT_KEY,
type TerminalPlacementStorage,
- writeTerminalPlacement,
} from './terminal-placement-store.ts';
function memoryStorage(initial: Record<string, string> = {}): TerminalPlacementStorage {
@@ -13,9 +12,6 @@ function memoryStorage(initial: Record<string, string> = {}): TerminalPlacementS
getItem(key) {
return data.get(key) ?? null;
},
- setItem(key, value) {
- data.set(key, value);
- },
};
}
@@ -25,10 +21,8 @@ describe('terminal placement persistence', () => {
expect(DEFAULT_TERMINAL_PLACEMENT).toBe('bottom');
});
- test.each(['right', 'bottom'] as const)('round-trips the %s home', (placement) => {
- const storage = memoryStorage();
- writeTerminalPlacement(placement, storage);
- expect(storage.getItem(TERMINAL_PLACEMENT_KEY)).toBe(placement);
+ test.each(['right', 'bottom'] as const)('reads the stored %s home', (placement) => {
+ const storage = memoryStorage({ [TERMINAL_PLACEMENT_KEY]: placement });
expect(readTerminalPlacement(storage)).toBe(placement);
});
diff --git a/packages/app/src/lib/terminal-placement-store.ts b/packages/app/src/lib/terminal-placement-store.ts
index d536d6d12..d3fe88c1f 100644
--- a/packages/app/src/lib/terminal-placement-store.ts
+++ b/packages/app/src/lib/terminal-placement-store.ts
@@ -1,34 +1,16 @@
import {
- DEFAULT_TERMINAL_PLACEMENT,
normalizeTerminalPlacement,
type TerminalPlacement,
} from '@inkeep/open-knowledge-core/terminal-layout';
export type { TerminalPlacement } from '@inkeep/open-knowledge-core/terminal-layout';
-export { DEFAULT_TERMINAL_PLACEMENT } from '@inkeep/open-knowledge-core/terminal-layout';
export const TERMINAL_PLACEMENT_KEY = 'ok-terminal-placement-v1';
export interface TerminalPlacementStorage {
getItem(key: string): string | null;
- setItem(key: string, value: string): void;
}
-export function readTerminalPlacement(storage?: TerminalPlacementStorage): TerminalPlacement {
- try {
- const target = storage ?? localStorage;
- return normalizeTerminalPlacement(target.getItem(TERMINAL_PLACEMENT_KEY));
- } catch {
- return DEFAULT_TERMINAL_PLACEMENT;
- }
-}
-
-export function writeTerminalPlacement(
- placement: TerminalPlacement,
- storage?: TerminalPlacementStorage,
-): void {
- try {
- const target = storage ?? localStorage;
- target.setItem(TERMINAL_PLACEMENT_KEY, placement);
- } catch {}
+export function readTerminalPlacement(storage: TerminalPlacementStorage): TerminalPlacement {
+ return normalizeTerminalPlacement(storage.getItem(TERMINAL_PLACEMENT_KEY));
}
diff --git a/packages/app/src/lib/terminal-right-width-store.test.ts b/packages/app/src/lib/terminal-right-width-store.test.ts
index b3b93f77a..eb97446a8 100644
--- a/packages/app/src/lib/terminal-right-width-store.test.ts
+++ b/packages/app/src/lib/terminal-right-width-store.test.ts
@@ -1,11 +1,12 @@
-import { describe, expect, test } from 'vitest';
import {
MIN_TERMINAL_RIGHT_WIDTH,
PREFERRED_TERMINAL_RIGHT_WIDTH,
+} from '@inkeep/open-knowledge-core/terminal-layout';
+import { describe, expect, test } from 'vitest';
+import {
readTerminalRightWidth,
TERMINAL_RIGHT_WIDTH_KEY,
type TerminalRightWidthStorage,
- writeTerminalRightWidth,
} from './terminal-right-width-store.ts';
const LEGACY_AGENTS_WIDTH_KEY = 'ok-terminal-width-v1';
@@ -16,9 +17,6 @@ function memoryStorage(initial: Record<string, string> = {}): TerminalRightWidth
getItem(key) {
return data.get(key) ?? null;
},
- setItem(key, value) {
- data.set(key, value);
- },
};
}
@@ -30,14 +28,12 @@ describe('right-terminal width persistence', () => {
});
test('keeps a width the user dragged below the preferred width', () => {
- const storage = memoryStorage();
- writeTerminalRightWidth(400, storage);
+ const storage = memoryStorage({ [TERMINAL_RIGHT_WIDTH_KEY]: '400' });
expect(readTerminalRightWidth(storage)).toBe(400);
});
- test('round-trips a supported width', () => {
- const storage = memoryStorage();
- writeTerminalRightWidth(840, storage);
+ test('reads a supported width', () => {
+ const storage = memoryStorage({ [TERMINAL_RIGHT_WIDTH_KEY]: '840' });
expect(readTerminalRightWidth(storage)).toBe(840);
});
@@ -55,11 +51,4 @@ describe('right-terminal width persistence', () => {
const storage = memoryStorage({ [TERMINAL_RIGHT_WIDTH_KEY]: '2400' });
expect(readTerminalRightWidth(storage)).toBe(2400);
});
-
- test('writes only the fresh width key and leaves the agents-panel key untouched', () => {
- const storage = memoryStorage({ [LEGACY_AGENTS_WIDTH_KEY]: '875' });
- writeTerminalRightWidth(700, storage);
- expect(storage.getItem(TERMINAL_RIGHT_WIDTH_KEY)).toBe('700');
- expect(storage.getItem(LEGACY_AGENTS_WIDTH_KEY)).toBe('875');
- });
});
diff --git a/packages/app/src/lib/terminal-right-width-store.ts b/packages/app/src/lib/terminal-right-width-store.ts
index 29d9f9e01..44c50da4c 100644
--- a/packages/app/src/lib/terminal-right-width-store.ts
+++ b/packages/app/src/lib/terminal-right-width-store.ts
@@ -3,35 +3,14 @@ import {
PREFERRED_TERMINAL_RIGHT_WIDTH,
} from '@inkeep/open-knowledge-core/terminal-layout';
-export {
- MIN_TERMINAL_RIGHT_WIDTH,
- PREFERRED_TERMINAL_RIGHT_WIDTH,
-} from '@inkeep/open-knowledge-core/terminal-layout';
-
export const TERMINAL_RIGHT_WIDTH_KEY = 'ok-terminal-right-width-v1';
export interface TerminalRightWidthStorage {
getItem(key: string): string | null;
- setItem(key: string, value: string): void;
-}
-
-export function readTerminalRightWidth(storage?: TerminalRightWidthStorage): number {
- try {
- const target = storage ?? localStorage;
- const raw = target.getItem(TERMINAL_RIGHT_WIDTH_KEY);
- if (raw === null || raw.trim() === '') return PREFERRED_TERMINAL_RIGHT_WIDTH;
- const parsed = Number(raw);
- return Number.isFinite(parsed)
- ? normalizeTerminalRightWidth(parsed)
- : PREFERRED_TERMINAL_RIGHT_WIDTH;
- } catch {
- return PREFERRED_TERMINAL_RIGHT_WIDTH;
- }
}
-export function writeTerminalRightWidth(width: number, storage?: TerminalRightWidthStorage): void {
- try {
- const target = storage ?? localStorage;
- target.setItem(TERMINAL_RIGHT_WIDTH_KEY, String(normalizeTerminalRightWidth(width)));
- } catch {}
+export function readTerminalRightWidth(storage: TerminalRightWidthStorage): number {
+ const raw = storage.getItem(TERMINAL_RIGHT_WIDTH_KEY);
+ if (raw === null || raw.trim() === '') return PREFERRED_TERMINAL_RIGHT_WIDTH;
+ return normalizeTerminalRightWidth(Number(raw));
}
diff --git a/packages/app/src/locales/ar/messages.po b/packages/app/src/locales/ar/messages.po
index df42a8199..a9d8208c6 100644
--- a/packages/app/src/locales/ar/messages.po
+++ b/packages/app/src/locales/ar/messages.po
@@ -1354,9 +1354,6 @@ msgstr "وضع الوكيل"
msgid "Agent panel"
msgstr "لوحة الوكيل"
-msgid "Agent panel closed to keep Terminal readable."
-msgstr "أُغلقت لوحة الوكيل لإبقاء Terminal سهل القراءة."
-
msgid "Agent settings"
msgstr "إعدادات الوكيل"
@@ -8758,15 +8755,15 @@ msgstr "إعادة تعيين مرشحات العرض"
msgid "Resize {handleKey}"
msgstr "تغيير حجم {handleKey}"
+msgid "Resize {pane}"
+msgstr "تغيير حجم {pane}"
+
msgid "Resize document panel"
msgstr "تغيير حجم لوحة المستند"
msgid "Resize skills panel"
msgstr "تغيير حجم لوحة المهارات"
-msgid "Resize terminal"
-msgstr "تغيير حجم الطرفية"
-
msgid "Resolve conflict in your terminal"
msgstr "حل التعارض في طرفيتك"
@@ -10290,9 +10287,6 @@ msgstr "الطرفية {0}"
msgid "Terminal access isn't enabled for this project."
msgstr "الوصول إلى الطرفية غير مفعّل لهذا المشروع."
-msgid "Terminal closed to make room for the agent panel."
-msgstr "أُغلق Terminal لإفساح المجال للوحة الوكيل."
-
msgid "Terminal disabled"
msgstr "الطرفية معطّلة"
diff --git a/packages/app/src/locales/bn/messages.po b/packages/app/src/locales/bn/messages.po
index 053a4b19a..af00237d1 100644
--- a/packages/app/src/locales/bn/messages.po
+++ b/packages/app/src/locales/bn/messages.po
@@ -1350,9 +1350,6 @@ msgstr "এজেন্ট মোড"
msgid "Agent panel"
msgstr "এজেন্ট প্যানেল"
-msgid "Agent panel closed to keep Terminal readable."
-msgstr "Terminal পাঠযোগ্য রাখতে এজেন্ট প্যানেল বন্ধ করা হয়েছে।"
-
msgid "Agent settings"
msgstr "এজেন্ট সেটিং"
@@ -8754,15 +8751,15 @@ msgstr "দৃশ্যের ছাঁকনি রিসেট করুন"
msgid "Resize {handleKey}"
msgstr "{handleKey}-এর আকার বদলান"
+msgid "Resize {pane}"
+msgstr "{pane}-এর আকার বদলান"
+
msgid "Resize document panel"
msgstr "নথি প্যানেলের আকার পরিবর্তন করুন"
msgid "Resize skills panel"
msgstr "স্কিল প্যানেলের আকার পরিবর্তন করুন"
-msgid "Resize terminal"
-msgstr "টার্মিনালের আকার পরিবর্তন করুন"
-
msgid "Resolve conflict in your terminal"
msgstr "আপনার টার্মিনালে দ্বন্দ্ব মীমাংসা করুন"
@@ -10286,9 +10283,6 @@ msgstr "টার্মিনাল {0}"
msgid "Terminal access isn't enabled for this project."
msgstr "এই প্রকল্পের জন্য টার্মিনালে প্রবেশ চালু নেই।"
-msgid "Terminal closed to make room for the agent panel."
-msgstr "এজেন্ট প্যানেলের জন্য জায়গা করতে Terminal বন্ধ করা হয়েছে।"
-
msgid "Terminal disabled"
msgstr "টার্মিনাল নিষ্ক্রিয়"
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index 039980efd..6f2a29dc8 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -1354,9 +1354,6 @@ msgstr "Agent mode"
msgid "Agent panel"
msgstr "Agent panel"
-msgid "Agent panel closed to keep Terminal readable."
-msgstr "Agent panel closed to keep Terminal readable."
-
msgid "Agent settings"
msgstr "Agent settings"
@@ -8758,15 +8755,15 @@ msgstr "Reset view filters"
msgid "Resize {handleKey}"
msgstr "Resize {handleKey}"
+msgid "Resize {pane}"
+msgstr "Resize {pane}"
+
msgid "Resize document panel"
msgstr "Resize document panel"
msgid "Resize skills panel"
msgstr "Resize skills panel"
-msgid "Resize terminal"
-msgstr "Resize terminal"
-
msgid "Resolve conflict in your terminal"
msgstr "Resolve conflict in your terminal"
@@ -10290,9 +10287,6 @@ msgstr "Terminal {0}"
msgid "Terminal access isn't enabled for this project."
msgstr "Terminal access isn't enabled for this project."
-msgid "Terminal closed to make room for the agent panel."
-msgstr "Terminal closed to make room for the agent panel."
-
msgid "Terminal disabled"
msgstr "Terminal disabled"
diff --git a/packages/app/src/locales/es/messages.po b/packages/app/src/locales/es/messages.po
index 618c51c65..04145a678 100644
--- a/packages/app/src/locales/es/messages.po
+++ b/packages/app/src/locales/es/messages.po
@@ -1354,9 +1354,6 @@ msgstr "Modo agente"
msgid "Agent panel"
msgstr "Panel de agentes"
-msgid "Agent panel closed to keep Terminal readable."
-msgstr "Se cerró el panel de agentes para mantener Terminal legible."
-
msgid "Agent settings"
msgstr "Ajustes del agente"
@@ -8758,15 +8755,15 @@ msgstr "Restablecer los filtros de vista"
msgid "Resize {handleKey}"
msgstr "Redimensionar {handleKey}"
+msgid "Resize {pane}"
+msgstr "Redimensionar {pane}"
+
msgid "Resize document panel"
msgstr "Redimensionar el panel del documento"
msgid "Resize skills panel"
msgstr "Redimensionar el panel de Habilidades"
-msgid "Resize terminal"
-msgstr "Redimensionar la terminal"
-
msgid "Resolve conflict in your terminal"
msgstr "Resuelve el conflicto en tu terminal"
@@ -10290,9 +10287,6 @@ msgstr "Terminal {0}"
msgid "Terminal access isn't enabled for this project."
msgstr "El acceso a la terminal no está activado en este proyecto."
-msgid "Terminal closed to make room for the agent panel."
-msgstr "Se cerró Terminal para dejar espacio al panel de agentes."
-
msgid "Terminal disabled"
msgstr "Terminal desactivada"
diff --git a/packages/app/src/locales/fr/messages.po b/packages/app/src/locales/fr/messages.po
index 0a8673fff..f7295b89a 100644
--- a/packages/app/src/locales/fr/messages.po
+++ b/packages/app/src/locales/fr/messages.po
@@ -1354,9 +1354,6 @@ msgstr "Mode agent"
msgid "Agent panel"
msgstr "Panneau des agents"
-msgid "Agent panel closed to keep Terminal readable."
-msgstr "Le panneau des agents a été fermé pour que Terminal reste lisible."
-
msgid "Agent settings"
msgstr "Paramètres de l'agent"
@@ -8758,15 +8755,15 @@ msgstr "Réinitialiser les filtres d'affichage"
msgid "Resize {handleKey}"
msgstr "Redimensionner {handleKey}"
+msgid "Resize {pane}"
+msgstr "Redimensionner {pane}"
+
msgid "Resize document panel"
msgstr "Redimensionner le panneau du document"
msgid "Resize skills panel"
msgstr "Redimensionner le panneau Compétences"
-msgid "Resize terminal"
-msgstr "Redimensionner le terminal"
-
msgid "Resolve conflict in your terminal"
msgstr "Résoudre le conflit dans votre terminal"
@@ -10290,9 +10287,6 @@ msgstr "Terminal {0}"
msgid "Terminal access isn't enabled for this project."
msgstr "L'accès au terminal n'est pas activé pour ce projet."
-msgid "Terminal closed to make room for the agent panel."
-msgstr "Terminal a été fermé pour faire de la place au panneau des agents."
-
msgid "Terminal disabled"
msgstr "Terminal désactivé"
diff --git a/packages/app/src/locales/hi/messages.po b/packages/app/src/locales/hi/messages.po
index 9927fc0fe..32d31ebea 100644
--- a/packages/app/src/locales/hi/messages.po
+++ b/packages/app/src/locales/hi/messages.po
@@ -1350,9 +1350,6 @@ msgstr "एजेंट मोड"
msgid "Agent panel"
msgstr "एजेंट पैनल"
-msgid "Agent panel closed to keep Terminal readable."
-msgstr "Terminal को पढ़ने योग्य बनाए रखने के लिए एजेंट पैनल बंद कर दिया गया।"
-
msgid "Agent settings"
msgstr "एजेंट सेटिंग"
@@ -8754,15 +8751,15 @@ msgstr "दृश्य फ़िल्टर रीसेट करें"
msgid "Resize {handleKey}"
msgstr "{handleKey} का आकार बदलें"
+msgid "Resize {pane}"
+msgstr "{pane} का आकार बदलें"
+
msgid "Resize document panel"
msgstr "दस्तावेज़ पैनल का आकार बदलें"
msgid "Resize skills panel"
msgstr "स्किल पैनल का आकार बदलें"
-msgid "Resize terminal"
-msgstr "टर्मिनल का आकार बदलें"
-
msgid "Resolve conflict in your terminal"
msgstr "अपने टर्मिनल में टकराव सुलझाएँ"
@@ -10286,9 +10283,6 @@ msgstr "टर्मिनल {0}"
msgid "Terminal access isn't enabled for this project."
msgstr "इस प्रोजेक्ट के लिए टर्मिनल पहुँच सक्षम नहीं है।"
-msgid "Terminal closed to make room for the agent panel."
-msgstr "एजेंट पैनल के लिए जगह बनाने हेतु Terminal बंद कर दिया गया।"
-
msgid "Terminal disabled"
msgstr "टर्मिनल अक्षम"
diff --git a/packages/app/src/locales/id/messages.po b/packages/app/src/locales/id/messages.po
index e3fc4c813..18b77e7f5 100644
--- a/packages/app/src/locales/id/messages.po
+++ b/packages/app/src/locales/id/messages.po
@@ -1350,9 +1350,6 @@ msgstr "Mode agen"
msgid "Agent panel"
msgstr "Panel agen"
-msgid "Agent panel closed to keep Terminal readable."
-msgstr "Panel agen ditutup agar Terminal tetap mudah dibaca."
-
msgid "Agent settings"
msgstr "Pengaturan agen"
@@ -8754,15 +8751,15 @@ msgstr "Setel ulang filter tampilan"
msgid "Resize {handleKey}"
msgstr "Ubah ukuran {handleKey}"
+msgid "Resize {pane}"
+msgstr "Ubah ukuran {pane}"
+
msgid "Resize document panel"
msgstr "Ubah ukuran panel dokumen"
msgid "Resize skills panel"
msgstr "Ubah ukuran panel Keterampilan"
-msgid "Resize terminal"
-msgstr "Ubah ukuran terminal"
-
msgid "Resolve conflict in your terminal"
msgstr "Selesaikan konfliknya di terminal Anda"
@@ -10286,9 +10283,6 @@ msgstr "Terminal {0}"
msgid "Terminal access isn't enabled for this project."
msgstr "Akses terminal belum diaktifkan untuk proyek ini."
-msgid "Terminal closed to make room for the agent panel."
-msgstr "Terminal ditutup untuk memberi ruang bagi panel agen."
-
msgid "Terminal disabled"
msgstr "Terminal dinonaktifkan"
diff --git a/packages/app/src/locales/ko/messages.po b/packages/app/src/locales/ko/messages.po
index 7b4d2ad22..4fc8ecd0d 100644
--- a/packages/app/src/locales/ko/messages.po
+++ b/packages/app/src/locales/ko/messages.po
@@ -1354,9 +1354,6 @@ msgstr "에이전트 모드"
msgid "Agent panel"
msgstr "에이전트 패널"
-msgid "Agent panel closed to keep Terminal readable."
-msgstr "Terminal을 읽기 쉽게 에이전트 패널을 닫았습니다."
-
msgid "Agent settings"
msgstr "에이전트 설정"
@@ -8758,15 +8755,15 @@ msgstr "보기 필터 초기화"
msgid "Resize {handleKey}"
msgstr "{handleKey} 크기 조정"
+msgid "Resize {pane}"
+msgstr "{pane} 크기 조정"
+
msgid "Resize document panel"
msgstr "문서 패널 크기 조절"
msgid "Resize skills panel"
msgstr "스킬 패널 크기 조절"
-msgid "Resize terminal"
-msgstr "터미널 크기 조절"
-
msgid "Resolve conflict in your terminal"
msgstr "터미널에서 충돌 해결"
@@ -10290,9 +10287,6 @@ msgstr "터미널 {0}"
msgid "Terminal access isn't enabled for this project."
msgstr "이 프로젝트의 터미널 접근 비활성화 상태."
-msgid "Terminal closed to make room for the agent panel."
-msgstr "에이전트 패널을 위한 공간을 만들려고 Terminal을 닫았습니다."
-
msgid "Terminal disabled"
msgstr "터미널 비활성화됨"
diff --git a/packages/app/src/locales/pl/messages.po b/packages/app/src/locales/pl/messages.po
index 46e00a540..82aeedf88 100644
--- a/packages/app/src/locales/pl/messages.po
+++ b/packages/app/src/locales/pl/messages.po
@@ -1354,9 +1354,6 @@ msgstr "Tryb agenta"
msgid "Agent panel"
msgstr "Panel agentów"
-msgid "Agent panel closed to keep Terminal readable."
-msgstr "Panel agenta został zamknięty, żeby Terminal pozostał czytelny."
-
msgid "Agent settings"
msgstr "Ustawienia agenta"
@@ -8758,15 +8755,15 @@ msgstr "Zresetuj filtry widoku"
msgid "Resize {handleKey}"
msgstr "Zmień rozmiar {handleKey}"
+msgid "Resize {pane}"
+msgstr "Zmień rozmiar: {pane}"
+
msgid "Resize document panel"
msgstr "Zmień rozmiar panelu dokumentu"
msgid "Resize skills panel"
msgstr "Zmień rozmiar panelu umiejętności"
-msgid "Resize terminal"
-msgstr "Zmień rozmiar terminala"
-
msgid "Resolve conflict in your terminal"
msgstr "Rozwiąż konflikt w terminalu"
@@ -10290,9 +10287,6 @@ msgstr "Terminal {0}"
msgid "Terminal access isn't enabled for this project."
msgstr "Dostęp do terminala nie jest włączony dla tego projektu."
-msgid "Terminal closed to make room for the agent panel."
-msgstr "Terminal zamknięty, aby zwolnić miejsce dla panelu agenta."
-
msgid "Terminal disabled"
msgstr "Terminal wyłączony"
diff --git a/packages/app/src/locales/pt-BR/messages.po b/packages/app/src/locales/pt-BR/messages.po
index 0387182e2..c36bf8938 100644
--- a/packages/app/src/locales/pt-BR/messages.po
+++ b/packages/app/src/locales/pt-BR/messages.po
@@ -1350,9 +1350,6 @@ msgstr "Modo agente"
msgid "Agent panel"
msgstr "Painel de agentes"
-msgid "Agent panel closed to keep Terminal readable."
-msgstr "O painel de agentes foi fechado para manter o Terminal legível."
-
msgid "Agent settings"
msgstr "Configurações do agente"
@@ -8754,15 +8751,15 @@ msgstr "Redefinir os filtros de visualização"
msgid "Resize {handleKey}"
msgstr "Redimensionar {handleKey}"
+msgid "Resize {pane}"
+msgstr "Redimensionar {pane}"
+
msgid "Resize document panel"
msgstr "Redimensionar o painel do documento"
msgid "Resize skills panel"
msgstr "Redimensionar o painel de Habilidades"
-msgid "Resize terminal"
-msgstr "Redimensionar o terminal"
-
msgid "Resolve conflict in your terminal"
msgstr "Resolva o conflito no seu terminal"
@@ -10286,9 +10283,6 @@ msgstr "Terminal {0}"
msgid "Terminal access isn't enabled for this project."
msgstr "O acesso ao terminal não está ativado neste projeto."
-msgid "Terminal closed to make room for the agent panel."
-msgstr "O Terminal foi fechado para abrir espaço para o painel de agentes."
-
msgid "Terminal disabled"
msgstr "Terminal desativado"
diff --git a/packages/app/src/locales/ur/messages.po b/packages/app/src/locales/ur/messages.po
index 6ee4e9c89..6a0c4b8e8 100644
--- a/packages/app/src/locales/ur/messages.po
+++ b/packages/app/src/locales/ur/messages.po
@@ -1354,9 +1354,6 @@ msgstr "ایجنٹ موڈ"
msgid "Agent panel"
msgstr "ایجنٹ پینل"
-msgid "Agent panel closed to keep Terminal readable."
-msgstr "Terminal کو پڑھنے کے قابل رکھنے کے لیے ایجنٹ پینل بند کر دیا گیا۔"
-
msgid "Agent settings"
msgstr "ایجنٹ کی ترتیبات"
@@ -8758,15 +8755,15 @@ msgstr "منظر کے فلٹرز دوبارہ ترتیب دیں"
msgid "Resize {handleKey}"
msgstr "{handleKey} کا حجم بدلیں"
+msgid "Resize {pane}"
+msgstr "{pane} کا حجم بدلیں"
+
msgid "Resize document panel"
msgstr "دستاویز کے پینل کا سائز تبدیل کریں"
msgid "Resize skills panel"
msgstr "مہارتوں کے پینل کا سائز تبدیل کریں"
-msgid "Resize terminal"
-msgstr "ٹرمینل کا سائز تبدیل کریں"
-
msgid "Resolve conflict in your terminal"
msgstr "اپنے ٹرمینل میں تصادم حل کریں"
@@ -10290,9 +10287,6 @@ msgstr "ٹرمینل {0}"
msgid "Terminal access isn't enabled for this project."
msgstr "اس پروجیکٹ کے لیے ٹرمینل کی رسائی فعال نہیں۔"
-msgid "Terminal closed to make room for the agent panel."
-msgstr "ایجنٹ پینل کے لیے جگہ بنانے کی خاطر Terminal بند کر دیا گیا۔"
-
msgid "Terminal disabled"
msgstr "ٹرمینل بند"
diff --git a/packages/app/src/locales/zh-Hans/messages.po b/packages/app/src/locales/zh-Hans/messages.po
index 619192502..f99316a9e 100644
--- a/packages/app/src/locales/zh-Hans/messages.po
+++ b/packages/app/src/locales/zh-Hans/messages.po
@@ -1354,9 +1354,6 @@ msgstr "智能体模式"
msgid "Agent panel"
msgstr "智能体面板"
-msgid "Agent panel closed to keep Terminal readable."
-msgstr "为保持 Terminal 清晰可读,已关闭智能体面板。"
-
msgid "Agent settings"
msgstr "智能体设置"
@@ -8758,15 +8755,15 @@ msgstr "重置视图筛选条件"
msgid "Resize {handleKey}"
msgstr "调整 {handleKey} 的大小"
+msgid "Resize {pane}"
+msgstr "调整 {pane} 的大小"
+
msgid "Resize document panel"
msgstr "调整文档面板大小"
msgid "Resize skills panel"
msgstr "调整「技能」面板大小"
-msgid "Resize terminal"
-msgstr "调整终端大小"
-
msgid "Resolve conflict in your terminal"
msgstr "在你的终端中解决冲突"
@@ -10290,9 +10287,6 @@ msgstr "终端 {0}"
msgid "Terminal access isn't enabled for this project."
msgstr "这个项目没有启用终端访问。"
-msgid "Terminal closed to make room for the agent panel."
-msgstr "已关闭 Terminal,为智能体面板腾出空间。"
-
msgid "Terminal disabled"
msgstr "终端已禁用"
diff --git a/packages/app/src/locales/zh-Hant/messages.po b/packages/app/src/locales/zh-Hant/messages.po
index f19a18c3f..4f7998b71 100644
--- a/packages/app/src/locales/zh-Hant/messages.po
+++ b/packages/app/src/locales/zh-Hant/messages.po
@@ -1354,9 +1354,6 @@ msgstr "代理模式"
msgid "Agent panel"
msgstr "智慧代理面板"
-msgid "Agent panel closed to keep Terminal readable."
-msgstr "為保持 Terminal 清晰可讀,已關閉智慧代理面板。"
-
msgid "Agent settings"
msgstr "代理設定"
@@ -8758,15 +8755,15 @@ msgstr "重設檢視篩選條件"
msgid "Resize {handleKey}"
msgstr "調整 {handleKey} 的大小"
+msgid "Resize {pane}"
+msgstr "調整 {pane} 的大小"
+
msgid "Resize document panel"
msgstr "調整文件面板大小"
msgid "Resize skills panel"
msgstr "調整「技能」面板大小"
-msgid "Resize terminal"
-msgstr "調整終端機大小"
-
msgid "Resolve conflict in your terminal"
msgstr "在你的終端機中解決衝突"
@@ -10290,9 +10287,6 @@ msgstr "終端機 {0}"
msgid "Terminal access isn't enabled for this project."
msgstr "這個專案沒有啟用終端機存取。"
-msgid "Terminal closed to make room for the agent panel."
-msgstr "已關閉 Terminal,為智慧代理面板騰出空間。"
-
msgid "Terminal disabled"
msgstr "終端機已停用"
diff --git a/packages/app/tests/stress/_helpers/index.ts b/packages/app/tests/stress/_helpers/index.ts
index 54a09755f..770275ade 100644
--- a/packages/app/tests/stress/_helpers/index.ts
+++ b/packages/app/tests/stress/_helpers/index.ts
@@ -101,7 +101,15 @@ export {
arrangeTerminalAlone,
CHAT_PANE_CARD,
type DesktopLayoutOptions,
+ DOCK_WORKSPACE,
+ type DockSeamDrag,
+ type DockUnitRect,
+ dockSeam,
+ dockUnit,
+ dockUnitRect,
+ dragDockSeam,
EDITOR_PANE_CARD,
+ expectDockUnitOff,
expectEditorHidden,
type HeaderPane,
headerPaneButton,
diff --git a/packages/app/tests/stress/_helpers/pane-layout.ts b/packages/app/tests/stress/_helpers/pane-layout.ts
index 5e6c212d1..47dca958d 100644
--- a/packages/app/tests/stress/_helpers/pane-layout.ts
+++ b/packages/app/tests/stress/_helpers/pane-layout.ts
@@ -24,6 +24,27 @@ const BOOT_TIMEOUT_MS = 30_000;
export const EDITOR_PANE_CARD = '[data-slot="pane-card"][data-pane="editor"]';
export const CHAT_PANE_CARD = '[data-slot="pane-card"][data-pane="agents"]';
+export const DOCK_WORKSPACE = '[data-dock-workspace]';
+
+const PANE_LABELS: Readonly<Record<HeaderPane, string>> = {
+ editor: 'Editor',
+ agents: 'Agents',
+ terminal: 'Terminal',
+};
+
+export interface DockUnitRect {
+ readonly x: number;
+ readonly y: number;
+ readonly width: number;
+ readonly height: number;
+}
+
+export interface DockSeamDrag {
+ readonly dx?: number;
+ readonly dy?: number;
+ readonly grabOffsetPx?: number;
+ readonly whileDragging?: () => Promise<void>;
+}
export function terminalPaneCard(placement: TerminalPlacement): string {
return `[data-slot="pane-card"][data-pane="terminal"][data-placement="${placement}"]`;
@@ -33,6 +54,54 @@ export function headerPaneButton(page: Page, pane: HeaderPane): Locator {
return page.getByTestId(`header-pane-button-${pane}`);
}
+export function dockUnit(page: Page, pane: HeaderPane): Locator {
+ return page.locator(`[data-dock-unit="${pane}"]`);
+}
+
+export function dockSeam(page: Page, trailingPane: HeaderPane): Locator {
+ return page
+ .locator('[data-dock-seam]')
+ .and(page.getByRole('separator', { name: `Resize ${PANE_LABELS[trailingPane]}`, exact: true }));
+}
+
+export async function dockUnitRect(page: Page, pane: HeaderPane): Promise<DockUnitRect | null> {
+ return await page.evaluate((selector) => {
+ const unit = document.querySelector(selector);
+ if (!(unit instanceof HTMLElement) || unit.hidden || unit.hasAttribute('data-dock-unit-off')) {
+ return null;
+ }
+ const { x, y, width, height } = unit.getBoundingClientRect();
+ return { x, y, width, height };
+ }, `[data-dock-unit="${pane}"]`);
+}
+
+export async function expectDockUnitOff(page: Page, pane: HeaderPane): Promise<void> {
+ const unit = dockUnit(page, pane);
+ await expect(unit).toHaveAttribute('data-dock-unit-off', '');
+ await expect(unit).toHaveAttribute('inert', '');
+ await expect(unit).toBeHidden();
+}
+
+export async function dragDockSeam(
+ page: Page,
+ seam: Locator,
+ { dx = 0, dy = 0, grabOffsetPx = 0, whileDragging }: DockSeamDrag = {},
+): Promise<void> {
+ const box = await seam.boundingBox();
+ if (box === null) throw new Error('the dock seam has no layout box');
+ const acrossRow = (await seam.getAttribute('data-dock-seam')) === 'row';
+ const x = box.x + box.width / 2 + (acrossRow ? grabOffsetPx : 0);
+ const y = box.y + box.height / 2 + (acrossRow ? 0 : grabOffsetPx);
+ const workspace = page.locator(DOCK_WORKSPACE);
+ await page.mouse.move(x, y);
+ await page.mouse.down();
+ await expect(workspace).toHaveAttribute('data-dragging', '');
+ await page.mouse.move(x + dx, y + dy, { steps: 8 });
+ await whileDragging?.();
+ await page.mouse.up();
+ await expect(workspace).not.toHaveAttribute('data-dragging');
+}
+
export async function stubAgentCatalog(page: Page): Promise<void> {
await page.route('**/api/acp/catalog', (route) => route.fulfill({ json: acpCatalogBody([]) }));
}
diff --git a/packages/app/tests/stress/agents-panel-reload-visibility.e2e.ts b/packages/app/tests/stress/agents-panel-reload-visibility.e2e.ts
index a3b08425e..bb528f88d 100644
--- a/packages/app/tests/stress/agents-panel-reload-visibility.e2e.ts
+++ b/packages/app/tests/stress/agents-panel-reload-visibility.e2e.ts
@@ -2,6 +2,7 @@ import { mkdirSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import AxeBuilder from '@axe-core/playwright';
import type { Locator, Page } from '@playwright/test';
+import { PANE_CARD_GAP_PX } from '../../src/components/ui/pane-card';
import {
HISTORY_DOCKED_MIN_PANE_WIDTH_PX,
HISTORY_PANEL_WIDTH_PX,
@@ -9,6 +10,9 @@ import {
import { AGENTS_PANEL_WIDTH_KEY } from '../../src/lib/agents-panel-width-store';
import {
contrastRatioOf,
+ DOCK_WORKSPACE,
+ dockSeam,
+ dockUnitRect,
expect,
readContrastPair,
servedModuleRoute,
@@ -28,6 +32,9 @@ const BOOT_TIMEOUT_MS = 30_000;
const ROSTER_TIMEOUT_MS = 30_000;
const AGENTS_HEADER_BUTTON = 'header-pane-button-agents';
const STORED_AGENTS_PANEL_WIDTH_PX = 400;
+const AGENTS_MIN_WIDTH_PX = 290;
+const SEAM_KEYBOARD_STEP_PX = 16;
+const SEAM_LARGE_KEYBOARD_STEP_PX = 64;
const THREAD_COMPOSER = '[data-testid="agent-thread-composer"]';
const HEADER_DRAFT = 'Draft kept across a header hide';
const SELECTION_DOC_TEXT = 'The quick brown fox jumps over the lazy dog.';
@@ -361,21 +368,28 @@ async function openAgentsPanel(page: Page): Promise<void> {
await settleAfterRoster(page);
}
+async function agentsPanelWidth(page: Page): Promise<number> {
+ return (await dockUnitRect(page, 'agents'))?.width ?? 0;
+}
+
+async function expectAgentsPanelWidth(page: Page, widthPx: number): Promise<void> {
+ await expect
+ .poll(async () => Math.abs((await agentsPanelWidth(page)) - widthPx))
+ .toBeLessThanOrEqual(1);
+}
+
async function resizeAgentsPanel(page: Page, targetWidth: number): Promise<void> {
- const mount = page.locator(AGENTS_PANEL_MOUNT);
- const panel = mount.locator('xpath=ancestor::*[@data-slot="resizable-panel"][1]');
- const handle = panel.locator('xpath=preceding-sibling::*[1]');
- await expect(handle).toHaveAttribute('data-slot', 'resizable-handle');
- await handle.focus();
- const currentWidth = await mount.evaluate((element) => element.getBoundingClientRect().width);
- const grows = currentWidth < targetWidth;
- for (let index = 0; index < 20; index += 1) {
- const width = await mount.evaluate((element) => element.getBoundingClientRect().width);
+ const seam = dockSeam(page, 'agents');
+ await seam.focus();
+ await expect(seam).toBeFocused();
+ const grows = (await agentsPanelWidth(page)) < targetWidth;
+ for (let index = 0; index < 40; index += 1) {
+ const width = await agentsPanelWidth(page);
if (grows ? width >= targetWidth : width <= targetWidth) break;
await page.keyboard.press(grows ? 'ArrowLeft' : 'ArrowRight');
await settleAfterRoster(page);
}
- const observedWidth = await mount.evaluate((element) => element.getBoundingClientRect().width);
+ const observedWidth = await agentsPanelWidth(page);
if (grows) expect(observedWidth).toBeGreaterThanOrEqual(targetWidth);
else expect(observedWidth).toBeLessThanOrEqual(targetWidth);
}
@@ -385,49 +399,43 @@ async function dragAgentsPanel(
targetWidth: number,
termination: 'pointerup' | 'pointercancel' = 'pointerup',
): Promise<number> {
- const mount = page.locator(AGENTS_PANEL_MOUNT);
- const panel = mount.locator('xpath=ancestor::*[@data-slot="resizable-panel"][1]');
- const handle = panel.locator('xpath=preceding-sibling::*[1]');
- const [handleBounds, startWidth] = await Promise.all([
- handle.boundingBox(),
- panel.evaluate((element) => element.getBoundingClientRect().width),
- ]);
- expect(handleBounds).not.toBeNull();
- if (handleBounds === null) throw new Error('Agents panel handle has no bounds');
- const startX = handleBounds.x + handleBounds.width / 2;
- const y = handleBounds.y + handleBounds.height / 2;
+ const seam = dockSeam(page, 'agents');
+ const workspace = page.locator(DOCK_WORKSPACE);
+ const [seamBounds, startWidth] = await Promise.all([seam.boundingBox(), agentsPanelWidth(page)]);
+ expect(seamBounds).not.toBeNull();
+ if (seamBounds === null) throw new Error('the Agents seam has no bounds');
+ const startX = seamBounds.x + seamBounds.width / 2;
+ const y = seamBounds.y + seamBounds.height / 2;
const targetX = startX + startWidth - targetWidth;
+ await seam.evaluate((element: HTMLElement) => {
+ element.addEventListener(
+ 'pointerdown',
+ (event) => {
+ (window as Window & { __agentsSeamPointerId?: number }).__agentsSeamPointerId =
+ event.pointerId;
+ },
+ { once: true },
+ );
+ });
await page.mouse.move(startX, y);
await page.mouse.down();
- await expect(page.locator('[data-dragging="true"]')).toHaveCount(1);
+ await expect(workspace).toHaveAttribute('data-dragging', '');
await page.mouse.move(targetX, y, { steps: 8 });
- const transientWidth = await panel.evaluate((element) => element.getBoundingClientRect().width);
+ const transientWidth = await agentsPanelWidth(page);
if (termination === 'pointercancel') {
- await page.evaluate(() => {
- document.dispatchEvent(new PointerEvent('pointercancel', { bubbles: true, pointerId: 1 }));
+ await seam.evaluate((element) => {
+ const pointerId =
+ (window as Window & { __agentsSeamPointerId?: number }).__agentsSeamPointerId ?? 1;
+ element.dispatchEvent(new PointerEvent('pointercancel', { bubbles: true, pointerId }));
});
}
await page.mouse.up();
- await expect(page.locator('[data-dragging="true"]')).toHaveCount(0);
+ await expect(workspace).not.toHaveAttribute('data-dragging');
return transientWidth;
}
-async function agentsPanelWidth(page: Page): Promise<number> {
- return page
- .locator(AGENTS_PANEL_MOUNT)
- .locator('xpath=ancestor::*[@data-slot="resizable-panel"][1]')
- .evaluate((element) => element.getBoundingClientRect().width);
-}
-
-async function persistedAgentsPanelWidth(page: Page): Promise<number | null> {
- return page.evaluate((key) => {
- const raw = window.localStorage.getItem(key);
- return raw === null ? null : Number.parseInt(raw, 10);
- }, AGENTS_PANEL_WIDTH_KEY);
-}
-
async function waitForAgentsHostSettled(page: Page): Promise<void> {
await expect(page.locator(`${AGENTS_PANEL_MOUNT} [role="tablist"]`)).toHaveCount(1, {
timeout: BOOT_TIMEOUT_MS,
@@ -479,7 +487,7 @@ test.describe('agents panel resize', () => {
await page.evaluate(() => window.__acpThreadHarness?.reset());
});
- test('the panel follows the pointer below its settled minimum and reverses before release', async ({
+ test('the panel follows a seam drag, stops at its minimum and reverses before release', async ({
page,
}) => {
await page.setViewportSize({ width: 1600, height: 900 });
@@ -496,45 +504,40 @@ test.describe('agents panel resize', () => {
await openAgentsPanel(page);
const mount = page.locator(AGENTS_PANEL_MOUNT);
- const panel = mount.locator('xpath=ancestor::*[@data-slot="resizable-panel"][1]');
- const handle = panel.locator('xpath=preceding-sibling::*[1]');
- const handleBounds = await handle.boundingBox();
- expect(handleBounds).not.toBeNull();
- if (handleBounds === null) return;
-
- const startWidth = await panel.evaluate((element) => element.getBoundingClientRect().width);
- expect(startWidth).toBeGreaterThan(420);
- expect(startWidth).toBeLessThan(540);
- const handleX = handleBounds.x + handleBounds.width / 2;
- const handleY = handleBounds.y + handleBounds.height / 2;
-
- await page.mouse.move(handleX, handleY);
+ const workspace = page.locator(DOCK_WORKSPACE);
+ const seamBounds = await dockSeam(page, 'agents').boundingBox();
+ expect(seamBounds).not.toBeNull();
+ if (seamBounds === null) return;
+
+ const startWidth = await agentsPanelWidth(page);
+ expect(startWidth).toBeGreaterThan(AGENTS_MIN_WIDTH_PX + 145);
+ const seamX = seamBounds.x + seamBounds.width / 2;
+ const seamY = seamBounds.y + seamBounds.height / 2;
+
+ await page.mouse.move(seamX, seamY);
await page.mouse.down();
- await expect(page.locator('[data-dragging="true"]')).toHaveCount(1);
+ await expect(workspace).toHaveAttribute('data-dragging', '');
- await page.mouse.move(handleX + 145, handleY, { steps: 8 });
- const firstShrinkWidth = await panel.evaluate(
- (element) => element.getBoundingClientRect().width,
- );
+ await page.mouse.move(seamX + 145, seamY, { steps: 8 });
+ const firstShrinkWidth = await agentsPanelWidth(page);
expect(firstShrinkWidth).toBeLessThan(startWidth - 100);
- await page.mouse.move(handleX + 190, handleY, { steps: 4 });
- const belowMinimumWidth = await panel.evaluate(
- (element) => element.getBoundingClientRect().width,
- );
- expect(belowMinimumWidth).toBeGreaterThan(200);
- expect(belowMinimumWidth).toBeLessThan(320);
+ await page.mouse.move(seamX + startWidth, seamY, { steps: 4 });
+ const atMinimumWidth = await agentsPanelWidth(page);
+ expect(Math.abs(atMinimumWidth - AGENTS_MIN_WIDTH_PX)).toBeLessThanOrEqual(1);
- await page.mouse.move(handleX + 110, handleY, { steps: 6 });
- const reversedWidth = await panel.evaluate((element) => element.getBoundingClientRect().width);
- expect(reversedWidth).toBeGreaterThan(belowMinimumWidth + 50);
+ await page.mouse.move(seamX + 100, seamY, { steps: 6 });
+ const reversedWidth = await agentsPanelWidth(page);
+ expect(reversedWidth).toBeGreaterThan(atMinimumWidth + 50);
expect(reversedWidth).toBeLessThan(startWidth);
await page.mouse.up();
- await expect(page.locator('[data-dragging="true"]')).toHaveCount(0);
+ await expect(workspace).not.toHaveAttribute('data-dragging');
+ await expect(mount).toBeVisible();
+ await expectAgentsPanelWidth(page, reversedWidth);
+ await reloadAndSettle(page);
await expect(mount).toBeVisible();
- await expect.poll(() => agentsPanelWidth(page)).toBeCloseTo(reversedWidth, -1);
- await expect.poll(() => persistedAgentsPanelWidth(page)).toBeCloseTo(reversedWidth, -1);
+ await expectAgentsPanelWidth(page, reversedWidth);
});
test('keyboard reveal of an empty agents panel keeps focus in the revealed surface', async ({
@@ -561,7 +564,7 @@ test.describe('agents panel resize', () => {
await expectFocusInsideAgentsPanel(page);
});
- test('release bands, cancellation, keyboard resizing, reveal, and reload preserve the settled contract', async ({
+ test('a release past the minimum settles at it, cancellation keeps the prior width, and keyboard steps, reveal and reload keep the settled width', async ({
page,
}) => {
await page.setViewportSize({ width: 1600, height: 900 });
@@ -577,46 +580,41 @@ test.describe('agents panel resize', () => {
});
await openAgentsPanel(page);
- const middleTransientWidth = await dragAgentsPanel(page, 250);
- expect(middleTransientWidth).toBeGreaterThan(200);
- expect(middleTransientWidth).toBeLessThan(320);
- await expect.poll(() => agentsPanelWidth(page)).toBeCloseTo(320, -1);
- await expect.poll(() => persistedAgentsPanelWidth(page)).toBe(320);
+ const minimumTransientWidth = await dragAgentsPanel(page, 250);
+ expect(Math.abs(minimumTransientWidth - AGENTS_MIN_WIDTH_PX)).toBeLessThanOrEqual(1);
+ await expectAgentsPanelWidth(page, AGENTS_MIN_WIDTH_PX);
await dragAgentsPanel(page, 520);
const preferredWidth = await agentsPanelWidth(page);
- expect(preferredWidth).toBeGreaterThan(500);
- expect(preferredWidth).toBeLessThan(540);
- await expect.poll(() => persistedAgentsPanelWidth(page)).toBeCloseTo(preferredWidth, -1);
+ expect(preferredWidth).toBeGreaterThan(510);
+ expect(preferredWidth).toBeLessThan(530);
const cancelledTransientWidth = await dragAgentsPanel(page, 240, 'pointercancel');
- expect(cancelledTransientWidth).toBeGreaterThan(200);
- expect(cancelledTransientWidth).toBeLessThan(320);
- await expect.poll(() => agentsPanelWidth(page)).toBeCloseTo(preferredWidth, -1);
- await expect.poll(() => persistedAgentsPanelWidth(page)).toBeCloseTo(preferredWidth, -1);
-
- const mount = page.locator(AGENTS_PANEL_MOUNT);
- const panel = mount.locator('xpath=ancestor::*[@data-slot="resizable-panel"][1]');
- const handle = panel.locator('xpath=preceding-sibling::*[1]');
- await handle.focus();
- for (let index = 0; index < 8; index += 1) {
- await page.keyboard.press('ArrowRight');
+ expect(Math.abs(cancelledTransientWidth - AGENTS_MIN_WIDTH_PX)).toBeLessThanOrEqual(1);
+ await expectAgentsPanelWidth(page, preferredWidth);
+
+ const seam = dockSeam(page, 'agents');
+ await seam.focus();
+ for (const key of [
+ 'ArrowRight',
+ 'ArrowRight',
+ 'ArrowRight',
+ 'ArrowRight',
+ 'Shift+ArrowRight',
+ ]) {
+ await page.keyboard.press(key);
await settleAfterRoster(page);
}
- await expect(handle).toBeFocused();
- await expect.poll(() => agentsPanelWidth(page)).toBeCloseTo(320, -1);
- await expect.poll(() => persistedAgentsPanelWidth(page)).toBeCloseTo(preferredWidth, -1);
-
- const closeTransientWidth = await dragAgentsPanel(page, 100);
- expect(closeTransientWidth).toBeLessThan(160);
- await expectAgentsPanelShown(page, false);
- await expect.poll(() => persistedAgentsPanelWidth(page)).toBeCloseTo(preferredWidth, -1);
+ await expect(seam).toBeFocused();
+ const keyboardWidth = preferredWidth - 4 * SEAM_KEYBOARD_STEP_PX - SEAM_LARGE_KEYBOARD_STEP_PX;
+ await expectAgentsPanelWidth(page, keyboardWidth);
+ await closeAgentsPanel(page);
await openAgentsPanel(page);
- await expect.poll(() => agentsPanelWidth(page)).toBeCloseTo(preferredWidth, -1);
+ await expectAgentsPanelWidth(page, keyboardWidth);
await reloadAndSettle(page);
- await expect(mount).toBeVisible();
- await expect.poll(() => agentsPanelWidth(page)).toBeCloseTo(preferredWidth, -1);
+ await expect(page.locator(AGENTS_PANEL_MOUNT)).toBeVisible();
+ await expectAgentsPanelWidth(page, keyboardWidth);
});
});
@@ -626,10 +624,11 @@ test.describe('header Agents button', () => {
await purgeLiveThreads(workerServer.port);
});
- test('clicking Agents while chat is hidden shows it at its stored width with focus inside it', async ({
+ test('clicking Agents while chat is hidden shows it at the share seeded from its stored width, with focus inside it', async ({
page,
}) => {
- await page.setViewportSize({ width: 1600, height: 900 });
+ const viewport = { width: 1600, height: 900 };
+ await page.setViewportSize(viewport);
await storeAgentsPanelWidth(page, STORED_AGENTS_PANEL_WIDTH_PX);
await stubAgentCatalog(page);
await openAppWithRoster(page);
@@ -637,7 +636,12 @@ test.describe('header Agents button', () => {
await agentsHeaderButton(page).click();
await expectAgentsPanelShown(page, true);
- await expect.poll(() => agentsPanelWidth(page)).toBeCloseTo(STORED_AGENTS_PANEL_WIDTH_PX, -1);
+ const workspaceWidth = await page
+ .locator(DOCK_WORKSPACE)
+ .evaluate((element) => element.getBoundingClientRect().width);
+ const seededWidth =
+ (STORED_AGENTS_PANEL_WIDTH_PX / viewport.width) * (workspaceWidth - PANE_CARD_GAP_PX);
+ await expect.poll(() => agentsPanelWidth(page)).toBeCloseTo(seededWidth, -1);
await expectFocusInsideAgentsPanel(page);
});
@@ -1113,7 +1117,7 @@ test.describe('chat history navigation', () => {
).toHaveAttribute('aria-selected', 'true');
});
- test('a covered agent pane dragged to zero width reads off and one Agents click brings it back at its width', async ({
+ test('a narrow agent pane keeps history in a cover, and hiding it from Agents brings it back at its width', async ({
page,
}) => {
await page.setViewportSize({ width: 1600, height: 900 });
@@ -1123,9 +1127,9 @@ test.describe('chat history navigation', () => {
const harness = window.__acpThreadHarness;
if (harness === undefined) throw new Error('ACP thread harness is not installed');
harness.openThread({
- threadId: 'history-drag-close',
- agent: { id: 'drag-close', name: 'First Agent', source: 'registry' },
- title: 'Drag close conversation',
+ threadId: 'history-narrow-cover',
+ agent: { id: 'narrow-cover', name: 'First Agent', source: 'registry' },
+ title: 'Narrow cover conversation',
});
});
await openAgentsPanel(page);
@@ -1169,24 +1173,13 @@ test.describe('chat history navigation', () => {
await mount.getByRole('button', { name: 'Chat history' }).click();
await expect(history).toHaveAttribute('data-history-mode', 'cover');
- const panel = mount.locator('xpath=ancestor::*[@data-slot="resizable-panel"][1]');
- const handle = panel.locator('xpath=preceding-sibling::*[1]');
- const handleBounds = await handle.boundingBox();
- expect(handleBounds).not.toBeNull();
- const handleX = (handleBounds?.x ?? 0) + (handleBounds?.width ?? 0) / 2;
- const handleY = (handleBounds?.y ?? 0) + (handleBounds?.height ?? 0) / 2;
- const widthBeforeDrag = await agentsPanelWidth(page);
- await page.mouse.move(handleX, handleY);
- await page.mouse.down();
- await page.mouse.move(1598, handleY, { steps: 10 });
- await page.mouse.up();
-
- await expect(page.locator('[data-dragging="true"]')).toHaveCount(0);
+ const widthBeforeHide = await agentsPanelWidth(page);
+ await agentsHeaderButton(page).click();
await expectAgentsPanelShown(page, false);
await agentsHeaderButton(page).click();
await expectAgentsPanelShown(page, true);
- await expect.poll(() => agentsPanelWidth(page)).toBeCloseTo(widthBeforeDrag, -1);
- await expect(mount.getByRole('tab', { name: 'Drag close conversation' })).toBeVisible();
+ await expectAgentsPanelWidth(page, widthBeforeHide);
+ await expect(mount.getByRole('tab', { name: 'Narrow cover conversation' })).toBeVisible();
});
});
diff --git a/packages/app/tests/stress/chat-explicit-hide-late-restore.e2e.ts b/packages/app/tests/stress/chat-explicit-hide-late-restore.e2e.ts
index 6b3838dfb..327218596 100644
--- a/packages/app/tests/stress/chat-explicit-hide-late-restore.e2e.ts
+++ b/packages/app/tests/stress/chat-explicit-hide-late-restore.e2e.ts
@@ -4,7 +4,7 @@ import type {
ThreadServerFrame,
} from '@inkeep/open-knowledge-core/acp/thread-protocol';
import type { WebSocketRoute } from '@playwright/test';
-import { expect, test, waitForActiveProviderSynced } from './_helpers';
+import { dockUnitRect, expect, test, waitForActiveProviderSynced } from './_helpers';
import { startHiddenChatAgent } from './hidden-chat-transport.test-helper';
test('a hidden Chat stays hidden through late thread restoration until its shortcut reveals it', async ({
@@ -70,9 +70,8 @@ test('a hidden Chat stays hidden through late thread restoration until its short
await waitForActiveProviderSynced(page);
const button = page.getByTestId('header-pane-button-agents');
- const mount = page.locator('[data-agents-panel-mount]');
const threadTab = page.locator(`[role="tab"][data-tab-id="${fixture.threadId}"]`);
- const panelWidth = () => mount.boundingBox().then((box) => box?.width ?? 0);
+ const panelWidth = () => dockUnitRect(page, 'agents').then((rect) => rect?.width ?? 0);
await expect
.poll(() => observedRosters.some((ids) => ids.includes(fixture.threadId)))
@@ -94,14 +93,6 @@ test('a hidden Chat stays hidden through late thread restoration until its short
await expect(threadTab).toHaveCount(1);
expect(createRequests).toEqual([]);
- const handle = mount
- .locator('xpath=ancestor::*[@data-slot="resizable-panel"][1]')
- .locator('xpath=preceding-sibling::*[1]');
- await expect(handle).toHaveAttribute('data-slot', 'resizable-handle');
- await handle.press('Home');
- await expect.poll(panelWidth).toBe(0);
- await button.press('ControlOrMeta+Shift+j');
- await expect.poll(panelWidth).toBeGreaterThan(250);
await button.press('ControlOrMeta+Shift+j');
await expect.poll(panelWidth).toBeGreaterThan(250);
@@ -137,10 +128,14 @@ test('a hidden Chat stays hidden through late thread restoration until its short
await page.evaluate(() => {
const samples: Array<{ visible: boolean; pressed: boolean }> = [];
const recordFrame = () => {
- const panel = document.querySelector('[data-agents-panel-mount]');
+ const unit = document.querySelector('[data-dock-unit="agents"]');
const button = document.querySelector('[data-testid="header-pane-button-agents"]');
samples.push({
- visible: (panel?.getBoundingClientRect().width ?? 0) > 0,
+ visible:
+ unit instanceof HTMLElement &&
+ !unit.hidden &&
+ !unit.hasAttribute('data-dock-unit-off') &&
+ unit.getBoundingClientRect().width > 0,
pressed: button?.getAttribute('aria-pressed') === 'true',
});
requestAnimationFrame(recordFrame);
diff --git a/packages/app/tests/stress/chat-shortcut-collapsed-thread.e2e.ts b/packages/app/tests/stress/chat-shortcut-collapsed-thread.e2e.ts
index 0aa2fc0c6..83b0de6e7 100644
--- a/packages/app/tests/stress/chat-shortcut-collapsed-thread.e2e.ts
+++ b/packages/app/tests/stress/chat-shortcut-collapsed-thread.e2e.ts
@@ -1,9 +1,13 @@
import { randomUUID } from 'node:crypto';
import type { Page } from '@playwright/test';
import type { AgentCatalog } from '@/lib/acp/catalog';
-import { expect, test, waitForActiveProviderSynced } from './_helpers';
+import { dockUnitRect, expect, test, waitForActiveProviderSynced } from './_helpers';
import { startHiddenChatAgent } from './hidden-chat-transport.test-helper';
+async function chatWidth(page: Page): Promise<number> {
+ return (await dockUnitRect(page, 'agents'))?.width ?? 0;
+}
+
async function registerFixtureAgent(page: Page, agentId: string): Promise<void> {
await page.addInitScript((id) => {
localStorage.setItem(
@@ -25,7 +29,7 @@ test.beforeEach(async ({ page }) => {
});
});
});
-test('Chat shortcut restores a keyboard-collapsed real thread in the same frame', async ({
+test('Chat shortcut restores a hidden real thread in the same frame', async ({
page,
api,
workerServer,
@@ -47,22 +51,14 @@ test('Chat shortcut restores a keyboard-collapsed real thread in the same frame'
await page.goto(`/#/${docName}`);
await waitForActiveProviderSynced(page);
const button = page.getByTestId('header-pane-button-agents');
- const mount = page.locator('[data-agents-panel-mount]');
await expect(button).toBeVisible();
await button.click();
- await expect
- .poll(() => mount.boundingBox().then((box) => box?.width ?? 0))
- .toBeGreaterThan(250);
+ await expect.poll(() => chatWidth(page)).toBeGreaterThan(250);
const threadTab = page.locator(`[role="tab"][data-tab-id="${fixture.threadId}"]`);
await expect(threadTab).toHaveCount(1);
await threadTab.click();
- const handle = mount
- .locator('xpath=ancestor::*[@data-slot="resizable-panel"][1]')
- .locator('xpath=preceding-sibling::*[1]');
- await expect(handle).toHaveAttribute('data-slot', 'resizable-handle');
- await handle.focus();
- await handle.press('Home');
- await expect.poll(() => mount.boundingBox().then((box) => box?.width ?? 0)).toBe(0);
+ await button.click();
+ await expect.poll(() => chatWidth(page)).toBe(0);
await expect(button).toHaveAttribute('aria-pressed', 'false');
await page.evaluate(() => {
const swatch = document.createElement('div');
@@ -76,10 +72,14 @@ test('Chat shortcut restores a keyboard-collapsed real thread in the same frame'
pointerEvents: 'none',
});
document.body.append(swatch);
- const panel = document.querySelector('[data-agents-panel-mount]');
+ const unit = document.querySelector('[data-dock-unit="agents"]');
const button = document.querySelector('[data-testid="header-pane-button-agents"]');
const sample = () => {
- const wide = (panel?.getBoundingClientRect().width ?? 0) > 0;
+ const wide =
+ unit instanceof HTMLElement &&
+ !unit.hidden &&
+ !unit.hasAttribute('data-dock-unit-off') &&
+ unit.getBoundingClientRect().width > 0;
const pressed = button?.getAttribute('aria-pressed') === 'true';
swatch.style.backgroundColor = wide
? pressed
@@ -91,8 +91,12 @@ test('Chat shortcut restores a keyboard-collapsed real thread in the same frame'
};
const mutation = new MutationObserver(sample);
if (button) mutation.observe(button, { attributes: true, attributeFilter: ['aria-pressed'] });
- const resize = new ResizeObserver(sample);
- if (panel) resize.observe(panel);
+ if (unit) {
+ mutation.observe(unit, {
+ attributes: true,
+ attributeFilter: ['hidden', 'data-dock-unit-off', 'style'],
+ });
+ }
let running = true;
const tick = () => {
if (!running) return;
@@ -106,7 +110,6 @@ test('Chat shortcut restores a keyboard-collapsed real thread in the same frame'
stop: () => {
running = false;
mutation.disconnect();
- resize.disconnect();
swatch.remove();
},
},
@@ -115,15 +118,11 @@ test('Chat shortcut restores a keyboard-collapsed real thread in the same frame'
await client.send('Page.startScreencast', { format: 'png', everyNthFrame: 1 });
await expect.poll(() => frames.length).toBeGreaterThan(0);
await page.keyboard.press('ControlOrMeta+Shift+j');
- await expect
- .poll(() => mount.boundingBox().then((box) => box?.width ?? 0))
- .toBeGreaterThan(250);
+ await expect.poll(() => chatWidth(page)).toBeGreaterThan(250);
await expect(button).toHaveAttribute('aria-pressed', 'true');
- const firstWidth = (await mount.boundingBox())?.width ?? 0;
+ const firstWidth = await chatWidth(page);
await page.keyboard.press('ControlOrMeta+Shift+j');
- await expect
- .poll(() => mount.boundingBox().then((box) => box?.width ?? 0))
- .toBeGreaterThan(250);
+ await expect.poll(() => chatWidth(page)).toBeGreaterThan(250);
await expect(button).toHaveAttribute('aria-pressed', 'true');
await expect.poll(() => frames.length).toBeGreaterThan(1);
await client.send('Page.stopScreencast');
@@ -185,7 +184,7 @@ for (const action of [
'reuse the active thread with Ask AI',
'launch an agent thread',
] as const) {
- test(`${action} reveals a keyboard-collapsed Chat pane with an existing thread`, async ({
+ test(`${action} reveals a hidden Chat pane with an existing thread`, async ({
page,
api,
workerServer,
@@ -204,18 +203,12 @@ for (const action of [
await expect(button).toBeVisible();
await expect(threadTab).toHaveCount(1);
await button.click();
- await expect
- .poll(() => mount.boundingBox().then((box) => box?.width ?? 0))
- .toBeGreaterThan(250);
+ await expect.poll(() => chatWidth(page)).toBeGreaterThan(250);
await expect(threadTab).toHaveCount(1);
await threadTab.click();
const tabs = mount.locator('[role="tab"][data-tab-id]');
- const handle = mount
- .locator('xpath=ancestor::*[@data-slot="resizable-panel"][1]')
- .locator('xpath=preceding-sibling::*[1]');
- await expect(handle).toHaveAttribute('data-slot', 'resizable-handle');
- await handle.press('Home');
- await expect.poll(() => mount.boundingBox().then((box) => box?.width ?? 0)).toBe(0);
+ await button.click();
+ await expect.poll(() => chatWidth(page)).toBe(0);
await expect(button).toHaveAttribute('aria-pressed', 'false');
const originalTabIds = await tabs.evaluateAll((elements) =>
elements.map((element) => element.getAttribute('data-tab-id')).sort(),
@@ -311,9 +304,7 @@ for (const action of [
if (originalTabIds.length === 1) await expect(tabs).toHaveCount(2);
}
- await expect
- .poll(() => mount.boundingBox().then((box) => box?.width ?? 0))
- .toBeGreaterThan(250);
+ await expect.poll(() => chatWidth(page)).toBeGreaterThan(250);
await expect(button).toHaveAttribute('aria-pressed', 'true');
await expect(threadTab).toBeVisible();
await threadTab.focus();
diff --git a/packages/app/tests/stress/dock-seam-focus.e2e.ts b/packages/app/tests/stress/dock-seam-focus.e2e.ts
new file mode 100644
index 000000000..db1c140da
--- /dev/null
+++ b/packages/app/tests/stress/dock-seam-focus.e2e.ts
@@ -0,0 +1,63 @@
+import type { Locator } from '@playwright/test';
+import {
+ dockSeam,
+ expect,
+ headerPaneButton,
+ setHeaderPane,
+ stubAgentCatalog,
+ test,
+ waitForActiveProviderSynced,
+} from './_helpers';
+
+const BOOT_TIMEOUT_MS = 30_000;
+
+interface FocusLook {
+ readonly focusVisible: boolean;
+ readonly outlineStyle: string;
+ readonly outlineWidthPx: number;
+ readonly boxShadow: string;
+}
+
+async function readFocusLook(seam: Locator): Promise<FocusLook> {
+ return await seam.evaluate((element) => {
+ const style = getComputedStyle(element);
+ return {
+ focusVisible: element.matches(':focus-visible'),
+ outlineStyle: style.outlineStyle,
+ outlineWidthPx: Number.parseFloat(style.outlineWidth),
+ boxShadow: style.boxShadow,
+ };
+ });
+}
+
+test.describe('dock seams', () => {
+ test('a keyboard-focused seam keeps a visible focus indicator when the system forces colors', async ({
+ page,
+ api,
+ }) => {
+ const name = `dock-seam-focus-${test.info().workerIndex}`;
+ await api.seedDocs([{ name, markdown: `# ${name}\n\nA document beside the Agents panel.\n` }]);
+ await stubAgentCatalog(page);
+ await page.setViewportSize({ width: 1600, height: 900 });
+ await page.goto(`/#/${name}`);
+ await waitForActiveProviderSynced(page);
+ await expect(headerPaneButton(page, 'editor')).toBeVisible({ timeout: BOOT_TIMEOUT_MS });
+ await setHeaderPane(page, 'agents', true);
+
+ const seam = dockSeam(page, 'agents');
+ await seam.focus();
+ await page.keyboard.press('Shift');
+ await expect(seam).toBeFocused();
+
+ const normal = await readFocusLook(seam);
+ expect(normal.focusVisible).toBe(true);
+ expect(normal.boxShadow).not.toBe('none');
+
+ await page.emulateMedia({ forcedColors: 'active' });
+ expect(await page.evaluate(() => matchMedia('(forced-colors: active)').matches)).toBe(true);
+ const forced = await readFocusLook(seam);
+ expect(forced.focusVisible).toBe(true);
+ expect(forced.outlineStyle).toBe('solid');
+ expect(forced.outlineWidthPx).toBeGreaterThanOrEqual(1);
+ });
+});
diff --git a/packages/app/tests/stress/editor-card-side-panel-width.e2e.ts b/packages/app/tests/stress/editor-card-side-panel-width.e2e.ts
index de74ccabf..3e55e7f54 100644
--- a/packages/app/tests/stress/editor-card-side-panel-width.e2e.ts
+++ b/packages/app/tests/stress/editor-card-side-panel-width.e2e.ts
@@ -11,7 +11,16 @@ import { setTimeout as wait } from 'node:timers/promises';
import { resolveShadowDir } from '@inkeep/open-knowledge-core/shadow-repo-layout';
import { saveInMemoryCheckpoint } from '@inkeep/open-knowledge-server';
import { chromium, type Locator, type Page } from '@playwright/test';
-import { acpCatalogBody, expect, test, waitForActiveProviderSynced } from './_helpers';
+import {
+ acpCatalogBody,
+ DOCK_WORKSPACE,
+ dockSeam,
+ dockUnit,
+ dragDockSeam,
+ expect,
+ test,
+ waitForActiveProviderSynced,
+} from './_helpers';
const AGENTS_PANEL_MOUNT = '[data-agents-panel-mount]';
const AGENTS_HEADER_BUTTON = 'header-pane-button-agents';
@@ -308,38 +317,25 @@ async function dragChatDivider(
deltaPx: number,
readMidDrag: () => Promise<void>,
): Promise<void> {
- const chatPanel = page
- .locator(AGENTS_PANEL_MOUNT)
- .locator('xpath=ancestor::*[@data-slot="resizable-panel"][1]');
- const handle = chatPanel.locator('xpath=preceding-sibling::*[1]');
- await expect(handle).toHaveAttribute('data-slot', 'resizable-handle');
- const bounds = await handle.boundingBox();
+ const seam = dockSeam(page, 'agents');
+ const bounds = await seam.boundingBox();
if (bounds == null) throw new Error('the chat divider has no bounds');
- const x = bounds.x + bounds.width / 2 + grabOffsetPx;
- const y = bounds.y + bounds.height / 2;
if (grabOffsetPx !== 0) {
expect(
await page.evaluate(
([px, py]) => {
const hit = document.elementFromPoint(px, py);
return {
- onDragBand: hit?.closest('[data-slot="resizable-handle"]') != null,
+ onDragBand: hit?.closest('[data-dock-seam]') != null,
onCard: hit?.closest('[data-slot="pane-card"]') != null,
};
},
- [x, y] as const,
+ [bounds.x + bounds.width / 2 + grabOffsetPx, bounds.y + bounds.height / 2] as const,
),
'the grab point is in the gap beside the divider line: on its drag band, on no card',
).toEqual({ onDragBand: true, onCard: false });
}
- await page.mouse.move(x, y);
- await page.mouse.down();
- await expect(handle).toHaveAttribute('data-separator', 'active');
- await page.mouse.move(x + deltaPx, y, { steps: 8 });
- await readMidDrag();
- await page.mouse.up();
- await expect(handle).not.toHaveAttribute('data-separator', 'active');
- await expect(page.locator('[data-dragging="true"]')).toHaveCount(0);
+ await dragDockSeam(page, seam, { dx: deltaPx, grabOffsetPx, whileDragging: readMidDrag });
await settleFrames(page);
}
@@ -350,6 +346,7 @@ for (const grab of GRABS) {
}) => {
const docName = `editor-card-side-panel-width-${test.info().workerIndex}`;
await api.seedDocs([{ name: docName, markdown: DOC_MARKDOWN }]);
+ await page.addInitScript(() => localStorage.setItem('ok-doc-panel-width-v1', '420'));
await page.setViewportSize({ width: 1400, height: 800 });
await page.goto(`/#/${docName}`);
await waitForActiveProviderSynced(page);
@@ -375,9 +372,7 @@ for (const grab of GRABS) {
await openChat(page);
await expect(sidePanel).not.toBeVisible();
- const chatPanel = page
- .locator(AGENTS_PANEL_MOUNT)
- .locator('xpath=ancestor::*[@data-slot="resizable-panel"][1]');
+ const chatPanel = dockUnit(page, 'agents');
const chatBefore = await widthOf(chatPanel);
const columnBefore = await widthOf(documentColumn);
@@ -512,6 +507,70 @@ for (const input of ['pointer', 'keyboard']) {
});
}
+test('a document pointerleave mid-drag resizes the side panel by the real travel and keeps it open', async ({
+ page,
+ api,
+}) => {
+ const docName = `editor-card-side-panel-pointerleave-${test.info().workerIndex}`;
+ await api.seedDocs([{ name: docName, markdown: DOC_MARKDOWN }]);
+ await page.addInitScript(() => localStorage.setItem('ok-doc-panel-width-v1', '420'));
+ await page.setViewportSize({ width: 1600, height: 900 });
+ await page.goto(`/#/${docName}`);
+ await waitForActiveProviderSynced(page);
+ const sidePanel = page.locator('#doc-panel');
+ const toggle = page.locator('[data-doc-panel-toggle]');
+ await expect(sidePanel).toBeVisible();
+ await expect(toggle).toHaveAttribute('aria-expanded', 'true');
+ const before = await widthOf(sidePanel);
+ expect(
+ Math.abs(before - 420),
+ 'the side panel starts with room to grow and shrink',
+ ).toBeLessThanOrEqual(WIDTH_TOLERANCE_PX);
+
+ const separator = page.getByRole('separator', { name: 'Resize document panel' });
+ const bounds = await separator.boundingBox();
+ if (bounds == null) throw new Error('the side panel separator has no bounds');
+ const travel = 40;
+ const originX = bounds.x + bounds.width / 2;
+ const originY = bounds.y + bounds.height / 2;
+ await page.mouse.move(originX, originY);
+ await page.mouse.down();
+ await expect(separator).toHaveAttribute('data-separator', 'active');
+ await page.mouse.move(originX - travel, originY, { steps: 4 });
+ await page.evaluate(
+ ({ x, y }) => {
+ document.dispatchEvent(
+ new PointerEvent('pointerleave', {
+ bubbles: false,
+ buttons: 1,
+ clientX: x,
+ clientY: y,
+ pointerId: 1,
+ pointerType: 'mouse',
+ }),
+ );
+ },
+ { x: originX - travel, y: originY },
+ );
+ await page.mouse.up();
+
+ let after = Number.NaN;
+ let stable = 0;
+ await expect(async () => {
+ const width = Math.round(await widthOf(sidePanel));
+ stable = width === after ? stable + 1 : 0;
+ after = width;
+ expect(
+ stable,
+ `the side panel width has not settled (last read ${width}px, before ${before}px)`,
+ ).toBeGreaterThanOrEqual(3);
+ }).toPass({ timeout: 10_000, intervals: [100] });
+ expect(after).toBeGreaterThan(before + travel * 0.75);
+ expect(after).toBeLessThan(before + travel * 1.25);
+ await expect(sidePanel).toBeVisible();
+ await expect(toggle).toHaveAttribute('aria-expanded', 'true');
+});
+
test('constrained docking swaps sidebars, restores both, and preserves explicit hiding and widths', async ({
page,
api,
@@ -1855,6 +1914,7 @@ test('information cover keeps every document tab usable at narrow browser widths
await page.setViewportSize({ width: 320, height: 480 });
await expect(toggle).toBeVisible();
+ await settleFrames(page);
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(320);
await page.setViewportSize({ width: 650, height: 700 });
@@ -2230,6 +2290,8 @@ for (const order of ['destination first', 'resize first'] as const) {
await agentsButton.click();
await expect(agentsButton).toHaveAttribute('aria-pressed', 'true');
await expect(page.locator(AGENTS_PANEL_MOUNT)).toBeVisible();
+ const editorWidth = await widthOf(page.locator('[data-slot="pane-card"][data-pane="editor"]'));
+ await dragDockSeam(page, dockSeam(page, 'agents'), { dx: 500 - editorWidth });
await page.locator('[data-doc-panel-toggle]').click();
const cover = page.locator('[data-doc-panel-cover]');
await expect(cover).toBeVisible();
@@ -3456,19 +3518,9 @@ test('closed wide information reopens as a cover after editor and window resizin
await toggle.click();
await expect(info).toBeHidden();
const card = page.locator('[data-slot="pane-card"][data-pane="editor"]');
- const chatDivider = page.locator('[data-agents-panel-resize-handle]');
- for (const target of [900, 650, 450, 270]) {
- await chatDivider.hover();
- const cb = await chatDivider.boundingBox();
+ for (const target of [900, 650, 450, 340]) {
const before = await card.evaluate((e) => e.getBoundingClientRect().width);
- if (!cb) throw new Error('Chat divider has no bounds');
- await page.mouse.down();
- await expect(chatDivider).toHaveAttribute('data-separator', 'active');
- await page.mouse.move(cb.x + cb.width / 2 + (target - before), cb.y + cb.height / 2, {
- steps: 12,
- });
- await page.mouse.up();
- await expect(chatDivider).not.toHaveAttribute('data-separator', 'active');
+ await dragDockSeam(page, dockSeam(page, 'agents'), { dx: target - before });
await page.screenshot({ path: test.info().outputPath(`closed-${target}.png`) });
await expect(toggle).toBeVisible();
await toggle.click();
@@ -3494,7 +3546,7 @@ test('closed wide information reopens as a cover after editor and window resizin
await expect(page.locator('[data-sidebar="sidebar"]')).toBeVisible();
await toggle.click();
await expect(info).toBeHidden();
- for (const width of [1400, 1200, 900]) {
+ for (const width of [1200, 1000, 900]) {
await page.setViewportSize({ width, height: 900 });
await settleFrames(page);
await expect(toggle).toBeVisible();
@@ -3575,13 +3627,14 @@ test('information yields after resizing the editor beside Chat below its docking
const info = page.locator('#doc-panel');
await expect(info).toBeVisible();
const card = page.locator('[data-slot="pane-card"][data-pane="editor"]');
- const handle = page.locator('[data-agents-panel-resize-handle]');
+ const handle = dockSeam(page, 'agents');
+ const workspace = page.locator(DOCK_WORKSPACE);
await handle.hover();
const box = await handle.boundingBox();
const before = await card.evaluate((e) => e.getBoundingClientRect().width);
if (!box) throw new Error('Chat divider has no bounds');
await page.mouse.down();
- await expect(handle).toHaveAttribute('data-separator', 'active');
+ await expect(workspace).toHaveAttribute('data-dragging', '');
try {
for (const target of [1300, 1150, 1000, 850, 750]) {
await page.mouse.move(box.x + box.width / 2 + target - before, box.y + box.height / 2, {
@@ -3606,7 +3659,7 @@ test('information yields after resizing the editor beside Chat below its docking
} finally {
await page.mouse.up();
}
- await expect(handle).not.toHaveAttribute('data-separator', 'active');
+ await expect(workspace).not.toHaveAttribute('data-dragging');
await settleFrames(page);
await page.screenshot({ path: test.info().outputPath('open-information-after-drag.png') });
await expect(info).toBeHidden();
diff --git a/packages/app/tests/stress/editor-pane-button.e2e.ts b/packages/app/tests/stress/editor-pane-button.e2e.ts
index 34cfecc13..837e1b0dd 100644
--- a/packages/app/tests/stress/editor-pane-button.e2e.ts
+++ b/packages/app/tests/stress/editor-pane-button.e2e.ts
@@ -3,8 +3,11 @@ import type { TerminalPlacement } from '../../src/lib/terminal-placement-store';
import type { ApiHelpers, WorkerServer } from './_helpers';
import {
CHAT_PANE_CARD,
+ dockSeam,
+ dragDockSeam,
EDITOR_PANE_CARD,
expect,
+ expectDockUnitOff,
expectEditorHidden,
headerPaneButton,
openDesktopHeader,
@@ -30,8 +33,8 @@ const DOC_TEXT = 'The quick brown fox jumps over the lazy dog.';
const BOTTOM_TERMINAL_CARD =
'[data-slot="pane-card"][data-pane="terminal"][data-placement="bottom"]';
const PANELS = '[data-editor-area-panels]';
-const EDITOR_COLUMN = '[data-editor-row="outer"] > [data-panel]';
const EDITOR_REGION = '[data-editor-region]';
+const FILE_LIST_SLOT = '[data-editor-file-list-slot]';
const MIN_CARD_PX = 100;
async function boxOf(page: Page, selector: string): Promise<Box> {
@@ -104,10 +107,6 @@ async function openDesktop(
return name;
}
-async function expectEditorColumnEmpty(page: Page): Promise<void> {
- await expect.poll(() => widthOf(page, EDITOR_COLUMN)).toBeLessThanOrEqual(1);
-}
-
async function expectFillsRow(page: Page, selectors: readonly string[]): Promise<void> {
await expect
.poll(async () => {
@@ -215,12 +214,13 @@ test.describe('the Editor header button', () => {
await openWeb(page, api, 'chat-alone');
await setHeaderPane(page, 'agents', true);
const chatWidthBefore = await widthOf(page, CHAT_PANE_CARD);
+ await expect(page.locator(FILE_LIST_SLOT)).toBeVisible();
await setHeaderPane(page, 'editor', false);
await expectEditorHidden(page);
- await expectEditorColumnEmpty(page);
+ await expectDockUnitOff(page, 'editor');
await expectFillsRow(page, [CHAT_PANE_CARD]);
- await expect(page.locator('[data-editor-file-list-slot]')).not.toBeInViewport();
+ await expect(page.locator(FILE_LIST_SLOT)).toBeHidden();
await expect(
page.getByRole('region', { name: /Document statistics|Editor status bar/ }),
).not.toBeVisible();
@@ -296,11 +296,11 @@ test.describe('filling the space on the mocked desktop', () => {
await setHeaderPane(page, 'editor', false);
await expectEditorHidden(page);
- await expectEditorColumnEmpty(page);
+ await expectDockUnitOff(page, 'editor');
await expectFillsRow(page, [RIGHT_TERMINAL_PANE_CARD]);
});
- test('a right terminal and chat share the row in proportion, and widths dragged while hidden are put back on show', async ({
+ test('a right terminal and chat share the row in proportion, and a drag between them while the editor is hidden gives the editor back its width on show', async ({
page,
api,
workerServer,
@@ -308,13 +308,14 @@ test.describe('filling the space on the mocked desktop', () => {
await openDesktop(page, api, workerServer, 'right-and-chat', 'right');
await setHeaderPane(page, 'terminal', true);
await setHeaderPane(page, 'agents', true);
+ const editorBefore = await widthOf(page, EDITOR_PANE_CARD);
const terminalBefore = await widthOf(page, RIGHT_TERMINAL_PANE_CARD);
const chatBefore = await widthOf(page, CHAT_PANE_CARD);
const sidePanelBefore = await widthOf(page, '#doc-panel');
await setHeaderPane(page, 'editor', false);
await expectEditorHidden(page);
- await expectEditorColumnEmpty(page);
+ await expectDockUnitOff(page, 'editor');
await expectFillsRow(page, [RIGHT_TERMINAL_PANE_CARD, CHAT_PANE_CARD]);
await expect
.poll(
@@ -323,20 +324,23 @@ test.describe('filling the space on the mocked desktop', () => {
)
.toBeCloseTo(terminalBefore / chatBefore, 1);
- const divider = page.locator('[data-agents-panel-resize-handle]');
- const bounds = await divider.boundingBox();
- if (bounds === null) throw new Error('no divider between terminal and chat');
- await page.mouse.move(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2);
- await page.mouse.down();
- await page.mouse.move(bounds.x - 150, bounds.y + bounds.height / 2, { steps: 10 });
- await page.mouse.up();
- await expect.poll(() => widthOf(page, CHAT_PANE_CARD)).toBeGreaterThan(chatBefore + 100);
+ const chatHidden = await widthOf(page, CHAT_PANE_CARD);
+ await dragDockSeam(page, dockSeam(page, 'agents'), { dx: 150 });
+ await expect.poll(() => widthOf(page, CHAT_PANE_CARD)).toBeLessThan(chatHidden - 100);
await expectFillsRow(page, [RIGHT_TERMINAL_PANE_CARD, CHAT_PANE_CARD]);
await setHeaderPane(page, 'editor', true);
- await expect.poll(() => widthOf(page, CHAT_PANE_CARD)).toBeCloseTo(chatBefore, 0);
- await expect.poll(() => widthOf(page, RIGHT_TERMINAL_PANE_CARD)).toBeCloseTo(terminalBefore, 0);
+ await expect.poll(() => widthOf(page, EDITOR_PANE_CARD)).toBeCloseTo(editorBefore, 0);
await expect.poll(() => widthOf(page, '#doc-panel')).toBeCloseTo(sidePanelBefore, 0);
+ expect(await widthOf(page, CHAT_PANE_CARD)).toBeLessThan(chatBefore);
+ expect(await widthOf(page, RIGHT_TERMINAL_PANE_CARD)).toBeGreaterThan(terminalBefore);
+ expect(
+ Math.abs(
+ (await widthOf(page, CHAT_PANE_CARD)) +
+ (await widthOf(page, RIGHT_TERMINAL_PANE_CARD)) -
+ (chatBefore + terminalBefore),
+ ),
+ ).toBeLessThanOrEqual(2);
});
});
diff --git a/packages/app/tests/stress/editor-pane-cards.e2e.ts b/packages/app/tests/stress/editor-pane-cards.e2e.ts
index fd23f3a2e..10a48ef2c 100644
--- a/packages/app/tests/stress/editor-pane-cards.e2e.ts
+++ b/packages/app/tests/stress/editor-pane-cards.e2e.ts
@@ -10,6 +10,7 @@ import { PANE_CARD_GAP_PX } from '../../src/components/ui/pane-card';
import { SCROLL_PIN_SLACK_PX } from '../../src/editor/document-scrollports';
import {
acpCatalogBody,
+ dockUnit,
expect,
placeCaretAtEndOfText,
readEditorCaretLine,
@@ -195,7 +196,10 @@ test('the editor and chat cards stand side by side, full height, one gap apart,
}
await expect(page.locator(TERMINAL_CARD), 'the web draws no terminal card').toHaveCount(0);
- await expect(page.locator('#terminal-dock-panel')).toHaveCount(0);
+ await expect(
+ dockUnit(page, 'terminal'),
+ 'the web never turns the terminal unit on',
+ ).toHaveAttribute('hidden', '');
await noSidewaysScroll(page);
});
diff --git a/packages/app/tests/stress/header-pane-buttons.e2e.ts b/packages/app/tests/stress/header-pane-buttons.e2e.ts
index 143b2535b..6f2bbb7dc 100644
--- a/packages/app/tests/stress/header-pane-buttons.e2e.ts
+++ b/packages/app/tests/stress/header-pane-buttons.e2e.ts
@@ -1,14 +1,15 @@
import { realpathSync } from 'node:fs';
import AxeBuilder from '@axe-core/playwright';
import type { Locator, Page } from '@playwright/test';
-import { TERMINAL_PLACEMENT_KEY } from '../../src/lib/terminal-placement-store';
import type { ApiHelpers, DesktopHeaderHost, WorkerServer } from './_helpers';
import {
+ dockUnitRect,
expect,
headerPaneButton,
openDesktopHeader,
presetTerminalPlacement,
stubAgentCatalog,
+ terminalPaneCard,
test,
waitForActiveProviderSynced,
} from './_helpers';
@@ -23,26 +24,18 @@ type Pane = 'agents' | 'terminal';
type PaneState = 'shown' | 'hidden';
const AGENTS_MOUNT = '[data-agents-panel-mount]';
-const BOTTOM_TERMINAL_PANEL = '#terminal-dock-panel';
-const RIGHT_TERMINAL_MOUNT = '[data-terminal-panel-mount]';
+const TERMINAL_MOUNT = '[data-terminal-panel-mount]';
+const TERMINAL_CARD = '[data-slot="pane-card"][data-pane="terminal"]';
const BOOT_TIMEOUT_MS = 30_000;
const DOC_TEXT = 'The quick brown fox jumps over the lazy dog.';
async function paneExtentPx(page: Page, pane: Pane): Promise<number> {
- return await page.evaluate(
- ({ pane, agentsMount, bottomPanel, rightMount }) => {
- const extent = (selector: string, axis: 'width' | 'height') =>
- document.querySelector(selector)?.getBoundingClientRect()[axis] ?? 0;
- if (pane === 'agents') return extent(agentsMount, 'width');
- return Math.max(extent(bottomPanel, 'height'), extent(rightMount, 'width'));
- },
- {
- pane,
- agentsMount: AGENTS_MOUNT,
- bottomPanel: BOTTOM_TERMINAL_PANEL,
- rightMount: RIGHT_TERMINAL_MOUNT,
- },
- );
+ const rect = await dockUnitRect(page, pane);
+ if (rect === null) return 0;
+ if (pane === 'agents') return rect.width;
+ return (await page.locator(TERMINAL_CARD).getAttribute('data-placement')) === 'bottom'
+ ? rect.height
+ : rect.width;
}
async function expectPane(page: Page, pane: Pane, state: PaneState): Promise<void> {
@@ -74,8 +67,7 @@ async function expectPaneKeepingFocus(page: Page, pane: Pane, state: PaneState):
}
async function waitForFocusInPane(page: Page, pane: Pane): Promise<void> {
- const container =
- pane === 'agents' ? AGENTS_MOUNT : `${RIGHT_TERMINAL_MOUNT}, ${BOTTOM_TERMINAL_PANEL}`;
+ const container = pane === 'agents' ? AGENTS_MOUNT : TERMINAL_MOUNT;
await expect
.poll(
() =>
@@ -174,42 +166,6 @@ async function openThread(page: Page, title: string): Promise<void> {
}, title);
}
-function handleBefore(page: Page, mount: string): Locator {
- return page
- .locator(mount)
- .locator('xpath=ancestor::*[@data-slot="resizable-panel"][1]')
- .locator('xpath=preceding-sibling::*[1]');
-}
-
-function bottomTerminalHandle(page: Page): Locator {
- return page.locator(BOTTOM_TERMINAL_PANEL).locator('xpath=preceding-sibling::*[1]');
-}
-
-async function dragHandleTo(page: Page, handle: Locator, x: number, y: number): Promise<void> {
- await expect(handle).toHaveAttribute('data-slot', 'resizable-handle');
- const bounds = await handle.boundingBox();
- if (bounds === null) throw new Error('the resize handle has no layout bounds');
- await page.mouse.move(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2);
- await page.mouse.down();
- await expect(page.locator('[data-dragging="true"]')).toHaveCount(1);
- await page.mouse.move(x, y, { steps: 10 });
- await page.mouse.up();
- await expect(page.locator('[data-dragging="true"]')).toHaveCount(0);
-}
-
-async function handleCenter(handle: Locator): Promise<{ x: number; y: number }> {
- const bounds = await handle.boundingBox();
- if (bounds === null) throw new Error('the resize handle has no layout bounds');
- return { x: bounds.x + bounds.width / 2, y: bounds.y + bounds.height / 2 };
-}
-
-async function collapseWithKeyboard(handle: Locator, key: 'Home' | 'End'): Promise<void> {
- await expect(handle).toHaveAttribute('data-slot', 'resizable-handle');
- await handle.focus();
- await expect(handle).toBeFocused();
- await handle.press(key);
-}
-
function viewportOf(page: Page): { width: number; height: number } {
const viewport = page.viewportSize();
if (viewport === null) throw new Error('the page has no viewport');
@@ -572,28 +528,6 @@ test.describe('the Agents button follows every chat show/hide path on the web',
await expectPane(page, 'agents', 'shown');
});
- test('dragging chat below its minimum width hides it', async ({ page, api }) => {
- await openWeb(page, api, 'drag-chat');
- await clickPaneButton(page, 'agents', 'shown');
- const handle = handleBefore(page, AGENTS_MOUNT);
- const { y } = await handleCenter(handle);
- await dragHandleTo(page, handle, viewportOf(page).width - 100, y);
- await expectPane(page, 'agents', 'hidden');
- });
-
- test('chat collapsed to zero with the keyboard reads off, and one click brings it back', async ({
- page,
- api,
- }) => {
- await openWeb(page, api, 'keyboard-chat');
- await clickPaneButton(page, 'agents', 'shown');
- await waitForFocusInPane(page, 'agents');
- const preferredWidth = await paneExtentPx(page, 'agents');
- await collapseWithKeyboard(handleBefore(page, AGENTS_MOUNT), 'Home');
- await expectPaneKeepingFocus(page, 'agents', 'hidden');
- await bringBackWithOneClick(page, 'agents', preferredWidth);
- });
-
test('a web reload keeps the button matching chat', async ({ page, api }) => {
await openWeb(page, api, 'reload');
await clickPaneButton(page, 'agents', 'shown');
@@ -666,9 +600,7 @@ test.describe('the Terminal button follows every terminal show/hide path on the
await expect(page.locator('[data-pane="editor"]')).toBeVisible();
await expectPane(page, 'agents', 'shown');
await expectPane(page, 'terminal', 'hidden');
- expect(await page.evaluate((key) => localStorage.getItem(key), TERMINAL_PLACEMENT_KEY)).toBe(
- 'bottom',
- );
+ await expect(page.locator(TERMINAL_CARD)).toHaveAttribute('data-placement', 'bottom');
await page.setViewportSize({ width: 767, height: 800 });
await expectPane(page, 'terminal', 'shown');
await expect(page.locator('[data-pane="editor"]')).toBeHidden();
@@ -724,56 +656,6 @@ test.describe('the Terminal button follows every terminal show/hide path on the
});
}
- test('dragging the bottom terminal to nothing hides it', async ({ page, api, workerServer }) => {
- await presetTerminalPlacement(page, 'bottom');
- await openDesktop(page, api, workerServer, 'drag-bottom');
- await clickPaneButton(page, 'terminal', 'shown');
- const handle = bottomTerminalHandle(page);
- const { x } = await handleCenter(handle);
- await dragHandleTo(page, handle, x, viewportOf(page).height - 2);
- await expectPane(page, 'terminal', 'hidden');
- });
-
- test('dragging the right terminal to nothing hides it', async ({ page, api, workerServer }) => {
- await presetTerminalPlacement(page, 'right');
- await openDesktop(page, api, workerServer, 'drag-right');
- await clickPaneButton(page, 'terminal', 'shown');
- const handle = handleBefore(page, RIGHT_TERMINAL_MOUNT);
- const { y } = await handleCenter(handle);
- await dragHandleTo(page, handle, viewportOf(page).width - 2, y);
- await expectPane(page, 'terminal', 'hidden');
- });
-
- test('a right terminal collapsed to zero with the keyboard reads off, and one click brings it back', async ({
- page,
- api,
- workerServer,
- }) => {
- await presetTerminalPlacement(page, 'right');
- await openDesktop(page, api, workerServer, 'keyboard-right');
- await clickPaneButton(page, 'terminal', 'shown');
- await waitForFocusInPane(page, 'terminal');
- const preferredWidth = await paneExtentPx(page, 'terminal');
- await collapseWithKeyboard(handleBefore(page, RIGHT_TERMINAL_MOUNT), 'Home');
- await expectPaneKeepingFocus(page, 'terminal', 'hidden');
- await bringBackWithOneClick(page, 'terminal', preferredWidth);
- });
-
- test('a bottom terminal collapsed to zero with the keyboard reads off, and one click brings it back', async ({
- page,
- api,
- workerServer,
- }) => {
- await presetTerminalPlacement(page, 'bottom');
- await openDesktop(page, api, workerServer, 'keyboard-bottom');
- await clickPaneButton(page, 'terminal', 'shown');
- await waitForFocusInPane(page, 'terminal');
- const preferredHeight = await paneExtentPx(page, 'terminal');
- await collapseWithKeyboard(bottomTerminalHandle(page), 'Home');
- await expectPaneKeepingFocus(page, 'terminal', 'hidden');
- await bringBackWithOneClick(page, 'terminal', preferredHeight);
- });
-
test('a terminal launch from Open with AI shows the terminal and keeps it shown', async ({
page,
api,
@@ -835,13 +717,14 @@ test.describe('the Terminal button follows every terminal show/hide path on the
await openDesktop(page, api, workerServer, 'move');
await clickPaneButton(page, 'terminal', 'shown');
await waitForFocusInPane(page, 'terminal');
- await expect(page.locator(BOTTOM_TERMINAL_PANEL)).toBeVisible();
+ await expect(page.locator(terminalPaneCard('bottom'))).toBeVisible();
await runPalette(page, 'move terminal', 'move-terminal');
- await expect(page.locator(RIGHT_TERMINAL_MOUNT)).toBeVisible();
+ await expect(page.locator(terminalPaneCard('right'))).toBeVisible();
+ await expect(page.locator(terminalPaneCard('bottom'))).toHaveCount(0);
await expectPane(page, 'terminal', 'shown');
await runPalette(page, 'move terminal', 'move-terminal');
- await expect(page.locator(BOTTOM_TERMINAL_PANEL)).toBeVisible();
- await expect(page.locator(RIGHT_TERMINAL_MOUNT)).toBeHidden();
+ await expect(page.locator(terminalPaneCard('bottom'))).toBeVisible();
+ await expect(page.locator(terminalPaneCard('right'))).toHaveCount(0);
await expectPane(page, 'terminal', 'shown');
});
});
@@ -889,7 +772,7 @@ test.describe('the Agents button on the mocked desktop', () => {
.toBeGreaterThanOrEqual(300);
});
- test('information yields before a right Terminal is closed when Chat opens', async ({
+ test('information yields while a right Terminal stays open when Chat opens', async ({
page,
api,
workerServer,
@@ -1243,68 +1126,61 @@ interface FrameSamplerWindow {
}
async function startFrameSampler(page: Page): Promise<void> {
- await page.evaluate(
- ({ agentsMount, bottomPanel, rightMount }) => {
- const hasArea = (element: Element | null) => {
- if (element === null) return false;
- const { width, height } = element.getBoundingClientRect();
- return width > 0 && height > 0;
- };
- const paneOnScreen = {
- agents: () => hasArea(document.querySelector(agentsMount)),
- terminal: () =>
- hasArea(document.querySelector(bottomPanel)) ||
- hasArea(document.querySelector(rightMount)),
- };
- const frames: Array<Partial<Record<'agents' | 'terminal', SampledPane>>> = [];
- let frame = -1;
- let running = true;
- const sample = () => {
- if (!running || frame < 0) return;
- const record: Partial<Record<'agents' | 'terminal', SampledPane>> = {};
- for (const pane of ['agents', 'terminal'] as const) {
- const button = document.querySelector(`[data-testid="header-pane-button-${pane}"]`);
- if (button === null) continue;
- record[pane] = {
- pressed: button.getAttribute('aria-pressed') === 'true',
- onScreen: paneOnScreen[pane](),
- };
- }
- frames[frame] = record;
- };
- const observer = new ResizeObserver(sample);
- const observed = new Set<Element>();
- const observeTargets = () => {
- for (const selector of [agentsMount, bottomPanel, rightMount]) {
- for (const element of document.querySelectorAll(selector)) {
- if (observed.has(element)) continue;
- observed.add(element);
- observer.observe(element);
- }
- }
- };
- const tick = () => {
- if (!running) return;
- frame += 1;
- observeTargets();
- sample();
- requestAnimationFrame(tick);
- };
+ await page.evaluate(() => {
+ const unitOf = (pane: 'agents' | 'terminal') =>
+ document.querySelector(`[data-dock-unit="${pane}"]`);
+ const paneOnScreen = (pane: 'agents' | 'terminal') => {
+ const unit = unitOf(pane);
+ if (!(unit instanceof HTMLElement) || unit.hidden) return false;
+ if (unit.hasAttribute('data-dock-unit-off')) return false;
+ const { width, height } = unit.getBoundingClientRect();
+ return width > 0 && height > 0;
+ };
+ const frames: Array<Partial<Record<'agents' | 'terminal', SampledPane>>> = [];
+ let frame = -1;
+ let running = true;
+ const sample = () => {
+ if (!running || frame < 0) return;
+ const record: Partial<Record<'agents' | 'terminal', SampledPane>> = {};
+ for (const pane of ['agents', 'terminal'] as const) {
+ const button = document.querySelector(`[data-testid="header-pane-button-${pane}"]`);
+ if (button === null) continue;
+ record[pane] = {
+ pressed: button.getAttribute('aria-pressed') === 'true',
+ onScreen: paneOnScreen(pane),
+ };
+ }
+ frames[frame] = record;
+ };
+ const observer = new MutationObserver(sample);
+ const observed = new Set<Element>();
+ const observeTargets = () => {
+ for (const pane of ['agents', 'terminal'] as const) {
+ const unit = unitOf(pane);
+ if (unit === null || observed.has(unit)) continue;
+ observed.add(unit);
+ observer.observe(unit, {
+ attributes: true,
+ attributeFilter: ['hidden', 'data-dock-unit-off', 'style'],
+ });
+ }
+ };
+ const tick = () => {
+ if (!running) return;
+ frame += 1;
+ observeTargets();
+ sample();
requestAnimationFrame(tick);
- (window as FrameSamplerWindow).__paneFrameSampler = {
- stop: () => {
- running = false;
- observer.disconnect();
- return frames;
- },
- };
- },
- {
- agentsMount: AGENTS_MOUNT,
- bottomPanel: BOTTOM_TERMINAL_PANEL,
- rightMount: RIGHT_TERMINAL_MOUNT,
- },
- );
+ };
+ requestAnimationFrame(tick);
+ (window as FrameSamplerWindow).__paneFrameSampler = {
+ stop: () => {
+ running = false;
+ observer.disconnect();
+ return frames;
+ },
+ };
+ });
await settleFrames(page);
}
@@ -1347,7 +1223,7 @@ async function expectEveryFrameMatches(page: Page, panes: readonly Pane[]): Prom
}
test.describe('the pane buttons match their panes in every frame', () => {
- test('chat: header show and hide, an agent auto-open, a keyboard collapse to zero and a one-click bring-back', async ({
+ test('chat: header show and hide, an agent auto-open, a header hide and a one-click bring-back', async ({
page,
api,
}) => {
@@ -1359,15 +1235,14 @@ test.describe('the pane buttons match their panes in every frame', () => {
await clickPaneButton(page, 'agents', 'hidden');
await openThread(page, 'Frame sampler thread');
await expectPane(page, 'agents', 'shown');
- await collapseWithKeyboard(handleBefore(page, AGENTS_MOUNT), 'Home');
- await expectPane(page, 'agents', 'hidden');
+ await clickPaneButton(page, 'agents', 'hidden');
await bringBackWithOneClick(page, 'agents', preferredWidth);
await expectEveryFrameMatches(page, ['agents']);
});
for (const placement of ['bottom', 'right'] as const) {
- test(`${placement} terminal: header show, a keyboard collapse to zero, a one-click bring-back and a header hide`, async ({
+ test(`${placement} terminal: header show and hide, a one-click bring-back and a header hide`, async ({
page,
api,
workerServer,
@@ -1379,13 +1254,7 @@ test.describe('the pane buttons match their panes in every frame', () => {
await clickPaneButton(page, 'terminal', 'shown');
await waitForFocusInPane(page, 'terminal');
const preferredExtent = await paneExtentPx(page, 'terminal');
- await collapseWithKeyboard(
- placement === 'bottom'
- ? bottomTerminalHandle(page)
- : handleBefore(page, RIGHT_TERMINAL_MOUNT),
- 'Home',
- );
- await expectPane(page, 'terminal', 'hidden');
+ await clickPaneButton(page, 'terminal', 'hidden');
await bringBackWithOneClick(page, 'terminal', preferredExtent);
await clickPaneButton(page, 'terminal', 'hidden');
diff --git a/packages/app/tests/stress/hidden-chat-activity.e2e.ts b/packages/app/tests/stress/hidden-chat-activity.e2e.ts
index acf1caa90..712746304 100644
--- a/packages/app/tests/stress/hidden-chat-activity.e2e.ts
+++ b/packages/app/tests/stress/hidden-chat-activity.e2e.ts
@@ -1,5 +1,5 @@
import { randomUUID } from 'node:crypto';
-import { acpCatalogBody, expect, test, waitForActiveProviderSynced } from './_helpers';
+import { acpCatalogBody, dockUnit, expect, test, waitForActiveProviderSynced } from './_helpers';
import { startHiddenChatAgent } from './hidden-chat-transport.test-helper';
const EDITOR_CARD = '[data-slot="pane-card"][data-pane="editor"]';
@@ -61,7 +61,7 @@ test('hidden Chat retains a live draft and unread completed stream until the thr
await editorButton.click();
await expect(page.locator(EDITOR_CARD)).toBeVisible();
await expect(chatCard).toBeHidden();
- await expect(chatCard).toHaveAttribute('inert', '');
+ await expect(dockUnit(page, 'agents')).toHaveAttribute('inert', '');
fixture.release();
await fixture.waitForFinalChunk();
fixture.finish();
diff --git a/packages/app/tests/stress/rail-flex-distribution-law.e2e.ts b/packages/app/tests/stress/rail-flex-distribution-law.e2e.ts
index cc65ddc71..1a061faf8 100644
--- a/packages/app/tests/stress/rail-flex-distribution-law.e2e.ts
+++ b/packages/app/tests/stress/rail-flex-distribution-law.e2e.ts
@@ -1,39 +1,31 @@
import type { Page } from '@playwright/test';
-import { AGENTS_COLUMN_ID, DOC_PANEL_ID } from '../../src/components/editor-area-rail-registry';
+import { DOC_PANEL_ID } from '../../src/components/editor-area-rail-registry';
import { acpCatalogBody, expect, test, waitForActiveProviderSynced } from './_helpers';
-const OUTER_ROW_SELECTOR = '[data-editor-area-panels] > [data-group]';
-const INNER_ROW_SELECTOR = '[data-editor-inner-panels] > [data-group]';
-const ROWS = [
- { name: 'outer', selector: OUTER_ROW_SELECTOR, pinnedPanelId: AGENTS_COLUMN_ID },
- { name: 'inner', selector: INNER_ROW_SELECTOR, pinnedPanelId: DOC_PANEL_ID },
-] as const;
-const AGENTS_PANEL_MOUNT = '[data-agents-panel-mount]';
-const AGENTS_HEADER_BUTTON = 'header-pane-button-agents';
+const ROW_SELECTOR = '[data-editor-inner-panels] > [data-group]';
const VIEWPORT_HEIGHT = 800;
const SWEEP_VIEWPORT_WIDTHS = [1281, 1367, 1451, 1610, 1687, 1733, 1813, 1953, 1960] as const;
const PROPORTIONALITY_TOLERANCE_PX = 0.25;
const MIN_RENDERED_ROW_PANELS = 2;
-const BOOT_TIMEOUT_MS = 30_000;
const LAYOUT_SETTLE_TIMEOUT_MS = 10_000;
const DOC_MARKDOWN = `---
title: "Rail flex distribution"
-description: "Fixture doc for the rail flex-distribution law"
+description: "Fixture doc for the document row flex-distribution law"
---
# Rail flex distribution
-Body text so the editor column renders real content while the rail is measured.`;
+Body text so the editor column renders real content while the row is measured.`;
-interface RailPanelSample {
+interface RowPanelSample {
readonly id: string;
readonly widthPx: number;
readonly flexGrow: number;
}
-async function readRowPanels(page: Page, selector: string): Promise<RailPanelSample[]> {
+async function readRowPanels(page: Page): Promise<RowPanelSample[]> {
return page.evaluate((selector) => {
const group = document.querySelector(selector);
if (group == null) return [];
@@ -44,27 +36,25 @@ async function readRowPanels(page: Page, selector: string): Promise<RailPanelSam
flexGrow: Number.parseFloat(panel.style.flexGrow || '0'),
}),
);
- }, selector);
+ }, ROW_SELECTOR);
}
-async function railSpacePx(page: Page): Promise<number> {
- const panels = await readRowPanels(page, OUTER_ROW_SELECTOR);
+async function rowSpacePx(page: Page): Promise<number> {
+ const panels = await readRowPanels(page);
return panels.reduce((total, panel) => total + panel.widthPx, 0);
}
-async function openAgentsColumn(page: Page): Promise<void> {
- const agentsButton = page.getByTestId(AGENTS_HEADER_BUTTON);
- await expect(agentsButton).toHaveAttribute('aria-pressed', 'false', { timeout: BOOT_TIMEOUT_MS });
- await agentsButton.click();
- await expect(agentsButton).toHaveAttribute('aria-pressed', 'true');
- await expect(page.locator(AGENTS_PANEL_MOUNT)).toBeVisible({ timeout: BOOT_TIMEOUT_MS });
+async function settleFrames(page: Page): Promise<void> {
+ await page.evaluate(
+ () => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))),
+ );
}
test.beforeEach(async ({ page }) => {
await page.route('**/api/acp/catalog', (route) => route.fulfill({ json: acpCatalogBody([]) }));
});
-test.describe('right rail flex distribution law', () => {
- test('rendered rail widths stay proportional to flex-grow across a viewport sweep', async ({
+test.describe('document panel row flex distribution law', () => {
+ test('rendered document row widths stay proportional to flex-grow across a viewport sweep', async ({
page,
api,
}) => {
@@ -73,7 +63,6 @@ test.describe('right rail flex distribution law', () => {
await page.setViewportSize({ width: SWEEP_VIEWPORT_WIDTHS[0], height: VIEWPORT_HEIGHT });
await page.goto(`/#/${docName}`);
await waitForActiveProviderSynced(page);
- await openAgentsColumn(page);
const filesToggle = page.locator('[data-sidebar="trigger"]').first();
if ((await filesToggle.getAttribute('aria-expanded')) === 'true') await filesToggle.click();
await expect(filesToggle).toHaveAttribute('aria-expanded', 'false');
@@ -84,55 +73,43 @@ test.describe('right rail flex distribution law', () => {
for (const viewportWidth of SWEEP_VIEWPORT_WIDTHS) {
await page.setViewportSize({ width: viewportWidth, height: VIEWPORT_HEIGHT });
await expect
- .poll(() => railSpacePx(page), { timeout: LAYOUT_SETTLE_TIMEOUT_MS })
+ .poll(() => rowSpacePx(page), { timeout: LAYOUT_SETTLE_TIMEOUT_MS })
.not.toBe(previousSpacePx);
- await page.evaluate(
- () => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))),
- );
-
- const outerPanels = await readRowPanels(page, OUTER_ROW_SELECTOR);
- previousSpacePx = outerPanels.reduce((total, panel) => total + panel.widthPx, 0);
-
- for (const row of ROWS) {
- await expect
- .poll(
- async () =>
- (await readRowPanels(page, row.selector)).filter((panel) => panel.widthPx > 1).length,
- { timeout: LAYOUT_SETTLE_TIMEOUT_MS },
- )
- .toBeGreaterThanOrEqual(MIN_RENDERED_ROW_PANELS);
- await page.evaluate(
- () =>
- new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))),
- );
- const panels = await readRowPanels(page, row.selector);
- const spacePx = panels.reduce((total, panel) => total + panel.widthPx, 0);
- const totalGrow = panels.reduce((total, panel) => total + panel.flexGrow, 0);
- const renderedPanels = panels.filter((panel) => panel.widthPx > 1);
- const pinnedPanel = panels.find((panel) => panel.id === row.pinnedPanelId);
-
- expect(
- totalGrow,
- `viewport ${viewportWidth}, ${row.name} row: the row's panels must carry flex-grow for the law to say anything`,
- ).toBeGreaterThan(0);
- expect(
- renderedPanels.length,
- `viewport ${viewportWidth}, ${row.name} row: the law only constrains a row that is splitting its space across several rendered panels`,
- ).toBeGreaterThanOrEqual(MIN_RENDERED_ROW_PANELS);
+ await expect
+ .poll(async () => (await readRowPanels(page)).filter((panel) => panel.widthPx > 1).length, {
+ timeout: LAYOUT_SETTLE_TIMEOUT_MS,
+ })
+ .toBeGreaterThanOrEqual(MIN_RENDERED_ROW_PANELS);
+ await settleFrames(page);
+
+ const panels = await readRowPanels(page);
+ const spacePx = panels.reduce((total, panel) => total + panel.widthPx, 0);
+ previousSpacePx = spacePx;
+ const totalGrow = panels.reduce((total, panel) => total + panel.flexGrow, 0);
+ const renderedPanels = panels.filter((panel) => panel.widthPx > 1);
+ const pinnedPanel = panels.find((panel) => panel.id === DOC_PANEL_ID);
+
+ expect(
+ totalGrow,
+ `viewport ${viewportWidth}: the row's panels must carry flex-grow for the law to say anything`,
+ ).toBeGreaterThan(0);
+ expect(
+ renderedPanels.length,
+ `viewport ${viewportWidth}: the law only constrains a row that is splitting its space across several rendered panels`,
+ ).toBeGreaterThanOrEqual(MIN_RENDERED_ROW_PANELS);
+ expect(
+ pinnedPanel?.widthPx ?? 0,
+ `viewport ${viewportWidth}: the px-pinned document panel (${DOC_PANEL_ID}) must be open so the sweep measures it beside a residual one`,
+ ).toBeGreaterThan(0);
+
+ if (panels.some((panel) => !Number.isInteger(panel.widthPx))) subPixelSplitSamples += 1;
+
+ for (const panel of panels) {
+ const modelledPx = (panel.flexGrow / totalGrow) * spacePx;
expect(
- pinnedPanel?.widthPx ?? 0,
- `viewport ${viewportWidth}, ${row.name} row: the px-pinned column (${row.pinnedPanelId}) must be open so the sweep measures it beside a residual one`,
- ).toBeGreaterThan(0);
-
- if (panels.some((panel) => !Number.isInteger(panel.widthPx))) subPixelSplitSamples += 1;
-
- for (const panel of panels) {
- const modelledPx = (panel.flexGrow / totalGrow) * spacePx;
- expect(
- Math.abs(panel.widthPx - modelledPx),
- `viewport ${viewportWidth}, ${row.name} row, panel ${panel.id}: the real engine rendered ${panel.widthPx}px, but distributing the row's ${spacePx}px in proportion to flex-grow ${panel.flexGrow} of ${totalGrow} predicts ${modelledPx}px. The jsdom panel-space tier derives rail widths from exactly this formula, so a divergence here means that model no longer describes the browser and every DOM-tier rail width is measuring a fiction.`,
- ).toBeLessThanOrEqual(PROPORTIONALITY_TOLERANCE_PX);
- }
+ Math.abs(panel.widthPx - modelledPx),
+ `viewport ${viewportWidth}, panel ${panel.id}: the real engine rendered ${panel.widthPx}px, but distributing the row's ${spacePx}px in proportion to flex-grow ${panel.flexGrow} of ${totalGrow} predicts ${modelledPx}px. The jsdom panel-space tier derives document row widths from exactly this formula, so a divergence here means that model no longer describes the browser and every DOM-tier row width is measuring a fiction.`,
+ ).toBeLessThanOrEqual(PROPORTIONALITY_TOLERANCE_PX);
}
}
diff --git a/packages/app/tests/stress/responsive-cycles-release-editor-callback-contexts.e2e.ts b/packages/app/tests/stress/responsive-cycles-release-editor-callback-contexts.e2e.ts
index e8f9deed9..af612d7ea 100644
--- a/packages/app/tests/stress/responsive-cycles-release-editor-callback-contexts.e2e.ts
+++ b/packages/app/tests/stress/responsive-cycles-release-editor-callback-contexts.e2e.ts
@@ -92,14 +92,14 @@ function retainedContextDepth(path: string, docNames: string[]) {
);
expect(refs).toHaveLength(1);
- const terminalHandles: number[] = [];
+ const docPanelHandles: number[] = [];
for (let index = 0; index < nodeCount; index++) {
- if (nodeType(index) === 'native' && nodeName(index)?.includes('data-terminal-panel-handle')) {
- terminalHandles.push(index);
+ if (nodeType(index) === 'native' && nodeName(index)?.includes('data-doc-panel-handle')) {
+ docPanelHandles.push(index);
}
}
- expect(terminalHandles).toHaveLength(1);
- const terminalHandleCallbacks = terminalHandles.flatMap((handle) =>
+ expect(docPanelHandles).toHaveLength(1);
+ const docPanelHandleCallbacks = docPanelHandles.flatMap((handle) =>
outgoing(handle)
.filter((edge) => edge.type === 'property' && edge.name?.startsWith('__reactFiber$'))
.flatMap((edge) =>
@@ -117,7 +117,7 @@ function retainedContextDepth(path: string, docNames: string[]) {
),
),
);
- expect(terminalHandleCallbacks).toHaveLength(1);
+ expect(docPanelHandleCallbacks).toHaveLength(1);
const editorAreaPanels: number[] = [];
for (let index = 0; index < nodeCount; index++) {
@@ -268,8 +268,8 @@ function retainedContextDepth(path: string, docNames: string[]) {
);
return {
files: depthFrom(refs),
- terminalHandle: depthFrom(
- terminalHandleCallbacks,
+ docPanelHandle: depthFrom(
+ docPanelHandleCallbacks,
process.env.QA101_CONTEXT_CHAIN_TRACE === '1',
),
editorAreaDestination: depthFrom(
@@ -547,7 +547,7 @@ test('responsive cycles release prior editor callback contexts', async ({
expect.soft(after.pageHeadings.maxDepth - before.pageHeadings.maxDepth).toBeLessThanOrEqual(8);
expect.soft(after.files.maxDepth - before.files.maxDepth).toBeLessThanOrEqual(8);
expect
- .soft(after.terminalHandle.maxDepth - before.terminalHandle.maxDepth)
+ .soft(after.docPanelHandle.maxDepth - before.docPanelHandle.maxDepth)
.toBeLessThanOrEqual(8);
expect
.soft(after.editorAreaDestination.maxDepth - before.editorAreaDestination.maxDepth)
diff --git a/packages/desktop/tests/smoke/_helpers/dock-height-settlement.uncached.test.ts b/packages/desktop/tests/smoke/_helpers/dock-height-settlement.uncached.test.ts
index 9153559f0..34b0eb07c 100644
--- a/packages/desktop/tests/smoke/_helpers/dock-height-settlement.uncached.test.ts
+++ b/packages/desktop/tests/smoke/_helpers/dock-height-settlement.uncached.test.ts
@@ -14,7 +14,7 @@ const ts: typeof TypeScript = createRequire(
const heightBefore = 300;
const heightAfter = heightBefore + 160;
-const reopenedHeightTolerance = 40;
+const restoredHeightTolerance = 2;
function currentDockHeightWait(label: string): string {
const path = fileURLToPath(new URL('../terminal-dock.e2e.ts', import.meta.url));
@@ -27,7 +27,7 @@ function currentDockHeightWait(label: string): string {
ts.isIdentifier(node.expression) &&
node.expression.text === 'test' &&
ts.isStringLiteral(node.arguments[0]) &&
- node.arguments[0].text === 'QA-023 panel height persists across reopen'
+ node.arguments[0].text === 'QA-023 panel height persists across reopen and reload'
) {
dockTest = node;
}
@@ -66,7 +66,7 @@ function currentDockHeightWait(label: string): string {
return waits[0].getText(parsed);
}
-function runCurrentDockWait(label: string, panelHeight: number, persistedHeight: number) {
+function runCurrentDockWait(label: string, panelHeight: number) {
const source = currentDockHeightWait(label);
const path = fileURLToPath(new URL('../terminal-dock.e2e.ts', import.meta.url));
let releaseRead: (() => void) | undefined;
@@ -86,23 +86,10 @@ function runCurrentDockWait(label: string, panelHeight: number, persistedHeight:
}) as number;
},
};
- const page = {
- async evaluate(callback: () => number): Promise<number> {
- markReadStarted?.();
- await reading;
- return runInNewContext(`(${callback.toString()})()`, {
- localStorage: {
- getItem: (key: string) =>
- key === 'ok-terminal-height-v1' ? String(persistedHeight) : null,
- },
- }) as number;
- },
- };
const bindings = {
...settledReading,
expect: playwrightExpect,
panel,
- page,
heightBefore,
heightAfter,
};
@@ -121,17 +108,13 @@ function runCurrentDockWait(label: string, panelHeight: number, persistedHeight:
afterEach(() => vi.useRealTimers());
-test.each(['height', 'persisted height', 'reopened height difference'])(
+test.each(['height', 'reopened height difference', 'reloaded height difference'])(
'%s settles when its dimension read completes within the layout budget',
async (label) => {
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] });
- const { result, readStarted, releaseRead } = runCurrentDockWait(
- label,
- heightAfter,
- heightAfter,
- );
+ const { result, readStarted, releaseRead } = runCurrentDockWait(label, heightAfter);
await readStarted;
- await vi.advanceTimersByTimeAsync(settledReading.RAIL_LAYOUT_SETTLE_TIMEOUT_MS - 1);
+ await vi.advanceTimersByTimeAsync(settledReading.LAYOUT_SETTLE_TIMEOUT_MS - 1);
releaseRead?.();
expect(await result).toBe('settled');
@@ -139,27 +122,27 @@ test.each(['height', 'persisted height', 'reopened height difference'])(
);
test.each([
- ['height', heightBefore, heightAfter, 'toBeGreaterThan', heightBefore],
- ['persisted height', heightAfter, heightBefore, 'toBeGreaterThan', heightBefore],
+ ['height', heightBefore, 'toBeGreaterThan', heightBefore],
[
'reopened height difference',
- heightAfter + reopenedHeightTolerance,
- heightAfter,
+ heightAfter + restoredHeightTolerance,
'toBeLessThan',
- reopenedHeightTolerance,
+ restoredHeightTolerance,
+ ],
+ [
+ 'reloaded height difference',
+ heightAfter + restoredHeightTolerance,
+ 'toBeLessThan',
+ restoredHeightTolerance,
],
] as const)(
'%s rejects a completed reading exactly on its strict boundary',
- async (label, panelHeight, persistedHeight, matcher, boundary) => {
+ async (label, panelHeight, matcher, boundary) => {
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] });
- const { result, readStarted, releaseRead } = runCurrentDockWait(
- label,
- panelHeight,
- persistedHeight,
- );
+ const { result, readStarted, releaseRead } = runCurrentDockWait(label, panelHeight);
releaseRead?.();
await readStarted;
- await vi.advanceTimersByTimeAsync(settledReading.RAIL_LAYOUT_SETTLE_TIMEOUT_MS + 1);
+ await vi.advanceTimersByTimeAsync(settledReading.LAYOUT_SETTLE_TIMEOUT_MS + 1);
const outcome = await result;
expect(outcome).toBeInstanceOf(Error);
diff --git a/packages/desktop/tests/smoke/_helpers/dock-reveal-latency.test.ts b/packages/desktop/tests/smoke/_helpers/dock-reveal-latency.test.ts
index 7dff5fd9a..e3423f883 100644
--- a/packages/desktop/tests/smoke/_helpers/dock-reveal-latency.test.ts
+++ b/packages/desktop/tests/smoke/_helpers/dock-reveal-latency.test.ts
@@ -12,9 +12,9 @@ import {
const ARMED_AT = 1_000;
const REVEAL_SPAN_MS = 5;
const SLOW_TRIGGER_MS = 120;
-const PANEL_ID = 'terminal-dock-panel';
-const COLLAPSED = { width: 1280, height: 0 };
-const EXPANDED = { width: 1280, height: 300 };
+const UNIT_ID = 'dock-unit-terminal';
+const ZERO_SIZE = { width: 0, height: 0 };
+const SHOWN = { width: 1280, height: 300 };
const sleep = (ms: number): Promise<void> =>
new Promise((resolve) => {
@@ -27,31 +27,34 @@ const armed = (over: Partial<DockRevealSample> = {}): DockRevealSample => ({
...over,
});
-interface FakePanel {
+interface FakeUnit {
box: { width: number; height: number };
visibility: string;
passesCheckVisibility: boolean;
}
-const fakePanel = (over: Partial<FakePanel> = {}): FakePanel => ({
- box: { ...COLLAPSED },
+const fakeUnit = (over: Partial<FakeUnit> = {}): FakeUnit => ({
+ box: { ...SHOWN },
visibility: 'visible',
passesCheckVisibility: true,
...over,
});
-function mountFakeRenderer(panel: FakePanel | null, clock: { now: number }) {
+const neverShownUnit = (): FakeUnit =>
+ fakeUnit({ box: { ...ZERO_SIZE }, passesCheckVisibility: false });
+
+function mountFakeRenderer(unit: FakeUnit | null, clock: { now: number }) {
const element =
- panel === null
+ unit === null
? null
: {
- checkVisibility: () => panel.passesCheckVisibility,
- getBoundingClientRect: () => panel.box,
+ checkVisibility: () => unit.passesCheckVisibility,
+ getBoundingClientRect: () => unit.box,
};
vi.stubGlobal('document', {
- getElementById: (id: string) => (id === PANEL_ID ? element : null),
+ getElementById: (id: string) => (id === UNIT_ID ? element : null),
});
- vi.stubGlobal('getComputedStyle', () => ({ visibility: panel?.visibility ?? 'hidden' }));
+ vi.stubGlobal('getComputedStyle', () => ({ visibility: unit?.visibility ?? 'hidden' }));
vi.stubGlobal('performance', { now: () => clock.now });
}
@@ -137,7 +140,7 @@ describe('dock reveal measurement', () => {
await expect(
measureDockRevealMs(
stubSteps({
- watchForReveal: () => Promise.reject(new Error('panel never mounted')),
+ watchForReveal: () => Promise.reject(new Error('dock unit never mounted')),
triggerReveal: () =>
new Promise<void>((_resolve, reject) => {
setTimeout(() => reject(new Error('View menu item missing')), 0);
@@ -146,7 +149,7 @@ describe('dock reveal measurement', () => {
),
).rejects.toThrow(/View menu item missing/u);
- expect(warn).toHaveBeenCalledWith(expect.stringContaining('panel never mounted'));
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('dock unit never mounted'));
} finally {
warn.mockRestore();
}
@@ -229,63 +232,68 @@ describe('dock reveal measurement', () => {
});
});
-describe('dock reveal probe reads the panel the way Playwright does', () => {
+describe('dock reveal probe reads the unit the way Playwright does', () => {
afterEach(() => {
vi.unstubAllGlobals();
});
- test('a collapsed zero-height panel is not revealed, though it is in the DOM', () => {
- mountFakeRenderer(fakePanel({ box: { ...COLLAPSED } }), { now: ARMED_AT });
+ test('a unit that was never shown is not revealed, though it is in the DOM', () => {
+ mountFakeRenderer(neverShownUnit(), { now: ARMED_AT });
- expect(dockRevealProbe(['arm', PANEL_ID])).toEqual({ at: ARMED_AT, revealed: false });
+ expect(dockRevealProbe(['arm', UNIT_ID])).toEqual({ at: ARMED_AT, revealed: false });
});
- test('an expanded panel at arm time is reported as already revealed', () => {
- mountFakeRenderer(fakePanel({ box: { ...EXPANDED } }), { now: ARMED_AT });
+ test('a unit shown at arm time is reported as already revealed', () => {
+ mountFakeRenderer(fakeUnit(), { now: ARMED_AT });
- expect(dockRevealProbe(['arm', PANEL_ID])).toEqual({ at: ARMED_AT, revealed: true });
+ expect(dockRevealProbe(['arm', UNIT_ID])).toEqual({ at: ARMED_AT, revealed: true });
});
- test('a poll against a still-collapsed panel yields no stamp', () => {
- mountFakeRenderer(fakePanel({ box: { ...COLLAPSED } }), { now: ARMED_AT });
+ test('a poll against a unit that is still not shown yields no stamp', () => {
+ mountFakeRenderer(neverShownUnit(), { now: ARMED_AT });
- expect(dockRevealProbe(['poll', PANEL_ID])).toBe(false);
+ expect(dockRevealProbe(['poll', UNIT_ID])).toBe(false);
});
- test('a transition-only reveal is stamped, with no DOM mutation anywhere in it', () => {
+ test('a poll stamps the first frame the unit shows, without watching for a DOM mutation', () => {
const clock = { now: ARMED_AT };
- const panel = fakePanel({ box: { ...COLLAPSED } });
- mountFakeRenderer(panel, clock);
+ const unit = neverShownUnit();
+ mountFakeRenderer(unit, clock);
- expect(dockRevealProbe(['poll', PANEL_ID])).toBe(false);
+ expect(dockRevealProbe(['poll', UNIT_ID])).toBe(false);
clock.now = ARMED_AT + REVEAL_SPAN_MS;
- panel.box = { width: 1280, height: 1 };
+ unit.passesCheckVisibility = true;
+ unit.box = { ...SHOWN };
- expect(dockRevealProbe(['poll', PANEL_ID])).toEqual({
+ expect(dockRevealProbe(['poll', UNIT_ID])).toEqual({
at: ARMED_AT + REVEAL_SPAN_MS,
revealed: true,
});
});
- test('a sized panel hidden by visibility is not revealed', () => {
- mountFakeRenderer(fakePanel({ box: { ...EXPANDED }, visibility: 'hidden' }), { now: ARMED_AT });
+ test('a unit turned off keeps its last size but is not revealed while it is invisible', () => {
+ mountFakeRenderer(fakeUnit({ visibility: 'hidden' }), { now: ARMED_AT });
- expect(dockRevealProbe(['poll', PANEL_ID])).toBe(false);
+ expect(dockRevealProbe(['poll', UNIT_ID])).toBe(false);
});
- test('a sized panel that fails checkVisibility is not revealed', () => {
- mountFakeRenderer(fakePanel({ box: { ...EXPANDED }, passesCheckVisibility: false }), {
- now: ARMED_AT,
- });
+ test('a sized unit that fails checkVisibility is not revealed', () => {
+ mountFakeRenderer(fakeUnit({ passesCheckVisibility: false }), { now: ARMED_AT });
+
+ expect(dockRevealProbe(['poll', UNIT_ID])).toBe(false);
+ });
+
+ test('a zero-size unit that passes checkVisibility is not revealed', () => {
+ mountFakeRenderer(fakeUnit({ box: { ...ZERO_SIZE } }), { now: ARMED_AT });
- expect(dockRevealProbe(['poll', PANEL_ID])).toBe(false);
+ expect(dockRevealProbe(['poll', UNIT_ID])).toBe(false);
});
- test('an absent panel is not revealed', () => {
+ test('an absent unit is not revealed', () => {
mountFakeRenderer(null, { now: ARMED_AT });
- expect(dockRevealProbe(['poll', PANEL_ID])).toBe(false);
+ expect(dockRevealProbe(['poll', UNIT_ID])).toBe(false);
});
});
@@ -299,7 +307,7 @@ describe('dock reveal watch budget', () => {
['a zero ceiling', 0],
['a NaN ceiling', Number.NaN],
])('rejects %s by naming the contract, not an already-elapsed deadline', async (_label, ms) => {
- await expect(watchForDockReveal(pageWithNoWait, PANEL_ID, ms)).rejects.toThrow(
+ await expect(watchForDockReveal(pageWithNoWait, UNIT_ID, ms)).rejects.toThrow(
/positive ceiling/u,
);
});
@@ -308,13 +316,13 @@ describe('dock reveal watch budget', () => {
expect(DOCK_REVEAL_WATCH_CEILING_MS).toBeGreaterThan(DOCK_REVEAL_BUDGET_MS);
});
- test('names the ceiling and the panel when the watch ends with no stamp', async () => {
+ test('names the ceiling and the unit when the watch ends with no stamp', async () => {
const pageThatNeverReveals = {
waitForFunction: () => Promise.reject(new Error('Timeout 2000ms exceeded')),
} as unknown as Parameters<typeof watchForDockReveal>[0];
- await expect(watchForDockReveal(pageThatNeverReveals, PANEL_ID, 2000)).rejects.toThrow(
- /terminal-dock-panel.*2000 ms ceiling/su,
+ await expect(watchForDockReveal(pageThatNeverReveals, UNIT_ID, 2000)).rejects.toThrow(
+ /dock-unit-terminal.*2000 ms ceiling/su,
);
});
@@ -325,7 +333,7 @@ describe('dock reveal watch budget', () => {
Promise.resolve({ jsonValue: () => Promise.reject(new Error(destroyed)) }),
} as unknown as Parameters<typeof watchForDockReveal>[0];
- const failure = await watchForDockReveal(pageLosingItsContext, PANEL_ID, 2000).then(
+ const failure = await watchForDockReveal(pageLosingItsContext, UNIT_ID, 2000).then(
() => new Error('the watch resolved where it had to reject'),
(error: unknown) => error,
);
@@ -339,8 +347,8 @@ describe('dock reveal watch budget', () => {
waitForFunction: () => Promise.resolve({ jsonValue: () => Promise.resolve(false) }),
} as unknown as Parameters<typeof watchForDockReveal>[0];
- await expect(watchForDockReveal(pageResolvingFalse, PANEL_ID, 2000)).rejects.toThrow(
- /resolved on a falsy sample for #terminal-dock-panel/u,
+ await expect(watchForDockReveal(pageResolvingFalse, UNIT_ID, 2000)).rejects.toThrow(
+ /resolved on a falsy sample for #dock-unit-terminal/u,
);
});
});
diff --git a/packages/desktop/tests/smoke/_helpers/dock-workspace.test.ts b/packages/desktop/tests/smoke/_helpers/dock-workspace.test.ts
new file mode 100644
index 000000000..f015210f1
--- /dev/null
+++ b/packages/desktop/tests/smoke/_helpers/dock-workspace.test.ts
@@ -0,0 +1,399 @@
+import { stripVTControlCharacters } from 'node:util';
+import type { Page } from '@playwright/test';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import {
+ expectStoredDockArrangementChanged,
+ readTerminalHome,
+ type StoredDockArrangement,
+ storedDockArrangement,
+ storedDockArrangementsProbe,
+ type TerminalHome,
+ terminalHomeProbe,
+} from './dock-workspace';
+import { settleBudget } from './settled-reading';
+
+interface Box {
+ readonly left: number;
+ readonly top: number;
+ readonly width: number;
+ readonly height: number;
+}
+
+interface FakeElement {
+ readonly visibility: string;
+ readonly textContent: string | null;
+ checkVisibility(): boolean;
+ getBoundingClientRect(): Box & { readonly right: number; readonly bottom: number };
+ getAttribute(name: string): string | null;
+ querySelector(selector: string): FakeElement | null;
+ querySelectorAll(selector: string): readonly FakeElement[];
+}
+
+interface FakeElementSpec {
+ readonly box?: Box;
+ readonly displayed?: boolean;
+ readonly visibility?: 'visible' | 'hidden';
+ readonly attributes?: Readonly<Record<string, string>>;
+ readonly descendants?: Readonly<Record<string, readonly FakeElement[]>>;
+ readonly textContent?: string;
+}
+
+interface SessionSpec {
+ readonly shown: boolean;
+ readonly rows: string;
+}
+
+type TerminalUnitSpec = { readonly box: Box; readonly state: 'shown' | 'off' } | 'never';
+
+interface WorkspaceSpec {
+ readonly editor: Box | 'off';
+ readonly terminal: TerminalUnitSpec;
+ readonly placement: TerminalHome;
+ readonly sessions?: readonly SessionSpec[];
+}
+
+const ZERO: Box = { left: 0, top: 0, width: 0, height: 0 };
+const EDITOR_BESIDE_RIGHT: Box = { left: 0, top: 0, width: 1200, height: 860 };
+const RIGHT_TERMINAL: Box = { left: 1208, top: 0, width: 500, height: 860 };
+const EDITOR_ABOVE_BOTTOM: Box = { left: 0, top: 0, width: 1400, height: 560 };
+const BOTTOM_TERMINAL: Box = { left: 0, top: 568, width: 1400, height: 292 };
+const LIVE_SESSION: SessionSpec = { shown: true, rows: '% echo ready' };
+const DECLARED_BOUND_MS = 300;
+const MOVED_ARRANGEMENT: StoredDockArrangement = {
+ key: 'ok-dock-arrangement-v1:3f2a',
+ value: '{"moved":true}',
+};
+const RESIZED_ARRANGEMENT: StoredDockArrangement = {
+ key: MOVED_ARRANGEMENT.key,
+ value: '{"resized":true}',
+};
+
+function fakeElement({
+ box = ZERO,
+ displayed = true,
+ visibility = 'visible',
+ attributes = {},
+ descendants = {},
+ textContent,
+}: FakeElementSpec = {}): FakeElement {
+ return {
+ visibility,
+ textContent: textContent ?? null,
+ checkVisibility: () => displayed,
+ getBoundingClientRect: () => ({
+ ...box,
+ right: box.left + box.width,
+ bottom: box.top + box.height,
+ }),
+ getAttribute: (name) => attributes[name] ?? null,
+ querySelector: (selector) => descendants[selector]?.[0] ?? null,
+ querySelectorAll: (selector) => descendants[selector] ?? [],
+ };
+}
+
+function mountWorkspace({
+ editor,
+ terminal,
+ placement,
+ sessions = [LIVE_SESSION],
+}: WorkspaceSpec): void {
+ const terminalVisibility =
+ terminal !== 'never' && terminal.state === 'off' ? 'hidden' : 'visible';
+ const sectionElements = sessions.map(({ shown, rows }) =>
+ fakeElement({
+ box: shown && terminal !== 'never' ? { left: 0, top: 44, width: 400, height: 200 } : ZERO,
+ displayed: shown && terminal !== 'never',
+ visibility: terminalVisibility,
+ descendants: { '.xterm-rows': [fakeElement({ textContent: rows })] },
+ }),
+ );
+ const terminalUnit = fakeElement({
+ box: terminal === 'never' ? ZERO : terminal.box,
+ displayed: terminal !== 'never',
+ visibility: terminalVisibility,
+ descendants: {
+ '[data-slot="pane-card"][data-pane="terminal"]': [
+ fakeElement({ attributes: { 'data-placement': placement } }),
+ ],
+ 'section[aria-label="Terminal"]': sectionElements,
+ },
+ });
+ const editorUnit = fakeElement({
+ box: editor === 'off' ? EDITOR_ABOVE_BOTTOM : editor,
+ visibility: editor === 'off' ? 'hidden' : 'visible',
+ });
+ const units: Readonly<Record<string, FakeElement>> = {
+ '[data-dock-unit="terminal"]': terminalUnit,
+ '[data-dock-unit="editor"]': editorUnit,
+ };
+ vi.stubGlobal('document', { querySelector: (selector: string) => units[selector] ?? null });
+ vi.stubGlobal('getComputedStyle', (element: FakeElement) => ({
+ visibility: element.visibility,
+ }));
+}
+
+function pageRunning(probe: (settledAt: TerminalHome | null) => unknown): Page {
+ return {
+ evaluate: (run: typeof terminalHomeProbe, settledAt: TerminalHome | null) =>
+ Promise.resolve(run === terminalHomeProbe ? probe(settledAt) : undefined),
+ } as unknown as Page;
+}
+
+function pageStoring(...readings: ReadonlyArray<readonly StoredDockArrangement[]>): Page {
+ let reads = 0;
+ return {
+ evaluate: (run: unknown) => {
+ if (run !== storedDockArrangementsProbe) {
+ return Promise.reject(new Error('the page was asked to run another probe'));
+ }
+ const reading = readings[Math.min(reads, readings.length - 1)] ?? [];
+ reads += 1;
+ return Promise.resolve(reading);
+ },
+ } as unknown as Page;
+}
+
+async function rejectionOf(run: Promise<unknown>): Promise<string> {
+ return run.then(
+ () => {
+ throw new Error('the wait resolved where it had to reject');
+ },
+ (error: unknown) =>
+ stripVTControlCharacters(error instanceof Error ? error.message : String(error)),
+ );
+}
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe('terminal home probe', () => {
+ test('reads a terminal under the editor and as wide as it as the bottom home', () => {
+ mountWorkspace({
+ editor: EDITOR_ABOVE_BOTTOM,
+ terminal: { box: BOTTOM_TERMINAL, state: 'shown' },
+ placement: 'bottom',
+ });
+
+ expect(terminalHomeProbe(null)).toEqual({
+ placement: 'bottom',
+ geometry: 'bottom',
+ painted: true,
+ });
+ });
+
+ test('reads a terminal after the editor and as tall as it as the right home', () => {
+ mountWorkspace({
+ editor: EDITOR_BESIDE_RIGHT,
+ terminal: { box: RIGHT_TERMINAL, state: 'shown' },
+ placement: 'right',
+ });
+
+ expect(terminalHomeProbe(null)).toEqual({
+ placement: 'right',
+ geometry: 'right',
+ painted: true,
+ });
+ });
+
+ test('gives no home to a terminal that sits below the editor without spanning it', () => {
+ mountWorkspace({
+ editor: EDITOR_ABOVE_BOTTOM,
+ terminal: { box: { ...BOTTOM_TERMINAL, width: 900 }, state: 'shown' },
+ placement: 'bottom',
+ });
+
+ expect(terminalHomeProbe(null)).toMatchObject({ placement: 'bottom', geometry: null });
+ });
+
+ test('gives no home to a terminal that sits beside the editor at another height', () => {
+ mountWorkspace({
+ editor: EDITOR_BESIDE_RIGHT,
+ terminal: { box: { ...RIGHT_TERMINAL, height: 600 }, state: 'shown' },
+ placement: 'right',
+ });
+
+ expect(terminalHomeProbe(null)).toMatchObject({ placement: 'right', geometry: null });
+ });
+
+ test('a terminal turned off keeps its last rect but has no home and nothing painted', () => {
+ mountWorkspace({
+ editor: EDITOR_ABOVE_BOTTOM,
+ terminal: { box: BOTTOM_TERMINAL, state: 'off' },
+ placement: 'bottom',
+ });
+
+ expect(terminalHomeProbe(null)).toEqual({
+ placement: 'bottom',
+ geometry: null,
+ painted: false,
+ });
+ });
+
+ test('a terminal that was never shown has no home', () => {
+ mountWorkspace({ editor: EDITOR_ABOVE_BOTTOM, terminal: 'never', placement: 'bottom' });
+
+ expect(terminalHomeProbe(null)).toEqual({
+ placement: 'bottom',
+ geometry: null,
+ painted: false,
+ });
+ });
+
+ test('without the editor on screen the terminal has no home to be measured against', () => {
+ mountWorkspace({
+ editor: 'off',
+ terminal: { box: BOTTOM_TERMINAL, state: 'shown' },
+ placement: 'bottom',
+ });
+
+ expect(terminalHomeProbe(null)).toMatchObject({ geometry: null, painted: true });
+ });
+
+ test('counts only a shown session with output as painted', () => {
+ mountWorkspace({
+ editor: EDITOR_ABOVE_BOTTOM,
+ terminal: { box: BOTTOM_TERMINAL, state: 'shown' },
+ placement: 'bottom',
+ sessions: [
+ { shown: false, rows: '% echo hidden tab' },
+ { shown: true, rows: '' },
+ ],
+ });
+
+ expect(terminalHomeProbe(null)).toMatchObject({ painted: false });
+ });
+
+ test('settles at a home only when the placement, the geometry and the paint all agree on it', () => {
+ mountWorkspace({
+ editor: EDITOR_ABOVE_BOTTOM,
+ terminal: { box: BOTTOM_TERMINAL, state: 'shown' },
+ placement: 'right',
+ });
+ expect(terminalHomeProbe('right')).toBe(false);
+ expect(terminalHomeProbe('bottom')).toBe(false);
+
+ mountWorkspace({
+ editor: EDITOR_BESIDE_RIGHT,
+ terminal: { box: RIGHT_TERMINAL, state: 'shown' },
+ placement: 'right',
+ sessions: [{ shown: true, rows: '' }],
+ });
+ expect(terminalHomeProbe('right')).toBe(false);
+
+ mountWorkspace({
+ editor: EDITOR_BESIDE_RIGHT,
+ terminal: { box: RIGHT_TERMINAL, state: 'shown' },
+ placement: 'right',
+ });
+ expect(terminalHomeProbe('right')).toEqual({
+ placement: 'right',
+ geometry: 'right',
+ painted: true,
+ });
+ });
+});
+
+describe('terminal home read', () => {
+ test('returns what the probe reads in the renderer', async () => {
+ mountWorkspace({
+ editor: EDITOR_BESIDE_RIGHT,
+ terminal: { box: RIGHT_TERMINAL, state: 'shown' },
+ placement: 'right',
+ });
+
+ await expect(readTerminalHome(pageRunning(terminalHomeProbe))).resolves.toEqual({
+ placement: 'right',
+ geometry: 'right',
+ painted: true,
+ });
+ });
+
+ test('refuses a renderer that answers a plain read with false', async () => {
+ await expect(readTerminalHome(pageRunning(() => false))).rejects.toThrow(
+ /different probe than this module ships/u,
+ );
+ });
+});
+
+describe('stored dock arrangements probe', () => {
+ test('lists every project arrangement in storage order and nothing else', () => {
+ const entries: ReadonlyArray<readonly [string, string]> = [
+ ['ok-dock-arrangement-v1:3f2a', '{"pane":"editor"}'],
+ ['ok-terminal-placement-v1', 'right'],
+ ['ok-dock-arrangement-v1:91c0', 'not a tree'],
+ ['ok-dock-arrangement-v2:91c0', 'another version'],
+ ];
+ vi.stubGlobal('localStorage', {
+ get length() {
+ return entries.length;
+ },
+ key: (index: number) => entries[index]?.[0] ?? null,
+ getItem: (key: string) => entries.find(([name]) => name === key)?.[1] ?? null,
+ });
+
+ expect(storedDockArrangementsProbe()).toEqual([
+ { key: 'ok-dock-arrangement-v1:3f2a', value: '{"pane":"editor"}' },
+ { key: 'ok-dock-arrangement-v1:91c0', value: 'not a tree' },
+ ]);
+ });
+});
+
+describe('stored dock arrangement of the open project', () => {
+ test('resolves the one stored arrangement once the project writes it', async () => {
+ await expect(
+ storedDockArrangement(pageStoring([], [MOVED_ARRANGEMENT]), {
+ timeout: DECLARED_BOUND_MS * 10,
+ }),
+ ).resolves.toEqual(MOVED_ARRANGEMENT);
+ });
+
+ test('refuses a project that keeps two stored arrangements, naming the count it read', async () => {
+ const message = await rejectionOf(
+ storedDockArrangement(
+ pageStoring([MOVED_ARRANGEMENT, { key: 'ok-dock-arrangement-v1:91c0', value: '{}' }]),
+ {
+ timeout: DECLARED_BOUND_MS,
+ },
+ ),
+ );
+
+ expect(message).toMatch(/stored arrangement count of the project dock arrangement/u);
+ expect(message).toMatch(/Received: 2\b/u);
+ });
+
+ test('settles once the arrangement stored under the same key changes', async () => {
+ await expect(
+ expectStoredDockArrangementChanged(
+ pageStoring([MOVED_ARRANGEMENT], [RESIZED_ARRANGEMENT]),
+ MOVED_ARRANGEMENT,
+ settleBudget('stored arrangement change', { timeout: DECLARED_BOUND_MS * 10 }),
+ ),
+ ).resolves.toBeUndefined();
+ });
+
+ test('refuses a stored arrangement that never changes', async () => {
+ const message = await rejectionOf(
+ expectStoredDockArrangementChanged(
+ pageStoring([MOVED_ARRANGEMENT]),
+ MOVED_ARRANGEMENT,
+ settleBudget('stored arrangement change', { timeout: DECLARED_BOUND_MS }),
+ ),
+ );
+
+ expect(message).toMatch(/stored arrangement of ok-dock-arrangement-v1:3f2a never settled/u);
+ });
+
+ test('refuses a change that lands under another project key', async () => {
+ const message = await rejectionOf(
+ expectStoredDockArrangementChanged(
+ pageStoring([{ key: 'ok-dock-arrangement-v1:91c0', value: RESIZED_ARRANGEMENT.value }]),
+ MOVED_ARRANGEMENT,
+ settleBudget('stored arrangement change', { timeout: DECLARED_BOUND_MS }),
+ ),
+ );
+
+ expect(message).toMatch(/never settled/u);
+ expect(message).toContain('ok-dock-arrangement-v1:91c0');
+ });
+});
diff --git a/packages/desktop/tests/smoke/_helpers/dock-workspace.ts b/packages/desktop/tests/smoke/_helpers/dock-workspace.ts
new file mode 100644
index 000000000..ffd0155df
--- /dev/null
+++ b/packages/desktop/tests/smoke/_helpers/dock-workspace.ts
@@ -0,0 +1,120 @@
+import { expect, type Page } from '@playwright/test';
+import { expectSettledReading, pollSettledReading, type SettleBudget } from './settled-reading';
+
+export type DockPane = 'editor' | 'agents' | 'terminal';
+
+export type TerminalHome = 'bottom' | 'right';
+
+export interface TerminalHomeReading {
+ readonly placement: string | null;
+ readonly geometry: TerminalHome | null;
+ readonly painted: boolean;
+}
+
+export interface StoredDockArrangement {
+ readonly key: string;
+ readonly value: string | null;
+}
+
+export const TERMINAL_CARD =
+ '[data-dock-unit="terminal"] [data-slot="pane-card"][data-pane="terminal"]';
+
+export function terminalHomeProbe(settledAt: TerminalHome | null): TerminalHomeReading | false {
+ const shownBox = (element: Element | null | undefined): DOMRect | null => {
+ if (element == null || !element.checkVisibility()) return null;
+ if (getComputedStyle(element).visibility !== 'visible') return null;
+ const box = element.getBoundingClientRect();
+ return box.width > 0 && box.height > 0 ? box : null;
+ };
+ const near = (from: number, to: number): boolean => Math.abs(from - to) <= 1;
+ const unit = document.querySelector('[data-dock-unit="terminal"]');
+ const placement =
+ unit
+ ?.querySelector('[data-slot="pane-card"][data-pane="terminal"]')
+ ?.getAttribute('data-placement') ?? null;
+ const editor = shownBox(document.querySelector('[data-dock-unit="editor"]'));
+ const terminal = shownBox(unit);
+ let geometry: TerminalHome | null = null;
+ if (editor !== null && terminal !== null) {
+ if (
+ terminal.top >= editor.bottom &&
+ near(terminal.left, editor.left) &&
+ near(terminal.right, editor.right)
+ ) {
+ geometry = 'bottom';
+ } else if (
+ terminal.left >= editor.right &&
+ near(terminal.top, editor.top) &&
+ near(terminal.bottom, editor.bottom)
+ ) {
+ geometry = 'right';
+ }
+ }
+ const painted = Array.from(unit?.querySelectorAll('section[aria-label="Terminal"]') ?? []).some(
+ (section) =>
+ shownBox(section) !== null &&
+ (section.querySelector('.xterm-rows')?.textContent ?? '').length > 0,
+ );
+ const reading: TerminalHomeReading = { placement, geometry, painted };
+ if (settledAt === null) return reading;
+ return placement === settledAt && geometry === settledAt && painted ? reading : false;
+}
+
+export async function readTerminalHome(page: Page): Promise<TerminalHomeReading> {
+ const reading = await page.evaluate(terminalHomeProbe, null);
+ if (reading === false) {
+ throw new Error(
+ 'the terminal home probe answered false to a plain read, which it never does, so the renderer ran a different probe than this module ships',
+ );
+ }
+ return reading;
+}
+
+export function storedDockArrangementsProbe(): StoredDockArrangement[] {
+ const arrangements: StoredDockArrangement[] = [];
+ for (let index = 0; index < localStorage.length; index += 1) {
+ const key = localStorage.key(index);
+ if (key?.startsWith('ok-dock-arrangement-v1:')) {
+ arrangements.push({ key, value: localStorage.getItem(key) });
+ }
+ }
+ return arrangements;
+}
+
+export function dockUnitWidth(page: Page, pane: DockPane): Promise<number> {
+ return page
+ .locator(`#dock-unit-${pane}`)
+ .evaluate((element) => element.getBoundingClientRect().width);
+}
+
+export async function storedDockArrangement(
+ page: Page,
+ { timeout }: { timeout: number },
+): Promise<StoredDockArrangement> {
+ let stored: StoredDockArrangement | undefined;
+ await pollSettledReading(
+ async () => {
+ const arrangements = await page.evaluate(storedDockArrangementsProbe);
+ stored = arrangements[0];
+ return arrangements.length;
+ },
+ { reading: 'stored arrangement count', of: 'the project dock arrangement', timeout },
+ ).toBe(1);
+ if (stored === undefined) throw new Error('the stored dock arrangement vanished between reads');
+ return stored;
+}
+
+export async function expectStoredDockArrangementChanged(
+ page: Page,
+ since: StoredDockArrangement,
+ budget: SettleBudget,
+): Promise<void> {
+ await expectSettledReading(
+ () => page.evaluate(storedDockArrangementsProbe),
+ (arrangements) => {
+ expect(arrangements.map(({ key }) => key)).toEqual([since.key]);
+ expect(arrangements[0]?.value).not.toBe(since.value);
+ },
+ { reading: 'stored arrangement', of: since.key, budget },
+ );
+}
diff --git a/packages/desktop/tests/smoke/_helpers/polled-reading.test.ts b/packages/desktop/tests/smoke/_helpers/polled-reading.test.ts
index da8ab823d..83376192a 100644
--- a/packages/desktop/tests/smoke/_helpers/polled-reading.test.ts
+++ b/packages/desktop/tests/smoke/_helpers/polled-reading.test.ts
@@ -1,5 +1,5 @@
import { afterEach, expect, test, vi } from 'vitest';
-import { pollSettledReading, RAIL_LAYOUT_SETTLE_TIMEOUT_MS } from './settled-reading';
+import { LAYOUT_SETTLE_TIMEOUT_MS, pollSettledReading } from './settled-reading';
afterEach(() => vi.useRealTimers());
@@ -30,7 +30,7 @@ test('a reading completed after its declared bound cannot turn the verdict into
{
reading: 'dimension',
of: 'test surface',
- timeout: RAIL_LAYOUT_SETTLE_TIMEOUT_MS,
+ timeout: LAYOUT_SETTLE_TIMEOUT_MS,
},
)
.toBe('ready')
@@ -39,7 +39,7 @@ test('a reading completed after its declared bound cannot turn the verdict into
(error: unknown) => error,
);
await started.promise;
- await vi.advanceTimersByTimeAsync(RAIL_LAYOUT_SETTLE_TIMEOUT_MS + 1);
+ await vi.advanceTimersByTimeAsync(LAYOUT_SETTLE_TIMEOUT_MS + 1);
reading.resolve('ready');
await vi.runAllTimersAsync();
@@ -61,7 +61,7 @@ test('a synchronous reader failure is preserved even if another attempt could su
{
reading: 'dimension',
of: 'test surface',
- timeout: RAIL_LAYOUT_SETTLE_TIMEOUT_MS,
+ timeout: LAYOUT_SETTLE_TIMEOUT_MS,
},
)
.toBe(1)
diff --git a/packages/desktop/tests/smoke/_helpers/rail-column.test.ts b/packages/desktop/tests/smoke/_helpers/rail-column.test.ts
deleted file mode 100644
index f245625b9..000000000
--- a/packages/desktop/tests/smoke/_helpers/rail-column.test.ts
+++ /dev/null
@@ -1,130 +0,0 @@
-import { stripVTControlCharacters } from 'node:util';
-import type { Page } from '@playwright/test';
-import { describe, expect, test } from 'vitest';
-import { readRailColumnWidth, waitForCollapsedWidth } from './rail-column';
-
-const COLUMN = '#agents-column';
-const PLAYWRIGHT_INHERITED_EXPECT_TIMEOUT_MS = 5_000;
-const CI_ATTEMPT_ZERO_READ_MS = 5_260;
-const DECLARED_BOUND_MS = 300;
-const UNCOLLAPSED_WIDTH_PX = 320;
-const DESTROYED = 'Execution context was destroyed, most likely because of a navigation';
-
-const answerAfter = <T>(ms: number, value: T): Promise<T> =>
- new Promise((resolve) => {
- setTimeout(() => resolve(value), ms);
- });
-
-const neverAnswers = (): Promise<number> => new Promise<number>(() => {});
-
-async function rejectionOf(run: Promise<unknown>): Promise<string> {
- return run.then(
- () => {
- throw new Error('the settle wait resolved where it had to reject');
- },
- (error: unknown) =>
- stripVTControlCharacters(error instanceof Error ? error.message : String(error)),
- );
-}
-
-type FakeRailElement = { getBoundingClientRect: () => { width: number } };
-
-function pageMatching(widths: readonly number[]): Page {
- const elements: FakeRailElement[] = widths.map((width) => ({
- getBoundingClientRect: () => ({ width }),
- }));
- return {
- locator: () => ({
- evaluateAll: async (read: (nodes: FakeRailElement[]) => number[]) => read(elements),
- }),
- } as unknown as Page;
-}
-
-describe('collapsed rail column settle', () => {
- test('replays CI attempt 0: a read that answers zero after the inherited expect default still settles the column', async () => {
- expect(CI_ATTEMPT_ZERO_READ_MS).toBeGreaterThan(PLAYWRIGHT_INHERITED_EXPECT_TIMEOUT_MS);
- let reads = 0;
-
- await waitForCollapsedWidth(
- () => {
- reads += 1;
- return answerAfter(CI_ATTEMPT_ZERO_READ_MS, 0);
- },
- { column: COLUMN },
- );
-
- expect(reads).toBeGreaterThan(0);
- });
-
- test('reports a read that never answers inside the declared bound as no reading, naming the column and the bound', async () => {
- const message = await rejectionOf(
- waitForCollapsedWidth(neverAnswers, { column: COLUMN, timeout: DECLARED_BOUND_MS }),
- );
-
- expect(message).toContain(COLUMN);
- expect(message).toMatch(new RegExp(`\\b${DECLARED_BOUND_MS} ms\\b`, 'u'));
- expect(message).toMatch(/no width reading completed/u);
- expect(message).not.toMatch(/Received/u);
- });
-
- test('reports a column that answered a non-zero width as that width, never as a missing reading', async () => {
- const message = await rejectionOf(
- waitForCollapsedWidth(() => Promise.resolve(UNCOLLAPSED_WIDTH_PX), {
- column: COLUMN,
- timeout: DECLARED_BOUND_MS,
- }),
- );
-
- expect(message).toMatch(new RegExp(`\\b${UNCOLLAPSED_WIDTH_PX}\\b`, 'u'));
- expect(message).not.toMatch(/no width reading completed/u);
- });
-
- test('settles once the column reaches zero after wider readings', async () => {
- const widths = [UNCOLLAPSED_WIDTH_PX, UNCOLLAPSED_WIDTH_PX, 0];
- let reads = 0;
-
- await waitForCollapsedWidth(
- () => {
- const width = widths[Math.min(reads, widths.length - 1)] ?? 0;
- reads += 1;
- return Promise.resolve(width);
- },
- { column: COLUMN },
- );
-
- expect(reads).toBeGreaterThanOrEqual(widths.length);
- });
-
- test('surfaces a read that keeps failing as the read failure, never as a width', async () => {
- const message = await rejectionOf(
- waitForCollapsedWidth(() => Promise.reject(new Error(DESTROYED)), {
- column: COLUMN,
- timeout: DECLARED_BOUND_MS,
- }),
- );
-
- expect(message).toContain(DESTROYED);
- expect(message).not.toMatch(/Received/u);
- });
-});
-describe('rail column cardinality', () => {
- test('reads the width when exactly one element matches', async () => {
- await expect(readRailColumnWidth(pageMatching([UNCOLLAPSED_WIDTH_PX]), COLUMN)).resolves.toBe(
- UNCOLLAPSED_WIDTH_PX,
- );
- });
-
- test('refuses a selector that matches no element, naming the selector and the count', async () => {
- const message = await rejectionOf(readRailColumnWidth(pageMatching([]), COLUMN));
-
- expect(message).toContain(COLUMN);
- expect(message).toMatch(/found 0\b/u);
- });
-
- test('refuses a selector that matches more than one collapsed element, naming the selector and the count', async () => {
- const message = await rejectionOf(readRailColumnWidth(pageMatching([0, 0]), COLUMN));
-
- expect(message).toContain(COLUMN);
- expect(message).toMatch(/found 2\b/u);
- });
-});
diff --git a/packages/desktop/tests/smoke/_helpers/rail-column.ts b/packages/desktop/tests/smoke/_helpers/rail-column.ts
deleted file mode 100644
index 0a28cefc0..000000000
--- a/packages/desktop/tests/smoke/_helpers/rail-column.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-import { expect, type Page } from '@playwright/test';
-import {
- expectSettledReading,
- RAIL_LAYOUT_SETTLE_TIMEOUT_MS,
- type SettleBudget,
-} from './settled-reading';
-
-export type RailSettleBound =
- | { timeout?: number; budget?: undefined }
- | { budget: SettleBudget; timeout?: undefined };
-
-export type CollapsedWidthOptions = { column: string } & RailSettleBound;
-
-export async function waitForCollapsedWidth(
- readWidth: () => Promise<number>,
- { column, timeout = RAIL_LAYOUT_SETTLE_TIMEOUT_MS, budget }: CollapsedWidthOptions,
-): Promise<void> {
- await expectSettledReading(
- readWidth,
- (width) => expect(width).toBe(0),
- budget === undefined
- ? { reading: 'width', of: column, timeout }
- : { reading: 'width', of: column, budget },
- );
-}
-
-export async function readRailColumnWidth(page: Page, selector: string): Promise<number> {
- const widths = await page
- .locator(selector)
- .evaluateAll((elements) => elements.map((element) => element.getBoundingClientRect().width));
- const [width] = widths;
- if (widths.length !== 1 || width === undefined) {
- throw new Error(`expected exactly one ${selector}, found ${widths.length}`);
- }
- return width;
-}
-
-export async function expectCollapsedRailColumn(
- page: Page,
- selector: string,
- bound: RailSettleBound = {},
-): Promise<void> {
- await waitForCollapsedWidth(() => readRailColumnWidth(page, selector), {
- column: selector,
- ...bound,
- });
-}
diff --git a/packages/desktop/tests/smoke/_helpers/settled-reading.test.ts b/packages/desktop/tests/smoke/_helpers/settled-reading.test.ts
index 181f90f70..53c79c1a3 100644
--- a/packages/desktop/tests/smoke/_helpers/settled-reading.test.ts
+++ b/packages/desktop/tests/smoke/_helpers/settled-reading.test.ts
@@ -1,16 +1,18 @@
import { stripVTControlCharacters } from 'node:util';
import { expect as playwrightExpect } from '@playwright/test';
import { describe, expect, test } from 'vitest';
-import { waitForCollapsedWidth } from './rail-column';
-import { expectSettledReading, settleBudget } from './settled-reading';
+import { expectSettledReading, LAYOUT_SETTLE_TIMEOUT_MS, settleBudget } from './settled-reading';
-const LABEL = 'rail admission after the window narrows to 900 px';
+const LABEL = 'the dock after the window narrows to 900 px';
const TOTAL_MS = 10_000;
const CLOCK_ORIGIN_MS = 50_000;
-const COLUMN = '#agents-column';
-const UNCOLLAPSED_WIDTH_PX = 320;
+const SURFACE = '#dock-unit-terminal';
+const UNSETTLED_WIDTH_PX = 320;
const LIVENESS_BOUND_MS = 500;
const REMAINING_MS = 300;
+const DECLARED_BOUND_MS = 300;
+const PLAYWRIGHT_INHERITED_EXPECT_TIMEOUT_MS = 5_000;
+const CI_ATTEMPT_ZERO_READ_MS = 5_260;
const DESTROYED = 'Execution context was destroyed, most likely because of a navigation';
function budgetOnClock(timeout: number) {
@@ -44,13 +46,18 @@ async function outcomeWithinLiveness(
return outcome;
}
-const uncollapsedUntil = (raceOver: () => boolean) => (): Promise<number> =>
+const unsettledUntil = (raceOver: () => boolean) => (): Promise<number> =>
raceOver()
? Promise.reject(new Error('the liveness race is over'))
- : Promise.resolve(UNCOLLAPSED_WIDTH_PX);
+ : Promise.resolve(UNSETTLED_WIDTH_PX);
const neverAnswers = (): Promise<number> => new Promise<number>(() => {});
+const answerAfter = <T>(ms: number, value: T): Promise<T> =>
+ new Promise((resolve) => {
+ setTimeout(() => resolve(value), ms);
+ });
+
async function rejectionOf(run: Promise<unknown>): Promise<string> {
return run.then(
() => {
@@ -67,6 +74,14 @@ function budgetWithRemainder() {
return budget;
}
+function settlesAtZero(read: () => Promise<number>, timeout: number): Promise<void> {
+ return expectSettledReading(read, (width) => playwrightExpect(width).toBe(0), {
+ reading: 'width',
+ of: SURFACE,
+ timeout,
+ });
+}
+
describe('settle budget shared by the waits on one layout transition', () => {
test('spends the time elapsed on its clock from the remaining budget', () => {
const { budget, advance } = budgetOnClock(TOTAL_MS);
@@ -104,60 +119,103 @@ describe('settle budget shared by the waits on one layout transition', () => {
});
describe('declared bound of a settled reading', () => {
- const entryPoints = [
- [
- 'expectSettledReading',
- (raceOver: () => boolean, timeout: number) =>
- expectSettledReading(uncollapsedUntil(raceOver), (width) => expect(width).toBe(0), {
- reading: 'width',
- of: COLUMN,
- timeout,
- }),
- ],
- [
- 'waitForCollapsedWidth',
- (raceOver: () => boolean, timeout: number) =>
- waitForCollapsedWidth(uncollapsedUntil(raceOver), { column: COLUMN, timeout }),
- ],
- ] as const;
- const bounds = [
+ test.each([
['a zero bound', 0],
['a NaN bound', Number.NaN],
['a negative bound', -1],
- ] as const;
+ ])('rejects %s promptly by naming the positive-bound contract', async (_bound, timeout) => {
+ const outcome = await outcomeWithinLiveness((raceOver) =>
+ settlesAtZero(unsettledUntil(raceOver), timeout),
+ );
- test.each(
- entryPoints.flatMap(([entry, wait]) =>
- bounds.map(([bound, timeout]) => [entry, bound, wait, timeout] as const),
- ),
- )(
- '%s rejects %s promptly by naming the positive-bound contract',
- async (_entry, _bound, wait, timeout) => {
- const outcome = await outcomeWithinLiveness((raceOver) => wait(raceOver, timeout));
+ expect(outcome).toMatch(/positive/u);
+ });
- expect(outcome).toMatch(/positive/u);
- },
- );
+ test('replays CI attempt 0: a reading that answers after the inherited expect default still settles within its declared bound', async () => {
+ expect(CI_ATTEMPT_ZERO_READ_MS).toBeGreaterThan(PLAYWRIGHT_INHERITED_EXPECT_TIMEOUT_MS);
+ let reads = 0;
+
+ await settlesAtZero(() => {
+ reads += 1;
+ return answerAfter(CI_ATTEMPT_ZERO_READ_MS, 0);
+ }, LAYOUT_SETTLE_TIMEOUT_MS);
+
+ expect(reads).toBeGreaterThan(0);
+ });
+
+ test('reports a read that never answers inside the declared bound as no reading, naming the surface and the bound', async () => {
+ const message = await rejectionOf(settlesAtZero(neverAnswers, DECLARED_BOUND_MS));
+
+ expect(message).toContain(SURFACE);
+ expect(message).toMatch(new RegExp(`\\b${DECLARED_BOUND_MS} ms\\b`, 'u'));
+ expect(message).toMatch(/no width reading completed/u);
+ expect(message).not.toMatch(/Received/u);
+ });
+
+ test('reports a reading that never matches as that reading, never as a missing one', async () => {
+ const message = await rejectionOf(
+ settlesAtZero(() => Promise.resolve(UNSETTLED_WIDTH_PX), DECLARED_BOUND_MS),
+ );
+
+ expect(message).toMatch(new RegExp(`\\b${UNSETTLED_WIDTH_PX}\\b`, 'u'));
+ expect(message).not.toMatch(/no width reading completed/u);
+ });
+
+ test('settles once the reading matches after earlier readings that did not', async () => {
+ const widths = [UNSETTLED_WIDTH_PX, UNSETTLED_WIDTH_PX, 0];
+ let reads = 0;
+
+ await settlesAtZero(() => {
+ const width = widths[Math.min(reads, widths.length - 1)] ?? 0;
+ reads += 1;
+ return Promise.resolve(width);
+ }, LAYOUT_SETTLE_TIMEOUT_MS);
+
+ expect(reads).toBeGreaterThanOrEqual(widths.length);
+ });
+
+ test('surfaces a read that keeps failing as the read failure, never as a reading', async () => {
+ const message = await rejectionOf(
+ settlesAtZero(() => Promise.reject(new Error(DESTROYED)), DECLARED_BOUND_MS),
+ );
+
+ expect(message).toContain(DESTROYED);
+ expect(message).not.toMatch(/Received/u);
+ });
});
describe('settled reading bounded by a shared settle budget', () => {
- const entryPoints = [
- [
- 'expectSettledReading',
- (read: () => Promise<number>) =>
- expectSettledReading(read, (width) => playwrightExpect(width).toBe(0), {
- reading: 'width',
- of: COLUMN,
- budget: budgetWithRemainder(),
- }),
- ],
- [
- 'waitForCollapsedWidth',
- (read: () => Promise<number>) =>
- waitForCollapsedWidth(read, { column: COLUMN, budget: budgetWithRemainder() }),
- ],
- ] as const;
- const failingReads = [
+ const settlesWithinBudget = (read: () => Promise<number>) =>
+ expectSettledReading(read, (width) => playwrightExpect(width).toBe(0), {
+ reading: 'width',
+ of: SURFACE,
+ budget: budgetWithRemainder(),
+ });
+
+ test('reports a read that never answers as no reading within the time the budget has left, naming its label and total', async () => {
+ const message = await rejectionOf(settlesWithinBudget(neverAnswers));
+
+ expect(message).toMatch(/no width reading completed/u);
+ expect(message).toContain(LABEL);
+ expect(message).toMatch(new RegExp(`\\b${REMAINING_MS} ms\\b`, 'u'));
+ expect(message).toMatch(new RegExp(`\\b${TOTAL_MS} ms\\b`, 'u'));
+ });
+
+ test('reports a width that never settles within the time the budget has left and keeps its Expected/Received reason', async () => {
+ const message = await rejectionOf(
+ settlesWithinBudget(() => Promise.resolve(UNSETTLED_WIDTH_PX)),
+ );
+
+ expect(message).toMatch(/never settled/u);
+ expect(message).toContain(SURFACE);
+ expect(message).toContain(LABEL);
+ expect(message).toMatch(new RegExp(`\\b${REMAINING_MS} ms\\b`, 'u'));
+ expect(message).toMatch(new RegExp(`\\b${TOTAL_MS} ms\\b`, 'u'));
+ expect(message).toMatch(/Expected: 0\b/u);
+ expect(message).toMatch(new RegExp(`Received: ${UNSETTLED_WIDTH_PX}\\b`, 'u'));
+ });
+
+ test.each([
['rejects', (): Promise<number> => Promise.reject(new Error(DESTROYED))],
[
'throws before it returns a promise',
@@ -165,43 +223,10 @@ describe('settled reading bounded by a shared settle budget', () => {
throw new Error(DESTROYED);
},
],
- ] as const;
-
- test.each(entryPoints)(
- '%s reports a read that never answers as no reading within the time the budget has left, naming its label and total',
- async (_entry, wait) => {
- const message = await rejectionOf(wait(neverAnswers));
-
- expect(message).toMatch(/no width reading completed/u);
- expect(message).toContain(LABEL);
- expect(message).toMatch(new RegExp(`\\b${REMAINING_MS} ms\\b`, 'u'));
- expect(message).toMatch(new RegExp(`\\b${TOTAL_MS} ms\\b`, 'u'));
- },
- );
-
- test.each(entryPoints)(
- '%s reports a width that never settles within the time the budget has left and keeps its Expected/Received reason',
- async (_entry, wait) => {
- const message = await rejectionOf(wait(() => Promise.resolve(UNCOLLAPSED_WIDTH_PX)));
-
- expect(message).toMatch(/never settled/u);
- expect(message).toContain(COLUMN);
- expect(message).toContain(LABEL);
- expect(message).toMatch(new RegExp(`\\b${REMAINING_MS} ms\\b`, 'u'));
- expect(message).toMatch(new RegExp(`\\b${TOTAL_MS} ms\\b`, 'u'));
- expect(message).toMatch(/Expected: 0\b/u);
- expect(message).toMatch(new RegExp(`Received: ${UNCOLLAPSED_WIDTH_PX}\\b`, 'u'));
- },
- );
-
- test.each(
- entryPoints.flatMap(([entry, wait]) =>
- failingReads.map(([how, read]) => [entry, how, wait, read] as const),
- ),
- )(
- '%s surfaces a read that %s as that failure, never as a missing or unsettled reading',
- async (_entry, _how, wait, read) => {
- const message = await rejectionOf(wait(read));
+ ] as const)(
+ 'surfaces a read that %s as that failure, never as a missing or unsettled reading',
+ async (_how, read) => {
+ const message = await rejectionOf(settlesWithinBudget(read));
expect(message).toContain(DESTROYED);
expect(message).not.toMatch(/no width reading completed|never settled|Received/u);
diff --git a/packages/desktop/tests/smoke/_helpers/settled-reading.ts b/packages/desktop/tests/smoke/_helpers/settled-reading.ts
index 637ae0fbb..7e0acb9e8 100644
--- a/packages/desktop/tests/smoke/_helpers/settled-reading.ts
+++ b/packages/desktop/tests/smoke/_helpers/settled-reading.ts
@@ -1,6 +1,6 @@
import { expect } from '@playwright/test';
-export const RAIL_LAYOUT_SETTLE_TIMEOUT_MS = 10_000;
+export const LAYOUT_SETTLE_TIMEOUT_MS = 10_000;
export interface SettleBudget {
readonly label: string;
@@ -13,7 +13,7 @@ export interface SettleBudgetOptions {
now?: () => number;
}
-export function requirePositiveTimeout(owner: string, timeout: number): void {
+function requirePositiveTimeout(owner: string, timeout: number): void {
if (!(timeout > 0) || !Number.isFinite(timeout)) {
throw new Error(
`${owner} needs a positive, finite timeout; received ${timeout}. ` +
diff --git a/packages/desktop/tests/smoke/_helpers/transient-notice.test.ts b/packages/desktop/tests/smoke/_helpers/transient-notice.test.ts
deleted file mode 100644
index 5decb6798..000000000
--- a/packages/desktop/tests/smoke/_helpers/transient-notice.test.ts
+++ /dev/null
@@ -1,566 +0,0 @@
-import { stripVTControlCharacters } from 'node:util';
-import { describe, expect, test, vi } from 'vitest';
-import {
- expectNoticeFromTrigger,
- type TransientNoticeObservation,
- type TransientNoticeRecorder,
- transientNoticeObservation,
-} from './transient-notice';
-
-const NOTICE = 'Agent panel closed to keep Terminal readable.';
-const OTHER_NOTICE = 'Terminal closed to make room for the agent panel.';
-const OBSERVE_BOUND_MS = 300;
-
-function noticeSurface() {
- let observing = false;
- const observed: string[] = [];
- return {
- show(text: string): void {
- if (observing) observed.push(text);
- },
- observation(
- trigger: () => Promise<void>,
- startObserving: () => Promise<void> = () => {
- observing = true;
- return Promise.resolve();
- },
- ): TransientNoticeObservation {
- return {
- startObserving,
- trigger,
- readObserved: () => Promise.resolve([...observed]),
- };
- },
- };
-}
-
-async function rejectionOf(run: Promise<unknown>): Promise<string> {
- return run.then(
- () => {
- throw new Error('the notice oracle resolved where it had to reject');
- },
- (error: unknown) =>
- stripVTControlCharacters(error instanceof Error ? error.message : String(error)),
- );
-}
-
-describe('transient notice caused by a trigger', () => {
- test('replays CI retry 1: observes a notice shown and dismissed before the trigger returned', async () => {
- const surface = noticeSurface();
-
- await expect(
- expectNoticeFromTrigger(
- NOTICE,
- surface.observation(() => {
- surface.show(NOTICE);
- return Promise.resolve();
- }),
- { timeout: OBSERVE_BOUND_MS },
- ),
- ).resolves.toBeUndefined();
- });
-
- test('observes a notice that fires after the trigger returns', async () => {
- const surface = noticeSurface();
-
- await expect(
- expectNoticeFromTrigger(
- NOTICE,
- surface.observation(() => {
- setTimeout(() => surface.show(NOTICE), 0);
- return Promise.resolve();
- }),
- { timeout: OBSERVE_BOUND_MS },
- ),
- ).resolves.toBeUndefined();
- });
-
- test('fails naming the notice when the trigger shows none', async () => {
- const surface = noticeSurface();
-
- const message = await rejectionOf(
- expectNoticeFromTrigger(
- NOTICE,
- surface.observation(() => Promise.resolve()),
- { timeout: OBSERVE_BOUND_MS },
- ),
- );
-
- expect(message).toContain(NOTICE);
- });
-
- test('is not satisfied by a different notice the trigger showed', async () => {
- const surface = noticeSurface();
-
- const message = await rejectionOf(
- expectNoticeFromTrigger(
- NOTICE,
- surface.observation(() => {
- surface.show(OTHER_NOTICE);
- return Promise.resolve();
- }),
- { timeout: OBSERVE_BOUND_MS },
- ),
- );
-
- expect(message).toContain(NOTICE);
- });
-
- test('surfaces an observer that cannot start as that failure, not as a missing notice', async () => {
- const OBSERVER_FAILURE = 'the recorder could not be installed in the renderer';
- const surface = noticeSurface();
-
- const message = await rejectionOf(
- expectNoticeFromTrigger(
- NOTICE,
- surface.observation(
- () => {
- surface.show(NOTICE);
- return Promise.resolve();
- },
- () => Promise.reject(new Error(OBSERVER_FAILURE)),
- ),
- { timeout: OBSERVE_BOUND_MS },
- ),
- );
-
- expect(message).toContain(OBSERVER_FAILURE);
- expect(message).not.toMatch(/Received/u);
- });
-});
-
-const STOP_FAILURE = 'the notice recorder could not be disconnected';
-const LIVENESS_BOUND_MS = 500;
-
-function stoppable(
- observation: TransientNoticeObservation,
- stop: () => Promise<void> = () => Promise.resolve(),
-) {
- let stops = 0;
- const stoppableObservation: TransientNoticeObservation = {
- ...observation,
- readObserved: () =>
- stops > 0
- ? Promise.reject(new Error('the notice record was read after the observer stopped'))
- : observation.readObserved(),
- stopObserving: () => {
- stops += 1;
- return stop();
- },
- };
- return { observation: stoppableObservation, stops: () => stops };
-}
-
-describe('transient notice observer teardown', () => {
- test('stops the observer once, after the notice was observed', async () => {
- const surface = noticeSurface();
- const observer = stoppable(
- surface.observation(() => {
- surface.show(NOTICE);
- return Promise.resolve();
- }),
- );
-
- await expectNoticeFromTrigger(NOTICE, observer.observation, { timeout: OBSERVE_BOUND_MS });
-
- expect(observer.stops()).toBe(1);
- });
-
- test('keeps the missing-notice verdict when stopping the observer also fails', async () => {
- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
-
- try {
- const surface = noticeSurface();
- const observer = stoppable(
- surface.observation(() => Promise.resolve()),
- () => Promise.reject(new Error(STOP_FAILURE)),
- );
-
- const message = await rejectionOf(
- expectNoticeFromTrigger(NOTICE, observer.observation, { timeout: OBSERVE_BOUND_MS }),
- );
-
- expect(observer.stops()).toBe(1);
- expect(message).toContain(NOTICE);
- expect(message).not.toContain(STOP_FAILURE);
- expect(warn).toHaveBeenCalledWith(expect.stringContaining(STOP_FAILURE));
- } finally {
- warn.mockRestore();
- }
- });
-
- test('surfaces a failure to stop the observer as itself once the notice was observed', async () => {
- const surface = noticeSurface();
- const observer = stoppable(
- surface.observation(() => {
- surface.show(NOTICE);
- return Promise.resolve();
- }),
- () => Promise.reject(new Error(STOP_FAILURE)),
- );
-
- const message = await rejectionOf(
- expectNoticeFromTrigger(NOTICE, observer.observation, { timeout: OBSERVE_BOUND_MS }),
- );
-
- expect(message).toContain(STOP_FAILURE);
- expect(message).not.toMatch(/Received/u);
- });
-});
-
-describe('transient notice observation bound', () => {
- test.each([
- ['a zero bound', 0],
- ['a NaN bound', Number.NaN],
- ['a negative bound', -1],
- ])(
- 'rejects %s promptly by naming the positive-bound contract, before it arms or triggers anything',
- async (_label, timeout) => {
- let starts = 0;
- let triggers = 0;
- let raceOver = false;
- let timer: ReturnType<typeof setTimeout> | undefined;
-
- const outcome = await Promise.race([
- expectNoticeFromTrigger(
- NOTICE,
- {
- startObserving: () => {
- starts += 1;
- return Promise.resolve();
- },
- trigger: () => {
- triggers += 1;
- return Promise.resolve();
- },
- readObserved: () =>
- raceOver
- ? Promise.reject(new Error('the liveness race is over'))
- : Promise.resolve([]),
- },
- { timeout },
- ).then(
- () => 'resolved',
- (error: unknown) =>
- stripVTControlCharacters(error instanceof Error ? error.message : String(error)),
- ),
- new Promise<string>((resolve) => {
- timer = setTimeout(() => resolve('still waiting'), LIVENESS_BOUND_MS);
- }),
- ]);
- raceOver = true;
- clearTimeout(timer);
-
- expect(outcome).toMatch(/positive/u);
- expect([starts, triggers]).toEqual([0, 0]);
- },
- );
-});
-
-type NoticeListener = (text: string) => void;
-
-interface FakeRealm {
- readonly noticeRegion: { subscribe(listener: NoticeListener): () => void };
- readonly sessionStorage: Pick<Storage, 'getItem' | 'setItem'>;
- [key: string]: unknown;
-}
-
-interface FakeDocument {
- readonly window: FakeRealm;
- readonly document: { readonly body: { readonly innerText: string } };
- show(text: string): void;
- dismiss(text: string): void;
- subscriptionsOpened(): number;
- activeSubscriptions(): number;
-}
-
-function fakeDocument(pageSessionStorage: Map<string, string>): FakeDocument {
- const visible: string[] = [];
- const listeners = new Set<NoticeListener>();
- let opened = 0;
- return {
- window: {
- noticeRegion: {
- subscribe(listener) {
- listeners.add(listener);
- opened += 1;
- return () => {
- listeners.delete(listener);
- };
- },
- },
- sessionStorage: {
- getItem: (key) => pageSessionStorage.get(key) ?? null,
- setItem: (key, value) => {
- pageSessionStorage.set(key, value);
- },
- },
- },
- document: {
- body: {
- get innerText() {
- return visible.join('\n');
- },
- },
- },
- show(text) {
- visible.push(text);
- for (const listener of listeners) listener(text);
- },
- dismiss(text) {
- const at = visible.indexOf(text);
- if (at >= 0) visible.splice(at, 1);
- },
- subscriptionsOpened: () => opened,
- activeSubscriptions: () => listeners.size,
- };
-}
-
-function runInDocument<A, R>(target: FakeDocument, pageFunction: (arg: A) => R, arg: A): R {
- vi.stubGlobal('window', target.window);
- vi.stubGlobal('document', target.document);
- vi.stubGlobal('sessionStorage', target.window.sessionStorage);
- try {
- return structuredClone(pageFunction(structuredClone(arg)));
- } finally {
- vi.unstubAllGlobals();
- }
-}
-
-function documentAwarePage({ honoursInitScripts = true }: { honoursInitScripts?: boolean } = {}) {
- const pageSessionStorage = new Map<string, string>();
- const initScripts = new Set<(target: FakeDocument) => void>();
- let current = fakeDocument(pageSessionStorage);
- let bootApp: (booted: FakeDocument) => void = () => {};
-
- const page = {
- addInitScript<A>(script: (arg: A) => unknown, arg: A) {
- const registeredArg = structuredClone(arg);
- const runOnNewDocument = (target: FakeDocument): void => {
- runInDocument(target, script, registeredArg);
- };
- initScripts.add(runOnNewDocument);
- const dispose = (): Promise<void> => {
- initScripts.delete(runOnNewDocument);
- return Promise.resolve();
- };
- return Promise.resolve({ dispose, [Symbol.asyncDispose]: dispose });
- },
- evaluate<A, R>(pageFunction: (arg: A) => R, arg: A): Promise<R> {
- return Promise.resolve().then(() => runInDocument(current, pageFunction, arg));
- },
- };
-
- return {
- page: page as unknown as Parameters<typeof transientNoticeObservation>[0],
- current: () => current,
- whenBooted(boot: (booted: FakeDocument) => void): void {
- bootApp = boot;
- },
- reload(): Promise<void> {
- const reloaded = fakeDocument(pageSessionStorage);
- if (honoursInitScripts)
- for (const runOnNewDocument of initScripts) runOnNewDocument(reloaded);
- current = reloaded;
- bootApp(reloaded);
- return Promise.resolve();
- },
- activeInitScripts: () => initScripts.size,
- };
-}
-
-interface FakeRecord {
- readonly seen: string[];
- readonly release: () => void;
-}
-
-const realmRecorder: TransientNoticeRecorder = {
- record({ key, notices }) {
- const realm = window as unknown as FakeRealm;
- if (realm[key] !== undefined) return;
- const seen: string[] = [];
- const release = realm.noticeRegion.subscribe((text) => {
- if (notices.includes(text) && !seen.includes(text)) seen.push(text);
- });
- const record: FakeRecord = { seen, release };
- Object.defineProperty(realm, key, { value: record });
- },
- read(key) {
- const record = (window as unknown as FakeRealm)[key] as FakeRecord | undefined;
- return record === undefined ? null : [...record.seen];
- },
- stop(key) {
- ((window as unknown as FakeRealm)[key] as FakeRecord | undefined)?.release();
- },
-};
-
-const showsAndRemoves = (target: FakeDocument, text: string): void => {
- target.show(text);
- target.dismiss(text);
-};
-
-describe('transient notice observed in the document its trigger produced', () => {
- test('replays CI retry 1: next-document arming observes a notice the reloaded document shows and removes before the reload resolves', async () => {
- const tab = documentAwarePage();
- tab.whenBooted((reloaded) => showsAndRemoves(reloaded, NOTICE));
-
- await expect(
- expectNoticeFromTrigger(
- NOTICE,
- transientNoticeObservation(tab.page, {
- document: 'next',
- trigger: () => tab.reload(),
- recorder: realmRecorder,
- }),
- { timeout: OBSERVE_BOUND_MS },
- ),
- ).resolves.toBeUndefined();
- });
-
- test('is never satisfied by a notice the pre-reload document was showing when observation armed', async () => {
- const tab = documentAwarePage();
- tab.current().show(NOTICE);
-
- const message = await rejectionOf(
- expectNoticeFromTrigger(
- NOTICE,
- transientNoticeObservation(tab.page, {
- document: 'next',
- trigger: () => tab.reload(),
- recorder: realmRecorder,
- }),
- { timeout: OBSERVE_BOUND_MS },
- ),
- );
-
- expect(tab.current().subscriptionsOpened()).toBeGreaterThan(0);
- expect(message).toContain(NOTICE);
- expect(message).not.toMatch(/not installed/u);
- });
-
- test('reports a reloaded document the recorder never reached as a missing recorder, never as a missing notice', async () => {
- const tab = documentAwarePage({ honoursInitScripts: false });
- tab.whenBooted((reloaded) => showsAndRemoves(reloaded, NOTICE));
-
- const message = await rejectionOf(
- expectNoticeFromTrigger(
- NOTICE,
- transientNoticeObservation(tab.page, {
- document: 'next',
- trigger: () => tab.reload(),
- recorder: realmRecorder,
- }),
- { timeout: OBSERVE_BOUND_MS },
- ),
- );
-
- expect(message).toMatch(/recorder\b.*\bnot installed/u);
- expect(message).not.toMatch(/Received/u);
- });
-
- test('current-document arming ignores a notice already on screen when it armed', async () => {
- const tab = documentAwarePage();
- tab.current().show(NOTICE);
-
- const message = await rejectionOf(
- expectNoticeFromTrigger(
- NOTICE,
- transientNoticeObservation(tab.page, {
- document: 'current',
- trigger: () => Promise.resolve(),
- recorder: realmRecorder,
- }),
- { timeout: OBSERVE_BOUND_MS },
- ),
- );
-
- expect(tab.current().subscriptionsOpened()).toBeGreaterThan(0);
- expect(message).toContain(NOTICE);
- expect(message).not.toMatch(/not installed/u);
- });
-
- test('current-document arming records a notice the trigger shows and removes', async () => {
- const tab = documentAwarePage();
-
- await expect(
- expectNoticeFromTrigger(
- NOTICE,
- transientNoticeObservation(tab.page, {
- document: 'current',
- trigger: () => {
- showsAndRemoves(tab.current(), NOTICE);
- return Promise.resolve();
- },
- recorder: realmRecorder,
- }),
- { timeout: OBSERVE_BOUND_MS },
- ),
- ).resolves.toBeUndefined();
- });
-
- test('gives each observation its own record, so a notice an earlier observation recorded never satisfies a later one', async () => {
- const tab = documentAwarePage();
- const observeCurrent = (trigger: () => Promise<void>) =>
- transientNoticeObservation(tab.page, {
- document: 'current',
- trigger,
- recorder: realmRecorder,
- });
-
- await expectNoticeFromTrigger(
- NOTICE,
- observeCurrent(() => {
- showsAndRemoves(tab.current(), NOTICE);
- return Promise.resolve();
- }),
- { timeout: OBSERVE_BOUND_MS },
- );
- const message = await rejectionOf(
- expectNoticeFromTrigger(
- NOTICE,
- observeCurrent(() => Promise.resolve()),
- { timeout: OBSERVE_BOUND_MS },
- ),
- );
-
- expect(message).toContain(NOTICE);
- expect(message).not.toMatch(/not installed/u);
- });
-
- test('disposes the init script and disconnects the recorder once the reload notice is judged', async () => {
- const tab = documentAwarePage();
- tab.whenBooted((reloaded) => showsAndRemoves(reloaded, NOTICE));
-
- await expectNoticeFromTrigger(
- NOTICE,
- transientNoticeObservation(tab.page, {
- document: 'next',
- trigger: () => tab.reload(),
- recorder: realmRecorder,
- }),
- { timeout: OBSERVE_BOUND_MS },
- );
-
- expect(tab.activeInitScripts()).toBe(0);
- expect(tab.current().activeSubscriptions()).toBe(0);
- });
-
- test('disconnects the recorder once an in-document notice is judged', async () => {
- const tab = documentAwarePage();
-
- await expectNoticeFromTrigger(
- NOTICE,
- transientNoticeObservation(tab.page, {
- document: 'current',
- trigger: () => {
- showsAndRemoves(tab.current(), NOTICE);
- return Promise.resolve();
- },
- recorder: realmRecorder,
- }),
- { timeout: OBSERVE_BOUND_MS },
- );
-
- expect(tab.current().activeSubscriptions()).toBe(0);
- });
-});
diff --git a/packages/desktop/tests/smoke/_helpers/transient-notice.ts b/packages/desktop/tests/smoke/_helpers/transient-notice.ts
deleted file mode 100644
index 2724084d1..000000000
--- a/packages/desktop/tests/smoke/_helpers/transient-notice.ts
+++ /dev/null
@@ -1,169 +0,0 @@
-import { randomUUID } from 'node:crypto';
-import { expect, type Page } from '@playwright/test';
-import { requirePositiveTimeout } from './settled-reading';
-
-export interface TransientNoticeObservation {
- startObserving: (notice: string) => Promise<void>;
- trigger: () => Promise<void>;
- readObserved: () => Promise<readonly string[]>;
- stopObserving?: () => Promise<void>;
-}
-
-export interface TransientNoticeOptions {
- timeout: number;
-}
-
-export interface TransientNoticeRecorder {
- record: (args: { key: string; notices: readonly string[] }) => void;
- read: (key: string) => string[] | null;
- stop: (key: string) => void;
-}
-
-export interface TransientNoticePageOptions {
- trigger: () => Promise<void>;
- document: 'next' | 'current';
- recorder?: TransientNoticeRecorder;
-}
-
-export async function expectNoticeFromTrigger(
- notice: string,
- { startObserving, trigger, readObserved, stopObserving }: TransientNoticeObservation,
- { timeout }: TransientNoticeOptions,
-): Promise<void> {
- requirePositiveTimeout('expectNoticeFromTrigger', timeout);
- await startObserving(notice);
- try {
- await trigger();
- await expect.poll(readObserved, { timeout }).toContain(notice);
- } catch (verdict) {
- await stopObserving?.().catch((stopFailure: unknown) => {
- const reason = stopFailure instanceof Error ? stopFailure.message : String(stopFailure);
- console.warn(
- `[transient-notice] could not stop observing "${notice}" after its verdict failed: ${reason}`,
- );
- });
- throw verdict;
- }
- await stopObserving?.();
-}
-
-export function transientNoticeObservation(
- page: Page,
- { trigger, document: arming, recorder = pageRecorder }: TransientNoticePageOptions,
-): TransientNoticeObservation {
- const key = `__okTransientNotices:${randomUUID()}`;
- let observed = '';
- let initScript: { dispose: () => Promise<void> } | undefined;
- return {
- async startObserving(notice) {
- observed = notice;
- const args = { key, notices: [notice] };
- if (arming === 'next') {
- initScript = await page.addInitScript(recorder.record, args);
- } else {
- await page.evaluate(recorder.record, args);
- }
- },
- trigger,
- async readObserved() {
- const seen = await page.evaluate(recorder.read, key);
- if (seen === null) {
- throw new Error(
- `the transient-notice recorder is not installed in the current document, so "${observed}" could not be observed there`,
- );
- }
- return seen;
- },
- async stopObserving() {
- try {
- await page.evaluate(recorder.stop, key);
- } finally {
- await initScript?.dispose();
- }
- },
- };
-}
-
-interface TransientNoticeRecord {
- readonly seen: string[];
- readonly flush: () => void;
- readonly observer: MutationObserver;
-}
-
-function recordTransientNotices({ key, notices }: { key: string; notices: readonly string[] }) {
- const realm = window as unknown as Record<string, unknown>;
- if (realm[key] !== undefined) return;
- const normalize = (text: string | null): string => (text ?? '').replace(/\s+/gu, ' ').trim();
- const watched = notices.map((notice) => ({ notice, text: normalize(notice) }));
- const seen: string[] = [];
- const pending = new Map<Element, string>();
- const carries = (element: Element, text: string): boolean =>
- normalize(element.textContent).includes(text);
- const innermost = (root: Element, text: string): Element[] => {
- const inner = [...root.children].filter((child) => carries(child, text));
- return inner.length === 0 ? [root] : inner.flatMap((child) => innermost(child, text));
- };
- const consider = (root: Element, wholeSubtreeIsNew: boolean): void => {
- for (const { notice, text } of watched) {
- if (!carries(root, text)) continue;
- for (const candidate of innermost(root, text)) {
- if (wholeSubtreeIsNew || candidate === root) pending.set(candidate, notice);
- }
- }
- };
- const isVisible = (element: Element): boolean => {
- const box = element.getBoundingClientRect();
- return box.width > 0 && box.height > 0 && getComputedStyle(element).visibility !== 'hidden';
- };
- const flush = (): void => {
- for (const [candidate, notice] of pending) {
- if (!candidate.isConnected) {
- pending.delete(candidate);
- } else if (isVisible(candidate)) {
- if (!seen.includes(notice)) seen.push(notice);
- pending.delete(candidate);
- }
- }
- };
- const observer = new MutationObserver((mutations) => {
- for (const mutation of mutations) {
- if (mutation.type === 'childList') {
- for (const node of mutation.addedNodes) {
- if (node instanceof Element) consider(node, true);
- else if (node.parentElement !== null) consider(node.parentElement, false);
- }
- } else if (mutation.type === 'characterData' && mutation.target.parentElement !== null) {
- consider(mutation.target.parentElement, false);
- }
- }
- flush();
- });
- observer.observe(document, {
- childList: true,
- subtree: true,
- characterData: true,
- attributes: true,
- attributeFilter: ['class', 'style', 'hidden'],
- });
- const record: TransientNoticeRecord = { seen, flush, observer };
- Object.defineProperty(realm, key, { value: record });
-}
-
-function readTransientNotices(key: string): string[] | null {
- const record = (window as unknown as Record<string, TransientNoticeRecord | undefined>)[key];
- if (record === undefined) return null;
- record.flush();
- return [...record.seen];
-}
-
-function stopTransientNotices(key: string): void {
- (window as unknown as Record<string, TransientNoticeRecord | undefined>)[
- key
- ]?.observer.disconnect();
-}
-
-const pageRecorder: TransientNoticeRecorder = {
- record: recordTransientNotices,
- read: readTransientNotices,
- stop: stopTransientNotices,
-};
diff --git a/packages/desktop/tests/smoke/_helpers/window-size-settlement.uncached.test.ts b/packages/desktop/tests/smoke/_helpers/window-size-settlement.uncached.test.ts
index e267f5f0a..f57257013 100644
--- a/packages/desktop/tests/smoke/_helpers/window-size-settlement.uncached.test.ts
+++ b/packages/desktop/tests/smoke/_helpers/window-size-settlement.uncached.test.ts
@@ -78,7 +78,7 @@ test('a requested editor width settles when the renderer read completes within t
Promise.resolve(requestedWidth),
);
await readStarted;
- await vi.advanceTimersByTimeAsync(settledReading.RAIL_LAYOUT_SETTLE_TIMEOUT_MS - 1);
+ await vi.advanceTimersByTimeAsync(settledReading.LAYOUT_SETTLE_TIMEOUT_MS - 1);
releaseRead();
expect(await result).toBe('settled');
@@ -91,7 +91,7 @@ test('the editor width at the requested minimum is accepted', async () => {
);
releaseRead();
await readStarted;
- await vi.advanceTimersByTimeAsync(settledReading.RAIL_LAYOUT_SETTLE_TIMEOUT_MS + 1);
+ await vi.advanceTimersByTimeAsync(settledReading.LAYOUT_SETTLE_TIMEOUT_MS + 1);
expect(await result).toBe('settled');
});
@@ -104,7 +104,7 @@ test('an editor width below the requested minimum is rejected', async () => {
);
releaseRead();
await readStarted;
- await vi.advanceTimersByTimeAsync(settledReading.RAIL_LAYOUT_SETTLE_TIMEOUT_MS + 1);
+ await vi.advanceTimersByTimeAsync(settledReading.LAYOUT_SETTLE_TIMEOUT_MS + 1);
const outcome = await result;
expect(outcome).toBeInstanceOf(Error);
diff --git a/packages/desktop/tests/smoke/terminal-collection-size.json b/packages/desktop/tests/smoke/terminal-collection-size.json
index 9f3968e3c..de30ee094 100644
--- a/packages/desktop/tests/smoke/terminal-collection-size.json
+++ b/packages/desktop/tests/smoke/terminal-collection-size.json
@@ -1,4 +1,4 @@
{
"$comment": "Total tests collected by `playwright test tests/smoke/terminal-*.e2e.ts` on Windows, skipped ones included. Inkeep runs that collection sharded across parallel Windows CI cells and sums each shard's Playwright JSON stats against this number, so a shard that never ran cannot leave part of the collection unexecuted while every cell reads green. That guard and the workflow driving it live in Inkeep's internal monorepo, so whether a stale number fails anything depends on which checkout you are reading: it does there, and in the public mirror the guard is absent and nothing reads this file. Add or remove a terminal smoke test and this number moves with it either way; the guard prints the observed total when the two disagree.",
- "terminalSmokeTestCount": 103
+ "terminalSmokeTestCount": 101
}
diff --git a/packages/desktop/tests/smoke/terminal-dock.e2e.ts b/packages/desktop/tests/smoke/terminal-dock.e2e.ts
index d0c81069c..2e18dc583 100644
--- a/packages/desktop/tests/smoke/terminal-dock.e2e.ts
+++ b/packages/desktop/tests/smoke/terminal-dock.e2e.ts
@@ -19,6 +19,7 @@ import {
measureDockRevealMs,
watchForDockReveal,
} from './_helpers/dock-reveal-latency';
+import { readTerminalHome, TERMINAL_CARD } from './_helpers/dock-workspace';
import { attachDomState, describeDomState } from './_helpers/dom-state';
import { desktopLaunchOptions, resolveDesktopTarget } from './_helpers/launch-desktop';
import { launchDesktopApp, readBootLog, waitForWindowByMode } from './_helpers/launch-readiness';
@@ -28,14 +29,8 @@ import {
PTY_PLATFORM_SUPPORTED,
userDataDirFor,
} from './_helpers/platform-gate';
-import { expectCollapsedRailColumn } from './_helpers/rail-column';
import { closeAppForRelaunch } from './_helpers/settings-surface';
-import {
- expectSettledReading,
- pollSettledReading,
- RAIL_LAYOUT_SETTLE_TIMEOUT_MS,
- settleBudget,
-} from './_helpers/settled-reading';
+import { type LAYOUT_SETTLE_TIMEOUT_MS, pollSettledReading } from './_helpers/settled-reading';
import { expect, test } from './_helpers/smoke-test';
import { captureTerminalStartupDiagnostics, waitForShellReady } from './_helpers/terminal-ready';
import {
@@ -45,15 +40,15 @@ import {
terminalSmokeShellCommands,
writeFakeClaudeShim,
} from './_helpers/terminal-smoke-shell';
-import { expectNoticeFromTrigger, transientNoticeObservation } from './_helpers/transient-notice';
const TARGET = resolveDesktopTarget();
const SMOKE_ENABLED = process.env.OK_DESKTOP_E2E_SMOKE === '1';
const PRIMARY_MODIFIER = process.platform === 'darwin' ? 'Meta' : 'Control';
const SHELL_COMMANDS = terminalSmokeShellCommands();
-const TERMINAL_DOCK_PANEL_ID = 'terminal-dock-panel';
-const TERMINAL_DOCK_PANEL_SELECTOR = `#${TERMINAL_DOCK_PANEL_ID}`;
+const TERMINAL_UNIT_ID = 'dock-unit-terminal';
+const TERMINAL_UNIT_SELECTOR = `#${TERMINAL_UNIT_ID}`;
+const AGENTS_UNIT_SELECTOR = '#dock-unit-agents';
interface SeedOpts {
consent?: boolean;
@@ -379,11 +374,11 @@ async function openTerminal(app: ElectronApplication, page: Page): Promise<void>
}
async function waitForTerminalWidthStable(page: Page): Promise<void> {
- const panel = page.locator('#terminal-dock-panel');
+ const unit = page.locator(TERMINAL_UNIT_SELECTOR);
let previous = Number.NaN;
let stable = 0;
await expect(async () => {
- const width = await panel.evaluate((el) => Math.round(el.getBoundingClientRect().width));
+ const width = await unit.evaluate((el) => Math.round(el.getBoundingClientRect().width));
stable = width === previous ? stable + 1 : 0;
previous = width;
expect(stable).toBeGreaterThanOrEqual(3);
@@ -425,7 +420,9 @@ async function attachTerminalStartupDiagnostics(page: Page, home: string): Promi
}
async function ensureBottomDock(page: Page): Promise<void> {
- await expect(page.locator('#terminal-dock-panel')).toBeVisible({ timeout: 10_000 });
+ await expect
+ .poll(() => readTerminalHome(page), { timeout: 10_000 })
+ .toMatchObject({ placement: 'bottom', geometry: 'bottom' });
}
async function typeInTerminal(page: Page, text: string): Promise<void> {
@@ -727,184 +724,23 @@ test.describe('Docked terminal — live Electron', () => {
await widenEditorWindow(app, page, 1900, 900);
await openTerminal(app, page);
+ await ensureBottomDock(page);
- const rightTerminal = page.locator('#terminal-column section[aria-label="Terminal"]');
const moveRightButton = page.getByRole('button', { name: 'Move Terminal to right' });
await expect(moveRightButton).toBeVisible();
await moveRightButton.click();
- await expect(rightTerminal).toBeVisible({ timeout: 10_000 });
+ await expect
+ .poll(() => readTerminalHome(page), { timeout: 10_000 })
+ .toMatchObject({ placement: 'right', geometry: 'right' });
+ await expect(page.locator(`${TERMINAL_CARD} section[aria-label="Terminal"]`)).toBeVisible();
const moveBottomButton = page.getByRole('button', { name: 'Move Terminal to bottom' });
await expect(moveBottomButton).toBeVisible();
await moveBottomButton.click();
- await expect(rightTerminal).toBeHidden({ timeout: 10_000 });
- await expect(moveRightButton).toBeVisible();
- });
-
- test('a pointerleave mid-drag resizes the right column by the real delta, never collapsing it', async ({
- captureStderrFor,
- }) => {
- test.setTimeout(sumOfDeclaredBoundsMs(test.info()));
- const s = seed('divider-pointerleave', { consent: true });
- track(s.tmpHome, s.projectDir);
- const app = await launchApp(s);
- captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
- const page = await findEditorWindow(app);
- await configureDesktopGitRepositories(page, s.realProjectDir);
-
- await widenEditorWindow(app, page, 1900, 900);
- await openTerminal(app, page);
- await page.getByRole('button', { name: 'Move Terminal to right' }).click();
- await expect(page.locator('#terminal-column section[aria-label="Terminal"]')).toBeVisible({
- timeout: 10_000,
- });
-
- const column = page.locator('#terminal-column');
- const before = await column.evaluate((element) => element.getBoundingClientRect().width);
- expect(before).toBeGreaterThan(0);
-
- const handle = await column.evaluate((element) => {
- const rect = element.previousElementSibling?.getBoundingClientRect();
- return rect == null ? null : { x: rect.x, y: rect.y, width: rect.width, height: rect.height };
- });
- if (!handle) throw new Error('right Terminal resize handle is unavailable');
-
- const travel = 40;
- const originX = handle.x + handle.width / 2;
- const originY = handle.y + handle.height / 2;
- await page.mouse.move(originX, originY);
- await page.mouse.down();
- await page.mouse.move(originX - travel, originY, { steps: 4 });
-
- await page.evaluate(
- ({ x, y }) => {
- document.dispatchEvent(
- new PointerEvent('pointerleave', {
- bubbles: false,
- buttons: 1,
- clientX: x,
- clientY: y,
- pointerId: 1,
- pointerType: 'mouse',
- }),
- );
- },
- { x: originX - travel, y: originY },
- );
- await page.mouse.up();
-
- let after = Number.NaN;
- let stable = 0;
- await expect(async () => {
- const width = await column.evaluate((element) =>
- Math.round(element.getBoundingClientRect().width),
- );
- stable = width === after ? stable + 1 : 0;
- after = width;
- expect(
- stable,
- `column width has not settled (last read ${width}px, before ${before}px)`,
- ).toBeGreaterThanOrEqual(3);
- }).toPass({ timeout: 10_000, intervals: [100] });
- expect(after).toBeGreaterThan(before + travel * 0.75);
- expect(after).toBeLessThan(before + travel * 1.25);
- });
-
- test('right Terminal and Agents exclude each other only when the window is infeasible', async ({
- captureStderrFor,
- }) => {
- test.setTimeout(sumOfDeclaredBoundsMs(test.info()));
- const s = seed('rail-admission', { consent: true, skipRestoreState: true });
- track(s.tmpHome, s.projectDir);
- const app = await launchApp(s);
- captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });
- const page = await findEditorWindow(app);
- await configureDesktopGitRepositories(page, s.realProjectDir);
-
- await widenEditorWindow(app, page, 1900, 900);
- await openTerminal(app, page);
- await clickTerminalPlacementItem(app, page);
- await expect(page.locator('#terminal-column section[aria-label="Terminal"]')).toBeVisible({
- timeout: 10_000,
- });
- await waitForStatus(page, 'running', 25_000);
- await clickViewAgentsItem(app, page);
- await expect(page.locator('#agents-column')).toBeVisible({ timeout: 10_000 });
await expect
- .poll(
- () =>
- page
- .locator('#terminal-column')
- .evaluate((element) => element.getBoundingClientRect().width),
- { timeout: 10_000 },
- )
- .toBeGreaterThan(739);
- await typeInTerminal(page, `${SHELL_COMMANDS.columns('RAIL_COLS')}\r`);
- await expect.poll(() => readTerminalText(page), { timeout: 15_000 }).toMatch(/RAIL_COLS=\d+/);
- const columns = (await readTerminalText(page)).match(/RAIL_COLS=(\d+)/)?.[1];
- expect(Number(columns)).toBeGreaterThanOrEqual(92);
-
- const editorWindow = await app.browserWindow(page);
- const shrink = settleBudget('rail admission after the window narrows to 900 px', {
- timeout: RAIL_LAYOUT_SETTLE_TIMEOUT_MS,
- });
- await expectNoticeFromTrigger(
- 'Agent panel closed to keep Terminal readable.',
- transientNoticeObservation(page, {
- document: 'current',
- trigger: async () => {
- await editorWindow.evaluate((win: unknown) => {
- const target = win as {
- setSize: (width: number, height: number, animate: boolean) => void;
- };
- target.setSize(900, 900, false);
- });
- },
- }),
- { timeout: shrink.remainingMs() },
- );
- await expectSettledReading(
- () => page.evaluate(() => window.innerWidth),
- (width) => expect(width).toBeLessThan(1000),
- { reading: 'innerWidth', of: 'the editor window', budget: shrink },
- );
- await expectCollapsedRailColumn(page, '#agents-column', { budget: shrink });
- await expect(page.locator('#terminal-column section[aria-label="Terminal"]')).toBeVisible();
- await expectHeaderPanes(page, { Agents: false, Terminal: true });
-
- await expectNoticeFromTrigger(
- 'Terminal closed to make room for the agent panel.',
- transientNoticeObservation(page, {
- document: 'current',
- trigger: () => clickViewAgentsItem(app, page),
- }),
- { timeout: 10_000 },
- );
- await expect(page.locator('#agents-column')).toBeVisible({ timeout: 10_000 });
- await expectCollapsedRailColumn(page, '#terminal-column');
- await expectHeaderPanes(page, { Agents: true, Terminal: false });
-
- await clickViewAgentsItem(app, page);
- await expectCollapsedRailColumn(page, '#agents-column');
- await expectCollapsedRailColumn(page, '#terminal-column');
- await expectHeaderPanes(page, { Agents: false, Terminal: false });
-
- await headerPaneButton(page, 'Terminal').click();
- await expect(page.locator('#terminal-column section[aria-label="Terminal"]')).toBeVisible({
- timeout: 10_000,
- });
- await expectHeaderPanes(page, { Agents: false, Terminal: true });
- await expectNoticeFromTrigger(
- 'Terminal closed to make room for the agent panel.',
- transientNoticeObservation(page, {
- document: 'current',
- trigger: () => headerPaneButton(page, 'Agents').click(),
- }),
- { timeout: 10_000 },
- );
- await expect(page.locator('#agents-column')).toBeVisible({ timeout: 10_000 });
- await expectCollapsedRailColumn(page, '#terminal-column');
- await expectHeaderPanes(page, { Agents: true, Terminal: false });
+ .poll(() => readTerminalHome(page), { timeout: 10_000 })
+ .toMatchObject({ placement: 'bottom', geometry: 'bottom' });
+ await expect(moveRightButton).toBeVisible();
});
test('QA-022 toggle reveals the dock and mounts the terminal inside their liveness budgets', async ({
@@ -922,15 +758,15 @@ test.describe('Docked terminal — live Electron', () => {
const t0 = await page.evaluate(() => performance.now());
const dockElapsed = await measureDockRevealMs({
- armProbe: () => armDockRevealProbe(page, TERMINAL_DOCK_PANEL_ID),
+ armProbe: () => armDockRevealProbe(page, TERMINAL_UNIT_ID),
watchForReveal: () =>
- watchForDockReveal(page, TERMINAL_DOCK_PANEL_ID, DOCK_REVEAL_WATCH_CEILING_MS),
+ watchForDockReveal(page, TERMINAL_UNIT_ID, DOCK_REVEAL_WATCH_CEILING_MS),
triggerReveal: async () => {
expect(await clickViewTerminalItem(app, page)).toBe('Show Terminal');
},
});
console.log(`[dock-reveal] revealMs=${dockElapsed.toFixed(1)}`);
- await expect(page.locator(TERMINAL_DOCK_PANEL_SELECTOR)).toBeVisible();
+ await expect(page.locator(TERMINAL_UNIT_SELECTOR)).toBeVisible();
expect(dockElapsed).toBeLessThan(DOCK_REVEAL_BUDGET_MS);
const mountBudgetMs = 15_000;
@@ -1032,7 +868,7 @@ test.describe('Docked terminal — live Electron', () => {
await expect(page.getByRole('button', { name: 'Drag to dock the terminal' })).toHaveCount(0);
});
- test('the terminal lives in the bottom panel, never in the right column', async ({
+ test('the terminal lives in its own card under the editor, never in the chat pane', async ({
captureStderrFor,
}) => {
test.setTimeout(sumOfDeclaredBoundsMs(test.info()));
@@ -1045,10 +881,15 @@ test.describe('Docked terminal — live Electron', () => {
await openTerminal(app, page);
await waitForStatus(page, 'running', 25_000);
- await expect(page.locator('#terminal-dock-panel section[aria-label="Terminal"]')).toBeVisible({
- timeout: 10_000,
- });
- await expect(page.locator('#agents-column section[aria-label="Terminal"]')).toHaveCount(0);
+ await expect
+ .poll(() => readTerminalHome(page), { timeout: 10_000 })
+ .toEqual({ placement: 'bottom', geometry: 'bottom', painted: true });
+ await expect(
+ page.locator(`${TERMINAL_CARD} [data-terminal-panel-mount] section[aria-label="Terminal"]`),
+ ).toBeVisible();
+ await expect(
+ page.locator('[data-agents-panel-mount] section[aria-label="Terminal"]'),
+ ).toHaveCount(0);
});
test('QA-020 panel exposes region + screen-reader mode + AA contrast', async ({
@@ -1130,9 +971,7 @@ test.describe('Docked terminal — live Electron', () => {
await expect.poll(() => viewTerminalLabel(app), { timeout: 8_000 }).toBe('Hide Terminal');
});
- test('QA-021 collapsed panel is inert and focus returns on collapse', async ({
- captureStderrFor,
- }) => {
+ test('QA-021 a hidden terminal is inert and gives up focus', async ({ captureStderrFor }) => {
test.setTimeout(sumOfDeclaredBoundsMs(test.info()));
const s = seed('inert', { consent: true });
track(s.tmpHome, s.projectDir);
@@ -1146,9 +985,10 @@ test.describe('Docked terminal — live Electron', () => {
await page.locator('section[aria-label="Terminal"] .xterm').click();
await clickViewTerminalItem(app, page);
- await expect(page.locator('#terminal-dock-panel')).toHaveAttribute('inert', '', {
+ await expect(page.locator(TERMINAL_UNIT_SELECTOR)).toHaveAttribute('inert', '', {
timeout: 10_000,
});
+ await expect(page.locator('[data-terminal-panel-mount]')).toHaveAttribute('inert', '');
await expect
.poll(() =>
page.evaluate(() => {
@@ -1159,7 +999,7 @@ test.describe('Docked terminal — live Electron', () => {
.toBe(false);
});
- test('QA-023 panel height persists across reopen', async ({ captureStderrFor }) => {
+ test('QA-023 panel height persists across reopen and reload', async ({ captureStderrFor }) => {
test.setTimeout(sumOfDeclaredBoundsMs(test.info()));
const s = seed('resize', { consent: true });
track(s.tmpHome, s.projectDir);
@@ -1171,13 +1011,13 @@ test.describe('Docked terminal — live Electron', () => {
await waitForStatus(page, 'running', 25_000);
await ensureBottomDock(page);
- const panel = page.locator('#terminal-dock-panel');
+ const panel = page.locator(TERMINAL_UNIT_SELECTOR);
const heightBefore = await panel.evaluate((el) => el.getBoundingClientRect().height);
- const handle = panel.locator('xpath=preceding-sibling::*[@role="separator"][1]');
+ const handle = page.getByRole('separator', { name: 'Resize Terminal', exact: true });
await expect(handle).toBeVisible();
const box = await handle.boundingBox();
- if (box == null) throw new Error('bottom terminal resize handle has no bounding box');
+ if (box == null) throw new Error('bottom terminal seam has no bounding box');
await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
await page.mouse.down();
await page.mouse.move(box.x + box.width / 2, box.y - 160, { steps: 12 });
@@ -1185,21 +1025,12 @@ test.describe('Docked terminal — live Electron', () => {
await pollSettledReading(() => panel.evaluate((el) => el.getBoundingClientRect().height), {
reading: 'height',
- of: '#terminal-dock-panel after resize',
- timeout: 10_000 satisfies typeof RAIL_LAYOUT_SETTLE_TIMEOUT_MS,
+ of: '#dock-unit-terminal after resize',
+ timeout: 10_000 satisfies typeof LAYOUT_SETTLE_TIMEOUT_MS,
}).toBeGreaterThan(heightBefore);
const heightAfter = await panel.evaluate((el) => el.getBoundingClientRect().height);
- await pollSettledReading(
- () => page.evaluate(() => Number(localStorage.getItem('ok-terminal-height-v1') ?? 0)),
- {
- reading: 'persisted height',
- of: 'bottom terminal',
- timeout: 10_000 satisfies typeof RAIL_LAYOUT_SETTLE_TIMEOUT_MS,
- },
- ).toBeGreaterThan(heightBefore);
-
await clickViewTerminalItem(app, page);
await expect(panel).toHaveAttribute('inert', '', { timeout: 10_000 });
await clickViewTerminalItem(app, page);
@@ -1211,10 +1042,24 @@ test.describe('Docked terminal — live Electron', () => {
},
{
reading: 'reopened height difference',
- of: '#terminal-dock-panel',
- timeout: 10_000 satisfies typeof RAIL_LAYOUT_SETTLE_TIMEOUT_MS,
+ of: '#dock-unit-terminal',
+ timeout: 10_000 satisfies typeof LAYOUT_SETTLE_TIMEOUT_MS,
+ },
+ ).toBeLessThan(2);
+
+ await page.reload();
+ await expect(terminalSection(page)).toBeVisible({ timeout: 20_000 });
+ await pollSettledReading(
+ async () => {
+ const heightReload = await panel.evaluate((el) => el.getBoundingClientRect().height);
+ return Math.abs(heightReload - heightAfter);
+ },
+ {
+ reading: 'reloaded height difference',
+ of: '#dock-unit-terminal',
+ timeout: 10_000 satisfies typeof LAYOUT_SETTLE_TIMEOUT_MS,
},
- ).toBeLessThan(40);
+ ).toBeLessThan(2);
});
test('QA-015/032 shell exit shows restart; banner hidden on exit', async ({
@@ -1691,7 +1536,7 @@ test.describe('Docked terminal — live Electron', () => {
await clickViewAgentsItem(app, page);
await expectHeaderPanes(page, { Agents: true, Terminal: false });
- await expect(page.locator('#agents-column')).toBeVisible({ timeout: 10_000 });
+ await expect(page.locator(AGENTS_UNIT_SELECTOR)).toBeVisible({ timeout: 10_000 });
await expect
.poll(async () => (await viewMenuPaneLabels(app)).agents, { timeout: 8_000 })
.toBe('Hide Agents');
@@ -1832,7 +1677,7 @@ test.describe('Docked terminal — live Electron', () => {
const second = await launchOnProfile();
await expectHeaderPanes(second.page, { Agents: true, Terminal: true }, 25_000);
await expect(terminalSection(second.page)).toBeVisible();
- await expect(second.page.locator('#agents-column')).toBeVisible();
+ await expect(second.page.locator(AGENTS_UNIT_SELECTOR)).toBeVisible();
await headerPaneButton(second.page, 'Agents').click();
await expectHeaderPanes(second.page, { Agents: false, Terminal: true });
await quitAfterMenuReads(second.app, { agents: 'Show Agents', terminal: 'Hide Terminal' });
@@ -1842,7 +1687,7 @@ test.describe('Docked terminal — live Electron', () => {
timeout: 25_000,
});
await expect(headerPaneButton(third.page, 'Agents')).toHaveAttribute('aria-pressed', 'false');
- await expectCollapsedRailColumn(third.page, '#agents-column');
+ await expect(third.page.locator(AGENTS_UNIT_SELECTOR)).toBeHidden();
await headerPaneButton(third.page, 'Agents').click();
await headerPaneButton(third.page, 'Terminal').click();
await expectHeaderPanes(third.page, { Agents: true, Terminal: false });
diff --git a/packages/desktop/tests/smoke/terminal-movement.e2e.ts b/packages/desktop/tests/smoke/terminal-movement.e2e.ts
index 2c936c57a..e81c0f9ab 100644
--- a/packages/desktop/tests/smoke/terminal-movement.e2e.ts
+++ b/packages/desktop/tests/smoke/terminal-movement.e2e.ts
@@ -5,6 +5,15 @@ import { join } from 'node:path';
import type { ElectronApplication, ElementHandle, JSHandle, Locator, Page } from '@playwright/test';
import { _electron as electron } from '@playwright/test';
import { configureDesktopGitRepositories } from '../support/git-fixture.test-helper.ts';
+import {
+ dockUnitWidth,
+ expectStoredDockArrangementChanged,
+ readTerminalHome,
+ storedDockArrangement,
+ TERMINAL_CARD,
+ type TerminalHome,
+ terminalHomeProbe,
+} from './_helpers/dock-workspace';
import { desktopLaunchOptions, resolveDesktopTarget } from './_helpers/launch-desktop';
import { waitForWindowByMode } from './_helpers/launch-readiness';
import { sumOfDeclaredBoundsMs } from './_helpers/parse-timeouts';
@@ -13,10 +22,9 @@ import {
PTY_PLATFORM_SUPPORTED,
userDataDirFor,
} from './_helpers/platform-gate';
-import { expectCollapsedRailColumn, readRailColumnWidth } from './_helpers/rail-column';
import {
expectSettledReading,
- RAIL_LAYOUT_SETTLE_TIMEOUT_MS,
+ LAYOUT_SETTLE_TIMEOUT_MS,
type SettleBudget,
settleBudget,
} from './_helpers/settled-reading';
@@ -40,7 +48,6 @@ import {
terminalTabIds,
terminalTabs,
} from './_helpers/terminal-tabs.test-helper';
-import { expectNoticeFromTrigger, transientNoticeObservation } from './_helpers/transient-notice';
const TARGET = resolveDesktopTarget();
const SMOKE_ENABLED = process.env.OK_DESKTOP_E2E_SMOKE === '1';
@@ -48,8 +55,8 @@ const PRIMARY_MODIFIER = process.platform === 'darwin' ? 'Meta' : 'Control';
const SHELL_COMMANDS = terminalSmokeShellCommands();
const SCROLLBACK_PAGE_LIMIT = 40;
const SCROLL_SETTLE_FRAME_LIMIT = 60;
-
-type TerminalHome = 'bottom' | 'right';
+const TERMINAL_UNIT = '#dock-unit-terminal';
+const AGENTS_UNIT = '#dock-unit-agents';
interface Seed {
tmpHome: string;
@@ -330,52 +337,25 @@ async function settleScrollPosition(page: Page, departFrom?: string): Promise<st
return previous;
}
-function waitForTerminalHome(page: Page, home: TerminalHome): Promise<void> {
- return page.evaluate((targetHome) => {
- return new Promise<void>((resolve, reject) => {
- const activeSelector =
- targetHome === 'right'
- ? '#terminal-column section[aria-label="Terminal"]'
- : '#terminal-dock-panel section[aria-label="Terminal"]';
- const inactiveSelector =
- targetHome === 'right'
- ? '#terminal-dock-panel section[aria-label="Terminal"]'
- : '#terminal-column section[aria-label="Terminal"]';
- let frame = 0;
- const timeout = window.setTimeout(() => {
- window.cancelAnimationFrame(frame);
- reject(new Error(`Terminal did not settle at ${targetHome}`));
- }, 5_000);
-
- const inspect = () => {
- const active = [...document.querySelectorAll(activeSelector)].find((candidate) => {
- const rect = candidate.getBoundingClientRect();
- return rect.width > 0 && rect.height > 0;
- });
- const inactive = document.querySelector(inactiveSelector);
- const text = active?.querySelector('.xterm-rows')?.textContent ?? '';
- const rect = active?.getBoundingClientRect();
- if (active && !inactive && rect && rect.width > 0 && rect.height > 0 && text.length > 0) {
- window.clearTimeout(timeout);
- resolve();
- return;
- }
- frame = window.requestAnimationFrame(inspect);
- };
-
- frame = window.requestAnimationFrame(inspect);
- });
- }, home);
-}
-
async function moveTerminal(
app: ElectronApplication,
page: Page,
home: TerminalHome,
): Promise<void> {
- const settlement = waitForTerminalHome(page, home);
+ const settlement = page
+ .waitForFunction(terminalHomeProbe, home, { polling: 'raf', timeout: 5_000 })
+ .then(
+ () => null,
+ (error: unknown) => error,
+ );
await clickTerminalPlacementItem(app, page);
- await settlement;
+ const failure = await settlement;
+ if (failure !== null) {
+ throw new Error(
+ `the terminal did not settle at ${home}; it last read ${JSON.stringify(await readTerminalHome(page))}`,
+ { cause: failure },
+ );
+ }
}
async function captureLiveTerminal(page: Page): Promise<ElementHandle<Element>> {
@@ -384,21 +364,29 @@ async function captureLiveTerminal(page: Page): Promise<ElementHandle<Element>>
return handle;
}
+async function captureTerminalMount(page: Page): Promise<ElementHandle<Element>> {
+ const handle = await page.locator('[data-terminal-panel-mount]').elementHandle();
+ if (!handle) throw new Error('no terminal mount to follow across the move');
+ return handle;
+}
+
async function expectTerminalMovedNotRebuilt(
surface: ElementHandle<Element>,
+ mount: ElementHandle<Element>,
home: TerminalHome,
): Promise<void> {
- const containerId = home === 'right' ? 'terminal-column' : 'terminal-dock-panel';
const placement = await surface.evaluate(
- (element, id) => ({
+ (element, { terminalMount, card }) => ({
connected: element.isConnected,
- atHome: element.closest(`#${id}`) !== null,
+ inMount: terminalMount.isConnected && terminalMount.contains(element),
+ placement: element.closest(card)?.getAttribute('data-placement') ?? null,
}),
- containerId,
+ { terminalMount: mount, card: TERMINAL_CARD },
);
expect(placement, `the live terminal surface did not survive the move to ${home}`).toEqual({
connected: true,
- atHome: true,
+ inMount: true,
+ placement: home,
});
}
@@ -424,19 +412,17 @@ function tallyMenuActionDeliveries(
function readBurstOutcome(
surface: ElementHandle<Element>,
+ mount: ElementHandle<Element>,
deliveries: JSHandle<MenuActionTally>,
- home: TerminalHome,
) {
return surface.evaluate(
- (element, { tally, containerId }) => ({
+ (element, { tally, terminalMount, card }) => ({
delivered: tally.count,
connected: element.isConnected,
- atHome: element.closest(`#${containerId}`) !== null,
+ inMount: terminalMount.isConnected && terminalMount.contains(element),
+ placement: element.closest(card)?.getAttribute('data-placement') ?? null,
}),
- {
- tally: deliveries,
- containerId: home === 'right' ? 'terminal-column' : 'terminal-dock-panel',
- },
+ { tally: deliveries, terminalMount: mount, card: TERMINAL_CARD },
);
}
@@ -461,27 +447,34 @@ async function growRightTerminal(
page: Page,
deltaPx: number,
): Promise<{ width: number; settle: SettleBudget }> {
- const column = page.locator('#terminal-column');
- const before = await column.evaluate((element) => element.getBoundingClientRect().width);
- const handle = await column.evaluate((element) => {
- const rect = element.previousElementSibling?.getBoundingClientRect();
- return rect == null ? null : { x: rect.x, y: rect.y, width: rect.width, height: rect.height };
- });
- if (!handle) throw new Error('right Terminal resize handle is unavailable');
- await page.mouse.move(handle.x + handle.width / 2, handle.y + handle.height / 2);
+ const before = await dockUnitWidth(page, 'terminal');
+ const seam = await page
+ .getByRole('separator', { name: 'Resize Terminal', exact: true })
+ .boundingBox({ timeout: 10_000 });
+ if (!seam) throw new Error('the right Terminal seam has no box to drag');
+ const x = seam.x + seam.width / 2;
+ const y = seam.y + seam.height / 2;
+ await page.mouse.move(x, y);
await page.mouse.down();
- await page.mouse.move(handle.x - deltaPx, handle.y + handle.height / 2, { steps: 12 });
+ await page.mouse.move(x - deltaPx, y, { steps: 12 });
await page.mouse.up();
- const settle = settleBudget('right Terminal resize and its persisted layout', {
- timeout: RAIL_LAYOUT_SETTLE_TIMEOUT_MS,
+ const settle = settleBudget('right Terminal resize and its persisted arrangement', {
+ timeout: LAYOUT_SETTLE_TIMEOUT_MS,
});
await expectSettledReading(
- () => readRailColumnWidth(page, '#terminal-column'),
- (width) => expect(width).toBeGreaterThan(before + deltaPx / 2),
- { reading: 'width', of: '#terminal-column', budget: settle },
+ () => dockUnitWidth(page, 'terminal'),
+ (width) => expect(Math.abs(width - before - deltaPx)).toBeLessThanOrEqual(deltaPx / 4),
+ { reading: 'width', of: TERMINAL_UNIT, budget: settle },
);
- const width = await column.evaluate((element) => element.getBoundingClientRect().width);
- return { width, settle };
+ return { width: await dockUnitWidth(page, 'terminal'), settle };
+}
+
+async function expectHeaderPanesOn(page: Page): Promise<void> {
+ for (const pane of ['Agents', 'Terminal']) {
+ await expect(
+ page.locator('header[data-app-header]').getByRole('button', { name: pane, exact: true }),
+ ).toHaveAttribute('aria-pressed', 'true', { timeout: 5_000 });
+ }
}
async function expectStillScrolledBack(page: Page, newestLine: string): Promise<void> {
@@ -535,8 +528,9 @@ test.describe('Terminal placement continuity — live Electron', () => {
await expectScrollbackRetains(page, scrollback);
const liveSurface = await captureLiveTerminal(page);
+ const liveMount = await captureTerminalMount(page);
await moveTerminal(app, page, 'right');
- await expectTerminalMovedNotRebuilt(liveSurface, 'right');
+ await expectTerminalMovedNotRebuilt(liveSurface, liveMount, 'right');
await expectStillScrolledBack(page, newestScrollLine);
await expectTerminalTabOrder(page, [firstTabId, secondTabId]);
await expect(terminalTabById(page, secondTabId)).toHaveAttribute('aria-selected', 'true');
@@ -548,7 +542,7 @@ test.describe('Terminal placement continuity — live Electron', () => {
await expectScrollbackRetains(page, scrollback);
await moveTerminal(app, page, 'bottom');
- await expectTerminalMovedNotRebuilt(liveSurface, 'bottom');
+ await expectTerminalMovedNotRebuilt(liveSurface, liveMount, 'bottom');
await expectStillScrolledBack(page, newestScrollLine);
await expectTerminalTabOrder(page, [firstTabId, secondTabId]);
await expect(terminalTabById(page, secondTabId)).toHaveAttribute('aria-selected', 'true');
@@ -562,19 +556,22 @@ test.describe('Terminal placement continuity — live Electron', () => {
const rapidDeliveries = await tallyMenuActionDeliveries(page, 'move-terminal');
await clickTerminalPlacementItemRapidly(app, rapidToggles, page);
await expect
- .poll(() => readBurstOutcome(liveSurface, rapidDeliveries, 'right'), {
+ .poll(() => readBurstOutcome(liveSurface, liveMount, rapidDeliveries), {
message: 'the rapid placement burst never settled at its final placement',
})
- .toEqual({ delivered: rapidToggles, connected: true, atHome: true });
+ .toEqual({ delivered: rapidToggles, connected: true, inMount: true, placement: 'right' });
await rapidDeliveries.evaluate((tally) => tally.stop());
await rapidDeliveries.dispose();
- await expectTerminalMovedNotRebuilt(liveSurface, 'right');
+ await expectTerminalMovedNotRebuilt(liveSurface, liveMount, 'right');
+ await expect
+ .poll(() => readTerminalHome(page), { timeout: 5_000 })
+ .toEqual({ placement: 'right', geometry: 'right', painted: true });
+ await expect(page.locator('[data-terminal-panel-mount]')).toHaveCount(1);
await expect(page.locator('section[aria-label="Terminal"]')).toHaveCount(2);
await expect(visibleTerminal(page)).toHaveCount(1);
- await expect(page.locator('#terminal-column section[aria-label="Terminal"]')).toHaveCount(2);
- await expect(page.locator('#terminal-dock-panel section[aria-label="Terminal"]')).toHaveCount(
- 0,
- );
+ await expect(
+ page.locator(`${TERMINAL_CARD} [data-terminal-panel-mount] section[aria-label="Terminal"]`),
+ ).toHaveCount(2);
await expectTerminalTabOrder(page, [firstTabId, secondTabId]);
await expect(terminalTabById(page, secondTabId)).toHaveAttribute('aria-selected', 'true');
expect(await readShellPid(page, processMarker)).toBe(processId);
@@ -584,7 +581,7 @@ test.describe('Terminal placement continuity — live Electron', () => {
await expectScrollbackRetains(page, scrollback);
});
- test('dragging the right Terminal divider narrows the document and keeps the side panel width', async ({
+ test('dragging the right Terminal seam narrows the document and keeps the side panel width', async ({
captureStderrFor,
}) => {
test.setTimeout(sumOfDeclaredBoundsMs(test.info()));
@@ -605,7 +602,6 @@ test.describe('Terminal placement continuity — live Electron', () => {
await openTerminal(app, page);
await moveTerminal(app, page, 'right');
- await expect(page.locator('#terminal-column')).toBeVisible({ timeout: 20_000 });
const sidePanel = page.locator('#doc-panel');
const documentColumn = page.locator('[data-editor-workspace-column]');
@@ -613,7 +609,7 @@ test.describe('Terminal placement continuity — live Electron', () => {
await expect(editorCard.locator('#doc-panel')).toHaveCount(1);
await expect
.poll(() => sidePanel.evaluate((element) => element.getBoundingClientRect().width), {
- timeout: RAIL_LAYOUT_SETTLE_TIMEOUT_MS,
+ timeout: LAYOUT_SETTLE_TIMEOUT_MS,
})
.toBeGreaterThanOrEqual(300);
const sidePanelBefore = await sidePanel.evaluate(
@@ -624,20 +620,25 @@ test.describe('Terminal placement continuity — live Electron', () => {
);
const deltaPx = 150;
- await growRightTerminal(page, deltaPx);
+ const { settle } = await growRightTerminal(page, deltaPx);
- const sidePanelAfter = await sidePanel.evaluate(
- (element) => element.getBoundingClientRect().width,
- );
- const columnAfter = await documentColumn.evaluate(
- (element) => element.getBoundingClientRect().width,
- );
- expect(
- Math.abs(sidePanelAfter - sidePanelBefore),
- 'the side panel keeps its width while the right Terminal divider is dragged',
- ).toBeLessThanOrEqual(1);
- expect(columnAfter, 'the document column gives up the width').toBeLessThan(
- columnBefore - deltaPx / 2,
+ await expectSettledReading(
+ async () => ({
+ sidePanel: await sidePanel.evaluate((element) => element.getBoundingClientRect().width),
+ documentColumn: await documentColumn.evaluate(
+ (element) => element.getBoundingClientRect().width,
+ ),
+ }),
+ (widths) => {
+ expect(
+ Math.abs(widths.sidePanel - sidePanelBefore),
+ 'the side panel keeps its width while the right Terminal seam is dragged',
+ ).toBeLessThanOrEqual(1);
+ expect(widths.documentColumn, 'the document column gives up the width').toBeLessThan(
+ columnBefore - deltaPx / 2,
+ );
+ },
+ { reading: 'side panel and document column widths', of: 'the editor card', budget: settle },
);
});
@@ -677,27 +678,16 @@ test.describe('Terminal placement continuity — live Electron', () => {
await expectTerminalTabOrder(page, [secondTabId, firstTabId]);
await expect(terminalTabById(page, secondTabId)).toHaveAttribute('aria-selected', 'true');
await moveTerminal(app, page, 'right');
- const { width: restoredWidth, settle: railResize } = await growRightTerminal(page, 120);
-
- await expectSettledReading(
- () => page.evaluate(() => localStorage.getItem('ok-terminal-placement-v1')),
- (placement) => expect(placement).toBe('right'),
- { reading: 'placement', of: 'localStorage ok-terminal-placement-v1', budget: railResize },
- );
- await expectSettledReading(
- () => page.evaluate(() => Number(localStorage.getItem('ok-terminal-right-width-v1'))),
- (retainedWidth) => expect(Math.abs(retainedWidth - restoredWidth)).toBeLessThan(20),
- { reading: 'width', of: 'localStorage ok-terminal-right-width-v1', budget: railResize },
- );
+ const movedArrangement = await storedDockArrangement(page, { timeout: 10_000 });
+ const { width: restoredWidth, settle: rightResize } = await growRightTerminal(page, 120);
+ await expectStoredDockArrangementChanged(page, movedArrangement, rightResize);
await page.reload({ waitUntil: 'domcontentloaded' });
- await expect(page.locator('#terminal-column')).toBeVisible({ timeout: 20_000 });
- await expect(page.locator('#terminal-dock-panel')).toHaveCount(0);
await expect(terminalTabs(page)).toHaveText([secondLabel, 'restart first'], {
timeout: 25_000,
});
const restoredTail = settleBudget('restored active tab and right Terminal width', {
- timeout: RAIL_LAYOUT_SETTLE_TIMEOUT_MS,
+ timeout: LAYOUT_SETTLE_TIMEOUT_MS,
});
await expect(page.getByRole('tab', { name: secondLabel })).toHaveAttribute(
'aria-selected',
@@ -705,9 +695,14 @@ test.describe('Terminal placement continuity — live Electron', () => {
{ timeout: restoredTail.remainingMs() },
);
await expectSettledReading(
- () => readRailColumnWidth(page, '#terminal-column'),
+ () => readTerminalHome(page),
+ (home) => expect(home).toEqual({ placement: 'right', geometry: 'right', painted: true }),
+ { reading: 'terminal home', of: 'the restored editor window', budget: restoredTail },
+ );
+ await expectSettledReading(
+ () => dockUnitWidth(page, 'terminal'),
(width) => expect(Math.abs(width - restoredWidth)).toBeLessThan(20),
- { reading: 'width', of: '#terminal-column', budget: restoredTail },
+ { reading: 'width', of: TERMINAL_UNIT, budget: restoredTail },
);
expect(await readShellPid(page, processMarker)).toBe(processId);
const afterRestart = `AFTER_RESTART_${token}`;
@@ -715,7 +710,7 @@ test.describe('Terminal placement continuity — live Electron', () => {
await expect.poll(() => readActiveTerminal(page), { timeout: 15_000 }).toContain(afterRestart);
await clickViewAgentsItem(app, page);
- await expect(page.locator('#agents-column')).toBeVisible({ timeout: 10_000 });
+ await expect(page.locator(AGENTS_UNIT)).toBeVisible({ timeout: 10_000 });
const editorWindow = await app.browserWindow(page);
await editorWindow.evaluate((windowHandle: unknown) => {
const target = windowHandle as {
@@ -723,42 +718,33 @@ test.describe('Terminal placement continuity — live Electron', () => {
};
target.setSize(900, 900, false);
});
- const shrink = settleBudget('rail admission after the window narrows to 900 px', {
- timeout: RAIL_LAYOUT_SETTLE_TIMEOUT_MS,
+ const shrink = settleBudget('the dock after the window narrows to 900 px', {
+ timeout: LAYOUT_SETTLE_TIMEOUT_MS,
});
await expectSettledReading(
() => page.evaluate(() => window.innerWidth),
(width) => expect(width).toBeLessThan(1000),
{ reading: 'innerWidth', of: 'the editor window', budget: shrink },
);
- await expectCollapsedRailColumn(page, '#agents-column', { budget: shrink });
- await page.evaluate(() => {
- window.okDesktop?.editor.notifyViewMenuStateChanged({
- agentPanelVisible: true,
- wideIntent: { agentPanelVisible: true },
- });
+ await expectSettledReading(
+ () => readTerminalHome(page),
+ (home) => expect(home).toEqual({ placement: 'right', geometry: 'right', painted: true }),
+ { reading: 'terminal home', of: 'the narrowed editor window', budget: shrink },
+ );
+ await expect(page.locator(AGENTS_UNIT)).toBeVisible();
+ await expectHeaderPanesOn(page);
+
+ await page.reload({ waitUntil: 'domcontentloaded' });
+ const narrowRestore = settleBudget('the narrowed dock after a renderer restart', {
+ timeout: 20_000,
});
- await expect
- .poll(
- async () =>
- page.evaluate(() =>
- window.okDesktop?.terminal?.getDockState()?.then((state) => state.agentPanelVisible),
- ),
- { timeout: 10_000 },
- )
- .toBe(true);
- await expectNoticeFromTrigger(
- 'Agent panel closed to keep Terminal readable.',
- transientNoticeObservation(page, {
- document: 'next',
- trigger: async () => {
- await page.reload({ waitUntil: 'domcontentloaded' });
- },
- }),
- { timeout: 20_000 },
+ await expectSettledReading(
+ () => readTerminalHome(page),
+ (home) => expect(home).toEqual({ placement: 'right', geometry: 'right', painted: true }),
+ { reading: 'terminal home', of: 'the restored narrow editor window', budget: narrowRestore },
);
- await expect(page.locator('#terminal-column')).toBeVisible({ timeout: 10_000 });
- await expectCollapsedRailColumn(page, '#agents-column');
+ await expect(page.locator(AGENTS_UNIT)).toBeVisible({ timeout: narrowRestore.remainingMs() });
+ await expectHeaderPanesOn(page);
await editorWindow.evaluate((windowHandle: unknown) => {
const target = windowHandle as {
setSize: (width: number, height: number, animate: boolean) => void;
@@ -780,31 +766,57 @@ test.describe('Terminal placement continuity — live Electron', () => {
await configureDesktopGitRepositories(page, s.projectDir);
await openTerminal(app, page);
- await expect(page.locator('#terminal-dock-panel')).toBeVisible();
- await expectCollapsedRailColumn(page, '#terminal-column');
+ await expect
+ .poll(() => readTerminalHome(page), { timeout: 10_000 })
+ .toEqual({ placement: 'bottom', geometry: 'bottom', painted: true });
const token = randomUUID().replaceAll('-', '');
const processMarker = `MALFORMED_PROCESS_${token}`;
const processId = await readShellPid(page, processMarker);
- await page.evaluate(() => {
- localStorage.setItem('ok-terminal-placement-v1', 'future-home');
- localStorage.setItem('ok-terminal-right-width-v1', 'not-a-width');
- localStorage.setItem('ok-terminal-width-v1', 'agents-width-sentinel');
- });
+ await moveTerminal(app, page, 'right');
+ await moveTerminal(app, page, 'bottom');
+ const storedArrangement = await storedDockArrangement(page, { timeout: 10_000 });
+ const malformed = {
+ arrangement: JSON.stringify({
+ direction: 'row',
+ items: [
+ { size: 1, node: { pane: 'editor' } },
+ { size: 1, node: { pane: 'agents' } },
+ ],
+ }),
+ placement: 'future-home',
+ rightWidth: 'not-a-width',
+ agentsWidth: 'agents-width-sentinel',
+ height: 'height-sentinel',
+ };
+ await page.evaluate(
+ ({ key, values }) => {
+ localStorage.setItem(key, values.arrangement);
+ localStorage.setItem('ok-terminal-placement-v1', values.placement);
+ localStorage.setItem('ok-terminal-right-width-v1', values.rightWidth);
+ localStorage.setItem('ok-terminal-width-v1', values.agentsWidth);
+ localStorage.setItem('ok-terminal-height-v1', values.height);
+ },
+ { key: storedArrangement.key, values: malformed },
+ );
await page.reload({ waitUntil: 'domcontentloaded' });
- await expect(page.locator('#terminal-dock-panel')).toBeVisible({ timeout: 20_000 });
- await expectCollapsedRailColumn(page, '#terminal-column');
+ await expect
+ .poll(() => readTerminalHome(page), { timeout: 20_000 })
+ .toEqual({ placement: 'bottom', geometry: 'bottom', painted: true });
expect(
await page.evaluate(() => ({
placement: localStorage.getItem('ok-terminal-placement-v1'),
rightWidth: localStorage.getItem('ok-terminal-right-width-v1'),
agentsWidth: localStorage.getItem('ok-terminal-width-v1'),
+ height: localStorage.getItem('ok-terminal-height-v1'),
})),
+ 'the retired per-install layout keys are read once to seed a project, never written',
).toEqual({
- placement: 'bottom',
- rightWidth: '740',
- agentsWidth: 'agents-width-sentinel',
+ placement: malformed.placement,
+ rightWidth: malformed.rightWidth,
+ agentsWidth: malformed.agentsWidth,
+ height: malformed.height,
});
expect(await readShellPid(page, processMarker)).toBe(processId);
const output = `AFTER_MALFORMED_RESTART_${token}`;
@@ -853,18 +865,20 @@ test.describe('Terminal placement continuity — live Electron', () => {
}
return clippers;
});
+ const terminalCard = page.locator(TERMINAL_CARD);
await openTerminal(app, page);
- const bottomCard = page.locator(
- '#terminal-dock-panel [data-slot="pane-card"][data-pane="terminal"]',
- );
- await expect(bottomCard).toBeVisible({ timeout: 10_000 });
+ await clickViewAgentsItem(app, page);
+ await expect(page.locator(AGENTS_UNIT)).toBeVisible({ timeout: 10_000 });
+ await expect
+ .poll(() => readTerminalHome(page), { timeout: 10_000 })
+ .toEqual({ placement: 'bottom', geometry: 'bottom', painted: true });
expect(
- await clippingAncestors(bottomCard),
+ await clippingAncestors(terminalCard),
'nothing between the bottom terminal card and the window clips its shadow',
).toEqual([]);
const editor = await box('[data-slot="pane-card"][data-pane="editor"]');
- const bottom = await box('#terminal-dock-panel [data-slot="pane-card"][data-pane="terminal"]');
+ const bottom = await box(TERMINAL_CARD);
const fileList = await box('[data-slot="sidebar-container"]');
const sidePanel = await box('#doc-panel');
expect(
@@ -885,22 +899,17 @@ test.describe('Terminal placement continuity — live Electron', () => {
expect(sidePanel.bottom, 'the side panel stops above the terminal card').toBeLessThanOrEqual(
bottom.y + 1,
);
- const bottomBar = await box('#terminal-dock-panel [data-terminal-tab-row]');
+ const bottomBar = await box(`${TERMINAL_CARD} [data-terminal-tab-row]`);
expect(Math.abs(bottomBar.height - 44), 'the terminal top bar is 44px').toBeLessThanOrEqual(1);
expect(Math.abs(bottomBar.y - bottom.y)).toBeLessThanOrEqual(1);
await moveTerminal(app, page, 'right');
- const rightCard = page.locator(
- '#terminal-column [data-slot="pane-card"][data-pane="terminal"]',
- );
- await expect(rightCard).toBeVisible({ timeout: 10_000 });
- await expect(page.locator('#terminal-dock-panel')).toHaveCount(0);
expect(
- await clippingAncestors(rightCard),
+ await clippingAncestors(terminalCard),
'nothing between the right terminal card and the window clips its shadow',
).toEqual([]);
const editorAfter = await box('[data-slot="pane-card"][data-pane="editor"]');
- const right = await box('#terminal-column [data-slot="pane-card"][data-pane="terminal"]');
+ const right = await box(TERMINAL_CARD);
expect(
Math.abs(right.y - editorAfter.y),
'the right terminal card top lines up with the editor card',
@@ -913,12 +922,13 @@ test.describe('Terminal placement continuity — live Electron', () => {
Math.abs(right.x - editorAfter.right - gapPx),
'one gap separates the editor card and the right terminal card',
).toBeLessThanOrEqual(1);
- const agentsColumn = await box('#agents-column');
- expect(right.right, 'the right terminal sits left of the chat column').toBeLessThanOrEqual(
- agentsColumn.x + 1,
- );
+ const chat = await box('[data-slot="pane-card"][data-pane="agents"]');
+ expect(
+ Math.abs(chat.x - right.right - gapPx),
+ 'one gap separates the right terminal card and the chat card after it',
+ ).toBeLessThanOrEqual(1);
const tabRow = await box('header[data-editor-header]');
- const rightBar = await box('#terminal-column [data-terminal-tab-row]');
+ const rightBar = await box(`${TERMINAL_CARD} [data-terminal-tab-row]`);
expect(
Math.abs(rightBar.height - tabRow.height),
'the right terminal top bar matches the tab row height',
diff --git a/packages/desktop/tests/smoke/terminal-process-restart.e2e.ts b/packages/desktop/tests/smoke/terminal-process-restart.e2e.ts
index 07e68ff51..812f30407 100644
--- a/packages/desktop/tests/smoke/terminal-process-restart.e2e.ts
+++ b/packages/desktop/tests/smoke/terminal-process-restart.e2e.ts
@@ -14,6 +14,13 @@ import {
runningAppProcesses,
watchCrashDumps,
} from './_helpers/crash-dumps';
+import {
+ dockUnitWidth,
+ expectStoredDockArrangementChanged,
+ readTerminalHome,
+ storedDockArrangement,
+ TERMINAL_CARD,
+} from './_helpers/dock-workspace';
import { desktopLaunchOptions, resolveDesktopTarget } from './_helpers/launch-desktop';
import { waitForWindowByMode } from './_helpers/launch-readiness';
import { sumOfDeclaredBoundsMs } from './_helpers/parse-timeouts';
@@ -22,11 +29,10 @@ import {
PTY_PLATFORM_SUPPORTED,
userDataDirFor,
} from './_helpers/platform-gate';
-import { readRailColumnWidth } from './_helpers/rail-column';
import {
expectSettledReading,
+ LAYOUT_SETTLE_TIMEOUT_MS,
pollSettledReading,
- RAIL_LAYOUT_SETTLE_TIMEOUT_MS,
settleBudget,
} from './_helpers/settled-reading';
import { expect, test } from './_helpers/smoke-test';
@@ -48,6 +54,7 @@ const ENABLED = process.env.OK_DESKTOP_E2E_SMOKE === '1';
const PRIMARY_MODIFIER = process.platform === 'darwin' ? 'Meta' : 'Control';
const QUIT_SAMPLES = process.platform === 'win32' ? 50 : 1;
const SECOND_TAB_LABEL = process.platform === 'win32' ? 'process second' : 'Terminal 2';
+const TERMINAL_UNIT = '#dock-unit-terminal';
interface RestartSeed {
tmpHome: string;
@@ -124,7 +131,7 @@ async function setWindowSize(
await pollSettledReading(() => page.evaluate(() => window.innerWidth), {
reading: 'viewport width',
of: 'editor window',
- timeout: 10_000 satisfies typeof RAIL_LAYOUT_SETTLE_TIMEOUT_MS,
+ timeout: 10_000 satisfies typeof LAYOUT_SETTLE_TIMEOUT_MS,
}).toBeGreaterThanOrEqual(width - 100);
}
@@ -169,7 +176,7 @@ async function expectArrangedTabs(page: Page): Promise<void> {
);
}
-async function arrangeTabsInRightColumn(
+async function arrangeTabsInRightTerminal(
page: Page,
firstTabId: string,
secondTabId: string,
@@ -185,24 +192,47 @@ async function arrangeTabsInRightColumn(
await expectTerminalTabOrder(page, [secondTabId, firstTabId]);
await expect(terminalTabById(page, secondTabId)).toHaveAttribute('aria-selected', 'true');
await dispatchRendererMenuAction(page, 'move-terminal');
- await expect(page.locator('#terminal-column')).toBeVisible({ timeout: 10_000 });
+ await expect(page.locator(TERMINAL_CARD)).toHaveAttribute('data-placement', 'right', {
+ timeout: 10_000,
+ });
await expectArrangedTabs(page);
}
-async function applyPersistedRightTerminalWidth(page: Page, width: number): Promise<number> {
- await page.evaluate((nextWidth) => {
- localStorage.setItem('ok-terminal-right-width-v1', String(nextWidth));
- }, width);
+async function terminalRowShare(page: Page): Promise<number> {
+ const editor = await dockUnitWidth(page, 'editor');
+ const terminal = await dockUnitWidth(page, 'terminal');
+ return terminal / (editor + terminal);
+}
+
+async function widenRightTerminalThenReload(page: Page): Promise<number> {
+ const movedArrangement = await storedDockArrangement(page, { timeout: 10_000 });
+ const before = await dockUnitWidth(page, 'terminal');
+ await page.getByRole('separator', { name: 'Resize Terminal', exact: true }).focus();
+ await page.keyboard.press('Shift+ArrowLeft');
+ await page.keyboard.press('Shift+ArrowLeft');
+ const grow = settleBudget('right Terminal keyboard resize and its stored arrangement', {
+ timeout: LAYOUT_SETTLE_TIMEOUT_MS,
+ });
+ await expectSettledReading(
+ () => dockUnitWidth(page, 'terminal'),
+ (width) => expect(width).toBeGreaterThan(before + 100),
+ { reading: 'width', of: TERMINAL_UNIT, budget: grow },
+ );
+ const widened = await dockUnitWidth(page, 'terminal');
+ await expectStoredDockArrangementChanged(page, movedArrangement, grow);
await page.reload({ waitUntil: 'domcontentloaded' });
const restore = settleBudget('restored right Terminal width', { timeout: 20_000 });
- const column = page.locator('#terminal-column');
- await expect(column).toBeVisible({ timeout: restore.remainingMs() });
await expectSettledReading(
- () => readRailColumnWidth(page, '#terminal-column'),
- (renderedWidth) => expect(Math.abs(renderedWidth - width)).toBeLessThan(20),
- { reading: 'width', of: '#terminal-column', budget: restore },
+ () => readTerminalHome(page),
+ (home) => expect(home).toMatchObject({ placement: 'right', geometry: 'right' }),
+ { reading: 'terminal home', of: 'the reloaded editor window', budget: restore },
);
- return column.evaluate((element) => element.getBoundingClientRect().width);
+ await expectSettledReading(
+ () => dockUnitWidth(page, 'terminal'),
+ (width) => expect(Math.abs(width - widened)).toBeLessThan(20),
+ { reading: 'width', of: TERMINAL_UNIT, budget: restore },
+ );
+ return terminalRowShare(page);
}
async function quitAndWait(app: ElectronApplication, child: ChildProcess): Promise<void> {
@@ -244,7 +274,7 @@ test.describe('terminal process restart', () => {
test.skip(!PTY_PLATFORM_SUPPORTED, PTY_PLATFORM_SKIP_REASON);
test.skip(!TARGET.exists, TARGET.missingReason);
- test('restores placement, width, tab order, and active tab in a separate Electron process', async ({
+ test('restores placement, relative width, tab order, and active tab in a separate Electron process', async ({
captureStderrFor,
}) => {
test.setTimeout(sumOfDeclaredBoundsMs(test.info()));
@@ -263,8 +293,8 @@ test.describe('terminal process restart', () => {
await openBareTab(firstPage);
const [, secondTabId] = await terminalTabIds(firstPage);
if (secondTabId === undefined) throw new Error('second terminal tab was not created');
- await arrangeTabsInRightColumn(firstPage, firstTabId, secondTabId);
- const retainedWidth = await applyPersistedRightTerminalWidth(firstPage, 860);
+ await arrangeTabsInRightTerminal(firstPage, firstTabId, secondTabId);
+ const retainedShare = await widenRightTerminalThenReload(firstPage);
await expectArrangedTabs(firstPage);
const firstQuitDumps = await quitAndCollectCrashDumps(firstApp, firstProcess, firstDumps);
expect.soft(firstQuitDumps.lines, firstQuitDumps.headline).toEqual([]);
@@ -276,13 +306,14 @@ test.describe('terminal process restart', () => {
});
const secondPage = await findEditorWindow(secondApp);
await setWindowSize(secondApp, secondPage, 1900, 900);
- await expect(secondPage.locator('#terminal-column')).toBeVisible({ timeout: 25_000 });
- await expect(secondPage.locator('#terminal-dock-panel')).toHaveCount(0);
+ await expect(secondPage.locator(TERMINAL_CARD)).toHaveAttribute('data-placement', 'right', {
+ timeout: 25_000,
+ });
await expect(terminalTabs(secondPage)).toHaveText([SECOND_TAB_LABEL, 'process first'], {
timeout: 25_000,
});
- const restoredTail = settleBudget('restored active tab and right Terminal width', {
- timeout: RAIL_LAYOUT_SETTLE_TIMEOUT_MS,
+ const restoredTail = settleBudget('restored active tab and right Terminal share', {
+ timeout: LAYOUT_SETTLE_TIMEOUT_MS,
});
await expect(secondPage.getByRole('tab', { name: SECOND_TAB_LABEL })).toHaveAttribute(
'aria-selected',
@@ -290,9 +321,14 @@ test.describe('terminal process restart', () => {
{ timeout: restoredTail.remainingMs() },
);
await expectSettledReading(
- () => readRailColumnWidth(secondPage, '#terminal-column'),
- (width) => expect(Math.abs(width - retainedWidth)).toBeLessThan(20),
- { reading: 'width', of: '#terminal-column', budget: restoredTail },
+ () => readTerminalHome(secondPage),
+ (home) => expect(home).toMatchObject({ placement: 'right', geometry: 'right' }),
+ { reading: 'terminal home', of: 'the relaunched editor window', budget: restoredTail },
+ );
+ await expectSettledReading(
+ () => terminalRowShare(secondPage),
+ (share) => expect(Math.abs(share - retainedShare)).toBeLessThan(0.01),
+ { reading: 'terminal share', of: 'the right dock row', budget: restoredTail },
);
});
@@ -317,8 +353,8 @@ test.describe('terminal process restart', () => {
await openBareTab(page);
const [, secondTabId] = await terminalTabIds(page);
if (secondTabId === undefined) throw new Error('second terminal tab was not created');
- await arrangeTabsInRightColumn(page, firstTabId, secondTabId);
- await applyPersistedRightTerminalWidth(page, 860);
+ await arrangeTabsInRightTerminal(page, firstTabId, secondTabId);
+ await widenRightTerminalThenReload(page);
await expectArrangedTabs(page);
const quit = await quitAndCollectCrashDumps(app, appProcess, dumps);
expect(quit.lines, quit.headline).toEqual([]);